Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 28 additions & 1 deletion docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ application: 2.5.2
image: v1.4.2
$ nanokvm power off
off
$ nanokvm media
* debian.iso
(data partition)
$ nanokvm unmount
```

| Command | Action |
Expand All @@ -22,6 +26,9 @@ off
| `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 |
| `media` | List what can be mounted; `*` marks the mounted one |
| `mount [IMAGE] [--cdrom] [--force]` | Mount an image on the target as a USB disk or a CD-ROM |
| `unmount [--force]` | Unmount the mounted medium |

- `--url` or `NANOKVM_URL` selects the device, and `--username` or
`NANOKVM_USERNAME` the account (default `admin`).
Expand All @@ -30,4 +37,24 @@ off
- 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.
cannot be reached (with a one-line message that includes the device's
reason), and 2 for usage errors.

## Media

`mount` takes an image as `media` lists it. From non-Pro 2.5.3, that is its
path in the media directory, such as `debian.iso`. On older firmware and on the
Pro, it is the full path, such as `/data/debian.iso`.

From non-Pro 2.5.3:

- `media` also lists the device's shared data partition, and `mount` without
an image attaches it.
- `unmount` leaves the target without a disk.
- While the target uses the disk, the device refuses to mount or unmount.
`--force` takes the disk back, losing the target's unflushed writes.

On older non-Pro firmware, `unmount` gives the target the data partition
instead. The API reference has the details for
[images](api.md#images-and-scripts) and for
[virtual media](api.md#virtual-media).
77 changes: 75 additions & 2 deletions nanokvm/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,21 @@

import aiohttp

from .exceptions import NanoKVMError
from .exceptions import NanoKVMApiError, NanoKVMError, NanoKVMNotSupportedError
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
# How 'media' lists the shared data partition, which 'mount' without an image
# attaches. It has no name to mount it by.
_PARTITION = "(data partition)"
_FORCE_HELP = (
"take the disk from a target that holds it, losing its unflushed writes "
"(non-Pro 2.5.3+)"
)


def main(argv: Sequence[str] | None = None) -> int:
Expand All @@ -42,7 +49,11 @@ def main(argv: Sequence[str] | None = None) -> int:
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)
message = str(err) or type(err).__name__
if isinstance(err, NanoKVMApiError) and err.msg:
# The device says why it refused, such as a medium the target holds.
message = f"{message}: {err.msg}"
print(f"nanokvm: error: {message}", file=sys.stderr)
return 1
except KeyboardInterrupt:
return 130
Expand Down Expand Up @@ -97,6 +108,23 @@ def _parser() -> argparse.ArgumentParser:
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)

commands.add_parser(
"media", help="list what can be mounted; * marks the mounted one"
).set_defaults(command=_media)
mount = commands.add_parser("mount", help="mount an image on the target")
mount.add_argument(
"image",
nargs="?",
help="image as 'media' lists it; without it, the data partition "
"(non-Pro 2.5.3+)",
)
mount.add_argument("--cdrom", action="store_true", help="mount as a CD-ROM")
mount.add_argument("--force", action="store_true", help=_FORCE_HELP)
mount.set_defaults(command=_mount)
unmount = commands.add_parser("unmount", help="unmount the mounted medium")
unmount.add_argument("--force", action="store_true", help=_FORCE_HELP)
unmount.set_defaults(command=_unmount)
return parser


Expand Down Expand Up @@ -154,5 +182,50 @@ def _reset(kvm: Any, args: argparse.Namespace) -> int:
return 0


# Non-Pro 2.5.3 moved virtual media to the storage API. The client refuses it
# on older firmware and on the Pro, which keep the image API.


def _media(kvm: Any, args: argparse.Namespace) -> int:
try:
media = kvm.get_media().media
except NanoKVMNotSupportedError:
mounted = kvm.get_mounted_image().file
listing = [(image == mounted, image) for image in kvm.get_images().files]
else:
listing = [(item.attached, item.rel or _PARTITION) for item in media]
for attached, name in listing:
print(f"{'*' if attached else ' '} {name}")
return 0


def _mount(kvm: Any, args: argparse.Namespace) -> int:
try:
kvm.mount_media(args.image, cdrom=args.cdrom, force=args.force)
except NanoKVMNotSupportedError:
if args.image is None:
raise NanoKVMNotSupportedError(
"name an image: mounting the data partition needs non-Pro 2.5.3 "
"or newer"
) from None
_refuse_force(args)
kvm.mount_image(args.image, cdrom=args.cdrom)
return 0


def _unmount(kvm: Any, args: argparse.Namespace) -> int:
try:
kvm.eject_media(force=args.force)
except NanoKVMNotSupportedError:
_refuse_force(args)
kvm.mount_image(None)
return 0


def _refuse_force(args: argparse.Namespace) -> None:
if args.force:
raise NanoKVMNotSupportedError("--force needs non-Pro 2.5.3 or newer")


def _on_off(value: bool) -> str:
return "on" if value else "off"
164 changes: 159 additions & 5 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,44 @@
import pytest

from nanokvm import cli
from nanokvm.client import NanoKVMApiError
from nanokvm.models import GetGpioRsp, GetHardwareRsp, GetInfoRsp, GpioType, HWVersion
from nanokvm.client import NanoKVMApiError, NanoKVMNotSupportedError
from nanokvm.models import (
GetGpioRsp,
GetHardwareRsp,
GetImagesRsp,
GetInfoRsp,
GetMediaRsp,
GetMountedImageRsp,
GpioType,
HWVersion,
)

_URL = "http://kvm.example.test/api/"


