Download Server Monitor(python-window)/session.py from mchuca/ServerMonitor: direct link, hf CLI and curl.
- Browser
- Download file 22.3 kB
-
https://huggingface.co/mchuca/ServerMonitor/resolve/main/Server%20Monitor(python-window)/session.py
- Command line
-
hf download 'hf://mchuca/ServerMonitor/Server Monitor(python-window)/session.py'
-
curl -L -o session.py 'https://huggingface.co/mchuca/ServerMonitor/resolve/main/Server%20Monitor(python-window)/session.py'
22.3 kB
| """Connection to one machine (local shell or system ssh), the per-server session | |
| (metrics, live history, rules, autopilot) and the manager of all sessions.""" | |
| import json, os, queue, shutil, subprocess, threading, time | |
| from collections import namedtuple | |
| from datetime import datetime | |
| from types import SimpleNamespace | |
| import plat | |
| from history import Analysis, ProcTrend, ServiceTrend, Store, analyze | |
| from metrics import Metrics | |
| from model import RULE_METRICS, ServerConfig, catalogue, command, new_id | |
| PIPE = subprocess.PIPE | |
| SSH_OPTIONS = ['ConnectTimeout=10', 'ServerAliveInterval=10', 'ServerAliveCountMax=3', 'StrictHostKeyChecking=accept-new', 'LogLevel=ERROR'] | |
| STATUS = ('Disabled', 'Connecting', 'Online', 'Offline') | |
| DISABLED, CONNECTING, ONLINE, OFFLINE = range(4) | |
| AlertEvent = namedtuple('AlertEvent', 'time server severity message') # severity: info|warning|critical|resolved|action | |
| # ---- UI-thread dispatch ----------------------------------------------------------------- | |
| class Loop: | |
| """Hands work to the UI thread: worker threads post() calls, timers are due in pump(), which the UI calls often.""" | |
| def __init__(self): self.calls, self.timers = queue.SimpleQueue(), set() | |
| def post(self, fn, *args): self.calls.put((fn, args)) | |
| def pump(self): | |
| while not self.calls.empty(): | |
| fn, args = self.calls.get() | |
| fn(*args) | |
| now = time.monotonic() | |
| for t in [t for t in self.timers if t.due <= now]: | |
| if t in self.timers: # not stopped by a call that ran just before | |
| t.start() if t.every else t.stop() | |
| t.fn() | |
| loop = Loop() | |
| class Timer: | |
| """Restartable timer on the loop; with every (seconds) it repeats.""" | |
| def __init__(self, fn, every=0): | |
| self.fn, self.every = fn, every | |
| if every: self.start() | |
| def start(self, seconds=None): | |
| self.due = time.monotonic() + (seconds or self.every) | |
| loop.timers.add(self) | |
| def stop(self): loop.timers.discard(self) | |
| class Signal(list): | |
| """List of listeners; calling it calls them all.""" | |
| def __call__(self, *args): | |
| for fn in list(self): fn(*args) | |
| # ---- Link --------------------------------------------------------------------------------- | |
| class Link: | |
| """Streams collector frames and runs one-shot commands on one machine. close() kills everything.""" | |
| def __init__(self, cfg, on_frame, on_lost): | |
| self.cfg, self.on_frame, self.on_lost, self.procs, self.pending, self.closed = cfg, on_frame, on_lost, set(), {}, False | |
| def spawn(self, interval=None, **kw): | |
| c, argv, env = self.cfg, plat.shell(interval), None | |
| if c.transport: | |
| options = SSH_OPTIONS + (['NumberOfPasswordPrompts=1'] if c.password else ['BatchMode=yes']) | |
| if c.password: # a helper script answers ssh's password prompt | |
| env = {'DISPLAY': ':0', **os.environ, 'SSH_ASKPASS': plat.askpass(), 'SSH_ASKPASS_REQUIRE': 'force', 'SERVERMONITOR_ASKPASS': c.password} | |
| argv = ['ssh', *(x for o in options for x in ('-o', o)), *(['-i', os.path.expanduser(c.keyFile)] if c.keyFile else []), | |
| *(['-p', str(c.port)] if c.port != 22 else []), '-T', f'{c.user}@{c.host}' if c.user else c.host, ' '.join(argv)] | |
| try: p = subprocess.Popen(argv, stdin=PIPE, stdout=PIPE, env=env, **plat.SPAWN, **kw) | |
| except OSError as e: raise OSError(f'cannot start {argv[0]}: {e.strerror}') from e | |
| self.procs.add(p) | |
| return p | |
| def post(self, fn, *args): # results reach the UI thread, unless the link was closed meanwhile | |
| loop.post(lambda: self.closed or fn(*args)) | |
| def start(self): | |
| try: p = self.spawn(self.cfg.interval, stderr=PIPE) | |
| except OSError as e: return self.post(self.on_lost, str(e)) | |
| threading.Thread(target=self.stream, args=(p,), daemon=True).start() | |
| def stream(self, p): # worker thread: frames out of stdout, the last error line out of stderr | |
| buf, err = b'', [b''] | |
| def errors(): | |
| for chunk in iter(lambda: p.stderr.read1(4096), b''): err[0] = (err[0] + chunk)[-4096:] | |
| reader = threading.Thread(target=errors, daemon=True) | |
| reader.start() | |
| try: | |
| p.stdin.write(plat.collector(self.cfg.interval).encode()) | |
| p.stdin.close() | |
| for chunk in iter(lambda: p.stdout.read1(1 << 16), b''): | |
| buf += chunk | |
| while b'@@SNAP_END' in buf: | |
| end = buf.find(b'@@SNAP_END') | |
| begin = buf.rfind(b'@@SNAP_BEGIN', 0, end) | |
| if begin >= 0 and loop.calls.qsize() < 100: # a stalled UI must not pile up frames | |
| self.post(self.on_frame, buf[begin:end].decode('utf-8', 'replace')) | |
| buf = buf[end + 10:] | |
| if len(buf) > 8 << 20: buf = b'' | |
| except (OSError, ValueError): | |
| pass # killed while writing or reading | |
| code = p.wait() | |
| reader.join(2) | |
| lines = err[0].decode('utf-8', 'replace').split('\n') | |
| self.post(self.on_lost, next((l.strip() for l in reversed(lines) if l.strip()), f'connection closed (exit code {code})')) | |
| def exec(self, script, timeout, done=None): | |
| """Runs a script; done(code, output) is called on the UI thread (code -1: killed, timed out or not started).""" | |
| try: p = self.spawn(stderr=subprocess.STDOUT) | |
| except OSError as e: return done and self.post(done, -1, str(e)) | |
| self.pending[p] = done | |
| def work(): | |
| try: | |
| out, code = p.communicate(script.encode(), timeout)[0], p.returncode | |
| except subprocess.TimeoutExpired: | |
| plat.kill(p) | |
| try: out, code = p.communicate(timeout=2)[0], -1 | |
| except subprocess.TimeoutExpired: out, code = b'', -1 # something it started still holds the pipe | |
| self.post(self.finished, p, -1 if code < 0 else code, out.decode('utf-8', 'replace') + ('\n[killed or timed out]' if code < 0 else '')) | |
| threading.Thread(target=work, daemon=True).start() | |
| def finished(self, p, code, out): | |
| self.procs.discard(p) | |
| done = self.pending.pop(p) | |
| if done: done(code, out) | |
| def close(self, reason='connection stopped'): | |
| self.closed = True | |
| for p in self.procs: plat.kill(p) | |
| for done in self.pending.values(): | |
| if done: done(-1, reason) | |
| # ---- live history ----------------------------------------------------------------------- | |
| class Live: | |
| """The last hour of samples in memory, for the live charts.""" | |
| KEYS, CAP = 'cpu user sys iowait steal mem cache swap rx tx rd wr load'.split(), 1800 | |
| def __init__(self): self.t, self.s, self.if_rx, self.if_tx = [], {k: [] for k in self.KEYS}, {}, {} | |
| def push(self, m): | |
| n = len(self.t) | |
| def add(v, x): | |
| v[:0] = [0.0] * (n - len(v)) # align series that appeared later | |
| v.append(x) | |
| del v[:-self.CAP] | |
| add(self.t, m.timestamp) | |
| values = (m.cpu_usage, m.cpu_user, m.cpu_system + m.cpu_irq, m.cpu_iowait, m.cpu_steal, m.mem_pct, | |
| (m.cached + m.buffers) * 100 / m.mem_total if m.mem_total > 0 else 0, m.swap_pct, m.net_rx_bps, m.net_tx_bps, | |
| m.disk_read_bps, m.disk_write_bps, m.load1) | |
| for k, x in zip(self.KEYS, values): add(self.s[k], x) | |
| for i in m.nets: | |
| add(self.if_rx.setdefault(i.name, []), i.rx_bps) | |
| add(self.if_tx.setdefault(i.name, []), i.tx_bps) | |
| # ---- session ---------------------------------------------------------------------------- | |
| class Session: | |
| def __init__(self, cfg): | |
| self.cfg, self.status, self.err, self.link, self.engine = cfg, DISABLED, '', None, {} | |
| self.m, self.live, self.an = Metrics(), Live(), Analysis() | |
| self.store = Store(os.path.join(Manager.config_dir(), 'history', cfg.id)) | |
| self.retries, self.paused, self.offline_alerted = 0, False, False | |
| self.reported, self.dry, self.cooldown, self.rules, self.procs, self.svcs = set(), set(), {}, {}, {}, {} # analyzer / rule / tracking state | |
| self.updated, self.analysis_updated, self.alert = Signal(), Signal(), Signal() | |
| self.retry, self.watchdog, first = Timer(self.start), Timer(lambda: self.lost('no data received (timeout)')), Timer(self.analyze) | |
| self.offline = Timer(self.down, cfg.interval) # downtime -> availability: one sample per interval, like uptime | |
| self.timers = [self.retry, self.watchdog, first, self.offline, Timer(self.analyze, 60)] | |
| first.start(3) | |
| def online(self): return self.status == ONLINE and self.m.valid | |
| def down(self): | |
| if self.status == OFFLINE or (self.status == CONNECTING and self.retries): self.record(False) | |
| def set_config(self, c): | |
| old, self.cfg, self.offline.every = self.cfg, c, c.interval | |
| if any(getattr(c, k) != getattr(old, k) for k in ('transport', 'host', 'port', 'user', 'keyFile', 'password', 'interval', 'enabled')): | |
| self.live, self.m, self.procs, self.svcs = Live(), Metrics(), {}, {} # may be another machine now | |
| self.start() if c.enabled else self.stop() | |
| self.updated() | |
| def set_paused(self, paused): | |
| self.paused = paused | |
| self.updated() | |
| def reconnect(self): | |
| self.retries, self.paused = 0, False | |
| self.start() | |
| def drop_link(self, reason): | |
| self.retry.stop() | |
| self.watchdog.stop() | |
| link, self.link = self.link, None | |
| if link: link.close(reason) | |
| def start(self): | |
| self.drop_link('connection restarted') | |
| if not self.cfg.enabled: return self.set_status(DISABLED) | |
| self.engine, self.m.valid = {}, False # online() only again with a fresh sample | |
| self.link = Link(self.cfg, self.frame, self.lost) | |
| self.set_status(CONNECTING) | |
| self.watchdog.start(25) | |
| self.link.start() | |
| def stop(self): | |
| self.drop_link('connection stopped') | |
| self.set_status(OFFLINE if self.cfg.enabled else DISABLED) | |
| def close(self): | |
| self.stop() | |
| for t in self.timers: t.stop() | |
| def set_status(self, status, err=''): | |
| if err or status == ONLINE: self.err = err | |
| if status != self.status: | |
| self.status = status | |
| self.updated() | |
| def frame(self, raw): | |
| now = time.time() * 1000 | |
| self.watchdog.start(max(15, self.cfg.interval * 5 + 10)) | |
| m = plat.parse(raw, self.engine, now) | |
| if m.uptime <= 0: return | |
| if self.status != ONLINE: | |
| self.retries = 0 | |
| if self.offline_alerted: self.raise_alert('resolved', 'Server is back online') | |
| self.offline_alerted = False | |
| self.set_status(ONLINE) | |
| if not m.valid or self.paused: # the first sample has no rates yet | |
| return | |
| if m.uptime < self.m.uptime: self.procs = {} # rebooted: PIDs start again, old trends would be blamed on new processes | |
| first, self.m = not self.m.valid, m | |
| self.live.push(m) | |
| self.record(True) | |
| self.track(now) | |
| self.evaluate_rules() | |
| if first: self.analyze() # first sample of this connection: the last analysis saw "unreachable" | |
| self.updated() | |
| def lost(self, why): | |
| was = self.status == ONLINE | |
| self.drop_link('connection lost: ' + why) | |
| self.set_status(OFFLINE, why) | |
| if (was or self.retries == 1) and not self.offline_alerted: | |
| self.raise_alert('critical', 'Server is unreachable: ' + why) | |
| self.offline_alerted = True | |
| if self.cfg.enabled: | |
| self.retry.start((3, 5, 10, 20, 30, 60)[min(self.retries, 5)]) # back-off | |
| self.retries += 1 | |
| def exec(self, cmd, privileged, done=None, timeout=60): | |
| """Runs a command on the machine; privileged ones go through sudo when the server is set up for it.""" | |
| if self.link and self.status == ONLINE: self.link.exec(plat.wrap(cmd, privileged, self.cfg.useSudo), timeout, done) | |
| elif done: loop.post(done, -1, 'server is not connected') | |
| def metric_value(self, key): | |
| m = self.m | |
| return {'cpu': m.cpu_usage, 'iowait': m.cpu_iowait, 'load': m.load1 * 100 / max(1, m.cpu_count), 'mem': m.mem_pct, 'swap': m.swap_pct, | |
| 'disk': m.max_disk_pct, 'diskio': m.max_disk_util, 'temp': m.max_temp, 'rx': m.net_rx_bps / 1e6, 'tx': m.net_tx_bps / 1e6, | |
| 'failed': m.services_failed, 'procs': len(m.procs), 'gpu': m.gpu_max(), 'gputemp': m.gpu_max(True)}.get(key, 0) | |
| def active_alerts(self): | |
| down = ['Unreachable: ' + self.err] if self.status == OFFLINE else [] | |
| return down + [r.condition() for r in self.cfg.rules if r.id in self.rules and self.rules[r.id].active] | |
| def raise_alert(self, severity, message): self.alert(AlertEvent(datetime.now(), self.cfg.name, severity, message)) | |
| def record(self, up): | |
| m, nan = self.m, float('nan') | |
| self.store.add(int(time.time()), ( | |
| m.cpu_usage, m.cpu_iowait, m.load1, m.mem_pct, m.swap_pct if m.swap_total > 0 else nan, m.max_disk_pct if m.mounts else nan, | |
| m.max_disk_util, m.net_rx_bps, m.net_tx_bps, m.disk_read_bps, m.disk_write_bps, m.max_temp if m.temps else nan, len(m.procs), | |
| m.gpu_max() if m.gpus else nan, m.services_failed), up) | |
| def track(self, now): | |
| """Per-process CPU streaks and RSS per minute; service failure transitions.""" | |
| procs = {} | |
| for p in self.m.procs: | |
| t = self.procs.get(p.pid) | |
| if not t or t.name != p.name: # new, or the pid was reused | |
| t = SimpleNamespace(name=p.name, high_since=0, last_minute=0, rss=[]) | |
| t.protected = plat.protected(p) | |
| t.high_since = 0 if p.cpu < self.cfg.autopilot.runawayCpu else t.high_since or now | |
| if now - t.last_minute >= 60000: t.last_minute, t.rss = now, t.rss[-59:] + [p.rss] | |
| procs[p.pid] = t | |
| self.procs, svcs = procs, {} | |
| for s in self.m.services: | |
| t, failed = self.svcs.get(s.unit) or SimpleNamespace(last='', preexisting=False, fails=[], restarts=[]), s.active == 'failed' | |
| svcs[s.unit] = t | |
| if not t.last: | |
| t.preexisting = failed # failed before monitoring started: leave it alone | |
| elif failed and t.last != 'failed': | |
| t.fails.append(now) | |
| t.preexisting = False | |
| elif not failed: | |
| t.preexisting = False | |
| t.last = s.active | |
| t.fails, t.restarts = ([x for x in v if now - x <= 3600000] for v in (t.fails, t.restarts)) | |
| if svcs: self.svcs = svcs # forgets removed services; a sample without a service list changes nothing | |
| def evaluate_rules(self): | |
| now, m = time.time() * 1000, self.m | |
| for r in self.cfg.rules: | |
| st = self.rules.setdefault(r.id, SimpleNamespace(since=0, last_fire=0, active=False)) | |
| v = self.metric_value(r.metric) | |
| idle = not r.enabled or (r.metric in ('gpu', 'gputemp') and not m.gpus) or (r.metric == 'temp' and not m.temps) | |
| if idle or (v >= r.value if r.op == '<' else v <= r.value): | |
| if st.active and not idle: self.raise_alert('resolved', f'Recovered: {r.condition()} (now {v:.1f})') | |
| del self.rules[r.id] | |
| continue | |
| st.since = st.since or now | |
| if now - st.since < r.duration * 1000 or (st.active and (r.action == 'notify' or now - st.last_fire < r.cooldown * 1000)): continue | |
| unit = catalogue(RULE_METRICS, r.metric, 2) | |
| if not st.active: self.raise_alert(r.severity, f'{r.condition()} (now {v:.1f}' + (f' {unit}' if unit else '') + ')') | |
| st.active, st.last_fire = True, now | |
| action, arg = r.action, r.arg | |
| if action.startswith('kill_top'): # heaviest process that is not protected | |
| best = max((p for p in m.procs if not plat.protected(p)), key=lambda p: p.rss if action == 'kill_top_mem' else p.cpu, default=None) | |
| action, arg = ('kill_pid', str(best.pid)) if best else ('notify', '') | |
| if action != 'notify': self.run(action, arg, f'Automation "{r.condition()}": {r.action_text()}') | |
| def run(self, action, arg, what, done=None): | |
| cmds = {'command': arg, 'disk_cleanup': self.cfg.autopilot.diskCleanupCommand, **{k: command(v, arg) for k, v in plat.CMD.items()}} | |
| if not cmds.get(action): return done and done(-1, 'nothing to do') | |
| def report(code, out): | |
| tail = ' '.join(out.split())[-300:] # one line: events are lines in alerts.log | |
| self.raise_alert('action', f'{what} -> ' + (f'failed ({code})' if code else 'OK') + (f' | {tail}' if tail else '')) | |
| if done: done(code, out) | |
| self.exec(cmds[action], True, report, 300) | |
| def run_finding(self, f, automatic, done=None): | |
| if automatic and f.action == 'restart_service': self.svcs[f.arg].restarts.append(time.time() * 1000) | |
| self.run(f.action, '' if f.action == 'disk_cleanup' else f.arg, ('Autopilot: ' if automatic else 'Manual fix: ') + f'{f.label} ({f.title})', done) | |
| def analyze(self): | |
| now, trends, ap = time.time() * 1000, [], self.cfg.autopilot | |
| for p in self.m.procs: | |
| t = self.procs.get(p.pid) | |
| rss = t.rss if t else [] | |
| growth = rss[-1] - rss[0] if len(rss) >= 2 else 0 | |
| pt = ProcTrend(p.pid, len(rss), p.name, p.user, p.cpu, (now - t.high_since) / 60000 if t and t.high_since else 0, p.rss, growth, | |
| growth * 100 / rss[0] if growth and rss[0] > 0 else 0, | |
| sum(b > a for a, b in zip(rss, rss[1:])) / (len(rss) - 1) if len(rss) >= 2 else 0, bool(t and t.protected)) | |
| if pt.high_cpu_minutes > 0 or pt.minutes >= 30: trends.append(pt) | |
| svcs = [ServiceTrend(unit, t.last == 'failed', t.preexisting, len(t.fails), len(t.restarts)) | |
| for unit, t in self.svcs.items() if t.last == 'failed' or t.fails] | |
| self.an = analyze(self.store, self.m, ap, trends, svcs, self.online()) | |
| for f in self.an.findings: # announce each new finding once | |
| if f.key not in self.reported and f.category != 'Availability': self.raise_alert(f.severity, f'Insight: {f.title} - {f.detail}') | |
| self.reported = {f.key for f in self.an.findings} | |
| dry = set() # act on eligible findings, with cooldowns; a dry run says once what it would do | |
| for f in self.an.findings if ap.enabled and self.online() else (): | |
| if not f.auto: continue | |
| if ap.dryRun: | |
| dry.add(f.key) | |
| if f.key not in self.dry: self.raise_alert('action', f'Autopilot (dry run) would: {f.label} - {f.title}') | |
| elif now - self.cooldown.get(f.key, 0) >= {'disk_cleanup': 6 * 3600000, 'restart_service': 120000}.get(f.action, 900000): | |
| self.cooldown[f.key] = now | |
| self.run_finding(f, True) | |
| self.dry = dry | |
| self.analysis_updated() | |
| # ---- manager ---------------------------------------------------------------------------- | |
| class Manager: | |
| def __init__(self): | |
| self.sessions, self.alerts = [], [] | |
| self.changed, self.alert, self.cleared = Signal(), Signal(), Signal() # server list changed, alert raised, alerts cleared | |
| def config_dir(): | |
| os.makedirs(plat.config_dir(), exist_ok=True) | |
| return plat.config_dir() | |
| def path(self, name): return os.path.join(self.config_dir(), name) | |
| def session(self, server_id): return next((s for s in self.sessions if s.cfg.id == server_id), None) | |
| def attach(self, cfg): | |
| s = Session(cfg) | |
| s.alert.append(self.on_alert) | |
| self.sessions.append(s) | |
| return s | |
| def on_alert(self, e): | |
| self.alerts[:0] = [e] | |
| del self.alerts[2000:] | |
| log = self.path('alerts.log') | |
| try: | |
| with open(log, 'w' if os.path.exists(log) and os.path.getsize(log) > 5 << 20 else 'a', encoding='utf-8') as f: | |
| f.write(f'{e.time.isoformat(timespec="seconds")}\t{e.severity}\t{e.server}\t{e.message}\n') | |
| except OSError: | |
| pass # the event still reaches the window | |
| self.alert(e) | |
| def load(self): | |
| try: | |
| with open(self.path('servers.json'), encoding='utf-8') as f: | |
| for o in json.load(f)['servers']: self.attach(ServerConfig.from_json(o)) | |
| except FileNotFoundError: # first start: monitor this machine | |
| self.attach(ServerConfig(new_id(), 'This computer', 'Local', transport=0)) | |
| self.save() | |
| except (OSError, ValueError, LookupError, TypeError, AttributeError): | |
| pass # unreadable or damaged file: start with the servers read so far | |
| for s in self.sessions: s.start() | |
| self.changed() | |
| def save(self): | |
| tmp = self.path('servers.json.tmp') | |
| with open(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), 'w', encoding='utf-8') as f: | |
| json.dump({'version': 1, 'servers': [s.cfg.to_json() for s in self.sessions]}, f, indent=4) | |
| os.replace(tmp, self.path('servers.json')) | |
| def add(self, cfg): | |
| s = self.attach(cfg) | |
| self.save() | |
| s.start() | |
| self.changed() | |
| return s | |
| def update(self, cfg): | |
| s = self.session(cfg.id) | |
| if s: | |
| s.set_config(cfg) | |
| self.save() | |
| self.changed() | |
| def remove(self, server_id, delete_history): | |
| s = self.session(server_id) | |
| if not s: return | |
| self.sessions.remove(s) | |
| s.alert.clear() | |
| s.close() | |
| if delete_history: shutil.rmtree(s.store.dir, ignore_errors=True) | |
| self.save() | |
| self.changed() | |
| def move(self, server_id, delta): | |
| i = self.sessions.index(self.session(server_id)) | |
| j = min(max(i + delta, 0), len(self.sessions) - 1) | |
| if i != j: | |
| self.sessions.insert(j, self.sessions.pop(i)) | |
| self.save() | |
| self.changed() | |
| def clear_alerts(self): | |
| self.alerts.clear() | |
| self.cleared() | |
| def close(self): | |
| for s in self.sessions: s.close() | |