diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 7530c79..599df99 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -11,5 +11,7 @@ jobs: uses: NAPALM/driver-standard/.gitea/workflows/driver.yml@main with: standard-ref: main + # Until napalm-device-types 4.54.0 (apply_updates' log) is on PyPI. + pre-install: "git+https://git.netork.io/NAPALM/napalm-device-types.git@059d97f6de229d05bc705bc57bb26520967544b5" secrets: PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }} diff --git a/CHANGELOG.md b/CHANGELOG.md index f3ed11e..52a6e67 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] ### Added +- `apply_updates(packages, log=None)` on FreeBSD and OpenBSD (#13): the chosen packages, + or every one, with `pkg upgrade` or `pkg_add -u`, then the base system's patches when + `base-system` is chosen or nothing is — a classic FreeBSD's `freebsd-update install`, + OpenBSD's `syspatch`, run again when it updated itself. Runs as root, and `log` + receives each line as the host prints it, through napalm-device-types' declaration + (4.54.0). The commands used to live in the application (NetOrk/netork#1112). - `get_ssh_server_auth()` on FreeBSD and OpenBSD, through napalm-device-types' `SshServerAuthMixin` (4.32.0): whether sshd takes passwords, keyboard-interactive or keys, its `AuthenticationMethods`, `PermitRootLogin` and, on FreeBSD, the modules of sshd's PAM diff --git a/README.md b/README.md index c3d1fac..dff9af0 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,7 @@ provisions and manages BSD VMs (NetOrk/netork#792). | `get_listening_sockets` | ✓ | ✓ | `sockstat -46lq` / `fstat -n` as root, `netstat -an` without | | `get_packages`, `install_package`, `uninstall_package` | ✓ | ✓ | `pkg query` / `pkg install`, `pkg delete`; `pkg_info` / `pkg_add -I`, `pkg_delete` | | `get_available_updates` | ✓ | ✓ | `pkg upgrade -n` + `pkg audit` (VuXML); `pkg_add -u -n -v` + `syspatch -c` | +| `apply_updates(packages, log=)` | ✓ | ✓ | `pkg upgrade -y` then `freebsd-update install` (classic base); `pkg_add -u -I` then `syspatch`; as root, each line to `log` as it comes | | `get_services`, `manage_service` | ✓ | ✓ | `service -e` + `service … status` / `service … `; `rcctl ls on` + `rcctl check` / `rcctl ` | | `run_device_action("fix_snmp")`, `get_snmp_config` | ✓ | ✓ | net-snmp from packages: `/usr/local/etc/snmp/snmpd.conf` + `service snmpd`; `/etc/snmp/snmpd.conf` + `rcctl … netsnmpd` | | `get_host_status` | ✓ | unknown | napalm-device-types' host status: on FreeBSD `freebsd-version -k` vs `-r` (4.1+) | @@ -71,6 +72,18 @@ reports what `freebsd-update` has fetched (`updatesready`). On FreeBSD with pkgbase the base system is packages from the `FreeBSD-base` repository and needs no extra entry. +`apply_updates(packages, log=None)` upgrades the chosen packages, or every one +when `packages` is empty, and installs the base system's patches after them +when `base-system` is chosen or nothing is: a classic FreeBSD base installs what +`freebsd-update` has fetched (nothing fetched is no failure, and pkgbase has no +extra step); OpenBSD runs `syspatch` once more when it updated itself, and its +"nothing left to install" is no failure. The whole upgrade runs as root as one +`sh` script on an exec channel, stdout and stderr merged, the sudo password on +stdin only and the script's stdin closed. `log` receives each line as the host +prints it; `output` holds all of it. The exit status decides `success`; a host +that prints nothing for 300 s, or a connection that drops, is a failure with +what was printed until then. + A reader that cannot read **raises** rather than return an empty list: netOrk takes `[]` as "no updates" and would close every patch clock on the host. That covers a refused sudo, a failing `pkg`, `syspatch` or `freebsd-update`, and a pkg diff --git a/napalm_bsd/base.py b/napalm_bsd/base.py index 2fd298c..db9e97b 100644 --- a/napalm_bsd/base.py +++ b/napalm_bsd/base.py @@ -30,16 +30,13 @@ from napalm_device_types.ssh_server_auth import SshServerAuthMixin from napalm_bsd import parse from napalm_bsd.scheduled_jobs import BsdScheduledJobsMixin +from napalm_bsd.updates import BASE_SYSTEM as BASE_SYSTEM # re-exported: the drivers use it +from napalm_bsd.updates import PACKAGE_NAME, BsdUpdatesMixin logger = logging.getLogger(__name__) -#: 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" - _SERVICE_ACTIONS = frozenset({"start", "stop", "restart", "enable", "disable"}) _SERVICE_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]*$") -_PACKAGE_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.+-]*$") #: What may stand in an snmpd.conf value: no whitespace, no quote, no comment. _SNMP_WORD = re.compile(r'^[^\s"#]+$') @@ -105,6 +102,7 @@ def _load_key(key_file: str | None) -> paramiko.PKey | None: class BsdDriver( + BsdUpdatesMixin, BsdScheduledJobsMixin, SnmpAgentMixin, EnsurePackageMixin, @@ -463,12 +461,12 @@ class BsdDriver( ) def install_package(self, name: str, version: str = "") -> None: - if not _PACKAGE_NAME.match(name) or (version and not _PACKAGE_NAME.match(version)): + if not PACKAGE_NAME.match(name) or (version and not PACKAGE_NAME.match(version)): raise ValueError(f"Not a package name: {name!r}") self._package_command(self.INSTALL_COMMAND, f"{name}-{version}" if version else name) def uninstall_package(self, name: str) -> None: - if not _PACKAGE_NAME.match(name): + if not PACKAGE_NAME.match(name): raise ValueError(f"Not a package name: {name!r}") self._package_command(self.UNINSTALL_COMMAND, name) diff --git a/napalm_bsd/freebsd.py b/napalm_bsd/freebsd.py index e60b1c2..a95f759 100644 --- a/napalm_bsd/freebsd.py +++ b/napalm_bsd/freebsd.py @@ -57,6 +57,17 @@ class FreeBSDDriver(FreeBSDLocalAccountsMixin, PeriodicJobsMixin, BsdDriver): # Bootstraps pkg on a classic system that never had it, instead of asking. INSTALL_COMMAND = "env ASSUME_ALWAYS_YES=yes pkg install -y {name}" UNINSTALL_COMMAND = "pkg delete -y {name}" + # apply_updates; bootstraps pkg on a classic system that never had it instead of asking. + UPGRADE_PACKAGES = "env ASSUME_ALWAYS_YES=yes pkg upgrade -y {packages}" + UPGRADE_ALL = "env ASSUME_ALWAYS_YES=yes pkg upgrade -y" + # On pkgbase the base system is packages, upgraded with them. A classic base + # installs what freebsd-update fetched; updatesready exits 2 when nothing is. + BASE_SYSTEM_UPGRADE = ( + "if pkg repos -l 2>/dev/null | grep -qx FreeBSD-base; then exit 0; fi; " + "freebsd-update --not-running-from-cron updatesready; r=$?; " + "if [ $r -eq 2 ]; then exit 0; fi; if [ $r -ne 0 ]; then exit $r; fi; " + "PAGER=cat freebsd-update --not-running-from-cron install" + ) # Root reads every daemon's pidfile; one-shot scripts have no status. SERVICE_STATUS_COMMAND = ( "for s in $(service -e); do n=${s##*/}; " diff --git a/napalm_bsd/openbsd.py b/napalm_bsd/openbsd.py index e51cba9..8c3451c 100644 --- a/napalm_bsd/openbsd.py +++ b/napalm_bsd/openbsd.py @@ -60,6 +60,15 @@ class OpenBSDDriver(BsdDriver): INSTALL_COMMAND = "pkg_add -I {name}" UNINSTALL_COMMAND = "pkg_delete {name}" + # apply_updates; -I: never stop at a question. + UPGRADE_PACKAGES = "pkg_add -u -I {packages}" + UPGRADE_ALL = "pkg_add -u -I" + # syspatch exits 2 both when it updated itself (run it again) and when it + # had nothing to install; a second 2 means the latter. A failure is 1. + BASE_SYSTEM_UPGRADE = ( + "syspatch; r=$?; if [ $r -eq 2 ]; then syspatch; r=$?; fi; " + "if [ $r -eq 2 ]; then r=0; fi; exit $r" + ) # rcctl check needs no root; "rcctl ls started" does. SERVICE_STATUS_COMMAND = ( "for s in $(rcctl ls on); do " diff --git a/napalm_bsd/updates.py b/napalm_bsd/updates.py new file mode 100644 index 0000000..f62f29e --- /dev/null +++ b/napalm_bsd/updates.py @@ -0,0 +1,140 @@ +"""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) + 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} diff --git a/tests/test_apply_updates.py b/tests/test_apply_updates.py new file mode 100644 index 0000000..5097772 --- /dev/null +++ b/tests/test_apply_updates.py @@ -0,0 +1,266 @@ +"""apply_updates on FreeBSD and OpenBSD: the commands sent, and each line as it comes (#13). + +The upgrade commands used to live in the application (NetOrk/netork#1112). They +run as root as one script on an exec channel, stderr merged, and every line the +host prints goes to the caller's ``log`` while the upgrade runs. +""" + +from __future__ import annotations + +import inspect +import shlex + +import pytest + +from napalm_bsd import FreeBSDDriver, OpenBSDDriver, updates +from napalm_bsd.base import BASE_SYSTEM + +_PW = "s3cret" + + +class _Channel: + """A paramiko exec channel that prints *chunks* and exits with *status*.""" + + def __init__(self, chunks: list[bytes], status: int, *, fail: Exception | None = None): + self._chunks = list(chunks) + self._status = status + self._fail = fail + self.line = "" + self.stdin = b"" + self.combined = False + self.timeout: float | None = None + self.write_closed = False + self.closed = False + + def set_combine_stderr(self, combine: bool) -> None: + self.combined = combine + + def settimeout(self, timeout: float | None) -> None: + self.timeout = timeout + + def exec_command(self, line: str) -> None: + self.line = line + + def sendall(self, data: bytes) -> None: + self.stdin += data + + def shutdown_write(self) -> None: + self.write_closed = True + + def recv(self, _max: int) -> bytes: + if self._chunks: + return self._chunks.pop(0) + if self._fail is not None: + raise self._fail + return b"" + + def recv_exit_status(self) -> int: + return self._status + + def close(self) -> None: + self.closed = True + + +class _Transport: + def __init__(self, channel: _Channel) -> None: + self.channel = channel + + def open_session(self) -> _Channel: + return self.channel + + +def _driver(cls, chunks=(b"",), status=0, *, sudo_password=_PW, root=False, fail=None): + args = {"sudo_password": sudo_password} if sudo_password else {} + driver = cls("host", "admin", "", optional_args=args) + channel = _Channel(list(chunks), status, fail=fail) + driver._transport = lambda: _Transport(channel) # type: ignore[method-assign] + driver._root = root + return driver, channel + + +def _script(channel: _Channel) -> str: + """The script root runs: the argument of ``sudo … sh -c``, unwrapped once more.""" + outer = shlex.split(channel.line) + assert outer[:4] == ["sudo", "-S", "-p", ""] and outer[4:6] == ["sh", "-c"] + inner = shlex.split(outer[6]) + assert inner[:2] == ["sh", "-c"] + return inner[2] + + +class TestTheContract: + @pytest.mark.parametrize("cls", [FreeBSDDriver, OpenBSDDriver]) + def test_both_apply_updates_and_take_a_log(self, cls): + """The application hands a run to a driver whose apply_updates takes ``log``.""" + parameter = inspect.signature(cls.apply_updates).parameters["log"] + assert parameter.kind is inspect.Parameter.KEYWORD_ONLY + assert parameter.default is None + + @pytest.mark.parametrize("name", ["curl; reboot", "-f", "", "a b", "$(id)"]) + def test_a_name_that_is_not_a_package_is_refused_before_anything_is_sent(self, name): + driver, channel = _driver(FreeBSDDriver) + with pytest.raises(ValueError, match="package name"): + driver.apply_updates([name]) + assert channel.line == "" + + def test_the_entry_for_the_base_system_is_one_name(self): + assert BASE_SYSTEM == updates.BASE_SYSTEM == "base-system" + + +class TestFreeBSD: + def test_chosen_packages_leave_the_base_system_alone(self): + driver, channel = _driver(FreeBSDDriver) + driver.apply_updates(["curl", "py311-requests"]) + script = _script(channel) + assert "env ASSUME_ALWAYS_YES=yes pkg upgrade -y curl py311-requests" in script + assert "freebsd-update" not in script + + def test_everything_upgrades_the_packages_then_the_base_system(self): + driver, channel = _driver(FreeBSDDriver) + driver.apply_updates([]) + script = _script(channel) + packages, base = script.split(" && ", 1) + assert packages.endswith("env ASSUME_ALWAYS_YES=yes pkg upgrade -y 2>&1") + assert "freebsd-update" in base + + def test_the_base_system_alone(self): + driver, channel = _driver(FreeBSDDriver) + driver.apply_updates([BASE_SYSTEM]) + script = _script(channel) + assert "pkg upgrade" not in script + assert "FreeBSD-base" in script + + def test_pkgbase_has_no_extra_step(self): + """On pkgbase the base system is packages, upgraded with them.""" + base = FreeBSDDriver.BASE_SYSTEM_UPGRADE + assert base.startswith("if pkg repos -l 2>/dev/null | grep -qx FreeBSD-base; then exit 0") + + def test_a_classic_base_installs_what_freebsd_update_fetched(self): + base = FreeBSDDriver.BASE_SYSTEM_UPGRADE + assert "freebsd-update --not-running-from-cron updatesready" in base + assert base.endswith("PAGER=cat freebsd-update --not-running-from-cron install") + + def test_nothing_fetched_is_no_failure(self): + """updatesready exits 2 when there is nothing to install.""" + assert "if [ $r -eq 2 ]; then exit 0; fi" in FreeBSDDriver.BASE_SYSTEM_UPGRADE + + +class TestOpenBSD: + def test_chosen_packages_leave_the_base_system_alone(self): + driver, channel = _driver(OpenBSDDriver) + driver.apply_updates(["curl"]) + script = _script(channel) + assert "pkg_add -u -I curl 2>&1" in script + assert "syspatch" not in script + + def test_everything_upgrades_the_packages_then_runs_syspatch(self): + driver, channel = _driver(OpenBSDDriver) + driver.apply_updates([]) + packages, base = _script(channel).split(" && ", 1) + assert packages.endswith("pkg_add -u -I 2>&1") + assert "syspatch" in base + + def test_chosen_packages_and_the_base_system(self): + driver, channel = _driver(OpenBSDDriver) + driver.apply_updates(["curl", BASE_SYSTEM]) + packages, base = _script(channel).split(" && ", 1) + assert packages.endswith("pkg_add -u -I curl 2>&1") + assert "syspatch" in base + + def test_the_base_system_alone_runs_syspatch_only(self): + driver, channel = _driver(OpenBSDDriver) + driver.apply_updates([BASE_SYSTEM]) + script = _script(channel) + assert "pkg_add" not in script + assert "syspatch" in script + + def test_syspatch_runs_again_after_updating_itself(self): + """syspatch exits 2 after replacing itself; the patches come with the second run.""" + base = OpenBSDDriver.BASE_SYSTEM_UPGRADE + assert base.count("syspatch") == 2 + assert "r=$?; if [ $r -eq 2 ]; then syspatch; r=$?; fi" in base + + def test_nothing_left_to_install_is_success(self): + """syspatch(8): a second 2 means no additional patch; a failure exits 1.""" + assert "if [ $r -eq 2 ]; then r=0; fi; exit $r" in OpenBSDDriver.BASE_SYSTEM_UPGRADE + + +class TestRoot: + def test_the_sudo_password_goes_to_stdin_never_into_the_line(self): + driver, channel = _driver(OpenBSDDriver) + driver.apply_updates(["curl"]) + assert _PW not in channel.line + assert channel.stdin == f"{_PW}\n".encode() + assert channel.write_closed + + def test_nothing_the_script_runs_reads_what_sudo_left_on_stdin(self): + """A sudo that does not prompt leaves the password on stdin (#8).""" + driver, channel = _driver(OpenBSDDriver) + driver.apply_updates(["curl"]) + assert _script(channel).startswith("exec