File size: 19,726 Bytes
bad179a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
// Linux: POSIX sh collector (reads /proc and /sys), its parser, and the control commands.
#include "Model.h"
#include <QRegularExpression>
#include <QSet>
#include <algorithm>

// One frame per interval: "@@SNAP_BEGIN", "@@S <section>" + raw lines, "@@SNAP_END". All maths happens in the parser.
static const char *const kCollector = R"SMSCRIPT(
sm_main() {
iv="${1:-2}" once="${2:-0}" n=0
export LC_ALL=C
while :; do
  echo "@@SNAP_BEGIN"
  if [ $((n % 15)) -eq 0 ]; then
    echo "@@S info"
    echo "hostname=$(cat /proc/sys/kernel/hostname 2>/dev/null)"
    echo "kernel=$(uname -r 2>/dev/null)"
    echo "arch=$(uname -m 2>/dev/null)"
    echo "os=$(sed -n 's/^PRETTY_NAME=//p' /etc/os-release 2>/dev/null | tr -d '"')"
    echo "cpumodel=$(grep -m1 -E '^(model name|Hardware|Processor|cpu model)' /proc/cpuinfo 2>/dev/null | cut -d: -f2- | sed 's/^ *//')"
    echo "clk=$(getconf CLK_TCK 2>/dev/null || echo 100)"
    echo "page=$(getconf PAGESIZE 2>/dev/null || echo 4096)"
    echo "virt=$(systemd-detect-virt 2>/dev/null || echo unknown)"
    echo "@@S passwd"; cut -d: -f1,3 /etc/passwd 2>/dev/null
  fi
  echo "@@S uptime"; cat /proc/uptime
  echo "@@S loadavg"; cat /proc/loadavg
  echo "@@S stat"
  grep -E '^(cpu|ctxt|processes|procs_)' /proc/stat
  awk '/^intr/ {print "intr", $2}' /proc/stat
  echo "@@S meminfo"; cat /proc/meminfo
  echo "@@S netdev"; cat /proc/net/dev
  echo "@@S netstate"
  for i in /sys/class/net/*; do
    [ -e "$i" ] || continue
    echo "${i##*/} $(cat "$i/operstate" 2>/dev/null || echo unknown) $(cat "$i/speed" 2>/dev/null || echo -1)"
  done
  echo "@@S diskstats"; cat /proc/diskstats
  echo "@@S df"; df -P -T -k 2>/dev/null || df -P -k 2>/dev/null
  echo "@@S sockstat"; cat /proc/net/sockstat 2>/dev/null
  echo "@@S tcp"
  cat /proc/net/tcp /proc/net/tcp6 2>/dev/null | awk '$4 ~ /^[0-9A-F][0-9A-F]$/ {c[$4]++} END {for (k in c) print k, c[k]}'
  echo "@@S thermal"
  for z in /sys/class/thermal/thermal_zone*; do
    [ -r "$z/temp" ] && echo "$(cat "$z/type" 2>/dev/null)|$(cat "$z/temp" 2>/dev/null)"
  done
  for h in /sys/class/hwmon/hwmon*; do
    [ -d "$h" ] || continue
    hn=$(cat "$h/name" 2>/dev/null)
    for t in "$h"/temp*_input; do
      [ -r "$t" ] || continue
      l=$(cat "${t%_input}_label" 2>/dev/null)
      echo "$hn ${l:-${t##*/}}|$(cat "$t" 2>/dev/null)"
    done
  done
  echo "@@S freq"
  for c in /sys/devices/system/cpu/cpu[0-9]*; do
    f=$(cat "$c/cpufreq/scaling_cur_freq" 2>/dev/null) && echo "${c##*/cpu} $f"
  done
  echo "@@S procs"
  cat /proc/[0-9]*/stat 2>/dev/null | awk '{
    if (!match($0, /\(.*\)/)) next
    comm = substr($0, RSTART + 1, RLENGTH - 2)
    rest = substr($0, RSTART + RLENGTH + 1)
    k = split(rest, r, " ")
    if (k < 22) next
    print $1, r[1], r[2], r[12] + r[13], r[17], r[18], r[20], r[21], r[22], comm
  }'
  echo "@@S uids"; ls -ln /proc 2>/dev/null | awk '$NF ~ /^[0-9]+$/ {print $NF, $3}'
  if [ $((n % 5)) -eq 0 ]; then
    echo "@@S services"
    systemctl list-units --type=service --all --no-legend --no-pager --plain 2>/dev/null | head -n 600
  fi
  if [ $((n % 3)) -eq 0 ] && command -v nvidia-smi >/dev/null 2>&1; then
    echo "@@S gpu"
    nvidia-smi --query-gpu=index,name,utilization.gpu,memory.used,memory.total,temperature.gpu,power.draw,fan.speed --format=csv,noheader,nounits 2>/dev/null
  fi
  echo "@@S users"; who 2>/dev/null | wc -l
  echo "@@SNAP_END" || exit 0
  [ "$once" = "once" ] && break
  n=$((n + 1))
  sleep "$iv"
