feat(host-repairs): a host's checks and repairs as a fixed catalog of runs (NetOrk/netork#2899)

HostRepairMixin declares one method per run -- verify_system_files,
repair_system_files, check_component_store, repair_component_store,
update_antimalware_signatures and scan_antimalware -- so the method list is the
guard, and a repair is never offered with its check. Each streams the tool's
lines to log and returns a HostRepairResultDict; tool_outcome builds it from the
lines and the exit code, failing a non-zero code with the tool's last lines.
offered_host_repairs lists the runs a driver defines.
This commit is contained in:
christianmanivong committed 2026-12-01 12:44:45 +01:00
1 parent 2df46741f2
commit 54bda2cb79
5 files changed
+349

No files matched your search

+13
View File
@@ -7,6 +7,19 @@ recorded here; their history is the git log.
## [Unreleased]
### Added
- `HostRepairMixin`: a host's own checks and repairs as a fixed catalog of runs
(NetOrk/netork#2899), one method each: `verify_system_files()`, `repair_system_files()`,
`check_component_store()`, `repair_component_store()`, `update_antimalware_signatures()`
and `scan_antimalware(quick=True)`. Each streams the tool's output line by line to `log`
and returns a `HostRepairResultDict` (`success`, `output`, `exit_code`, `error`). A check
never repairs: a repair is a method of its own. Not on any role base; a driver defines the
runs its host can do, and `offered_host_repairs(driver_cls)` lists them.
- `tool_outcome(lines, exit_code, tool=...)`: the result of a run from its tool's output and
exit code. Exit code 0 succeeds; any other, or none, fails with the tool's last lines. A
negative (signed 32-bit) exit code is read as unsigned, and an HRESULT shows in hex. The
kept output is bounded to its last 64,000 characters.
## [4.55.0] - 2026-12-01
### Added
+11
View File
@@ -137,6 +137,17 @@ on its own CPU; on Debian with its archive's firmware component added first;
change in one call overrides the template method. A driver mixes in the fixes its device
can take; none is on a role base. They replace `run_device_action`, which is deprecated.
**Repair runs are a fixed catalog** (`napalm_device_types.host_repairs`). A host's own
checks and repairs of its system are one method per run, so the method list is the guard:
`HostRepairMixin.verify_system_files()`, `repair_system_files()`,
`check_component_store()`, `repair_component_store()`, `update_antimalware_signatures()`
and `scan_antimalware(quick)`. Each takes `log` for every line of the tool's output as the
host prints it, is bounded in time by the driver and returns a `HostRepairResultDict`
(`success`, `output`, `exit_code`, `error`); `tool_outcome(lines, exit_code, tool=...)`
builds it, so every driver fails a run the same way (a non-zero exit code, with the tool's
last lines). A repair is a method of its own beside its check, and a driver defines only
the runs it can do: `offered_host_repairs(driver_cls)` lists them. None restarts the host.
**SNMP is the application's** (`docs/STRUCTURE.md`). `HealthMetricsMixin` is deprecated
since 4.12 and goes in 5.0. A driver does not collect over SNMP; a driver whose device
publishes its health values under OIDs of its own declares them as data:
+11
View File
@@ -51,6 +51,7 @@ instead of being restated on every role that happens to need it:
* :class:`~napalm_device_types.host_status.HostStatusMixin`
* :class:`~napalm_device_types.host_reboot.HostRebootMixin`
* :class:`~napalm_device_types.host_shutdown.HostShutdownMixin`
* :class:`~napalm_device_types.host_repairs.HostRepairMixin`
* :class:`~napalm_device_types.interface_filter.InterfaceFilterMixin`
* :class:`~napalm_device_types.kernel.KernelFactsMixin`
* :class:`~napalm_device_types.listening.ListeningSocketsMixin`
@@ -214,6 +215,12 @@ from napalm_device_types.host_firewall import (
parse_host_firewall,
)
from napalm_device_types.host_reboot import HostRebootMixin
from napalm_device_types.host_repairs import (
HostRepairMixin,
HostRepairResultDict,
offered_host_repairs,
tool_outcome,
)
from napalm_device_types.host_shutdown import HostShutdownMixin
from napalm_device_types.host_status import HOST_STATUS_COMMAND, HostStatusMixin, parse_host_status
from napalm_device_types.hypervisor import HypervisorDriver
@@ -614,6 +621,10 @@ __all__ = [
"HostStatusMixin",
"HostRebootMixin",
"HostShutdownMixin",
"HostRepairMixin",
"HostRepairResultDict",
"offered_host_repairs",
"tool_outcome",
"HypervisorDriver",
"InterfaceFilterMixin",
"MacAclMixin",
+184
View File
@@ -0,0 +1,184 @@
"""Repair runs: a host's own checks and repairs of its system, one method per run.
A fixed catalog, not a command line: each run is a method of its own, so the list of
methods is the guard -- an application can start these runs and nothing else. A driver
mixes :class:`HostRepairMixin` in where its host has the tools and defines the runs it
can do; the others stay declared only, so ``hasattr`` (or :func:`offered_host_repairs`)
tells an application which to offer. A run that changes the host is a method of its own
(``repair_system_files`` beside ``verify_system_files``), so offering a check never
offers the repair.
The runs are long -- minutes, a component store's scan up to half an hour -- so each
takes ``log``, which receives every line of the tool's output as the host prints it,
and each is bounded in time by the driver. They are runs an application starts, never
part of a reading. None restarts the host: a repair that wants a restart says so in its
output, and restarting is the caller's.
:func:`tool_outcome` is the shared part of every run: the tool's exit code decides, a
failure names the tool's last lines, and the output the result keeps is bounded.
Declared under ``if TYPE_CHECKING``: a contract, not a placeholder (see the package
docstring). Not mixed into any role base.
"""
from __future__ import annotations
from collections.abc import Callable, Sequence
from typing import TYPE_CHECKING, NotRequired
from typing_extensions import TypedDict
#: Receives one line of a tool's output, without its line break.
LineLog = Callable[[str], None]
#: The runs of the catalog, in the order an application lists them.
HOST_REPAIR_METHODS: tuple[str, ...] = (
"verify_system_files",
"repair_system_files",
"check_component_store",
"repair_component_store",
"update_antimalware_signatures",
"scan_antimalware",
)
#: How many of a failed tool's last lines its ``error`` names.
FAILURE_TAIL_LINES = 10
#: The most characters of output a result keeps: the end, where tools say how they ended.
OUTPUT_LIMIT = 64_000
# Exit codes at or above this are HRESULTs (0x8007…, 0x800F…) and read better in hex.
_HRESULT_FLOOR = 0x8000_0000
_UINT32 = 0xFFFF_FFFF
class HostRepairResultDict(TypedDict):
"""How a repair run ended (every method of :class:`HostRepairMixin`)."""
success: bool # the tool ended with exit code 0
output: str # the tool's output as text, its end kept within OUTPUT_LIMIT
exit_code: int | None # unsigned; None where the tool gave none (cut off, not started)
error: NotRequired[str] # on failure: the exit code and the tool's last lines
def _exit_code_text(code: int) -> str:
return f"0x{code:X}" if code >= _HRESULT_FLOOR else str(code)
def _bounded(text: str) -> str:
return text if len(text) <= OUTPUT_LIMIT else text[-OUTPUT_LIMIT:]
def tool_outcome(lines: Sequence[str], exit_code: int | None, *, tool: str) -> HostRepairResultDict:
"""The result of a run whose tool printed *lines* and ended with *exit_code*.
Exit code 0 succeeds. Any other, or none, fails, and ``error`` names it with the
tool's last non-blank lines. A negative code is a signed 32-bit one (.NET's
``Process.ExitCode``) and is read as unsigned, so an HRESULT keeps its usual form.
"""
code = None if exit_code is None else exit_code & _UINT32
result: HostRepairResultDict = {
"success": code == 0,
"output": _bounded("\n".join(lines)),
"exit_code": code,
}
if code == 0:
return result
said = [line for line in lines if line.strip()][-FAILURE_TAIL_LINES:]
head = (
f"{tool} ended without an exit code"
if code is None
else f"{tool} ended with exit code {_exit_code_text(code)}"
)
result["error"] = f"{head}: " + "\n".join(said) if said else head
return result
def offered_host_repairs(driver_cls: type) -> list[str]:
"""The runs of the catalog *driver_cls* defines, in the catalog's order."""
return [name for name in HOST_REPAIR_METHODS if callable(getattr(driver_cls, name, None))]
class HostRepairMixin:
"""A host's checks and repairs of its own system files, its component store and its
antimalware, as fixed runs. See the module docstring."""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def verify_system_files(self, *, log: LineLog | None = None) -> HostRepairResultDict:
"""
Checks the protected system files against the host's own record of them,
and changes nothing (Windows: ``sfc /verifyonly``).
:param log: Receives each line of the tool's output as the host prints it.
:returns: How it ended (:class:`HostRepairResultDict`). A check that finds
damaged files can still end with exit code 0: the verdict is in the
output, in the host's language.
"""
...
def repair_system_files(self, *, log: LineLog | None = None) -> HostRepairResultDict:
"""
Checks the protected system files and replaces damaged ones from the host's
own store (Windows: ``sfc /scannow``). Changes the host; does not restart it.
:param log: As :meth:`verify_system_files`.
"""
...
def check_component_store(self, *, log: LineLog | None = None) -> HostRepairResultDict:
"""
Scans the store the system files are repaired from for damage, and changes
nothing (Windows: ``DISM /Online /Cleanup-Image /ScanHealth``). Takes up to
half an hour.
:param log: As :meth:`verify_system_files`.
"""
...
def repair_component_store(self, *, log: LineLog | None = None) -> HostRepairResultDict:
"""
Repairs that store from a repair source (Windows: ``DISM /Online
/Cleanup-Image /RestoreHealth``, from Windows Update unless a policy names
another source). Changes the host; does not restart it.
:param log: As :meth:`verify_system_files`.
"""
...
def update_antimalware_signatures(
self, *, log: LineLog | None = None
) -> HostRepairResultDict:
"""
Updates the host's antimalware signatures from the sources the host is set
to use (Windows: ``Update-MpSignature``). A host without the antimalware
fails with a result that says so, not with an exception.
:param log: As :meth:`verify_system_files`; it also receives the signature
version before and after.
"""
...
def scan_antimalware(
self, quick: bool = True, *, log: LineLog | None = None
) -> HostRepairResultDict:
"""
Scans the host with its antimalware (Windows: ``Start-MpScan``): the places
malware usually sits when *quick*, every file otherwise. What the scan finds
is handled as the antimalware is set to handle it; the output names it.
:param quick: A quick scan (minutes) rather than a full one (hours).
:param log: As :meth:`verify_system_files`.
"""
...
__all__ = [
"FAILURE_TAIL_LINES",
"HOST_REPAIR_METHODS",
"OUTPUT_LIMIT",
"HostRepairMixin",
"HostRepairResultDict",
"LineLog",
"offered_host_repairs",
"tool_outcome",
]
+130
View File
@@ -0,0 +1,130 @@
"""HostRepairMixin: a host's own checks and repairs of its system, as fixed runs (NetOrk/netork#2899).
One method per run, declared and not implemented, so ``hasattr`` tells an application
which runs a driver offers. ``tool_outcome`` is the shared part of every run: a tool's
exit code decides, a failure names the tool's last lines, and the output is bounded.
"""
from __future__ import annotations
import inspect
import pytest
from napalm_device_types import (
DeviceTypeDriver,
HostRepairMixin,
HostRepairResultDict,
tool_outcome,
)
from napalm_device_types.host_repairs import (
FAILURE_TAIL_LINES,
HOST_REPAIR_METHODS,
OUTPUT_LIMIT,
LineLog,
offered_host_repairs,
)
_RUNS = (
"verify_system_files",
"repair_system_files",
"check_component_store",
"repair_component_store",
"update_antimalware_signatures",
"scan_antimalware",
)
class TestContract:
@pytest.mark.parametrize("name", _RUNS)
def test_declared_not_implemented(self, name):
assert not hasattr(HostRepairMixin, name)
@pytest.mark.parametrize("name", _RUNS)
def test_each_run_is_documented(self, name):
source = inspect.getsource(HostRepairMixin)
assert f"def {name}(" in source
assert "log: LineLog | None = None" in source
def test_not_on_any_role_base(self):
# A driver mixes it in where its host has these tools.
assert not issubclass(DeviceTypeDriver, HostRepairMixin)
def test_the_catalog_names_every_run(self):
assert set(HOST_REPAIR_METHODS) == set(_RUNS)
def test_a_line_log_takes_one_line(self):
lines: list[str] = []
log: LineLog = lines.append
log("x")
assert lines == ["x"]
class TestOffered:
def test_only_the_runs_a_driver_defines(self):
class _Host(HostRepairMixin):
def verify_system_files(self, *, log=None): # noqa: ARG002
return tool_outcome(["ok"], 0, tool="sfc")
def update_antimalware_signatures(self, *, log=None): # noqa: ARG002
return tool_outcome([], 0, tool="Update-MpSignature")
assert offered_host_repairs(_Host) == [
"verify_system_files",
"update_antimalware_signatures",
]
def test_a_run_set_to_none_is_not_offered(self):
class _Host(HostRepairMixin):
scan_antimalware = None
assert offered_host_repairs(_Host) == []
def test_a_driver_without_the_mixin_offers_none(self):
assert offered_host_repairs(object) == []
class TestToolOutcome:
def test_exit_code_zero_succeeds_with_the_whole_output(self):
result: HostRepairResultDict = tool_outcome(["one", "two"], 0, tool="sfc")
assert result == {"success": True, "output": "one\ntwo", "exit_code": 0}
def test_a_non_zero_exit_code_fails_with_the_last_lines(self):
lines = [f"line {n}" for n in range(30)]
result = tool_outcome(lines, 5, tool="DISM")
assert result["success"] is False
assert result["exit_code"] == 5
assert result["error"].startswith("DISM ended with exit code 5:")
tail = result["error"].split(":", 1)[1].strip().splitlines()
assert tail == lines[-FAILURE_TAIL_LINES:]
def test_a_failure_without_output_names_the_code_only(self):
result = tool_outcome([], 2, tool="sfc")
assert result["error"] == "sfc ended with exit code 2"
def test_exit_codes_are_shown_as_hex_when_they_are_hresults(self):
result = tool_outcome(["Error: 0x800f081f"], 0x800F081F, tool="DISM")
assert result["error"].startswith("DISM ended with exit code 0x800F081F:")
def test_a_negative_exit_code_is_read_as_unsigned(self):
# .NET's Process.ExitCode is an Int32: 0x800F081F arrives as -2146498529.
result = tool_outcome([], -2146498529, tool="DISM")
assert result["exit_code"] == 0x800F081F
assert "0x800F081F" in result["error"]
def test_no_exit_code_is_a_failure(self):
result = tool_outcome(["started"], None, tool="sfc")
assert result["success"] is False
assert result["exit_code"] is None
assert result["error"] == "sfc ended without an exit code: started"
def test_blank_lines_are_not_the_tail(self):
result = tool_outcome(["the reason", "", " "], 1, tool="sfc")
assert result["error"] == "sfc ended with exit code 1: the reason"
def test_the_output_keeps_its_end_within_the_limit(self):
lines = ["x" * 1000] * (OUTPUT_LIMIT // 1000 + 50) + ["the end"]
result = tool_outcome(lines, 0, tool="sfc")
assert len(result["output"]) <= OUTPUT_LIMIT
assert result["output"].endswith("the end")