feat(power): reboot_host and shutdown_host on FreeBSD and OpenBSD (NetOrk/netork#2841)
driver / lint (pull_request) Successful in 12s
driver / standard (pull_request) Successful in 14s
driver / lowest (pull_request) Successful in 28s
driver / test (3.12) (pull_request) Successful in 54s
driver / types (pull_request) Successful in 57s
driver / test (3.13) (pull_request) Successful in 54s
driver / build (pull_request) Successful in 25s
driver / security (pull_request) Successful in 54s
CI / driver (pull_request) Successful in 1m59s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 12s
driver / standard (pull_request) Successful in 14s
driver / lowest (pull_request) Successful in 28s
driver / test (3.12) (pull_request) Successful in 54s
driver / types (pull_request) Successful in 57s
driver / test (3.13) (pull_request) Successful in 54s
driver / build (pull_request) Successful in 25s
driver / security (pull_request) Successful in 54s
CI / driver (pull_request) Successful in 1m59s
driver / publish (pull_request) Skipped
The host's restart and its clean shutdown, through napalm-device-types' HostRebootMixin and HostShutdownMixin: shutdown -r now and shutdown -p now as root, through the driver's sudo, detached and two seconds late, so the exit status comes back before the session drops and closing the session cannot take the command with it. A refusal raises RuntimeError with what the host said.
This commit is contained in:
1 parent
41f253dafd
commit
4532c0ea1c
4 files changed
+115
No files matched your search
@@ -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
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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]:
|
||||
|
||||
@@ -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)()
|
||||
Reference in new issue
Block a user