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
62 changes: 61 additions & 1 deletion docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ Request and response models live in `nanokvm.models`.
|---|---|
| `get_info`, `get_hardware`, `get_gpio`, `push_button` | all |
| `get_oled_info`, `set_oled_sleep` | all |
| `get_virtual_device_status`, `update_virtual_device` | all |
| `get_virtual_device_status`, `update_virtual_device` | all; `enable=` non-Pro 2.5.3 |
| `get_hostname`, `set_hostname`, `get_web_title`, `set_web_title` | non-Pro 2.2.6 / Pro |
| `get_ssh_state`, `enable_ssh`, `disable_ssh` | non-Pro 2.1.6 / Pro |
| `get_mdns_state`, `enable_mdns`, `disable_mdns` | non-Pro 2.2.2 / Pro |
Expand Down Expand Up @@ -83,6 +83,11 @@ Check the power LED rather than the video signal: on the PCIe,
`get_hdmi_state().signal` can stay `True` for about ten seconds after the
target is off.

`update_virtual_device(device)` toggles the device. From non-Pro 2.5.3,
`enable=True` or `enable=False` sets the state instead, and leaves a device
already in that state alone. Older firmware ignores `enable` and toggles, so
the client refuses it there.

### Keyboard and mouse

| Methods | Requires |
Expand Down Expand Up @@ -222,6 +227,42 @@ async for status in client.watch_image_download():

Autostart scripts run when the device boots.

### Virtual media

| Methods | Requires |
|---|---|
| `get_media`, `get_media_state`, `get_media_status`, `mount_media`, `eject_media`, `delete_media` | non-Pro 2.5.3 |
| `list_media_files`, `upload_media_file`, `download_media_file`, `delete_media_file`, `download_media` | non-Pro 2.5.3 |
| `create_media_directory` | non-Pro 2.5.4 |

From 2.5.3 the USB disk carries a medium: an image, or the device's shared data
partition. `rel` names an image by its path in the media directory, as
`get_media()` lists it; leaving `rel` out means the partition. The image
methods above keep working.

```python
media = await client.get_media() # media.media[0].rel: "debian.iso"
await client.mount_media("debian.iso", cdrom=True)
await client.eject_media()
await client.mount_media() # serve the data partition again

listing = await client.list_media_files("/") # files on the partition
await client.upload_media_file("notes.txt", "/docs")
await client.download_media_file("/docs/notes.txt", "notes-copy.txt")
await client.list_media_files("/", rel="debian.iso") # files inside an image
```

- An image is always served read-only. `cdrom=True` needs an ISO 9660 or UDF
image.
- While the target machine holds the partition, `/data` is read-only on the
device and writes fail. `get_media_state().local_writable` (2.5.4) reports it.
- `force=True` on `mount_media` and `eject_media` takes the disk back from a
target machine that holds it, losing its unflushed writes.
- The device refuses a busy, attached or full medium with `NanoKVMApiError`:
-10 virtual disk off, -11 medium attached, -12 medium in use, -13 not
browsable, -14 not enough space, -15 not an optical image, -16 name taken.
- A failed download raises and leaves no file at the destination.

### Network

| Methods | Requires |
Expand Down Expand Up @@ -285,3 +326,22 @@ package from a local file. Pass `sha256=` to check the file first; non-Pro
|---|---|
| `authenticate`, `logout`, `get_account`, `change_password`, `is_password_updated` | all |
| `get_users`, `create_user`, `update_user`, `delete_user`, `set_user_password` | non-Pro 2.5.1 |
| `get_permissions`; `permissions=` and `rotate_mcp_key=` on the methods above | non-Pro 2.5.3 |

From non-Pro 2.5.3, a `user` account holds an explicit set of `Permission`
grants; administrators hold them all. `get_permissions()` lists the catalog
with each grant's group, risk and implied grants, and `get_account().permissions`
lists what the logged-in account can do.

```python
await client.create_user("viewer", "password", permissions=[Permission.CONSOLE_VIEW])
await client.update_user("viewer", permissions=[], rotate_mcp_key=True)
```

