ploop/scripts/check_dev_services.py

111 lines
3.4 KiB
Python

"""Explicit, secret-safe TCP reachability checks for development services."""
from __future__ import annotations
import argparse
from dataclasses import dataclass
from pathlib import Path
import socket
REQUIRED_ENDPOINT_SETTINGS = {
"postgres": ("PLOOP_POSTGRES_HOST", "PLOOP_POSTGRES_PORT"),
"redis": ("PLOOP_REDIS_HOST", "PLOOP_REDIS_PORT"),
}
@dataclass(frozen=True)
class Endpoint:
name: str
host: str
port: int
class ConfigurationError(ValueError):
"""Raised when the explicitly supplied environment file is incomplete."""
def main() -> int:
arguments = _parser().parse_args()
try:
endpoints = endpoints_from_file(arguments.environment_file)
except ConfigurationError as error:
print(error)
return 1
reachable = True
for endpoint in endpoints:
if _is_reachable(endpoint, arguments.timeout):
print(f"{endpoint.name}: reachable {endpoint.host}:{endpoint.port}")
continue
print(f"{endpoint.name}: unreachable {endpoint.host}:{endpoint.port}")
reachable = False
return 0 if reachable else 1
def endpoints_from_file(environment_file: Path) -> tuple[Endpoint, ...]:
settings = _read_environment_file(environment_file)
endpoints: list[Endpoint] = []
for name, (host_key, port_key) in REQUIRED_ENDPOINT_SETTINGS.items():
host = _required_setting(settings, host_key)
port = _port_setting(settings, port_key)
endpoints.append(Endpoint(name=name, host=host, port=port))
return tuple(endpoints)
def _parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="Check explicit development PostgreSQL and Redis TCP reachability."
)
parser.add_argument("--env", dest="environment_file", type=Path, required=True)
parser.add_argument("--timeout", type=float, default=3.0)
return parser
def _read_environment_file(environment_file: Path) -> dict[str, str]:
try:
lines = environment_file.read_text(encoding="utf-8").splitlines()
except FileNotFoundError as error:
raise ConfigurationError(f"environment file not found: {environment_file}") from error
settings: dict[str, str] = {}
for line in lines:
stripped = line.strip()
if not stripped or stripped.startswith("#"):
continue
key, separator, value = stripped.partition("=")
if not separator or not key:
raise ConfigurationError("invalid environment file entry")
settings[key] = value
return settings
def _required_setting(settings: dict[str, str], key: str) -> str:
value = settings.get(key, "").strip()
if not value:
raise ConfigurationError(f"missing required setting: {key}")
return value
def _port_setting(settings: dict[str, str], key: str) -> int:
raw_value = _required_setting(settings, key)
try:
port = int(raw_value)
except ValueError as error:
raise ConfigurationError(f"invalid port setting: {key}") from error
if not 1 <= port <= 65535:
raise ConfigurationError(f"invalid port setting: {key}")
return port
def _is_reachable(endpoint: Endpoint, timeout: float) -> bool:
try:
with socket.create_connection((endpoint.host, endpoint.port), timeout=timeout):
return True
except OSError:
return False
if __name__ == "__main__":
raise SystemExit(main())