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
Add SMART disk lifecycle monitoring with historical charts
rcourtman5c1874874224
diff --git a/frontend-modern/src/api/charts.ts b/frontend-modern/src/api/charts.tsindex 62feb0cf9d..85119c98aa 100644--- a/frontend-modern/src/api/charts.ts+++ b/frontend-modern/src/api/charts.ts@@ -49,7 +49,7 @@ export interface ChartsResponse {// Persistent metrics history types (SQLite-backed, longer retention)export type HistoryTimeRange = '1h' | '6h' | '12h' | '24h' | '7d' | '30d' | '90d';-export type ResourceType = 'node' | 'guest' | 'vm' | 'container' | 'storage' | 'docker' | 'dockerHost' | 'k8s' | 'host';+export type ResourceType = 'node' | 'guest' | 'vm' | 'container' | 'storage' | 'docker' | 'dockerHost' | 'k8s' | 'host' | 'disk';export interface MetricsHistoryParams {resourceType: ResourceType;diff --git a/frontend-modern/src/components/Storage/DiskDetail.tsx b/frontend-modern/src/components/Storage/DiskDetail.tsxnew file mode 100644index 0000000000..01f54114d6--- /dev/null+++ b/frontend-modern/src/components/Storage/DiskDetail.tsx@@ -0,0 +1,270 @@+import { Component, Show, createSignal } from 'solid-js';+import type { PhysicalDisk } from '@/types/api';+import { diskResourceId } from '@/types/api';+import { HistoryChart } from '@/components/shared/HistoryChart';+import type { HistoryTimeRange } from '@/api/charts';+import { formatTemperature } from '@/utils/temperature';++/** Format power-on hours into human-readable form. */+function formatPowerOnHours(hours: number): string {+ if (hours >= 8760) {+ return `${(hours / 8760).toFixed(1)} years`;+ }+ if (hours >= 24) {+ return `${Math.round(hours / 24)} days`;+ }+ return `${hours} hours`;+}++/** Color class for attribute values. */+function attrColor(ok: boolean): string {+ return ok+ ? 'text-green-600 dark:text-green-400'+ : 'text-red-600 dark:text-red-400';+}++interface DiskDetailProps {+ disk: PhysicalDisk;+}++export const DiskDetail: Component<DiskDetailProps> = (props) => {+ const [chartRange, setChartRange] = createSignal<HistoryTimeRange>('24h');++ const resId = () => diskResourceId(props.disk);+ const attrs = () => props.disk.smartAttributes;+ const isNvme = () => props.disk.type?.toLowerCase() === 'nvme';++ return (+ <div class="space-y-3">+ {/* Disk info */}+ <div class="flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px]">+ <span class="font-semibold text-gray-900 dark:text-gray-100">+ {props.disk.model || 'Unknown Disk'}+ </span>+ <span class="text-gray-500 dark:text-gray-400 font-mono">+ {props.disk.devPath}+ </span>+ <span class="text-gray-500 dark:text-gray-400">+ {props.disk.node}+ </span>+ <Show when={props.disk.serial}>+ <span class="text-gray-400 font-mono">+ S/N: {props.disk.serial}+ </span>+ </Show>+ </div>++ {/* SMART attribute cards */}+ <Show when={attrs()}>+ <div class="flex flex-wrap gap-3 [&>*]:flex-1 [&>*]:basis-[calc(16.666%-0.5rem)] [&>*]:min-w-[120px]">+ {/* Common attributes */}+ <Show when={attrs()!.powerOnHours != null}>+ <AttrCard+ label="Power-On Time"+ value={formatPowerOnHours(attrs()!.powerOnHours!)}+ ok={true}+ />+ </Show>+ <Show when={props.disk.temperature > 0}>+ <AttrCard+ label="Temperature"+ value={formatTemperature(props.disk.temperature)}+ ok={props.disk.temperature <= 60}+ />+ </Show>+ <Show when={attrs()!.powerCycles != null}>+ <AttrCard+ label="Power Cycles"+ value={attrs()!.powerCycles!.toLocaleString()}+ ok={true}+ />+ </Show>++ {/* SATA-specific */}+ <Show when={!isNvme() && attrs()!.reallocatedSectors != null}>+ <AttrCard+ label="Reallocated Sectors"+ value={attrs()!.reallocatedSectors!.toString()}+ ok={attrs()!.reallocatedSectors === 0}+ />+ </Show>+ <Show when={!isNvme() && attrs()!.pendingSectors != null}>+ <AttrCard+ label="Pending Sectors"+ value={attrs()!.pendingSectors!.toString()}+ ok={attrs()!.pendingSectors === 0}+ />+ </Show>+ <Show when={!isNvme() && attrs()!.offlineUncorrectable != null}>+ <AttrCard+ label="Offline Uncorrectable"+ value={attrs()!.offlineUncorrectable!.toString()}+ ok={attrs()!.offlineUncorrectable === 0}+ />+ </Show>+ <Show when={!isNvme() && attrs()!.udmaCrcErrors != null}>+ <AttrCard+ label="CRC Errors"+ value={attrs()!.udmaCrcErrors!.toString()}+ ok={attrs()!.udmaCrcErrors === 0}+ />+ </Show>++ {/* NVMe-specific */}+ <Show when={isNvme() && attrs()!.percentageUsed != null}>+ <AttrCard+ label="Life Used"+ value={`${attrs()!.percentageUsed}%`}+ ok={(attrs()!.percentageUsed ?? 0) <= 90}+ />+ </Show>+ <Show when={isNvme() && attrs()!.availableSpare != null}>+ <AttrCard+ label="Available Spare"+ value={`${attrs()!.availableSpare}%`}+ ok={(attrs()!.availableSpare ?? 0) >= 20}+ />+ </Show>+ <Show when={isNvme() && attrs()!.mediaErrors != null}>+ <AttrCard+ label="Media Errors"+ value={attrs()!.mediaErrors!.toString()}+ ok={attrs()!.mediaErrors === 0}+ />+ </Show>+ <Show when={isNvme() && attrs()!.unsafeShutdowns != null}>+ <AttrCard+ label="Unsafe Shutdowns"+ value={attrs()!.unsafeShutdowns!.toLocaleString()}+ ok={true}+ />+ </Show>+ </div>+ </Show>++ {/* Historical charts */}+ <Show+ when={resId()}+ fallback={+ <div class="rounded border border-gray-200 bg-white/70 p-3 shadow-sm dark:border-gray-600/70 dark:bg-gray-900/30 text-center text-[11px] text-gray-500 dark:text-gray-400">+ Install the Pulse host agent for detailed SMART monitoring and historical charts.+ </div>+ }+ >+ <div class="space-y-2">+ {/* Time range selector */}+ <div class="flex items-center justify-between">+ <span class="text-[11px] font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400">+ History+ </span>+ <select+ value={chartRange()}+ onChange={(e) => setChartRange(e.currentTarget.value as HistoryTimeRange)}+ class="text-[11px] font-medium pl-2 pr-6 py-1 rounded-md border border-gray-200 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-200 cursor-pointer focus:ring-1 focus:ring-blue-500 focus:border-blue-500 appearance-none"+ style={{ "background-image": "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%239ca3af' stroke-width='2'%3E%3Cpath d='M6 9l6 6 6-6'/%3E%3C/svg%3E\")", "background-repeat": "no-repeat", "background-position": "right 6px center" }}+ >+ <option value="1h">Last 1 hour</option>+ <option value="6h">Last 6 hours</option>+ <option value="12h">Last 12 hours</option>+ <option value="24h">Last 24 hours</option>+ <option value="7d">Last 7 days</option>+ <option value="30d">Last 30 days</option>+ <option value="90d">Last 90 days</option>+ </select>+ </div>++ {/* Charts grid */}+ <div class="flex flex-wrap gap-3 [&>*]:flex-1 [&>*]:basis-[calc(33.333%-0.5rem)] [&>*]:min-w-[250px]">+ {/* Temperature chart (all disk types) */}+ <Show when={props.disk.temperature > 0}>+ <div class="rounded border border-gray-200 bg-white/70 p-3 shadow-sm dark:border-gray-600/70 dark:bg-gray-900/30">+ <HistoryChart+ resourceType="disk"+ resourceId={resId()!}+ metric="smart_temp"+ label="Temperature"+ unit="C"+ height={120}+ color="#ef4444"+ range={chartRange()}+ hideSelector={true}+ compact={true}+ hideLock={true}+ />+ </div>+ </Show>++ {/* SATA charts */}+ <Show when={!isNvme() && attrs()?.reallocatedSectors != null}>+ <div class="rounded border border-gray-200 bg-white/70 p-3 shadow-sm dark:border-gray-600/70 dark:bg-gray-900/30">+ <HistoryChart+ resourceType="disk"+ resourceId={resId()!}+ metric="smart_reallocated_sectors"+ label="Reallocated Sectors"+ unit="sectors"+ height={120}+ color="#f59e0b"+ range={chartRange()}+ hideSelector={true}+ compact={true}+ hideLock={true}+ />+ </div>+ </Show>++ {/* NVMe charts */}+ <Show when={isNvme() && attrs()?.percentageUsed != null}>+ <div class="rounded border border-gray-200 bg-white/70 p-3 shadow-sm dark:border-gray-600/70 dark:bg-gray-900/30">+ <HistoryChart+ resourceType="disk"+ resourceId={resId()!}+ metric="smart_percentage_used"+ label="Life Used"+ unit="%"+ height={120}+ color="#f59e0b"+ range={chartRange()}+ hideSelector={true}+ compact={true}+ hideLock={true}+ />+ </div>+ </Show>+ <Show when={isNvme() && attrs()?.availableSpare != null}>+ <div class="rounded border border-gray-200 bg-white/70 p-3 shadow-sm dark:border-gray-600/70 dark:bg-gray-900/30">+ <HistoryChart+ resourceType="disk"+ resourceId={resId()!}+ metric="smart_available_spare"+ label="Available Spare"+ unit="%"+ height={120}+ color="#10b981"+ range={chartRange()}+ hideSelector={true}+ compact={true}+ hideLock={true}+ />+ </div>+ </Show>+ </div>+ </div>+ </Show>+ </div>+ );+};++/** Small attribute summary card matching the NodeDrawer card pattern. */+const AttrCard: Component<{ label: string; value: string; ok: boolean }> = (props) => {+ return (+ <div class="rounded border border-gray-200 bg-white/70 p-3 shadow-sm dark:border-gray-600/70 dark:bg-gray-900/30">+ <div class="text-[10px] font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-0.5">+ {props.label}+ </div>+ <div class={`text-sm font-semibold ${attrColor(props.ok)}`}>+ {props.value}+ </div>+ </div>+ );+};diff --git a/frontend-modern/src/components/Storage/DiskList.tsx b/frontend-modern/src/components/Storage/DiskList.tsxindex 3c676ea7ad..cc3023989f 100644--- a/frontend-modern/src/components/Storage/DiskList.tsx+++ b/frontend-modern/src/components/Storage/DiskList.tsx@@ -1,9 +1,31 @@-import { Component, For, Show, createMemo } from 'solid-js';+import { Component, For, Show, createMemo, createSignal } from 'solid-js';import { Card } from '@/components/shared/Card';import { formatBytes } from '@/utils/format';import { formatTemperature } from '@/utils/temperature';import type { PhysicalDisk } from '@/types/api';import { useWebSocket } from '@/App';+import { DiskDetail } from './DiskDetail';++/** Format power-on hours into human-readable form (e.g., "2.3y", "140d", "5h"). */+function formatPowerOnHours(hours: number): string {+ if (hours >= 8760) {+ return `${(hours / 8760).toFixed(1)}y`;+ }+ if (hours >= 24) {+ return `${Math.round(hours / 24)}d`;+ }+ return `${hours}h`;+}++/** Returns true if any critical SMART counters are non-zero. */+function hasSmartWarning(disk: PhysicalDisk): boolean {+ const attrs = disk.smartAttributes;+ if (!attrs) return false;+ if (attrs.reallocatedSectors && attrs.reallocatedSectors > 0) return true;+ if (attrs.pendingSectors && attrs.pendingSectors > 0) return true;+ if (attrs.mediaErrors && attrs.mediaErrors > 0) return true;+ return false;+}interface DiskListProps {disks: PhysicalDisk[];@@ -13,6 +35,7 @@ interface DiskListProps {export const DiskList: Component<DiskListProps> = (props) => {const { state } = useWebSocket();+ const [selectedDisk, setSelectedDisk] = createSignal<PhysicalDisk | null>(null);// Check if there are any PVE nodes configuredconst hasPVENodes = createMemo(() => {@@ -111,6 +134,15 @@ export const DiskList: Component<DiskListProps> = (props) => {return node?.name || null;});+ const handleRowClick = (disk: PhysicalDisk) => {+ const current = selectedDisk();+ if (current && current.id === disk.id) {+ setSelectedDisk(null);+ } else {+ setSelectedDisk(disk);+ }+ };+return (<div><Show when={filteredDisks().length === 0}>@@ -152,51 +184,67 @@ export const DiskList: Component<DiskListProps> = (props) => {<Show when={filteredDisks().length > 0}><Card padding="none" tone="glass" class="overflow-hidden"><div class="overflow-x-auto">- <table class="w-full" style={{ "min-width": "750px" }}>+ <table class="w-full" style={{ "min-width": "800px" }}><thead><tr class="bg-gray-50 dark:bg-gray-700/50 text-gray-600 dark:text-gray-300 border-b border-gray-200 dark:border-gray-600"><th class="px-1 py-1.5 text-left text-[11px] sm:text-xs font-medium uppercase tracking-wider w-[10%]">Node</th>- <th class="px-1 py-1.5 text-left text-[11px] sm:text-xs font-medium uppercase tracking-wider w-[10%]">+ <th class="px-1 py-1.5 text-left text-[11px] sm:text-xs font-medium uppercase tracking-wider w-[9%]">Device</th>- <th class="px-1 py-1.5 text-left text-[11px] sm:text-xs font-medium uppercase tracking-wider w-[20%]">+ <th class="px-1 py-1.5 text-left text-[11px] sm:text-xs font-medium uppercase tracking-wider w-[19%]">Model</th>- <th class="px-1 py-1.5 text-left text-[11px] sm:text-xs font-medium uppercase tracking-wider w-[8%]">+ <th class="px-1 py-1.5 text-left text-[11px] sm:text-xs font-medium uppercase tracking-wider w-[7%]">Type</th>- <th class="px-1 py-1.5 text-left text-[11px] sm:text-xs font-medium uppercase tracking-wider w-[8%]">+ <th class="px-1 py-1.5 text-left text-[11px] sm:text-xs font-medium uppercase tracking-wider w-[7%]">FS</th><th class="px-1 py-1.5 text-left text-[11px] sm:text-xs font-medium uppercase tracking-wider w-[10%]">Health</th>- <th class="px-1 py-1.5 text-left text-[11px] sm:text-xs font-medium uppercase tracking-wider w-[15%]">+ <th class="px-1 py-1.5 text-left text-[11px] sm:text-xs font-medium uppercase tracking-wider w-[13%]">SSD Life</th><th class="px-1 py-1.5 text-left text-[11px] sm:text-xs font-medium uppercase tracking-wider w-[8%]">+ Power-On+ </th>+ <th class="px-1 py-1.5 text-left text-[11px] sm:text-xs font-medium uppercase tracking-wider w-[7%]">Temp</th><th class="px-1 py-1.5 text-left text-[11px] sm:text-xs font-medium uppercase tracking-wider w-[10%]">Size</th>- <th class="px-1 py-1.5 w-8"></th></tr></thead><tbody class="divide-y divide-gray-200 dark:divide-gray-700"><For each={filteredDisks()}>{(disk) => {const health = getHealthStatus(disk);+ const isSelected = () => selectedDisk()?.id === disk.id;+ const warning = hasSmartWarning(disk);return (<>- <tr class="hover:bg-gray-50 dark:hover:bg-gray-700/30 transition-colors">+ <tr+ class={`cursor-pointer transition-colors ${isSelected() ? 'bg-blue-50 dark:bg-blue-900/20' : 'hover:bg-gray-50 dark:hover:bg-gray-700/30'}`}+ onClick={() => handleRowClick(disk)}+ ><td class="px-1 py-1.5 text-xs">- <span class="font-medium text-gray-900 dark:text-gray-100">- {disk.node}- </span>+ <div class="flex items-center gap-1.5 min-w-0">+ <div+ class={`cursor-pointer transition-transform duration-200 ${isSelected() ? 'rotate-90' : ''}`}+ >+ <svg class="w-3.5 h-3.5 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300" fill="none" viewBox="0 0 24 24" stroke="currentColor">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />+ </svg>+ </div>+ <span class="font-medium text-gray-900 dark:text-gray-100">+ {disk.node}+ </span>+ </div></td><td class="px-1 py-1.5 text-xs"><span class="font-mono text-gray-600 dark:text-gray-400">@@ -231,6 +279,11 @@ export const DiskList: Component<DiskListProps> = (props) => {>{health.text}</span>+ <Show when={warning}>+ <span class="ml-1 text-yellow-500 dark:text-yellow-400" title="SMART warning: critical counters non-zero">+ ⚠+ </span>+ </Show></td><td class="px-1 py-1.5 text-xs"><Show@@ -255,6 +308,16 @@ export const DiskList: Component<DiskListProps> = (props) => {</div></Show></td>+ <td class="px-1 py-1.5 text-xs">+ <Show+ when={disk.smartAttributes?.powerOnHours != null}+ fallback={<span class="text-gray-400">-</span>}+ >+ <span class="text-gray-700 dark:text-gray-300">+ {formatPowerOnHours(disk.smartAttributes!.powerOnHours!)}+ </span>+ </Show>+ </td><td class="px-1 py-1.5 text-xs"><Showwhen={typeof disk.temperature === 'number'}@@ -277,8 +340,14 @@ export const DiskList: Component<DiskListProps> = (props) => {{formatBytes(disk.size)}</span></td>- <td class="px-1 py-1.5"></td></tr>+ <Show when={isSelected()}>+ <tr>+ <td colSpan={10} class="bg-gray-50/50 dark:bg-gray-900/20 px-4 py-4 border-b border-gray-100 dark:border-gray-700 shadow-inner">+ <DiskDetail disk={disk} />+ </td>+ </tr>+ </Show></>);}}diff --git a/frontend-modern/src/components/shared/HistoryChart.tsx b/frontend-modern/src/components/shared/HistoryChart.tsxindex 794545eeb3..3ba406dc00 100644--- a/frontend-modern/src/components/shared/HistoryChart.tsx+++ b/frontend-modern/src/components/shared/HistoryChart.tsx@@ -13,10 +13,21 @@ import { formatBytes } from '@/utils/format';import { calculateOptimalPoints } from '@/utils/downsample';+/** Format a tooltip value according to the metric unit. */+function formatTooltipValue(value: number, unit?: string): string {+ if (unit === '%') return `${value.toFixed(1)}%`;+ if (unit === 'B/s') return `${formatBytes(value)}/s`;+ if (unit === 'C') return `${Math.round(value)}°C`;+ // If no unit or unrecognized, try byte formatting for large values, plain number for small+ if (!unit) return formatBytes(value);+ // Generic numeric with unit suffix+ return `${Number.isInteger(value) ? value : value.toFixed(1)} ${unit}`;+}+interface HistoryChartProps {resourceType: ResourceType;resourceId: string;- metric: 'cpu' | 'memory' | 'disk' | 'diskread' | 'diskwrite' | 'netin' | 'netout';+ metric: string;height?: number;color?: string;label?: string;@@ -246,6 +257,18 @@ export const HistoryChart: Component<HistoryChartProps> = (props) => {if (props.metric === 'memory') mainColor = '#f59e0b'; // amber-500if (props.metric === 'disk') mainColor = '#10b981'; // emerald-500+ // Unit classification (doesn't depend on data)+ const isPercentLike = props.unit === '%';+ const isByteLike = !props.unit || props.unit === 'B/s';++ // Calculate scale (needs data for absolute metrics)+ const minValue = 0;+ let maxValue = 100; // default for empty/percentage+ if (points.length > 0) {+ const rawMax = Math.max(...points.map(p => p.max || p.value));+ maxValue = isPercentLike ? Math.max(100, rawMax) : Math.max(1, rawMax * 1.15);+ }+// Draw grid lines (horizontal)ctx.strokeStyle = gridColor;ctx.lineWidth = 1;@@ -264,11 +287,15 @@ export const HistoryChart: Component<HistoryChartProps> = (props) => {ctx.textAlign = 'right';ctx.textBaseline = 'middle';let label = '';- if (pct === 0) label = '0';- else if (pct === 1) label = props.unit === '%' ? '100' : 'Max';- else label = props.unit === '%' ? '50' : 'Avg';-- if (props.unit === '%') label += '%';+ if (isPercentLike) {+ label = pct === 0 ? '0%' : pct === 1 ? '100%' : '50%';+ } else if (isByteLike) {+ label = pct === 0 ? '0' : pct === 1 ? 'Max' : 'Avg';+ } else {+ // Absolute numeric values (temperature, counters) — show computed scale+ const scaleVal = Math.round(minValue + pct * (maxValue - minValue));+ label = pct === 0 ? '0' : `${scaleVal}`;+ }ctx.fillText(label, 35, y);});@@ -277,15 +304,11 @@ export const HistoryChart: Component<HistoryChartProps> = (props) => {return; // Empty state handled in JSX}- // Calculate Scale- // X is time, Y is value+ // Calculate time scaleconst startTime = points[0].timestamp;const endTime = points[points.length - 1].timestamp;const timeSpan = Math.max(1, endTime - startTime);- const maxValue = Math.max(100, ...points.map(p => p.max || p.value));- const minValue = 0;-// Plotconst getX = (ts: number) => 40 + ((ts - startTime) / timeSpan) * (w - 40);const getY = (val: number) => (h - 20) - ((val - minValue) / (maxValue - minValue)) * (h - 40);@@ -601,18 +624,12 @@ export const HistoryChart: Component<HistoryChartProps> = (props) => {><div class="font-medium text-center mb-0.5">{new Date(point().timestamp).toLocaleString()}</div><div class="text-gray-300">- {props.unit === '%'- ? `${point().value.toFixed(1)}%`- : `${formatBytes(point().value)}${props.unit === 'B/s' ? '/s' : ''}`}+ {formatTooltipValue(point().value, props.unit)}</div><Show when={point().min !== point().value}><div class="text-[10px] text-gray-400 mt-0.5">- Min: {props.unit === '%'- ? point().min.toFixed(1)- : `${formatBytes(point().min)}${props.unit === 'B/s' ? '/s' : ''}`} •- Max: {props.unit === '%'- ? point().max.toFixed(1)- : `${formatBytes(point().max)}${props.unit === 'B/s' ? '/s' : ''}`}+ Min: {formatTooltipValue(point().min, props.unit)} •+ Max: {formatTooltipValue(point().max, props.unit)}</div></Show></div>diff --git a/frontend-modern/src/types/api.ts b/frontend-modern/src/types/api.tsindex 29c7851ed5..d844fbf272 100644--- a/frontend-modern/src/types/api.ts+++ b/frontend-modern/src/types/api.ts@@ -887,6 +887,19 @@ export interface Disk {device?: string;}+export interface SMARTAttributes {+ powerOnHours?: number;+ powerCycles?: number;+ reallocatedSectors?: number;+ pendingSectors?: number;+ offlineUncorrectable?: number;+ udmaCrcErrors?: number;+ percentageUsed?: number;+ availableSpare?: number;+ mediaErrors?: number;+ unsafeShutdowns?: number;+}+export interface PhysicalDisk {id: string;node: string;@@ -895,6 +908,7 @@ export interface PhysicalDisk {device?: string;model: string;serial: string;+ wwn: string;type: 'nvme' | 'sata' | 'sas' | string;size: number;health: 'PASSED' | 'FAILED' | 'UNKNOWN' | string;@@ -903,7 +917,12 @@ export interface PhysicalDisk {rpm: number;used: string;lastChecked: string;- smart?: unknown;+ smartAttributes?: SMARTAttributes;+}++/** Returns the best resource ID for disk metrics queries (serial preferred, WWN fallback). */+export function diskResourceId(disk: PhysicalDisk): string | null {+ return disk.serial || disk.wwn || null;}export interface CPUInfo {diff --git a/internal/api/router.go b/internal/api/router.goindex 29ed0c9e53..5917cdd1de 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -5785,6 +5785,16 @@ func (r *Router) handleMetricsHistory(w http.ResponseWriter, req *http.Request)return nil}+ findDisk := func(id string) *models.PhysicalDisk {+ for i := range state.PhysicalDisks {+ d := &state.PhysicalDisks[i]+ if d.Serial == id || d.WWN == id || d.ID == id {+ return d+ }+ }+ return nil+ }+liveMetricPoints := func(resourceType, resourceID string) map[string]monitoring.MetricPoint {now := time.Now()points := make(map[string]monitoring.MetricPoint)@@ -5886,6 +5896,47 @@ func (r *Router) handleMetricsHistory(w http.ResponseWriter, req *http.Request)}points["disk"] = monitoring.MetricPoint{Timestamp: now, Value: diskPercent}}+ case "disk":+ disk := findDisk(resourceID)+ if disk == nil {+ return points+ }+ if disk.Temperature > 0 {+ points["smart_temp"] = monitoring.MetricPoint{Timestamp: now, Value: float64(disk.Temperature)}+ }+ if disk.SmartAttributes != nil {+ attrs := disk.SmartAttributes+ if attrs.PowerOnHours != nil {+ points["smart_power_on_hours"] = monitoring.MetricPoint{Timestamp: now, Value: float64(*attrs.PowerOnHours)}+ }+ if attrs.PowerCycles != nil {+ points["smart_power_cycles"] = monitoring.MetricPoint{Timestamp: now, Value: float64(*attrs.PowerCycles)}+ }+ if attrs.ReallocatedSectors != nil {+ points["smart_reallocated_sectors"] = monitoring.MetricPoint{Timestamp: now, Value: float64(*attrs.ReallocatedSectors)}+ }+ if attrs.PendingSectors != nil {+ points["smart_pending_sectors"] = monitoring.MetricPoint{Timestamp: now, Value: float64(*attrs.PendingSectors)}+ }+ if attrs.OfflineUncorrectable != nil {+ points["smart_offline_uncorrectable"] = monitoring.MetricPoint{Timestamp: now, Value: float64(*attrs.OfflineUncorrectable)}+ }+ if attrs.UDMACRCErrors != nil {+ points["smart_crc_errors"] = monitoring.MetricPoint{Timestamp: now, Value: float64(*attrs.UDMACRCErrors)}+ }+ if attrs.PercentageUsed != nil {+ points["smart_percentage_used"] = monitoring.MetricPoint{Timestamp: now, Value: float64(*attrs.PercentageUsed)}+ }+ if attrs.AvailableSpare != nil {+ points["smart_available_spare"] = monitoring.MetricPoint{Timestamp: now, Value: float64(*attrs.AvailableSpare)}+ }+ if attrs.MediaErrors != nil {+ points["smart_media_errors"] = monitoring.MetricPoint{Timestamp: now, Value: float64(*attrs.MediaErrors)}+ }+ if attrs.UnsafeShutdowns != nil {+ points["smart_unsafe_shutdowns"] = monitoring.MetricPoint{Timestamp: now, Value: float64(*attrs.UnsafeShutdowns)}+ }+ }}return pointsdiff --git a/internal/hostagent/agent.go b/internal/hostagent/agent.goindex 1500a70528..838735e6ef 100644--- a/internal/hostagent/agent.go+++ b/internal/hostagent/agent.go@@ -758,7 +758,7 @@ func (a *Agent) collectSMARTData(ctx context.Context) []agentshost.DiskSMART {// Convert internal smartctl types to agent report typesresult := make([]agentshost.DiskSMART, 0, len(smartData))for _, disk := range smartData {- result = append(result, agentshost.DiskSMART{+ entry := agentshost.DiskSMART{Device: disk.Device,Model: disk.Model,Serial: disk.Serial,@@ -767,7 +767,22 @@ func (a *Agent) collectSMARTData(ctx context.Context) []agentshost.DiskSMART {Temperature: disk.Temperature,Health: disk.Health,Standby: disk.Standby,- })+ }+ if disk.Attributes != nil {+ entry.Attributes = &agentshost.SMARTAttributes{+ PowerOnHours: disk.Attributes.PowerOnHours,+ PowerCycles: disk.Attributes.PowerCycles,+ ReallocatedSectors: disk.Attributes.ReallocatedSectors,+ PendingSectors: disk.Attributes.PendingSectors,+ OfflineUncorrectable: disk.Attributes.OfflineUncorrectable,+ UDMACRCErrors: disk.Attributes.UDMACRCErrors,+ PercentageUsed: disk.Attributes.PercentageUsed,+ AvailableSpare: disk.Attributes.AvailableSpare,+ MediaErrors: disk.Attributes.MediaErrors,+ UnsafeShutdowns: disk.Attributes.UnsafeShutdowns,+ }+ }+ result = append(result, entry)}a.logger.Debug().diff --git a/internal/models/converters.go b/internal/models/converters.goindex 22566812f3..49ba792e00 100644--- a/internal/models/converters.go+++ b/internal/models/converters.go@@ -750,6 +750,7 @@ func hostSensorSummaryToFrontend(src HostSensorSummary) *HostSensorSummaryFronteTemperature: disk.Temperature,Health: disk.Health,Standby: disk.Standby,+ Attributes: disk.Attributes,}}}diff --git a/internal/models/models.go b/internal/models/models.goindex b8c53b0ae6..f60a37ac95 100644--- a/internal/models/models.go+++ b/internal/models/models.go@@ -225,14 +225,29 @@ type HostSensorSummary struct {// HostDiskSMART represents S.M.A.R.T. data for a disk from a host agent.type HostDiskSMART struct {- Device string `json:"device"` // Device name (e.g., sda)- Model string `json:"model,omitempty"` // Disk model- Serial string `json:"serial,omitempty"` // Serial number- WWN string `json:"wwn,omitempty"` // World Wide Name- Type string `json:"type,omitempty"` // Transport type: sata, sas, nvme- Temperature int `json:"temperature"` // Temperature in Celsius- Health string `json:"health,omitempty"` // PASSED, FAILED, UNKNOWN- Standby bool `json:"standby,omitempty"` // True if disk was in standby+ Device string `json:"device"` // Device name (e.g., sda)+ Model string `json:"model,omitempty"` // Disk model+ Serial string `json:"serial,omitempty"` // Serial number+ WWN string `json:"wwn,omitempty"` // World Wide Name+ Type string `json:"type,omitempty"` // Transport type: sata, sas, nvme+ Temperature int `json:"temperature"` // Temperature in Celsius+ Health string `json:"health,omitempty"` // PASSED, FAILED, UNKNOWN+ Standby bool `json:"standby,omitempty"` // True if disk was in standby+ Attributes *SMARTAttributes `json:"attributes,omitempty"`+}++// SMARTAttributes holds normalized SMART attributes for both SATA and NVMe disks.+type SMARTAttributes struct {+ PowerOnHours *int64 `json:"powerOnHours,omitempty"`+ PowerCycles *int64 `json:"powerCycles,omitempty"`+ ReallocatedSectors *int64 `json:"reallocatedSectors,omitempty"`+ PendingSectors *int64 `json:"pendingSectors,omitempty"`+ OfflineUncorrectable *int64 `json:"offlineUncorrectable,omitempty"`+ UDMACRCErrors *int64 `json:"udmaCrcErrors,omitempty"`+ PercentageUsed *int `json:"percentageUsed,omitempty"`+ AvailableSpare *int `json:"availableSpare,omitempty"`+ MediaErrors *int64 `json:"mediaErrors,omitempty"`+ UnsafeShutdowns *int64 `json:"unsafeShutdowns,omitempty"`}// HostRAIDArray represents an mdadm RAID array on a host.@@ -774,21 +789,22 @@ type CephServiceStatus struct {// PhysicalDisk represents a physical disk on a nodetype PhysicalDisk struct {- ID string `json:"id"` // "{instance}-{node}-{devpath}"- Node string `json:"node"`- Instance string `json:"instance"`- DevPath string `json:"devPath"` // /dev/nvme0n1, /dev/sda- Model string `json:"model"`- Serial string `json:"serial"`- WWN string `json:"wwn"` // World Wide Name- Type string `json:"type"` // nvme, sata, sas- Size int64 `json:"size"` // bytes- Health string `json:"health"` // PASSED, FAILED, UNKNOWN- Wearout int `json:"wearout"` // SSD wear metric from Proxmox (0-100, -1 when unavailable)- Temperature int `json:"temperature"` // Celsius (if available)- RPM int `json:"rpm"` // 0 for SSDs- Used string `json:"used"` // Filesystem or partition usage- LastChecked time.Time `json:"lastChecked"`+ ID string `json:"id"` // "{instance}-{node}-{devpath}"+ Node string `json:"node"`+ Instance string `json:"instance"`+ DevPath string `json:"devPath"` // /dev/nvme0n1, /dev/sda+ Model string `json:"model"`+ Serial string `json:"serial"`+ WWN string `json:"wwn"` // World Wide Name+ Type string `json:"type"` // nvme, sata, sas+ Size int64 `json:"size"` // bytes+ Health string `json:"health"` // PASSED, FAILED, UNKNOWN+ Wearout int `json:"wearout"` // SSD wear metric from Proxmox (0-100, -1 when unavailable)+ Temperature int `json:"temperature"` // Celsius (if available)+ RPM int `json:"rpm"` // 0 for SSDs+ Used string `json:"used"` // Filesystem or partition usage+ SmartAttributes *SMARTAttributes `json:"smartAttributes,omitempty"`+ LastChecked time.Time `json:"lastChecked"`}// PBSInstance represents a Proxmox Backup Server instancediff --git a/internal/models/models_frontend.go b/internal/models/models_frontend.goindex 335301d7f7..162185a032 100644--- a/internal/models/models_frontend.go+++ b/internal/models/models_frontend.go@@ -453,14 +453,15 @@ type HostSensorSummaryFrontend struct {// HostDiskSMARTFrontend represents S.M.A.R.T. data for a disk from a host agent.type HostDiskSMARTFrontend struct {- Device string `json:"device"` // Device name (e.g., sda)- Model string `json:"model,omitempty"` // Disk model- Serial string `json:"serial,omitempty"` // Serial number- WWN string `json:"wwn,omitempty"` // World Wide Name- Type string `json:"type,omitempty"` // Transport type: sata, sas, nvme- Temperature int `json:"temperature"` // Temperature in Celsius- Health string `json:"health,omitempty"` // PASSED, FAILED, UNKNOWN- Standby bool `json:"standby,omitempty"` // True if disk was in standby+ Device string `json:"device"` // Device name (e.g., sda)+ Model string `json:"model,omitempty"` // Disk model+ Serial string `json:"serial,omitempty"` // Serial number+ WWN string `json:"wwn,omitempty"` // World Wide Name+ Type string `json:"type,omitempty"` // Transport type: sata, sas, nvme+ Temperature int `json:"temperature"` // Temperature in Celsius+ Health string `json:"health,omitempty"` // PASSED, FAILED, UNKNOWN+ Standby bool `json:"standby,omitempty"` // True if disk was in standby+ Attributes *SMARTAttributes `json:"attributes,omitempty"`}// StorageFrontend represents Storage with frontend-friendly field namesdiff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.goindex 715bdf505a..7115d64a9c 100644--- a/internal/monitoring/monitor.go+++ b/internal/monitoring/monitor.go@@ -367,71 +367,126 @@ func mergeHostAgentSMARTIntoDisks(disks []models.PhysicalDisk, nodes []models.Nocopy(updated, disks)for i := range updated {- // Skip if temperature is already populated- if updated[i].Temperature > 0 {- continue- }-smartData, ok := smartByNodeName[updated[i].Node]if !ok || len(smartData) == 0 {continue}+ // Find matching SMART entry by WWN, serial, or device path+ var matched *models.HostDiskSMART+// Try to match by WWN (most reliable)if updated[i].WWN != "" {- for _, disk := range smartData {- if disk.WWN != "" && strings.EqualFold(disk.WWN, updated[i].WWN) {- if disk.Temperature > 0 && !disk.Standby {- updated[i].Temperature = disk.Temperature- log.Debug().- Str("device", updated[i].DevPath).- Str("wwn", updated[i].WWN).- Int("temp", disk.Temperature).- Msg("Matched host agent SMART temperature by WWN")- }+ for j := range smartData {+ if smartData[j].WWN != "" && strings.EqualFold(smartData[j].WWN, updated[i].WWN) {+ matched = &smartData[j]break}}}// Fall back to serial number match- if updated[i].Serial != "" && updated[i].Temperature == 0 {- for _, disk := range smartData {- if disk.Serial != "" && strings.EqualFold(disk.Serial, updated[i].Serial) {- if disk.Temperature > 0 && !disk.Standby {- updated[i].Temperature = disk.Temperature- log.Debug().- Str("device", updated[i].DevPath).- Str("serial", updated[i].Serial).- Int("temp", disk.Temperature).- Msg("Matched host agent SMART temperature by serial")- }+ if matched == nil && updated[i].Serial != "" {+ for j := range smartData {+ if smartData[j].Serial != "" && strings.EqualFold(smartData[j].Serial, updated[i].Serial) {+ matched = &smartData[j]break}}}// Last resort: match by device path- if updated[i].Temperature == 0 {+ if matched == nil {normalizedDevPath := strings.TrimPrefix(updated[i].DevPath, "/dev/")- for _, disk := range smartData {- normalizedDiskDev := strings.TrimPrefix(disk.Device, "/dev/")+ for j := range smartData {+ normalizedDiskDev := strings.TrimPrefix(smartData[j].Device, "/dev/")if normalizedDiskDev == normalizedDevPath {- if disk.Temperature > 0 && !disk.Standby {- updated[i].Temperature = disk.Temperature- log.Debug().- Str("device", updated[i].DevPath).- Int("temp", disk.Temperature).- Msg("Matched host agent SMART temperature by device path")- }+ matched = &smartData[j]break}}}++ if matched == nil || matched.Standby {+ continue+ }++ // Merge temperature if not already set+ if updated[i].Temperature == 0 && matched.Temperature > 0 {+ updated[i].Temperature = matched.Temperature+ log.Debug().+ Str("device", updated[i].DevPath).+ Int("temp", matched.Temperature).+ Msg("Matched host agent SMART temperature")+ }++ // Always merge SMART attributes from host agent+ if matched.Attributes != nil {+ updated[i].SmartAttributes = matched.Attributes+ }}return updated}++// writeSMARTMetrics writes SMART attribute metrics to the persistent metrics store for a single disk.+func (m *Monitor) writeSMARTMetrics(disk models.PhysicalDisk, now time.Time) {+ // Determine resource ID: serial (preferred) → WWN → composite fallback+ resourceID := disk.Serial+ if resourceID == "" {+ resourceID = disk.WWN+ }+ if resourceID == "" {+ resourceID = fmt.Sprintf("%s-%s-%s", disk.Instance, disk.Node, strings.ReplaceAll(disk.DevPath, "/", "-"))+ }++ // Temperature (always write if > 0)+ if disk.Temperature > 0 {+ m.metricsStore.Write("disk", resourceID, "smart_temp", float64(disk.Temperature), now)+ }++ attrs := disk.SmartAttributes+ if attrs == nil {+ return+ }++ // Common+ if attrs.PowerOnHours != nil {+ m.metricsStore.Write("disk", resourceID, "smart_power_on_hours", float64(*attrs.PowerOnHours), now)+ }+ if attrs.PowerCycles != nil {+ m.metricsStore.Write("disk", resourceID, "smart_power_cycles", float64(*attrs.PowerCycles), now)+ }++ // SATA-specific+ if attrs.ReallocatedSectors != nil {+ m.metricsStore.Write("disk", resourceID, "smart_reallocated_sectors", float64(*attrs.ReallocatedSectors), now)+ }+ if attrs.PendingSectors != nil {+ m.metricsStore.Write("disk", resourceID, "smart_pending_sectors", float64(*attrs.PendingSectors), now)+ }+ if attrs.OfflineUncorrectable != nil {+ m.metricsStore.Write("disk", resourceID, "smart_offline_uncorrectable", float64(*attrs.OfflineUncorrectable), now)+ }+ if attrs.UDMACRCErrors != nil {+ m.metricsStore.Write("disk", resourceID, "smart_crc_errors", float64(*attrs.UDMACRCErrors), now)+ }++ // NVMe-specific+ if attrs.PercentageUsed != nil {+ m.metricsStore.Write("disk", resourceID, "smart_percentage_used", float64(*attrs.PercentageUsed), now)+ }+ if attrs.AvailableSpare != nil {+ m.metricsStore.Write("disk", resourceID, "smart_available_spare", float64(*attrs.AvailableSpare), now)+ }+ if attrs.MediaErrors != nil {+ m.metricsStore.Write("disk", resourceID, "smart_media_errors", float64(*attrs.MediaErrors), now)+ }+ if attrs.UnsafeShutdowns != nil {+ m.metricsStore.Write("disk", resourceID, "smart_unsafe_shutdowns", float64(*attrs.UnsafeShutdowns), now)+ }+}+func lookupClusterEndpointLabel(instance *config.PVEInstance, nodeName string) string {if instance == nil {return ""@@ -6232,6 +6287,14 @@ func (m *Monitor) pollPVEInstance(ctx context.Context, instanceName string, clie// Also merge SMART data from linked host agentsallDisks = mergeHostAgentSMARTIntoDisks(allDisks, currentState.Nodes, currentState.Hosts)+ // Write SMART metrics to persistent store+ if m.metricsStore != nil {+ now := time.Now()+ for _, disk := range allDisks {+ m.writeSMARTMetrics(disk, now)+ }+ }+// Update physical disks in statelog.Debug().Str("instance", inst).@@ -10545,7 +10608,7 @@ func convertAgentSMARTToModels(smart []agentshost.DiskSMART) []models.HostDiskSM}result := make([]models.HostDiskSMART, 0, len(smart))for _, disk := range smart {- result = append(result, models.HostDiskSMART{+ entry := models.HostDiskSMART{Device: disk.Device,Model: disk.Model,Serial: disk.Serial,@@ -10554,11 +10617,34 @@ func convertAgentSMARTToModels(smart []agentshost.DiskSMART) []models.HostDiskSMTemperature: disk.Temperature,Health: disk.Health,Standby: disk.Standby,- })+ }+ if disk.Attributes != nil {+ entry.Attributes = convertAgentSMARTAttributes(disk.Attributes)+ }+ result = append(result, entry)}return result}+// convertAgentSMARTAttributes converts agent SMARTAttributes to models SMARTAttributes.+func convertAgentSMARTAttributes(src *agentshost.SMARTAttributes) *models.SMARTAttributes {+ if src == nil {+ return nil+ }+ return &models.SMARTAttributes{+ PowerOnHours: src.PowerOnHours,+ PowerCycles: src.PowerCycles,+ ReallocatedSectors: src.ReallocatedSectors,+ PendingSectors: src.PendingSectors,+ OfflineUncorrectable: src.OfflineUncorrectable,+ UDMACRCErrors: src.UDMACRCErrors,+ PercentageUsed: src.PercentageUsed,+ AvailableSpare: src.AvailableSpare,+ MediaErrors: src.MediaErrors,+ UnsafeShutdowns: src.UnsafeShutdowns,+ }+}+// convertAgentCephToModels converts agent report Ceph data to the models.HostCephCluster format.func convertAgentCephToModels(ceph *agentshost.CephCluster) *models.HostCephCluster {if ceph == nil {diff --git a/internal/smartctl/collector.go b/internal/smartctl/collector.goindex 9fe6982075..d51f3e8204 100644--- a/internal/smartctl/collector.go+++ b/internal/smartctl/collector.go@@ -23,15 +23,36 @@ var (// DiskSMART represents S.M.A.R.T. data for a single disk.type DiskSMART struct {- Device string `json:"device"` // Device path (e.g., /dev/sda)- Model string `json:"model,omitempty"` // Disk model- Serial string `json:"serial,omitempty"` // Serial number- WWN string `json:"wwn,omitempty"` // World Wide Name- Type string `json:"type,omitempty"` // Transport type: sata, sas, nvme- Temperature int `json:"temperature"` // Temperature in Celsius- Health string `json:"health,omitempty"` // PASSED, FAILED, UNKNOWN- Standby bool `json:"standby,omitempty"` // True if disk was in standby- LastUpdated time.Time `json:"lastUpdated"` // When this reading was taken+ Device string `json:"device"` // Device path (e.g., /dev/sda)+ Model string `json:"model,omitempty"` // Disk model+ Serial string `json:"serial,omitempty"` // Serial number+ WWN string `json:"wwn,omitempty"` // World Wide Name+ Type string `json:"type,omitempty"` // Transport type: sata, sas, nvme+ Temperature int `json:"temperature"` // Temperature in Celsius+ Health string `json:"health,omitempty"` // PASSED, FAILED, UNKNOWN+ Standby bool `json:"standby,omitempty"` // True if disk was in standby+ Attributes *SMARTAttributes `json:"attributes,omitempty"`+ LastUpdated time.Time `json:"lastUpdated"` // When this reading was taken+}++// SMARTAttributes holds normalized SMART attributes for both SATA and NVMe disks.+// Pointer fields distinguish zero from absent.+type SMARTAttributes struct {+ // Common attributes+ PowerOnHours *int64 `json:"powerOnHours,omitempty"`+ PowerCycles *int64 `json:"powerCycles,omitempty"`++ // SATA-specific (by ATA attribute ID)+ ReallocatedSectors *int64 `json:"reallocatedSectors,omitempty"` // ID 5+ PendingSectors *int64 `json:"pendingSectors,omitempty"` // ID 197+ OfflineUncorrectable *int64 `json:"offlineUncorrectable,omitempty"` // ID 198+ UDMACRCErrors *int64 `json:"udmaCrcErrors,omitempty"` // ID 199++ // NVMe-specific+ PercentageUsed *int `json:"percentageUsed,omitempty"`+ AvailableSpare *int `json:"availableSpare,omitempty"`+ MediaErrors *int64 `json:"mediaErrors,omitempty"`+ UnsafeShutdowns *int64 `json:"unsafeShutdowns,omitempty"`}// smartctlJSON represents the JSON output from smartctl --json.@@ -55,9 +76,29 @@ type smartctlJSON struct {Temperature struct {Current int `json:"current"`} `json:"temperature"`- // NVMe-specific temperature+ // ATA SMART attributes table+ ATASmartAttributes struct {+ Table []struct {+ ID int `json:"id"`+ Name string `json:"name"`+ Value int `json:"value"`+ Worst int `json:"worst"`+ Thresh int `json:"thresh"`+ Raw struct {+ Value int64 `json:"value"`+ String string `json:"string"`+ } `json:"raw"`+ } `json:"table"`+ } `json:"ata_smart_attributes"`+ // NVMe-specific health informationNVMeSmartHealthInformationLog struct {- Temperature int `json:"temperature"`+ Temperature int `json:"temperature"`+ AvailableSpare int `json:"available_spare"`+ PercentageUsed int `json:"percentage_used"`+ PowerOnHours int64 `json:"power_on_hours"`+ UnsafeShutdowns int64 `json:"unsafe_shutdowns"`+ MediaErrors int64 `json:"media_errors"`+ PowerCycles int64 `json:"power_cycles"`} `json:"nvme_smart_health_information_log"`PowerMode string `json:"power_mode"`}@@ -241,6 +282,9 @@ func collectDeviceSMART(ctx context.Context, device string) (*DiskSMART, error)result.Health = "FAILED"}+ // Parse SMART attributes+ result.Attributes = parseSMARTAttributes(&smartData, result.Type)+log.Debug().Str("device", result.Device).Str("model", result.Model).@@ -251,6 +295,64 @@ func collectDeviceSMART(ctx context.Context, device string) (*DiskSMART, error)return result, nil}+// parseSMARTAttributes extracts normalized SMART attributes from smartctl JSON output.+func parseSMARTAttributes(data *smartctlJSON, diskType string) *SMARTAttributes {+ attrs := &SMARTAttributes{}+ hasData := false++ if diskType == "nvme" {+ nvmeLog := &data.NVMeSmartHealthInformationLog+ // NVMe health log fields are always present when the log is available.+ // We use simple heuristics: power_on_hours > 0 means the log was populated.+ if nvmeLog.PowerOnHours > 0 || nvmeLog.PowerCycles > 0 || nvmeLog.AvailableSpare > 0 {+ hasData = true+ poh := nvmeLog.PowerOnHours+ attrs.PowerOnHours = &poh+ pc := nvmeLog.PowerCycles+ attrs.PowerCycles = &pc+ pu := nvmeLog.PercentageUsed+ attrs.PercentageUsed = &pu+ as := nvmeLog.AvailableSpare+ attrs.AvailableSpare = &as+ me := nvmeLog.MediaErrors+ attrs.MediaErrors = &me+ us := nvmeLog.UnsafeShutdowns+ attrs.UnsafeShutdowns = &us+ }+ } else {+ // SATA / SAS — iterate the ATA attributes table+ for _, attr := range data.ATASmartAttributes.Table {+ hasData = true+ raw := attr.Raw.Value+ switch attr.ID {+ case 5: // Reallocated Sector Count+ v := raw+ attrs.ReallocatedSectors = &v+ case 9: // Power-On Hours+ v := raw+ attrs.PowerOnHours = &v+ case 12: // Power Cycle Count+ v := raw+ attrs.PowerCycles = &v+ case 197: // Current Pending Sector Count+ v := raw+ attrs.PendingSectors = &v+ case 198: // Offline Uncorrectable+ v := raw+ attrs.OfflineUncorrectable = &v+ case 199: // UDMA CRC Error Count+ v := raw+ attrs.UDMACRCErrors = &v+ }+ }+ }++ if !hasData {+ return nil+ }+ return attrs+}+// detectDiskType determines the disk transport type from smartctl output.func detectDiskType(data smartctlJSON) string {protocol := strings.ToLower(data.Device.Protocol)diff --git a/internal/smartctl/collector_test.go b/internal/smartctl/collector_test.goindex 5b41931579..d7f8be7771 100644--- a/internal/smartctl/collector_test.go+++ b/internal/smartctl/collector_test.go@@ -198,6 +198,162 @@ func TestNVMeTemperatureFallback(t *testing.T) {}}+func TestParseSMARTAttributes_SATA(t *testing.T) {+ data := &smartctlJSON{}+ data.ATASmartAttributes.Table = []struct {+ ID int `json:"id"`+ Name string `json:"name"`+ Value int `json:"value"`+ Worst int `json:"worst"`+ Thresh int `json:"thresh"`+ Raw struct {+ Value int64 `json:"value"`+ String string `json:"string"`+ } `json:"raw"`+ }{+ {ID: 5, Name: "Reallocated_Sector_Ct", Raw: struct {+ Value int64 `json:"value"`+ String string `json:"string"`+ }{Value: 3}},+ {ID: 9, Name: "Power_On_Hours", Raw: struct {+ Value int64 `json:"value"`+ String string `json:"string"`+ }{Value: 12345}},+ {ID: 12, Name: "Power_Cycle_Count", Raw: struct {+ Value int64 `json:"value"`+ String string `json:"string"`+ }{Value: 42}},+ {ID: 197, Name: "Current_Pending_Sector", Raw: struct {+ Value int64 `json:"value"`+ String string `json:"string"`+ }{Value: 0}},+ {ID: 198, Name: "Offline_Uncorrectable", Raw: struct {+ Value int64 `json:"value"`+ String string `json:"string"`+ }{Value: 1}},+ {ID: 199, Name: "UDMA_CRC_Error_Count", Raw: struct {+ Value int64 `json:"value"`+ String string `json:"string"`+ }{Value: 7}},+ }++ attrs := parseSMARTAttributes(data, "sata")+ if attrs == nil {+ t.Fatal("expected non-nil attributes for SATA disk with data")+ }+ if attrs.PowerOnHours == nil || *attrs.PowerOnHours != 12345 {+ t.Errorf("PowerOnHours: got %v, want 12345", attrs.PowerOnHours)+ }+ if attrs.PowerCycles == nil || *attrs.PowerCycles != 42 {+ t.Errorf("PowerCycles: got %v, want 42", attrs.PowerCycles)+ }+ if attrs.ReallocatedSectors == nil || *attrs.ReallocatedSectors != 3 {+ t.Errorf("ReallocatedSectors: got %v, want 3", attrs.ReallocatedSectors)+ }+ if attrs.PendingSectors == nil || *attrs.PendingSectors != 0 {+ t.Errorf("PendingSectors: got %v, want 0", attrs.PendingSectors)+ }+ if attrs.OfflineUncorrectable == nil || *attrs.OfflineUncorrectable != 1 {+ t.Errorf("OfflineUncorrectable: got %v, want 1", attrs.OfflineUncorrectable)+ }+ if attrs.UDMACRCErrors == nil || *attrs.UDMACRCErrors != 7 {+ t.Errorf("UDMACRCErrors: got %v, want 7", attrs.UDMACRCErrors)+ }+ // NVMe fields should be nil+ if attrs.PercentageUsed != nil {+ t.Errorf("PercentageUsed should be nil for SATA disk")+ }+ if attrs.AvailableSpare != nil {+ t.Errorf("AvailableSpare should be nil for SATA disk")+ }+}++func TestParseSMARTAttributes_NVMe(t *testing.T) {+ data := &smartctlJSON{}+ data.NVMeSmartHealthInformationLog.PowerOnHours = 5000+ data.NVMeSmartHealthInformationLog.PowerCycles = 100+ data.NVMeSmartHealthInformationLog.PercentageUsed = 5+ data.NVMeSmartHealthInformationLog.AvailableSpare = 100+ data.NVMeSmartHealthInformationLog.MediaErrors = 0+ data.NVMeSmartHealthInformationLog.UnsafeShutdowns = 12++ attrs := parseSMARTAttributes(data, "nvme")+ if attrs == nil {+ t.Fatal("expected non-nil attributes for NVMe disk")+ }+ if attrs.PowerOnHours == nil || *attrs.PowerOnHours != 5000 {+ t.Errorf("PowerOnHours: got %v, want 5000", attrs.PowerOnHours)+ }+ if attrs.PowerCycles == nil || *attrs.PowerCycles != 100 {+ t.Errorf("PowerCycles: got %v, want 100", attrs.PowerCycles)+ }+ if attrs.PercentageUsed == nil || *attrs.PercentageUsed != 5 {+ t.Errorf("PercentageUsed: got %v, want 5", attrs.PercentageUsed)+ }+ if attrs.AvailableSpare == nil || *attrs.AvailableSpare != 100 {+ t.Errorf("AvailableSpare: got %v, want 100", attrs.AvailableSpare)+ }+ if attrs.MediaErrors == nil || *attrs.MediaErrors != 0 {+ t.Errorf("MediaErrors: got %v, want 0", attrs.MediaErrors)+ }+ if attrs.UnsafeShutdowns == nil || *attrs.UnsafeShutdowns != 12 {+ t.Errorf("UnsafeShutdowns: got %v, want 12", attrs.UnsafeShutdowns)+ }+ // SATA fields should be nil+ if attrs.ReallocatedSectors != nil {+ t.Errorf("ReallocatedSectors should be nil for NVMe disk")+ }+}++func TestParseSMARTAttributes_PartialData(t *testing.T) {+ // SATA disk with only power-on hours — other attributes missing+ data := &smartctlJSON{}+ data.ATASmartAttributes.Table = []struct {+ ID int `json:"id"`+ Name string `json:"name"`+ Value int `json:"value"`+ Worst int `json:"worst"`+ Thresh int `json:"thresh"`+ Raw struct {+ Value int64 `json:"value"`+ String string `json:"string"`+ } `json:"raw"`+ }{+ {ID: 9, Name: "Power_On_Hours", Raw: struct {+ Value int64 `json:"value"`+ String string `json:"string"`+ }{Value: 100}},+ }++ attrs := parseSMARTAttributes(data, "sata")+ if attrs == nil {+ t.Fatal("expected non-nil attributes")+ }+ if attrs.PowerOnHours == nil || *attrs.PowerOnHours != 100 {+ t.Errorf("PowerOnHours: got %v, want 100", attrs.PowerOnHours)+ }+ if attrs.ReallocatedSectors != nil {+ t.Errorf("ReallocatedSectors should be nil when not in table")+ }+ if attrs.PendingSectors != nil {+ t.Errorf("PendingSectors should be nil when not in table")+ }+}++func TestParseSMARTAttributes_Standby(t *testing.T) {+ // No data at all — simulates standby or no SMART support+ data := &smartctlJSON{}+ attrs := parseSMARTAttributes(data, "sata")+ if attrs != nil {+ t.Errorf("expected nil attributes for empty data, got %+v", attrs)+ }++ attrs = parseSMARTAttributes(data, "nvme")+ if attrs != nil {+ t.Errorf("expected nil attributes for empty NVMe data, got %+v", attrs)+ }+}+func TestMatchesDeviceExclude(t *testing.T) {tests := []struct {name stringdiff --git a/pkg/agents/host/report.go b/pkg/agents/host/report.goindex 197d31770f..79a4f68ab7 100644--- a/pkg/agents/host/report.go+++ b/pkg/agents/host/report.go@@ -109,14 +109,29 @@ type Sensors struct {// DiskSMART represents S.M.A.R.T. data for a single disk.type DiskSMART struct {- Device string `json:"device"` // Device path (e.g., sda)- Model string `json:"model,omitempty"` // Disk model- Serial string `json:"serial,omitempty"` // Serial number- WWN string `json:"wwn,omitempty"` // World Wide Name- Type string `json:"type,omitempty"` // Transport type: sata, sas, nvme- Temperature int `json:"temperature"` // Temperature in Celsius- Health string `json:"health,omitempty"` // PASSED, FAILED, UNKNOWN- Standby bool `json:"standby,omitempty"` // True if disk was in standby+ Device string `json:"device"` // Device path (e.g., sda)+ Model string `json:"model,omitempty"` // Disk model+ Serial string `json:"serial,omitempty"` // Serial number+ WWN string `json:"wwn,omitempty"` // World Wide Name+ Type string `json:"type,omitempty"` // Transport type: sata, sas, nvme+ Temperature int `json:"temperature"` // Temperature in Celsius+ Health string `json:"health,omitempty"` // PASSED, FAILED, UNKNOWN+ Standby bool `json:"standby,omitempty"` // True if disk was in standby+ Attributes *SMARTAttributes `json:"attributes,omitempty"`+}++// SMARTAttributes holds normalized SMART attributes for both SATA and NVMe disks.+type SMARTAttributes struct {+ PowerOnHours *int64 `json:"powerOnHours,omitempty"`+ PowerCycles *int64 `json:"powerCycles,omitempty"`+ ReallocatedSectors *int64 `json:"reallocatedSectors,omitempty"`+ PendingSectors *int64 `json:"pendingSectors,omitempty"`+ OfflineUncorrectable *int64 `json:"offlineUncorrectable,omitempty"`+ UDMACRCErrors *int64 `json:"udmaCrcErrors,omitempty"`+ PercentageUsed *int `json:"percentageUsed,omitempty"`+ AvailableSpare *int `json:"availableSpare,omitempty"`+ MediaErrors *int64 `json:"mediaErrors,omitempty"`+ UnsafeShutdowns *int64 `json:"unsafeShutdowns,omitempty"`}// RAIDArray represents an mdadm RAID array.