File size: 9,081 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
"""Lifecycle + leak test of one edition: ui2.py <project> <shots> <long-run seconds> [WxH]. Scratch config, dry run; kills only its own collector child."""
import gc, os, signal, subprocess, sys, threading, time, traceback
sys.dont_write_bytecode = True
proj, shots, long_secs = sys.argv[1], sys.argv[2], float(sys.argv[3])
size = sys.argv[4] if len(sys.argv) > 4 else '1500x940'
sys.path.insert(0, proj)
import tkinter as tk
import plat, session
from model import AutopilotConfig, ServerConfig, new_id
from session import Manager, OFFLINE, ONLINE, CONNECTING, loop
from ui import MainWindow
from widgets import Dialog, Paint
import tabs as tabsmod

os.makedirs(shots, exist_ok=True)
errors, checks = [], []
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)
root.geometry(size + '+0+0')
mgr.load()
tabs = win.detail.tabs
tab = dict(zip((t for t, _ in tabsmod.TABS), tabs.pages))
def wait(sec, until=lambda: False):
    end = time.time() + sec
    while time.time() < end and not until(): root.update(); time.sleep(0.01)
def shot(name):
    wait(0.4)
    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(bool(ok)); print(('PASS ' if ok else 'FAIL ') + name + (f'  [{info}]' if info else ''), flush=True)
def all_widgets(w=None):
    w = w or root; yield w
    for c in w.winfo_children(): yield from all_widgets(c)
def kids():  # live child processes of this test
    out = subprocess.run(['ps', '-o', 'pid=,stat=,comm=', '--ppid', str(os.getpid())], capture_output=True, text=True).stdout.split('\n')
    return [l.split() for l in out if l.strip() and 'Z' not in l.split()[1] and l.split()[2] not in ('ps', 'xwd', 'ffmpeg')]
def modal(action, pick, delay=1200):
    def go():
        ds = [w for w in all_widgets() if isinstance(w, Dialog)]
        if not ds: errors.append('dialog did not open'); return
        [b for b in ds[-1].winfo_children()[-1].winfo_children() if pick in b['text']][0].invoke()
    root.after(delay, go); return action()
def stats():
    gc.collect()
    rss = int(next(l for l in open('/proc/self/status') if l.startswith('VmRSS')).split()[1]) / 1024
    items = sum(len(w.find_all()) for w in all_widgets() if isinstance(w, tk.Canvas))
    return dict(rss=round(rss, 1), threads=threading.active_count(), items=items, widgets=sum(1 for _ in all_widgets()), after=len(root.tk.call('after', 'info')),
                timers=len(loop.timers), fds=len(os.listdir('/proc/self/fd')), kids=len(kids()), queue=loop.calls.qsize())

local = mgr.sessions[0]
print('edition', plat.NAME, 'config', mgr.config_dir(), 'size', size, flush=True)
wait(12, lambda: local.online())
check('local online', local.online(), f'{local.m.hostname} cpu={local.m.cpu_usage:.0f}%')
tag = size.split('x')[0]
shot(f'{tag}-00-dashboard'); win.open(local.cfg.id); wait(1)
for i, title in enumerate(tab):
    tabs.show(i); wait(1.0); shot(f'{tag}-{i + 1:02d}-{title.split()[0].lower()}')
win.show_events(); shot(f'{tag}-12-events'); win.show_dashboard()

# ---- collector dies mid-run -> offline, back-off 3 s, online again; an action in flight fails once ------------------------
win.open(local.cfg.id); tabs.show(list(tab).index('Console')); con = tab['Console']
n_alerts = len(mgr.alerts); threads0 = threading.active_count()
got = []
local.exec('sleep 25', False, lambda code, out: got.append((code, out)))
wait(0.5)
p = next(x for x in local.link.procs if x not in local.link.pending)
t0 = time.time(); os.kill(p.pid, signal.SIGKILL)       # our own collector child
wait(4, lambda: local.status == OFFLINE)
t_off = time.time() - t0
check('killed collector -> offline', local.status == OFFLINE and not local.online(), f'after {t_off:.1f} s: {local.err}')
check('pending command failed with the link', got and (got[0][0] == -1 and 'connection lost' in got[0][1] or plat.NAME != 'Linux'), str(got)[:120])
wait(1); check('command child is gone after the link dropped', not [k for k in kids() if k[2] == 'sleep'], str(kids()))
shot(f'{tag}-30-offline')
wait(12, lambda: local.online())
check('reconnected after the back-off', local.online() and local.retries == 0, f'online again {time.time() - t0:.1f} s after the kill')
msgs = [e.message for e in mgr.alerts[:len(mgr.alerts) - n_alerts]]
check('events: unreachable + back online', any('unreachable' in m for m in msgs) and any('back online' in m for m in msgs), ' | '.join(m[:50] for m in msgs))
wait(1.5); check('reader threads ended', threading.active_count() <= threads0 + 1, f'{threads0} -> {threading.active_count()}')

