hegemony-probe-net 0.57.2__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,36 @@
1
+ # SPDX-FileCopyrightText: 2025-2026 Rexonix s.r.o.
2
+ # SPDX-FileContributor: Jakub Trávník <jakub.travnik@gmail.com>
3
+ #
4
+ # SPDX-License-Identifier: AGPL-3.0-or-later
5
+
6
+ """Network reachability probes for Hegemony (tcp/icmp/http/dns).
7
+
8
+ Registers under the ``hegemony.probes`` entry-point group. Each probe
9
+ implements one ``check_type`` consumed by both the background MonitorManager
10
+ and the one-shot ``probe.*`` step handlers via ``HandlerServices.run_probe``.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from hegemony_step_sdk import BaseProbe, ProbeRegistry
16
+
17
+ from .dns_resolve import DnsResolveProbe
18
+ from .http_health import HttpHealthProbe
19
+ from .icmp_ping import IcmpPingProbe
20
+ from .tcp_connect import TcpConnectProbe
21
+
22
+ ALL_PROBES: tuple[type[BaseProbe], ...] = (
23
+ TcpConnectProbe,
24
+ IcmpPingProbe,
25
+ HttpHealthProbe,
26
+ DnsResolveProbe,
27
+ )
28
+
29
+
30
+ def register(registry: ProbeRegistry) -> None:
31
+ """Entry point: register this wheel's probes with the host registry."""
32
+ for probe_class in ALL_PROBES:
33
+ registry.register_probe(probe_class)
34
+
35
+
36
+ __all__ = ["ALL_PROBES", "register", *sorted(cls.__name__ for cls in ALL_PROBES)]
@@ -0,0 +1,126 @@
1
+ # SPDX-FileCopyrightText: 2025-2026 Rexonix s.r.o.
2
+ # SPDX-FileContributor: Jakub Trávník <jakub.travnik@gmail.com>
3
+ #
4
+ # SPDX-License-Identifier: AGPL-3.0-or-later
5
+
6
+ """DNS resolution probe.
7
+
8
+ Resolves a hostname (the ``hostname`` option, falling back to the target
9
+ address) via the system resolver. The name looked up must not be an IP
10
+ address, so an IP address target needs the option: the resolver hands an
11
+ address back without a lookup. Record types, custom resolvers, and
12
+ expected-answer assertions live in the ``probe.dns`` step handler.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import asyncio
18
+ import ipaddress
19
+ import logging
20
+ import socket
21
+ import time
22
+ from typing import Any
23
+
24
+ from hegemony_step_sdk import BaseProbe, ProbeResult
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ def _is_ip_address(value: str) -> bool:
30
+ """Is this an address literal rather than a name to look up?
31
+
32
+ A bracketed IPv6 address, as written in a URL, counts as one: the
33
+ resolver would fail it as a name that does not resolve, which hides
34
+ that no name was given.
35
+ """
36
+ if value.startswith("[") and value.endswith("]"):
37
+ value = value[1:-1]
38
+ try:
39
+ ipaddress.ip_address(value)
40
+ except ValueError:
41
+ return False
42
+ return True
43
+
44
+
45
+ class DnsResolveProbe(BaseProbe):
46
+ """DNS resolution probe using the system resolver.
47
+
48
+ Options:
49
+ hostname: Name to resolve, never an IP address (default: the
50
+ target address; required when the target is an IP address)
51
+ timeout_ms: Resolution timeout in milliseconds (default: 5000)
52
+
53
+ Metrics produced:
54
+ resolve_ms: Resolution time
55
+ addresses: Number of resolved addresses
56
+ """
57
+
58
+ probe_id = "dns_resolve"
59
+
60
+ async def execute(self, address: str, options: dict[str, Any]) -> ProbeResult:
61
+ # This probe uses the host resolver, which no SOCKS5 CONNECT tunnel
62
+ # can carry (DNS is UDP, and RFC 1928 UDP ASSOCIATE is not
63
+ # implemented). Accepting the option would resolve on the *worker* and
64
+ # report a success describing a network path the caller never asked
65
+ # for — the same misleading result icmp_ping refuses. Fail closed
66
+ # instead; socks5h:// on a TCP-based check resolves at the bastion.
67
+ if (options.get("socks_proxy") or "").strip():
68
+ return ProbeResult(
69
+ ok=False,
70
+ error_kind="config_error",
71
+ error_detail=(
72
+ "dns_resolve cannot use socks_proxy (DNS does not traverse a "
73
+ "SOCKS5 CONNECT tunnel); use socks5h:// on tcp_connect or "
74
+ "http_health to resolve at the bastion"
75
+ ),
76
+ )
77
+
78
+ hostname = (options.get("hostname") or "").strip()
79
+ source = "hostname" if hostname else "target"
80
+ hostname = hostname or address
81
+ # getaddrinfo returns an IP literal as it is, so an IP address, given
82
+ # as the option or as the target it falls back to, would pass without
83
+ # asking any DNS server.
84
+ if _is_ip_address(hostname):
85
+ return ProbeResult(
86
+ ok=False,
87
+ error_kind="config_error",
88
+ error_detail=(
89
+ f"dns_resolve needs a hostname to look up: the {source} "
90
+ f"{hostname} is an IP address"
91
+ ),
92
+ )
93
+ timeout_sec = options.get("timeout_ms", 5000) / 1000.0
94
+
95
+ loop = asyncio.get_running_loop()
96
+ start = time.perf_counter()
97
+ try:
98
+ infos = await asyncio.wait_for(
99
+ loop.getaddrinfo(hostname, None, type=socket.SOCK_STREAM),
100
+ timeout=timeout_sec,
101
+ )
102
+ except TimeoutError:
103
+ elapsed = (time.perf_counter() - start) * 1000
104
+ return ProbeResult(
105
+ ok=False,
106
+ metrics={"resolve_ms": round(elapsed, 3)},
107
+ error_kind="timeout",
108
+ error_detail=f"Resolution timed out after {timeout_sec}s",
109
+ )
110
+ except socket.gaierror as exc:
111
+ elapsed = (time.perf_counter() - start) * 1000
112
+ return ProbeResult(
113
+ ok=False,
114
+ metrics={"resolve_ms": round(elapsed, 3)},
115
+ error_kind="resolution_failed",
116
+ error_detail=str(exc),
117
+ )
118
+
119
+ elapsed = (time.perf_counter() - start) * 1000
120
+ addresses = sorted({info[4][0] for info in infos})
121
+ return ProbeResult(
122
+ ok=bool(addresses),
123
+ metrics={"resolve_ms": round(elapsed, 3), "addresses": len(addresses)},
124
+ error_kind=None if addresses else "no_answers",
125
+ error_detail=None if addresses else f"no addresses for {hostname}",
126
+ )
@@ -0,0 +1,205 @@
1
+ # SPDX-FileCopyrightText: 2025-2026 Rexonix s.r.o.
2
+ # SPDX-FileContributor: Jakub Trávník <jakub.travnik@gmail.com>
3
+ #
4
+ # SPDX-License-Identifier: AGPL-3.0-or-later
5
+
6
+ """HTTP health probe.
7
+
8
+ GETs ``http://<address>[:port]<url_path>`` and reports ok for any status below
9
+ 400. Redirects are not followed: a 3xx already counts as healthy, and the
10
+ egress gate has only seen the first target. The richer one-shot variant
11
+ (https, methods, status specs, body matching) lives in the ``probe.http`` step
12
+ handler.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import asyncio
18
+ import logging
19
+ import time
20
+ from typing import Any
21
+
22
+ import httpx
23
+
24
+ from hegemony_step_sdk import BaseProbe, ProbeResult
25
+
26
+ from .socks import SocksError, SocksTargetError, open_socks_connection, parse_socks_proxy
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+ #: Floor on the exchange's share of the request budget. A handshake that ate
31
+ #: the whole timeout must still surface as a *read* timeout against the target
32
+ #: rather than an instant zero-timeout failure that hides which leg was slow.
33
+ _MIN_EXCHANGE_TIMEOUT_SEC = 0.5
34
+
35
+
36
+ class _SocksAsyncTransport(httpx.AsyncBaseTransport):
37
+ """httpx transport that dials every request through a SOCKS5 proxy.
38
+
39
+ Dependency-free stand-in for httpx-socks: reuses the probe's minimal
40
+ SOCKS client to open the tunnel, then hands httpx the tunneled stream via
41
+ an :class:`httpx.AsyncHTTPTransport` bound to that connection.
42
+ """
43
+
44
+ def __init__(self, proxy_url: str, timeout_sec: float) -> None:
45
+ self._proxy = parse_socks_proxy(proxy_url)
46
+ self._timeout = timeout_sec
47
+
48
+ async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
49
+ host = request.url.host
50
+ # This transport speaks cleartext HTTP/1.1 on the tunneled stream (see
51
+ # _exchange below) — it does no TLS handshake. `execute` only ever
52
+ # builds http:// URLs today, so this cannot currently be reached, but
53
+ # if a scheme option is added later, silently picking 443 would send
54
+ # the request line and Host header in the clear to a TLS port. Refuse
55
+ # rather than leave that waiting to happen.
56
+ if request.url.scheme != "http":
57
+ raise SocksError(
58
+ f"tunneled http_health supports http:// only (got {request.url.scheme}://); "
59
+ "the SOCKS transport does not perform a TLS handshake"
60
+ )
61
+ port = request.url.port or 80
62
+ # One budget for the whole request, matching the direct path. Charging
63
+ # self._timeout to the handshake and again to the exchange lets a
64
+ # proxied probe run for twice timeout_ms, which overlaps the ticks of a
65
+ # short-interval monitor.
66
+ started = time.perf_counter()
67
+ reader, writer = await open_socks_connection(self._proxy, host, port, timeout=self._timeout)
68
+ remaining = max(self._timeout - (time.perf_counter() - started), _MIN_EXCHANGE_TIMEOUT_SEC)
69
+ # Speak HTTP/1.1 over the tunneled stream ourselves: only the status
70
+ # line matters for a health check, so read headers and stop.
71
+ path = request.url.raw_path.decode()
72
+ # httpx's own Host header: an IPv6 host bracketed, a non-default port
73
+ # kept, as RFC 9112 requires.
74
+ head = (
75
+ f"GET {path} HTTP/1.1\r\n"
76
+ f"Host: {request.headers['host']}\r\n"
77
+ "User-Agent: hegemony-probe/1\r\n"
78
+ "Accept: */*\r\n"
79
+ "Connection: close\r\n\r\n"
80
+ )
81
+
82
+ async def _exchange() -> int:
83
+ writer.write(head.encode())
84
+ await writer.drain()
85
+ status_line = await reader.readline()
86
+ parts = status_line.decode("latin-1").split(" ", 2)
87
+ if len(parts) < 2 or not parts[1].isdigit():
88
+ raise SocksError("malformed HTTP status line from tunneled target")
89
+ status_code = int(parts[1])
90
+ # Drain remaining headers (bounded) so the peer close is clean.
91
+ while True:
92
+ line = await reader.readline()
93
+ if line in (b"\r\n", b"\n", b""):
94
+ break
95
+ return status_code
96
+
97
+ try:
98
+ # httpx's client timeout does NOT apply to a custom transport, so
99
+ # bound the post-CONNECT exchange ourselves — otherwise a target
100
+ # that accepts the tunnel then withholds its response would hang
101
+ # the probe (and its bastion connection) indefinitely.
102
+ status_code = await asyncio.wait_for(_exchange(), timeout=remaining)
103
+ except TimeoutError as exc:
104
+ raise httpx.ReadTimeout("tunneled HTTP exchange timed out", request=request) from exc
105
+ finally:
106
+ writer.close()
107
+ return httpx.Response(status_code=status_code, request=request)
108
+
109
+
110
+ class HttpHealthProbe(BaseProbe):
111
+ """HTTP health probe.
112
+
113
+ Options:
114
+ port: TCP port (default: 80)
115
+ url_path: Request path (default: /health)
116
+ timeout_ms: Request timeout in milliseconds (default: 5000)
117
+ socks_proxy: Optional ``socks5[h]://[user:pass@]host:port`` to route
118
+ the request through (design-dind-sandbox.md §11.4).
119
+
120
+ Metrics produced:
121
+ connect_ms: Total request time
122
+ http_status: Response status code
123
+ """
124
+
125
+ probe_id = "http_health"
126
+
127
+ async def execute(self, address: str, options: dict[str, Any]) -> ProbeResult:
128
+ port = options.get("port")
129
+ url_path = options.get("url_path") or "/health"
130
+ if not url_path.startswith("/"):
131
+ url_path = "/" + url_path
132
+ timeout_sec = options.get("timeout_ms", 5000) / 1000.0
133
+ socks_proxy = (options.get("socks_proxy") or "").strip()
134
+
135
+ # A colon marks an IPv6 literal (hostnames and IPv4 cannot carry one),
136
+ # and a URL authority requires it bracketed.
137
+ authority = f"[{address}]" if ":" in address else address
138
+ netloc = authority if port in (None, 80) else f"{authority}:{port}"
139
+ url = f"http://{netloc}{url_path}"
140
+
141
+ transport: _SocksAsyncTransport | None = None
142
+ if socks_proxy:
143
+ # A value that does not parse fails every attempt the same way:
144
+ # a config_error, which callers stop on. A socks_error is a
145
+ # handshake failure that a later attempt may get past.
146
+ try:
147
+ transport = _SocksAsyncTransport(socks_proxy, timeout_sec)
148
+ except SocksError as exc:
149
+ return ProbeResult(ok=False, error_kind="config_error", error_detail=str(exc))
150
+
151
+ start = time.perf_counter()
152
+ try:
153
+ async with httpx.AsyncClient(
154
+ timeout=timeout_sec, follow_redirects=False, transport=transport
155
+ ) as client:
156
+ response = await client.get(url)
157
+ except SocksError as exc:
158
+ elapsed = (time.perf_counter() - start) * 1000
159
+ return ProbeResult(
160
+ ok=False,
161
+ metrics={"connect_ms": round(elapsed, 3)},
162
+ # The proxy reached its end but not the target: report the
163
+ # target's failure, as without a proxy.
164
+ error_kind=exc.error_kind if isinstance(exc, SocksTargetError) else "socks_error",
165
+ error_detail=str(exc),
166
+ )
167
+ except httpx.TimeoutException:
168
+ elapsed = (time.perf_counter() - start) * 1000
169
+ return ProbeResult(
170
+ ok=False,
171
+ metrics={"connect_ms": round(elapsed, 3)},
172
+ error_kind="timeout",
173
+ error_detail=f"Request timed out after {timeout_sec}s",
174
+ )
175
+ except httpx.HTTPError as exc:
176
+ elapsed = (time.perf_counter() - start) * 1000
177
+ return ProbeResult(
178
+ ok=False,
179
+ metrics={"connect_ms": round(elapsed, 3)},
180
+ error_kind="http_error",
181
+ error_detail=f"{type(exc).__name__}: {exc}",
182
+ )
183
+ except Exception as exc: # noqa: BLE001 - a probe must fail one target, never the batch
184
+ # The custom SOCKS transport can surface raw OSError/ValueError
185
+ # (peer reset mid-read, oversized header line) that httpx does not
186
+ # wrap; record this target as failed instead of aborting the whole
187
+ # multi-device check, matching the tcp_connect contract.
188
+ elapsed = (time.perf_counter() - start) * 1000
189
+ return ProbeResult(
190
+ ok=False,
191
+ metrics={"connect_ms": round(elapsed, 3)},
192
+ error_kind="error",
193
+ error_detail=f"{type(exc).__name__}: {exc}",
194
+ )
195
+
196
+ elapsed = (time.perf_counter() - start) * 1000
197
+ metrics = {"connect_ms": round(elapsed, 3), "http_status": response.status_code}
198
+ if response.status_code >= 400:
199
+ return ProbeResult(
200
+ ok=False,
201
+ metrics=metrics,
202
+ error_kind="http_status",
203
+ error_detail=f"HTTP {response.status_code}",
204
+ )
205
+ return ProbeResult(ok=True, metrics=metrics)
@@ -0,0 +1,185 @@
1
+ # SPDX-FileCopyrightText: 2025-2026 Rexonix s.r.o.
2
+ # SPDX-FileContributor: Jakub Trávník <jakub.travnik@gmail.com>
3
+ #
4
+ # SPDX-License-Identifier: AGPL-3.0-or-later
5
+
6
+ """ICMP ping probe.
7
+
8
+ Runs the system ``ping`` command via an asyncio subprocess (cross-platform),
9
+ extracting RTT/jitter/packet-loss metrics.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import asyncio
15
+ import contextlib
16
+ import logging
17
+ import platform
18
+ import re
19
+ from typing import Any
20
+
21
+ from hegemony_step_sdk import BaseProbe, ProbeResult
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+ # Regex patterns for parsing ping output.
26
+ # Linux: "rtt min/avg/max/mdev = 0.123/0.456/0.789/0.012 ms"
27
+ LINUX_RTT_PATTERN = re.compile(r"rtt min/avg/max/mdev = ([\d.]+)/([\d.]+)/([\d.]+)/([\d.]+) ms")
28
+ # Windows: "Minimum = 1ms, Maximum = 2ms, Average = 1ms"
29
+ WINDOWS_RTT_PATTERN = re.compile(r"Minimum = (\d+)ms, Maximum = (\d+)ms, Average = (\d+)ms")
30
+ # Single ping RTT — Linux: "time=0.123 ms"
31
+ LINUX_SINGLE_RTT = re.compile(r"time=([\d.]+)\s*ms")
32
+ # Windows: "time=1ms" or "time<1ms"
33
+ WINDOWS_SINGLE_RTT = re.compile(r"time[<=]([\d.]+)ms")
34
+
35
+
36
+ def calculate_jitter(rtt_values: list[float]) -> float | None:
37
+ """Mean absolute difference between consecutive RTTs (simplified RFC 3550)."""
38
+ if len(rtt_values) < 2:
39
+ return None
40
+ diffs = [abs(rtt_values[i + 1] - rtt_values[i]) for i in range(len(rtt_values) - 1)]
41
+ return sum(diffs) / len(diffs)
42
+
43
+
44
+ class IcmpPingProbe(BaseProbe):
45
+ """ICMP ping probe using the system ping command.
46
+
47
+ Options:
48
+ count: Number of pings to send (default: 1)
49
+ timeout_ms: Timeout per ping in milliseconds (default: 1000)
50
+
51
+ Metrics produced:
52
+ rtt_ms, rtt_min_ms, rtt_max_ms, rtt_mdev_ms (Linux), jitter_ms,
53
+ packets_sent, packets_received, packet_loss_pct
54
+ """
55
+
56
+ probe_id = "icmp_ping"
57
+
58
+ async def execute(self, address: str, options: dict[str, Any]) -> ProbeResult:
59
+ # ICMP cannot traverse an SSH tunnel / SOCKS proxy (design §11.4):
60
+ # reject the option explicitly rather than silently ignoring it and
61
+ # reporting misleading local reachability. tcp_connect:22 is the
62
+ # recommended liveness substitute for tunneled targets.
63
+ if (options.get("socks_proxy") or "").strip():
64
+ return ProbeResult(
65
+ ok=False,
66
+ error_kind="config_error",
67
+ error_detail=(
68
+ "icmp_ping cannot use socks_proxy (ICMP does not traverse a "
69
+ "SOCKS/SSH tunnel); use tcp_connect for tunneled targets"
70
+ ),
71
+ )
72
+
73
+ count = options.get("count", 1)
74
+ timeout_ms = options.get("timeout_ms", 1000)
75
+ timeout_sec = timeout_ms / 1000.0
76
+
77
+ is_windows = platform.system().lower() == "windows"
78
+ if is_windows:
79
+ cmd = ["ping", "-n", str(count), "-w", str(timeout_ms), address]
80
+ else:
81
+ cmd = ["ping", "-c", str(count), "-W", str(max(1, int(timeout_sec))), address]
82
+
83
+ try:
84
+ process = await asyncio.create_subprocess_exec(
85
+ *cmd,
86
+ stdout=asyncio.subprocess.PIPE,
87
+ stderr=asyncio.subprocess.PIPE,
88
+ )
89
+ try:
90
+ stdout, _stderr = await asyncio.wait_for(
91
+ process.communicate(),
92
+ timeout=timeout_sec * count + 5, # extra buffer
93
+ )
94
+ except TimeoutError:
95
+ return ProbeResult(
96
+ ok=False,
97
+ error_kind="timeout",
98
+ error_detail=f"Ping command timed out after {timeout_sec * count + 5}s",
99
+ )
100
+ finally:
101
+ # Our own timeout, or a caller cancelling the probe (a shorter
102
+ # poll deadline, a sibling target's egress denial), stops
103
+ # communicate() with ping still running. Kill and reap it
104
+ # before returning or re-raising, so no child outlives us.
105
+ if process.returncode is None:
106
+ with contextlib.suppress(ProcessLookupError):
107
+ process.kill()
108
+ await process.wait()
109
+
110
+ output = stdout.decode("utf-8", errors="replace")
111
+ return self._parse_output(output, process.returncode, is_windows)
112
+
113
+ except FileNotFoundError:
114
+ return ProbeResult(
115
+ ok=False,
116
+ error_kind="command_not_found",
117
+ error_detail="ping command not found on system",
118
+ )
119
+ except Exception as e: # noqa: BLE001 - probe never raises for a single target
120
+ logger.exception("Ping check failed for %s", address)
121
+ return ProbeResult(ok=False, error_kind="exception", error_detail=str(e))
122
+
123
+ def _extract_individual_rtts(self, output: str, is_windows: bool) -> list[float]:
124
+ """Extract individual RTT values from ping output for jitter calculation."""
125
+ pattern = WINDOWS_SINGLE_RTT if is_windows else LINUX_SINGLE_RTT
126
+ return [float(match.group(1)) for match in pattern.finditer(output)]
127
+
128
+ def _parse_output(self, output: str, return_code: int | None, is_windows: bool) -> ProbeResult:
129
+ """Parse ping command output to extract metrics."""
130
+ metrics: dict[str, Any] = {}
131
+ individual_rtts = self._extract_individual_rtts(output, is_windows)
132
+
133
+ if is_windows:
134
+ match = WINDOWS_RTT_PATTERN.search(output)
135
+ if match:
136
+ metrics["rtt_min_ms"] = float(match.group(1))
137
+ metrics["rtt_max_ms"] = float(match.group(2))
138
+ metrics["rtt_ms"] = float(match.group(3))
139
+ elif individual_rtts:
140
+ metrics["rtt_ms"] = individual_rtts[-1]
141
+ else:
142
+ match = LINUX_RTT_PATTERN.search(output)
143
+ if match:
144
+ metrics["rtt_min_ms"] = float(match.group(1))
145
+ metrics["rtt_ms"] = float(match.group(2)) # avg
146
+ metrics["rtt_max_ms"] = float(match.group(3))
147
+ metrics["rtt_mdev_ms"] = float(match.group(4))
148
+ elif individual_rtts:
149
+ metrics["rtt_ms"] = individual_rtts[-1]
150
+
151
+ if len(individual_rtts) >= 2:
152
+ jitter = calculate_jitter(individual_rtts)
153
+ if jitter is not None:
154
+ metrics["jitter_ms"] = round(jitter, 3)
155
+ elif "rtt_mdev_ms" in metrics:
156
+ metrics["jitter_ms"] = metrics["rtt_mdev_ms"]
157
+
158
+ # Packet statistics.
159
+ # Linux: "2 packets transmitted, 2 received, 0% packet loss"
160
+ # Windows: "Packets: Sent = 2, Received = 2, Lost = 0 (0% loss)"
161
+ sent_match = re.search(r"(\d+)\s*packets?\s*(?:transmitted|Sent)", output, re.I)
162
+ recv_match = re.search(r"(\d+)\s*(?:packets?\s*)?received", output, re.I)
163
+ loss_match = re.search(r"(\d+(?:\.\d+)?)[%]\s*(?:packet\s*)?loss", output, re.I)
164
+ if sent_match:
165
+ metrics["packets_sent"] = int(sent_match.group(1))
166
+ if recv_match:
167
+ metrics["packets_received"] = int(recv_match.group(1))
168
+ if loss_match:
169
+ metrics["packet_loss_pct"] = float(loss_match.group(1))
170
+
171
+ ok = return_code == 0 and metrics.get("packets_received", 0) > 0
172
+
173
+ if not ok and not metrics:
174
+ error_detail = output.strip()[:500] if output else "No response"
175
+ return ProbeResult(
176
+ ok=False, error_kind="no_response", error_detail=error_detail, raw_text=output
177
+ )
178
+
179
+ return ProbeResult(
180
+ ok=ok,
181
+ metrics=metrics,
182
+ raw_text=output if not ok else None,
183
+ error_kind="packet_loss" if not ok else None,
184
+ error_detail=f"{metrics.get('packet_loss_pct', 100)}% packet loss" if not ok else None,
185
+ )