File size: 28,213 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 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 | """Main window: sidebar, dashboard with server cards, server detail page, events page, add / edit dialog."""
import copy, json, os, time, tkinter as tk
from tkinter import filedialog
import plat
from model import ServerConfig, TRANSPORTS, duration, fmt_bytes, new_id, pct, rate
from session import DISABLED, OFFLINE, STATUS, Link, Timer, loop
from tabs import TABS
from widgets import (C, Cell, Chips, Dialog, Entry, F, FIELD, Paint, Scroll, Spin, Table, Tabs, app_icon, ask, box, button, check, choose, combo, down,
elide, field, health, label, level, mix, on_wheel, panel, popup, press, right, severity, textbox, theme, tiles, write)
STATUS_COLORS = (C.faint, C.amber, C.green, C.red) # disabled, connecting, online, offline
# ============================================================================ dashboard cards
class Card(Paint):
def __init__(self, parent, on_click):
super().__init__(parent, 340, 262, cursor='hand2')
self.over = False
self.bind('<Enter>', lambda e: self.hover(True))
self.bind('<Leave>', lambda e: self.hover(False))
self.bind('<ButtonRelease-1>', lambda e: on_click())
def hover(self, over):
self.over = over
self.redraw()
class ServerCard(Card):
def __init__(self, parent, s, win):
super().__init__(parent, lambda: win.open(s.cfg.id))
self.s = s
for signal in (s.updated, s.analysis_updated):
signal.append(self.redraw)
self.bind('<Destroy>', lambda e, signal=signal: signal.remove(self.redraw), add='+')
self.bind('<Button-3>', lambda e: popup(self, e, [('Open details', lambda: win.open(s.cfg.id)), ('Reconnect', s.reconnect), None,
('Edit…', lambda: win.edit(s.cfg.id)), ('Remove…', lambda: win.remove(s.cfg.id))]))
def draw(self):
s, c, m, an, w = self.s, self.s.cfg, self.s.m, self.s.an, self.w
live, sc, bg = s.online(), STATUS_COLORS[s.status], C.hover if self.over else C.card
self.rrect(1, 1, w - 1, self.h - 1, 14, bg, C.accent if self.over else C.border)
for i in range(12): # status strip fading out to the right
self.create_rectangle(10 + i * w / 20, 2, 11 + (i + 1) * w / 20, 6, width=0, fill=mix(sc, bg, i / 12))
self.create_oval(17, 23, 27, 33, fill=sc, width=0)
self.text(36, 28, elide(c.name, F(16, True), w - 120), px=16, bold=True)
self.text(36, 47, elide(c.address() + (f' · {m.os}' if m.os else ''), F(11), w - 60), C.muted, 11)
if live: # health badge
self.ring(w - 62, 12, 44, an.health, health(an.health), 4, False)
self.text(w - 40, 34, an.grade, health(an.health), 15, True, 'center')
else:
chip = STATUS[s.status].upper()
cw = F(10, True).measure(chip) + 18
self.rrect(w - cw - 16, 18, w - 16, 38, 10, mix(bg, sc, .16), sc)
self.text(w - 16 - cw / 2, 28, chip, sc, 10, True, 'center')
hot = bool(m.temps) # four gauges; the last one shows the temperature when there are sensors
gw = (w - 32) / 4
gs = min(gw - 14, 70)
last = ('Temp', m.max_temp) if hot else ('Swap', m.swap_pct)
for i, (name, v) in enumerate((('CPU', m.cpu_usage), ('Memory', m.mem_pct), ('Disk', m.max_disk_pct), last)):
cx, color = 16 + gw * i + gw / 2, level(v, 70, 85) if hot and i == 3 else level(v)
self.ring(cx - gs / 2, 66, gs, min(100, v) if live else 0, color if live else C.faint, 6, live)
self.text(cx, 66 + gs / 2, f'{v:.0f}' + ('°' if hot and i == 3 else '%') if live else '—', C.text if live else C.faint, 14, True, 'center')
self.text(cx, 70 + gs, name, C.muted, 11, anchor='center')
x0, y0, x1, y1 = 16, 166, w - 16, 210 # CPU + memory sparkline (last 5 min)
spark = mix(bg, '#000000', .16)
self.rrect(x0, y0, x1, y1, 8, spark)
for key, color in (('mem', C.violet), ('cpu', C.accent)):
v = s.live.s[key][-150:]
if len(v) > 1:
line = [(x1 - 4 - (x1 - x0 - 8) * (len(v) - 1 - i) / 149, y1 - 4 - min(max(x, 0), 100) / 100 * (y1 - y0 - 8)) for i, x in enumerate(v)]
self.create_polygon(line + [(line[-1][0], y1 - 2), (line[0][0], y1 - 2)], fill=mix(spark, color, .16), width=0)
self.create_line(line, fill=color, width=1.5)
self.text(x0 + 8, y0 + 10, 'CPU', C.accent, 10)
self.text(x0 + 36, y0 + 10, 'MEM', C.violet, 10)
if not live:
state = {DISABLED: 'Monitoring disabled', OFFLINE: 'Unreachable: ' + s.err}.get(s.status, 'Waiting for data…')
return self.text(16, 218, state, C.red if s.status == OFFLINE else C.muted, 11, anchor='nw', width=w - 32)
self.text(16, 226, '↓ ' + rate(m.net_rx_bps), C.teal, 11)
self.text(116, 226, '↑ ' + rate(m.net_tx_bps), C.pink, 11)
self.text(w - 16, 226, f'load {m.load1:.2f} · up {duration(m.uptime)}', C.muted, 11, anchor='e')
pilot = (' · autopilot (dry run)' if c.autopilot.dryRun else ' · autopilot on') if c.autopilot.enabled else ''
self.text(16, 242, f'{m.cpu_count} cores · {len(m.procs)} procs{pilot}', C.muted, 11)
rules = len(s.active_alerts())
if rules + len(an.findings):
badge, color = f'⚠ {rules + len(an.findings)}', C.red if rules or any(f.severity == 'critical' for f in an.findings) else C.amber
bw = F(11).measure(badge) + 14
self.rrect(w - 16 - bw, 233, w - 16, 250, 8, mix(bg, color, .18))
self.text(w - 16 - bw / 2, 242, badge, color, 11, anchor='center')
class AddCard(Card):
def draw(self):
color, cx, cy = C.accent if self.over else C.muted, self.w / 2, self.h / 2 - 14
self.rrect(2, 2, self.w - 2, self.h - 2, 14, mix(C.bg, C.accent, .07) if self.over else '', C.accent if self.over else C.border, width=1.5, dash=(5, 4))
self.create_line(cx - 14, cy, cx + 14, cy, fill=color, width=3, capstyle='round')
self.create_line(cx, cy - 14, cx, cy + 14, fill=color, width=3, capstyle='round')
self.text(cx, cy + 37, 'Add server', color, 14, True, 'center')
self.text(cx, cy + 57, 'This machine · SSH', C.faint, 11, anchor='center')
class Flow(tk.Frame):
"""Lays its cards out in equally wide columns."""
def __init__(self, parent):
super().__init__(parent, bg=parent['bg'])
self.cards = []
self.bind('<Configure>', lambda e: self.arrange())
def arrange(self):
gap, width = 16, self.winfo_width()
cols = max(1, (width + gap) // (320 + gap))
cw = (width - (cols - 1) * gap) // cols
for i, card in enumerate(self.cards): card.place(x=i % cols * (cw + gap), y=i // cols * (262 + gap), width=cw, height=262)
self.config(height=max(1, -(-len(self.cards) // cols) * (262 + gap)))
# ============================================================================ dashboard
class Dashboard(tk.Frame):
def __init__(self, parent, mgr, win):
super().__init__(parent, bg=C.bg, padx=28, pady=20)
self.mgr, self.win, self.cards = mgr, win, []
head = down(box(self))
button(head, '+ Add server', win.add, 'Primary').pack(side='right')
self.search = Entry(head, hint='Search servers…', width=28)
self.search.pack(side='right', padx=10)
self.search.bind('<KeyRelease>', lambda e: self.filter())
down(label(head, 'Dashboard', 'H1'), 2)
self.subtitle = down(label(head, kind='Muted'), 0)
self.t = tiles(self, [('Servers online', C.green), ('Avg health', C.teal), ('Active problems', C.red), ('Avg CPU', C.accent),
('Avg memory', C.violet), ('Total network', C.pink)])
events = panel(self, 'Recent events', 330)
events.pack(side='right', fill='y')
self.events = textbox(events, False, bg=C.panel, wrap='word', padx=0, pady=0, spacing3=8)
down(self.events.frame, 0, fill='both', expand=True)
self.flow = down(Flow(right(Scroll(self), 14, True).body), 0)
self.add_card = AddCard(self.flow, win.add)
mgr.changed.append(self.rebuild)
mgr.alert.append(lambda e: self.list_events())
mgr.cleared.append(self.list_events)
def list_events(self):
write(self.events, '', clear=True)
for e in self.mgr.alerts[:200]: write(self.events, f'{e.time:%H:%M:%S} · {e.server}\n{e.message}\n', severity(e.severity))
self.events.yview_moveto(0)
def rebuild(self):
for card in self.cards: # not destroyed at once: a card's own menu may have caused this
card.place_forget()
card.after_idle(card.destroy)
self.cards = [ServerCard(self.flow, s, self.win) for s in self.mgr.sessions]
self.filter()
self.refresh()
def filter(self):
needle = self.search.text().lower()
for card in self.cards + [self.add_card]: card.place_forget()
self.flow.cards = [c for c in self.cards if needle in ' '.join((c.s.cfg.name, c.s.cfg.host, c.s.cfg.group, c.s.m.hostname)).lower()] + [self.add_card]
self.flow.arrange()
def refresh(self):
t, enabled = self.t, [s for s in self.mgr.sessions if s.cfg.enabled]
up = [s for s in enabled if s.online()]
problems = sum(len(s.active_alerts()) for s in enabled) + sum(f.severity != 'info' for s in up for f in s.an.findings)
self.subtitle.config(text=f'{len(self.mgr.sessions)} server(s) monitored · updated {time.strftime("%H:%M:%S")}')
t[0].set(f'{len(up)} / {len(enabled)}', f'{len(enabled) - len(up)} unreachable' if len(enabled) > len(up) else 'all reachable',
C.green if len(up) == len(enabled) else C.amber)
t[2].set(str(problems), 'alerts + insights' if problems else 'all clear', C.red if problems else C.green)
if not up:
for i in (1, 3, 4, 5): t[i].set('—')
return
score, cpu, mem = (sum(v) / len(up) for v in zip(*((s.an.health, s.m.cpu_usage, s.m.mem_pct) for s in up)))
rx, tx = sum(s.m.net_rx_bps for s in up), sum(s.m.net_tx_bps for s in up)
t[1].set(f'{score:.0f}', 'score 0–100', health(score))
t[3].set(pct(cpu), color=level(cpu))
t[4].set(pct(mem), color=level(mem))
t[5].set(rate(rx + tx), f'↓ {rate(rx)} ↑ {rate(tx)}')
# ============================================================================ detail page
class Detail(tk.Frame):
def __init__(self, parent, mgr, win):
super().__init__(parent, bg=C.bg, padx=28, pady=16)
self.s, self.win = None, win
head = down(box(self), 6)
actions = box(head)
actions.pack(side='right', anchor='s')
window = right(box(actions))
down(label(window, 'LIVE WINDOW', 'Section'), 4)
self.span = down(combo(window, ['Last 5 minutes', 'Last 15 minutes', 'Last 30 minutes', 'Last hour'], 16, lambda: self.refresh(False)), 0)
self.span.current(1)
right(button(actions, '⟳ Reconnect', lambda: self.s.reconnect()), anchor='s', fill='none')
self.pause = right(button(actions, '❚❚ Pause', lambda: self.s.set_paused(not self.s.paused)), anchor='s', fill='none')
right(button(actions, 'Edit', lambda: win.edit(self.s.cfg.id)), anchor='s', fill='none')
power = right(button(actions, '⏻ Power', kind='Danger'), 0, anchor='s', fill='none')
power.bind('<Button-1>', lambda e: popup(self, e, [(f'{text}…', lambda text=text, cmd=cmd: self.power(text, cmd)) for text, cmd in plat.POWER.items()]
+ [None, ('Remove from monitor…', lambda: win.remove(self.s.cfg.id))]))
down(button(head, '‹ Dashboard', win.show_dashboard, 'Flat', padx=0), 2, fill='none', anchor='w')
names = down(box(head), 2)
self.name, self.state = right(label(names, kind='H1')), right(label(names, font=F(12, True)))
self.sub = down(label(head, kind='Muted', wrap=True), 6)
self.chips = down(Chips(head), 0)
self.tabs = down(Tabs(self, lambda: self.refresh(True)), 0, fill='both', expand=True)
for title, make in TABS: self.tabs.add(title, make(self.tabs, mgr.update))
def power(self, text, cmd):
if ask(self, f'{text}…', f'{text} {self.s.cfg.name} now?', True): self.s.exec(cmd, True)
def attach(self, s):
if self.s:
self.s.updated.remove(self.update_sample)
self.s.analysis_updated.remove(self.update_analysis)
self.s = s
for tab in self.tabs.pages: tab.attach(s)
if s:
s.updated.append(self.update_sample)
s.analysis_updated.append(self.update_analysis)
self.header()
self.tabs.show(self.tabs.current)
def refresh(self, with_analysis):
tab = self.tabs.pages[self.tabs.current]
if self.s:
tab.span = (5, 15, 30, 60)[self.span.current()] * 60000
tab.refresh()
if with_analysis: tab.analysis()
def update_sample(self):
if self.winfo_ismapped():
self.header()
self.refresh(False)
def update_analysis(self):
if self.winfo_ismapped():
self.header()
self.tabs.pages[self.tabs.current].analysis()
def header(self):
s, c, m, a = self.s, self.s.cfg, self.s.m, self.s.an
self.name.config(text=c.name)
self.state.config(text='● ' + ('PAUSED' if s.paused else STATUS[s.status].upper()), fg=C.amber if s.paused else STATUS_COLORS[s.status])
self.sub.config(text=f'{c.address()} · {TRANSPORTS[c.transport]}' + (f' · host {m.hostname}' if m.hostname else '')
+ (f' · up {duration(m.uptime)}' if s.online() else f' · {s.err}' if s.status == OFFLINE else ''))
chips = [(m.os, ''), (plat.TEXT['kernel'] + m.kernel if m.kernel else '', ''), (f'{m.cpu_count} cores' if m.cpu_count else '', ''),
(f'{fmt_bytes(m.mem_total)} RAM' if m.mem_total > 0 else '', ''), (c.group, '#7dd3fc'),
(f'health {a.health} ({a.grade})' if s.online() else '', health(a.health)),
(('autopilot: dry run' if c.autopilot.dryRun else 'autopilot: on') if c.autopilot.enabled else '', C.violet)]
self.chips.set([(text, color or '#b9c3d8') for text, color in chips if text.strip()])
self.pause.config(text='▶ Resume' if s.paused else '❚❚ Pause')
# ============================================================================ add / edit dialog
class ServerDialog(Dialog):
"""Edits a copy of a server configuration; run() returns it, or None when cancelled."""
def __init__(self, parent, cfg, groups):
super().__init__(parent, f'Edit server — {cfg.name}' if cfg.name else 'Add server')
self.cfg, self.link, self.timeout = cfg, None, Timer(lambda: self.tested('✗ Timed out after 20 s', C.red))
down(label(self, 'Edit server' if cfg.name else 'Add a server', 'H2'))
f = down(box(self))
self.name = field(f, 'Name', Entry(f, cfg.name, 'e.g. web-01', 50))
self.group = field(f, 'Group', combo(f, groups, edit=True))
self.group.set(cfg.group)
self.via = field(f, 'Connect via', combo(f, ['This machine (local)', 'SSH — nothing to install on the server'], command=self.sync))
self.via.current(cfg.transport)
address, key = field(f, 'Address', box(f)), box(f)
self.host = right(Entry(address, cfg.host, 'hostname or IP address'), grow=True)
right(label(address, 'port', 'Muted'), 6)
self.port = right(Spin(address, 1, 65535, cfg.port), 0)
self.user = field(f, 'User', Entry(f, cfg.user, 'default: your local user name'))
self.key = right(Entry(field(f, 'Private key', key), cfg.keyFile, plat.TEXT['key_hint']), grow=True)
self.browse = right(button(key, 'Browse…', lambda: self.key.put(filedialog.askopenfilename(
parent=self, title='Private key', initialdir=os.path.expanduser('~/.ssh')) or self.key.text())), 0)
self.password = field(f, 'Password', Entry(f, cfg.password, 'optional — keys are recommended', show='•'))
every = field(f, 'Sample every', box(f))
self.interval = right(Spin(every, 1, 300, cfg.interval), 6)
right(label(every, 's', 'Muted'))
self.sudo = check(f, plat.TEXT.get('sudo', ''), cfg.useSudo)
if plat.HAS_SUDO: field(f, '', self.sudo)
self.enabled = field(f, '', check(f, 'Monitoring enabled', cfg.enabled))
self.notes = field(f, 'Notes', tk.Text(f, height=3, width=1, font=F(13), **FIELD))
self.notes.insert('1.0', cfg.notes)
self.hint = down(label(self, kind='Muted', wrap=600))
r = down(box(self))
self.test = right(button(r, 'Test connection', self.run_test))
self.outcome = right(label(r, wrap=440), 0, True) # not .result: that is what run() returns
self.buttons(('Cancel', self.close), ('Save', self.save, 'Primary'))
self.sync()
def collect(self):
c, ssh = copy.deepcopy(self.cfg), self.via.current()
c.name, c.group, c.transport, c.port = self.name.text().strip(), self.group.get().strip(), ssh, self.port.value()
c.host = self.host.text().strip() if ssh else ''
c.user, c.keyFile, c.password, c.interval = self.user.text().strip(), self.key.text().strip(), self.password.text(), self.interval.value()
c.useSudo, c.enabled, c.notes = self.sudo.var.get(), self.enabled.var.get(), self.notes.get('1.0', 'end-1c')
return c
def sync(self):
ssh = self.via.current() == 1
for w in (self.host, self.port, self.user, self.key, self.browse, self.password): w.config(state='normal' if ssh else 'disabled')
self.hint.config(text=plat.TEXT['ssh_hint'] if ssh else 'Monitors the computer this program runs on. No setup needed.')
if not ssh and not self.name.text(): self.name.put('This computer')
def show(self, text, color): self.outcome.config(text=text, fg=color)
def save(self):
c = self.collect()
if not c.name or (c.transport and not c.host): return self.show('Please enter a name and an address.', C.red)
self.close(c)
def run_test(self):
"""Two frames prove that data and rates work."""
c, state, frames, t0 = self.collect(), {}, [], time.monotonic()
c.interval = 1
def frame(raw):
frames.append(plat.parse(raw, state, time.time() * 1000))
if len(frames) == 2:
m = frames[1]
self.tested(f'✓ Connected in {(time.monotonic() - t0) * 1000:.0f} ms — {m.hostname} · {m.os} · {m.cpu_count} cores · '
f'{fmt_bytes(m.mem_total)} RAM · CPU {pct(m.cpu_usage, 0)}', C.green)
self.stop_test()
self.link = Link(c, frame, lambda why: self.tested('✗ ' + why, C.red))
self.test.config(state='disabled')
self.show('Connecting…', C.amber)
self.timeout.start(20)
self.link.start()
def stop_test(self):
self.timeout.stop()
if self.link:
self.link.close()
self.link = None
def tested(self, text, color):
self.stop_test()
self.show(text, color)
self.test.config(state='normal')
def destroy(self): # also when the app quits while the dialog is open
self.stop_test()
super().destroy()
# ============================================================================ main window
class ServerList(Paint):
"""Sidebar list: one row per server with status dot, name, alert count and mini CPU / memory bars."""
ROW = 58
def __init__(self, parent, mgr, win):
super().__init__(parent, 220, 200)
self.mgr, self.current, self.over, self.top = mgr, None, None, 0
self.bind('<Motion>', lambda e: self.hover(self.at(e)))
self.bind('<Leave>', lambda e: self.hover(None))
self.bind('<Button-1>', lambda e: self.at(e) and win.open(self.at(e).cfg.id))
self.bind('<Button-3>', lambda e: self.at(e) and popup(self, e, self.menu(self.at(e).cfg.id, win)))
def menu(self, sid, win):
return [('Open', lambda: win.open(sid)), ('Reconnect', lambda: self.mgr.session(sid).reconnect()), None,
('Move up', lambda: self.mgr.move(sid, -1)), ('Move down', lambda: self.mgr.move(sid, 1)), None,
('Edit…', lambda: win.edit(sid)), ('Remove…', lambda: win.remove(sid))]
def at(self, e):
i = self.top + e.y // self.ROW
return self.mgr.sessions[i] if i < len(self.mgr.sessions) else None
def hover(self, s):
if s is not self.over:
self.over = s
self.redraw()
def scroll(self, step):
top = min(max(self.top + (step > 0) - (step < 0), 0), max(0, len(self.mgr.sessions) - self.h // self.ROW))
moved, self.top = top != self.top, top
self.redraw()
return moved
def draw(self):
w = self.w
for i, s in enumerate(self.mgr.sessions[self.top:]):
y, m, alerts = i * self.ROW + 2, s.m, len(s.active_alerts())
if s.cfg.id == self.current or s is self.over: self.rrect(6, y, w - 6, y + 54, 8, C.select if s.cfg.id == self.current else C.card)
self.create_oval(15.5, y + 13.5, 24.5, y + 22.5, fill=STATUS_COLORS[s.status], width=0)
self.text(32, y + 18, elide(s.cfg.name, F(13, True), w - 82), bold=True)
if alerts:
self.rrect(w - 32, y + 10, w - 12, y + 26, 8, C.red)
self.text(w - 22, y + 18, str(alerts), '#ffffff', 10, True, 'center')
for k, (name, v) in enumerate((('CPU', m.cpu_usage), ('MEM', m.mem_pct))):
by = y + 34 + k * 11
self.text(32, by, name, C.faint, 9)
self.rrect(62, by - 2, w - 20, by + 2, 2, C.grid)
if s.online() and v >= 1: self.rrect(62, by - 2, 62 + (w - 82) * min(v, 100) / 100, by + 2, 2, level(v))
class MainWindow:
def __init__(self, root, mgr):
self.root, self.mgr, self.unseen = root, mgr, 0
theme(root)
try:
with open(mgr.path('window.json')) as f: geometry = json.load(f)['geometry']
except (OSError, ValueError, KeyError):
geometry = '1500x940'
root.title('Server Monitor')
root.geometry(geometry)
root.minsize(1100, 700)
self.icons = app_icon(64), app_icon(34)
root.iconphoto(True, self.icons[0])
root.protocol('WM_DELETE_WINDOW', self.quit)
for event in ('<MouseWheel>', '<Button-4>', '<Button-5>'): root.bind_all(event, on_wheel)
side = tk.Frame(root, bg=C.side, width=260, padx=12, pady=16)
side.pack(side='left', fill='y')
side.pack_propagate(False)
brand = down(box(side), 18)
right(tk.Label(brand, image=self.icons[1], bg=C.side))
down(label(brand, 'Server Monitor', font=F(16, True)), 0)
down(label(brand, 'monitor · analyze · control', 'Small'), 0)
self.nav_dash = down(button(side, '▦ Dashboard', self.show_dashboard, 'Nav', pady=8), 4)
row = down(box(side), 14)
self.badge = tk.Label(row, bg=C.red, fg='#ffffff', font=F(11, True), padx=7)
self.nav_events = right(button(row, '◉ Events & alerts', self.show_events, 'Nav', pady=8), 6, True)
down(label(side, ' SERVERS', 'Section'), 6)
buttons = box(side)
buttons.pack(side='bottom', fill='x')
self.list = down(ServerList(side, mgr, self), 8, fill='both', expand=True)
for i, (text, command, kind) in enumerate((('+ Add', self.add, 'Primary'), ('Edit', lambda: self.edit(self.list.current), None),
('Remove', lambda: self.remove(self.list.current), 'Danger'))):
button(buttons, text, command, kind, padx=4).grid(row=0, column=i, sticky='ew', padx=(6 if i else 0, 0))
buttons.columnconfigure(i, weight=1, uniform='buttons')
self.dash, self.detail, self.events_page = Dashboard(root, mgr, self), Detail(root, mgr, self), tk.Frame(root, bg=C.bg, padx=28, pady=20)
head = down(box(self.events_page))
button(head, 'Clear list', mgr.clear_alerts).pack(side='right')
button(head, 'Open log folder', lambda: plat.open_folder(mgr.config_dir())).pack(side='right', padx=10)
self.event_filter = combo(head, ['All events', 'critical', 'warning', 'info', 'resolved', 'action'], 12, self.list_events)
self.event_filter.pack(side='right')
down(label(head, 'Events & alerts', 'H1'), 2)
down(label(head, 'Alerts, recoveries, insights and every automatic or manual action, newest first. Also written to alerts.log.', 'Muted'), 0)
self.events = down(Table(self.events_page, ['Time', 'Server', 'Type', 'Message'], [170, 180, 100]), 0, fill='both', expand=True)
self.page = self.dash
mgr.changed.append(self.list.redraw)
mgr.cleared.append(self.list_events)
mgr.alert.append(self.on_alert)
Timer(self.tick, 1)
self.show_dashboard()
self.pump()
def pump(self): # worker-thread results and timers run on the UI thread
self.root.after(20, self.pump)
loop.pump()
def tick(self): # sidebar bars + dashboard tiles
self.list.redraw()
if self.page is self.dash: self.dash.refresh()
def show(self, page):
self.page.pack_forget()
self.page = page
page.pack(side='left', fill='both', expand=True)
press(self.nav_dash, page is self.dash)
press(self.nav_events, page is self.events_page)
if page is not self.detail: self.list.current = None
self.list.redraw()
def show_dashboard(self):
self.show(self.dash)
self.dash.refresh()
def show_events(self):
self.show(self.events_page)
self.unseen = 0
self.badge.pack_forget()
self.list_events()
def list_events(self):
kind = self.event_filter.get() if self.event_filter.current() else None
self.events.set([[Cell(f'{e.time:%Y-%m-%d %H:%M:%S}', C.muted, key=i), e.server, Cell(e.severity.upper(), severity(e.severity)),
e.message.replace('\n', ' ')] for i, e in enumerate(self.mgr.alerts) if kind in (None, e.severity)])
def on_alert(self, e):
if self.page is self.events_page:
self.list_events()
elif e.severity in ('critical', 'warning', 'action'):
self.unseen += 1
self.badge.config(text=str(self.unseen))
self.badge.pack(side='left')
def open(self, sid):
if self.mgr.session(sid):
self.detail.attach(self.mgr.session(sid))
self.show(self.detail)
self.list.current = sid
self.list.redraw()
def dialog(self, cfg):
groups = list(dict.fromkeys(s.cfg.group for s in self.mgr.sessions if s.cfg.group))
return ServerDialog(self.root, cfg, groups).run()
def add(self):
cfg = self.dialog(ServerConfig(new_id()))
if cfg: self.open(self.mgr.add(cfg).cfg.id)
def edit(self, sid):
cfg = self.mgr.session(sid) and self.dialog(self.mgr.session(sid).cfg)
if cfg: self.mgr.update(cfg)
def remove(self, sid):
s = self.mgr.session(sid)
choice = s and choose(self.root, 'Remove server', f'Stop monitoring "{s.cfg.name}" and remove it from the list?',
[('Cancel', None), ('Remove, keep history files', None), ('Remove + delete history', 'Danger')])
if choice and choice != 'Cancel':
if self.detail.s is s:
self.detail.attach(None)
self.show_dashboard()
self.mgr.remove(sid, 'delete' in choice)
def quit(self):
try:
with open(self.mgr.path('window.json'), 'w') as f: json.dump({'geometry': self.root.geometry()}, f)
except OSError:
pass
self.mgr.close()
self.root.destroy()
|