cmvr-es/scripts/wait_network_devices.py
xtkuang 3d8391f3c6 chore(config): sync dev real and simulation device profiles
Sync configuration-related changes from dev 7d230fa5, including profile-aware readiness helpers and test paths. Keep linbo_dev legacy/minimal arm and Lingkong templates so existing references remain valid. Disable repository device defaults in both real and simulation profiles. Preserve the SocketCAN fix. Validate full Release all-target build, ten readiness tests and fifteen protobuf configurations.
2026-11-20 09:43:35 +08:00

203 lines
7.8 KiB
Python
Executable File

#!/usr/bin/env python3
"""Startup readiness only. Never sends device commands or restarts a running service."""
import argparse
import concurrent.futures
import dataclasses
import ipaddress
import json
import os
from pathlib import Path
import re
import socket
import sys
import time
@dataclasses.dataclass(frozen=True)
class Endpoint:
device: str
host: str
port: int
def label(self):
return f"{self.device} {self.host}:{self.port}"
def uncomment(text):
pattern = r'"(?:\\.|[^"\\])*"|\#[^\n]*|//[^\n]*'
return re.sub(pattern, lambda m: m[0] if m[0].startswith('"') else "", text)
def blocks(text, name):
"""Read balanced named textproto blocks, preserving quoted braces."""
text = uncomment(text)
masked = re.sub(r'"(?:\\.|[^"\\])*"', lambda m: " " * len(m[0]), text)
for match in re.finditer(r'\b' + re.escape(name) + r'\s*:?\s*\{', masked):
start = match.end()
depth, quoted, escape = 1, False, False
for i in range(start, len(text)):
c = text[i]
if quoted:
if escape:
escape = False
elif c == "\\":
escape = True
elif c == '"':
quoted = False
elif c == '"':
quoted = True
elif c == "{":
depth += 1
elif c == "}":
depth -= 1
if not depth:
yield text[start:i]
break
else:
raise ValueError(f"unterminated {name} configuration block")
def scalar(text, key, default=None):
match = re.search(r'\b' + re.escape(key) + r'\s*:\s*("(?:\\.|[^"\\])*"|[^\s{};,]+)', uncomment(text))
if not match:
return default
value = match[1]
return json.loads(value) if value.startswith('"') else value
def endpoints(config_dir):
root = Path(config_dir).resolve()
app_config = (root / "cmvr_es.pb.txt").read_text(encoding="utf-8")
app = next(blocks(app_config, "cmvr_es"), "")
manager_file = scalar(app, "device_manager_config_file")
if not manager_file:
raise ValueError("missing device_manager_config_file in cmvr_es.pb.txt")
manager = (root / manager_file).read_text(encoding="utf-8")
result = []
for device in blocks(manager, "devices"):
if scalar(device, "enable", "false") != "true":
continue
kind, identifier = scalar(device, "type"), scalar(device, "id")
if kind not in ("DEVICE_TYPE_ROBOT_ARM", "DEVICE_TYPE_AGV"):
continue
relative = scalar(device, "config_file")
if not relative:
raise ValueError(f"missing config_file for {identifier}")
path = (root / relative).resolve()
if root not in path.parents:
raise ValueError(f"config path outside runtime config: {identifier}")
content = path.read_text(encoding="utf-8")
candidates = [b for b in blocks(content, "robot_arms" if kind == "DEVICE_TYPE_ROBOT_ARM" else "agvs")
if scalar(b, "id") == identifier]
if len(candidates) != 1:
raise ValueError(f"expected one matching configuration for {identifier}")
entry = candidates[0]
if kind == "DEVICE_TYPE_ROBOT_ARM":
vendor = next(blocks(entry, "vendor"), None)
if not vendor or scalar(vendor, "brand") != "VENDOR_ROBOT_ARM_BRAND_AUBO_ARM":
continue
pairs = [(scalar(vendor, "ip"), scalar(vendor, "port", "30004"))]
else:
vendor = next(blocks(entry, "seer_robokit_agv"), None)
if vendor is None:
continue
host = scalar(vendor, "ip")
keys = ["port_status", "port_control", "port_nav", "port_config"]
if scalar(vendor, "enable_state_push", "false") == "true":
keys.append("port_push")
pairs = [(host, scalar(vendor, key)) for key in keys]
for host, port in pairs:
if not host or not port or not 1 <= int(port) <= 65535:
raise ValueError(f"missing or invalid network endpoint for {identifier}")
ipaddress.IPv4Address(host)
item = Endpoint(identifier, host, int(port))
if item not in result:
result.append(item)
return result
def reachable(endpoint):
try:
with socket.create_connection((endpoint.host, endpoint.port), timeout=1.5):
return True
except OSError:
return False
def process_connections(pid):
directory = Path(f"/proc/{pid}")
if not directory.exists():
raise RuntimeError(f"main process {pid} exited during startup")
inodes = set()
for fd in (directory / "fd").iterdir():
try:
target = os.readlink(fd)
except OSError:
continue
if target.startswith("socket:["):
inodes.add(target[8:-1])
result = set()
for line in (directory / "net/tcp").read_text().splitlines()[1:]:
fields = line.split()
if fields[3] == "01" and fields[9] in inodes:
host, port = fields[2].split(":")
result.add((socket.inet_ntoa(bytes.fromhex(host)[::-1]), int(port, 16)))
return result
def wait_ready(expected, timeout, stable, mode="ports", pid=None, interval=2.0):
print(f"[cmvr-startup] checking {mode}: " + (", ".join(e.label() for e in expected) or "no enabled AUBO/SEER network devices"), flush=True)
if not expected:
return True
deadline = time.monotonic() + timeout
since, previous, last_report = None, None, 0.0
with concurrent.futures.ThreadPoolExecutor(max_workers=min(8, len(expected))) as pool:
while time.monotonic() < deadline:
if mode == "connected":
connections = process_connections(pid)
ready = [(e.host, e.port) in connections for e in expected]
else:
ready = list(pool.map(reachable, expected))
now = time.monotonic()
missing = tuple(e.label() for e, ok in zip(expected, ready) if not ok)
if not missing:
since = now if since is None else since
if now - since >= stable:
print(f"[cmvr-startup] ready, stable for {stable:g}s", flush=True)
return True
else:
since = None
if missing != previous or now - last_report >= 15:
print("[cmvr-startup] " + ("waiting: " + ", ".join(missing) if missing else "all available; waiting for stable readiness"), flush=True)
previous, last_report = missing, now
time.sleep(min(interval, max(0.0, deadline - time.monotonic())))
print("[cmvr-startup] readiness timed out; systemd will retry startup", flush=True)
return False
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--config-dir", required=True)
parser.add_argument("--mode", choices=["ports", "connected"], default="ports")
parser.add_argument("--pid", type=int)
parser.add_argument("--timeout", type=float, default=180)
parser.add_argument("--stable-seconds", type=float, default=10)
parser.add_argument("--list", action="store_true")
args = parser.parse_args()
try:
expected = endpoints(args.config_dir)
if args.list:
for item in expected:
print(item.label())
return 0
if args.mode == "connected" and (args.pid is None or args.pid <= 0):
raise ValueError("connected check requires the service MAINPID")
return 0 if wait_ready(expected, args.timeout, args.stable_seconds, args.mode, args.pid) else 1
except (OSError, ValueError, RuntimeError) as error:
print(f"[cmvr-startup] configuration/check error: {error}", file=sys.stderr, flush=True)
return 1
if __name__ == "__main__":
sys.exit(main())