Download dev/tests/python/t_core.py from mchuca/ServerMonitor: direct link, hf CLI and curl.
- Browser
- Download file 8.33 kB
-
https://huggingface.co/mchuca/ServerMonitor/resolve/main/dev/tests/python/t_core.py
- Command line
-
hf download hf://mchuca/ServerMonitor/dev/tests/python/t_core.py
-
curl -L -o t_core.py https://huggingface.co/mchuca/ServerMonitor/resolve/main/dev/tests/python/t_core.py
8.33 kB
| """Core checks without a UI: t_core.py <project dir>. Scratch config only; nothing here controls the machine.""" | |
| import os, shutil, struct, subprocess, sys, time | |
| sys.dont_write_bytecode = True | |
| proj = sys.argv[1] | |
| sys.path.insert(0, proj) | |
| scratch = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'scratch-core') | |
| shutil.rmtree(scratch, ignore_errors=True) | |
| os.environ['XDG_CONFIG_HOME'] = os.environ['APPDATA'] = scratch | |
| import plat, session, history | |
| from history import Store, REC, HEADER, H_COUNT | |
| from model import ServerConfig | |
| from metrics import Metrics, Service, Proc | |
| res = [] | |
| def check(name, ok, info=''): | |
| res.append(ok); print(('PASS ' if ok else 'FAIL ') + name + (f' [{info}]' if info else ''), flush=True) | |
| def pump(sec, until=lambda: False): | |
| end = time.time() + sec | |
| while time.time() < end and not until(): | |
| session.loop.pump(); time.sleep(0.02) | |
| # ---- 1. store: buckets left open by the last run are rebuilt ------------------------------- | |
| d = os.path.join(scratch, 'h1') | |
| now = int(time.time()) | |
| st = Store(d) | |
| t_end = now - 3 * 3600 - 1800 # the "previous run" stopped 3.5 h ago, after 2 h of samples | |
| for t in range(t_end - 7200, t_end, 10): st.add(t, [5.0] * H_COUNT, True) | |
| m_before, h_before = len(st.tiers[1]), len(st.tiers[2]) | |
| st = Store(d) | |
| st.add(now, [5.0] * H_COUNT, True) # the new run's first sample closes the old buckets | |
| lm, lh = (t_end - 10) // 60 * 60, (t_end - 10) // 3600 * 3600 | |
| check('reload keeps the minute bucket the last run left open', lm in st.tiers[1].ts, f'minute pts {m_before}->{len(st.tiers[1])}') | |
| check('reload keeps the hour bucket the last run left open', lh in st.tiers[2].ts and st.tiers[2].n[list(st.tiers[2].ts).index(lh)] > 0, f'hour pts {h_before}->{len(st.tiers[2])}') | |
| st = Store(d) | |
| check('second reload changes nothing', lm in st.tiers[1].ts and lh in st.tiers[2].ts and len(set(st.tiers[1].ts)) == len(st.tiers[1]), f'minute={len(st.tiers[1])} hour={len(st.tiers[2])}') | |
| # ---- 2. a cut-off record at the end of a file is removed before appending --------------------- | |
| d = os.path.join(scratch, 'h2') | |
| st = Store(d) | |
| for t in range(now - 600, now - 300, 10): st.add(t, [7.0] * H_COUNT, True) | |
| n0 = len(st.tiers[0]) | |
| with open(os.path.join(d, 'raw.bin'), 'ab') as f: f.write(b'\x01' * 50) # crash in the middle of a write | |
| st = Store(d) | |
| for t in range(now - 300, now, 10): st.add(t, [7.0] * H_COUNT, True) | |
| n1 = len(st.tiers[0]) | |
| st = Store(d) | |
| size = os.path.getsize(os.path.join(d, 'raw.bin')) - len(HEADER) | |
| check('cut-off record does not misalign later appends', len(st.tiers[0]) == n1 and size % REC.size == 0 and all(abs(v - 7) < 1e-6 for v in st.tiers[0].avg[0]), f'before={n0} written={n1} reloaded={len(st.tiers[0])} tail={size % REC.size}') | |
| # ---- 3. link: no orphan after close, exec timeout returns at once ---------------------------- | |
| if plat.NAME == 'Linux': | |
| cfg = ServerConfig('t1', 't', transport=0, interval=30) | |
| frames = [] | |
| link = session.Link(cfg, frames.append, lambda why: frames.append(('lost', why))) | |
| link.start() | |
| pump(8, lambda: frames) | |
| p = next(iter(link.procs)) | |
| kids = subprocess.run(['pgrep', '-P', str(p.pid)], capture_output=True, text=True).stdout.split() | |
| link.close() | |
| time.sleep(0.5) | |
| alive = [k for k in kids if os.path.exists(f'/proc/{k}') and 'sleep' in open(f'/proc/{k}/comm').read()] | |
| check('closing a link leaves no orphaned sleep', frames and kids and not alive, f'frames={len(frames)} children={kids} alive={alive}') | |
| for k in alive: os.kill(int(k), 15) | |
| link = session.Link(cfg, None, None) | |
| got, t0 = [], time.time() | |
| link.exec('sleep 6\n', 1, lambda code, out: got.append((code, out, time.time() - t0))) | |
| pump(9, lambda: got) | |
| check('command time-out reports at once (child still holds the pipe)', got and got[0][2] < 3 and got[0][0] == -1, f'{got}') | |
| link.close() | |
| # a command that is running when the link closes: callback gets -1 and nothing is left behind | |
| link = session.Link(cfg, None, None) | |
| got = [] | |
| link.exec('sleep 20\n', 60, lambda code, out: got.append((code, out))) | |
| pump(0.5) | |
| p = next(iter(link.procs)); kids = subprocess.run(['pgrep', '-P', str(p.pid)], capture_output=True, text=True).stdout.split() | |
| link.close('connection lost: test') | |
| pump(1) | |
| alive = [k for k in kids if os.path.exists(f'/proc/{k}')] | |
| check('pending command fails when the link closes, once', got == [(-1, 'connection lost: test')], f'{got}') | |
| check('its child process is gone', kids and not alive, f'children={kids} alive={alive}') | |
| for k in alive: os.kill(int(k), 15) | |
| # ---- 4. session logic with fed metrics (no processes) --------------------------------------- | |
| session.Link.start = lambda self: None | |
| mgr = session.Manager() | |
| cfg = ServerConfig('s1', 'srv', transport=0) | |
| cfg.autopilot.dryRun = True | |
| s = mgr.attach(cfg) | |
| events = [] | |
| s.alert.append(events.append) | |
| s.status = session.ONLINE | |
| def feed(services, procs=()): | |
| m = Metrics(time.time() * 1000); m.valid = True; m.uptime = 1000; m.cpu_count = 2; m.mem_total = 8e9 | |
| m.services, m.procs = list(services), list(procs) | |
| m.services_failed = sum(x.active == 'failed' for x in m.services) | |
| s.m = m; s.track(m.timestamp); s.evaluate_rules() | |
| svc = lambda name, active: Service(name, 'loaded', active, 'failed' if active == 'failed' else 'running', name) | |
| feed([svc('a.service', 'failed'), svc('b.service', 'active')]) | |
| feed([svc('a.service', 'failed'), svc('b.service', 'failed')]) | |
| s.analyze() | |
| f = {x.key: x for x in s.an.findings} | |
| check('service failed before monitoring is never auto-restarted', 'svc:a.service' in f and not f['svc:a.service'].auto) | |
| check('service that failed later is auto-eligible', 'svc:b.service' in f and f['svc:b.service'].auto) | |
| dry = [e.message for e in events if e.severity == 'action'] | |
| check('dry run only reports', len(dry) == 1 and 'dry run' in dry[0] and 'b.service' in dry[0], f'{dry}') | |
| n = len(events); s.analyze() | |
| check('restart cooldown (2 min) holds', len([e for e in events[n:] if e.severity == 'action']) == 0) | |
| ran = []; s.run_finding = lambda f, automatic, done=None: ran.append(f.key) # never runs anything | |
| s.cfg.autopilot.dryRun = False | |
| s.analyze(); s.analyze() | |
| check('real mode: one restart, then the 2 min cooldown', ran == ['svc:b.service'], str(ran)) | |
| s.cooldown['svc:b.service'] -= 121000; s.analyze() | |
| check('after the cooldown it acts again', ran == ['svc:b.service'] * 2, str(ran)) | |
| s.cfg.autopilot.dryRun = True; n = len(events); s.analyze(); s.analyze() | |
| check('dry run says it once per finding', len([e for e in events[n:] if e.severity == 'action']) == 1) | |
| s.status = session.OFFLINE; s.analyze(); s.status = session.ONLINE | |
| s.m.valid = False; n = len(ran) + len(events); s.cfg.autopilot.dryRun = False; s.analyze(); s.cfg.autopilot.dryRun = True; s.m.valid = True | |
| check('no autopilot action without valid data', len(ran) + len([e for e in events if e.severity == 'action']) <= n, str(ran)) | |
| feed([svc('b.service', 'active')]) # a.service is gone from the list (reset-failed / removed) | |
| s.analyze() | |
| check('a service that disappeared is no longer reported as failed', not any(x.key == 'svc:a.service' for x in s.an.findings), f'{[x.key for x in s.an.findings]}') | |
| # action results are one line in alerts.log | |
| s.exec = lambda cmd, priv, done=None, timeout=60: done(1, 'line one\nline two\n\nline three\n') | |
| s.run('command', 'echo x', 'Test action') | |
| log = open(mgr.path('alerts.log'), encoding='utf-8').read().splitlines() | |
| check('alerts.log has one line per event', all(len(l.split('\t')) == 4 for l in log) and 'line three' in log[-1], f'last={log[-1]!r} lines={len(log)}') | |
| # offline samples weigh like online ones | |
| s.status = session.OFFLINE | |
| n0 = len(s.store.tiers[0]) | |
| t0 = time.time() | |
| while time.time() - t0 < 2 * cfg.interval + 1.5: session.loop.pump(); time.sleep(0.05) | |
| got = len(s.store.tiers[0]) - n0 | |
| check('downtime is sampled once per interval', got >= 2, f'{got} offline samples in {time.time() - t0:.1f} s at interval {cfg.interval} s') | |
| mgr.close() | |
| # corrupt servers.json must not stop the app from starting | |
| open(mgr.path('servers.json'), 'w').write('{"version":1,"servers":[{"id":') | |
| try: | |
| m2 = session.Manager(); m2.load(); ok = True; m2.close() | |
| except Exception as e: ok = repr(e) | |
| check('damaged servers.json does not crash the start', ok is True, str(ok)) | |
| print(f'{sum(res)}/{len(res)} passed') | |