File size: 13,306 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
// Everything that depends on the operating system (Linux edition): where the config lives, how to start a shell,
// the collector script with its frame parser, the control commands and the texts the page shows for them.
// The Windows edition replaces this file and the collector script; every other file is identical.
const fs = require('fs'), os = require('os'), path = require('path');
const { num, blank, sections, kv, rater, addDisk, addMount, finish } = require('./metrics');

const collector = fs.readFileSync(path.join(__dirname, 'collector.sh'), 'utf8'); // POSIX sh, reads /proc and /sys
const quote = s => "'" + s.replace(/'/g, "'\\''") + "'";
const restartFailed = "for u in $(systemctl list-units --type=service --state=failed --no-legend --plain | awk '{print $1}'); do echo restart $u; systemctl restart $u; done";
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';
// rows: label, command ({n} = pid, {q} = quoted name), danger, confirm, has a button
const cmds = rows => rows.map(([label, cmd, danger = false, confirm = true, button = true]) => ({ label, cmd, danger, confirm, button }));

// ---- collector frame parser: raw /proc text in, Metrics out; `st` keeps counters between frames ----
const F = l => l.trim().split(/\s+/);
const VIRT = /^(lo|veth|docker|br-|virbr|cni|flannel|cali|vxlan|kube|tun|tap)/;
const WHOLE = /^(sd[a-z]+|vd[a-z]+|xvd[a-z]+|hd[a-z]+|nvme\d+n\d+|mmcblk\d+|md\d+)$/;
const TCP = ['', 'ESTABLISHED', 'SYN_SENT', 'SYN_RECV', 'FIN_WAIT1', 'FIN_WAIT2', 'TIME_WAIT', 'CLOSE', 'CLOSE_WAIT', 'LAST_ACK', 'LISTEN', 'CLOSING'];
const SKIP_FS = new Set(['tmpfs', 'devtmpfs', 'squashfs', 'overlay', 'efivarfs', 'ramfs', 'proc', 'sysfs', 'autofs', 'nsfs', 'devfs', 'cgroup', 'cgroup2',
    'fuse.snapfuse', 'fuse.portal']);

function parse(frame, st, now) {
    const sec = sections(frame), L = k => sec[k] || [], first = k => F(L(k)[0] || '');
    const m = blank(now), info = kv(sec.info, st.info ??= {});
    if (sec.passwd) {
        st.users = {};
        for (const l of sec.passwd) {
            const c = l.lastIndexOf(':');
            if (c > 0) st.users[parseInt(l.slice(c + 1))] = l.slice(0, c);
        }
    }
    m.hostname = info.hostname || '', m.os = info.os || '', m.kernel = info.kernel || '', m.arch = info.arch || '';
    m.cpuModel = info.cpumodel || '', m.virt = info.virt || '';
    const clk = Math.max(1, parseInt(info.clk ?? 100) || 0), page = Math.max(512, parseInt(info.page ?? 4096) || 0);
    [m.load1, m.load5, m.load15] = first('loadavg').map(num);
    m.load5 ||= 0, m.load15 ||= 0, m.uptime = num(first('uptime')[0]);
    if (m.uptime <= 0) return m;
    const dt = st.upt > 0 ? m.uptime - st.upt : 0, rates = dt > 0.05, delta = rater(st, dt);

    // CPU
    const cpu = [], stat = [0, 0, 0];
    for (const f of L('stat').map(F)) {
        if (f[0].startsWith('cpu')) cpu.push(f.slice(1, 9).map(num));
        else if (f[0] === 'ctxt') stat[0] = num(f[1]);
        else if (f[0] === 'intr') stat[1] = num(f[1]);
        else if (f[0] === 'processes') stat[2] = num(f[1]);
        else if (f[0] === 'procs_running') m.procsRunning = num(f[1]);
        else if (f[0] === 'procs_blocked') m.procsBlocked = num(f[1]);
    }
    m.cpuCount = Math.max(1, cpu.length - 1);
    m.cores = Array.from({ length: m.cpuCount }, () => ({ usage: 0, mhz: 0 }));
    let jiffies = 0;
    if (rates && st.cpu?.length === cpu.length)
        cpu.forEach((t, i) => {
            const d = Array.from({ length: 8 }, (_, k) => (t[k] || 0) - (st.cpu[i][k] || 0)), tot = d.reduce((a, b) => a + b, 0);
            if (tot <= 0) return;
            const p = k => Math.min(100, Math.max(0, d[k] * 100 / tot)); // user nice system idle iowait irq softirq steal
            const use = Math.min(100, Math.max(0, 100 - p(3) - p(4)));
            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);
        });
    st.cpu = cpu;
    [m.ctxtPerSec, m.intrPerSec, m.forksPerSec] = delta('stat', stat);
    let nf = 0;
    for (const f of L('freq').map(F)) {
        const c = m.cores[parseInt(f[0])];
        if (c) m.avgMhz += c.mhz = num(f[1]) / 1000, ++nf;
    }
    m.avgMhz = nf ? m.avgMhz / nf : 0;

    // memory
    const mi = {}, mem = k => mi[k] || 0;
    for (const l of L('meminfo')) {
        const c = l.indexOf(':');
        if (c > 0) mi[l.slice(0, c)] = num(F(l.slice(c + 1))[0]) * 1024;
    }
    m.memTotal = mem('MemTotal'), m.memFree = mem('MemFree'), m.buffers = mem('Buffers'), m.cached = mem('Cached') + mem('SReclaimable');
    m.memAvailable = 'MemAvailable' in mi ? mi.MemAvailable : m.memFree + m.buffers + m.cached;
    m.shared = mem('Shmem'), m.slab = mem('Slab'), m.dirty = mem('Dirty'), m.swapTotal = mem('SwapTotal');
    m.swapUsed = Math.max(0, m.swapTotal - mem('SwapFree'));

    // network
    const state = Object.fromEntries(L('netstate').map(l => [F(l)[0], F(l)]));
    for (const l of L('netdev')) {
        const c = l.indexOf(':'), f = F(l.slice(c + 1)).map(num), name = l.slice(0, Math.max(0, c)).trim();
        if (c <= 0 || f.length < 16) continue;
        const [rxBps, txBps, rxPps, txPps] = delta('net:' + name, [f[0], f[8], f[1], f[9]]);
        m.nets.push({ name, virt: VIRT.test(name), state: state[name]?.[1] ?? 'unknown', speed: parseInt(state[name]?.[2] ?? -1) || 0,
            rxBps, txBps, rxPps, txPps, rxBytes: f[0], txBytes: f[8], errors: f[2] + f[10], drops: f[3] + f[11] });
    }
    for (const f of L('tcp').map(F)) {
        const name = TCP[parseInt(f[0], 16)] ?? '?';
        m.tcp[name] = (m.tcp[name] || 0) + num(f[1]);
    }
    for (const l of L('sockstat')) if (l.startsWith('sockets:')) m.socketsUsed = num(F(l)[2]);

    // disks: whole devices + device-mapper; totals over physical disks only
    for (const f of L('diskstats').map(F)) {
        const name = f[2], whole = WHOLE.test(name);
        if (f.length < 14 || (!whole && !name.startsWith('dm-'))) continue;
        const totalRead = num(f[5]) * 512, totalWritten = num(f[9]) * 512;
        const [readIops, readBps, writeIops, writeBps, busy] = delta('disk:' + name, [num(f[3]), totalRead, num(f[7]), totalWritten, num(f[12])]);
        addDisk(m, { name, readBps, writeBps, readIops, writeIops, util: Math.min(100, busy / 10), totalRead, totalWritten }, whole && !name.startsWith('md'));
    }
    const df = L('df'), b = df[0]?.includes('Type') ? 1 : 0, seen = new Set();
    for (const f of df.slice(1).map(F)) {
        if (f.length < 6 + b) continue;
        const mt = { device: f[0], type: b ? f[1] : '', mount: f.slice(5 + b).join(' '), total: num(f[1 + b]) * 1024, used: num(f[2 + b]) * 1024, avail: num(f[3 + b]) * 1024 };
        const key = mt.device + mt.total;
        if (SKIP_FS.has(b ? mt.type : mt.device) || mt.total <= 0 || mt.mount.startsWith('/snap/') || (mt.device.startsWith('/') && seen.has(key))) continue;
        seen.add(key), addMount(m, mt);
    }

    // processes: "pid state ppid ticks nice threads start vsize rss comm..."
    const uid = Object.fromEntries(L('uids').map(l => F(l).map(num))), ticks = {};
    const perCore = jiffies > 0 ? jiffies / m.cpuCount : rates ? dt * clk : 0;
    for (const l of L('procs')) {
        const f = l.split(' '), pid = parseInt(f[0]);
        if (f.length < 10 || !(pid > 0)) continue;
        ticks[pid] = num(f[3]);
        m.procs.push({ pid, ppid: num(f[2]), threads: num(f[5]), nice: num(f[4]), name: f.slice(9).join(' '), state: f[1][0] || '?',
            user: pid in uid ? st.users?.[uid[pid]] ?? String(uid[pid]) : '?',
            cpu: perCore > 0 && st.ticks && pid in st.ticks ? Math.min(100 * m.cpuCount, Math.max(0, (ticks[pid] - st.ticks[pid]) * 100 / perCore)) : 0,
            rss: num(f[8]) * page, vsz: num(f[7]), age: Math.max(0, m.uptime - num(f[6]) / clk) });
    }

    // services arrive every few samples: keep the last list
    if (sec.services)
        st.services = sec.services.map(F).filter(f => f.length >= 4 && f[0].endsWith('.service'))
            .map(f => ({ unit: f[0], load: f[1], active: f[2], sub: f[3], description: f.slice(4).join(' ') }));
    m.loggedUsers = num(first('users')[0]);
    finish(m, st, sec, 0.001);

    st.ticks = ticks, st.upt = m.uptime;
    m.valid = rates; // the first sample has no rates yet
    return m;
}

