feat(time-sync): servers and zone on Proxmox VE and Backup Server #63
No files matched your search
+18
-1
@@ -8,6 +8,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
- Time sync on both drivers (NetOrk/netork#2365), through napalm-device-types'
|
||||
`TimeSyncMixin` (4.35.0); both write the servers and the zone. Neither API keeps time
|
||||
servers -- both products run chrony on Debian -- so `get_time_sync()` reads chrony's
|
||||
sources, whether it is synchronised and the zone (`timedatectl`) in one round trip over
|
||||
the driver's SSH session (`PosixTimeSyncMixin`), and the zone from `GET
|
||||
/nodes/{node}/time` only where the host names none. `configure_time_sync()` writes the
|
||||
servers to `/etc/chrony/sources.d/netork.sources` with every other source commented out
|
||||
(Debian's vendor pool, the DHCP `sourcedir`) and reloads or restarts chrony; the zone
|
||||
goes through `PUT /nodes/{node}/time`, Proxmox's own call, so `/etc/timezone` and the
|
||||
web UI follow `/etc/localtime`. The token needs `Sys.Modify` for it (PVE on
|
||||
`/nodes/{node}`, PBS on `/system/time`). Only the node of the connection is read and
|
||||
written: in a PVE cluster each node keeps its own clock.
|
||||
- What a restart would abort, on both drivers (NetOrk/netork#2318), through
|
||||
napalm-device-types' `RunningBackupsMixin` (4.34.0): `get_running_backups()` lists on
|
||||
Proxmox VE the node's active vzdump tasks with the guests each is taking now -- the task's
|
||||
@@ -33,7 +45,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
in its own daemons; `get_clusters()` and `get_backup_jobs()` keep them.
|
||||
|
||||
### Changed
|
||||
- Requires napalm-device-types 4.34.0.
|
||||
- Requires napalm-device-types 4.35.0.
|
||||
|
||||
### Fixed
|
||||
- `get_ntp_servers()` read `GET /nodes/{node}/ntp`, a path Proxmox VE does not have, and so
|
||||
always reported no servers. It now reports chrony's configured sources, the ones
|
||||
`get_time_sync()` reads, and the backup server has it too.
|
||||
|
||||
## [0.10.0] - 2026-11-03
|
||||
|
||||
|
||||
@@ -110,7 +110,7 @@ device = driver(
|
||||
| `get_mac_address_table` | `bridge fdb show` (Linux) + `ovs-appctl fdb/show` (OVS) |
|
||||
| `get_vlans` | SDN VNet tags + `bridge vlan show` |
|
||||
| `get_network_instances` | SDN zones (VLAN→L2VPN, EVPN→L3VRF) + default instance |
|
||||
| `get_ntp_servers` | From `node/ntp` API |
|
||||
| `get_ntp_servers` | chrony's configured sources, as `get_time_sync` reads them |
|
||||
| `get_ntp_stats` | Parses `chronyc` / `ntpq -pn` output |
|
||||
| `get_snmp_information` | Parses `/etc/snmp/snmpd.conf` |
|
||||
| `get_users` | Proxmox access/users API + local `/etc/passwd` |
|
||||
@@ -129,6 +129,8 @@ device = driver(
|
||||
| `get_scheduled_jobs` | cron, `/etc/cron.d`, user crontabs, run-parts, anacron, systemd timers, as root over SSH (napalm-device-types' `PosixScheduledJobsMixin`); `pve-*` units, `pvesr.timer` and `/etc/cron.d/vzdump` are `platform` |
|
||||
| `manage_scheduled_job(key, action, digest=)` | enable, disable, run now; a `/etc/cron.d/vzdump` line only runs |
|
||||
| `put_scheduled_job(spec)` / `delete_scheduled_job(key, digest=)` | an application's own job, as a systemd timer |
|
||||
| `get_time_sync` | chrony's sources and whether it is synchronised, the zone from `timedatectl`, in one round trip over SSH (napalm-device-types' `PosixTimeSyncMixin`); the zone from `GET /nodes/{node}/time` only where the host names none |
|
||||
| `configure_time_sync(ntp_servers=, timezone=)` | servers to `/etc/chrony/sources.d/netork.sources`, every other source commented out, then a reload or a restart of chrony; the zone through `PUT /nodes/{node}/time` (the token needs `Sys.Modify` on `/nodes/{node}`), so `/etc/timezone` and the web UI follow. Only this node: in a cluster each node keeps its own clock |
|
||||
|
||||
**Not implemented** (raise `NotImplementedError`):
|
||||
`get_bgp_config`, `get_bgp_neighbors`, `get_bgp_neighbors_detail`,
|
||||
@@ -188,6 +190,7 @@ the disks and ZFS pools the server manages itself.
|
||||
| `get_licenses` | `pbs-subscription` |
|
||||
| packages, updates, services, kernel, listening sockets, sshd hardening, `reboot_host`, `shutdown_host` | as on Proxmox VE |
|
||||
| scheduled jobs | as on Proxmox VE; `proxmox-backup*` units are `platform`. Verify, prune, sync and GC jobs are `get_backup_jobs`, not scheduled jobs |
|
||||
| `get_time_sync`, `configure_time_sync`, `get_ntp_servers` | as on Proxmox VE, the zone through `/nodes/localhost/time` (writing it needs `Sys.Modify` on `/system/time`) |
|
||||
|
||||
**API token rights.** Reading needs the role `Audit` on `/` (`Sys.Audit`,
|
||||
`Datastore.Audit`); the remotes need `Remote.Audit` on `/remote` as well, which
|
||||
@@ -241,7 +244,8 @@ tests/
|
||||
├── test_environment.py # get_environment
|
||||
├── test_sdn.py # get_vlans, get_network_instances
|
||||
├── test_ovs_and_arp.py # get_arp_table, get_mac_address_table, ARP/OVS utils
|
||||
├── test_misc.py # NTP, SNMP, users, config, ping, traceroute, CLI, LLDP
|
||||
├── test_misc.py # NTP statistics, SNMP, users, config, ping, traceroute, CLI, LLDP
|
||||
├── test_time_sync.py # get_time_sync / configure_time_sync on both drivers
|
||||
├── test_utils.py # Unit tests for napalm_proxmox.utils
|
||||
├── fixtures/pbs_api.json # What a Proxmox Backup Server 4.2 answered (sanitised)
|
||||
├── pbs_fake.py # A proxmoxer stand-in answering from that recording
|
||||
|
||||
@@ -43,6 +43,7 @@ from napalm_proxmox.pbs_backups import ProxmoxBackupServerMixin
|
||||
from napalm_proxmox.pbs_host import ProxmoxPbsHostMixin
|
||||
from napalm_proxmox.running_backups import PbsRunningBackupsMixin
|
||||
from napalm_proxmox.scheduled_jobs import PBS_PLATFORM_SOURCES, ProxmoxScheduledJobsMixin
|
||||
from napalm_proxmox.time_sync import ProxmoxTimeSyncMixin
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -56,6 +57,7 @@ class ProxmoxBackupDriver(
|
||||
PbsRunningBackupsMixin,
|
||||
ProxmoxPbsHostMixin,
|
||||
ProxmoxHostMixin,
|
||||
ProxmoxTimeSyncMixin,
|
||||
BackupServerDriver,
|
||||
StorageDriver,
|
||||
KernelFactsMixin,
|
||||
|
||||
@@ -59,6 +59,7 @@ from napalm_proxmox.running_backups import ProxmoxRunningBackupsMixin
|
||||
from napalm_proxmox.scheduled_jobs import PVE_PLATFORM_SOURCES, ProxmoxScheduledJobsMixin
|
||||
from napalm_proxmox.sdn_mixin import ProxmoxSDNMixin
|
||||
from napalm_proxmox.system_mixin import ProxmoxSystemMixin
|
||||
from napalm_proxmox.time_sync import ProxmoxTimeSyncMixin
|
||||
from napalm_proxmox.vm_contract_mixin import ProxmoxVMContractMixin
|
||||
from napalm_proxmox.vm_migrate_mixin import ProxmoxVMMigrateMixin
|
||||
from napalm_proxmox.vm_mixin import ProxmoxVMMixin
|
||||
@@ -100,6 +101,7 @@ class ProxmoxDriver(
|
||||
SystemdServicesMixin,
|
||||
ProxmoxScheduledJobsMixin,
|
||||
ProxmoxRunningBackupsMixin,
|
||||
ProxmoxTimeSyncMixin,
|
||||
HostStatusMixin,
|
||||
LicenseMixin,
|
||||
SnmpAgentMixin,
|
||||
@@ -198,18 +200,6 @@ class ProxmoxDriver(
|
||||
f"set the 'node' driver argument"
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Node info helpers (PVE only)
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
def _get_node_ntp(self) -> _JsonDict:
|
||||
"""Return NTP configuration for this node."""
|
||||
try:
|
||||
return self._node_api().ntp.get() or {}
|
||||
except Exception as exc:
|
||||
logger.debug("Failed to fetch node NTP: %s", exc)
|
||||
return {}
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# NAPALM getters kept in driver
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
@@ -176,21 +176,9 @@ class ProxmoxSystemMixin:
|
||||
return env
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# get_ntp_servers / get_ntp_stats
|
||||
# get_ntp_stats (get_ntp_servers: time_sync.ProxmoxTimeSyncMixin)
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
def get_ntp_servers(self) -> dict[str, _JsonDict]:
|
||||
"""Return configured NTP servers."""
|
||||
ntp = self._get_node_ntp()
|
||||
servers: dict[str, _JsonDict] = {}
|
||||
# Proxmox reports a comma-separated or space-separated server list
|
||||
raw = ntp.get("server", "") or ntp.get("servers", "")
|
||||
for srv in re.split(r"[\s,]+", raw):
|
||||
srv = srv.strip()
|
||||
if srv:
|
||||
servers[srv] = {}
|
||||
return servers
|
||||
|
||||
def get_ntp_stats(self) -> list[_JsonDict]:
|
||||
"""Return NTP synchronisation statistics from chrony, or ntpd where chrony is missing."""
|
||||
return parse_ntp_stats(self._exec_ssh_command(NTP_STATS_COMMAND))
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Time sync on a Proxmox VE node and a Proxmox Backup Server (``TimeSyncMixin``).
|
||||
|
||||
Neither API keeps time servers: ``/nodes/{node}/time`` knows only the zone, and
|
||||
both products run chrony on Debian. So the servers are
|
||||
:class:`~napalm_device_types.PosixTimeSyncMixin`'s, over the driver's SSH session
|
||||
(``run_command``, root): read from chrony's configuration, written to
|
||||
``/etc/chrony/sources.d/netork.sources`` with every other source commented out.
|
||||
|
||||
The zone is read with them, from the host (``timedatectl``, the zone the node's
|
||||
clock really runs in), and the API's ``GET /nodes/{node}/time`` answers only when
|
||||
the host names none. It is written through ``PUT /nodes/{node}/time``, not
|
||||
``timedatectl set-timezone``: Proxmox's own call validates the name and keeps
|
||||
``/etc/timezone``, which its web UI and API show, in step with ``/etc/localtime``.
|
||||
The token needs ``Sys.Modify`` for it (PVE on ``/nodes/{node}``, PBS on
|
||||
``/system/time``).
|
||||
|
||||
One device is one node: in a PVE cluster every node has its own clock, and only
|
||||
the node this connection resolved is read and written.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any, ClassVar
|
||||
|
||||
from napalm_device_types import TIME_SYNC_VALUES, PosixTimeSyncMixin, TimeSyncDict
|
||||
from napalm_device_types.models import FixStepOutcomeDict
|
||||
|
||||
_JsonDict = dict[str, Any]
|
||||
|
||||
|
||||
class ProxmoxTimeSyncMixin(PosixTimeSyncMixin):
|
||||
"""Servers through chrony over SSH, the zone through the node's API."""
|
||||
|
||||
time_sync_writes: ClassVar[frozenset[str]] = TIME_SYNC_VALUES
|
||||
|
||||
_node_name: str
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - the driver's (napalm_proxmox._base)
|
||||
|
||||
def _node_api(self) -> Any: ...
|
||||
def _get_node_time(self) -> _JsonDict: ...
|
||||
|
||||
def get_time_sync(self) -> TimeSyncDict:
|
||||
"""The node's time sources, zone and client: one round trip over SSH, and the
|
||||
API's zone only where the host names none.
|
||||
|
||||
:raises ValueError: when the reading came back cut short.
|
||||
:raises ConnectionException: when the node's shell could not be reached.
|
||||
"""
|
||||
found = super().get_time_sync()
|
||||
if found["timezone"] is None:
|
||||
found["timezone"] = self._get_node_time().get("timezone") or None
|
||||
return found
|
||||
|
||||
def get_ntp_servers(self) -> dict[str, _JsonDict]:
|
||||
"""NAPALM's shape of the servers ``get_time_sync`` reads, in chrony's order."""
|
||||
return {server: {} for server in super().get_time_sync()["ntp_servers"]}
|
||||
|
||||
def _write_time_zone(self, zone: str) -> FixStepOutcomeDict:
|
||||
path = f"PUT /nodes/{self._node_name}/time"
|
||||
try:
|
||||
self._node_api().time.put(timezone=zone)
|
||||
except Exception as exc:
|
||||
return {"ok": False, "output": f"{path}: {exc}"}
|
||||
return {"ok": True, "output": f"time zone set to {zone} ({path})"}
|
||||
+1
-1
@@ -21,7 +21,7 @@ classifiers = [
|
||||
requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"napalm>=5.0.0",
|
||||
"napalm_device_types>=4.34.0", # RunningBackupsMixin
|
||||
"napalm_device_types>=4.35.0", # TimeSyncMixin, PosixTimeSyncMixin
|
||||
"paramiko>=5.0.0", # CVE-2026-44405; imported directly for the node's SSH session (_base.py)
|
||||
"proxmoxer>=2.0.0",
|
||||
"netaddr>=0.9.0",
|
||||
|
||||
@@ -96,8 +96,6 @@ SDN_SUBNETS_VNET2: list = []
|
||||
# driver bug rather than bad test data.
|
||||
DNS_INFO = {"search": "example.com", "dns1": "8.8.8.8"}
|
||||
|
||||
NTP_INFO = {"server": "pool.ntp.org,time.cloudflare.com"}
|
||||
|
||||
NODE_NETSTAT = [
|
||||
{
|
||||
"dev": "eth0",
|
||||
@@ -164,7 +162,6 @@ def _build_mock_api(
|
||||
sdn_vnets=None,
|
||||
sdn_subnets=None,
|
||||
dns=None,
|
||||
ntp=None,
|
||||
netstat=None,
|
||||
pve_users=None,
|
||||
sensors=None,
|
||||
@@ -186,7 +183,6 @@ def _build_mock_api(
|
||||
node_res.status.get.return_value = node_status or NODE_STATUS
|
||||
node_res.network.get.return_value = network if network is not None else NODE_NETWORK
|
||||
node_res.dns.get.return_value = dns or DNS_INFO
|
||||
node_res.ntp.get.return_value = ntp or NTP_INFO
|
||||
node_res.netstat.get.return_value = netstat or NODE_NETSTAT
|
||||
node_res.hardware.sensors.get.return_value = sensors or []
|
||||
node_res.time.get.return_value = {}
|
||||
|
||||
@@ -43,6 +43,9 @@ class _Resource:
|
||||
def post(self, **params: Any) -> Any:
|
||||
return self._api.post(self._path, **params)
|
||||
|
||||
def put(self, **params: Any) -> Any:
|
||||
return self._api.put(self._path, **params)
|
||||
|
||||
|
||||
class FakePbsApi:
|
||||
"""``get``/``post``/``put``/``delete`` by path, like ``ProxmoxAPI.get("admin/gc")``,
|
||||
|
||||
+1
-13
@@ -1,4 +1,4 @@
|
||||
"""Tests for NTP, SNMP, users, config management, ping, traceroute, CLI."""
|
||||
"""Tests for NTP statistics, SNMP, users, config management, ping, traceroute, CLI."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -7,18 +7,6 @@ from unittest.mock import patch
|
||||
import pytest
|
||||
|
||||
|
||||
class TestGetNTPServers:
|
||||
def test_returns_configured_servers(self, driver):
|
||||
result = driver.get_ntp_servers()
|
||||
assert "pool.ntp.org" in result
|
||||
assert "time.cloudflare.com" in result
|
||||
|
||||
def test_empty_when_no_ntp(self, driver):
|
||||
driver._node_api().ntp.get.return_value = {}
|
||||
result = driver.get_ntp_servers()
|
||||
assert result == {}
|
||||
|
||||
|
||||
class TestGetNTPStats:
|
||||
NTP_OUTPUT = (
|
||||
"*192.168.1.1 10.0.0.1 4 u 12 64 377 1.234 0.567 0.123\n"
|
||||
|
||||
@@ -0,0 +1,358 @@
|
||||
"""Time sync on a Proxmox VE node and a Proxmox Backup Server (NetOrk/netork#2365).
|
||||
|
||||
Neither API keeps time servers: both products run chrony on Debian. The servers
|
||||
are napalm-device-types' ``PosixTimeSyncMixin``'s, over the driver's SSH session
|
||||
(``run_command``, as root); the zone is read from the host the same way and
|
||||
written through the product's own ``PUT /nodes/{node}/time``, which also keeps
|
||||
``/etc/timezone`` for the web UI. One netOrk device is one node: a PVE node in a
|
||||
cluster has its own clock, and only that node is written.
|
||||
|
||||
The readings are what ``reading_command`` prints on a PVE 8 / PBS 3 host (Debian
|
||||
12's chrony 4.3, its configuration comments shortened).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import CommandResult, PosixTimeSyncMixin, TimeSyncMixin
|
||||
from proxmoxer.core import ResourceException
|
||||
|
||||
from napalm_proxmox import ProxmoxBackupDriver, ProxmoxDriver
|
||||
from tests.conftest import _build_mock_api
|
||||
from tests.pbs_fake import FakePbsApi, forbidden
|
||||
|
||||
_ACTIVE_CHRONY = """\
|
||||
chrony chrony active
|
||||
chronyd chrony active
|
||||
systemd-timesyncd systemd-timesyncd inactive
|
||||
ntpsec ntpd inactive
|
||||
ntp ntpd inactive
|
||||
ntpd ntpd inactive
|
||||
openntpd openntpd inactive"""
|
||||
|
||||
_CHRONYC_SYNCED = """\
|
||||
MS Name/IP address Stratum Poll Reach LastRx Last sample
|
||||
===============================================================================
|
||||
^- 162.159.200.123 3 6 377 41 +814us[ +814us] +/- 14ms
|
||||
^* 185.248.188.98 2 6 377 40 -45us[ -63us] +/- 10ms"""
|
||||
|
||||
#: Debian 12's /etc/chrony/chrony.conf as Proxmox VE 8 and PBS 3 ship it.
|
||||
_CHRONY_CONF = """\
|
||||
# Welcome to the chrony configuration file. See chrony.conf(5) for more
|
||||
# information about usable directives.
|
||||
|
||||
# Include configuration files found in /etc/chrony/conf.d.
|
||||
confdir /etc/chrony/conf.d
|
||||
|
||||
# Use Debian vendor zone.
|
||||
{pool}pool 2.debian.pool.ntp.org iburst
|
||||
|
||||
# Use time sources from DHCP.
|
||||
{dhcp}sourcedir /run/chrony-dhcp
|
||||
|
||||
# Use NTP sources found in /etc/chrony/sources.d.
|
||||
sourcedir /etc/chrony/sources.d
|
||||
|
||||
keyfile /etc/chrony/chrony.keys
|
||||
driftfile /var/lib/chrony/chrony.drift
|
||||
ntsdumpdir /var/lib/chrony
|
||||
logdir /var/log/chrony
|
||||
maxupdateskew 100.0
|
||||
rtcsync
|
||||
makestep 1 3
|
||||
leapsectz right/UTC"""
|
||||
|
||||
_MARK = "#napalm-time-sync: "
|
||||
|
||||
|
||||
def _reading(
|
||||
zone: str = "Europe/Berlin", *, servers: tuple[str, ...] = (), timedatectl: bool = True
|
||||
) -> str:
|
||||
"""What the reading prints; *servers* in netOrk's sources file, the vendor's pool
|
||||
commented out with it (as a write leaves the host)."""
|
||||
written = bool(servers)
|
||||
conf = _CHRONY_CONF.format(pool=_MARK if written else "", dhcp=_MARK if written else "")
|
||||
parts = ["@@ts timedatectl"]
|
||||
if timedatectl:
|
||||
parts += [
|
||||
f"Timezone={zone}",
|
||||
"LocalRTC=no",
|
||||
"CanNTP=yes",
|
||||
"NTP=yes",
|
||||
"NTPSynchronized=yes",
|
||||
"TimeUSec=Wed 2026-11-11 14:23:16 CET",
|
||||
"RTCTimeUSec=Wed 2026-11-11 13:23:16 CET",
|
||||
]
|
||||
parts += ["@@ts zone", zone if timedatectl else ""]
|
||||
parts += ["@@ts active", _ACTIVE_CHRONY, "@@ts timesync", "@@ts chronyc", _CHRONYC_SYNCED]
|
||||
parts += ["@@ts chrony 0 main /etc/chrony/chrony.conf", conf, ""]
|
||||
if written:
|
||||
parts += ["@@ts chrony 14 sourcedir /etc/chrony/sources.d/netork.sources"]
|
||||
parts += [f"{'pool' if '.pool.' in s else 'server'} {s} iburst" for s in servers]
|
||||
parts += [""]
|
||||
parts += ["@@ts end", ""]
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
class Node:
|
||||
"""The node's command channel: the readings in turn (the last one stays), and
|
||||
every other command succeeds. Records ``(command, privileged, stdin)``."""
|
||||
|
||||
def __init__(self, *readings: str) -> None:
|
||||
self.readings = list(readings)
|
||||
self.calls: list[tuple[str, bool, bytes | None]] = []
|
||||
|
||||
def __call__(
|
||||
self,
|
||||
command: str,
|
||||
*,
|
||||
privileged: bool = False,
|
||||
timeout: float = 60,
|
||||
stdin: bytes | None = None,
|
||||
) -> CommandResult:
|
||||
self.calls.append((command, privileged, stdin))
|
||||
if "@@ts timedatectl" in command:
|
||||
reading = self.readings.pop(0) if len(self.readings) > 1 else self.readings[0]
|
||||
return CommandResult(reading, "", 0)
|
||||
if command.startswith("t=$(mktemp)"):
|
||||
return CommandResult("/tmp/tmp.Xk3fQ9", "", 0)
|
||||
return CommandResult("", "", 0)
|
||||
|
||||
def root(self) -> list[str]:
|
||||
return [c for c, privileged, _ in self.calls if privileged]
|
||||
|
||||
def staged(self) -> list[bytes]:
|
||||
return [stdin for _, _, stdin in self.calls if stdin is not None]
|
||||
|
||||
|
||||
def _pve(*readings: str, node: str | None = None) -> tuple[ProxmoxDriver, Any, Node]:
|
||||
args = {"verify_ssl": False} if node is None else {"verify_ssl": False, "node": node}
|
||||
driver = ProxmoxDriver("pve1.example.com", "root", "secret", optional_args=args)
|
||||
api = _build_mock_api()
|
||||
with patch("napalm_proxmox.driver.ProxmoxAPI", return_value=api):
|
||||
driver.open()
|
||||
shell = Node(*readings)
|
||||
driver.run_command = shell # type: ignore[method-assign]
|
||||
return driver, api, shell
|
||||
|
||||
|
||||
def _pbs(*readings: str, **responses: Any) -> tuple[ProxmoxBackupDriver, FakePbsApi, Node]:
|
||||
api = FakePbsApi(**responses)
|
||||
driver = ProxmoxBackupDriver("pbs1.example.com", "root@pam", "secret")
|
||||
with patch("napalm_proxmox.backup_driver.ProxmoxAPI", return_value=api):
|
||||
driver.open()
|
||||
shell = Node(*readings)
|
||||
driver.run_command = shell # type: ignore[method-assign]
|
||||
return driver, api, shell
|
||||
|
||||
|
||||
# -- the contract -----------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cls", [ProxmoxDriver, ProxmoxBackupDriver], ids=["pve", "pbs"])
|
||||
def test_both_drivers_read_and_write_servers_and_zone(cls: type) -> None:
|
||||
assert issubclass(cls, TimeSyncMixin)
|
||||
assert issubclass(cls, PosixTimeSyncMixin)
|
||||
assert callable(getattr(cls, "get_time_sync", None))
|
||||
assert callable(getattr(cls, "configure_time_sync", None))
|
||||
assert cls.time_sync_writes == frozenset({"ntp_servers", "timezone"})
|
||||
|
||||
|
||||
# -- reading ----------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_pve_reads_chrony_and_the_zone_in_one_round_trip() -> None:
|
||||
driver, api, shell = _pve(_reading())
|
||||
|
||||
assert driver.get_time_sync() == {
|
||||
"ntp_servers": ["2.debian.pool.ntp.org"],
|
||||
"timezone": "Europe/Berlin",
|
||||
"synchronized": True,
|
||||
"daemon": "chrony",
|
||||
}
|
||||
assert len(shell.calls) == 1
|
||||
assert shell.root() == [] # the reading writes nothing
|
||||
api.nodes.return_value.time.put.assert_not_called()
|
||||
|
||||
|
||||
def test_pbs_reads_chrony_and_the_zone() -> None:
|
||||
driver, api, shell = _pbs(_reading("Europe/Vienna", servers=("10.0.0.1",)))
|
||||
|
||||
assert driver.get_time_sync() == {
|
||||
"ntp_servers": ["10.0.0.1"],
|
||||
"timezone": "Europe/Vienna",
|
||||
"synchronized": True,
|
||||
"daemon": "chrony",
|
||||
}
|
||||
assert len(shell.calls) == 1
|
||||
assert not [c for c in api.calls if c[0] != "GET"]
|
||||
|
||||
|
||||
def test_a_host_without_a_zone_of_its_own_reads_the_apis() -> None:
|
||||
"""No timedatectl and no /etc/timezone or /etc/localtime link: the API's word."""
|
||||
driver, api, _ = _pve(_reading(timedatectl=False))
|
||||
api.nodes.return_value.time.get.return_value = {"timezone": "Europe/Paris"}
|
||||
|
||||
assert driver.get_time_sync()["timezone"] == "Europe/Paris"
|
||||
|
||||
|
||||
def test_no_zone_anywhere_reads_none() -> None:
|
||||
driver, _, _ = _pbs(_reading(timedatectl=False), **{"nodes/localhost/time": forbidden()})
|
||||
|
||||
assert driver.get_time_sync()["timezone"] is None
|
||||
|
||||
|
||||
def test_a_cut_reading_raises() -> None:
|
||||
driver, _, _ = _pve("@@ts timedatectl\nTimezone=Europe/Berlin\n")
|
||||
|
||||
with pytest.raises(ValueError, match="cut short"):
|
||||
driver.get_time_sync()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("make", [_pve, _pbs], ids=["pve", "pbs"])
|
||||
def test_get_ntp_servers_is_what_get_time_sync_reads(make: Any) -> None:
|
||||
servers = ("10.0.0.1", "0.de.pool.ntp.org")
|
||||
driver, _, _ = make(_reading(servers=servers))
|
||||
|
||||
assert list(driver.get_ntp_servers()) == list(servers)
|
||||
assert driver.get_ntp_servers() == {s: {} for s in driver.get_time_sync()["ntp_servers"]}
|
||||
|
||||
|
||||
def test_get_ntp_servers_no_longer_asks_an_api_path_pve_does_not_have() -> None:
|
||||
"""``GET /nodes/{node}/ntp`` does not exist; asking it read as "no servers"."""
|
||||
driver, api, _ = _pve(_reading())
|
||||
|
||||
assert driver.get_ntp_servers() == {"2.debian.pool.ntp.org": {}}
|
||||
api.nodes.return_value.ntp.get.assert_not_called()
|
||||
|
||||
|
||||
# -- writing the zone -------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_pve_writes_the_zone_through_its_node_api_and_reads_it_back() -> None:
|
||||
driver, api, shell = _pve(_reading("Europe/Vienna"))
|
||||
|
||||
result = driver.configure_time_sync(timezone="Europe/Vienna")
|
||||
|
||||
assert result["success"], result["output"]
|
||||
assert [s["step"] for s in result["steps"]] == ["timezone", "verify"]
|
||||
api.nodes.return_value.time.put.assert_called_once_with(timezone="Europe/Vienna")
|
||||
assert shell.root() == [] # not timedatectl: the API keeps /etc/timezone as well
|
||||
|
||||
|
||||
def test_in_a_cluster_only_this_node_is_written() -> None:
|
||||
driver, api, _ = _pve(_reading("Europe/Vienna"), node="pve2")
|
||||
api.nodes.reset_mock()
|
||||
|
||||
driver.configure_time_sync(timezone="Europe/Vienna")
|
||||
|
||||
assert {c.args for c in api.nodes.call_args_list} == {("pve2",)}
|
||||
api.nodes.return_value.time.put.assert_called_once_with(timezone="Europe/Vienna")
|
||||
|
||||
|
||||
def test_pbs_writes_the_zone_through_its_api() -> None:
|
||||
driver, api, _ = _pbs(_reading("Europe/Vienna"), **{"PUT nodes/localhost/time": None})
|
||||
|
||||
result = driver.configure_time_sync(timezone="Europe/Vienna")
|
||||
|
||||
assert result["success"], result["output"]
|
||||
assert ("PUT", "nodes/localhost/time", {"timezone": "Europe/Vienna"}) in api.calls
|
||||
|
||||
|
||||
def test_a_refused_zone_fails_the_step_and_says_why() -> None:
|
||||
"""An API token without ``Sys.Modify``: the step fails, nothing else is tried."""
|
||||
driver, api, shell = _pbs(_reading(), **{"PUT nodes/localhost/time": forbidden()})
|
||||
|
||||
result = driver.configure_time_sync(timezone="Europe/Vienna")
|
||||
|
||||
assert not result["success"]
|
||||
assert result["steps"][-1]["step"] == "timezone"
|
||||
assert "403" in result["steps"][-1]["output"]
|
||||
assert shell.calls == []
|
||||
|
||||
|
||||
def test_a_zone_the_device_did_not_take_fails_verify() -> None:
|
||||
driver, api, _ = _pve(_reading("Europe/Berlin"))
|
||||
|
||||
result = driver.configure_time_sync(timezone="Europe/Vienna")
|
||||
|
||||
assert not result["success"]
|
||||
assert result["steps"][-1] == {
|
||||
"step": "verify",
|
||||
"ok": False,
|
||||
"output": "the device is in the time zone Europe/Berlin",
|
||||
}
|
||||
|
||||
|
||||
def test_a_proxmoxer_error_on_the_zone_is_the_steps_output() -> None:
|
||||
driver, api, _ = _pve(_reading())
|
||||
api.nodes.return_value.time.put.side_effect = ResourceException(
|
||||
400, "Bad Request", "Parameter verification failed: timezone: No such timezone"
|
||||
)
|
||||
|
||||
result = driver.configure_time_sync(timezone="Europe/Vienna")
|
||||
|
||||
assert not result["success"]
|
||||
assert "No such timezone" in result["steps"][0]["output"]
|
||||
|
||||
|
||||
# -- writing the servers ----------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize("make", [_pve, _pbs], ids=["pve", "pbs"])
|
||||
def test_servers_go_to_chronys_sources_d_and_the_vendor_pool_stops_counting(make: Any) -> None:
|
||||
servers = ["10.0.0.1", "0.de.pool.ntp.org"]
|
||||
driver, _, shell = make(_reading(), _reading(servers=tuple(servers)))
|
||||
|
||||
result = driver.configure_time_sync(ntp_servers=servers)
|
||||
|
||||
assert result["success"], result["output"]
|
||||
assert shell.staged() == [b"server 10.0.0.1 iburst\npool 0.de.pool.ntp.org iburst\n"]
|
||||
root = shell.root()
|
||||
assert any(
|
||||
"/etc/chrony/sources.d/netork.sources" in c and c.startswith("install") for c in root
|
||||
)
|
||||
# line 8 is the vendor's pool, line 11 the DHCP sourcedir: both in the main file,
|
||||
# which chronyd reads only when it starts.
|
||||
sed = next(c for c in root if c.startswith("sed -i"))
|
||||
assert "8{" in sed and "11{" in sed and sed.endswith("/etc/chrony/chrony.conf")
|
||||
assert root[-1] == "systemctl restart chrony.service"
|
||||
|
||||
|
||||
def test_servers_already_written_are_written_the_same_way_again() -> None:
|
||||
"""No churn: the second write stages the same file and comments out nothing."""
|
||||
servers = ("10.0.0.1",)
|
||||
driver, _, shell = _pve(_reading(servers=servers))
|
||||
|
||||
result = driver.configure_time_sync(ntp_servers=list(servers))
|
||||
|
||||
assert result["success"], result["output"]
|
||||
assert shell.staged() == [b"server 10.0.0.1 iburst\n"]
|
||||
assert not [c for c in shell.root() if c.startswith("sed")]
|
||||
assert "chronyc reload sources" in shell.root()
|
||||
|
||||
|
||||
def test_both_values_in_one_change() -> None:
|
||||
driver, api, _ = _pve(_reading(), _reading("Europe/Vienna", servers=("10.0.0.1",)))
|
||||
|
||||
result = driver.configure_time_sync(ntp_servers=["10.0.0.1"], timezone="Europe/Vienna")
|
||||
|
||||
assert result["success"], result["output"]
|
||||
assert [s["step"] for s in result["steps"]] == ["ntp_servers", "timezone", "verify"]
|
||||
api.nodes.return_value.time.put.assert_called_once_with(timezone="Europe/Vienna")
|
||||
|
||||
|
||||
def test_the_templates_refusals_hold() -> None:
|
||||
driver, api, shell = _pve(_reading())
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
driver.configure_time_sync()
|
||||
with pytest.raises(ValueError):
|
||||
driver.configure_time_sync(ntp_servers=["not a server"])
|
||||
with pytest.raises(ValueError):
|
||||
driver.configure_time_sync(timezone="CET-1CEST,M3.5.0,M10.5.0/3")
|
||||
assert shell.calls == []
|
||||
api.nodes.return_value.time.put.assert_not_called()
|
||||
Reference in new issue
Block a user