# several quick reconnects in a row: no pile-up of children or threads
for _ in range(5): local.reconnect(); wait(0.3)
wait(10, lambda: local.online()); wait(1.5)
k = kids()
check('5 quick reconnects: one collector left, threads back', local.online() and len(k) == 1 and threading.active_count() <= threads0 + 1, f'children={k} threads={threading.active_count()}')

# ---- remove a server while its page is open, a command runs and its log dialog is open ---------------------------
extra = mgr.add(ServerConfig(new_id(), 'Temp local', 'Test', transport=0, autopilot=AutopilotConfig(dryRun=True)))
win.open(extra.cfg.id); wait(10, lambda: extra.online())
check('second local server online', extra.online())
tabs.show(list(tab).index('Services')); st = tab['Services']; wait(1.5)
if st.tbl.rows:
    st.tbl.selected = st.tbl.ident(st.tbl.rows[0]); st.logs(); wait(2)
tabs.show(list(tab).index('Console')); con.cmd.put('sleep 25'); con.enter(); wait(0.8)
pt = tab['Processes']; pt.freeze.var.set(True)
before = len(kids())
modal(lambda: win.remove(extra.cfg.id), 'keep history')
wait(1.5)
out = con.out.get('1.0', 'end')
check('server removed while its page was open', mgr.session(extra.cfg.id) is None and win.page is win.dash and win.detail.s is None)
check('its running command was ended', not [k for k in kids() if k[2] == 'sleep'] and len(kids()) == 1, f'{before} -> {kids()}')
dl = [w for w in all_widgets() if isinstance(w, Dialog)]
if dl:
    [b for b in dl[0].winfo_children()[-1].winfo_children() if isinstance(b, tk.Button) and b['text'] == 'Reload'][0].invoke(); wait(0.8)
    txt = [w for w in all_widgets(dl[0]) if isinstance(w, tk.Text)][0].get('1.0', 'end').strip()
    check('log dialog of the removed server: reload is harmless', 'not connected' in txt, txt[:60]); dl[0].close()
wait(3)
check('removed session gets no more samples or timers', extra.link is None and not any(t in loop.timers for t in extra.timers))
win.open(local.cfg.id)
check('freeze switched off for another server', not pt.freeze.var.get())
check('no callback errors so far', not errors, f'{len(errors)}')

# ---- long run: memory, threads, canvas items, timers ---------------------------------------------------------------
samples, t_start, i = [], time.time(), 0
while time.time() - t_start < long_secs:
    tabs.show(i % len(tabs.pages)); i += 1
    if i % 13 == 0: win.show_dashboard(); wait(2); win.show_events(); wait(1); win.open(local.cfg.id)
    if i % 7 == 0: local.analyze()
    if i % 9 == 0: con.cmd.put('echo tick'); con.enter()
    wait(3)
    if i % 5 == 0: samples.append(stats()); print('  ', round(time.time() - t_start), samples[-1], flush=True)
if len(samples) >= 4:
    a, b = samples[1], samples[-1]
    check(f'long run {long_secs:.0f} s: threads, timers, children, fds steady',
          b['threads'] <= a['threads'] and b['timers'] == a['timers'] and b['kids'] == a['kids'] and b['fds'] <= a['fds'] + 2 and b['after'] <= a['after'] + 2, f'{a} -> {b}')
    check('long run: canvas items and widgets do not pile up', b['items'] < a['items'] * 1.5 + 200 and b['widgets'] < a['widgets'] + 80, f"items {a['items']} -> {b['items']}, widgets {a['widgets']} -> {b['widgets']}")
    check('long run: memory steady', b['rss'] - a['rss'] < 12, f"{a['rss']} -> {b['rss']} MB")
check('still online, history grows', local.online() and len(local.store.tiers[0]) > 5, f'{len(local.live.t)} live samples, raw {len(local.store.tiers[0])}')

# ---- quit while a command is running and a test connection is open -------------------------------------------------------
tabs.show(list(tab).index('Console')); con.cmd.put('sleep 25'); con.enter(); wait(0.8)
root.after(600, lambda: [w for w in all_widgets() if isinstance(w, Dialog)][-1].run_test())
root.after(2200, win.quit)
t0 = time.time(); win.add()
root.mainloop() if root.children else None
check('quit with a command running and a dialog open returns at once', time.time() - t0 < 5, f'{time.time() - t0:.1f} s')
time.sleep(0.6)
check('no child process after quit', not kids(), str(kids()))
check('no callback errors', not errors, f'{len(errors)}: ' + ' / '.join(e.strip().splitlines()[-1] for e in errors))
print(f'RESULT {sum(checks)}/{len(checks)} passed', flush=True)