hegemony-steps-probe 0.48.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,42 @@
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
+ """Unauthenticated probe step handlers (reachability, DNS, HTTP, TLS) for Hegemony.
7
+
8
+ Outside-observation probes: one-shot connectivity, DNS, HTTP and TLS
9
+ certificate checks, and stable-reachability waits. No device credentials
10
+ involved.
11
+
12
+ Registers under the ``hegemony.step_handlers`` entry-point group; the entry
13
+ point name is the claimed handler-id namespace prefix (``probe``).
14
+ Handlers reach every platform facility through ``ctx.services``.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from hegemony_step_sdk import BaseHandler, StepHandlerRegistry
20
+
21
+ from .connectivity import ConnectivityCheckHandler
22
+ from .dns_check import DnsProbeHandler
23
+ from .http_check import HttpProbeHandler
24
+ from .tls_check import TlsProbeHandler
25
+ from .wait_reachable import WaitReachableHandler
26
+
27
+ ALL_HANDLERS: tuple[type[BaseHandler], ...] = (
28
+ ConnectivityCheckHandler,
29
+ DnsProbeHandler,
30
+ HttpProbeHandler,
31
+ TlsProbeHandler,
32
+ WaitReachableHandler,
33
+ )
34
+
35
+
36
+ def register(registry: StepHandlerRegistry) -> None:
37
+ """Entry point: register this wheel's handlers with the host registry."""
38
+ for handler_class in ALL_HANDLERS:
39
+ registry.register_handler_type(handler_class)
40
+
41
+
42
+ __all__ = ["ALL_HANDLERS", "register", *sorted(cls.__name__ for cls in ALL_HANDLERS)]
@@ -0,0 +1,40 @@
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
+ """What the handlers that run checks through ``run_probe`` share.
7
+
8
+ ``probe.connectivity`` and ``probe.wait_reachable`` both offer the worker's
9
+ registered checks and build their probe options the same way.
10
+ """
11
+
12
+ #: Display names for the check types the probe wheel ships. Cosmetic: the
13
+ #: options themselves come from the worker's probe registry, and an id
14
+ #: without a label shows as itself.
15
+ CHECK_TYPE_LABELS = {
16
+ "tcp_connect": "TCP Connect",
17
+ "icmp_ping": "ICMP Ping",
18
+ "http_health": "HTTP Health",
19
+ "dns_resolve": "DNS Resolve",
20
+ }
21
+
22
+ #: Checks that connect to a port; the others (icmp_ping, dns_resolve) take none.
23
+ PORT_CHECKS = frozenset({"tcp_connect", "http_health", "tls_handshake", "ssh_banner"})
24
+
25
+
26
+ class CheckUnavailable(Exception):
27
+ """``run_probe`` has no probe for the check type (it raised KeyError)."""
28
+
29
+
30
+ #: Ports a check uses when the step sets none, where SSH's 22 would be wrong.
31
+ _CHECK_DEFAULT_PORTS = {"http_health": 80}
32
+
33
+
34
+ def default_port(check_type: str, fallback: int = 22) -> int:
35
+ """The port ``check_type`` uses when the step sets none.
36
+
37
+ HTTP Health asks port 80; every other check keeps ``fallback``, which is
38
+ the SSH port the steps have always defaulted to.
39
+ """
40
+ return _CHECK_DEFAULT_PORTS.get(check_type, fallback)
@@ -0,0 +1,310 @@
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
+ """ConnectivityCheckHandler: one-shot connectivity probes against targets.
7
+
8
+ The probe implementations (tcp/icmp/http/dns) come from the host's
9
+ ``hegemony.probes`` registry via ``ctx.services.run_probe`` — the *same*
10
+ probes the background monitor runs, so there is a single implementation of
11
+ each check type rather than one copy here and one in the monitor.
12
+ """
13
+
14
+ import asyncio
15
+ import logging
16
+ from typing import Any
17
+
18
+ from pydantic import AliasChoices, BaseModel, ConfigDict, Field
19
+
20
+ from hegemony_step_sdk import (
21
+ MAX_PARALLEL_DEVICES_LIMIT,
22
+ BaseHandler,
23
+ HandlerContext,
24
+ HandlerResult,
25
+ InvalidConfigError,
26
+ ProbeResult,
27
+ StepKind,
28
+ for_each_target_device,
29
+ )
30
+
31
+ from .checks import CHECK_TYPE_LABELS, PORT_CHECKS, CheckUnavailable, default_port
32
+ from .targets import (
33
+ DEFAULT_MAX_PARALLEL_TARGETS,
34
+ TARGETS_OUTPUT_FIELDS,
35
+ TargetOutcome,
36
+ all_probe_targets,
37
+ chain_output,
38
+ merge_outcomes,
39
+ )
40
+
41
+ logger = logging.getLogger(__name__)
42
+
43
+
44
+ class ConnectivityCheckConfig(BaseModel):
45
+ """Config for ``probe.connectivity``."""
46
+
47
+ model_config = ConfigDict(extra="allow")
48
+
49
+ # Registry-driven: the selectable check types are whatever the host's
50
+ # ``hegemony.probes`` registry provides. The wheel declares intent via
51
+ # ``x_options_source`` and the host injects the enum at the metadata
52
+ # endpoint; ``run_probe`` enforces validity at run time. ``x_option_labels``
53
+ # are cosmetic — unknown ids fall back to the id string.
54
+ check_type: str = Field(
55
+ default="tcp_connect",
56
+ title="Check Type",
57
+ description=(
58
+ "Which probe to run against each target; the list comes from the "
59
+ "checks registered on the worker. Defaults to a TCP connection "
60
+ "attempt (tcp_connect) on the configured port."
61
+ ),
62
+ json_schema_extra={
63
+ "x_widget": "select",
64
+ "x_options_source": "probes",
65
+ "x_option_labels": CHECK_TYPE_LABELS,
66
+ },
67
+ )
68
+ port: int | None = Field(
69
+ default=None,
70
+ ge=1,
71
+ le=65535,
72
+ title="Port",
73
+ description=(
74
+ "Port the port-based checks connect to. When empty, HTTP Health "
75
+ "uses 80 and the other checks 22. Ignored by ICMP Ping and DNS "
76
+ "Resolve."
77
+ ),
78
+ json_schema_extra={
79
+ "x_placeholder": "22, or 80 for HTTP Health",
80
+ "x_hide_when": {"field": "check_type", "value": "icmp_ping"},
81
+ },
82
+ )
83
+ attempt_timeout_seconds: int = Field(
84
+ default=10,
85
+ ge=1,
86
+ # Steps saved before the rename carry timeout_sec.
87
+ validation_alias=AliasChoices("attempt_timeout_seconds", "timeout_sec"),
88
+ title="Timeout (sec)",
89
+ description=(
90
+ "Time limit for each probe attempt, in seconds. An attempt that "
91
+ "does not complete in time counts as failed. Defaults to 10."
92
+ ),
93
+ json_schema_extra={"x_legacy_keys": ["timeout_sec"]},
94
+ )
95
+ attempts: int = Field(
96
+ default=1, ge=1, le=10, title="Attempts", description="Number of attempts (1-10)"
97
+ )
98
+ url_path: str = Field(
99
+ default="",
100
+ title="URL Path",
101
+ description=(
102
+ "URL path requested by the HTTP Health check; when omitted the "
103
+ "check requests /health. Ignored by every other check type."
104
+ ),
105
+ json_schema_extra={
106
+ "x_placeholder": "/health",
107
+ "x_show_when": {"field": "check_type", "value": "http_health"},
108
+ "x_col_span": 2,
109
+ },
110
+ )
111
+ hostname: str = Field(
112
+ default="",
113
+ title="Hostname to Resolve",
114
+ description=(
115
+ "DNS name the DNS Resolve check looks up with the worker's system "
116
+ "resolver, once per target; the target is not asked. When empty, "
117
+ "each target's own name is looked up, so an IP address target "
118
+ "needs this field. An IP address here fails the check, as the "
119
+ "resolver returns it without a lookup. Ignored by every other "
120
+ "check type."
121
+ ),
122
+ json_schema_extra={
123
+ "x_placeholder": "device.example.com",
124
+ "x_show_when": {"field": "check_type", "value": "dns_resolve"},
125
+ "x_col_span": 2,
126
+ },
127
+ )
128
+ socks_proxy: str = Field(
129
+ default="",
130
+ title="SOCKS5 Proxy",
131
+ description=(
132
+ "Route TCP-based checks through an authenticated SOCKS5 proxy "
133
+ "(socks5[h]://user:pass@host:port), e.g. the lab bastion. "
134
+ "icmp_ping rejects it — use tcp_connect for tunneled targets."
135
+ ),
136
+ json_schema_extra={
137
+ "x_placeholder": "socks5://user:{{ secret('vault://lab/bastion/password') }}@dind:1080",
138
+ "x_col_span": 2,
139
+ },
140
+ )
141
+ max_parallel_devices: int = Field(
142
+ default=DEFAULT_MAX_PARALLEL_TARGETS,
143
+ ge=1,
144
+ le=MAX_PARALLEL_DEVICES_LIMIT,
145
+ title="Max Parallel Devices",
146
+ description="Targets checked at the same time (1 = one after another). Defaults to 10.",
147
+ )
148
+
149
+
150
+ class ConnectivityCheckHandler(BaseHandler):
151
+ """Unified connectivity check handler.
152
+
153
+ Performs single or few connectivity checks against targets and
154
+ emits results as evidence. Settings: :class:`ConnectivityCheckConfig`.
155
+ """
156
+
157
+ handler_id = "probe.connectivity"
158
+ supported_kinds = [StepKind.CHECK]
159
+ display_name = "Connectivity Check"
160
+ description = "One-shot connectivity probes (TCP/ICMP/HTTP/DNS) against targets."
161
+ category = "Checks"
162
+ config_model = ConnectivityCheckConfig
163
+ output_fields = TARGETS_OUTPUT_FIELDS
164
+ default_config = {"check_type": "tcp_connect", "attempt_timeout_seconds": 10, "attempts": 1}
165
+
166
+ async def execute(self, ctx: HandlerContext) -> HandlerResult:
167
+ """Run connectivity check against all targets (devices and direct IPs)."""
168
+ target_devices = all_probe_targets(ctx)
169
+ if not target_devices:
170
+ return HandlerResult(
171
+ success=False,
172
+ error="No target devices or IPs configured",
173
+ summary="Missing targets",
174
+ )
175
+
176
+ try:
177
+ config = self.parse_config(ctx.config, ConnectivityCheckConfig)
178
+ except InvalidConfigError as exc:
179
+ return exc.result()
180
+ check_type = config.check_type
181
+ # An empty Port means the check's own default: 80 for HTTP Health,
182
+ # 22 (the old fixed default) for the rest.
183
+ port = config.port or default_port(check_type)
184
+ attempts = config.attempts
185
+
186
+ # Build check options based on type. An unregistered check type fails
187
+ # the step below when run_probe raises KeyError — validity is the host
188
+ # probe registry, not a hardcoded allowlist here.
189
+ options: dict[str, Any] = {"timeout_ms": config.attempt_timeout_seconds * 1000}
190
+ if check_type in PORT_CHECKS:
191
+ options["port"] = port
192
+ if check_type == "http_health":
193
+ options["url_path"] = config.url_path or "/health"
194
+ elif check_type == "icmp_ping":
195
+ options["count"] = 1
196
+ elif check_type == "dns_resolve":
197
+ options["hostname"] = config.hostname
198
+
199
+ # Bastion routing (design-dind-sandbox.md §11.4): forwarded for every
200
+ # check type — the probes that cannot carry it (icmp_ping, dns_resolve)
201
+ # reject it with a clear config_error instead of silently probing the
202
+ # wrong path.
203
+ socks_proxy = config.socks_proxy.strip()
204
+ if socks_proxy:
205
+ options["socks_proxy"] = socks_proxy
206
+
207
+ services = ctx.require_services()
208
+
209
+ async def _check(device: dict[str, Any]) -> TargetOutcome:
210
+ """Probe one target, retrying up to ``attempts`` times."""
211
+ # None for a direct-IP target: it has no inventory identity, and
212
+ # the artifact column behind evidence device_id is a UUID.
213
+ device_id = device.get("id")
214
+ device_name = device.get("name") or device_id or "unknown"
215
+ host = device.get("mgmt_host")
216
+ if not host:
217
+ return TargetOutcome(device_name, ok=False, error="no host")
218
+
219
+ # Run checks with attempts, through the host's shared probe registry.
220
+ best_result: ProbeResult | None = None
221
+ for attempt in range(attempts):
222
+ try:
223
+ result = await services.run_probe(check_type, host, options)
224
+ except KeyError:
225
+ raise CheckUnavailable from None
226
+ best_result = result
227
+ if result.ok:
228
+ break
229
+ if attempt < attempts - 1:
230
+ await asyncio.sleep(0.5) # Brief pause between retries
231
+
232
+ if best_result and best_result.ok:
233
+ # Extract primary metric
234
+ latency_ms = None
235
+ if "rtt_ms" in best_result.metrics:
236
+ latency_ms = best_result.metrics["rtt_ms"]
237
+ elif "connect_ms" in best_result.metrics:
238
+ latency_ms = best_result.metrics["connect_ms"]
239
+ return TargetOutcome(
240
+ device_name,
241
+ ok=True,
242
+ latency_ms=latency_ms,
243
+ evidence={
244
+ "kind": "transport_meta",
245
+ "name": f"connectivity_{check_type}_{device_name}",
246
+ "device_id": device_id,
247
+ "content_json": {
248
+ "device_id": device_id,
249
+ "device_name": device_name,
250
+ "host": host,
251
+ "check_type": check_type,
252
+ "success": True,
253
+ "metrics": best_result.metrics,
254
+ },
255
+ },
256
+ )
257
+ error_msg = best_result.error_detail if best_result else "unknown error"
258
+ return TargetOutcome(
259
+ device_name,
260
+ ok=False,
261
+ error=error_msg,
262
+ evidence={
263
+ "kind": "transport_meta",
264
+ "name": f"connectivity_{check_type}_{device_name}",
265
+ "device_id": device_id,
266
+ "content_json": {
267
+ "device_id": device_id,
268
+ "device_name": device_name,
269
+ "host": host,
270
+ "check_type": check_type,
271
+ "success": False,
272
+ "error": error_msg,
273
+ },
274
+ },
275
+ )
276
+
277
+ # Egress denials raised by run_probe propagate and cancel the rest.
278
+ try:
279
+ outcomes = await for_each_target_device(
280
+ target_devices,
281
+ _check,
282
+ max_parallel=config.max_parallel_devices,
283
+ )
284
+ except CheckUnavailable:
285
+ return HandlerResult(
286
+ success=False,
287
+ error=f"Check type '{check_type}' is not available on this worker",
288
+ summary=f"Unsupported check type: {check_type}",
289
+ )
290
+ all_evidence, all_metrics, failed_devices = merge_outcomes(outcomes)
291
+ success_count = sum(outcome.ok for outcome in outcomes)
292
+
293
+ total = len(target_devices)
294
+ if failed_devices:
295
+ return HandlerResult(
296
+ success=False,
297
+ error=f"Failed: {', '.join(failed_devices)}",
298
+ summary=f"{check_type}: {success_count}/{total} targets OK",
299
+ metrics=all_metrics,
300
+ evidence=all_evidence,
301
+ output=chain_output(outcomes),
302
+ )
303
+
304
+ return HandlerResult(
305
+ success=True,
306
+ summary=f"{check_type}: {success_count}/{total} targets OK",
307
+ metrics=all_metrics,
308
+ evidence=all_evidence,
309
+ output=chain_output(outcomes),
310
+ )