- `create_user` without `permissions` grants console view, console control and
power, as the `user` role did before 2.5.3. An empty list grants nothing.
- `update_user(permissions=...)` replaces the stored grants. From 2.5.3 only
disabling an account ends its sessions.
- `rotate_mcp_key=True` regenerates the device MCP API key when the change or
deletion takes the `mcp` grant away, which disconnects every MCP client.
- An account without the grant for a route gets `NanoKVMPermissionError`.
2 changes: 2 additions & 0 deletions nanokvm/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from . import models
from .compatibility import require_application_version, require_hardware
from .components.hid import PASTE_CHAR_MAP, HidController
from .components.media import MediaController
from .components.mouse import MouseController
from .components.network import NetworkController
from .components.services import ServiceController
Expand Down Expand Up @@ -60,6 +61,7 @@ class NanoKVMClient(
HidController,
VideoController,
StorageController,
MediaController,
NetworkController,
ServiceController,
UserController,
Expand Down
207 changes: 207 additions & 0 deletions nanokvm/components/media.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
"""Internal virtual media operations (non-Pro 2.5.3 storage API)."""

from __future__ import annotations

import asyncio
from os import PathLike
from pathlib import Path

from aiohttp import ClientTimeout, hdrs

from ..compatibility import require_hardware
from ..exceptions import NanoKVMInvalidResponseError
from ..models.common import HWFamily
from ..models.non_pro import (
EjectMediaReq,
GetMediaFilesRsp,
GetMediaRsp,
GetMediaStateRsp,
GetMediaStatusRsp,
MediaFile,
MediaPathReq,
MediaRefReq,
MediaType,
MountMediaReq,
)
from .session import Controller


def _media_type(rel: str | None) -> MediaType:
# An image is named by its path in the media directory; no name is the
# shared data partition.
return MediaType.IMAGE if rel else MediaType.PARTITION


def _media_params(rel: str | None, **extra: str) -> dict[str, str]:
return {"type": _media_type(rel).value, "rel": rel or "", **extra}


class MediaController(Controller):
"""Implement virtual media operations behind the public client facade.

``rel`` names an image by its path relative to the media directory, as
``get_media()`` lists it. Leaving it out means the shared data partition.
"""

def _transfer_timeout(self) -> ClientTimeout:
return ClientTimeout(
total=None,
sock_connect=self._session._request_timeout,
sock_read=self._session._request_timeout,
)

@require_hardware(HWFamily.NON_PRO, min_version="2.5.3")
async def get_media(self) -> GetMediaRsp:
"""List the images and the data partition the USB disk can carry."""
return await self._session.api_request_json(
hdrs.METH_GET, "/storage/media", response_model=GetMediaRsp
)

@require_hardware(HWFamily.NON_PRO, min_version="2.5.3")
async def get_media_state(self) -> GetMediaStateRsp:
"""Get what the target machine currently sees on the USB disk."""
return await self._session.api_request_json(
hdrs.METH_GET, "/storage/media/state", response_model=GetMediaStateRsp
)

@require_hardware(HWFamily.NON_PRO, min_version="2.5.3")
async def get_media_status(self) -> GetMediaStatusRsp:
"""Get the progress of the running media file transfer."""
return await self._session.api_request_json(
hdrs.METH_GET, "/storage/media/status", response_model=GetMediaStatusRsp
)

@require_hardware(HWFamily.NON_PRO, min_version="2.5.3")
async def mount_media(
self, rel: str | None = None, *, cdrom: bool = False, force: bool = False
) -> None:
"""Attach an image, or the data partition, to the target machine.

An image is always served read-only. ``cdrom`` needs an ISO 9660 or
UDF image. ``force`` takes the disk back from a target machine that
holds it, losing its unflushed writes.
"""
await self._session.api_request_json(
hdrs.METH_POST,
"/storage/media/mount",
data=MountMediaReq(
type=_media_type(rel), rel=rel or "", cdrom=cdrom, force=force
),
)

@require_hardware(HWFamily.NON_PRO, min_version="2.5.3")
async def eject_media(self, *, force: bool = False) -> None:
"""Release the attached medium; ``force`` as in ``mount_media``."""
await self._session.api_request_json(
hdrs.METH_POST, "/storage/media/eject", data=EjectMediaReq(force=force)
)

@require_hardware(HWFamily.NON_PRO, min_version="2.5.3")
async def delete_media(self, rel: str) -> None:
"""Delete an image. The data partition cannot be deleted."""
if not rel:
raise ValueError("rel must name an image")
await self._session.api_request_json(
hdrs.METH_POST,
"/storage/media/delete",
data=MediaRefReq(type=MediaType.IMAGE, rel=rel),
)

@require_hardware(HWFamily.NON_PRO, min_version="2.5.3")
async def list_media_files(
self, path: str = "/", *, rel: str | None = None
) -> GetMediaFilesRsp:
"""List a directory inside an image or the data partition."""
return await self._session.api_request_json(
hdrs.METH_GET,
"/storage/media/files",
response_model=GetMediaFilesRsp,
params=_media_params(rel, path=path),
)

@require_hardware(HWFamily.NON_PRO, min_version="2.5.3")
async def upload_media_file(
self,
file_path: str | PathLike[str],
path: str = "/",
*,
rel: str | None = None,
) -> MediaFile:
"""Upload a local file into a directory of an image or the partition.

An existing name raises ``NanoKVMApiError`` with code -16.
"""
return await self._session.upload_file(
"/storage/media/files/upload",
file_path,
response_model=MediaFile,
params=_media_params(rel, path=path),
timeout=self._transfer_timeout(),
)

@require_hardware(HWFamily.NON_PRO, min_version="2.5.4")
async def create_media_directory(
self, path: str, *, rel: str | None = None, exist_ok: bool = False
) -> None:
"""Create a directory inside an image or the data partition."""
await self._session.api_request_json(
hdrs.METH_POST,
"/storage/media/files/mkdir",
data=MediaPathReq(
type=_media_type(rel),
rel=rel or "",
path=path,
exists_ok=exist_ok or None,
),
)

@require_hardware(HWFamily.NON_PRO, min_version="2.5.3")
async def delete_media_file(self, path: str, *, rel: str | None = None) -> None:
"""Delete a file or directory inside an image or the data partition."""
await self._session.api_request_json(
hdrs.METH_POST,
"/storage/media/files/delete",
data=MediaPathReq(type=_media_type(rel), rel=rel or "", path=path),
)

@require_hardware(HWFamily.NON_PRO, min_version="2.5.3")
async def download_media_file(
self,
path: str,
destination: str | PathLike[str],
*,
rel: str | None = None,
) -> None:
"""Save a file from inside an image or the data partition locally."""
await self._download(
"/storage/media/files/download", _media_params(rel, path=path), destination
)

@require_hardware(HWFamily.NON_PRO, min_version="2.5.3")
async def download_media(self, rel: str, destination: str | PathLike[str]) -> None:
"""Save a whole image locally. An attached image is refused."""
if not rel:
raise ValueError("rel must name an image")
await self._download("/storage/media/download", _media_params(rel), destination)

async def _download(
self, path: str, params: dict[str, str], destination: str | PathLike[str]
) -> None:
target = Path(destination)
async with self._session.request(
hdrs.METH_GET, path, params=params, timeout=self._transfer_timeout()
) as response:
# The device answers a refusal with its JSON envelope instead of
# the file.
if response.content_type == "application/json":
self._session.validate_api_response(
await self._session.read_json_response(response)
)
raise NanoKVMInvalidResponseError("Expected a file, got JSON")
try:
with target.open("wb") as file:
async for chunk in response.content.iter_chunked(1024 * 1024):
await asyncio.to_thread(file.write, chunk)
except BaseException:
target.unlink(missing_ok=True)
raise
22 changes: 20 additions & 2 deletions nanokvm/components/system.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@
from aiohttp import ClientTimeout, ServerDisconnectedError, hdrs

from ..compatibility import require_application_version, require_hardware
from ..exceptions import NanoKVMApiError, NanoKVMInvalidResponseError
from ..exceptions import (
NanoKVMApiError,
NanoKVMInvalidResponseError,
NanoKVMNotSupportedError,
)
from ..models.common import (
GetGpioRsp,
GetHardwareRsp,
Expand Down Expand Up @@ -194,15 +198,29 @@ async def update_virtual_device(
self,
device: VirtualDevice,
*,
enable: bool | None = None, # non-Pro 2.5.3
disk_type: DiskType | None = None, # Pro only
) -> None:
"""Toggle the state of a virtual device."""
"""Toggle a virtual device, or with ``enable`` set it on or off.

Older firmware ignores ``enable`` and toggles, so it is refused there.
"""
if enable is not None and not (
await self._session.application_version_at_least(non_pro="2.5.3")
and self._session.is_hardware_family(HWFamily.NON_PRO)
):
raise NanoKVMNotSupportedError(
"update_virtual_device enable requires non-Pro application "
f"version >= 2.5.3 (detected: {self._session._hw_version} "
f"{self._session._application_version})"
)
await self._session.api_request_json(
hdrs.METH_POST,
"/vm/device/virtual",
data=UpdateVirtualDeviceReq(
device=device,
type=disk_type.value if disk_type else None,
enable=enable,
),
)

Expand Down
Loading
Loading