diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e09335..cbe6c7e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.25.0] - 2026-11-29 + +### Added +- `shutdown_host()` (napalm-device-types' `HostShutdownMixin`): the host's clean shutdown, + next to `reboot_host` (NetOrk/netork#2841). `/sbin/poweroff` as root, detached and two + seconds late like the restart, so the exit status comes back before the session drops; + a refusal raises `RuntimeError` with what the host said. `poweroff` rather than + `shutdown -h now`, because BusyBox (Alpine) has no `shutdown` and sysvinit's `-h` may + only halt. OpenMediaVault and QNAP have it through `LinuxDriver`. + ## [0.24.0] - 2026-11-28 ### Added diff --git a/napalm_linux/_host_power.py b/napalm_linux/_host_power.py new file mode 100644 index 0000000..6533757 --- /dev/null +++ b/napalm_linux/_host_power.py @@ -0,0 +1,59 @@ +"""Restarting and shutting the host down, cleanly and detached (NetOrk/netork#2841). + +``reboot_host`` and ``shutdown_host`` (napalm-device-types ``HostRebootMixin``, +``HostShutdownMixin``) run their command as root two seconds late and detached +from the session: the launcher's exit status comes back before the host goes +down, and closing the session cannot take the restart or shutdown with it. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Callable + +#: Restart the host two seconds later, detached from this session. +_REBOOT_DETACHED = "sh -c '(trap \"\" HUP; sleep 2; /sbin/reboot) /dev/null 2>&1 &'" +#: Power the host off the same way, two seconds later and detached. ``poweroff`` +#: rather than ``shutdown -h now``: systemd links it to ``systemctl poweroff``, +#: sysvinit and BusyBox (Alpine) ship it themselves, while BusyBox has no +#: ``shutdown`` and sysvinit's ``-h`` may only halt, leaving the machine on. +_POWEROFF_DETACHED = "sh -c '(trap \"\" HUP; sleep 2; /sbin/poweroff) /dev/null 2>&1 &'" + + +class LinuxHostPowerMixin: + if TYPE_CHECKING: + _run_privileged: Callable[[str, int], str] + + def reboot_host(self) -> None: + """Restart the host (``HostRebootMixin``); returns once the restart is under way. + + :raises RuntimeError: when the host refuses -- sudo without a password, + no ``reboot`` -- or its answer carried no exit status. + """ + self._launch_detached(_REBOOT_DETACHED, "reboot") + + def shutdown_host(self) -> None: + """Shut the host down cleanly (``HostShutdownMixin``); returns once it is under way. + + Runs ``/sbin/poweroff`` as root, detached and two seconds late like the + restart, so the exit status comes back before the session drops. A + clean shutdown only: cutting the power is the BMC's business. + + :raises RuntimeError: when the host refuses -- sudo without a password, + no ``poweroff`` -- or its answer carried no exit status. + """ + self._launch_detached(_POWEROFF_DETACHED, "poweroff") + + def _launch_detached(self, command: str, name: str) -> None: + """Launch a detached power *command* as root; raise what the host said on refusal.""" + # Imported here: linux.py builds the driver from this mixin. + from napalm_linux.linux import _RC_MARKER, _SUDO_PASSWORD_HINT, _split_status + + output, status = _split_status(self._run_privileged(f"{command}; echo {_RC_MARKER}$?", 30)) + if status != 0: + reason = output or f"the {name} command exited with status {status}" + if "password is required" in output: + reason = f"{reason}\n{_SUDO_PASSWORD_HINT}" + raise RuntimeError(reason) diff --git a/napalm_linux/linux.py b/napalm_linux/linux.py index fe67862..7176f35 100644 --- a/napalm_linux/linux.py +++ b/napalm_linux/linux.py @@ -76,6 +76,7 @@ from netmiko import ConnectHandler from netmiko.exceptions import NetmikoAuthenticationException, NetmikoTimeoutException from napalm_linux._dpkg import DPKG_QUERY_COMMAND, parse_dpkg_query +from napalm_linux._host_power import LinuxHostPowerMixin from napalm_linux._hostname import HostnameMixin from napalm_linux._local_accounts import LinuxLocalAccountsMixin from napalm_linux._open_port import OpenPortMixin @@ -138,16 +139,11 @@ _YUM_SECURITY_COMMAND = ( #: The exit status ``DNF_SECURITY_COMMAND`` and ``_YUM_SECURITY_COMMAND`` report. _DNF_RC_RE = re.compile(r"^__DNF_RC=(\d+)\s*$", re.MULTILINE) -#: Restart the host two seconds later, detached from this session: the launcher's -#: exit status comes back before the host goes down, and closing the session -#: cannot take the restart with it. #: ``running`` when systemd has lldpd active or a process of that name runs, else ``stopped``. _LLDPD_STATE_COMMAND = ( "if systemctl is-active --quiet lldpd 2>/dev/null || pgrep -x lldpd >/dev/null 2>&1; " "then echo running; else echo stopped; fi" ) -_REBOOT_DETACHED = "sh -c '(trap \"\" HUP; sleep 2; /sbin/reboot) /dev/null 2>&1 &'" - #: Why ``run_command`` refuses stdin to a privileged command while a sudo #: password is set (NetOrk/netork#1029). _PRIVILEGED_STDIN = ( @@ -269,6 +265,7 @@ _USER_NAME = re.compile(r"^[a-z_][a-z0-9_.\-]{0,31}$") class LinuxDriver( + LinuxHostPowerMixin, LinuxSudoHistoryMixin, LinuxLocalAccountsMixin, SnmpAgentMixin, @@ -568,21 +565,6 @@ class LinuxDriver( line, prefix = unprompted_stream(self._transport(), command, line, prefix) return open_stream_on_transport(self._transport(), line, stdin_prefix=prefix) - def reboot_host(self) -> None: - """Restart the host (``HostRebootMixin``); returns once the restart is under way. - - :raises RuntimeError: when the host refuses -- sudo without a password, - no ``reboot`` -- or its answer carried no exit status. - """ - output, status = _split_status( - self._run_privileged(f"{_REBOOT_DETACHED}; echo {_RC_MARKER}$?", 30) - ) - if status != 0: - reason = output or f"the reboot command exited with status {status}" - if "password is required" in output: - reason = f"{reason}\n{_SUDO_PASSWORD_HINT}" - raise RuntimeError(reason) - def _run_host_status_command(self, command: str) -> str: """The transport for ``HostStatusMixin.get_host_status``: read-only, no sudo.""" return self._send(command, read_timeout=60) diff --git a/pyproject.toml b/pyproject.toml index 71ce50a..5902f75 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "napalm-linux" -version = "0.24.0" +version = "0.25.0" description = "NAPALM driver for generic Linux systems via SSH" readme = "README.md" requires-python = ">=3.12" diff --git a/tests/quality_baseline.json b/tests/quality_baseline.json index 764b710..3247722 100644 --- a/tests/quality_baseline.json +++ b/tests/quality_baseline.json @@ -20,7 +20,7 @@ "napalm_linux.linux" ], "python_file_lines": { - "napalm_linux/linux.py": 1990 + "napalm_linux/linux.py": 1972 }, "untyped_public": [] } diff --git a/tests/test_linux.py b/tests/test_linux.py index 27e1725..efa1ee5 100644 --- a/tests/test_linux.py +++ b/tests/test_linux.py @@ -1896,6 +1896,51 @@ class TestRebootHost: driver.reboot_host() +class TestShutdownHost: + """``shutdown_host`` (napalm-device-types' ``HostShutdownMixin``) powers the host off. + + netOrk offers a clean shutdown where the driver defines ``shutdown_host`` + (NetOrk/netork#2841). Like the restart it is detached and a moment late, so + the launcher's exit status comes back before the host goes down. + """ + + def test_the_driver_can_shut_its_host_down(self): + assert callable(getattr(LinuxDriver, "shutdown_host", None)) + + def test_the_shutdown_is_detached_and_privileged(self, driver): + driver._root = False + driver._device.send_command.return_value = "\n__NETORK_RC=0" + + driver.shutdown_host() + + sent = driver._device.send_command.call_args[0][0] + assert sent.startswith("sudo -n sh -c ") + assert "/sbin/poweroff" in sent and "trap" in sent and "&" in sent + assert "reboot" not in sent + assert sent.endswith("echo __NETORK_RC=$?") + + def test_a_refusal_is_raised_with_what_the_host_said(self, driver): + driver._root = False + driver._device.send_command.return_value = "sudo: a password is required\n__NETORK_RC=1" + + with pytest.raises(RuntimeError, match="password is required"): + driver.shutdown_host() + + def test_a_nonzero_status_without_output_names_the_status(self, driver): + driver._root = True + driver._device.send_command.return_value = "__NETORK_RC=127" + + with pytest.raises(RuntimeError, match="status 127"): + driver.shutdown_host() + + def test_no_exit_status_is_no_success(self, driver): + driver._root = True + driver._device.send_command.return_value = "something else" + + with pytest.raises(RuntimeError): + driver.shutdown_host() + + # --------------------------------------------------------------------------- # Listening sockets: ss and the processes' cgroups, as root when it can # --------------------------------------------------------------------------- diff --git a/tests/test_sudo_without_password.py b/tests/test_sudo_without_password.py index b895475..43e523b 100644 --- a/tests/test_sudo_without_password.py +++ b/tests/test_sudo_without_password.py @@ -88,6 +88,7 @@ class TestTheSecurityAdvisories: #: Every caller of ``_run_privileged``, with an answer that satisfies it. _CALLERS = { "reboot_host": (lambda d: d.reboot_host(), ["__NETORK_RC=0"]), + "shutdown_host": (lambda d: d.shutdown_host(), ["__NETORK_RC=0"]), "refresh apt": (lambda d: d.refresh_available_updates(), ["__NETORK_RC=0"]), "check-update": ( lambda d: d.get_available_updates(),