"""ICMP / TCP reachability checks — pure probes returning a result dict.""" from __future__ import annotations import asyncio import logging import time logger = logging.getLogger(__name__) TCP_TIMEOUT = 5.0 DEFAULT_TCP_PORT = 80 async def tcp_check(address: str, port: int) -> dict: """TCP connect probe. Returns {is_up, response_ms}.""" start = time.monotonic() try: reader, writer = await asyncio.wait_for( asyncio.open_connection(address, port), timeout=TCP_TIMEOUT, ) writer.close() await writer.wait_closed() return {"is_up": True, "response_ms": round((time.monotonic() - start) * 1000, 2)} except Exception: return {"is_up": False, "response_ms": None} async def icmp_check(address: str) -> dict: """ICMP echo via the system ping binary (setuid; no raw-socket privilege). Falls back to a TCP connect on the default port if the ping binary is unavailable or errors, so a host with ICMP filtered still gets a signal. """ start = time.monotonic() try: proc = await asyncio.create_subprocess_exec( "ping", "-c", "1", "-W", "2", address, stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.DEVNULL, ) await asyncio.wait_for(proc.wait(), timeout=5.0) if proc.returncode == 0: return {"is_up": True, "response_ms": round((time.monotonic() - start) * 1000, 2)} return {"is_up": False, "response_ms": None} except Exception as exc: logger.warning("ICMP ping failed for %s: %s, falling back to TCP", address, exc) return await tcp_check(address, DEFAULT_TCP_PORT)