The upgrade commands move here from the application (NetOrk/netork#1112): pkg upgrade or pkg_add -u for the chosen packages or every one, then the base system's patches when base-system is chosen or nothing is. A classic FreeBSD base installs what freebsd-update fetched (nothing fetched is no failure; pkgbase needs no extra step); OpenBSD runs syspatch again when it updated itself, and a second exit 2 is "nothing left". The whole upgrade runs as root as one sh script on an exec channel, stderr merged, the sudo password on stdin only and the script's stdin closed. The log keyword napalm-device-types declares on apply_updates receives each line as the host prints it. A host silent for 300 s, or a dropped connection, is a failure with what was printed until then. CI pre-installs napalm-device-types' branch commit with that declaration until 4.54.0 is on PyPI.
141 lines
5.5 KiB
Python
141 lines
5.5 KiB
Python
"""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 </dev/null; "
|
|
#: What a package name may be: it never starts an option, and never leaves the word.
|
|
PACKAGE_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.+-]*$")
|
|
_READ = 32 * 1024
|
|
|
|
Log = Callable[[str], None]
|
|
|
|
|
|
class _Lines:
|
|
"""What the channel printed, and each complete line handed to *log*."""
|
|
|
|
def __init__(self, log: Log | None) -> 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)
|
|
channel.exec_command(line)
|
|
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}
|