File size: 14,767 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 | """Headless UI drive of one edition: uitest.py <project dir> <shots dir> [min seconds]. Run under xvfb with a scratch config dir."""
import json, os, struct, subprocess, sys, time, traceback
sys.dont_write_bytecode = True
proj, shots, min_secs = sys.argv[1], sys.argv[2], float(sys.argv[3]) if len(sys.argv) > 3 else 70
sys.path.insert(0, proj)
import tkinter as tk
from tkinter import filedialog
import plat
from session import Manager, OFFLINE, ONLINE
from ui import MainWindow, ServerDialog
from widgets import Dialog
os.makedirs(shots, exist_ok=True)
errors, checks, t_start = [], [], time.time()
root, mgr = tk.Tk(), Manager()
def report(*exc):
errors.append(''.join(traceback.format_exception(*exc))); traceback.print_exception(*exc)
root.report_callback_exception = report
win = MainWindow(root, mgr)
mgr.load()
tabs = win.detail.tabs
tab = dict(zip((t for t, _ in __import__('tabs').TABS), tabs.pages))
def wait(sec):
end = time.time() + sec
while time.time() < end:
root.update(); time.sleep(0.01)
def shot(name):
wait(0.3)
xwd = subprocess.run(['xwd', '-root', '-silent'], capture_output=True).stdout
subprocess.run(['ffmpeg', '-loglevel', 'error', '-y', '-f', 'xwd_pipe', '-i', '-', '-pix_fmt', 'rgb24', os.path.join(shots, name + '.png')], input=xwd)
def check(name, ok, info=''):
checks.append((name, bool(ok))); print(('PASS ' if ok else 'FAIL ') + name + (f' [{info}]' if info else ''), flush=True)
def dialogs():
return [w for w in root.winfo_children() + win.detail.winfo_children() + [c for p in tabs.pages for c in p.winfo_children()] if isinstance(w, Dialog) and w.winfo_exists()]
def modal(action, script, delay=1500):
"""Runs a blocking dialog action; script(dialog) is called once it is open and must close it."""
def go():
ds = dialogs()
if not ds: errors.append('dialog did not open'); return
try: script(ds[-1])
except Exception: report(*sys.exc_info()); ds[-1].winfo_exists() and ds[-1].close()
root.after(delay, go)
return action()
local, dead = mgr.sessions[0], mgr.sessions[1]
print('edition', plat.NAME, 'config', mgr.config_dir(), flush=True)
wait(9)
check('local server online with valid data', local.online(), f'status={local.status} cpu={local.m.cpu_usage:.0f}% procs={len(local.m.procs)} host={local.m.hostname}')
check('first frames parsed: cores, memory, mounts, nets', local.m.cpu_count >= 1 and local.m.mem_total > 0 and local.m.mounts and local.m.nets)
check('unreachable ssh host detected', dead.status == OFFLINE and dead.err, dead.err)
shot('00-dashboard')
win.dash.search.put('unreach'); win.dash.filter(); wait(0.3)
check('dashboard search filters cards', len(win.dash.flow.cards) == 2, f'{len(win.dash.flow.cards) - 1} card(s) + add card')
win.dash.search.put(''); win.dash.filter()
win.open(local.cfg.id); wait(1)
for i, (title, page) in enumerate(tab.items()):
tabs.show(i); wait(1.2); shot(f'{i + 1:02d}-{title.split()[0].lower()}')
check('every tab opened', tabs.current == len(tabs.pages) - 1)
# console: a harmless command
con = tab['Console']; tabs.show(list(tab).index('Console'))
con.cmd.put('echo hello-from-test'); con.enter(); wait(3)
out = con.out.get('1.0', 'end')
check('console ran echo', 'hello-from-test' in out and '[exit 0' in out, out.strip().splitlines()[-1])
con.recall(-1); check('console history recall', con.cmd.text() == 'echo hello-from-test')
con.cmd.put(''); shot('20-console-echo')
# processes / services lists
pt = tab['Processes']; tabs.show(list(tab).index('Processes')); wait(1)
n_all = len(pt.tbl.rows); pt.filter.put('python' if plat.NAME == 'Linux' else 'sql'); pt.show(); wait(0.3)
check('process list + filter', 0 < len(pt.tbl.rows) < n_all, f'{len(pt.tbl.rows)} of {n_all} rows')
pt.filter.put(''); pt.show()
pt.tbl.selected = pt.tbl.ident(pt.tbl.rows[0]); check('process selection', pt.selected() is not None, str(pt.selected()))
st = tab['Services']; tabs.show(list(tab).index('Services')); wait(1.5)
n_all = len(st.tbl.rows); st.state.current(2); st.show(); wait(0.3)
check('service list + failed filter', n_all > 0 and len(st.tbl.rows) < n_all, f'{len(st.tbl.rows)} failed of {n_all}')
st.state.current(0); st.show()
st.tbl.selected = st.tbl.ident(st.tbl.rows[0]); st.logs(); wait(4)
logs = [d for d in dialogs()]
text = [w for w in logs[0].winfo_children()[0].winfo_children() if isinstance(w, tk.Text)][0].get('1.0', 'end') if logs else ''
check('service logs dialog loaded', logs and len(text.strip()) > 20 and 'Loading' not in text, text.strip().splitlines()[0][:80] if text.strip() else '')
shot('21-service-logs'); [d.close() for d in logs]
# rule editor: open + cancel, then add a rule with OK, toggle, delete
rt = tab['Alert rules']; tabs.show(list(tab).index('Alert rules')); wait(0.5)
n_rules = len(local.cfg.rules)
modal(lambda: rt.edit(0), lambda d: (shot('22-rule-editor'), d.close()))
check('rule editor opened and cancelled', len(local.cfg.rules) == n_rules)
def ok(d):
[b for b in d.winfo_children()[-1].winfo_children() if b['text'] == 'OK'][0].invoke()
modal(lambda: rt.edit(-1), ok)
check('rule added through the editor', len(local.cfg.rules) == n_rules + 1, local.cfg.rules[-1].condition())
rt.toggle(n_rules); check('rule toggled off', not local.cfg.rules[n_rules].enabled)
rt.rules.selected = n_rules; rt.store([x for i, x in enumerate(local.cfg.rules) if i != rt.index()])
check('rule deleted', len(local.cfg.rules) == n_rules)
# add-server dialog + test connection against the local machine
res = {}
def test_conn(d):
d.via.current(0); d.sync(); shot('23-add-server'); d.run_test()
def done():
res['text'] = d.outcome['text']; shot('24-test-connection'); d.close()
root.after(9000, done)
modal(win.add, test_conn)
check('add-server dialog: test connection (local)', res.get('text', '').startswith('✓ Connected'), res.get('text', ''))
check('cancelled add-server dialog adds nothing', len(mgr.sessions) == 2)
# history: ranges + CSV export
ht = tab['History']; tabs.show(list(tab).index('History')); wait(0.5)
ht.pick(3600); wait(0.5); check('history 1 h range', len(ht.pts) > 3, ht.res['text'])
csv = os.path.join(shots, 'export.csv'); filedialog.asksaveasfilename = lambda **kw: csv
ht.export(); lines = open(csv).read().split('\n')
check('history CSV export', lines[0].startswith('time,samples,online_pct,cpu_avg,cpu_max') and len(lines) == len(ht.pts) + 1 and len(lines[1].split(',')) == 33, lines[1][:60])
os.remove(csv); shot('25-history-1h'); ht.pick(86400)
# insights: analysis + autopilot form edit keeps dry run
it = tab['Insights & Autopilot']; tabs.show(list(tab).index('Insights & Autopilot')); local.analyze(); wait(0.8)
check('analysis ran', local.an.when > 0, f'health {local.an.health} {local.an.grade}, {len(local.an.findings)} finding(s)')
put = dict((n, p) for n, g, p in it.binds)['anomalyZ']; put(3.5); it.store(); wait(0.3)
saved = json.load(open(mgr.path('servers.json')))['servers'][0]
check('autopilot form saved (still dry run)', saved['autopilot']['anomalyZ'] == 3.5 and saved['autopilot']['dryRun'] is True and local.cfg.autopilot.dryRun)
shot('26-insights')
# pause / resume, live window, reconnect, reorder, events page
win.detail.pause.invoke(); wait(0.3); check('pause', local.paused); win.detail.pause.invoke(); check('resume', not local.paused)
tabs.show(0); win.detail.span.current(0); win.detail.refresh(False); check('live window 5 min', tab['Overview'].span == 300000)
mgr.move(dead.cfg.id, -1); check('reorder servers', mgr.sessions[0] is dead); mgr.move(dead.cfg.id, 1)
win.show_events(); wait(0.5); n_ev = len(win.events.rows)
win.event_filter.current(1); win.list_events(); wait(0.3)
check('events page + filter', n_ev > 0 and 0 < len(win.events.rows) <= n_ev, f'{len(win.events.rows)} critical of {n_ev}')
shot('27-events'); win.event_filter.current(0); win.show_dashboard()
# context menus (posting is replaced by a recorder), table sorting, mouse wheel
menus = []
tk.Menu.tk_popup = lambda self, x, y, entry='': menus.append([self.entrycget(i, 'label') for i in range(self.index('end') + 1) if self.type(i) == 'command'])
wait(0.5); win.dash.cards[0].event_generate('<Button-3>', x=30, y=30); win.list.event_generate('<Button-3>', x=40, y=20); root.update()
win.open(local.cfg.id); tabs.show(list(tab).index('Processes')); wait(1)
pt.tbl.cv.event_generate('<Button-3>', x=60, y=80); root.update()
[w for w in win.detail.winfo_children()[0].winfo_children()[0].winfo_children() if isinstance(w, tk.Button) and 'Power' in w['text']][0].event_generate('<Button-1>', x=5, y=5); root.update()
check('context menus: card, sidebar, process, power', len(menus) == 4 and 'Move up' in menus[1] and 'Change priority…' in menus[2] and 'Reboot…' in menus[3], ' | '.join(str(len(m)) for m in menus))
pt.tbl.cv.event_generate('<Button-1>', x=140, y=10); root.update(); names = [r[1].text.lower() for r in pt.tbl.rows]
check('table sorts by a clicked header', pt.tbl.sort == (1, False) and names == sorted(names))
pt.tbl.sort = (4, True); before = pt.tbl.top; pt.tbl.cv.event_generate('<Button-5>', x=140, y=100); pt.tbl.cv.event_generate('<MouseWheel>', x=140, y=100, delta=-120); root.update()
check('mouse wheel scrolls the table', pt.tbl.top > before or len(pt.tbl.rows) <= pt.tbl.visible(), f'top {before} -> {pt.tbl.top}')
# a rule with a harmless command action
import copy
from model import AutopilotConfig, Rule, ServerConfig, new_id, xor_b64
from session import DISABLED
rules = copy.deepcopy(local.cfg.rules) + [Rule(new_id(), 'procs', '>', 'command', 'echo rule-fired-ok', 'info', True, 0.0, 0, 10)]
tabs.show(list(tab).index('Alert rules')); rt.store(rules); wait(7)
log = open(mgr.path('alerts.log')).read()
check('rule action ran a command', 'Process count > 0 (now' in log and 'Automation "Process count > 0": Run a command: echo rule-fired-ok -> OK' in log and 'rule-fired-ok' in log.split('-> OK')[1][:400])
check('rule shows as active problem', 'Process count > 0' in local.active_alerts())
rt.store(rules[:-1])
# autopilot in dry run: a simulated 11-minute CPU streak of an unprotected process must only be reported
busy = next(p for p in local.m.procs if not plat.protected(p))
assert local.cfg.autopilot.dryRun and local.cfg.autopilot.enabled
local.procs[busy.pid].high_since = time.time() * 1000 - 11 * 60000
tabs.show(list(tab).index('Insights & Autopilot')); local.analyze(); wait(0.8)
found = [f for f in local.an.findings if f.key == f'runaway:{busy.pid}']; log = open(mgr.path('alerts.log')).read()
check('autopilot dry run reports instead of acting', found and found[0].auto and found[0].action == 'renice' and
'Autopilot (dry run) would: ' + plat.TEXT['renice'] + ' - Runaway process: ' + busy.name in log and 'Autopilot: ' not in log, found[0].title if found else '')
check('protected processes are excluded', plat.protected(next(p for p in local.m.procs if p.pid <= 4 or p.name in ('systemd', 'sshd'))))
shot('29-insights-dry-run')
# add (edit dialog), disable, remove with its history
extra = mgr.add(ServerConfig(new_id(), 'Temp box', 'Test', '127.0.0.1', 'nobody', port=1, autopilot=AutopilotConfig(dryRun=True))); wait(13)
hdir = extra.store.dir
check('added server: offline, downtime recorded', extra.status == OFFLINE and os.path.getsize(os.path.join(hdir, 'raw.bin')) >= 144, extra.err)
def rename(d): d.name.put('Renamed box'); d.interval.put(5); d.save()
modal(lambda: win.edit(extra.cfg.id), rename)
check('edit dialog saved', extra.cfg.name == 'Renamed box' and extra.cfg.interval == 5 and 'Renamed box' in open(mgr.path('servers.json')).read())
c = copy.deepcopy(extra.cfg); c.enabled = False; mgr.update(c); wait(0.3); check('server disabled', extra.status == DISABLED)
modal(lambda: win.remove(extra.cfg.id), lambda d: [b for b in d.winfo_children()[-1].winfo_children() if 'delete' in b['text']][0].invoke())
check('server removed with its history', len(mgr.sessions) == 2 and not os.path.exists(hdir))
# formats
c = ServerConfig(new_id(), 'x', password='p@ss wörd', notes='n'); j = json.loads(json.dumps(c.to_json()))
check('servers.json round trip + password disguise', ServerConfig.from_json(j) == c and j['password'] != c.password and xor_b64('abc', True) == 'MgcR' and j['transport'] == 1)
import shutil; from history import Store, CPU, DISK, stats
for label, cpp, tier, want in (('C++ app', '~/.local/share/sm-dev/tmp/cfgc/ServerMonitor/ServerMonitor/history/local1', 0, None),
('C++ analyzer test (4 tiers)', '~/.local/share/sm-dev/tmp/python/hist_cpp', 1, [4320, 72, 3])):
cpp, tmp = os.path.expanduser(cpp), os.path.join(shots, 'cpp-hist')
if os.path.isdir(cpp):
shutil.rmtree(tmp, ignore_errors=True); shutil.copytree(cpp, tmp); cs = Store(tmp); n = [len(t) for t in cs.tiers]
on_disk = (os.path.getsize(os.path.join(cpp, 'raw.bin')) - 8) // 136
check(f'history written by the {label} loads', n[tier] > 0 and 0 <= stats(cs.tiers[tier], CPU).avg <= 100 and (want is None and n[0] == on_disk or n[1:] == want),
f'tiers {n}, cpu avg {stats(cs.tiers[tier], CPU).avg:.1f}%, disk avg {stats(cs.tiers[tier], DISK).avg:.1f}%')
shutil.rmtree(tmp)
win.show_dashboard()
wait(max(0, min_secs - (time.time() - t_start)))
shot('28-dashboard-end')
check(f'ran {time.time() - t_start:.0f} s, still online', local.online() and len(local.live.t) > 10, f'{len(local.live.t)} live samples')
hist = os.path.join(mgr.config_dir(), 'history', local.cfg.id)
sizes = {n: os.path.getsize(os.path.join(hist, n)) for n in sorted(os.listdir(hist))}
head = open(os.path.join(hist, 'raw.bin'), 'rb').read(8)
check('history files: SMH1 header + 136-byte records', head == b'SMH1' + bytes([15, 0]) + struct.pack('<H', 136) and all((s - 8) % 136 == 0 for s in sizes.values())
and sizes['raw.bin'] > 8 + 136 * 10 and sizes.get('minute.bin', 0) >= 8 + 136, str(sizes))
dh = os.path.join(mgr.config_dir(), 'history', dead.cfg.id)
check('downtime recorded for the offline host', os.path.getsize(os.path.join(dh, 'raw.bin')) >= 8 + 136 * 3 and len(dead.store.tiers[0]) and sum(dead.store.tiers[0].up) == 0)
log = open(mgr.path('alerts.log')).read()
check('alerts.log has the unreachable event', 'Server is unreachable' in log and len(log.split('\n')[0].split('\t')) == 4)
check('servers.json keeps schema and mode 600', set(saved) >= {'id', 'name', 'transport', 'password', 'rules', 'autopilot', 'keyFile', 'useSudo'} and oct(os.stat(mgr.path('servers.json')).st_mode)[-3:] == '600')
check('no real autopilot action (dry run)', 'Autopilot:' not in log and 'Manual fix' not in log)
win.quit()
check('no exceptions in callbacks', not errors, f'{len(errors)} error(s)')
print(f'RESULT {sum(ok for _, ok in checks)}/{len(checks)} passed, {len(errors)} callback errors')
|