Skip to content
Merged
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
33 changes: 33 additions & 0 deletions docs/cli.md
Original file line number Diff line number Diff line change
@@ -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.
158 changes: 158 additions & 0 deletions nanokvm/cli.py
Original file line number Diff line number Diff line change
@@ -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"
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ dependencies = [
"paramiko",
]

[project.scripts]
nanokvm = "nanokvm.cli:main"

[tool.setuptools.packages.find]
exclude = ["tests", "tests.*"]

Expand Down
Loading
Loading