jetstan-agent 0.1.11__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.
- jetstan_agent/__init__.py +3 -0
- jetstan_agent/__main__.py +8 -0
- jetstan_agent/agent.py +40 -0
- jetstan_agent/cli.py +78 -0
- jetstan_agent/config.py +93 -0
- jetstan_agent/installer.py +311 -0
- jetstan_agent/logger.py +25 -0
- jetstan_agent/message_router.py +114 -0
- jetstan_agent/mqtt.py +141 -0
- jetstan_agent/sd_notify.py +37 -0
- jetstan_agent/service_cli.py +34 -0
- jetstan_agent/service_unit.py +45 -0
- jetstan_agent/system_checks.py +41 -0
- jetstan_agent/templates/__init__.py +1 -0
- jetstan_agent/templates/agent.env.example +5 -0
- jetstan_agent/templates/jetstan-agent.service.template +41 -0
- jetstan_agent/uninstaller.py +97 -0
- jetstan_agent/updater.py +106 -0
- jetstan_agent-0.1.11.dist-info/METADATA +199 -0
- jetstan_agent-0.1.11.dist-info/RECORD +34 -0
- jetstan_agent-0.1.11.dist-info/WHEEL +5 -0
- jetstan_agent-0.1.11.dist-info/entry_points.txt +4 -0
- jetstan_agent-0.1.11.dist-info/licenses/LICENSE +21 -0
- jetstan_agent-0.1.11.dist-info/top_level.txt +2 -0
- software/__init__.py +6 -0
- software/frontend/__init__.py +1 -0
- software/frontend/index.html +388 -0
- software/gen_sample/__init__.py +3 -0
- software/gen_sample/simulator.py +92 -0
- software/handlers.py +28 -0
- software/logic/__init__.py +7 -0
- software/logic/calculations.py +157 -0
- software/test/__init__.py +3 -0
- software/test/server.py +81 -0
jetstan_agent/agent.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Agent lifecycle: wires MQTT to message routing and keeps the process alive.
|
|
2
|
+
|
|
3
|
+
This is the composition point. Incoming payloads are handed to
|
|
4
|
+
``message_router`` for command dispatch; future OTA logic (downloads,
|
|
5
|
+
installs) is added there, not here or in ``mqtt.py``.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
|
|
12
|
+
from jetstan_agent.config import MQTTConfig
|
|
13
|
+
from jetstan_agent.message_router import route_message
|
|
14
|
+
from jetstan_agent.mqtt import MQTTClient
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class JetstanAgent:
|
|
20
|
+
"""Top-level OTA agent process."""
|
|
21
|
+
|
|
22
|
+
def __init__(self, config: MQTTConfig) -> None:
|
|
23
|
+
self._config = config
|
|
24
|
+
self._mqtt_client = MQTTClient(config=config, on_message=self._handle_message)
|
|
25
|
+
|
|
26
|
+
def run(self) -> None:
|
|
27
|
+
"""Start the agent and block until interrupted."""
|
|
28
|
+
logger.info("Jetstan Agent starting.")
|
|
29
|
+
try:
|
|
30
|
+
self._mqtt_client.run_forever()
|
|
31
|
+
except KeyboardInterrupt:
|
|
32
|
+
logger.info("Shutdown requested.")
|
|
33
|
+
finally:
|
|
34
|
+
self._mqtt_client.disconnect()
|
|
35
|
+
logger.info("Jetstan Agent stopped.")
|
|
36
|
+
|
|
37
|
+
def _handle_message(self, topic: str, payload: bytes) -> None:
|
|
38
|
+
"""Handle an incoming MQTT message by routing it to a command handler."""
|
|
39
|
+
logger.debug("Message received on '%s'.", topic)
|
|
40
|
+
route_message(payload)
|
jetstan_agent/cli.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""Command-line entrypoint for the ``jetstan-agent`` console script.
|
|
2
|
+
|
|
3
|
+
``run`` is the in-process foreground agent (what the systemd unit's
|
|
4
|
+
``ExecStart=`` invokes). ``status``/``start``/``stop``/``restart``/``logs``
|
|
5
|
+
are a separate concern: they operate on the *systemd service* from the
|
|
6
|
+
operator's side, delegating to ``service_cli``. Keeping these as distinct
|
|
7
|
+
subcommands avoids the ambiguity of "start" meaning two different things.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import logging
|
|
14
|
+
import sys
|
|
15
|
+
|
|
16
|
+
from jetstan_agent import service_cli
|
|
17
|
+
from jetstan_agent.agent import JetstanAgent
|
|
18
|
+
from jetstan_agent.config import ConfigError, MQTTConfig
|
|
19
|
+
from jetstan_agent.logger import configure_logging
|
|
20
|
+
|
|
21
|
+
logger = logging.getLogger(__name__)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
25
|
+
"""Build the CLI argument parser."""
|
|
26
|
+
parser = argparse.ArgumentParser(
|
|
27
|
+
prog="jetstan-agent",
|
|
28
|
+
description="Jetstan OTA agent for Linux-based vehicles.",
|
|
29
|
+
)
|
|
30
|
+
subparsers = parser.add_subparsers(dest="command")
|
|
31
|
+
subparsers.add_parser("run", help="Run the agent in the foreground (used by systemd).")
|
|
32
|
+
subparsers.add_parser("status", help="Show systemd service status.")
|
|
33
|
+
subparsers.add_parser("start", help="Start the systemd service.")
|
|
34
|
+
subparsers.add_parser("stop", help="Stop the systemd service.")
|
|
35
|
+
subparsers.add_parser("restart", help="Restart the systemd service.")
|
|
36
|
+
logs_parser = subparsers.add_parser("logs", help="Show/follow service logs via journalctl.")
|
|
37
|
+
logs_parser.add_argument("-n", "--lines", type=int, default=100)
|
|
38
|
+
logs_parser.add_argument(
|
|
39
|
+
"--no-follow", action="store_true", help="Print recent logs and exit."
|
|
40
|
+
)
|
|
41
|
+
parser.set_defaults(command="run")
|
|
42
|
+
return parser
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def main(argv: list[str] | None = None) -> int:
|
|
46
|
+
"""CLI entrypoint. Returns a process exit code."""
|
|
47
|
+
args = build_parser().parse_args(argv)
|
|
48
|
+
|
|
49
|
+
if args.command == "run":
|
|
50
|
+
configure_logging()
|
|
51
|
+
return _run()
|
|
52
|
+
if args.command == "status":
|
|
53
|
+
return service_cli.status()
|
|
54
|
+
if args.command == "start":
|
|
55
|
+
return service_cli.start()
|
|
56
|
+
if args.command == "stop":
|
|
57
|
+
return service_cli.stop()
|
|
58
|
+
if args.command == "restart":
|
|
59
|
+
return service_cli.restart()
|
|
60
|
+
if args.command == "logs":
|
|
61
|
+
return service_cli.logs(lines=args.lines, follow=not args.no_follow)
|
|
62
|
+
|
|
63
|
+
return 1
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _run() -> int:
|
|
67
|
+
try:
|
|
68
|
+
config = MQTTConfig.from_env()
|
|
69
|
+
except ConfigError as exc:
|
|
70
|
+
logger.error("Configuration error: %s", exc)
|
|
71
|
+
return 1
|
|
72
|
+
|
|
73
|
+
JetstanAgent(config=config).run()
|
|
74
|
+
return 0
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
if __name__ == "__main__":
|
|
78
|
+
sys.exit(main())
|
jetstan_agent/config.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Runtime configuration for the Jetstan Agent.
|
|
2
|
+
|
|
3
|
+
All tunable values live here so no other module contains a hardcoded
|
|
4
|
+
constant. Non-secret values (host, port, topic, keepalive) have sane
|
|
5
|
+
defaults for HiveMQ Cloud. Secrets (username, password) have no default
|
|
6
|
+
and must be supplied via environment variables — they must never be
|
|
7
|
+
committed to source control.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
|
|
15
|
+
from dotenv import load_dotenv
|
|
16
|
+
|
|
17
|
+
# Loads variables from a local .env file (if present) into the process
|
|
18
|
+
# environment for local development. Never overrides variables that are
|
|
19
|
+
# already set, so real deployments (systemd, CI) are unaffected. A no-op
|
|
20
|
+
# when no .env file exists, so this is always safe to call.
|
|
21
|
+
load_dotenv()
|
|
22
|
+
|
|
23
|
+
DEFAULT_PORT = 8883 # HiveMQ Cloud TLS port
|
|
24
|
+
DEFAULT_KEEPALIVE_SECONDS = 60
|
|
25
|
+
DEFAULT_TOPIC_UPDATE = "jetstan/demo/update"
|
|
26
|
+
DEFAULT_LOG_LEVEL = "INFO"
|
|
27
|
+
DEFAULT_CLIENT_ID = "jetstan-agent"
|
|
28
|
+
|
|
29
|
+
_ENV_HOST = "MQTT_HOST"
|
|
30
|
+
_ENV_PORT = "MQTT_PORT"
|
|
31
|
+
_ENV_USERNAME = "MQTT_USERNAME"
|
|
32
|
+
_ENV_PASSWORD = "MQTT_PASSWORD"
|
|
33
|
+
_ENV_CLIENT_ID = "JETSTAN_MQTT_CLIENT_ID"
|
|
34
|
+
_ENV_TOPIC_UPDATE = "MQTT_TOPIC"
|
|
35
|
+
_ENV_LOG_LEVEL = "JETSTAN_LOG_LEVEL"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class ConfigError(RuntimeError):
|
|
39
|
+
"""Raised when required configuration is missing or invalid."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class MQTTConfig:
|
|
44
|
+
"""Connection settings for the HiveMQ Cloud MQTT broker."""
|
|
45
|
+
|
|
46
|
+
host: str
|
|
47
|
+
port: int
|
|
48
|
+
username: str
|
|
49
|
+
password: str
|
|
50
|
+
client_id: str
|
|
51
|
+
keepalive_seconds: int
|
|
52
|
+
topic_update: str
|
|
53
|
+
|
|
54
|
+
@classmethod
|
|
55
|
+
def from_env(cls) -> "MQTTConfig":
|
|
56
|
+
"""Build configuration from environment variables.
|
|
57
|
+
|
|
58
|
+
Credentials are read from the environment (never hardcoded) so
|
|
59
|
+
the same code runs unmodified across a developer's Raspberry Pi,
|
|
60
|
+
CI, and future automotive targets — only the environment changes.
|
|
61
|
+
"""
|
|
62
|
+
host = os.environ.get(_ENV_HOST)
|
|
63
|
+
username = os.environ.get(_ENV_USERNAME)
|
|
64
|
+
password = os.environ.get(_ENV_PASSWORD)
|
|
65
|
+
|
|
66
|
+
missing = [
|
|
67
|
+
name
|
|
68
|
+
for name, value in (
|
|
69
|
+
(_ENV_HOST, host),
|
|
70
|
+
(_ENV_USERNAME, username),
|
|
71
|
+
(_ENV_PASSWORD, password),
|
|
72
|
+
)
|
|
73
|
+
if not value
|
|
74
|
+
]
|
|
75
|
+
if missing:
|
|
76
|
+
raise ConfigError(
|
|
77
|
+
f"Missing required environment variable(s): {', '.join(missing)}"
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
return cls(
|
|
81
|
+
host=host,
|
|
82
|
+
port=int(os.environ.get(_ENV_PORT, DEFAULT_PORT)),
|
|
83
|
+
username=username,
|
|
84
|
+
password=password,
|
|
85
|
+
client_id=os.environ.get(_ENV_CLIENT_ID, DEFAULT_CLIENT_ID),
|
|
86
|
+
keepalive_seconds=DEFAULT_KEEPALIVE_SECONDS,
|
|
87
|
+
topic_update=os.environ.get(_ENV_TOPIC_UPDATE, DEFAULT_TOPIC_UPDATE),
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def get_log_level() -> str:
|
|
92
|
+
"""Return the configured log level name (e.g. ``"INFO"``, ``"DEBUG"``)."""
|
|
93
|
+
return os.environ.get(_ENV_LOG_LEVEL, DEFAULT_LOG_LEVEL).upper()
|
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
"""Installer entry point: turns `pip install jetstan-agent` into a managed
|
|
2
|
+
systemd service.
|
|
3
|
+
|
|
4
|
+
Every step checks existing state before acting, so running the installer
|
|
5
|
+
twice is always safe. If a later step fails, everything this run actually
|
|
6
|
+
created is unwound in reverse order (LIFO) via the rollback stack.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import logging
|
|
12
|
+
import os
|
|
13
|
+
import shutil
|
|
14
|
+
import subprocess
|
|
15
|
+
import sys
|
|
16
|
+
import time
|
|
17
|
+
from importlib.resources import files
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Callable
|
|
20
|
+
|
|
21
|
+
from jetstan_agent import system_checks
|
|
22
|
+
from jetstan_agent.logger import configure_logging
|
|
23
|
+
from jetstan_agent.service_unit import ServiceUnitConfig, render_unit_file
|
|
24
|
+
from jetstan_agent.updater import current_version
|
|
25
|
+
|
|
26
|
+
try:
|
|
27
|
+
import grp
|
|
28
|
+
import pwd
|
|
29
|
+
except ImportError: # pragma: no cover - grp/pwd are POSIX-only
|
|
30
|
+
grp = None # type: ignore[assignment]
|
|
31
|
+
pwd = None # type: ignore[assignment]
|
|
32
|
+
|
|
33
|
+
logger = logging.getLogger(__name__)
|
|
34
|
+
|
|
35
|
+
SERVICE_NAME = "jetstan-agent"
|
|
36
|
+
SERVICE_USER = "jetstan"
|
|
37
|
+
SERVICE_GROUP = "jetstan"
|
|
38
|
+
OPT_DIR = Path("/opt/jetstan")
|
|
39
|
+
VENV_DIR = OPT_DIR / "venv"
|
|
40
|
+
ETC_DIR = Path("/etc/jetstan")
|
|
41
|
+
ENV_FILE = ETC_DIR / "agent.env"
|
|
42
|
+
UNIT_PATH = Path("/etc/systemd/system/jetstan-agent.service")
|
|
43
|
+
|
|
44
|
+
START_VERIFY_TIMEOUT_SECONDS = 15
|
|
45
|
+
START_VERIFY_POLL_SECONDS = 1
|
|
46
|
+
_SUBPROCESS_TIMEOUT_SECONDS = 180
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class InstallError(RuntimeError):
|
|
50
|
+
"""Raised when an install step fails; triggers rollback."""
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class _RollbackStack:
|
|
54
|
+
"""Runs undo callables in reverse order if the install fails partway."""
|
|
55
|
+
|
|
56
|
+
def __init__(self) -> None:
|
|
57
|
+
self._actions: list[tuple[str, Callable[[], None]]] = []
|
|
58
|
+
|
|
59
|
+
def push(self, description: str, undo: Callable[[], None]) -> None:
|
|
60
|
+
self._actions.append((description, undo))
|
|
61
|
+
|
|
62
|
+
def unwind(self) -> None:
|
|
63
|
+
for description, undo in reversed(self._actions):
|
|
64
|
+
try:
|
|
65
|
+
logger.warning("Rolling back: %s", description)
|
|
66
|
+
undo()
|
|
67
|
+
except Exception: # noqa: BLE001 - best-effort cleanup
|
|
68
|
+
logger.exception("Rollback step failed: %s", description)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def main() -> int:
|
|
72
|
+
configure_logging()
|
|
73
|
+
rollback = _RollbackStack()
|
|
74
|
+
env_file_existed = ENV_FILE.exists()
|
|
75
|
+
|
|
76
|
+
try:
|
|
77
|
+
_check_prerequisites()
|
|
78
|
+
_print_diagnostics()
|
|
79
|
+
_ensure_service_account(rollback)
|
|
80
|
+
_ensure_venv(rollback)
|
|
81
|
+
_install_package_into_venv()
|
|
82
|
+
_ensure_config_dir(rollback)
|
|
83
|
+
_ensure_env_file(rollback)
|
|
84
|
+
_write_unit_file(rollback)
|
|
85
|
+
_daemon_reload()
|
|
86
|
+
_enable_service()
|
|
87
|
+
_start_service()
|
|
88
|
+
|
|
89
|
+
if env_file_existed:
|
|
90
|
+
_verify_running()
|
|
91
|
+
else:
|
|
92
|
+
logger.warning(
|
|
93
|
+
"Skipping startup verification: %s was just created with blank "
|
|
94
|
+
"credentials, so the service is expected to exit until you fill "
|
|
95
|
+
"it in and restart.",
|
|
96
|
+
ENV_FILE,
|
|
97
|
+
)
|
|
98
|
+
except InstallError as exc:
|
|
99
|
+
logger.error("Install failed: %s", exc)
|
|
100
|
+
rollback.unwind()
|
|
101
|
+
return 1
|
|
102
|
+
|
|
103
|
+
_print_next_steps()
|
|
104
|
+
return 0
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _check_prerequisites() -> None:
|
|
108
|
+
if not system_checks.is_root():
|
|
109
|
+
raise InstallError("must be run as root (try: sudo jetstan-agent-install)")
|
|
110
|
+
if not system_checks.has_systemd():
|
|
111
|
+
raise InstallError("systemd not detected on this system")
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _print_diagnostics() -> None:
|
|
115
|
+
logger.info("OS: %s", system_checks.os_release_pretty_name())
|
|
116
|
+
logger.info("Architecture: %s", system_checks.architecture())
|
|
117
|
+
logger.info("Python: %s", sys.executable)
|
|
118
|
+
logger.info("jetstan-agent version: %s", current_version())
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _user_exists(name: str) -> bool:
|
|
122
|
+
try:
|
|
123
|
+
pwd.getpwnam(name)
|
|
124
|
+
return True
|
|
125
|
+
except KeyError:
|
|
126
|
+
return False
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _group_exists(name: str) -> bool:
|
|
130
|
+
try:
|
|
131
|
+
grp.getgrnam(name)
|
|
132
|
+
return True
|
|
133
|
+
except KeyError:
|
|
134
|
+
return False
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _nologin_shell() -> str:
|
|
138
|
+
return shutil.which("nologin") or "/usr/sbin/nologin"
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _ensure_service_account(rollback: _RollbackStack) -> None:
|
|
142
|
+
if _user_exists(SERVICE_USER):
|
|
143
|
+
logger.info("System user '%s' already exists.", SERVICE_USER)
|
|
144
|
+
return
|
|
145
|
+
|
|
146
|
+
created_group = not _group_exists(SERVICE_GROUP)
|
|
147
|
+
if created_group:
|
|
148
|
+
_run(["groupadd", "--system", SERVICE_GROUP], "create group")
|
|
149
|
+
|
|
150
|
+
_run(
|
|
151
|
+
[
|
|
152
|
+
"useradd",
|
|
153
|
+
"--system",
|
|
154
|
+
"--gid",
|
|
155
|
+
SERVICE_GROUP,
|
|
156
|
+
"--no-create-home",
|
|
157
|
+
"--shell",
|
|
158
|
+
_nologin_shell(),
|
|
159
|
+
SERVICE_USER,
|
|
160
|
+
],
|
|
161
|
+
"create user",
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
def _undo() -> None:
|
|
165
|
+
_run(["userdel", SERVICE_USER], "remove user", check=False)
|
|
166
|
+
if created_group:
|
|
167
|
+
_run(["groupdel", SERVICE_GROUP], "remove group", check=False)
|
|
168
|
+
|
|
169
|
+
rollback.push(f"remove system account '{SERVICE_USER}'", _undo)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _venv_python() -> Path:
|
|
173
|
+
return VENV_DIR / "bin" / "python"
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _ensure_venv(rollback: _RollbackStack) -> None:
|
|
177
|
+
if VENV_DIR.exists():
|
|
178
|
+
logger.info("Venv already exists at %s.", VENV_DIR)
|
|
179
|
+
return
|
|
180
|
+
|
|
181
|
+
OPT_DIR.mkdir(parents=True, exist_ok=True)
|
|
182
|
+
_run([sys.executable, "-m", "venv", str(VENV_DIR)], "create venv")
|
|
183
|
+
_run(["chown", "-R", f"{SERVICE_USER}:{SERVICE_GROUP}", str(VENV_DIR)], "chown venv")
|
|
184
|
+
rollback.push(
|
|
185
|
+
f"remove venv at {VENV_DIR}",
|
|
186
|
+
lambda: shutil.rmtree(VENV_DIR, ignore_errors=True),
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _install_package_into_venv() -> None:
|
|
191
|
+
target_version = current_version()
|
|
192
|
+
spec = f"jetstan-agent=={target_version}" if target_version else "jetstan-agent"
|
|
193
|
+
_run(
|
|
194
|
+
[str(_venv_python()), "-m", "pip", "install", "--no-input", "--upgrade", spec],
|
|
195
|
+
f"install {spec} into venv",
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _ensure_config_dir(rollback: _RollbackStack) -> None:
|
|
200
|
+
if ETC_DIR.exists():
|
|
201
|
+
return
|
|
202
|
+
|
|
203
|
+
ETC_DIR.mkdir(parents=True)
|
|
204
|
+
os.chmod(ETC_DIR, 0o750)
|
|
205
|
+
shutil.chown(ETC_DIR, user="root", group=SERVICE_GROUP)
|
|
206
|
+
rollback.push(f"remove {ETC_DIR}", lambda: shutil.rmtree(ETC_DIR, ignore_errors=True))
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _ensure_env_file(rollback: _RollbackStack) -> None:
|
|
210
|
+
if ENV_FILE.exists():
|
|
211
|
+
logger.info("Config already exists at %s (not overwritten).", ENV_FILE)
|
|
212
|
+
return
|
|
213
|
+
|
|
214
|
+
template = files("jetstan_agent.templates").joinpath("agent.env.example").read_text()
|
|
215
|
+
_atomic_write(ENV_FILE, template)
|
|
216
|
+
os.chmod(ENV_FILE, 0o600)
|
|
217
|
+
shutil.chown(ENV_FILE, user=SERVICE_USER, group=SERVICE_GROUP)
|
|
218
|
+
rollback.push(f"remove {ENV_FILE}", lambda: ENV_FILE.unlink(missing_ok=True))
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _write_unit_file(rollback: _RollbackStack) -> None:
|
|
222
|
+
config = ServiceUnitConfig(
|
|
223
|
+
exec_start=f"{_venv_python()} -m jetstan_agent run",
|
|
224
|
+
user=SERVICE_USER,
|
|
225
|
+
group=SERVICE_GROUP,
|
|
226
|
+
environment_file=str(ENV_FILE),
|
|
227
|
+
venv_dir=str(VENV_DIR),
|
|
228
|
+
)
|
|
229
|
+
unit_existed = UNIT_PATH.exists()
|
|
230
|
+
_atomic_write(UNIT_PATH, render_unit_file(config))
|
|
231
|
+
|
|
232
|
+
if not unit_existed:
|
|
233
|
+
rollback.push(f"remove {UNIT_PATH}", lambda: UNIT_PATH.unlink(missing_ok=True))
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _atomic_write(path: Path, content: str) -> None:
|
|
237
|
+
tmp_path = path.with_suffix(path.suffix + ".tmp")
|
|
238
|
+
tmp_path.write_text(content)
|
|
239
|
+
os.replace(tmp_path, path)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _daemon_reload() -> None:
|
|
243
|
+
_run(["systemctl", "daemon-reload"], "reload systemd")
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _enable_service() -> None:
|
|
247
|
+
_run(["systemctl", "enable", SERVICE_NAME], "enable service")
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _start_service() -> None:
|
|
251
|
+
_run(["systemctl", "restart", SERVICE_NAME], "start service")
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _verify_running() -> None:
|
|
255
|
+
deadline = time.monotonic() + START_VERIFY_TIMEOUT_SECONDS
|
|
256
|
+
while time.monotonic() < deadline:
|
|
257
|
+
result = subprocess.run(
|
|
258
|
+
["systemctl", "is-active", SERVICE_NAME],
|
|
259
|
+
capture_output=True,
|
|
260
|
+
text=True,
|
|
261
|
+
check=False,
|
|
262
|
+
timeout=10,
|
|
263
|
+
)
|
|
264
|
+
if result.stdout.strip() == "active":
|
|
265
|
+
logger.info("Service is active and running.")
|
|
266
|
+
return
|
|
267
|
+
time.sleep(START_VERIFY_POLL_SECONDS)
|
|
268
|
+
|
|
269
|
+
journal = subprocess.run(
|
|
270
|
+
["journalctl", "-u", SERVICE_NAME, "-n", "50", "--no-pager"],
|
|
271
|
+
capture_output=True,
|
|
272
|
+
text=True,
|
|
273
|
+
check=False,
|
|
274
|
+
timeout=10,
|
|
275
|
+
)
|
|
276
|
+
logger.error(
|
|
277
|
+
"Service did not become active within %ds.\n%s",
|
|
278
|
+
START_VERIFY_TIMEOUT_SECONDS,
|
|
279
|
+
journal.stdout,
|
|
280
|
+
)
|
|
281
|
+
raise InstallError("service failed to start; see journal output above")
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _run(
|
|
285
|
+
command: list[str], description: str, check: bool = True
|
|
286
|
+
) -> subprocess.CompletedProcess:
|
|
287
|
+
logger.debug("Running: %s", " ".join(command))
|
|
288
|
+
try:
|
|
289
|
+
result = subprocess.run(
|
|
290
|
+
command, capture_output=True, text=True, timeout=_SUBPROCESS_TIMEOUT_SECONDS
|
|
291
|
+
)
|
|
292
|
+
except subprocess.TimeoutExpired as exc:
|
|
293
|
+
raise InstallError(f"timed out trying to {description}") from exc
|
|
294
|
+
|
|
295
|
+
if check and result.returncode != 0:
|
|
296
|
+
raise InstallError(f"failed to {description}: {result.stderr.strip()}")
|
|
297
|
+
return result
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _print_next_steps() -> None:
|
|
301
|
+
logger.info("=" * 60)
|
|
302
|
+
logger.info("jetstan-agent installed.")
|
|
303
|
+
logger.info("Next steps:")
|
|
304
|
+
logger.info(" 1. Edit %s with your HiveMQ credentials.", ENV_FILE)
|
|
305
|
+
logger.info(" 2. Run: sudo systemctl restart %s", SERVICE_NAME)
|
|
306
|
+
logger.info(" 3. Check: jetstan-agent status / jetstan-agent logs")
|
|
307
|
+
logger.info("=" * 60)
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
if __name__ == "__main__":
|
|
311
|
+
sys.exit(main())
|
jetstan_agent/logger.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Logging configuration for the Jetstan Agent.
|
|
2
|
+
|
|
3
|
+
Centralizing setup here means every module can simply call
|
|
4
|
+
``logging.getLogger(__name__)`` and inherit consistent formatting,
|
|
5
|
+
without any module configuring handlers itself.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
|
|
12
|
+
from jetstan_agent.config import get_log_level
|
|
13
|
+
|
|
14
|
+
_LOG_FORMAT = "%(asctime)s | %(levelname)-8s | %(name)s | %(message)s"
|
|
15
|
+
_DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def configure_logging() -> None:
|
|
19
|
+
"""Configure the root logger. Must be called once, at process startup."""
|
|
20
|
+
level_name = get_log_level()
|
|
21
|
+
level = logging.getLevelName(level_name)
|
|
22
|
+
if not isinstance(level, int):
|
|
23
|
+
level = logging.INFO
|
|
24
|
+
|
|
25
|
+
logging.basicConfig(level=level, format=_LOG_FORMAT, datefmt=_DATE_FORMAT)
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""Routes parsed MQTT command payloads to the appropriate handler.
|
|
2
|
+
|
|
3
|
+
Keeps command semantics entirely out of ``mqtt.py``: that module only
|
|
4
|
+
ever deals with raw ``(topic, payload)`` bytes. ``agent.py`` hands the
|
|
5
|
+
raw payload to :func:`route_message` once received. Adding a new
|
|
6
|
+
command later means adding one handler function and one entry in
|
|
7
|
+
``_HANDLERS`` — nothing else in the agent needs to change.
|
|
8
|
+
|
|
9
|
+
Application-specific commands live in the top-level ``software/``
|
|
10
|
+
package, not here — this file stays fixed OTA plumbing. If ``software``
|
|
11
|
+
defines a ``CUSTOM_HANDLERS`` dict, it's merged in automatically; if
|
|
12
|
+
``software`` doesn't exist yet (or has nothing to add), that's a no-op,
|
|
13
|
+
so this module works standalone either way.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import json
|
|
19
|
+
import logging
|
|
20
|
+
import threading
|
|
21
|
+
from typing import Any, Callable
|
|
22
|
+
|
|
23
|
+
from jetstan_agent import updater
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger(__name__)
|
|
26
|
+
|
|
27
|
+
CommandHandler = Callable[[dict[str, Any]], None]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def route_message(payload: bytes) -> None:
|
|
31
|
+
"""Parse a JSON MQTT payload and dispatch it based on its "type" field.
|
|
32
|
+
|
|
33
|
+
Never raises: invalid JSON, a non-object payload, or an unrecognized
|
|
34
|
+
command type is logged and swallowed, so a single bad message can
|
|
35
|
+
never crash the agent.
|
|
36
|
+
"""
|
|
37
|
+
command = _parse_payload(payload)
|
|
38
|
+
if command is None:
|
|
39
|
+
return
|
|
40
|
+
|
|
41
|
+
command_type = command.get("type")
|
|
42
|
+
handler = _HANDLERS.get(command_type)
|
|
43
|
+
if handler is None:
|
|
44
|
+
logger.warning("Unknown command type: %r", command_type)
|
|
45
|
+
return
|
|
46
|
+
|
|
47
|
+
handler(command)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _parse_payload(payload: bytes) -> dict[str, Any] | None:
|
|
51
|
+
"""Decode ``payload`` as a JSON object, or return None if it isn't one."""
|
|
52
|
+
try:
|
|
53
|
+
data = json.loads(payload)
|
|
54
|
+
except json.JSONDecodeError:
|
|
55
|
+
logger.warning("Received invalid JSON payload: %r", payload)
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
if not isinstance(data, dict):
|
|
59
|
+
logger.warning("Expected a JSON object, got: %r", data)
|
|
60
|
+
return None
|
|
61
|
+
|
|
62
|
+
return data
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _handle_hello(command: dict[str, Any]) -> None:
|
|
66
|
+
logger.info("Hello command received.")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _handle_restart(command: dict[str, Any]) -> None:
|
|
70
|
+
logger.info("Restart command received.")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _handle_heartbeat(command: dict[str, Any]) -> None:
|
|
74
|
+
logger.info("Heartbeat requested.")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _handle_ota_available(command: dict[str, Any]) -> None:
|
|
78
|
+
logger.info("OTA update available")
|
|
79
|
+
version = command.get("version")
|
|
80
|
+
logger.info("Version: %s", version)
|
|
81
|
+
|
|
82
|
+
# apply_update() retries for minutes if the index hasn't propagated yet;
|
|
83
|
+
# running it on its own thread keeps the MQTT network loop (and its
|
|
84
|
+
# keepalive) unaffected while that plays out.
|
|
85
|
+
threading.Thread(target=_apply_update_and_restart, args=(version,), daemon=True).start()
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _apply_update_and_restart(version: str | None) -> None:
|
|
89
|
+
if updater.apply_update(version):
|
|
90
|
+
updater.trigger_restart()
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _load_custom_handlers() -> dict[str, CommandHandler]:
|
|
94
|
+
"""Load application-specific handlers from the top-level ``software`` package.
|
|
95
|
+
|
|
96
|
+
Returns an empty dict if ``software`` doesn't exist or doesn't define
|
|
97
|
+
``CUSTOM_HANDLERS`` — the OTA plumbing must keep working even before
|
|
98
|
+
any application code has been written.
|
|
99
|
+
"""
|
|
100
|
+
try:
|
|
101
|
+
from software.handlers import CUSTOM_HANDLERS
|
|
102
|
+
except ImportError:
|
|
103
|
+
return {}
|
|
104
|
+
|
|
105
|
+
return CUSTOM_HANDLERS
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
_HANDLERS: dict[str, CommandHandler] = {
|
|
109
|
+
"hello": _handle_hello,
|
|
110
|
+
"restart": _handle_restart,
|
|
111
|
+
"heartbeat": _handle_heartbeat,
|
|
112
|
+
"ota.available": _handle_ota_available,
|
|
113
|
+
**_load_custom_handlers(),
|
|
114
|
+
}
|