feat: set_hostname through OMV's own database
driver / standard (pull_request) Successful in 17s
driver / lint (pull_request) Successful in 15s
driver / types (pull_request) Successful in 1m7s
driver / test (3.13) (pull_request) Successful in 1m0s
driver / lowest (pull_request) Successful in 26s
driver / security (pull_request) Successful in 1m9s
driver / build (pull_request) Successful in 31s
driver / test (3.12) (pull_request) Successful in 1m9s
CI / driver (pull_request) Successful in 1m9s
driver / publish (pull_request) Skipped

napalm-linux now renames a host through hostnamectl, /etc/hostname and
/etc/hosts (NAPALM/napalm-linux#45). OMV regenerates those files from
conf.system.network.dns on its next apply, so the inherited rename would
not last.

set_hostname() goes where OMV's web UI goes: Network.setGeneralSettings
(an FQDN sets the domain too, a bare name keeps it), then
Config.applyChanges with an explicit module list -- the modules the
rename made dirty, plus the hostname modules that already were. Changes
someone left pending in the web UI stay pending. Checked against the RPC
sources of OMV 8.6 (rpc/network.inc, rpc/config.inc).
This commit is contained in:
Christian Manivong committed 2026-10-29 23:11:04 +01:00
1 parent 879e4a6d87
commit de8f041100
3 files changed
+228

No files matched your search

+66
View File
@@ -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}(?<!-)$")
#: The modules OMV regenerates from ``conf.system.network.dns``. One already
#: dirty before the rename is applied with it, or the new name would not reach it.
_HOSTNAME_MODULES = frozenset(
{"hostname", "hosts", "postfix", "avahi", "samba", "proftpd", "systemdnetworkd"}
)
_DIRTY_MODULES = "/var/lib/openmediavault/dirtymodules.json"
class OpenMediaVaultDriver(StorageDriver, LinuxDriver):
"""NAPALM driver for OpenMediaVault NAS systems.
@@ -84,6 +94,62 @@ class OpenMediaVaultDriver(StorageDriver, LinuxDriver):
logger.debug("%s: OMV version not read: ignored", self.hostname, exc_info=True)
return facts
# ── Hostname ───────────────────────────────────────────────────────────────
def set_hostname(self, new_hostname: str) -> 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]: