Skip to content

LordOS — a free, fast and secure GNU/Linux distribution based on Debian, with its own desktop environment: display server and Wayland compositor in C, a React UI engine on QuickJS, and private native apps.

Disks: live disk temperatures in the Monitor and full SMART with smartmontools

Federico Pereira8842a277cb22
diff --git a/apps/disks/health.jsx b/apps/disks/health.jsx
index 952b6d9..48790a9 100644
--- a/apps/disks/health.jsx
+++ b/apps/disks/health.jsx
@@ -1,88 +1,388 @@
-// health.jsx — disk health (SMART). Read only on request (disk-smart action), never in the
-// background, so the disk is not woken up and nothing stalls.
-import { View, Text, Button, useTheme, useLocale, admin, formatBytes, formatNumber, GroupBox, FormRow, spacing, typeScale } from '@lordos/sdk';
-import { useEffect, useState } from 'react';
+// health.jsx — disk health (SMART). Read only on request, never in the background, so the disk is
+// not woken up and nothing stalls.
+//
+// With smartmontools (Debian's smartctl) the card shows the full report: overall health and why,
+// temperature and its limits, SSD wear, power-on hours and cycles, reallocated and pending
+// sectors, every attribute with a plain name, the error log, the SCT temperature history and
+// self-tests (short/long) with progress — all through the root helper's closed smart-* actions.
+// Without it, LordOS's own reader (disk-smart) gives the basic health, and the card offers to
+// install smartmontools with the package engine (pkg-install, an administrator), like Settings →
+// Sharing does for SSH.
+import {
+ View, Text, Button, useTheme, useLocale, admin, formatBytes, formatNumber, GroupBox, FormRow, spacing, typeScale,
+ smart, smartSummaries, prettyAttrName,
+} from '@lordos/sdk';
+import { useEffect, useRef, useState } from 'react';
const cache = new Map(); // disk → last result (while the app is open)
const HEALTH_COLOR = { ok: '#30d158', warning: '#ff9f0a', failing: '#ff453a', unknown: '#8e8e93' };
const KNOWN = [1, 3, 4, 5, 7, 9, 10, 12, 177, 183, 184, 187, 188, 190, 192, 193, 194, 196, 197, 198, 199, 231, 233, 241, 242];
-function attrName(tr, id) { return KNOWN.includes(id) ? tr(`disks.attr.a${id}`) : tr('disks.attr.unknown', { id }); }
+function ownAttrName(tr, id) { return KNOWN.includes(id) ? tr(`disks.attr.a${id}`) : tr('disks.attr.unknown', { id }); }
+// smartctl attribute: our plain name when we have one, else smartctl's own (from its drive database)
+function attrName(tr, a) { return a.key ? tr(`disks.attr.${a.key}`) : prettyAttrName(a.name) || tr('disks.attr.unknown', { id: a.id }); }
-function readSmart(name) {
+// LordOS's own reader (no smartmontools): summary and ATA attributes
+function readOwn(name) {
const res = { summary: null, attrs: [] };
+ const t0 = Date.now();
return admin.run('disk-smart', name, (line) => {
try {
if (line.startsWith('smart ')) res.summary = JSON.parse(line.slice(6));
else if (line.startsWith('attr ')) res.attrs.push(JSON.parse(line.slice(5)));
} catch (e) { /* malformed line */ }
- }, { quiet: true }).then((ms) => ({ ...res, ms }));
+ }, { quiet: true }).then((ms) => ({ src: 'own', ...res, ms: ms || `${Date.now() - t0} ms` }));
}
-export function HealthCard({ disk }) {
+function readFull(name) {
+ const t0 = Date.now();
+ return smart.info(name).then((m) => {
+ smartSummaries.set((all) => ({ ...all, [name]: { health: m.health, reasons: m.reasons, temp: m.temp, wear: m.wear ? m.wear.used : null, hours: m.hours, standby: false, supported: m.supported, t: Date.now() } }));
+ return { src: 'smartctl', m, ms: Date.now() - t0 };
+ });
+}
+
+const useTr = () => useLocale().t;
+
+function Dim({ children, color }) {
+ const t = useTheme();
+ return <Text style={{ fontSize: typeScale.callout, color: color || t.textDim, lineHeight: 1.4, textAlign: 'start' }}>{children}</Text>;
+}
+
+function Line({ label, value, color }) {
+ const t = useTheme();
+ if (value == null || value === '') return null;
+ return (
+ <FormRow label={label} labelWidth={190} minHeight={30}>
+ <Text style={{ fontSize: typeScale.body, color: color || t.text, textAlign: 'start' }}>{value}</Text>
+ </FormRow>
+ );
+}
+
+function Bar({ frac, color }) {
+ const t = useTheme();
+ return (
+ <View style={{ height: 8, borderRadius: 4, backgroundColor: t.control, overflow: 'hidden', flexDirection: 'row', direction: 'ltr' }}>
+ <View style={{ flexGrow: Math.max(0, Math.min(1, frac)), backgroundColor: color || t.accent }} />
+ <View style={{ flexGrow: 1 - Math.max(0, Math.min(1, frac)) }} />
+ </View>
+ );
+}
+
+// ---- the card ----
+
+export function HealthCard({ disk, isAdmin }) {
const t = useTheme();
- const { t: tr } = useLocale();
+ const tr = useTr();
const [st, setSt] = useState(() => cache.get(disk.name) || null);
- const [showAll, setShowAll] = useState(false);
+ const [installed, setInstalled] = useState(() => smart.installed());
+ const [inst, setInst] = useState(null); // null, { busy } or { error }
useEffect(() => { setSt(cache.get(disk.name) || null); }, [disk.name]);
- const supported = /^(sd|hd|nvme)/.test(disk.name) && disk.transport !== 'loop';
+ const can = smart.smartable(disk.name) && disk.transport !== 'loop';
+ const ownCan = /^(sd|hd|nvme)/.test(disk.name) && disk.transport !== 'loop';
+ const save = (r) => { cache.set(disk.name, r); setSt(r); };
const check = () => {
setSt({ loading: true });
- readSmart(disk.name).then((r) => { cache.set(disk.name, r); setSt(r); }, (e) => { const r = { error: e.message }; cache.set(disk.name, r); setSt(r); });
+ (installed && can ? readFull(disk.name) : readOwn(disk.name)).then(save, (e) => save({ error: e.message }));
};
- const s = st && st.summary;
- const line = (label, value) => (value == null || value === -1 ? null : (
- <FormRow key={label} label={label} labelWidth={170} minHeight={30}>
- <Text style={{ fontSize: typeScale.body, color: t.text, textAlign: 'start' }}>{value}</Text>
- </FormRow>));
- const dim = (text, color) => <Text style={{ fontSize: typeScale.callout, color: color || t.textDim, lineHeight: 1.4, textAlign: 'start' }}>{text}</Text>;
- // first row: the state (or what to do) and the check button
+ const install = () => {
+ setInst({ busy: true });
+ smart.install().then(() => {
+ setInst(null);
+ const ok = smart.installed();
+ setInstalled(ok);
+ if (ok && can) { setSt({ loading: true }); readFull(disk.name).then(save, (e) => save({ error: e.message })); } // the full report right away
+ }, (e) => setInst({ error: e.message }));
+ };
+ const m = st && st.src === 'smartctl' ? st.m : null;
+ const own = st && st.src === 'own' ? st.summary : null;
+ const health = m ? m.health : own ? own.health : null;
const head = (
<View key="head" style={{ minHeight: 44, flexDirection: 'row', alignItems: 'center', gap: spacing.m, paddingVertical: spacing.s }}>
- {s ? <View style={{ width: 10, height: 10, borderRadius: 5, backgroundColor: HEALTH_COLOR[s.health] || HEALTH_COLOR.unknown }} /> : null}
+ {health ? <View style={{ width: 10, height: 10, borderRadius: 5, backgroundColor: HEALTH_COLOR[health] || HEALTH_COLOR.unknown }} /> : null}
<View style={{ flex: 1, minWidth: 0, gap: 2 }}>
- <Text style={{ fontSize: typeScale.body, fontWeight: 600, color: t.text, textAlign: 'start' }}>{s ? tr(`disks.healthState.${s.health}`) : tr('disks.health')}</Text>
- {s ? dim(tr(`disks.healthHint.${s.health}`))
- : !supported ? dim(tr('disks.noSmart'))
- : st && st.loading ? dim(tr('disks.reading'))
- : st && st.error ? dim(st.error, '#ff9f0a') : null}
+ <Text style={{ fontSize: typeScale.body, fontWeight: 600, color: t.text, textAlign: 'start' }}>{health ? tr(`disks.healthState.${health}`) : tr('disks.health')}</Text>
+ {m && !m.supported ? <Dim>{m.messages.find((x) => x.severity === 'error') ? tr('disks.smart.unsupportedBridge') : tr('disks.noSmart')}</Dim>
+ : health ? <Dim>{tr(`disks.healthHint.${health}`)}</Dim>
+ : !ownCan ? <Dim>{tr('disks.noSmart')}</Dim>
+ : st && st.loading ? <Dim>{tr('disks.reading')}</Dim>
+ : st && st.error ? <Dim color="#ff9f0a">{st.error}</Dim> : null}
+ {m && m.reasons.length ? <Dim color={HEALTH_COLOR[health]}>{m.reasons.map((r) => tr(`disks.reason.${r}`, { n: reasonCount(m, r) })).join(' · ')}</Dim> : null}
</View>
- {supported ? <Button small label={st && !st.loading ? tr('disks.checkAgain') : tr('disks.checkHealth')} disabled={!!(st && st.loading)} onClick={check} /> : null}
+ {ownCan ? <Button small label={st && !st.loading ? tr('disks.checkAgain') : tr('disks.checkHealth')} disabled={!!(st && st.loading)} onClick={check} /> : null}
+ </View>
+ );
+ const footer = st && st.ms != null && !st.loading ? (m ? tr('disks.smart.readWith', { ms: `${st.ms} ms` }) : tr('disks.readIn', { ms: st.ms })) : null;
+ return (
+ <View style={{ gap: spacing.l }}>
+ <GroupBox footer={footer}>
+ {[head, ...(m ? fullRows(tr, m) : own ? ownRows(tr, own) : []), own && st.attrs.length ? <OwnAttrs key="oa" attrs={st.attrs} /> : null].filter(Boolean)}
+ </GroupBox>
+ {ownCan && !installed ? <InstallBox isAdmin={isAdmin} inst={inst} onInstall={install} /> : null}
+ {m && m.supported ? <SelfTests disk={disk} m={m} isAdmin={isAdmin} onDone={check} onUpdate={(nm) => save({ ...st, m: nm })} /> : null}
+ {m && m.tempHistory ? <TempHistory h={m.tempHistory} max={m.tempMax} /> : null}
+ {m && m.supported ? <ErrorLog m={m} /> : null}
+ {m && (m.attrs.length || m.nvme) ? <Attributes m={m} /> : null}
</View>
);
- const rows = !s ? [] : [
- line(tr('disks.temperature'), s.temp >= 0 ? tr('disks.celsius', { v: s.temp }) : null),
- line(tr('disks.powerOn'), s.hours >= 0 ? tr('disks.hours', { count: s.hours, v: formatNumber(s.hours, 0), d: formatNumber(s.hours / 24, 0) }) : null),
- line(tr('disks.powerCycles'), s.cycles >= 0 ? formatNumber(s.cycles, 0) : null),
+}
+
+function reasonCount(m, r) {
+ return r === 'reallocated' ? m.reallocated : r === 'pending' ? m.pending : r === 'uncorrectable' ? m.uncorrectable
+ : r === 'mediaErrors' ? m.nvme?.mediaErrors : r === 'worn' ? m.wear?.used : r === 'grownDefects' ? m.grownDefects : 0;
+}
+
+const hoursText = (tr, h) => tr('disks.hours', { count: h, v: formatNumber(h, 0), d: formatNumber(h / 24, 0) });
+
+function fullRows(tr, m) {
+ const temp = m.temp == null ? null
+ : m.tempMax != null ? tr('disks.smart.tempWithLimit', { v: m.temp, max: m.tempMax, crit: m.tempCrit ?? '—' }) : tr('disks.celsius', { v: m.temp });
+ const n = m.nvme;
+ return [
+ <Line key="t" label={tr('disks.temperature')} value={temp} />,
+ <Line key="h" label={tr('disks.powerOn')} value={m.hours != null ? hoursText(tr, m.hours) : null} />,
+ <Line key="c" label={tr('disks.powerCycles')} value={m.cycles != null ? formatNumber(m.cycles, 0) : null} />,
+ <Line key="w" label={tr('disks.smart.wear')} value={m.wear ? tr('disks.smart.wearValue', { v: m.wear.used }) : null} color={m.wear && m.wear.used >= 90 ? '#ff9f0a' : null} />,
+ <Line key="r" label={tr('disks.reallocated')} value={m.reallocated != null ? formatNumber(m.reallocated, 0) : null} color={m.reallocated > 0 ? '#ff9f0a' : null} />,
+ <Line key="p" label={tr('disks.pending')} value={m.pending != null ? formatNumber(m.pending, 0) : null} color={m.pending > 0 ? '#ff9f0a' : null} />,
+ <Line key="u" label={tr('disks.uncorrectable')} value={m.uncorrectable != null ? formatNumber(m.uncorrectable, 0) : null} color={m.uncorrectable > 0 ? '#ff9f0a' : null} />,
+ n ? <Line key="s" label={tr('disks.spare')} value={n.spare != null ? tr('disks.spareValue', { v: n.spare, min: n.spareThreshold ?? '—' }) : null} /> : null,
+ n ? <Line key="me" label={tr('disks.mediaErrors')} value={n.mediaErrors != null ? formatNumber(n.mediaErrors, 0) : null} color={n.mediaErrors > 0 ? '#ff9f0a' : null} /> : null,
+ n ? <Line key="us" label={tr('disks.unsafeShutdowns')} value={n.unsafeShutdowns != null ? formatNumber(n.unsafeShutdowns, 0) : null} /> : null,
+ <Line key="dr" label={tr('disks.dataRead')} value={m.read != null ? formatBytes(m.read) : null} />,
+ <Line key="dw" label={tr('disks.dataWritten')} value={m.written != null ? formatBytes(m.written) : null} />,
+ <Line key="st" label={tr('disks.selfStatus')} value={m.passed === true ? tr('disks.statusOk') : m.passed === false ? tr('disks.statusFail') : null} color={m.passed === false ? '#ff453a' : null} />,
+ <Line key="fw" label={tr('disks.smart.firmware')} value={m.firmware || null} />,
+ ].filter((x) => x && x.props.value != null);
+}
+
+function ownRows(tr, s) {
+ return [
+ <Line key="t" label={tr('disks.temperature')} value={s.temp >= 0 ? tr('disks.celsius', { v: s.temp }) : null} />,
+ <Line key="h" label={tr('disks.powerOn')} value={s.hours >= 0 ? hoursText(tr, s.hours) : null} />,
+ <Line key="c" label={tr('disks.powerCycles')} value={s.cycles >= 0 ? formatNumber(s.cycles, 0) : null} />,
...(s.kind === 'ata' ? [
- line(tr('disks.reallocated'), s.reallocated >= 0 ? formatNumber(s.reallocated, 0) : null),
- line(tr('disks.pending'), s.pending >= 0 ? formatNumber(s.pending, 0) : null),
- line(tr('disks.uncorrectable'), s.uncorrectable >= 0 ? formatNumber(s.uncorrectable, 0) : null),
- line(tr('disks.selfStatus'), s.status === 1 ? tr('disks.statusOk') : s.status === 0 ? tr('disks.statusFail') : null),
+ <Line key="r" label={tr('disks.reallocated')} value={s.reallocated >= 0 ? formatNumber(s.reallocated, 0) : null} />,
+ <Line key="p" label={tr('disks.pending')} value={s.pending >= 0 ? formatNumber(s.pending, 0) : null} />,
+ <Line key="u" label={tr('disks.uncorrectable')} value={s.uncorrectable >= 0 ? formatNumber(s.uncorrectable, 0) : null} />,
+ <Line key="s" label={tr('disks.selfStatus')} value={s.status === 1 ? tr('disks.statusOk') : s.status === 0 ? tr('disks.statusFail') : null} />,
] : [
- line(tr('disks.lifeUsed'), tr('disks.pctValue', { v: s.used })),
- line(tr('disks.spare'), tr('disks.spareValue', { v: s.spare, min: s.spareThreshold })),
- line(tr('disks.dataRead'), formatBytes(s.read)),
- line(tr('disks.dataWritten'), formatBytes(s.written)),
- line(tr('disks.mediaErrors'), formatNumber(s.mediaErrors, 0)),
- line(tr('disks.unsafeShutdowns'), formatNumber(s.unsafeShutdowns, 0)),
+ <Line key="l" label={tr('disks.lifeUsed')} value={tr('disks.pctValue', { v: s.used })} />,
+ <Line key="sp" label={tr('disks.spare')} value={tr('disks.spareValue', { v: s.spare, min: s.spareThreshold })} />,
+ <Line key="dr" label={tr('disks.dataRead')} value={formatBytes(s.read)} />,
+ <Line key="dw" label={tr('disks.dataWritten')} value={formatBytes(s.written)} />,
+ <Line key="me" label={tr('disks.mediaErrors')} value={formatNumber(s.mediaErrors, 0)} />,
+ <Line key="us" label={tr('disks.unsafeShutdowns')} value={formatNumber(s.unsafeShutdowns, 0)} />,
]),
- ].filter(Boolean);
+ ].filter((x) => x.props.value != null);
+}
+
+function InstallBox({ isAdmin, inst, onInstall }) {
+ const tr = useTr();
+ return (
+ <GroupBox title={tr('disks.smart.advanced')}>
+ <View style={{ paddingVertical: spacing.m, gap: spacing.s }}>
+ <Dim>{tr('disks.smart.installHint')}</Dim>
+ {inst && inst.error ? <Dim color="#ff453a">{inst.error}</Dim> : null}
+ {!isAdmin ? <Dim>{tr('disks.smart.installAdmin')}</Dim> : null}
+ <View style={{ flexDirection: 'row' }}>
+ <Button small primary label={inst && inst.busy ? tr('disks.smart.installing') : tr('disks.smart.install')} disabled={!isAdmin || !!(inst && inst.busy)} onClick={onInstall} />
+ </View>
+ </View>
+ </GroupBox>
+ );
+}
+
+// ---- self-tests ----
+
+function SelfTests({ disk, m, isAdmin, onDone, onUpdate }) {
+ const t = useTheme();
+ const tr = useTr();
+ const [busy, setBusy] = useState(false);
+ const [err, setErr] = useState(null);
+ const live = useRef(m);
+ live.current = m;
+ const allowed = isAdmin || disk.removable;
+ const running = m.selfTest.running;
+ // while a test runs, ask every 15 s (smart-health: short) and read everything once it ends
+ useEffect(() => {
+ if (!running) return undefined;
+ const id = setInterval(() => {
+ smart.health(disk.name).then((h) => {
+ if (h.standby) return;
+ const nm = { ...live.current, selfTest: h.selfTest, selfTests: h.selfTests.length ? h.selfTests : live.current.selfTests };
+ onUpdate(nm);
+ if (!h.selfTest.running) onDone();
+ }, () => {});
+ }, 15000);
+ return () => clearInterval(id);
+ }, [running, disk.name]);
+ const start = (kind) => {
+ setBusy(true);
+ setErr(null);
+ smart.test(disk.name, kind).then(() => smart.health(disk.name)).then((h) => {
+ onUpdate({ ...live.current, selfTest: { ...h.selfTest, running: true, remaining: h.selfTest.running ? h.selfTest.remaining : 100 } }); // the next poll says when it ended
+ }, (e) => setErr(e.message)).finally(() => setBusy(false));
+ };
+ const abort = () => {
+ setBusy(true);
+ smart.abort(disk.name).then(onDone, (e) => setErr(e.message)).finally(() => setBusy(false));
+ };
+ const p = m.selfTest.polling;
+ const rows = [
+ <View key="h" style={{ paddingVertical: spacing.m, gap: spacing.s }}>
+ <Dim>{tr('disks.smart.testHint')}</Dim>
+ {running ? (
+ <View style={{ gap: 6 }}>
+ <Text style={{ fontSize: typeScale.body, color: t.text, textAlign: 'start' }}>
+ {m.selfTest.remaining != null ? tr('disks.smart.testRunning', { pct: 100 - m.selfTest.remaining }) : tr('disks.smart.testRunningNoPct')}</Text>
+ <Bar frac={m.selfTest.remaining != null ? (100 - m.selfTest.remaining) / 100 : 0.05} />
+ </View>
+ ) : null}
+ {err ? <Dim color="#ff453a">{err}</Dim> : null}
+ {!allowed ? <Dim>{tr('disks.adminNote')}</Dim> : null}
+ {!m.selfTest.supported ? <Dim>{tr('disks.smart.testUnsupported')}</Dim> : (
+ <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: spacing.s }}>
+ {running ? <Button small label={tr('disks.smart.testAbort')} disabled={busy || !allowed} onClick={abort} /> : [
+ <Button key="s" small label={p.short != null ? tr('disks.smart.testShortMin', { n: p.short }) : tr('disks.smart.testShort')} disabled={busy || !allowed} onClick={() => start('short')} />,
+ <Button key="l" small label={p.long != null ? tr('disks.smart.testLongMin', { n: p.long }) : tr('disks.smart.testLong')} disabled={busy || !allowed} onClick={() => start('long')} />,
+ ]}
+ </View>
+ )}
+ </View>,
+ ...m.selfTests.slice(0, 8).map((x, i) => (
+ <FormRow key={`r${i}`} label={x.type === 'other' ? x.typeText || tr('disks.smart.testOther') : tr(`disks.smart.test.${x.type}`)} labelWidth={190} minHeight={30}>
+ <Text style={{ fontSize: typeScale.body, color: x.passed ? t.text : '#ff453a', textAlign: 'start' }}>
+ {`${x.resultKey ? tr(`disks.smart.nvmeResult.${x.resultKey}`) : x.result}${x.hours != null ? ` · ${tr('disks.smart.atHour', { h: formatNumber(x.hours, 0) })}` : ''}`}</Text>
+ </FormRow>
+ )),
+ ];
+ if (!m.selfTests.length) rows.push(<Line key="none" label={tr('disks.smart.testResults')} value={tr('disks.smart.testNone')} />);
+ return <GroupBox title={tr('disks.smart.tests')}>{rows}</GroupBox>;
+}
+
+// ---- SCT temperature history (ATA): one thin bar per sample ----
+
+function TempHistory({ h, max }) {
+ const t = useTheme();
+ const tr = useTr();
+ const vals = h.values.slice(-128);
+ const known = vals.filter((v) => v != null);
+ const lo = Math.min(...known) - 2, hi = Math.max(...known, max || 0) + 2;
+ return (
+ <GroupBox title={tr('disks.smart.tempHistory')} footer={tr('disks.smart.tempHistoryFoot', { n: vals.length, min: h.interval, lo: Math.min(...known), hi: Math.max(...known) })}>
+ <View style={{ height: 70, flexDirection: 'row', alignItems: 'flex-end', gap: 1, paddingVertical: spacing.s, direction: 'ltr' }}>
+ {vals.map((v, i) => (
+ <View key={i} style={{ flex: 1, height: v == null ? 1 : Math.max(2, ((v - lo) / Math.max(1, hi - lo)) * 54),
+ backgroundColor: v == null ? t.separator : max != null && v >= max ? '#ff453a' : '#ff9f0a', borderRadius: 1 }} />
+ ))}
+ </View>
+ </GroupBox>
+ );
+}
+
+// ---- error log ----
+
+function ErrorLog({ m }) {
+ const t = useTheme();
+ const tr = useTr();
+ const e = m.errors;
+ return (
+ <GroupBox title={tr('disks.smart.errorLog')}>
+ {[
+ <Line key="c" label={tr('disks.smart.errorCount')} value={e.count ? formatNumber(e.count, 0) : tr('disks.smart.errorNone')} color={e.count && m.kind === 'ata' ? '#ff9f0a' : null} />,
+ ...(m.kind === 'nvme' && e.count ? [<View key="n" style={{ paddingVertical: 6 }}><Dim>{tr('disks.smart.nvmeErrorsHint')}</Dim></View>] : []),
+ ...e.list.slice(0, 6).map((x, i) => (
+ <FormRow key={i} label={x.hours != null ? tr('disks.smart.atHour', { h: formatNumber(x.hours, 0) }) : `#${x.n ?? i + 1}`} labelWidth={190} minHeight={30}>
+ <Text style={{ fontSize: typeScale.caption, color: t.text, fontFamily: 'monospace', textAlign: 'start' }}>{x.text}</Text>
+ </FormRow>
+ )),
+ ]}
+ </GroupBox>
+ );
+}
+
+// ---- every attribute (ATA) or the NVMe health log ----
+
+function Attributes({ m }) {
+ const t = useTheme();
+ const tr = useTr();
+ const [open, setOpen] = useState(false);
+ const toggle = (
+ <View key="tg" onClick={() => setOpen(!open)} style={{ alignSelf: 'flex-start', paddingVertical: spacing.s }}>
+ <Text style={{ fontSize: typeScale.callout, color: t.accent, textAlign: 'start' }}>
+ {open ? tr('disks.hideAttrs') : tr('disks.showAttrs', { n: m.attrs.length || nvmeRows(tr, m.nvme).length })}</Text>
+ </View>
+ );
+ if (!open) return <GroupBox title={tr('disks.smart.attributes')}>{[toggle]}</GroupBox>;
+ if (!m.attrs.length) {
+ return <GroupBox title={tr('disks.smart.attributes')}>{[toggle, ...nvmeRows(tr, m.nvme).map(([k, v]) => <Line key={k} label={k} value={v} />)]}</GroupBox>;
+ }
+ const cols = [['disks.attrName', 2.6], ['disks.attrValue', 0.8], ['disks.attrWorst', 0.8], ['disks.attrThresh', 0.9], ['disks.attrRaw', 1.6]];
+ return (
+ <GroupBox title={tr('disks.smart.attributes')} footer={tr('disks.prefailNote')}>
+ {[toggle,
+ <View key="hd" style={{ flexDirection: 'row', gap: spacing.s, paddingVertical: 4 }}>
+ {cols.map(([k, f]) => <Text key={k} style={{ flex: f, fontSize: typeScale.caption, fontWeight: 600, color: t.textDim, textAlign: 'start' }}>{tr(k)}</Text>)}
+ </View>,
+ ...m.attrs.map((a) => (
+ <View key={a.id} style={{ flexDirection: 'row', gap: spacing.s, paddingVertical: 3 }}>
+ <View style={{ flex: 2.6, minWidth: 0 }}>
+ <Text style={{ fontSize: typeScale.caption, color: a.failed === 'now' ? '#ff453a' : t.text, whiteSpace: 'nowrap', overflow: 'hidden', textAlign: 'start' }}>{`${a.id} · ${attrName(tr, a)}${a.prefail ? ' *' : ''}`}</Text>
+ {a.key ? <Text style={{ fontSize: 10, color: t.textDim, whiteSpace: 'nowrap', overflow: 'hidden', textAlign: 'start' }}>{a.name}</Text> : null}
+ </View>
+ {[a.value, a.worst, a.thresh].map((v, i) => <Text key={i} style={{ flex: i === 2 ? 0.9 : 0.8, fontSize: typeScale.caption, color: t.text, textAlign: 'start' }}>{v == null ? '—' : String(v)}</Text>)}
+ <Text style={{ flex: 1.6, fontSize: typeScale.caption, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden', textAlign: 'start' }}>{a.raw}</Text>
+ </View>
+ ))]}
+ </GroupBox>
+ );
+}
+
+function nvmeRows(tr, n) {
+ if (!n) return [];
+ const num = (v) => (v == null ? null : formatNumber(v, 0));
+ return [
+ [tr('disks.nvme.criticalWarning'), n.criticalWarning ? `0x${n.criticalWarning.toString(16).padStart(2, '0')}` : tr('disks.nvme.none')],
+ [tr('disks.temperature'), n.temp != null ? tr('disks.celsius', { v: n.temp }) : null],
+ [tr('disks.nvme.sensors'), n.sensors.length ? n.sensors.map((v) => tr('disks.celsius', { v })).join(' · ') : null],
+ [tr('disks.spare'), n.spare != null ? tr('disks.spareValue', { v: n.spare, min: n.spareThreshold ?? '—' }) : null],
+ [tr('disks.lifeUsed'), n.used != null ? tr('disks.pctValue', { v: n.used }) : null],
+ [tr('disks.dataRead'), n.read != null ? formatBytes(n.read) : null],
+ [tr('disks.dataWritten'), n.written != null ? formatBytes(n.written) : null],
+ [tr('disks.nvme.hostReads'), num(n.hostReads)],
+ [tr('disks.nvme.hostWrites'), num(n.hostWrites)],
+ [tr('disks.nvme.busy'), n.busyMinutes != null ? tr('disks.nvme.minutes', { v: num(n.busyMinutes) }) : null],
+ [tr('disks.powerCycles'), num(n.cycles)],
+ [tr('disks.powerOn'), n.hours != null ? hoursText(tr, n.hours) : null],
+ [tr('disks.unsafeShutdowns'), num(n.unsafeShutdowns)],
+ [tr('disks.mediaErrors'), num(n.mediaErrors)],
+ [tr('disks.nvme.errorEntries'), num(n.errorLogEntries)],
+ [tr('disks.nvme.warnTemp'), n.warningTempMinutes != null ? tr('disks.nvme.minutes', { v: num(n.warningTempMinutes) }) : null],
+ [tr('disks.nvme.critTemp'), n.criticalTempMinutes != null ? tr('disks.nvme.minutes', { v: num(n.criticalTempMinutes) }) : null],
+ ].filter(([, v]) => v != null);
+}
+
+// LordOS's own reader's attribute list (no smartmontools)
+function OwnAttrs({ attrs }) {
+ const t = useTheme();
+ const tr = useTr();
+ const [open, setOpen] = useState(false);
const cols = [['disks.attrName', 2], ['disks.attrValue', 1], ['disks.attrWorst', 1], ['disks.attrThresh', 1], ['disks.attrRaw', 1.4]];
- const attrs = s && st.attrs.length ? (
- <View key="attrs" style={{ paddingVertical: spacing.s, gap: 2 }}>
- <View onClick={() => setShowAll(!showAll)} style={{ alignSelf: 'flex-start' }}>
- <Text style={{ fontSize: typeScale.callout, color: t.accent, textAlign: 'start' }}>{showAll ? tr('disks.hideAttrs') : tr('disks.showAttrs', { n: st.attrs.length })}</Text>
+ return (
+ <View style={{ paddingVertical: spacing.s, gap: 2 }}>
+ <View onClick={() => setOpen(!open)} style={{ alignSelf: 'flex-start' }}>
+ <Text style={{ fontSize: typeScale.callout, color: t.accent, textAlign: 'start' }}>{open ? tr('disks.hideAttrs') : tr('disks.showAttrs', { n: attrs.length })}</Text>
</View>
- {showAll ? (
+ {open ? (
<View style={{ marginTop: spacing.xs }}>
<View style={{ flexDirection: 'row', gap: spacing.s, paddingVertical: 4 }}>
{cols.map(([k, f]) => <Text key={k} style={{ flex: f, fontSize: typeScale.caption, fontWeight: 600, color: t.textDim, textAlign: 'start' }}>{tr(k)}</Text>)}
</View>
- {st.attrs.map((a) => (
+ {attrs.map((a) => (
<View key={a.id} style={{ flexDirection: 'row', gap: spacing.s, paddingVertical: 3 }}>
- <Text style={{ flex: 2, fontSize: typeScale.caption, color: a.failing ? '#ff453a' : t.text, whiteSpace: 'nowrap', overflow: 'hidden', textAlign: 'start' }}>{`${a.id} · ${attrName(tr, a.id)}${a.prefail ? ' *' : ''}`}</Text>
+ <Text style={{ flex: 2, fontSize: typeScale.caption, color: a.failing ? '#ff453a' : t.text, whiteSpace: 'nowrap', overflow: 'hidden', textAlign: 'start' }}>{`${a.id} · ${ownAttrName(tr, a.id)}${a.prefail ? ' *' : ''}`}</Text>
{[a.value, a.worst, a.thresh].map((v, i) => <Text key={i} style={{ flex: 1, fontSize: typeScale.caption, color: t.text, textAlign: 'start' }}>{String(v)}</Text>)}
<Text style={{ flex: 1.4, fontSize: typeScale.caption, color: t.text, textAlign: 'start' }}>{String(a.raw)}</Text>
</View>
@@ -91,10 +391,5 @@ export function HealthCard({ disk }) {
</View>
) : null}
</View>
- ) : null;
- return (
- <GroupBox footer={s ? tr('disks.readIn', { ms: st.ms }) : null}>
- {[head, ...rows, attrs].filter(Boolean)}
- </GroupBox>
);
}
diff --git a/apps/disks/index.jsx b/apps/disks/index.jsx
index 33328ca..22e6593 100644
--- a/apps/disks/index.jsx
+++ b/apps/disks/index.jsx
@@ -8,7 +8,7 @@
// actions, which validate again on the root side: never the system disk, and internal disks only
// for an administrator.
import {
- View, Text, ScrollView, useTheme, useLocale, useSystemInfo, admin, useDisks, disks, formatBytes,
+ View, Text, ScrollView, useTheme, useLocale, useSystemInfo, useAppWindow, admin, useDisks, disks, formatBytes,
Toolbar as Bar, ToolbarButton, ToolbarSpacer, MenuButton, Hairline, GroupBox, FormRow, EmptyState, spacing, typeScale,
} from '@lordos/sdk';
import { useEffect, useMemo, useRef, useState } from 'react';
@@ -205,6 +205,7 @@ function DiskToolbar({ disk, part, onDialog, run, busy }) {
function Details({ disk, part, onDialog }) {
const t = useTheme();
+ const { isAdmin } = useCanTouch();
const { t: tr } = useLocale();
const [busy, setBusy] = useState(false);
const [msg, setMsg] = useState(null);
@@ -260,7 +261,7 @@ function Details({ disk, part, onDialog }) {
<Row key="parts" label={tr('disks.partitions')} value={String(disk.partitions.length)} />,
]}
</GroupBox>
- {!part ? <HealthCard disk={disk} /> : null}
+ {!part ? <HealthCard disk={disk} isAdmin={isAdmin} /> : null}
{target.ro ? <Text style={{ fontSize: typeScale.caption, color: t.textDim, textAlign: 'start' }}>{tr('disks.readOnlyNote')}</Text> : null}
</View>
</ScrollView>
@@ -273,6 +274,9 @@ export default function Disks() {
const [raw, reload] = useDisks();
const list = useMemo(() => [...raw].sort((a, b) => a.name.localeCompare(b.name)), [raw]);
const [sel, setSel] = useState({ disk: null, part: null });
+ // "Open in Disks" from the Monitor or a notice: that disk selected
+ const { args } = useAppWindow() || {};
+ useEffect(() => { if (args?.disk) setSel({ disk: args.disk, part: null }); }, [args?.disk, args?.nonce]);
const [dialog, setDialog] = useState(null);
const tools = useMemo(() => disks.tools(), []);
// pick something on open (the first removable, if any) and keep a valid selection if it disappears
diff --git a/apps/monitor/DisksTab.jsx b/apps/monitor/DisksTab.jsx
new file mode 100644
index 0000000..a1280fc
--- /dev/null
+++ b/apps/monitor/DisksTab.jsx
@@ -0,0 +1,158 @@
+// Monitor → Disks: read/write rates, and for each physical disk its live temperature (from the
+// kernel's hwmon sensors: the nvme driver, or drivetemp for SATA; lord.monitor, no root) and a
+// simple health light (OK / Check / Failing) from a cached SMART summary (smart.refresh, at most
+// every 5 minutes per disk, never waking a resting disk). The chosen disk shows its temperature over
+// the last 30 minutes, Cooling style, and "Open in Disks" for the full SMART report.
+import {
+ View, Text, Button, Toggle, useTheme, useLocale, useStore, useSettings, useAppWindow, wm, formatNumber, formatTemp, heatColor,
+ diskTempHistory, DISK_TEMP_HISTORY, smart, useSmartSummaries, diskTempLimit, diskAlertPrefs, setDiskAlerts, typeScale,
+} from '@lordos/sdk';
+import { useEffect, useMemo, useState } from 'react';
+import { Card, Big, Pair, Stat, Table, Cell, C, fmt, useCardStyle } from './index.jsx';
+import { Chart } from './Chart.jsx';
+
+export const HEALTH_COLOR = { ok: '#30d158', warning: '#ff9f0a', failing: '#ff453a', unknown: '#8e8e93' };
+
+function tempColor(t, d) {
+ if (d.temp == null) return t.textDim;
+ const lim = diskTempLimit(d);
+ return d.temp >= lim.max ? '#ff453a' : d.temp >= lim.max - 8 ? '#ff9f0a' : t.text;
+}
+
+// "38 °C", "No sensor", "Resting" (a spinning disk that is not read while it rests)
+function tempText(tr, d) {
+ if (!d.sensor) return tr('monitor.temp.noSensor');
+ if (d.temp == null) return d.tempIdle ? tr('monitor.temp.resting') : '—';
+ return formatTemp(d.temp);
+}
+
+function HealthDot({ health, size = 8 }) {
+ return <View style={{ width: size, height: size, borderRadius: size / 2, backgroundColor: HEALTH_COLOR[health] || HEALTH_COLOR.unknown }} />;
+}
+
+// Refreshes the summaries of the disks on screen, one at a time (each is a smartctl run as root).
+function useHealthRefresh(disks) {
+ const names = disks.map((d) => `${d.name}:${d.awake ? 1 : 0}`).join(',');
+ useEffect(() => {
+ let alive = true;
+ const run = async () => {
+ for (const d of disks) { if (!alive) return; await smart.refresh(d, { awake: d.awake }); }
+ };
+ run();
+ const id = setInterval(run, 60 * 1000);
+ return () => { alive = false; clearInterval(id); };
+ }, [names]);
+}
+
+export function DisksTab({ s, last }) {
+ const t = useTheme();
+ const { t: tr } = useLocale();
+ const card = useCardStyle();
+ const { args } = useAppWindow() || {};
+ useSettings(); // redraw when the alert switch changes
+ const list = last.disk.disks;
+ const sums = useSmartSummaries();
+ const hist = useStore(diskTempHistory);
+ useHealthRefresh(list);
+ const [pick, setPick] = useState(args?.disk || null);
+ useEffect(() => { if (args?.disk) setPick(args.disk); }, [args?.disk, args?.nonce]);
+ const sel = list.find((d) => d.name === pick) || list.find((d) => d.sensor) || list[0];
+ const cols = [
+ { key: 'name', label: tr('monitor.diskCol'), flex: 1 },
+ { key: 'dev', label: tr('monitor.device'), width: 100 },
+ { key: 'size', label: tr('monitor.size'), width: 84, num: true },
+ { key: 'temp', label: tr('monitor.temp.col'), width: 100, num: true },
+ { key: 'health', label: tr('monitor.health.col'), width: 100 },
+ { key: 'read', label: tr('monitor.read'), width: 96, num: true },
+ { key: 'write', label: tr('monitor.write'), width: 96, num: true },
+ ];
+ const healthOf = (d) => sums[d.name]?.health || 'unknown';
+ const healthText = (d) => {
+ const x = sums[d.name];
+ if (!smart.smartable(d.name)) return tr('monitor.health.none');
+ if (!x || x.idle) return '—';
+ return tr(`monitor.health.${x.health}`);
+ };
+ return (
+ <>
+ <Card icon="disk" title={tr('monitor.allDisks')}>
+ <Pair items={[{ label: tr('monitor.read'), value: fmt.rate(tr, last.disk.read), color: C.read }, { label: tr('monitor.write'), value: fmt.rate(tr, last.disk.write), color: C.write }]} />
+ <Chart series={[{ label: tr('monitor.read'), values: s.read, color: C.read }, { label: tr('monitor.write'), values: s.write, color: C.write }]}
+ format={(v) => fmt.rate(tr, v)} times={s.times} height={150} bg={card.bg} />
+ </Card>
+ <Table cols={cols} rows={list.map((d, i) => (
+ <View key={d.name} onClick={() => setPick(d.name)}
+ style={{ flexDirection: 'row', height: 30, alignItems: 'center', paddingHorizontal: 10,
+ backgroundColor: sel && sel.name === d.name ? (t.mode === 'dark' ? 'rgba(10,132,255,0.24)' : 'rgba(0,122,255,0.12)') : i % 2 ? t.hover : 'transparent' }}>
+ <Cell col={cols[0]}>{d.model || tr('monitor.diskUnknown')}</Cell>
+ <Cell col={cols[1]} color={t.textDim}>{`/dev/${d.name}`}</Cell>
+ <Cell col={cols[2]}>{fmt.mem(d.size)}</Cell>
+ <Cell col={cols[3]} color={d.sensor && d.temp != null ? tempColor(t, d) : t.textDim}>{tempText(tr, d)}</Cell>
+ <Cell col={cols[4]}>
+ {smart.smartable(d.name) && sums[d.name] && !sums[d.name].idle ? <HealthDot health={healthOf(d)} /> : null}
+ <Text style={{ fontSize: 12, color: sums[d.name] ? t.text : t.textDim, whiteSpace: 'nowrap', textAlign: 'start' }}>{healthText(d)}</Text>
+ </Cell>
+ <Cell col={cols[5]}>{fmt.rate(tr, d.read)}</Cell>
+ <Cell col={cols[6]}>{fmt.rate(tr, d.write)}</Cell>
+ </View>
+ ))} />
+ {!list.length && <Text style={{ fontSize: 12, color: t.textDim }}>{tr('monitor.noDisks')}</Text>}
+ {sel ? <DiskDetail d={sel} sum={sums[sel.name]} h={hist[sel.name]} /> : null}
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 10 }}>
+ <Toggle small on={diskAlertPrefs()} onChange={(on) => setDiskAlerts(on)} />
+ <Text style={{ flex: 1, fontSize: 12, color: t.textDim, textAlign: 'start' }}>{tr('monitor.diskAlert.toggle')}</Text>
+ </View>
+ </>
+ );
+}
+
+function DiskDetail({ d, sum, h }) {
+ const t = useTheme();
+ const { t: tr } = useLocale();
+ const card = useCardStyle();
+ const lim = diskTempLimit(d);
+ const series = useMemo(() => ({ times: h ? h.t : [], v: h ? h.v : [] }), [h]);
+ const peak = series.v.reduce((a, v) => Math.max(a, v), 0);
+ const top = Math.ceil(Math.max(lim.crit || lim.max, peak + 5) / 10) * 10;
+ const health = sum?.health || 'unknown';
+ const open = () => wm.open('disks', { args: { disk: d.name, nonce: Date.now() } });
+ const tempHint = !d.sensor ? tr('monitor.temp.noSensorHint')
+ : d.temp == null && d.tempIdle ? tr('monitor.temp.restingHint')
+ : tr(lim.own ? 'monitor.temp.limitOwn' : 'monitor.temp.limitDefault', { max: lim.max });
+ return (
+ <View style={{ flexDirection: 'row', gap: 12 }}>
+ <Card icon="temp" title={tr('monitor.temp.title', { name: d.model || `/dev/${d.name}` })} style={{ flex: 3 }}>
+ <View style={{ flexDirection: 'row', alignItems: 'flex-end', gap: 12 }}>
+ <Big value={d.sensor ? (d.temp != null ? formatTemp(d.temp) : '—') : tr('monitor.temp.noSensor')} small={d.sensor ? tr(`monitor.temp.sensor.${d.sensor}`) : null} />
+ {d.temp != null ? <View style={{ width: 10, height: 10, borderRadius: 5, marginBottom: 6, backgroundColor: heatColor(d.temp) }} /> : null}
+ </View>
+ <Text style={{ fontSize: 11, color: t.textDim, textAlign: 'start' }}>{tempHint}</Text>
+ {d.sensor && series.v.length ? (
+ <Chart series={[{ label: tr('cooling.temperature'), values: series.v, color: '#ff9f0a' }]} max={top}
+ format={(v) => formatNumber(Math.round(v), 0)} times={series.times} capacity={DISK_TEMP_HISTORY} height={130} bg={card.bg} />
+ ) : null}
+ </Card>
+ <Card icon="disk" title={tr('monitor.health.title')} style={{ flex: 2 }}
+ right={<View onClick={open}><Text style={{ fontSize: 11, color: t.accent, whiteSpace: 'nowrap' }}>{tr('monitor.health.openDisks')}</Text></View>}>
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
+ <HealthDot health={health} size={12} />
+ <Text style={{ fontSize: 20, fontWeight: 600, color: t.text }}>{smart.smartable(d.name) ? (sum && !sum.idle ? tr(`monitor.health.${health}`) : '—') : tr('monitor.health.none')}</Text>
+ </View>
+ <Text style={{ fontSize: 12, color: t.textDim, lineHeight: 1.4, textAlign: 'start' }}>
+ {!smart.smartable(d.name) ? tr('monitor.health.noneHint')
+ : !sum ? tr('monitor.health.waiting')
+ : sum.standby ? tr('monitor.health.standby')
+ : sum.idle ? tr('monitor.health.idle')
+ : sum.error ? tr('monitor.health.errorHint')
+ : tr(`monitor.health.hint.${health}`)}
+ </Text>
+ <View style={{ flexDirection: 'row', gap: 8 }}>
+ <Stat label={tr('monitor.health.hours')} value={sum?.hours != null ? formatNumber(sum.hours, 0) : '—'} unit={sum?.hours != null ? tr('monitor.health.hoursUnit') : null} />
+ <Stat label={tr('monitor.health.wear')} value={sum?.wear != null ? formatNumber(sum.wear, 0) : '—'} unit={sum?.wear != null ? '%' : null} />
+ </View>
+ {!smart.installed() && smart.smartable(d.name) ? <Text style={{ fontSize: 11, color: t.textDim, lineHeight: 1.4, textAlign: 'start' }}>{tr('monitor.health.basic')}</Text> : null}
+ <Button small label={tr('monitor.health.openDisks')} onClick={open} />
+ </Card>
+ </View>
+ );
+}
diff --git a/apps/monitor/index.jsx b/apps/monitor/index.jsx
index bcb759a..1fddfb2 100644
--- a/apps/monitor/index.jsx
+++ b/apps/monitor/index.jsx
@@ -18,6 +18,7 @@ import { FirewallPrivacy } from './Firewall.jsx';
import { FirewallRulesPrivacy } from './FwRules.jsx';
import { CoolingTab } from './Cooling.jsx';
import { ProcessesTab, ProcessLayers } from './Processes.jsx';
+import { DisksTab } from './DisksTab.jsx';
export function Icon({ size }) { return <MonitorIcon size={size} />; }
@@ -117,6 +118,7 @@ export function Stat({ label, value, unit, icon, children }) {
registerDockActions('monitor', () => [
{ id: 'network', label: 'monitor.network', args: { tab: 'network' } },
{ id: 'cooling', label: 'monitor.tab.cooling', args: { tab: 'cooling' } },
+ { id: 'disks', label: 'monitor.disks', args: { tab: 'disks' } },
]);
function useSeries(samples) {
@@ -318,38 +320,6 @@ export function Cell({ col, children, color, bold }) {
);
}
-function DisksTab({ s, last }) {
- const t = useTheme();
- const { t: tr } = useLocale();
- const card = useCardStyle();
- const cols = [
- { key: 'name', label: tr('monitor.diskCol'), flex: 1 },
- { key: 'dev', label: tr('monitor.device'), width: 110 },
- { key: 'size', label: tr('monitor.size'), width: 100, num: true },
- { key: 'read', label: tr('monitor.read'), width: 110, num: true },
- { key: 'write', label: tr('monitor.write'), width: 110, num: true },
- ];
- return (
- <>
- <Card icon="disk" title={tr('monitor.allDisks')}>
- <Pair items={[{ label: tr('monitor.read'), value: fmt.rate(tr, last.disk.read), color: C.read }, { label: tr('monitor.write'), value: fmt.rate(tr, last.disk.write), color: C.write }]} />
- <Chart series={[{ label: tr('monitor.read'), values: s.read, color: C.read }, { label: tr('monitor.write'), values: s.write, color: C.write }]}
- format={(v) => fmt.rate(tr, v)} times={s.times} height={150} bg={card.bg} />
- </Card>
- <Table cols={cols} rows={last.disk.disks.map((d, i) => (
- <View key={d.name} style={{ flexDirection: 'row', height: 30, alignItems: 'center', paddingHorizontal: 10, backgroundColor: i % 2 ? t.hover : 'transparent' }}>
- <Cell col={cols[0]}>{d.model || tr('monitor.diskUnknown')}</Cell>
- <Cell col={cols[1]} color={t.textDim}>{`/dev/${d.name}`}</Cell>
- <Cell col={cols[2]}>{fmt.mem(d.size)}</Cell>
- <Cell col={cols[3]}>{fmt.rate(tr, d.read)}</Cell>
- <Cell col={cols[4]}>{fmt.rate(tr, d.write)}</Cell>
- </View>
- ))} />
- {!last.disk.disks.length && <Text style={{ fontSize: 12, color: t.textDim }}>{tr('monitor.noDisks')}</Text>}
- </>
- );
-}
-
// ---- Processes ----
export function AppGlyph({ item, size = 16 }) {
diff --git a/assets/locales/en/disks.json b/assets/locales/en/disks.json
index 170e0bd..5136c02 100644
--- a/assets/locales/en/disks.json
+++ b/assets/locales/en/disks.json
@@ -175,5 +175,100 @@
"phase.verify": "Verifying…",
"progress": "{done} of {total} ({pct}%)",
"kindRemovable": "Removable drive",
- "more": "More actions"
+ "more": "More actions",
+ "smart.unsupportedBridge": "The disk is behind an adapter that does not pass SMART through.",
+ "smart.readWith": "Read with smartmontools in {ms}",
+ "smart.tempWithLimit": "{v} °C (limit {max} °C, critical {crit} °C)",
+ "smart.wear": "SSD wear",
+ "smart.wearValue": "{v}% of its rated life used",
+ "smart.firmware": "Firmware",
+ "smart.advanced": "Detailed health",
+ "smart.installHint": "Self-tests, the error log, the temperature history and every attribute with its meaning come from smartmontools, Debian’s standard disk health tools. It is installed once, with the Store’s package engine.",
+ "smart.installAdmin": "An administrator has to install it.",
+ "smart.install": "Install smartmontools",
+ "smart.installing": "Installing…",
+ "smart.tests": "Self-tests",
+ "smart.testHint": "The disk checks itself while you keep using it. The short test reads the most important areas; the long one reads the whole surface.",
+ "smart.testRunning": "Running: {pct}% done",
+ "smart.testRunningNoPct": "Running…",
+ "smart.testUnsupported": "This disk does not offer self-tests.",
+ "smart.testAbort": "Stop the test",
+ "smart.testShort": "Short test",
+ "smart.testShortMin": "Short test (~{n} min)",
+ "smart.testLong": "Long test",
+ "smart.testLongMin": "Long test (~{n} min)",
+ "smart.testOther": "Other test",
+ "smart.test.short": "Short test",
+ "smart.test.long": "Long test",
+ "smart.atHour": "at hour {h}",
+ "smart.testResults": "Results",
+ "smart.testNone": "No tests yet",
+ "smart.nvmeResult.completed": "Completed without error",
+ "smart.nvmeResult.abortedCommand": "Stopped by request",
+ "smart.nvmeResult.abortedReset": "Stopped by a controller reset",
+ "smart.nvmeResult.abortedRemoved": "Stopped: the namespace was removed",
+ "smart.nvmeResult.abortedFormat": "Stopped by a format",
+ "smart.nvmeResult.fatal": "Failed: fatal error",
+ "smart.nvmeResult.failedUnknownSegment": "Failed (unknown segment)",
+ "smart.nvmeResult.failedSegments": "Failed: one or more segments",
+ "smart.nvmeResult.abortedUnknown": "Stopped for an unknown reason",
+ "smart.nvmeResult.abortedSanitize": "Stopped by a sanitize operation",
+ "smart.tempHistory": "Temperature history (recorded by the disk)",
+ "smart.tempHistoryFoot": "{n} samples, one every {min} min · {lo}–{hi} °C",
+ "smart.errorLog": "Error log",
+ "smart.errorCount": "Errors logged",
+ "smart.errorNone": "None",
+ "smart.nvmeErrorsHint": "NVMe drives also log harmless events here (such as an unsupported command): what matters is the health above.",
+ "smart.attributes": "All attributes",
+ "reason.smartFailed": "The disk reports that it is failing",
+ "reason.prefailNow": "A critical attribute is below its limit",
+ "reason.oldAgeNow": "A wear attribute is below its limit",
+ "reason.prefailPast": "A critical attribute was below its limit in the past",
+ "reason.reallocated": "{n} reallocated sectors",
+ "reason.pending": "{n} sectors waiting to be reallocated",
+ "reason.uncorrectable": "{n} sectors that could not be read",
+ "reason.grownDefects": "{n} defects found since it was made",
+ "reason.nvmeReliability": "The drive reports its reliability has degraded",
+ "reason.nvmeReadOnly": "The drive switched itself to read-only",
+ "reason.nvmeSpare": "Spare blocks are below the safe level",
+ "reason.nvmeTemp": "The drive reports a temperature problem",
+ "reason.nvmeBackup": "The drive’s power-loss protection failed",
+ "reason.mediaErrors": "{n} media errors",
+ "reason.worn": "{n}% of its rated life used",
+ "nvme.criticalWarning": "Critical warning",
+ "nvme.none": "None",
+ "nvme.sensors": "Temperature sensors",
+ "nvme.hostReads": "Read commands",
+ "nvme.hostWrites": "Write commands",
+ "nvme.busy": "Time busy",
+ "nvme.minutes": "{v} min",
+ "nvme.errorEntries": "Error log entries",
+ "nvme.warnTemp": "Time above the warning temperature",
+ "nvme.critTemp": "Time above the critical temperature",
+ "attr.a2": "Throughput performance",
+ "attr.a8": "Seek time performance",
+ "attr.a11": "Calibration retries",
+ "attr.a13": "Soft read error rate",
+ "attr.a22": "Helium level",
+ "attr.a171": "Program (write) failures",
+ "attr.a172": "Erase failures",
+ "attr.a173": "Average erase count",
+ "attr.a174": "Unexpected power losses",
+ "attr.a179": "Reserved blocks used",
+ "attr.a180": "Reserved blocks left",
+ "attr.a181": "Program failures (total)",
+ "attr.a182": "Erase failures (total)",
+ "attr.a189": "High fly writes",
+ "attr.a191": "Shock events",
+ "attr.a195": "Errors corrected by ECC",
+ "attr.a200": "Write error rate",
+ "attr.a202": "Life left",
+ "attr.a220": "Disk shift",
+ "attr.a222": "Hours with heads loaded",
+ "attr.a223": "Load retries",
+ "attr.a224": "Load friction",
+ "attr.a226": "Load-in time",
+ "attr.a232": "Reserved space left",
+ "attr.a240": "Head flying hours",
+ "attr.a254": "Free fall events"
}
diff --git a/assets/locales/en/errors.json b/assets/locales/en/errors.json
index c1886e6..79733e5 100644
--- a/assets/locales/en/errors.json
+++ b/assets/locales/en/errors.json
@@ -558,5 +558,8 @@
"proc.denied": "Not allowed to stop this process",
"proc.failed": "Could not stop the process",
"proc.badArgument": "Invalid process request",
- "proc.notOwn": "This process belongs to another user"
+ "proc.notOwn": "This process belongs to another user",
+ "disk.noSmartctl": "smartmontools is not installed",
+ "disk.smartFailed": "Could not read the disk health",
+ "disk.smartTestFailed": "The disk did not start the self-test"
}
diff --git a/assets/locales/en/monitor.json b/assets/locales/en/monitor.json
index cb074f5..85e75da 100644
--- a/assets/locales/en/monitor.json
+++ b/assets/locales/en/monitor.json
@@ -217,5 +217,45 @@
"proc.cmdline": "Command line",
"proc.noCmdline": "(none: a kernel thread or a process that cleared it)",
"proc.tab.stats": "Statistics",
- "proc.tab.files": "Open files and ports"
+ "proc.tab.files": "Open files and ports",
+ "temp.col": "Temperature",
+ "temp.noSensor": "No sensor",
+ "temp.resting": "Resting",
+ "temp.noSensorHint": "This disk has no temperature sensor the system can read (memory cards, virtual disks and many USB adapters don’t).",
+ "temp.restingHint": "The disk is resting: it is read again as soon as it is used, so it can stay spun down.",
+ "temp.limitOwn": "Limit {max} °C, reported by the drive",
+ "temp.limitDefault": "Limit {max} °C (the drive does not report its own)",
+ "temp.title": "Temperature · {name}",
+ "temp.sensor.nvme": "NVMe sensor",
+ "temp.sensor.drivetemp": "SATA sensor",
+ "health.col": "Health",
+ "health.title": "Health (SMART)",
+ "health.ok": "OK",
+ "health.warning": "Check",
+ "health.failing": "Failing",
+ "health.unknown": "No data",
+ "health.none": "No SMART",
+ "health.noneHint": "This kind of disk does not report its health (memory cards, virtual disks).",
+ "health.waiting": "Reading the disk’s health…",
+ "health.standby": "The disk is resting: its health is read the next time it is used.",
+ "health.errorHint": "The disk did not answer SMART (it may not have it, or be behind a USB adapter that blocks it).",
+ "health.hint.ok": "The disk reports no problems.",
+ "health.hint.warning": "There are signs of wear: open it in Disks to see why, and keep a backup.",
+ "health.hint.failing": "The disk says it will fail soon. Copy your data now.",
+ "health.hint.unknown": "The disk answered, but without enough data.",
+ "health.openDisks": "Open in Disks",
+ "health.hours": "Powered on",
+ "health.hoursUnit": "h",
+ "health.wear": "SSD wear",
+ "health.basic": "Basic reading. Install smartmontools in Disks for the full report and self-tests.",
+ "diskAlert.toggle": "Notify me when a disk gets too hot or its health gets worse",
+ "diskAlert.hotTitle": "{name} is too hot",
+ "diskAlert.critTitle": "{name} is at a critical temperature",
+ "diskAlert.hotBody": "{dev} is at {temp} °C (limit {max} °C). Check the airflow around it.",
+ "diskAlert.open": "Open Monitor",
+ "diskAlert.checkTitle": "{name} needs a check",
+ "diskAlert.checkBody": "{dev} shows signs of wear. Make sure you have a backup.",
+ "diskAlert.failTitle": "{name} is failing",
+ "diskAlert.failBody": "{dev} reports that it will fail soon. Copy your data now.",
+ "health.idle": "Not read yet: a spinning disk is read the next time it is in use, so a resting disk is not woken up. With smartmontools it is read without waking it."
}
diff --git a/assets/locales/es/disks.json b/assets/locales/es/disks.json
index 534b7cc..05412c6 100644
--- a/assets/locales/es/disks.json
+++ b/assets/locales/es/disks.json
@@ -175,5 +175,100 @@
"phase.verify": "Verificando…",
"progress": "{done} de {total} ({pct} %)",
"kindRemovable": "Unidad extraíble",
- "more": "Más acciones"
+ "more": "Más acciones",
+ "smart.unsupportedBridge": "El disco está detrás de un adaptador que no deja pasar SMART.",
+ "smart.readWith": "Leído con smartmontools en {ms}",
+ "smart.tempWithLimit": "{v} °C (límite {max} °C, crítica {crit} °C)",
+ "smart.wear": "Desgaste del SSD",
+ "smart.wearValue": "{v}% de su vida útil usada",
+ "smart.firmware": "Firmware",
+ "smart.advanced": "Salud detallada",
+ "smart.installHint": "Las autopruebas, el registro de errores, el historial de temperatura y todos los atributos con su significado vienen de smartmontools, las herramientas estándar de salud de discos de Debian. Se instala una vez, con el motor de paquetes de la Tienda.",
+ "smart.installAdmin": "Lo tiene que instalar un administrador.",
+ "smart.install": "Instalar smartmontools",
+ "smart.installing": "Instalando…",
+ "smart.tests": "Autopruebas",
+ "smart.testHint": "El disco se revisa a sí mismo mientras lo seguís usando. La prueba corta lee las zonas más importantes; la larga lee toda la superficie.",
+ "smart.testRunning": "En curso: {pct}% hecho",
+ "smart.testRunningNoPct": "En curso…",
+ "smart.testUnsupported": "Este disco no ofrece autopruebas.",
+ "smart.testAbort": "Detener la prueba",
+ "smart.testShort": "Prueba corta",
+ "smart.testShortMin": "Prueba corta (~{n} min)",
+ "smart.testLong": "Prueba larga",
+ "smart.testLongMin": "Prueba larga (~{n} min)",
+ "smart.testOther": "Otra prueba",
+ "smart.test.short": "Prueba corta",
+ "smart.test.long": "Prueba larga",
+ "smart.atHour": "en la hora {h}",
+ "smart.testResults": "Resultados",
+ "smart.testNone": "Todavía no hay pruebas",
+ "smart.nvmeResult.completed": "Terminada sin errores",
+ "smart.nvmeResult.abortedCommand": "Detenida a pedido",
+ "smart.nvmeResult.abortedReset": "Detenida por un reinicio del controlador",
+ "smart.nvmeResult.abortedRemoved": "Detenida: se quitó el espacio de nombres",
+ "smart.nvmeResult.abortedFormat": "Detenida por un formateo",
+ "smart.nvmeResult.fatal": "Falló: error fatal",
+ "smart.nvmeResult.failedUnknownSegment": "Falló (segmento desconocido)",
+ "smart.nvmeResult.failedSegments": "Falló: uno o más segmentos",
+ "smart.nvmeResult.abortedUnknown": "Detenida por un motivo desconocido",
+ "smart.nvmeResult.abortedSanitize": "Detenida por un borrado seguro",
+ "smart.tempHistory": "Historial de temperatura (registrado por el disco)",
+ "smart.tempHistoryFoot": "{n} muestras, una cada {min} min · {lo}–{hi} °C",
+ "smart.errorLog": "Registro de errores",
+ "smart.errorCount": "Errores registrados",
+ "smart.errorNone": "Ninguno",
+ "smart.nvmeErrorsHint": "Las unidades NVMe también anotan aquí eventos inofensivos (como un comando no soportado): lo que importa es la salud de arriba.",
+ "smart.attributes": "Todos los atributos",
+ "reason.smartFailed": "El disco informa que está fallando",
+ "reason.prefailNow": "Un atributo crítico está por debajo de su límite",
+ "reason.oldAgeNow": "Un atributo de desgaste está por debajo de su límite",
+ "reason.prefailPast": "Un atributo crítico estuvo por debajo de su límite",
+ "reason.reallocated": "{n} sectores reasignados",
+ "reason.pending": "{n} sectores pendientes de reasignar",
+ "reason.uncorrectable": "{n} sectores que no se pudieron leer",
+ "reason.grownDefects": "{n} defectos aparecidos desde su fabricación",
+ "reason.nvmeReliability": "La unidad informa que su fiabilidad bajó",
+ "reason.nvmeReadOnly": "La unidad se pasó a solo lectura",
+ "reason.nvmeSpare": "Los bloques de reserva están por debajo del nivel seguro",
+ "reason.nvmeTemp": "La unidad informa un problema de temperatura",
+ "reason.nvmeBackup": "Falló la protección ante cortes de la unidad",
+ "reason.mediaErrors": "{n} errores de medio",
+ "reason.worn": "{n}% de su vida útil usada",
+ "nvme.criticalWarning": "Advertencia crítica",
+ "nvme.none": "Ninguna",
+ "nvme.sensors": "Sensores de temperatura",
+ "nvme.hostReads": "Comandos de lectura",
+ "nvme.hostWrites": "Comandos de escritura",
+ "nvme.busy": "Tiempo ocupado",
+ "nvme.minutes": "{v} min",
+ "nvme.errorEntries": "Entradas del registro de errores",
+ "nvme.warnTemp": "Tiempo sobre la temperatura de aviso",
+ "nvme.critTemp": "Tiempo sobre la temperatura crítica",
+ "attr.a2": "Rendimiento de transferencia",
+ "attr.a8": "Rendimiento de búsqueda",
+ "attr.a11": "Reintentos de calibración",
+ "attr.a13": "Tasa de errores leves de lectura",
+ "attr.a22": "Nivel de helio",
+ "attr.a171": "Fallas de programación (escritura)",
+ "attr.a172": "Fallas de borrado",
+ "attr.a173": "Promedio de borrados",
+ "attr.a174": "Cortes de energía inesperados",
+ "attr.a179": "Bloques de reserva usados",
+ "attr.a180": "Bloques de reserva libres",
+ "attr.a181": "Fallas de programación (total)",
+ "attr.a182": "Fallas de borrado (total)",
+ "attr.a189": "Escrituras con el cabezal alto",
+ "attr.a191": "Golpes detectados",
+ "attr.a195": "Errores corregidos por ECC",
+ "attr.a200": "Tasa de errores de escritura",
+ "attr.a202": "Vida restante",
+ "attr.a220": "Desplazamiento del disco",
+ "attr.a222": "Horas con los cabezales cargados",
+ "attr.a223": "Reintentos de carga",
+ "attr.a224": "Fricción de carga",
+ "attr.a226": "Tiempo de carga",
+ "attr.a232": "Espacio de reserva libre",
+ "attr.a240": "Horas de vuelo del cabezal",
+ "attr.a254": "Caídas detectadas"
}
diff --git a/assets/locales/es/errors.json b/assets/locales/es/errors.json
index 51eb699..e3f5e3a 100644
--- a/assets/locales/es/errors.json
+++ b/assets/locales/es/errors.json
@@ -558,5 +558,8 @@
"proc.denied": "No tenés permiso para detener este proceso",
"proc.failed": "No se pudo detener el proceso",
"proc.badArgument": "Pedido de proceso no válido",
- "proc.notOwn": "Este proceso es de otro usuario"
+ "proc.notOwn": "Este proceso es de otro usuario",
+ "disk.noSmartctl": "smartmontools no está instalado",
+ "disk.smartFailed": "No se pudo leer la salud del disco",
+ "disk.smartTestFailed": "El disco no inició la autoprueba"
}
diff --git a/assets/locales/es/monitor.json b/assets/locales/es/monitor.json
index 78afbc6..e1afc46 100644
--- a/assets/locales/es/monitor.json
+++ b/assets/locales/es/monitor.json
@@ -217,5 +217,45 @@
"proc.cmdline": "Línea de comandos",
"proc.noCmdline": "(ninguna: un hilo del núcleo o un proceso que la borró)",
"proc.tab.stats": "Estadísticas",
- "proc.tab.files": "Archivos y puertos abiertos"
+ "proc.tab.files": "Archivos y puertos abiertos",
+ "temp.col": "Temperatura",
+ "temp.noSensor": "Sin sensor",
+ "temp.resting": "En reposo",
+ "temp.noSensorHint": "Este disco no tiene un sensor de temperatura que el sistema pueda leer (las tarjetas de memoria, los discos virtuales y muchos adaptadores USB no lo tienen).",
+ "temp.restingHint": "El disco está en reposo: se vuelve a leer en cuanto se use, así puede seguir detenido.",
+ "temp.limitOwn": "Límite {max} °C, informado por el disco",
+ "temp.limitDefault": "Límite {max} °C (el disco no informa el suyo)",
+ "temp.title": "Temperatura · {name}",
+ "temp.sensor.nvme": "sensor NVMe",
+ "temp.sensor.drivetemp": "sensor SATA",
+ "health.col": "Salud",
+ "health.title": "Salud (SMART)",
+ "health.ok": "Bien",
+ "health.warning": "Revisar",
+ "health.failing": "Fallando",
+ "health.unknown": "Sin datos",
+ "health.none": "Sin SMART",
+ "health.noneHint": "Este tipo de disco no informa su salud (tarjetas de memoria, discos virtuales).",
+ "health.waiting": "Leyendo la salud del disco…",
+ "health.standby": "El disco está en reposo: su salud se lee la próxima vez que se use.",
+ "health.errorHint": "El disco no respondió SMART (puede no tenerlo, o estar detrás de un adaptador USB que lo bloquea).",
+ "health.hint.ok": "El disco no informa problemas.",
+ "health.hint.warning": "Hay señales de desgaste: abrilo en Discos para ver por qué y tené una copia de seguridad.",
+ "health.hint.failing": "El disco dice que va a fallar pronto. Copiá tus datos ya.",
+ "health.hint.unknown": "El disco respondió, pero sin datos suficientes.",
+ "health.openDisks": "Abrir en Discos",
+ "health.hours": "Encendido",
+ "health.hoursUnit": "h",
+ "health.wear": "Desgaste del SSD",
+ "health.basic": "Lectura básica. Instalá smartmontools en Discos para el informe completo y las autopruebas.",
+ "diskAlert.toggle": "Avisarme cuando un disco se caliente demasiado o empeore su salud",
+ "diskAlert.hotTitle": "{name} está muy caliente",
+ "diskAlert.critTitle": "{name} está a una temperatura crítica",
+ "diskAlert.hotBody": "{dev} está a {temp} °C (límite {max} °C). Revisá la ventilación a su alrededor.",
+ "diskAlert.open": "Abrir Monitor",
+ "diskAlert.checkTitle": "{name} necesita revisión",
+ "diskAlert.checkBody": "{dev} muestra señales de desgaste. Asegurate de tener una copia de seguridad.",
+ "diskAlert.failTitle": "{name} está fallando",
+ "diskAlert.failBody": "{dev} informa que va a fallar pronto. Copiá tus datos ya.",
+ "health.idle": "Todavía sin leer: un disco giratorio se lee la próxima vez que se use, para no despertarlo si está en reposo. Con smartmontools se lee sin despertarlo."
}
diff --git a/assets/locales/pt/disks.json b/assets/locales/pt/disks.json
index 3ea2a37..0bf66ef 100644
--- a/assets/locales/pt/disks.json
+++ b/assets/locales/pt/disks.json
@@ -175,5 +175,100 @@
"phase.verify": "Verificando…",
"progress": "{done} de {total} ({pct}%)",
"kindRemovable": "Unidade removível",
- "more": "Mais ações"
+ "more": "Mais ações",
+ "smart.unsupportedBridge": "O disco está atrás de um adaptador que não deixa passar o SMART.",
+ "smart.readWith": "Lido com o smartmontools em {ms}",
+ "smart.tempWithLimit": "{v} °C (limite {max} °C, crítica {crit} °C)",
+ "smart.wear": "Desgaste do SSD",
+ "smart.wearValue": "{v}% da vida útil usada",
+ "smart.firmware": "Firmware",
+ "smart.advanced": "Saúde detalhada",
+ "smart.installHint": "Os autotestes, o registro de erros, o histórico de temperatura e todos os atributos com seu significado vêm do smartmontools, as ferramentas padrão de saúde de discos do Debian. É instalado uma vez, com o motor de pacotes da Loja.",
+ "smart.installAdmin": "Um administrador precisa instalar.",
+ "smart.install": "Instalar smartmontools",
+ "smart.installing": "Instalando…",
+ "smart.tests": "Autotestes",
+ "smart.testHint": "O disco verifica a si mesmo enquanto você continua usando. O teste curto lê as áreas mais importantes; o longo lê toda a superfície.",
+ "smart.testRunning": "Em andamento: {pct}% feito",
+ "smart.testRunningNoPct": "Em andamento…",
+ "smart.testUnsupported": "Este disco não oferece autotestes.",
+ "smart.testAbort": "Parar o teste",
+ "smart.testShort": "Teste curto",
+ "smart.testShortMin": "Teste curto (~{n} min)",
+ "smart.testLong": "Teste longo",
+ "smart.testLongMin": "Teste longo (~{n} min)",
+ "smart.testOther": "Outro teste",
+ "smart.test.short": "Teste curto",
+ "smart.test.long": "Teste longo",
+ "smart.atHour": "na hora {h}",
+ "smart.testResults": "Resultados",
+ "smart.testNone": "Ainda não há testes",
+ "smart.nvmeResult.completed": "Concluído sem erros",
+ "smart.nvmeResult.abortedCommand": "Parado a pedido",
+ "smart.nvmeResult.abortedReset": "Parado por um reinício do controlador",
+ "smart.nvmeResult.abortedRemoved": "Parado: o namespace foi removido",
+ "smart.nvmeResult.abortedFormat": "Parado por uma formatação",
+ "smart.nvmeResult.fatal": "Falhou: erro fatal",
+ "smart.nvmeResult.failedUnknownSegment": "Falhou (segmento desconhecido)",
+ "smart.nvmeResult.failedSegments": "Falhou: um ou mais segmentos",
+ "smart.nvmeResult.abortedUnknown": "Parado por um motivo desconhecido",
+ "smart.nvmeResult.abortedSanitize": "Parado por um apagamento seguro",
+ "smart.tempHistory": "Histórico de temperatura (registrado pelo disco)",
+ "smart.tempHistoryFoot": "{n} amostras, uma a cada {min} min · {lo}–{hi} °C",
+ "smart.errorLog": "Registro de erros",
+ "smart.errorCount": "Erros registrados",
+ "smart.errorNone": "Nenhum",
+ "smart.nvmeErrorsHint": "As unidades NVMe também anotam aqui eventos inofensivos (como um comando não suportado): o que importa é a saúde acima.",
+ "smart.attributes": "Todos os atributos",
+ "reason.smartFailed": "O disco informa que está falhando",
+ "reason.prefailNow": "Um atributo crítico está abaixo do limite",
+ "reason.oldAgeNow": "Um atributo de desgaste está abaixo do limite",
+ "reason.prefailPast": "Um atributo crítico esteve abaixo do limite no passado",
+ "reason.reallocated": "{n} setores realocados",
+ "reason.pending": "{n} setores aguardando realocação",
+ "reason.uncorrectable": "{n} setores que não puderam ser lidos",
+ "reason.grownDefects": "{n} defeitos surgidos desde a fabricação",
+ "reason.nvmeReliability": "A unidade informa que sua confiabilidade caiu",
+ "reason.nvmeReadOnly": "A unidade passou para somente leitura",
+ "reason.nvmeSpare": "Os blocos reserva estão abaixo do nível seguro",
+ "reason.nvmeTemp": "A unidade informa um problema de temperatura",
+ "reason.nvmeBackup": "Falhou a proteção contra quedas de energia da unidade",
+ "reason.mediaErrors": "{n} erros de mídia",
+ "reason.worn": "{n}% da vida útil usada",
+ "nvme.criticalWarning": "Aviso crítico",
+ "nvme.none": "Nenhum",
+ "nvme.sensors": "Sensores de temperatura",
+ "nvme.hostReads": "Comandos de leitura",
+ "nvme.hostWrites": "Comandos de escrita",
+ "nvme.busy": "Tempo ocupado",
+ "nvme.minutes": "{v} min",
+ "nvme.errorEntries": "Entradas do registro de erros",
+ "nvme.warnTemp": "Tempo acima da temperatura de aviso",
+ "nvme.critTemp": "Tempo acima da temperatura crítica",
+ "attr.a2": "Desempenho de transferência",
+ "attr.a8": "Desempenho de busca",
+ "attr.a11": "Novas tentativas de calibração",
+ "attr.a13": "Taxa de erros leves de leitura",
+ "attr.a22": "Nível de hélio",
+ "attr.a171": "Falhas de programação (escrita)",
+ "attr.a172": "Falhas de apagamento",
+ "attr.a173": "Média de apagamentos",
+ "attr.a174": "Quedas de energia inesperadas",
+ "attr.a179": "Blocos reserva usados",
+ "attr.a180": "Blocos reserva livres",
+ "attr.a181": "Falhas de programação (total)",
+ "attr.a182": "Falhas de apagamento (total)",
+ "attr.a189": "Escritas com a cabeça alta",
+ "attr.a191": "Impactos detectados",
+ "attr.a195": "Erros corrigidos por ECC",
+ "attr.a200": "Taxa de erros de escrita",
+ "attr.a202": "Vida restante",
+ "attr.a220": "Deslocamento do disco",
+ "attr.a222": "Horas com as cabeças carregadas",
+ "attr.a223": "Novas tentativas de carga",
+ "attr.a224": "Atrito de carga",
+ "attr.a226": "Tempo de carga",
+ "attr.a232": "Espaço reserva livre",
+ "attr.a240": "Horas de voo da cabeça",
+ "attr.a254": "Quedas detectadas"
}
diff --git a/assets/locales/pt/errors.json b/assets/locales/pt/errors.json
index 0543704..a42ee7a 100644
--- a/assets/locales/pt/errors.json
+++ b/assets/locales/pt/errors.json
@@ -558,5 +558,8 @@
"proc.denied": "Sem permissão para parar este processo",
"proc.failed": "Não foi possível parar o processo",
"proc.badArgument": "Pedido de processo inválido",
- "proc.notOwn": "Este processo pertence a outro usuário"
+ "proc.notOwn": "Este processo pertence a outro usuário",
+ "disk.noSmartctl": "O smartmontools não está instalado",
+ "disk.smartFailed": "Não foi possível ler a saúde do disco",
+ "disk.smartTestFailed": "O disco não iniciou o autoteste"
}
diff --git a/assets/locales/pt/monitor.json b/assets/locales/pt/monitor.json
index c0a44a7..6121b49 100644
--- a/assets/locales/pt/monitor.json
+++ b/assets/locales/pt/monitor.json
@@ -217,5 +217,45 @@
"proc.cmdline": "Linha de comando",
"proc.noCmdline": "(nenhuma: uma thread do núcleo ou um processo que a apagou)",
"proc.tab.stats": "Estatísticas",
- "proc.tab.files": "Arquivos e portas abertos"
+ "proc.tab.files": "Arquivos e portas abertos",
+ "temp.col": "Temperatura",
+ "temp.noSensor": "Sem sensor",
+ "temp.resting": "Em repouso",
+ "temp.noSensorHint": "Este disco não tem um sensor de temperatura que o sistema possa ler (cartões de memória, discos virtuais e muitos adaptadores USB não têm).",
+ "temp.restingHint": "O disco está em repouso: volta a ser lido assim que for usado, para que possa continuar parado.",
+ "temp.limitOwn": "Limite {max} °C, informado pelo disco",
+ "temp.limitDefault": "Limite {max} °C (o disco não informa o seu)",
+ "temp.title": "Temperatura · {name}",
+ "temp.sensor.nvme": "sensor NVMe",
+ "temp.sensor.drivetemp": "sensor SATA",
+ "health.col": "Saúde",
+ "health.title": "Saúde (SMART)",
+ "health.ok": "OK",
+ "health.warning": "Verificar",
+ "health.failing": "Falhando",
+ "health.unknown": "Sem dados",
+ "health.none": "Sem SMART",
+ "health.noneHint": "Este tipo de disco não informa sua saúde (cartões de memória, discos virtuais).",
+ "health.waiting": "Lendo a saúde do disco…",
+ "health.standby": "O disco está em repouso: sua saúde é lida na próxima vez que for usado.",
+ "health.errorHint": "O disco não respondeu SMART (pode não ter, ou estar atrás de um adaptador USB que o bloqueia).",
+ "health.hint.ok": "O disco não informa problemas.",
+ "health.hint.warning": "Há sinais de desgaste: abra-o em Discos para ver por quê e mantenha um backup.",
+ "health.hint.failing": "O disco diz que vai falhar em breve. Copie seus dados agora.",
+ "health.hint.unknown": "O disco respondeu, mas sem dados suficientes.",
+ "health.openDisks": "Abrir em Discos",
+ "health.hours": "Ligado",
+ "health.hoursUnit": "h",
+ "health.wear": "Desgaste do SSD",
+ "health.basic": "Leitura básica. Instale o smartmontools em Discos para o relatório completo e os autotestes.",
+ "diskAlert.toggle": "Avisar quando um disco esquentar demais ou sua saúde piorar",
+ "diskAlert.hotTitle": "{name} está quente demais",
+ "diskAlert.critTitle": "{name} está a uma temperatura crítica",
+ "diskAlert.hotBody": "{dev} está a {temp} °C (limite {max} °C). Verifique a ventilação ao redor.",
+ "diskAlert.open": "Abrir Monitor",
+ "diskAlert.checkTitle": "{name} precisa de verificação",
+ "diskAlert.checkBody": "{dev} mostra sinais de desgaste. Garanta que você tem um backup.",
+ "diskAlert.failTitle": "{name} está falhando",
+ "diskAlert.failBody": "{dev} informa que vai falhar em breve. Copie seus dados agora.",
+ "health.idle": "Ainda não lido: um disco giratório é lido na próxima vez que for usado, para não acordá-lo em repouso. Com o smartmontools é lido sem acordá-lo."
}
diff --git a/packaging/migrations/003-0.8.2-drivetemp.sh b/packaging/migrations/003-0.8.2-drivetemp.sh
new file mode 100644
index 0000000..b8c2a97
--- /dev/null
+++ b/packaging/migrations/003-0.8.2-drivetemp.sh
@@ -0,0 +1,7 @@
+# 0.8.2: SATA disk temperatures (Monitor → Disks). The package now ships
+# /usr/lib/modules-load.d/lordos-drivetemp.conf, read at boot; on a running system the module is
+# loaded once here so the temperatures show without a restart. Harmless where the kernel has no
+# drivetemp (the Monitor then says "No sensor").
+[ -d /run/systemd/system ] || exit 0
+command -v modprobe >/dev/null 2>&1 || exit 0
+modprobe -q drivetemp 2>/dev/null || true
diff --git a/sdk/diskwatch.js b/sdk/diskwatch.js
new file mode 100644
index 0000000..c563d2a
--- /dev/null
+++ b/sdk/diskwatch.js
@@ -0,0 +1,92 @@
+// diskwatch.js — session notices when a disk gets too hot or its SMART health gets worse
+// (docs/MONITOR.md, "Disk temperature and health"). startShell calls startDiskWatch().
+//
+// Temperatures: lord.monitor.watchDisks(true) lets the Monitor's thread read only the disk sensors
+// every 30 s while the Monitor is closed (a spinning disk only while awake); this polls the result
+// every 30 s. A notice when a disk reaches its limit (diskTempLimit), at most one per disk every 30
+// minutes, and again only after it has cooled 3 °C below the limit.
+// Health: every 6 hours (the first 3 minutes after login) the cached summary of each disk is
+// refreshed (smart.refresh: smart-health, which never wakes a resting disk). A notice only when a
+// disk is worse than the last time it was noticed (settings.monitor.diskHealth, by model and serial).
+// Both are off with settings.monitor.diskAlerts = false (the switch in Monitor → Disks).
+import { settings } from './settings.js';
+import { notify } from './notify.js';
+import { t } from './i18n.js';
+import { wm } from './windows.js';
+import { smart, diskTempLimit, diskAlertPrefs } from './smart.js';
+import { HEALTH_RANK } from './smartparse.js';
+
+const TEMP_EVERY = 30 * 1000, HEALTH_EVERY = 6 * 3600 * 1000, HEALTH_FIRST = 3 * 60 * 1000;
+const RENOTIFY = 30 * 60 * 1000, HYSTERESIS = 3;
+const hot = new Map(); // disk → { at (ms of the last notice), armed }
+let started = false;
+
+const label = (d) => d.model || `/dev/${d.name}`;
+
+let watching = false;
+function checkTemps() {
+ const on = diskAlertPrefs();
+ if (on !== watching) { watching = on; try { lord.monitor.watchDisks(on); } catch (e) { /* older server */ } }
+ if (!on) return;
+ let r = null;
+ try { r = lord.monitor.diskTemps(); } catch (e) { return; }
+ if (!r || !Array.isArray(r.disks)) return;
+ const now = Date.now();
+ for (const d of r.disks) {
+ if (d.temp == null || !d.sensor) continue;
+ const lim = diskTempLimit(d);
+ const st = hot.get(d.name) || { at: 0, armed: true };
+ if (d.temp < lim.max - HYSTERESIS) st.armed = true;
+ if (d.temp >= lim.max && st.armed && now - st.at > RENOTIFY) {
+ st.at = now;
+ st.armed = false;
+ const critical = lim.crit != null && d.temp >= lim.crit;
+ notify({
+ app: 'monitor',
+ title: t(critical ? 'monitor.diskAlert.critTitle' : 'monitor.diskAlert.hotTitle', { name: label(d) }),
+ body: t('monitor.diskAlert.hotBody', { dev: `/dev/${d.name}`, temp: Math.round(d.temp), max: lim.max }),
+ sticky: critical,
+ actions: [{ id: 'open', label: t('monitor.diskAlert.open'), run: () => wm.open('monitor', { args: { tab: 'disks', disk: d.name, nonce: Date.now() } }) }],
+ });
+ }
+ hot.set(d.name, st);
+ }
+}
+
+async function checkHealth() {
+ if (!diskAlertPrefs()) return;
+ let list = [];
+ try { list = lord.disks.list() || []; } catch (e) { return; }
+ let temps = null;
+ try { temps = lord.monitor.diskTemps(); } catch (e) { /* none yet */ }
+ const awake = new Set((temps?.disks || []).filter((d) => d.awake).map((d) => d.name));
+ for (const d of list) {
+ if (!smart.smartable(d.name) || d.transport === 'loop') continue;
+ const s = await smart.refresh(d, { awake: awake.has(d.name) });
+ if (!s || s.standby || s.health === 'unknown') continue;
+ const key = `${d.model || d.name}|${d.serial || d.name}`;
+ const seen = ((settings.get().monitor || {}).diskHealth || {})[key];
+ if (seen === s.health) continue;
+ settings.set((all) => {
+ const mon = all.monitor || {};
+ return { ...all, monitor: { ...mon, diskHealth: { ...(mon.diskHealth || {}), [key]: s.health } } };
+ });
+ // the first time a disk is seen healthy, or when it gets better: nothing to say
+ if (HEALTH_RANK[s.health] <= HEALTH_RANK[seen || 'ok']) continue;
+ notify({
+ app: 'monitor',
+ title: t(s.health === 'failing' ? 'monitor.diskAlert.failTitle' : 'monitor.diskAlert.checkTitle', { name: label(d) }),
+ body: t(s.health === 'failing' ? 'monitor.diskAlert.failBody' : 'monitor.diskAlert.checkBody', { dev: `/dev/${d.name}` }),
+ sticky: s.health === 'failing',
+ actions: [{ id: 'open', label: t('monitor.health.openDisks'), run: () => wm.open('disks', { args: { disk: d.name, nonce: Date.now() } }) }],
+ });
+ }
+}
+
+export function startDiskWatch() {
+ if (started || typeof lord === 'undefined' || !lord.monitor?.watchDisks || !lord.disks || typeof lord.greeter !== 'undefined') return;
+ started = true;
+ checkTemps(); // turns the background reading on (or leaves it off)
+ setInterval(checkTemps, TEMP_EVERY);
+ setTimeout(() => { checkHealth(); setInterval(checkHealth, HEALTH_EVERY); }, HEALTH_FIRST);
+}
diff --git a/sdk/index.js b/sdk/index.js
index 8827657..26cc2e8 100644
--- a/sdk/index.js
+++ b/sdk/index.js
@@ -48,7 +48,7 @@ export {
dockDrag, dockPoof, beginDockDrag, registerDockTarget, dockDragJustEnded,
} from './dock.js';
export { sound, useSound, useSoundPeak, soundState, defaultSink, defaultSource, microphones } from './sound.js';
-export { monitor, useMonitor, monitorSamples, monitorProcesses, monitorConnections, monitorDevices, monitorDetail, MONITOR_HISTORY, firewall, firewallState } from './monitor.js';
+export { monitor, useMonitor, monitorSamples, monitorProcesses, monitorConnections, monitorDevices, monitorDetail, MONITOR_HISTORY, diskTempHistory, DISK_TEMP_HISTORY, firewall, firewallState } from './monitor.js';
export * as fwRule from './fwrule.js'; // checks what the user types for a firewall rule
export { packages, packageList, refreshPackages, packageFile, loadWasm } from './packages.js';
import { refreshPackages } from './packages.js';
@@ -68,6 +68,7 @@ export { clockAlarms, clockTimer, timerStart, timerPause, timerResume, timerRese
export { help } from './help.js';
import { NotificationBanner } from './notify.js';
import { startAlarms } from './alarms.js';
+import { startDiskWatch } from './diskwatch.js';
import { maybeStartTour } from './help.js';
import { getApp as getAppOf, isLiveSystem as isLiveSystemOf, wm as wmOf } from './windows.js';
export const windowIcon = (w) => windowIconOf(w, getAppOf);
@@ -88,6 +89,8 @@ export {
} from './controls.jsx';
export { media, useMedia, usePlayer, nowPlaying, useNowPlaying, NowPlayingTile, mediaFormatTime, thumbFor, useThumb, userDirs } from './media.js';
export { disks, useDisks } from './disks.js';
+export { smart, smartSummaries, useSmartSummaries, diskTempLimit, diskAlertPrefs, setDiskAlerts } from './smart.js';
+export { parseSmartctl, prettyAttrName, ATTR_KEYS, HEALTH_RANK } from './smartparse.js';
export { backup, useBackup, backupStatus } from './backup.js'; // Backups (docs/SYSTEM.md)
export { lordosUpdate, restartNeeded, updatePrefs, setUpdatePrefs, UPDATE_DEFAULTS } from './updates.js'; // updating LordOS in place (docs/UPDATES.md)
export { vaultAvailable, vaultRequest, onVaultEvent, keyring, autofill, autofillReveal, KeyringPrompt, AutofillButton } from './vault.js'; // Passwords and keyring (docs/PASSWORDS.md)
@@ -172,6 +175,7 @@ export function startShell(element) {
startReminders(); // calendar and reminder alarms, with the apps closed
maybeStartTour(); // "Welcome to LordOS", the first time
startHardware(); // Night Light, idle timers, battery in the menu bar (hardware.jsx)
+ startDiskWatch(); // notices when a disk gets too hot or its health gets worse
}
// Changing the language remounts the whole interface (windows, tabs and
diff --git a/sdk/monitor.js b/sdk/monitor.js
index 8e99dea..5b9f761 100644
--- a/sdk/monitor.js
+++ b/sdk/monitor.js
@@ -29,6 +29,29 @@ export const monitorProcesses = createStore(null);
export const monitorConnections = createStore(null);
export const monitorDevices = createStore([]); // phase 2
export const monitorDetail = createStore(null); // Get Info of one process (procctl.c's JSON)
+// Disk temperatures while the Monitor is open: { [disk]: { t: [ms], v: [°C] } }, one point per new
+// reading (every 3 s; a resting spinning disk is not read), the last DISK_TEMP_HISTORY points.
+export const DISK_TEMP_HISTORY = 600; // 30 min at one reading every 3 s
+export const diskTempHistory = createStore({});
+const lastTempT = new Map();
+function noteDiskTemps(s) {
+ const add = [];
+ for (const d of s?.disk?.disks || []) {
+ if (d.temp == null || !d.tempT || lastTempT.get(d.name) === d.tempT) continue;
+ lastTempT.set(d.name, d.tempT);
+ add.push(d);
+ }
+ if (!add.length) return;
+ diskTempHistory.set((h) => {
+ const n = { ...h };
+ for (const d of add) {
+ const o = n[d.name] || { t: [], v: [] };
+ const cut = o.t.length >= DISK_TEMP_HISTORY ? 1 : 0;
+ n[d.name] = { t: [...o.t.slice(cut), d.tempT], v: [...o.v.slice(cut), d.temp] };
+ }
+ return n;
+ });
+}
const available = () => typeof lord.monitor !== 'undefined';
const wants = new Map(); // mounted useMonitor → { procs, conns }
@@ -46,7 +69,10 @@ function poll() {
const key = `${w.procs}|${w.conns}|${w.geo}`;
if (key !== lastWant) { lastWant = key; lord.monitor.want(w.procs, w.conns, w.geo); }
const s = lord.monitor.sample();
- if (s) monitorSamples.set((list) => (list.length >= MONITOR_HISTORY ? [...list.slice(1 - MONITOR_HISTORY), s] : [...list, s]));
+ if (s) {
+ monitorSamples.set((list) => (list.length >= MONITOR_HISTORY ? [...list.slice(1 - MONITOR_HISTORY), s] : [...list, s]));
+ noteDiskTemps(s);
+ }
const lang = locale.get().lang;
if (w.procs) { const p = lord.monitor.processes(lang); if (p) monitorProcesses.set(() => p); }
if (watched && !watched.viaAdmin) { const d = lord.monitor.detailInfo(); if (d) monitorDetail.set(() => d); }
diff --git a/sdk/smart.js b/sdk/smart.js
new file mode 100644
index 0000000..637c04a
--- /dev/null
+++ b/sdk/smart.js
@@ -0,0 +1,101 @@
+// smart.js — disk health through smartmontools (Disks app, Monitor; docs/SYSTEM.md, "SMART with
+// smartmontools", and docs/MONITOR.md, "Disk temperature and health").
+//
+// smart.installed() is /usr/sbin/smartctl there (lord.disks.tools().smartctl)
+// await smart.install(onLog) installs Debian's smartmontools with the package engine
+// (pkg-install, an administrator; as Settings → Sharing does for SSH)
+// await smart.info(disk) the full model (smart-info: smartctl -j -x), sdk/smartparse.js
+// await smart.health(disk) the summary (smart-health: does not wake a resting disk)
+// await smart.test(disk, 'short' | 'long'), await smart.abort(disk)
+// await smart.refresh(disk, { awake, force }) updates smartSummaries[disk.name], at most every 5 min
+// useSmartSummaries() { [disk]: { health, reasons, temp, wear, hours, standby, t } }
+//
+// All of it runs as the root helper's closed smart-* actions: fixed /usr/sbin/smartctl, a validated
+// whole disk, JSON back in LOG lines. Without smartmontools the summary comes from LordOS's own
+// reader (disk-smart), only for disks that will not be woken up by it.
+import { admin } from './admin.js';
+import { createStore, useStore } from './store.js';
+import { settings } from './settings.js';
+import { codeError } from './errors.js';
+import { parseSmartctl, summarize, summaryFromOwn } from './smartparse.js';
+
+export const SMART_PACKAGE = 'smartmontools';
+export const SUMMARY_MS = 5 * 60 * 1000; // the Monitor asks a disk at most every 5 minutes
+export const smartSummaries = createStore({});
+export const useSmartSummaries = () => useStore(smartSummaries);
+
+const hasLord = () => typeof lord !== 'undefined' && !!lord.disks;
+const smartable = (name) => /^(sd[a-z]{1,3}|hd[a-z]{1,3}|nvme\d{1,3}n\d{1,3})$/.test(name || '');
+
+// The helper sends the JSON in pieces; OK says "<lines> <smartctl exit status>".
+function runJson(action, arg) {
+ let text = '';
+ return admin.run(action, arg, (line) => { text += line; }, { quiet: true }).then((ok) => {
+ const rc = Number(String(ok).split(' ')[1]) || 0;
+ let j;
+ try { j = JSON.parse(text); } catch (e) { throw codeError('disk.smartFailed'); }
+ return parseSmartctl(j, rc);
+ });
+}
+
+export const smart = {
+ smartable,
+ installed: () => { try { return hasLord() && !!lord.disks.tools().smartctl; } catch (e) { return false; } },
+ install(onLog) {
+ const go = () => admin.run('pkg-install', SMART_PACKAGE, onLog);
+ return go().catch((e) => {
+ if (e.code !== 'pkg.noIndex') throw e; // no package lists yet (fresh install): fetch them once
+ return admin.run('pkg-update', '', onLog).then(go);
+ });
+ },
+ info: (name) => runJson('smart-info', name),
+ health: (name) => runJson('smart-health', name),
+ test: (name, kind) => runJson('smart-test', `${name}\n${kind === 'long' ? 'long' : 'short'}`).then((m) => {
+ if (m.exit & 6) throw codeError('disk.smartTestFailed'); // device open or a command failed
+ return m;
+ }),
+ abort: (name) => runJson('smart-abort', name),
+ // disk: an entry of lord.disks.list() or of a Monitor sample ({ name, rota|rotational }).
+ // awake: it had I/O lately (a spinning disk that rests is never asked by our own reader).
+ async refresh(disk, { awake = false, force = false } = {}) {
+ const name = disk?.name;
+ if (!smartable(name)) return null;
+ const old = smartSummaries.get()[name];
+ if (!force && old && old.t && Date.now() - old.t < SUMMARY_MS) return old;
+ let s = null;
+ try {
+ if (smart.installed()) {
+ const m = await smart.health(name);
+ s = m.standby && old ? { ...old, standby: true, t: Date.now() } : summarize(m);
+ } else if (!(disk.rota ?? disk.rotational) || awake) {
+ let own = null;
+ await admin.run('disk-smart', name, (line) => {
+ if (line.startsWith('smart ')) { try { own = JSON.parse(line.slice(6)); } catch (e) { /* malformed */ } }
+ }, { quiet: true });
+ s = summaryFromOwn(own);
+ } else {
+ // a spinning disk with no I/O lately, and no smartmontools to ask without waking it:
+ // read it the next time it is in use (t 0: retried at the next refresh)
+ s = old && old.health !== 'unknown' ? old : { health: 'unknown', reasons: [], temp: null, wear: null, hours: null, standby: false, supported: true, idle: true, t: 0 };
+ if (s === old) return old;
+ }
+ } catch (e) {
+ s = { health: 'unknown', reasons: [], temp: null, wear: null, hours: null, standby: false, supported: false, t: Date.now(), error: e.code || 'disk.smartFailed' };
+ }
+ if (s) smartSummaries.set((all) => ({ ...all, [name]: s }));
+ return s;
+ },
+};
+
+// When a disk counts as too hot: its own limit when it reports one, otherwise a conservative
+// default for its kind (spinning disks run cooler than flash). crit: the drive's critical limit.
+export function diskTempLimit(d) {
+ const max = d.tempMax ?? (d.sensor === 'nvme' ? 75 : d.rota ? 55 : 70);
+ return { max, crit: d.tempCrit ?? null, own: d.tempMax != null };
+}
+
+// settings.monitor.diskAlerts (default on): notices when a disk gets too hot or less healthy.
+export const diskAlertPrefs = (s = settings.get()) => (s.monitor || {}).diskAlerts !== false;
+export function setDiskAlerts(on) {
+ settings.set((s) => ({ ...s, monitor: { ...(s.monitor || {}), diskAlerts: !!on } }));
+}
diff --git a/sdk/smartparse.js b/sdk/smartparse.js
new file mode 100644
index 0000000..b3def01
--- /dev/null
+++ b/sdk/smartparse.js
@@ -0,0 +1,317 @@
+// smartparse.js — smartctl's JSON (smartmontools, `smartctl -j`) turned into one model the Disks
+// app and the Monitor can show (see docs/SYSTEM.md, "SMART with smartmontools"). Pure functions,
+// no lord.* and no React: tests/smart_parse_test.mjs runs them under node with real smartctl output.
+//
+// const m = parseSmartctl(json, exitStatus)
+// m.health 'ok' | 'warning' | 'failing' | 'unknown' (the UI says OK / Check / Failing)
+// m.reasons why it is not 'ok': ['reallocated', 'pending', 'smartFailed', 'nvmeSpare', …]
+// m.attrs ATA attributes [{ id, name, key, value, worst, thresh, raw, prefail, failed }]
+// m.nvme NVMe health log fields (or null)
+// m.selfTest { supported, running, remaining, polling: { short, long } } (minutes)
+// m.selfTests past results [{ type, result, passed, hours }]
+// m.errors { count, list: [{ n, hours, text }] }
+// m.tempHistory { interval (minutes), values: [°C | null] } (ATA SCT; null if none)
+//
+// Everything a drive sends is outside data: numbers are checked, strings are only shown as text.
+
+const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
+const obj = (v) => (v && typeof v === 'object' && !Array.isArray(v) ? v : null);
+const arr = (v) => (Array.isArray(v) ? v : []);
+const str = (v, max = 200) => (typeof v === 'string' ? v.slice(0, max) : '');
+
+// smartctl's attribute names → our plain-language strings (disks.attr.<key>). By name, not by id:
+// vendors reuse ids, and smartctl's drive database already gives each one its real meaning.
+const NAME_KEYS = {
+ Raw_Read_Error_Rate: 'a1', Throughput_Performance: 'a2', Spin_Up_Time: 'a3', Start_Stop_Count: 'a4',
+ Reallocated_Sector_Ct: 'a5', Reallocate_NAND_Blk_Cnt: 'a5', Seek_Error_Rate: 'a7', Seek_Time_Performance: 'a8',
+ Power_On_Hours: 'a9', Power_On_Hours_and_Msec: 'a9', Spin_Retry_Count: 'a10', Calibration_Retry_Count: 'a11',
+ Power_Cycle_Count: 'a12', Read_Soft_Error_Rate: 'a13', Helium_Level: 'a22', Program_Fail_Count: 'a171',
+ Program_Fail_Cnt: 'a171', Erase_Fail_Count: 'a172', Ave_Block_Erase_Count: 'a173', Unexpect_Power_Loss_Ct: 'a174',
+ Unsafe_Shutdown_Count: 'a174', Wear_Leveling_Count: 'a177', Used_Rsvd_Blk_Cnt_Tot: 'a179', Unused_Rsvd_Blk_Cnt_Tot: 'a180',
+ Program_Fail_Cnt_Total: 'a181', Erase_Fail_Count_Total: 'a182', Runtime_Bad_Block: 'a183', SATA_Downshift_Count: 'a183',
+ 'End-to-End_Error': 'a184', Reported_Uncorrect: 'a187', Command_Timeout: 'a188', High_Fly_Writes: 'a189',
+ Airflow_Temperature_Cel: 'a190', Temperature_Case: 'a190', 'G-Sense_Error_Rate': 'a191', 'Power-Off_Retract_Count': 'a192',
+ Load_Cycle_Count: 'a193', Temperature_Celsius: 'a194', Temperature_Internal: 'a194', Hardware_ECC_Recovered: 'a195',
+ Reallocated_Event_Count: 'a196', Current_Pending_Sector: 'a197', Offline_Uncorrectable: 'a198', UDMA_CRC_Error_Count: 'a199',
+ CRC_Error_Count: 'a199', Multi_Zone_Error_Rate: 'a200', Percent_Lifetime_Remain: 'a202', Disk_Shift: 'a220',
+ Loaded_Hours: 'a222', Load_Retry_Count: 'a223', Load_Friction: 'a224', Load_In_Time: 'a226', SSD_Life_Left: 'a231',
+ Available_Reservd_Space: 'a232', Media_Wearout_Indicator: 'a233', Total_LBAs_Written: 'a241', Total_LBAs_Read: 'a242',
+ Head_Flying_Hours: 'a240', Free_Fall_Sensor: 'a254',
+};
+export const ATTR_KEYS = [...new Set(Object.values(NAME_KEYS))];
+
+// "Unknown_SSD_Attribute" → "Unknown SSD Attribute"
+export const prettyAttrName = (n) => str(n, 64).replace(/_/g, ' ').trim();
+
+// A count attribute's raw number: smartctl's raw string starts with it ("12 (Min/Max 0/40)").
+function rawCount(a) {
+ const s = str(a?.raw?.string, 64).trim();
+ const m = /^(\d{1,15})\b/.exec(s);
+ if (m) return Number(m[1]);
+ const v = num(a?.raw?.value);
+ return v != null && v >= 0 ? v : null;
+}
+
+function parseAttrs(j) {
+ return arr(obj(j.ata_smart_attributes)?.table).filter((a) => obj(a) && num(a.id) != null && a.id > 0 && a.id < 256).slice(0, 64).map((a) => {
+ const name = str(a.name, 64);
+ return {
+ id: a.id,
+ name,
+ key: NAME_KEYS[name] || null,
+ value: num(a.value), worst: num(a.worst), thresh: num(a.thresh),
+ raw: str(a?.raw?.string, 64) || (num(a?.raw?.value) != null ? String(a.raw.value) : ''),
+ count: rawCount(a),
+ prefail: !!a?.flags?.prefailure,
+ failed: a.when_failed === 'now' ? 'now' : a.when_failed === 'past' ? 'past' : '',
+ };
+ });
+}
+
+const byKey = (attrs, ...keys) => attrs.find((a) => keys.includes(a.key)) || null;
+
+// Percentage of the rated life already used (SSD wear), from the most reliable source available.
+function wearOf(j, attrs, nvme) {
+ if (nvme && nvme.used != null) return { used: nvme.used, source: 'nvme' };
+ for (const p of arr(obj(j.ata_device_statistics)?.pages)) {
+ for (const e of arr(p?.table)) {
+ if (/Percentage Used Endurance Indicator/i.test(str(e?.name)) && num(e?.value) != null && e.value >= 0 && e.value <= 255) return { used: e.value, source: 'devstat' };
+ }
+ }
+ const scsi = num(j.scsi_percentage_used_endurance_indicator);
+ if (scsi != null) return { used: scsi, source: 'scsi' };
+ // normalized values that count down from 100 as the flash wears out
+ const a = byKey(attrs, 'a231', 'a233', 'a202', 'a177');
+ if (a && a.value != null && a.value <= 100 && a.value >= 0) return { used: 100 - a.value, source: `attr${a.id}` };
+ return null;
+}
+
+function parseNvme(j) {
+ const h = obj(j.nvme_smart_health_information_log);
+ if (!h) return null;
+ const units = (v) => (num(v) != null ? v * 512000 : null); // data units are 1000 × 512 bytes
+ return {
+ criticalWarning: num(h.critical_warning) ?? 0,
+ temp: num(h.temperature),
+ spare: num(h.available_spare), spareThreshold: num(h.available_spare_threshold),
+ used: num(h.percentage_used),
+ read: units(h.data_units_read), written: units(h.data_units_written),
+ hostReads: num(h.host_reads), hostWrites: num(h.host_writes),
+ busyMinutes: num(h.controller_busy_time),
+ cycles: num(h.power_cycles), hours: num(h.power_on_hours),
+ unsafeShutdowns: num(h.unsafe_shutdowns), mediaErrors: num(h.media_errors),
+ errorLogEntries: num(h.num_err_log_entries),
+ warningTempMinutes: num(h.warning_temp_time), criticalTempMinutes: num(h.critical_comp_time),
+ sensors: arr(h.temperature_sensors).map(num).filter((v) => v != null).slice(0, 8),
+ };
+}
+
+const ATA_TEST_RUNNING = (v) => v != null && v >> 4 === 15; // status 0xF?: in progress
+
+function parseSelfTest(j, nvme) {
+ const polling = obj(obj(obj(j.ata_smart_data)?.self_test)?.polling_minutes);
+ const st = obj(obj(obj(j.ata_smart_data)?.self_test)?.status);
+ const caps = obj(obj(j.ata_smart_data)?.capabilities);
+ const res = {
+ supported: false, running: false, remaining: null,
+ polling: { short: num(polling?.short), long: num(polling?.extended) },
+ };
+ if (caps) res.supported = !!caps.self_tests_supported;
+ if (st) {
+ res.running = ATA_TEST_RUNNING(num(st.value));
+ if (res.running) res.remaining = num(st.remaining_percent) ?? (num(st.value) & 15) * 10;
+ res.last = { result: str(st.string, 120), passed: st.passed !== false };
+ }
+ const nl = obj(j.nvme_self_test_log);
+ if (nvme || nl) {
+ const opt = obj(j.nvme_optional_admin_commands);
+ res.supported = !!nl || (opt ? !!opt.self_test : false);
+ const op = num(obj(nl?.current_self_test_operation)?.value);
+ if (op) {
+ res.running = true;
+ const done = num(nl.current_self_test_completion_percent);
+ res.remaining = done != null ? Math.max(0, 100 - done) : null;
+ }
+ const ext = num(j.nvme_extended_self_test_time ?? obj(j.nvme_self_test_time)?.extended);
+ if (ext != null) res.polling.long = ext;
+ }
+ return res;
+}
+
+const NVME_RESULT = { 0: 'completed', 1: 'abortedCommand', 2: 'abortedReset', 3: 'abortedRemoved', 4: 'abortedFormat',
+ 5: 'fatal', 6: 'failedUnknownSegment', 7: 'failedSegments', 8: 'abortedUnknown', 9: 'abortedSanitize' };
+
+function parseSelfTests(j) {
+ const out = [];
+ const log = obj(j.ata_smart_self_test_log);
+ const tab = arr(obj(log?.extended)?.table).length ? obj(log.extended).table : arr(obj(log?.standard)?.table);
+ for (const e of tab.slice(0, 32)) {
+ if (!obj(e)) continue;
+ out.push({
+ type: /extended|long/i.test(str(e.type?.string)) ? 'long' : /short/i.test(str(e.type?.string)) ? 'short' : 'other',
+ typeText: str(e.type?.string, 60),
+ result: str(e.status?.string, 120),
+ passed: e.status?.passed !== false,
+ hours: num(e.lifetime_hours),
+ });
+ }
+ for (const e of arr(obj(j.nvme_self_test_log)?.table).slice(0, 32)) {
+ if (!obj(e)) continue;
+ const code = num(e.self_test_code?.value), r = num(e.self_test_result?.value);
+ out.push({
+ type: code === 1 ? 'short' : code === 2 ? 'long' : 'other',
+ typeText: str(e.self_test_code?.string, 60),
+ result: str(e.self_test_result?.string, 120),
+ resultKey: r != null ? NVME_RESULT[r] || null : null,
+ passed: r === 0,
+ hours: num(e.power_on_hours),
+ });
+ }
+ return out;
+}
+
+function parseErrors(j, nvme) {
+ const log = obj(j.ata_smart_error_log);
+ const part = obj(log?.extended) || obj(log?.summary);
+ if (part) {
+ return {
+ count: num(part.count) ?? 0,
+ list: arr(part.table).slice(0, 16).filter(obj).map((e) => ({
+ n: num(e.error_number), hours: num(e.lifetime_hours), text: str(e.error_description, 160),
+ })),
+ };
+ }
+ const ne = obj(j.nvme_error_information_log);
+ if (ne || nvme) {
+ return {
+ count: nvme?.errorLogEntries ?? num(ne?.unread) ?? 0,
+ list: arr(ne?.table).slice(0, 16).filter(obj).map((e) => ({
+ n: num(e.error_count), hours: null, text: str(e.status_field?.string, 160),
+ })),
+ };
+ }
+ return { count: 0, list: [] };
+}
+
+function parseTempHistory(j) {
+ const h = obj(j.ata_sct_temperature_history);
+ if (!h) return null;
+ const values = arr(h.table).slice(0, 1024).map((v) => (num(v) != null && v > -40 && v < 150 ? v : null));
+ if (!values.some((v) => v != null)) return null;
+ return { interval: num(h.logging_interval_minutes) ?? num(h.sampling_period_minutes) ?? 1, values };
+}
+
+function tempLimits(j) {
+ const t = obj(j.temperature) || {};
+ const sct = obj(obj(j.ata_sct_temperature_history)?.temperature) || {};
+ const max = num(t.op_limit_max) ?? num(sct.op_limit_max) ?? num(j.nvme_warning_composite_temperature_threshold) ?? null;
+ const crit = num(t.critical_limit_max) ?? num(sct.limit_max) ?? num(j.nvme_critical_composite_temperature_threshold) ?? null;
+ const ok = (v) => (v != null && v >= 30 && v <= 150 ? v : null);
+ return { max: ok(max), crit: ok(crit) };
+}
+
+const STANDBY = /\b(STANDBY|SLEEP|IDLE(_[A-Z])?) mode\b/;
+
+export function parseSmartctl(j, exit = 0) {
+ j = obj(j) || {};
+ const sc = obj(j.smartctl) || {};
+ const messages = arr(sc.messages).filter(obj).map((m) => ({ text: str(m.string, 200), severity: str(m.severity, 16) })).slice(0, 8);
+ const status = num(sc.exit_status) ?? num(exit) ?? 0;
+ const dev = obj(j.device);
+ const protocol = str(dev?.protocol, 16);
+ const kind = protocol === 'NVMe' ? 'nvme' : protocol === 'ATA' ? 'ata' : protocol === 'SCSI' ? 'scsi' : null;
+ const nvme = parseNvme(j);
+ const attrs = parseAttrs(j);
+ const smartAvail = obj(j.smart_support) ? j.smart_support.available !== false : !!nvme || attrs.length > 0;
+ const standby = !obj(j.smart_status) && messages.some((m) => STANDBY.test(m.text));
+ const temp = num(obj(j.temperature)?.current) ?? nvme?.temp ?? null;
+ const lim = tempLimits(j);
+ const a5 = byKey(attrs, 'a5'), a197 = byKey(attrs, 'a197'), a198 = byKey(attrs, 'a198');
+ const m = {
+ kind,
+ model: str(j.model_name, 80) || str(j.scsi_model_name, 80) || [str(j.scsi_vendor, 40), str(j.scsi_product, 40)].filter(Boolean).join(' '),
+ serial: str(j.serial_number, 64),
+ firmware: str(j.firmware_version, 40) || str(j.scsi_revision, 40),
+ capacity: num(obj(j.user_capacity)?.bytes) ?? num(j.nvme_total_capacity),
+ rotation: num(j.rotation_rate),
+ supported: !!kind && smartAvail,
+ enabled: obj(j.smart_support) ? j.smart_support.enabled !== false : true,
+ standby,
+ passed: obj(j.smart_status) ? j.smart_status.passed !== false : null,
+ temp: temp != null && temp > -40 && temp < 150 && !(kind === 'scsi' && temp === 0) ? temp : null,
+ tempMax: lim.max, tempCrit: lim.crit,
+ hours: num(obj(j.power_on_time)?.hours) ?? nvme?.hours ?? null,
+ cycles: num(j.power_cycle_count) ?? nvme?.cycles ?? null,
+ reallocated: a5 ? a5.count : null,
+ pending: a197 ? a197.count : null,
+ uncorrectable: a198 ? a198.count : null,
+ grownDefects: num(j.scsi_grown_defect_list),
+ attrs,
+ nvme,
+ wear: null,
+ read: nvme?.read ?? null,
+ written: nvme?.written ?? null,
+ selfTest: parseSelfTest(j, nvme),
+ selfTests: parseSelfTests(j),
+ errors: parseErrors(j, nvme),
+ tempHistory: parseTempHistory(j),
+ messages,
+ exit: status,
+ health: 'unknown',
+ reasons: [],
+ };
+ if (!nvme) {
+ const lbaW = byKey(attrs, 'a241'), lbaR = byKey(attrs, 'a242');
+ if (lbaW && lbaW.count != null) m.written = lbaW.count * 512;
+ if (lbaR && lbaR.count != null) m.read = lbaR.count * 512;
+ }
+ m.wear = wearOf(j, attrs, nvme);
+ Object.assign(m, judge(m));
+ return m;
+}
+
+// health from what the drive says about itself; never guessed when there is no data
+export function judge(m) {
+ const fail = [], warn = [];
+ if (m.passed === false) fail.push('smartFailed');
+ for (const a of m.attrs) {
+ if (a.failed === 'now' && a.prefail) fail.push('prefailNow');
+ else if (a.failed === 'now') warn.push('oldAgeNow');
+ else if (a.failed === 'past' && a.prefail) warn.push('prefailPast');
+ }
+ if (m.reallocated > 0) warn.push('reallocated');
+ if (m.pending > 0) warn.push('pending');
+ if (m.uncorrectable > 0) warn.push('uncorrectable');
+ if (m.grownDefects > 0) warn.push('grownDefects');
+ const n = m.nvme;
+ if (n) {
+ const w = n.criticalWarning;
+ if (w & 0x04) fail.push('nvmeReliability');
+ if (w & 0x08) fail.push('nvmeReadOnly');
+ if (w & 0x01 || (n.spare != null && n.spareThreshold != null && n.spare < n.spareThreshold)) warn.push('nvmeSpare');
+ if (w & 0x02) warn.push('nvmeTemp');
+ if (w & 0x10) warn.push('nvmeBackup');
+ if (n.mediaErrors > 0) warn.push('mediaErrors');
+ }
+ if (m.wear && m.wear.used >= 90) warn.push('worn');
+ if (m.passed == null && m.exit & 8) fail.push('smartFailed'); // smartctl: "DISK FAILING"
+ const reasons = [...new Set([...fail, ...warn])];
+ const known = m.passed != null || !!n || m.attrs.length > 0;
+ return { health: fail.length ? 'failing' : warn.length ? 'warning' : known ? 'ok' : 'unknown', reasons };
+}
+
+// The little summary the Monitor keeps: { health, reasons, temp, wear, hours, t }
+export function summarize(m, t = Date.now()) {
+ return { health: m.health, reasons: m.reasons, temp: m.temp, wear: m.wear ? m.wear.used : null, hours: m.hours, standby: m.standby, supported: m.supported, t };
+}
+
+// Summary from LordOS's own SMART reader (disk-smart: smart.c), used when smartmontools is missing.
+export function summaryFromOwn(s, t = Date.now()) {
+ if (!obj(s)) return null;
+ const map = { ok: 'ok', warning: 'warning', failing: 'failing' };
+ return { health: map[s.health] || 'unknown', reasons: [], temp: num(s.temp) != null && s.temp >= 0 ? s.temp : null,
+ wear: num(s.used) != null && s.kind === 'nvme' ? s.used : null, hours: num(s.hours) != null && s.hours >= 0 ? s.hours : null, standby: false, supported: true, t };
+}
+
+// health order, to notice when a disk gets worse
+export const HEALTH_RANK = { unknown: 0, ok: 1, warning: 2, failing: 3 };
diff --git a/server/Makefile b/server/Makefile
index 832ff4f..1c810cc 100644
--- a/server/Makefile
+++ b/server/Makefile
@@ -48,7 +48,7 @@ QJS_OBJ := $(patsubst %,build/qjs/%.o,quickjs libregexp libunicode cutils dtoa)
# .lpk app isolation, permissions and signing (src/sec, see docs/PRIVACY.md and docs/SIGNING.md)
# Monitor: metrics, connections and the country of an IP (src/monitor, see docs/MONITOR.md)
-MON_SRC := src/monitor/mon.c src/monitor/conn.c src/monitor/procctl.c src/monitor/proc_admin.c src/monitor/mmdb.c src/monitor/map.c src/ui/js_monitor.c
+MON_SRC := src/monitor/mon.c src/monitor/disktemp.c src/monitor/conn.c src/monitor/procctl.c src/monitor/proc_admin.c src/monitor/mmdb.c src/monitor/map.c src/ui/js_monitor.c
# Media (src/media, docs/MEDIA.md): only the lord-server side. Only lord-media links FFmpeg.
MEDIA_SRC := src/media/media.c src/media/mview.c src/media/capture.c src/media/annot.c src/media/maudio.c src/media/mpulse.c src/media/proto.c src/ui/js_media.c
SEC_SRC := src/sec/json.c src/sec/sign.c src/sec/pkgstate.c src/sec/perms.c src/sec/cgroup.c src/sec/sandbox.c src/sec/brokersrv.c src/sec/brokercam.c src/sec/brokerkr.c src/sec/restrict.c src/sec/appid.c src/sec/pwguard.c
@@ -97,7 +97,7 @@ HDR += $(wildcard src/backup/*.h)
# optional encryption uses Monocypher (vendored in third_party/monocypher; the object comes from mk/vault.mk)
build/obj/backup/%.o: CPPFLAGS += -isystem ../third_party/monocypher
# Disks (docs/SYSTEM.md): disks, partitions and mounts without root, our own SMART and the disk-* actions
-DISK_SRC := src/disk/disk.c src/disk/smart.c src/disk/disk_admin.c src/ui/js_disk.c
+DISK_SRC := src/disk/disk.c src/disk/smart.c src/disk/smartctl.c src/disk/disk_admin.c src/disk/smartctl_admin.c src/ui/js_disk.c
SRC += $(DISK_SRC)
HDR += $(wildcard src/disk/*.h)
OBJ := $(SRC:src/%.c=build/obj/%.o)
@@ -302,13 +302,13 @@ build/backup-test: tests/backup_test.c src/backup/engine.c src/backup/crypt.c sr
build/mmdb-test: tests/mmdb_test.c src/monitor/mmdb.c src/monitor/mmdb.h src/pkg/xz.c build/obj/ui/stb.o
$(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/mmdb_test.c src/monitor/mmdb.c src/pkg/xz.c build/obj/ui/stb.o -lm
# drawing time of the Monitor's vector map (not a test: it measures; see docs/MONITOR.md)
-build/map-bench: tests/map_bench.c src/monitor/map.c src/monitor/map.h src/monitor/mon.c src/monitor/conn.c src/monitor/procctl.c src/monitor/mmdb.c src/pkg/xz.c build/obj/ui/stb.o
- $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/map_bench.c src/monitor/map.c src/monitor/mon.c src/monitor/conn.c src/monitor/procctl.c src/monitor/mmdb.c src/pkg/xz.c build/obj/ui/stb.o -lm -lpthread
+build/map-bench: tests/map_bench.c src/monitor/map.c src/monitor/map.h src/monitor/mon.c src/monitor/disktemp.c src/monitor/conn.c src/monitor/procctl.c src/monitor/mmdb.c src/pkg/xz.c build/obj/ui/stb.o
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/map_bench.c src/monitor/map.c src/monitor/mon.c src/monitor/disktemp.c src/monitor/conn.c src/monitor/procctl.c src/monitor/mmdb.c src/pkg/xz.c build/obj/ui/stb.o -lm -lpthread
# Monitor process actions (src/monitor/procctl.c): the protected list, stat parsing, a signal that
# refuses a stale start time (PID reuse), TERM/KILL on a child, and the Get Info JSON
test: build/procctl-test
-build/procctl-test: tests/procctl_test.c src/monitor/procctl.c src/monitor/procctl.h src/monitor/mon.c src/monitor/conn.c src/monitor/mmdb.c src/pkg/xz.c build/obj/ui/stb.o
- $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/procctl_test.c src/monitor/procctl.c src/monitor/mon.c src/monitor/conn.c src/monitor/mmdb.c src/pkg/xz.c build/obj/ui/stb.o -lm -lpthread
+build/procctl-test: tests/procctl_test.c src/monitor/procctl.c src/monitor/procctl.h src/monitor/mon.c src/monitor/disktemp.c src/monitor/conn.c src/monitor/mmdb.c src/pkg/xz.c build/obj/ui/stb.o
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/procctl_test.c src/monitor/procctl.c src/monitor/mon.c src/monitor/disktemp.c src/monitor/conn.c src/monitor/mmdb.c src/pkg/xz.c build/obj/ui/stb.o -lm -lpthread
./$@ || { rm -f $@; exit 1; }
# canvas.c rows: SIMD (NEON on aarch64) against C, bit for bit, and how long each one takes
# UI engine (docs/DESIGN.md "Engine notes"): ellipsis in LTR/RTL/Arabic/Thai/emoji, per-side borders,
@@ -494,10 +494,22 @@ build/smart-test: tests/smart_test.c src/disk/smart.c src/disk/disk.h src/admin.
@mkdir -p build
$(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/smart_test.c src/disk/smart.c
./$@ || { rm -f $@; exit 1; }
+# smart-* actions (smartmontools): which device names are accepted, JSON compaction and LOG pieces;
+# disk temperatures (src/monitor/disktemp.c) on fake sysfs trees: NVMe, multipath NVMe, drivetemp,
+# a card and a virtual disk without a sensor, and chips that must be ignored
+test: build/smartctl-test build/disktemp-test
+build/smartctl-test: tests/smartctl_test.c src/disk/smartctl.c src/disk/disk.h src/admin.h
+ @mkdir -p build
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/smartctl_test.c src/disk/smartctl.c
+ ./$@ || { rm -f $@; exit 1; }
+build/disktemp-test: tests/disktemp_test.c src/monitor/disktemp.c src/monitor/disktemp.h
+ @mkdir -p build
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -D_GNU_SOURCE -o $@ tests/disktemp_test.c src/monitor/disktemp.c
+ ./$@ || { rm -f $@; exit 1; }
# manual test of the disk-* actions (root and real devices; not part of `test`)
-build/disk-cli: tests/disk_cli.c src/disk/disk.c src/disk/smart.c src/disk/disk_admin.c src/pkg/crypto.c src/disk/disk.h
+build/disk-cli: tests/disk_cli.c src/disk/disk.c src/disk/smart.c src/disk/smartctl.c src/disk/disk_admin.c src/disk/smartctl_admin.c src/pkg/crypto.c src/disk/disk.h
@mkdir -p build
- $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/disk_cli.c src/disk/disk.c src/disk/smart.c src/disk/disk_admin.c src/pkg/crypto.c
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/disk_cli.c src/disk/disk.c src/disk/smart.c src/disk/smartctl.c src/disk/disk_admin.c src/disk/smartctl_admin.c src/pkg/crypto.c
# user folders (src/users/homedirs.c): languages, user-dirs.dirs, no overwriting, no symlinks
test: build/homedirs-test
build/homedirs-test: tests/homedirs_test.c src/users/homedirs.c src/users/homedirs.h
diff --git a/server/src/disk/disk.c b/server/src/disk/disk.c
index 94af91f..47faa58 100644
--- a/server/src/disk/disk.c
+++ b/server/src/disk/disk.c
@@ -461,9 +461,10 @@ char *disk_list_json(void) {
char *disk_tools_json(void) {
char *out = malloc(160);
if (!out) return NULL;
- snprintf(out, 160, "{\"fat32\":%d,\"exfat\":%d,\"ext4\":%d,\"ntfs\":%d}",
+ snprintf(out, 160, "{\"fat32\":%d,\"exfat\":%d,\"ext4\":%d,\"ntfs\":%d,\"smartctl\":%d}",
!access("/usr/sbin/mkfs.fat", X_OK), !access("/usr/sbin/mkfs.exfat", X_OK),
- !access("/usr/sbin/mkfs.ext4", X_OK), !access("/usr/sbin/mkfs.ntfs", X_OK));
+ !access("/usr/sbin/mkfs.ext4", X_OK), !access("/usr/sbin/mkfs.ntfs", X_OK),
+ !access("/usr/sbin/smartctl", X_OK));
return out;
}
diff --git a/server/src/disk/disk.h b/server/src/disk/disk.h
index 5bcef8a..d7c8290 100644
--- a/server/src/disk/disk.h
+++ b/server/src/disk/disk.h
@@ -83,7 +83,24 @@ int smart_summary_json(const SmartReport *r, char *out, size_t n);
/* One ATA attribute as JSON: {id, value, worst, thresh, raw, prefail, failing}. */
int smart_attr_json(const SmartAttr *a, char *out, size_t n);
-/* ---- helper actions (disk_admin.c) ---- */
+/* ---- smartctl (smartctl.c, pure: tests/smartctl_test.c) ---- */
+
+/* sd<letters>, hd<letters> or nvme<N>n<M>: the whole disks the smart-* actions accept. */
+int smartctl_valid_disk(const char *name);
+/* Drops the whitespace outside JSON strings, in place; returns the new length. */
+size_t smartctl_compact(char *s, size_t n);
+/* Length of the next LOG piece (at most max bytes, never inside a UTF-8 sequence). */
+size_t smartctl_chunk(const char *s, size_t n, size_t max);
+
+/* ---- helper actions (disk_admin.c, smartctl_admin.c) ---- */
+
+/* The disk-* target() check for a whole disk (the system disk allowed): /dev path into dev, and
+ * whether it is on USB. need_admin: an internal disk needs an administrator. -1 after admin_err. */
+int disk_admin_target(const AdminReq *r, const char *name, int need_admin, char *dev, size_t n, int *usb);
+void smart_act_info(const AdminReq *r, const char *arg, size_t len);
+void smart_act_health(const AdminReq *r, const char *arg, size_t len);
+void smart_act_test(const AdminReq *r, const char *arg, size_t len);
+void smart_act_abort(const AdminReq *r, const char *arg, size_t len);
void disk_act_smart(const AdminReq *r, const char *arg, size_t len);
void disk_act_mount(const AdminReq *r, const char *arg, size_t len);
@@ -96,7 +113,9 @@ void disk_act_write_image(const AdminReq *r, const char *arg, size_t len);
void disk_act_cancel(const AdminReq *r, const char *arg, size_t len);
/* All are A_ANYONE: each one requires an administrator for internal disks (removable ones are
- * open to any session user, like udisks) and refuses the system disk. */
+ * open to any session user, like udisks) and refuses the system disk. The smart-* ones
+ * (smartmontools) accept the system disk: reading is open to anyone, a self-test on an internal disk
+ * needs an administrator. */
#define DISK_ADMIN_ACTIONS \
{ "disk-smart", disk_act_smart, A_FORK | A_ANYONE }, \
{ "disk-mount", disk_act_mount, A_ANYONE }, \
@@ -106,6 +125,10 @@ void disk_act_cancel(const AdminReq *r, const char *arg, size_t len);
{ "disk-label", disk_act_label, A_FORK | A_ANYONE }, \
{ "disk-erase", disk_act_erase, A_FORK | A_ANYONE }, \
{ "disk-write-image", disk_act_write_image, A_FORK | A_ANYONE }, \
- { "disk-cancel", disk_act_cancel, A_ANYONE },
+ { "disk-cancel", disk_act_cancel, A_ANYONE }, \
+ { "smart-info", smart_act_info, A_FORK | A_ANYONE }, \
+ { "smart-health", smart_act_health, A_FORK | A_ANYONE }, \
+ { "smart-test", smart_act_test, A_FORK | A_ANYONE }, \
+ { "smart-abort", smart_act_abort, A_FORK | A_ANYONE },
#endif
diff --git a/server/src/disk/disk_admin.c b/server/src/disk/disk_admin.c
index 4c042a7..28b2a8e 100644
--- a/server/src/disk/disk_admin.c
+++ b/server/src/disk/disk_admin.c
@@ -115,6 +115,18 @@ static int target(const AdminReq *r, const char *name, int want, int allow_syste
return 0;
}
+/* For the smart-* actions (smartctl_admin.c): a whole disk, the system disk allowed. need_admin:
+ * an internal disk also needs an administrator (starting or stopping a self-test). */
+int disk_admin_target(const AdminReq *r, const char *name, int need_admin, char *dev, size_t n, int *usb) {
+ Target t;
+ if (target(r, name, 1, 1, &t)) return -1;
+ if (need_admin && !t.removable && !r->admin) { admin_err("disk.internalNeedsAdmin", NULL); return -1; }
+ char bus[16];
+ *usb = disk_udev_prop(t.disk, "ID_BUS", bus, sizeof bus) == 0 && !strcmp(bus, "usb");
+ snprintf(dev, n, "%s", t.dev);
+ return 0;
+}
+
/* ---- long jobs that can be cancelled (disk-cancel) ---- */
static volatile sig_atomic_t cancelled;
diff --git a/server/src/disk/smartctl.c b/server/src/disk/smartctl.c
new file mode 100644
index 0000000..c9842fb
--- /dev/null
+++ b/server/src/disk/smartctl.c
@@ -0,0 +1,67 @@
+/* smartctl.c — pure helpers for the smart-* actions (smartctl_admin.c), tested in
+ * tests/smartctl_test.c: which device names smartctl may be pointed at, and the compaction of its
+ * JSON so it travels in few LOG lines. No I/O here. */
+#include "disk.h"
+
+#include <ctype.h>
+#include <string.h>
+
+/* sd<letters> / hd<letters> (SATA, SAS, USB disks behind a bridge) and nvme<N>n<M> (an NVMe
+ * namespace). Nothing else: no partitions (sda1, nvme0n1p1), loop, dm, md, zram, mmcblk (cards
+ * have no SMART), sr (optical), and no path characters at all. */
+int smartctl_valid_disk(const char *n) {
+ if (!n) return 0;
+ size_t l = strlen(n);
+ if (l < 3 || l > 15) return 0;
+ if ((n[0] == 's' || n[0] == 'h') && n[1] == 'd') {
+ if (l > 5) return 0; /* sda … sdzzz */
+ for (size_t i = 2; i < l; i++) if (n[i] < 'a' || n[i] > 'z') return 0;
+ return 1;
+ }
+ if (strncmp(n, "nvme", 4)) return 0;
+ size_t i = 4, d = 0;
+ while (i < l && isdigit((unsigned char)n[i])) { i++; d++; }
+ if (!d || d > 3 || i >= l || n[i] != 'n') return 0;
+ if (d > 1 && n[4] == '0') return 0; /* no leading zeros */
+ i++;
+ size_t start = i;
+ d = 0;
+ while (i < l && isdigit((unsigned char)n[i])) { i++; d++; }
+ if (!d || d > 3 || i != l) return 0;
+ if (d > 1 && n[start] == '0') return 0;
+ if (n[start] == '0') return 0; /* namespaces start at 1 */
+ return 1;
+}
+
+/* Removes the whitespace outside JSON strings, in place. Returns the new length. Raw control
+ * characters (which valid JSON never has outside strings, and smartctl escapes inside them)
+ * become spaces inside strings and are dropped outside. */
+size_t smartctl_compact(char *s, size_t n) {
+ size_t o = 0;
+ int in = 0, esc = 0;
+ for (size_t i = 0; i < n; i++) {
+ unsigned char c = (unsigned char)s[i];
+ if (!c) break;
+ if (in) {
+ if (c < 0x20) c = ' ';
+ s[o++] = (char)c;
+ if (esc) esc = 0;
+ else if (c == '\\') esc = 1;
+ else if (c == '"') in = 0;
+ continue;
+ }
+ if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c < 0x20) continue;
+ if (c == '"') in = 1;
+ s[o++] = (char)c;
+ }
+ if (o < n) s[o] = 0;
+ return o;
+}
+
+/* Cut point for a LOG line of at most max bytes from s[0..n): never inside a UTF-8 sequence. */
+size_t smartctl_chunk(const char *s, size_t n, size_t max) {
+ if (n <= max) return n;
+ size_t k = max;
+ while (k > 1 && ((unsigned char)s[k] & 0xc0) == 0x80) k--;
+ return k;
+}
diff --git a/server/src/disk/smartctl_admin.c b/server/src/disk/smartctl_admin.c
new file mode 100644
index 0000000..cf14b39
--- /dev/null
+++ b/server/src/disk/smartctl_admin.c
@@ -0,0 +1,104 @@
+/* smartctl_admin.c — the "smart-*" actions of the privileged helper: the Disks app's advanced
+ * SMART section and the Monitor's health summary, through Debian's smartmontools.
+ *
+ * smart-info <disk> smartctl -j -x (everything: attributes, logs, tests)
+ * smart-health <disk> smartctl -j -n standby -H -A -c -l selftest
+ * (the summary; a resting disk is not woken up)
+ * smart-test <disk>\nshort|long smartctl -j -t short|long (starts a self-test)
+ * smart-abort <disk> smartctl -j -X (stops a running self-test)
+ *
+ * Rules, all on the root side:
+ * - <disk> is a whole disk that smartctl understands: sd<letters>, hd<letters> or nvme<N>n<M>
+ * (smartctl_valid_disk), it exists in /sys/block and /dev/<disk> is a block device with the same
+ * number (the same target() check as the disk-* actions). Partitions, loop, dm, md, zram,
+ * cards and path tricks are refused before anything runs;
+ * - one program at a fixed path, /usr/sbin/smartctl, with a fixed argument list built here; the
+ * only variable parts are the validated /dev/<disk> and one of two words. No shell;
+ * - reading is open to any session user (like disk-smart); starting or stopping a self-test on an
+ * internal disk needs an administrator, on a removable one any session user (like udisks);
+ * - a USB disk whose bridge smartctl does not know is retried once with "-d sat".
+ * The JSON is compacted (smartctl_compact) and sent as LOG lines of at most 900 bytes, cut on
+ * UTF-8 boundaries; OK carries "<lines> <smartctl exit status>" (its bit mask: the app reads it).
+ * Missing smartctl is the error disk.noSmartctl: the app offers to install smartmontools with the
+ * package engine (pkg-install), never from here. */
+#include "disk.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#define SMARTCTL "/usr/sbin/smartctl"
+#define OUT_MAX (1024 * 1024)
+#define CHUNK 900
+#define MAX_LINES 1200
+
+/* runs smartctl with argv (argv[0] is SMARTCTL), output in out; exit status, -1 if it did not run */
+static int run(const char *const argv[], char *out, size_t cap, size_t *len) {
+ int rc = admin_run_capture(argv, out, cap);
+ *len = strlen(out);
+ return rc;
+}
+
+static int unknown_bridge(const char *out) { return strstr(out, "Unknown USB bridge") != NULL; }
+
+static void send_json(char *out, size_t n, int rc) {
+ n = smartctl_compact(out, n);
+ if (!n || out[0] != '{') { admin_err("disk.smartFailed", NULL); return; }
+ int lines = 0;
+ for (size_t i = 0; i < n && lines < MAX_LINES;) {
+ size_t k = smartctl_chunk(out + i, n - i, CHUNK);
+ admin_say("LOG", "%.*s", (int)k, out + i); /* i18n-ok */
+ i += k;
+ lines++;
+ }
+ admin_say("OK", "%d %d", lines, rc); /* i18n-ok */
+}
+
+/* mode: 'i' info, 'h' health, 't' test, 'x' abort */
+static void act(const AdminReq *r, const char *arg, size_t len, int mode) {
+ char a[64], *word = NULL;
+ if (!len || len >= sizeof a || memchr(arg, 0, len)) { admin_err("admin.invalidArgument", NULL); return; }
+ memcpy(a, arg, len);
+ a[len] = 0;
+ char *nl = strchr(a, '\n');
+ if (nl) { *nl = 0; word = nl + 1; char *e = strchr(word, '\n'); if (e) { if (e[1]) { admin_err("admin.invalidArgument", NULL); return; } *e = 0; } }
+ if (mode == 't' ? !word || (strcmp(word, "short") && strcmp(word, "long")) : word && *word) {
+ admin_err("admin.invalidArgument", NULL);
+ return;
+ }
+ if (!smartctl_valid_disk(a)) { admin_err("disk.badDevice", NULL); return; }
+ char dev[48];
+ int usb = 0;
+ if (disk_admin_target(r, a, mode == 't' || mode == 'x', dev, sizeof dev, &usb)) return; /* it said why */
+ if (access(SMARTCTL, X_OK)) { admin_err("disk.noSmartctl", NULL); return; }
+ char *out = malloc(OUT_MAX);
+ if (!out) { admin_err("disk.smartFailed", NULL); return; }
+ for (int sat = 0; sat < 2; sat++) {
+ const char *v[16];
+ int k = 0;
+ v[k++] = SMARTCTL;
+ v[k++] = "-j";
+ if (sat) { v[k++] = "-d"; v[k++] = "sat"; }
+ if (mode == 'i') v[k++] = "-x";
+ else if (mode == 'h') { v[k++] = "-n"; v[k++] = "standby"; v[k++] = "-H"; v[k++] = "-A"; v[k++] = "-c"; v[k++] = "-l"; v[k++] = "selftest"; }
+ else if (mode == 't') { v[k++] = "-t"; v[k++] = !strcmp(word, "long") ? "long" : "short"; }
+ else v[k++] = "-X";
+ v[k++] = dev;
+ v[k] = NULL;
+ size_t n = 0;
+ int rc = run(v, out, OUT_MAX, &n);
+ if (rc < 0 || rc >= 128) { free(out); admin_err("disk.smartFailed", NULL); return; }
+ if (!sat && usb && unknown_bridge(out)) continue; /* try SAT pass-through once */
+ send_json(out, n, rc);
+ free(out);
+ return;
+ }
+ free(out);
+ admin_err("disk.smartFailed", NULL);
+}
+
+void smart_act_info(const AdminReq *r, const char *arg, size_t len) { act(r, arg, len, 'i'); }
+void smart_act_health(const AdminReq *r, const char *arg, size_t len) { act(r, arg, len, 'h'); }
+void smart_act_test(const AdminReq *r, const char *arg, size_t len) { act(r, arg, len, 't'); }
+void smart_act_abort(const AdminReq *r, const char *arg, size_t len) { act(r, arg, len, 'x'); }
diff --git a/server/src/monitor/disktemp.c b/server/src/monitor/disktemp.c
new file mode 100644
index 0000000..f453bec
--- /dev/null
+++ b/server/src/monitor/disktemp.c
@@ -0,0 +1,149 @@
+/* disktemp.c — which hwmon sensor belongs to which disk (see disktemp.h).
+ *
+ * Kernel layouts (all world-readable, no root):
+ * NVMe: /sys/block/nvme0n1/device → the controller (class nvme), and its sensor is a class
+ * device directly under it: .../nvme0/hwmonN (name "nvme"). With native multipath the
+ * block device's `device` is the nvme-subsystem, which lists its controllers (nvme0 …).
+ * SATA: /sys/block/sda/device → the SCSI device (a bus device), so the sensor sits in a glue
+ * folder: .../0:0:0:0/hwmon/hwmonN (name "drivetemp", from the drivetemp module).
+ * temp1 is the drive's main ("Composite" on NVMe) temperature; temp1_max / temp1_crit are the
+ * drive's own warning and critical limits when it reports them. */
+#include "disktemp.h"
+
+#include <ctype.h>
+#include <dirent.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+static long read_small(const char *path, char *out, size_t n) {
+ int fd = open(path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
+ if (fd < 0) return -1;
+ ssize_t r = read(fd, out, n - 1);
+ close(fd);
+ if (r < 0) return -1;
+ out[r] = 0;
+ return r;
+}
+
+/* millidegrees in a file → whole °C within a sane range, or -1 */
+static int read_limit(const char *dir, const char *file) {
+ char p[PATH_MAX + 32], t[32];
+ snprintf(p, sizeof p, "%s/%s", dir, file);
+ if (read_small(p, t, sizeof t) <= 0) return -1;
+ char *end;
+ long v = strtol(t, &end, 10);
+ if (end == t) return -1;
+ v /= 1000;
+ return v >= 30 && v <= 150 ? (int)v : -1;
+}
+
+static int is_hwmon_name(const char *n) {
+ if (strncmp(n, "hwmon", 5) || !n[5]) return 0;
+ for (const char *p = n + 5; *p; p++) if (!isdigit((unsigned char)*p)) return 0;
+ return 1;
+}
+
+/* A hwmon folder whose chip is one we trust for a disk. */
+static int try_chip(const char *dir, DiskSensor *s) {
+ char p[PATH_MAX + 32], name[32];
+ snprintf(p, sizeof p, "%s/name", dir);
+ if (read_small(p, name, sizeof name) <= 0) return 0;
+ name[strcspn(name, "\n")] = 0;
+ int kind = !strcmp(name, "nvme") ? DT_NVME : !strcmp(name, "drivetemp") ? DT_DRIVETEMP : DT_NONE;
+ if (!kind) return 0;
+ struct stat st;
+ snprintf(p, sizeof p, "%s/temp1_input", dir);
+ size_t pl = strlen(p);
+ if (pl >= sizeof s->input || stat(p, &st) || !S_ISREG(st.st_mode)) return 0;
+ s->kind = kind;
+ memcpy(s->input, p, pl + 1);
+ s->max_c = read_limit(dir, "temp1_max");
+ s->crit_c = read_limit(dir, "temp1_crit");
+ if (s->max_c >= 0 && s->crit_c >= 0 && s->crit_c < s->max_c) s->crit_c = -1; /* nonsense pair */
+ return kind;
+}
+
+/* hwmonN directly in dev, or in dev/hwmon/ */
+static int scan_dev(const char *dev, DiskSensor *s) {
+ char sub[PATH_MAX];
+ for (int pass = 0; pass < 2; pass++) {
+ if (pass) snprintf(sub, sizeof sub, "%s/hwmon", dev); else snprintf(sub, sizeof sub, "%s", dev);
+ DIR *d = opendir(sub);
+ if (!d) continue;
+ struct dirent *e;
+ int found = 0;
+ while (!found && (e = readdir(d))) {
+ if (!is_hwmon_name(e->d_name)) continue;
+ char p[PATH_MAX + 300];
+ snprintf(p, sizeof p, "%s/%s", sub, e->d_name);
+ if (strlen(p) < PATH_MAX) found = try_chip(p, s);
+ }
+ closedir(d);
+ if (found) return found;
+ }
+ return 0;
+}
+
+static int valid_disk(const char *n) {
+ size_t l = strlen(n);
+ if (!l || l > 31 || !islower((unsigned char)n[0])) return 0;
+ for (size_t i = 0; i < l; i++) if (!islower((unsigned char)n[i]) && !isdigit((unsigned char)n[i])) return 0;
+ return 1;
+}
+
+int disktemp_find(const char *sys, const char *disk, DiskSensor *s) {
+ memset(s, 0, sizeof *s);
+ s->max_c = s->crit_c = -1;
+ if (!sys || !valid_disk(disk)) return DT_NONE;
+ char p[PATH_MAX], dev[PATH_MAX];
+ snprintf(p, sizeof p, "%s/block/%s/device", sys, disk);
+ if (!realpath(p, dev)) return DT_NONE;
+ if (scan_dev(dev, s)) return s->kind;
+ if (strncmp(disk, "nvme", 4)) return DT_NONE;
+ /* native multipath: device is nvme-subsysN, whose entries nvme0, nvme1… are its controllers */
+ DIR *d = opendir(dev);
+ if (d) {
+ struct dirent *e;
+ while ((e = readdir(d))) {
+ if (strncmp(e->d_name, "nvme", 4) || !isdigit((unsigned char)e->d_name[4])) continue;
+ int digits = 1;
+ for (const char *c = e->d_name + 4; *c; c++) if (!isdigit((unsigned char)*c)) digits = 0;
+ if (!digits) continue;
+ char q[PATH_MAX + 300], r[PATH_MAX];
+ snprintf(q, sizeof q, "%s/%s", dev, e->d_name);
+ if (strlen(q) < PATH_MAX && realpath(q, r) && scan_dev(r, s)) break;
+ }
+ closedir(d);
+ if (s->kind) return s->kind;
+ }
+ /* last resort: nvmeXnY → the class device of controller nvmeX */
+ char ctrl[32];
+ size_t k = 4;
+ while (isdigit((unsigned char)disk[k])) k++;
+ if (k == 4 || disk[k] != 'n') return DT_NONE;
+ snprintf(ctrl, sizeof ctrl, "%.*s", (int)k, disk);
+ snprintf(p, sizeof p, "%s/class/nvme/%s", sys, ctrl);
+ if (realpath(p, dev) && scan_dev(dev, s)) return s->kind;
+ return DT_NONE;
+}
+
+int disktemp_read(const DiskSensor *s, double *celsius) {
+ if (!s || !s->kind) return -1;
+ char t[32];
+ if (read_small(s->input, t, sizeof t) <= 0) return -1;
+ char *end;
+ long v = strtol(t, &end, 10);
+ if (end == t) return -1;
+ double c = v / 1000.0;
+ if (c <= -40 || c >= 150) return -1; /* a bogus reading is "no value", not a value */
+ *celsius = c;
+ return 0;
+}
+
+const char *disktemp_kind_name(int kind) {
+ return kind == DT_NVME ? "nvme" : kind == DT_DRIVETEMP ? "drivetemp" : NULL;
+}
diff --git a/server/src/monitor/disktemp.h b/server/src/monitor/disktemp.h
new file mode 100644
index 0000000..08d97ff
--- /dev/null
+++ b/server/src/monitor/disktemp.h
@@ -0,0 +1,31 @@
+/* disktemp.h — disk temperatures from the kernel's hwmon sensors, without root (see disktemp.c and
+ * docs/MONITOR.md, "Disk temperature and health").
+ *
+ * NVMe (also an M.2 drive on a Raspberry Pi 5 HAT) has a sensor from the nvme driver itself; SATA
+ * disks get one from the drivetemp module (loaded at boot by the lordos package). microSD/eMMC cards,
+ * virtual disks and anything else have none: the caller shows "No sensor", never a made-up value. */
+#ifndef LORD_DISKTEMP_H
+#define LORD_DISKTEMP_H
+
+#include <limits.h>
+#include <stddef.h>
+
+enum { DT_NONE = 0, DT_NVME = 1, DT_DRIVETEMP = 2 };
+
+typedef struct {
+ int kind; /* DT_NONE: no sensor */
+ char input[PATH_MAX]; /* .../hwmonN/temp1_input */
+ int max_c, crit_c; /* the drive's own limits (temp1_max / temp1_crit), -1 if not exposed */
+} DiskSensor;
+
+/* Finds the sensor of whole disk `disk` (sda, nvme0n1) under sysfs root `sys` ("/sys"; a fake tree
+ * in tests). Looks in the disk's device folder (hwmonN directly, as for an NVMe controller, or
+ * hwmon/hwmonN, as for a SCSI device), then, for NVMe with native multipath (the device is an
+ * nvme-subsystem), in its controllers. Only chips named "nvme" or "drivetemp" count. Returns kind. */
+int disktemp_find(const char *sys, const char *disk, DiskSensor *s);
+/* Reads the current temperature in °C (one small sysfs read). 0 on success. */
+int disktemp_read(const DiskSensor *s, double *celsius);
+/* Short name for the JSON: "nvme", "drivetemp" or NULL. */
+const char *disktemp_kind_name(int kind);
+
+#endif
diff --git a/server/src/monitor/mon.c b/server/src/monitor/mon.c
index 1611cd9..579c471 100644
--- a/server/src/monitor/mon.c
+++ b/server/src/monitor/mon.c
@@ -12,6 +12,7 @@
#include "mon.h"
#include "monpriv.h"
#include "procctl.h"
+#include "disktemp.h"
#include <ctype.h>
#include <dirent.h>
@@ -128,8 +129,9 @@ static struct {
pthread_cond_t cv;
int started, refs, want_procs, want_conns, want_geo;
double last_poll;
- char *sample, *procs, *conns, *detail;
- uint64_t sseq, pseq, cseq, dseq;
+ char *sample, *procs, *conns, *detail, *dtemps;
+ uint64_t sseq, pseq, cseq, dseq, tseq;
+ int watch_disks; /* background disk temperatures (notifications), see below */
int detail_pid; /* Get Info: 0 = none */
unsigned long long detail_start;
char geo_path[PATH_MAX];
@@ -149,9 +151,23 @@ static struct {
int ndisk;
} prev;
-/* Disks: model and size (read once per thread start). */
-static struct { char name[32], model[96]; unsigned long long size; } dinfo[MAX_DISK];
+/* Disks: model and size (read once per thread start), the temperature sensor (disktemp.c) and
+ * the state that decides when it may be read. */
+typedef struct {
+ char name[32], model[96];
+ unsigned long long size;
+ int rota; /* spinning disk (queue/rotational) */
+ DiskSensor sensor;
+ unsigned long long io; /* reads + writes seen last time */
+ double last_io; /* mon_now_ms of the last I/O seen (0: none yet) */
+ double temp, temp_t; /* last reading (°C) and its wall-clock time; temp_t 0 = none */
+} DiskInfo;
+static DiskInfo dinfo[MAX_DISK];
static int ndinfo;
+static unsigned temp_ticks; /* samples since the last temperature read */
+#define TEMP_EVERY 12 /* 3 s at 4 samples per second */
+#define AWAKE_MS 60000 /* a spinning disk counts as awake for 60 s after its last I/O */
+#define WATCH_MS 30000 /* background disk temperatures: every 30 s */
/* Sensors: paths found at startup. */
static char temp_path[8][PATH_MAX], fan_path[8][PATH_MAX];
@@ -286,6 +302,9 @@ static int whole_disk(const char *name) {
}
static void disk_info_scan(void) {
+ DiskInfo old[MAX_DISK];
+ int nold = ndinfo;
+ memcpy(old, dinfo, sizeof dinfo[0] * (size_t)nold);
ndinfo = 0;
DIR *d = opendir("/sys/block");
if (!d) return;
@@ -293,20 +312,74 @@ static void disk_info_scan(void) {
while ((e = readdir(d)) && ndinfo < MAX_DISK) {
if (e->d_name[0] == '.' || strlen(e->d_name) >= 32 || !whole_disk(e->d_name)) continue;
char p[PATH_MAX], t[128];
- snprintf(dinfo[ndinfo].name, sizeof dinfo[0].name, "%s", e->d_name);
+ DiskInfo *di = &dinfo[ndinfo];
+ memset(di, 0, sizeof *di);
+ snprintf(di->name, sizeof di->name, "%s", e->d_name);
snprintf(p, sizeof p, "/sys/block/%s/device/model", e->d_name);
if (mon_read_small(p, t, sizeof t) <= 0) t[0] = 0;
size_t k = strlen(t);
while (k && isspace((unsigned char)t[k - 1])) t[--k] = 0;
- snprintf(dinfo[ndinfo].model, sizeof dinfo[0].model, "%s", t);
+ snprintf(di->model, sizeof di->model, "%s", t);
snprintf(p, sizeof p, "/sys/block/%s/size", e->d_name);
- dinfo[ndinfo].size = mon_read_small(p, t, sizeof t) > 0 ? ull(t) * 512 : 0;
+ di->size = mon_read_small(p, t, sizeof t) > 0 ? ull(t) * 512 : 0;
+ snprintf(p, sizeof p, "/sys/block/%s/queue/rotational", e->d_name);
+ di->rota = mon_read_small(p, t, sizeof t) > 0 && t[0] == '1';
+ disktemp_find("/sys", e->d_name, &di->sensor);
+ for (int i = 0; i < nold; i++) /* keep what was learned about it (a rescan) */
+ if (!strcmp(old[i].name, di->name)) { di->io = old[i].io; di->last_io = old[i].last_io; di->temp = old[i].temp; di->temp_t = old[i].temp_t; }
ndinfo++;
}
closedir(d);
}
-static void disk_sample(Buf *b, double dt) {
+/* Temperatures of the disks with a sensor. A spinning disk is only read while it is awake (I/O in
+ * the last minute): asking a resting drive for its temperature can keep it from spinning down. */
+static void disk_temps_read(void) {
+ double now = mon_now_ms(), wall = mon_wall_ms();
+ for (int i = 0; i < ndinfo; i++) {
+ DiskInfo *di = &dinfo[i];
+ if (!di->sensor.kind) continue;
+ if (di->rota && !(di->last_io > 0 && now - di->last_io < AWAKE_MS)) continue;
+ double c;
+ if (!disktemp_read(&di->sensor, &c)) { di->temp = c; di->temp_t = wall; }
+ }
+}
+
+static DiskInfo *dinfo_of(const char *name) {
+ for (int i = 0; i < ndinfo; i++) if (!strcmp(dinfo[i].name, name)) return &dinfo[i];
+ return NULL;
+}
+
+/* ,"rota":0,"sensor":"nvme","temp":38.9,"tempT":…,"tempMax":81,"tempCrit":84,"tempIdle":false,"awake":true
+ * (tempIdle: a spinning disk at rest, so not read; awake: I/O in the last minute) */
+static void disk_temp_fields(Buf *b, const DiskInfo *di) {
+ const char *k = di ? disktemp_kind_name(di->sensor.kind) : NULL;
+ mon_buf_printf(b, ",\"rota\":%d,\"sensor\":", di ? di->rota : 0);
+ if (k) mon_buf_str(b, k); else mon_buf_printf(b, "null");
+ if (di && k && di->temp_t > 0) mon_buf_printf(b, ",\"temp\":%.1f,\"tempT\":%.0f", di->temp, di->temp_t);
+ else mon_buf_printf(b, ",\"temp\":null,\"tempT\":0");
+ if (di && k && di->sensor.max_c >= 0) mon_buf_printf(b, ",\"tempMax\":%d", di->sensor.max_c); else mon_buf_printf(b, ",\"tempMax\":null");
+ if (di && k && di->sensor.crit_c >= 0) mon_buf_printf(b, ",\"tempCrit\":%d", di->sensor.crit_c); else mon_buf_printf(b, ",\"tempCrit\":null");
+ int awake = di && di->last_io > 0 && mon_now_ms() - di->last_io < AWAKE_MS;
+ int idle = di && k && di->rota && !awake;
+ mon_buf_printf(b, ",\"tempIdle\":%s,\"awake\":%s", idle ? "true" : "false", awake ? "true" : "false");
+}
+
+/* Just the temperatures, for the session's notifications: {"t", "disks": [{name, model, …}]} */
+static void disk_temps_json(Buf *b) {
+ mon_buf_printf(b, "{\"t\":%.0f,\"disks\":[", mon_wall_ms());
+ for (int i = 0; i < ndinfo; i++) {
+ mon_buf_printf(b, "%s{\"name\":", i ? "," : "");
+ mon_buf_str(b, dinfo[i].name);
+ mon_buf_printf(b, ",\"model\":");
+ mon_buf_str(b, dinfo[i].model);
+ disk_temp_fields(b, &dinfo[i]);
+ mon_buf_printf(b, "}");
+ }
+ mon_buf_printf(b, "]}");
+}
+
+static void disk_sample(Buf *b, double dt, int temps) {
static char txt[65536];
struct { char name[32]; unsigned long long rd, wr; } cur[MAX_DISK];
int n = 0;
@@ -323,9 +396,13 @@ static void disk_sample(Buf *b, double dt) {
snprintf(cur[n].name, sizeof cur[n].name, "%.31s", name);
cur[n].rd = f[2] * 512; /* sectors read */
cur[n].wr = f[6] * 512; /* sectors written */
+ DiskInfo *di = dinfo_of(name);
+ unsigned long long io = f[0] + f[4]; /* reads + writes completed */
+ if (di && di->io != io) { if (di->io || di->last_io > 0) di->last_io = mon_now_ms(); di->io = io; }
n++;
}
}
+ if (temps) disk_temps_read();
double rd = 0, wr = 0;
Buf list = { 0 };
for (int i = 0; i < n; i++) {
@@ -334,14 +411,16 @@ static void disk_sample(Buf *b, double dt) {
if (!strcmp(prev.disks[j].name, cur[i].name)) { r = rate(cur[i].rd, prev.disks[j].rd, dt); w = rate(cur[i].wr, prev.disks[j].wr, dt); }
rd += r;
wr += w;
- const char *model = "";
- unsigned long long size = 0;
- for (int k = 0; k < ndinfo; k++) if (!strcmp(dinfo[k].name, cur[i].name)) { model = dinfo[k].model; size = dinfo[k].size; }
+ const DiskInfo *di = dinfo_of(cur[i].name);
+ const char *model = di ? di->model : "";
+ unsigned long long size = di ? di->size : 0;
mon_buf_printf(&list, "%s{\"name\":", i ? "," : "");
mon_buf_str(&list, cur[i].name);
mon_buf_printf(&list, ",\"model\":");
mon_buf_str(&list, model);
- mon_buf_printf(&list, ",\"size\":%llu,\"read\":%.0f,\"write\":%.0f,\"readTotal\":%llu,\"writeTotal\":%llu}", size, r, w, cur[i].rd, cur[i].wr);
+ mon_buf_printf(&list, ",\"size\":%llu,\"read\":%.0f,\"write\":%.0f,\"readTotal\":%llu,\"writeTotal\":%llu", size, r, w, cur[i].rd, cur[i].wr);
+ disk_temp_fields(&list, di);
+ mon_buf_printf(&list, "}");
}
memcpy(prev.disks, cur, sizeof cur[0] * (size_t)n);
prev.ndisk = n;
@@ -531,8 +610,27 @@ static void publish(char **slot, uint64_t *seq, Buf *b) {
memset(b, 0, sizeof *b);
}
+/* Publishes the latest disk temperatures (lord.monitor.diskTemps). */
+static void publish_temps(void) {
+ Buf t = { 0 };
+ disk_temps_json(&t);
+ publish(&M.dtemps, &M.tseq, &t);
+}
+
+/* Background pass (the Monitor closed): rescan the disks (one plugged in), note their I/O, read. */
+static void watch_pass(void) {
+ disk_info_scan();
+ Buf junk = { 0 };
+ disk_sample(&junk, 0, 0); /* only to see which spinning disks are awake */
+ mon_buf_free(&junk);
+ memset(&prev, 0, sizeof prev); /* no stale rates when the Monitor opens */
+ disk_temps_read();
+ publish_temps();
+}
+
static void *worker(void *arg) {
(void)arg;
+ double next_watch = 0;
Mmdb geo;
int geo_open = 0, geo_tried = 0;
unsigned tick = 0;
@@ -541,7 +639,23 @@ static void *worker(void *arg) {
int slept = 0;
while (!(M.refs > 0 && mon_now_ms() - M.last_poll < IDLE_MS)) {
slept = 1;
- pthread_cond_wait(&M.cv, &M.mu);
+ if (!M.watch_disks) { pthread_cond_wait(&M.cv, &M.mu); continue; }
+ /* nobody looks at the Monitor, but the session wants disk temperature notices:
+ * only the disk list and its sensors, every 30 s */
+ double left = next_watch - mon_now_ms();
+ if (left <= 0) {
+ pthread_mutex_unlock(&M.mu);
+ watch_pass();
+ next_watch = mon_now_ms() + WATCH_MS;
+ pthread_mutex_lock(&M.mu);
+ continue;
+ }
+ struct timespec ts;
+ clock_gettime(CLOCK_REALTIME, &ts);
+ long long ns = ts.tv_nsec + (long long)(left * 1e6);
+ ts.tv_sec += (time_t)(ns / 1000000000LL);
+ ts.tv_nsec = (long)(ns % 1000000000LL);
+ pthread_cond_timedwait(&M.cv, &M.mu, &ts);
}
int wp = M.want_procs, wc = M.want_conns, wg = M.want_geo, dpid = M.detail_pid;
unsigned long long dstart = M.detail_start;
@@ -554,6 +668,7 @@ static void *worker(void *arg) {
disk_info_scan();
sensors_scan();
tick = 0;
+ temp_ticks = 0;
}
double t0 = mon_now_ms(), dt = prev.t > 0 ? t0 - prev.t : 0;
Buf b = { 0 };
@@ -562,11 +677,13 @@ static void *worker(void *arg) {
mem_sample(&b);
load_sample(&b);
net_sample(&b, dt);
- disk_sample(&b, dt);
+ int temps = temp_ticks++ % TEMP_EVERY == 0;
+ disk_sample(&b, dt, temps);
sensors_sample(&b);
mon_buf_printf(&b, "}");
prev.t = t0;
publish(&M.sample, &M.sseq, &b);
+ if (temps) publish_temps();
if (wp && tick % 4 == 0) {
Buf p = { 0 };
procs_scan(&p);
@@ -616,13 +733,11 @@ void mon_reset(void) {
M.refs = 0;
M.want_procs = M.want_conns = M.want_geo = 0;
M.detail_pid = 0;
+ M.watch_disks = 0;
pthread_mutex_unlock(&M.mu);
}
-void mon_start(void) {
- pthread_mutex_lock(&M.mu);
- if (M.refs < 64) M.refs++;
- M.last_poll = mon_now_ms();
+static void start_thread_locked(void) {
if (!M.started) {
pthread_t th;
pthread_attr_t at;
@@ -632,10 +747,34 @@ void mon_start(void) {
if (!pthread_create(&th, &at, worker, NULL)) M.started = 1;
pthread_attr_destroy(&at);
}
+}
+
+void mon_start(void) {
+ pthread_mutex_lock(&M.mu);
+ if (M.refs < 64) M.refs++;
+ M.last_poll = mon_now_ms();
+ start_thread_locked();
+ pthread_cond_signal(&M.cv);
+ pthread_mutex_unlock(&M.mu);
+}
+
+void mon_watch_disks(int on) {
+ pthread_mutex_lock(&M.mu);
+ M.watch_disks = !!on;
+ if (on) start_thread_locked();
pthread_cond_signal(&M.cv);
pthread_mutex_unlock(&M.mu);
}
+/* Unlike take(), reading the temperatures does not keep the 4 Hz sampling awake. */
+char *mon_disk_temps_json(uint64_t *seq) {
+ pthread_mutex_lock(&M.mu);
+ char *r = NULL;
+ if (M.dtemps && M.tseq != *seq) { r = strdup(M.dtemps); *seq = M.tseq; }
+ pthread_mutex_unlock(&M.mu);
+ return r;
+}
+
void mon_stop(void) {
pthread_mutex_lock(&M.mu);
if (M.refs > 0) M.refs--;
diff --git a/server/src/monitor/mon.h b/server/src/monitor/mon.h
index 744991d..1b0af55 100644
--- a/server/src/monitor/mon.h
+++ b/server/src/monitor/mon.h
@@ -27,6 +27,12 @@ char *mon_conns_json(uint64_t *seq);
* and the latest JSON. start: its start time in ticks, so a reused PID shows as gone. */
void mon_detail(int pid, unsigned long long start);
char *mon_detail_json(uint64_t *seq);
+/* Disk temperatures for the session's notifications (sdk/diskwatch.js): with on, the thread also
+ * wakes every 30 s while the Monitor is closed and reads only the disk sensors (spinning disks only
+ * when awake). mon_disk_temps_json: {"t", "disks": [{name, model, rota, sensor, temp, tempT, tempMax,
+ * tempCrit, tempIdle}]} if newer than *seq; reading it does not keep the 4 Hz sampling alive. */
+void mon_watch_disks(int on);
+char *mon_disk_temps_json(uint64_t *seq);
/* Fixed data: CPU model, cores, location from the time zone, country database. */
char *mon_info_json(void);
diff --git a/server/src/ui/js_monitor.c b/server/src/ui/js_monitor.c
index ba3736a..c308e5a 100644
--- a/server/src/ui/js_monitor.c
+++ b/server/src/ui/js_monitor.c
@@ -19,6 +19,9 @@
* an error code (proc.gone, proc.protected…, proc.notOwn, proc.denied).
* Other users' processes go through the root helper (proc-signal,
* administrators only; sdk/monitor.js).
+ * watchDisks(on) disk temperatures with the Monitor closed (every 30 s; sdk/diskwatch.js)
+ * diskTemps() the latest { t, disks: [{ name, model, sensor, temp, tempMax, … }] } or
+ * null if nothing new; it does not keep the 4 Hz sampling awake
*/
#include "js_monitor.h"
#include "../monitor/mon.h"
@@ -38,7 +41,7 @@
#include <sys/stat.h>
#include <unistd.h>
-static uint64_t seq_sample, seq_procs, seq_conns, seq_detail;
+static uint64_t seq_sample, seq_procs, seq_conns, seq_detail, seq_temps;
static JSValue parse(JSContext *c, char *j, const char *what) {
if (!j) return JS_NULL;
@@ -71,6 +74,17 @@ static JSValue f_sample(JSContext *c, JSValueConst t, int argc, JSValueConst *ar
return parse(c, mon_sample_json(&seq_sample), "<monitor.sample>");
}
+static JSValue f_watch_disks(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ mon_watch_disks(argc > 0 && JS_ToBool(c, argv[0]) > 0);
+ return JS_TRUE;
+}
+
+static JSValue f_disk_temps(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t; (void)argc; (void)argv;
+ return parse(c, mon_disk_temps_json(&seq_temps), "<monitor.diskTemps>");
+}
+
static JSValue f_info(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
(void)t; (void)argc; (void)argv;
JSValue o = parse(c, mon_info_json(), "<monitor.info>");
@@ -376,13 +390,15 @@ static const JSCFunctionListEntry monitor_funcs[] = {
JS_CFUNC_DEF("detail", 2, f_detail),
JS_CFUNC_DEF("detailInfo", 0, f_detail_info),
JS_CFUNC_DEF("signal", 3, f_signal),
+ JS_CFUNC_DEF("watchDisks", 1, f_watch_disks),
+ JS_CFUNC_DEF("diskTemps", 0, f_disk_temps),
};
void js_monitor_register(JSContext *c, JSValue lord, const char *assets_dir) {
mon_init(assets_dir);
map_init(assets_dir);
mon_reset(); /* new context: the previous one's start() calls don't count */
- seq_sample = seq_procs = seq_conns = seq_detail = 0;
+ seq_sample = seq_procs = seq_conns = seq_detail = seq_temps = 0;
JSValue o = JS_NewObject(c);
JS_SetPropertyFunctionList(c, o, monitor_funcs, sizeof monitor_funcs / sizeof monitor_funcs[0]);
JS_SetPropertyStr(c, lord, "monitor", o);
diff --git a/server/tests/disk_cli.c b/server/tests/disk_cli.c
index bbe9d88..9bc4889 100644
--- a/server/tests/disk_cli.c
+++ b/server/tests/disk_cli.c
@@ -89,6 +89,7 @@ int main(int argc, char **argv) {
{ "disk-smart", disk_act_smart }, { "disk-mount", disk_act_mount }, { "disk-unmount", disk_act_unmount },
{ "disk-eject", disk_act_eject }, { "disk-format", disk_act_format }, { "disk-label", disk_act_label },
{ "disk-erase", disk_act_erase }, { "disk-write-image", disk_act_write_image }, { "disk-cancel", disk_act_cancel },
+ { "smart-info", smart_act_info }, { "smart-health", smart_act_health }, { "smart-test", smart_act_test }, { "smart-abort", smart_act_abort },
};
for (size_t k = 0; k < sizeof acts / sizeof *acts; k++)
if (!strcmp(acts[k].n, argv[i])) { acts[k].fn(&r, arg, strlen(arg)); free(arg); return 0; }
diff --git a/server/tests/disktemp_test.c b/server/tests/disktemp_test.c
new file mode 100644
index 0000000..fce0fae
--- /dev/null
+++ b/server/tests/disktemp_test.c
@@ -0,0 +1,121 @@
+/* disktemp_test.c — which hwmon sensor belongs to which disk (src/monitor/disktemp.c), on fake
+ * sysfs trees laid out like the kernel's:
+ * nvme0n1 device → controller nvme0, sensor nvme0/hwmon3 (name "nvme", with max/crit)
+ * nvme1n1 native multipath: device → nvme-subsys1, whose entry nvme1 → the controller
+ * sda device → SCSI device 0:0:0:0, sensor in its glue folder hwmon/hwmon4 ("drivetemp")
+ * sdb a SCSI device whose only hwmon chip is something else ("acpitz"): no sensor
+ * mmcblk0 an SD card: no hwmon at all
+ * vda a virtual disk: no hwmon at all
+ *
+ * make -C server build/disktemp-test && ./server/build/disktemp-test (in `make test`) */
+#include "../src/monitor/disktemp.h"
+
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+static int fails, checks;
+#define CHECK(c, ...) do { checks++; if (!(c)) { fails++; printf("✗ " __VA_ARGS__); printf("\n"); } } while (0)
+
+static char root[256];
+
+static void mkdirs(const char *rel) {
+ char p[1024];
+ snprintf(p, sizeof p, "%s/%s", root, rel);
+ for (char *s = p + strlen(root) + 1; *s; s++) if (*s == '/') { *s = 0; mkdir(p, 0755); *s = '/'; }
+ mkdir(p, 0755);
+}
+
+static void put(const char *rel, const char *text) {
+ char p[1024];
+ snprintf(p, sizeof p, "%s/%s", root, rel);
+ char d[1024];
+ snprintf(d, sizeof d, "%s", rel);
+ char *sl = strrchr(d, '/');
+ if (sl) { *sl = 0; mkdirs(d); }
+ FILE *f = fopen(p, "w");
+ if (f) { fputs(text, f); fclose(f); }
+}
+
+static void link_to(const char *target, const char *rel) {
+ char p[1024], d[1024];
+ snprintf(d, sizeof d, "%s", rel);
+ char *sl = strrchr(d, '/');
+ if (sl) { *sl = 0; mkdirs(d); }
+ snprintf(p, sizeof p, "%s/%s", root, rel);
+ if (symlink(target, p)) perror(p);
+}
+
+int main(void) {
+ snprintf(root, sizeof root, "/tmp/disktemp-test-XXXXXX");
+ if (!mkdtemp(root)) { perror("mkdtemp"); return 1; }
+
+ /* NVMe: the sensor is a class device right under the controller */
+ put("devices/pci0000:00/0000:00:1d.0/0000:3d:00.0/nvme/nvme0/hwmon3/name", "nvme\n");
+ put("devices/pci0000:00/0000:00:1d.0/0000:3d:00.0/nvme/nvme0/hwmon3/temp1_input", "38850\n");
+ put("devices/pci0000:00/0000:00:1d.0/0000:3d:00.0/nvme/nvme0/hwmon3/temp1_max", "81850\n");
+ put("devices/pci0000:00/0000:00:1d.0/0000:3d:00.0/nvme/nvme0/hwmon3/temp1_crit", "84850\n");
+ put("devices/pci0000:00/0000:00:1d.0/0000:3d:00.0/nvme/nvme0/hwmon3/temp2_input", "41850\n");
+ link_to("../../devices/pci0000:00/0000:00:1d.0/0000:3d:00.0/nvme/nvme0", "block/nvme0n1/device");
+
+ /* NVMe with native multipath: device is the subsystem; the controller is listed inside */
+ put("devices/pci0000:00/0000:00:1c.0/0000:04:00.0/nvme/nvme1/hwmon5/name", "nvme\n");
+ put("devices/pci0000:00/0000:00:1c.0/0000:04:00.0/nvme/nvme1/hwmon5/temp1_input", "45000\n");
+ mkdirs("devices/virtual/nvme-subsystem/nvme-subsys1");
+ link_to("../../../pci0000:00/0000:00:1c.0/0000:04:00.0/nvme/nvme1", "devices/virtual/nvme-subsystem/nvme-subsys1/nvme1");
+ link_to("../../devices/virtual/nvme-subsystem/nvme-subsys1", "block/nvme1n1/device");
+
+ /* SATA with drivetemp: hwmon/hwmonN under the SCSI device; no limits exposed */
+ put("devices/pci0000:00/0000:00:1f.2/ata1/host0/target0:0:0/0:0:0:0/hwmon/hwmon4/name", "drivetemp\n");
+ put("devices/pci0000:00/0000:00:1f.2/ata1/host0/target0:0:0/0:0:0:0/hwmon/hwmon4/temp1_input", "31000\n");
+ link_to("../../devices/pci0000:00/0000:00:1f.2/ata1/host0/target0:0:0/0:0:0:0", "block/sda/device");
+
+ /* a chip that is not a disk sensor must not count */
+ put("devices/platform/x/host1/target1:0:0/1:0:0:0/hwmon/hwmon6/name", "acpitz\n");
+ put("devices/platform/x/host1/target1:0:0/1:0:0:0/hwmon/hwmon6/temp1_input", "50000\n");
+ link_to("../../devices/platform/x/host1/target1:0:0/1:0:0:0", "block/sdb/device");
+
+ /* card and virtual disk: no sensor */
+ mkdirs("devices/platform/axi/1000fff000.mmc/mmc_host/mmc0/mmc0:aaaa");
+ link_to("../../devices/platform/axi/1000fff000.mmc/mmc_host/mmc0/mmc0:aaaa", "block/mmcblk0/device");
+ mkdirs("devices/pci0000:00/0000:00:05.0/virtio2");
+ link_to("../../devices/pci0000:00/0000:00:05.0/virtio2", "block/vda/device");
+
+ DiskSensor s;
+ double c = 0;
+ CHECK(disktemp_find(root, "nvme0n1", &s) == DT_NVME, "nvme0n1 has an nvme sensor");
+ CHECK(s.max_c == 81 && s.crit_c == 84, "nvme0n1 limits 81/84, got %d/%d", s.max_c, s.crit_c);
+ CHECK(!disktemp_read(&s, &c) && c > 38.8 && c < 38.9, "nvme0n1 reads 38.85, got %.2f", c);
+ CHECK(!strcmp(disktemp_kind_name(s.kind), "nvme"), "kind name nvme");
+
+ CHECK(disktemp_find(root, "nvme1n1", &s) == DT_NVME, "nvme1n1 (multipath) found through its controller");
+ CHECK(s.max_c == -1 && s.crit_c == -1, "nvme1n1 without limits");
+ CHECK(!disktemp_read(&s, &c) && c == 45.0, "nvme1n1 reads 45");
+
+ CHECK(disktemp_find(root, "sda", &s) == DT_DRIVETEMP, "sda has a drivetemp sensor");
+ CHECK(!disktemp_read(&s, &c) && c == 31.0, "sda reads 31");
+
+ CHECK(disktemp_find(root, "sdb", &s) == DT_NONE, "sdb: an acpitz chip is not a disk sensor");
+ CHECK(disktemp_find(root, "mmcblk0", &s) == DT_NONE, "mmcblk0: no sensor");
+ CHECK(disktemp_read(&s, &c) == -1, "no sensor: no value");
+ CHECK(disktemp_find(root, "vda", &s) == DT_NONE, "vda: no sensor");
+ CHECK(disktemp_find(root, "sdx", &s) == DT_NONE, "missing disk: no sensor");
+ CHECK(disktemp_find(root, "../sda", &s) == DT_NONE, "a path is not a disk name");
+ CHECK(disktemp_kind_name(DT_NONE) == NULL, "no kind name without a sensor");
+
+ /* a bogus reading is "no value", never a number */
+ put("devices/pci0000:00/0000:00:1f.2/ata1/host0/target0:0:0/0:0:0:0/hwmon/hwmon4/temp1_input", "-273150\n");
+ disktemp_find(root, "sda", &s);
+ CHECK(disktemp_read(&s, &c) == -1, "absurd reading refused");
+ put("devices/pci0000:00/0000:00:1f.2/ata1/host0/target0:0:0/0:0:0:0/hwmon/hwmon4/temp1_input", "garbage\n");
+ CHECK(disktemp_read(&s, &c) == -1, "garbage refused");
+
+ char cmd[300];
+ snprintf(cmd, sizeof cmd, "rm -rf '%s'", root);
+ if (system(cmd)) printf("could not remove %s\n", root);
+ printf("disktemp-test: %d checks, %d failures\n", checks, fails);
+ return fails ? 1 : 0;
+}
diff --git a/server/tests/run_suites.sh b/server/tests/run_suites.sh
index b47e29e..544d9ec 100644
--- a/server/tests/run_suites.sh
+++ b/server/tests/run_suites.sh
@@ -153,6 +153,9 @@ EOF
# the Dock's pinned-list model (sdk/dockmodel.js)
if have node; then run "dock-model-test (sdk/dockmodel.js)" node tests/dock_model_test.mjs
else skip "dock-model-test" "node"; fi
+ # smartctl's JSON → the Disks/Monitor SMART model (sdk/smartparse.js), with real smartctl output
+ if have node; then run "smart-parse-test (sdk/smartparse.js)" node tests/smart_parse_test.mjs
+ else skip "smart-parse-test" "node"; fi
}
full() {
diff --git a/server/tests/smart/ata-hdd-failing.json b/server/tests/smart/ata-hdd-failing.json
new file mode 100644
index 0000000..961d234
--- /dev/null
+++ b/server/tests/smart/ata-hdd-failing.json
@@ -0,0 +1,262 @@
+{
+ "json_format_version": [
+ 1,
+ 0
+ ],
+ "smartctl": {
+ "version": [
+ 7,
+ 4
+ ],
+ "pre_release": false,
+ "svn_revision": "5530",
+ "platform_info": "x86_64-linux-6.12.113+deb13-amd64",
+ "build_info": "(local build)",
+ "argv": [
+ "smartctl",
+ "-j",
+ "-x",
+ "/dev/sdb"
+ ],
+ "drive_database_version": {
+ "string": "7.3/5528"
+ },
+ "exit_status": 24
+ },
+ "local_time": {
+ "time_t": 1792378099,
+ "asctime": "Sun Oct 18 23:48:19 2026 -03"
+ },
+ "device": {
+ "name": "/dev/sdb",
+ "info_name": "/dev/sdb [SAT]",
+ "type": "sat",
+ "protocol": "ATA"
+ },
+ "model_name": "SATA HDD 2TB",
+ "serial_number": "TEST0000000002",
+ "firmware_version": "2.5+",
+ "user_capacity": {
+ "blocks": 16777216,
+ "bytes": 8589934592
+ },
+ "logical_block_size": 512,
+ "physical_block_size": 512,
+ "trim": {
+ "supported": true,
+ "deterministic": true,
+ "zeroed": false
+ },
+ "in_smartctl_database": false,
+ "ata_version": {
+ "string": "ATA/ATAPI-7, ATA/ATAPI-5 published, ANSI NCITS 340-2000",
+ "major_value": 240,
+ "minor_value": 22
+ },
+ "smart_support": {
+ "available": true,
+ "enabled": true
+ },
+ "write_cache": {
+ "enabled": true
+ },
+ "smart_status": {
+ "passed": false
+ },
+ "ata_smart_data": {
+ "offline_data_collection": {
+ "status": {
+ "value": 130,
+ "string": "was completed without error",
+ "passed": true
+ },
+ "completion_seconds": 288
+ },
+ "self_test": {
+ "status": {
+ "value": 0,
+ "string": "completed without error",
+ "passed": true
+ },
+ "polling_minutes": {
+ "short": 2,
+ "extended": 54
+ }
+ },
+ "capabilities": {
+ "values": [
+ 25,
+ 3
+ ],
+ "exec_offline_immediate_supported": true,
+ "offline_is_aborted_upon_new_cmd": false,
+ "offline_surface_scan_supported": true,
+ "self_tests_supported": true,
+ "conveyance_self_test_supported": false,
+ "selective_self_test_supported": false,
+ "attribute_autosave_enabled": true,
+ "error_logging_supported": true,
+ "gp_logging_supported": false
+ }
+ },
+ "ata_smart_attributes": {
+ "revision": 1,
+ "table": [
+ {
+ "id": 1,
+ "name": "Raw_Read_Error_Rate",
+ "value": 100,
+ "worst": 100,
+ "thresh": 6,
+ "when_failed": "",
+ "flags": {
+ "value": 3,
+ "string": "PO--CK ",
+ "prefailure": true,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": true
+ },
+ "raw": {
+ "value": 0,
+ "string": "0"
+ }
+ },
+ {
+ "id": 5,
+ "name": "Reallocated_Sector_Ct",
+ "value": 5,
+ "worst": 5,
+ "thresh": 36,
+ "when_failed": "now",
+ "flags": {
+ "value": 3,
+ "string": "PO--CK ",
+ "prefailure": true,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": true
+ },
+ "raw": {
+ "value": 3912,
+ "string": "3912"
+ }
+ },
+ {
+ "id": 9,
+ "name": "Power_On_Hours",
+ "value": 40,
+ "worst": 40,
+ "thresh": 0,
+ "when_failed": "",
+ "flags": {
+ "value": 50,
+ "string": "-O--CK ",
+ "prefailure": false,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": true,
+ "auto_keep": true
+ },
+ "raw": {
+ "value": 52000,
+ "string": "52000"
+ }
+ },
+ {
+ "id": 194,
+ "name": "Temperature_Celsius",
+ "value": 41,
+ "worst": 55,
+ "thresh": 0,
+ "when_failed": "",
+ "flags": {
+ "value": 50,
+ "string": "-O--CK ",
+ "prefailure": false,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": true,
+ "auto_keep": true
+ },
+ "raw": {
+ "value": 41,
+ "string": "41 (0 15 0 0 0)"
+ }
+ },
+ {
+ "id": 197,
+ "name": "Current_Pending_Sector",
+ "value": 100,
+ "worst": 100,
+ "thresh": 0,
+ "when_failed": "",
+ "flags": {
+ "value": 50,
+ "string": "-O--CK ",
+ "prefailure": false,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": true,
+ "auto_keep": true
+ },
+ "raw": {
+ "value": 24,
+ "string": "24"
+ }
+ },
+ {
+ "id": 198,
+ "name": "Offline_Uncorrectable",
+ "value": 100,
+ "worst": 100,
+ "thresh": 0,
+ "when_failed": "",
+ "flags": {
+ "value": 50,
+ "string": "-O--CK ",
+ "prefailure": false,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": true,
+ "auto_keep": true
+ },
+ "raw": {
+ "value": 24,
+ "string": "24"
+ }
+ }
+ ]
+ },
+ "power_on_time": {
+ "hours": 52000
+ },
+ "power_cycle_count": 0,
+ "temperature": {
+ "current": 41
+ },
+ "ata_smart_error_log": {
+ "summary": {
+ "revision": 1,
+ "count": 0
+ }
+ },
+ "ata_smart_self_test_log": {
+ "standard": {
+ "revision": 1,
+ "count": 0
+ }
+ },
+ "seagate_farm_log": {
+ "supported": false
+ },
+ "rotation_rate": 7200
+}
\ No newline at end of file
diff --git a/server/tests/smart/ata-qemu-health.json b/server/tests/smart/ata-qemu-health.json
new file mode 100644
index 0000000..e720263
--- /dev/null
+++ b/server/tests/smart/ata-qemu-health.json
@@ -0,0 +1,253 @@
+{
+ "json_format_version": [
+ 1,
+ 0
+ ],
+ "smartctl": {
+ "version": [
+ 7,
+ 4
+ ],
+ "pre_release": false,
+ "svn_revision": "5530",
+ "platform_info": "x86_64-linux-6.12.113+deb13-amd64",
+ "build_info": "(local build)",
+ "argv": [
+ "smartctl",
+ "-j",
+ "-n",
+ "standby",
+ "-H",
+ "-A",
+ "-c",
+ "-l",
+ "selftest",
+ "/dev/sdb"
+ ],
+ "drive_database_version": {
+ "string": "7.3/5528"
+ },
+ "exit_status": 0
+ },
+ "local_time": {
+ "time_t": 1792378099,
+ "asctime": "Sun Oct 18 23:48:19 2026 -03"
+ },
+ "device": {
+ "name": "/dev/sdb",
+ "info_name": "/dev/sdb [SAT]",
+ "type": "sat",
+ "protocol": "ATA"
+ },
+ "smart_status": {
+ "passed": true
+ },
+ "ata_smart_data": {
+ "offline_data_collection": {
+ "status": {
+ "value": 130,
+ "string": "was completed without error",
+ "passed": true
+ },
+ "completion_seconds": 288
+ },
+ "self_test": {
+ "status": {
+ "value": 0,
+ "string": "completed without error",
+ "passed": true
+ },
+ "polling_minutes": {
+ "short": 2,
+ "extended": 54
+ }
+ },
+ "capabilities": {
+ "values": [
+ 25,
+ 3
+ ],
+ "exec_offline_immediate_supported": true,
+ "offline_is_aborted_upon_new_cmd": false,
+ "offline_surface_scan_supported": true,
+ "self_tests_supported": true,
+ "conveyance_self_test_supported": false,
+ "selective_self_test_supported": false,
+ "attribute_autosave_enabled": true,
+ "error_logging_supported": true,
+ "gp_logging_supported": false
+ }
+ },
+ "ata_smart_attributes": {
+ "revision": 1,
+ "table": [
+ {
+ "id": 1,
+ "name": "Raw_Read_Error_Rate",
+ "value": 100,
+ "worst": 100,
+ "thresh": 6,
+ "when_failed": "",
+ "flags": {
+ "value": 3,
+ "string": "PO---- ",
+ "prefailure": true,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": false
+ },
+ "raw": {
+ "value": 0,
+ "string": "0"
+ }
+ },
+ {
+ "id": 3,
+ "name": "Spin_Up_Time",
+ "value": 100,
+ "worst": 100,
+ "thresh": 0,
+ "when_failed": "",
+ "flags": {
+ "value": 3,
+ "string": "PO---- ",
+ "prefailure": true,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": false
+ },
+ "raw": {
+ "value": 16,
+ "string": "16"
+ }
+ },
+ {
+ "id": 4,
+ "name": "Start_Stop_Count",
+ "value": 100,
+ "worst": 100,
+ "thresh": 20,
+ "when_failed": "",
+ "flags": {
+ "value": 2,
+ "string": "-O---- ",
+ "prefailure": false,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": false
+ },
+ "raw": {
+ "value": 100,
+ "string": "100"
+ }
+ },
+ {
+ "id": 5,
+ "name": "Reallocated_Sector_Ct",
+ "value": 100,
+ "worst": 100,
+ "thresh": 36,
+ "when_failed": "",
+ "flags": {
+ "value": 3,
+ "string": "PO---- ",
+ "prefailure": true,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": false
+ },
+ "raw": {
+ "value": 0,
+ "string": "0"
+ }
+ },
+ {
+ "id": 9,
+ "name": "Power_On_Hours",
+ "value": 100,
+ "worst": 100,
+ "thresh": 0,
+ "when_failed": "",
+ "flags": {
+ "value": 3,
+ "string": "PO---- ",
+ "prefailure": true,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": false
+ },
+ "raw": {
+ "value": 1,
+ "string": "1"
+ }
+ },
+ {
+ "id": 12,
+ "name": "Power_Cycle_Count",
+ "value": 100,
+ "worst": 100,
+ "thresh": 0,
+ "when_failed": "",
+ "flags": {
+ "value": 3,
+ "string": "PO---- ",
+ "prefailure": true,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": false
+ },
+ "raw": {
+ "value": 0,
+ "string": "0"
+ }
+ },
+ {
+ "id": 190,
+ "name": "Airflow_Temperature_Cel",
+ "value": 69,
+ "worst": 69,
+ "thresh": 50,
+ "when_failed": "",
+ "flags": {
+ "value": 3,
+ "string": "PO---- ",
+ "prefailure": true,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": false
+ },
+ "raw": {
+ "value": 522125343,
+ "string": "31 (Min/Max 31/31)"
+ }
+ }
+ ]
+ },
+ "power_on_time": {
+ "hours": 1
+ },
+ "power_cycle_count": 0,
+ "temperature": {
+ "current": 31
+ },
+ "ata_smart_self_test_log": {
+ "standard": {
+ "revision": 1,
+ "count": 0
+ }
+ }
+}
diff --git a/server/tests/smart/ata-qemu-x-selftests.json b/server/tests/smart/ata-qemu-x-selftests.json
new file mode 100644
index 0000000..8075535
--- /dev/null
+++ b/server/tests/smart/ata-qemu-x-selftests.json
@@ -0,0 +1,311 @@
+{
+ "json_format_version": [
+ 1,
+ 0
+ ],
+ "smartctl": {
+ "version": [
+ 7,
+ 4
+ ],
+ "pre_release": false,
+ "svn_revision": "5530",
+ "platform_info": "x86_64-linux-6.12.113+deb13-amd64",
+ "build_info": "(local build)",
+ "argv": [
+ "smartctl",
+ "-j",
+ "-x",
+ "/dev/sdb"
+ ],
+ "drive_database_version": {
+ "string": "7.3/5528"
+ },
+ "exit_status": 4
+ },
+ "local_time": {
+ "time_t": 1792379709,
+ "asctime": "Mon Oct 19 00:15:09 2026 -03"
+ },
+ "device": {
+ "name": "/dev/sdb",
+ "info_name": "/dev/sdb [SAT]",
+ "type": "sat",
+ "protocol": "ATA"
+ },
+ "model_name": "QEMU HARDDISK",
+ "serial_number": "QM00015",
+ "firmware_version": "2.5+",
+ "user_capacity": {
+ "blocks": 16777216,
+ "bytes": 8589934592
+ },
+ "logical_block_size": 512,
+ "physical_block_size": 512,
+ "trim": {
+ "supported": true,
+ "deterministic": true,
+ "zeroed": false
+ },
+ "in_smartctl_database": false,
+ "ata_version": {
+ "string": "ATA/ATAPI-7, ATA/ATAPI-5 published, ANSI NCITS 340-2000",
+ "major_value": 240,
+ "minor_value": 22
+ },
+ "smart_support": {
+ "available": true,
+ "enabled": true
+ },
+ "write_cache": {
+ "enabled": true
+ },
+ "smart_status": {
+ "passed": true
+ },
+ "ata_smart_data": {
+ "offline_data_collection": {
+ "status": {
+ "value": 130,
+ "string": "was completed without error",
+ "passed": true
+ },
+ "completion_seconds": 288
+ },
+ "self_test": {
+ "status": {
+ "value": 0,
+ "string": "completed without error",
+ "passed": true
+ },
+ "polling_minutes": {
+ "short": 2,
+ "extended": 54
+ }
+ },
+ "capabilities": {
+ "values": [
+ 25,
+ 3
+ ],
+ "exec_offline_immediate_supported": true,
+ "offline_is_aborted_upon_new_cmd": false,
+ "offline_surface_scan_supported": true,
+ "self_tests_supported": true,
+ "conveyance_self_test_supported": false,
+ "selective_self_test_supported": false,
+ "attribute_autosave_enabled": true,
+ "error_logging_supported": true,
+ "gp_logging_supported": false
+ }
+ },
+ "ata_smart_attributes": {
+ "revision": 1,
+ "table": [
+ {
+ "id": 1,
+ "name": "Raw_Read_Error_Rate",
+ "value": 100,
+ "worst": 100,
+ "thresh": 6,
+ "when_failed": "",
+ "flags": {
+ "value": 3,
+ "string": "PO---- ",
+ "prefailure": true,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": false
+ },
+ "raw": {
+ "value": 0,
+ "string": "0"
+ }
+ },
+ {
+ "id": 3,
+ "name": "Spin_Up_Time",
+ "value": 100,
+ "worst": 100,
+ "thresh": 0,
+ "when_failed": "",
+ "flags": {
+ "value": 3,
+ "string": "PO---- ",
+ "prefailure": true,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": false
+ },
+ "raw": {
+ "value": 16,
+ "string": "16"
+ }
+ },
+ {
+ "id": 4,
+ "name": "Start_Stop_Count",
+ "value": 100,
+ "worst": 100,
+ "thresh": 20,
+ "when_failed": "",
+ "flags": {
+ "value": 2,
+ "string": "-O---- ",
+ "prefailure": false,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": false
+ },
+ "raw": {
+ "value": 100,
+ "string": "100"
+ }
+ },
+ {
+ "id": 5,
+ "name": "Reallocated_Sector_Ct",
+ "value": 100,
+ "worst": 100,
+ "thresh": 36,
+ "when_failed": "",
+ "flags": {
+ "value": 3,
+ "string": "PO---- ",
+ "prefailure": true,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": false
+ },
+ "raw": {
+ "value": 0,
+ "string": "0"
+ }
+ },
+ {
+ "id": 9,
+ "name": "Power_On_Hours",
+ "value": 100,
+ "worst": 100,
+ "thresh": 0,
+ "when_failed": "",
+ "flags": {
+ "value": 3,
+ "string": "PO---- ",
+ "prefailure": true,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": false
+ },
+ "raw": {
+ "value": 1,
+ "string": "1"
+ }
+ },
+ {
+ "id": 12,
+ "name": "Power_Cycle_Count",
+ "value": 100,
+ "worst": 100,
+ "thresh": 0,
+ "when_failed": "",
+ "flags": {
+ "value": 3,
+ "string": "PO---- ",
+ "prefailure": true,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": false
+ },
+ "raw": {
+ "value": 0,
+ "string": "0"
+ }
+ },
+ {
+ "id": 190,
+ "name": "Airflow_Temperature_Cel",
+ "value": 69,
+ "worst": 69,
+ "thresh": 50,
+ "when_failed": "",
+ "flags": {
+ "value": 3,
+ "string": "PO---- ",
+ "prefailure": true,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": false
+ },
+ "raw": {
+ "value": 522125343,
+ "string": "31 (Min/Max 31/31)"
+ }
+ }
+ ]
+ },
+ "power_on_time": {
+ "hours": 1
+ },
+ "power_cycle_count": 0,
+ "temperature": {
+ "current": 31
+ },
+ "ata_smart_error_log": {
+ "summary": {
+ "revision": 1,
+ "count": 0
+ }
+ },
+ "ata_smart_self_test_log": {
+ "standard": {
+ "revision": 1,
+ "table": [
+ {
+ "type": {
+ "value": 1,
+ "string": "Short offline"
+ },
+ "status": {
+ "value": 0,
+ "string": "Completed without error",
+ "passed": true
+ },
+ "lifetime_hours": 4660
+ },
+ {
+ "type": {
+ "value": 1,
+ "string": "Short offline"
+ },
+ "status": {
+ "value": 0,
+ "string": "Completed without error",
+ "passed": true
+ },
+ "lifetime_hours": 4660
+ }
+ ],
+ "count": 2,
+ "error_count_total": 0,
+ "error_count_outdated": 0
+ }
+ },
+ "seagate_farm_log": {
+ "supported": false
+ }
+}
diff --git a/server/tests/smart/ata-qemu-x.json b/server/tests/smart/ata-qemu-x.json
new file mode 100644
index 0000000..a43be28
--- /dev/null
+++ b/server/tests/smart/ata-qemu-x.json
@@ -0,0 +1,283 @@
+{
+ "json_format_version": [
+ 1,
+ 0
+ ],
+ "smartctl": {
+ "version": [
+ 7,
+ 4
+ ],
+ "pre_release": false,
+ "svn_revision": "5530",
+ "platform_info": "x86_64-linux-6.12.113+deb13-amd64",
+ "build_info": "(local build)",
+ "argv": [
+ "smartctl",
+ "-j",
+ "-x",
+ "/dev/sdb"
+ ],
+ "drive_database_version": {
+ "string": "7.3/5528"
+ },
+ "exit_status": 4
+ },
+ "local_time": {
+ "time_t": 1792378099,
+ "asctime": "Sun Oct 18 23:48:19 2026 -03"
+ },
+ "device": {
+ "name": "/dev/sdb",
+ "info_name": "/dev/sdb [SAT]",
+ "type": "sat",
+ "protocol": "ATA"
+ },
+ "model_name": "QEMU HARDDISK",
+ "serial_number": "QM00015",
+ "firmware_version": "2.5+",
+ "user_capacity": {
+ "blocks": 16777216,
+ "bytes": 8589934592
+ },
+ "logical_block_size": 512,
+ "physical_block_size": 512,
+ "trim": {
+ "supported": true,
+ "deterministic": true,
+ "zeroed": false
+ },
+ "in_smartctl_database": false,
+ "ata_version": {
+ "string": "ATA/ATAPI-7, ATA/ATAPI-5 published, ANSI NCITS 340-2000",
+ "major_value": 240,
+ "minor_value": 22
+ },
+ "smart_support": {
+ "available": true,
+ "enabled": true
+ },
+ "write_cache": {
+ "enabled": true
+ },
+ "smart_status": {
+ "passed": true
+ },
+ "ata_smart_data": {
+ "offline_data_collection": {
+ "status": {
+ "value": 130,
+ "string": "was completed without error",
+ "passed": true
+ },
+ "completion_seconds": 288
+ },
+ "self_test": {
+ "status": {
+ "value": 0,
+ "string": "completed without error",
+ "passed": true
+ },
+ "polling_minutes": {
+ "short": 2,
+ "extended": 54
+ }
+ },
+ "capabilities": {
+ "values": [
+ 25,
+ 3
+ ],
+ "exec_offline_immediate_supported": true,
+ "offline_is_aborted_upon_new_cmd": false,
+ "offline_surface_scan_supported": true,
+ "self_tests_supported": true,
+ "conveyance_self_test_supported": false,
+ "selective_self_test_supported": false,
+ "attribute_autosave_enabled": true,
+ "error_logging_supported": true,
+ "gp_logging_supported": false
+ }
+ },
+ "ata_smart_attributes": {
+ "revision": 1,
+ "table": [
+ {
+ "id": 1,
+ "name": "Raw_Read_Error_Rate",
+ "value": 100,
+ "worst": 100,
+ "thresh": 6,
+ "when_failed": "",
+ "flags": {
+ "value": 3,
+ "string": "PO---- ",
+ "prefailure": true,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": false
+ },
+ "raw": {
+ "value": 0,
+ "string": "0"
+ }
+ },
+ {
+ "id": 3,
+ "name": "Spin_Up_Time",
+ "value": 100,
+ "worst": 100,
+ "thresh": 0,
+ "when_failed": "",
+ "flags": {
+ "value": 3,
+ "string": "PO---- ",
+ "prefailure": true,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": false
+ },
+ "raw": {
+ "value": 16,
+ "string": "16"
+ }
+ },
+ {
+ "id": 4,
+ "name": "Start_Stop_Count",
+ "value": 100,
+ "worst": 100,
+ "thresh": 20,
+ "when_failed": "",
+ "flags": {
+ "value": 2,
+ "string": "-O---- ",
+ "prefailure": false,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": false
+ },
+ "raw": {
+ "value": 100,
+ "string": "100"
+ }
+ },
+ {
+ "id": 5,
+ "name": "Reallocated_Sector_Ct",
+ "value": 100,
+ "worst": 100,
+ "thresh": 36,
+ "when_failed": "",
+ "flags": {
+ "value": 3,
+ "string": "PO---- ",
+ "prefailure": true,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": false
+ },
+ "raw": {
+ "value": 0,
+ "string": "0"
+ }
+ },
+ {
+ "id": 9,
+ "name": "Power_On_Hours",
+ "value": 100,
+ "worst": 100,
+ "thresh": 0,
+ "when_failed": "",
+ "flags": {
+ "value": 3,
+ "string": "PO---- ",
+ "prefailure": true,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": false
+ },
+ "raw": {
+ "value": 1,
+ "string": "1"
+ }
+ },
+ {
+ "id": 12,
+ "name": "Power_Cycle_Count",
+ "value": 100,
+ "worst": 100,
+ "thresh": 0,
+ "when_failed": "",
+ "flags": {
+ "value": 3,
+ "string": "PO---- ",
+ "prefailure": true,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": false
+ },
+ "raw": {
+ "value": 0,
+ "string": "0"
+ }
+ },
+ {
+ "id": 190,
+ "name": "Airflow_Temperature_Cel",
+ "value": 69,
+ "worst": 69,
+ "thresh": 50,
+ "when_failed": "",
+ "flags": {
+ "value": 3,
+ "string": "PO---- ",
+ "prefailure": true,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": false
+ },
+ "raw": {
+ "value": 522125343,
+ "string": "31 (Min/Max 31/31)"
+ }
+ }
+ ]
+ },
+ "power_on_time": {
+ "hours": 1
+ },
+ "power_cycle_count": 0,
+ "temperature": {
+ "current": 31
+ },
+ "ata_smart_error_log": {
+ "summary": {
+ "revision": 1,
+ "count": 0
+ }
+ },
+ "ata_smart_self_test_log": {
+ "standard": {
+ "revision": 1,
+ "count": 0
+ }
+ },
+ "seagate_farm_log": {
+ "supported": false
+ }
+}
diff --git a/server/tests/smart/ata-selftest-running.json b/server/tests/smart/ata-selftest-running.json
new file mode 100644
index 0000000..b2db243
--- /dev/null
+++ b/server/tests/smart/ata-selftest-running.json
@@ -0,0 +1,253 @@
+{
+ "json_format_version": [
+ 1,
+ 0
+ ],
+ "smartctl": {
+ "version": [
+ 7,
+ 4
+ ],
+ "pre_release": false,
+ "svn_revision": "5530",
+ "platform_info": "x86_64-linux-6.12.113+deb13-amd64",
+ "build_info": "(local build)",
+ "argv": [
+ "smartctl",
+ "-j",
+ "-n",
+ "standby",
+ "-H",
+ "-A",
+ "-c",
+ "-l",
+ "selftest",
+ "/dev/sdb"
+ ],
+ "drive_database_version": {
+ "string": "7.3/5528"
+ },
+ "exit_status": 0
+ },
+ "local_time": {
+ "time_t": 1792378099,
+ "asctime": "Sun Oct 18 23:48:19 2026 -03"
+ },
+ "device": {
+ "name": "/dev/sdb",
+ "info_name": "/dev/sdb [SAT]",
+ "type": "sat",
+ "protocol": "ATA"
+ },
+ "smart_status": {
+ "passed": true
+ },
+ "ata_smart_data": {
+ "offline_data_collection": {
+ "status": {
+ "value": 130,
+ "string": "was completed without error",
+ "passed": true
+ },
+ "completion_seconds": 288
+ },
+ "self_test": {
+ "status": {
+ "value": 249,
+ "string": "in progress, 90% remaining",
+ "remaining_percent": 90
+ },
+ "polling_minutes": {
+ "short": 2,
+ "extended": 54
+ }
+ },
+ "capabilities": {
+ "values": [
+ 25,
+ 3
+ ],
+ "exec_offline_immediate_supported": true,
+ "offline_is_aborted_upon_new_cmd": false,
+ "offline_surface_scan_supported": true,
+ "self_tests_supported": true,
+ "conveyance_self_test_supported": false,
+ "selective_self_test_supported": false,
+ "attribute_autosave_enabled": true,
+ "error_logging_supported": true,
+ "gp_logging_supported": false
+ }
+ },
+ "ata_smart_attributes": {
+ "revision": 1,
+ "table": [
+ {
+ "id": 1,
+ "name": "Raw_Read_Error_Rate",
+ "value": 100,
+ "worst": 100,
+ "thresh": 6,
+ "when_failed": "",
+ "flags": {
+ "value": 3,
+ "string": "PO---- ",
+ "prefailure": true,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": false
+ },
+ "raw": {
+ "value": 0,
+ "string": "0"
+ }
+ },
+ {
+ "id": 3,
+ "name": "Spin_Up_Time",
+ "value": 100,
+ "worst": 100,
+ "thresh": 0,
+ "when_failed": "",
+ "flags": {
+ "value": 3,
+ "string": "PO---- ",
+ "prefailure": true,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": false
+ },
+ "raw": {
+ "value": 16,
+ "string": "16"
+ }
+ },
+ {
+ "id": 4,
+ "name": "Start_Stop_Count",
+ "value": 100,
+ "worst": 100,
+ "thresh": 20,
+ "when_failed": "",
+ "flags": {
+ "value": 2,
+ "string": "-O---- ",
+ "prefailure": false,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": false
+ },
+ "raw": {
+ "value": 100,
+ "string": "100"
+ }
+ },
+ {
+ "id": 5,
+ "name": "Reallocated_Sector_Ct",
+ "value": 100,
+ "worst": 100,
+ "thresh": 36,
+ "when_failed": "",
+ "flags": {
+ "value": 3,
+ "string": "PO---- ",
+ "prefailure": true,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": false
+ },
+ "raw": {
+ "value": 0,
+ "string": "0"
+ }
+ },
+ {
+ "id": 9,
+ "name": "Power_On_Hours",
+ "value": 100,
+ "worst": 100,
+ "thresh": 0,
+ "when_failed": "",
+ "flags": {
+ "value": 3,
+ "string": "PO---- ",
+ "prefailure": true,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": false
+ },
+ "raw": {
+ "value": 1,
+ "string": "1"
+ }
+ },
+ {
+ "id": 12,
+ "name": "Power_Cycle_Count",
+ "value": 100,
+ "worst": 100,
+ "thresh": 0,
+ "when_failed": "",
+ "flags": {
+ "value": 3,
+ "string": "PO---- ",
+ "prefailure": true,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": false
+ },
+ "raw": {
+ "value": 0,
+ "string": "0"
+ }
+ },
+ {
+ "id": 190,
+ "name": "Airflow_Temperature_Cel",
+ "value": 69,
+ "worst": 69,
+ "thresh": 50,
+ "when_failed": "",
+ "flags": {
+ "value": 3,
+ "string": "PO---- ",
+ "prefailure": true,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": false
+ },
+ "raw": {
+ "value": 522125343,
+ "string": "31 (Min/Max 31/31)"
+ }
+ }
+ ]
+ },
+ "power_on_time": {
+ "hours": 1
+ },
+ "power_cycle_count": 0,
+ "temperature": {
+ "current": 31
+ },
+ "ata_smart_self_test_log": {
+ "standard": {
+ "revision": 1,
+ "count": 0
+ }
+ }
+}
\ No newline at end of file
diff --git a/server/tests/smart/ata-ssd-worn.json b/server/tests/smart/ata-ssd-worn.json
new file mode 100644
index 0000000..a0e0921
--- /dev/null
+++ b/server/tests/smart/ata-ssd-worn.json
@@ -0,0 +1,440 @@
+{
+ "json_format_version": [
+ 1,
+ 0
+ ],
+ "smartctl": {
+ "version": [
+ 7,
+ 4
+ ],
+ "pre_release": false,
+ "svn_revision": "5530",
+ "platform_info": "x86_64-linux-6.12.113+deb13-amd64",
+ "build_info": "(local build)",
+ "argv": [
+ "smartctl",
+ "-j",
+ "-x",
+ "/dev/sdb"
+ ],
+ "drive_database_version": {
+ "string": "7.3/5528"
+ },
+ "exit_status": 64
+ },
+ "local_time": {
+ "time_t": 1792378099,
+ "asctime": "Sun Oct 18 23:48:19 2026 -03"
+ },
+ "device": {
+ "name": "/dev/sdb",
+ "info_name": "/dev/sdb [SAT]",
+ "type": "sat",
+ "protocol": "ATA"
+ },
+ "model_name": "SATA SSD 512GB",
+ "serial_number": "TEST0000000001",
+ "firmware_version": "1.0",
+ "user_capacity": {
+ "blocks": 16777216,
+ "bytes": 8589934592
+ },
+ "logical_block_size": 512,
+ "physical_block_size": 512,
+ "trim": {
+ "supported": true,
+ "deterministic": true,
+ "zeroed": false
+ },
+ "in_smartctl_database": false,
+ "ata_version": {
+ "string": "ATA/ATAPI-7, ATA/ATAPI-5 published, ANSI NCITS 340-2000",
+ "major_value": 240,
+ "minor_value": 22
+ },
+ "smart_support": {
+ "available": true,
+ "enabled": true
+ },
+ "write_cache": {
+ "enabled": true
+ },
+ "smart_status": {
+ "passed": true
+ },
+ "ata_smart_data": {
+ "offline_data_collection": {
+ "status": {
+ "value": 130,
+ "string": "was completed without error",
+ "passed": true
+ },
+ "completion_seconds": 288
+ },
+ "self_test": {
+ "status": {
+ "value": 0,
+ "string": "completed without error",
+ "passed": true
+ },
+ "polling_minutes": {
+ "short": 2,
+ "extended": 54
+ }
+ },
+ "capabilities": {
+ "values": [
+ 25,
+ 3
+ ],
+ "exec_offline_immediate_supported": true,
+ "offline_is_aborted_upon_new_cmd": false,
+ "offline_surface_scan_supported": true,
+ "self_tests_supported": true,
+ "conveyance_self_test_supported": false,
+ "selective_self_test_supported": false,
+ "attribute_autosave_enabled": true,
+ "error_logging_supported": true,
+ "gp_logging_supported": false
+ }
+ },
+ "ata_smart_attributes": {
+ "revision": 1,
+ "table": [
+ {
+ "id": 5,
+ "name": "Reallocated_Sector_Ct",
+ "value": 99,
+ "worst": 99,
+ "thresh": 10,
+ "when_failed": "",
+ "flags": {
+ "value": 3,
+ "string": "PO--CK ",
+ "prefailure": true,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": true
+ },
+ "raw": {
+ "value": 8,
+ "string": "8"
+ }
+ },
+ {
+ "id": 9,
+ "name": "Power_On_Hours",
+ "value": 90,
+ "worst": 90,
+ "thresh": 0,
+ "when_failed": "",
+ "flags": {
+ "value": 50,
+ "string": "-O--CK ",
+ "prefailure": false,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": true,
+ "auto_keep": true
+ },
+ "raw": {
+ "value": 43210,
+ "string": "43210"
+ }
+ },
+ {
+ "id": 12,
+ "name": "Power_Cycle_Count",
+ "value": 99,
+ "worst": 99,
+ "thresh": 0,
+ "when_failed": "",
+ "flags": {
+ "value": 50,
+ "string": "-O--CK ",
+ "prefailure": false,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": true,
+ "auto_keep": true
+ },
+ "raw": {
+ "value": 1520,
+ "string": "1520"
+ }
+ },
+ {
+ "id": 177,
+ "name": "Wear_Leveling_Count",
+ "value": 7,
+ "worst": 7,
+ "thresh": 0,
+ "when_failed": "",
+ "flags": {
+ "value": 3,
+ "string": "PO--CK ",
+ "prefailure": true,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": false,
+ "auto_keep": true
+ },
+ "raw": {
+ "value": 2950,
+ "string": "2950"
+ }
+ },
+ {
+ "id": 190,
+ "name": "Airflow_Temperature_Cel",
+ "value": 62,
+ "worst": 45,
+ "thresh": 0,
+ "when_failed": "past",
+ "flags": {
+ "value": 50,
+ "string": "-O--CK ",
+ "prefailure": false,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": true,
+ "auto_keep": true
+ },
+ "raw": {
+ "value": 38,
+ "string": "38 (Min/Max 18/55)"
+ }
+ },
+ {
+ "id": 197,
+ "name": "Current_Pending_Sector",
+ "value": 100,
+ "worst": 100,
+ "thresh": 0,
+ "when_failed": "",
+ "flags": {
+ "value": 50,
+ "string": "-O--CK ",
+ "prefailure": false,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": true,
+ "auto_keep": true
+ },
+ "raw": {
+ "value": 2,
+ "string": "2"
+ }
+ },
+ {
+ "id": 198,
+ "name": "Offline_Uncorrectable",
+ "value": 100,
+ "worst": 100,
+ "thresh": 0,
+ "when_failed": "",
+ "flags": {
+ "value": 50,
+ "string": "-O--CK ",
+ "prefailure": false,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": true,
+ "auto_keep": true
+ },
+ "raw": {
+ "value": 0,
+ "string": "0"
+ }
+ },
+ {
+ "id": 199,
+ "name": "UDMA_CRC_Error_Count",
+ "value": 100,
+ "worst": 100,
+ "thresh": 0,
+ "when_failed": "",
+ "flags": {
+ "value": 50,
+ "string": "-O--CK ",
+ "prefailure": false,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": true,
+ "auto_keep": true
+ },
+ "raw": {
+ "value": 0,
+ "string": "0"
+ }
+ },
+ {
+ "id": 241,
+ "name": "Total_LBAs_Written",
+ "value": 99,
+ "worst": 99,
+ "thresh": 0,
+ "when_failed": "",
+ "flags": {
+ "value": 50,
+ "string": "-O--CK ",
+ "prefailure": false,
+ "updated_online": true,
+ "performance": false,
+ "error_rate": false,
+ "event_count": true,
+ "auto_keep": true
+ },
+ "raw": {
+ "value": 93750000000,
+ "string": "93750000000"
+ }
+ }
+ ]
+ },
+ "power_on_time": {
+ "hours": 43210
+ },
+ "power_cycle_count": 1520,
+ "temperature": {
+ "current": 38,
+ "power_cycle_min": 24,
+ "power_cycle_max": 41,
+ "lifetime_min": 18,
+ "lifetime_max": 55
+ },
+ "ata_smart_error_log": {
+ "extended": {
+ "revision": 1,
+ "sectors": 1,
+ "count": 2,
+ "table": [
+ {
+ "error_number": 2,
+ "lifetime_hours": 43100,
+ "completion_registers": {
+ "error": 64,
+ "status": 81,
+ "count": 0,
+ "lba": 123456,
+ "device": 64
+ },
+ "error_description": "Error: UNC at LBA = 0x0001e240 = 123456",
+ "previous_commands": []
+ },
+ {
+ "error_number": 1,
+ "lifetime_hours": 42990,
+ "completion_registers": {
+ "error": 64,
+ "status": 81,
+ "count": 0,
+ "lba": 123456,
+ "device": 64
+ },
+ "error_description": "Error: UNC at LBA = 0x0001e240 = 123456",
+ "previous_commands": []
+ }
+ ]
+ }
+ },
+ "ata_smart_self_test_log": {
+ "extended": {
+ "revision": 1,
+ "sectors": 1,
+ "table": [
+ {
+ "type": {
+ "value": 2,
+ "string": "Extended offline"
+ },
+ "status": {
+ "value": 121,
+ "string": "Completed: read failure",
+ "remaining_percent": 90,
+ "passed": false
+ },
+ "lifetime_hours": 43150,
+ "lba": 123456
+ },
+ {
+ "type": {
+ "value": 1,
+ "string": "Short offline"
+ },
+ "status": {
+ "value": 0,
+ "string": "Completed without error",
+ "passed": true
+ },
+ "lifetime_hours": 43000
+ }
+ ],
+ "count": 2,
+ "error_count_total": 1,
+ "error_count_outdated": 0
+ }
+ },
+ "seagate_farm_log": {
+ "supported": false
+ },
+ "rotation_rate": 0,
+ "ata_sct_temperature_history": {
+ "version": 2,
+ "sampling_period_minutes": 1,
+ "logging_interval_minutes": 1,
+ "temperature": {
+ "op_limit_min": 0,
+ "op_limit_max": 70,
+ "limit_min": -5,
+ "limit_max": 75
+ },
+ "size": 8,
+ "index": 3,
+ "table": [
+ 35,
+ 36,
+ null,
+ 37,
+ 38,
+ 38,
+ 37,
+ 38
+ ]
+ },
+ "ata_device_statistics": {
+ "pages": [
+ {
+ "number": 7,
+ "name": "Solid State Device Statistics",
+ "revision": 1,
+ "table": [
+ {
+ "offset": 8,
+ "name": "Percentage Used Endurance Indicator",
+ "size": 1,
+ "value": 93,
+ "flags": {
+ "value": 192,
+ "string": "N--- ",
+ "valid": true,
+ "normalized": true,
+ "supports_dsn": false,
+ "monitored_condition_met": false
+ }
+ }
+ ]
+ }
+ ]
+ }
+}
\ No newline at end of file
diff --git a/server/tests/smart/ata-standby.json b/server/tests/smart/ata-standby.json
new file mode 100644
index 0000000..84fc874
--- /dev/null
+++ b/server/tests/smart/ata-standby.json
@@ -0,0 +1,45 @@
+{
+ "json_format_version": [
+ 1,
+ 0
+ ],
+ "smartctl": {
+ "version": [
+ 7,
+ 4
+ ],
+ "pre_release": false,
+ "svn_revision": "5530",
+ "platform_info": "x86_64-linux-6.12.113+deb13-amd64",
+ "build_info": "(local build)",
+ "argv": [
+ "smartctl",
+ "-j",
+ "-n",
+ "standby",
+ "-H",
+ "-A",
+ "-c",
+ "-l",
+ "selftest",
+ "/dev/sdb"
+ ],
+ "messages": [
+ {
+ "string": "Device is in STANDBY mode, exit(2)",
+ "severity": "information"
+ }
+ ],
+ "exit_status": 2
+ },
+ "local_time": {
+ "time_t": 1792378099,
+ "asctime": "Sun Oct 18 23:48:19 2026 -03"
+ },
+ "device": {
+ "name": "/dev/sdb",
+ "info_name": "/dev/sdb [SAT]",
+ "type": "sat",
+ "protocol": "ATA"
+ }
+}
\ No newline at end of file
diff --git a/server/tests/smart/ata-test-started.json b/server/tests/smart/ata-test-started.json
new file mode 100644
index 0000000..b6184ab
--- /dev/null
+++ b/server/tests/smart/ata-test-started.json
@@ -0,0 +1,37 @@
+{
+ "json_format_version": [
+ 1,
+ 0
+ ],
+ "smartctl": {
+ "version": [
+ 7,
+ 4
+ ],
+ "pre_release": false,
+ "svn_revision": "5530",
+ "platform_info": "x86_64-linux-6.12.113+deb13-amd64",
+ "build_info": "(local build)",
+ "argv": [
+ "smartctl",
+ "-j",
+ "-t",
+ "short",
+ "/dev/sdb"
+ ],
+ "drive_database_version": {
+ "string": "7.3/5528"
+ },
+ "exit_status": 0
+ },
+ "local_time": {
+ "time_t": 1792378099,
+ "asctime": "Sun Oct 18 23:48:19 2026 -03"
+ },
+ "device": {
+ "name": "/dev/sdb",
+ "info_name": "/dev/sdb [SAT]",
+ "type": "sat",
+ "protocol": "ATA"
+ }
+}
diff --git a/server/tests/smart/nvme-failing-testing.json b/server/tests/smart/nvme-failing-testing.json
new file mode 100644
index 0000000..63039a3
--- /dev/null
+++ b/server/tests/smart/nvme-failing-testing.json
@@ -0,0 +1,201 @@
+{
+ "json_format_version": [
+ 1,
+ 0
+ ],
+ "smartctl": {
+ "version": [
+ 7,
+ 4
+ ],
+ "pre_release": false,
+ "svn_revision": "5530",
+ "platform_info": "aarch64-linux-6.18.57-lordos-rpi-2712",
+ "build_info": "(local build)",
+ "argv": [
+ "smartctl",
+ "-j",
+ "-x",
+ "/dev/nvme0n1"
+ ],
+ "exit_status": 0
+ },
+ "local_time": {
+ "time_t": 1792378099,
+ "asctime": "Sun Oct 18 23:48:19 2026 -03"
+ },
+ "device": {
+ "name": "/dev/nvme0n1",
+ "info_name": "/dev/nvme0n1",
+ "type": "nvme",
+ "protocol": "NVMe"
+ },
+ "model_name": "M.2 NVMe SSD 1TB",
+ "serial_number": "TEST0000000003",
+ "firmware_version": "2B2QEXM7",
+ "nvme_pci_vendor": {
+ "id": 5197,
+ "subsystem_id": 5197
+ },
+ "nvme_ieee_oui_identifier": 9528,
+ "nvme_total_capacity": 1000204886016,
+ "nvme_unallocated_capacity": 0,
+ "nvme_controller_id": 6,
+ "nvme_version": {
+ "string": "1.4",
+ "value": 66560
+ },
+ "nvme_number_of_namespaces": 1,
+ "nvme_namespaces": [
+ {
+ "id": 1,
+ "size": {
+ "blocks": 1953525168,
+ "bytes": 1000204886016
+ },
+ "capacity": {
+ "blocks": 1953525168,
+ "bytes": 1000204886016
+ },
+ "utilization": {
+ "blocks": 402653184,
+ "bytes": 206158430208
+ },
+ "formatted_lba_size": 512,
+ "eui64": {
+ "oui": 9528,
+ "ext_id": 1234567890
+ }
+ }
+ ],
+ "user_capacity": {
+ "blocks": 1953525168,
+ "bytes": 1000204886016
+ },
+ "logical_block_size": 512,
+ "smart_support": {
+ "available": true,
+ "enabled": true
+ },
+ "nvme_firmware_update_capabilities": {
+ "value": 22,
+ "slots": 3,
+ "first_slot_is_read_only": false,
+ "activiation_without_reset": true,
+ "multiple_update_detection": false,
+ "other": 0
+ },
+ "nvme_optional_admin_commands": {
+ "value": 23,
+ "security_send_receive": true,
+ "format_nvm": true,
+ "firmware_download": true,
+ "namespace_management": false,
+ "self_test": true,
+ "directives": false,
+ "mi_send_receive": false,
+ "virtualization_management": false,
+ "doorbell_buffer_config": false,
+ "get_lba_status": false,
+ "command_and_feature_lockdown": false
+ },
+ "nvme_power_states": [
+ {
+ "non_operational_state": false,
+ "relative_read_latency": 0,
+ "relative_read_throughput": 0,
+ "relative_write_latency": 0,
+ "relative_write_throughput": 0,
+ "entry_latency_us": 0,
+ "exit_latency_us": 0,
+ "max_power": {
+ "value": 690,
+ "scale": 2,
+ "units_per_watt": 100
+ }
+ }
+ ],
+ "smart_status": {
+ "passed": false,
+ "nvme": {
+ "value": 5
+ }
+ },
+ "nvme_smart_health_information_log": {
+ "critical_warning": 5,
+ "temperature": 41,
+ "available_spare": 4,
+ "available_spare_threshold": 10,
+ "percentage_used": 104,
+ "data_units_read": 12345678,
+ "data_units_written": 23456789,
+ "host_reads": 234567890,
+ "host_writes": 345678901,
+ "controller_busy_time": 1234,
+ "power_cycles": 812,
+ "power_on_hours": 5021,
+ "unsafe_shutdowns": 37,
+ "media_errors": 3,
+ "num_err_log_entries": 12,
+ "warning_temp_time": 0,
+ "critical_comp_time": 0,
+ "temperature_sensors": [
+ 41,
+ 47
+ ]
+ },
+ "temperature": {
+ "current": 41,
+ "op_limit_max": 82,
+ "critical_limit_max": 85
+ },
+ "power_cycle_count": 812,
+ "power_on_time": {
+ "hours": 5021
+ },
+ "nvme_error_information_log": {
+ "size": 64,
+ "read": 16,
+ "unread": 0,
+ "table": [
+ {
+ "error_count": 12,
+ "submission_queue_id": 0,
+ "command_id": 4105,
+ "status_field": {
+ "value": 8194,
+ "do_not_retry": true,
+ "status_code_type": 0,
+ "status_code": 2,
+ "string": "Invalid Field in Command"
+ },
+ "phase_tag": false,
+ "parm_error_location": 40,
+ "lba": {
+ "value": 0
+ },
+ "nsid": 0
+ }
+ ]
+ },
+ "nvme_self_test_log": {
+ "current_self_test_operation": {
+ "value": 2,
+ "string": "Extended self-test in progress"
+ },
+ "table": [
+ {
+ "self_test_code": {
+ "value": 1,
+ "string": "Short"
+ },
+ "self_test_result": {
+ "value": 0,
+ "string": "Completed without error"
+ },
+ "power_on_hours": 5000
+ }
+ ],
+ "current_self_test_completion_percent": 35
+ }
+}
\ No newline at end of file
diff --git a/server/tests/smart/nvme-x.json b/server/tests/smart/nvme-x.json
new file mode 100644
index 0000000..ec2644e
--- /dev/null
+++ b/server/tests/smart/nvme-x.json
@@ -0,0 +1,200 @@
+{
+ "json_format_version": [
+ 1,
+ 0
+ ],
+ "smartctl": {
+ "version": [
+ 7,
+ 4
+ ],
+ "pre_release": false,
+ "svn_revision": "5530",
+ "platform_info": "aarch64-linux-6.18.57-lordos-rpi-2712",
+ "build_info": "(local build)",
+ "argv": [
+ "smartctl",
+ "-j",
+ "-x",
+ "/dev/nvme0n1"
+ ],
+ "exit_status": 0
+ },
+ "local_time": {
+ "time_t": 1792378099,
+ "asctime": "Sun Oct 18 23:48:19 2026 -03"
+ },
+ "device": {
+ "name": "/dev/nvme0n1",
+ "info_name": "/dev/nvme0n1",
+ "type": "nvme",
+ "protocol": "NVMe"
+ },
+ "model_name": "M.2 NVMe SSD 1TB",
+ "serial_number": "TEST0000000003",
+ "firmware_version": "2B2QEXM7",
+ "nvme_pci_vendor": {
+ "id": 5197,
+ "subsystem_id": 5197
+ },
+ "nvme_ieee_oui_identifier": 9528,
+ "nvme_total_capacity": 1000204886016,
+ "nvme_unallocated_capacity": 0,
+ "nvme_controller_id": 6,
+ "nvme_version": {
+ "string": "1.4",
+ "value": 66560
+ },
+ "nvme_number_of_namespaces": 1,
+ "nvme_namespaces": [
+ {
+ "id": 1,
+ "size": {
+ "blocks": 1953525168,
+ "bytes": 1000204886016
+ },
+ "capacity": {
+ "blocks": 1953525168,
+ "bytes": 1000204886016
+ },
+ "utilization": {
+ "blocks": 402653184,
+ "bytes": 206158430208
+ },
+ "formatted_lba_size": 512,
+ "eui64": {
+ "oui": 9528,
+ "ext_id": 1234567890
+ }
+ }
+ ],
+ "user_capacity": {
+ "blocks": 1953525168,
+ "bytes": 1000204886016
+ },
+ "logical_block_size": 512,
+ "smart_support": {
+ "available": true,
+ "enabled": true
+ },
+ "nvme_firmware_update_capabilities": {
+ "value": 22,
+ "slots": 3,
+ "first_slot_is_read_only": false,
+ "activiation_without_reset": true,
+ "multiple_update_detection": false,
+ "other": 0
+ },
+ "nvme_optional_admin_commands": {
+ "value": 23,
+ "security_send_receive": true,
+ "format_nvm": true,
+ "firmware_download": true,
+ "namespace_management": false,
+ "self_test": true,
+ "directives": false,
+ "mi_send_receive": false,
+ "virtualization_management": false,
+ "doorbell_buffer_config": false,
+ "get_lba_status": false,
+ "command_and_feature_lockdown": false
+ },
+ "nvme_power_states": [
+ {
+ "non_operational_state": false,
+ "relative_read_latency": 0,
+ "relative_read_throughput": 0,
+ "relative_write_latency": 0,
+ "relative_write_throughput": 0,
+ "entry_latency_us": 0,
+ "exit_latency_us": 0,
+ "max_power": {
+ "value": 690,
+ "scale": 2,
+ "units_per_watt": 100
+ }
+ }
+ ],
+ "smart_status": {
+ "passed": true,
+ "nvme": {
+ "value": 0
+ }
+ },
+ "nvme_smart_health_information_log": {
+ "critical_warning": 0,
+ "temperature": 41,
+ "available_spare": 100,
+ "available_spare_threshold": 10,
+ "percentage_used": 3,
+ "data_units_read": 12345678,
+ "data_units_written": 23456789,
+ "host_reads": 234567890,
+ "host_writes": 345678901,
+ "controller_busy_time": 1234,
+ "power_cycles": 812,
+ "power_on_hours": 5021,
+ "unsafe_shutdowns": 37,
+ "media_errors": 0,
+ "num_err_log_entries": 12,
+ "warning_temp_time": 0,
+ "critical_comp_time": 0,
+ "temperature_sensors": [
+ 41,
+ 47
+ ]
+ },
+ "temperature": {
+ "current": 41,
+ "op_limit_max": 82,
+ "critical_limit_max": 85
+ },
+ "power_cycle_count": 812,
+ "power_on_time": {
+ "hours": 5021
+ },
+ "nvme_error_information_log": {
+ "size": 64,
+ "read": 16,
+ "unread": 0,
+ "table": [
+ {
+ "error_count": 12,
+ "submission_queue_id": 0,
+ "command_id": 4105,
+ "status_field": {
+ "value": 8194,
+ "do_not_retry": true,
+ "status_code_type": 0,
+ "status_code": 2,
+ "string": "Invalid Field in Command"
+ },
+ "phase_tag": false,
+ "parm_error_location": 40,
+ "lba": {
+ "value": 0
+ },
+ "nsid": 0
+ }
+ ]
+ },
+ "nvme_self_test_log": {
+ "current_self_test_operation": {
+ "value": 0,
+ "string": "No self-test in progress"
+ },
+ "table": [
+ {
+ "self_test_code": {
+ "value": 1,
+ "string": "Short"
+ },
+ "self_test_result": {
+ "value": 0,
+ "string": "Completed without error"
+ },
+ "power_on_hours": 5000
+ }
+ ]
+ }
+}
\ No newline at end of file
diff --git a/server/tests/smart/scsi-qemu-x.json b/server/tests/smart/scsi-qemu-x.json
new file mode 100644
index 0000000..73c3685
--- /dev/null
+++ b/server/tests/smart/scsi-qemu-x.json
@@ -0,0 +1,71 @@
+{
+ "json_format_version": [
+ 1,
+ 0
+ ],
+ "smartctl": {
+ "version": [
+ 7,
+ 4
+ ],
+ "pre_release": false,
+ "svn_revision": "5530",
+ "platform_info": "x86_64-linux-6.12.113+deb13-amd64",
+ "build_info": "(local build)",
+ "argv": [
+ "smartctl",
+ "-j",
+ "-x",
+ "/dev/sda"
+ ],
+ "exit_status": 4
+ },
+ "local_time": {
+ "time_t": 1792378099,
+ "asctime": "Sun Oct 18 23:48:19 2026 -03"
+ },
+ "device": {
+ "name": "/dev/sda",
+ "info_name": "/dev/sda",
+ "type": "scsi",
+ "protocol": "SCSI"
+ },
+ "scsi_vendor": "QEMU",
+ "scsi_product": "QEMU HARDDISK",
+ "scsi_model_name": "QEMU QEMU HARDDISK",
+ "scsi_revision": "2.5+",
+ "scsi_version": "SPC-3",
+ "user_capacity": {
+ "blocks": 67108864,
+ "bytes": 34359738368
+ },
+ "logical_block_size": 512,
+ "scsi_lb_provisioning": {
+ "name": "thin provisioned",
+ "value": 2,
+ "management_enabled": {
+ "name": "LBPME",
+ "value": -1
+ },
+ "read_zeros": {
+ "name": "LBPRZ",
+ "value": 0
+ }
+ },
+ "rotation_rate": 0,
+ "device_type": {
+ "scsi_terminology": "Peripheral Device Type [PDT]",
+ "scsi_value": 0,
+ "name": "disk"
+ },
+ "smart_support": {
+ "available": false
+ },
+ "temperature": {
+ "current": 0,
+ "drive_trip": 0
+ },
+ "seagate_farm_log": {
+ "supported": false
+ }
+}
diff --git a/server/tests/smart/usb-sat-nodata.json b/server/tests/smart/usb-sat-nodata.json
new file mode 100644
index 0000000..2dfb271
--- /dev/null
+++ b/server/tests/smart/usb-sat-nodata.json
@@ -0,0 +1,35 @@
+{
+ "json_format_version": [
+ 1,
+ 0
+ ],
+ "smartctl": {
+ "version": [
+ 7,
+ 4
+ ],
+ "pre_release": false,
+ "svn_revision": "5530",
+ "platform_info": "x86_64-linux-6.12.113+deb13-amd64",
+ "build_info": "(local build)",
+ "argv": [
+ "smartctl",
+ "-j",
+ "-x",
+ "-d",
+ "sat",
+ "/dev/sdc"
+ ],
+ "exit_status": 2
+ },
+ "local_time": {
+ "time_t": 1792378115,
+ "asctime": "Sun Oct 18 23:48:35 2026 -03"
+ },
+ "device": {
+ "name": "/dev/sdc",
+ "info_name": "/dev/sdc [SAT]",
+ "type": "sat",
+ "protocol": "ATA"
+ }
+}
diff --git a/server/tests/smart/usb-unknown-bridge.json b/server/tests/smart/usb-unknown-bridge.json
new file mode 100644
index 0000000..f269bd2
--- /dev/null
+++ b/server/tests/smart/usb-unknown-bridge.json
@@ -0,0 +1,33 @@
+{
+ "json_format_version": [
+ 1,
+ 0
+ ],
+ "smartctl": {
+ "version": [
+ 7,
+ 4
+ ],
+ "pre_release": false,
+ "svn_revision": "5530",
+ "platform_info": "x86_64-linux-6.12.113+deb13-amd64",
+ "build_info": "(local build)",
+ "argv": [
+ "smartctl",
+ "-j",
+ "-x",
+ "/dev/sdc"
+ ],
+ "messages": [
+ {
+ "string": "/dev/sdc: Unknown USB bridge [0x0525:0xa4a5 (0x612)]",
+ "severity": "error"
+ }
+ ],
+ "exit_status": 1
+ },
+ "local_time": {
+ "time_t": 1792378099,
+ "asctime": "Sun Oct 18 23:48:19 2026 -03"
+ }
+}
diff --git a/server/tests/smart_parse_test.mjs b/server/tests/smart_parse_test.mjs
new file mode 100644
index 0000000..b4b6ee1
--- /dev/null
+++ b/server/tests/smart_parse_test.mjs
@@ -0,0 +1,146 @@
+// smart_parse_test.mjs — smartctl JSON → the Disks/Monitor model (sdk/smartparse.js).
+//
+// Fixtures in tests/smart/:
+// real smartctl 7.4 output captured on VM 119 (Debian 13):
+// ata-qemu-x.json (smartctl -j -x, QEMU SATA disk), ata-qemu-health.json (the smart-health
+// command), scsi-qemu-x.json (virtio-scsi disk: no SMART), usb-unknown-bridge.json (a USB
+// gadget smartctl does not know), usb-sat-nodata.json (the same retried with -d sat),
+// ata-test-started.json (smartctl -j -t short), ata-qemu-x-selftests.json (the same disk after
+// two short self-tests run from the Disks app: the self-test log)
+// the same smartctl 7.4 schema with edited values (no such drive on the test machines):
+// ata-ssd-worn.json, ata-hdd-failing.json, ata-selftest-running.json, ata-standby.json,
+// nvme-x.json, nvme-failing-testing.json
+//
+// node tests/smart_parse_test.mjs (from server/; run_suites.sh runs it when node exists)
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+const { parseSmartctl, summarize, summaryFromOwn, prettyAttrName, ATTR_KEYS, HEALTH_RANK } = await import(path.join(here, '../../sdk/smartparse.js'));
+const load = (f) => JSON.parse(fs.readFileSync(path.join(here, 'smart', f), 'utf8'));
+
+let n = 0, bad = 0;
+const eq = (name, got, want) => {
+ n++;
+ const g = JSON.stringify(got), w = JSON.stringify(want);
+ if (g !== w) { bad++; console.log(`✗ ${name}: want ${w}, got ${g}`); }
+};
+
+// ---- real: QEMU SATA disk, full report ----
+let m = parseSmartctl(load('ata-qemu-x.json'));
+eq('qemu kind', m.kind, 'ata');
+eq('qemu model', m.model, 'QEMU HARDDISK');
+eq('qemu serial', m.serial, 'QM00015');
+eq('qemu supported', m.supported, true);
+eq('qemu passed', m.passed, true);
+eq('qemu health', m.health, 'ok');
+eq('qemu reasons', m.reasons, []);
+eq('qemu temp', m.temp, 31);
+eq('qemu hours', m.hours, 1);
+eq('qemu cycles', m.cycles, 0);
+eq('qemu reallocated', m.reallocated, 0);
+eq('qemu pending (absent)', m.pending, null);
+eq('qemu attrs', m.attrs.map((a) => a.id), [1, 3, 4, 5, 9, 12, 190]);
+eq('qemu attr names', m.attrs.map((a) => a.key), ['a1', 'a3', 'a4', 'a5', 'a9', 'a12', 'a190']);
+eq('qemu attr 190 raw string', m.attrs[6].raw, '31 (Min/Max 31/31)');
+eq('qemu attr 190 count', m.attrs[6].count, 31);
+eq('qemu prefail', m.attrs[0].prefail, true);
+eq('qemu errors', m.errors, { count: 0, list: [] });
+eq('qemu self-test', [m.selfTest.supported, m.selfTest.running, m.selfTest.polling.short, m.selfTest.polling.long], [true, false, 2, 54]);
+eq('qemu self-tests', m.selfTests, []);
+eq('qemu no wear (a disk)', m.wear, null);
+eq('qemu no history', m.tempHistory, null);
+eq('qemu exit', m.exit, 4);
+eq('qemu standby', m.standby, false);
+
+// ---- real: after two short self-tests ----
+m = parseSmartctl(load('ata-qemu-x-selftests.json'));
+eq('self-test log', m.selfTests.map((x) => [x.type, x.passed, x.hours, x.result]), [['short', true, 4660, 'Completed without error'], ['short', true, 4660, 'Completed without error']]);
+eq('self-test log health', m.health, 'ok');
+
+// ---- real: the smart-health command on the same disk ----
+m = parseSmartctl(load('ata-qemu-health.json'));
+eq('health cmd', [m.health, m.temp, m.hours, m.attrs.length, m.selfTest.running], ['ok', 31, 1, 7, false]);
+eq('summary', summarize(m, 5), { health: 'ok', reasons: [], temp: 31, wear: null, hours: 1, standby: false, supported: true, t: 5 });
+
+// ---- real: virtio-scsi disk, USB bridges ----
+m = parseSmartctl(load('scsi-qemu-x.json'));
+eq('scsi kind', m.kind, 'scsi');
+eq('scsi unsupported', m.supported, false);
+eq('scsi temp 0 is no value', m.temp, null);
+eq('scsi health unknown', m.health, 'unknown');
+eq('scsi model', m.model, 'QEMU QEMU HARDDISK');
+m = parseSmartctl(load('usb-unknown-bridge.json'));
+eq('usb bridge', [m.kind, m.supported, m.health], [null, false, 'unknown']);
+eq('usb bridge message', m.messages[0].text, '/dev/sdc: Unknown USB bridge [0x0525:0xa4a5 (0x612)]');
+m = parseSmartctl(load('usb-sat-nodata.json'));
+eq('usb sat no data', [m.kind, m.supported, m.health, m.exit], ['ata', false, 'unknown', 2]);
+m = parseSmartctl(load('ata-test-started.json'));
+eq('test started', [m.exit, m.messages.length], [0, 0]);
+
+// ---- edited: worn SSD with reallocated and pending sectors ----
+m = parseSmartctl(load('ata-ssd-worn.json'));
+eq('worn health', m.health, 'warning');
+eq('worn reasons', m.reasons, ['reallocated', 'pending', 'worn']);
+eq('worn wear from device statistics', m.wear, { used: 93, source: 'devstat' });
+eq('worn counts', [m.reallocated, m.pending, m.uncorrectable, m.hours, m.cycles], [8, 2, 0, 43210, 1520]);
+eq('worn written', m.written, 93750000000 * 512);
+eq('worn temp limits', [m.temp, m.tempMax, m.tempCrit], [38, 70, 75]);
+eq('worn history', m.tempHistory, { interval: 1, values: [35, 36, null, 37, 38, 38, 37, 38] });
+eq('worn errors', [m.errors.count, m.errors.list.length, m.errors.list[0].hours], [2, 2, 43100]);
+eq('worn self-tests', m.selfTests.map((x) => [x.type, x.passed, x.hours]), [['long', false, 43150], ['short', true, 43000]]);
+eq('past old-age failure is not a warning', m.reasons.includes('oldAgeNow'), false);
+const noStats = load('ata-ssd-worn.json');
+delete noStats.ata_device_statistics;
+eq('wear from attribute 177', parseSmartctl(noStats).wear, { used: 93, source: 'attr177' });
+
+// ---- edited: failing disk ----
+m = parseSmartctl(load('ata-hdd-failing.json'));
+eq('failing', m.health, 'failing');
+eq('failing reasons', m.reasons, ['smartFailed', 'prefailNow', 'reallocated', 'pending', 'uncorrectable']);
+eq('failing attr flagged', m.attrs.find((a) => a.id === 5).failed, 'now');
+eq('failing temp 194 name', m.attrs.find((a) => a.id === 194).key, 'a194');
+
+// ---- edited: self-test running, resting disk ----
+m = parseSmartctl(load('ata-selftest-running.json'));
+eq('running', [m.selfTest.running, m.selfTest.remaining], [true, 90]);
+m = parseSmartctl(load('ata-standby.json'));
+eq('standby', [m.standby, m.health, m.supported], [true, 'unknown', false]);
+
+// ---- edited: NVMe ----
+m = parseSmartctl(load('nvme-x.json'));
+eq('nvme kind', m.kind, 'nvme');
+eq('nvme health', m.health, 'ok');
+eq('nvme temp + limits', [m.temp, m.tempMax, m.tempCrit], [41, 82, 85]);
+eq('nvme wear', m.wear, { used: 3, source: 'nvme' });
+eq('nvme hours, cycles', [m.hours, m.cycles], [5021, 812]);
+eq('nvme bytes', [m.read, m.written], [12345678 * 512000, 23456789 * 512000]);
+eq('nvme log', [m.nvme.spare, m.nvme.spareThreshold, m.nvme.unsafeShutdowns, m.nvme.mediaErrors, m.nvme.sensors], [100, 10, 37, 0, [41, 47]]);
+eq('nvme errors (benign entries do not change health)', [m.errors.count, m.errors.list[0].text], [12, 'Invalid Field in Command']);
+eq('nvme self-test', [m.selfTest.supported, m.selfTest.running], [true, false]);
+eq('nvme self-tests', m.selfTests.map((x) => [x.type, x.passed, x.resultKey]), [['short', true, 'completed']]);
+m = parseSmartctl(load('nvme-failing-testing.json'));
+eq('nvme failing', m.health, 'failing');
+eq('nvme failing reasons', m.reasons, ['smartFailed', 'nvmeReliability', 'nvmeSpare', 'mediaErrors', 'worn']);
+eq('nvme test progress', [m.selfTest.running, m.selfTest.remaining], [true, 65]);
+
+// ---- hostile input: nothing breaks, nothing is invented ----
+for (const junk of [null, 42, 'x', [], {}, { smartctl: 7 }, { ata_smart_attributes: { table: [{ id: 'x' }, { id: 300 }, null] } },
+ { nvme_smart_health_information_log: { temperature: 'hot' } }, { temperature: { current: 9999 } }]) {
+ const r = parseSmartctl(junk);
+ eq(`junk ${JSON.stringify(junk)} health`, ['unknown', 'ok'].includes(r.health), true);
+ eq(`junk ${JSON.stringify(junk)} temp`, r.temp, null);
+}
+const long = parseSmartctl({ device: { protocol: 'ATA' }, model_name: 'x'.repeat(5000) });
+eq('long strings cut', long.model.length, 80);
+
+// ---- helpers ----
+eq('pretty name', prettyAttrName('Unknown_SSD_Attribute'), 'Unknown SSD Attribute');
+eq('keys are a<id>', ATTR_KEYS.every((k) => /^a\d{1,3}$/.test(k)), true);
+eq('rank', HEALTH_RANK.failing > HEALTH_RANK.warning && HEALTH_RANK.warning > HEALTH_RANK.ok, true);
+eq('own reader summary', summaryFromOwn({ kind: 'ata', health: 'warning', temp: 40, hours: 10 }, 1), { health: 'warning', reasons: [], temp: 40, wear: null, hours: 10, standby: false, supported: true, t: 1 });
+eq('own reader nothing', summaryFromOwn(null), null);
+
+console.log(`smart-parse-test: ${n} checks, ${bad} failures`);
+process.exit(bad ? 1 : 0);
diff --git a/server/tests/smartctl_test.c b/server/tests/smartctl_test.c
new file mode 100644
index 0000000..93d6e22
--- /dev/null
+++ b/server/tests/smartctl_test.c
@@ -0,0 +1,39 @@
+/* smartctl_test.c — the smart-* actions' pure helpers (src/disk/smartctl.c): which device names
+ * reach smartctl, the JSON compaction and the LOG pieces.
+ *
+ * make -C server build/smartctl-test && ./server/build/smartctl-test (in `make test`) */
+#include "../src/disk/disk.h"
+
+#include <stdio.h>
+#include <string.h>
+
+static int fails, checks;
+#define CHECK(c, ...) do { checks++; if (!(c)) { fails++; printf("✗ " __VA_ARGS__); printf("\n"); } } while (0)
+
+int main(void) {
+ const char *good[] = { "sda", "sdb", "sdz", "sdaa", "sdzzz", "hda", "nvme0n1", "nvme1n1", "nvme12n3", "nvme0n128" };
+ for (size_t i = 0; i < sizeof good / sizeof *good; i++) CHECK(smartctl_valid_disk(good[i]), "accepts %s", good[i]);
+ const char *bad[] = { "", "sd", "sda1", "sdA", "sdaaaa", "nvme0", "nvme0n0", "nvme0n1p1", "nvme00n1", "nvme0n01", "nvmen1",
+ "nvme1234n1", "nvme0n1234", "loop0", "dm-0", "md0", "zram0", "mmcblk0", "mmcblk0p1", "sr0", "vda", "xvda", "../sda",
+ "sda/", "/dev/sda", "sda ", " sda", "sd-a", "sda\n", "nvme0n1\n", "hd1", "sdá" };
+ for (size_t i = 0; i < sizeof bad / sizeof *bad; i++) CHECK(!smartctl_valid_disk(bad[i]), "refuses \"%s\"", bad[i]);
+ CHECK(!smartctl_valid_disk(NULL), "refuses NULL");
+
+ /* compaction keeps strings (spaces, escapes, an escaped quote) and drops the rest */
+ char j[] = "{\n \"model_name\": \"QEMU HARDDISK\",\n \"x\": [\n 1,\n 2\n ],\n \"s\": \"a \\\"b\\\" \\\\ c\"\t}\n";
+ size_t n = smartctl_compact(j, strlen(j));
+ const char *want = "{\"model_name\":\"QEMU HARDDISK\",\"x\":[1,2],\"s\":\"a \\\"b\\\" \\\\ c\"}";
+ CHECK(n == strlen(want) && !strcmp(j, want), "compact: got %s", j);
+ char raw[] = "{\"a\":\"x\ty\"}"; /* a raw tab inside a string becomes a space */
+ smartctl_compact(raw, strlen(raw));
+ CHECK(!strcmp(raw, "{\"a\":\"x y\"}"), "raw control: got %s", raw);
+
+ /* pieces never cut a UTF-8 sequence */
+ const char *u = "ab\xc3\xa9" "cd"; /* "abécd" */
+ CHECK(smartctl_chunk(u, 6, 3) == 2, "chunk before é: %zu", smartctl_chunk(u, 6, 3));
+ CHECK(smartctl_chunk(u, 6, 4) == 4, "chunk after é: %zu", smartctl_chunk(u, 6, 4));
+ CHECK(smartctl_chunk(u, 6, 900) == 6, "short text in one piece");
+
+ printf("smartctl-test: %d checks, %d failures\n", checks, fails);
+ return fails ? 1 : 0;
+}
diff --git a/tools/iso/mkdeb.sh b/tools/iso/mkdeb.sh
index 4541b9e..b445141 100755
--- a/tools/iso/mkdeb.sh
+++ b/tools/iso/mkdeb.sh
@@ -24,6 +24,7 @@
# /usr/share/keyrings/lordos-archive-keyring.gpg the key that signs that repository
# /usr/lib/lordos/migrate, migrations/ version-to-version system migrations, run by postinst
# /etc/kernel/postinst.d/zz-lordos-reboot-required "restart required" after a kernel update
+# /usr/lib/modules-load.d/lordos-drivetemp.conf SATA disk temperatures (drivetemp) at boot
set -eu
OUT=${1:?uso: mkdeb.sh salida.deb}
ROOT=$(pwd)
@@ -89,6 +90,8 @@ install -D -m 644 tools/iso/rootfs/etc/pipewire/pipewire-pulse.conf.d/lordos-no-
install -D -m 644 tools/iso/rootfs/etc/wireplumber/wireplumber.conf.d/lordos-vm-audio.conf "$PKG/etc/wireplumber/wireplumber.conf.d/lordos-vm-audio.conf"
# vmwgfx only on VMware itself; elsewhere it removes the firmware framebuffer and fails (docs/ISO.md)
install -D -m 644 tools/iso/rootfs/etc/modprobe.d/lordos-vmwgfx.conf "$PKG/etc/modprobe.d/lordos-vmwgfx.conf"
+# SATA disk temperatures for Monitor → Disks: the drivetemp module at boot (docs/MONITOR.md)
+install -D -m 644 tools/iso/rootfs/etc/modules-load.d/lordos-drivetemp.conf "$PKG/usr/lib/modules-load.d/lordos-drivetemp.conf"
# remote login (SSH) defaults, read only once openssh-server is installed (docs/REMOTE.md)
install -D -m 644 tools/iso/rootfs/etc/ssh/sshd_config.d/10-lordos.conf "$PKG/etc/ssh/sshd_config.d/10-lordos.conf"
# a process may only trace its own descendants: a restricted Linux app must not take over an
diff --git a/tools/iso/rootfs/etc/modules-load.d/lordos-drivetemp.conf b/tools/iso/rootfs/etc/modules-load.d/lordos-drivetemp.conf
new file mode 100644
index 0000000..db783ab
--- /dev/null
+++ b/tools/iso/rootfs/etc/modules-load.d/lordos-drivetemp.conf
@@ -0,0 +1,4 @@
+# LordOS: SATA disk temperatures for Monitor → Disks (docs/MONITOR.md, "Disk temperature and health").
+# drivetemp gives each SATA disk that reports its temperature a hwmon sensor the session reads
+# without root. NVMe drives need nothing: the nvme driver has its own sensor.
+drivetemp