diff --git a/CHANGELOG.md b/CHANGELOG.md index 67e7acc..6aed5ad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,14 @@ All notable changes to this driver. The format follows ## [Unreleased] +### Added +- `set_hostname()` the way OMV's web UI renames the NAS: `Network.setGeneralSettings` + (an FQDN sets the domain too, a bare name keeps it), then `Config.applyChanges` for the + modules the rename made dirty plus the hostname modules already dirty. Changes left + pending in the web UI are not deployed with it. Replaces the inherited napalm-linux + rename (NAPALM/napalm-linux#45), whose `/etc/hostname` and `/etc/hosts` OMV would + regenerate on its next apply. + ### Changed - 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). diff --git a/napalm_openmediavault/openmediavault.py b/napalm_openmediavault/openmediavault.py index 0b070d7..0bc92f6 100644 --- a/napalm_openmediavault/openmediavault.py +++ b/napalm_openmediavault/openmediavault.py @@ -20,6 +20,7 @@ from __future__ import annotations import json as _json import logging import re +from shlex import quote as _shlex_quote from typing import Any from napalm_device_types import FingerprintRule, StorageDriver @@ -37,6 +38,15 @@ from napalm_linux.linux import LinuxDriver logger = logging.getLogger(__name__) +#: One label of a hostname (RFC 1123); OMV's own schema asks the same. +_HOSTNAME_LABEL_RE = re.compile(r"^(?!-)[A-Za-z0-9-]{1,63}(? None: + """Rename the NAS the way OMV's web UI does, through its own database. + + LinuxDriver's rename writes ``/etc/hostname`` and ``/etc/hosts``, which + OMV regenerates from ``conf.system.network.dns`` on its next apply. So the + name goes to ``Network.setGeneralSettings`` -- an FQDN sets the domain as + well, a bare name keeps it -- and ``Config.applyChanges`` deploys the + modules the rename made dirty, plus the hostname modules that already + were. Other changes pending in the web UI stay pending. + + :raises ValueError: for a name that is not a valid hostname, before + anything runs on the NAS. + :raises RuntimeError: when OMV refuses a step. + """ + labels = new_hostname.split(".") + if len(new_hostname) > 253 or not all(_HOSTNAME_LABEL_RE.match(x) for x in labels): + raise ValueError(f"not a valid hostname: {new_hostname!r}") + current = self._omv_rpc("Network", "getGeneralSettings") + domain = ".".join(labels[1:]) if len(labels) > 1 else current.get("domainname", "") + before = set(self._omv_dirty_modules()) + self._omv_rpc( + "Network", "setGeneralSettings", {"hostname": labels[0], "domainname": domain} + ) + after = set(self._omv_dirty_modules()) + modules = sorted((after - before) | (after & _HOSTNAME_MODULES)) + if modules: + # Salt restarts what it deploys (Samba, Postfix, networkd): give it time. + self._omv_rpc("Config", "applyChanges", {"modules": modules, "force": False}, 600) + + def _omv_rpc( + self, service: str, method: str, params: dict[str, Any] | None = None, timeout: float = 60 + ) -> Any: + """Call ``omv-rpc`` as root and return its decoded answer. + + :raises RuntimeError: when the call fails, with OMV's answer. + """ + command = f"omv-rpc -u admin {service} {method}" + if params is not None: + command += f" {_shlex_quote(_json.dumps(params))}" + output, status = self._sudo_status(command, timeout) + if status != 0: + raise RuntimeError(f"omv-rpc {service}.{method} failed: {output[-300:]}") + lines = output.splitlines() + return _json.loads(lines[-1]) if lines else None + + def _omv_dirty_modules(self) -> list[str]: + """The modules with configuration changes not yet deployed.""" + output, _status = self._sudo_status(f"cat {_DIRTY_MODULES} 2>/dev/null || echo '[]'", 30) + try: + dirty = _json.loads(output or "[]") + except ValueError: + return [] + return [m for m in dirty if isinstance(m, str)] if isinstance(dirty, list) else [] + # ── Physical disks ───────────────────────────────────────────────────────── def get_disks(self) -> list[PhysicalDiskDict]: diff --git a/tests/test_set_hostname.py b/tests/test_set_hostname.py new file mode 100644 index 0000000..cda826e --- /dev/null +++ b/tests/test_set_hostname.py @@ -0,0 +1,154 @@ +"""OpenMediaVault renames itself through its own database, not through /etc. + +The rename napalm-linux offers (``hostnamectl``, ``/etc/hosts``) would be taken +back by the next apply of OMV's settings, which regenerates both from +``conf.system.network.dns``. So the name goes where OMV's web UI puts it: +``Network.setGeneralSettings``, then ``Config.applyChanges`` -- for the modules +the rename made dirty only, so changes someone left pending in the web UI +(here ``apt`` and ``rsyslog``) are not deployed along with it. +""" + +from __future__ import annotations + +import json +import shlex + +import pytest + +from napalm_openmediavault.openmediavault import OpenMediaVaultDriver + +_RENAME_DIRTIES = ["hostname", "hosts", "postfix", "avahi", "samba", "systemdnetworkd"] + + +class Omv: + """The NAS as ``_sudo_status`` sees it: omv-rpc calls and the dirty-modules file.""" + + def __init__(self, *, dirty=("apt", "rsyslog"), fail=""): + self.settings = {"hostname": "nas", "domainname": "home.example"} + self.dirty = list(dirty) + self.fail = fail + self.calls: list[tuple[str, str, object]] = [] + self.commands: list[str] = [] + + def __call__(self, command: str, read_timeout: float = 100) -> tuple[str, int | None]: + self.commands.append(command) + if command.startswith("cat /var/lib/openmediavault/dirtymodules.json"): + return json.dumps(self.dirty), 0 + argv = shlex.split(command) + assert argv[:3] == ["omv-rpc", "-u", "admin"], command + service, method = argv[3], argv[4] + params = json.loads(argv[5]) if len(argv) > 5 else None + self.calls.append((service, method, params)) + if f"{service}.{method}" == self.fail: + return '{"response":null,"error":{"message":"boom"}}', 1 + if (service, method) == ("Network", "getGeneralSettings"): + return json.dumps(self.settings), 0 + if (service, method) == ("Network", "setGeneralSettings"): + self.settings = params + self.dirty += [m for m in _RENAME_DIRTIES if m not in self.dirty] + return json.dumps(params), 0 + if (service, method) == ("Config", "applyChanges"): + self.dirty = [m for m in self.dirty if m not in params["modules"]] + return "null", 0 + raise AssertionError(command) + + def call(self, method: str): + return [params for s, m, params in self.calls if f"{s}.{m}" == method] + + +def _driver(omv: Omv) -> OpenMediaVaultDriver: + driver = OpenMediaVaultDriver("nas", "admin", "p") + driver._sudo_status = omv # type: ignore[method-assign] + return driver + + +def test_bare_name_keeps_the_domain(): + omv = Omv() + + _driver(omv).set_hostname("nas2") + + assert omv.call("Network.setGeneralSettings") == [ + {"hostname": "nas2", "domainname": "home.example"} + ] + + +def test_fqdn_sets_the_domain_too(): + omv = Omv() + + _driver(omv).set_hostname("nas2.lab.example") + + assert omv.call("Network.setGeneralSettings") == [ + {"hostname": "nas2", "domainname": "lab.example"} + ] + + +def test_only_what_the_rename_made_dirty_is_applied(): + omv = Omv() + + _driver(omv).set_hostname("nas2") + + assert omv.call("Config.applyChanges") == [{"modules": sorted(_RENAME_DIRTIES), "force": False}] + assert omv.dirty == ["apt", "rsyslog"] + + +def test_a_hostname_module_already_dirty_is_applied_as_well(): + omv = Omv(dirty=("apt", "samba")) + + _driver(omv).set_hostname("nas2") + + (apply,) = omv.call("Config.applyChanges") + assert "samba" in apply["modules"] + assert "apt" not in apply["modules"] + + +def test_nothing_dirty_nothing_applied(): + omv = Omv() + omv.settings = {"hostname": "nas2", "domainname": "home.example"} + + driver = _driver(omv) + driver._sudo_status = _no_new_dirt(omv) # type: ignore[method-assign] + driver.set_hostname("nas2") + + assert omv.call("Config.applyChanges") == [] + + +def _no_new_dirt(omv: Omv): + """OMV marks nothing dirty when the settings did not change.""" + + def status(command: str, read_timeout: float = 100): + if "setGeneralSettings" in command: + omv.calls.append(("Network", "setGeneralSettings", json.loads(shlex.split(command)[5]))) + return json.dumps(omv.settings), 0 + return omv(command, read_timeout) + + return status + + +@pytest.mark.parametrize("name", ["", "nas_2", "-nas", "nas.", "a" * 64, "nas;reboot", "$(id)"]) +def test_invalid_name_runs_nothing(name): + omv = Omv() + + with pytest.raises(ValueError): + _driver(omv).set_hostname(name) + + assert omv.commands == [] + + +def test_unreadable_settings_change_nothing(): + omv = Omv(fail="Network.getGeneralSettings") + + with pytest.raises(RuntimeError, match="getGeneralSettings"): + _driver(omv).set_hostname("nas2") + + assert omv.call("Network.setGeneralSettings") == [] + + +def test_failed_apply_raises(): + omv = Omv(fail="Config.applyChanges") + + with pytest.raises(RuntimeError, match="applyChanges"): + _driver(omv).set_hostname("nas2") + + +def test_offered_as_a_capability(): + assert callable(getattr(OpenMediaVaultDriver, "set_hostname", None))