done
}
sm_main "$@"
)SMSCRIPT";
static const char *const kRestartFailed = "for u in $(systemctl list-units --type=service --state=failed --no-legend --plain | awk '{print $1}'); do echo restart $u; systemctl restart $u; done";

namespace P {
const char *const prioLabel = "Nice", *const kernelPrefix = "Linux ",
    *const sshHint = "Uses your system <b>ssh</b> client; nothing is installed on the server. Set up key login once with <code>ssh-copy-id user@host</code>.",
    *const cleanup = "journalctl --vacuum-time=7d 2>/dev/null; apt-get clean 2>/dev/null; dnf clean all 2>/dev/null; "
                     "find /tmp /var/tmp -xdev -type f -atime +7 -delete 2>/dev/null; true";
const bool sudo = true, posixCpu = true;
const int interval = 2, normalPrio = 0;

QStringList shell(int iv) { return iv ? QStringList{"sh", "-s", "--", QString::number(iv)} : QStringList{"sh", "-s"}; }
QByteArray collector(int) { return kCollector; }
QByteArray wrap(const QString &cmd, bool sudo) { return (sudo ? "sudo -n sh -c " + quote(cmd) : cmd).toUtf8() + "\n"; }
QString quote(QString s) { return "'" + s.replace("'", "'\\''") + "'"; }
QString command(const QString &action, const QString &arg)
{
    const QString n = QString::number(arg.toInt());
    return QHash<QString, QString>{{"kill_pid", "kill -TERM " + n}, {"renice", "renice -n 19 -p " + n}, {"drop_caches", "sync && echo 3 > /proc/sys/vm/drop_caches"},
        {"restart_service", QString("systemctl reset-failed %1 2>/dev/null; systemctl restart %1").arg(quote(arg))}, {"restart_failed", kRestartFailed}}.value(action);
}
QString serviceLogs(const QString &unit, int lines)
{
    return QString("systemctl status --no-pager -l %1 2>&1 | head -n 15; echo; echo '==== journal ===='; journalctl -u %1 -n %2 --no-pager 2>&1").arg(quote(unit)).arg(lines);
}
QString power(bool reboot) { return QString("(sleep 2; systemctl %1) >/dev/null 2>&1 &").arg(reboot ? "reboot" : "poweroff"); }
bool isProtected(int pid, int ppid, double rss, const QString &name) { return pid <= 2 || ppid == 2 || rss <= 0 || name == "sshd" || name == "systemd"; } // init, kernel threads, ssh

const QVector<Def> &ruleActions()
{
    static const QVector<Def> d = {{"notify", "Notify only", ""}, {"restart_failed", "Restart failed services", ""},
        {"restart_service", "Restart a service", "nginx.service"}, {"kill_top_cpu", "Terminate top CPU process", ""},
        {"kill_top_mem", "Terminate top memory process", ""}, {"drop_caches", "Sync + drop page cache", ""},
        {"command", "Run a command", "find /tmp -mtime +7 -delete"}};
    return d;
}
const QVector<Cmd> &procActions()
{
    static const QVector<Cmd> d = {{"Terminate", "kill -TERM %1"}, {"Kill", "kill -KILL %1", true}, {"Hang up", "kill -HUP %1", false, true, false},
        {"Suspend", "kill -STOP %1"}, {"Resume", "kill -CONT %1", false, false}};
    return d;
}
const QVector<Cmd> &priorities()
{
    static const QVector<Cmd> d = {{"-20 (highest)", "renice -n -20 -p %1"}, {"-10", "renice -n -10 -p %1"}, {"0 (normal)", "renice -n 0 -p %1"},
        {"10", "renice -n 10 -p %1"}, {"19 (lowest)", "renice -n 19 -p %1"}};
    return d;
}
const QVector<Cmd> &serviceActions()
{
    static const QVector<Cmd> d = {{"Start", "systemctl start %1", false, false}, {"Stop", "systemctl stop %1", true}, {"Restart", "systemctl restart %1"},
        {"Reload", "systemctl reload %1", false, false}, {"Enable", "systemctl enable %1", false, false}, {"Disable", "systemctl disable %1", true}};
    return d;
}
const QVector<Cmd> &diagnostics()
{
    static const QVector<Cmd> d = {{"Disk usage", "df -hT -x tmpfs -x devtmpfs -x squashfs -x overlay"}, {"Largest dirs in /var", "du -xh --max-depth=2 /var 2>/dev/null | sort -rh | head -n 20"},
        {"Memory", "free -h; echo; vmstat 1 3"}, {"Top CPU processes", "ps -eo pid,user,pcpu,pmem,rss,etime,comm --sort=-pcpu | head -n 20"},
        {"Listening ports", "ss -tulpn 2>/dev/null || netstat -tulpn"}, {"Kernel messages", "dmesg -T 2>/dev/null | tail -n 40 || journalctl -k -n 40 --no-pager"},
        {"Errors in journal", "journalctl -p err -n 60 --no-pager"}, {"Failed services", "systemctl --failed --no-pager"},
        {"Logged-in users", "w"}, {"Last reboots", "last -x reboot shutdown 2>/dev/null | head -n 15"}};
    return d;
}
const QVector<Cmd> &systemActions()
{
    static const QVector<Cmd> d = {{"Sync + drop page cache", "sync && echo 3 > /proc/sys/vm/drop_caches && echo done"}, {"Vacuum journal to 200 MB", "journalctl --vacuum-size=200M"},
        {"Clean package cache", "(apt-get clean || dnf clean all || yum clean all) 2>&1"}, {"Restart failed services", QString(kRestartFailed) + "; echo done"},
        {"Reboot", "(sleep 2; systemctl reboot) >/dev/null 2>&1 & echo 'reboot scheduled'", true},
        {"Shut down", "(sleep 2; systemctl poweroff) >/dev/null 2>&1 & echo 'shutdown scheduled'", true}};
    return d;
}
} // namespace P

