#!/usr/bin/env python3 """Liveness probe for the pymodbus simulator: one FC03 read with a hard deadline (#909). A TCP connect is not enough. The #909 fixture accepted connections while answering every request after the client had timed out, so a connect-only check stayed green. This probe sends a real FC03 read and passes only on a timely, well-formed reply. A Modbus exception reply also passes: it proves the request loop is serving. Pure stdlib, so it runs in the image without extra packages. It is used two ways: * as the compose ``healthcheck`` (exit code 0 = healthy, 1 = unhealthy); * imported by ``run_simulator.py``, whose watchdog exits the container after repeated failures so ``restart: unless-stopped`` brings up a fresh one. Usage: fc3_probe.py [--port 5020] [--framer socket|rtu] [--deadline 3] """ import argparse import socket import struct import sys import time def _crc16(data: bytes) -> int: crc = 0xFFFF for b in data: crc ^= b for _ in range(8): crc = (crc >> 1) ^ 0xA001 if crc & 1 else crc >> 1 return crc def _recv_exact(sock: socket.socket, n: int, end: float) -> bytes: buf = b"" while len(buf) < n: remaining = end - time.monotonic() if remaining <= 0: raise TimeoutError("deadline passed") sock.settimeout(remaining) chunk = sock.recv(n - len(buf)) if not chunk: raise ConnectionError("closed mid-reply") buf += chunk return buf def probe(host: str = "127.0.0.1", port: int = 5020, framer: str = "socket", deadline: float = 3.0, unit: int = 1, address: int = 0) -> None: """Raise on failure; return on a timely, well-formed FC03 reply (data or exception).""" end = time.monotonic() + deadline pdu = struct.pack(">BHH", 3, address, 1) with socket.create_connection((host, port), timeout=deadline) as sock: if framer == "rtu": frame = bytes([unit]) + pdu sock.sendall(frame + struct.pack("HHHB", tid, 0, len(pdu) + 1, unit) + pdu) header = _recv_exact(sock, 7, end) rtid, _, length, _ = struct.unpack(">HHHB", header) if rtid != tid: raise ValueError(f"transaction id {rtid} != {tid}") if length < 2: raise ValueError(f"MBAP length {length} too small") _recv_exact(sock, length - 1, end) def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--host", default="127.0.0.1") ap.add_argument("--port", type=int, default=5020) ap.add_argument("--framer", choices=["socket", "rtu"], default="socket") ap.add_argument("--deadline", type=float, default=3.0) args = ap.parse_args() try: probe(args.host, args.port, args.framer, args.deadline) except Exception as exc: # noqa: BLE001 - any failure is "unhealthy" print(f"FC03 probe failed: {type(exc).__name__}: {exc}", file=sys.stderr) return 1 return 0 if __name__ == "__main__": sys.exit(main())