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.
267 lines
11 KiB
Python
267 lines
11 KiB
Python
"""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 </dev/null; ")
|
|
|
|
def test_without_a_password_sudo_never_waits_for_one(self):
|
|
driver, channel = _driver(FreeBSDDriver, sudo_password=None)
|
|
driver.apply_updates(["curl"])
|
|
assert channel.line.startswith("sudo -n sh -c ")
|
|
assert channel.stdin == b""
|
|
|
|
def test_a_root_login_runs_it_in_sh_whatever_its_shell(self):
|
|
"""root's login shell on FreeBSD may be csh, which does not read the script."""
|
|
driver, channel = _driver(FreeBSDDriver, root=True)
|
|
driver.apply_updates(["curl"])
|
|
words = shlex.split(channel.line)
|
|
assert words[:2] == ["sh", "-c"]
|
|
assert words[2].startswith("exec </dev/null; ")
|
|
assert channel.stdin == b""
|
|
|
|
|
|
class TestOutput:
|
|
def test_each_line_goes_to_log_as_it_comes(self):
|
|
chunks = [b"Updating FreeBSD repo", b"sitory catalogue...\nInstalling", b" curl\n", b"done"]
|
|
driver, channel = _driver(FreeBSDDriver, chunks)
|
|
lines: list[str] = []
|
|
result = driver.apply_updates(["curl"], log=lines.append)
|
|
assert lines == ["Updating FreeBSD repository catalogue...", "Installing curl", "done"]
|
|
assert result == {
|
|
"success": True,
|
|
"output": "Updating FreeBSD repository catalogue...\nInstalling curl\ndone",
|
|
}
|
|
assert channel.combined # sudo's own complaints reach the output too
|
|
assert channel.closed
|
|
|
|
def test_without_a_log_the_output_is_returned(self):
|
|
driver, _ = _driver(OpenBSDDriver, [b"quirks-7.50 signed on 2026-11-20\n"])
|
|
result = driver.apply_updates([])
|
|
assert result["output"] == "quirks-7.50 signed on 2026-11-20\n"
|
|
|
|
def test_carriage_returns_of_a_progress_line_are_dropped(self):
|
|
driver, _ = _driver(OpenBSDDriver, [b"curl-8.11.0: ok\r\n"])
|
|
lines: list[str] = []
|
|
driver.apply_updates(["curl"], log=lines.append)
|
|
assert lines == ["curl-8.11.0: ok"]
|
|
|
|
def test_the_exit_status_decides(self):
|
|
driver, _ = _driver(OpenBSDDriver, [b"syspatch: cannot relink the kernel\n"], 1)
|
|
result = driver.apply_updates([BASE_SYSTEM])
|
|
assert result["success"] is False
|
|
assert result["error"] == "the upgrade exited with status 1"
|
|
assert result["output"] == "syspatch: cannot relink the kernel\n"
|
|
|
|
def test_a_host_that_falls_silent_is_a_failure_with_what_it_printed(self):
|
|
driver, channel = _driver(
|
|
FreeBSDDriver, [b"Fetching curl-8.11.0.pkg\n"], fail=TimeoutError("timed out")
|
|
)
|
|
lines: list[str] = []
|
|
result = driver.apply_updates(["curl"], log=lines.append)
|
|
assert result["success"] is False
|
|
assert "no output for 300 s" in result["error"]
|
|
assert result["output"] == "Fetching curl-8.11.0.pkg\n"
|
|
assert lines == ["Fetching curl-8.11.0.pkg"]
|
|
assert channel.timeout == updates.IDLE_TIMEOUT
|
|
assert channel.closed
|
|
|
|
def test_a_dropped_connection_is_a_failure(self):
|
|
driver, _ = _driver(FreeBSDDriver, [], fail=OSError("Socket is closed"))
|
|
result = driver.apply_updates(["curl"])
|
|
assert result["success"] is False
|
|
assert "Socket is closed" in result["error"]
|