// ---- collector frame parser ----------------------------------------------------------------
Metrics MetricsEngine::process(const QByteArray &raw, qint64 now)
{
    QHash<QString, QList<QByteArray>> sec;
    QList<QByteArray> *cur = nullptr;
    for (const QByteArray &l : raw.split('\n')) {
        if (l.startsWith("@@S ")) cur = &sec[QString(l.mid(4).trimmed())];
        else if (cur && !l.startsWith("@@")) cur->append(l);
    }
    auto F = [](const QByteArray &l) { return l.simplified().split(' '); };
    auto L = [&](const char *k) { return sec.value(k); };
    auto first = [&](const char *k) { const auto v = L(k); return v.isEmpty() ? QList<QByteArray>() : F(v[0]); };
    Metrics m;
    m.timestamp = now;
    for (const auto &l : L("info")) {
        const int e = l.indexOf('=');
        if (e > 0) m_info[l.left(e)] = QString::fromUtf8(l.mid(e + 1)).trimmed();
    }
    if (sec.contains("passwd")) {
        m_users.clear();
        for (const auto &l : L("passwd")) {
            const int c = l.lastIndexOf(':');
            if (c > 0) m_users[l.mid(c + 1).toInt()] = l.left(c);
        }
    }
    m.hostname = m_info["hostname"], m.os = m_info["os"], m.kernel = m_info["kernel"], m.arch = m_info["arch"];
    m.cpuModel = m_info["cpumodel"], m.virt = m_info["virt"];
    const int clk = qMax(1, m_info.value("clk", "100").toInt()), page = qMax(512, m_info.value("page", "4096").toInt());
    const auto la = first("loadavg");
    m.load1 = la.value(0).toDouble(), m.load5 = la.value(1).toDouble(), m.load15 = la.value(2).toDouble();
    m.uptime = first("uptime").value(0).toDouble();
    if (m.uptime <= 0) return m;
    const double dt = m_upt > 0 ? m.uptime - m_upt : 0;
    const bool rates = dt > 0.05;
    QHash<QString, QVector<double>> next;
    auto delta = [&](const QString &key, const QVector<double> &v) { // per-second rates of a counter vector
        QVector<double> d(v.size(), 0.0);
        const auto p = m_ctr.value(key);
        if (rates && p.size() == v.size())
            for (int i = 0; i < v.size(); ++i) d[i] = qMax(0.0, (v[i] - p[i]) / dt);
        next[key] = v;
        return d;
    };

    // CPU
    QVector<QVector<double>> cpu;
    QVector<double> st(3);
    for (const auto &l : L("stat")) {
        const auto f = F(l);
        if (f[0].startsWith("cpu")) {
            QVector<double> t;
            for (int i = 1; i <= 8; ++i) t << f.value(i).toDouble();
            cpu << t;
        } else if (f[0] == "ctxt") st[0] = f.value(1).toDouble();
        else if (f[0] == "intr") st[1] = f.value(1).toDouble();
        else if (f[0] == "processes") st[2] = f.value(1).toDouble();
        else if (f[0] == "procs_running") m.procsRunning = f.value(1).toInt();
        else if (f[0] == "procs_blocked") m.procsBlocked = f.value(1).toInt();
    }
    m.cpuCount = qMax(1, cpu.size() - 1);
    m.cores.resize(m.cpuCount);
    double jiffies = 0;
    if (rates && m_cpu.size() == cpu.size())
        for (int i = 0; i < cpu.size(); ++i) {
            double d[8], tot = 0;
            for (int k = 0; k < 8; ++k) tot += d[k] = cpu[i][k] - m_cpu[i][k];
            if (tot <= 0) continue;
            auto p = [&](int k) { return qBound(0.0, d[k] * 100 / tot, 100.0); }; // user nice system idle iowait irq softirq steal
            const double use = qBound(0.0, 100 - p(3) - p(4), 100.0);
            if (i) m.cores[i - 1].usage = use;
            else jiffies = tot, m.cpuUsage = use, m.cpuUser = p(0) + p(1), m.cpuSystem = p(2), m.cpuIowait = p(4), m.cpuIrq = p(5) + p(6), m.cpuSteal = p(7);
        }
    m_cpu = cpu;
    const auto sd = delta("stat", st);
    m.ctxtPerSec = sd[0], m.intrPerSec = sd[1], m.forksPerSec = sd[2];
    int nf = 0;
    for (const auto &l : L("freq")) {
        const auto f = F(l);
        const int i = f.value(0).toInt();
        if (i >= 0 && i < m.cores.size()) m.avgMhz += m.cores[i].mhz = f.value(1).toDouble() / 1000, ++nf;
    }
    m.avgMhz = nf ? m.avgMhz / nf : 0;

    // memory
    QHash<QByteArray, double> mi;
    for (const auto &l : L("meminfo")) {
        const int c = l.indexOf(':');
        if (c > 0) mi[l.left(c)] = F(l.mid(c + 1)).value(0).toDouble() * 1024;
    }
    m.memTotal = mi["MemTotal"], m.memFree = mi["MemFree"], m.buffers = mi["Buffers"], m.cached = mi["Cached"] + mi["SReclaimable"];
    m.memAvailable = mi.contains("MemAvailable") ? mi["MemAvailable"] : m.memFree + m.buffers + m.cached;
    m.shared = mi["Shmem"], m.slab = mi["Slab"], m.dirty = mi["Dirty"], m.swapTotal = mi["SwapTotal"];
    m.memUsed = qMax(0.0, m.memTotal - m.memAvailable), m.swapUsed = qMax(0.0, m.swapTotal - mi["SwapFree"]);
    m.memPct = m.memTotal > 0 ? m.memUsed * 100 / m.memTotal : 0;
    m.swapPct = m.swapTotal > 0 ? m.swapUsed * 100 / m.swapTotal : 0;

    // network
    static const QRegularExpression virt("^(lo|veth|docker|br-|virbr|cni|flannel|cali|vxlan|kube|tun|tap)");
    QHash<QString, QList<QByteArray>> state;
    for (const auto &l : L("netstate")) state[F(l)[0]] = F(l);
    for (const auto &l : L("netdev")) {
        const int c = l.indexOf(':');
        const auto f = F(l.mid(c + 1));
        if (c <= 0 || f.size() < 16) continue;
        NetIf n;
        n.name = l.left(c).trimmed();
        n.virt = virt.match(n.name).hasMatch();
        n.state = state[n.name].value(1, "unknown"), n.speed = state[n.name].value(2, "-1").toInt();
        n.rxBytes = f[0].toDouble(), n.txBytes = f[8].toDouble();
        n.errors = f[2].toDouble() + f[10].toDouble(), n.drops = f[3].toDouble() + f[11].toDouble();
        const auto d = delta("net:" + n.name, {n.rxBytes, n.txBytes, f[1].toDouble(), f[9].toDouble()});
        n.rxBps = d[0], n.txBps = d[1], n.rxPps = d[2], n.txPps = d[3];
        if (!n.virt) m.netRxBps += n.rxBps, m.netTxBps += n.txBps;
        m.nets << n;
    }
    std::sort(m.nets.begin(), m.nets.end(), [](const NetIf &a, const NetIf &b) { return a.virt != b.virt ? !a.virt : a.name < b.name; });
    static const QStringList tcpNames = {"", "ESTABLISHED", "SYN_SENT", "SYN_RECV", "FIN_WAIT1", "FIN_WAIT2", "TIME_WAIT", "CLOSE", "CLOSE_WAIT", "LAST_ACK", "LISTEN", "CLOSING"};
    for (const auto &l : L("tcp")) m.tcp[tcpNames.value(F(l)[0].toInt(nullptr, 16), "?")] += F(l).value(1).toInt();
    for (const auto &l : L("sockstat"))
        if (l.startsWith("sockets:")) m.socketsUsed = F(l).value(2).toInt();

    // disks: whole devices + device-mapper; totals over physical disks only
    static const QRegularExpression whole("^(sd[a-z]+|vd[a-z]+|xvd[a-z]+|hd[a-z]+|nvme\\d+n\\d+|mmcblk\\d+|md\\d+)$");
    for (const auto &l : L("diskstats")) {
        const auto f = F(l);
        if (f.size() < 14) continue;
        DiskIO d;
        d.name = f[2];
        const bool w = whole.match(d.name).hasMatch();
        if (!w && !d.name.startsWith("dm-")) continue;
        d.totalRead = f[5].toDouble() * 512, d.totalWritten = f[9].toDouble() * 512;
        const auto r = delta("disk:" + d.name, {f[3].toDouble(), d.totalRead, f[7].toDouble(), d.totalWritten, f[12].toDouble()});
        d.readIops = r[0], d.readBps = r[1], d.writeIops = r[2], d.writeBps = r[3], d.util = qMin(100.0, r[4] / 10);
        if (w && !d.name.startsWith("md")) {
            m.diskReadBps += d.readBps, m.diskWriteBps += d.writeBps;
            if (d.util >= m.maxDiskUtil) m.maxDiskUtil = d.util, m.busiestDisk = d.name;
        }
        m.disks << d;
    }
    static const QSet<QString> skipFs = {"tmpfs", "devtmpfs", "squashfs", "overlay", "efivarfs", "ramfs", "proc", "sysfs", "autofs",
                                         "nsfs", "devfs", "cgroup", "cgroup2", "fuse.snapfuse", "fuse.portal"};
    const auto df = L("df");
    const int b = !df.isEmpty() && df[0].contains("Type") ? 1 : 0;
    QSet<QString> seen;
    for (int i = 1; i < df.size(); ++i) {
        const auto f = F(df[i]);
        if (f.size() < 6 + b) continue;
        MountInfo mt;
        mt.device = f[0], mt.type = b ? f[1] : QByteArray();
        mt.total = f[1 + b].toDouble() * 1024, mt.used = f[2 + b].toDouble() * 1024, mt.avail = f[3 + b].toDouble() * 1024;
        mt.mount = f.mid(5 + b).join(' ');
        const QString key = mt.device + QString::number(mt.total);
        if (skipFs.contains(b ? mt.type : mt.device) || mt.total <= 0 || mt.mount.startsWith("/snap/") || (mt.device.startsWith('/') && seen.contains(key))) continue;
        seen << key;
        mt.pct = mt.used + mt.avail > 0 ? mt.used * 100 / (mt.used + mt.avail) : 0;
        if (mt.pct >= m.maxDiskPct) m.maxDiskPct = mt.pct, m.fullestMount = mt.mount;
        m.mounts << mt;
    }

    // processes: "pid state ppid ticks nice threads start vsize rss comm..."
    QHash<int, int> uid;
    for (const auto &l : L("uids")) uid[F(l)[0].toInt()] = F(l).value(1).toInt();
    QHash<int, double> ticks;
    const double perCore = jiffies > 0 ? jiffies / m.cpuCount : rates ? dt * clk : 0;
    for (const auto &l : L("procs")) {
        const auto f = l.split(' ');
        ProcInfo p;
        if (f.size() < 10 || (p.pid = f[0].toInt()) <= 0) continue;
        p.state = f[1].isEmpty() ? '?' : f[1][0];
        p.ppid = f[2].toInt(), p.nice = f[4].toInt(), p.threads = f[5].toInt();
        p.age = qMax(0.0, m.uptime - f[6].toDouble() / clk), p.vsz = f[7].toDouble(), p.rss = f[8].toDouble() * page;
        p.name = QString::fromUtf8(f.mid(9).join(' '));
        ticks[p.pid] = f[3].toDouble();
        if (perCore > 0 && m_ticks.contains(p.pid)) p.cpu = qBound(0.0, (ticks[p.pid] - m_ticks[p.pid]) * 100 / perCore, 100.0 * m.cpuCount);
        p.memPct = m.memTotal > 0 ? p.rss * 100 / m.memTotal : 0;
        p.user = uid.contains(p.pid) ? m_users.value(uid[p.pid], QString::number(uid[p.pid])) : "?";
        m.threadsTotal += p.threads;
        m.procs << p;
    }
    std::sort(m.procs.begin(), m.procs.end(), [](const ProcInfo &a, const ProcInfo &b) { return a.cpu != b.cpu ? a.cpu > b.cpu : a.rss > b.rss; });

    // services / GPUs arrive every few samples: keep the last list
    if (sec.contains("services")) {
        m_services.clear();
        for (const auto &l : L("services")) {
            const auto f = F(l);
            if (f.size() >= 4 && f[0].endsWith(".service")) m_services << ServiceInfo{f[0], f[1], f[2], f[3], QString::fromUtf8(f.mid(4).join(' '))};
        }
    }
    m.services = m_services;
    for (const auto &s : m.services) m.servicesFailed += s.active == "failed", m.servicesRunning += s.sub == "running";
    if (sec.contains("gpu")) {
        m_gpus.clear();
        for (const auto &l : L("gpu")) {
            const auto f = l.split(',');
            auto n = [&](int i) { return f[i].trimmed().toDouble(); };
            if (f.size() >= 8) m_gpus << GpuInfo{int(n(0)), f[1].trimmed(), n(2), n(3), n(4), n(5), n(6), n(7)};
        }
    }
    m.gpus = m_gpus;
    QSet<QString> tn;
    for (const auto &l : L("thermal")) {
        const int bar = l.lastIndexOf('|');
        TempSensor t{QString::fromUtf8(l.left(bar)).trimmed(), l.mid(bar + 1).toDouble() / 1000};
        if (bar <= 0 || t.celsius <= 0 || t.celsius > 150 || tn.contains(t.name)) continue;
        tn << t.name, m.temps << t, m.maxTemp = qMax(m.maxTemp, t.celsius);
    }
    m.loggedUsers = first("users").value(0).toInt();

    m_ctr = next, m_ticks = ticks, m_upt = m.uptime;
    m.valid = rates; // the first sample has no rates yet
    return m;
}