dutchmate-cli 0.1.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.
- dutchmate_cli/__init__.py +1 -0
- dutchmate_cli/baseline.py +38 -0
- dutchmate_cli/capture.py +94 -0
- dutchmate_cli/client.py +427 -0
- dutchmate_cli/config.py +160 -0
- dutchmate_cli/devices.py +63 -0
- dutchmate_cli/dut.py +32 -0
- dutchmate_cli/gpio.py +33 -0
- dutchmate_cli/lifecycle.py +225 -0
- dutchmate_cli/logs.py +92 -0
- dutchmate_cli/main.py +615 -0
- dutchmate_cli/mcp.py +51 -0
- dutchmate_cli/send.py +32 -0
- dutchmate_cli/sessions.py +137 -0
- dutchmate_cli/status.py +185 -0
- dutchmate_cli/wait.py +41 -0
- dutchmate_cli-0.1.0.dist-info/METADATA +15 -0
- dutchmate_cli-0.1.0.dist-info/RECORD +20 -0
- dutchmate_cli-0.1.0.dist-info/WHEEL +4 -0
- dutchmate_cli-0.1.0.dist-info/licenses/LICENSE +73 -0
dutchmate_cli/config.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""CLI configuration loading for `.dutchmate/config.toml`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any, Final, cast
|
|
10
|
+
|
|
11
|
+
from dutchmate_core.backends.settings import (
|
|
12
|
+
BackendConfig,
|
|
13
|
+
BackendConfigError,
|
|
14
|
+
parse_backend_config,
|
|
15
|
+
)
|
|
16
|
+
from dutchmate_core.validation import (
|
|
17
|
+
DEFAULT_SESSION_MAX_SIZE_MB,
|
|
18
|
+
validate_session_max_size_mb,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
DEFAULT_CONFIG_PATH: Final = Path(".dutchmate/config.toml")
|
|
22
|
+
DEFAULT_DAEMON_HOST: Final = "127.0.0.1"
|
|
23
|
+
DEFAULT_DAEMON_PORT: Final = 2040
|
|
24
|
+
DEFAULT_SESSION_PATH: Final = Path(".dutchmate/sessions")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class CliConfigError(RuntimeError):
|
|
28
|
+
"""Raised when the CLI configuration file is invalid."""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True, slots=True)
|
|
32
|
+
class DaemonConfig:
|
|
33
|
+
"""Device Core Service daemon configuration."""
|
|
34
|
+
|
|
35
|
+
host: str = DEFAULT_DAEMON_HOST
|
|
36
|
+
port: int = DEFAULT_DAEMON_PORT
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True, slots=True)
|
|
40
|
+
class SessionsConfig:
|
|
41
|
+
"""Debug session storage configuration."""
|
|
42
|
+
|
|
43
|
+
path: Path = DEFAULT_SESSION_PATH
|
|
44
|
+
max_size_mb: int = DEFAULT_SESSION_MAX_SIZE_MB
|
|
45
|
+
max_count: int | None = None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True, slots=True)
|
|
49
|
+
class CliConfig:
|
|
50
|
+
"""Merged CLI configuration."""
|
|
51
|
+
|
|
52
|
+
daemon: DaemonConfig = DaemonConfig()
|
|
53
|
+
sessions: SessionsConfig = SessionsConfig()
|
|
54
|
+
backend: BackendConfig = BackendConfig()
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def service_url(self) -> str:
|
|
58
|
+
return f"http://{self.daemon.host}:{self.daemon.port}"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def load_cli_config(path: Path = DEFAULT_CONFIG_PATH) -> CliConfig:
|
|
62
|
+
"""Load CLI configuration from TOML, returning defaults when missing."""
|
|
63
|
+
|
|
64
|
+
try:
|
|
65
|
+
with path.open("rb") as file:
|
|
66
|
+
raw_config = _toml_module().load(file)
|
|
67
|
+
except FileNotFoundError:
|
|
68
|
+
return CliConfig()
|
|
69
|
+
|
|
70
|
+
if not isinstance(raw_config, Mapping):
|
|
71
|
+
raise CliConfigError("CLI config must be a TOML table")
|
|
72
|
+
return parse_cli_config(raw_config)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def parse_cli_config(raw_config: Mapping[str, object]) -> CliConfig:
|
|
76
|
+
"""Parse a raw TOML mapping into validated CLI configuration."""
|
|
77
|
+
|
|
78
|
+
daemon = _parse_daemon_config(_optional_table(raw_config, "daemon"))
|
|
79
|
+
sessions = _parse_sessions_config(_optional_table(raw_config, "sessions"))
|
|
80
|
+
try:
|
|
81
|
+
backend = parse_backend_config(raw_config)
|
|
82
|
+
except BackendConfigError as exc:
|
|
83
|
+
raise CliConfigError(str(exc)) from exc
|
|
84
|
+
return CliConfig(daemon=daemon, sessions=sessions, backend=backend)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _parse_daemon_config(raw_daemon: Mapping[str, object]) -> DaemonConfig:
|
|
88
|
+
host = _optional_str(raw_daemon, "host", DEFAULT_DAEMON_HOST, "[daemon].host")
|
|
89
|
+
port = _optional_port(raw_daemon, "port", DEFAULT_DAEMON_PORT, "[daemon].port")
|
|
90
|
+
return DaemonConfig(host=host, port=port)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _parse_sessions_config(raw_sessions: Mapping[str, object]) -> SessionsConfig:
|
|
94
|
+
path = Path(_optional_str(raw_sessions, "path", str(DEFAULT_SESSION_PATH), "[sessions].path"))
|
|
95
|
+
raw_max_size_mb = raw_sessions.get("max_size_mb", DEFAULT_SESSION_MAX_SIZE_MB)
|
|
96
|
+
try:
|
|
97
|
+
max_size_mb = validate_session_max_size_mb(raw_max_size_mb)
|
|
98
|
+
except ValueError as exc:
|
|
99
|
+
raise CliConfigError("[sessions].max_size_mb must be a positive integer") from exc
|
|
100
|
+
max_count = (
|
|
101
|
+
_optional_positive_int(raw_sessions, "max_count", 1, "[sessions].max_count")
|
|
102
|
+
if "max_count" in raw_sessions
|
|
103
|
+
else None
|
|
104
|
+
)
|
|
105
|
+
return SessionsConfig(path=path, max_size_mb=max_size_mb, max_count=max_count)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _optional_table(raw_config: Mapping[str, object], key: str) -> Mapping[str, object]:
|
|
109
|
+
value = raw_config.get(key, {})
|
|
110
|
+
if not isinstance(value, Mapping):
|
|
111
|
+
raise CliConfigError(f"[{key}] must be a TOML table")
|
|
112
|
+
return cast(Mapping[str, object], value)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _optional_str(
|
|
116
|
+
raw_config: Mapping[str, object],
|
|
117
|
+
key: str,
|
|
118
|
+
default: str,
|
|
119
|
+
field_name: str,
|
|
120
|
+
) -> str:
|
|
121
|
+
value = raw_config.get(key, default)
|
|
122
|
+
if not isinstance(value, str):
|
|
123
|
+
raise CliConfigError(f"{field_name} must be a string")
|
|
124
|
+
stripped = value.strip()
|
|
125
|
+
if not stripped:
|
|
126
|
+
raise CliConfigError(f"{field_name} must not be empty")
|
|
127
|
+
return stripped
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _optional_port(
|
|
131
|
+
raw_config: Mapping[str, object],
|
|
132
|
+
key: str,
|
|
133
|
+
default: int,
|
|
134
|
+
field_name: str,
|
|
135
|
+
) -> int:
|
|
136
|
+
value = _optional_positive_int(raw_config, key, default, field_name)
|
|
137
|
+
if value > 65535:
|
|
138
|
+
raise CliConfigError(f"{field_name} must be between 1 and 65535")
|
|
139
|
+
return value
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _optional_positive_int(
|
|
143
|
+
raw_config: Mapping[str, object],
|
|
144
|
+
key: str,
|
|
145
|
+
default: int,
|
|
146
|
+
field_name: str,
|
|
147
|
+
) -> int:
|
|
148
|
+
value = raw_config.get(key, default)
|
|
149
|
+
if not isinstance(value, int) or isinstance(value, bool):
|
|
150
|
+
raise CliConfigError(f"{field_name} must be an integer")
|
|
151
|
+
if value < 1:
|
|
152
|
+
raise CliConfigError(f"{field_name} must be greater than zero")
|
|
153
|
+
return value
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _toml_module() -> Any:
|
|
157
|
+
try:
|
|
158
|
+
return importlib.import_module("tomllib")
|
|
159
|
+
except ModuleNotFoundError: # pragma: no cover - exercised only on Python 3.10.
|
|
160
|
+
return importlib.import_module("tomli")
|
dutchmate_cli/devices.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Terminal formatting for serial device discovery."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
|
|
7
|
+
from dutchmate_core.device_connection.discovery import SerialPortCandidate
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class DeviceSelectionError(RuntimeError):
|
|
11
|
+
"""Raised when the CLI cannot choose one Debug Helper serial port."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def format_devices(candidates: Sequence[SerialPortCandidate]) -> str:
|
|
15
|
+
"""Format discovered serial ports for CLI output."""
|
|
16
|
+
|
|
17
|
+
if not candidates:
|
|
18
|
+
return "No serial ports found."
|
|
19
|
+
|
|
20
|
+
lines = ["Serial ports:"]
|
|
21
|
+
for candidate in candidates:
|
|
22
|
+
backend_kind = "enhanced_candidate" if candidate.is_dutchmate_hint else "generic"
|
|
23
|
+
metadata = _format_metadata(candidate)
|
|
24
|
+
lines.append(
|
|
25
|
+
f" {candidate.device} [{backend_kind}]: {candidate.description}{metadata}"
|
|
26
|
+
)
|
|
27
|
+
return "\n".join(lines)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def resolve_start_serial_port(
|
|
31
|
+
explicit_serial_port: str | None,
|
|
32
|
+
candidates: Sequence[SerialPortCandidate],
|
|
33
|
+
) -> str | None:
|
|
34
|
+
"""Resolve the serial port used by `dutchmate start`."""
|
|
35
|
+
|
|
36
|
+
if explicit_serial_port is not None:
|
|
37
|
+
return explicit_serial_port
|
|
38
|
+
if not candidates:
|
|
39
|
+
return None
|
|
40
|
+
if len(candidates) == 1:
|
|
41
|
+
return candidates[0].device
|
|
42
|
+
|
|
43
|
+
devices = ", ".join(candidate.device for candidate in candidates)
|
|
44
|
+
raise DeviceSelectionError(
|
|
45
|
+
f"Multiple DUTchMate serial devices found: {devices}. "
|
|
46
|
+
"Run 'dutchmate devices' and pass --serial-port."
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _format_metadata(candidate: SerialPortCandidate) -> str:
|
|
51
|
+
parts: list[str] = []
|
|
52
|
+
if candidate.vid is not None and candidate.pid is not None:
|
|
53
|
+
parts.append(f"vid:pid={candidate.vid:04X}:{candidate.pid:04X}")
|
|
54
|
+
if candidate.manufacturer:
|
|
55
|
+
parts.append(f"manufacturer={candidate.manufacturer}")
|
|
56
|
+
if candidate.product:
|
|
57
|
+
parts.append(f"product={candidate.product}")
|
|
58
|
+
if candidate.serial_number:
|
|
59
|
+
parts.append(f"serial={candidate.serial_number}")
|
|
60
|
+
|
|
61
|
+
if not parts:
|
|
62
|
+
return ""
|
|
63
|
+
return f" ({', '.join(parts)})"
|
dutchmate_cli/dut.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Terminal formatting for DUT action commands."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def format_reset_result(payload: Mapping[str, object]) -> str:
|
|
9
|
+
"""Format a successful DUT reset response."""
|
|
10
|
+
|
|
11
|
+
return (
|
|
12
|
+
"Reset command accepted "
|
|
13
|
+
f"(pulse_ms={_display(payload.get('pulse_ms'))}, "
|
|
14
|
+
f"performed_at={_display(payload.get('performed_at'))}, "
|
|
15
|
+
f"device_timestamp_us={_display(payload.get('device_timestamp_us'))})"
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def format_boot_mode_result(payload: Mapping[str, object]) -> str:
|
|
20
|
+
"""Format a successful DUT boot-mode response."""
|
|
21
|
+
|
|
22
|
+
return (
|
|
23
|
+
f"Boot mode set to {_display(payload.get('mode'))} "
|
|
24
|
+
f"(performed_at={_display(payload.get('performed_at'))}, "
|
|
25
|
+
f"device_timestamp_us={_display(payload.get('device_timestamp_us'))})"
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _display(value: object) -> str:
|
|
30
|
+
if value is None or value == "":
|
|
31
|
+
return "none"
|
|
32
|
+
return str(value)
|
dutchmate_cli/gpio.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Terminal formatting for GPIO control commands."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def format_gpio_mode_result(payload: Mapping[str, object]) -> str:
|
|
9
|
+
"""Format a successful GPIO mode configuration response."""
|
|
10
|
+
|
|
11
|
+
channel = _display(payload.get("channel"))
|
|
12
|
+
role = _display(payload.get("role"))
|
|
13
|
+
dut_signal = _display(payload.get("dut_signal"))
|
|
14
|
+
mode = _display(payload.get("mode"))
|
|
15
|
+
active_level = _display(payload.get("active_level"))
|
|
16
|
+
idle_level = payload.get("idle_level")
|
|
17
|
+
source = _display(payload.get("source"))
|
|
18
|
+
|
|
19
|
+
details = [
|
|
20
|
+
f"mode={mode}",
|
|
21
|
+
f"active={active_level}",
|
|
22
|
+
]
|
|
23
|
+
if idle_level is not None:
|
|
24
|
+
details.append(f"idle={_display(idle_level)}")
|
|
25
|
+
details.append(f"source={source}")
|
|
26
|
+
|
|
27
|
+
return f"Configured {channel}: {role} -> {dut_signal} ({', '.join(details)})"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _display(value: object) -> str:
|
|
31
|
+
if value is None or value == "":
|
|
32
|
+
return "none"
|
|
33
|
+
return str(value)
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
"""Local Device Core Service process lifecycle helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import signal
|
|
7
|
+
import subprocess
|
|
8
|
+
import time
|
|
9
|
+
from collections.abc import Callable, Sequence
|
|
10
|
+
from contextlib import suppress
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Final, Protocol
|
|
14
|
+
|
|
15
|
+
from dutchmate_cli.client import ServiceClientError, fetch_status
|
|
16
|
+
from dutchmate_cli.config import (
|
|
17
|
+
DEFAULT_CONFIG_PATH,
|
|
18
|
+
DEFAULT_DAEMON_HOST,
|
|
19
|
+
DEFAULT_DAEMON_PORT,
|
|
20
|
+
DEFAULT_SESSION_PATH,
|
|
21
|
+
)
|
|
22
|
+
from dutchmate_core.backends.settings import BackendSettings
|
|
23
|
+
from dutchmate_core.validation import DEFAULT_SESSION_MAX_SIZE_MB
|
|
24
|
+
|
|
25
|
+
DEFAULT_HOST: Final = DEFAULT_DAEMON_HOST
|
|
26
|
+
DEFAULT_PORT: Final = DEFAULT_DAEMON_PORT
|
|
27
|
+
DEFAULT_SESSION_ROOT: Final = DEFAULT_SESSION_PATH
|
|
28
|
+
DEFAULT_PID_FILE: Final = Path(".dutchmate/dutchmate-service.pid")
|
|
29
|
+
DEFAULT_LOG_FILE: Final = Path(".dutchmate/dutchmate-service.log")
|
|
30
|
+
DEFAULT_START_TIMEOUT_SECONDS: Final = 5.0
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class LifecycleError(RuntimeError):
|
|
34
|
+
"""Raised when the CLI cannot start or stop the local service process."""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class StartedProcess(Protocol):
|
|
38
|
+
pid: int
|
|
39
|
+
|
|
40
|
+
def poll(self) -> int | None:
|
|
41
|
+
"""Return the process exit code, or None while still running."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True, slots=True)
|
|
45
|
+
class ServiceStartResult:
|
|
46
|
+
"""Result of a Device Core Service start attempt."""
|
|
47
|
+
|
|
48
|
+
pid: int
|
|
49
|
+
url: str
|
|
50
|
+
pid_file: Path
|
|
51
|
+
log_file: Path
|
|
52
|
+
ready: bool
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True, slots=True)
|
|
56
|
+
class ServiceStopResult:
|
|
57
|
+
"""Result of a Device Core Service stop attempt."""
|
|
58
|
+
|
|
59
|
+
pid: int
|
|
60
|
+
pid_file: Path
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def start_service(
|
|
64
|
+
*,
|
|
65
|
+
backend_settings: BackendSettings,
|
|
66
|
+
host: str = DEFAULT_HOST,
|
|
67
|
+
port: int = DEFAULT_PORT,
|
|
68
|
+
config_path: Path = DEFAULT_CONFIG_PATH,
|
|
69
|
+
session_root: Path = DEFAULT_SESSION_ROOT,
|
|
70
|
+
session_max_size_mb: int = DEFAULT_SESSION_MAX_SIZE_MB,
|
|
71
|
+
session_max_count: int | None = None,
|
|
72
|
+
pid_file: Path = DEFAULT_PID_FILE,
|
|
73
|
+
log_file: Path = DEFAULT_LOG_FILE,
|
|
74
|
+
command: Sequence[str] | None = None,
|
|
75
|
+
wait_timeout_s: float = DEFAULT_START_TIMEOUT_SECONDS,
|
|
76
|
+
health_check: Callable[[str], bool] | None = None,
|
|
77
|
+
is_running: Callable[[int], bool] | None = None,
|
|
78
|
+
) -> ServiceStartResult:
|
|
79
|
+
"""Start the Device Core Service as a background process."""
|
|
80
|
+
|
|
81
|
+
service_url = f"http://{host}:{port}"
|
|
82
|
+
running_check = is_running or is_process_running
|
|
83
|
+
existing_pid = _read_pid_file(pid_file)
|
|
84
|
+
if existing_pid is not None and running_check(existing_pid):
|
|
85
|
+
raise LifecycleError(f"Device Core Service is already running (pid {existing_pid}).")
|
|
86
|
+
|
|
87
|
+
if (health_check or _service_responds)(service_url):
|
|
88
|
+
raise LifecycleError(f"Device Core Service is already running at {service_url}.")
|
|
89
|
+
|
|
90
|
+
pid_file.parent.mkdir(parents=True, exist_ok=True)
|
|
91
|
+
log_file.parent.mkdir(parents=True, exist_ok=True)
|
|
92
|
+
if command is None:
|
|
93
|
+
service_command = [
|
|
94
|
+
"dutchmate-service",
|
|
95
|
+
"--host",
|
|
96
|
+
host,
|
|
97
|
+
"--port",
|
|
98
|
+
str(port),
|
|
99
|
+
"--session-root",
|
|
100
|
+
str(session_root),
|
|
101
|
+
"--session-max-size-mb",
|
|
102
|
+
str(session_max_size_mb),
|
|
103
|
+
"--config",
|
|
104
|
+
str(config_path),
|
|
105
|
+
"--backend",
|
|
106
|
+
backend_settings.mode,
|
|
107
|
+
"--baudrate",
|
|
108
|
+
str(backend_settings.baudrate),
|
|
109
|
+
"--data-bits",
|
|
110
|
+
str(backend_settings.data_bits),
|
|
111
|
+
"--parity",
|
|
112
|
+
backend_settings.parity,
|
|
113
|
+
"--stop-bits",
|
|
114
|
+
str(backend_settings.stop_bits),
|
|
115
|
+
"--reconnect-timeout-s",
|
|
116
|
+
str(backend_settings.reconnect_timeout_s),
|
|
117
|
+
"--tx-enabled" if backend_settings.tx_enabled else "--no-tx-enabled",
|
|
118
|
+
]
|
|
119
|
+
if backend_settings.serial_port is not None:
|
|
120
|
+
service_command.extend(["--serial-port", backend_settings.serial_port])
|
|
121
|
+
if session_max_count is not None:
|
|
122
|
+
service_command.extend(["--session-max-count", str(session_max_count)])
|
|
123
|
+
else:
|
|
124
|
+
service_command = list(command)
|
|
125
|
+
|
|
126
|
+
with log_file.open("ab") as log:
|
|
127
|
+
process: StartedProcess = subprocess.Popen(
|
|
128
|
+
service_command,
|
|
129
|
+
stdout=log,
|
|
130
|
+
stderr=subprocess.STDOUT,
|
|
131
|
+
start_new_session=True,
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
pid_file.write_text(f"{process.pid}\n", encoding="utf-8")
|
|
135
|
+
ready = _wait_until_ready(
|
|
136
|
+
process=process,
|
|
137
|
+
service_url=service_url,
|
|
138
|
+
wait_timeout_s=wait_timeout_s,
|
|
139
|
+
health_check=health_check or _service_responds,
|
|
140
|
+
)
|
|
141
|
+
if process.poll() is not None and not ready:
|
|
142
|
+
_unlink_if_exists(pid_file)
|
|
143
|
+
raise LifecycleError(f"Device Core Service exited during startup. Check {log_file}.")
|
|
144
|
+
|
|
145
|
+
return ServiceStartResult(
|
|
146
|
+
pid=process.pid,
|
|
147
|
+
url=service_url,
|
|
148
|
+
pid_file=pid_file,
|
|
149
|
+
log_file=log_file,
|
|
150
|
+
ready=ready,
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def stop_service(
|
|
155
|
+
*,
|
|
156
|
+
pid_file: Path = DEFAULT_PID_FILE,
|
|
157
|
+
is_running: Callable[[int], bool] | None = None,
|
|
158
|
+
kill: Callable[[int, int], None] = os.kill,
|
|
159
|
+
) -> ServiceStopResult:
|
|
160
|
+
"""Stop the background Device Core Service process recorded in the PID file."""
|
|
161
|
+
|
|
162
|
+
running_check = is_running or is_process_running
|
|
163
|
+
pid = _read_pid_file(pid_file)
|
|
164
|
+
if pid is None:
|
|
165
|
+
raise LifecycleError("Device Core Service is not running.")
|
|
166
|
+
|
|
167
|
+
if not running_check(pid):
|
|
168
|
+
_unlink_if_exists(pid_file)
|
|
169
|
+
raise LifecycleError("Device Core Service is not running.")
|
|
170
|
+
|
|
171
|
+
kill(pid, signal.SIGTERM)
|
|
172
|
+
_unlink_if_exists(pid_file)
|
|
173
|
+
return ServiceStopResult(pid=pid, pid_file=pid_file)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def is_process_running(pid: int) -> bool:
|
|
177
|
+
"""Return whether a process ID currently exists."""
|
|
178
|
+
|
|
179
|
+
try:
|
|
180
|
+
os.kill(pid, 0)
|
|
181
|
+
except OSError:
|
|
182
|
+
return False
|
|
183
|
+
return True
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _service_responds(service_url: str) -> bool:
|
|
187
|
+
try:
|
|
188
|
+
fetch_status(service_url=service_url)
|
|
189
|
+
except ServiceClientError:
|
|
190
|
+
return False
|
|
191
|
+
return True
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _wait_until_ready(
|
|
195
|
+
*,
|
|
196
|
+
process: StartedProcess,
|
|
197
|
+
service_url: str,
|
|
198
|
+
wait_timeout_s: float,
|
|
199
|
+
health_check: Callable[[str], bool],
|
|
200
|
+
) -> bool:
|
|
201
|
+
deadline = time.monotonic() + wait_timeout_s
|
|
202
|
+
while time.monotonic() < deadline:
|
|
203
|
+
if health_check(service_url):
|
|
204
|
+
return True
|
|
205
|
+
if process.poll() is not None:
|
|
206
|
+
return False
|
|
207
|
+
time.sleep(0.1)
|
|
208
|
+
return health_check(service_url)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _read_pid_file(pid_file: Path) -> int | None:
|
|
212
|
+
try:
|
|
213
|
+
raw_pid = pid_file.read_text(encoding="utf-8").strip()
|
|
214
|
+
except FileNotFoundError:
|
|
215
|
+
return None
|
|
216
|
+
|
|
217
|
+
try:
|
|
218
|
+
return int(raw_pid)
|
|
219
|
+
except ValueError as exc:
|
|
220
|
+
raise LifecycleError(f"Invalid Device Core Service PID file: {pid_file}") from exc
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _unlink_if_exists(path: Path) -> None:
|
|
224
|
+
with suppress(FileNotFoundError):
|
|
225
|
+
path.unlink()
|
dutchmate_cli/logs.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""CLI formatting for bounded recent UART replay."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from typing import cast
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def format_recent_logs(payload: Mapping[str, object]) -> str:
|
|
10
|
+
"""Format replayed lines with CLI-only segment/channel separators."""
|
|
11
|
+
|
|
12
|
+
lines = [
|
|
13
|
+
f"Session: {_display(payload.get('session_id'))} "
|
|
14
|
+
f"({_display(payload.get('session_selection'))})"
|
|
15
|
+
]
|
|
16
|
+
records = _merged_records(payload)
|
|
17
|
+
current_stream: tuple[object, object] | None = None
|
|
18
|
+
for category, record in records:
|
|
19
|
+
stream = record.get("segment_id"), record.get("channel")
|
|
20
|
+
if stream != current_stream:
|
|
21
|
+
lines.append(
|
|
22
|
+
f"--- segment {_display(stream[0])}, channel {_display(stream[1])} ---"
|
|
23
|
+
)
|
|
24
|
+
current_stream = stream
|
|
25
|
+
if category == "oversized_lines":
|
|
26
|
+
lines.append(
|
|
27
|
+
"[line omitted: "
|
|
28
|
+
f"{_display(record.get('total_line_bytes'))} bytes exceeds processing limit; "
|
|
29
|
+
f"terminated={_display(record.get('terminated'))}]"
|
|
30
|
+
)
|
|
31
|
+
continue
|
|
32
|
+
text = _display_text(record.get("line_text"))
|
|
33
|
+
marker = " [partial]" if category == "partial_lines" else ""
|
|
34
|
+
lines.append(f"{text}{marker}")
|
|
35
|
+
|
|
36
|
+
if not records:
|
|
37
|
+
lines.append("No UART lines in the selected snapshot.")
|
|
38
|
+
lines.extend(_warnings(payload))
|
|
39
|
+
return "\n".join(lines)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _merged_records(
|
|
43
|
+
payload: Mapping[str, object],
|
|
44
|
+
) -> list[tuple[str, Mapping[str, object]]]:
|
|
45
|
+
records: list[tuple[str, Mapping[str, object]]] = []
|
|
46
|
+
for category in ("complete_lines", "partial_lines", "oversized_lines"):
|
|
47
|
+
value = payload.get(category)
|
|
48
|
+
if not isinstance(value, list):
|
|
49
|
+
continue
|
|
50
|
+
for raw_record in value:
|
|
51
|
+
if isinstance(raw_record, Mapping):
|
|
52
|
+
records.append((category, cast(Mapping[str, object], raw_record)))
|
|
53
|
+
records.sort(
|
|
54
|
+
key=lambda item: (
|
|
55
|
+
_sort_int(item[1].get("ingestion_index")),
|
|
56
|
+
_sort_int(item[1].get("line_index_in_event")),
|
|
57
|
+
)
|
|
58
|
+
)
|
|
59
|
+
return records
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _warnings(payload: Mapping[str, object]) -> list[str]:
|
|
63
|
+
warnings: list[str] = []
|
|
64
|
+
integrity = payload.get("integrity")
|
|
65
|
+
if isinstance(integrity, Mapping) and integrity.get("loss_status") != "none_reported":
|
|
66
|
+
warnings.append(
|
|
67
|
+
f"Warning: UART integrity is {_display(integrity.get('loss_status'))}."
|
|
68
|
+
)
|
|
69
|
+
if payload.get("truncated") is True:
|
|
70
|
+
warnings.append("Warning: session evidence was truncated.")
|
|
71
|
+
if payload.get("response_truncated") is True:
|
|
72
|
+
warnings.append(
|
|
73
|
+
"Warning: response omitted "
|
|
74
|
+
f"{_display(payload.get('omitted_complete_lines'))} complete, "
|
|
75
|
+
f"{_display(payload.get('omitted_partial_lines'))} partial, and "
|
|
76
|
+
f"{_display(payload.get('omitted_oversized_lines'))} oversized lines."
|
|
77
|
+
)
|
|
78
|
+
return warnings
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _sort_int(value: object) -> int:
|
|
82
|
+
return value if isinstance(value, int) and not isinstance(value, bool) else -1
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _display_text(value: object) -> str:
|
|
86
|
+
if not isinstance(value, str):
|
|
87
|
+
return "<invalid line>"
|
|
88
|
+
return value[:-1] if value.endswith("\n") else value
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _display(value: object) -> str:
|
|
92
|
+
return "none" if value is None or value == "" else str(value)
|