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:
1 parent
2df46741f2
commit
54bda2cb79
5 files changed
+349
No files matched your search
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
]
|
||||
Reference in new issue
Block a user