diff --git a/CHANGELOG.md b/CHANGELOG.md index 6dc89a7..435840f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added +- `get_time_sync()` and `configure_time_sync()` through napalm-device-types' + `TimeSyncMixin` (4.35.0) on the `redfish` and `bmc` drivers: the BMC's NTP servers + from `Managers/{id}/NetworkProtocol` (`NTP.NTPServers`), written with a PATCH that + carries the resource's `@odata.etag` as `If-Match` and turns `NTP.ProtocolEnabled` + on where it is off (NetOrk/netork#2367). An array that shows empty slots keeps its + length (the rest stay empty) and more servers than slots are refused before + anything is written; servers the BMC already uses are not written again. + `time_sync_writes` is `{"ntp_servers"}`: a BMC runs on UTC or an offset, so the + zone is read only where the manager names an IANA zone (`TimeZoneName`) and never + written. A BMC whose Redfish has no NTP block (Supermicro X10) cannot tell and + raises. `ipmi` has no time sync; `bmc` has it over Redfish only. +- `RedfishTransport.patch()`, with an optional `If-Match` ETag. + ### Changed +- `get_ntp_servers()` reports no servers while the BMC's NTP is off: they are not in + use, and `get_time_sync()` says the same. +- Needs napalm-device-types 4.35.0. - Python 3.12 is the floor (`requires-python = ">=3.12"`): netOrk runs every driver on 3.12, so 3.10 and 3.11 are no longer tested (NAPALM/driver-standard#6). - The floor on napalm is 5.1: older releases import `pkg_resources`, which a Python diff --git a/docs/redfish-map.md b/docs/redfish-map.md index b08434e..b92c37d 100644 --- a/docs/redfish-map.md +++ b/docs/redfish-map.md @@ -21,7 +21,7 @@ must follow the collections instead of assuming IDs, because vendors differ (Del | `get_interfaces_ip` | same | `IPv4Addresses`, `IPv6Addresses` | | `get_environment` | `Chassis/{id}/Thermal` (`Temperatures[]`, `Fans[]`), `Chassis/{id}/Power` (`PowerSupplies[]`, `PowerControl[].PowerConsumedWatts`) | Newer services move these to `ThermalSubsystem`, `PowerSubsystem` and `Sensors`; read whichever exists. CPU and memory of the host OS are unknown to a BMC | | `get_users` | `AccountService/Accounts/*` | `UserName`, `RoleId`, `Enabled` | -| `get_ntp_servers` | `Managers/{id}/NetworkProtocol` | `NTP.NTPServers` (newer schema versions only) | +| `get_ntp_servers` | `Managers/{id}/NetworkProtocol` | `NTP.NTPServers` (newer schema versions only); none while `NTP.ProtocolEnabled` is false | | `get_snmp_information` | `Managers/{id}/NetworkProtocol` | `SNMP.ProtocolEnabled` (details vary) | | `get_config` | n/a | A BMC has no configuration file. Not implemented | @@ -37,6 +37,13 @@ must follow the collections instead of assuming IDs, because vendors differ (Del | `get_firmware_inventory` | `UpdateService/FirmwareInventory/*`: `Name`, `Version`, `Updateable` | | `get_management_protocols` | `Managers/{id}/NetworkProtocol`: `HTTP`, `HTTPS`, `SSH`, `IPMI`, `SNMP`, `KVMIP`, `VirtualMedia`, `SSDP`, each with `ProtocolEnabled` and `Port` | +## Time sync (napalm-device-types' `TimeSyncMixin`) + +| Method | Resource | +|---|---| +| `get_time_sync` | `Managers/{id}/NetworkProtocol`: `NTP.NTPServers` (empty slots dropped; none while `NTP.ProtocolEnabled` is false). `timezone` is `Managers/{id}` `TimeZoneName` (Manager v1.10) where that is an IANA zone, else none: `DateTimeLocalOffset` is an offset, not a zone. A `NetworkProtocol` without an `NTP` block (Supermicro X10, `v1_0_0`) raises | +| `configure_time_sync` | `PATCH Managers/{id}/NetworkProtocol` with `{"NTP": {"NTPServers": [...]}}` and `If-Match: <@odata.etag>` where the resource has one; `ProtocolEnabled: true` too where NTP is off. An array that shows empty slots (`""`, null; three on an iDRAC 9, two on an iLO 5) has a fixed length: the servers fill it, the rest keep the empty value, and more servers than slots are refused before the PATCH. Only the servers are written (`time_sync_writes == {"ntp_servers"}`): BMCs run on UTC or an offset. The `ipmi` driver has no time sync; `bmc` has it over Redfish only | + ## IPMI fallback (`ipmi` entry point) Via `pyghmi`: device ID and FRU data for `get_facts`, sensor data repository for diff --git a/napalm_redfish/bmc.py b/napalm_redfish/bmc.py index 6fd5d4f..c742683 100644 --- a/napalm_redfish/bmc.py +++ b/napalm_redfish/bmc.py @@ -24,6 +24,8 @@ from typing import Any from napalm.base.exceptions import ConnectionException from napalm_device_types import HealthMetricsMixin, LicenseMixin, ManagementControllerDriver +from napalm_device_types.models import FixStepOutcomeDict +from napalm_device_types.time_sync import TimeSyncDict, TimeSyncMixin from napalm_redfish.driver import BMC_HTTP_FINGERPRINT, BMC_PORT_SPECS, RedfishDriver from napalm_redfish.ipmi import IpmiDriver @@ -35,8 +37,11 @@ _JsonDict = dict[str, Any] _IPMI_PORT = 623 -class BmcDriver(HealthMetricsMixin, LicenseMixin, ManagementControllerDriver): - """One BMC over Redfish and IPMI: Redfish first, IPMI where Redfish does not answer.""" +class BmcDriver(HealthMetricsMixin, LicenseMixin, TimeSyncMixin, ManagementControllerDriver): + """One BMC over Redfish and IPMI: Redfish first, IPMI where Redfish does not answer. + + Time sync is Redfish's alone: IPMI has no NTP settings. + """ platform = "bmc" DRIVER_NAME = "bmc" @@ -46,6 +51,7 @@ class BmcDriver(HealthMetricsMixin, LicenseMixin, ManagementControllerDriver): HTTP_FINGERPRINT = BMC_HTTP_FINGERPRINT #: A BMC restart takes a few minutes before Redfish answers again. REBOOT_SETTLE_SECONDS = RedfishDriver.REBOOT_SETTLE_SECONDS + time_sync_writes = RedfishDriver.time_sync_writes def __init__( self, @@ -136,6 +142,15 @@ class BmcDriver(HealthMetricsMixin, LicenseMixin, ManagementControllerDriver): def get_snmp_information(self) -> _JsonDict: return self._call("get_snmp_information") + def get_time_sync(self) -> TimeSyncDict: + """Over Redfish only; a BMC read over IPMI cannot tell.""" + return self._call("get_time_sync") + + def _write_ntp_servers(self, servers: list[str]) -> FixStepOutcomeDict: + if not self._redfish_ok: + raise RuntimeError(f"{self.hostname}: setting the NTP servers needs Redfish") + return self._redfish._write_ntp_servers(servers) + def get_licenses(self) -> list[_JsonDict]: """Redfish's license facts, also while IPMI reads the BMC: IPMI knows none.""" return self._redfish.get_licenses() diff --git a/napalm_redfish/driver.py b/napalm_redfish/driver.py index d772144..e39f771 100644 --- a/napalm_redfish/driver.py +++ b/napalm_redfish/driver.py @@ -32,7 +32,9 @@ from typing import Any from napalm.base.exceptions import ConnectionException from napalm_device_types import HealthMetricsMixin, LicenseMixin, ManagementControllerDriver from napalm_device_types.base import FingerprintRule, PortSpec -from napalm_device_types.models import POWER_ACTIONS +from napalm_device_types.models import POWER_ACTIONS, FixStepOutcomeDict +from napalm_device_types.posix_tz import is_iana_zone +from napalm_device_types.time_sync import TimeSyncDict, TimeSyncMixin from napalm_redfish.parsers import ( build_environment, @@ -64,7 +66,7 @@ from napalm_redfish.parsers import ( parse_thermal_subsystem, to_napalm_users, ) -from napalm_redfish.parsers.common import link, link_list, odata_id +from napalm_redfish.parsers.common import boolean, link, link_list, odata_id, text from napalm_redfish.transport import ( RedfishError, RedfishFeatureLicenseError, @@ -134,13 +136,41 @@ def _status(item: _JsonDict) -> str: return item.get("health") or "" -class RedfishDriver(HealthMetricsMixin, LicenseMixin, ManagementControllerDriver): +def _fixed_slots(ntp: _JsonDict) -> tuple[int, str | None] | None: + """``(slots, the empty value)`` of an ``NTPServers`` array that shows empty slots (``""`` + or null): its length is fixed. None for an array without any.""" + slots = ntp.get("NTPServers") + empty = [slot for slot in slots if slot in ("", None)] if isinstance(slots, list) else [] + return (len(slots), empty[0]) if empty and isinstance(slots, list) else None + + +def _ntp_patch( + ntp: _JsonDict, servers: list[str], fixed: tuple[int, str | None] | None +) -> _JsonDict: + """The ``NTP`` body that leaves the BMC with *servers*: the fixed slots filled up with + their empty value, and the protocol turned on where it is off.""" + value: list[str | None] = list(servers) + if fixed is not None: + value += [fixed[1]] * (fixed[0] - len(servers)) + body: _JsonDict = {"NTPServers": value} + if boolean(ntp.get("ProtocolEnabled")) is False: + body["ProtocolEnabled"] = True + return body + + +class RedfishDriver(HealthMetricsMixin, LicenseMixin, TimeSyncMixin, ManagementControllerDriver): """NAPALM driver for Redfish BMCs (Supermicro, iDRAC, iLO, XCC and others). ``HealthMetricsMixin``: the BMC's own load, memory and interfaces over SNMP (UCD-MIB), where the BMC runs net-snmp. The managed server's sensors come from ``get_environment``. + + ``TimeSyncMixin``: the BMC's NTP servers (``ManagerNetworkProtocol.NTP``). A BMC keeps + UTC or an offset, not a zone name, so only the servers are written. """ + #: Redfish has a writable zone name only from Manager v1.10, and BMCs run on UTC. + time_sync_writes = frozenset({"ntp_servers"}) + platform = "redfish" DRIVER_NAME = "redfish" # No fingerprint of its own: discovery suggests ``bmc`` (BMC_PORT_SPECS and @@ -376,7 +406,64 @@ class RedfishDriver(HealthMetricsMixin, LicenseMixin, ManagementControllerDriver return to_napalm_users(parse_account(raw) for raw in self._members_of(service, "Accounts")) def get_ntp_servers(self) -> _JsonDict: - return {server: {} for server in self._network_protocol()["ntp"]["servers"]} + """The NTP servers in use: none while the BMC's NTP is off (as ``get_time_sync``).""" + ntp = self._network_protocol()["ntp"] + return {} if ntp["enabled"] is False else {server: {} for server in ntp["servers"]} + + # --- time sync ----------------------------------------------------------------------- + + def _ntp_protocol_raw(self) -> _JsonDict: + """``NetworkProtocol``, read anew; a BMC whose Redfish has no NTP block cannot tell.""" + raw = self.transport.follow(self._manager_raw(), "NetworkProtocol") + if raw is None or not isinstance(raw.get("NTP"), dict): + raise RedfishError(f"{self.hostname}: the BMC's Redfish has no NTP settings") + return raw + + def get_time_sync(self) -> TimeSyncDict: + """The BMC's NTP servers in its order; none while its NTP is off. + + ``timezone`` is the manager's ``TimeZoneName`` where that is an IANA zone, else + None: ``DateTimeLocalOffset`` is an offset, not a zone. Redfish says neither + whether the clock is synchronised nor anything about the client. + + :raises RedfishError: for a BMC whose ``NetworkProtocol`` has no NTP block. + """ + ntp = parse_network_protocol(self._ntp_protocol_raw())["ntp"] + zone = text(self._manager_raw().get("TimeZoneName")) + return { + "ntp_servers": [] if ntp["enabled"] is False else ntp["servers"], + "timezone": zone if zone and is_iana_zone(zone) else None, + "synchronized": None, + "daemon": None, + } + + def _write_ntp_servers(self, servers: list[str]) -> FixStepOutcomeDict: + """PATCH ``NTP.NTPServers`` to *servers*, and ``ProtocolEnabled`` on where it is off. + + An array with empty slots (``""`` or null) has a fixed length: *servers* fill it + and the rest stay empty, and more servers than slots are refused. The PATCH + carries the resource's ``@odata.etag``. Servers the BMC already uses, in this + order, are not written again. + """ + raw = self._ntp_protocol_raw() + fixed = _fixed_slots(raw["NTP"]) + if fixed is not None and len(servers) > fixed[0]: + return { + "ok": False, + "output": f"the BMC keeps {fixed[0]} NTP servers, not {len(servers)}", + } + ntp = parse_network_protocol(raw)["ntp"] + if ntp["enabled"] is not False and [s.lower() for s in ntp["servers"]] == [ + s.lower() for s in servers + ]: + return {"ok": True, "output": "the BMC already uses these NTP servers"} + etag = raw.get("@odata.etag") + self.transport.patch( + link(self._manager_raw(), "NetworkProtocol") or "", + {"NTP": _ntp_patch(raw["NTP"], servers, fixed)}, + etag=etag if isinstance(etag, str) else None, + ) + return {"ok": True, "output": f"NTP servers set to {', '.join(servers)}"} def get_snmp_information(self) -> _JsonDict: """SNMP state from ManagerNetworkProtocol. Redfish hides community strings, so the diff --git a/napalm_redfish/transport.py b/napalm_redfish/transport.py index 119e464..d0e17d7 100644 --- a/napalm_redfish/transport.py +++ b/napalm_redfish/transport.py @@ -333,15 +333,18 @@ class RedfishTransport: raise RedfishError(f"not an absolute Redfish path: {ref}") return parts.path + (f"?{parts.query}" if parts.query else "") - def _request(self, method: str, ref: Reference, body: Any = None) -> dict[str, Any]: + def _request( + self, + method: str, + ref: Reference, + body: Any = None, + headers: Mapping[str, str] | None = None, + ) -> dict[str, Any]: if self._client is None: raise RedfishError("not connected: call open() first") path = self.path(ref) try: - if method == "GET": - resp = self._client.get(path) - else: - resp = self._client.post(path, body=body) + resp = self._send(method, path, body, headers) except RetriesExhaustedError as exc: raise RedfishError(f"{method} {path}: no response", path=path) from exc status = resp.status @@ -374,6 +377,13 @@ class RedfishTransport: raise RedfishNotFound(message, status=status, path=path) raise RedfishHTTPError(message, status=status, path=path) + def _send(self, method: str, path: str, body: Any, headers: Mapping[str, str] | None) -> Any: + if method == "GET": + return self._client.get(path) + if method == "PATCH": + return self._client.patch(path, body=body, headers=dict(headers or {})) + return self._client.post(path, body=body) + def get(self, ref: Reference) -> dict[str, Any]: return self._request("GET", ref) @@ -389,6 +399,14 @@ class RedfishTransport: def post(self, ref: Reference, body: Mapping[str, Any]) -> dict[str, Any]: return self._request("POST", ref, dict(body)) + def patch( + self, ref: Reference, body: Mapping[str, Any], *, etag: str | None = None + ) -> dict[str, Any]: + """PATCH *body*; with *etag* (the resource's ``@odata.etag``) as ``If-Match``, so a + resource changed since it was read is refused (412) instead of overwritten.""" + headers = {"If-Match": etag} if etag else None + return self._request("PATCH", ref, dict(body), headers) + def follow(self, resource: Mapping[str, Any], key: str) -> dict[str, Any] | None: """The resource linked as ``resource[key]``; ``None`` if not linked or not found.""" link = resource.get(key) diff --git a/pyproject.toml b/pyproject.toml index 5ab88c3..78dd549 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -11,7 +11,7 @@ license = "Apache-2.0" requires-python = ">=3.12" dependencies = [ "napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks - "napalm-device-types>=4.21.1", + "napalm-device-types>=4.35.0", # Before 3.4.1, max_retry=0 (retries=0) gets no response back at all. "redfish>=3.4.1", # 1.5.0 imports python-dateutil without declaring it. @@ -80,7 +80,8 @@ ignore_errors = true [tool.pytest.ini_options] testpaths = ["tests"] -# The tests import their helpers as tests.conftest, also under a bare pytest. +# The tests import their helpers by their own name (conftest, test_ipmi): a package +# "tests" may come with a dependency (textfsm 2.1.1 ships one). pythonpath = ["."] [tool.coverage.run] diff --git a/tests/conftest.py b/tests/conftest.py index 35ac84b..b2485bb 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -2,6 +2,7 @@ import json import re +from collections.abc import Callable from pathlib import Path from urllib.parse import urlsplit @@ -53,15 +54,17 @@ class MockupServer: """Serve a fixture mockup over mocked HTTP, plus a SessionService that hands out one token. Unknown paths return a Redfish error body with 404, like a real service. ``override`` - replaces the answer for one method and path (the path may include a query string). + replaces the answer for one method and path (the path may include a query string); + ``answer`` does so with a callback that takes the request and returns ``(status, body)``. """ def __init__(self, rsps, mockup: str): self.rsps = rsps self.mockup = mockup self.overrides: dict[tuple[str, str], tuple[int, dict, dict]] = {} + self.callbacks: dict[tuple[str, str], Callable] = {} anything = re.compile(re.escape(BASE_URL) + r"/.*") - for method in (responses.GET, responses.POST, responses.DELETE): + for method in (responses.GET, responses.POST, responses.PATCH, responses.DELETE): rsps.add_callback(method, anything, callback=self._handle) def override( @@ -74,6 +77,9 @@ class MockupServer: ): self.overrides[(method, path)] = (status, body if body is not None else {}, headers or {}) + def answer(self, method: str, path: str, callback: Callable): + self.callbacks[(method, path)] = callback + @staticmethod def _reply(status, body, headers=None): if isinstance(body, str): @@ -85,6 +91,8 @@ class MockupServer: def _handle(self, request): parts = urlsplit(request.url) for key in ((request.method, f"{parts.path}?{parts.query}"), (request.method, parts.path)): + if key in self.callbacks: + return self._reply(*self.callbacks[key](request)) if key in self.overrides: return self._reply(*self.overrides[key]) if request.method == "POST" and parts.path == SESSIONS: diff --git a/tests/quality_baseline.json b/tests/quality_baseline.json index efda9c9..f83b53d 100644 --- a/tests/quality_baseline.json +++ b/tests/quality_baseline.json @@ -6,7 +6,7 @@ "napalm_redfish/driver.py::RedfishDriver.get_facts": 15, "napalm_redfish/parsers/environment.py::build_environment": 13, "napalm_redfish/parsers/manager.py::parse_network_protocol": 14, - "napalm_redfish/transport.py::RedfishTransport._request": 14, + "napalm_redfish/transport.py::RedfishTransport._request": 13, "napalm_redfish/transport.py::RedfishTransport.members": 15 }, "function_lines": {}, diff --git a/tests/test_bmc_driver.py b/tests/test_bmc_driver.py index c06adb5..0a55433 100644 --- a/tests/test_bmc_driver.py +++ b/tests/test_bmc_driver.py @@ -12,13 +12,13 @@ import json from pathlib import Path import pytest +from conftest import BASE_URL, FIXTURES, MockupServer from napalm_device_types import ManagementControllerDriver from napalm_device_types.roles import primary_role_of +from test_ipmi import FakeCommand import napalm_redfish.ipmi as ipmi from napalm_redfish.bmc import BmcDriver -from tests.conftest import BASE_URL, FIXTURES, MockupServer -from tests.test_ipmi import FakeCommand X10 = Path(__file__).parent / "fixtures" / "supermicro-x10drl-i-3.91" MOCKUP = "supermicro-x10drl-i-3.91/redfish" diff --git a/tests/test_time_sync.py b/tests/test_time_sync.py new file mode 100644 index 0000000..fc32780 --- /dev/null +++ b/tests/test_time_sync.py @@ -0,0 +1,228 @@ +"""Time sync of a BMC over Redfish (NetOrk/netork#2367): ``ManagerNetworkProtocol.NTP``. + +The BMC's NTP servers are ``NTP.NTPServers``, in use while ``NTP.ProtocolEnabled`` is +not false. Its clock runs on UTC or an offset (``Manager.DateTimeLocalOffset``), which +is no zone name: only a manager that names an IANA zone (``TimeZoneName``, Manager +v1.10) reads one, and the zone is never written. + +The answers are the DMTF mockups (public-telemetry's NTP block), and the shapes BMCs +give the array: a fixed number of slots with empty strings for the unused ones +(three on an iDRAC 9, two on an iLO 5), with an ``@odata.etag`` to PATCH against. +""" + +import copy +import json + +import pytest +from conftest import load +from napalm_device_types.time_sync import TimeSyncMixin + +import napalm_redfish.ipmi as ipmi +from napalm_redfish import RedfishDriver +from napalm_redfish.bmc import BmcDriver +from napalm_redfish.ipmi import IpmiDriver +from napalm_redfish.transport import RedfishError + +MANAGER = "/redfish/v1/Managers/BMC" +PROTOCOL = MANAGER + "/NetworkProtocol" +TELEMETRY_NTP = load("dmtf-public-telemetry", "/redfish/v1/Managers/1/NetworkProtocol")["NTP"] + + +class Bmc: + """The rackmount mockup's NetworkProtocol with an NTP block, PATCHed in place.""" + + def __init__(self, server, ntp: dict, etag: str | None = None) -> None: + self.body = load("dmtf-public-rackmount1", PROTOCOL) + self.body["NTP"] = copy.deepcopy(ntp) + self.etag = etag + self.patches: list[tuple[dict, str | None]] = [] + self.refuse: tuple[int, dict] | None = None + server.answer("GET", PROTOCOL, self._get) + server.answer("PATCH", PROTOCOL, self._patch) + + def _get(self, request): + body = dict(self.body) + if self.etag: + body["@odata.etag"] = self.etag + return 200, body + + def _patch(self, request): + patch = json.loads(request.body) + self.patches.append((patch, request.headers.get("If-Match"))) + if self.refuse: + return self.refuse + self.body["NTP"].update(patch["NTP"]) + self.etag = self.etag and f'W/"{len(self.patches)}"' + return 204, {} + + +@pytest.fixture +def driver(server): + d = RedfishDriver("bmc.example.net", "netork", "s3cret", optional_args={"verify_ssl": False}) + d.open() + yield d + d.close() + + +# --- opt-in -------------------------------------------------------------------------------- + + +def test_redfish_and_bmc_offer_it_and_write_only_servers(): + for cls in (RedfishDriver, BmcDriver): + assert issubclass(cls, TimeSyncMixin) + assert callable(cls.get_time_sync) + assert callable(cls.configure_time_sync) + assert cls.time_sync_writes == frozenset({"ntp_servers"}) + + +def test_ipmi_has_no_time_sync(): + """IPMI has no NTP settings: the driver does not offer it.""" + assert getattr(IpmiDriver, "get_time_sync", None) is None + assert getattr(IpmiDriver, "configure_time_sync", None) is None + + +# --- reading ------------------------------------------------------------------------------- + + +def test_reads_the_servers_of_the_telemetry_mockup(driver, server): + Bmc(server, TELEMETRY_NTP) + assert driver.get_time_sync() == { + "ntp_servers": ["0.pool.ntp.org", "1.pool.ntp.org", "time-a.nist.gov"], + "timezone": None, # the manager has only DateTimeLocalOffset "+06:00" + "synchronized": None, + "daemon": None, + } + + +def test_empty_slots_are_no_servers(driver, server): + Bmc(server, {"NTPServers": ["10.0.0.1", "", ""], "ProtocolEnabled": True}) + assert driver.get_time_sync()["ntp_servers"] == ["10.0.0.1"] + + +def test_servers_of_a_disabled_ntp_are_not_in_use(driver, server): + Bmc(server, {"NTPServers": ["10.0.0.1", ""], "ProtocolEnabled": False}) + assert driver.get_time_sync()["ntp_servers"] == [] + assert driver.get_ntp_servers() == {} + + +def test_get_ntp_servers_names_the_same_servers(driver, server): + Bmc(server, TELEMETRY_NTP) + assert list(driver.get_ntp_servers()) == driver.get_time_sync()["ntp_servers"] + + +def test_a_named_iana_zone_is_read(driver, server): + manager = load("dmtf-public-rackmount1", MANAGER) + server.override("GET", MANAGER, 200, {**manager, "TimeZoneName": "Europe/Berlin"}) + Bmc(server, TELEMETRY_NTP) + assert driver.get_time_sync()["timezone"] == "Europe/Berlin" + + +def test_a_zone_name_that_is_no_iana_zone_is_none(driver, server): + manager = load("dmtf-public-rackmount1", MANAGER) + server.override("GET", MANAGER, 200, {**manager, "TimeZoneName": "GMT+01:00"}) + Bmc(server, TELEMETRY_NTP) + assert driver.get_time_sync()["timezone"] is None + + +def test_a_bmc_without_ntp_settings_cannot_tell(driver): + """The rackmount mockup's NetworkProtocol (and a Supermicro X10's, v1_0_0) has no NTP.""" + with pytest.raises(RedfishError, match="NTP"): + driver.get_time_sync() + assert driver.get_ntp_servers() == {} + + +# --- writing ------------------------------------------------------------------------------- + + +def test_fills_fixed_slots_with_empty_strings_and_the_etag(driver, server): + bmc = Bmc(server, {"NTPServers": ["", "", ""], "ProtocolEnabled": True}, etag='W/"a1"') + result = driver.configure_time_sync(ntp_servers=["ntp1.example.org", "10.0.0.1"]) + assert result["success"], result["output"] + assert bmc.patches == [ + ({"NTP": {"NTPServers": ["ntp1.example.org", "10.0.0.1", ""]}}, 'W/"a1"'), + ] + assert [s["step"] for s in result["steps"]] == ["ntp_servers", "verify"] + + +def test_more_servers_than_slots_are_refused_before_writing(driver, server): + bmc = Bmc(server, {"NTPServers": ["", ""], "ProtocolEnabled": True}) + result = driver.configure_time_sync(ntp_servers=["a.example.org", "b.example.org", "c.org"]) + assert not result["success"] + assert "2 NTP servers" in result["steps"][0]["output"] + assert bmc.patches == [] + + +def test_an_array_without_placeholders_gets_exactly_the_servers(driver, server): + bmc = Bmc(server, TELEMETRY_NTP) + result = driver.configure_time_sync(ntp_servers=["10.0.0.1"]) + assert result["success"], result["output"] + assert bmc.patches == [({"NTP": {"NTPServers": ["10.0.0.1"]}}, None)] + assert driver.get_time_sync()["ntp_servers"] == ["10.0.0.1"] + + +def test_turns_a_disabled_ntp_on(driver, server): + bmc = Bmc(server, {"NTPServers": ["10.0.0.1", ""], "ProtocolEnabled": False}) + result = driver.configure_time_sync(ntp_servers=["10.0.0.1"]) + assert result["success"], result["output"] + assert bmc.patches == [ + ({"NTP": {"NTPServers": ["10.0.0.1", ""], "ProtocolEnabled": True}}, None), + ] + + +def test_the_same_servers_again_patch_nothing(driver, server): + bmc = Bmc(server, {"NTPServers": ["NTP1.example.org", "", ""], "ProtocolEnabled": True}) + result = driver.configure_time_sync(ntp_servers=["ntp1.example.org"]) + assert result["success"], result["output"] + assert bmc.patches == [] + + +def test_a_refusal_fails_the_step_with_the_bmc_message(driver, server): + bmc = Bmc(server, {"NTPServers": ["", ""], "ProtocolEnabled": True}, etag='W/"a1"') + bmc.refuse = (400, {"error": {"message": "NTPServers is read-only while DHCP sets them"}}) + result = driver.configure_time_sync(ntp_servers=["10.0.0.1"]) + assert not result["success"] + assert "read-only while DHCP" in result["steps"][0]["output"] + + +def test_no_ntp_settings_no_write(driver, server): + result = driver.configure_time_sync(ntp_servers=["10.0.0.1"]) + assert not result["success"] + assert "NTP" in result["steps"][0]["output"] + assert server.calls("PATCH") == [] + + +def test_the_zone_is_refused(driver): + with pytest.raises(ValueError, match="timezone"): + driver.configure_time_sync(timezone="Europe/Berlin") + + +# --- the bmc driver: over Redfish only ----------------------------------------------------- + + +@pytest.fixture +def bmc_driver(server, monkeypatch): + from test_ipmi import FakeCommand + + FakeCommand.instances = [] + monkeypatch.setattr(ipmi, "Command", FakeCommand) + d = BmcDriver("bmc.example.net", "netork", "s3cret", optional_args={"verify_ssl": False}) + d.open() + yield d + d.close() + + +def test_bmc_reads_and_writes_over_redfish(bmc_driver, server): + bmc = Bmc(server, {"NTPServers": ["", ""], "ProtocolEnabled": True}) + result = bmc_driver.configure_time_sync(ntp_servers=["10.0.0.1"]) + assert result["success"], result["output"] + assert bmc.patches == [({"NTP": {"NTPServers": ["10.0.0.1", ""]}}, None)] + assert bmc_driver.get_time_sync()["ntp_servers"] == ["10.0.0.1"] + + +def test_bmc_without_redfish_cannot_tell_nor_write(bmc_driver): + bmc_driver._redfish_ok = False + with pytest.raises(NotImplementedError, match="Redfish"): + bmc_driver.get_time_sync() + result = bmc_driver.configure_time_sync(ntp_servers=["10.0.0.1"]) + assert not result["success"] + assert "Redfish" in result["steps"][0]["output"] diff --git a/tests/test_transport.py b/tests/test_transport.py index 3780b9f..1b24a8c 100644 --- a/tests/test_transport.py +++ b/tests/test_transport.py @@ -450,3 +450,33 @@ def test_post_error(transport, server): with pytest.raises(RedfishHTTPError) as exc: transport.post(target, {"ResetType": "PowerCycle"}) assert exc.value.status == 400 + + +# --- PATCH --------------------------------------------------------------------------------- + + +def test_patch_sends_json_with_the_etag(transport, server): + target = "/redfish/v1/Managers/BMC/NetworkProtocol" + server.override("PATCH", target, 204, {}) + body = {"NTP": {"NTPServers": ["10.0.0.1", ""]}} + assert transport.patch(target, body, etag='W/"5a1c"') == {} + (call,) = server.calls("PATCH", target) + assert json.loads(call.request.body) == body + assert call.request.headers["If-Match"] == 'W/"5a1c"' + assert call.request.headers["X-Auth-Token"] == TOKEN + + +def test_patch_without_an_etag_sends_no_precondition(transport, server): + target = "/redfish/v1/Managers/BMC/NetworkProtocol" + server.override("PATCH", target, 200, {"@odata.id": target}) + assert transport.patch(target, {"NTP": {"ProtocolEnabled": True}}) == {"@odata.id": target} + (call,) = server.calls("PATCH", target) + assert "If-Match" not in call.request.headers + + +def test_patch_refused_by_a_changed_etag(transport, server): + target = "/redfish/v1/Managers/BMC/NetworkProtocol" + server.override("PATCH", target, 412, {"error": {"message": "PreconditionFailed"}}) + with pytest.raises(RedfishHTTPError) as exc: + transport.patch(target, {"NTP": {}}, etag='W/"old"') + assert exc.value.status == 412 diff --git a/tests/test_x10_redfish.py b/tests/test_x10_redfish.py index 31c7c5c..9807c16 100644 --- a/tests/test_x10_redfish.py +++ b/tests/test_x10_redfish.py @@ -10,10 +10,10 @@ files hold the error body the BMC sent. import json import pytest +from conftest import BASE_URL, FIXTURES, MockupServer from napalm_device_types import models from napalm_redfish import RedfishDriver -from tests.conftest import BASE_URL, FIXTURES, MockupServer MOCKUP = "supermicro-x10drl-i-3.91/redfish" REFUSED = json.loads((FIXTURES / MOCKUP / "STATUS.json").read_text())