File size: 16,731 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
"""Platform module (Linux): everything OS-specific - collector script, process spawning, frame parser,
command tables and the texts that differ between the editions."""
import atexit, functools, os, re, signal, subprocess, tempfile

from metrics import Core, Disk, Metrics, Mount, Net, Proc, Service, add_disk, add_mount, finish, num, rates, sections, to_int

NAME, HAS_SUDO, POSIX_CPU, INTERVAL = 'Linux', True, True, 2  # POSIX_CPU: I/O wait and steal exist; INTERVAL: default sample seconds
SPAWN = {'start_new_session': True}  # extra subprocess.Popen arguments: own process group, so that kill() reaches what the shell started

def config_dir(): return os.path.join(os.environ.get('XDG_CONFIG_HOME') or os.path.expanduser('~/.config'), 'ServerMonitorPy')
def open_folder(path): subprocess.Popen(['xdg-open', path])

def shell(interval=None):
    """Command line that runs the script arriving on stdin (locally, or joined by spaces as the ssh remote command)."""
    return ['sh', '-s'] + (['--', str(interval)] if interval else [])

def collector(interval):
    """Stdin for the collector process (the interval travels on the command line)."""
    return COLLECTOR

def kill(p):
    """Ends a child process with everything it started (a shell's sleep or pipeline would keep its output pipe open)."""
    try: p.poll() is None and os.killpg(p.pid, signal.SIGKILL)
    except OSError: pass

def quote(s): return "'" + s.replace("'", "'\\''") + "'"

def wrap(cmd, privileged, sudo):
    """Stdin for a one-shot command."""
    return (f'sudo -n sh -c {quote(cmd)}' if privileged and sudo else cmd) + '\n'

@functools.lru_cache(None)
def askpass():
    """Helper script that answers ssh's password prompt from $SERVERMONITOR_ASKPASS; removed on exit."""
    fd, path = tempfile.mkstemp(prefix='servermonitor-askpass-', suffix='.sh')
    os.write(fd, b'#!/bin/sh\nprintf \'%s\\n\' "$SERVERMONITOR_ASKPASS"\n')
    os.close(fd)
    os.chmod(path, 0o700)
    atexit.register(os.remove, path)
    return path

def protected(p):
    """Processes that are never killed automatically and get no leak / runaway findings."""
    return p.pid <= 2 or p.ppid == 2 or p.rss <= 0 or p.name in ('sshd', 'systemd')

def thrashing(iowait, mem, disk_busy):
    """Rest of the sentence "Swap … used" when heavy swap use is thrashing ('' = it is not); iowait and disk_busy are 15-minute averages."""
    return f' and CPU waits on I/O {iowait:.1f}% of the time' if iowait > 20 else ''

def priority_level(nice):
    """How the priority column value compares with normal: > 0 raised, < 0 lowered."""
    return -nice

def cpu_tile(m):
    """(value, sub text, warn) of the CPU tab tile TEXT['cpu_tile']."""
    return f'{m.cpu_steal:.1f}% / {m.cpu_irq:.1f}%', 'steal > 5% = noisy neighbours', m.cpu_steal > 5

# ---- command tables: {q} = quoted argument, {n} = integer argument ---------------------------
CMD = {
    'kill_pid': 'kill -TERM {n}', 'renice': 'renice -n 19 -p {n}', 'drop_caches': 'sync && echo 3 > /proc/sys/vm/drop_caches',
    'restart_service': 'systemctl reset-failed {q} 2>/dev/null; systemctl restart {q}',
    'restart_failed': "for u in $(systemctl list-units --type=service --state=failed --no-legend --plain | awk '{print $1}'); "
                      "do echo restart $u; systemctl restart $u; done"}
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')
HINTS = {'restart_service': 'nginx.service', 'command': 'find /tmp -mtime +7 -delete'}  # rule-argument placeholders
POWER = {'Reboot': '(sleep 2; systemctl reboot) >/dev/null 2>&1 &', 'Shut down': '(sleep 2; systemctl poweroff) >/dev/null 2>&1 &'}
# (label, command, flags): b = toolbar button, c = ask first, d = dangerous
PROC_ACTIONS = [('Terminate', 'kill -TERM {n}', 'bc'), ('Kill', 'kill -KILL {n}', 'bcd'), ('Hang up', 'kill -HUP {n}', 'c'),
                ('Suspend', 'kill -STOP {n}', 'bc'), ('Resume', 'kill -CONT {n}', 'b')]
PRIORITIES = {'-20 (highest)': -20, '-10': -10, '0 (normal)': 0, '10': 10, '19 (lowest)': 19}
PRIORITY_CMD = 'renice -n {v} -p {n}'
SERVICE_VERBS = {v: f'systemctl {v} {{q}}' for v in ('start', 'stop', 'restart', 'reload', 'enable', 'disable')}
SERVICE_LOGS = "systemctl status --no-pager -l {q} 2>&1 | head -n 15; echo; echo '==== journal ===='; journalctl -u {q} -n {n} --no-pager 2>&1"
QUICK = [  # console: quick diagnostics
    ('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')]
