diff --git a/CHANGELOG.md b/CHANGELOG.md index a640423..cd9e856 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,6 +51,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `get_lldp_neighbors()` lists every neighbour of a port: a second neighbour on the same port no longer overwrites the first, and a neighbour that sends no system name is listed with an empty `hostname` instead of being dropped (#22). +- `set_hostname()` renames only the node's own names in `/etc/hosts`: other + hosts whose names start with the old one (`pve-backup`) and comments stay as + they are, and the old FQDN becomes the new one instead of a mix of both (#21). ## [0.8.0] - 2026-10-23 diff --git a/napalm_proxmox/system_mixin.py b/napalm_proxmox/system_mixin.py index fa8e74e..7f63931 100644 --- a/napalm_proxmox/system_mixin.py +++ b/napalm_proxmox/system_mixin.py @@ -49,6 +49,30 @@ _SNMP_WORD = re.compile(r'^[^\s"#]+$') _SNMPD_CONF = "/etc/snmp/snmpd.conf" +def _rename_in_hosts(hosts: str, old_short: str, new_short: str, new_domain: str | None) -> str: + """*hosts* (an /etc/hosts) with the node's names renamed from *old_short*. + + Only whole names change: ``old_short`` becomes ``new_short``, and + ``old_short.`` becomes ``new_short.`` (the old domain + kept when *new_domain* is None). Other names that merely start with the + old name (``pve-backup``) and comments stay as they are. + """ + + def rename(match: re.Match[str]) -> str: + name = match.group(0) + if name == old_short: + return new_short + if name.startswith(f"{old_short}."): + return f"{new_short}.{new_domain or name[len(old_short) + 1 :]}" + return name + + lines = [] + for line in hosts.splitlines(keepends=True): + entry, hash_, comment = line.partition("#") + lines.append(re.sub(r"\S+", rename, entry) + hash_ + comment) + return "".join(lines) + + def _net(value: str) -> str: return str(ipaddress.ip_network(value.strip(), strict=False)) @@ -633,17 +657,7 @@ class ProxmoxSystemMixin: # write back via base64 to avoid shell-escaping issues. if old_short and old_short != short_hostname: hosts_raw = self._exec_ssh_command("cat /etc/hosts 2>/dev/null") - # Replace whole-word occurrences of the old short hostname. - # Both "hostname" and "hostname.domain" forms are covered because - # the new value is the full fqdn when a domain was given. - import re as _re - - new_replace = fqdn if domain else short_hostname - hosts_new = _re.sub( - r"\b" + _re.escape(old_short) + r"\b", - new_replace, - hosts_raw, - ) + hosts_new = _rename_in_hosts(hosts_raw, old_short, short_hostname, domain) hosts_b64 = _b64.b64encode(hosts_new.encode()).decode() self._exec_ssh_command( f"echo {hosts_b64} | base64 -d > /tmp/_netork_hosts" diff --git a/tests/quality_baseline.json b/tests/quality_baseline.json index 75fd5b4..17d19e2 100644 --- a/tests/quality_baseline.json +++ b/tests/quality_baseline.json @@ -36,7 +36,7 @@ "napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.get_disk_smart": 74, "napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.get_packages": 66, "napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.get_users": 51, - "napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.set_hostname": 124, + "napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.set_hostname": 114, "napalm_proxmox/vm_mixin.py::ProxmoxVMMixin.get_vm_interfaces": 179, "napalm_proxmox/vm_mixin.py::ProxmoxVMMixin.get_vms": 114, "napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin._download_cloud_image": 61, diff --git a/tests/test_set_hostname.py b/tests/test_set_hostname.py new file mode 100644 index 0000000..cc59e31 --- /dev/null +++ b/tests/test_set_hostname.py @@ -0,0 +1,72 @@ +"""set_hostname: what it writes to /etc/hosts (napalm-proxmox#21).""" + +from __future__ import annotations + +import base64 +import re + +import pytest + +from napalm_proxmox import ProxmoxDriver + +HOSTS = """\ +127.0.0.1 localhost.localdomain localhost +# pve is the node; pve-backup its backup target +10.0.0.1 pve.old.lan pve +10.0.0.2 pve-backup.old.lan pve-backup +""" + + +class _Node: + """The node's shell: /etc/hostname reads "pve", /etc/hosts reads HOSTS.""" + + def __init__(self) -> None: + self.ran: list[str] = [] + + def __call__(self, command: str) -> str: + self.ran.append(command) + if command.startswith("cat /etc/hostname"): + return "pve\n" + if command.startswith("cat /etc/hosts"): + return HOSTS + return "" + + def written_hosts(self) -> str: + write = next(c for c in self.ran if c.rstrip().endswith("chmod 644 /etc/hosts")) + return base64.b64decode(re.match(r"echo (\S+) \| base64 -d", write).group(1)).decode() + + +@pytest.fixture +def node() -> _Node: + return _Node() + + +@pytest.fixture +def driver(node: _Node) -> ProxmoxDriver: + d = ProxmoxDriver("pve", "root@pam", "pw") + d._exec_ssh_command = node + return d + + +def test_an_fqdn_renames_the_nodes_names_and_nothing_else(driver, node): + driver.set_hostname("new.dom.lan") + + assert node.written_hosts() == ( + "127.0.0.1 localhost.localdomain localhost\n" + "# pve is the node; pve-backup its backup target\n" + "10.0.0.1 new.dom.lan new\n" + "10.0.0.2 pve-backup.old.lan pve-backup\n" + ) + + +def test_a_short_name_keeps_the_old_domain(driver, node): + driver.set_hostname("new") + + assert "10.0.0.1 new.old.lan new\n" in node.written_hosts() + assert "10.0.0.2 pve-backup.old.lan pve-backup\n" in node.written_hosts() + + +def test_the_same_name_leaves_hosts_alone(driver, node): + driver.set_hostname("pve") + + assert not any("/etc/hosts" in c and "base64 -d" in c for c in node.ran)