diff --git a/napalm_windows/host_basics.py b/napalm_windows/host_basics.py new file mode 100644 index 0000000..694e6d0 --- /dev/null +++ b/napalm_windows/host_basics.py @@ -0,0 +1,14 @@ +"""What every host reports about itself, gathered for the driver (NetOrk/netork#2888-#2891). + +One mixin made of one module per reading, so the driver names a single base: + +* :mod:`napalm_windows.system_identity` -- ``get_system_identity`` +""" + +from __future__ import annotations + +from napalm_windows.system_identity import WindowsSystemIdentityMixin + + +class WindowsHostBasicsMixin(WindowsSystemIdentityMixin): + """The readings napalm-linux has as a matter of course; each module documents its own.""" diff --git a/napalm_windows/system_identity.py b/napalm_windows/system_identity.py new file mode 100644 index 0000000..f2c85a6 --- /dev/null +++ b/napalm_windows/system_identity.py @@ -0,0 +1,86 @@ +"""The SMBIOS identity of a Windows host: what ties it to its BMC (NetOrk/netork#2888). + +:class:`WindowsSystemIdentityMixin` gives the driver ``get_system_identity`` with the +shape and the placeholder rules of napalm-device-types' ``SystemIdentityMixin``, which +reads Linux' DMI files. Windows reads the same SMBIOS tables through its CIM classes, +in one script of its own -- not folded into ``get_facts``, so a class only the identity +needs cannot fail the facts: + +* ``Win32_ComputerSystemProduct``: ``UUID`` (the system UUID, which Windows decodes from + SMBIOS 2.6+ the way dmidecode does) and ``IdentifyingNumber`` (the product serial); +* ``Win32_BaseBoard``: ``SerialNumber``, of the first board; +* ``Win32_BIOS``: ``Manufacturer``, ``SMBIOSBIOSVersion`` and ``ReleaseDate``. CIM gives + the date as midnight UTC; it travels as Unix time and is read as that UTC day. + +Vendor placeholders ("To be filled by O.E.M.", all-F UUIDs) read as empty +(``clean_system_identity``). +""" + +from __future__ import annotations + +import json +from datetime import UTC, datetime +from typing import TYPE_CHECKING, Any + +from napalm_device_types import clean_system_identity +from napalm_device_types.system_identity import SystemIdentityDict + +_PS_SYSTEM_IDENTITY = r""" +$ErrorActionPreference = 'Stop' +$product = Get-CimInstance -ClassName Win32_ComputerSystemProduct +$board = @(Get-CimInstance -ClassName Win32_BaseBoard) | Select-Object -First 1 +$bios = Get-CimInstance -ClassName Win32_BIOS +[pscustomobject]@{ + uuid = [string]$product.UUID + product_serial = [string]$product.IdentifyingNumber + board_serial = if ($board) { [string]$board.SerialNumber } else { $null } + bios_vendor = [string]$bios.Manufacturer + bios_version = [string]$bios.SMBIOSBIOSVersion + bios_date = if ($bios.ReleaseDate) { + ([DateTimeOffset]$bios.ReleaseDate).ToUnixTimeSeconds() + } else { $null } +} | ConvertTo-Json -Compress +""" + + +def _text(raw: dict[str, Any], key: str) -> str: + return str(raw.get(key) or "") + + +def _utc_day(value: Any) -> str: + """Unix time as its UTC day, ``YYYY-MM-DD``; empty for none.""" + if not isinstance(value, int | float) or isinstance(value, bool): + return "" + return datetime.fromtimestamp(value, UTC).date().isoformat() + + +def parse_system_identity(raw: dict[str, Any]) -> SystemIdentityDict: + """``_PS_SYSTEM_IDENTITY``'s JSON as napalm-device-types' identity, placeholders empty.""" + return clean_system_identity( + system_uuid=_text(raw, "uuid"), + product_serial=_text(raw, "product_serial"), + board_serial=_text(raw, "board_serial"), + bios_vendor=_text(raw, "bios_vendor"), + bios_version=_text(raw, "bios_version"), + bios_date=_utc_day(raw.get("bios_date")), + ) + + +class WindowsSystemIdentityMixin: + """``get_system_identity`` from the CIM classes; the driver carries the script.""" + + if TYPE_CHECKING: # pragma: no cover - declared for type checkers only + + def _run_raw(self, script: str) -> str: ... + + def get_system_identity(self) -> SystemIdentityDict: + """The host's SMBIOS identity and system firmware, each value empty when unknown + or a vendor placeholder; see the module. + + :raises ValueError: when the reading came back empty. + """ + out = self._run_raw(_PS_SYSTEM_IDENTITY).strip() + raw = json.loads(out) if out else None + if not isinstance(raw, dict): + raise ValueError("the system identity reading came back empty") + return parse_system_identity(raw) diff --git a/napalm_windows/windows.py b/napalm_windows/windows.py index fbd26dd..fb7e465 100644 --- a/napalm_windows/windows.py +++ b/napalm_windows/windows.py @@ -27,6 +27,7 @@ from napalm_device_types import FingerprintRule, OSDriver, PortSpec from napalm_device_types.models import ListeningSocketDict, ListeningSocketsDict, ServiceDict from napalm_windows._powershell import _as_list, _ps_quote +from napalm_windows.host_basics import WindowsHostBasicsMixin from napalm_windows.scheduled_tasks import WindowsScheduledJobsMixin from napalm_windows.time_sync import WindowsTimeSyncMixin from napalm_windows.transport import PowerShellError, PsrpTransport @@ -261,7 +262,9 @@ def _is_noise_route(destination: str) -> bool: # --------------------------------------------------------------------------- -class WindowsDriver(WindowsScheduledJobsMixin, WindowsTimeSyncMixin, OSDriver): +class WindowsDriver( + WindowsHostBasicsMixin, WindowsScheduledJobsMixin, WindowsTimeSyncMixin, OSDriver +): """NAPALM driver for Windows Server 2016+ and Windows 10/11. ``optional_args``: diff --git a/tests/fixtures/synthetic/system_identity.json b/tests/fixtures/synthetic/system_identity.json new file mode 100644 index 0000000..a953853 --- /dev/null +++ b/tests/fixtures/synthetic/system_identity.json @@ -0,0 +1 @@ +{"uuid":"4C4C4544-0042-3510-8051-B4C04F4D3732","product_serial":"4B5QM72","board_serial":".4B5QM72.CNCMS0012345AB.","bios_vendor":"Dell Inc.","bios_version":"2.19.0","bios_date":1692057600} diff --git a/tests/test_system_identity.py b/tests/test_system_identity.py new file mode 100644 index 0000000..424b02f --- /dev/null +++ b/tests/test_system_identity.py @@ -0,0 +1,93 @@ +"""The SMBIOS identity on Windows: CIM classes instead of the DMI files (NetOrk/netork#2888). + +One script reads ``Win32_ComputerSystemProduct``, ``Win32_BaseBoard`` and ``Win32_BIOS``; +a fake transport answers it from tests/fixtures/synthetic/system_identity.json, a Dell +server as the classes describe it. The placeholders are napalm-device-types' own +(``clean_system_identity``). +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest + +from napalm_windows import WindowsDriver +from napalm_windows import system_identity as mod + +FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "system_identity.json" + + +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(**changes: Any) -> WindowsDriver: + d = WindowsDriver("win01", "admin", "secret") + d._transport = FakeTransport(json.dumps({**json.loads(FIXTURE.read_text()), **changes})) + return d + + +def test_reads_the_identity_and_the_firmware(): + assert _driver().get_system_identity() == { + "system_uuid": "4c4c4544-0042-3510-8051-b4c04f4d3732", + "product_serial": "4B5QM72", + "board_serial": ".4B5QM72.CNCMS0012345AB.", + "bios_vendor": "Dell Inc.", + "bios_version": "2.19.0", + "bios_date": "2023-08-15", + } + + +def test_one_script_reads_the_three_classes(): + d = _driver() + d.get_system_identity() + (script,) = d._transport.sent # type: ignore[union-attr] + assert script == mod._PS_SYSTEM_IDENTITY + for cls in ("Win32_ComputerSystemProduct", "Win32_BaseBoard", "Win32_BIOS"): + assert cls in script + + +@pytest.mark.parametrize( + ("field", "value"), + [ + ("product_serial", "To be filled by O.E.M."), + ("board_serial", "Default string"), + ("uuid", "FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF"), + ("uuid", "03000200-0400-0500-0006-000700080009"), + ("bios_vendor", "To be filled by O.E.M."), + ], +) +def test_oem_placeholders_read_as_empty(field, value): + identity = _driver(**{field: value}).get_system_identity() + key = {"uuid": "system_uuid"}.get(field, field) + assert identity[key] == "" # type: ignore[literal-required] + + +@pytest.mark.parametrize("field", ["uuid", "product_serial", "board_serial", "bios_date"]) +def test_a_value_the_host_did_not_give_reads_as_empty(field): + # A VM without a base board, a firmware without a release date: null in the JSON. + identity = _driver(**{field: None}).get_system_identity() + key = {"uuid": "system_uuid"}.get(field, field) + assert identity[key] == "" # type: ignore[literal-required] + + +def test_the_release_date_is_the_utc_day(): + # CIM gives the SMBIOS date as midnight UTC; the script sends it as Unix time. + assert _driver(bios_date=1692057600 + 86399).get_system_identity()["bios_date"] == "2023-08-15" + + +def test_an_empty_answer_is_no_reading(): + d = WindowsDriver("win01", "admin", "secret") + d._transport = FakeTransport("") + with pytest.raises(ValueError): + d.get_system_identity()