module.exports = {
    quote, parse, cleanup,
    configDir: () => path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'ServerMonitorWeb'),
    shell: interval => interval ? ['sh', '-s', '--', String(interval)] : ['sh', '-s'], // argv of a shell that runs a script from stdin
    collector: () => collector,                                                         // stdin for the collector
    wrap: (cmd, sudo) => (sudo ? 'sudo -n sh -c ' + quote(cmd) : cmd) + '\n',            // stdin for a one-shot command
    askpass: ['askpass.sh', '#!/bin/sh\nprintf \'%s\\n\' "$SERVERMONITOR_ASKPASS"\n'],  // answers ssh's password prompt
    command: (action, arg) => ({
        kill_pid: `kill -TERM ${parseInt(arg) || 0}`, renice: `renice -n 19 -p ${parseInt(arg) || 0}`, drop_caches: 'sync && echo 3 > /proc/sys/vm/drop_caches',
        restart_service: `systemctl reset-failed ${quote(arg)} 2>/dev/null; systemctl restart ${quote(arg)}`, restart_failed: restartFailed,
    })[action],
    serviceLogs: (unit, lines) => `systemctl status --no-pager -l ${quote(unit)} 2>&1 | head -n 15; echo; echo '==== journal ===='; journalctl -u ${quote(unit)} -n ${lines} --no-pager 2>&1`,
    power: reboot => `(sleep 2; systemctl ${reboot ? 'reboot' : 'poweroff'}) >/dev/null 2>&1 &`,
    detached: true, // every child leads its own process group, so that kill() also ends what its shell started
    kill: p => { try { process.kill(-p.pid, 'SIGKILL'); } catch { /* not started or already gone */ } },
    // told "+pid" / "-pid" on stdin; when stdin closes (the monitor is gone, even killed) it ends the process groups still listed
    reaper: ['sh', '-c', 'p=" "; while read -r l; do x=${l#?}; case $l in +*) p="$p$x ";; -*) p="${p%% $x *} ${p#* $x }";; esac; done; for x in $p; do kill -KILL -$x; done 2>/dev/null'],
    // never killed automatically, no leak / runaway findings: init, kernel threads, ssh
    isProtected: p => p.pid <= 2 || p.ppid === 2 || p.rss <= 0 || p.name === 'sshd' || p.name === 'systemd',

    ui: { // sent to the page
        name: 'Linux', sudo: true, posixCpu: true, interval: 2, prioLabel: 'Nice', normalPrio: 0, kernelPrefix: 'Linux ',
        sshHint: 'Uses your system ssh client; nothing is installed on the server. Set up key login once with: ssh-copy-id user@host',
        keyHint: 'default keys / ssh-agent (~/.ssh/id_*)',
        ruleActions: [['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']],
        procActions: cmds([['Terminate', 'kill -TERM {n}'], ['Kill', 'kill -KILL {n}', true], ['Hang up', 'kill -HUP {n}', false, true, false],
            ['Suspend', 'kill -STOP {n}'], ['Resume', 'kill -CONT {n}', false, false]]),
        priorities: cmds([['-20 (highest)', -20], ['-10', -10], ['0 (normal)', 0], ['10', 10], ['19 (lowest)', 19]].map(([label, v]) => [label, `renice -n ${v} -p {n}`])),
        serviceActions: cmds([['Start', 'systemctl start {q}', false, false], ['Stop', 'systemctl stop {q}', true], ['Restart', 'systemctl restart {q}'],
            ['Reload', 'systemctl reload {q}', false, false], ['Enable', 'systemctl enable {q}', false, false], ['Disable', 'systemctl disable {q}', true]]),
        diagnostics: cmds([['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']]),
        systemActions: cmds([['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', restartFailed + '; 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]]),
    },
};