feat(host-events): host events, event channels as log sources, how a service's run ended (NetOrk/netork#2897)

- HostEventsMixin.get_host_events(since=None), declared: the events of a fixed
  set of kinds a host's own log recorded (unexpected shutdowns, system crashes,
  hardware errors, disk errors, programs and services that crashed), with
  HostEventDict, HostEventsDict and host_event().
- LogSourceDict: kind "eventlog" for a Windows event channel, named by the new
  optional channel field (eventlog_source, LOG_SOURCE_KINDS).
- ServiceDict: optional result, exit_code, trigger_start and account; exported.
This commit is contained in:
christianmanivong committed 2026-12-01 12:48:09 +01:00
1 parent 2df46741f2
commit 6c273ea346
10 files changed
+458 -7

No files matched your search

+29
View File
@@ -58,6 +58,7 @@ instead of being restated on every role that happens to need it:
* :class:`~napalm_device_types.login_accounts.LoginAccountsMixin`
* :class:`~napalm_device_types.login_sessions.LoginSessionsMixin`
* :class:`~napalm_device_types.log_sources.LogSourcesMixin`
* :class:`~napalm_device_types.host_events.HostEventsMixin`
* :class:`~napalm_device_types.host_firewall.HostFirewallMixin`
* :class:`~napalm_device_types.mac_acl.MacAclMixin`
* :class:`~napalm_device_types.ap_config.ApConfigMixin`
@@ -208,6 +209,15 @@ from napalm_device_types.hardening import (
parse_hardening,
)
from napalm_device_types.health_metrics import HealthMetricsMixin
from napalm_device_types.host_events import (
HOST_EVENT_KINDS,
HOST_EVENT_MESSAGE_CHARS,
HOST_EVENT_WINDOW_DAYS,
HostEventDict,
HostEventsDict,
HostEventsMixin,
host_event,
)
from napalm_device_types.host_firewall import (
HostFirewallMixin,
HostFirewallUnavailable,
@@ -257,11 +267,14 @@ from napalm_device_types.log_forwarding import (
parse_rsyslog,
)
from napalm_device_types.log_sources import (
EVENTLOG,
LOG_SOURCE_KINDS,
LOG_SOURCES_COMMAND,
LogSourceDict,
LogSourcesDict,
LogSourcesMixin,
LogSourcesUnavailable,
eventlog_source,
parse_log_forwarding,
parse_log_sources,
)
@@ -294,6 +307,8 @@ from napalm_device_types.management_controller import ManagementControllerDriver
from napalm_device_types.media import MediaDriver
from napalm_device_types.models import (
POWER_ACTIONS,
SERVICE_RESULT_EXIT_CODE,
SERVICE_RESULT_SUCCESS,
ConfigSyncDict,
DhcpHaDict,
DhcpHaPeerDict,
@@ -311,6 +326,7 @@ from napalm_device_types.models import (
OspfInterfaceDict,
PowerAction,
PowerStateDict,
ServiceDict,
SnmpAgentSettingsDict,
UpdateProgressDict,
)
@@ -612,6 +628,13 @@ __all__ = [
"HealthMetricsMixin",
"HOST_STATUS_COMMAND",
"HostStatusMixin",
"HOST_EVENT_KINDS",
"HOST_EVENT_MESSAGE_CHARS",
"HOST_EVENT_WINDOW_DAYS",
"HostEventDict",
"HostEventsDict",
"HostEventsMixin",
"host_event",
"HostRebootMixin",
"HostShutdownMixin",
"HypervisorDriver",
@@ -620,6 +643,9 @@ __all__ = [
"ManagementControllerDriver",
"ARP_AGE_UNKNOWN",
"POWER_ACTIONS",
"SERVICE_RESULT_EXIT_CODE",
"SERVICE_RESULT_SUCCESS",
"ServiceDict",
"PowerAction",
"PowerStateDict",
"HardwareInventoryDict",
@@ -685,6 +711,9 @@ __all__ = [
"ListeningSocketsMixin",
"ListeningSocketsUnavailable",
"LOG_SOURCES_COMMAND",
"EVENTLOG",
"LOG_SOURCE_KINDS",
"eventlog_source",
"FileInputDict",
"ForwardRuleDict",
"LogForwardingDict",
+157
View File
@@ -0,0 +1,157 @@
"""What a host's own log recorded that says something is wrong with it (NetOrk/netork#2897).
A crash, a power loss, a hardware error the CPU or the memory corrected, a disk
that reports bad blocks, a program that keeps dying: the host writes each of them
down itself -- Windows in its event log, Linux in its journal -- and nothing on the
outside sees it. :meth:`HostEventsMixin.get_host_events` reads those, and only
those: a fixed set of kinds (:data:`HOST_EVENT_KINDS`), not the log. Each event says
its kind, when it happened, what it is about where the host names that in words
that do not depend on its language (a stop code, a disk, a program's path, a
service), and where it was recorded. Whether that is a problem, and from how many,
is the application's to decide.
**Bounded.** The reading covers :data:`HOST_EVENT_WINDOW_DAYS` days unless the
caller names a start, and a driver reads at most a fixed number of events of each
query, newest first; a kind read up to that bound is in ``capped``, so a count of it
is "at least". A host's message is cut to :data:`HOST_EVENT_MESSAGE_CHARS`.
**Not read is not nothing.** A kind the driver could not read -- its log missing,
the query refused -- is in ``unread``; a kind neither read nor unread is one the
driver does not read at all. Only a kind that was read and found nothing means
nothing happened.
"""
from __future__ import annotations
from datetime import UTC, datetime
from typing import TYPE_CHECKING, TypedDict
#: The host stopped without shutting down: power lost, a reset, or a crash.
UNEXPECTED_SHUTDOWN = "unexpected_shutdown"
#: The operating system stopped itself on an error it could not go on from: a
#: Windows bugcheck, a Linux kernel panic. ``subject`` is the stop code.
SYSTEM_CRASH = "system_crash"
#: The hardware reported an error it could not correct (Windows' WHEA, a machine check).
HARDWARE_ERROR_FATAL = "hardware_error_fatal"
#: The hardware reported an error and corrected it: harmless once, a failing part
#: when it repeats.
HARDWARE_ERROR_CORRECTED = "hardware_error_corrected"
#: A disk or a file system reported an error: a bad block, a retried I/O, a
#: corruption. ``subject`` is the disk or the volume.
DISK_ERROR = "disk_error"
#: A program crashed. ``subject`` is its path, or its name where the host gives no path.
APP_CRASH = "app_crash"
#: A service ended without being stopped. ``subject`` is the service as the host names it.
SERVICE_CRASH = "service_crash"
#: Every kind of event the reading knows, in this order.
HOST_EVENT_KINDS = (
UNEXPECTED_SHUTDOWN,
SYSTEM_CRASH,
HARDWARE_ERROR_FATAL,
HARDWARE_ERROR_CORRECTED,
DISK_ERROR,
APP_CRASH,
SERVICE_CRASH,
)
#: How far back the reading goes when the caller names no start.
HOST_EVENT_WINDOW_DAYS = 7
#: The characters of a host's message an event keeps.
HOST_EVENT_MESSAGE_CHARS = 300
class HostEventDict(TypedDict):
"""One event the host recorded."""
kind: str # one of HOST_EVENT_KINDS
time: str # ISO 8601 in UTC
#: What it is about, in words that do not depend on the host's language: the
#: stop code, the disk or volume, the program's path, the service; None where
#: the host does not say.
subject: str | None
#: Where the host recorded it: ``System: Microsoft-Windows-Kernel-Power 41``.
source: str
#: The host's own text, in its language, cut to HOST_EVENT_MESSAGE_CHARS; None
#: where it has none or the driver does not read it.
message: str | None
class HostEventsDict(TypedDict):
"""What :meth:`HostEventsMixin.get_host_events` read."""
since: str # the start of the reading, ISO 8601 in UTC
events: list[HostEventDict] # newest first
#: Kinds read up to the driver's bound: there may be older ones in the window.
capped: list[str]
#: Kinds the driver reads and could not read this time.
unread: list[str]
def _text(value: str | None, limit: int | None = None) -> str | None:
text = (value or "").strip()
if limit is not None:
text = text[:limit].strip()
return text or None
def host_event(
kind: str,
at: float,
source: str,
subject: str | None,
message: str | None = None,
) -> HostEventDict:
"""One event: *at* in unix seconds, *message* cut to :data:`HOST_EVENT_MESSAGE_CHARS`.
:raises ValueError: for a kind :data:`HOST_EVENT_KINDS` does not name.
"""
if kind not in HOST_EVENT_KINDS:
raise ValueError(f"{kind!r} is not a host event kind")
return {
"kind": kind,
"time": datetime.fromtimestamp(at, UTC).isoformat(),
"subject": _text(subject),
"source": source,
"message": _text(message, HOST_EVENT_MESSAGE_CHARS),
}
class HostEventsMixin:
"""Declares :meth:`get_host_events` for a driver that reads its host's own log.
A contract, declared under ``if TYPE_CHECKING``: how the events are read is the
host's (Windows' event log, a journal), so a driver implements it, and
``hasattr(driver, "get_host_events")`` stays truthful.
"""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def get_host_events(self, since: float | None = None) -> HostEventsDict:
"""
Returns the events of :data:`HOST_EVENT_KINDS` the host recorded since
*since* (unix seconds), by default over the last
:data:`HOST_EVENT_WINDOW_DAYS` days.
* since (str) - the start of the reading, ISO 8601 UTC
* events (list) - newest first, see :class:`HostEventDict`
* capped (list) - kinds read up to the driver's bound
* unread (list) - kinds the driver could not read this time
Example::
{
"since": "2026-11-24T10:00:00+00:00",
"events": [
{"kind": "system_crash", "time": "2026-11-30T03:12:09+00:00",
"subject": "0x0000009f",
"source": "System: Microsoft-Windows-WER-SystemErrorReporting 1001",
"message": "The computer has rebooted from a bugcheck. ..."},
],
"capped": [],
"unread": [],
}
:raises ValueError: when the reading came back without a report.
"""
...
+35 -6
View File
@@ -45,28 +45,55 @@ from __future__ import annotations
import re
from datetime import UTC, datetime
from shlex import quote
from typing import TYPE_CHECKING, TypedDict
from typing import TYPE_CHECKING, NotRequired, TypedDict
from napalm_device_types.listening import _cgroup_paths, _container, _sections, _unit
from napalm_device_types.log_forwarding import LogForwardingDict, log_forwarding, parse_rsyslog
from napalm_device_types.terminal import strip_terminal_codes
#: A Windows event channel (NetOrk/netork#2897).
EVENTLOG = "eventlog"
#: Every kind of log source, in this order.
LOG_SOURCE_KINDS = ("journald", "file", "container", EVENTLOG)
class LogSourceDict(TypedDict):
"""A log the host writes: a unit's journal, a file a process holds open, or a
container's stream as the engine keeps it.
"""A log the host writes: a unit's journal, a file a process holds open, a
container's stream as the engine keeps it, or a Windows event channel.
``path`` is as its writer sees it: a file a container writes is named inside
that container. Whether anything reads the log is the consumer's question.
"""
kind: str # "journald", "file" or "container"
path: str | None # the file; None for a journal
kind: str # one of LOG_SOURCE_KINDS
path: str | None # the file (an event channel's .evtx); None for a journal
unit: str | None # the journal's unit, or the file writer's service; without ".service"
container_id: str | None # the full container ID: the writer's, or the stream's
process: str | None # the first process writing the file; None when only readers hold it
size: int | None # bytes; None for a journal, or when the file could not be read
modified: str | None # the last write, ISO 8601 UTC; None as for size
#: The event channel an "eventlog" source is read by -- ``System``,
#: ``Microsoft-Windows-Sysmon/Operational`` --, what a log reader names it by;
#: absent for the other kinds.
channel: NotRequired[str]
def eventlog_source(
channel: str, path: str | None, size: int | None, modified: float | None
) -> LogSourceDict:
"""A Windows event channel as a source: *path* its ``.evtx`` file, *size* in bytes,
*modified* its last write in unix seconds (NetOrk/netork#2897). No process holds it
for writing that a reading could name: the Event Log service writes them all."""
return {
"kind": EVENTLOG,
"path": path,
"unit": None,
"container_id": None,
"process": None,
"size": size,
"modified": None if modified is None else datetime.fromtimestamp(modified, UTC).isoformat(),
"channel": channel,
}
class LogSourcesDict(TypedDict):
@@ -75,7 +102,9 @@ class LogSourcesDict(TypedDict):
``attributed`` is False when the reading ran without root: only the login
user's own processes show their files then, so a missing log means "not
told", not "not there". ``journald`` is False on a host without systemd's
journal, where no unit has one.
journal, where no unit has one -- a Windows host among them, whose logs are
its event channels (``"eventlog"``). ``forwarding`` is None where the reading
cannot tell where the logs go.
"""
attributed: bool
+23 -1
View File
@@ -68,13 +68,35 @@ class PackageDict(TypedDict):
source: str
#: A service's last run ended as it should, or it has not ended (systemd's ``Result``).
SERVICE_RESULT_SUCCESS = "success"
#: A service's last run ended with an exit code that is not success.
SERVICE_RESULT_EXIT_CODE = "exit-code"
class ServiceDict(TypedDict):
"""A system service managed by the device's init system (e.g. procd on OpenWrt)."""
"""A system service managed by the device's init system (e.g. procd on OpenWrt).
The optional fields tell a service that died from one stopped on purpose
(NetOrk/netork#2897, #2703); a driver that cannot tell leaves them out.
"""
name: str
running: bool
enabled: bool
pid: int # 0 if not running
#: How its last run ended, in systemd's ``Result`` words: SERVICE_RESULT_SUCCESS,
#: SERVICE_RESULT_EXIT_CODE, ``signal``, ``core-dump``, ``timeout`` …; None where
#: it has not run since the host started.
result: NotRequired[str | None]
#: The code its last run ended with, where that was not success; else None.
exit_code: NotRequired[int | None]
#: Started by a trigger (a device, a network change, a request) and stopped when
#: idle, so that it is stopped while enabled says nothing.
trigger_start: NotRequired[bool]
#: The account it runs as: ``LocalSystem``, ``NT AUTHORITY\NetworkService``,
#: ``CORP\svc-backup``, ``www-data``; None where the driver does not say.
account: NotRequired[str | None]
class UpdateDict(TypedDict):
+8
View File
@@ -31,6 +31,14 @@ class ServiceControlMixin:
* enabled (bool) - ``True`` if the service starts automatically at boot
* pid (int) - process ID of the main service process; 0 if not running
Optional, where the driver can tell (NetOrk/netork#2897):
* result (str) - how its last run ended, in systemd's ``Result`` words
(``success``, ``exit-code``, ``signal`` ...); None if it has not run since boot
* exit_code (int) - the code its last run ended with where that was not success
* trigger_start (bool) - a trigger starts it and idleness stops it
* account (str) - the account it runs as
Example::
[