"""What the event log recorded that says something is wrong with the host (NetOrk/netork#2897). :class:`WindowsHostEventsMixin` implements napalm-device-types' :class:`~napalm_device_types.host_events.HostEventsMixin` for the driver, which carries the script across ``PsrpTransport.run``. **One script, three queries**, each an XPath filter over a fixed set of providers and event IDs, from the reading's start (``TimeCreated[@SystemTime>=…]``), newest first and bounded by count: * *rare*, the System log, with each event's message: Kernel-Power 41 and EventLog 6008 (an unexpected shutdown; 41's first property is the bugcheck code, 0 for a power loss), WER-SystemErrorReporting 1001 (a bugcheck, its stop code first), WHEA-Logger 18 (a fatal hardware error), disk 7 (a bad block) and Ntfs 55 (a corruption); * *frequent*, the System log without messages, which Windows formats slowly: WHEA-Logger 19 and 47 (corrected hardware errors), disk 153 (a retried I/O) and Service Control Manager 7031 and 7034 (a service that ended unexpectedly); * *apps*, the Application log without messages: Application Error 1000 (a program that crashed, its path the eleventh property). ``Get-WinEvent`` throws ``NoMatchingEventsFound`` when nothing matches, and under ``$ErrorActionPreference = 'Stop'`` that would fail the whole reading: each query catches it as no events. Any other failure costs only that query, whose kinds the reading names ``unread``; a query that returned its bound names its kinds ``capped``. **What an event is about** is taken from its properties, which do not depend on the host's language, never from its message, which does: the stop code, the disk or volume, the program's path (its name on a Windows that records no path), the service's display name. The message is kept as the host wrote it, cut short. """ from __future__ import annotations import time from collections.abc import Callable from datetime import UTC, datetime from typing import TYPE_CHECKING, Any from napalm_device_types import HOST_EVENT_KINDS, HostEventDict, HostEventsDict, HostEventsMixin from napalm_device_types import host_event as _event from napalm_device_types.host_events import ( APP_CRASH, DISK_ERROR, HARDWARE_ERROR_CORRECTED, HARDWARE_ERROR_FATAL, HOST_EVENT_MESSAGE_CHARS, HOST_EVENT_WINDOW_DAYS, SERVICE_CRASH, SYSTEM_CRASH, UNEXPECTED_SHUTDOWN, ) from napalm_windows._powershell import _as_list _KERNEL_POWER = "Microsoft-Windows-Kernel-Power" _BUGCHECK = "Microsoft-Windows-WER-SystemErrorReporting" _WHEA = "Microsoft-Windows-WHEA-Logger" _SCM = "Service Control Manager" _APP_ERROR = "Application Error" def _bugcheck(props: list[str]) -> str | None: """Kernel-Power 41's ``BugcheckCode``, a decimal number, as a stop code; 0 is none.""" word = props[0].strip() if props else "" return f"0x{int(word):08x}" if word.isdigit() and int(word) else None def _stop_code(props: list[str]) -> str | None: """1001's first property: ``0x0000009f (0x…, 0x…, 0x…, 0x…)``.""" word = props[0].split(maxsplit=1)[0] if props and props[0].strip() else "" return word or None def _first(props: list[str]) -> str | None: return props[0] if props else None def _program(props: list[str]) -> str | None: """Application Error 1000: its path where the host records one, else its name.""" path = props[10] if len(props) > 10 else "" return path.strip() or _first(props) def _none(props: list[str]) -> str | None: return None _Subject = Callable[[list[str]], str | None] #: (provider, event ID) -> the kind and what the event is about. _EVENTS: dict[tuple[str, int], tuple[str, _Subject]] = { (_KERNEL_POWER, 41): (UNEXPECTED_SHUTDOWN, _bugcheck), ("EventLog", 6008): (UNEXPECTED_SHUTDOWN, _none), (_BUGCHECK, 1001): (SYSTEM_CRASH, _stop_code), (_WHEA, 18): (HARDWARE_ERROR_FATAL, _none), (_WHEA, 19): (HARDWARE_ERROR_CORRECTED, _none), (_WHEA, 47): (HARDWARE_ERROR_CORRECTED, _none), ("disk", 7): (DISK_ERROR, _first), ("disk", 153): (DISK_ERROR, _first), ("Microsoft-Windows-Ntfs", 55): (DISK_ERROR, _first), ("Ntfs", 55): (DISK_ERROR, _first), (_SCM, 7031): (SERVICE_CRASH, _first), (_SCM, 7034): (SERVICE_CRASH, _first), (_APP_ERROR, 1000): (APP_CRASH, _program), } #: Each query's log, its events, its bound and whether it reads their messages. _QUERIES: dict[str, tuple[str, tuple[tuple[str, int], ...], int, bool]] = { "rare": ( "System", ( (_KERNEL_POWER, 41), ("EventLog", 6008), (_BUGCHECK, 1001), (_WHEA, 18), ("disk", 7), ("Microsoft-Windows-Ntfs", 55), ("Ntfs", 55), ), 100, True, ), "frequent": ( "System", ((_WHEA, 19), (_WHEA, 47), ("disk", 153), (_SCM, 7031), (_SCM, 7034)), 500, False, ), "apps": ("Application", ((_APP_ERROR, 1000),), 200, False), } #: The kinds each query reads, in the order of HOST_EVENT_KINDS. _PART_KINDS: dict[str, tuple[str, ...]] = { part: tuple(k for k in HOST_EVENT_KINDS if k in {_EVENTS[e][0] for e in events}) for part, (_log, events, _max, _message) in _QUERIES.items() } # Q runs one query: its events with their properties as strings, or why not. # $_ inside catch is the error; NoMatchingEventsFound is an empty log, not a failure. _PS_QUERY = rf""" $ErrorActionPreference = 'Stop' function Q($log, $xpath, $max, $withMessage) {{ try {{ $rows = @(Get-WinEvent -LogName $log -FilterXPath $xpath -MaxEvents $max | ForEach-Object {{ $m = $null if ($withMessage) {{ try {{ $m = [string]$_.Message }} catch {{ $m = $null }} if ($m.Length -gt {HOST_EVENT_MESSAGE_CHARS}) {{ $m = $m.Substring(0, {HOST_EVENT_MESSAGE_CHARS}) }} }} [pscustomobject]@{{ provider = $_.ProviderName id = [int]$_.Id time = ([DateTimeOffset]$_.TimeCreated).ToUnixTimeSeconds() props = @($_.Properties | Select-Object -First 11 | ForEach-Object {{ [string]$_.Value }}) message = $m }} }}) [pscustomobject]@{{ ok = $true; capped = ($rows.Count -ge $max); events = $rows }} }} catch {{ if ([string]$_.FullyQualifiedErrorId -like 'NoMatchingEventsFound*') {{ [pscustomobject]@{{ ok = $true; capped = $false; events = @() }} }} else {{ [pscustomobject]@{{ ok = $false; capped = $false; events = @(); error = [string]$_.Exception.Message }} }} }} }} """ def _xpath(events: tuple[tuple[str, int], ...], since: str) -> str: which = " or ".join(f"(Provider[@Name='{p}'] and EventID={i})" for p, i in events) return f"*[System[TimeCreated[@SystemTime>='{since}'] and ({which})]]" def host_events_script(since: float) -> str: """The reading's script, from *since* (unix seconds) on.""" start = datetime.fromtimestamp(since, UTC).strftime("%Y-%m-%dT%H:%M:%S.000Z") lines = [_PS_QUERY] parts = [] for part, (log, events, bound, message) in _QUERIES.items(): lines.append(f'${part} = "{_xpath(events, start)}"') parts.append(f" {part} = (Q '{log}' ${part} {bound} ${str(message).lower()})") lines.append("[pscustomobject]@{ parts = [pscustomobject]@{") lines.extend(parts) lines.append("} } | ConvertTo-Json -Compress -Depth 6") return "\n".join(lines) + "\n" def _parse_event(raw: dict[str, Any], source_log: str) -> HostEventDict | None: known = _EVENTS.get((str(raw.get("provider") or ""), int(raw.get("id") or 0))) if known is None: return None kind, subject = known props = [str(p) for p in _as_list(raw.get("props"))] source = f"{source_log}: {raw.get('provider')} {raw.get('id')}" return _event(kind, float(raw.get("time") or 0), source, subject(props), raw.get("message")) def _part(answer: Any, log: str) -> list[HostEventDict] | None: """One query's events; None when it was not read.""" if not isinstance(answer, dict) or not answer.get("ok"): return None found = (_parse_event(e, log) for e in _as_list(answer.get("events"))) return [e for e in found if e is not None] def _in_order(kinds: set[str]) -> list[str]: return [k for k in HOST_EVENT_KINDS if k in kinds] def _reading(raw: Any, since: float) -> HostEventsDict: if not isinstance(raw, dict) or not isinstance(raw.get("parts"), dict): raise ValueError("the host events reading came back without a report") events: list[HostEventDict] = [] capped: set[str] = set() unread: set[str] = set() for part, (log, _events, _bound, _message) in _QUERIES.items(): answer = raw["parts"].get(part) found = _part(answer, log) if found is None: unread.update(_PART_KINDS[part]) continue if answer.get("capped"): capped.update(_PART_KINDS[part]) events.extend(found) events.sort(key=lambda e: e["time"], reverse=True) return { "since": datetime.fromtimestamp(since, UTC).isoformat(), "events": events, "capped": _in_order(capped), "unread": _in_order(unread), } class WindowsHostEventsMixin(HostEventsMixin): """The event log's warnings-worthy events; the driver carries the script.""" if TYPE_CHECKING: # pragma: no cover - declared for type checkers only def _run_ps(self, script: str) -> Any: ... def get_host_events(self, since: float | None = None) -> HostEventsDict: """The events of ``HOST_EVENT_KINDS`` since *since* (unix seconds), by default over the last ``HOST_EVENT_WINDOW_DAYS`` days; one round trip, see the module. :raises ValueError: when the reading came back without a report. """ start = time.time() - HOST_EVENT_WINDOW_DAYS * 86400 if since is None else since return _reading(self._run_ps(host_events_script(start)), start)