From 4108eb83dd7f6690171b927c66e17554e866f381 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Thu, 29 Oct 2026 21:57:40 +0100 Subject: [PATCH] feat: set_hostname renames the host (#45) netOrk could save a Linux host's new name but not apply it: the driver had no set_hostname(), so apply-hostname answered "The driver linux does not support set_hostname()". HostnameMixin.set_hostname() takes a bare name or an FQDN. The short name goes to hostnamectl, or to /etc/hostname and hostname(1) without systemd. /etc/hosts follows: every line naming the old name, else the 127.0.1.1 line; a file with neither is left alone. A cloud-init host gets preserve_hostname: true, or its next boot restores the image's name. Names that are not RFC 1123 hostnames are refused before anything runs. Files are staged unprivileged and installed by root (_install_file_as_root), never written from privileged stdin. It lives in its own module because linux.py may not grow (quality ratchet); the two lines it adds there are offset by a stale comment and an import that fits on one line, so the baseline drops to 2286. --- CHANGELOG.md | 8 + napalm_linux/_hostname.py | 145 ++++++++++++++++++ napalm_linux/linux.py | 8 +- tests/quality_baseline.json | 2 +- tests/test_set_hostname.py | 289 ++++++++++++++++++++++++++++++++++++ 5 files changed, 446 insertions(+), 6 deletions(-) create mode 100644 napalm_linux/_hostname.py create mode 100644 tests/test_set_hostname.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 91909fc..4709f0d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added +- `set_hostname()` (#45): netOrk could save a Linux host's new name but not apply it + ("The driver linux does not support set_hostname()"). The host now takes the short + name through `hostnamectl`, or `/etc/hostname` and `hostname(1)` without systemd; + `/etc/hosts` follows (the lines naming the old name, else the `127.0.1.1` line), and a + cloud-init host gets `preserve_hostname: true` so its next boot keeps the name. Names + that are not valid hostnames are refused before anything runs on the host. + ### 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_linux/_hostname.py b/napalm_linux/_hostname.py new file mode 100644 index 0000000..c797ef1 --- /dev/null +++ b/napalm_linux/_hostname.py @@ -0,0 +1,145 @@ +"""Renaming the host: static and runtime hostname, ``/etc/hosts``, cloud-init (#45).""" + +from __future__ import annotations + +import re +from shlex import quote as _shlex_quote +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from napalm_device_types import CommandResult + from napalm_device_types.models import FixStepOutcomeDict + +#: One label of a hostname (RFC 1123): letters, digits and inner hyphens. It +#: also keeps every name ``set_hostname`` accepts safe in a root shell. +_LABEL_RE = re.compile(r"^(?!-)[A-Za-z0-9-]{1,63}(?/dev/null") +#: Without this, cloud-init's ``update_hostname`` puts the image's name back on +#: the next boot. +_CLOUD_INIT_PRESERVE = "/etc/cloud/cloud.cfg.d/99-preserve-hostname.cfg" +_CLOUD_INIT_PRESERVE_CONTENT = ( + "# The hostname was set on purpose: keep it across reboots.\npreserve_hostname: true\n" +) + + +def _split_hostname(name: str) -> tuple[str, str | None]: + """``(short name, FQDN or None)`` of *name*. + + :raises ValueError: when *name* is not a valid hostname or FQDN. + """ + labels = name.split(".") + if len(name) > 253 or not all(_LABEL_RE.match(label) for label in labels): + raise ValueError(f"not a valid hostname: {name!r}") + return labels[0], (name if len(labels) > 1 else None) + + +def _renamed_line(line: str, targets: set[str], new: list[str]) -> str | None: + """*line* of ``/etc/hosts`` with *new* where the first of *targets* stood. + + The other names on it stay; ``None`` when the line names none of *targets*. + """ + entry, hash_, comment = line.partition("#") + address, *names = entry.split() or [""] + if not any(n.lower() in targets for n in names): + return None + result: list[str] = [] + inserted = False + for name in names: + if name.lower() not in targets: + result.append(name) + elif not inserted: + result += new + inserted = True + tail = f" {hash_}{comment}" if hash_ else "" + return f"{address}\t{' '.join(dict.fromkeys(result))}{tail}" + + +def _rename_in_hosts(content: str, old_names: set[str], short: str, fqdn: str | None) -> str: + """*content* of ``/etc/hosts`` with the host's old names replaced by the new. + + Every line naming the host gets the new names. When no line names it, the + Debian ``127.0.1.1`` line takes them; a file with neither is returned + unchanged -- nothing is appended to a host that never listed itself. + """ + old = {n.lower() for n in old_names} - _LOOPBACK_NAMES + new = [fqdn, short] if fqdn else [short] + lines = content.split("\n") + renamed = [_renamed_line(line, old, new) for line in lines] + if all(r is None for r in renamed): + renamed = _renamed_self_line(lines, new) + return "\n".join(r or line for line, r in zip(lines, renamed, strict=True)) + + +def _renamed_self_line(lines: list[str], new: list[str]) -> list[str | None]: + """The first ``127.0.1.1`` line of *lines* naming *new* instead, the rest ``None``.""" + result: list[str | None] = [None] * len(lines) + for i, line in enumerate(lines): + address, *names = line.partition("#")[0].split() or [""] + if address == "127.0.1.1" and names: + result[i] = _renamed_line(line, {n.lower() for n in names}, new) + break + return result + + +class HostnameMixin: + """``set_hostname`` for a Linux host, over the driver's command channel.""" + + if TYPE_CHECKING: + + def run_command( + self, + command: str, + *, + privileged: bool = False, + timeout: float = 60, + stdin: bytes | None = None, + ) -> CommandResult: ... + + def _install_file_as_root(self, path: str, content: str) -> CommandResult: ... + + def _root_outcome(self, command: str, timeout: float, done: str) -> FixStepOutcomeDict: ... + + def set_hostname(self, new_hostname: str) -> None: + """Rename the host: static and runtime hostname, ``/etc/hosts``, cloud-init. + + Takes a bare name or an FQDN; the hostname itself is the short name, and + an FQDN goes to ``/etc/hosts`` in front of it. ``hostnamectl`` sets it + where there is one, otherwise ``/etc/hostname`` and ``hostname(1)``. + Files are installed from a staged copy (``_install_file_as_root``). + + :raises ValueError: for a name that is not a valid hostname, before + anything runs on the host. + :raises RuntimeError: when the host refuses a step; the steps before it + stay done. + """ + short, fqdn = _split_hostname(new_hostname) + old_names = {self.run_command(c, timeout=30).stdout.strip() for c in _OLD_NAME_COMMANDS} + hosts = self.run_command("cat /etc/hosts", timeout=30) + + name = _shlex_quote(short) + outcome = self._root_outcome( + f"if command -v hostnamectl >/dev/null 2>&1 && hostnamectl set-hostname {name} " + f"2>/dev/null; then :; else printf '%s\\n' {name} > /etc/hostname " + f"&& hostname {name}; fi", + 30, + "", + ) + if not outcome["ok"]: + raise RuntimeError(outcome["output"] or "the host refused the new hostname") + + if hosts.exit_code == 0: + renamed = _rename_in_hosts(hosts.stdout, old_names - {""}, short, fqdn) + if renamed != hosts.stdout: + self._install_or_raise("/etc/hosts", renamed) + if self.run_command("test -d /etc/cloud/cloud.cfg.d", timeout=30).exit_code == 0: + self._install_or_raise(_CLOUD_INIT_PRESERVE, _CLOUD_INIT_PRESERVE_CONTENT) + + def _install_or_raise(self, path: str, content: str) -> None: + """``_install_file_as_root``, raising its output when it failed.""" + result = self._install_file_as_root(path, content) + if result.exit_code != 0: + reason = (result.stderr or result.stdout).strip() or f"status {result.exit_code}" + raise RuntimeError(f"hostname set, but {path} could not be written: {reason}") diff --git a/napalm_linux/linux.py b/napalm_linux/linux.py index ba781c2..3a7e41d 100644 --- a/napalm_linux/linux.py +++ b/napalm_linux/linux.py @@ -69,11 +69,9 @@ from napalm_device_types.models import ( ) from napalm_device_types.ssh_host_keys import HostKeyCheck from netmiko import ConnectHandler -from netmiko.exceptions import ( - NetmikoAuthenticationException, - NetmikoTimeoutException, -) +from netmiko.exceptions import NetmikoAuthenticationException, NetmikoTimeoutException +from napalm_linux._hostname import HostnameMixin from napalm_linux._shell import PROMPT_RE as _PROMPT_RE from napalm_linux._shell import prepare_shell @@ -321,6 +319,7 @@ class LinuxDriver( SystemdServicesMixin, HostStatusMixin, ContainerEngineMixin, + HostnameMixin, OSDriver, ): """NAPALM driver for generic Linux systems. @@ -367,7 +366,6 @@ class LinuxDriver( self._secret: str = optional_args.get("secret", password) # Optional sudo password for privilege escalation (e.g. apt-get update) self._sudo_password: str | None = optional_args.get("sudo_password") - # Expected apt proxy URL — checked as a device warning on apt systems. if optional_args.get("debugging"): logger.setLevel(logging.DEBUG) diff --git a/tests/quality_baseline.json b/tests/quality_baseline.json index cc50fe9..88483be 100644 --- a/tests/quality_baseline.json +++ b/tests/quality_baseline.json @@ -22,7 +22,7 @@ "napalm_linux.linux" ], "python_file_lines": { - "napalm_linux/linux.py": 2288 + "napalm_linux/linux.py": 2286 }, "untyped_public": [] } diff --git a/tests/test_set_hostname.py b/tests/test_set_hostname.py new file mode 100644 index 0000000..0326236 --- /dev/null +++ b/tests/test_set_hostname.py @@ -0,0 +1,289 @@ +"""``set_hostname`` renames the host itself, not only what netOrk calls it (#45). + +The static and runtime hostname take the short name; ``/etc/hosts`` follows, so +the host still resolves its own name; and a cloud-init host is told to keep the +name, or its next boot puts the image's name back. Every file root writes is +staged without privilege first, as ``_install_file_as_root`` does for the fixes. +""" + +from __future__ import annotations + +import shlex +from types import SimpleNamespace +from unittest.mock import MagicMock + +import pytest + +from napalm_linux import LinuxDriver +from napalm_linux._hostname import _rename_in_hosts, _split_hostname + +_PW = "pw-45" +_STAGED = "/tmp/netork-stage.Xy34Zw" +_HOSTS = "127.0.0.1\tlocalhost\n127.0.1.1\told.example.net old\n\n::1 localhost ip6-localhost\n" + + +class Host: + """The host's exec channels: every line, its stdin, and whether it ran as root.""" + + def __init__(self, *, hosts=_HOSTS, cloud_init=False, rename_status=0, hosts_status=0): + self.runs: list[SimpleNamespace] = [] + self.hosts = hosts + self.cloud_init = cloud_init + self.rename_status = rename_status + self.hosts_status = hosts_status + + def open_session(self): + return _Channel(self) + + def answer(self, command: str, script: str) -> tuple[str, int]: + if command.startswith("sudo -n "): + return "sudo: a password is required\n", 1 + if script == "hostname": + return "old\n", 0 + if script.startswith("hostname -f"): + return "old.example.net\n", 0 + if script == "cat /etc/hosts": + return self.hosts, 0 + if script.startswith("test -d /etc/cloud"): + return "", 0 if self.cloud_init else 1 + if "mktemp" in script: + return _STAGED, 0 + if "hostnamectl" in script: + return ( + "hostname: you must be root\n" if self.rename_status else "" + ), self.rename_status + if "/etc/hosts" in script and "install" in script: + return ("install: cannot create\n" if self.hosts_status else ""), self.hosts_status + return "", 0 + + @property + def root_scripts(self) -> list[str]: + return [run.script for run in self.runs if run.root] + + def staged(self) -> list[bytes]: + return [run.stdin for run in self.runs if "mktemp" in run.script] + + +class _Channel: + def __init__(self, host: Host): + self._host = host + self._run: SimpleNamespace | None = None + self._out = b"" + self._status = 0 + + def exec_command(self, command): + assert _PW not in command + root = command.startswith(("sudo ", "sh -c ")) + parts = shlex.split(command) + script = parts[parts.index("-c") + 1] if root else command + script = script.removeprefix("exec LinuxDriver: + optional_args = {"sudo_password": sudo_password} if sudo_password else {} + driver = LinuxDriver("h", "admin", "p", optional_args=optional_args) + driver._device = MagicMock() + driver._device.remote_conn_pre = SimpleNamespace(get_transport=lambda: host) + driver._root = False + driver._pkg_manager = "apt" + return driver + + +def _hosts_written(host: Host) -> str: + """What was staged for /etc/hosts, or "" when it was left alone.""" + staged = b"" + for run in host.runs: + if "mktemp" in run.script: + staged = run.stdin + elif run.root and "/etc/hosts" in run.script: + return staged.decode() + return "" + + +class TestSplitHostname: + @pytest.mark.parametrize( + "name, expected", + [ + ("web-01", ("web-01", None)), + ("web-01.example.net", ("web-01", "web-01.example.net")), + ("A1", ("A1", None)), + ("a" * 63, ("a" * 63, None)), + ], + ) + def test_valid(self, name, expected): + assert _split_hostname(name) == expected + + @pytest.mark.parametrize( + "name", + [ + "", + "web_01", + "-web", + "web-", + "a" * 64, + ".".join(["a" * 60] * 5), + "web 01", + "web;reboot", + "web.", + ".web", + "web..example", + "$(id)", + ], + ) + def test_invalid(self, name): + with pytest.raises(ValueError): + _split_hostname(name) + + +class TestRenameInHosts: + def test_old_names_replaced_on_every_line_they_appear(self): + content = "127.0.0.1 localhost old\n10.0.0.5 old.example.net old # me\n" + assert _rename_in_hosts(content, {"old", "old.example.net"}, "new", "new.example.net") == ( + "127.0.0.1\tlocalhost new.example.net new\n10.0.0.5\tnew.example.net new # me\n" + ) + + def test_other_aliases_and_lines_kept(self): + content = "# static\n127.0.1.1 old mail\n::1 localhost\n" + assert _rename_in_hosts(content, {"old"}, "new", None) == ( + "# static\n127.0.1.1\tnew mail\n::1 localhost\n" + ) + + def test_names_compared_without_case(self): + assert _rename_in_hosts("127.0.1.1 OLD\n", {"old"}, "new", None) == "127.0.1.1\tnew\n" + + def test_no_old_name_but_a_127_0_1_1_line_takes_the_new_name(self): + content = "127.0.0.1 localhost\n127.0.1.1 ubuntu\n" + assert _rename_in_hosts(content, {"old"}, "new", "new.example.net") == ( + "127.0.0.1 localhost\n127.0.1.1\tnew.example.net new\n" + ) + + def test_neither_leaves_the_file_alone(self): + content = "127.0.0.1 localhost localhost.localdomain\n::1 localhost\n" + assert _rename_in_hosts(content, {"old"}, "new", None) == content + + def test_localhost_is_never_renamed(self): + content = "127.0.0.1 localhost\n" + assert _rename_in_hosts(content, {"localhost"}, "new", None) == content + + +class TestSetHostname: + def test_short_name_set_as_root(self): + host = Host() + + _driver(host).set_hostname("new") + + rename = host.root_scripts[0] + assert "hostnamectl set-hostname new" in rename + assert "/etc/hostname" in rename and "hostname new" in rename + + def test_fqdn_sets_the_short_name_and_both_in_hosts(self): + host = Host() + + _driver(host).set_hostname("new.example.net") + + assert "hostnamectl set-hostname new " in host.root_scripts[0] + assert "example" not in host.root_scripts[0] + assert _hosts_written(host) == ( + "127.0.0.1\tlocalhost\n127.0.1.1\tnew.example.net new\n\n::1 localhost ip6-localhost\n" + ) + + def test_hosts_installed_from_a_staged_file_never_privileged_stdin(self): + host = Host() + + _driver(host).set_hostname("new") + + hosts_install = [s for s in host.root_scripts if "/etc/hosts" in s] + assert len(hosts_install) == 1 + assert f"install -m 644 -o root -g root -- {_STAGED}" in hosts_install[0] + for run in host.runs: + if run.root: + assert run.stdin == f"{_PW}\n".encode() + + def test_unchanged_hosts_not_rewritten(self): + host = Host(hosts="127.0.0.1 localhost\n") + + _driver(host).set_hostname("new") + + assert not any("/etc/hosts" in s for s in host.root_scripts) + + def test_cloud_init_host_keeps_the_name(self): + host = Host(cloud_init=True) + + _driver(host).set_hostname("new") + + assert any( + "/etc/cloud/cloud.cfg.d/99-preserve-hostname.cfg" in s for s in host.root_scripts + ) + assert any(b"preserve_hostname: true" in staged for staged in host.staged()) + + def test_no_cloud_init_no_drop_in(self): + host = Host() + + _driver(host).set_hostname("new") + + assert not any("cloud.cfg.d" in s for s in host.root_scripts) + + def test_invalid_name_runs_nothing(self): + host = Host() + driver = _driver(host) + + with pytest.raises(ValueError): + driver.set_hostname("new;reboot") + + assert host.runs == [] + driver._device.send_command.assert_not_called() + + def test_failed_rename_raises_and_writes_nothing(self): + host = Host(rename_status=1) + + with pytest.raises(RuntimeError): + _driver(host).set_hostname("new") + + assert not any("/etc/hosts" in s for s in host.root_scripts) + + def test_sudo_without_password_says_what_to_do(self): + host = Host() + + with pytest.raises(RuntimeError, match="no sudo password was given"): + _driver(host, sudo_password=None).set_hostname("new") + + def test_failed_hosts_write_raises(self): + host = Host(hosts_status=1) + + with pytest.raises(RuntimeError, match="/etc/hosts"): + _driver(host).set_hostname("new") -- 2.54.0