"""Applying updates on the BSDs: the packages, then the base system's patches (#13). ``apply_updates`` upgrades the chosen packages, or every package when given none, with the system's package manager. The base system's patches are one entry in ``get_available_updates``, :data:`BASE_SYSTEM`: OpenBSD's ``syspatch``, a classic FreeBSD's ``freebsd-update``. They are installed after the packages when that entry is chosen, or when nothing is. The whole upgrade runs as root as one ``sh`` script on an exec channel, stdout and stderr merged, so the package manager's own words -- and sudo's -- are what the caller sees. Each line goes to *log* as the host prints it: an upgrade takes minutes, and the person following it wants to see it move. """ from __future__ import annotations import re from collections.abc import Callable from shlex import quote from typing import TYPE_CHECKING, Any, ClassVar import paramiko from napalm_device_types.models import ApplyUpdatesResultDict #: The update-list entry for base-system patches (OpenBSD syspatch, classic #: FreeBSD freebsd-update): one entry, as they are applied together (#799). BASE_SYSTEM = "base-system" #: Seconds the host may print nothing before the upgrade counts as stuck. IDLE_TIMEOUT = 300 #: First in the script: a sudo that did not prompt (NOPASSWD, a cached #: timestamp) leaves the password on stdin, and nothing the script runs may read it. _NO_STDIN = "exec None: self._log = log self._received = b"" self._pending = b"" def feed(self, chunk: bytes) -> None: self._received += chunk *complete, self._pending = (self._pending + chunk).split(b"\n") for raw in complete: self._say(raw) def finish(self) -> str: if self._pending: self._say(self._pending) self._pending = b"" return self._received.decode("utf-8", "replace") def _say(self, raw: bytes) -> None: if self._log is not None: self._log(raw.decode("utf-8", "replace").rstrip("\r")) class BsdUpdatesMixin: """``UpdateMixin.apply_updates`` for a BSD; the concrete driver names its commands.""" #: Upgrades the packages in ``{packages}``, already checked and quoted. UPGRADE_PACKAGES: ClassVar[str] = "" #: Upgrades every package that has an update. UPGRADE_ALL: ClassVar[str] = "" #: A script that installs the base system's pending patches; exit 0 when there are none. BASE_SYSTEM_UPGRADE: ClassVar[str] = "" if TYPE_CHECKING: # pragma: no cover - BsdDriver provides them def _transport(self) -> Any: ... def _privileged(self, command: str, privileged: bool) -> tuple[str, bytes | None]: ... def apply_updates( self, packages: list[str], *, log: Log | None = None ) -> ApplyUpdatesResultDict: """Upgrade *packages* (every package when empty), and the base system with :data:`BASE_SYSTEM` among them or when *packages* is empty. *log* receives each line the host prints, as it prints it. :raises ValueError: for a name that is not a package name; nothing is sent then. """ for name in packages: if not PACKAGE_NAME.match(name): raise ValueError(f"Invalid package name: {name!r}") script = _NO_STDIN + " && ".join(self._upgrade_steps(packages)) line, prefix = self._privileged(f"sh -c {quote(script)}", True) lines = _Lines(log) try: status = self._stream(line, prefix, lines) except TimeoutError: return _failed(lines, f"no output for {IDLE_TIMEOUT} s; the upgrade may still run") except (OSError, EOFError, paramiko.SSHException) as exc: return _failed(lines, f"the connection failed during the upgrade: {exc}") output = lines.finish() if status != 0: error = f"the upgrade exited with status {status}" return {"success": False, "output": output, "error": error} return {"success": True, "output": output} def _upgrade_steps(self, packages: list[str]) -> list[str]: chosen = [name for name in packages if name != BASE_SYSTEM] steps = [] if chosen: named = " ".join(quote(name) for name in chosen) steps.append(f"{self.UPGRADE_PACKAGES.format(packages=named)} 2>&1") elif not packages: steps.append(f"{self.UPGRADE_ALL} 2>&1") if not packages or BASE_SYSTEM in packages: steps.append(f"sh -c {quote(self.BASE_SYSTEM_UPGRADE)} 2>&1") return steps def _stream(self, line: str, prefix: bytes | None, lines: _Lines) -> int: channel = self._transport().open_session() try: channel.set_combine_stderr(True) channel.settimeout(IDLE_TIMEOUT) # The line is built from this module's constants and package names that # passed PACKAGE_NAME and are shell-quoted, never from free text. channel.exec_command(line) # nosec B601 if prefix: channel.sendall(prefix) channel.shutdown_write() while chunk := channel.recv(_READ): lines.feed(chunk) return int(channel.recv_exit_status()) finally: channel.close() def _failed(lines: _Lines, error: str) -> ApplyUpdatesResultDict: return {"success": False, "output": lines.finish(), "error": error}