Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

fix(truenas): read the API shapes TrueNAS actually serves (#1573 residuals)

rcourtman41c0c219a245
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 8018a5715e..ebf571977e 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -375,8 +375,19 @@ resource health.
unified-resources contract (record-declared succession, item 27).
TrueNAS storage and alert inventory follow native query methods first:
pools use `pool.query`, datasets use `pool.dataset.query`, disks use
- `disk.query` with pool join options, and alerts use `alert.list`, with
- legacy REST allowed only as compatibility fallback. Unhealthy pool state
+ `disk.query`, and alerts use `alert.list`, with legacy REST allowed only
+ as compatibility fallback. Inventory readers must only consume fields the
+ API actually serves on every supported TrueNAS line (CORE 13 REST-only
+ included): `pool.dataset.query` carries no `mounted` field, so a listed
+ dataset counts as mounted unless `locked` or an explicit value says
+ otherwise; `disk.query` carries no health/status field and its
+ `extra.pools` join cannot cross the REST bridge, so per-disk pool
+ membership and ZFS member state derive from the vdev topology that
+ `pool.query` attaches unconditionally; and `disk.temperatures` is a
+ parameterized method the REST bridge only serves as POST, tried after
+ native JSON-RPC reporting. Missing disk telemetry is reported as
+ unknown, never as a failure signal. Regression coverage:
+ `internal/truenas/client_api_shapes_test.go`. Unhealthy pool state
from `pool.query` must emit a provider-native `zfs_pool_state` incident on
the canonical pool resource when `alert.list` does not already provide a
warning or critical pool alert for that same pool, so pool degradation does
diff --git a/frontend-modern/src/features/truenas/__tests__/truenasPageModel.test.ts b/frontend-modern/src/features/truenas/__tests__/truenasPageModel.test.ts
index c3403d4972..3f1d9a30a8 100644
--- a/frontend-modern/src/features/truenas/__tests__/truenasPageModel.test.ts
+++ b/frontend-modern/src/features/truenas/__tests__/truenasPageModel.test.ts
@@ -560,6 +560,28 @@ describe('truenasPageModel', () => {
).toEqual(['pool:pool-tank', 'disk:disk-sdb']);
});
+ it('does not flag unknown disk health as attention', () => {
+ // The TrueNAS disk API has no SMART/health field, so "unknown" is the
+ // normal state of a healthy disk, not a warning signal (#1573).
+ const unknownDisk = makeResource({
+ id: 'disk-unknown',
+ type: 'physical_disk',
+ name: 'ada0',
+ status: 'unknown',
+ physicalDisk: { devPath: '/dev/ada0', serial: 'serial-unknown', health: 'UNKNOWN' },
+ });
+ expect(mapTrueNASStorageStatus(unknownDisk)).toBe('unknown');
+
+ const healthyByState = makeResource({
+ id: 'disk-online',
+ type: 'physical_disk',
+ name: 'ada1',
+ status: 'online',
+ physicalDisk: { devPath: '/dev/ada1', serial: 'serial-online', health: 'PASSED' },
+ });
+ expect(mapTrueNASStorageStatus(healthyByState)).toBe('healthy');
+ });
+
it('filters apps using native TrueNAS app.query metadata', () => {
const nextcloud = makeResource({
id: 'app-nextcloud',
diff --git a/frontend-modern/src/features/truenas/truenasPageModel.ts b/frontend-modern/src/features/truenas/truenasPageModel.ts
index 56a4eacf6e..e0c0feb2d5 100644
--- a/frontend-modern/src/features/truenas/truenasPageModel.ts
+++ b/frontend-modern/src/features/truenas/truenasPageModel.ts
@@ -626,7 +626,16 @@ const storageStatusRank = (resource: Resource): number => {
const compareStorageResources = (left: Resource, right: Resource): number => {
const rankDelta = storageStatusRank(left) - storageStatusRank(right);
if (rankDelta !== 0) return rankDelta;
- return resourceDisplayName(left).localeCompare(resourceDisplayName(right));
+ const nameDelta = resourceDisplayName(left).localeCompare(resourceDisplayName(right));
+ if (nameDelta !== 0) return nameDelta;
+ // Two systems can expose identically-named pools (a DR pair both named
+ // "tank"); without a deterministic tie-break their order tracked map
+ // iteration order and flipped between refreshes (#1573).
+ const parentDelta = (asTrimmedString(left.parentName) ?? '').localeCompare(
+ asTrimmedString(right.parentName) ?? '',
+ );
+ if (parentDelta !== 0) return parentDelta;
+ return left.id.localeCompare(right.id);
};
const serviceStatusRank = (row: TrueNASServiceRow): number => {
@@ -686,7 +695,13 @@ export function mapTrueNASStorageStatus(
}
if (['offline', 'stopped'].includes(status)) return 'offline';
if (zfsState && zfsState !== 'online' && zfsState !== 'healthy') return 'attention';
- if (diskHealth && diskHealth !== 'passed' && diskHealth !== 'healthy' && diskHealth !== 'ok') {
+ // The TrueNAS disk API carries no SMART/health field, so "unknown" is the
+ // normal state of a healthy disk, not a warning signal (#1573). Only an
+ // affirmatively bad health value earns the attention bucket.
+ if (
+ diskHealth &&
+ !['passed', 'healthy', 'ok', 'unknown', 'unavailable'].includes(diskHealth)
+ ) {
return 'attention';
}
if (['online', 'running', 'healthy'].includes(status)) return 'healthy';
diff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.go
index 7f7d70f63a..b6483c3c3d 100644
--- a/internal/monitoring/canonical_guardrails_test.go
+++ b/internal/monitoring/canonical_guardrails_test.go
@@ -2177,7 +2177,7 @@ func TestTrueNASSystemTelemetryUsesCanonicalHostTemperatureModel(t *testing.T) {
providerSnippets := []string{
`if temperature := maxTrueNASSystemTemperature(system); temperature != nil {`,
`agent.Temperature = temperature`,
- `if sensors := sensorMetaFromTrueNASSystem(system); sensors != nil {`,
+ `if sensors := sensorMetaFromTrueNASSystem(system, disks); sensors != nil {`,
`agent.Sensors = sensors`,
}
for _, snippet := range providerSnippets {
diff --git a/internal/truenas/client.go b/internal/truenas/client.go
index 4acdebb2af..1da4036b5d 100644
--- a/internal/truenas/client.go
+++ b/internal/truenas/client.go
@@ -267,17 +267,71 @@ func (c *Client) getPoolsRPC(ctx context.Context) ([]Pool, error) {
id = name
}
pools = append(pools, Pool{
- ID: id,
- Name: name,
- Status: strings.TrimSpace(readStringAny(item, "status")),
- TotalBytes: readInt64Any(item, "size", "total", "total_bytes", "totalBytes"),
- UsedBytes: readInt64Any(item, "allocated", "used", "used_bytes", "usedBytes"),
- FreeBytes: readInt64Any(item, "free", "free_bytes", "freeBytes", "available"),
+ ID: id,
+ Name: name,
+ Status: strings.TrimSpace(readStringAny(item, "status")),
+ TotalBytes: readInt64Any(item, "size", "total", "total_bytes", "totalBytes"),
+ UsedBytes: readInt64Any(item, "allocated", "used", "used_bytes", "usedBytes"),
+ FreeBytes: readInt64Any(item, "free", "free_bytes", "freeBytes", "available"),
+ DiskMembers: poolDiskMembersFromTopology(item["topology"]),
})
}
return pools, nil
}
+// poolDiskMembersFromTopology collects the leaf disks of a pool.query
+// topology object across every vdev group, including detached/unavailable
+// members that only appear through their unavail_disk datastore row.
+func poolDiskMembersFromTopology(topology any) []PoolDiskMember {
+ groups, ok := topology.(map[string]any)
+ if !ok {
+ return nil
+ }
+
+ var members []PoolDiskMember
+ var walk func(node any)
+ walk = func(node any) {
+ vdev, ok := node.(map[string]any)
+ if !ok {
+ return
+ }
+ if children, ok := vdev["children"].([]any); ok && len(children) > 0 {
+ for _, child := range children {
+ walk(child)
+ }
+ return
+ }
+
+ member := PoolDiskMember{
+ Disk: strings.TrimSpace(readStringAny(vdev, "disk")),
+ Device: strings.TrimSpace(readStringAny(vdev, "device")),
+ Status: strings.TrimSpace(readStringAny(vdev, "status")),
+ }
+ if member.Disk == "" {
+ // A missing/faulted member's device path no longer resolves;
+ // middleware then attaches the disk's datastore row instead.
+ if unavail, ok := vdev["unavail_disk"].(map[string]any); ok {
+ member.Disk = strings.TrimSpace(readStringAny(unavail, "devname", "name"))
+ }
+ }
+ if member.Disk == "" && member.Device == "" {
+ return
+ }
+ members = append(members, member)
+ }
+
+ for _, group := range groups {
+ nodes, ok := group.([]any)
+ if !ok {
+ continue
+ }
+ for _, node := range nodes {
+ walk(node)
+ }
+ }
+ return members
+}
+
func (c *Client) getPoolsREST(ctx context.Context) ([]Pool, error) {
var response []poolResponse
if err := c.getJSON(ctx, http.MethodGet, "/pool", &response); err != nil {
@@ -290,13 +344,21 @@ func (c *Client) getPoolsREST(ctx context.Context) ([]Pool, error) {
if id == "0" && strings.TrimSpace(item.Name) != "" {
id = strings.TrimSpace(item.Name)
}
+ var topology any
+ if len(item.Topology) > 0 {
+ if err := json.Unmarshal(item.Topology, &topology); err != nil {
+ topology = nil
+ }
+ }
+
pools = append(pools, Pool{
- ID: id,
- Name: strings.TrimSpace(item.Name),
- Status: strings.TrimSpace(item.Status),
- TotalBytes: item.Size,
- UsedBytes: item.Allocated,
- FreeBytes: item.Free,
+ ID: id,
+ Name: strings.TrimSpace(item.Name),
+ Status: strings.TrimSpace(item.Status),
+ TotalBytes: item.Size,
+ UsedBytes: item.Allocated,
+ FreeBytes: item.Free,
+ DiskMembers: poolDiskMembersFromTopology(topology),
})
}
@@ -342,8 +404,15 @@ func (c *Client) getDatasetsRPC(ctx context.Context) ([]Dataset, error) {
Pool: poolName,
UsedBytes: used,
AvailBytes: available,
- Mounted: readBoolAny(item, "mounted"),
- ReadOnly: readBoolAny(item, "readonly", "read_only", "readOnly"),
+ // pool.dataset.query has never returned a "mounted" field on any
+ // TrueNAS version (CORE 13 and SCALE both strip it from the
+ // property allowlist), so absence must not read as unmounted —
+ // that marked every dataset Offline (#1573). A dataset the API
+ // lists is treated as mounted unless it is locked (encrypted
+ // with the key unloaded), the one unmounted state the API does
+ // report. An explicit "mounted" value still wins when present.
+ Mounted: readBoolAnyDefault(item, true, "mounted") && !readBoolAny(item, "locked"),
+ ReadOnly: readBoolAny(item, "readonly", "read_only", "readOnly"),
})
}
return datasets, nil
@@ -381,13 +450,21 @@ func (c *Client) getDatasetsREST(ctx context.Context) ([]Dataset, error) {
poolName = parentPoolFromDataset(name)
}
+ // See getDatasetsRPC: "mounted" does not exist in the API response,
+ // so a listed dataset counts as mounted unless locked or explicitly
+ // reported otherwise.
+ mounted := !item.Locked
+ if item.Mounted != nil {
+ mounted = *item.Mounted && !item.Locked
+ }
+
datasets = append(datasets, Dataset{
ID: id,
Name: name,
Pool: poolName,
UsedBytes: used,
AvailBytes: available,
- Mounted: item.Mounted,
+ Mounted: mounted,
ReadOnly: readOnly,
})
}
@@ -527,6 +604,52 @@ func (c *Client) disksFromMaps(ctx context.Context, response []map[string]any) (
return disks, nil
}
+// enrichDisksFromPoolTopology fills each disk's pool membership and ZFS
+// member state from the pools' vdev topology. disk.query itself reports no
+// health/status field on any TrueNAS version and only names the pool behind
+// an extra option the REST bridge cannot pass, so without this every disk
+// rendered as an unparented "Unknown" (#1573).
+func enrichDisksFromPoolTopology(pools []Pool, disks []Disk) {
+ type membership struct {
+ pool string
+ status string
+ }
+ byDevice := make(map[string]membership)
+ for _, pool := range pools {
+ for _, member := range pool.DiskMembers {
+ for _, device := range []string{member.Disk, member.Device} {
+ device = strings.TrimSpace(device)
+ if device == "" {
+ continue
+ }
+ if _, exists := byDevice[device]; !exists {
+ byDevice[device] = membership{pool: pool.Name, status: member.Status}
+ }
+ }
+ }
+ }
+ if len(byDevice) == 0 {
+ return
+ }
+
+ for i := range disks {
+ disk := &disks[i]
+ member, ok := byDevice[strings.TrimSpace(disk.Name)]
+ if !ok {
+ member, ok = byDevice[strings.TrimSpace(disk.ID)]
+ }
+ if !ok {
+ continue
+ }
+ if strings.TrimSpace(disk.Pool) == "" {
+ disk.Pool = member.pool
+ }
+ if strings.TrimSpace(disk.Status) == "" {
+ disk.Status = member.status
+ }
+ }
+}
+
// GetDiskTemperatures returns the current temperature by TrueNAS disk name.
func (c *Client) GetDiskTemperatures(ctx context.Context) (map[string]int, error) {
return c.getDiskTemperaturesWithFallback(ctx, nil)
@@ -554,15 +677,6 @@ func (c *Client) GetDiskTemperatureHistory(ctx context.Context, identifiers []st
}
func (c *Client) getDiskTemperaturesWithFallback(ctx context.Context, identifiers []string) (map[string]int, error) {
- var response any
- restErr := c.getJSON(ctx, http.MethodGet, "/disk/temperatures", &response)
- if restErr == nil {
- temperatures := parseDiskTemperatures(response)
- if len(temperatures) > 0 {
- return temperatures, nil
- }
- }
-
if len(identifiers) == 0 {
reportingIdentifiers, err := c.listDiskReportingIdentifiers(ctx)
if err == nil {
@@ -570,14 +684,30 @@ func (c *Client) getDiskTemperaturesWithFallback(ctx context.Context, identifier
}
}
+ // Native JSON-RPC reporting first: it is the supported surface on
+ // SCALE 25.04+ and avoids waking the deprecated REST bridge (#1550).
reportingTemperatures, reportingErr := c.getDiskTemperaturesFromReporting(ctx, identifiers)
if reportingErr == nil && len(reportingTemperatures) > 0 {
return reportingTemperatures, nil
}
+ // disk.temperatures takes parameters, so REST v2.0 serves it as POST
+ // with a body keyed by parameter name — on CORE 13.x (which has no
+ // JSON-RPC endpoint at all) this is the only path that can answer.
+ // An empty names list means "all disks eligible for temp monitoring";
+ // the remaining parameter (powermode on CORE, options on SCALE) is
+ // omitted so each version applies its own default.
+ var response any
+ restErr := c.postJSON(ctx, "/disk/temperatures", map[string]any{"names": []string{}}, &response)
+ if restErr == nil {
+ if temperatures := parseDiskTemperatures(response); len(temperatures) > 0 {
+ return temperatures, nil
+ }
+ }
+
if restErr != nil {
if reportingErr != nil {
- return nil, fmt.Errorf("fetch truenas disk temperatures via rest and reporting: rest=%w reporting=%v", restErr, reportingErr)
+ return nil, fmt.Errorf("fetch truenas disk temperatures via reporting and rest: reporting=%w rest=%v", reportingErr, restErr)
}
return nil, restErr
}
@@ -1304,6 +1434,7 @@ func (c *Client) FetchSnapshot(ctx context.Context) (*FixtureSnapshot, error) {
if err != nil {
return nil, fmt.Errorf("fetch truenas disks: %w", err)
}
+ enrichDisksFromPoolTopology(pools, disks)
alerts, err := c.GetAlerts(ctx)
if err != nil {
@@ -3408,7 +3539,23 @@ func dedupeStrings(values []string) []string {
}
func (c *Client) getJSON(ctx context.Context, method string, path string, destination any) (err error) {
- request, err := c.newRequest(ctx, method, path)
+ return c.requestJSON(ctx, method, path, nil, destination)
+}
+
+// postJSON issues a POST with a JSON body. REST v2.0 exposes middleware
+// methods that take parameters (disk.temperatures, reporting.get_data) as
+// POST endpoints whose body is a dict keyed by parameter name; a GET on
+// those paths fails on every TrueNAS version.
+func (c *Client) postJSON(ctx context.Context, path string, payload any, destination any) error {
+ body, err := json.Marshal(payload)
+ if err != nil {
+ return fmt.Errorf("encode truenas request body for POST %s: %w", path, err)
+ }
+ return c.requestJSON(ctx, http.MethodPost, path, bytes.NewReader(body), destination)
+}
+
+func (c *Client) requestJSON(ctx context.Context, method string, path string, body io.Reader, destination any) (err error) {
+ request, err := c.newRequestWithBody(ctx, method, path, body)
if err != nil {
return fmt.Errorf("build truenas request %s %s: %w", method, path, err)
}
@@ -3449,11 +3596,18 @@ func (c *Client) getJSON(ctx context.Context, method string, path string, destin
}
func (c *Client) newRequest(ctx context.Context, method string, path string) (*http.Request, error) {
+ return c.newRequestWithBody(ctx, method, path, nil)
+}
+
+func (c *Client) newRequestWithBody(ctx context.Context, method string, path string, body io.Reader) (*http.Request, error) {
url := c.endpoint(path)
- request, err := http.NewRequestWithContext(ctx, method, url, nil)
+ request, err := http.NewRequestWithContext(ctx, method, url, body)
if err != nil {
return nil, fmt.Errorf("build truenas request %s %s: %w", method, path, err)
}
+ if body != nil {
+ request.Header.Set("Content-Type", "application/json")
+ }
request.Header.Set("Accept", "application/json")
if apiKey := strings.TrimSpace(c.config.APIKey); apiKey != "" {
@@ -3687,12 +3841,13 @@ func (f *int64ResponseField) UnmarshalJSON(data []byte) error {
}
type poolResponse struct {
- ID int64 `json:"id"`
- Name string `json:"name"`
- Status string `json:"status"`
- Size int64 `json:"size"`
- Allocated int64 `json:"allocated"`
- Free int64 `json:"free"`
+ ID int64 `json:"id"`
+ Name string `json:"name"`
+ Status string `json:"status"`
+ Size int64 `json:"size"`
+ Allocated int64 `json:"allocated"`
+ Free int64 `json:"free"`
+ Topology json.RawMessage `json:"topology"`
}
type datasetResponse struct {
@@ -3702,8 +3857,12 @@ type datasetResponse struct {
Used nestedValue `json:"used"`
Available nestedValue `json:"available"`
ReadOnly nestedValue `json:"readonly"`
- Mounted bool `json:"mounted"`
- MountPath string `json:"mountpoint"`
+ // Mounted is a pointer because the real API never sends the field
+ // (see getDatasetsRPC); only fixtures and hypothetical future versions
+ // populate it, and absence must stay distinguishable from false.
+ Mounted *bool `json:"mounted"`
+ Locked bool `json:"locked"`
+ MountPath string `json:"mountpoint"`
}
type diskResponse struct {
diff --git a/internal/truenas/client_api_shapes_test.go b/internal/truenas/client_api_shapes_test.go
new file mode 100644
index 0000000000..2e05594813
--- /dev/null
+++ b/internal/truenas/client_api_shapes_test.go
@@ -0,0 +1,182 @@
+package truenas
+
+import (
+ "context"
+ "net/http"
+ "testing"
+)
+
+// The real pool.dataset.query response has never carried a "mounted" field on
+// any TrueNAS version (CORE 13 and SCALE both strip it from the property
+// allowlist), so its absence must not read as "unmounted" — that rendered
+// every dataset Offline (#1573). "locked" is the one unmounted-like state the
+// API does report.
+func TestGetDatasetsRESTDefaultsMountedWhenFieldAbsent(t *testing.T) {
+ server := newMockServer(t, map[string]apiResponse{
+ "/api/v2.0/pool/dataset": {
+ body: `[
+ {"id":"tank/media","name":"tank/media","pool":"tank","used":{"parsed":1},"available":{"parsed":2},"readonly":{"parsed":false},"mountpoint":"/mnt/tank/media"},
+ {"id":"tank/vault","name":"tank/vault","pool":"tank","used":{"parsed":1},"available":{"parsed":2},"readonly":{"parsed":false},"mountpoint":"/mnt/tank/vault","locked":true},
+ {"id":"tank/legacy","name":"tank/legacy","pool":"tank","used":{"parsed":1},"available":{"parsed":2},"readonly":{"parsed":false},"mountpoint":"/mnt/tank/legacy","mounted":false}
+ ]`,
+ },
+ }, nil)
+ t.Cleanup(server.Close)
+
+ client := mustClientForServer(t, server.URL, ClientConfig{APIKey: "api-key"})
+ datasets, err := client.getDatasetsREST(context.Background())
+ if err != nil {
+ t.Fatalf("getDatasetsREST() error = %v", err)
+ }
+ if len(datasets) != 3 {
+ t.Fatalf("expected 3 datasets, got %d", len(datasets))
+ }
+ if !datasets[0].Mounted {
+ t.Fatalf("dataset without mounted field must default to mounted: %+v", datasets[0])
+ }
+ if datasets[1].Mounted {
+ t.Fatalf("locked dataset must not count as mounted: %+v", datasets[1])
+ }
+ if datasets[2].Mounted {
+ t.Fatalf("explicit mounted=false must be honored: %+v", datasets[2])
+ }
+}
+
+func TestDatasetsFromRPCMapsDefaultMountedWhenFieldAbsent(t *testing.T) {
+ server := newMockServer(t, map[string]apiResponse{}, nil)
+ t.Cleanup(server.Close)
+ client := mustClientForServer(t, server.URL, ClientConfig{APIKey: "api-key"})
+ _ = client
+
+ items := []map[string]any{
+ {"id": "tank/media", "name": "tank/media", "pool": "tank", "used": map[string]any{"parsed": 1}, "available": map[string]any{"parsed": 2}},
+ {"id": "tank/vault", "name": "tank/vault", "pool": "tank", "locked": true},
+ {"id": "tank/legacy", "name": "tank/legacy", "pool": "tank", "mounted": false},
+ }
+ // Mirror getDatasetsRPC's mounted derivation on raw maps.
+ mounted := func(item map[string]any) bool {
+ return readBoolAnyDefault(item, true, "mounted") && !readBoolAny(item, "locked")
+ }
+ if !mounted(items[0]) {
+ t.Fatal("dataset without mounted field must default to mounted")
+ }
+ if mounted(items[1]) {
+ t.Fatal("locked dataset must not count as mounted")
+ }
+ if mounted(items[2]) {
+ t.Fatal("explicit mounted=false must be honored")
+ }
+}
+
+// disk.temperatures takes parameters, so REST v2.0 serves it as POST with a
+// body keyed by parameter name on every TrueNAS version; the old GET always
+// failed, which left disk temperatures blank wherever the JSON-RPC endpoint
+// does not exist (CORE 13, SCALE < 25.04) (#1573).
+func TestDiskTemperaturesFallBackToRESTPost(t *testing.T) {
+ sawPost := false
+ server := newMockServer(t, map[string]apiResponse{
+ "/api/v2.0/disk/temperatures": {
+ body: `{"ada0":33,"ada1":null}`,
+ },
+ }, func(t *testing.T, request *http.Request) {
+ if request.URL.Path == "/api/v2.0/disk/temperatures" {
+ if request.Method != http.MethodPost {
+ t.Fatalf("disk/temperatures must be requested via POST, got %s", request.Method)
+ }
+ sawPost = true
+ }
+ })
+ t.Cleanup(server.Close)
+
+ client := mustClientForServer(t, server.URL, ClientConfig{APIKey: "api-key"})
+ temperatures, err := client.getDiskTemperaturesWithFallback(context.Background(), []string{"ada0", "ada1"})
+ if err != nil {
+ t.Fatalf("getDiskTemperaturesWithFallback() error = %v", err)
+ }
+ if !sawPost {
+ t.Fatal("expected a POST request to /disk/temperatures")
+ }
+ if len(temperatures) != 1 || temperatures["ada0"] != 33 {
+ t.Fatalf("unexpected temperatures: %#v", temperatures)
+ }
+}
+
+func TestPoolDiskMembersFromTopology(t *testing.T) {
+ topology := map[string]any{
+ "data": []any{
+ map[string]any{
+ "type": "RAIDZ1",
+ "status": "DEGRADED",
+ "children": []any{
+ map[string]any{
+ "type": "DISK", "status": "ONLINE",
+ "device": "ada0p2", "disk": "ada0",
+ "children": []any{},
+ },
+ map[string]any{
+ "type": "DISK", "status": "UNAVAIL",
+ "device": "", "disk": "",
+ "unavail_disk": map[string]any{"devname": "ada1"},
+ "children": []any{},
+ },
+ },
+ },
+ },
+ "spare": []any{
+ map[string]any{"type": "DISK", "status": "AVAIL", "device": "da9p1", "disk": "da9", "children": []any{}},
+ },
+ }
+
+ members := poolDiskMembersFromTopology(topology)
+ if len(members) != 3 {
+ t.Fatalf("expected 3 members, got %#v", members)
+ }
+ byDisk := map[string]PoolDiskMember{}
+ for _, member := range members {
+ key := member.Disk
+ if key == "" {
+ key = member.Device
+ }
+ byDisk[key] = member
+ }
+ if byDisk["ada0"].Status != "ONLINE" {
+ t.Fatalf("expected ada0 ONLINE, got %#v", byDisk["ada0"])
+ }
+ if byDisk["ada1"].Status != "UNAVAIL" {
+ t.Fatalf("expected unavail_disk member ada1 UNAVAIL, got %#v", byDisk["ada1"])
+ }
+ if byDisk["da9"].Status != "AVAIL" {
+ t.Fatalf("expected spare da9 AVAIL, got %#v", byDisk["da9"])
+ }
+}
+
+func TestEnrichDisksFromPoolTopology(t *testing.T) {
+ pools := []Pool{{
+ Name: "tank",
+ DiskMembers: []PoolDiskMember{
+ {Disk: "ada0", Device: "ada0p2", Status: "ONLINE"},
+ {Disk: "ada1", Device: "ada1p2", Status: "FAULTED"},
+ },
+ }}
+ disks := []Disk{
+ {ID: "{serial}A", Name: "ada0"},
+ {ID: "{serial}B", Name: "ada1"},
+ {ID: "{serial}C", Name: "ada2"},
+ {ID: "{serial}D", Name: "ada3", Pool: "other", Status: "ONLINE"},
+ }
+
+ enrichDisksFromPoolTopology(pools, disks)
+
+ if disks[0].Pool != "tank" || disks[0].Status != "ONLINE" {
+ t.Fatalf("expected ada0 in tank/ONLINE, got %+v", disks[0])
+ }
+ if disks[1].Pool != "tank" || disks[1].Status != "FAULTED" {
+ t.Fatalf("expected ada1 in tank/FAULTED, got %+v", disks[1])
+ }
+ if disks[2].Pool != "" || disks[2].Status != "" {
+ t.Fatalf("unassigned disk must stay unassigned, got %+v", disks[2])
+ }
+ if disks[3].Pool != "other" || disks[3].Status != "ONLINE" {
+ t.Fatalf("explicit disk fields must not be overwritten, got %+v", disks[3])
+ }
+}
diff --git a/internal/truenas/client_test.go b/internal/truenas/client_test.go
index 1ef0b0d9d1..54dd3dbba7 100644
--- a/internal/truenas/client_test.go
+++ b/internal/truenas/client_test.go
@@ -416,6 +416,18 @@ func TestGetDisksUsesNativeDiskQueryShape(t *testing.T) {
payload[0]["smart_status"] = "FAILED"
writeRPCResult(t, conn, request.ID, payload[:1])
case 2:
+ if request.Method != "reporting.get_data" {
+ t.Fatalf("expected reporting.get_data, got %q", request.Method)
+ }
+ writeRPCResult(t, conn, request.ID, []map[string]any{{
+ "name": "disktemp",
+ "identifier": "sda",
+ "legend": []string{"time", "temperature"},
+ "aggregations": map[string]any{
+ "mean": map[string]any{"temperature": 34.0},
+ },
+ }})
+ case 3:
if request.Method != "disk.temperature_agg" {
t.Fatalf("expected disk.temperature_agg, got %q", request.Method)
}
@@ -1338,6 +1350,12 @@ func TestGetDisksIncludesDiskTemperatureAggregatesFromRPC(t *testing.T) {
writeRPCResult(t, conn, aggregateReq.ID, defaultRoutePayloadMaps(t, "/api/v2.0/disk")[:1])
return
}
+ if aggregateReq.Method == "reporting.get_data" {
+ // Current-temperature reporting probe: answer empty so the
+ // client falls back to the REST POST /disk/temperatures route.
+ writeRPCResult(t, conn, aggregateReq.ID, []map[string]any{})
+ return
+ }
if aggregateReq.Method != "disk.temperature_agg" {
t.Fatalf("expected disk.temperature_agg, got %q", aggregateReq.Method)
}
diff --git a/internal/truenas/provider.go b/internal/truenas/provider.go
index ce3ad1036d..9e3e145e61 100644
--- a/internal/truenas/provider.go
+++ b/internal/truenas/provider.go
@@ -504,7 +504,7 @@ func truenasRecordsFromSnapshot(snapshot *FixtureSnapshot, connectionID string,
records := make([]unifiedresources.IngestRecord, 0, 1+len(snapshot.Pools)+len(snapshot.Datasets)+len(snapshot.Apps)+len(snapshot.VMs)+len(snapshot.Shares)+len(snapshot.Disks))
totalCapacity, totalUsed := aggregatePoolUsage(snapshot.Pools)
- systemAgent := agentDataFromTrueNASSystem(connectionID, snapshot.System, systemRisk, protectionReduced, protectionSummary, rebuildInProgress, rebuildSummary)
+ systemAgent := agentDataFromTrueNASSystem(connectionID, snapshot.System, snapshot.Disks, systemRisk, protectionReduced, protectionSummary, rebuildInProgress, rebuildSummary)
records = append(records, unifiedresources.IngestRecord{
SourceID: systemSourceID,
SupersededCanonicalIDs: systemSupersededIDs,
@@ -913,7 +913,7 @@ func metricsFromTrueNASSystem(system SystemInfo, totalCapacity, totalUsed int64)
return metrics
}
-func agentDataFromTrueNASSystem(connectionID string, system SystemInfo, storageRisk *unifiedresources.StorageRisk, protectionReduced bool, protectionSummary string, rebuildInProgress bool, rebuildSummary string) *unifiedresources.AgentData {
+func agentDataFromTrueNASSystem(connectionID string, system SystemInfo, disks []Disk, storageRisk *unifiedresources.StorageRisk, protectionReduced bool, protectionSummary string, rebuildInProgress bool, rebuildSummary string) *unifiedresources.AgentData {
agent := &unifiedresources.AgentData{
AgentID: trueNASSystemMetricResourceID(connectionID, system),
Hostname: strings.TrimSpace(system.Hostname),
@@ -955,7 +955,7 @@ func agentDataFromTrueNASSystem(connectionID string, system SystemInfo, storageR
if temperature := maxTrueNASSystemTemperature(system); temperature != nil {
agent.Temperature = temperature
}
- if sensors := sensorMetaFromTrueNASSystem(system); sensors != nil {
+ if sensors := sensorMetaFromTrueNASSystem(system, disks); sensors != nil {
agent.Sensors = sensors
}
@@ -989,22 +989,51 @@ func maxTrueNASSystemTemperature(system SystemInfo) *float64 {
return &best
}
-func sensorMetaFromTrueNASSystem(system SystemInfo) *unifiedresources.HostSensorMeta {
- if len(system.TemperatureCelsius) == 0 {
- return nil
- }
+func sensorMetaFromTrueNASSystem(system SystemInfo, disks []Disk) *unifiedresources.HostSensorMeta {
+ sensors := &unifiedresources.HostSensorMeta{}
- sensors := &unifiedresources.HostSensorMeta{
- TemperatureCelsius: make(map[string]float64, len(system.TemperatureCelsius)),
+ if len(system.TemperatureCelsius) > 0 {
+ sensors.TemperatureCelsius = make(map[string]float64, len(system.TemperatureCelsius))
+ for key, value := range system.TemperatureCelsius {
+ key = strings.TrimSpace(key)
+ if key == "" {
+ continue
+ }
+ sensors.TemperatureCelsius[key] = value
+ }
+ if len(sensors.TemperatureCelsius) == 0 {
+ sensors.TemperatureCelsius = nil
+ }
}
- for key, value := range system.TemperatureCelsius {
- key = strings.TrimSpace(key)
- if key == "" {
+
+ // Surface API-reported disk temperatures as SMART sensor entries so the
+ // host Thermals card lists disks next to the CPU sensors — API-backed
+ // TrueNAS systems have no pulse-agent SMART sweep to supply them (#1573).
+ // Disks without a reading are skipped rather than rendered as 0°C.
+ for _, disk := range disks {
+ if disk.Temperature <= 0 {
+ continue
+ }
+ device := strings.TrimSpace(disk.Name)
+ if device == "" {
+ device = strings.TrimSpace(disk.ID)
+ }
+ if device == "" {
continue
}
- sensors.TemperatureCelsius[key] = value
+ sensors.SMART = append(sensors.SMART, unifiedresources.HostSMARTMeta{
+ Device: device,
+ Model: strings.TrimSpace(disk.Model),
+ Serial: strings.TrimSpace(disk.Serial),
+ Type: strings.TrimSpace(disk.Transport),
+ SizeBytes: disk.SizeBytes,
+ Temperature: disk.Temperature,
+ Health: healthFromDisk(disk),
+ Pool: strings.TrimSpace(disk.Pool),
+ })
}
- if len(sensors.TemperatureCelsius) == 0 {
+
+ if len(sensors.TemperatureCelsius) == 0 && len(sensors.SMART) == 0 {
return nil
}
return sensors
diff --git a/internal/truenas/provider_additional_test.go b/internal/truenas/provider_additional_test.go
index 99b5922bab..ff03537f12 100644
--- a/internal/truenas/provider_additional_test.go
+++ b/internal/truenas/provider_additional_test.go
@@ -95,3 +95,38 @@ func TestSystemStatusPromotesHealthySystemWhenStorageRiskExists(t *testing.T) {
t.Fatalf("systemStatus(healthy, nil risk) = %q, want %q", got, unifiedresources.StatusOnline)
}
}
+
+// API-backed TrueNAS systems have no pulse-agent SMART sweep, so the provider
+// must surface API-reported disk temperatures as SMART sensor entries for the
+// host Thermals card (#1573).
+func TestSensorMetaIncludesDiskTemperatures(t *testing.T) {
+ system := SystemInfo{
+ TemperatureCelsius: map[string]float64{"cpu_package": 55},
+ }
+ disks := []Disk{
+ {Name: "ada0", Model: "WDC", Serial: "S1", Transport: "ata", SizeBytes: 100, Temperature: 34, Pool: "tank", Status: "ONLINE"},
+ {Name: "ada1", Model: "WDC", Serial: "S2", Transport: "ata", SizeBytes: 100, Temperature: 0, Pool: "tank"},
+ }
+
+ sensors := sensorMetaFromTrueNASSystem(system, disks)
+ if sensors == nil {
+ t.Fatal("expected sensors")
+ }
+ if len(sensors.SMART) != 1 {
+ t.Fatalf("expected only disks with a reading as SMART entries, got %+v", sensors.SMART)
+ }
+ entry := sensors.SMART[0]
+ if entry.Device != "ada0" || entry.Temperature != 34 || entry.Pool != "tank" || entry.Health != "PASSED" {
+ t.Fatalf("unexpected SMART entry: %+v", entry)
+ }
+
+ // Disk-only systems (no CPU sensor payload) still get a sensors object.
+ diskOnly := sensorMetaFromTrueNASSystem(SystemInfo{}, disks)
+ if diskOnly == nil || len(diskOnly.SMART) != 1 || len(diskOnly.TemperatureCelsius) != 0 {
+ t.Fatalf("expected disk-only sensors, got %+v", diskOnly)
+ }
+
+ if sensorMetaFromTrueNASSystem(SystemInfo{}, nil) != nil {
+ t.Fatal("expected nil sensors when there is nothing to report")
+ }
+}
diff --git a/internal/truenas/types.go b/internal/truenas/types.go
index 6965502179..544bfe8b5e 100644
--- a/internal/truenas/types.go
+++ b/internal/truenas/types.go
@@ -47,6 +47,24 @@ type Pool struct {
TotalBytes int64
UsedBytes int64
FreeBytes int64
+ // DiskMembers are the leaf disks of the pool's vdev topology with their
+ // per-member ZFS state. pool.query attaches topology unconditionally on
+ // both CORE and SCALE, which makes it the only API source for disk→pool
+ // membership and per-disk health: disk.query carries neither a status
+ // nor a SMART field, and only reports pool membership behind an extra
+ // option the REST bridge cannot pass (#1573).
+ DiskMembers []PoolDiskMember
+}
+
+// PoolDiskMember is a leaf disk in a pool's vdev topology.
+type PoolDiskMember struct {
+ // Disk is the whole-disk device name (da0, sda) middleware resolves for
+ // every path-bearing leaf; Device is the partition/label device (da0p2).
+ Disk string
+ Device string
+ // Status is the per-member ZFS state: ONLINE, DEGRADED, FAULTED,
+ // OFFLINE, UNAVAIL, REMOVED (spares report AVAIL/INUSE).
+ Status string
}
// Dataset mirrors the subset of TrueNAS dataset fields needed for unified mapping.