dnskit 0.1.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.
dnskit/cli/render.py ADDED
@@ -0,0 +1,1334 @@
1
+ """Rich renderers for core results."""
2
+
3
+ import re
4
+ import threading
5
+ import time
6
+ from collections.abc import Sequence
7
+
8
+ from rich.console import Console
9
+ from rich.markup import escape
10
+ from rich.padding import Padding
11
+ from rich.panel import Panel
12
+ from rich.spinner import Spinner
13
+ from rich.table import Table
14
+ from rich.tree import Tree
15
+
16
+ from dnskit.core import (
17
+ ANYCAST_NOTE,
18
+ CACHE_TTL_S,
19
+ CHECK_LABELS,
20
+ SLOW_THRESHOLD_MS,
21
+ SPF_LOOKUP_LIMIT,
22
+ Adapter,
23
+ Agreement,
24
+ BatchCheck,
25
+ BatchItem,
26
+ BatchReport,
27
+ Check,
28
+ CheckState,
29
+ CheckStatus,
30
+ ClockState,
31
+ CompareReport,
32
+ Config,
33
+ ConnectError,
34
+ Diagnosis,
35
+ DnssecReport,
36
+ DnssecStatus,
37
+ DoctorReport,
38
+ EmailReport,
39
+ EmailSection,
40
+ FailReason,
41
+ Impact,
42
+ IPv6State,
43
+ KeyInfo,
44
+ LocalReport,
45
+ LookupReport,
46
+ LookupResult,
47
+ LookupStatus,
48
+ PropagationReport,
49
+ ReachReport,
50
+ ReachVerdict,
51
+ ResolverChoice,
52
+ ReverseReport,
53
+ Severity,
54
+ StepStatus,
55
+ TraceMode,
56
+ TraceReport,
57
+ TraceStep,
58
+ Verdict,
59
+ WatchSample,
60
+ WatchSummary,
61
+ ZoneStatus,
62
+ blocked_diagnosis,
63
+ clock_diagnosis,
64
+ describe_key,
65
+ doctor_verdict,
66
+ explain,
67
+ explain_dnssec,
68
+ explain_propagation,
69
+ explain_reach,
70
+ explain_reverse,
71
+ explain_trace,
72
+ trace_blocked_diagnosis,
73
+ )
74
+
75
+ # Short reasons shown inside result tables; the full explanation goes in a panel below.
76
+ _STATUS_LABELS: dict[LookupStatus, str] = {
77
+ LookupStatus.NXDOMAIN: "domain does not exist (NXDOMAIN)",
78
+ LookupStatus.NO_ANSWER: "no records",
79
+ LookupStatus.SERVFAIL: "server failure (SERVFAIL)",
80
+ LookupStatus.TIMEOUT: "timed out",
81
+ LookupStatus.NO_NETWORK: "no network",
82
+ LookupStatus.NO_NAMESERVERS: "refused by all nameservers",
83
+ }
84
+
85
+ # Problems that warrant a red panel; the rest (no records, NXDOMAIN) are answers, not faults.
86
+ _FAULTS = {
87
+ LookupStatus.SERVFAIL,
88
+ LookupStatus.TIMEOUT,
89
+ LookupStatus.NO_NETWORK,
90
+ LookupStatus.NO_NAMESERVERS,
91
+ }
92
+
93
+ # Hosts files used as ad blockers can have thousands of lines; show only the first few.
94
+ _MAX_HOSTS_ROWS = 15
95
+
96
+
97
+ def _age(probed_at: float) -> str:
98
+ seconds = max(0.0, time.time() - probed_at)
99
+ if seconds < 60:
100
+ return f"{seconds:.0f}s ago"
101
+ return f"{seconds / 60:.0f} min ago"
102
+
103
+
104
+ def _print_footer(
105
+ console: Console,
106
+ nameserver: str,
107
+ source: str,
108
+ elapsed_ms: float,
109
+ choice: ResolverChoice | None,
110
+ ) -> None:
111
+ """The resolver line, plus any system nameservers that failed or were slow to answer."""
112
+ if choice is not None and choice.from_cache:
113
+ source += f"; cached, probed {_age(choice.probed_at)}"
114
+ console.print(
115
+ f"[dim]Resolver: {escape(nameserver)} ({escape(source)}) · {elapsed_ms:.0f} ms total[/dim]"
116
+ )
117
+ if choice is None:
118
+ return
119
+
120
+ problems = []
121
+ if choice.failed:
122
+ names = ", ".join(escape(p.nameserver) for p in choice.failed)
123
+ problems.append(f"no response from {names}")
124
+ if choice.slow:
125
+ names = ", ".join(f"{escape(p.nameserver)} ({p.latency_ms:.0f} ms)" for p in choice.slow)
126
+ problems.append(f"slow: {names}")
127
+ if problems:
128
+ console.print(
129
+ f"[yellow]Nameserver problems[/yellow] [dim](probed {_age(choice.probed_at)}; "
130
+ f"run `dnskit resolvers` for details):[/dim] {'; '.join(problems)}"
131
+ )
132
+
133
+
134
+ def render_diagnosis(
135
+ diagnosis: Diagnosis, status: LookupStatus, console: Console, affected: str = ""
136
+ ) -> None:
137
+ title = f"[bold]{escape(diagnosis.title)}[/bold]"
138
+ if affected:
139
+ title += f" [dim]({escape(affected)})[/dim]"
140
+ body = (
141
+ f"{escape(diagnosis.explanation)}\n\n[bold]Next step:[/bold] {escape(diagnosis.suggestion)}"
142
+ )
143
+ style = "red" if status in _FAULTS else "yellow"
144
+ console.print(Panel(body, title=title, title_align="left", border_style=style))
145
+
146
+
147
+ def _diagnosed_statuses(results: Sequence[LookupResult]) -> dict[LookupStatus, list[str]]:
148
+ """Group non-OK results by status, for the explanation panels.
149
+
150
+ In a multi-type lookup, a few types having no records is normal (most domains have no
151
+ CNAME at the apex, for example), so NO_ANSWER is only explained when it's the whole story.
152
+ """
153
+ groups: dict[LookupStatus, list[str]] = {}
154
+ for result in results:
155
+ if result.status is not LookupStatus.OK:
156
+ groups.setdefault(result.status, []).append(result.rtype)
157
+ no_answer = groups.get(LookupStatus.NO_ANSWER, [])
158
+ if len(results) > 1 and 0 < len(no_answer) < len(results):
159
+ del groups[LookupStatus.NO_ANSWER]
160
+ return groups
161
+
162
+
163
+ def render_report(report: LookupReport, console: Console, timeout: float | None = None) -> None:
164
+ groups = _diagnosed_statuses(report.results)
165
+
166
+ if not all(r.status is LookupStatus.NXDOMAIN for r in report.results):
167
+ table = Table(title=escape(report.name), title_justify="left")
168
+ table.add_column("Type", style="bold")
169
+ table.add_column("Value", style="cyan", overflow="fold")
170
+ table.add_column("TTL", justify="right")
171
+ for i, result in enumerate(report.results):
172
+ if i:
173
+ table.add_section()
174
+ if result.status is LookupStatus.OK:
175
+ for j, record in enumerate(result.records):
176
+ rtype = result.rtype if j == 0 else ""
177
+ table.add_row(rtype, escape(record.value), str(record.ttl))
178
+ else:
179
+ table.add_row(result.rtype, f"[dim]{_STATUS_LABELS[result.status]}[/dim]", "")
180
+ console.print(table)
181
+
182
+ multi_type = len(report.results) > 1
183
+ for status, rtypes in groups.items():
184
+ diagnosis = explain(status, report.name, rtypes[0], timeout)
185
+ if diagnosis is not None:
186
+ affected = (
187
+ ", ".join(rtypes) if multi_type and status is not LookupStatus.NXDOMAIN else ""
188
+ )
189
+ render_diagnosis(diagnosis, status, console, affected)
190
+
191
+ _print_footer(
192
+ console,
193
+ report.nameserver,
194
+ report.nameserver_source,
195
+ report.elapsed_ms,
196
+ report.resolver_choice,
197
+ )
198
+
199
+
200
+ def render_reverse(report: ReverseReport, console: Console, timeout: float | None = None) -> None:
201
+ result = report.result
202
+ if result.status is LookupStatus.OK:
203
+ # A heading line rather than a table title: titles wrap to the (narrow) table width.
204
+ console.print(f"[bold]{escape(report.ip)}[/bold] [dim](IPv{report.version})[/dim]")
205
+ table = Table()
206
+ table.add_column("Hostname", style="cyan", overflow="fold")
207
+ table.add_column("TTL", justify="right")
208
+ for record in result.records:
209
+ table.add_row(escape(record.value), str(record.ttl))
210
+ console.print(table)
211
+ else:
212
+ diagnosis = explain_reverse(result.status, report.ip, timeout)
213
+ if diagnosis is not None:
214
+ render_diagnosis(diagnosis, result.status, console, f"{report.ip}, IPv{report.version}")
215
+
216
+ console.print(f"[dim]PTR name: {escape(report.ptr_name)}[/dim]")
217
+ _print_footer(
218
+ console,
219
+ report.nameserver,
220
+ report.nameserver_source,
221
+ report.elapsed_ms,
222
+ report.resolver_choice,
223
+ )
224
+
225
+
226
+ def render_compare(report: CompareReport, console: Console) -> None:
227
+ table = Table(
228
+ title=f"{escape(report.name)} {report.rtype} across {len(report.answers)} resolvers",
229
+ title_justify="left",
230
+ )
231
+ table.add_column("Resolver", style="bold")
232
+ table.add_column("IP")
233
+ table.add_column("Answer", overflow="fold")
234
+ table.add_column("TTL", justify="right")
235
+ table.add_column("Time", justify="right")
236
+ table.add_column("")
237
+ split = not report.all_agree # only mark the majority when someone disagrees
238
+
239
+ for i, answer in enumerate(report.answers):
240
+ if i:
241
+ table.add_section()
242
+ result = answer.result
243
+ value, marker = _agreement_cells(result, answer.agreement, report.has_majority, split)
244
+ ttl = "" if answer.ttl is None else str(answer.ttl)
245
+ table.add_row(
246
+ escape(answer.label),
247
+ escape(answer.nameserver),
248
+ value,
249
+ ttl,
250
+ f"{result.elapsed_ms:.0f} ms",
251
+ marker,
252
+ )
253
+ console.print(table)
254
+ console.print(_compare_summary(report))
255
+ console.print(
256
+ f"[dim]Queried {len(report.answers)} resolvers in parallel · "
257
+ f"{report.elapsed_ms:.0f} ms total[/dim]"
258
+ )
259
+
260
+
261
+ def _agreement_cells(
262
+ result: LookupResult, agreement: Agreement, has_majority: bool, split: bool
263
+ ) -> tuple[str, str]:
264
+ """The answer and marker cells for one resolver in compare or propagation."""
265
+ if agreement is Agreement.FAILED:
266
+ return f"[red]{_STATUS_LABELS[result.status]}[/red]", "[bold red]✗ failed[/bold red]"
267
+ # With no majority nobody is the odd one out, so the answers aren't highlighted.
268
+ odd_one_out = agreement is Agreement.DIFFERS and has_majority
269
+ style = "yellow" if odd_one_out else "cyan"
270
+ if result.status is LookupStatus.OK:
271
+ # Sorted, because resolvers return records in varying order.
272
+ values = sorted((r.value for r in result.records), key=_natural_key)
273
+ value = "\n".join(f"[{style}]{escape(v)}[/{style}]" for v in values)
274
+ else:
275
+ value = f"[{style}]{_STATUS_LABELS[result.status]}[/{style}]"
276
+ if odd_one_out:
277
+ marker = "[bold yellow]≠ differs[/bold yellow]"
278
+ elif agreement is Agreement.DIFFERS:
279
+ marker = "[dim]varies[/dim]"
280
+ else:
281
+ marker = "[green]majority[/green]" if split else ""
282
+ return value, marker
283
+
284
+
285
+ def _compare_summary(report: CompareReport) -> str:
286
+ responded = len(report.responded)
287
+ failed = ""
288
+ if report.failed:
289
+ names = ", ".join(
290
+ f"{escape(a.label)} ({_STATUS_LABELS[a.result.status]})" for a in report.failed
291
+ )
292
+ failed = f" [red]{len(report.failed)} failed:[/red] {names}."
293
+
294
+ if not responded:
295
+ return f"[bold red]No resolver answered.[/bold red]{failed} Check your network connection."
296
+ if report.all_agree:
297
+ if report.failed:
298
+ return (
299
+ f"[bold green]✓ All {responded} resolvers that answered agree.[/bold green]{failed}"
300
+ )
301
+ return f"[bold green]✓ All {responded} resolvers agree.[/bold green]"
302
+
303
+ if report.has_majority:
304
+ names = ", ".join(escape(a.label) for a in report.differing)
305
+ verdict = (
306
+ f"[bold yellow]≠ {len(report.differing)} of {responded} resolvers disagree with the "
307
+ f"majority answer[/bold yellow] (given by {len(report.majority)}): {names}."
308
+ )
309
+ else:
310
+ verdict = (
311
+ f"[bold yellow]≠ Resolvers disagree, with no majority:[/bold yellow] {responded} "
312
+ f"resolvers gave {report.distinct_answers} different answers."
313
+ )
314
+ if report.rtype in ("A", "AAAA"):
315
+ verdict += (
316
+ " [dim]Different addresses can be normal for sites on a CDN, which give each "
317
+ "resolver a nearby server.[/dim]"
318
+ )
319
+ return verdict + failed
320
+
321
+
322
+ def _natural_key(value: str) -> list[int | str]:
323
+ """Sort key that orders numbers numerically, so "5 mx." comes before "10 mx."."""
324
+ return [int(part) if part.isdigit() else part.lower() for part in re.split(r"(\d+)", value)]
325
+
326
+
327
+ def _adapter_order(adapters: tuple[Adapter, ...]) -> list[Adapter]:
328
+ """Connected adapters first, each bridge member right after the adapter it's bridged into."""
329
+ ordered = sorted(adapters, key=lambda a: not a.connected)
330
+ names = {a.name for a in adapters}
331
+ result = []
332
+ for adapter in ordered:
333
+ if adapter.bridged_into in names:
334
+ continue # listed under its bridge
335
+ result.append(adapter)
336
+ result.extend(m for m in ordered if m.bridged_into == adapter.name)
337
+ return result
338
+
339
+
340
+ def render_local(report: LocalReport, console: Console) -> None:
341
+ scan = report.scan
342
+ table = Table(title=f"Network adapters ({report.platform})", title_justify="left")
343
+ table.add_column("Adapter", style="bold")
344
+ table.add_column("Status")
345
+ table.add_column("DNS servers", overflow="fold")
346
+ for adapter in _adapter_order(scan.adapters):
347
+ status = "[green]connected[/green]" if adapter.connected else "[dim]disconnected[/dim]"
348
+ if adapter.vpn:
349
+ status += ", [cyan]VPN[/cyan]" if adapter.connected else "[dim], VPN[/dim]"
350
+ if adapter.bridged_into:
351
+ status += f", bridged into {escape(adapter.bridged_into)}"
352
+ dns = f"[dim]uses {escape(adapter.bridged_into)}'s[/dim]"
353
+ elif scan.dns_per_adapter:
354
+ dns = ", ".join(escape(ns) for ns in adapter.dns_servers) or "[dim]none[/dim]"
355
+ else:
356
+ dns = "[dim]not reported[/dim]"
357
+ table.add_row(
358
+ escape(adapter.name), status, dns if adapter.connected else f"[dim]{dns}[/dim]"
359
+ )
360
+ if scan.adapters:
361
+ console.print(table)
362
+ else:
363
+ console.print("[yellow]No network adapters found.[/yellow]")
364
+ if not scan.dns_per_adapter and not scan.error:
365
+ console.print(
366
+ "[dim]This system doesn't report DNS servers per adapter (no systemd-resolved or "
367
+ "scutil), so the servers below come from the system configuration.[/dim]"
368
+ )
369
+
370
+ servers = Table(
371
+ title=f"DNS servers (test query, {report.probe_timeout:g} s timeout)", title_justify="left"
372
+ )
373
+ servers.add_column("Server")
374
+ servers.add_column("Adapter")
375
+ servers.add_column("Response", justify="right")
376
+ servers.add_column("")
377
+ for server in report.servers:
378
+ if server.adapters:
379
+ listed = ", ".join(
380
+ escape(a.name) if a.connected else f"[dim]{escape(a.name)} (disconnected)[/dim]"
381
+ for a in server.adapters
382
+ )
383
+ else:
384
+ listed = "[dim]none[/dim]" if scan.dns_per_adapter else "[dim]system config[/dim]"
385
+ if server.vpn_blocked:
386
+ response = "[yellow]no response[/yellow]"
387
+ elif server.failed:
388
+ response = "[red]no response[/red]"
389
+ elif server.slow:
390
+ response = f"[yellow]{server.latency_ms:.0f} ms[/yellow]"
391
+ else:
392
+ response = f"[green]{server.latency_ms:.0f} ms[/green]"
393
+ if server.ghost:
394
+ marker = "[magenta]ghost (ignored)[/magenta]"
395
+ elif server.vpn_blocked:
396
+ marker = "[yellow]blocked by VPN?[/yellow]"
397
+ elif server.failed:
398
+ marker = "[bold red]✗ failing[/bold red]"
399
+ elif server.slow:
400
+ marker = "[yellow]slow[/yellow]"
401
+ else:
402
+ marker = ""
403
+ name = escape(server.nameserver)
404
+ if server.public:
405
+ name += f" [dim]({escape(server.public)})[/dim]"
406
+ servers.add_row(name, listed, response, marker)
407
+ if report.servers:
408
+ console.print(servers)
409
+ else:
410
+ console.print("[red]No DNS servers are configured.[/red]")
411
+ _local_checks(report, console)
412
+
413
+ hosts = report.hosts
414
+ if hosts.entries:
415
+ entries = Table(
416
+ title=f"Hosts file entries that override DNS ({escape(hosts.path)})",
417
+ title_justify="left",
418
+ )
419
+ entries.add_column("Line", justify="right")
420
+ entries.add_column("Address")
421
+ entries.add_column("Names", overflow="fold")
422
+ entries.add_column("Effect")
423
+ for entry in hosts.entries[:_MAX_HOSTS_ROWS]:
424
+ entries.add_row(
425
+ str(entry.line), escape(entry.ip), escape(" ".join(entry.names)), entry.kind
426
+ )
427
+ console.print(entries)
428
+ if len(hosts.entries) > _MAX_HOSTS_ROWS:
429
+ console.print(f"[dim]… and {len(hosts.entries) - _MAX_HOSTS_ROWS} more lines[/dim]")
430
+ elif not hosts.error:
431
+ console.print(f"Hosts file: no entries override DNS [dim]({escape(hosts.path)})[/dim]")
432
+
433
+ if report.flush.command:
434
+ console.print(
435
+ f"Flush the DNS cache: [bold cyan]{escape(report.flush.command)}[/bold cyan]\n"
436
+ f"[dim]{escape(report.flush.note)}[/dim]"
437
+ )
438
+ else:
439
+ console.print(f"Flush the DNS cache: [dim]{escape(report.flush.note)}[/dim]")
440
+
441
+ console.print()
442
+ for problem in report.problems:
443
+ error = problem.severity is Severity.ERROR
444
+ icon = "✗" if error else "!"
445
+ body = f"{escape(problem.detail)}\n\n[bold]Fix:[/bold] {escape(problem.fix)}"
446
+ console.print(
447
+ Panel(
448
+ body,
449
+ title=f"[bold]{icon} {escape(problem.title)}[/bold]",
450
+ title_align="left",
451
+ border_style="red" if error else "yellow",
452
+ )
453
+ )
454
+ console.print(_local_summary(report))
455
+ console.print(
456
+ f"[dim]Tested {len(report.servers)} DNS servers in parallel · "
457
+ f"{report.elapsed_ms:.0f} ms total[/dim]"
458
+ )
459
+
460
+
461
+ _VERDICT_MARKS = {
462
+ Verdict.OK: "[green]✓[/green]",
463
+ Verdict.SUSPECT: "[bold yellow]![/bold yellow]",
464
+ Verdict.UNKNOWN: "[dim]?[/dim]",
465
+ }
466
+ _IPV6_MARKS = {
467
+ IPv6State.WORKING: "[green]✓[/green]",
468
+ IPv6State.NOT_AVAILABLE: "[dim]–[/dim]",
469
+ IPv6State.BROKEN: "[bold yellow]![/bold yellow]",
470
+ IPv6State.UNKNOWN: "[dim]?[/dim]",
471
+ }
472
+
473
+
474
+ def _local_checks(report: LocalReport, console: Console) -> None:
475
+ """Hijacking, interception and IPv6: one row each, details in the problem panels."""
476
+ rows = [
477
+ (f"NXDOMAIN hijacking: {escape(h.nameserver)}", _VERDICT_MARKS[h.verdict], h.summary)
478
+ for h in report.hijack
479
+ ]
480
+ rows += [
481
+ (
482
+ f"Interception: {escape(c.nameserver)} ({escape(c.provider)})",
483
+ _VERDICT_MARKS[c.verdict],
484
+ c.summary,
485
+ )
486
+ for c in report.interception
487
+ ]
488
+ if report.ipv6 is not None:
489
+ rows.append(("IPv6", _IPV6_MARKS[report.ipv6.state], report.ipv6.summary))
490
+ if not rows:
491
+ return
492
+ table = Table(title="Network checks", title_justify="left")
493
+ table.add_column("Check")
494
+ table.add_column("Result", overflow="fold")
495
+ for check, mark, summary in rows:
496
+ table.add_row(check, f"{mark} {escape(summary)}")
497
+ console.print(table)
498
+
499
+
500
+ def render_reach(report: ReachReport, console: Console, timeout: float | None = None) -> None:
501
+ table = Table(title=f"{escape(report.name)} on port {report.port}", title_justify="left")
502
+ table.add_column("Address")
503
+ table.add_column("Type")
504
+ table.add_column("Connection", justify="right")
505
+ tried = {a.address: a for a in report.attempts}
506
+ skipped = 0
507
+ for record_set, family in ((report.a, "IPv4"), (report.aaaa, "IPv6")):
508
+ for record in record_set.records:
509
+ attempt = tried.get(record.value)
510
+ if report.blocked_by_dns:
511
+ result = "[red]✗ blocked by DNS[/red]"
512
+ elif attempt is None:
513
+ skipped += 1 # beyond the per-family limit
514
+ continue
515
+ elif attempt.ok:
516
+ result = f"[green]✓ {attempt.latency_ms:.0f} ms[/green]"
517
+ elif attempt.version == 6 and attempt.error is ConnectError.UNREACHABLE:
518
+ result = "[dim]– no IPv6 route[/dim]"
519
+ else:
520
+ result = f"[red]✗ {attempt.error}[/red]"
521
+ table.add_row(escape(record.value), family, result)
522
+ if report.addresses:
523
+ console.print(table)
524
+ if skipped:
525
+ console.print(f"[dim]… and {skipped} more addresses, not tried[/dim]")
526
+ else:
527
+ statuses = f"A: {_STATUS_LABELS[report.a.status]}"
528
+ statuses += f", AAAA: {_STATUS_LABELS[report.aaaa.status]}"
529
+ console.print(f"[red]No addresses for {escape(report.name)}[/red] [dim]({statuses})[/dim]")
530
+
531
+ diagnosis = explain_reach(report, timeout)
532
+ ok = report.verdict is ReachVerdict.REACHABLE
533
+ console.print(
534
+ Panel(
535
+ f"{escape(diagnosis.explanation)}\n\n[bold]Next step:[/bold] "
536
+ f"{escape(diagnosis.suggestion)}",
537
+ title=f"[bold]{'✓' if ok else '✗'} {escape(diagnosis.title)}[/bold]",
538
+ title_align="left",
539
+ border_style="green" if ok else "red",
540
+ )
541
+ )
542
+ _print_footer(
543
+ console,
544
+ report.nameserver,
545
+ report.nameserver_source,
546
+ report.elapsed_ms,
547
+ report.resolver_choice,
548
+ )
549
+
550
+
551
+ def _local_summary(report: LocalReport) -> str:
552
+ in_use = [s for s in report.servers if s.used]
553
+ if not report.problems:
554
+ return (
555
+ f"[bold green]✓ No problems found.[/bold green] {len(in_use)} DNS servers in use, "
556
+ "all responding."
557
+ )
558
+ errors = sum(p.severity is Severity.ERROR for p in report.problems)
559
+ warnings = len(report.problems) - errors
560
+ counts = ", ".join(
561
+ f"{n} {word}{'' if n == 1 else 's'}"
562
+ for n, word in ((errors, "error"), (warnings, "warning"))
563
+ if n
564
+ )
565
+ if errors:
566
+ return f"[bold red]✗ DNS isn't working properly:[/bold red] {counts} (see above)."
567
+ working = sum(not s.failed for s in in_use)
568
+ return (
569
+ f"[bold yellow]DNS is working[/bold yellow] ({working} of {len(in_use)} servers in use "
570
+ f"responding), with {counts} (see above)."
571
+ )
572
+
573
+
574
+ def render_probes(
575
+ choice: ResolverChoice, console: Console, cache_location: str, ignored: Sequence[str] = ()
576
+ ) -> None:
577
+ table = Table(title="System nameservers (in system order)", title_justify="left")
578
+ table.add_column("#", justify="right")
579
+ table.add_column("Nameserver")
580
+ table.add_column("Latency", justify="right")
581
+ table.add_column("")
582
+ slow = set(choice.slow)
583
+ for i, probe in enumerate(choice.probes, start=1):
584
+ if probe.latency_ms is None:
585
+ latency = "[red]no response[/red]"
586
+ elif probe in slow:
587
+ latency = f"[yellow]{probe.latency_ms:.0f} ms (slow)[/yellow]"
588
+ else:
589
+ latency = f"[green]{probe.latency_ms:.0f} ms[/green]"
590
+ marker = "[bold]← used by lookup[/bold]" if probe.nameserver == choice.nameserver else ""
591
+ table.add_row(str(i), escape(probe.nameserver), latency, marker)
592
+ console.print(table)
593
+ if ignored:
594
+ console.print(
595
+ f"[dim]Ignored (not on a connected adapter): {escape(', '.join(ignored))}. "
596
+ "Run `dnskit local` for details.[/dim]"
597
+ )
598
+
599
+ if choice.nameserver is None:
600
+ console.print(
601
+ "[red]No nameserver answered.[/red] Lookups will try them in system order; "
602
+ "check your network connection."
603
+ )
604
+ return
605
+ console.print(
606
+ f"[dim]Slow means slower than {SLOW_THRESHOLD_MS:.0f} ms. {escape(choice.nameserver)} "
607
+ f"is cached as the lookup choice for {CACHE_TTL_S / 60:.0f} min "
608
+ f"({escape(cache_location)}).[/dim]"
609
+ )
610
+
611
+
612
+ _CHECK_ICONS: dict[CheckStatus, str] = {
613
+ CheckStatus.PASS: "[bold green]✓[/bold green]",
614
+ CheckStatus.WARN: "[bold yellow]![/bold yellow]",
615
+ CheckStatus.FAIL: "[bold red]✗[/bold red]",
616
+ }
617
+ _CHECK_LABELS: dict[CheckStatus, str] = {
618
+ CheckStatus.PASS: "[green]pass[/green]",
619
+ CheckStatus.WARN: "[yellow]warn[/yellow]",
620
+ CheckStatus.FAIL: "[bold red]fail[/bold red]",
621
+ }
622
+ _CHECK_HEADINGS = {
623
+ "MX": "MX · where mail for the domain is delivered",
624
+ "SPF": "SPF · which servers may send its mail",
625
+ "DMARC": "DMARC · what receivers do with mail that fails SPF and DKIM",
626
+ "DKIM": "DKIM · keys that sign its mail",
627
+ }
628
+
629
+
630
+ def render_email(report: EmailReport, console: Console, timeout: float | None = None) -> None:
631
+ console.print(f"[bold]Email DNS check for {escape(report.domain)}[/bold]")
632
+ if report.domain_status is not LookupStatus.OK:
633
+ diagnosis = explain(report.domain_status, report.domain, "MX", timeout)
634
+ if diagnosis is not None:
635
+ render_diagnosis(diagnosis, report.domain_status, console)
636
+ else:
637
+ details = {"MX": _email_mx, "SPF": _email_spf, "DMARC": _email_dmarc, "DKIM": _email_dkim}
638
+ for label, section in report.checks:
639
+ console.print()
640
+ console.rule(f"[bold]{escape(_CHECK_HEADINGS[label])}[/bold]", align="left")
641
+ details[label](report, console)
642
+ _print_findings(section, console)
643
+ console.print()
644
+ _print_email_summary(report, console)
645
+
646
+ _print_footer(
647
+ console,
648
+ report.nameserver,
649
+ report.nameserver_source,
650
+ report.elapsed_ms,
651
+ report.resolver_choice,
652
+ )
653
+
654
+
655
+ def _print_findings(section: EmailSection, console: Console) -> None:
656
+ for finding in section.findings:
657
+ icon = _CHECK_ICONS[finding.status]
658
+ if finding.status is CheckStatus.PASS:
659
+ console.print(
660
+ f"{icon} [bold]{escape(finding.title)}[/bold] "
661
+ f"[dim]— {escape(finding.explanation)}[/dim]"
662
+ )
663
+ continue
664
+ body = escape(finding.explanation)
665
+ if finding.fix:
666
+ body += f"\n\n[bold]Fix:[/bold] {escape(finding.fix)}"
667
+ console.print(
668
+ Panel(
669
+ body,
670
+ title=f"{icon} [bold]{escape(finding.title)}[/bold]",
671
+ title_align="left",
672
+ border_style="red" if finding.status is CheckStatus.FAIL else "yellow",
673
+ )
674
+ )
675
+
676
+
677
+ def _email_mx(report: EmailReport, console: Console) -> None:
678
+ mx = report.mx
679
+ if mx is None or not mx.hosts or (mx.null_mx and len(mx.hosts) == 1):
680
+ return
681
+ table = Table()
682
+ table.add_column("Priority", justify="right")
683
+ table.add_column("Mail server", style="bold")
684
+ table.add_column("Addresses", style="cyan", overflow="fold")
685
+ for host in mx.hosts:
686
+ if host.addresses:
687
+ addresses = "\n".join(escape(a) for a in host.addresses)
688
+ elif not host.host:
689
+ addresses = "[dim]null MX: accepts no mail[/dim]"
690
+ else:
691
+ addresses = f"[red]{_STATUS_LABELS[host.lookup_status]}[/red]"
692
+ table.add_row(str(host.preference), escape(host.host or "."), addresses)
693
+ console.print(table)
694
+
695
+
696
+ def _email_spf(report: EmailReport, console: Console) -> None:
697
+ spf = report.spf
698
+ if spf is None:
699
+ return
700
+ for record in spf.records:
701
+ console.print(f"Record: [cyan]{escape(record)}[/cyan]")
702
+ if spf.lookups:
703
+ at_least = "" if spf.complete else "at least "
704
+ too_many = spf.lookup_count > SPF_LOOKUP_LIMIT
705
+ console.print(
706
+ f"DNS lookups: {at_least}{spf.lookup_count} of {SPF_LOOKUP_LIMIT}"
707
+ + (" [bold red](too many)[/bold red]" if too_many else "")
708
+ )
709
+ for lookup in spf.lookups:
710
+ where = f" [dim](in {escape(lookup.source)})[/dim]" if lookup.depth else ""
711
+ console.print(f" {' ' * lookup.depth}{escape(lookup.term)}{where}")
712
+
713
+
714
+ def _email_dmarc(report: EmailReport, console: Console) -> None:
715
+ dmarc = report.dmarc
716
+ if dmarc is None:
717
+ return
718
+ for record in dmarc.records:
719
+ console.print(f"Record at {escape(dmarc.name)}: [cyan]{escape(record)}[/cyan]")
720
+
721
+
722
+ def _email_dkim(report: EmailReport, console: Console) -> None:
723
+ dkim = report.dkim
724
+ if dkim is None:
725
+ return
726
+ table = Table()
727
+ table.add_column("Selector", style="bold")
728
+ table.add_column("Key")
729
+ for selector in dkim.selectors:
730
+ if selector.malformed:
731
+ key = "[red]malformed key[/red]"
732
+ elif selector.revoked:
733
+ key = "[yellow]revoked (empty p=)[/yellow]"
734
+ elif selector.found:
735
+ key = f"[green]{escape(describe_key(selector))}[/green]"
736
+ elif selector.lookup_status in _FAULTS:
737
+ key = f"[red]{_STATUS_LABELS[selector.lookup_status]}[/red]"
738
+ else:
739
+ key = "[dim]not found[/dim]"
740
+ name = escape(selector.selector) + (" [dim](--selector)[/dim]" if selector.custom else "")
741
+ table.add_row(name, key)
742
+ console.print(table)
743
+ console.print(f"[dim]Looked up <selector>._domainkey.{escape(report.domain)}[/dim]")
744
+
745
+
746
+ def _print_email_summary(report: EmailReport, console: Console) -> None:
747
+ table = Table(title="Summary", title_justify="left")
748
+ table.add_column("Check", style="bold")
749
+ table.add_column("Result")
750
+ table.add_column("", overflow="fold")
751
+ for label, section in report.checks:
752
+ headline = section.headline
753
+ table.add_row(
754
+ label,
755
+ f"{_CHECK_ICONS[section.status]} {_CHECK_LABELS[section.status]}",
756
+ escape(headline.title) if headline else "",
757
+ )
758
+ console.print(table)
759
+
760
+ statuses = [section.status for _, section in report.checks]
761
+ failed = statuses.count(CheckStatus.FAIL)
762
+ warned = statuses.count(CheckStatus.WARN)
763
+ passed = statuses.count(CheckStatus.PASS)
764
+ if failed:
765
+ console.print(
766
+ f"[bold red]✗ {failed} of {len(statuses)} checks failed[/bold red]"
767
+ + (f", {warned} with warnings" if warned else "")
768
+ + ". Fix the problems marked ✗ above."
769
+ )
770
+ elif warned:
771
+ console.print(
772
+ f"[bold yellow]! No check failed, but {warned} of {len(statuses)} "
773
+ f"{'has warnings' if warned == 1 else 'have warnings'}.[/bold yellow] "
774
+ f"{passed} passed. See the suggestions marked ! above."
775
+ )
776
+ else:
777
+ console.print(f"[bold green]✓ All {len(statuses)} checks passed.[/bold green]")
778
+
779
+
780
+ def _diagnosis_panel(diagnosis: Diagnosis, style: str, mark: str = "") -> Panel:
781
+ title = f"[bold]{mark + ' ' if mark else ''}{escape(diagnosis.title)}[/bold]"
782
+ body = (
783
+ f"{escape(diagnosis.explanation)}\n\n[bold]Next step:[/bold] {escape(diagnosis.suggestion)}"
784
+ )
785
+ return Panel(body, title=title, title_align="left", border_style=style)
786
+
787
+
788
+ # --- trace --------------------------------------------------------------------------------
789
+
790
+ _FAIL_REASONS = {
791
+ FailReason.NO_RESPONSE: "no response",
792
+ FailReason.REFUSED: "refused",
793
+ FailReason.SERVFAIL: "server failure (SERVFAIL)",
794
+ FailReason.LAME: "not serving the zone (lame delegation)",
795
+ FailReason.NO_ADDRESS: "its nameservers have no address",
796
+ FailReason.TOO_DEEP: "too many referrals",
797
+ }
798
+
799
+
800
+ def _short_list(names: Sequence[str], limit: int = 3) -> str:
801
+ shown = ", ".join(escape(n) for n in names[:limit])
802
+ return f"{shown} and {len(names) - limit} more" if len(names) > limit else shown
803
+
804
+
805
+ def _trace_label(step: TraceStep, report: TraceReport) -> str:
806
+ zone = ". (root)" if step.zone == "." else step.zone
807
+ lines = [f"[bold]{escape(zone)}[/bold]"]
808
+ if step.server is not None:
809
+ who = escape(step.server.address)
810
+ if step.server.name != step.server.address:
811
+ who = f"{escape(step.server.name)} ({who})"
812
+ lines[0] += f" [dim]asked {who} · {step.latency_ms:.0f} ms[/dim]"
813
+ match step.status:
814
+ case StepStatus.REFERRAL:
815
+ servers = step.referral_servers
816
+ count = f" [dim]({len(servers)} servers)[/dim]" if len(servers) > 3 else ""
817
+ lines.append(
818
+ f"[cyan]→ referral to {escape(step.referral_zone or '')}[/cyan] "
819
+ f"{_short_list(servers)}{count}"
820
+ )
821
+ case StepStatus.ANSWER:
822
+ values = ", ".join(escape(v) for v in step.records)
823
+ lines.append(f"[green]✓ answer:[/green] {values}")
824
+ case StepStatus.NXDOMAIN:
825
+ lines.append("[yellow]✗ the name doesn't exist (NXDOMAIN)[/yellow]")
826
+ case StepStatus.NO_ANSWER:
827
+ lines.append(f"[yellow]no {report.rtype} records[/yellow]")
828
+ case StepStatus.FAILED:
829
+ reason = _FAIL_REASONS[step.reason or FailReason.NO_RESPONSE]
830
+ lines.append(f"[bold red]✗ failed at this level: {reason}[/bold red]")
831
+ if step.note:
832
+ lines.append(f"[red]{escape(step.note)}[/red]")
833
+ lines.extend(
834
+ f"[red] ✗ {escape(failure.server.name)} ({escape(failure.server.address)})"
835
+ f": {escape(failure.error)}[/red]"
836
+ for failure in step.failures
837
+ )
838
+ return "\n".join(lines)
839
+ if step.note:
840
+ lines.append(f"[dim]{escape(step.note)}[/dim]")
841
+ lines.extend(
842
+ f"[dim]{escape(failure.server.name)} {escape(failure.error)}; another server answered[/dim]"
843
+ for failure in step.failures
844
+ )
845
+ return "\n".join(lines)
846
+
847
+
848
+ def render_trace(report: TraceReport, console: Console) -> None:
849
+ if report.mode is TraceMode.DIRECT:
850
+ how = "from the root servers down"
851
+ else:
852
+ how = f"through {report.resolver}: direct queries are blocked"
853
+ tree = Tree(f"[bold]{escape(report.name)} {report.rtype}[/bold] [dim]({escape(how)})[/dim]")
854
+ node = tree
855
+ for step in report.steps:
856
+ node = node.add(_trace_label(step, report))
857
+ console.print(tree)
858
+
859
+ diagnosis = explain_trace(report)
860
+ blocked = trace_blocked_diagnosis(report)
861
+ if blocked is not None and blocked != diagnosis:
862
+ console.print(_diagnosis_panel(blocked, "yellow"))
863
+ if diagnosis is not None:
864
+ failed = report.final.status is StepStatus.FAILED
865
+ console.print(_diagnosis_panel(diagnosis, "red" if failed else "yellow"))
866
+ steps = f"{len(report.steps)} step{'s' if len(report.steps) != 1 else ''}"
867
+ console.print(f"[dim]{steps} · {report.elapsed_ms:.0f} ms total[/dim]")
868
+
869
+
870
+ # --- dnssec -------------------------------------------------------------------------------
871
+
872
+ _ZONE_MARKS = {
873
+ ZoneStatus.SECURE: "[green]✓[/green]",
874
+ ZoneStatus.UNSIGNED: "[yellow]–[/yellow]",
875
+ ZoneStatus.BOGUS: "[bold red]✗[/bold red]",
876
+ ZoneStatus.UNKNOWN: "[dim]?[/dim]",
877
+ }
878
+ _DNSSEC_STYLES = {
879
+ DnssecStatus.SECURE: ("green", "✓"),
880
+ DnssecStatus.INSECURE: ("yellow", "–"),
881
+ DnssecStatus.BOGUS: ("red", "✗"),
882
+ DnssecStatus.UNKNOWN: ("red", "?"),
883
+ }
884
+
885
+
886
+ def _keys_cell(keys: Sequence[KeyInfo]) -> str:
887
+ if not keys:
888
+ return "[dim]none[/dim]"
889
+ ksk = sum(1 for k in keys if k.ksk)
890
+ parts = [f"{ksk} KSK"] if ksk else []
891
+ if len(keys) - ksk:
892
+ parts.append(f"{len(keys) - ksk} ZSK")
893
+ algorithms = sorted({k.algorithm for k in keys})
894
+ return f"{' + '.join(parts)} [dim]({escape(', '.join(algorithms))})[/dim]"
895
+
896
+
897
+ def render_dnssec(report: DnssecReport, console: Console) -> None:
898
+ if report.stripped_by and not report.signatures_stripped:
899
+ console.print(
900
+ f"[yellow]This computer's DNS server ({escape(report.stripped_by)}) strips DNSSEC "
901
+ f"signatures, so this was checked through {escape(report.nameserver)}.[/yellow]"
902
+ )
903
+ if report.zones:
904
+ table = Table(
905
+ title=f"DNSSEC chain of trust for {escape(report.name)}", title_justify="left"
906
+ )
907
+ table.add_column("Zone", style="bold")
908
+ table.add_column("DS (at parent)")
909
+ table.add_column("Keys")
910
+ table.add_column("Result", overflow="fold")
911
+ for zone in report.zones:
912
+ if zone.zone == ".":
913
+ ds = "trust anchors " + ", ".join(str(d.key_tag) for d in zone.ds)
914
+ else:
915
+ ds = ", ".join(str(d.key_tag) for d in zone.ds) or "[dim]none[/dim]"
916
+ table.add_row(
917
+ ". (root)" if zone.zone == "." else escape(zone.zone),
918
+ ds,
919
+ _keys_cell(zone.keys),
920
+ f"{_ZONE_MARKS[zone.status]} {escape(zone.summary)}",
921
+ )
922
+ for record in report.records:
923
+ table.add_row(
924
+ f"{escape(record.name)} {record.rtype}",
925
+ "",
926
+ "",
927
+ f"{_ZONE_MARKS[record.status]} {escape(record.summary)}",
928
+ )
929
+ console.print(table)
930
+
931
+ clock_warning = clock_diagnosis(report.clock)
932
+ if clock_warning is not None:
933
+ console.print(_diagnosis_panel(clock_warning, "yellow", "!"))
934
+ elif report.clock.state is ClockState.OK or report.zones:
935
+ mark = "[green]✓[/green]" if report.clock.state is ClockState.OK else "[dim]?[/dim]"
936
+ console.print(f"Clock: {mark} {escape(report.clock.summary)}")
937
+
938
+ diagnosis = explain_dnssec(report)
939
+ style, mark = _DNSSEC_STYLES[report.status]
940
+ if report.name_missing:
941
+ style, mark = "yellow", "✗"
942
+ console.print(_diagnosis_panel(diagnosis, style, mark))
943
+ _print_footer(
944
+ console,
945
+ report.nameserver,
946
+ report.nameserver_source,
947
+ report.elapsed_ms,
948
+ report.resolver_choice,
949
+ )
950
+
951
+
952
+ # --- propagation --------------------------------------------------------------------------
953
+
954
+
955
+ def render_propagation(report: PropagationReport, console: Console) -> None:
956
+ table = Table(
957
+ title=f"{escape(report.name)} {report.rtype} across {len(report.answers)} public resolvers",
958
+ title_justify="left",
959
+ )
960
+ table.add_column("Region", style="bold")
961
+ table.add_column("Resolver")
962
+ table.add_column("Location", style="dim")
963
+ table.add_column("Answer", overflow="fold")
964
+ table.add_column("TTL", justify="right")
965
+ table.add_column("")
966
+ split = bool(report.differing)
967
+ region = None
968
+ for answer in report.answers:
969
+ resolver = answer.resolver
970
+ if region is not None and resolver.region != region:
971
+ table.add_section()
972
+ value, marker = _agreement_cells(
973
+ answer.result, answer.agreement, report.has_majority, split
974
+ )
975
+ table.add_row(
976
+ escape(resolver.region) if resolver.region != region else "",
977
+ f"{escape(resolver.name)} [dim]{escape(resolver.address)}[/dim]",
978
+ escape(resolver.location),
979
+ value,
980
+ "" if answer.ttl is None else str(answer.ttl),
981
+ marker,
982
+ )
983
+ region = resolver.region
984
+ console.print(table)
985
+ if any(a.resolver.anycast for a in report.answers):
986
+ console.print(f"[dim]{escape(ANYCAST_NOTE)}[/dim]")
987
+
988
+ if not report.blocked and report.responded:
989
+ failed = f" · {len(report.failed)} didn't respond" if report.failed else ""
990
+ style = "green" if report.complete else "yellow"
991
+ console.print(
992
+ f"[bold {style}]{report.percent:.0f}%[/bold {style}] of the resolvers that answered "
993
+ f"({len(report.majority)} of {len(report.responded)}) give the most common "
994
+ f"answer{failed}"
995
+ )
996
+ diagnosis = explain_propagation(report)
997
+ if report.complete:
998
+ style, mark = "green", "✓"
999
+ elif report.blocked or not report.responded:
1000
+ style, mark = "red", "✗"
1001
+ else:
1002
+ style, mark = "yellow", "…"
1003
+ console.print(_diagnosis_panel(diagnosis, style, mark))
1004
+ if report.blocking is not None and not report.blocked:
1005
+ blocked = blocked_diagnosis(
1006
+ report.blocking, f"{len(report.failed)} of the {len(report.answers)} resolvers"
1007
+ )
1008
+ console.print(_diagnosis_panel(blocked, "yellow"))
1009
+ console.print(
1010
+ f"[dim]Queried {len(report.answers)} resolvers in parallel · "
1011
+ f"{report.elapsed_ms:.0f} ms total[/dim]"
1012
+ )
1013
+
1014
+
1015
+ # --- doctor -------------------------------------------------------------------------------
1016
+
1017
+ _IMPACT_STYLES = {
1018
+ Impact.CRITICAL: "red",
1019
+ Impact.MAJOR: "yellow",
1020
+ Impact.MINOR: "cyan",
1021
+ Impact.NOTE: "dim",
1022
+ }
1023
+
1024
+
1025
+ class DoctorProgress:
1026
+ """Live view of the doctor checks; `update` is safe to call from worker threads."""
1027
+
1028
+ def __init__(self) -> None:
1029
+ self._lock = threading.Lock()
1030
+ self._states: dict[Check, CheckState] = dict.fromkeys(Check, CheckState.PENDING)
1031
+ self._started: dict[Check, float] = {}
1032
+ self._spinner = Spinner("dots", style="cyan")
1033
+
1034
+ def update(self, check: Check, state: CheckState) -> None:
1035
+ with self._lock:
1036
+ self._states[check] = state
1037
+ if state is CheckState.RUNNING:
1038
+ self._started[check] = time.perf_counter()
1039
+
1040
+ def __rich__(self) -> Table:
1041
+ table = Table.grid(padding=(0, 1))
1042
+ with self._lock:
1043
+ states = dict(self._states)
1044
+ started = dict(self._started)
1045
+ for check, state in states.items():
1046
+ if state is CheckState.RUNNING:
1047
+ seconds = time.perf_counter() - started.get(check, time.perf_counter())
1048
+ table.add_row(self._spinner, CHECK_LABELS[check], f"[dim]{seconds:.1f} s[/dim]")
1049
+ elif state is CheckState.PENDING:
1050
+ table.add_row("[dim]·[/dim]", f"[dim]{CHECK_LABELS[check]}[/dim]", "")
1051
+ elif state is CheckState.SKIPPED:
1052
+ table.add_row("[dim]-[/dim]", f"[dim]{CHECK_LABELS[check]} (skipped)[/dim]", "")
1053
+ elif state is CheckState.ERROR:
1054
+ table.add_row("[red]✗[/red]", CHECK_LABELS[check], "")
1055
+ else:
1056
+ table.add_row("[green]✓[/green]", CHECK_LABELS[check], "")
1057
+ return table
1058
+
1059
+
1060
+ def render_doctor(report: DoctorReport, console: Console) -> None:
1061
+ console.print(f"[bold]Health check for {escape(report.name)}[/bold]")
1062
+ checks = Table(show_header=True, header_style="bold", box=None, padding=(0, 2, 0, 0))
1063
+ checks.add_column("Check")
1064
+ checks.add_column("Result")
1065
+ checks.add_column("Time", justify="right", style="dim")
1066
+ for run in report.runs:
1067
+ found = [i for i in report.issues if i.check is run.check]
1068
+ problems = [i for i in found if i.impact is not Impact.NOTE]
1069
+ notes = len(found) - len(problems)
1070
+ noted = f" [dim]({notes} note{'' if notes == 1 else 's'})[/dim]" if notes else ""
1071
+ if run.state is CheckState.SKIPPED:
1072
+ result = f"[dim]skipped ({escape(run.reason or '--quick')})[/dim]"
1073
+ elif run.state is CheckState.ERROR:
1074
+ result = f"[red]✗ couldn't run[/red] [dim]{escape(run.error or '')}[/dim]"
1075
+ elif not problems and report.failed(run.check):
1076
+ result = "[red]✗ failed[/red] [dim](explained below)[/dim]"
1077
+ elif not problems:
1078
+ result = "[green]✓ OK[/green]" + noted
1079
+ else:
1080
+ worst = min(problems, key=lambda i: list(Impact).index(i.impact)).impact
1081
+ style = _IMPACT_STYLES[worst]
1082
+ count = f"{len(problems)} issue" + ("" if len(problems) == 1 else "s")
1083
+ mark = "✗" if worst is Impact.CRITICAL else "!"
1084
+ result = f"[{style}]{mark} {count}[/{style}]{noted}"
1085
+ if run.check is Check.DNSSEC and report.dnssec_via:
1086
+ # This computer's DNS server strips signatures, so a public resolver stood in.
1087
+ result += f" [dim](via {report.dnssec_via})[/dim]"
1088
+ time_text = "" if run.state is CheckState.SKIPPED else f"{run.elapsed_ms:.0f} ms"
1089
+ checks.add_row(escape(CHECK_LABELS[run.check]), result, time_text)
1090
+ console.print(checks)
1091
+ console.print()
1092
+
1093
+ score = report.score
1094
+ style = "green" if score >= 90 else "yellow" if score >= 60 else "red"
1095
+ if any(i.impact is Impact.CRITICAL for i in report.issues):
1096
+ style = "red"
1097
+ verdict = doctor_verdict(report)
1098
+ console.print(f"Health score: [bold {style}]{score}/100[/bold {style}]")
1099
+ console.print(_diagnosis_panel(verdict, style))
1100
+
1101
+ sections = [
1102
+ ("This computer", report.machine_issues),
1103
+ (report.name, report.domain_issues),
1104
+ ]
1105
+ # The section with the most important issue first (this computer on a tie).
1106
+ sections.sort(key=lambda s: report.issues.index(s[1][0]) if s[1] else len(report.issues))
1107
+ number = 0
1108
+ for heading, issues in sections:
1109
+ if not issues:
1110
+ continue
1111
+ console.print()
1112
+ console.print(f"[bold underline]{escape(heading)}[/bold underline]")
1113
+ section_notes = [i for i in issues if i.impact is Impact.NOTE]
1114
+ for issue in issues:
1115
+ if issue.impact is Impact.NOTE:
1116
+ continue
1117
+ number += 1
1118
+ style = _IMPACT_STYLES[issue.impact]
1119
+ console.print(
1120
+ f"[bold]{number}.[/bold] [{style}]{issue.impact.value.upper()}[/{style}] "
1121
+ f"[bold]{escape(issue.title)}[/bold]"
1122
+ )
1123
+ body = f"[dim]{escape(issue.detail)}[/dim]\n[bold]Fix:[/bold] {escape(issue.fix)}"
1124
+ console.print(Padding(body, (0, 0, 0, 3)), highlight=False)
1125
+ if section_notes:
1126
+ console.print("[dim]Notes, nothing to fix:[/dim]")
1127
+ for note in section_notes:
1128
+ # Check values are the command names: `dnskit local` has the details.
1129
+ where = f"dnskit {note.check.value}"
1130
+ console.print(Padding(f"[dim]· {escape(note.title)} — {where}[/dim]", (0, 0, 0, 2)))
1131
+
1132
+ console.print()
1133
+ ran = sum(r.state is not CheckState.SKIPPED for r in report.runs)
1134
+ console.print(f"[dim]Ran {ran} checks in parallel · {report.elapsed_ms:.0f} ms total[/dim]")
1135
+
1136
+
1137
+ # --- batch --------------------------------------------------------------------------------
1138
+
1139
+
1140
+ class BatchProgress:
1141
+ """Live count of checked domains; `done` is safe to call from worker threads."""
1142
+
1143
+ def __init__(self, total: int, check: BatchCheck) -> None:
1144
+ self._lock = threading.Lock()
1145
+ self._total = total
1146
+ self._done = 0
1147
+ self._spinner = Spinner("dots", style="cyan")
1148
+ self._check = check
1149
+
1150
+ def done(self, item: BatchItem) -> None:
1151
+ with self._lock:
1152
+ self._done += 1
1153
+ self._spinner.update(text=self._text(item.name))
1154
+
1155
+ def _text(self, last: str = "") -> str:
1156
+ latest = f" [dim]· last: {escape(last)}[/dim]" if last else ""
1157
+ return f"Running {self._check.value} on {self._done}/{self._total} domains{latest}"
1158
+
1159
+ def __rich__(self) -> Spinner:
1160
+ with self._lock:
1161
+ if not self._done:
1162
+ self._spinner.update(text=self._text())
1163
+ return self._spinner
1164
+
1165
+
1166
+ def render_batch(report: BatchReport, console: Console) -> None:
1167
+ if report.local is not None:
1168
+ problems = [p for p in report.local.problems if p.severity is Severity.ERROR]
1169
+ state = (
1170
+ f"[red]{len(problems)} error{'s' if len(problems) > 1 else ''}[/red]"
1171
+ if problems
1172
+ else "[green]OK[/green]"
1173
+ )
1174
+ console.print(
1175
+ f"This computer: {state} [dim](checked once for every domain; details: "
1176
+ "dnskit local)[/dim]"
1177
+ )
1178
+ if report.items:
1179
+ table = Table(
1180
+ title=f"dnskit {report.check.value} for {len(report.items)} "
1181
+ f"domain{'s' if len(report.items) > 1 else ''}",
1182
+ title_justify="left",
1183
+ )
1184
+ table.add_column("Line", justify="right", style="dim")
1185
+ table.add_column("Domain", style="bold")
1186
+ table.add_column("Result")
1187
+ table.add_column("Summary", overflow="fold")
1188
+ table.add_column("Time", justify="right", style="dim")
1189
+ for item in report.items:
1190
+ result = "[green]✓ OK[/green]" if item.ok else "[red]✗ not OK[/red]"
1191
+ summary = escape(item.summary)
1192
+ if item.error:
1193
+ summary += f" [dim]({escape(item.error)})[/dim]"
1194
+ table.add_row(
1195
+ str(item.line), escape(item.name), result, summary, f"{item.elapsed_ms:.0f} ms"
1196
+ )
1197
+ console.print(table)
1198
+ for line in report.invalid:
1199
+ console.print(
1200
+ f"[yellow]Skipped line {line.line}:[/yellow] {escape(line.error or line.text)}"
1201
+ )
1202
+ for line in report.duplicates:
1203
+ console.print(
1204
+ f"[dim]Line {line.line}: {escape(line.name or line.text)} is listed again "
1205
+ "(checked once).[/dim]"
1206
+ )
1207
+
1208
+ parts = [f"[green]{len(report.passed)} OK[/green]"]
1209
+ if report.failed:
1210
+ parts.append(f"[red]{len(report.failed)} not OK[/red]")
1211
+ if report.invalid:
1212
+ count = len(report.invalid)
1213
+ parts.append(f"[yellow]{count} invalid line{'s' if count > 1 else ''}[/yellow]")
1214
+ console.print(
1215
+ " · ".join(parts) + f" [dim]· {report.elapsed_ms / 1000:.1f} s total[/dim]",
1216
+ highlight=False,
1217
+ )
1218
+
1219
+
1220
+ # --- watch --------------------------------------------------------------------------------
1221
+
1222
+
1223
+ def render_watch_start(
1224
+ name: str, rtype: str, interval: float, until: str | None, console: Console
1225
+ ) -> None:
1226
+ goal = f", until it includes {escape(until)}" if until else ""
1227
+ console.print(
1228
+ f"Watching [bold]{escape(name)} {rtype}[/bold] every {interval:g} s{goal} "
1229
+ "[dim](Ctrl+C to stop)[/dim]"
1230
+ )
1231
+
1232
+
1233
+ def watch_answer(result: LookupResult) -> str:
1234
+ """The answer in one line: the records sorted, or what went wrong."""
1235
+ if result.records:
1236
+ values = ", ".join(sorted(r.value for r in result.records))
1237
+ return f"{values} [dim](TTL {result.records[0].ttl})[/dim]"
1238
+ return _STATUS_LABELS.get(result.status, result.status.value)
1239
+
1240
+
1241
+ def render_watch_sample(
1242
+ sample: WatchSample, console: Console, until: str | None = None, strict: bool = False
1243
+ ) -> None:
1244
+ at = sample.at.astimezone().strftime("%H:%M:%S")
1245
+ answer = watch_answer(sample.result)
1246
+ if not sample.answered:
1247
+ note = "[red]lookup failed[/red] [dim](not counted as a change)[/dim]"
1248
+ answer = f"[red]{escape(answer)}[/red]"
1249
+ elif sample.rotating and not strict:
1250
+ note = "[blue]rotating (CDN)[/blue] [dim](all seen before)[/dim]"
1251
+ elif sample.changed:
1252
+ assert sample.previous is not None
1253
+ note = (
1254
+ f"[bold yellow]CHANGED[/bold yellow] [dim](was {watch_answer(sample.previous)})[/dim]"
1255
+ )
1256
+ answer = f"[bold]{answer}[/bold]"
1257
+ elif sample.number == 1:
1258
+ note = f"[dim]first answer, from {escape(sample.nameserver)}[/dim]"
1259
+ else:
1260
+ note = "[dim]unchanged[/dim]"
1261
+ if until and sample.matches(until):
1262
+ note += f" [green]✓ includes {escape(until)}[/green]"
1263
+ console.print(f"[dim]{at}[/dim] {answer} {note}", highlight=False)
1264
+
1265
+
1266
+ def _times(n: int) -> str:
1267
+ return f"{n} time{'s' if n != 1 else ''}"
1268
+
1269
+
1270
+ def render_watch_end(summary: WatchSummary, reason: str, strict: bool, console: Console) -> None:
1271
+ checks = summary.checks
1272
+ changes = summary.new_changes + (summary.rotations if strict else 0)
1273
+ parts = [f"the answer changed {_times(changes)}"] if changes else []
1274
+ if summary.rotations and not strict:
1275
+ parts.append(f"rotated {_times(summary.rotations)} between addresses already seen")
1276
+ what = " and ".join(parts) if parts else "the answer didn't change"
1277
+ console.print(f"{reason} after {checks} check{'s' if checks != 1 else ''}; {what}.")
1278
+ if summary.failures:
1279
+ console.print(
1280
+ f"[dim]{summary.failures} lookup{'s' if summary.failures > 1 else ''} "
1281
+ "failed and weren't counted.[/dim]"
1282
+ )
1283
+ if not summary.values:
1284
+ return
1285
+ table = Table(title="Everything seen", title_justify="left")
1286
+ table.add_column("Answer")
1287
+ table.add_column("Checks", justify="right")
1288
+ table.add_column("First seen", style="dim")
1289
+ table.add_column("Last seen", style="dim")
1290
+ for value in summary.values:
1291
+ table.add_row(
1292
+ escape(value.value),
1293
+ str(value.times),
1294
+ value.first.astimezone().strftime("%H:%M:%S"),
1295
+ value.last.astimezone().strftime("%H:%M:%S"),
1296
+ )
1297
+ console.print(table)
1298
+
1299
+
1300
+ # --- config -------------------------------------------------------------------------------
1301
+
1302
+
1303
+ def render_config(config: Config, console: Console) -> None:
1304
+ if not config.exists:
1305
+ console.print(f"No config file at [bold]{escape(str(config.path))}[/bold].")
1306
+ console.print(
1307
+ "[dim]dnskit uses its built-in defaults. Run `dnskit config --init` to create a "
1308
+ "commented starter file there.[/dim]"
1309
+ )
1310
+ return
1311
+ console.print(f"Config file: [bold]{escape(str(config.path))}[/bold]")
1312
+ if config.settings:
1313
+ table = Table(title="Settings", title_justify="left")
1314
+ table.add_column("Command", style="bold")
1315
+ table.add_column("Setting")
1316
+ table.add_column("Value")
1317
+ for command, settings in config.settings.items():
1318
+ for n, (name, value) in enumerate(settings.items()):
1319
+ table.add_row(command if n == 0 else "", name, escape(repr(value)))
1320
+ console.print(table)
1321
+ for label, resolvers in (
1322
+ ("compare", config.compare_resolvers),
1323
+ (
1324
+ "propagation",
1325
+ tuple((r.name, r.address) for r in config.propagation_resolvers)
1326
+ if config.propagation_resolvers
1327
+ else None,
1328
+ ),
1329
+ ):
1330
+ if resolvers:
1331
+ listed = ", ".join(f"{escape(name)} ({address})" for name, address in resolvers)
1332
+ console.print(f"[bold]{label}[/bold] resolvers: {listed}")
1333
+ if not config.settings and not config.compare_resolvers and not config.propagation_resolvers:
1334
+ console.print("[dim]It sets nothing: everything uses the built-in defaults.[/dim]")