"""The switch's time sources and zone through napalm-device-types' TimeSyncMixin (netOrk #2366). A ProCurve keeps them in its configuration as (management and configuration guide, "Time Protocols"):: time timezone 60 time daylight-time-rule middle-europe-and-portugal timesync sntp sntp unicast sntp server priority 1 10.0.0.1 or, with ArubaOS-Switch 16.x in NTP mode, ``timesync ntp`` and ``ntp server`` lines. The fake switch below keeps those lines the way ``show running-config`` lists them and applies what the driver sends in ``configure``. """ from __future__ import annotations import base64 from unittest.mock import MagicMock import pytest from napalm.base.exceptions import CommandErrorException, ConnectionException from napalm_device_types import TimeSyncMixin from napalm_procurve.procurve import ProcurveDriver from napalm_procurve.time_sync import parse_time_config, zone_settings HEADER = """\ ; J9774A Configuration Editor; Created on release #YA.16.10.0012 ; Ver #14:41.44.00.04.19.02.13.98.82.34.61.18.28.f3.84.9c.63.ff.37.27:05 hostname "HP-2530-8G-PoEP" """ SNTP_CONFIG = ( HEADER + """\ time timezone 60 time daylight-time-rule middle-europe-and-portugal timesync sntp sntp unicast sntp server priority 1 10.0.0.1 sntp server priority 2 10.0.0.2 4 ip default-gateway 192.168.0.254 """ ) NTP_CONFIG = ( HEADER + """\ timesync ntp ntp unicast ntp server 10.0.0.1 iburst ntp server 10.0.0.2 ntp enable """ ) #: Factory default: no time lines at all (TimeP, UTC, no summer time). BARE_CONFIG = HEADER + "ip default-gateway 192.168.0.254\n" class FakeSwitch: """The time lines of a switch's running configuration, as the CLI changes them.""" def __init__(self, config: str) -> None: self.lines = config.splitlines() self.sent: list[str] = [] self.saved = 0 self.refuse = False @property def config(self) -> str: return "\n".join(self.lines) + "\n" def _drop(self, prefix: str) -> None: self.lines = [x for x in self.lines if not x.startswith(prefix)] def send_command(self, cmd: str, **_kw: object) -> str: if cmd == "show running-config": return self.config if cmd in ("configure", "end"): return "" if cmd == "write memory": self.saved += 1 return "" self.sent.append(cmd) if self.refuse: return "Invalid input: " + cmd.split()[-1] if cmd.startswith("no "): before = len(self.lines) self._drop(cmd[3:]) return "" if len(self.lines) < before else "The server is not configured." if cmd.startswith("sntp server priority"): prefix = " ".join(cmd.split()[:4]) + " " if any(x.startswith(prefix) for x in self.lines): return "Error: this priority is already in use." self.lines.append(cmd) elif cmd.startswith("ntp server "): self.lines.append(cmd) else: # time timezone, time daylight-time-rule, timesync, sntp unicast words = 2 if cmd.startswith(("time ", "sntp ")) else 1 self._drop(" ".join(cmd.split()[:words]) + " ") self.lines.append(cmd) return "" def _cli_driver(switch: FakeSwitch) -> ProcurveDriver: d = ProcurveDriver("10.0.0.40", "manager", "pw") d._transport = "ssh" d._device = MagicMock() d._device.base_prompt = "HP-2530-8G-PoEP" d._device.send_command.side_effect = switch.send_command return d @pytest.fixture def switch() -> FakeSwitch: return FakeSwitch(SNTP_CONFIG) @pytest.fixture def driver(switch: FakeSwitch) -> ProcurveDriver: return _cli_driver(switch) # -- reading ----------------------------------------------------------------- def test_the_driver_is_a_time_sync_driver(): assert issubclass(ProcurveDriver, TimeSyncMixin) assert callable(getattr(ProcurveDriver, "get_time_sync", None)) assert ProcurveDriver.time_sync_writes == frozenset({"ntp_servers", "timezone"}) def test_reads_the_sntp_servers_by_priority_and_no_zone_name(driver): assert driver.get_time_sync() == { "ntp_servers": ["10.0.0.1", "10.0.0.2"], "timezone": None, # minutes and a summer-time rule, no name "synchronized": None, "daemon": None, } def test_sntp_servers_read_in_priority_order(): config = parse_time_config("sntp server priority 2 10.0.0.2\nsntp server priority 1 10.0.0.1\n") assert config.servers == ["10.0.0.1", "10.0.0.2"] def test_reads_the_ntp_servers_in_ntp_mode(driver, switch): switch.lines = NTP_CONFIG.splitlines() assert driver.get_time_sync()["ntp_servers"] == ["10.0.0.1", "10.0.0.2"] def test_a_bare_switch_has_no_servers_in_utc(): config = parse_time_config(BARE_CONFIG) assert (config.servers, config.offset, config.dst_rule) == ([], 0, "none") def test_get_ntp_servers_lists_what_get_time_sync_reads(driver): assert driver.get_ntp_servers() == {"10.0.0.1": {}, "10.0.0.2": {}} def test_reads_over_rest_through_the_cli_endpoint(): d = ProcurveDriver("10.0.0.40", "manager", "pw") d._transport = "api" d._api = MagicMock() encoded = base64.b64encode(SNTP_CONFIG.encode() + b"\x00").decode() d._api.post.return_value.ok = True d._api.post.return_value.json.return_value = {"result_base64_encoded": encoded} assert d.get_time_sync()["ntp_servers"] == ["10.0.0.1", "10.0.0.2"] d._api.post.assert_called_once_with("cli", json={"cmd": "show running-config"}) def test_a_failed_rest_read_raises(): d = ProcurveDriver("10.0.0.40", "manager", "pw") d._transport = "api" d._api = MagicMock() d._api.post.return_value.ok = False d._api.post.return_value.status_code = 500 with pytest.raises(CommandErrorException, match="HTTP 500"): d.get_ntp_servers() SHOW_NTP_ASSOCIATIONS = """\ NTP associations Address Ref-clock St When Poll Reach Delay Offset Jitter --------------- --------- -- ----- ---- ----- ------ ------ ------ *10.0.0.10 10.0.0.1 2 64 1024 377 0.620 0.000 0.000 10.0.0.20 .INIT. 16 - 1024 0 0.000 - 0.000 """ def test_get_ntp_stats_reads_the_associations(driver, switch): driver._send_command = MagicMock(return_value=SHOW_NTP_ASSOCIATIONS) synced, init = driver.get_ntp_stats() assert (synced["remote"], synced["synchronized"], synced["stratum"]) == ("10.0.0.10", True, 2) assert (synced["hostpoll"], synced["reachability"], synced["delay"]) == (1024, 0o377, 0.62) assert (init["remote"], init["synchronized"], init["offset"]) == ("10.0.0.20", False, 0.0) # -- the zone as the switch takes it ------------------------------------------ @pytest.mark.parametrize( "zone, settings", [ ("Europe/Berlin", (60, "middle-europe-and-portugal")), ("Europe/London", (0, "western-europe")), ("Europe/Dublin", (0, "western-europe")), # negative summer time, turned round ("America/New_York", (-300, "canada-and-continental-us")), ("America/Anchorage", (-540, "canada-and-continental-us")), ("Asia/Kolkata", (330, "none")), ("Asia/Kathmandu", (345, "none")), ("UTC", (0, "none")), ("Australia/Sydney", (600, "user-defined begin-date 10/01 end-date 04/01")), ("Pacific/Auckland", (720, "user-defined begin-date 09/24 end-date 04/01")), ], ) def test_zone_settings(zone, settings): assert zone_settings(zone) == settings @pytest.mark.parametrize( "zone, why", [ ("Australia/Lord_Howe", "one hour"), # 30 minutes of summer time ("Asia/Jerusalem", "Sunday"), # changes on a Friday ], ) def test_a_zone_the_switch_cannot_keep_is_refused(zone, why): with pytest.raises(ValueError, match=why): zone_settings(zone) # -- writing the servers ----------------------------------------------------- def test_writes_new_sntp_servers_in_priority_order(driver, switch): result = driver.configure_time_sync(ntp_servers=["10.0.0.5", "10.0.0.6"]) assert result["success"] is True, result assert switch.sent == [ "no sntp server priority 1 10.0.0.1", "no sntp server priority 2 10.0.0.2", "sntp server priority 1 10.0.0.5", "sntp server priority 2 10.0.0.6", ] assert switch.saved == 1 def test_keeps_the_servers_already_in_place(driver, switch): result = driver.configure_time_sync(ntp_servers=["10.0.0.1", "10.0.0.9"]) assert result["success"] is True, result assert switch.sent == ["no sntp server priority 2 10.0.0.2", "sntp server priority 2 10.0.0.9"] def test_the_same_servers_again_change_nothing(driver, switch): result = driver.configure_time_sync(ntp_servers=["10.0.0.1", "10.0.0.2"]) assert result["success"] is True, result assert switch.sent == [] assert switch.saved == 0 def test_a_bare_switch_gets_sntp_switched_on(driver, switch): switch.lines = BARE_CONFIG.splitlines() result = driver.configure_time_sync(ntp_servers=["10.0.0.5", "2001:db8::1"]) assert result["success"] is True, result assert switch.sent == [ "sntp server priority 1 10.0.0.5", "sntp server priority 2 2001:db8::1", "sntp unicast", "timesync sntp", ] assert driver.get_time_sync()["ntp_servers"] == ["10.0.0.5", "2001:db8::1"] def test_ntp_mode_keeps_its_protocol(driver, switch): switch.lines = NTP_CONFIG.splitlines() result = driver.configure_time_sync(ntp_servers=["10.0.0.2", "10.0.0.3"]) assert result["success"] is True, result assert switch.sent == [ "no ntp server 10.0.0.1", "no ntp server 10.0.0.2", "ntp server 10.0.0.2 iburst", "ntp server 10.0.0.3 iburst", ] @pytest.mark.parametrize( "servers, why", [ (["10.0.0.1", "10.0.0.2", "10.0.0.3", "10.0.0.4"], "at most 3"), (["ntp.example.org"], "IP addresses"), ], ) def test_servers_the_switch_cannot_take_are_refused_before_writing(driver, switch, servers, why): result = driver.configure_time_sync(ntp_servers=servers) assert result["success"] is False assert why in result["output"] assert switch.sent == [] def test_ntp_mode_takes_eight_servers(driver, switch): switch.lines = NTP_CONFIG.splitlines() servers = [f"10.0.1.{i}" for i in range(1, 9)] assert driver.configure_time_sync(ntp_servers=servers)["success"] is True assert driver.configure_time_sync(ntp_servers=[*servers, "10.0.1.9"])["success"] is False def test_a_refused_command_fails_the_step_and_is_not_saved(driver, switch): switch.refuse = True result = driver.configure_time_sync(ntp_servers=["10.0.0.5"]) assert result["success"] is False assert "Invalid input" in result["output"] assert switch.saved == 0 # -- writing the zone -------------------------------------------------------- def test_writes_minutes_and_summer_time_rule(driver, switch): result = driver.configure_time_sync(timezone="America/New_York") assert result["success"] is True, result assert switch.sent == [ "time timezone -300", "time daylight-time-rule canada-and-continental-us", ] assert switch.saved == 1 def test_the_same_zone_again_changes_nothing(driver, switch): result = driver.configure_time_sync(timezone="Europe/Berlin") assert result["success"] is True, result assert switch.sent == [] assert switch.saved == 0 def test_either_european_rule_stands_for_the_eu_dates(driver, switch): switch.lines = [x.replace("middle-europe-and-portugal", "western-europe") for x in switch.lines] assert driver.configure_time_sync(timezone="Europe/Berlin")["success"] is True assert switch.sent == [] def test_a_user_defined_rule_reads_back_by_its_dates(driver, switch): switch.lines[3:5] = [ "time timezone 600", "time daylight-time-rule user-defined begin-date 10/1 end-date 4/1", ] assert driver.configure_time_sync(timezone="Australia/Sydney")["success"] is True assert switch.sent == [] def test_a_bare_switch_gets_its_zone(driver, switch): switch.lines = BARE_CONFIG.splitlines() result = driver.configure_time_sync(timezone="Asia/Kolkata") assert result["success"] is True, result assert switch.sent == ["time timezone 330"] def test_servers_and_zone_together(driver, switch): result = driver.configure_time_sync(ntp_servers=["10.0.0.1"], timezone="UTC") assert result["success"] is True, result assert switch.sent == [ "no sntp server priority 2 10.0.0.2", "time timezone 0", "time daylight-time-rule none", ] assert [s["step"] for s in result["steps"]] == ["ntp_servers", "timezone", "verify"] assert switch.saved == 2 # -- over REST: the CLI on a temporary SSH session --------------------------- def _rest_driver(switch: FakeSwitch) -> tuple[ProcurveDriver, MagicMock]: d = ProcurveDriver("10.0.0.40", "manager", "pw") d._transport = "api" d._api = MagicMock() d._api.post.side_effect = lambda _ep, json: MagicMock( ok=True, json=MagicMock( return_value={ "result_base64_encoded": base64.b64encode( switch.send_command(json["cmd"]).encode() + b"\x00" ).decode() } ), ) ssh = MagicMock() ssh.base_prompt = "HP-2530-8G-PoEP" ssh.send_command.side_effect = switch.send_command d._ssh_connect = MagicMock(return_value=ssh) return d, ssh def test_over_rest_writes_through_ssh_and_reads_through_rest(switch): d, ssh = _rest_driver(switch) result = d.configure_time_sync(ntp_servers=["10.0.0.5"]) assert result["success"] is True, result assert switch.sent[-1] == "sntp server priority 1 10.0.0.5" assert switch.saved == 1 d._ssh_connect.assert_called_once() ssh.disconnect.assert_called_once() assert d._transport == "api" def test_over_rest_nothing_to_write_opens_no_ssh(switch): d, _ssh = _rest_driver(switch) assert d.configure_time_sync(ntp_servers=["10.0.0.1", "10.0.0.2"])["success"] is True d._ssh_connect.assert_not_called() def test_over_rest_without_ssh_the_step_fails(switch): d, _ssh = _rest_driver(switch) d._ssh_connect.side_effect = ConnectionException("connection refused") result = d.configure_time_sync(timezone="UTC") assert result["success"] is False assert "no SSH for the CLI" in result["output"] assert switch.sent == []