"""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}")