breezed 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.
- breezed/__init__.py +3 -0
- breezed/cli.py +471 -0
- breezed/config.py +172 -0
- breezed/controller.py +182 -0
- breezed/curve.py +58 -0
- breezed/daemon.py +429 -0
- breezed/ipmi.py +134 -0
- breezed/logs.py +81 -0
- breezed/metrics.py +108 -0
- breezed/policy.py +18 -0
- breezed/ports.py +35 -0
- breezed/templates/breezed.service.template +33 -0
- breezed/templates/breezed.toml.example +22 -0
- breezed/types.py +64 -0
- breezed/watcher.py +47 -0
- breezed-0.1.0.dist-info/METADATA +159 -0
- breezed-0.1.0.dist-info/RECORD +20 -0
- breezed-0.1.0.dist-info/WHEEL +4 -0
- breezed-0.1.0.dist-info/entry_points.txt +2 -0
- breezed-0.1.0.dist-info/licenses/LICENSE +21 -0
breezed/__init__.py
ADDED
breezed/cli.py
ADDED
|
@@ -0,0 +1,471 @@
|
|
|
1
|
+
"""Typer CLI: run/set/auto/status/validate plus the exit-code contract.
|
|
2
|
+
|
|
3
|
+
0 ok, 1 runtime error (IpmiError), 2 usage/config error (ConfigError,
|
|
4
|
+
out-of-range PCT). Errors go to stderr prefixed "breezed:"; stdout stays
|
|
5
|
+
reserved for JSON/machine output. Kept free of module-level side effects beyond
|
|
6
|
+
``app`` and ``deps`` so daemon_app can mount via ``app.add_typer(...)``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import getpass
|
|
10
|
+
import json
|
|
11
|
+
import logging
|
|
12
|
+
import os
|
|
13
|
+
import shutil
|
|
14
|
+
import signal
|
|
15
|
+
import subprocess
|
|
16
|
+
import sys
|
|
17
|
+
import tempfile
|
|
18
|
+
import threading
|
|
19
|
+
from collections.abc import Callable
|
|
20
|
+
from dataclasses import asdict, dataclass
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from traceback import format_exc
|
|
23
|
+
from typing import Annotated, NoReturn
|
|
24
|
+
|
|
25
|
+
import rich.console
|
|
26
|
+
import typer
|
|
27
|
+
|
|
28
|
+
from breezed import __version__
|
|
29
|
+
from breezed.config import ConfigError, Settings, load_settings
|
|
30
|
+
from breezed.controller import Controller, EventSink
|
|
31
|
+
from breezed.curve import interpolate
|
|
32
|
+
from breezed.daemon import (
|
|
33
|
+
DaemonError,
|
|
34
|
+
Step,
|
|
35
|
+
StepOutcome,
|
|
36
|
+
apply,
|
|
37
|
+
build_remove_steps,
|
|
38
|
+
build_steps,
|
|
39
|
+
daemon_status,
|
|
40
|
+
remove,
|
|
41
|
+
stage_files,
|
|
42
|
+
)
|
|
43
|
+
from breezed.ipmi import IpmiClient, IpmiError
|
|
44
|
+
from breezed.logs import LoggingEventSink, setup_logging
|
|
45
|
+
from breezed.metrics import MetricsState, start_metrics_server
|
|
46
|
+
from breezed.types import EventType, FanPercent, OperatingMode, TempC, make_fan_pct
|
|
47
|
+
from breezed.watcher import ConfigWatcher
|
|
48
|
+
|
|
49
|
+
app = typer.Typer(add_completion=False, pretty_exceptions_enable=False)
|
|
50
|
+
|
|
51
|
+
ClientFactory = Callable[[Settings], IpmiClient]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True)
|
|
55
|
+
class AppDeps:
|
|
56
|
+
build_client: ClientFactory
|
|
57
|
+
sleep_interruptible: Callable[[threading.Event, float], bool]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
deps = AppDeps(build_client=IpmiClient, sleep_interruptible=threading.Event.wait)
|
|
61
|
+
|
|
62
|
+
__all__ = ["app", "deps"]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _print_version(value: bool) -> None:
|
|
66
|
+
if value:
|
|
67
|
+
print(f"breezed {__version__}")
|
|
68
|
+
raise typer.Exit()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@app.callback()
|
|
72
|
+
def _root_callback(
|
|
73
|
+
version: Annotated[
|
|
74
|
+
bool,
|
|
75
|
+
typer.Option("--version", callback=_print_version, is_eager=True, help="Show version."),
|
|
76
|
+
] = False,
|
|
77
|
+
) -> None:
|
|
78
|
+
"""Curve-based fan controller for Dell PowerEdge servers via iDRAC/IPMI."""
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _fail(err: Exception, *, code: int) -> NoReturn:
|
|
82
|
+
typer.secho(f"breezed: {err}", fg=typer.colors.RED, err=True)
|
|
83
|
+
raise typer.Exit(code=code) from err
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _load_settings_or_fail(config: Path) -> Settings:
|
|
87
|
+
try:
|
|
88
|
+
return load_settings(config)
|
|
89
|
+
except ConfigError as err:
|
|
90
|
+
_fail(err, code=2)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _connect(config: Path) -> tuple[Settings, IpmiClient]:
|
|
94
|
+
try:
|
|
95
|
+
settings = _load_settings_or_fail(config)
|
|
96
|
+
return settings, deps.build_client(settings)
|
|
97
|
+
except IpmiError as err:
|
|
98
|
+
_fail(err, code=1)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class _MetricsSink:
|
|
102
|
+
"""Thin EventSink wrapper: forwards to LoggingEventSink, mirrors counters."""
|
|
103
|
+
|
|
104
|
+
def __init__(self, base: EventSink, state: MetricsState | None) -> None:
|
|
105
|
+
self._base = base
|
|
106
|
+
self._state = state
|
|
107
|
+
|
|
108
|
+
def emit(self, event: EventType, /, **fields: object) -> None:
|
|
109
|
+
self._base.emit(event, **fields)
|
|
110
|
+
if self._state is None:
|
|
111
|
+
return
|
|
112
|
+
if event is EventType.IPMI_ERROR:
|
|
113
|
+
self._state.record_ipmi_error()
|
|
114
|
+
elif event is EventType.POLL:
|
|
115
|
+
temp_c = fields.get("temp_c")
|
|
116
|
+
fan_pct = fields.get("fan_pct")
|
|
117
|
+
mode = fields.get("mode")
|
|
118
|
+
if isinstance(temp_c, int) and isinstance(mode, str):
|
|
119
|
+
pct: FanPercent | None = FanPercent(fan_pct) if isinstance(fan_pct, int) else None
|
|
120
|
+
self._state.record_poll(TempC(temp_c), pct, OperatingMode(mode))
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _install_signal_handlers(stop_event: threading.Event) -> None:
|
|
124
|
+
def stop(_signum: int, _frame: object) -> None:
|
|
125
|
+
stop_event.set()
|
|
126
|
+
|
|
127
|
+
try:
|
|
128
|
+
if threading.current_thread() is not threading.main_thread():
|
|
129
|
+
return
|
|
130
|
+
signal.signal(signal.SIGINT, stop)
|
|
131
|
+
signal.signal(signal.SIGTERM, stop)
|
|
132
|
+
except ValueError:
|
|
133
|
+
pass
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@app.command()
|
|
137
|
+
def run(
|
|
138
|
+
config: Annotated[Path, typer.Option("--config", "-c")] = Path("breezed.toml"),
|
|
139
|
+
metrics_port: Annotated[
|
|
140
|
+
int | None, typer.Option("--metrics-port", help="Loopback port for the metrics endpoint")
|
|
141
|
+
] = None,
|
|
142
|
+
verbose: Annotated[
|
|
143
|
+
bool, typer.Option("-v", "--verbose", help="Plain-text debug logging instead of JSON")
|
|
144
|
+
] = False,
|
|
145
|
+
) -> None:
|
|
146
|
+
"""Run the control loop until SIGINT/SIGTERM."""
|
|
147
|
+
setup_logging(verbose)
|
|
148
|
+
try:
|
|
149
|
+
_run_body(config, metrics_port)
|
|
150
|
+
except typer.Exit:
|
|
151
|
+
raise
|
|
152
|
+
except Exception as err:
|
|
153
|
+
logging.getLogger("breezed").error(
|
|
154
|
+
"fatal",
|
|
155
|
+
extra={
|
|
156
|
+
"event": "fatal",
|
|
157
|
+
"error": type(err).__name__,
|
|
158
|
+
"detail": str(err),
|
|
159
|
+
"traceback": format_exc(),
|
|
160
|
+
},
|
|
161
|
+
)
|
|
162
|
+
raise
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _run_body(config: Path, metrics_port: int | None) -> None:
|
|
166
|
+
settings = _load_settings_or_fail(config)
|
|
167
|
+
watcher = ConfigWatcher(config)
|
|
168
|
+
|
|
169
|
+
port = metrics_port if metrics_port is not None else settings.metrics_port
|
|
170
|
+
state: MetricsState | None = None
|
|
171
|
+
server = None
|
|
172
|
+
if port is not None:
|
|
173
|
+
state = MetricsState()
|
|
174
|
+
server = start_metrics_server(port, state)
|
|
175
|
+
|
|
176
|
+
sink = _MetricsSink(LoggingEventSink(), state)
|
|
177
|
+
current_settings = settings
|
|
178
|
+
controller = None
|
|
179
|
+
|
|
180
|
+
stop_event = threading.Event()
|
|
181
|
+
_install_signal_handlers(stop_event)
|
|
182
|
+
|
|
183
|
+
sink.emit(EventType.STARTUP)
|
|
184
|
+
try:
|
|
185
|
+
client = deps.build_client(current_settings)
|
|
186
|
+
controller = Controller(client, client, current_settings, sink)
|
|
187
|
+
while not deps.sleep_interruptible(stop_event, current_settings.poll_interval_s):
|
|
188
|
+
controller.tick()
|
|
189
|
+
if watcher.changed():
|
|
190
|
+
try:
|
|
191
|
+
new_settings = watcher.reload()
|
|
192
|
+
except ConfigError as err:
|
|
193
|
+
sink.emit(EventType.CONFIG_ERROR, error=str(err))
|
|
194
|
+
else:
|
|
195
|
+
if controller.replace_settings(new_settings):
|
|
196
|
+
current_settings = new_settings
|
|
197
|
+
sink.emit(EventType.CONFIG_RELOAD)
|
|
198
|
+
finally:
|
|
199
|
+
if controller is not None:
|
|
200
|
+
controller.shutdown()
|
|
201
|
+
if server is not None:
|
|
202
|
+
server.shutdown()
|
|
203
|
+
sink.emit(EventType.SHUTDOWN)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
@app.command("set")
|
|
207
|
+
def set_speed(
|
|
208
|
+
pct: Annotated[int, typer.Argument()],
|
|
209
|
+
config: Annotated[Path, typer.Option("--config", "-c")] = Path("breezed.toml"),
|
|
210
|
+
) -> None:
|
|
211
|
+
"""Set a fixed manual fan percentage (1-100) until the next mode change."""
|
|
212
|
+
if not 1 <= pct <= 100:
|
|
213
|
+
err = ValueError(f"PCT must be in 1..100, got {pct}")
|
|
214
|
+
_fail(err, code=2)
|
|
215
|
+
_, client = _connect(config)
|
|
216
|
+
try:
|
|
217
|
+
client.disable_auto()
|
|
218
|
+
client.set_manual_pct(make_fan_pct(pct))
|
|
219
|
+
except IpmiError as err:
|
|
220
|
+
_fail(err, code=1)
|
|
221
|
+
print(json.dumps({"event": "speed_change", "fan_pct": pct}))
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
@app.command()
|
|
225
|
+
def auto(
|
|
226
|
+
config: Annotated[Path, typer.Option("--config", "-c")] = Path("breezed.toml"),
|
|
227
|
+
) -> None:
|
|
228
|
+
"""Hand fan control back to the iDRAC's automatic policy."""
|
|
229
|
+
_, client = _connect(config)
|
|
230
|
+
try:
|
|
231
|
+
client.enable_auto()
|
|
232
|
+
except IpmiError as err:
|
|
233
|
+
_fail(err, code=1)
|
|
234
|
+
print(json.dumps({"event": "mode_change", "to": "auto"}))
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
@app.command()
|
|
238
|
+
def status(
|
|
239
|
+
config: Annotated[Path, typer.Option("--config")] = Path("breezed.toml"),
|
|
240
|
+
verbose: Annotated[bool, typer.Option("--verbose")] = False,
|
|
241
|
+
) -> None:
|
|
242
|
+
"""Print one-shot sensor status as JSON (human-readable with --verbose)."""
|
|
243
|
+
settings, client = _connect(config)
|
|
244
|
+
try:
|
|
245
|
+
temp = client.read_max_cpu_temp()
|
|
246
|
+
rpms = client.read_fan_rpms()
|
|
247
|
+
except IpmiError as err:
|
|
248
|
+
_fail(err, code=1)
|
|
249
|
+
target = interpolate(settings.curve, temp)
|
|
250
|
+
if verbose:
|
|
251
|
+
console = rich.console.Console()
|
|
252
|
+
console.print(f"CPU max: {temp}C", style="bold")
|
|
253
|
+
for name, rpm in rpms:
|
|
254
|
+
console.print(f"{name}: {rpm} RPM")
|
|
255
|
+
if target is None:
|
|
256
|
+
console.print("Curve target: auto (above curve)", style="cyan")
|
|
257
|
+
else:
|
|
258
|
+
console.print(f"Curve target: {target}% (manual)", style="cyan")
|
|
259
|
+
else:
|
|
260
|
+
print(json.dumps({"temp_c": temp, "fan_rpms": rpms, "target_pct": target}))
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
@app.command()
|
|
264
|
+
def validate(
|
|
265
|
+
path: Annotated[Path, typer.Argument()],
|
|
266
|
+
probe: Annotated[
|
|
267
|
+
bool, typer.Option("--probe", help="Also read a live temperature from the iDRAC")
|
|
268
|
+
] = False,
|
|
269
|
+
) -> None:
|
|
270
|
+
"""Validate a config file and print a JSON summary; --probe adds a live read."""
|
|
271
|
+
try:
|
|
272
|
+
settings = load_settings(path)
|
|
273
|
+
except ConfigError as err:
|
|
274
|
+
print(json.dumps({"valid": False, "error": str(err)}))
|
|
275
|
+
_fail(err, code=2)
|
|
276
|
+
summary: dict[str, object] = {
|
|
277
|
+
"valid": True,
|
|
278
|
+
"path": str(path),
|
|
279
|
+
"host": settings.host,
|
|
280
|
+
"poll_interval_s": settings.poll_interval_s,
|
|
281
|
+
"curve_points": len(settings.curve),
|
|
282
|
+
"metrics_port": settings.metrics_port,
|
|
283
|
+
}
|
|
284
|
+
if probe:
|
|
285
|
+
try:
|
|
286
|
+
client = deps.build_client(settings)
|
|
287
|
+
temp = client.read_max_cpu_temp()
|
|
288
|
+
except IpmiError as err:
|
|
289
|
+
summary["probe"] = {"ok": False, "error": str(err)}
|
|
290
|
+
print(json.dumps(summary))
|
|
291
|
+
_fail(err, code=1)
|
|
292
|
+
target = interpolate(settings.curve, temp)
|
|
293
|
+
summary["probe"] = {
|
|
294
|
+
"ok": True,
|
|
295
|
+
"temp_c": temp,
|
|
296
|
+
"target_pct": target,
|
|
297
|
+
"would_auto": target is None,
|
|
298
|
+
}
|
|
299
|
+
print(json.dumps(summary))
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
daemon_app = typer.Typer(add_completion=False, pretty_exceptions_enable=False)
|
|
303
|
+
|
|
304
|
+
_KEEP = ["/etc/breezed.env", "/etc/breezed"]
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _resolve_self() -> Path:
|
|
308
|
+
return Path(os.path.realpath(sys.argv[0]))
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _resolve_sudo() -> str:
|
|
312
|
+
sudo = shutil.which("sudo")
|
|
313
|
+
if sudo is None:
|
|
314
|
+
_fail(DaemonError("sudo not found; `daemon install` needs a single sudo prompt"), code=1)
|
|
315
|
+
return sudo
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _resolve_uv() -> str:
|
|
319
|
+
uv = shutil.which("uv")
|
|
320
|
+
if uv is None:
|
|
321
|
+
_fail(DaemonError("uv not found on PATH; install uv first"), code=1)
|
|
322
|
+
return uv
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _print_step_plan(steps: list[Step], note: str) -> None:
|
|
326
|
+
typer.secho(note, fg=typer.colors.YELLOW, err=True)
|
|
327
|
+
for step in steps:
|
|
328
|
+
typer.secho(f" • {step.label}", fg=typer.colors.CYAN, bold=True, err=True)
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def _print_results(results: list[tuple[str, StepOutcome]]) -> None:
|
|
332
|
+
for label, outcome in results:
|
|
333
|
+
if outcome is StepOutcome.SKIPPED:
|
|
334
|
+
typer.secho(f" · {label}", dim=True, err=True)
|
|
335
|
+
else:
|
|
336
|
+
typer.secho(f" ✔ {label}", fg=typer.colors.GREEN, err=True)
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def _run_sudo(argv: list[str]) -> None:
|
|
340
|
+
completed = subprocess.run(argv, check=False)
|
|
341
|
+
if completed.returncode != 0:
|
|
342
|
+
raise typer.Exit(code=completed.returncode or 1)
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
@daemon_app.command("install")
|
|
346
|
+
def daemon_install(
|
|
347
|
+
staging_dir: Annotated[
|
|
348
|
+
Path | None, typer.Option("--staging-dir", help="Override the private staging directory")
|
|
349
|
+
] = None,
|
|
350
|
+
source: Annotated[
|
|
351
|
+
Path | None, typer.Option("--source", help="uv source spec (defaults to current checkout)")
|
|
352
|
+
] = None,
|
|
353
|
+
dry_run: Annotated[
|
|
354
|
+
bool, typer.Option("--dry-run", help="Print the privileged steps without escalating")
|
|
355
|
+
] = False,
|
|
356
|
+
) -> None:
|
|
357
|
+
"""Stage the unit/env/config, then install the system service via one sudo prompt."""
|
|
358
|
+
resolved_source = str((source or Path.cwd()).resolve())
|
|
359
|
+
resolved_uv = _resolve_uv()
|
|
360
|
+
owner = getpass.getuser()
|
|
361
|
+
stage_dir = staging_dir or Path(tempfile.mkdtemp(prefix="breezed-install-"))
|
|
362
|
+
try:
|
|
363
|
+
stage_files(stage_dir)
|
|
364
|
+
except DaemonError as err:
|
|
365
|
+
_fail(err, code=1)
|
|
366
|
+
|
|
367
|
+
steps = build_steps(stage_dir, owner, resolved_uv, resolved_source)
|
|
368
|
+
|
|
369
|
+
if os.geteuid() == 0:
|
|
370
|
+
try:
|
|
371
|
+
_print_results(apply(stage_dir, owner, resolved_uv, resolved_source))
|
|
372
|
+
except DaemonError as err:
|
|
373
|
+
_fail(err, code=1)
|
|
374
|
+
print(json.dumps({"event": "install_complete"}))
|
|
375
|
+
return
|
|
376
|
+
|
|
377
|
+
_print_step_plan(steps, "The following privileged steps will run:")
|
|
378
|
+
if dry_run:
|
|
379
|
+
print(json.dumps({"event": "install_planned", "steps": [step.label for step in steps]}))
|
|
380
|
+
return
|
|
381
|
+
argv = [
|
|
382
|
+
_resolve_sudo(),
|
|
383
|
+
str(_resolve_self()),
|
|
384
|
+
"daemon",
|
|
385
|
+
"apply",
|
|
386
|
+
"--staging-dir",
|
|
387
|
+
str(stage_dir),
|
|
388
|
+
"--owner",
|
|
389
|
+
owner,
|
|
390
|
+
"--uv",
|
|
391
|
+
resolved_uv,
|
|
392
|
+
"--source",
|
|
393
|
+
resolved_source,
|
|
394
|
+
]
|
|
395
|
+
_run_sudo(argv)
|
|
396
|
+
print(json.dumps({"event": "install_complete"}))
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
@daemon_app.command("apply", hidden=True)
|
|
400
|
+
def daemon_apply(
|
|
401
|
+
staging_dir: Annotated[Path, typer.Option()],
|
|
402
|
+
owner: Annotated[str, typer.Option()],
|
|
403
|
+
uv: Annotated[str, typer.Option()],
|
|
404
|
+
source: Annotated[str, typer.Option()],
|
|
405
|
+
) -> None:
|
|
406
|
+
"""Internal privileged install step, invoked via sudo by `daemon install`."""
|
|
407
|
+
try:
|
|
408
|
+
results = apply(staging_dir, owner, uv, source)
|
|
409
|
+
except DaemonError as err:
|
|
410
|
+
_fail(err, code=1)
|
|
411
|
+
_print_results(results)
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
@daemon_app.command("status")
|
|
415
|
+
def daemon_status_command() -> None:
|
|
416
|
+
try:
|
|
417
|
+
report = daemon_status()
|
|
418
|
+
except DaemonError as err:
|
|
419
|
+
_fail(err, code=1)
|
|
420
|
+
print(json.dumps(asdict(report)))
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
@daemon_app.command("uninstall")
|
|
424
|
+
def daemon_uninstall(
|
|
425
|
+
dry_run: Annotated[
|
|
426
|
+
bool, typer.Option("--dry-run", help="Print the privileged steps without escalating")
|
|
427
|
+
] = False,
|
|
428
|
+
) -> None:
|
|
429
|
+
"""Stop and remove the service and runtime via one sudo prompt; keeps /etc/breezed.env/."""
|
|
430
|
+
resolved_uv = _resolve_uv()
|
|
431
|
+
|
|
432
|
+
steps = build_remove_steps(resolved_uv)
|
|
433
|
+
|
|
434
|
+
if os.geteuid() == 0:
|
|
435
|
+
try:
|
|
436
|
+
_print_results(remove(resolved_uv))
|
|
437
|
+
except DaemonError as err:
|
|
438
|
+
_fail(err, code=1)
|
|
439
|
+
print(json.dumps({"event": "uninstall_complete", "keeps": _KEEP}))
|
|
440
|
+
return
|
|
441
|
+
|
|
442
|
+
_print_step_plan(steps, "The following privileged steps will run:")
|
|
443
|
+
if dry_run:
|
|
444
|
+
print(
|
|
445
|
+
json.dumps(
|
|
446
|
+
{
|
|
447
|
+
"event": "uninstall_planned",
|
|
448
|
+
"keeps": _KEEP,
|
|
449
|
+
"steps": [step.label for step in steps],
|
|
450
|
+
}
|
|
451
|
+
)
|
|
452
|
+
)
|
|
453
|
+
return
|
|
454
|
+
argv = [_resolve_sudo(), str(_resolve_self()), "daemon", "remove", "--uv", resolved_uv]
|
|
455
|
+
_run_sudo(argv)
|
|
456
|
+
print(json.dumps({"event": "uninstall_complete", "keeps": _KEEP}))
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
@daemon_app.command("remove", hidden=True)
|
|
460
|
+
def daemon_remove(
|
|
461
|
+
uv: Annotated[str, typer.Option()],
|
|
462
|
+
) -> None:
|
|
463
|
+
"""Internal privileged uninstall step, invoked via sudo by `daemon uninstall`."""
|
|
464
|
+
try:
|
|
465
|
+
results = remove(uv)
|
|
466
|
+
except DaemonError as err:
|
|
467
|
+
_fail(err, code=1)
|
|
468
|
+
_print_results(results)
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
app.add_typer(daemon_app, name="daemon")
|
breezed/config.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"""TOML config loader: structural adapter only.
|
|
2
|
+
|
|
3
|
+
Every business rule (positive ints, fan_pct bounds, curve validity) delegates to
|
|
4
|
+
the domain layer in breezed.types / breezed.curve. This module only handles key
|
|
5
|
+
presence, TOML type shape, env/file precedence, and error wrapping.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
import tomllib
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import TypeIs
|
|
12
|
+
|
|
13
|
+
from pydantic import BaseModel, ConfigDict, ValidationError, field_validator, model_validator
|
|
14
|
+
|
|
15
|
+
from breezed.curve import CurvePoint, validate_curve
|
|
16
|
+
from breezed.types import DomainError, TempC, make_fan_pct, make_positive_int
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ConfigError(DomainError):
|
|
20
|
+
"""Field-naming failure; also wraps TOML decode, OS, and validation errors.
|
|
21
|
+
|
|
22
|
+
Messages reference field names, never secret values (password discipline).
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
DEFAULT_CURVE: tuple[CurvePoint, ...] = (
|
|
27
|
+
CurvePoint(temp_c=TempC(45), fan_pct=make_fan_pct(6)),
|
|
28
|
+
CurvePoint(temp_c=TempC(60), fan_pct=make_fan_pct(8)),
|
|
29
|
+
CurvePoint(temp_c=TempC(68), fan_pct=make_fan_pct(12)),
|
|
30
|
+
CurvePoint(temp_c=TempC(74), fan_pct=make_fan_pct(18)),
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _is_int(value: object) -> TypeIs[int]:
|
|
35
|
+
# TOML has no distinct bool/int ambiguity, but Python's bool is an int and
|
|
36
|
+
# `true` for poll_interval_s would otherwise silently mean 1.
|
|
37
|
+
return isinstance(value, int) and not isinstance(value, bool)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
_IDENTITY_KEYS = (("host", "IDRAC_HOST"), ("user", "IDRAC_USER"))
|
|
41
|
+
_ENV_OVERRIDES = (*_IDENTITY_KEYS, ("password", "IDRAC_PASSWORD"))
|
|
42
|
+
_POSITIVE_INT_FIELDS = (
|
|
43
|
+
"poll_interval_s",
|
|
44
|
+
"read_failure_limit",
|
|
45
|
+
"step_down_hysteresis_s",
|
|
46
|
+
"metrics_port",
|
|
47
|
+
)
|
|
48
|
+
_DEFAULT_TOOL_PATH = "/usr/bin/ipmitool"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _curve_row(index: int, row: dict[str, object]) -> CurvePoint:
|
|
52
|
+
def require(column: str) -> int:
|
|
53
|
+
value = row.get(column)
|
|
54
|
+
if not _is_int(value):
|
|
55
|
+
got = type(value).__name__
|
|
56
|
+
msg = f"curve[{index}].{column}: expected an integer, got {got}"
|
|
57
|
+
raise ValueError(msg)
|
|
58
|
+
return value
|
|
59
|
+
|
|
60
|
+
temp_raw = require("temp_c")
|
|
61
|
+
pct_raw = require("fan_pct")
|
|
62
|
+
try:
|
|
63
|
+
fan_pct = make_fan_pct(pct_raw)
|
|
64
|
+
except ValueError as exc:
|
|
65
|
+
msg = f"curve[{index}].{exc}"
|
|
66
|
+
raise ValueError(msg) from exc
|
|
67
|
+
return CurvePoint(temp_c=TempC(temp_raw), fan_pct=fan_pct)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class Settings(BaseModel):
|
|
71
|
+
"""Validated runtime configuration; frozen so consumers can share it safely."""
|
|
72
|
+
|
|
73
|
+
model_config = ConfigDict(frozen=True)
|
|
74
|
+
|
|
75
|
+
host: str
|
|
76
|
+
user: str
|
|
77
|
+
password: str = ""
|
|
78
|
+
curve: tuple[CurvePoint, ...] = DEFAULT_CURVE
|
|
79
|
+
poll_interval_s: int = 10
|
|
80
|
+
read_failure_limit: int = 3
|
|
81
|
+
step_down_hysteresis_s: int = 30
|
|
82
|
+
metrics_port: int | None = None
|
|
83
|
+
ipmitool_path: str = _DEFAULT_TOOL_PATH
|
|
84
|
+
|
|
85
|
+
@model_validator(mode="before")
|
|
86
|
+
@classmethod
|
|
87
|
+
def _require_identity(cls, data: object) -> object:
|
|
88
|
+
if not isinstance(data, dict):
|
|
89
|
+
return data
|
|
90
|
+
missing = []
|
|
91
|
+
for name, env_key in _IDENTITY_KEYS:
|
|
92
|
+
value = data.get(name)
|
|
93
|
+
if isinstance(value, str) and value:
|
|
94
|
+
continue
|
|
95
|
+
missing.append(f"{name}: missing (set [settings].{name} or {env_key})")
|
|
96
|
+
if missing:
|
|
97
|
+
msg = "; ".join(missing)
|
|
98
|
+
raise ValueError(msg)
|
|
99
|
+
return data
|
|
100
|
+
|
|
101
|
+
@model_validator(mode="before")
|
|
102
|
+
@classmethod
|
|
103
|
+
def _check_int_fields(cls, data: object) -> object:
|
|
104
|
+
if not isinstance(data, dict):
|
|
105
|
+
return data
|
|
106
|
+
for key in _POSITIVE_INT_FIELDS:
|
|
107
|
+
value = data.get(key)
|
|
108
|
+
if value is None:
|
|
109
|
+
continue
|
|
110
|
+
if not _is_int(value):
|
|
111
|
+
got = type(value).__name__
|
|
112
|
+
msg = f"{key}: expected an integer, got {got}"
|
|
113
|
+
raise ValueError(msg)
|
|
114
|
+
data[key] = make_positive_int(key, value)
|
|
115
|
+
return data
|
|
116
|
+
|
|
117
|
+
@field_validator("curve", mode="before")
|
|
118
|
+
@classmethod
|
|
119
|
+
def _parse_curve(cls, value: object) -> object:
|
|
120
|
+
if value is None or (isinstance(value, list) and not value):
|
|
121
|
+
return DEFAULT_CURVE
|
|
122
|
+
# Programmatic construction (tests, callers) passes validated points directly.
|
|
123
|
+
if isinstance(value, tuple) and all(isinstance(p, CurvePoint) for p in value):
|
|
124
|
+
return value
|
|
125
|
+
if not isinstance(value, list) or any(not isinstance(r, dict) for r in value):
|
|
126
|
+
msg = "curve: expected an array of tables"
|
|
127
|
+
raise ValueError(msg)
|
|
128
|
+
points = tuple(_curve_row(i, r) for i, r in enumerate(value))
|
|
129
|
+
try:
|
|
130
|
+
return validate_curve(points)
|
|
131
|
+
except ValueError as exc:
|
|
132
|
+
msg = f"curve: {exc}"
|
|
133
|
+
raise ValueError(msg) from exc
|
|
134
|
+
|
|
135
|
+
@field_validator("ipmitool_path", mode="before")
|
|
136
|
+
@classmethod
|
|
137
|
+
def _empty_tool_path_falls_back(cls, value: object) -> object:
|
|
138
|
+
return value or _DEFAULT_TOOL_PATH
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def load_settings(path: str | Path) -> Settings:
|
|
142
|
+
"""Binary-mode tomllib load; env wins over file for host/user/password.
|
|
143
|
+
|
|
144
|
+
Omitted/empty [[curve]] falls back to DEFAULT_CURVE; unknown keys are ignored
|
|
145
|
+
everywhere. All business rules live in the domain layer.
|
|
146
|
+
"""
|
|
147
|
+
try:
|
|
148
|
+
with open(path, "rb") as f:
|
|
149
|
+
data = tomllib.load(f)
|
|
150
|
+
except tomllib.TOMLDecodeError as exc:
|
|
151
|
+
msg = f"config: invalid TOML in {path}: {exc}"
|
|
152
|
+
raise ConfigError(msg) from exc
|
|
153
|
+
except OSError as exc:
|
|
154
|
+
msg = f"config: cannot read {path}: {exc}"
|
|
155
|
+
raise ConfigError(msg) from exc
|
|
156
|
+
|
|
157
|
+
raw_settings = data.get("settings")
|
|
158
|
+
settings_table = dict(raw_settings) if isinstance(raw_settings, dict) else {}
|
|
159
|
+
for name, env_key in _ENV_OVERRIDES:
|
|
160
|
+
# An empty env value counts as unset, same as absent.
|
|
161
|
+
env_value = os.environ.get(env_key)
|
|
162
|
+
if env_value:
|
|
163
|
+
settings_table[name] = env_value
|
|
164
|
+
try:
|
|
165
|
+
# [[curve]] is a top-level TOML table array, sibling of [settings].
|
|
166
|
+
return Settings.model_validate({**settings_table, "curve": data.get("curve")})
|
|
167
|
+
except ValidationError as exc:
|
|
168
|
+
msg = "; ".join(str(error["msg"]) for error in exc.errors())
|
|
169
|
+
raise ConfigError(msg) from exc
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
__all__ = ["ConfigError", "DEFAULT_CURVE", "Settings", "load_settings"]
|