From 6c273ea346a4baf20b35d3607059e130d15fe282 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Tue, 1 Dec 2026 12:48:09 +0100 Subject: [PATCH] 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. --- CHANGELOG.md | 18 ++++ README.md | 25 +++++ napalm_device_types/__init__.py | 29 ++++++ napalm_device_types/host_events.py | 157 +++++++++++++++++++++++++++++ napalm_device_types/log_sources.py | 41 ++++++-- napalm_device_types/models.py | 24 ++++- napalm_device_types/services.py | 8 ++ tests/test_eventlog_sources.py | 50 +++++++++ tests/test_host_events.py | 90 +++++++++++++++++ tests/test_service_result.py | 23 +++++ 10 files changed, 458 insertions(+), 7 deletions(-) create mode 100644 napalm_device_types/host_events.py create mode 100644 tests/test_eventlog_sources.py create mode 100644 tests/test_host_events.py create mode 100644 tests/test_service_result.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 847c85a..05753c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,24 @@ recorded here; their history is the git log. ## [Unreleased] +### Added +- `HostEventsMixin.get_host_events(since=None)`, declared: what a host's own log recorded + that says something is wrong with it (NetOrk/netork#2897), for an application that warns + of it. A fixed set of kinds (`HOST_EVENT_KINDS`): unexpected shutdowns, system crashes + with their stop code, fatal and corrected hardware errors, disk and file system errors, + programs and services that crashed. Each `HostEventDict` names its kind, time (ISO, UTC), + what it is about in words that do not depend on the host's language, where it was + recorded and the host's message, cut to `HOST_EVENT_MESSAGE_CHARS`; `host_event()` builds + one. The reading covers `HOST_EVENT_WINDOW_DAYS` (7) days by default and says which kinds + it read up to its bound (`capped`) and which it could not read (`unread`). +- Log sources of kind `"eventlog"`: a Windows event channel, named by the new optional + `LogSourceDict.channel`, with its `.evtx` file as `path` (`eventlog_source()`, + `LOG_SOURCE_KINDS`, `EVENTLOG`). +- `ServiceDict` says how a service's last run ended, all optional: `result` in systemd's + `Result` words (`SERVICE_RESULT_SUCCESS`, `SERVICE_RESULT_EXIT_CODE`), `exit_code`, + `trigger_start` and the `account` it runs as, so that a service that died is told from + one stopped on purpose. `ServiceDict` is exported from the package. + ## [4.55.0] - 2026-12-01 ### Added diff --git a/README.md b/README.md index 8248567..b06688d 100644 --- a/README.md +++ b/README.md @@ -412,6 +412,31 @@ driver mixes it in and supplies `run_command`. list only when nothing is pending; netOrk keeps "pending since" per package, and an empty list for "don't know" would reset it. +A Windows host has no journal and no log files a process holds open: its logs are its event +channels. A driver for it implements `get_log_sources` itself and lists each channel as a +source of kind `"eventlog"` (`eventlog_source(channel, path, size, modified)`, one of +`LOG_SOURCE_KINDS`), named by `channel` -- the name a log reader takes (CrowdSec's +`event_channel`, Wazuh's `eventchannel`) -- with its `.evtx` file as `path`. `journald` is +False there and `forwarding` None. + +`HostEventsMixin` (`get_host_events(since=None)`) only declares: what a host's own log +recorded that says something is wrong with it, read from its event log or its journal by the +driver. A fixed set of kinds (`HOST_EVENT_KINDS`: an unexpected shutdown, a system crash with +its stop code, a fatal or a corrected hardware error, a disk or file system error, a program's +or a service's crash), never the log itself; each event with its time, what it is about in +words that do not depend on the host's language (`subject`), where it was recorded and the +host's message cut to `HOST_EVENT_MESSAGE_CHARS` (`host_event()` builds one). The reading +covers `HOST_EVENT_WINDOW_DAYS` days unless the caller names a start; `capped` names the kinds +read up to the driver's bound, `unread` those it could not read this time. Whether an event is +a problem is the application's to decide. + +`ServiceDict` says, beside whether a service runs, how its last run ended where the driver can +tell (all optional): `result` in systemd's `Result` words (`SERVICE_RESULT_SUCCESS`, +`SERVICE_RESULT_EXIT_CODE`, `signal` …; None where it has not run since the host started), +`exit_code`, `trigger_start` for a service a trigger starts and idleness stops, and the +`account` it runs as. A service that is enabled, not running and whose last run did not +succeed has failed; one stopped on purpose has not. + `SystemdServicesMixin` (`get_services`, `manage_service`) is mixed in the same way, by the drivers whose host runs systemd. Listing the services, checking a unit name and reading an action's exit status are the same on every such host, so they are concrete diff --git a/napalm_device_types/__init__.py b/napalm_device_types/__init__.py index b6ff305..7867fbd 100644 --- a/napalm_device_types/__init__.py +++ b/napalm_device_types/__init__.py @@ -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", diff --git a/napalm_device_types/host_events.py b/napalm_device_types/host_events.py new file mode 100644 index 0000000..fd01a63 --- /dev/null +++ b/napalm_device_types/host_events.py @@ -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. + """ + ... diff --git a/napalm_device_types/log_sources.py b/napalm_device_types/log_sources.py index cdb6a26..53d0225 100644 --- a/napalm_device_types/log_sources.py +++ b/napalm_device_types/log_sources.py @@ -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 diff --git a/napalm_device_types/models.py b/napalm_device_types/models.py index 60f6744..678c0fe 100644 --- a/napalm_device_types/models.py +++ b/napalm_device_types/models.py @@ -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): diff --git a/napalm_device_types/services.py b/napalm_device_types/services.py index 5e43ec2..912efa6 100644 --- a/napalm_device_types/services.py +++ b/napalm_device_types/services.py @@ -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:: [ diff --git a/tests/test_eventlog_sources.py b/tests/test_eventlog_sources.py new file mode 100644 index 0000000..35d76c3 --- /dev/null +++ b/tests/test_eventlog_sources.py @@ -0,0 +1,50 @@ +"""A Windows event channel as a log source (NetOrk/netork#2897). + +A Windows host keeps its logs in event channels (``System``, ``Security``, +``Microsoft-Windows-Sysmon/Operational``), not in a journal or in files a process +holds open. A log reader takes a channel by its name -- CrowdSec's +``event_channel``, Wazuh's ``eventchannel`` -- so a channel is a source of its own +kind, named by its channel; ``path`` is the ``.evtx`` file behind it. +""" + +from __future__ import annotations + +from typing import NotRequired, get_origin, get_type_hints + +from napalm_device_types import EVENTLOG, LOG_SOURCE_KINDS, LogSourceDict, eventlog_source + + +def test_the_kinds_a_source_can_be(): + assert LOG_SOURCE_KINDS == ("journald", "file", "container", "eventlog") + assert EVENTLOG == "eventlog" + + +def test_a_channel_is_named_by_its_channel(): + source = eventlog_source( + "Microsoft-Windows-Sysmon/Operational", + r"C:\Windows\System32\Winevt\Logs\Microsoft-Windows-Sysmon%4Operational.evtx", + 1052672, + 1764583200, + ) + assert source == { + "kind": "eventlog", + "path": r"C:\Windows\System32\Winevt\Logs\Microsoft-Windows-Sysmon%4Operational.evtx", + "unit": None, + "container_id": None, + "process": None, + "size": 1052672, + "modified": "2025-12-01T10:00:00+00:00", + "channel": "Microsoft-Windows-Sysmon/Operational", + } + + +def test_a_channel_without_a_file_or_a_last_write_says_none(): + source = eventlog_source("Application", None, None, None) + assert (source["path"], source["size"], source["modified"]) == (None, None, None) + + +def test_the_channel_is_optional_for_the_other_kinds(): + """Additive: a journal, a file and a container's stream carry no channel.""" + hints = get_type_hints(LogSourceDict, include_extras=True) + assert get_origin(hints["channel"]) is NotRequired + assert get_origin(hints["kind"]) is None diff --git a/tests/test_host_events.py b/tests/test_host_events.py new file mode 100644 index 0000000..763cf02 --- /dev/null +++ b/tests/test_host_events.py @@ -0,0 +1,90 @@ +"""get_host_events: what a host's own log recorded that says something is wrong with it. + +A crash, a power loss, a hardware error or a program that keeps dying is written +down by the host itself, in its event log or its journal; nothing on the outside +sees it. The reading is the same shape for every operating system: each event as +its kind, when, what it is about and where the host recorded it. Whether that is +a problem is the application's to decide (NetOrk/netork#2897). +""" + +from __future__ import annotations + +from typing import get_type_hints + +import pytest + +from napalm_device_types import ( + HOST_EVENT_KINDS, + HOST_EVENT_MESSAGE_CHARS, + HOST_EVENT_WINDOW_DAYS, + HostEventDict, + HostEventsDict, + HostEventsMixin, + host_event, +) + + +class TestTheKinds: + def test_every_kind_the_contract_names(self): + assert HOST_EVENT_KINDS == ( + "unexpected_shutdown", + "system_crash", + "hardware_error_fatal", + "hardware_error_corrected", + "disk_error", + "app_crash", + "service_crash", + ) + + def test_the_window_is_a_week(self): + assert HOST_EVENT_WINDOW_DAYS == 7 + + +class TestHostEvent: + def test_the_time_is_iso_in_utc(self): + event = host_event("system_crash", 1764583200, "System: BugCheck 1001", "0x0000009f") + assert event == { + "kind": "system_crash", + "time": "2025-12-01T10:00:00+00:00", + "subject": "0x0000009f", + "source": "System: BugCheck 1001", + "message": None, + } + + def test_the_message_is_cut_to_its_limit(self): + event = host_event("disk_error", 0, "System: disk 7", None, "x" * 1000) + assert event["message"] == "x" * HOST_EVENT_MESSAGE_CHARS + + def test_the_message_keeps_its_words_without_the_surrounding_space(self): + event = host_event("disk_error", 0, "System: disk 7", None, " bad block\r\n ") + assert event["message"] == "bad block" + + @pytest.mark.parametrize("empty", ["", " ", None]) + def test_an_empty_subject_or_message_is_none(self, empty): + event = host_event("app_crash", 0, "Application: Application Error 1000", empty, empty) + assert event["subject"] is None + assert event["message"] is None + + def test_an_unknown_kind_is_refused(self): + with pytest.raises(ValueError, match="bluescreen"): + host_event("bluescreen", 0, "System", None) + + +class TestTheContract: + def test_the_getter_is_declared_only(self): + """A contract: nothing at runtime until a driver implements it, so + ``hasattr(driver, "get_host_events")`` stays truthful.""" + assert not hasattr(HostEventsMixin(), "get_host_events") + + def test_the_reading_says_what_it_could_not_read(self): + hints = get_type_hints(HostEventsDict) + assert set(hints) == {"since", "events", "capped", "unread"} + + def test_an_event_names_its_kind_time_subject_source_and_message(self): + assert set(get_type_hints(HostEventDict)) == { + "kind", + "time", + "subject", + "source", + "message", + } diff --git a/tests/test_service_result.py b/tests/test_service_result.py new file mode 100644 index 0000000..8d7c189 --- /dev/null +++ b/tests/test_service_result.py @@ -0,0 +1,23 @@ +"""How a service's last run ended, beside whether it runs (NetOrk/netork#2897, #2703). + +``running=False`` alone does not tell a service that died from one stopped on +purpose. The service manager knows: systemd's ``Result`` (``exit-code``, +``signal``, ``core-dump``, ``timeout`` …), Windows' exit code of the service. So +:class:`ServiceDict` carries the result in systemd's words, the exit code where +there is one, whether the service only runs when a trigger starts it, and the +account it runs as. All optional: a driver that cannot tell leaves them out. +""" + +from __future__ import annotations + +from napalm_device_types import SERVICE_RESULT_EXIT_CODE, SERVICE_RESULT_SUCCESS, ServiceDict + + +def test_the_result_is_said_in_systemds_words(): + assert SERVICE_RESULT_SUCCESS == "success" + assert SERVICE_RESULT_EXIT_CODE == "exit-code" + + +def test_the_new_fields_are_optional(): + assert ServiceDict.__required_keys__ == {"name", "running", "enabled", "pid"} + assert ServiceDict.__optional_keys__ == {"result", "exit_code", "trigger_start", "account"}