pingerplot 1.6.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,684 @@
1
+ """The History page: what a target did over a span of time, from the history.
2
+
3
+ Pick a target and a range (the last hour to the last year, stepped back and
4
+ forth), and the page shows:
5
+
6
+ * a chart of the destination's latency and loss (or any hop's, picked from
7
+ the Hops table), with the route in use drawn as a coloured band above it
8
+ and reroutes and alerts marked; hovering reads out the moment under the
9
+ pointer;
10
+ * Routes: every route taken, how long, and how the destination did on each,
11
+ so the bad path stands out;
12
+ * Hops: every router seen at each hop and how it did, so "which router" has
13
+ an answer;
14
+ * Events: alerts, reroutes, DNS moves and warnings, filtered and searched.
15
+
16
+ Queries run on a worker thread (a year of minutes is a lot of rows) and the
17
+ results come back through the app's UI queue. Everything can be exported.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import csv
22
+ import os
23
+ import threading
24
+ import time
25
+ import tkinter as tk
26
+ from tkinter import filedialog, messagebox, ttk
27
+ from typing import Dict, List, Optional
28
+
29
+ from . import gui_hopinfo, history, investigate, locating
30
+ from .gui_charts import fmt_ms, nice_max
31
+ from .gui_widgets import Nav, fit_columns, side_scroll
32
+ from .model import csv_safe
33
+
34
+ RANGES = (("Last hour", 3600), ("Last 6 hours", 6 * 3600), ("Last 24 hours", 86400),
35
+ ("Last 7 days", 7 * 86400), ("Last 30 days", 30 * 86400), ("Last year", 365 * 86400))
36
+ DEFAULT_RANGE = "Last 24 hours"
37
+
38
+ # Routes are identities, so a categorical palette in a fixed order: the
39
+ # reference order without its green and red (PingerPlot's latency line and
40
+ # loss). Checked with the dataviz validator against the app's own surfaces
41
+ # (#ffffff, #2b2b2b): adjacent pairs pass in both modes, the first three pass
42
+ # all-pairs. Three light-mode colours are under 3:1 on white, which is why the
43
+ # band carries route numbers and the Routes table repeats them. A seventh
44
+ # route and beyond are grey, numbered.
45
+ ROUTE_COLOURS = {
46
+ False: ("#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#6250d6"),
47
+ True: ("#3987e5", "#d95926", "#199e70", "#c98500", "#d55181", "#9085e9"),
48
+ }
49
+ OTHER_ROUTE = {False: "#9a9a9a", True: "#6e6e6e"}
50
+ EVENT_KINDS = (("alert", "Alerts"), ("route", "Reroutes and moves"), ("warn", "Warnings"),
51
+ ("info", "Notes"), ("clear", "Cleared"))
52
+ MAX_EVENT_ROWS = 2000
53
+ LIVE_REFRESH_MS = 30_000
54
+
55
+
56
+ def _when(t: float, span: float) -> str:
57
+ fmt = "%H:%M" if span <= 86400 else "%a %d %b %H:%M"
58
+ return time.strftime(fmt, time.localtime(t))
59
+
60
+
61
+ def _duration(seconds: float) -> str:
62
+ seconds = int(seconds)
63
+ if seconds < 3600:
64
+ return f"{seconds // 60} min"
65
+ if seconds < 86400:
66
+ return f"{seconds // 3600} h {seconds % 3600 // 60:02d} min"
67
+ return f"{seconds // 86400} d {seconds % 86400 // 3600} h"
68
+
69
+
70
+ def route_colour(index: int, dark: bool) -> str:
71
+ """Colour for the ``index``-th route ever recorded to a target (stable,
72
+ so a route keeps its colour whatever range is shown)."""
73
+ palette = ROUTE_COLOURS[dark]
74
+ return palette[index] if 0 <= index < len(palette) else OTHER_ROUTE[dark]
75
+
76
+
77
+ def draw_chart(c, ink, data: dict, dark: bool, hop: Optional[int]) -> None:
78
+ """The latency/loss chart with the route band. ``data`` is what
79
+ HistoryPage._load produced."""
80
+ S = ink.s
81
+ c.delete("all")
82
+ w, h = c.winfo_width(), c.winfo_height()
83
+ if w < 80 or h < 80:
84
+ return
85
+ since, until = data["since"], data["until"]
86
+ span = max(1.0, until - since)
87
+ pad_l, pad_r, pad_t, pad_b = S(52), S(16), S(46), S(24)
88
+ band_top, band_h = S(22), S(16)
89
+ x0, x1 = pad_l, w - pad_r
90
+ y_base, y_top = h - pad_b, pad_t
91
+
92
+ def X(t):
93
+ return x0 + (x1 - x0) * ((t - since) / span)
94
+
95
+ points = data["series"]
96
+ avgs = [p.avg for p in points if p.avg is not None]
97
+ y_max = nice_max(max(10.0, (max(avgs) if avgs else 50.0) * 1.1))
98
+
99
+ def Y(v):
100
+ return y_base + (y_top - y_base) * (min(v, y_max) / y_max)
101
+
102
+ for frac in (0.0, 0.5, 1.0):
103
+ y = y_base + (y_top - y_base) * frac
104
+ c.create_line(x0, y, x1, y, fill=ink.col["grid"])
105
+ c.create_text(x0 - S(8), y, text=f"{y_max * frac:g}", anchor="e",
106
+ fill=ink.col["axis_text"], font=ink.font(-2))
107
+ what = "Destination" if hop is None else f"Hop {hop}"
108
+ c.create_text(x0, S(10), text=f"{what} · latency (ms) and loss", anchor="w",
109
+ fill=ink.col["title"], font=ink.font(-1, "semibold"))
110
+ for i in range(5):
111
+ t = since + span * i / 4
112
+ c.create_text(X(t), y_base + S(12), text=_when(t, span),
113
+ anchor="w" if i == 0 else ("e" if i == 4 else "center"),
114
+ fill=ink.col["axis_text"], font=ink.font(-2))
115
+
116
+ # The route band: which route was in use, numbered for colour-blind
117
+ # readers and for the three light colours that are faint on white.
118
+ c.create_rectangle(x0, band_top, x1, band_top + band_h, fill=ink.col["grid"], outline="")
119
+ for route in data["routes"]:
120
+ colour = route_colour(data["route_index"].get(route.id, -1), dark)
121
+ for a, b in route.spans:
122
+ xa, xb = X(a), X(b)
123
+ if xb - xa < 1:
124
+ xb = xa + 1
125
+ # A 2 px gap of surface between neighbouring segments.
126
+ c.create_rectangle(xa + 1, band_top, xb - 1, band_top + band_h, fill=colour, outline="")
127
+ if xb - xa > S(18):
128
+ c.create_text((xa + xb) / 2, band_top + band_h / 2, text=str(route.id),
129
+ fill="#ffffff", font=ink.font(-2, "semibold"))
130
+
131
+ # Loss: bars up from the baseline, height = share of probes lost.
132
+ bucket_w = max(1.0, (x1 - x0) / max(1, len(points)))
133
+ for p in points:
134
+ if p.sent and p.recv < p.sent:
135
+ xb = X(p.t)
136
+ top = y_base - (y_base - y_top) * 0.35 * (p.loss_pct / 100.0)
137
+ c.create_rectangle(xb, top, xb + max(1.0, bucket_w - 1), y_base,
138
+ fill=ink.col["loss"], outline="")
139
+ # Latency: a line through each bucket's average, broken where a bucket
140
+ # had no replies at all.
141
+ seg: List[float] = []
142
+ for p in points:
143
+ if p.avg is None:
144
+ if len(seg) >= 4:
145
+ c.create_line(seg, fill=ink.col["line"], width=max(1, S(2)), joinstyle="round")
146
+ seg = []
147
+ continue
148
+ seg.extend((X(p.t + 30), Y(p.avg)))
149
+ if len(seg) >= 4:
150
+ c.create_line(seg, fill=ink.col["line"], width=max(1, S(2)), joinstyle="round")
151
+ elif len(seg) == 2:
152
+ r = max(2, S(3))
153
+ c.create_oval(seg[0] - r, seg[1] - r, seg[0] + r, seg[1] + r, fill=ink.col["line"], outline="")
154
+
155
+ # Reroutes and alerts, marked where they happened.
156
+ for e in data["events"]:
157
+ if e["kind"] not in ("route", "alert") or not since <= e["t"] <= until:
158
+ continue
159
+ x = X(e["t"])
160
+ colour = ink.col["loss"] if e["kind"] == "alert" else ink.col["axis_text"]
161
+ c.create_line(x, band_top + band_h + S(2), x, y_base, fill=colour, dash=(2, 3))
162
+ if not points:
163
+ c.create_text((x0 + x1) / 2, (y_top + y_base) / 2, fill=ink.col["axis_text"],
164
+ font=ink.font(0), text="Nothing recorded for this target in this range.")
165
+
166
+
167
+ class HistoryPage(ttk.Frame):
168
+ def __init__(self, parent, app) -> None:
169
+ super().__init__(parent, padding=(app.s(24), app.s(10), app.s(24), app.s(14)))
170
+ self.app = app
171
+ S = app.s
172
+ self.target_var = tk.StringVar(master=self)
173
+ self.range_var = tk.StringVar(master=self, value=DEFAULT_RANGE)
174
+ self.search_var = tk.StringVar(master=self)
175
+ self.kind_vars = {k: tk.BooleanVar(master=self, value=True) for k, _ in EVENT_KINDS}
176
+ self.until: Optional[float] = None # None: up to now, refreshed while shown
177
+ self.hop: Optional[int] = None # None: the destination
178
+ self.data: Optional[dict] = None
179
+ self._load_seq = 0
180
+ self._refresh_job = None
181
+ self._swatches: Dict[str, tk.PhotoImage] = {}
182
+
183
+ bar = ttk.Frame(self)
184
+ bar.pack(side="top", fill="x")
185
+ ttk.Label(bar, text="Target").pack(side="left")
186
+ self.target_box = ttk.Combobox(bar, textvariable=self.target_var, state="readonly", width=30)
187
+ self.target_box.pack(side="left", padx=(S(6), S(16)))
188
+ self.target_box.bind("<<ComboboxSelected>>", lambda _e: self._pick_target())
189
+ ttk.Combobox(bar, textvariable=self.range_var, values=[r for r, _ in RANGES],
190
+ state="readonly", width=14).pack(side="left")
191
+ self.range_var.trace_add("write", lambda *_a: self._set_until(None))
192
+ ttk.Button(bar, text="◀ Earlier", command=lambda: self._step(-1)).pack(side="left", padx=(S(8), 0))
193
+ self.later_btn = ttk.Button(bar, text="Later ▶", command=lambda: self._step(1))
194
+ self.later_btn.pack(side="left", padx=(S(4), 0))
195
+ ttk.Button(bar, text="Now", command=lambda: self._set_until(None)).pack(side="left", padx=(S(4), 0))
196
+ self.export_btn = ttk.Button(bar, text="Export…", command=self._export_menu)
197
+ self.export_btn.pack(side="right")
198
+
199
+ self.summary = ttk.Label(self, text="", style="Strong.TLabel")
200
+ self.summary.pack(side="top", anchor="w", pady=(S(10), 0))
201
+ self.detail = ttk.Label(self, text="", style="Muted.TLabel")
202
+ self.detail.pack(side="top", anchor="w")
203
+
204
+ card = ttk.Frame(self, style="Tile.TFrame", padding=(S(6), S(6)))
205
+ card.pack(side="top", fill="x", pady=(S(8), 0))
206
+ self.canvas = tk.Canvas(card, height=S(240), highlightthickness=0, bd=0)
207
+ self.canvas.pack(fill="x", expand=True)
208
+ self.canvas.bind("<Configure>", lambda _e: self._draw())
209
+ self.canvas.bind("<Motion>", self._hover)
210
+ self.canvas.bind("<Leave>", lambda _e: self.canvas.delete("hover"))
211
+
212
+ nav_row = ttk.Frame(self)
213
+ nav_row.pack(side="top", fill="x", pady=(S(10), 0))
214
+ self.tabs: Dict[str, ttk.Frame] = {}
215
+ self.nav = Nav(nav_row, app.look, [("routes", "Routes"), ("hops", "Hops"), ("events", "Events")],
216
+ self._show_tab)
217
+ self.nav.pack(side="left")
218
+ self.chart_note = ttk.Label(nav_row, text="", style="Muted.TLabel")
219
+ self.chart_note.pack(side="right")
220
+ host = ttk.Frame(self)
221
+ host.pack(side="top", fill="both", expand=True, pady=(S(6), 0))
222
+ self.tabs["routes"] = self._build_routes(host)
223
+ self.tabs["hops"] = self._build_hops(host)
224
+ self.tabs["events"] = self._build_events(host)
225
+ self.nav.select("routes")
226
+ self._show_tab("routes")
227
+ self.recolor()
228
+
229
+ # --- building -------------------------------------------------------------
230
+ def _table(self, host, cols, tree_col=None):
231
+ S = self.app.s
232
+ card = ttk.Frame(host, style="Tile.TFrame", padding=(S(6), S(6)))
233
+ tree = ttk.Treeview(card, columns=[c[0] for c in cols],
234
+ show="tree headings" if tree_col else "headings", selectmode="browse")
235
+ if tree_col:
236
+ title, width = tree_col
237
+ tree.heading("#0", text=title, anchor="w")
238
+ tree.column("#0", width=S(width), stretch=False, anchor="w")
239
+ for key, title, width, stretch, anchor in cols:
240
+ tree.heading(key, text=title, anchor=anchor)
241
+ tree.column(key, width=S(width), stretch=False, anchor=anchor)
242
+ # The text columns (stretch=True above) give way, down to 70 px,
243
+ # before any number is pushed out of view.
244
+ fit_columns(tree, {key: (S(width), S(70)) for key, _t, width, stretch, _a in cols if stretch})
245
+ vsb = ttk.Scrollbar(card, orient="vertical", command=tree.yview, style="Card.Vertical.TScrollbar")
246
+ tree.configure(yscrollcommand=vsb.set)
247
+ vsb.pack(side="right", fill="y")
248
+ tree.pack(side="left", fill="both", expand=True)
249
+ side_scroll(tree, card)
250
+ return card, tree
251
+
252
+ def _build_routes(self, host):
253
+ card, self.routes_tree = self._table(host, (
254
+ ("time", "Time on it", 110, False, "e"), ("share", "Share", 60, False, "e"),
255
+ ("avg", "Destination avg", 110, False, "e"), ("loss", "Destination loss", 110, False, "e"),
256
+ ("path", "Path (hop by hop)", 520, True, "w")), tree_col=("Route", 80))
257
+ return card
258
+
259
+ def _build_hops(self, host):
260
+ card, self.hops_tree = self._table(host, (
261
+ ("router", "Router", 130, False, "w"), ("name", "Name", 220, True, "w"),
262
+ ("where", "Where", 130, True, "w"), ("net", "Network", 170, True, "w"),
263
+ ("share", "Answered", 80, False, "e"),
264
+ ("loss", "Loss", 60, False, "e"), ("avg", "Avg", 60, False, "e"),
265
+ ("min", "Best", 60, False, "e"), ("max", "Worst", 60, False, "e"),
266
+ ("jitter", "Jitter", 60, False, "e")), tree_col=("Hop", 70))
267
+ self.hops_tree.bind("<<TreeviewSelect>>", lambda _e: self._pick_hop())
268
+ return card
269
+
270
+ def _build_events(self, host):
271
+ S = self.app.s
272
+ view = ttk.Frame(host)
273
+ filt = ttk.Frame(view)
274
+ filt.pack(side="top", fill="x", pady=(0, S(6)))
275
+ for key, label in EVENT_KINDS:
276
+ ttk.Checkbutton(filt, text=label, variable=self.kind_vars[key],
277
+ command=self._fill_events).pack(side="left", padx=(0, S(10)))
278
+ entry = ttk.Entry(filt, textvariable=self.search_var, width=28)
279
+ entry.pack(side="right")
280
+ ttk.Label(filt, text="Search").pack(side="right", padx=(0, S(6)))
281
+ self.search_var.trace_add("write", lambda *_a: self._fill_events())
282
+ card, self.events_tree = self._table(view, (
283
+ ("time", "Time", 150, False, "w"), ("type", "Type", 90, False, "w"),
284
+ ("detail", "Detail", 600, True, "w")))
285
+ card.pack(side="top", fill="both", expand=True)
286
+ self.events_tree.bind("<Double-1>", lambda _e: self._jump_to_event())
287
+ return view
288
+
289
+ def _show_tab(self, key: str) -> None:
290
+ for k, v in self.tabs.items():
291
+ if k == key:
292
+ v.pack(fill="both", expand=True)
293
+ else:
294
+ v.pack_forget()
295
+
296
+ def recolor(self) -> None:
297
+ self.canvas.configure(bg=self.app._ink().col["graph_bg"])
298
+ p = self.app._ink().col
299
+ for kind in ("alert", "clear", "route", "warn"):
300
+ self.events_tree.tag_configure(kind, background=p[f"ev_{kind}"], foreground=p["fg"])
301
+ self._swatches.clear()
302
+ if self.data is not None:
303
+ self._fill()
304
+
305
+ # --- what's shown -----------------------------------------------------------
306
+ def show(self, target: Optional[str] = None) -> None:
307
+ """Called when the page is opened (``target``: the one to show)."""
308
+ if target:
309
+ self.target_var.set(target)
310
+ self.refresh()
311
+
312
+ def hide(self) -> None:
313
+ if self._refresh_job is not None:
314
+ self.after_cancel(self._refresh_job)
315
+ self._refresh_job = None
316
+
317
+ def _span(self) -> int:
318
+ return dict(RANGES).get(self.range_var.get(), 86400)
319
+
320
+ def _range(self):
321
+ until = self.until if self.until is not None else time.time()
322
+ return until - self._span(), until
323
+
324
+ def _step(self, direction: int) -> None:
325
+ since, until = self._range()
326
+ new = until + direction * self._span()
327
+ # Stepping forward back to the present lands a few milliseconds short
328
+ # of it; within a minute of now is now, and the page goes live again.
329
+ self._set_until(None if new >= time.time() - 60 else new)
330
+
331
+ def _set_until(self, until: Optional[float]) -> None:
332
+ self.until = until
333
+ self.refresh()
334
+
335
+ def _pick_target(self) -> None:
336
+ self.hop = None
337
+ self.refresh()
338
+
339
+ def _pick_hop(self) -> None:
340
+ sel = self.hops_tree.selection()
341
+ if not sel:
342
+ return
343
+ item = sel[0]
344
+ parent = self.hops_tree.parent(item) or item
345
+ ttl = int(self.hops_tree.item(parent, "text").split()[-1])
346
+ last = self.data["hops"][-1].ttl if self.data and self.data["hops"] else None
347
+ new = None if ttl == last else ttl
348
+ if new != self.hop:
349
+ self.hop = new
350
+ self.refresh()
351
+
352
+ def _jump_to_event(self) -> None:
353
+ sel = self.events_tree.selection()
354
+ if not sel or not self.data:
355
+ return
356
+ try:
357
+ t = float(sel[0].split(":", 1)[1])
358
+ except (IndexError, ValueError):
359
+ return # the "showing the latest N" note
360
+ half = self._span() / 2
361
+ self._set_until(None if t + half >= time.time() else t + half)
362
+
363
+ # --- loading --------------------------------------------------------------
364
+ def refresh(self) -> None:
365
+ if self._refresh_job is not None:
366
+ self.after_cancel(self._refresh_job)
367
+ self._refresh_job = None
368
+ self._load_seq += 1
369
+ seq = self._load_seq
370
+ target = self.target_var.get()
371
+ since, until = self._range()
372
+ hop = self.hop
373
+ threading.Thread(target=self._load, args=(seq, target, since, until, hop),
374
+ name="history-query", daemon=True).start()
375
+ if self.until is None:
376
+ self._refresh_job = self.after(LIVE_REFRESH_MS, self.refresh)
377
+
378
+ def _load(self, seq, target, since, until, hop) -> None:
379
+ rec = self.app.recorder
380
+ if rec is not None:
381
+ rec.flush(timeout=2) # include what was measured a moment ago
382
+ reader = history.Reader()
383
+ try:
384
+ targets = [r["target"] for r in reader.targets()]
385
+ if not target and targets:
386
+ target = targets[0]
387
+ data = {"targets": targets, "target": target, "since": since, "until": until,
388
+ "series": [], "hops": [], "routes": [], "events": [], "route_index": {},
389
+ "dest": None, "error": ""}
390
+ if target:
391
+ whole = investigate.series(reader, target, since, until, buckets=1)
392
+ data["dest"] = whole[0] if whole else None
393
+ data["series"] = investigate.series(reader, target, since, until, buckets=600, ttl=hop)
394
+ data["hops"] = investigate.hops(reader, target, since, until)
395
+ data["anchors"] = locating.anchors(
396
+ investigate.named_routers(reader, since, until)
397
+ + [(r.name, r.rtt_min) for h in data["hops"] for r in h.routers])
398
+ data["routes"] = investigate.routes(reader, target, since, until)
399
+ data["route_index"] = {r["id"]: i for i, r in enumerate(reader.routes(target))}
400
+ data["events"] = [dict(e) for e in reader.events(since, until, target=target)]
401
+ data["runs"] = [dict(r) for r in reader.runs(target)]
402
+ except Exception as exc: # a locked or damaged file: say so, don't die
403
+ data = {"targets": [], "target": target, "since": since, "until": until, "series": [],
404
+ "hops": [], "routes": [], "events": [], "route_index": {}, "dest": None,
405
+ "error": str(exc)}
406
+ finally:
407
+ reader.close()
408
+ self.app._post(lambda: self._loaded(seq, data))
409
+
410
+ def _loaded(self, seq: int, data: dict) -> None:
411
+ if seq != self._load_seq:
412
+ return # a newer request is on its way
413
+ try:
414
+ if not self.winfo_exists():
415
+ return
416
+ except tk.TclError:
417
+ return
418
+ self.data = data
419
+ live = set(self.app._monitors) - set(self.app._loaded)
420
+ self.target_box.configure(values=sorted(set(data["targets"]) | live))
421
+ if data["target"] and self.target_var.get() != data["target"]:
422
+ self.target_var.set(data["target"])
423
+ self.later_btn.state(["disabled"] if self.until is None else ["!disabled"])
424
+ self._fill()
425
+
426
+ # --- filling ---------------------------------------------------------------
427
+ def _fill(self) -> None:
428
+ d = self.data
429
+ span = d["until"] - d["since"]
430
+ if d["error"]:
431
+ self.summary.configure(text="The history couldn't be read.")
432
+ self.detail.configure(text=d["error"])
433
+ elif not d["target"]:
434
+ self.summary.configure(text="Nothing recorded yet.")
435
+ self.detail.configure(text="Add a target on the Targets page; what it measures appears here.")
436
+ else:
437
+ dest = d["dest"]
438
+ reroutes = sum(1 for e in d["events"] if e["kind"] == "route")
439
+ alerts = sum(1 for e in d["events"] if e["kind"] == "alert")
440
+ when = f"{_when(d['since'], span)} to {'now' if self.until is None else _when(d['until'], span)}"
441
+ if dest and dest.sent:
442
+ self.summary.configure(
443
+ text=f"{d['target']}: {fmt_ms(dest.avg)} ms average, {dest.loss_pct:.1f}% loss "
444
+ f"at the destination")
445
+ else:
446
+ self.summary.configure(text=f"{d['target']}: nothing recorded in this range")
447
+ self.detail.configure(text=f"{when} · {len(d['routes'])} route(s) · {reroutes} reroute(s) "
448
+ f"or moves · {alerts} alert(s)")
449
+ self.chart_note.configure(
450
+ text="Graphing the destination. Pick a hop under Hops to graph it." if self.hop is None
451
+ else f"Graphing hop {self.hop}. Pick the last hop to go back to the destination.")
452
+ self._fill_routes()
453
+ self._fill_hops()
454
+ self._fill_events()
455
+ self._draw()
456
+
457
+ def _swatch(self, colour: str) -> tk.PhotoImage:
458
+ img = self._swatches.get(colour)
459
+ if img is None:
460
+ n = self.app.s(12)
461
+ img = tk.PhotoImage(master=self, width=n, height=n)
462
+ img.put(colour, to=(0, 0, n, n))
463
+ self._swatches[colour] = img
464
+ return img
465
+
466
+ def _fill_routes(self) -> None:
467
+ tree = self.routes_tree
468
+ tree.delete(*tree.get_children())
469
+ dark = self.app.look.dark
470
+ for r in self.data["routes"]:
471
+ colour = route_colour(self.data["route_index"].get(r.id, -1), dark)
472
+ tree.insert("", "end", text=f" {r.id}", image=self._swatch(colour), values=(
473
+ _duration(r.seconds), f"{r.share * 100:.0f}%",
474
+ f"{fmt_ms(r.dest_avg)} ms" if r.dest_avg is not None else "—",
475
+ f"{r.dest_loss_pct:.1f}%" if r.dest_loss_pct is not None else "—",
476
+ investigate.describe_route(r.hops)))
477
+
478
+ def _fill_hops(self) -> None:
479
+ tree = self.hops_tree
480
+ tree.delete(*tree.get_children())
481
+ geo = self.app.geo
482
+ if self.app.lookup_var.get():
483
+ for hop in self.data["hops"]:
484
+ for r in hop.routers:
485
+ geo.request(r.addr)
486
+ where = locating.Locator(geo, self.data.get("anchors", ()), [
487
+ (hop.ttl, hop.routers[0].addr, hop.routers[0].name, hop.routers[0].rtt_min)
488
+ for hop in self.data["hops"] if len(hop.routers) == 1])
489
+ for hop in self.data["hops"]:
490
+ routers = hop.routers
491
+ first = routers[0] if routers else None
492
+ label = first.addr if len(routers) == 1 else (f"{len(routers)} routers" if routers else "no reply")
493
+ one = len(routers) == 1
494
+ parent = tree.insert("", "end", text=f"Hop {hop.ttl}", open=len(routers) > 1, values=(
495
+ label, (first.name or "") if one else "",
496
+ where.where(first.addr, first.name, first.rtt_min, hop.ttl).text if one else "",
497
+ gui_hopinfo.network(first.addr, geo) if one else "",
498
+ f"{hop.recv:,}", f"{hop.loss_pct:.1f}%",
499
+ fmt_ms(first.avg) if len(routers) == 1 else "",
500
+ fmt_ms(first.rtt_min) if len(routers) == 1 else "",
501
+ fmt_ms(first.rtt_max) if len(routers) == 1 else "",
502
+ fmt_ms(first.jitter) if len(routers) == 1 else ""))
503
+ if len(routers) > 1:
504
+ total = sum(r.recv for r in routers) or 1
505
+ for r in routers:
506
+ tree.insert(parent, "end", text="", values=(
507
+ r.addr, r.name or "", where.where(r.addr, r.name, r.rtt_min).text,
508
+ gui_hopinfo.network(r.addr, geo),
509
+ f"{r.recv / total * 100:.0f}%", "", fmt_ms(r.avg),
510
+ fmt_ms(r.rtt_min), fmt_ms(r.rtt_max), fmt_ms(r.jitter)))
511
+
512
+ def _fill_events(self) -> None:
513
+ if self.data is None:
514
+ return
515
+ tree = self.events_tree
516
+ tree.delete(*tree.get_children())
517
+ kinds = {k for k, v in self.kind_vars.items() if v.get()}
518
+ needle = self.search_var.get().strip().lower()
519
+ span = self.data["until"] - self.data["since"]
520
+ rows = [e for e in self.data["events"]
521
+ if (e["kind"] if e["kind"] in self.kind_vars else "info") in kinds
522
+ and (not needle or needle in e["text"].lower())]
523
+ for i, e in enumerate(rows[-MAX_EVENT_ROWS:]):
524
+ tag = e["kind"] if e["kind"] in ("alert", "clear", "route", "warn") else ""
525
+ tree.insert("", "end", iid=f"{i}:{e['t']}", tags=(tag,),
526
+ values=(_when(e["t"], max(span, 86401)), e["kind"], e["text"]))
527
+ if len(rows) > MAX_EVENT_ROWS:
528
+ tree.insert("", 0, values=("", "", f"Showing the latest {MAX_EVENT_ROWS:,} of {len(rows):,}: "
529
+ f"search or pick a shorter range to see the rest."))
530
+
531
+ def _draw(self) -> None:
532
+ if self.data is not None:
533
+ draw_chart(self.canvas, self.app._ink(), self.data, self.app.look.dark, self.hop)
534
+
535
+ def _hover(self, event) -> None:
536
+ c = self.canvas
537
+ c.delete("hover")
538
+ d = self.data
539
+ if not d or not d["series"]:
540
+ return
541
+ S, ink = self.app.s, self.app._ink()
542
+ x0, x1 = S(52), c.winfo_width() - S(16)
543
+ if not x0 <= event.x <= x1:
544
+ return
545
+ span = max(1.0, d["until"] - d["since"])
546
+ t = d["since"] + span * (event.x - x0) / (x1 - x0)
547
+ p = min(d["series"], key=lambda q: abs(q.t + 30 - t))
548
+ route = next((r.id for r in d["routes"] if any(a <= t < b for a, b in r.spans)), None)
549
+ text = f"{_when(p.t, max(span, 86401))} · {fmt_ms(p.avg)} ms · {p.loss_pct:.0f}% loss"
550
+ if route is not None:
551
+ text += f" · route {route}"
552
+ c.create_line(event.x, S(22), event.x, c.winfo_height() - S(24), fill=ink.col["axis_text"],
553
+ tags="hover")
554
+ c.create_text(x1, S(10), text=text, anchor="e", fill=ink.col["title"], font=ink.font(-1),
555
+ tags="hover")
556
+
557
+ # --- export -----------------------------------------------------------------
558
+ def _export_menu(self) -> None:
559
+ menu = tk.Menu(self, tearoff=0)
560
+ menu.add_command(label="Events in this range (CSV)…", command=lambda: self._export("events"))
561
+ menu.add_command(label="Minute summaries in this range (CSV)…", command=lambda: self._export("minutes"))
562
+ menu.add_command(label="Every probe in this range (CSV)…", command=lambda: self._export("probes"))
563
+ try:
564
+ menu.tk_popup(self.winfo_pointerx(), self.winfo_pointery())
565
+ finally:
566
+ menu.grab_release()
567
+
568
+ def _export(self, what: str) -> None:
569
+ d = self.data
570
+ if not d or not d["target"]:
571
+ return
572
+ stamp = time.strftime("%Y%m%d-%H%M", time.localtime(d["until"]))
573
+ path = filedialog.asksaveasfilename(
574
+ parent=self, title="Export from the history", defaultextension=".csv",
575
+ initialfile=f"pingerplot_{d['target']}_{what}_{stamp}.csv",
576
+ filetypes=[("CSV files", "*.csv"), ("All files", "*.*")])
577
+ if not path:
578
+ return
579
+ # A week of every probe is millions of rows: on the window's thread
580
+ # that froze it for many seconds (2026-11 review).
581
+ self.export_btn.state(["disabled"])
582
+ self.export_btn.configure(text="Exporting…")
583
+ post = self.app._post
584
+
585
+ def work() -> None:
586
+ try:
587
+ n = export(what, d["target"], d["since"], d["until"], path,
588
+ progress=lambda k: post(lambda: self._export_progress(k)))
589
+ except Exception as exc: # shown to the user; the button must come back either way
590
+ why = str(exc) or type(exc).__name__
591
+ post(lambda: self._exported(path, None, why))
592
+ return
593
+ post(lambda: self._exported(path, n, ""))
594
+ threading.Thread(target=work, name="history-export", daemon=True).start()
595
+
596
+ def _export_progress(self, n: int) -> None:
597
+ try:
598
+ self.export_btn.configure(text=f"Exporting… {n:,} rows")
599
+ except tk.TclError:
600
+ pass
601
+
602
+ def _exported(self, path: str, n: Optional[int], why: str) -> None:
603
+ try:
604
+ if not self.winfo_exists():
605
+ return
606
+ except tk.TclError:
607
+ return
608
+ self.export_btn.configure(text="Export…")
609
+ self.export_btn.state(["!disabled"])
610
+ if n is None:
611
+ messagebox.showerror("Export failed", why, parent=self)
612
+ else:
613
+ messagebox.showinfo("Exported", f"{n:,} rows written to\n{path}", parent=self)
614
+
615
+
616
+ EXPORT_PROGRESS_EVERY = 50_000
617
+
618
+
619
+ def export(what: str, target: str, since: float, until: float, path: str,
620
+ folder=None, progress=None) -> int:
621
+ """Write one kind of history for ``target`` over the range as CSV.
622
+ Returns the number of rows. Text that a spreadsheet would run as a
623
+ formula is defanged. Rows are written as they're read, so memory stays
624
+ flat however many there are; ``progress(n)`` hears every
625
+ EXPORT_PROGRESS_EVERY rows. The file only takes ``path``'s name once it's
626
+ whole: a failed export leaves no half file behind."""
627
+ if what == "events":
628
+ header = ["time", "iso_time", "kind", "text"]
629
+ elif what == "minutes":
630
+ header = ["minute_start", "iso_time", "hop", "router", "sent", "received", "loss_pct",
631
+ "avg_ms", "min_ms", "max_ms", "jitter_ms"]
632
+ elif what == "probes":
633
+ header = ["time", "iso_time", "round", "hop", "router", "rtt_ms", "status"]
634
+ else:
635
+ raise ValueError(f"nothing called {what!r} to export")
636
+ reader = history.Reader(folder)
637
+ part = path + ".part"
638
+ n = 0
639
+ try:
640
+ with open(part, "w", encoding="utf-8", newline="") as fh:
641
+ w = csv.writer(fh)
642
+ w.writerow(["# PingerPlot history", csv_safe(target), _iso(since), _iso(until)])
643
+ w.writerow(header)
644
+ for row in _export_rows(reader, what, target, since, until):
645
+ w.writerow(row)
646
+ n += 1
647
+ if progress is not None and n % EXPORT_PROGRESS_EVERY == 0:
648
+ progress(n)
649
+ os.replace(part, path)
650
+ except BaseException:
651
+ try:
652
+ os.remove(part)
653
+ except OSError:
654
+ pass
655
+ raise
656
+ finally:
657
+ reader.close()
658
+ return n
659
+
660
+
661
+ def _export_rows(reader: history.Reader, what: str, target: str, since: float, until: float):
662
+ if what == "events":
663
+ for e in reader.events(since, until, target=target, limit=None, lazy=True):
664
+ yield (f"{e['t']:.3f}", _iso(e["t"]), e["kind"], csv_safe(e["text"]))
665
+ elif what == "minutes":
666
+ for m in reader.minutes(target, since, until, lazy=True):
667
+ t = m["minute"] * 60.0
668
+ loss = 100.0 * (m["sent"] - m["recv"]) / m["sent"] if m["sent"] else 0.0
669
+ yield (f"{t:.0f}", _iso(t), m["ttl"], csv_safe(m["addr"]), m["sent"], m["recv"],
670
+ f"{loss:.1f}", _num(m["rtt_sum"] / m["recv"] if m["recv"] else None),
671
+ _num(m["rtt_min"]), _num(m["rtt_max"]),
672
+ _num(m["jit_sum"] / m["jit_n"] if m["jit_n"] else None))
673
+ else:
674
+ for p in reader.probes(target, since, until, lazy=True):
675
+ yield (f"{p['t']:.3f}", _iso(p["t"]), p["round"], p["ttl"], csv_safe(p["addr"]),
676
+ _num(p["rtt"]), p["status"])
677
+
678
+
679
+ def _iso(t: float) -> str:
680
+ return time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(t))
681
+
682
+
683
+ def _num(v) -> str:
684
+ return "" if v is None else f"{v:.3f}".rstrip("0").rstrip(".")