feat(power): reboot_host and shutdown_host on FreeBSD and OpenBSD (NetOrk/netork#2841) #36

Merged
christianmanivong merged 1 commits from feature/host-shutdown-2841 into main 2026-11-29 21:58:22 +00:00
4 changed files with 115 additions and 0 deletions

No files matched your search

+5
View File
@@ -8,6 +8,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
- `reboot_host()` and `shutdown_host()` on FreeBSD and OpenBSD, through napalm-device-types'
`HostRebootMixin` and `HostShutdownMixin`: the host's restart (`shutdown -r now`) and its
clean shutdown (`shutdown -p now`) as root, detached and two seconds late, so the exit
status comes back before the session drops (NetOrk/netork#2841). A refusal raises
`RuntimeError` with what the host said.
- `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
+1
View File
@@ -42,6 +42,7 @@ provisions and manages BSD VMs (NetOrk/netork#792).
| `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+) |
| `get_ssh_server_auth` | ✓ | ✓ | napalm-device-types' `SshServerAuthMixin`: `sshd -T` as root, sshd's PAM `auth` stack from `/etc/pam.d` (FreeBSD; OpenBSD's sshd has no PAM) |
| `reboot_host`, `shutdown_host` | ✓ | ✓ | `shutdown -r now` / `shutdown -p now` as root, detached two seconds late (napalm-device-types' `HostRebootMixin`, `HostShutdownMixin`) |
| `first_boot_pending` | ✓ | always `False` | whether `/firstboot` still exists |
`get_listening_sockets` has the shape of napalm-device-types'
+40
View File
@@ -65,6 +65,14 @@ _STAGE = (
'{ cat > "$t" && printf %s "$t" || { s=$?; rm -f -- "$t"; exit $s; }; }'
)
#: Run a power command 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 command with it. ``shutdown`` takes the same flags on
#: FreeBSD and OpenBSD: ``-r`` restarts, ``-p`` powers off after the clean halt.
_DETACHED = "sh -c '(trap \"\" HUP; sleep 2; {command}) </dev/null >/dev/null 2>&1 &'"
_REBOOT_COMMAND = "/sbin/shutdown -r now"
_POWEROFF_COMMAND = "/sbin/shutdown -p now"
def _source(value: str) -> str:
"""An allowed source as an address or network, or ValueError."""
@@ -317,6 +325,38 @@ class BsdDriver(
"""
return self.run_command(command).stdout
# -- power (napalm-device-types HostRebootMixin, HostShutdownMixin) ------------
def reboot_host(self) -> None:
"""Restart the host (``HostRebootMixin``); returns once the restart is under way.
``shutdown -r now`` as root, detached and two seconds late, so its exit
status comes back before the session drops (NetOrk/netork#2841).
:raises RuntimeError: with the host's answer when it refuses -- sudo
without a password, no ``shutdown``.
"""
self._launch_detached(_REBOOT_COMMAND)
def shutdown_host(self) -> None:
"""Shut the host down cleanly (``HostShutdownMixin``); returns once it is under way.
``shutdown -p now`` as root, detached like the restart: rc's shutdown
scripts stop the services, then the machine powers off (NetOrk/netork#2841).
A clean shutdown only: cutting the power is the BMC's business.
:raises RuntimeError: with the host's answer when it refuses -- sudo
without a password, no ``shutdown``.
"""
self._launch_detached(_POWEROFF_COMMAND)
def _launch_detached(self, command: str) -> None:
"""Launch *command* as root, detached (``_DETACHED``); raise what the host said."""
result = self.run_command(_DETACHED.format(command=command), privileged=True, timeout=30)
if result.exit_code != 0:
reason = (result.stderr or result.stdout).strip()
raise RuntimeError(reason or f"{command} exited with status {result.exit_code}")
# -- facts -------------------------------------------------------------------
def _platform(self) -> dict[str, str]:
+69
View File
@@ -802,3 +802,72 @@ class TestNoServicesRestartReading:
def test_it_is_not_offered(self, cls):
assert not hasattr(cls, "get_services_need_restart")
assert not hasattr(cls, "_run_services_restart_command")
class TestHostPower:
"""``reboot_host`` and ``shutdown_host`` (napalm-device-types' ``HostRebootMixin``
and ``HostShutdownMixin``) restart and power off the BSD host (NetOrk/netork#2841).
netOrk offers either where the driver defines it. ``shutdown`` runs as root,
detached and two seconds late, so its exit status comes back before the
session drops, and closing the session cannot take it along.
"""
CASES = [("reboot_host", "/sbin/shutdown -r now"), ("shutdown_host", "/sbin/shutdown -p now")]
@pytest.mark.parametrize("cls", [FreeBSDDriver, OpenBSDDriver])
@pytest.mark.parametrize("method", ["reboot_host", "shutdown_host"])
def test_both_have_it(self, cls, method):
assert callable(getattr(cls, method, None))
@pytest.mark.parametrize("cls", [FreeBSDDriver, OpenBSDDriver])
@pytest.mark.parametrize(("method", "command"), CASES)
def test_it_is_detached_and_privileged(self, cls, method, command):
driver = _channel(cls, {})
getattr(driver, method)()
[(sent, privileged)] = driver.calls
assert privileged is True
assert command in sent and "sleep 2" in sent and "trap" in sent
assert sent.endswith("&'")
assert "</dev/null >/dev/null 2>&1" in sent
@pytest.mark.parametrize(("method", "command"), CASES)
def test_the_line_sudo_runs_parses(self, monkeypatch, method, command):
import subprocess
sent = []
monkeypatch.setattr(
base,
"run_on_transport",
lambda transport, line, stdin=None, timeout=60: sent.append(line) or _Result(),
)
driver = FreeBSDDriver("host", "netork", "")
driver._transport = lambda: object() # type: ignore[method-assign]
driver._root = False
getattr(driver, method)()
[line] = sent
assert line.startswith("sudo -n sh -c '")
parsed = subprocess.run(["sh", "-n", "-c", line], capture_output=True, text=True)
assert parsed.returncode == 0, parsed.stderr
@pytest.mark.parametrize("method", ["reboot_host", "shutdown_host"])
def test_a_refusal_is_raised_with_what_the_host_said(self, method):
driver = _channel(OpenBSDDriver, {})
driver.run_command = lambda *a, **k: _Result( # type: ignore[method-assign]
"", 1, "sudo: a password is required\n"
)
with pytest.raises(RuntimeError, match="password is required"):
getattr(driver, method)()
@pytest.mark.parametrize("method", ["reboot_host", "shutdown_host"])
def test_a_silent_refusal_names_the_exit_status(self, method):
driver = _channel(FreeBSDDriver, {})
driver.run_command = lambda *a, **k: _Result("", 127) # type: ignore[method-assign]
with pytest.raises(RuntimeError, match="127"):
getattr(driver, method)()