Files
napalm-linux/napalm_linux/_hostname.py
T
Christian Manivong 4108eb83dd
driver / standard (pull_request) Successful in 18s
driver / lint (pull_request) Successful in 14s
driver / types (pull_request) Successful in 1m12s
driver / test (3.12) (pull_request) Successful in 1m11s
driver / test (3.13) (pull_request) Successful in 1m6s
driver / lowest (pull_request) Successful in 29s
driver / build (pull_request) Successful in 32s
driver / security (pull_request) Successful in 1m14s
CI / driver (pull_request) Successful in 1m15s
driver / publish (pull_request) Skipped
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.
2026-10-29 21:57:40 +01:00

146 lines
6.1 KiB
Python

"""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}(?<!-)$")
#: Names ``/etc/hosts`` keeps whatever the host was called.
_LOOPBACK_NAMES = frozenset({"localhost", "localhost.localdomain"})
#: What the host is called before the rename: its short name and its FQDN.
_OLD_NAME_COMMANDS = ("hostname", "hostname -f 2>/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}")