def _medium(rel: str, *, attached: bool) -> dict[str, Any]:
return {
"type": "image" if rel else "partition",
"rel": rel,
"name": rel or "Shared folder",
"size": 0,
"fs": "iso9660" if rel else "exfat",
"browsable": True,
"attached": attached,
"modifiedAt": "2026-11-16T00:00:00Z",
}


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
# Whether the device has the non-Pro 2.5.3 media API; without it, the
# client refuses those calls and only the image API is left.
media_api = True

def __init__(self, url: str, **kwargs: Any) -> None:
self.url = url
Expand Down Expand Up @@ -63,13 +88,50 @@ def get_gpio(self) -> GetGpioRsp:
def push_button(self, button: GpioType, duration_ms: int) -> None:
self.calls.append(("push_button", button, duration_ms))

def _require_media_api(self) -> None:
if not self.media_api:
raise NanoKVMNotSupportedError("requires non-Pro 2.5.3")

def get_media(self) -> GetMediaRsp:
self._require_media_api()
return GetMediaRsp.model_validate(
{
"media": [
_medium("debian.iso", attached=False),
_medium("isos/win.iso", attached=True),
_medium("", attached=False),
],
"capabilities": {"loop": True},
}
)

def mount_media(
self, rel: str | None = None, *, cdrom: bool = False, force: bool = False
) -> None:
self._require_media_api()
self.calls.append(("mount_media", rel, cdrom, force))

def eject_media(self, *, force: bool = False) -> None:
self._require_media_api()
self.calls.append(("eject_media", force))

def get_images(self) -> GetImagesRsp:
return GetImagesRsp(files=["/data/debian.iso", "/data/win.iso"])

def get_mounted_image(self) -> GetMountedImageRsp:
return GetMountedImageRsp(file="/data/win.iso")

def mount_image(self, file: str | None = None, cdrom: bool = False) -> None:
self.calls.append(("mount_image", file, cdrom))


@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(_FakeKVM, "media_api", True)
monkeypatch.setattr(cli, "NanoKVMSyncClient", _FakeKVM)
monkeypatch.setattr(cli, "_POLL_INTERVAL", 0)
monkeypatch.setenv("NANOKVM_URL", _URL)
Expand All @@ -91,6 +153,14 @@ def _led_reads(kvm: _FakeKVM) -> int:
return kvm.calls.count(("get_gpio",))


def _mounts(kvm: _FakeKVM) -> list[tuple[Any, ...]]:
return [
call
for call in kvm.calls
if call[0] in {"mount_media", "eject_media", "mount_image"}
]


def test_info_logs_in_with_the_environment_and_prints_versions(
capsys: pytest.CaptureFixture[str],
) -> None:
Expand Down Expand Up @@ -245,18 +315,102 @@ def test_power_off_fails_when_the_led_stays_on(
assert "not off after 0.05 s" in capsys.readouterr().err


def test_media_lists_images_and_the_data_partition(
capsys: pytest.CaptureFixture[str],
) -> None:
"""From non-Pro 2.5.3, images go by their path in the media directory."""
assert cli.main(["media"]) == 0

assert capsys.readouterr().out == (
" debian.iso\n* isos/win.iso\n (data partition)\n"
)


def test_media_lists_images_on_the_image_api(
monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
"""Older firmware and the Pro list images by their full path."""
monkeypatch.setattr(_FakeKVM, "media_api", False)

assert cli.main(["media"]) == 0

assert capsys.readouterr().out == " /data/debian.iso\n* /data/win.iso\n"


@pytest.mark.parametrize(
("argv", "media_api", "calls"),
[
(["mount", "debian.iso"], True, [("mount_media", "debian.iso", False, False)]),
(
["mount", "debian.iso", "--cdrom", "--force"],
True,
[("mount_media", "debian.iso", True, True)],
),
(["mount"], True, [("mount_media", None, False, False)]),
(["unmount"], True, [("eject_media", False)]),
(["unmount", "--force"], True, [("eject_media", True)]),
(
["mount", "/data/debian.iso", "--cdrom"],
False,
[("mount_image", "/data/debian.iso", True)],
),
(["unmount"], False, [("mount_image", None, False)]),
],
)
def test_mount_and_unmount(
monkeypatch: pytest.MonkeyPatch,
argv: list[str],
media_api: bool,
calls: list[tuple[Any, ...]],
) -> None:
"""The media API from non-Pro 2.5.3, the image API before it and on the Pro."""
monkeypatch.setattr(_FakeKVM, "media_api", media_api)

assert cli.main(argv) == 0

assert _mounts(_kvm()) == calls


@pytest.mark.parametrize(
("argv", "error"),
[
(["mount"], "mounting the data partition needs non-Pro 2.5.3"),
(["mount", "/data/debian.iso", "--force"], "--force needs non-Pro 2.5.3"),
(["unmount", "--force"], "--force needs non-Pro 2.5.3"),
],
)
def test_the_image_api_refuses_media_api_options(
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
argv: list[str],
error: str,
) -> None:
"""Without the media API, nothing is mounted or unmounted instead."""
monkeypatch.setattr(_FakeKVM, "media_api", False)

assert cli.main(argv) == 1

assert _mounts(_kvm()) == []
assert error 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."""
"""Errors print one line, with the device's reason, instead of a traceback."""
monkeypatch.setattr(
_FakeKVM,
"login_error",
NanoKVMApiError("API returned error (Code: -2)", code=-2, msg="failed"),
NanoKVMApiError(
"API returned error (Code: -11)",
code=-11,
msg="the target machine is using the medium",
),
)

assert cli.main(["status"]) == 1

assert capsys.readouterr().err == (
"nanokvm: error: API returned error (Code: -2)\n"
"nanokvm: error: API returned error (Code: -11): "
"the target machine is using the medium\n"
)
Loading