From c9c11812333686b4bca17fb7478f41e53f5ef14b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antonio=20V=C3=A1zquez=20Blanco?= Date: Wed, 28 Oct 2026 11:15:52 +0100 Subject: [PATCH] Add a nanokvm command for one-off actions The command runs on the blocking client: info, status, power press, on and off, reset, images, mount and unmount. 'power on' and 'power off' do nothing when the power LED already shows that state, and otherwise wait for the LED. The password comes from NANOKVM_PASSWORD or a prompt, never from the command line. --- README.md | 1 + docs/cli.md | 33 ++++++ nanokvm/cli.py | 158 ++++++++++++++++++++++++++++ pyproject.toml | 3 + tests/test_cli.py | 262 ++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 457 insertions(+) create mode 100644 docs/cli.md create mode 100644 nanokvm/cli.py create mode 100644 tests/test_cli.py diff --git a/README.md b/README.md index 52ad7a6..1b387d7 100644 --- a/README.md +++ b/README.md @@ -45,5 +45,6 @@ Scripts that do not use asyncio can use the same API as blocking calls through needs - [Video streaming](docs/streaming.md): snapshots, MJPEG and WebRTC signaling - [Blocking client](docs/sync.md): the API without asyncio +- [Command line](docs/cli.md): the `nanokvm` command for one-off actions - [Errors](docs/errors.md) - [SSH](docs/ssh.md) diff --git a/docs/cli.md b/docs/cli.md new file mode 100644 index 0000000..c7fc2c3 --- /dev/null +++ b/docs/cli.md @@ -0,0 +1,33 @@ +# Command line + +Installing the package adds a `nanokvm` command for one-off actions, built on +the [blocking client](sync.md): + +```console +$ export NANOKVM_URL=http://kvm.local/api/ +$ nanokvm info +Password for admin: +hardware: PCIE +application: 2.5.2 +image: v1.4.2 +$ nanokvm power off +off +``` + +| Command | Action | +|---|---| +| `info` | Hardware, application and image versions | +| `status` | Power and HDD LEDs | +| `power press [--ms 800]` | Press the power button | +| `power on [--timeout 30]` | Short press, unless the power LED is already on; wait for the LED | +| `power off [--timeout 30]` | Hold the power button for 6 s to force the target off, unless the LED is already off; wait for the LED | +| `reset [--ms 800]` | Press the reset button | + +- `--url` or `NANOKVM_URL` selects the device, and `--username` or + `NANOKVM_USERNAME` the account (default `admin`). +- The password comes from `NANOKVM_PASSWORD` or is asked for. There is no + option for it, so it never shows in the process list. +- For HTTPS, `--ca-cert PATH` trusts a custom CA and `--insecure` skips + certificate verification (see [Connecting](connecting.md)). +- The exit status is 0 on success, 1 when the device reports an error or + cannot be reached (with a one-line message), and 2 for usage errors. diff --git a/nanokvm/cli.py b/nanokvm/cli.py new file mode 100644 index 0000000..32c453b --- /dev/null +++ b/nanokvm/cli.py @@ -0,0 +1,158 @@ +"""Command-line interface for one-off NanoKVM actions.""" + +from __future__ import annotations + +import argparse +from collections.abc import Callable, Sequence +import getpass +import os +import sys +import time +from typing import Any + +import aiohttp + +from .exceptions import NanoKVMError +from .models import GpioType +from .sync_client import NanoKVMSyncClient + +# Holding the power button this long forces a hung target off. +_FORCE_OFF_MS = 6000 +_PRESS_MS = 800 +_POLL_INTERVAL = 1.0 + + +def main(argv: Sequence[str] | None = None) -> int: + """Run the ``nanokvm`` command and return its exit status.""" + parser = _parser() + args = parser.parse_args(argv) + url = args.url or os.environ.get("NANOKVM_URL") + if not url: + parser.error("the device URL is required: pass --url or set NANOKVM_URL") + username = args.username or os.environ.get("NANOKVM_USERNAME") or "admin" + password = os.environ.get("NANOKVM_PASSWORD") + if password is None: + password = getpass.getpass(f"Password for {username}: ") + + try: + with NanoKVMSyncClient( + url, verify_ssl=not args.insecure, ssl_ca_cert=args.ca_cert + ) as kvm: + kvm.authenticate(username, password) + command: Callable[[Any, argparse.Namespace], int] = args.command + return command(kvm, args) + except (NanoKVMError, aiohttp.ClientError, TimeoutError, OSError) as err: + print(f"nanokvm: error: {str(err) or type(err).__name__}", file=sys.stderr) + return 1 + except KeyboardInterrupt: + return 130 + + +def _parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="nanokvm", + description="Run one-off actions on a NanoKVM. The password is read " + "from NANOKVM_PASSWORD or asked for.", + ) + parser.add_argument( + "--url", help="API base, e.g. http://kvm.local/api/ (default: NANOKVM_URL)" + ) + parser.add_argument( + "--username", help="login name (default: NANOKVM_USERNAME, else admin)" + ) + parser.add_argument("--ca-cert", help="CA certificate to trust for HTTPS") + parser.add_argument( + "--insecure", + action="store_true", + help="do not verify the HTTPS certificate", + ) + commands = parser.add_subparsers(metavar="COMMAND", required=True) + + commands.add_parser( + "info", help="show the hardware and firmware versions" + ).set_defaults(command=_info) + commands.add_parser( + "status", help="show the target's power and HDD LEDs" + ).set_defaults(command=_status) + + power = commands.add_parser( + "power", help="press the target's power button" + ).add_subparsers(metavar="ACTION", required=True) + press = power.add_parser("press", help="press the power button") + press.add_argument("--ms", type=int, default=_PRESS_MS, help="press duration") + press.set_defaults(command=_power_press) + for action, command, help_text in ( + ("on", _power_on, "turn the target on with a short press"), + ("off", _power_off, "force the target off by holding the button"), + ): + subcommand = power.add_parser(action, help=help_text) + subcommand.add_argument( + "--timeout", + type=float, + default=30.0, + help="seconds to wait for the power LED (default: 30)", + ) + subcommand.set_defaults(command=command) + + reset = commands.add_parser("reset", help="press the target's reset button") + reset.add_argument("--ms", type=int, default=_PRESS_MS, help="press duration") + reset.set_defaults(command=_reset) + return parser + + +def _info(kvm: Any, args: argparse.Namespace) -> int: + hardware = kvm.get_hardware() + info = kvm.get_info() + print(f"hardware: {hardware.version}") + print(f"application: {info.application}") + print(f"image: {info.image}") + return 0 + + +def _status(kvm: Any, args: argparse.Namespace) -> int: + gpio = kvm.get_gpio() + print(f"power LED: {_on_off(gpio.pwr)}") + print(f"HDD LED: {_on_off(gpio.hdd)}") + return 0 + + +def _power_press(kvm: Any, args: argparse.Namespace) -> int: + kvm.push_button(GpioType.POWER, args.ms) + return 0 + + +def _power_on(kvm: Any, args: argparse.Namespace) -> int: + return _switch_power(kvm, on=True, press_ms=_PRESS_MS, timeout=args.timeout) + + +def _power_off(kvm: Any, args: argparse.Namespace) -> int: + return _switch_power(kvm, on=False, press_ms=_FORCE_OFF_MS, timeout=args.timeout) + + +def _switch_power(kvm: Any, *, on: bool, press_ms: int, timeout: float) -> int: + """Press power unless the LED already shows ``on``, then wait for it.""" + state = _on_off(on) + if kvm.get_gpio().pwr == on: + print(f"already {state}") + return 0 + kvm.push_button(GpioType.POWER, press_ms) + deadline = time.monotonic() + timeout + while kvm.get_gpio().pwr != on: + if time.monotonic() >= deadline: + print( + f"nanokvm: error: the power LED is not {state} after {timeout:g} s", + file=sys.stderr, + ) + return 1 + time.sleep(_POLL_INTERVAL) + print(state) + return 0 + + +def _reset(kvm: Any, args: argparse.Namespace) -> int: + kvm.push_button(GpioType.RESET, args.ms) + return 0 + + +def _on_off(value: bool) -> str: + return "on" if value else "off" diff --git a/pyproject.toml b/pyproject.toml index 85cc4d3..b972aca 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -22,6 +22,9 @@ dependencies = [ "paramiko", ] +[project.scripts] +nanokvm = "nanokvm.cli:main" + [tool.setuptools.packages.find] exclude = ["tests", "tests.*"] diff --git a/tests/test_cli.py b/tests/test_cli.py new file mode 100644 index 0000000..a9991ef --- /dev/null +++ b/tests/test_cli.py @@ -0,0 +1,262 @@ +"""Tests for the nanokvm command-line interface.""" + +from __future__ import annotations + +from collections.abc import Iterator +import getpass +from typing import Any + +import pytest + +from nanokvm import cli +from nanokvm.client import NanoKVMApiError +from nanokvm.models import GetGpioRsp, GetHardwareRsp, GetInfoRsp, GpioType, HWVersion + +_URL = "http://kvm.example.test/api/" + + +class _FakeKVM: + """Stands in for NanoKVMSyncClient and records what the command does.""" + + instances: list[_FakeKVM] = [] + # Power LED readings in order; the last one repeats. + power_leds: list[bool] = [False] + login_error: Exception | None = None + + def __init__(self, url: str, **kwargs: Any) -> None: + self.url = url + self.kwargs = kwargs + self.calls: list[tuple[Any, ...]] = [] + self.power_leds = list(type(self).power_leds) + _FakeKVM.instances.append(self) + + def __enter__(self) -> _FakeKVM: + return self + + def __exit__(self, *exc_info: object) -> None: + self.calls.append(("close",)) + + def authenticate(self, username: str, password: str) -> None: + self.calls.append(("authenticate", username, password)) + if self.login_error is not None: + raise self.login_error + + def get_hardware(self) -> GetHardwareRsp: + return GetHardwareRsp(version=HWVersion.PCIE) + + def get_info(self) -> GetInfoRsp: + return GetInfoRsp.model_validate( + { + "ips": [], + "mdns": "kvm", + "image": "v1.4.2", + "application": "2.5.2", + "deviceKey": "synthetic", + } + ) + + def get_gpio(self) -> GetGpioRsp: + self.calls.append(("get_gpio",)) + pwr = self.power_leds.pop(0) if len(self.power_leds) > 1 else self.power_leds[0] + return GetGpioRsp(pwr=pwr, hdd=False) + + def push_button(self, button: GpioType, duration_ms: int) -> None: + self.calls.append(("push_button", button, duration_ms)) + + +@pytest.fixture(autouse=True) +def fake_kvm(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]: + """Replace the client and the device settings for every test.""" + _FakeKVM.instances = [] + monkeypatch.setattr(_FakeKVM, "power_leds", [False]) + monkeypatch.setattr(_FakeKVM, "login_error", None) + monkeypatch.setattr(cli, "NanoKVMSyncClient", _FakeKVM) + monkeypatch.setattr(cli, "_POLL_INTERVAL", 0) + monkeypatch.setenv("NANOKVM_URL", _URL) + monkeypatch.setenv("NANOKVM_USERNAME", "synthetic-user") + monkeypatch.setenv("NANOKVM_PASSWORD", "synthetic-password") + yield + + +def _kvm() -> _FakeKVM: + (kvm,) = _FakeKVM.instances + return kvm + + +def _presses(kvm: _FakeKVM) -> list[tuple[Any, ...]]: + return [call[1:] for call in kvm.calls if call[0] == "push_button"] + + +def _led_reads(kvm: _FakeKVM) -> int: + return kvm.calls.count(("get_gpio",)) + + +def test_info_logs_in_with_the_environment_and_prints_versions( + capsys: pytest.CaptureFixture[str], +) -> None: + """The device and login come from the environment.""" + assert cli.main(["info"]) == 0 + + kvm = _kvm() + assert kvm.url == _URL + assert kvm.kwargs == {"verify_ssl": True, "ssl_ca_cert": None} + assert kvm.calls[0] == ("authenticate", "synthetic-user", "synthetic-password") + assert kvm.calls[-1] == ("close",) + assert capsys.readouterr().out == ( + "hardware: PCIE\napplication: 2.5.2\nimage: v1.4.2\n" + ) + + +def test_options_override_the_environment() -> None: + """--url, --username and the HTTPS options reach the client.""" + cli.main( + [ + "--url", + "https://other.example.test/api/", + "--username", + "other-user", + "--ca-cert", + "ca.pem", + "--insecure", + "status", + ] + ) + + kvm = _kvm() + assert kvm.url == "https://other.example.test/api/" + assert kvm.kwargs == {"verify_ssl": False, "ssl_ca_cert": "ca.pem"} + assert kvm.calls[0] == ("authenticate", "other-user", "synthetic-password") + + +def test_the_password_is_asked_for_when_not_in_the_environment( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The password never has to appear on the command line.""" + monkeypatch.delenv("NANOKVM_PASSWORD") + prompts: list[str] = [] + + def ask(prompt: str) -> str: + prompts.append(prompt) + return "typed" + + monkeypatch.setattr(getpass, "getpass", ask) + + cli.main(["status"]) + + assert prompts == ["Password for synthetic-user: "] + assert _kvm().calls[0] == ("authenticate", "synthetic-user", "typed") + + +def test_there_is_no_password_option() -> None: + """A password option would show the password to other local users.""" + with pytest.raises(SystemExit) as exc_info: + cli.main(["--password", "secret", "status"]) + + assert exc_info.value.code == 2 + + +def test_the_url_is_required( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + """Without a device URL the command stops before connecting.""" + monkeypatch.delenv("NANOKVM_URL") + + with pytest.raises(SystemExit) as exc_info: + cli.main(["info"]) + + assert exc_info.value.code == 2 + assert "NANOKVM_URL" in capsys.readouterr().err + assert not _FakeKVM.instances + + +def test_status_prints_the_leds(capsys: pytest.CaptureFixture[str]) -> None: + """The LEDs read as on or off.""" + assert cli.main(["status"]) == 0 + + assert capsys.readouterr().out == "power LED: off\nHDD LED: off\n" + + +@pytest.mark.parametrize( + ("argv", "press"), + [ + (["power", "press"], (GpioType.POWER, 800)), + (["power", "press", "--ms", "1500"], (GpioType.POWER, 1500)), + (["reset"], (GpioType.RESET, 800)), + (["reset", "--ms", "200"], (GpioType.RESET, 200)), + ], +) +def test_button_presses(argv: list[str], press: tuple[GpioType, int]) -> None: + """Each press command holds the button for the requested time.""" + assert cli.main(argv) == 0 + + assert _presses(_kvm()) == [press] + + +def test_power_off_forces_the_target_off_and_waits_for_the_led( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + """A 6 s hold, then the power LED is polled until it goes off.""" + monkeypatch.setattr(_FakeKVM, "power_leds", [True, True, True, False]) + + assert cli.main(["power", "off"]) == 0 + + assert _presses(_kvm()) == [(GpioType.POWER, 6000)] + assert _led_reads(_kvm()) == 4 + assert capsys.readouterr().out == "off\n" + + +def test_power_on_presses_briefly_and_waits_for_the_led( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + """A short press turns the target on.""" + monkeypatch.setattr(_FakeKVM, "power_leds", [False, False, True]) + + assert cli.main(["power", "on"]) == 0 + + assert _presses(_kvm()) == [(GpioType.POWER, 800)] + assert _led_reads(_kvm()) == 3 + assert capsys.readouterr().out == "on\n" + + +@pytest.mark.parametrize(("action", "led"), [("on", True), ("off", False)]) +def test_power_does_nothing_when_already_in_that_state( + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + action: str, + led: bool, +) -> None: + """A second 'power on' must not press the button and turn it off.""" + monkeypatch.setattr(_FakeKVM, "power_leds", [led]) + + assert cli.main(["power", action]) == 0 + + assert _presses(_kvm()) == [] + assert capsys.readouterr().out == f"already {action}\n" + + +def test_power_off_fails_when_the_led_stays_on( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + """The wait is bounded by --timeout.""" + monkeypatch.setattr(_FakeKVM, "power_leds", [True]) + + assert cli.main(["power", "off", "--timeout", "0.05"]) == 1 + + assert "not off after 0.05 s" in capsys.readouterr().err + + +def test_device_errors_exit_with_a_message( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + """Errors print one line instead of a traceback.""" + monkeypatch.setattr( + _FakeKVM, + "login_error", + NanoKVMApiError("API returned error (Code: -2)", code=-2, msg="failed"), + ) + + assert cli.main(["status"]) == 1 + + assert capsys.readouterr().err == ( + "nanokvm: error: API returned error (Code: -2)\n" + )