"""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)