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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Align TrueNAS storage with native queries
rcourtman179f88d72166
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.mdindex 72526816e3..7b1b7e7bb0 100644--- a/docs/release-control/v6/internal/subsystems/monitoring.md+++ b/docs/release-control/v6/internal/subsystems/monitoring.md@@ -123,6 +123,10 @@ truth for live infrastructure data.dataset, app, VM, share, and disk names from different appliances remaindistinct. Mock fixture metrics and seeded/live history must use the samescoped source keys as the TrueNAS provider metrics targets.+ 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.TrueNAS VMs and network shares follow the same provider-owned inventoryboundary: `vm.query` data publishes native `TrueNASData.VM` on canonical`vm` resources, while SMB/NFS share data from `sharing.smb.query` anddiff --git a/internal/truenas/client.go b/internal/truenas/client.goindex 4c8637d868..5074ea3f4e 100644--- a/internal/truenas/client.go+++ b/internal/truenas/client.go@@ -240,6 +240,43 @@ func (c *Client) GetSystemMetricHistory(ctx context.Context, duration time.Durat// GetPools returns storage pools.func (c *Client) GetPools(ctx context.Context) ([]Pool, error) {+ pools, err := c.getPoolsRPC(ctx)+ if err == nil {+ return pools, nil+ }+ restPools, restErr := c.getPoolsREST(ctx)+ if restErr != nil {+ return nil, fmt.Errorf("fetch truenas pools via rpc and rest: rpc=%w rest=%v", err, restErr)+ }+ return restPools, nil+}++func (c *Client) getPoolsRPC(ctx context.Context) ([]Pool, error) {+ var response []map[string]any+ if err := c.queryRPC(ctx, "pool.query", &response); err != nil {+ return nil, err+ }++ pools := make([]Pool, 0, len(response))+ for _, item := range response {+ id := strings.TrimSpace(readStringAny(item, "id"))+ name := strings.TrimSpace(readStringAny(item, "name"))+ if id == "" || id == "0" {+ 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"),+ })+ }+ return pools, nil+}++func (c *Client) getPoolsREST(ctx context.Context) ([]Pool, error) {var response []poolResponseif err := c.getJSON(ctx, http.MethodGet, "/pool", &response); err != nil {return nil, err@@ -266,6 +303,51 @@ func (c *Client) GetPools(ctx context.Context) ([]Pool, error) {// GetDatasets returns datasets and normalized capacity/read-only fields.func (c *Client) GetDatasets(ctx context.Context) ([]Dataset, error) {+ datasets, err := c.getDatasetsRPC(ctx)+ if err == nil {+ return datasets, nil+ }+ restDatasets, restErr := c.getDatasetsREST(ctx)+ if restErr != nil {+ return nil, fmt.Errorf("fetch truenas datasets via rpc and rest: rpc=%w rest=%v", err, restErr)+ }+ return restDatasets, nil+}++func (c *Client) getDatasetsRPC(ctx context.Context) ([]Dataset, error) {+ var response []map[string]any+ if err := c.queryRPC(ctx, "pool.dataset.query", &response); err != nil {+ return nil, err+ }++ datasets := make([]Dataset, 0, len(response))+ for _, item := range response {+ name := strings.TrimSpace(readStringAny(item, "name", "id"))+ id := strings.TrimSpace(readStringAny(item, "id"))+ if id == "" {+ id = name+ }+ poolName := strings.TrimSpace(readStringAny(item, "pool"))+ if poolName == "" {+ poolName = parentPoolFromDataset(name)+ }+ used := readInt64Any(item, "used", "used_bytes", "usedBytes")+ available := readInt64Any(item, "available", "avail", "avail_bytes", "available_bytes", "availableBytes")++ datasets = append(datasets, Dataset{+ ID: id,+ Name: name,+ Pool: poolName,+ UsedBytes: used,+ AvailBytes: available,+ Mounted: readBoolAny(item, "mounted"),+ ReadOnly: readBoolAny(item, "readonly", "read_only", "readOnly"),+ })+ }+ return datasets, nil+}++func (c *Client) getDatasetsREST(ctx context.Context) ([]Dataset, error) {var response []datasetResponseif err := c.getJSON(ctx, http.MethodGet, "/pool/dataset", &response); err != nil {return nil, err@@ -313,6 +395,28 @@ func (c *Client) GetDatasets(ctx context.Context) ([]Dataset, error) {// GetDisks returns the system disk inventory.func (c *Client) GetDisks(ctx context.Context) ([]Disk, error) {+ disks, err := c.getDisksRPC(ctx)+ if err == nil {+ return disks, nil+ }+ restDisks, restErr := c.getDisksREST(ctx)+ if restErr != nil {+ return nil, fmt.Errorf("fetch truenas disks via rpc and rest: rpc=%w rest=%v", err, restErr)+ }+ return restDisks, nil+}++func (c *Client) getDisksRPC(ctx context.Context) ([]Disk, error) {+ var response []map[string]any+ if err := c.callRPC(ctx, "disk.query", []any{[]any{}, map[string]any{+ "extra": map[string]any{"pools": true},+ }}, &response); err != nil {+ return nil, err+ }+ return c.disksFromMaps(ctx, response)+}++func (c *Client) getDisksREST(ctx context.Context) ([]Disk, error) {var response []diskResponseif err := c.getJSON(ctx, http.MethodGet, "/disk", &response); err != nil {return nil, err@@ -363,6 +467,58 @@ func (c *Client) GetDisks(ctx context.Context) ([]Disk, error) {return disks, nil}+func (c *Client) disksFromMaps(ctx context.Context, response []map[string]any) ([]Disk, error) {+ identifiers := diskReportingIdentifiersFromMaps(response)+ temperatures, err := c.getDiskTemperaturesWithFallback(ctx, identifiers)+ if err != nil {+ temperatures = nil+ }+ aggregates, err := c.getDiskTemperatureAggregates(ctx, identifiers, defaultDiskTemperatureAggregateWindowDays)+ if err != nil {+ aggregates = nil+ }++ disks := make([]Disk, 0, len(response))+ for _, item := range response {+ rotationRate := readIntAny(item, "rotationrate", "rotation_rate", "rotationRate")+ rotational := rotationRate > 0+ diskType := strings.ToLower(strings.TrimSpace(readStringAny(item, "type")))+ if rotationRate == 0 {+ switch diskType {+ case "hdd":+ rotational = true+ case "ssd", "nvme":+ rotational = false+ }+ }++ diskID := strings.TrimSpace(readStringAny(item, "identifier", "id"))+ if diskID == "" {+ diskID = strings.TrimSpace(readStringAny(item, "name", "devname"))+ }+ name := strings.TrimSpace(readStringAny(item, "name", "devname"))+ disk := Disk{+ ID: diskID,+ Name: name,+ Pool: strings.TrimSpace(readStringAny(item, "pool", "pool_name", "poolName")),+ Status: strings.TrimSpace(readStringAny(item, "status")),+ Model: strings.TrimSpace(readStringAny(item, "model")),+ Serial: strings.TrimSpace(readStringAny(item, "serial")),+ SizeBytes: readInt64Any(item, "size", "size_bytes", "sizeBytes"),+ Temperature: temperatureForTrueNASDiskMap(temperatures, item),+ TemperatureAggregate: temperatureAggregateForTrueNASDiskMap(aggregates, item),+ Transport: strings.ToLower(strings.TrimSpace(readStringAny(item, "bus", "transport"))),+ Rotational: rotational,+ }+ if disk.Transport == "" {+ disk.Transport = diskType+ }+ disks = append(disks, disk)+ }++ return disks, nil+}+// 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)@@ -443,6 +599,20 @@ func diskReportingIdentifiers(disks []diskResponse) []string {return dedupeStrings(identifiers)}+func diskReportingIdentifiersFromMaps(disks []map[string]any) []string {+ identifiers := make([]string, 0, len(disks))+ for _, disk := range disks {+ if name := strings.TrimSpace(readStringAny(disk, "name", "devname")); name != "" {+ identifiers = append(identifiers, name)+ continue+ }+ if identifier := strings.TrimSpace(readStringAny(disk, "identifier", "id")); identifier != "" {+ identifiers = append(identifiers, identifier)+ }+ }+ return dedupeStrings(identifiers)+}+func (c *Client) getDiskTemperaturesFromReporting(ctx context.Context, identifiers []string) (map[string]int, error) {identifiers = dedupeStrings(identifiers)if len(identifiers) == 0 {@@ -483,6 +653,46 @@ func (c *Client) getDiskTemperatureAggregates(ctx context.Context, identifiers [// GetAlerts returns active and dismissed TrueNAS alerts.func (c *Client) GetAlerts(ctx context.Context) ([]Alert, error) {+ alerts, err := c.getAlertsRPC(ctx)+ if err == nil {+ return alerts, nil+ }+ restAlerts, restErr := c.getAlertsREST(ctx)+ if restErr != nil {+ return nil, fmt.Errorf("fetch truenas alerts via rpc and rest: rpc=%w rest=%v", err, restErr)+ }+ return restAlerts, nil+}++func (c *Client) getAlertsRPC(ctx context.Context) ([]Alert, error) {+ var response []map[string]any+ if err := c.callRPC(ctx, "alert.list", []any{}, &response); err != nil {+ return nil, err+ }++ alerts := make([]Alert, 0, len(response))+ for _, item := range response {+ id := strings.TrimSpace(readStringAny(item, "uuid", "id", "key"))+ if id == "" {+ id = strings.TrimSpace(readStringAny(item, "klass"))+ }+ var datetime time.Time+ if t := readTimeAny(item, "datetime", "last_occurrence", "lastOccurrence"); t != nil {+ datetime = *t+ }+ alerts = append(alerts, Alert{+ ID: id,+ Level: strings.TrimSpace(readStringAny(item, "level")),+ Message: strings.TrimSpace(readStringAny(item, "formatted", "text", "message", "klass")),+ Source: strings.TrimSpace(readStringAny(item, "source", "node")),+ Dismissed: readBoolAny(item, "dismissed"),+ Datetime: datetime,+ })+ }+ return alerts, nil+}++func (c *Client) getAlertsREST(ctx context.Context) ([]Alert, error) {var response []alertResponseif err := c.getJSON(ctx, http.MethodGet, "/alert/list", &response); err != nil {return nil, err@@ -1113,6 +1323,26 @@ func temperatureForTrueNASDisk(temperatures map[string]int, item diskResponse) ireturn 0}+func temperatureForTrueNASDiskMap(temperatures map[string]int, item map[string]any) int {+ if len(temperatures) == 0 {+ return 0+ }+ keys := []string{+ strings.TrimSpace(readStringAny(item, "name", "devname")),+ strings.TrimSpace(readStringAny(item, "identifier", "id")),+ strings.TrimSpace(readStringAny(item, "serial")),+ }+ for _, key := range keys {+ if key == "" {+ continue+ }+ if temperature, ok := temperatures[key]; ok {+ return temperature+ }+ }+ return 0+}+func temperatureAggregateForTrueNASDisk(aggregates map[string]DiskTemperatureAggregate, item diskResponse) DiskTemperatureAggregate {if len(aggregates) == 0 {return DiskTemperatureAggregate{}@@ -1133,6 +1363,26 @@ func temperatureAggregateForTrueNASDisk(aggregates map[string]DiskTemperatureAggreturn DiskTemperatureAggregate{}}+func temperatureAggregateForTrueNASDiskMap(aggregates map[string]DiskTemperatureAggregate, item map[string]any) DiskTemperatureAggregate {+ if len(aggregates) == 0 {+ return DiskTemperatureAggregate{}+ }+ keys := []string{+ strings.TrimSpace(readStringAny(item, "name", "devname")),+ strings.TrimSpace(readStringAny(item, "identifier", "id")),+ strings.TrimSpace(readStringAny(item, "serial")),+ }+ for _, key := range keys {+ if key == "" {+ continue+ }+ if aggregate, ok := aggregates[key]; ok {+ return aggregate+ }+ }+ return DiskTemperatureAggregate{}+}+func parseDiskTemperatures(raw any) map[string]int {switch typed := raw.(type) {case nil:@@ -2560,7 +2810,7 @@ func readBoolAny(record map[string]any, keys ...string) bool {return true}case map[string]any:- if parsed, ok := firstAny(typed, "parsed", "rawvalue", "value"); ok {+ if parsed, ok := firstAny(typed, "parsed", "rawvalue", "value", "raw"); ok {if readBoolAny(map[string]any{"value": parsed}, "value") {return true}@@ -3665,6 +3915,10 @@ func parseInt64Any(value any) (int64, bool) {if v, err := strconv.ParseInt(s, 10, 64); err == nil {return v, true}+ case map[string]any:+ if parsed, ok := firstAny(typed, "parsed", "value", "rawvalue", "raw"); ok {+ return parseInt64Any(parsed)+ }}return 0, false}@@ -3692,7 +3946,7 @@ func parseFloat64Any(value any) (float64, bool) {return v, true}case map[string]any:- if parsed, ok := firstAny(typed, "parsed", "value", "rawvalue"); ok {+ if parsed, ok := firstAny(typed, "parsed", "value", "rawvalue", "raw"); ok {return parseFloat64Any(parsed)}}diff --git a/internal/truenas/client_test.go b/internal/truenas/client_test.goindex 104e76fe5f..1747950b68 100644--- a/internal/truenas/client_test.go+++ b/internal/truenas/client_test.go@@ -277,6 +277,121 @@ func TestFetchSnapshot(t *testing.T) {}}+func TestGetPoolsDatasetsAndAlertsUseNativeQueryShapes(t *testing.T) {+ server := newMockServerWithRPC(t, map[string]apiResponse{+ "/api/v2.0/pool": {status: http.StatusInternalServerError, body: `{"error":"legacy pool endpoint should not be used"}`},+ "/api/v2.0/pool/dataset": {status: http.StatusInternalServerError, body: `{"error":"legacy dataset endpoint should not be used"}`},+ "/api/v2.0/alert/list": {status: http.StatusInternalServerError, body: `{"error":"legacy alert endpoint should not be used"}`},+ }, nil, func(t *testing.T, conn *websocket.Conn) {+ authReq := readRPCRequest(t, conn)+ if authReq.Method != "auth.login_with_api_key" {+ t.Fatalf("expected api-key auth method, got %q", authReq.Method)+ }+ writeRPCResult(t, conn, authReq.ID, true)++ request := readRPCRequest(t, conn)+ switch request.Method {+ case "pool.query":+ assertQueryParams(t, request.Params, "pool.query")+ writeRPCResult(t, conn, request.ID, defaultRoutePayloadMaps(t, "/api/v2.0/pool"))+ case "pool.dataset.query":+ assertQueryParams(t, request.Params, "pool.dataset.query")+ writeRPCResult(t, conn, request.ID, defaultRoutePayloadMaps(t, "/api/v2.0/pool/dataset"))+ case "alert.list":+ params, ok := request.Params.([]any)+ if !ok || len(params) != 0 {+ t.Fatalf("expected alert.list to use no params, got %#v", request.Params)+ }+ writeRPCResult(t, conn, request.ID, defaultRoutePayloadMaps(t, "/api/v2.0/alert/list"))+ default:+ t.Fatalf("unexpected rpc method %q", request.Method)+ }+ })+ t.Cleanup(server.Close)++ client := mustClientForServer(t, server.URL, ClientConfig{APIKey: "api-key"})+ pools, err := client.GetPools(context.Background())+ if err != nil {+ t.Fatalf("GetPools() error = %v", err)+ }+ if len(pools) != 1 || pools[0].Name != "tank" || pools[0].UsedBytes != 400 {+ t.Fatalf("unexpected native pool mapping: %+v", pools)+ }++ datasets, err := client.GetDatasets(context.Background())+ if err != nil {+ t.Fatalf("GetDatasets() error = %v", err)+ }+ if len(datasets) != 1 || datasets[0].ID != "tank/apps" || datasets[0].Pool != "tank" || datasets[0].UsedBytes != 12345 {+ t.Fatalf("unexpected native dataset mapping: %+v", datasets)+ }++ alerts, err := client.GetAlerts(context.Background())+ if err != nil {+ t.Fatalf("GetAlerts() error = %v", err)+ }+ if len(alerts) != 1 || alerts[0].ID != "a1" || alerts[0].Level != "WARNING" {+ t.Fatalf("unexpected native alert mapping: %+v", alerts)+ }+}++func TestGetDisksUsesNativeDiskQueryShape(t *testing.T) {+ connectionCount := 0+ server := newMockServerWithRPC(t, map[string]apiResponse{+ "/api/v2.0/disk": {status: http.StatusInternalServerError, body: `{"error":"legacy disk endpoint should not be used"}`},+ "/api/v2.0/disk/temperatures": {+ body: `{"sda":34}`,+ },+ }, nil, func(t *testing.T, conn *websocket.Conn) {+ authReq := readRPCRequest(t, conn)+ if authReq.Method != "auth.login_with_api_key" {+ t.Fatalf("expected api-key auth method, got %q", authReq.Method)+ }+ writeRPCResult(t, conn, authReq.ID, true)++ connectionCount+++ request := readRPCRequest(t, conn)+ switch connectionCount {+ case 1:+ if request.Method != "disk.query" {+ t.Fatalf("expected disk.query, got %q", request.Method)+ }+ params, ok := request.Params.([]any)+ if !ok || len(params) != 2 {+ t.Fatalf("expected disk.query filters/options params, got %#v", request.Params)+ }+ writeRPCResult(t, conn, request.ID, defaultRoutePayloadMaps(t, "/api/v2.0/disk")[:1])+ case 2:+ if request.Method != "disk.temperature_agg" {+ t.Fatalf("expected disk.temperature_agg, got %q", request.Method)+ }+ writeRPCResult(t, conn, request.ID, map[string]any{+ "sda": map[string]any{+ "min": 29.0,+ "avg": 32.8,+ "max": 38.0,+ "window_days": 7,+ },+ })+ default:+ t.Fatalf("unexpected extra websocket connection %d", connectionCount)+ }+ })+ t.Cleanup(server.Close)++ client := mustClientForServer(t, server.URL, ClientConfig{APIKey: "api-key"})+ disks, err := client.GetDisks(context.Background())+ if err != nil {+ t.Fatalf("GetDisks() error = %v", err)+ }+ if len(disks) != 1 {+ t.Fatalf("expected 1 disk, got %d", len(disks))+ }+ if disks[0].Name != "sda" || disks[0].Temperature != 34 || disks[0].TemperatureAggregate.MaxCelsius != 38 {+ t.Fatalf("unexpected native disk mapping: %+v", disks[0])+ }+}+func TestGetVMsParsesNativeVMQueryShape(t *testing.T) {server := newMockServerWithRPC(t, map[string]apiResponse{}, nil, func(t *testing.T, conn *websocket.Conn) {authReq := readRPCRequest(t, conn)@@ -1041,6 +1156,11 @@ func TestGetDisksFallsBackToReportingRPCWhenTemperatureEndpointUnavailable(t *terequest := readRPCRequest(t, conn)switch connectionCount {case 1:+ if request.Method != "disk.query" {+ t.Fatalf("expected disk.query, got %q", request.Method)+ }+ writeRPCResult(t, conn, request.ID, defaultRoutePayloadMaps(t, "/api/v2.0/disk")[:1])+ case 2:if request.Method != "reporting.get_data" {t.Fatalf("expected reporting.get_data, got %q", request.Method)}@@ -1057,7 +1177,7 @@ func TestGetDisksFallsBackToReportingRPCWhenTemperatureEndpointUnavailable(t *te"start": time.Now().Add(-5 * time.Minute).Unix(),"end": time.Now().Unix(),}})- case 2:+ case 3:if request.Method != "disk.temperature_agg" {t.Fatalf("expected disk.temperature_agg, got %q", request.Method)}@@ -1092,6 +1212,7 @@ func TestGetDisksFallsBackToReportingRPCWhenTemperatureEndpointUnavailable(t *te}func TestGetDisksIncludesDiskTemperatureAggregatesFromRPC(t *testing.T) {+ connectionCount := 0server := newMockServerWithRPC(t, map[string]apiResponse{"/api/v2.0/disk": {body: `[{"identifier":"{disk-1}","name":"sda","serial":"SER-A","size":1000000,"model":"Seagate","type":"HDD","pool":"tank","bus":"SATA","rotationrate":7200,"status":"ONLINE"}]`,@@ -1106,7 +1227,15 @@ func TestGetDisksIncludesDiskTemperatureAggregatesFromRPC(t *testing.T) {}writeRPCResult(t, conn, authReq.ID, true)+ connectionCount++aggregateReq := readRPCRequest(t, conn)+ if connectionCount == 1 {+ if aggregateReq.Method != "disk.query" {+ t.Fatalf("expected disk.query, got %q", aggregateReq.Method)+ }+ writeRPCResult(t, conn, aggregateReq.ID, defaultRoutePayloadMaps(t, "/api/v2.0/disk")[:1])+ return+ }if aggregateReq.Method != "disk.temperature_agg" {t.Fatalf("expected disk.temperature_agg, got %q", aggregateReq.Method)}@@ -1405,13 +1534,32 @@ func TestClientCloseNilSafe(t *testing.T) {func defaultAppQueryPayload(t *testing.T) []map[string]any {t.Helper()+ return defaultRoutePayloadMaps(t, "/api/v2.0/app")+}++func defaultRoutePayloadMaps(t *testing.T, route string) []map[string]any {+ t.Helper()++ response, ok := defaultAPIResponses()[route]+ if !ok {+ t.Fatalf("missing default fixture route %q", route)+ }var payload []map[string]any- if err := json.Unmarshal([]byte(defaultAPIResponses()["/api/v2.0/app"].body), &payload); err != nil {- t.Fatalf("unmarshal default app fixture: %v", err)+ if err := json.Unmarshal([]byte(response.body), &payload); err != nil {+ t.Fatalf("unmarshal default fixture route %q: %v", route, err)}return payload}+func assertQueryParams(t *testing.T, params any, method string) {+ t.Helper()++ values, ok := params.([]any)+ if !ok || len(values) != 2 {+ t.Fatalf("expected %s filters/options params, got %#v", method, params)+ }+}+func defaultAPIResponses() map[string]apiResponse {return map[string]apiResponse{"/api/v2.0/system/info": {