ACTIONS = [  # console: system actions (confirmed, privileged); the POWER ones are shown as dangerous
    ('Sync + drop page cache', CMD['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', CMD['restart_failed'] + '; echo done'),
    ('Reboot', POWER['Reboot'] + " echo 'reboot scheduled'"),
    ('Shut down', POWER['Shut down'] + " echo 'shutdown scheduled'")]
TEXT = {
    'cpu_tile': 'Steal / IRQ', 'priority': 'Nice', 'kernel': 'Linux ',
    'renice': 'Renice to 19', 'renice_mode': 'Lower priority (renice 19)', 'renice_advice': 'Lower its priority (renice) or stop it if it is stuck.',
    'ssh_hint': 'Uses your system ssh client; nothing is installed on the server. Set up key login once with: ssh-copy-id user@host',
    'key_hint': 'default keys / ssh-agent (~/.ssh/id_*)', 'sudo': 'Run control commands with sudo -n (needs passwordless sudo)',
    'console_hint': 'Type a shell command and press Enter (↑/↓ history)',
    'privileged_tip': "Wrap in sudo -n when the server has 'Run control commands with sudo' enabled"}

# ---- collector frame parser -------------------------------------------------------------------
VIRTUAL_IF = re.compile(r'lo|veth|docker|br-|virbr|cni|flannel|cali|vxlan|kube|tun|tap')
WHOLE_DISK = re.compile(r'(sd[a-z]+|vd[a-z]+|xvd[a-z]+|hd[a-z]+|nvme\d+n\d+|mmcblk\d+|md\d+)$')
TCP_STATES = ['', 'ESTABLISHED', 'SYN_SENT', 'SYN_RECV', 'FIN_WAIT1', 'FIN_WAIT2', 'TIME_WAIT', 'CLOSE', 'CLOSE_WAIT', 'LAST_ACK', 'LISTEN', 'CLOSING']
SKIP_FS = {'tmpfs', 'devtmpfs', 'squashfs', 'overlay', 'efivarfs', 'ramfs', 'proc', 'sysfs', 'autofs', 'nsfs', 'devfs', 'cgroup', 'cgroup2',
           'fuse.snapfuse', 'fuse.portal'}

def parse(frame, st, now):
    """Collector frame -> Metrics; st keeps the counters of the previous frame (rates) and the slow sections."""
    sec, m = sections(frame), Metrics(now)

    def rows(name):  # non-empty lines of a section, split into fields
        return [f for f in map(str.split, sec.get(name, ())) if f]

    def first(name): return (rows(name) or [['']])[0]

    info = st.setdefault('info', {})
    for line in sec.get('info', ()):
        k, eq, v = line.partition('=')
        if eq and k: info[k] = v.strip()
    if 'passwd' in sec: st['users'] = {to_int(uid): name for name, _, uid in (l.rpartition(':') for l in sec['passwd']) if name}
    m.hostname, m.os, m.kernel, m.arch, m.cpu_model, m.virt = (info.get(k, '') for k in ('hostname', 'os', 'kernel', 'arch', 'cpumodel', 'virt'))
    clk, page = max(1, to_int(info.get('clk', 100))), max(512, to_int(info.get('page', 4096)))
    m.load1, m.load5, m.load15 = (num(x) for x in (first('loadavg') + [''] * 3)[:3])
    m.uptime = num(first('uptime')[0])
    if m.uptime <= 0: return m
    dt = m.uptime - st['uptime'] if st.get('uptime', 0) > 0 else 0
    live, delta = dt > 0.05, rates(st, dt)

    # CPU
    cpu, counters = [], [0.0] * 3
    for f in rows('stat'):
        v = num(f[1]) if len(f) > 1 else 0.0
        if f[0].startswith('cpu'): cpu.append([num(x) for x in (f[1:9] + [''] * 8)[:8]])
        elif f[0] in ('ctxt', 'intr', 'processes'): counters[('ctxt', 'intr', 'processes').index(f[0])] = v
        elif f[0] == 'procs_running': m.procs_running = int(v)
        elif f[0] == 'procs_blocked': m.procs_blocked = int(v)
    m.cpu_count = max(1, len(cpu) - 1)
    usage, mhz, jiffies, old = [0.0] * m.cpu_count, [0.0] * m.cpu_count, 0, st.get('cpu', [])
    for i, (new, was) in enumerate(zip(cpu, old) if live and len(cpu) == len(old) else ()):
        d = [a - b for a, b in zip(new, was)]
        total = sum(d)
        if total <= 0: continue
        p = [min(max(x * 100 / total, 0), 100) for x in d]  # user nice system idle iowait irq softirq steal
        use = min(max(100 - p[3] - p[4], 0), 100)
        if i:
            usage[i - 1] = use
        else:
            jiffies, m.cpu_usage, m.cpu_user, m.cpu_system, m.cpu_iowait, m.cpu_irq, m.cpu_steal = total, use, p[0] + p[1], p[2], p[4], p[5] + p[6], p[7]
    st['cpu'] = cpu
    m.ctxt_per_sec, m.intr_per_sec, m.forks_per_sec = delta('stat', counters)
    freqs = [(to_int(f[0]), num(f[1]) / 1000) for f in rows('freq') if len(f) > 1 and 0 <= to_int(f[0]) < m.cpu_count]
    for i, v in freqs: mhz[i] = v
    m.avg_mhz = sum(v for _, v in freqs) / len(freqs) if freqs else 0
    m.cores = [Core(*c) for c in zip(usage, mhz)]

    # memory
    mi = {k: num((v.split() or [''])[0]) * 1024 for k, _, v in (l.partition(':') for l in sec.get('meminfo', ())) if v}
    m.mem_total, m.mem_free, m.buffers, m.cached = (mi.get(k, 0.0) for k in ('MemTotal', 'MemFree', 'Buffers', 'Cached'))
    m.cached += mi.get('SReclaimable', 0.0)
    m.mem_available = mi.get('MemAvailable', m.mem_free + m.buffers + m.cached)
    m.shared, m.slab, m.dirty, m.swap_total = (mi.get(k, 0.0) for k in ('Shmem', 'Slab', 'Dirty', 'SwapTotal'))
    m.mem_used, m.swap_used = max(0.0, m.mem_total - m.mem_available), max(0.0, m.swap_total - mi.get('SwapFree', 0.0))

    # network
    state = {f[0]: f for f in rows('netstate')}
    for line in sec.get('netdev', ()):
        name, _, rest = line.partition(':')
        name, f = name.strip(), [num(x) for x in rest.split()]
        if not name or len(f) < 16: continue
        s = state.get(name, [])
        m.nets.append(Net(name, s[1] if len(s) > 1 else 'unknown', to_int(s[2]) if len(s) > 2 else -1, bool(VIRTUAL_IF.match(name)),
                          *delta('net:' + name, [f[0], f[8], f[1], f[9]]), f[0], f[8], f[2] + f[10], f[3] + f[11]))
    for f in rows('tcp'):
        i = to_int(f[0], 16)
        name = TCP_STATES[i] if i < len(TCP_STATES) else '?'
        m.tcp[name] = m.tcp.get(name, 0) + to_int(f[-1] if len(f) > 1 else 0)
    for f in rows('sockstat'):
        if f[0] == 'sockets:' and len(f) > 2: m.sockets_used = to_int(f[2])

    # disks: whole devices + device-mapper; totals over physical disks only
    for f in rows('diskstats'):
        whole = bool(WHOLE_DISK.match(f[2])) if len(f) >= 14 else False
        if len(f) < 14 or not (whole or f[2].startswith('dm-')): continue
        read, written = num(f[5]) * 512, num(f[9]) * 512
        r = delta('disk:' + f[2], [num(f[3]), read, num(f[7]), written, num(f[12])])
        add_disk(m, Disk(f[2], r[1], r[3], r[0], r[2], min(100.0, r[4] / 10), read, written), whole and not f[2].startswith('md'))
    df, seen = sec.get('df', []), set()
    b = int(bool(df) and 'Type' in df[0])  # 1 when df printed the file system type
    for f in map(str.split, df[1:]):
        if len(f) < 6 + b: continue
        device, fs, mount = f[0], f[1] if b else '', ' '.join(f[5 + b:])
        total, used, avail = (num(x) * 1024 for x in f[1 + b:4 + b])
        if (fs if b else device) in SKIP_FS or total <= 0 or mount.startswith('/snap/') or (device.startswith('/') and (device, total) in seen):
            continue
        seen.add((device, total))
        add_mount(m, Mount(device, fs, mount, total, used, avail, used * 100 / (used + avail) if used + avail > 0 else 0))

    # processes: "pid state ppid ticks nice threads start vsize rss comm..."
    uid = {to_int(f[0]): to_int(f[1]) for f in rows('uids') if len(f) > 1}
    users, old, ticks = st.get('users', {}), st.get('ticks', {}), {}
    per_core = jiffies / m.cpu_count if jiffies > 0 else dt * clk if live else 0
    for line in sec.get('procs', ()):
        f = line.split(' ', 9)
        pid = to_int(f[0])
        if len(f) < 10 or pid <= 0: continue
        ticks[pid], rss = num(f[3]), num(f[8]) * page
        cpu = min(max((ticks[pid] - old[pid]) * 100 / per_core, 0), 100.0 * m.cpu_count) if per_core > 0 and pid in old else 0.0
        m.procs.append(Proc(pid, to_int(f[2]), to_int(f[5]), to_int(f[4]), f[9], users.get(uid[pid], str(uid[pid])) if pid in uid else '?',
                            f[1][:1] or '?', cpu, rss * 100 / m.mem_total if m.mem_total > 0 else 0, rss, num(f[7]), max(0.0, m.uptime - num(f[6]) / clk)))

    if 'services' in sec: st['services'] = [Service(*f[:4], ' '.join(f[4:])) for f in rows('services') if len(f) >= 4 and f[0].endswith('.service')]
    m.logged_users = to_int(first('users')[0])
    st['ticks'], st['uptime'] = ticks, m.uptime
    m.valid = live  # the first sample has no rates yet
    return finish(m, sec, st, 1000)

COLLECTOR = r'''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 "$@"
'''