WindowsHostEventsMixin.get_host_events(since=None) reads, in one script, three bounded queries over the window: the System log's rare events (Kernel-Power 41, EventLog 6008, WER-SystemErrorReporting 1001, WHEA-Logger 18, disk 7, Ntfs 55) with their messages, its frequent ones (WHEA-Logger 19/47, disk 153, Service Control Manager 7031/7034) and the Application log's crashes (Application Error 1000). Each query catches NoMatchingEventsFound; one that fails names its kinds unread, one read up to its bound names them capped.
207 lines
8.0 KiB
Python
207 lines
8.0 KiB
Python
"""What the event log recorded that says something is wrong with the host (NetOrk/netork#2897).
|
|
|
|
One script asks the event log three questions over the reading's window: the rare
|
|
events of the System log (an unexpected shutdown, a bugcheck, a fatal hardware
|
|
error, a bad block, a file system corruption), its frequent ones (corrected
|
|
hardware errors, retried disk I/O, services that ended unexpectedly) and the
|
|
Application log's crashing programs. Each is bounded by time and count, and each
|
|
catches ``NoMatchingEventsFound``: ``Get-WinEvent`` throws when nothing matches. The
|
|
answer is the shape of tests/fixtures/synthetic/host_events.json.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import re
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
import pytest
|
|
from napalm_device_types import HOST_EVENT_KINDS, HostEventsMixin
|
|
|
|
from napalm_windows import WindowsDriver
|
|
from napalm_windows import host_events as mod
|
|
|
|
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "host_events.json"
|
|
NOW = 1764500000.0
|
|
WEEK = 7 * 86400
|
|
|
|
|
|
class FakeTransport:
|
|
def __init__(self, answer: str) -> None:
|
|
self.answer = answer
|
|
self.sent: list[str] = []
|
|
self.is_open = True
|
|
|
|
def run(self, script: str) -> str:
|
|
self.sent.append(script)
|
|
return self.answer
|
|
|
|
|
|
def _driver(answer: dict[str, Any] | str | None = None) -> WindowsDriver:
|
|
if answer is None:
|
|
answer = FIXTURE.read_text()
|
|
d = WindowsDriver("win01", "admin", "secret")
|
|
d._transport = FakeTransport(answer if isinstance(answer, str) else json.dumps(answer))
|
|
return d
|
|
|
|
|
|
def _fixture() -> dict[str, Any]:
|
|
return json.loads(FIXTURE.read_text())
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _now(monkeypatch):
|
|
monkeypatch.setattr(mod.time, "time", lambda: NOW)
|
|
|
|
|
|
def _kinds(reading) -> list[tuple[str, str | None]]:
|
|
return [(e["kind"], e["subject"]) for e in reading["events"]]
|
|
|
|
|
|
class TestTheEvents:
|
|
def test_every_event_as_its_kind_and_subject_newest_first(self):
|
|
assert _kinds(_driver().get_host_events()) == [
|
|
("app_crash", r"C:\Program Files\Vendor\vendorapp.exe"),
|
|
("app_crash", r"C:\Program Files\Vendor\vendorapp.exe"),
|
|
("app_crash", "legacy.exe"),
|
|
("service_crash", "Backup Agent"),
|
|
("hardware_error_corrected", None),
|
|
("disk_error", r"\Device\Harddisk1\DR1"),
|
|
("service_crash", "Vendor Sync"),
|
|
("hardware_error_corrected", None),
|
|
("system_crash", "0x0000009f"),
|
|
("unexpected_shutdown", None),
|
|
("unexpected_shutdown", "0x0000009f"),
|
|
("disk_error", r"\Device\Harddisk1\DR1"),
|
|
("disk_error", "D:"),
|
|
("hardware_error_fatal", None),
|
|
("unexpected_shutdown", None),
|
|
]
|
|
|
|
def test_an_event_says_when_where_and_what_the_host_wrote(self):
|
|
crash = next(
|
|
e for e in _driver().get_host_events()["events"] if e["kind"] == "system_crash"
|
|
)
|
|
assert crash == {
|
|
"kind": "system_crash",
|
|
"time": "2025-11-30T02:35:50+00:00",
|
|
"subject": "0x0000009f",
|
|
"source": "System: Microsoft-Windows-WER-SystemErrorReporting 1001",
|
|
"message": crash["message"],
|
|
}
|
|
assert crash["message"].startswith("The computer has rebooted from a bugcheck.")
|
|
|
|
def test_a_power_loss_without_a_bugcheck_has_no_stop_code(self):
|
|
shutdowns = [
|
|
e for e in _driver().get_host_events()["events"] if e["kind"] == "unexpected_shutdown"
|
|
]
|
|
assert [e["subject"] for e in shutdowns] == [None, "0x0000009f", None]
|
|
|
|
def test_the_hosts_message_is_cut(self):
|
|
answer = _fixture()
|
|
answer["parts"]["rare"]["events"][0]["message"] = "y" * 5000
|
|
events = _driver(answer).get_host_events()["events"]
|
|
assert max(len(e["message"] or "") for e in events) == 300
|
|
|
|
def test_an_event_the_reading_does_not_know_is_left_out(self):
|
|
answer = _fixture()
|
|
answer["parts"]["rare"]["events"] = [
|
|
{"provider": "Microsoft-Windows-Kernel-General", "id": 12, "time": NOW, "props": []}
|
|
]
|
|
kinds = {e["kind"] for e in _driver(answer).get_host_events()["events"]}
|
|
assert "unexpected_shutdown" not in kinds
|
|
|
|
def test_a_single_event_is_still_a_list(self):
|
|
answer = _fixture()
|
|
answer["parts"]["apps"]["events"] = answer["parts"]["apps"]["events"][0]
|
|
apps = [e for e in _driver(answer).get_host_events()["events"] if e["kind"] == "app_crash"]
|
|
assert len(apps) == 1
|
|
|
|
|
|
class TestWhatWasRead:
|
|
def test_a_full_reading_names_nothing_capped_or_unread(self):
|
|
reading = _driver().get_host_events()
|
|
assert (reading["capped"], reading["unread"]) == ([], [])
|
|
|
|
def test_an_empty_log_is_no_events_not_an_error(self):
|
|
"""What the script makes of ``NoMatchingEventsFound``: read, nothing found."""
|
|
answer = _fixture()
|
|
for part in answer["parts"].values():
|
|
part["events"] = []
|
|
reading = _driver(answer).get_host_events()
|
|
assert (reading["events"], reading["unread"]) == ([], [])
|
|
|
|
def test_a_query_that_failed_names_its_kinds_unread(self):
|
|
answer = _fixture()
|
|
answer["parts"]["frequent"] = {"ok": False, "capped": False, "events": [], "error": "x"}
|
|
reading = _driver(answer).get_host_events()
|
|
assert reading["unread"] == ["hardware_error_corrected", "disk_error", "service_crash"]
|
|
assert "service_crash" not in {e["kind"] for e in reading["events"]}
|
|
|
|
def test_a_query_read_up_to_its_bound_names_its_kinds_capped(self):
|
|
answer = _fixture()
|
|
answer["parts"]["apps"]["capped"] = True
|
|
assert _driver(answer).get_host_events()["capped"] == ["app_crash"]
|
|
|
|
def test_a_part_missing_from_the_answer_is_unread(self):
|
|
answer = _fixture()
|
|
del answer["parts"]["apps"]
|
|
assert _driver(answer).get_host_events()["unread"] == ["app_crash"]
|
|
|
|
def test_every_kind_is_read_by_some_query(self):
|
|
read = {kind for kinds in mod._PART_KINDS.values() for kind in kinds}
|
|
assert read == set(HOST_EVENT_KINDS)
|
|
|
|
@pytest.mark.parametrize("answer", ["", "[]", '{"since": 1}'])
|
|
def test_an_answer_without_a_report_raises(self, answer):
|
|
with pytest.raises(ValueError):
|
|
_driver(answer).get_host_events()
|
|
|
|
|
|
class TestTheWindow:
|
|
def test_a_week_by_default(self):
|
|
d = _driver()
|
|
reading = d.get_host_events()
|
|
assert reading["since"] == "2025-11-23T10:53:20+00:00"
|
|
assert "@SystemTime>='2025-11-23T10:53:20.000Z'" in d._transport.sent[0]
|
|
|
|
def test_the_callers_start(self):
|
|
d = _driver()
|
|
reading = d.get_host_events(since=NOW - 3600)
|
|
assert reading["since"] == "2025-11-30T09:53:20+00:00"
|
|
assert "@SystemTime>='2025-11-30T09:53:20.000Z'" in d._transport.sent[0]
|
|
|
|
|
|
class TestTheScript:
|
|
script = mod.host_events_script(NOW - WEEK)
|
|
|
|
def test_every_query_catches_no_matching_events(self):
|
|
assert self.script.count("Get-WinEvent") == 1
|
|
assert "NoMatchingEventsFound" in self.script
|
|
assert len(re.findall(r"\(Q '(System|Application)'", self.script)) == 3
|
|
|
|
def test_every_query_is_bounded_by_count(self):
|
|
bounds = [int(n) for n in re.findall(r"\(Q '\w+' \$\w+ (\d+)", self.script)]
|
|
assert bounds == [100, 500, 200]
|
|
assert "-MaxEvents $max" in self.script
|
|
|
|
def test_every_query_is_bounded_by_time(self):
|
|
assert self.script.count("TimeCreated[@SystemTime>=") == 3
|
|
|
|
def test_only_the_rare_events_carry_their_message(self):
|
|
assert re.findall(r"\(Q '\w+' \$\w+ \d+ \$(true|false)\)", self.script) == [
|
|
"true",
|
|
"false",
|
|
"false",
|
|
]
|
|
|
|
def test_the_answer_survives_a_deep_object(self):
|
|
assert "-Depth 6" in self.script
|
|
|
|
def test_stops_on_errors_it_does_not_catch(self):
|
|
assert self.script.lstrip().startswith("$ErrorActionPreference = 'Stop'")
|
|
|
|
def test_the_driver_carries_the_contract(self):
|
|
assert isinstance(WindowsDriver("h", "u", "p"), HostEventsMixin)
|