"""Base client classes with the full generated API surface.
Generated by codegen from the OpenAPI spec - do not edit.
"""
# E501 only: spec-provided docstrings embed markdown tables that
# cannot be wrapped without breaking them; everything else in this
# file obeys the line limit and stays lint-gated
from __future__ import annotations
import asyncio
import logging
import math
import platform
import sys
import time
from abc import ABC, abstractmethod
from collections.abc import AsyncGenerator, Iterable, Iterator, Sequence
from contextlib import aclosing
from datetime import datetime
from pathlib import Path
from types import EllipsisType, TracebackType
from typing import IO, Any, Literal, TypeVar
from urllib.parse import urlsplit
from . import operations
from .exceptions import (
APIConnectionError,
APIStatusError,
NotFoundError,
)
from .models import (
ClosableStreamRepr,
DirectoryList,
File,
FileResponse,
FilesListResponse,
FileSpec,
GrepResult,
Image,
ImageImportRegistry,
ImageListResponse,
InstanceNetworking,
InstanceResourcesLimits,
InstanceResult,
InstanceSpawnResponse,
ListNetworkPolicyTagsResponse,
NetworkPolicy,
NetworkPolicyCIDRRule,
NetworkPolicyListResponse,
NetworkPolicyTag,
OperationEvent,
OperationResponse,
OperationStatus,
OperationSummary,
ProcessResourcesLimits,
WhoAmIResponse,
)
from .profiles import AUTH_TYPE_IAM, Profile, ProfileError, resolve_profile
from .runtime import (
REQUEST_DEADLINE_MESSAGE,
TIGHT_LOOP_FLOOR,
BodyFormatter,
HeaderFormatter,
RequestSpec,
ResponseData,
RetryPolicy,
SSEParser,
body_start,
closing_iterator,
decode_event_frame,
encode_query,
file_sha256,
is_uuid,
logger,
package_version,
retry_generator,
rewind_body,
)
from .spec_info import DEFAULT_BASE_URL
TClient = TypeVar("TClient", bound="ContreeClientBase")
TSyncClient = TypeVar("TSyncClient", bound="ContreeSyncClient")
TAsyncClient = TypeVar("TAsyncClient", bound="ContreeAsyncClient")
[docs]
def deadline_limits_timeout(
deadline: float | None,
timeout: float | None,
) -> bool:
return deadline is not None and (
timeout is None or deadline - time.monotonic() <= timeout
)
[docs]
def deadline_due(
deadline: float | None,
timeout_limited: bool = False,
) -> bool:
return deadline is not None and (timeout_limited or time.monotonic() >= deadline)
[docs]
class ContreeClientBase:
"""Shared configuration, URL and header building.
Implementations replace ``log`` with a child logger named after
the backend; raw request/response logging happens here so every
transport reports uniformly.
"""
log: logging.Logger = logger
# User-Agent product tokens; adapters override UA_TRANSPORT_LIBRARY
UA_PRODUCT = f"contree-client/{package_version()}"
UA_TRANSPORT_LIBRARY = ""
UA_PYTHON_VERSION = f"Python/{'.'.join(map(str, sys.version_info[:3]))}"
UA_PLATFORM = platform.platform()
def __init__(
self,
token: str,
*,
base_url: str = DEFAULT_BASE_URL,
project: str | None = None,
timeout: float | None = 300.0,
retry: RetryPolicy | None = None,
identity: str | None = None,
) -> None:
# a typo like "htps://" must not silently degrade to plaintext
# HTTP on port 80 with the bearer token in the clear
parts = urlsplit(base_url)
if parts.scheme not in ("http", "https"):
raise ValueError(
f"unsupported base_url scheme {parts.scheme!r}"
f" in {base_url!r}: use http:// or https://"
)
# Reject permanent URL syntax errors before a backend can
# misclassify them as transient transport failures.
hostname = parts.hostname
if not hostname:
raise ValueError(f"base_url has no hostname: {base_url!r}")
if any(
character.isspace() or ord(character) < 32 or ord(character) == 127
for character in hostname
):
raise ValueError(f"base_url has invalid hostname: {base_url!r}")
try:
_ = parts.port
except ValueError as exc:
raise ValueError(f"base_url has invalid port: {base_url!r}") from exc
self.token = token
self.base_url = base_url.rstrip("/")
self.project = project
self.timeout = timeout
self.retry = retry
# an application product token prepended to the User-Agent,
# e.g. identity="my-app/1.2.3" - the library tokens stay
self.identity = identity
[docs]
@classmethod
def from_profile(
cls: type[TClient],
profile: str | Profile | None = None,
*,
config_path: str | Path | None = None,
**kwargs: Any,
) -> TClient:
"""Create a client from a saved Contree profile.
Resolution order: explicit *profile* argument, then the
``CONTREE_PROFILE`` environment variable, then the active
profile recorded in the config file.
"""
resolved = (
profile
if isinstance(profile, Profile)
else resolve_profile(profile, path=config_path)
)
if resolved.token is None or not resolved.token.strip():
raise ProfileError(f"profile {resolved.name!r} has no token")
if not resolved.url and resolved.auth_type != AUTH_TYPE_IAM:
raise ProfileError(f"profile {resolved.name!r} has no URL")
return cls(
resolved.token,
base_url=resolved.url or DEFAULT_BASE_URL,
project=resolved.project,
**kwargs,
)
[docs]
def build_url(self, spec: RequestSpec) -> str:
url = f"{self.base_url}/v1{spec.path}"
if spec.query:
url = f"{url}?{encode_query(spec.query)}"
return url
[docs]
def user_agent(self) -> str:
"""Compose the User-Agent from the ``UA_*`` product tokens.
The caller's ``identity`` (constructor kwarg) leads, so an
application announces itself without erasing the library and
transport tokens.
"""
parts = (
self.identity or "",
self.UA_PRODUCT,
self.UA_TRANSPORT_LIBRARY,
self.UA_PYTHON_VERSION,
self.UA_PLATFORM,
)
return " ".join(part for part in parts if part)
[docs]
def log_request(self, spec: RequestSpec) -> None:
"""Log the raw outgoing request; secrets are redacted."""
if not self.log.isEnabledFor(logging.DEBUG):
return
self.log.debug(
"%s %s headers=%s body=%s",
spec.method,
self.build_url(spec),
HeaderFormatter(self.build_headers(spec)),
BodyFormatter(spec.body, spec.content_type or ""),
)
[docs]
def log_response(self, spec: RequestSpec, response: ResponseData) -> None:
"""Log the raw buffered response."""
if not self.log.isEnabledFor(logging.DEBUG):
return
self.log.debug(
"%s %s -> %d headers=%s body=%s",
spec.method,
self.build_url(spec),
response.status,
HeaderFormatter(response.headers.items()),
BodyFormatter(
response.body,
response.headers.get("content-type", ""),
),
)
[docs]
class ContreeSyncClient(ContreeClientBase, ABC):
"""Synchronous Contree API client interface.
Backend implementations only provide :meth:`request`,
:meth:`stream` and :meth:`close`.
"""
[docs]
@abstractmethod
def request(self, spec: RequestSpec) -> ResponseData:
"""Execute the request and return the buffered response."""
[docs]
@abstractmethod
def stream(
self,
spec: RequestSpec,
auto_decompress: bool = True,
) -> Iterator[bytes]:
"""Execute the request and yield response body chunks.
With ``auto_decompress=False`` the body is yielded exactly as
served (e.g. the gzip the server always applies is kept).
"""
[docs]
@abstractmethod
def close(self) -> None:
"""Release the underlying transport resources."""
[docs]
def open(self) -> None:
"""Eagerly initialize the underlying transport.
Called by ``__enter__``. Backends that create their resources
lazily override this; the default is a no-op.
"""
def __enter__(self: TSyncClient) -> TSyncClient:
self.open()
return self
def __exit__(
self,
exc_type: type[BaseException] | None,
exc: BaseException | None,
tb: TracebackType | None,
) -> None:
self.close()
[docs]
def call(self, spec: RequestSpec) -> ResponseData:
"""Execute a buffered request, retrying per the client policy.
Without a policy this is a transparent single :meth:`request`.
Streaming requests are never routed here - SSE consumers
reconnect with ``Last-Event-Id`` instead.
"""
policy = self.retry
if policy is None:
if spec.deadline is not None and time.monotonic() >= spec.deadline:
raise TimeoutError(REQUEST_DEADLINE_MESSAGE)
deadline_limited = deadline_limits_timeout(spec.deadline, self.timeout)
try:
response = self.request(spec)
except APIConnectionError as exc:
if deadline_due(spec.deadline, deadline_limited and exc.timed_out):
raise TimeoutError(REQUEST_DEADLINE_MESSAGE) from exc
raise
if spec.deadline is not None and time.monotonic() >= spec.deadline:
raise TimeoutError(REQUEST_DEADLINE_MESSAGE)
return response
# a lost response after a non-idempotent request (POST) could
# mean a second execution server-side: never blind-retry
# unless the caller explicitly opted into that risk. 425 Too
# Early and 429 Too Many Requests are the exceptions - the
# backend's contract guarantees both mean the request was
# rejected before any processing, so replaying is always safe.
replay_safe = spec.idempotent or policy.retry_unsafe
delays = retry_generator(policy.delays)
# a retry must replay exactly the bytes the first attempt sent
start = body_start(spec)
attempts = 0
while True:
if spec.deadline is not None and time.monotonic() >= spec.deadline:
raise TimeoutError(REQUEST_DEADLINE_MESSAGE)
attempts += 1
exhausted = (
policy.max_attempts is not None and attempts >= policy.max_attempts
)
deadline_limited = deadline_limits_timeout(spec.deadline, self.timeout)
try:
response = self.request(spec)
except APIConnectionError as exc:
if deadline_due(spec.deadline, deadline_limited and exc.timed_out):
raise TimeoutError(REQUEST_DEADLINE_MESSAGE) from exc
if not replay_safe or exhausted:
raise
delay = next(delays)
self.log.warning(
"network error (%s), retrying in %.1fs...",
type(exc).__name__,
delay,
)
if spec.deadline is not None:
delay = min(
delay,
max(0.0, spec.deadline - time.monotonic()),
)
time.sleep(delay)
rewind_body(spec, start)
continue
except APIStatusError as exc:
if not policy.retryable_status(exc.status) or exhausted:
raise
if not replay_safe and exc.status not in (425, 429):
raise
delay = exc.retry_after
if delay is None:
delay = next(delays)
self.log.warning(
"server answered %d, retrying in %.1fs...",
exc.status,
delay,
)
if spec.deadline is not None:
delay = min(
delay,
max(0.0, spec.deadline - time.monotonic()),
)
time.sleep(delay)
rewind_body(spec, start)
continue
if spec.deadline is not None and time.monotonic() >= spec.deadline:
raise TimeoutError(REQUEST_DEADLINE_MESSAGE)
return response
[docs]
def operation_terminal(
self,
operation_id: str,
deadline: float | None = None,
) -> bool:
"""Best-effort check that the operation reached a terminal state."""
spec = operations.build_get_operation_status(operation_id=operation_id)
spec.deadline = deadline
deadline_limited = deadline_limits_timeout(deadline, self.timeout)
try:
self.log_request(spec)
response = self.request(spec)
if deadline is not None and time.monotonic() >= deadline:
raise TimeoutError(
f"operation {operation_id} status probe exceeded its deadline"
)
self.log_response(spec, response)
status = operations.parse_get_operation_status(response).status
except APIConnectionError as exc:
if deadline_due(deadline, deadline_limited and exc.timed_out):
raise TimeoutError(
f"operation {operation_id} status probe exceeded its deadline"
) from exc
return False
except APIStatusError as exc:
if deadline_due(deadline):
raise TimeoutError(
f"operation {operation_id} status probe exceeded its deadline"
) from exc
if exc.status in (410, 425, 429) or exc.status >= 500:
return False
raise
except TimeoutError as exc:
if deadline is not None:
raise TimeoutError(
f"operation {operation_id} status probe exceeded its deadline"
) from exc
raise
return not isinstance(status, EllipsisType) and status.is_terminal()
def _read_operation_status(
self,
operation_id: str,
deadline: float | None,
) -> OperationResponse:
"""Fetch status using the waiter's deadline."""
spec = operations.build_get_operation_status(operation_id=operation_id)
spec.deadline = deadline
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_get_operation_status(response)
[docs]
def wait_operation(
self,
operation_id: str,
*,
timeout: float | None = None,
follow_events: bool | None = None,
idle_timeout: float = 15.0,
) -> OperationResponse:
"""Wait for the terminal operation response.
``follow_events=None`` follows instance events and polls image imports
every 0.5 seconds. Use ``True`` to force events or ``False`` to force
polling. Keep the event stream open until completion, EOF, a transport
error, or a timeout. ``idle_timeout`` is the maximum gap between
incoming data chunks in seconds (default 15.0; 0 disables it).
Ping/keepalive traffic resets this limit; it does not extend the
overall timeout. Gaps between payload events do not trigger checks.
After completion, poll until the status is terminal.
Return failed and cancelled responses unchanged.
``timeout`` covers the entire wait and raises :class:`TimeoutError`
on expiry. Sync buffered reads can delay the exception until the
response ends.
"""
if not math.isfinite(idle_timeout) or idle_timeout < 0:
raise ValueError("idle_timeout must be finite and non-negative")
deadline = None if timeout is None else time.monotonic() + timeout
timeout_message = f"operation {operation_id} did not complete within {timeout}s"
try:
result = None
if follow_events is None:
result = self._read_operation_status(operation_id, deadline)
follow_events = result.kind != "image_import"
if follow_events:
remaining = (
None if deadline is None else max(0.0, deadline - time.monotonic())
)
for event in self.follow_operation_events(
operation_id, timeout=remaining, idle_timeout=idle_timeout
):
self.log.debug("wait_operation: event %s %s", event.id, event.type)
result = self._read_operation_status(operation_id, deadline)
if result is None:
result = self._read_operation_status(operation_id, deadline)
while True:
if (
not isinstance(result.status, EllipsisType)
and result.status.is_terminal()
):
return result
delay = TIGHT_LOOP_FLOOR
if deadline is not None:
delay = min(delay, max(0.0, deadline - time.monotonic()))
time.sleep(delay)
result = self._read_operation_status(operation_id, deadline)
except TimeoutError as exc:
if deadline is not None:
raise TimeoutError(timeout_message) from exc
raise
[docs]
def follow_operation_events(
self,
operation_id: str,
*,
last_event_id: int | None = None,
spid: int | None = None,
since: int | None = None,
timeout: float | None = None,
idle_timeout: float = 15.0,
) -> Iterator[OperationEvent]:
"""Stream operation events with transparent reconnection.
Native stream failures trigger a terminal-status probe and a
reconnect from the last event id. Iteration ends at the
``completion`` event or the timeout. After a terminal status,
drain the retained log without following before ending iteration.
Interrupted retained reads resume from the last event id, using
the configured retry policy (three attempts by default). Normal
EOF also completes a filtered or explicitly resumed retained log.
An unfiltered log must include completion. An unavailable or
incomplete event log raises APIConnectionError.
The timeout is an absolute deadline checked whenever iteration
resumes. Caller code between events is not interrupted. A
synchronous native read can delay ``TimeoutError`` until it
returns. ``idle_timeout`` bounds gaps between incoming data in seconds
(default 15.0; 0 disables it). Ping/keepalive traffic resets this
limit without extending the overall timeout.
"""
if not math.isfinite(idle_timeout) or idle_timeout < 0:
raise ValueError("idle_timeout must be finite and non-negative")
last_id = last_event_id
terminal = False
drain_attempts = 0
policy = self.retry or RetryPolicy(max_attempts=3)
delays = retry_generator(policy.delays)
deadline = None if timeout is None else time.monotonic() + timeout
def check_deadline() -> None:
if deadline_due(deadline):
raise TimeoutError(
f"operation {operation_id} events did not complete"
f" within {timeout}s"
)
while True:
check_deadline()
events_before = last_id
if terminal:
drain_attempts += 1
try:
with closing_iterator(
self.iter_operation_events(
operation_id,
follow=not terminal,
spid=spid,
since=since,
last_event_id=last_id,
deadline=deadline,
idle_timeout=idle_timeout,
)
) as source:
for event in source:
last_id = event.id
yield event
if event.type == "completion":
return
check_deadline()
except (APIConnectionError, APIStatusError) as exc:
check_deadline()
retryable = not isinstance(exc, APIStatusError) or (
policy.retryable_status(exc.status)
)
resume_id = getattr(exc, "last_event_id", None)
if isinstance(resume_id, int):
last_id = resume_id
self.log.warning("stream broken (last_id=%s): %s", last_id, exc)
if not retryable or (
terminal
and policy.max_attempts is not None
and drain_attempts >= policy.max_attempts
):
raise APIConnectionError(
f"operation {operation_id} event log could not be read"
) from exc
if terminal:
delay = next(delays)
if deadline is not None:
delay = min(delay, max(0.0, deadline - time.monotonic()))
time.sleep(delay)
continue
else:
if terminal:
if spid is None and since is None and last_event_id is None:
raise APIConnectionError(
f"operation {operation_id} event log"
" ended without completion"
)
return
# A terminal status does not mean this subscriber received all
# events. Reconnect to drain the retained tail, retaining
# the cursor, filters and original deadline.
terminal = self.operation_terminal(operation_id, deadline)
if not terminal and last_id == events_before:
delay = TIGHT_LOOP_FLOOR
if deadline is not None:
delay = min(delay, max(0.0, deadline - time.monotonic()))
time.sleep(delay)
[docs]
def resolve_image(self, ref: str) -> str:
"""Resolve an image reference to a UUID.
Accepts a raw UUID, ``tag:NAME`` or a bare tag name.
"""
if ref.startswith("tag:"):
return self.inspect_find_image_by_tag(ref[4:])
if is_uuid(ref):
return ref
return self.inspect_find_image_by_tag(ref)
[docs]
def ensure_file(
self,
content: bytes | IO[bytes],
*,
sha256: str | None = None,
) -> FileResponse | File:
"""Upload *content* unless the server already stores it.
The digest (*sha256* when the caller already knows it,
computed locally otherwise) is probed via :meth:`get_file`;
only a miss uploads. Returns the stored file record either way
(both shapes carry ``uuid``, ``sha256`` and ``size``).
Non-seekable streams cannot be hashed and rewound, so without
a caller-provided *sha256* they skip deduplication and upload
directly.
"""
digest = sha256 if sha256 is not None else file_sha256(content)
if digest is None:
return self.upload_file(content)
try:
return self.get_file(digest)
except NotFoundError:
return self.upload_file(content)
[docs]
def list_network_policies(
self,
*,
search: str | None = None,
limit: int | None = None,
offset: int | None = None,
) -> NetworkPolicyListResponse:
"""List network policies.
Returns policies in your namespace and the shared namespace. Deleted
policies are excluded.
Reusing or restoring a policy does not change its creation time or
listing position.
Each entry contains the policy UUID, creation timestamp, accessible
tags, and a summary
with the number of IP rules. Tags are sorted by name. Your tag takes
precedence over
a shared tag with the same name; the overridden shared binding is
omitted.
Use ``GET /network/policies/{uuid}`` to retrieve the full rules.
Requires ``spawn`` or ``spawn_disposable`` permission.
Search:
Supply ``search`` to find active policies in your namespace and the
shared namespace
that allow the destination. The input determines the search type;
currently only IPv4
and IPv6 addresses and CIDRs are supported. Domains and other
unsupported inputs
return 400. An omitted search parameter lists policies normally; an
empty value
returns 400.
Use ``[tcp://|udp://]address-or-cidr[:port]``. IPv6 addresses and CIDRs
must be
enclosed in brackets when specifying a port, with the prefix length
inside
the brackets. Examples: ``192.0.2.1``, ``192.0.2.0/24:443``,
``tcp://192.0.2.0/24:443``, and ``udp://[2001:db8::/64]:53``.
This is search syntax, not a URL. CIDRs must use their network address;
host bits, scoped IPv6 addresses, and ports outside 1-65535 return 400.
A match must allow the requested protocol and port throughout the entire
CIDR,
not merely overlap it. An IP address is treated as a /32 or /128 CIDR.
All-port rules match every requested port. If protocol or port is
omitted,
any single protocol/port combination covering the entire destination
matches.
Complementary subnets granting that same access are normalized into a
covering
rule. Permissions from different policies are never combined for search.
Empty policies do not match. Filtering happens before pagination, and
results
retain the same order, summary, timestamp, and tags as the normal
listing.
Args:
search: IP or CIDR search, optionally qualified by TCP/UDP and a
destination port.
limit: Maximum number of results to return. Invalid values raise
400 error.
offset: Number of results to skip. Invalid values raise 400
error.
"""
spec = operations.build_list_network_policies(
search=search, limit=limit, offset=offset
)
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_list_network_policies(response)
[docs]
def create_network_policy(
self, cidrs: list[NetworkPolicyCIDRRule]
) -> NetworkPolicy:
"""Create a network policy.
Creates a policy with immutable rules in the caller's namespace.
Requires ``network_policy`` permission.
**Rules**
- Each rule allows a CIDR for the selected protocol and ports. An empty
or
omitted port list allows all ports.
- ICMP is allowed to every listed CIDR, regardless of protocol or ports.
- An empty rules array (``cidrs: []``) blocks all IP egress, including
ICMP
and traffic to the host.
- ARP is blocked for all policies.
**Limits**
The same limit of 16384 units applies before and after normalization.
Sum the number of ports across all rules, counting an empty or omitted
port list (all ports) as 1. The limit covers the entire policy, across
all IP versions and protocols.
Duplicates count toward the limit before normalization. Exceeding the
limit returns 400, even if normalization would remove redundant rules or
ports.
**Normalization**
Before storage, duplicate rules and ports are removed, CIDRs are merged
per protocol and port, and rules and ports are sorted. This preserves
the
allowed traffic. The response contains the normalized rules.
**Policy identity**
Equivalent normalized policies in the same namespace reuse the same
UUID,
including concurrent requests. The UUID is UUIDv5 derived from the
namespace
and the normalized policy hash. Resubmitting a deleted policy restores
it
without restoring its tags. To change the rules, create a new policy.
"""
spec = operations.build_create_network_policy(cidrs=cidrs)
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_create_network_policy(response)
[docs]
def get_network_policy(self, uuid: str) -> NetworkPolicy:
"""Get a network policy.
Returns an accessible policy, including deleted policies.
Returns 404 if the policy does not exist.
Requires ``spawn`` or ``spawn_disposable`` permission.
Args:
uuid: Network policy UUID Example:
``12345678-9abc-baba-deda-0123456789ab``.
"""
spec = operations.build_get_network_policy(uuid=uuid)
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_get_network_policy(response)
[docs]
def delete_network_policy(self, uuid: str) -> None:
"""Remove a network policy.
Removes a policy in your namespace. Requires ``network_policy``
permission.
Returns 204 if the policy is removed or was already removed.
Returns 404 if the policy does not exist in your namespace.
Removes its tags and excludes it from listings. The policy remains
accessible
and usable by UUID, but cannot be assigned to tags.
Args:
uuid: Network policy UUID Example:
``12345678-9abc-baba-deda-0123456789ab``.
"""
spec = operations.build_delete_network_policy(uuid=uuid)
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_delete_network_policy(response)
[docs]
def get_network_policy_tag(self, tag: str) -> NetworkPolicyTag:
"""Get a network policy tag.
Redirects to the policy referenced by your tag, or the shared tag if you
have no tag with that name.
The redirect response includes the effective tag binding as JSON.
Requires ``spawn`` or ``spawn_disposable`` permission. Returns 404 if
the tag or its target
policy does not exist or is removed.
Args:
tag: Network policy tag name
"""
spec = operations.build_get_network_policy_tag(tag=tag)
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_get_network_policy_tag(response)
[docs]
def set_network_policy_tag(self, tag: str, uuid: str) -> NetworkPolicyTag:
"""Bind a tag to a network policy.
Creates or replaces your tag's binding to an active policy in your
namespace or the shared namespace.
Repeating the same binding has no effect. Returns 404 if the target
policy
does not exist, is inaccessible, or is removed. The tag belongs to your
namespace.
Requires ``network_policy`` permission.
Args:
tag: Network policy tag name
"""
spec = operations.build_set_network_policy_tag(tag=tag, uuid=uuid)
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_set_network_policy_tag(response)
[docs]
def delete_network_policy_tag(self, tag: str) -> None:
"""Remove a network policy tag.
Removes your tag, including when operations use its policy. Repeated
deletion succeeds.
If a shared tag has the same name, it becomes visible again.
Requires ``network_policy`` permission.
Args:
tag: Network policy tag name
"""
spec = operations.build_delete_network_policy_tag(tag=tag)
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_delete_network_policy_tag(response)
[docs]
def list_images(
self,
*,
limit: int | None = None,
offset: int | None = None,
tagged: bool = False,
tag: str | None = None,
uuid: str | None = None,
since: str | int | float | datetime | None = None,
until: str | int | float | datetime | None = None,
) -> ImageListResponse:
"""List publicly available images.
Returns a list of all publicly available container images.
Args:
limit: Maximum number of images to return. Must be between 1 and
1000. Default is 100. Invalid values raise 400 error.
offset: Number of images to skip before starting to collect the
result set. Default is 0. Invalid values raise 400 error.
tagged: Example: ``1``.
tag: A valid image tag prefix to filter images by this prefix.
Only images with tags starting with. Implies ``tagged``
parameter. Example: ``ubuntu``.
uuid: Filter images by UUID Example:
``12345678-9abc-baba-deda-0123456789ab``.
since: **Show only results created after the given date/time or
interval.** Accepts a Unix timestamp or interval string.
Interval format: ``600s``/``15m``/``2h``/``3d``/``1w`` means
600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago
respectively). For example: * ``2025-01-01T12:00:00+00:00``
means January 1st, 2025 at 12:00 UTC * ``600s`` means 600
seconds ago * ``15m`` means 15 minutes ago Invalid values
raise 400 error. Example: ``1w``.
until: **Show only results created before the given date/time or
interval.** Accepts a Unix timestamp or interval string.
Interval format: ``600s``/``15m``/``2h``/``3d``/``1w`` means
600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago
respectively). For example: * ``2025-01-01T12:00:00+00:00``
means January 1st, 2025 at 12:00 UTC * ``600s`` means 600
seconds ago * ``15m`` means 15 minutes ago Invalid values
raise 400 error. Example: ``1h``.
"""
spec = operations.build_list_images(
limit=limit,
offset=offset,
tagged=tagged,
tag=tag,
uuid=uuid,
since=since,
until=until,
)
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_list_images(response)
[docs]
def iter_images(
self,
*,
tagged: bool = False,
tag: str | None = None,
uuid: str | None = None,
since: str | int | float | datetime | None = None,
until: str | int | float | datetime | None = None,
page_size: int = 1000,
limit: int | None = None,
) -> Iterator[Image]:
"""Iterate over list_images() results across pages.
Offset pagination happens transparently as items are consumed; breaking
out of the loop stops fetching. Note that offset pagination is not a
snapshot - records created or deleted between page fetches may shift, so
items can repeat or be skipped under concurrent modification.
Args:
tagged: Example: ``1``.
tag: A valid image tag prefix to filter images by this prefix.
Only images with tags starting with. Implies ``tagged``
parameter. Example: ``ubuntu``.
uuid: Filter images by UUID Example:
``12345678-9abc-baba-deda-0123456789ab``.
since: **Show only results created after the given date/time or
interval.** Accepts a Unix timestamp or interval string.
Interval format: ``600s``/``15m``/``2h``/``3d``/``1w`` means
600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago
respectively). For example: * ``2025-01-01T12:00:00+00:00``
means January 1st, 2025 at 12:00 UTC * ``600s`` means 600
seconds ago * ``15m`` means 15 minutes ago Invalid values
raise 400 error. Example: ``1w``.
until: **Show only results created before the given date/time or
interval.** Accepts a Unix timestamp or interval string.
Interval format: ``600s``/``15m``/``2h``/``3d``/``1w`` means
600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago
respectively). For example: * ``2025-01-01T12:00:00+00:00``
means January 1st, 2025 at 12:00 UTC * ``600s`` means 600
seconds ago * ``15m`` means 15 minutes ago Invalid values
raise 400 error. Example: ``1h``.
page_size: how many records to fetch per request (the server
caps a page at 1000)
limit: stop after this many records in total; None iterates
everything
"""
if not 1 <= page_size <= 1000:
raise ValueError("page_size must be between 1 and 1000")
fetched = 0
offset = 0
while True:
size = page_size if limit is None else min(page_size, limit - fetched)
if size <= 0:
return
page = (
self.list_images(
tagged=tagged,
tag=tag,
uuid=uuid,
since=since,
until=until,
limit=size,
offset=offset,
)
).images
if isinstance(page, EllipsisType) or not page:
return
for item in page:
yield item
fetched += 1
if limit is not None and fetched >= limit:
return
if len(page) < size:
return
offset += len(page)
[docs]
def delete_image_tag(self, image_uuid: str, *, tag: str | None = None) -> None:
"""Remove tags from an image.
Removes a tag (or all tags) from an image.
When ``tag`` query parameter is provided, only that specific tag is
removed.
When omitted, all tags are removed from the image.
If any public image has the same tag, tag will start tracking that
public image again.
In all other cases tag will be removed and the image will be accessible
only by its UUID.
Args:
image_uuid: The UUID of the image to untag Example:
``12345678-9abc-baba-deda-0123456789ab``.
tag: The tag to remove. If omitted, all tags are removed from
the image. Example: ``busybox:latest``.
"""
spec = operations.build_delete_image_tag(image_uuid=image_uuid, tag=tag)
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_delete_image_tag(response)
[docs]
def update_image_tag(self, image_uuid: str, tag: str) -> Image:
"""Add a tag to an image.
Adds a tag to an image. Tags are unique per namespace; if the requested
tag is already
assigned to another image, it will be moved to this image.
Assigning a tag that matches a public tag to a public image will freeze
that tag
to the current image - subsequent public updates to the tag will not
affect it.
To make the public tag track the latest public image again, remove your
tag assignment.
When a tag is removed from an image that resides in the public
namespace, the API returns HTTP 200 OK.
response body contains the tag that now points to the public image
(i.e., the image that the tag is automatically re-assigned to).
In other words, un-tagging a public image does not delete the tag; it
simply moves the tag back to the public
image and the caller receives that tag in the successful response.
Args:
image_uuid: The UUID of the image to update Example:
``12345678-9abc-baba-deda-0123456789ab``.
tag: New tag for the image Example: ``busybox:latest``.
"""
spec = operations.build_update_image_tag(image_uuid=image_uuid, tag=tag)
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_update_image_tag(response)
[docs]
def import_image(
self,
registry: ImageImportRegistry,
*,
tag: str | None | EllipsisType = ...,
timeout: int | EllipsisType = ...,
) -> str:
"""Import a container image from a registry.
Imports the OCI image filesystem content of from a specified registry.
Important limitations and behavior:
- Only the image root filesystem (files and directories) is imported.
This is like to the output of
``docker export`` and does not preserve layers metadata.
- Most image configuration and manifest data are ignored. Metadata such
as ``LABEL``,
``ENTRYPOINT``, ``CMD``, ``WORKDIR``, ``EXPOSE`` and other image
configuration directives
will **NOT be imported or applied**.
- ``ENV`` variables defined in the image **are imported** and
automatically applied to the
instance environment when ``shell`` is set to ``true``. When ``shell``
is ``false``, image
environment variables are not inherited and must be passed explicitly
via the ``env`` field.
- The result is a flat rootfs snapshot with preserved environment
variables.
- If the specified tag already exists in the public images, the imported
image will replace it.
To avoid this, you can tag the existing image with a different tag for
use it later.
You also can use image UUIDs it is not changing for imported and
existend image.
- In case the remote image is unchanged and already imported, the
operation will complete and the same UUID
will be returned without re-importing the image.
The request creates an import operation which runs asynchronously.
Args:
tag: Tag to identify the image when listing publicly available
images. If omitted, the image will be private and only
accessible by ID. Example: ``busybox:latest``.
timeout: Maximum time in seconds to wait for the import
operation to complete Example: ``300``.
"""
spec = operations.build_import_image(
registry=registry, tag=tag, timeout=timeout
)
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_import_image(response)
[docs]
def list_files(
self,
*,
limit: int | None = None,
offset: int | None = None,
since: str | int | float | datetime | None = None,
until: str | int | float | datetime | None = None,
) -> FilesListResponse:
"""List uploaded files for the current namespace.
Returns a paginated list of uploaded files for the current namespace.
Args:
limit: Maximum number of files to return
offset: Number of files to skip
since: Filter files created after this time
until: Filter files created before this time
"""
spec = operations.build_list_files(
limit=limit, offset=offset, since=since, until=until
)
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_list_files(response)
[docs]
def iter_files(
self,
*,
since: str | int | float | datetime | None = None,
until: str | int | float | datetime | None = None,
page_size: int = 1000,
limit: int | None = None,
) -> Iterator[File]:
"""Iterate over list_files() results across pages.
Offset pagination happens transparently as items are consumed; breaking
out of the loop stops fetching. Note that offset pagination is not a
snapshot - records created or deleted between page fetches may shift, so
items can repeat or be skipped under concurrent modification.
Args:
since: Filter files created after this time
until: Filter files created before this time
page_size: how many records to fetch per request (the server
caps a page at 1000)
limit: stop after this many records in total; None iterates
everything
"""
if not 1 <= page_size <= 1000:
raise ValueError("page_size must be between 1 and 1000")
fetched = 0
offset = 0
while True:
size = page_size if limit is None else min(page_size, limit - fetched)
if size <= 0:
return
page = (
self.list_files(since=since, until=until, limit=size, offset=offset)
).files
if isinstance(page, EllipsisType) or not page:
return
for item in page:
yield item
fetched += 1
if limit is not None and fetched >= limit:
return
if len(page) < size:
return
offset += len(page)
[docs]
def upload_file(self, content: bytes | IO[bytes]) -> FileResponse:
"""Upload a file to the server. the body must be a file content.
Uploads a file to the server. The body must contain the file content.
Args:
content: Raw file content: bytes or a binary stream.
"""
spec = operations.build_upload_file(content=content)
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_upload_file(response)
[docs]
def get_file(self, sha256: str) -> File:
"""Get file info by SHA256.
Returns file info (uuid, sha256, created_at, updated_at).
Args:
sha256: SHA256 hash of the file (64 hex characters)
"""
spec = operations.build_get_file(sha256=sha256)
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_get_file(response)
[docs]
def check_file_exists(self, sha256: str) -> bool:
"""Check if a file exists for the current namespace.
Returns 200 if the file is uploaded by the current namespace, otherwise
404.
Args:
sha256: SHA256 hash of the file (64 hex characters)
"""
spec = operations.build_check_file_exists(sha256=sha256)
self.log_request(spec)
try:
response = self.call(spec)
except NotFoundError:
return False
self.log_response(spec, response)
return operations.parse_check_file_exists(response)
[docs]
def spawn_instance(
self,
command: str,
image: str,
*,
disposable: bool | EllipsisType = ...,
hostname: str | EllipsisType = ...,
args: list[str] | EllipsisType = ...,
shell: bool | EllipsisType = ...,
env: dict[str, str] | None | EllipsisType = ...,
preserve_env: bool | EllipsisType = ...,
preserve_cwd: bool | EllipsisType = ...,
cwd: str | EllipsisType = ...,
uid: int | EllipsisType = ...,
gid: int | EllipsisType = ...,
resources_limits: InstanceResourcesLimits | EllipsisType = ...,
networking: InstanceNetworking | EllipsisType = ...,
stdin: ClosableStreamRepr | EllipsisType = ...,
timeout: int | EllipsisType = ...,
truncate_output_at: int | EllipsisType = ...,
files: dict[str, FileSpec] | EllipsisType = ...,
) -> InstanceSpawnResponse:
"""Spawn a new container instance.
Creates and runs a new execution instance with the specified
configuration.
Requires a valid ``Authorization`` header.
Common request body rules:
* The request body must contain at least ``command`` and ``image``
fields all other fields can be omitted.
* If the ``command`` field is a shell expression, you must set
``shell`` field to ``true``.
* For specifying the shell binary, you can use ``env`` field to set
``SHELL`` variable.
* When ``shell`` is ``true``, environment variables defined in the
image (via ``ENV`` directives) are
automatically inherited. When ``shell`` is ``false``, image
environment variables are not inherited
and must be passed explicitly via the ``env`` field.
Args:
command: The command to execute. In case if ``shell`` is set to
``true``, this MUST contain shell expression. For example
``echo hello world`` or ``ls -l /app``. If ``shell`` is set
to ``false``, this must be a relative or absolute path to
the executable inside the image rootfs. For example:
``/bin/app`` or ``/usr/bin/find``. Do not forget pass
necessary ``PATH`` variable to env field, by default
``PATH`` is set to
``/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin``.
Example: ``/bin/app``.
disposable: Creates a disposable execution environment no any
state will be saved.
hostname: Hostname to set when execution. Example:
``container-name``.
args: Arguments to pass to the command if shell is set to false.
Example: ``["arg1","arg2"]``.
shell: Whether to run the command through a shell. If ``true``,
the command must be a shell expression and all values from
args will be ignored. If ``false``, the command field must
be a path to an executable and args will be used. When
``true``, environment variables from the image are
automatically inherited. When ``false``, they are not - use
the ``env`` field to pass them explicitly.
env: Environment variables to set in the container. These are
merged with image-defined variables when ``shell`` is
``true``. When ``shell`` is ``false``, only variables
specified here are available - image-defined variables are
not inherited. Example:
``{"KEY1":"value1","KEY2":"value2"}``.
preserve_env: Preserve environment variables in resulting image
after execution. When ``true``, the image's existing
environment variables from ``metadata/env`` are merged with
user-provided ``env`` values (user values take priority on
conflicts), and the combined result is written back to
``metadata/env`` after command execution. Setting a variable
to an empty string or ``null`` removes it from the preserved
environment.
preserve_cwd: Save the resolved initial working directory as the
default in the resulting image. An empty or omitted ``cwd``
resolves to the image's current workdir, or ``/`` if none
exists. The metadata file is opened for writing only when
its contents differ from the new value. Directory changes
made by the command do not change the saved value. Requires
``disposable: false`` to retain the metadata in a resulting
image.
cwd: Path to the working directory, must be absolute or a
special value the empty string. It means the default working
directory of the image or server default will be used. If
field is omitted it will be set to the empty string. The
directory will be created automatically if it does not
exist. Example: ``/app``.
uid: User ID to run the process as. Example: ``0``.
gid: Group ID to run the process as. Example: ``0``.
timeout: Maximum execution time in seconds Example: ``60``.
truncate_output_at: Maximum number of bytes to keep per stream
(stdout, stderr, and stdin) in the subprocess event log.
Does not affect stdin delivery to the child, which always
receives the complete stream regardless of this cap. Default
is ``1048576`` (1 MiB). The maximum value is ``10485760``
(10 MiB). Example: ``65535``.
files: Map of absolute file paths to file metadata Example:
``{"/root/hello.txt":{"uuid":"a9165a5d-5c86-4bd8-8ee4-ae46c...``.
"""
spec = operations.build_spawn_instance(
command=command,
image=image,
disposable=disposable,
hostname=hostname,
args=args,
shell=shell,
env=env,
preserve_env=preserve_env,
preserve_cwd=preserve_cwd,
cwd=cwd,
uid=uid,
gid=gid,
resources_limits=resources_limits,
networking=networking,
stdin=stdin,
timeout=timeout,
truncate_output_at=truncate_output_at,
files=files,
)
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_spawn_instance(response)
[docs]
def list_operations(
self,
*,
limit: int | None = None,
offset: int | None = None,
status: OperationStatus | str | None = None,
kind: Literal["image_import", "instance"] | None = None,
since: str | int | float | datetime | None = None,
until: str | int | float | datetime | None = None,
) -> list[OperationSummary]:
"""List operations.
Returns a list of running and completed operations
Args:
limit: Maximum number of operations to return. Must be between 1
and 1000. Default is 100. Invalid values raise 400 error.
offset: Number of operations to skip before starting to collect
the result set. Default is 0. Invalid values raise 400
error.
status: Filter operations by their state
kind: Filter operations by their kind
since: **Show only results created after the given date/time or
interval.** Accepts a Unix timestamp or interval string.
Interval format: ``600s``/``15m``/``2h``/``3d``/``1w`` means
600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago
respectively). For example: * ``2025-01-01T12:00:00+00:00``
means January 1st, 2025 at 12:00 UTC * ``600s`` means 600
seconds ago * ``15m`` means 15 minutes ago Invalid values
raise 400 error. Example: ``1w``.
until: **Show only results created before the given date/time or
interval.** Accepts a Unix timestamp or interval string.
Interval format: ``600s``/``15m``/``2h``/``3d``/``1w`` means
600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago
respectively). For example: * ``2025-01-01T12:00:00+00:00``
means January 1st, 2025 at 12:00 UTC * ``600s`` means 600
seconds ago * ``15m`` means 15 minutes ago Invalid values
raise 400 error. Example: ``1h``.
"""
spec = operations.build_list_operations(
limit=limit,
offset=offset,
status=status,
kind=kind,
since=since,
until=until,
)
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_list_operations(response)
[docs]
def iter_operations(
self,
*,
status: OperationStatus | str | None = None,
kind: Literal["image_import", "instance"] | None = None,
since: str | int | float | datetime | None = None,
until: str | int | float | datetime | None = None,
page_size: int = 1000,
limit: int | None = None,
) -> Iterator[OperationSummary]:
"""Iterate over list_operations() results across pages.
Offset pagination happens transparently as items are consumed; breaking
out of the loop stops fetching. Note that offset pagination is not a
snapshot - records created or deleted between page fetches may shift, so
items can repeat or be skipped under concurrent modification.
Args:
status: Filter operations by their state
kind: Filter operations by their kind
since: **Show only results created after the given date/time or
interval.** Accepts a Unix timestamp or interval string.
Interval format: ``600s``/``15m``/``2h``/``3d``/``1w`` means
600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago
respectively). For example: * ``2025-01-01T12:00:00+00:00``
means January 1st, 2025 at 12:00 UTC * ``600s`` means 600
seconds ago * ``15m`` means 15 minutes ago Invalid values
raise 400 error. Example: ``1w``.
until: **Show only results created before the given date/time or
interval.** Accepts a Unix timestamp or interval string.
Interval format: ``600s``/``15m``/``2h``/``3d``/``1w`` means
600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago
respectively). For example: * ``2025-01-01T12:00:00+00:00``
means January 1st, 2025 at 12:00 UTC * ``600s`` means 600
seconds ago * ``15m`` means 15 minutes ago Invalid values
raise 400 error. Example: ``1h``.
page_size: how many records to fetch per request (the server
caps a page at 1000)
limit: stop after this many records in total; None iterates
everything
"""
if not 1 <= page_size <= 1000:
raise ValueError("page_size must be between 1 and 1000")
fetched = 0
offset = 0
while True:
size = page_size if limit is None else min(page_size, limit - fetched)
if size <= 0:
return
page = self.list_operations(
status=status,
kind=kind,
since=since,
until=until,
limit=size,
offset=offset,
)
if isinstance(page, EllipsisType) or not page:
return
for item in page:
yield item
fetched += 1
if limit is not None and fetched >= limit:
return
if len(page) < size:
return
offset += len(page)
[docs]
def get_operation_status(
self, operation_id: str, *, inflight: bool = False
) -> OperationResponse:
"""Get an operation status.
Returns the status of an operation.
For an EXECUTING INSTANCE operation, pass ``?inflight=1`` to
also synthesize the partial ``result.stdout`` / ``result.stderr``
from the live event log. Off by default — each fetch with
``inflight`` triggers an extra subscribe RPC to the guest and
drains its current events.gz, which is wasted work for
clients that only poll for status transitions.
Args:
operation_id: The ID of the operation Example:
``12345678-9abc-baba-deda-0123456789ab``.
inflight: HTTP-flag boolean. Present without a value
(``?inflight``) and ``?inflight=1`` both enable;
``?inflight=0`` and absence disable. When enabled and the
operation is EXECUTING INSTANCE, partial stdout/stderr is
synthesized from the live event log and attached under
``result``.
"""
spec = operations.build_get_operation_status(
operation_id=operation_id, inflight=inflight
)
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_get_operation_status(response)
[docs]
def cancel_operation(self, operation_id: str) -> None:
"""Cancel an operation.
Cancels an operation
Args:
operation_id: The ID of the import operation to cancel Example:
``12345678-9abc-baba-deda-0123456789ab``.
"""
spec = operations.build_cancel_operation(operation_id=operation_id)
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_cancel_operation(response)
[docs]
def iter_operation_events(
self,
operation_id: str,
*,
follow: bool = False,
spid: int | None = None,
since: int | None = None,
last_event_id: int | None = None,
deadline: float | None = None,
idle_timeout: float = 0.0,
) -> Iterator[OperationEvent]:
"""Stream the operation event log via Server-Sent Events.
Always returns ``text/event-stream`` (SSE) on success. The body
is a sequence of three kinds of lines (per RFC W3C SSE), each
terminated by ``\\n\\n``:
.. rubric:: Frame shapes
**Normal event frame** — one ``OperationEvent`` JSON object in
``data:``, dispatchable via ``event:``:
::
id: <integer event.id>
event: <OperationEventType, e.g. stdout|stderr|spawn|exit>
data: {"id": N, "ts": "...", "spid": ..., "type": "...", "data": {...}}
``event:`` always matches ``data.type``. See ``OperationEvent`` and
``OperationEventType`` for the per-type payload shape. Native
``EventSource`` dispatches each frame to the matching
``addEventListener("<type>", ...)`` handler.
**Server-side error frame** — surfaces handler exceptions to
the connected client without tearing the TCP connection down
mid-stream. Sent right before the server closes the response:
::
: stream ended with error, retry since last event id
event: sse_error
data: <one-line exception message>
The leading SSE comment line lets pure-EventSource clients see
the intent ("retry from Last-Event-Id"); the ``sse_error`` frame
carries the error text for logging. Clients should treat this
as a non-clean close and reconnect with the standard SSE
``Last-Event-Id`` semantics (see Resuming).
**Keepalive comment** — periodic ``: keepalive\\n\\n`` lines
emitted while the stream is idle. They keep upstream
``proxy_read_timeout`` / TCP idle timers fresh and have no
application meaning. Spec-compliant; EventSource and any SSE
parser must ignore comment lines (those beginning with ``:``).
.. rubric:: ``follow`` semantics
The ``follow`` parameter controls only whether the stream stays
open after the last currently-known event:
* ``follow=0`` (default) — the server emits everything
currently available and closes the connection.
* ``follow=1`` — same start; if the operation is still
running the server keeps the connection open and forwards
new events as they appear. For terminal operations
``follow=1`` is a no-op: there's nothing more to subscribe
to, so the connection closes after the last event just
like ``follow=0``.
Optional filters:
* ``?spid=N`` — only events whose ``spid`` (Spawned Process ID,
the routing identity in ``OperationEvent``) matches.
* ``?since=N`` — only events with ``id > N``.
``follow=1`` requires ``SPAWN`` or ``SPAWN_DISPOSABLE`` on top of
the baseline ``LIST`` — a long-lived subscription reserves
per-operation server state. ``follow=0`` is read-only and
stays under ``LIST``.
.. rubric:: Resuming after a drop
Every normal frame carries ``id:`` — the canonical event id.
On reconnect send the last successfully received id in the
standard ``Last-Event-Id`` request header (or ``?since=N`` on
manual GETs); the server resumes from that point.
.. rubric:: Error handling
.. list-table::
:header-rows: 1
* - Status
- Meaning
- Client action
* - 200
- Stream open
- Read frames; reconnect with Last-Event-Id if the stream closes
before reaching a terminal event
* - 400
- Malformed query/header (non-integer param)
- Fix request
* - 401
- Missing/invalid auth
- Refresh credentials
* - 403
- Auth lacks LIST (or SPAWN for ``follow=1``)
- Use a token with the right scope
* - 404
- Operation not in this namespace
- Wrong UUID
* - 410
- Stream is over but the terminal artifact isn't ready yet
- Retry after ``Retry-After``
* - 425
- Not yet ready (operation is still being prepared)
- Retry after ``Retry-After``
* - 502
- Upstream returned an error opening the stream
- Retry; if persistent, escalate
* - 504
- Upstream took too long to respond
- Retry
A ``200`` followed by an ``event: sse_error`` frame and immediate
close is the in-band equivalent of "the stream broke after we
already committed to a 200" — handle it the same way as 410:
wait briefly, reconnect with ``Last-Event-Id``.
See ``OperationEvent`` for the per-event shape.
Args:
operation_id: The ID of the operation Example:
``12345678-9abc-baba-deda-0123456789ab``.
follow: HTTP-flag boolean. Present without a value (``?follow``)
and ``?follow=1`` both enable; ``?follow=0`` and absence
disable. When enabled, the SSE stream stays open after the
currently-known events have been sent — for a running
operation new events are forwarded as they appear; for a
terminal operation it has no effect.
spid: Only emit events whose ``spid`` field matches. Filter is
applied server-side regardless of whether the operation is
still running or already terminal.
since: Only emit events with ``id > since`` (event IDs are
monotonically increasing). Overridden by the
``Last-Event-Id`` header when present.
last_event_id: Standard SSE resume header sent automatically by
``EventSource`` on reconnect. Treated as ``?since=N``; takes
precedence over the query param.
deadline: absolute monotonic deadline. Checked whenever
iteration resumes; caller code between events is not
interrupted.
idle_timeout: seconds without incoming data before a transport
timeout; 0 disables it
"""
spec = operations.build_iter_operation_events(
operation_id=operation_id,
follow=follow,
spid=spid,
since=since,
last_event_id=last_event_id,
)
if not math.isfinite(idle_timeout) or idle_timeout < 0:
raise ValueError("idle_timeout must be finite and non-negative")
spec.read_timeout = idle_timeout or None
spec.deadline = deadline
if deadline is not None:
spec.read_timeout = min(
spec.read_timeout or math.inf, max(0.0, deadline - time.monotonic())
)
self.log_request(spec)
parser = SSEParser()
last_seen = last_event_id
with closing_iterator(self.stream(spec)) as source:
for chunk in source:
if deadline is not None and time.monotonic() >= deadline:
raise TimeoutError("iter_operation_events exceeded its deadline")
for frame in parser.feed(chunk):
if frame.id is not None:
last_seen = frame.id
event = decode_event_frame(frame, last_seen)
if event is None:
continue
self.log.debug("sse event: %r", event)
yield event
if deadline is not None and time.monotonic() >= deadline:
raise TimeoutError(
"iter_operation_events exceeded its deadline"
)
[docs]
def operation_subprocess_create(
self,
operation_id: str,
command: str,
*,
resources_limits: ProcessResourcesLimits | EllipsisType = ...,
args: list[str] | EllipsisType = ...,
shell: bool | EllipsisType = ...,
env: dict[str, str] | None | EllipsisType = ...,
cwd: str | EllipsisType = ...,
uid: int | EllipsisType = ...,
gid: int | EllipsisType = ...,
stdin: ClosableStreamRepr | EllipsisType = ...,
truncate_output_at: int | EllipsisType = ...,
) -> int:
"""Spawn an additional subprocess inside a running instance.
Starts a new process inside the VM that already hosts the named
operation. Distinct from ``POST /instances``, which spins up a
VM: this endpoint requires a running operation (EXECUTING or
ASSIGNED) and reuses the existing VM.
The body is an ``ExecSpec`` — process-execution fields only.
VM-level concerns (``image``, ``hostname``,
``files``, ``timeout``, ``disposable``, ``preserve_env``) are not
accepted here; they were set when the parent operation was
created.
``resources_limits.cpu`` and ``resources_limits.memory_mib`` use the
same names and units as operation creation. Each omitted or null
subprocess limit inherits the corresponding operation limit.
Values above the operation limit return 400. Limits apply at
launch: memory_mib sets RLIMIT_AS for each process and memory.max
for the entire process tree. They cannot be changed through this
API. Guest root can modify limits; these limits do not
provide security isolation between processes in one VM.
The required permission follows the parent instance:
``SPAWN_DISPOSABLE`` when it was spawned with ``disposable=true``,
``SPAWN`` otherwise.
On success the worker assigns a fresh ``spid`` (≥2; ``spid=1`` is
the main process spawned from ``metadata``) and the response
carries it in the body plus a ``Location`` header pointing at
``GET /operations/{operationId}/subprocesses/{spid}`` — the
subprocess result reconstructed from its events.
Args:
operation_id: The ID of the operation Example:
``12345678-9abc-baba-deda-0123456789ab``.
command: The command to execute. Same semantics as in
``InstanceSpawnRequest.command`` — when ``shell=true`` it is
a shell expression, otherwise a path to an executable.
Example: ``/bin/app``.
args: Arguments to pass to the command if shell is set to false.
Example: ``["arg1","arg2"]``.
shell: Run command through a shell expression (args must be
empty).
env: Environment variables to set in the child process.
cwd: Working directory; empty string means image / server
default.
uid: User ID to run the process as.
gid: Group ID to run the process as.
stdin: Bytes fed to the child's stdin — honored for both the
main process and exec'd subprocesses. With ``close=false``
the pipe stays open and more data can be written via
``POST /operations/{operationId}/subprocesses/{spid}/stdin``.
truncate_output_at: Maximum number of bytes to keep per stream
(stdout, stderr, and stdin) in the subprocess event log.
Does not affect delivery to the child — stdin is always
delivered in full regardless of this cap. Defaults to 1 MiB;
capped at 10 MiB. Example: ``65535``.
"""
spec = operations.build_operation_subprocess_create(
operation_id=operation_id,
command=command,
resources_limits=resources_limits,
args=args,
shell=shell,
env=env,
cwd=cwd,
uid=uid,
gid=gid,
stdin=stdin,
truncate_output_at=truncate_output_at,
)
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_operation_subprocess_create(response)
[docs]
def operation_subprocess(self, operation_id: str, spid: int) -> InstanceResult:
"""Result of one subprocess, reconstructed from its events.
Returns an ``InstanceResult`` for ``spid`` — the same shape as the
parent operation's ``metadata.result`` — folded from the
subprocess's event log (spawn / stdout / stderr / exit).
Works for running and terminal operations alike. While the
process is still running, ``state.exit_code`` and ``state.signal``
are ``-1`` (unknown) and ``resources`` holds sentinel defaults;
once the exit event lands they carry the real values.
``stdout`` / ``stderr`` are consolidated and capped at the spec's
``truncate_output_at``. The raw event stream stays available at
``GET /operations/{operationId}/events?spid={spid}``.
Args:
operation_id: The ID of the operation Example:
``12345678-9abc-baba-deda-0123456789ab``.
spid: Spawn id (1 = main process; ≥2 = exec'd children).
"""
spec = operations.build_operation_subprocess(
operation_id=operation_id, spid=spid
)
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_operation_subprocess(response)
[docs]
def operation_subprocess_kill(
self, operation_id: str, spid: int, *, signal: str | None = None
) -> None:
"""Kill one subprocess.
Sends a signal to the process group of ``spid`` inside the
running instance. Without the ``signal`` parameter the group
gets SIGKILL. Termination is observable, not returned: the
``exit`` event lands in the event log and
``GET /operations/{operationId}/subprocesses/{spid}`` reports
the terminal ``state`` (``signal`` set, ``exit_code`` -1 when killed).
Killing ``spid=1`` (the main process) effectively ends the
operation, like letting the command fail.
Args:
operation_id: The ID of the operation Example:
``12345678-9abc-baba-deda-0123456789ab``.
spid: Spawn id (1 = main process; ≥2 = exec'd children).
signal: Signal to send instead of SIGKILL — a number (``15``) or
a name with or without the SIG prefix (``TERM``,
``SIGTERM``). Example: ``SIGTERM``.
"""
spec = operations.build_operation_subprocess_kill(
operation_id=operation_id, spid=spid, signal=signal
)
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_operation_subprocess_kill(response)
[docs]
def operation_subprocess_stdin(
self,
operation_id: str,
spid: int,
value: str,
*,
encoding: Literal["ascii", "base64"] | EllipsisType = ...,
close: bool | EllipsisType = ...,
) -> None:
"""Write to a subprocess's stdin and/or close it.
Writes a chunk to the stdin of a live process inside the
running instance — ``spid=1`` targets the main process, ``≥2`` the
exec'd children. Requires the process to have been started
with ``stdin.close=false``; otherwise its pipe is already at EOF
and the call returns 409.
``close=true`` (the default) signals EOF after writing ``value``;
an empty ``value`` with ``close=true`` just closes the pipe. A
client that serializes its own requests gets ordered writes;
concurrent requests to the same spid are safe but their order
is unspecified.
A 504 means the guest write timed out mid-call — the chunk may
or may not have been delivered (e.g. the process stopped
reading and the pipe is full), so blind retries can duplicate
data.
Args:
operation_id: The ID of the operation Example:
``12345678-9abc-baba-deda-0123456789ab``.
spid: Spawn id (1 = main process; ≥2 = exec'd children).
value: Content to write to stdin (may be empty for a close-only
request) Example: ``aGVsbG8K``.
encoding: Encoding of the content
close: ``true`` (default) closes stdin (EOF) after writing
``value`` — the pre-existing one-shot behavior. ``false``
keeps the pipe open so more data can be sent later via
``POST /operations/{operationId}/subprocesses/{spid}/stdin``.
"""
spec = operations.build_operation_subprocess_stdin(
operation_id=operation_id,
spid=spid,
value=value,
encoding=encoding,
close=close,
)
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_operation_subprocess_stdin(response)
[docs]
def apply_instance_file(
self,
operation_uuid: str,
file_uuid: str,
path: str,
*,
unpack: bool | EllipsisType = ...,
replace: bool | EllipsisType = ...,
merge: bool | EllipsisType = ...,
) -> None:
"""Apply an uploaded file to a running instance.
Reads a file previously uploaded through POST /files and writes it to a
running INSTANCE operation, including disposable instances. Requires
LIST
and the permission used to start the instance. Both the operation and
the
uploaded file must belong to the request namespace. Expired files are
unavailable.
The assigned worker streams the stored object to the guest through RPC.
Init records request metadata in ``inspect`` events and the terminal
publication result in ``file_upload``, including ``file_uuid`` and byte
count.
File contents do not enter operation events.
With unpack omitted or false, path is the full destination filename.
Missing parent directories are created. The file is published atomically
after
transfer and SHA256 verification. The new file has mode 0644 and is
owned by the guest runtime user. With replace true, an existing leaf
symlink is replaced.
Directories and special files are not regular file destinations.
With unpack true, path is the destination directory. Supports tar,
tar.gz and tar.bz2; compression is detected from the stored bytes. Xz is
unsupported and rejected before subsequent chunks are sent. Without
unpack,
compressed archives are copied unchanged. Content-Type describes this
JSON
request and never controls extraction.
Extraction accepts regular files, directories, symlinks and hardlinks to
regular files already extracted in the staging tree. Parent symlinks
inside that tree are
not followed. Absolute entry names and entries containing '..' are
rejected.
procfs, sysfs, devices, FIFOs and sockets are unsupported. New
directories
have mode 0755; regular files retain tar permission bits (0777).
Ownership
and timestamps are not restored. Other entries fail explicitly.
With replace omitted or false, any existing destination returns 409,
including
a symlink or empty directory. This condition is checked again atomically
at publication.
replace true permits an existing destination. With merge omitted or
false,
directory replacement removes the entire old tree without merging
contents.
Archives are extracted into a temporary sibling directory. The
destination
remains unchanged until the complete stream and SHA256 have been
verified.
Without merge, publication uses an atomic rename or exchange, then
removes the old tree.
Root and mount-point replacement are unavailable. Existing open
descriptors
can still refer to old inodes; concurrent workload access is not a
snapshot.
merge true requires both unpack true and replace true. After complete
staging
and verification, it combines directories and atomically replaces
individual
files and symlinks. Existing entries absent from the archive remain.
Destination
directory symlinks are not followed; directory/file conflicts fail
explicitly.
Same-filesystem hardlinks are retained. Crossing a destination mount
requires
copying file bytes and does not preserve hardlinks across filesystems.
Merge is not atomic for the whole tree: errors, cancellation or timeout
after
application starts can leave completed changes. These changes are not
rolled back.
Returns 204 only after completion. Transfers have a 300-second deadline
and bounded buffers and handles. Disconnect or VM exit cancels the
transfer.
A lost response can leave an uncertain outcome; requests are not
replayed
automatically. This endpoint does not write to a completed result image.
A transfer timeout does not stop the instance. Before publication or
merge starts, cancellation
preserves the old destination and removes the temporary file or
extraction tree.
A timeout while awaiting the final response can occur after publication;
it does not prove that no changes were made. An old-tree cleanup failure
is
reported as an error after publication; it does not roll back the new
tree.
The uploaded source object retains its normal lifetime. Automatically
created
parent directories have mode 0755 and can remain after errors.
The primary command's timeout follows normal instance finalization:
ordinary
instances persist their filesystem, including successfully published
uploads;
disposable instances do not. Instance shutdown waits for pending upload
cleanup.
A timeout or crash of the execution environment can bypass this cleanup
and does not produce
a successfully persisted result image through normal finalization.
Args:
operation_uuid: Example:
``12345678-9abc-baba-deda-0123456789ab``.
path: Absolute guest filename, or directory when unpack is true.
Missing parents are created.
unpack: Extract tar, tar.gz or tar.bz2 instead of copying the
stored bytes.
replace: Permit an existing destination. Without merge,
directories are replaced in full.
merge: Merge verified archive contents. Requires unpack and
replace. Can leave partial changes.
"""
spec = operations.build_apply_instance_file(
operation_uuid=operation_uuid,
file_uuid=file_uuid,
path=path,
unpack=unpack,
replace=replace,
merge=merge,
)
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_apply_instance_file(response)
[docs]
def inspect_instance_download(self, operation_uuid: str, path: str) -> bytes:
"""Download a file from a running instance.
Reads through guest RPC without recording file contents in operation
events.
Requires LIST and the permission used to start this instance (SPAWN or
SPAWN_DISPOSABLE). Reads include tmpfs and additional mounts visible to
the guest runtime. procfs, sysfs, devices, sockets, and FIFOs are
unavailable.
Reads do not form a snapshot. The opened inode and initial size are
used;
later growth is excluded. Truncation or VM exit interrupts the response.
A transfer has a 300-second deadline. No result-image fallback is
performed.
Args:
operation_uuid: The UUID of the running instance to inspect
Example: ``12345678-9abc-baba-deda-0123456789ab``.
path: The path of the file to inspect inside the running
instance, e.g. ``/etc/hosts``
"""
spec = operations.build_inspect_instance_download(
operation_uuid=operation_uuid, path=path
)
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_inspect_instance_download(response)
[docs]
def inspect_instance_download_stream(
self, operation_uuid: str, path: str
) -> Iterator[bytes]:
"""Streaming variant of ``inspect_instance_download()``.
Reads through guest RPC without recording file contents in operation
events.
Requires LIST and the permission used to start this instance (SPAWN or
SPAWN_DISPOSABLE). Reads include tmpfs and additional mounts visible to
the guest runtime. procfs, sysfs, devices, sockets, and FIFOs are
unavailable.
Reads do not form a snapshot. The opened inode and initial size are
used;
later growth is excluded. Truncation or VM exit interrupts the response.
A transfer has a 300-second deadline. No result-image fallback is
performed.
Args:
operation_uuid: The UUID of the running instance to inspect
Example: ``12345678-9abc-baba-deda-0123456789ab``.
path: The path of the file to inspect inside the running
instance, e.g. ``/etc/hosts``
"""
spec = operations.build_inspect_instance_download(
operation_uuid=operation_uuid, path=path
)
self.log_request(spec)
for chunk in self.stream(spec):
self.log.debug("stream chunk: %d bytes", len(chunk))
yield chunk
[docs]
def check_instance_file(self, operation_uuid: str, path: str) -> bool:
"""Check if a file exists in running instance.
Checks if a file exists in the specified running instance without
returning the file content
Args:
operation_uuid: The UUID of the running instance to inspect
Example: ``12345678-9abc-baba-deda-0123456789ab``.
path: The path of the file to check inside the running instance,
e.g. ``/etc/hosts``
"""
spec = operations.build_check_instance_file(
operation_uuid=operation_uuid, path=path
)
self.log_request(spec)
try:
response = self.call(spec)
except NotFoundError:
return False
self.log_response(spec, response)
return operations.parse_check_instance_file(response)
[docs]
def inspect_instance_list(self, operation_uuid: str, path: str) -> DirectoryList:
"""List files in running instance.
Lists guest files without recording contents in operation events.
Requires LIST and the permission used to start this instance.
Reads do not form a snapshot. A directory can contain at most 10000
entries.
procfs and sysfs cannot be listed.
Args:
operation_uuid: The UUID of the running instance to inspect
Example: ``12345678-9abc-baba-deda-0123456789ab``.
path: The path of the directory to inspect inside the running
instance Example: ``/etc``.
"""
spec = operations.build_inspect_instance_list(
operation_uuid=operation_uuid, path=path
)
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_inspect_instance_list(response)
[docs]
def inspect_instance_archive(
self, operation_uuid: str, path: str, *, compressed: bool = False
) -> Iterator[bytes]:
"""Download a file or a directory from running instance as tar archive.
Streams the specified path inside the running instance root filesystem
as a POSIX PAX
tar archive. A directory becomes the archive root; a regular file
becomes
a single-entry archive. The response is chunked; total size is not known
upfront. Served as an attachment, ``filename`` is the path with ``/``
replaced
by ``_`` plus ``.tar`` (e.g. ``/bin/true`` -> ``bin_true.tar``).
Requires LIST and the permission used to start this instance.
Contents do not enter operation events. Reads do not form a snapshot.
Traversal skips procfs and sysfs and preserves descendant symlinks.
File changes or VM exit can interrupt the stream. Transfers have a
300-second deadline.
Args:
operation_uuid: The UUID of the running instance to inspect
Example: ``12345678-9abc-baba-deda-0123456789ab``.
path: The path of the file or directory to archive inside the
running instance, e.g. ``/etc``
compressed: disable transparent decompression: the body is
yielded exactly as served - a tar.gz stream when the server
compresses the response, a plain tar otherwise.
"""
spec = operations.build_inspect_instance_archive(
operation_uuid=operation_uuid, path=path
)
self.log_request(spec)
source = self.stream(spec, auto_decompress=not compressed)
for chunk in source:
self.log.debug("stream chunk: %d bytes", len(chunk))
yield chunk
[docs]
def check_instance_archive(self, operation_uuid: str, path: str) -> bool:
"""Check if a path can be archived from running instance.
Checks if a file or a directory exists in the specified running instance
without streaming the archive
Args:
operation_uuid: The UUID of the running instance to inspect
Example: ``12345678-9abc-baba-deda-0123456789ab``.
path: The path of the file or directory to check inside the
running instance, e.g. ``/etc``
"""
spec = operations.build_check_instance_archive(
operation_uuid=operation_uuid, path=path
)
self.log_request(spec)
try:
response = self.call(spec)
except NotFoundError:
return False
self.log_response(spec, response)
return operations.parse_check_instance_archive(response)
[docs]
def inspect_find_image_by_tag(self, tag: str) -> str:
"""Find image by tag.
Redirects to the image inspection endpoint for the specified tag
Args:
tag: The tag of the image to inspect
"""
spec = operations.build_inspect_find_image_by_tag(tag=tag)
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_inspect_find_image_by_tag(response)
[docs]
def inspect_image(self, image_uuid: str) -> Image:
"""Inspect an image.
Returns image metadata
Args:
image_uuid: The UUID of the image to inspect Example:
``12345678-9abc-baba-deda-0123456789ab``.
"""
spec = operations.build_inspect_image(image_uuid=image_uuid)
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_inspect_image(response)
[docs]
def inspect_image_download(self, image_uuid: str, path: str) -> bytes:
"""Download a file from image.
Returns file content
Args:
image_uuid: The UUID of the image to inspect Example:
``12345678-9abc-baba-deda-0123456789ab``.
path: The path of the file to inspect inside the image, e.g.
``/etc/hosts``
"""
spec = operations.build_inspect_image_download(image_uuid=image_uuid, path=path)
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_inspect_image_download(response)
[docs]
def inspect_image_download_stream(
self, image_uuid: str, path: str
) -> Iterator[bytes]:
"""Streaming variant of ``inspect_image_download()``.
Returns file content
Args:
image_uuid: The UUID of the image to inspect Example:
``12345678-9abc-baba-deda-0123456789ab``.
path: The path of the file to inspect inside the image, e.g.
``/etc/hosts``
"""
spec = operations.build_inspect_image_download(image_uuid=image_uuid, path=path)
self.log_request(spec)
for chunk in self.stream(spec):
self.log.debug("stream chunk: %d bytes", len(chunk))
yield chunk
[docs]
def check_image_file(self, image_uuid: str, path: str) -> bool:
"""Check if a file exists in image.
Checks if a file exists in the specified image without returning the
file content
Args:
image_uuid: The UUID of the image to inspect Example:
``12345678-9abc-baba-deda-0123456789ab``.
path: The path of the file to check inside the image, e.g.
``/etc/hosts``
"""
spec = operations.build_check_image_file(image_uuid=image_uuid, path=path)
self.log_request(spec)
try:
response = self.call(spec)
except NotFoundError:
return False
self.log_response(spec, response)
return operations.parse_check_image_file(response)
[docs]
def inspect_image_archive(
self, image_uuid: str, path: str, *, compressed: bool = False
) -> Iterator[bytes]:
"""Download a file or a directory from image as tar archive.
Streams the specified path inside the image root filesystem as a POSIX
PAX
tar archive. A directory becomes the archive root; a regular file
becomes
a single-entry archive. The response is chunked; total size is not known
upfront. Served as an attachment, ``filename`` is the path with ``/``
replaced
by ``_`` plus ``.tar`` (e.g. ``/bin/true`` -> ``bin_true.tar``).
Args:
image_uuid: The UUID of the image to inspect Example:
``12345678-9abc-baba-deda-0123456789ab``.
path: The path of the file or directory to archive inside the
image, e.g. ``/etc``
compressed: disable transparent decompression: the body is
yielded exactly as served - a tar.gz stream when the server
compresses the response, a plain tar otherwise.
"""
spec = operations.build_inspect_image_archive(image_uuid=image_uuid, path=path)
self.log_request(spec)
source = self.stream(spec, auto_decompress=not compressed)
for chunk in source:
self.log.debug("stream chunk: %d bytes", len(chunk))
yield chunk
[docs]
def check_image_archive(self, image_uuid: str, path: str) -> bool:
"""Check if a path can be archived from image.
Checks if a file or a directory exists in the specified image without
streaming the archive
Args:
image_uuid: The UUID of the image to inspect Example:
``12345678-9abc-baba-deda-0123456789ab``.
path: The path of the file or directory to check inside the
image, e.g. ``/etc``
"""
spec = operations.build_check_image_archive(image_uuid=image_uuid, path=path)
self.log_request(spec)
try:
response = self.call(spec)
except NotFoundError:
return False
self.log_response(spec, response)
return operations.parse_check_image_archive(response)
[docs]
def inspect_image_list(self, image_uuid: str, path: str) -> DirectoryList:
"""List files in image.
Returns files list
Args:
image_uuid: The UUID of the image to inspect Example:
``12345678-9abc-baba-deda-0123456789ab``.
path: The path of the directory to inspect inside the image
Example: ``/etc``.
"""
spec = operations.build_inspect_image_list(image_uuid=image_uuid, path=path)
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_inspect_image_list(response)
[docs]
def inspect_instance_grep(
self,
operation_uuid: str,
pattern: str | Sequence[str],
*,
path: str | Sequence[str] | None = None,
glob: str | Sequence[str] | None = None,
max_count: int | None = None,
max_total: int | None = None,
case: Literal["sensitive", "insensitive", "smart"] | None = None,
before: int | None = None,
after: int | None = None,
) -> GrepResult:
"""Search file contents in running instance.
Regex content search inside the running instance's root filesystem,
through guest RPC.
A Go converter translates supported Rust regex syntax to Go regexp.
Symlinks are never followed during traversal, hidden files are searched,
``.ignore`` and ``.gitignore`` rules within each search root are
respected.
A NUL byte in the first 64 KiB causes a file to be skipped; a later NUL
ends that file's search. Go regexp uses linear-time matching.
The classes \\w/\\W, \\d/\\D, and \\s/\\S use Unicode semantics.
Unicode properties and case folding are pinned to Unicode 16.0.0,
matching the image engine.
Scoped flags, nested class set operations, and bounded expansion of
large repetitions are supported.
Expanded patterns share a 1 MiB limit per request. Unsupported syntax
returns 400 with a pattern
index and byte offset. Unicode \\b/\\B, CRLF mode, non-ASCII byte mode,
and \\Q…\\E are rejected.
Use (?-u:\\b) for an ASCII word boundary. Smart case examines parsed
literals.
Results are a flat, file-ordered list of lines. ``before``/``after``
request extra
``type: context`` lines around each ``type: match`` line, mirroring
ripgrep's
--json message type field.
``path`` may be repeated to search multiple roots in one call, the same
way
``pattern``/``glob`` already can; results are concatenated in the given
order
and share the ``max_total`` budget across all of them.
Results never enter operation events. Reads are live and do not form a
snapshot.
procfs, sysfs, devices, sockets, and FIFOs are not searched.
Requires LIST and the permission used to start this instance.
Searches have a 10-second budget per root and permit two concurrent
searches per instance. Reaching the time, depth, or result limit sets
``truncated``. Context lines count towards ``max_total``. Display text
is
limited to 4096 bytes per line; matching can continue beyond this
window.
Args:
operation_uuid: The UUID of the running instance to inspect
Example: ``12345678-9abc-baba-deda-0123456789ab``.
pattern: Regex pattern to search for. May be repeated (max 16);
patterns are OR-ed. Max 1024 characters each. Example:
``^PermitRootLogin``.
path: File or directory to search inside the running instance.
May be repeated (max 16) to search multiple roots; results
are concatenated in the given order, sharing max_total
across all paths. Defaults to the rootfs root. Example:
``/etc``.
glob: Glob to filter files (ripgrep -g semantics, "!" negates).
May be repeated. Example: ``*.conf``.
max_count: Maximum matches per file (hard cap 10000).
max_total: Maximum total matches across all files (default 1000,
hard cap 10000).
case: Case sensitivity mode.
before: Lines of context to include before each match (ripgrep
-B semantics, hard cap 50). For symmetric context (grep -C
n), pass both before and after yourself.
after: Lines of context to include after each match (ripgrep -A
semantics, hard cap 50).
"""
spec = operations.build_inspect_instance_grep(
operation_uuid=operation_uuid,
pattern=pattern,
path=path,
glob=glob,
max_count=max_count,
max_total=max_total,
case=case,
before=before,
after=after,
)
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_inspect_instance_grep(response)
[docs]
def inspect_image_grep(
self,
image_uuid: str,
pattern: str | Sequence[str],
*,
path: str | Sequence[str] | None = None,
glob: str | Sequence[str] | None = None,
max_count: int | None = None,
max_total: int | None = None,
case: Literal["sensitive", "insensitive", "smart"] | None = None,
before: int | None = None,
after: int | None = None,
) -> GrepResult:
"""Search file contents in image.
Regex content search inside the image's root filesystem, powered by
ripgrep.
Symlinks are never followed during traversal, hidden files are searched,
``.gitignore``-style files inside the image are ignored, and binary
files
(containing a NUL byte) are skipped. Rust regex syntax, linear-time
matching.
Results are a flat, file-ordered list of lines. ``before``/``after``
request extra
``type: context`` lines around each ``type: match`` line, mirroring
ripgrep's
--json message type field.
``path`` may be repeated to search multiple roots in one call, the same
way
``pattern``/``glob`` already can; results are concatenated in the given
order
and share the ``max_total`` budget across all of them.
Args:
image_uuid: The UUID of the image to inspect Example:
``12345678-9abc-baba-deda-0123456789ab``.
pattern: Regex pattern to search for. May be repeated (max 16);
patterns are OR-ed. Max 1024 characters each. Example:
``^PermitRootLogin``.
path: File or directory to search inside the image. May be
repeated (max 16) to search multiple roots; results are
concatenated in the given order, sharing max_total across
all paths. Defaults to the rootfs root. Example: ``/etc``.
glob: Glob to filter files (ripgrep -g semantics, "!" negates).
May be repeated. Example: ``*.conf``.
max_count: Maximum matches per file (hard cap 10000).
max_total: Maximum total matches across all files (default 1000,
hard cap 10000).
case: Case sensitivity mode.
before: Lines of context to include before each match (ripgrep
-B semantics, hard cap 50). For symmetric context (grep -C
n), pass both before and after yourself.
after: Lines of context to include after each match (ripgrep -A
semantics, hard cap 50).
"""
spec = operations.build_inspect_image_grep(
image_uuid=image_uuid,
pattern=pattern,
path=path,
glob=glob,
max_count=max_count,
max_total=max_total,
case=case,
before=before,
after=after,
)
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_inspect_image_grep(response)
[docs]
def whoami(self) -> WhoAmIResponse:
"""Get current token information.
Returns information about the current authentication token, including
the token UUID, expiration time, and a map of all known permissions
with their granted status.
"""
spec = operations.build_whoami()
self.log_request(spec)
response = self.call(spec)
self.log_response(spec, response)
return operations.parse_whoami(response)
[docs]
class ContreeAsyncClient(ContreeClientBase, ABC):
"""Asynchronous Contree API client interface.
Backend implementations only provide :meth:`request`,
:meth:`stream` and :meth:`close`.
"""
[docs]
@abstractmethod
async def request(self, spec: RequestSpec) -> ResponseData:
"""Execute the request and return the buffered response."""
[docs]
@abstractmethod
def stream(
self,
spec: RequestSpec,
auto_decompress: bool = True,
) -> AsyncGenerator[bytes, None]:
"""Execute the request and yield response body chunks.
With ``auto_decompress=False`` the body is yielded exactly as
served (e.g. the gzip the server always applies is kept).
"""
[docs]
@abstractmethod
async def close(self) -> None:
"""Release the underlying transport resources."""
[docs]
async def open(self) -> None:
"""Eagerly initialize the underlying transport.
Called by ``__aenter__`` from inside the running event loop,
so backends can create loop-bound resources here (for example
the ``aiohttp.ClientSession``). The default is a no-op.
"""
async def __aenter__(self: TAsyncClient) -> TAsyncClient:
await self.open()
return self
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc: BaseException | None,
tb: TracebackType | None,
) -> None:
await self.close()
[docs]
async def call(self, spec: RequestSpec) -> ResponseData:
"""Execute a buffered request, retrying per the client policy.
Without a policy this is a transparent single :meth:`request`.
Streaming requests are never routed here - SSE consumers
reconnect with ``Last-Event-Id`` instead.
"""
policy = self.retry
if policy is None:
if spec.deadline is not None:
remaining = spec.deadline - time.monotonic()
if remaining <= 0:
raise TimeoutError(REQUEST_DEADLINE_MESSAGE)
deadline_limited = deadline_limits_timeout(spec.deadline, self.timeout)
try:
if spec.deadline is None:
response = await self.request(spec)
else:
response = await asyncio.wait_for(
self.request(spec), timeout=remaining
)
except APIConnectionError as exc:
if deadline_due(spec.deadline, deadline_limited and exc.timed_out):
raise TimeoutError(REQUEST_DEADLINE_MESSAGE) from exc
raise
except (asyncio.TimeoutError, TimeoutError) as exc:
if spec.deadline is not None:
raise TimeoutError(REQUEST_DEADLINE_MESSAGE) from exc
raise
if spec.deadline is not None and time.monotonic() >= spec.deadline:
raise TimeoutError(REQUEST_DEADLINE_MESSAGE)
return response
# a lost response after a non-idempotent request (POST) could
# mean a second execution server-side: never blind-retry
# unless the caller explicitly opted into that risk. 425 Too
# Early and 429 Too Many Requests are the exceptions - the
# backend's contract guarantees both mean the request was
# rejected before any processing, so replaying is always safe.
replay_safe = spec.idempotent or policy.retry_unsafe
delays = retry_generator(policy.delays)
# a retry must replay exactly the bytes the first attempt sent
start = body_start(spec)
attempts = 0
while True:
if spec.deadline is not None:
remaining = spec.deadline - time.monotonic()
if remaining <= 0:
raise TimeoutError(REQUEST_DEADLINE_MESSAGE)
attempts += 1
exhausted = (
policy.max_attempts is not None and attempts >= policy.max_attempts
)
deadline_limited = deadline_limits_timeout(spec.deadline, self.timeout)
try:
if spec.deadline is None:
response = await self.request(spec)
else:
response = await asyncio.wait_for(
self.request(spec), timeout=remaining
)
except APIConnectionError as exc:
if deadline_due(spec.deadline, deadline_limited and exc.timed_out):
raise TimeoutError(REQUEST_DEADLINE_MESSAGE) from exc
if not replay_safe or exhausted:
raise
delay = next(delays)
self.log.warning(
"network error (%s), retrying in %.1fs...",
type(exc).__name__,
delay,
)
if spec.deadline is not None:
delay = min(
delay,
max(0.0, spec.deadline - time.monotonic()),
)
await asyncio.sleep(delay)
rewind_body(spec, start)
continue
except APIStatusError as exc:
if not policy.retryable_status(exc.status) or exhausted:
raise
if not replay_safe and exc.status not in (425, 429):
raise
delay = exc.retry_after
if delay is None:
delay = next(delays)
self.log.warning(
"server answered %d, retrying in %.1fs...",
exc.status,
delay,
)
if spec.deadline is not None:
delay = min(
delay,
max(0.0, spec.deadline - time.monotonic()),
)
await asyncio.sleep(delay)
rewind_body(spec, start)
continue
except (asyncio.TimeoutError, TimeoutError) as exc:
if spec.deadline is not None:
raise TimeoutError(REQUEST_DEADLINE_MESSAGE) from exc
raise
if spec.deadline is not None and time.monotonic() >= spec.deadline:
raise TimeoutError(REQUEST_DEADLINE_MESSAGE)
return response
[docs]
async def operation_terminal(
self,
operation_id: str,
deadline: float | None = None,
) -> bool:
"""Best-effort check that the operation reached a terminal state."""
spec = operations.build_get_operation_status(operation_id=operation_id)
spec.deadline = deadline
deadline_limited = deadline_limits_timeout(deadline, self.timeout)
try:
self.log_request(spec)
if deadline is None:
response = await self.request(spec)
else:
remaining = deadline - time.monotonic()
if remaining <= 0:
raise TimeoutError(
f"operation {operation_id} status probe exceeded its deadline"
)
response = await asyncio.wait_for(self.request(spec), timeout=remaining)
if deadline is not None and time.monotonic() >= deadline:
raise TimeoutError(
f"operation {operation_id} status probe exceeded its deadline"
)
self.log_response(spec, response)
status = operations.parse_get_operation_status(response).status
except APIConnectionError as exc:
if deadline_due(deadline, deadline_limited and exc.timed_out):
raise TimeoutError(
f"operation {operation_id} status probe exceeded its deadline"
) from exc
return False
except APIStatusError as exc:
if deadline_due(deadline):
raise TimeoutError(
f"operation {operation_id} status probe exceeded its deadline"
) from exc
if exc.status in (410, 425, 429) or exc.status >= 500:
return False
raise
except (asyncio.TimeoutError, TimeoutError) as exc:
if deadline is not None:
raise TimeoutError(
f"operation {operation_id} status probe exceeded its deadline"
) from exc
raise
return not isinstance(status, EllipsisType) and status.is_terminal()
async def _read_operation_status(
self,
operation_id: str,
deadline: float | None,
) -> OperationResponse:
"""Fetch status using the waiter's deadline."""
spec = operations.build_get_operation_status(operation_id=operation_id)
spec.deadline = deadline
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_get_operation_status(response)
[docs]
async def wait_operation(
self,
operation_id: str,
*,
timeout: float | None = None,
follow_events: bool | None = None,
idle_timeout: float = 15.0,
) -> OperationResponse:
"""Wait for the terminal operation response.
``follow_events=None`` follows instance events and polls image imports
every 0.5 seconds. Use ``True`` to force events or ``False`` to force
polling. Keep the event stream open until completion, EOF, a transport
error, or a timeout. ``idle_timeout`` is the maximum gap between
incoming data chunks in seconds (default 15.0; 0 disables it).
Ping/keepalive traffic resets this limit; it does not extend the
overall timeout. Gaps between payload events do not trigger checks.
After completion, poll until the status is terminal.
Return failed and cancelled responses unchanged.
``timeout`` covers the entire wait and raises :class:`TimeoutError`
on expiry.
"""
if not math.isfinite(idle_timeout) or idle_timeout < 0:
raise ValueError("idle_timeout must be finite and non-negative")
deadline = None if timeout is None else time.monotonic() + timeout
timeout_message = f"operation {operation_id} did not complete within {timeout}s"
try:
result = None
if follow_events is None:
result = await self._read_operation_status(operation_id, deadline)
follow_events = result.kind != "image_import"
if follow_events:
remaining = (
None if deadline is None else max(0.0, deadline - time.monotonic())
)
async for event in self.follow_operation_events(
operation_id, timeout=remaining, idle_timeout=idle_timeout
):
self.log.debug("wait_operation: event %s %s", event.id, event.type)
result = await self._read_operation_status(operation_id, deadline)
if result is None:
result = await self._read_operation_status(operation_id, deadline)
while True:
if (
not isinstance(result.status, EllipsisType)
and result.status.is_terminal()
):
return result
delay = TIGHT_LOOP_FLOOR
if deadline is not None:
delay = min(delay, max(0.0, deadline - time.monotonic()))
await asyncio.sleep(delay)
result = await self._read_operation_status(operation_id, deadline)
except (asyncio.TimeoutError, TimeoutError) as exc:
if deadline is not None:
raise TimeoutError(timeout_message) from exc
raise
[docs]
async def follow_operation_events(
self,
operation_id: str,
*,
last_event_id: int | None = None,
spid: int | None = None,
since: int | None = None,
timeout: float | None = None,
idle_timeout: float = 15.0,
) -> AsyncGenerator[OperationEvent, None]:
"""Stream operation events with transparent reconnection.
Native stream failures trigger a terminal-status probe and a
reconnect from the last event id. Iteration ends at the
``completion`` event or the timeout. After a terminal status,
drain the retained log without following before ending iteration.
Interrupted retained reads resume from the last event id, using
the configured retry policy (three attempts by default). Normal
EOF also completes a filtered or explicitly resumed retained log.
An unfiltered log must include completion. An unavailable or
incomplete event log raises APIConnectionError.
The timeout is an absolute deadline checked whenever iteration
resumes. Caller code between events is not interrupted.
``idle_timeout`` bounds gaps between incoming data in seconds
(default 15.0; 0 disables it). Ping/keepalive traffic resets this
limit without extending the overall timeout.
"""
if not math.isfinite(idle_timeout) or idle_timeout < 0:
raise ValueError("idle_timeout must be finite and non-negative")
last_id = last_event_id
terminal = False
drain_attempts = 0
policy = self.retry or RetryPolicy(max_attempts=3)
delays = retry_generator(policy.delays)
deadline = None if timeout is None else time.monotonic() + timeout
def check_deadline() -> None:
if deadline_due(deadline):
raise TimeoutError(
f"operation {operation_id} events did not complete"
f" within {timeout}s"
)
while True:
check_deadline()
events_before = last_id
if terminal:
drain_attempts += 1
try:
# aclosing: leaving this scope must close the transport
# stream even when the caller aborts the iteration
async with aclosing(
self.iter_operation_events(
operation_id,
follow=not terminal,
spid=spid,
since=since,
last_event_id=last_id,
deadline=deadline,
idle_timeout=idle_timeout,
)
) as source:
async for event in source:
last_id = event.id
yield event
if event.type == "completion":
return
check_deadline()
except (APIConnectionError, APIStatusError) as exc:
check_deadline()
retryable = not isinstance(exc, APIStatusError) or (
policy.retryable_status(exc.status)
)
resume_id = getattr(exc, "last_event_id", None)
if isinstance(resume_id, int):
last_id = resume_id
self.log.warning("stream broken (last_id=%s): %s", last_id, exc)
if not retryable or (
terminal
and policy.max_attempts is not None
and drain_attempts >= policy.max_attempts
):
raise APIConnectionError(
f"operation {operation_id} event log could not be read"
) from exc
if terminal:
retry_at = time.monotonic() + next(delays)
if deadline is not None:
retry_at = min(retry_at, deadline)
# asyncio timers can wake early on coarse-resolution clocks.
while True:
await asyncio.sleep(max(0.0, retry_at - time.monotonic()))
if time.monotonic() >= retry_at:
break
continue
else:
if terminal:
if spid is None and since is None and last_event_id is None:
raise APIConnectionError(
f"operation {operation_id} event log"
" ended without completion"
)
return
# A terminal status does not mean this subscriber received all
# events. Reconnect to drain the retained tail, retaining
# the cursor, filters and original deadline.
terminal = await self.operation_terminal(operation_id, deadline)
if not terminal and last_id == events_before:
delay = TIGHT_LOOP_FLOOR
if deadline is not None:
delay = min(delay, max(0.0, deadline - time.monotonic()))
await asyncio.sleep(delay)
[docs]
async def resolve_image(self, ref: str) -> str:
"""Resolve an image reference to a UUID.
Accepts a raw UUID, ``tag:NAME`` or a bare tag name.
"""
if ref.startswith("tag:"):
return await self.inspect_find_image_by_tag(ref[4:])
if is_uuid(ref):
return ref
return await self.inspect_find_image_by_tag(ref)
[docs]
async def ensure_file(
self,
content: bytes | IO[bytes],
*,
sha256: str | None = None,
) -> FileResponse | File:
"""Upload *content* unless the server already stores it.
The digest (*sha256* when the caller already knows it,
computed locally in a worker thread otherwise, so a large file
does not block the event loop) is probed via :meth:`get_file`;
only a miss uploads. Returns the stored file record either way
(both shapes carry ``uuid``, ``sha256`` and ``size``).
Non-seekable streams cannot be hashed and rewound, so without
a caller-provided *sha256* they skip deduplication and upload
directly.
"""
if sha256 is not None:
digest: str | None = sha256
else:
digest = await asyncio.to_thread(file_sha256, content)
if digest is None:
return await self.upload_file(content)
try:
return await self.get_file(digest)
except NotFoundError:
return await self.upload_file(content)
[docs]
async def list_network_policies(
self,
*,
search: str | None = None,
limit: int | None = None,
offset: int | None = None,
) -> NetworkPolicyListResponse:
"""List network policies.
Returns policies in your namespace and the shared namespace. Deleted
policies are excluded.
Reusing or restoring a policy does not change its creation time or
listing position.
Each entry contains the policy UUID, creation timestamp, accessible
tags, and a summary
with the number of IP rules. Tags are sorted by name. Your tag takes
precedence over
a shared tag with the same name; the overridden shared binding is
omitted.
Use ``GET /network/policies/{uuid}`` to retrieve the full rules.
Requires ``spawn`` or ``spawn_disposable`` permission.
Search:
Supply ``search`` to find active policies in your namespace and the
shared namespace
that allow the destination. The input determines the search type;
currently only IPv4
and IPv6 addresses and CIDRs are supported. Domains and other
unsupported inputs
return 400. An omitted search parameter lists policies normally; an
empty value
returns 400.
Use ``[tcp://|udp://]address-or-cidr[:port]``. IPv6 addresses and CIDRs
must be
enclosed in brackets when specifying a port, with the prefix length
inside
the brackets. Examples: ``192.0.2.1``, ``192.0.2.0/24:443``,
``tcp://192.0.2.0/24:443``, and ``udp://[2001:db8::/64]:53``.
This is search syntax, not a URL. CIDRs must use their network address;
host bits, scoped IPv6 addresses, and ports outside 1-65535 return 400.
A match must allow the requested protocol and port throughout the entire
CIDR,
not merely overlap it. An IP address is treated as a /32 or /128 CIDR.
All-port rules match every requested port. If protocol or port is
omitted,
any single protocol/port combination covering the entire destination
matches.
Complementary subnets granting that same access are normalized into a
covering
rule. Permissions from different policies are never combined for search.
Empty policies do not match. Filtering happens before pagination, and
results
retain the same order, summary, timestamp, and tags as the normal
listing.
Args:
search: IP or CIDR search, optionally qualified by TCP/UDP and a
destination port.
limit: Maximum number of results to return. Invalid values raise
400 error.
offset: Number of results to skip. Invalid values raise 400
error.
"""
spec = operations.build_list_network_policies(
search=search, limit=limit, offset=offset
)
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_list_network_policies(response)
[docs]
async def create_network_policy(
self, cidrs: list[NetworkPolicyCIDRRule]
) -> NetworkPolicy:
"""Create a network policy.
Creates a policy with immutable rules in the caller's namespace.
Requires ``network_policy`` permission.
**Rules**
- Each rule allows a CIDR for the selected protocol and ports. An empty
or
omitted port list allows all ports.
- ICMP is allowed to every listed CIDR, regardless of protocol or ports.
- An empty rules array (``cidrs: []``) blocks all IP egress, including
ICMP
and traffic to the host.
- ARP is blocked for all policies.
**Limits**
The same limit of 16384 units applies before and after normalization.
Sum the number of ports across all rules, counting an empty or omitted
port list (all ports) as 1. The limit covers the entire policy, across
all IP versions and protocols.
Duplicates count toward the limit before normalization. Exceeding the
limit returns 400, even if normalization would remove redundant rules or
ports.
**Normalization**
Before storage, duplicate rules and ports are removed, CIDRs are merged
per protocol and port, and rules and ports are sorted. This preserves
the
allowed traffic. The response contains the normalized rules.
**Policy identity**
Equivalent normalized policies in the same namespace reuse the same
UUID,
including concurrent requests. The UUID is UUIDv5 derived from the
namespace
and the normalized policy hash. Resubmitting a deleted policy restores
it
without restoring its tags. To change the rules, create a new policy.
"""
spec = operations.build_create_network_policy(cidrs=cidrs)
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_create_network_policy(response)
[docs]
async def get_network_policy(self, uuid: str) -> NetworkPolicy:
"""Get a network policy.
Returns an accessible policy, including deleted policies.
Returns 404 if the policy does not exist.
Requires ``spawn`` or ``spawn_disposable`` permission.
Args:
uuid: Network policy UUID Example:
``12345678-9abc-baba-deda-0123456789ab``.
"""
spec = operations.build_get_network_policy(uuid=uuid)
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_get_network_policy(response)
[docs]
async def delete_network_policy(self, uuid: str) -> None:
"""Remove a network policy.
Removes a policy in your namespace. Requires ``network_policy``
permission.
Returns 204 if the policy is removed or was already removed.
Returns 404 if the policy does not exist in your namespace.
Removes its tags and excludes it from listings. The policy remains
accessible
and usable by UUID, but cannot be assigned to tags.
Args:
uuid: Network policy UUID Example:
``12345678-9abc-baba-deda-0123456789ab``.
"""
spec = operations.build_delete_network_policy(uuid=uuid)
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_delete_network_policy(response)
[docs]
async def get_network_policy_tag(self, tag: str) -> NetworkPolicyTag:
"""Get a network policy tag.
Redirects to the policy referenced by your tag, or the shared tag if you
have no tag with that name.
The redirect response includes the effective tag binding as JSON.
Requires ``spawn`` or ``spawn_disposable`` permission. Returns 404 if
the tag or its target
policy does not exist or is removed.
Args:
tag: Network policy tag name
"""
spec = operations.build_get_network_policy_tag(tag=tag)
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_get_network_policy_tag(response)
[docs]
async def set_network_policy_tag(self, tag: str, uuid: str) -> NetworkPolicyTag:
"""Bind a tag to a network policy.
Creates or replaces your tag's binding to an active policy in your
namespace or the shared namespace.
Repeating the same binding has no effect. Returns 404 if the target
policy
does not exist, is inaccessible, or is removed. The tag belongs to your
namespace.
Requires ``network_policy`` permission.
Args:
tag: Network policy tag name
"""
spec = operations.build_set_network_policy_tag(tag=tag, uuid=uuid)
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_set_network_policy_tag(response)
[docs]
async def delete_network_policy_tag(self, tag: str) -> None:
"""Remove a network policy tag.
Removes your tag, including when operations use its policy. Repeated
deletion succeeds.
If a shared tag has the same name, it becomes visible again.
Requires ``network_policy`` permission.
Args:
tag: Network policy tag name
"""
spec = operations.build_delete_network_policy_tag(tag=tag)
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_delete_network_policy_tag(response)
[docs]
async def list_images(
self,
*,
limit: int | None = None,
offset: int | None = None,
tagged: bool = False,
tag: str | None = None,
uuid: str | None = None,
since: str | int | float | datetime | None = None,
until: str | int | float | datetime | None = None,
) -> ImageListResponse:
"""List publicly available images.
Returns a list of all publicly available container images.
Args:
limit: Maximum number of images to return. Must be between 1 and
1000. Default is 100. Invalid values raise 400 error.
offset: Number of images to skip before starting to collect the
result set. Default is 0. Invalid values raise 400 error.
tagged: Example: ``1``.
tag: A valid image tag prefix to filter images by this prefix.
Only images with tags starting with. Implies ``tagged``
parameter. Example: ``ubuntu``.
uuid: Filter images by UUID Example:
``12345678-9abc-baba-deda-0123456789ab``.
since: **Show only results created after the given date/time or
interval.** Accepts a Unix timestamp or interval string.
Interval format: ``600s``/``15m``/``2h``/``3d``/``1w`` means
600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago
respectively). For example: * ``2025-01-01T12:00:00+00:00``
means January 1st, 2025 at 12:00 UTC * ``600s`` means 600
seconds ago * ``15m`` means 15 minutes ago Invalid values
raise 400 error. Example: ``1w``.
until: **Show only results created before the given date/time or
interval.** Accepts a Unix timestamp or interval string.
Interval format: ``600s``/``15m``/``2h``/``3d``/``1w`` means
600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago
respectively). For example: * ``2025-01-01T12:00:00+00:00``
means January 1st, 2025 at 12:00 UTC * ``600s`` means 600
seconds ago * ``15m`` means 15 minutes ago Invalid values
raise 400 error. Example: ``1h``.
"""
spec = operations.build_list_images(
limit=limit,
offset=offset,
tagged=tagged,
tag=tag,
uuid=uuid,
since=since,
until=until,
)
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_list_images(response)
[docs]
async def iter_images(
self,
*,
tagged: bool = False,
tag: str | None = None,
uuid: str | None = None,
since: str | int | float | datetime | None = None,
until: str | int | float | datetime | None = None,
page_size: int = 1000,
limit: int | None = None,
) -> AsyncGenerator[Image, None]:
"""Iterate over list_images() results across pages.
Offset pagination happens transparently as items are consumed; breaking
out of the loop stops fetching. Note that offset pagination is not a
snapshot - records created or deleted between page fetches may shift, so
items can repeat or be skipped under concurrent modification.
Args:
tagged: Example: ``1``.
tag: A valid image tag prefix to filter images by this prefix.
Only images with tags starting with. Implies ``tagged``
parameter. Example: ``ubuntu``.
uuid: Filter images by UUID Example:
``12345678-9abc-baba-deda-0123456789ab``.
since: **Show only results created after the given date/time or
interval.** Accepts a Unix timestamp or interval string.
Interval format: ``600s``/``15m``/``2h``/``3d``/``1w`` means
600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago
respectively). For example: * ``2025-01-01T12:00:00+00:00``
means January 1st, 2025 at 12:00 UTC * ``600s`` means 600
seconds ago * ``15m`` means 15 minutes ago Invalid values
raise 400 error. Example: ``1w``.
until: **Show only results created before the given date/time or
interval.** Accepts a Unix timestamp or interval string.
Interval format: ``600s``/``15m``/``2h``/``3d``/``1w`` means
600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago
respectively). For example: * ``2025-01-01T12:00:00+00:00``
means January 1st, 2025 at 12:00 UTC * ``600s`` means 600
seconds ago * ``15m`` means 15 minutes ago Invalid values
raise 400 error. Example: ``1h``.
page_size: how many records to fetch per request (the server
caps a page at 1000)
limit: stop after this many records in total; None iterates
everything
"""
if not 1 <= page_size <= 1000:
raise ValueError("page_size must be between 1 and 1000")
fetched = 0
offset = 0
while True:
size = page_size if limit is None else min(page_size, limit - fetched)
if size <= 0:
return
page = (
await self.list_images(
tagged=tagged,
tag=tag,
uuid=uuid,
since=since,
until=until,
limit=size,
offset=offset,
)
).images
if isinstance(page, EllipsisType) or not page:
return
for item in page:
yield item
fetched += 1
if limit is not None and fetched >= limit:
return
if len(page) < size:
return
offset += len(page)
[docs]
async def delete_image_tag(
self, image_uuid: str, *, tag: str | None = None
) -> None:
"""Remove tags from an image.
Removes a tag (or all tags) from an image.
When ``tag`` query parameter is provided, only that specific tag is
removed.
When omitted, all tags are removed from the image.
If any public image has the same tag, tag will start tracking that
public image again.
In all other cases tag will be removed and the image will be accessible
only by its UUID.
Args:
image_uuid: The UUID of the image to untag Example:
``12345678-9abc-baba-deda-0123456789ab``.
tag: The tag to remove. If omitted, all tags are removed from
the image. Example: ``busybox:latest``.
"""
spec = operations.build_delete_image_tag(image_uuid=image_uuid, tag=tag)
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_delete_image_tag(response)
[docs]
async def update_image_tag(self, image_uuid: str, tag: str) -> Image:
"""Add a tag to an image.
Adds a tag to an image. Tags are unique per namespace; if the requested
tag is already
assigned to another image, it will be moved to this image.
Assigning a tag that matches a public tag to a public image will freeze
that tag
to the current image - subsequent public updates to the tag will not
affect it.
To make the public tag track the latest public image again, remove your
tag assignment.
When a tag is removed from an image that resides in the public
namespace, the API returns HTTP 200 OK.
response body contains the tag that now points to the public image
(i.e., the image that the tag is automatically re-assigned to).
In other words, un-tagging a public image does not delete the tag; it
simply moves the tag back to the public
image and the caller receives that tag in the successful response.
Args:
image_uuid: The UUID of the image to update Example:
``12345678-9abc-baba-deda-0123456789ab``.
tag: New tag for the image Example: ``busybox:latest``.
"""
spec = operations.build_update_image_tag(image_uuid=image_uuid, tag=tag)
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_update_image_tag(response)
[docs]
async def import_image(
self,
registry: ImageImportRegistry,
*,
tag: str | None | EllipsisType = ...,
timeout: int | EllipsisType = ...,
) -> str:
"""Import a container image from a registry.
Imports the OCI image filesystem content of from a specified registry.
Important limitations and behavior:
- Only the image root filesystem (files and directories) is imported.
This is like to the output of
``docker export`` and does not preserve layers metadata.
- Most image configuration and manifest data are ignored. Metadata such
as ``LABEL``,
``ENTRYPOINT``, ``CMD``, ``WORKDIR``, ``EXPOSE`` and other image
configuration directives
will **NOT be imported or applied**.
- ``ENV`` variables defined in the image **are imported** and
automatically applied to the
instance environment when ``shell`` is set to ``true``. When ``shell``
is ``false``, image
environment variables are not inherited and must be passed explicitly
via the ``env`` field.
- The result is a flat rootfs snapshot with preserved environment
variables.
- If the specified tag already exists in the public images, the imported
image will replace it.
To avoid this, you can tag the existing image with a different tag for
use it later.
You also can use image UUIDs it is not changing for imported and
existend image.
- In case the remote image is unchanged and already imported, the
operation will complete and the same UUID
will be returned without re-importing the image.
The request creates an import operation which runs asynchronously.
Args:
tag: Tag to identify the image when listing publicly available
images. If omitted, the image will be private and only
accessible by ID. Example: ``busybox:latest``.
timeout: Maximum time in seconds to wait for the import
operation to complete Example: ``300``.
"""
spec = operations.build_import_image(
registry=registry, tag=tag, timeout=timeout
)
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_import_image(response)
[docs]
async def list_files(
self,
*,
limit: int | None = None,
offset: int | None = None,
since: str | int | float | datetime | None = None,
until: str | int | float | datetime | None = None,
) -> FilesListResponse:
"""List uploaded files for the current namespace.
Returns a paginated list of uploaded files for the current namespace.
Args:
limit: Maximum number of files to return
offset: Number of files to skip
since: Filter files created after this time
until: Filter files created before this time
"""
spec = operations.build_list_files(
limit=limit, offset=offset, since=since, until=until
)
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_list_files(response)
[docs]
async def iter_files(
self,
*,
since: str | int | float | datetime | None = None,
until: str | int | float | datetime | None = None,
page_size: int = 1000,
limit: int | None = None,
) -> AsyncGenerator[File, None]:
"""Iterate over list_files() results across pages.
Offset pagination happens transparently as items are consumed; breaking
out of the loop stops fetching. Note that offset pagination is not a
snapshot - records created or deleted between page fetches may shift, so
items can repeat or be skipped under concurrent modification.
Args:
since: Filter files created after this time
until: Filter files created before this time
page_size: how many records to fetch per request (the server
caps a page at 1000)
limit: stop after this many records in total; None iterates
everything
"""
if not 1 <= page_size <= 1000:
raise ValueError("page_size must be between 1 and 1000")
fetched = 0
offset = 0
while True:
size = page_size if limit is None else min(page_size, limit - fetched)
if size <= 0:
return
page = (
await self.list_files(
since=since, until=until, limit=size, offset=offset
)
).files
if isinstance(page, EllipsisType) or not page:
return
for item in page:
yield item
fetched += 1
if limit is not None and fetched >= limit:
return
if len(page) < size:
return
offset += len(page)
[docs]
async def upload_file(self, content: bytes | IO[bytes]) -> FileResponse:
"""Upload a file to the server. the body must be a file content.
Uploads a file to the server. The body must contain the file content.
Args:
content: Raw file content: bytes or a binary stream.
"""
spec = operations.build_upload_file(content=content)
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_upload_file(response)
[docs]
async def get_file(self, sha256: str) -> File:
"""Get file info by SHA256.
Returns file info (uuid, sha256, created_at, updated_at).
Args:
sha256: SHA256 hash of the file (64 hex characters)
"""
spec = operations.build_get_file(sha256=sha256)
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_get_file(response)
[docs]
async def check_file_exists(self, sha256: str) -> bool:
"""Check if a file exists for the current namespace.
Returns 200 if the file is uploaded by the current namespace, otherwise
404.
Args:
sha256: SHA256 hash of the file (64 hex characters)
"""
spec = operations.build_check_file_exists(sha256=sha256)
self.log_request(spec)
try:
response = await self.call(spec)
except NotFoundError:
return False
self.log_response(spec, response)
return operations.parse_check_file_exists(response)
[docs]
async def spawn_instance(
self,
command: str,
image: str,
*,
disposable: bool | EllipsisType = ...,
hostname: str | EllipsisType = ...,
args: list[str] | EllipsisType = ...,
shell: bool | EllipsisType = ...,
env: dict[str, str] | None | EllipsisType = ...,
preserve_env: bool | EllipsisType = ...,
preserve_cwd: bool | EllipsisType = ...,
cwd: str | EllipsisType = ...,
uid: int | EllipsisType = ...,
gid: int | EllipsisType = ...,
resources_limits: InstanceResourcesLimits | EllipsisType = ...,
networking: InstanceNetworking | EllipsisType = ...,
stdin: ClosableStreamRepr | EllipsisType = ...,
timeout: int | EllipsisType = ...,
truncate_output_at: int | EllipsisType = ...,
files: dict[str, FileSpec] | EllipsisType = ...,
) -> InstanceSpawnResponse:
"""Spawn a new container instance.
Creates and runs a new execution instance with the specified
configuration.
Requires a valid ``Authorization`` header.
Common request body rules:
* The request body must contain at least ``command`` and ``image``
fields all other fields can be omitted.
* If the ``command`` field is a shell expression, you must set
``shell`` field to ``true``.
* For specifying the shell binary, you can use ``env`` field to set
``SHELL`` variable.
* When ``shell`` is ``true``, environment variables defined in the
image (via ``ENV`` directives) are
automatically inherited. When ``shell`` is ``false``, image
environment variables are not inherited
and must be passed explicitly via the ``env`` field.
Args:
command: The command to execute. In case if ``shell`` is set to
``true``, this MUST contain shell expression. For example
``echo hello world`` or ``ls -l /app``. If ``shell`` is set
to ``false``, this must be a relative or absolute path to
the executable inside the image rootfs. For example:
``/bin/app`` or ``/usr/bin/find``. Do not forget pass
necessary ``PATH`` variable to env field, by default
``PATH`` is set to
``/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin``.
Example: ``/bin/app``.
disposable: Creates a disposable execution environment no any
state will be saved.
hostname: Hostname to set when execution. Example:
``container-name``.
args: Arguments to pass to the command if shell is set to false.
Example: ``["arg1","arg2"]``.
shell: Whether to run the command through a shell. If ``true``,
the command must be a shell expression and all values from
args will be ignored. If ``false``, the command field must
be a path to an executable and args will be used. When
``true``, environment variables from the image are
automatically inherited. When ``false``, they are not - use
the ``env`` field to pass them explicitly.
env: Environment variables to set in the container. These are
merged with image-defined variables when ``shell`` is
``true``. When ``shell`` is ``false``, only variables
specified here are available - image-defined variables are
not inherited. Example:
``{"KEY1":"value1","KEY2":"value2"}``.
preserve_env: Preserve environment variables in resulting image
after execution. When ``true``, the image's existing
environment variables from ``metadata/env`` are merged with
user-provided ``env`` values (user values take priority on
conflicts), and the combined result is written back to
``metadata/env`` after command execution. Setting a variable
to an empty string or ``null`` removes it from the preserved
environment.
preserve_cwd: Save the resolved initial working directory as the
default in the resulting image. An empty or omitted ``cwd``
resolves to the image's current workdir, or ``/`` if none
exists. The metadata file is opened for writing only when
its contents differ from the new value. Directory changes
made by the command do not change the saved value. Requires
``disposable: false`` to retain the metadata in a resulting
image.
cwd: Path to the working directory, must be absolute or a
special value the empty string. It means the default working
directory of the image or server default will be used. If
field is omitted it will be set to the empty string. The
directory will be created automatically if it does not
exist. Example: ``/app``.
uid: User ID to run the process as. Example: ``0``.
gid: Group ID to run the process as. Example: ``0``.
timeout: Maximum execution time in seconds Example: ``60``.
truncate_output_at: Maximum number of bytes to keep per stream
(stdout, stderr, and stdin) in the subprocess event log.
Does not affect stdin delivery to the child, which always
receives the complete stream regardless of this cap. Default
is ``1048576`` (1 MiB). The maximum value is ``10485760``
(10 MiB). Example: ``65535``.
files: Map of absolute file paths to file metadata Example:
``{"/root/hello.txt":{"uuid":"a9165a5d-5c86-4bd8-8ee4-ae46c...``.
"""
spec = operations.build_spawn_instance(
command=command,
image=image,
disposable=disposable,
hostname=hostname,
args=args,
shell=shell,
env=env,
preserve_env=preserve_env,
preserve_cwd=preserve_cwd,
cwd=cwd,
uid=uid,
gid=gid,
resources_limits=resources_limits,
networking=networking,
stdin=stdin,
timeout=timeout,
truncate_output_at=truncate_output_at,
files=files,
)
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_spawn_instance(response)
[docs]
async def list_operations(
self,
*,
limit: int | None = None,
offset: int | None = None,
status: OperationStatus | str | None = None,
kind: Literal["image_import", "instance"] | None = None,
since: str | int | float | datetime | None = None,
until: str | int | float | datetime | None = None,
) -> list[OperationSummary]:
"""List operations.
Returns a list of running and completed operations
Args:
limit: Maximum number of operations to return. Must be between 1
and 1000. Default is 100. Invalid values raise 400 error.
offset: Number of operations to skip before starting to collect
the result set. Default is 0. Invalid values raise 400
error.
status: Filter operations by their state
kind: Filter operations by their kind
since: **Show only results created after the given date/time or
interval.** Accepts a Unix timestamp or interval string.
Interval format: ``600s``/``15m``/``2h``/``3d``/``1w`` means
600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago
respectively). For example: * ``2025-01-01T12:00:00+00:00``
means January 1st, 2025 at 12:00 UTC * ``600s`` means 600
seconds ago * ``15m`` means 15 minutes ago Invalid values
raise 400 error. Example: ``1w``.
until: **Show only results created before the given date/time or
interval.** Accepts a Unix timestamp or interval string.
Interval format: ``600s``/``15m``/``2h``/``3d``/``1w`` means
600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago
respectively). For example: * ``2025-01-01T12:00:00+00:00``
means January 1st, 2025 at 12:00 UTC * ``600s`` means 600
seconds ago * ``15m`` means 15 minutes ago Invalid values
raise 400 error. Example: ``1h``.
"""
spec = operations.build_list_operations(
limit=limit,
offset=offset,
status=status,
kind=kind,
since=since,
until=until,
)
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_list_operations(response)
[docs]
async def iter_operations(
self,
*,
status: OperationStatus | str | None = None,
kind: Literal["image_import", "instance"] | None = None,
since: str | int | float | datetime | None = None,
until: str | int | float | datetime | None = None,
page_size: int = 1000,
limit: int | None = None,
) -> AsyncGenerator[OperationSummary, None]:
"""Iterate over list_operations() results across pages.
Offset pagination happens transparently as items are consumed; breaking
out of the loop stops fetching. Note that offset pagination is not a
snapshot - records created or deleted between page fetches may shift, so
items can repeat or be skipped under concurrent modification.
Args:
status: Filter operations by their state
kind: Filter operations by their kind
since: **Show only results created after the given date/time or
interval.** Accepts a Unix timestamp or interval string.
Interval format: ``600s``/``15m``/``2h``/``3d``/``1w`` means
600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago
respectively). For example: * ``2025-01-01T12:00:00+00:00``
means January 1st, 2025 at 12:00 UTC * ``600s`` means 600
seconds ago * ``15m`` means 15 minutes ago Invalid values
raise 400 error. Example: ``1w``.
until: **Show only results created before the given date/time or
interval.** Accepts a Unix timestamp or interval string.
Interval format: ``600s``/``15m``/``2h``/``3d``/``1w`` means
600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago
respectively). For example: * ``2025-01-01T12:00:00+00:00``
means January 1st, 2025 at 12:00 UTC * ``600s`` means 600
seconds ago * ``15m`` means 15 minutes ago Invalid values
raise 400 error. Example: ``1h``.
page_size: how many records to fetch per request (the server
caps a page at 1000)
limit: stop after this many records in total; None iterates
everything
"""
if not 1 <= page_size <= 1000:
raise ValueError("page_size must be between 1 and 1000")
fetched = 0
offset = 0
while True:
size = page_size if limit is None else min(page_size, limit - fetched)
if size <= 0:
return
page = await self.list_operations(
status=status,
kind=kind,
since=since,
until=until,
limit=size,
offset=offset,
)
if isinstance(page, EllipsisType) or not page:
return
for item in page:
yield item
fetched += 1
if limit is not None and fetched >= limit:
return
if len(page) < size:
return
offset += len(page)
[docs]
async def get_operation_status(
self, operation_id: str, *, inflight: bool = False
) -> OperationResponse:
"""Get an operation status.
Returns the status of an operation.
For an EXECUTING INSTANCE operation, pass ``?inflight=1`` to
also synthesize the partial ``result.stdout`` / ``result.stderr``
from the live event log. Off by default — each fetch with
``inflight`` triggers an extra subscribe RPC to the guest and
drains its current events.gz, which is wasted work for
clients that only poll for status transitions.
Args:
operation_id: The ID of the operation Example:
``12345678-9abc-baba-deda-0123456789ab``.
inflight: HTTP-flag boolean. Present without a value
(``?inflight``) and ``?inflight=1`` both enable;
``?inflight=0`` and absence disable. When enabled and the
operation is EXECUTING INSTANCE, partial stdout/stderr is
synthesized from the live event log and attached under
``result``.
"""
spec = operations.build_get_operation_status(
operation_id=operation_id, inflight=inflight
)
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_get_operation_status(response)
[docs]
async def cancel_operation(self, operation_id: str) -> None:
"""Cancel an operation.
Cancels an operation
Args:
operation_id: The ID of the import operation to cancel Example:
``12345678-9abc-baba-deda-0123456789ab``.
"""
spec = operations.build_cancel_operation(operation_id=operation_id)
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_cancel_operation(response)
[docs]
async def iter_operation_events(
self,
operation_id: str,
*,
follow: bool = False,
spid: int | None = None,
since: int | None = None,
last_event_id: int | None = None,
deadline: float | None = None,
idle_timeout: float = 0.0,
) -> AsyncGenerator[OperationEvent, None]:
"""Stream the operation event log via Server-Sent Events.
Always returns ``text/event-stream`` (SSE) on success. The body
is a sequence of three kinds of lines (per RFC W3C SSE), each
terminated by ``\\n\\n``:
.. rubric:: Frame shapes
**Normal event frame** — one ``OperationEvent`` JSON object in
``data:``, dispatchable via ``event:``:
::
id: <integer event.id>
event: <OperationEventType, e.g. stdout|stderr|spawn|exit>
data: {"id": N, "ts": "...", "spid": ..., "type": "...", "data": {...}}
``event:`` always matches ``data.type``. See ``OperationEvent`` and
``OperationEventType`` for the per-type payload shape. Native
``EventSource`` dispatches each frame to the matching
``addEventListener("<type>", ...)`` handler.
**Server-side error frame** — surfaces handler exceptions to
the connected client without tearing the TCP connection down
mid-stream. Sent right before the server closes the response:
::
: stream ended with error, retry since last event id
event: sse_error
data: <one-line exception message>
The leading SSE comment line lets pure-EventSource clients see
the intent ("retry from Last-Event-Id"); the ``sse_error`` frame
carries the error text for logging. Clients should treat this
as a non-clean close and reconnect with the standard SSE
``Last-Event-Id`` semantics (see Resuming).
**Keepalive comment** — periodic ``: keepalive\\n\\n`` lines
emitted while the stream is idle. They keep upstream
``proxy_read_timeout`` / TCP idle timers fresh and have no
application meaning. Spec-compliant; EventSource and any SSE
parser must ignore comment lines (those beginning with ``:``).
.. rubric:: ``follow`` semantics
The ``follow`` parameter controls only whether the stream stays
open after the last currently-known event:
* ``follow=0`` (default) — the server emits everything
currently available and closes the connection.
* ``follow=1`` — same start; if the operation is still
running the server keeps the connection open and forwards
new events as they appear. For terminal operations
``follow=1`` is a no-op: there's nothing more to subscribe
to, so the connection closes after the last event just
like ``follow=0``.
Optional filters:
* ``?spid=N`` — only events whose ``spid`` (Spawned Process ID,
the routing identity in ``OperationEvent``) matches.
* ``?since=N`` — only events with ``id > N``.
``follow=1`` requires ``SPAWN`` or ``SPAWN_DISPOSABLE`` on top of
the baseline ``LIST`` — a long-lived subscription reserves
per-operation server state. ``follow=0`` is read-only and
stays under ``LIST``.
.. rubric:: Resuming after a drop
Every normal frame carries ``id:`` — the canonical event id.
On reconnect send the last successfully received id in the
standard ``Last-Event-Id`` request header (or ``?since=N`` on
manual GETs); the server resumes from that point.
.. rubric:: Error handling
.. list-table::
:header-rows: 1
* - Status
- Meaning
- Client action
* - 200
- Stream open
- Read frames; reconnect with Last-Event-Id if the stream closes
before reaching a terminal event
* - 400
- Malformed query/header (non-integer param)
- Fix request
* - 401
- Missing/invalid auth
- Refresh credentials
* - 403
- Auth lacks LIST (or SPAWN for ``follow=1``)
- Use a token with the right scope
* - 404
- Operation not in this namespace
- Wrong UUID
* - 410
- Stream is over but the terminal artifact isn't ready yet
- Retry after ``Retry-After``
* - 425
- Not yet ready (operation is still being prepared)
- Retry after ``Retry-After``
* - 502
- Upstream returned an error opening the stream
- Retry; if persistent, escalate
* - 504
- Upstream took too long to respond
- Retry
A ``200`` followed by an ``event: sse_error`` frame and immediate
close is the in-band equivalent of "the stream broke after we
already committed to a 200" — handle it the same way as 410:
wait briefly, reconnect with ``Last-Event-Id``.
See ``OperationEvent`` for the per-event shape.
Args:
operation_id: The ID of the operation Example:
``12345678-9abc-baba-deda-0123456789ab``.
follow: HTTP-flag boolean. Present without a value (``?follow``)
and ``?follow=1`` both enable; ``?follow=0`` and absence
disable. When enabled, the SSE stream stays open after the
currently-known events have been sent — for a running
operation new events are forwarded as they appear; for a
terminal operation it has no effect.
spid: Only emit events whose ``spid`` field matches. Filter is
applied server-side regardless of whether the operation is
still running or already terminal.
since: Only emit events with ``id > since`` (event IDs are
monotonically increasing). Overridden by the
``Last-Event-Id`` header when present.
last_event_id: Standard SSE resume header sent automatically by
``EventSource`` on reconnect. Treated as ``?since=N``; takes
precedence over the query param.
deadline: absolute monotonic deadline. Checked whenever
iteration resumes; caller code between events is not
interrupted.
idle_timeout: seconds without incoming data before a transport
timeout; 0 disables it
"""
spec = operations.build_iter_operation_events(
operation_id=operation_id,
follow=follow,
spid=spid,
since=since,
last_event_id=last_event_id,
)
if not math.isfinite(idle_timeout) or idle_timeout < 0:
raise ValueError("idle_timeout must be finite and non-negative")
spec.read_timeout = idle_timeout or None
spec.deadline = deadline
if deadline is not None:
spec.read_timeout = min(
spec.read_timeout or math.inf, max(0.0, deadline - time.monotonic())
)
self.log_request(spec)
parser = SSEParser()
last_seen = last_event_id
async with aclosing(self.stream(spec)) as source:
async for chunk in source:
if deadline is not None and time.monotonic() >= deadline:
raise TimeoutError("iter_operation_events exceeded its deadline")
for frame in parser.feed(chunk):
if frame.id is not None:
last_seen = frame.id
event = decode_event_frame(frame, last_seen)
if event is None:
continue
self.log.debug("sse event: %r", event)
yield event
if deadline is not None and time.monotonic() >= deadline:
raise TimeoutError(
"iter_operation_events exceeded its deadline"
)
[docs]
async def operation_subprocess_create(
self,
operation_id: str,
command: str,
*,
resources_limits: ProcessResourcesLimits | EllipsisType = ...,
args: list[str] | EllipsisType = ...,
shell: bool | EllipsisType = ...,
env: dict[str, str] | None | EllipsisType = ...,
cwd: str | EllipsisType = ...,
uid: int | EllipsisType = ...,
gid: int | EllipsisType = ...,
stdin: ClosableStreamRepr | EllipsisType = ...,
truncate_output_at: int | EllipsisType = ...,
) -> int:
"""Spawn an additional subprocess inside a running instance.
Starts a new process inside the VM that already hosts the named
operation. Distinct from ``POST /instances``, which spins up a
VM: this endpoint requires a running operation (EXECUTING or
ASSIGNED) and reuses the existing VM.
The body is an ``ExecSpec`` — process-execution fields only.
VM-level concerns (``image``, ``hostname``,
``files``, ``timeout``, ``disposable``, ``preserve_env``) are not
accepted here; they were set when the parent operation was
created.
``resources_limits.cpu`` and ``resources_limits.memory_mib`` use the
same names and units as operation creation. Each omitted or null
subprocess limit inherits the corresponding operation limit.
Values above the operation limit return 400. Limits apply at
launch: memory_mib sets RLIMIT_AS for each process and memory.max
for the entire process tree. They cannot be changed through this
API. Guest root can modify limits; these limits do not
provide security isolation between processes in one VM.
The required permission follows the parent instance:
``SPAWN_DISPOSABLE`` when it was spawned with ``disposable=true``,
``SPAWN`` otherwise.
On success the worker assigns a fresh ``spid`` (≥2; ``spid=1`` is
the main process spawned from ``metadata``) and the response
carries it in the body plus a ``Location`` header pointing at
``GET /operations/{operationId}/subprocesses/{spid}`` — the
subprocess result reconstructed from its events.
Args:
operation_id: The ID of the operation Example:
``12345678-9abc-baba-deda-0123456789ab``.
command: The command to execute. Same semantics as in
``InstanceSpawnRequest.command`` — when ``shell=true`` it is
a shell expression, otherwise a path to an executable.
Example: ``/bin/app``.
args: Arguments to pass to the command if shell is set to false.
Example: ``["arg1","arg2"]``.
shell: Run command through a shell expression (args must be
empty).
env: Environment variables to set in the child process.
cwd: Working directory; empty string means image / server
default.
uid: User ID to run the process as.
gid: Group ID to run the process as.
stdin: Bytes fed to the child's stdin — honored for both the
main process and exec'd subprocesses. With ``close=false``
the pipe stays open and more data can be written via
``POST /operations/{operationId}/subprocesses/{spid}/stdin``.
truncate_output_at: Maximum number of bytes to keep per stream
(stdout, stderr, and stdin) in the subprocess event log.
Does not affect delivery to the child — stdin is always
delivered in full regardless of this cap. Defaults to 1 MiB;
capped at 10 MiB. Example: ``65535``.
"""
spec = operations.build_operation_subprocess_create(
operation_id=operation_id,
command=command,
resources_limits=resources_limits,
args=args,
shell=shell,
env=env,
cwd=cwd,
uid=uid,
gid=gid,
stdin=stdin,
truncate_output_at=truncate_output_at,
)
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_operation_subprocess_create(response)
[docs]
async def operation_subprocess(
self, operation_id: str, spid: int
) -> InstanceResult:
"""Result of one subprocess, reconstructed from its events.
Returns an ``InstanceResult`` for ``spid`` — the same shape as the
parent operation's ``metadata.result`` — folded from the
subprocess's event log (spawn / stdout / stderr / exit).
Works for running and terminal operations alike. While the
process is still running, ``state.exit_code`` and ``state.signal``
are ``-1`` (unknown) and ``resources`` holds sentinel defaults;
once the exit event lands they carry the real values.
``stdout`` / ``stderr`` are consolidated and capped at the spec's
``truncate_output_at``. The raw event stream stays available at
``GET /operations/{operationId}/events?spid={spid}``.
Args:
operation_id: The ID of the operation Example:
``12345678-9abc-baba-deda-0123456789ab``.
spid: Spawn id (1 = main process; ≥2 = exec'd children).
"""
spec = operations.build_operation_subprocess(
operation_id=operation_id, spid=spid
)
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_operation_subprocess(response)
[docs]
async def operation_subprocess_kill(
self, operation_id: str, spid: int, *, signal: str | None = None
) -> None:
"""Kill one subprocess.
Sends a signal to the process group of ``spid`` inside the
running instance. Without the ``signal`` parameter the group
gets SIGKILL. Termination is observable, not returned: the
``exit`` event lands in the event log and
``GET /operations/{operationId}/subprocesses/{spid}`` reports
the terminal ``state`` (``signal`` set, ``exit_code`` -1 when killed).
Killing ``spid=1`` (the main process) effectively ends the
operation, like letting the command fail.
Args:
operation_id: The ID of the operation Example:
``12345678-9abc-baba-deda-0123456789ab``.
spid: Spawn id (1 = main process; ≥2 = exec'd children).
signal: Signal to send instead of SIGKILL — a number (``15``) or
a name with or without the SIG prefix (``TERM``,
``SIGTERM``). Example: ``SIGTERM``.
"""
spec = operations.build_operation_subprocess_kill(
operation_id=operation_id, spid=spid, signal=signal
)
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_operation_subprocess_kill(response)
[docs]
async def operation_subprocess_stdin(
self,
operation_id: str,
spid: int,
value: str,
*,
encoding: Literal["ascii", "base64"] | EllipsisType = ...,
close: bool | EllipsisType = ...,
) -> None:
"""Write to a subprocess's stdin and/or close it.
Writes a chunk to the stdin of a live process inside the
running instance — ``spid=1`` targets the main process, ``≥2`` the
exec'd children. Requires the process to have been started
with ``stdin.close=false``; otherwise its pipe is already at EOF
and the call returns 409.
``close=true`` (the default) signals EOF after writing ``value``;
an empty ``value`` with ``close=true`` just closes the pipe. A
client that serializes its own requests gets ordered writes;
concurrent requests to the same spid are safe but their order
is unspecified.
A 504 means the guest write timed out mid-call — the chunk may
or may not have been delivered (e.g. the process stopped
reading and the pipe is full), so blind retries can duplicate
data.
Args:
operation_id: The ID of the operation Example:
``12345678-9abc-baba-deda-0123456789ab``.
spid: Spawn id (1 = main process; ≥2 = exec'd children).
value: Content to write to stdin (may be empty for a close-only
request) Example: ``aGVsbG8K``.
encoding: Encoding of the content
close: ``true`` (default) closes stdin (EOF) after writing
``value`` — the pre-existing one-shot behavior. ``false``
keeps the pipe open so more data can be sent later via
``POST /operations/{operationId}/subprocesses/{spid}/stdin``.
"""
spec = operations.build_operation_subprocess_stdin(
operation_id=operation_id,
spid=spid,
value=value,
encoding=encoding,
close=close,
)
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_operation_subprocess_stdin(response)
[docs]
async def apply_instance_file(
self,
operation_uuid: str,
file_uuid: str,
path: str,
*,
unpack: bool | EllipsisType = ...,
replace: bool | EllipsisType = ...,
merge: bool | EllipsisType = ...,
) -> None:
"""Apply an uploaded file to a running instance.
Reads a file previously uploaded through POST /files and writes it to a
running INSTANCE operation, including disposable instances. Requires
LIST
and the permission used to start the instance. Both the operation and
the
uploaded file must belong to the request namespace. Expired files are
unavailable.
The assigned worker streams the stored object to the guest through RPC.
Init records request metadata in ``inspect`` events and the terminal
publication result in ``file_upload``, including ``file_uuid`` and byte
count.
File contents do not enter operation events.
With unpack omitted or false, path is the full destination filename.
Missing parent directories are created. The file is published atomically
after
transfer and SHA256 verification. The new file has mode 0644 and is
owned by the guest runtime user. With replace true, an existing leaf
symlink is replaced.
Directories and special files are not regular file destinations.
With unpack true, path is the destination directory. Supports tar,
tar.gz and tar.bz2; compression is detected from the stored bytes. Xz is
unsupported and rejected before subsequent chunks are sent. Without
unpack,
compressed archives are copied unchanged. Content-Type describes this
JSON
request and never controls extraction.
Extraction accepts regular files, directories, symlinks and hardlinks to
regular files already extracted in the staging tree. Parent symlinks
inside that tree are
not followed. Absolute entry names and entries containing '..' are
rejected.
procfs, sysfs, devices, FIFOs and sockets are unsupported. New
directories
have mode 0755; regular files retain tar permission bits (0777).
Ownership
and timestamps are not restored. Other entries fail explicitly.
With replace omitted or false, any existing destination returns 409,
including
a symlink or empty directory. This condition is checked again atomically
at publication.
replace true permits an existing destination. With merge omitted or
false,
directory replacement removes the entire old tree without merging
contents.
Archives are extracted into a temporary sibling directory. The
destination
remains unchanged until the complete stream and SHA256 have been
verified.
Without merge, publication uses an atomic rename or exchange, then
removes the old tree.
Root and mount-point replacement are unavailable. Existing open
descriptors
can still refer to old inodes; concurrent workload access is not a
snapshot.
merge true requires both unpack true and replace true. After complete
staging
and verification, it combines directories and atomically replaces
individual
files and symlinks. Existing entries absent from the archive remain.
Destination
directory symlinks are not followed; directory/file conflicts fail
explicitly.
Same-filesystem hardlinks are retained. Crossing a destination mount
requires
copying file bytes and does not preserve hardlinks across filesystems.
Merge is not atomic for the whole tree: errors, cancellation or timeout
after
application starts can leave completed changes. These changes are not
rolled back.
Returns 204 only after completion. Transfers have a 300-second deadline
and bounded buffers and handles. Disconnect or VM exit cancels the
transfer.
A lost response can leave an uncertain outcome; requests are not
replayed
automatically. This endpoint does not write to a completed result image.
A transfer timeout does not stop the instance. Before publication or
merge starts, cancellation
preserves the old destination and removes the temporary file or
extraction tree.
A timeout while awaiting the final response can occur after publication;
it does not prove that no changes were made. An old-tree cleanup failure
is
reported as an error after publication; it does not roll back the new
tree.
The uploaded source object retains its normal lifetime. Automatically
created
parent directories have mode 0755 and can remain after errors.
The primary command's timeout follows normal instance finalization:
ordinary
instances persist their filesystem, including successfully published
uploads;
disposable instances do not. Instance shutdown waits for pending upload
cleanup.
A timeout or crash of the execution environment can bypass this cleanup
and does not produce
a successfully persisted result image through normal finalization.
Args:
operation_uuid: Example:
``12345678-9abc-baba-deda-0123456789ab``.
path: Absolute guest filename, or directory when unpack is true.
Missing parents are created.
unpack: Extract tar, tar.gz or tar.bz2 instead of copying the
stored bytes.
replace: Permit an existing destination. Without merge,
directories are replaced in full.
merge: Merge verified archive contents. Requires unpack and
replace. Can leave partial changes.
"""
spec = operations.build_apply_instance_file(
operation_uuid=operation_uuid,
file_uuid=file_uuid,
path=path,
unpack=unpack,
replace=replace,
merge=merge,
)
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_apply_instance_file(response)
[docs]
async def inspect_instance_download(self, operation_uuid: str, path: str) -> bytes:
"""Download a file from a running instance.
Reads through guest RPC without recording file contents in operation
events.
Requires LIST and the permission used to start this instance (SPAWN or
SPAWN_DISPOSABLE). Reads include tmpfs and additional mounts visible to
the guest runtime. procfs, sysfs, devices, sockets, and FIFOs are
unavailable.
Reads do not form a snapshot. The opened inode and initial size are
used;
later growth is excluded. Truncation or VM exit interrupts the response.
A transfer has a 300-second deadline. No result-image fallback is
performed.
Args:
operation_uuid: The UUID of the running instance to inspect
Example: ``12345678-9abc-baba-deda-0123456789ab``.
path: The path of the file to inspect inside the running
instance, e.g. ``/etc/hosts``
"""
spec = operations.build_inspect_instance_download(
operation_uuid=operation_uuid, path=path
)
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_inspect_instance_download(response)
[docs]
async def inspect_instance_download_stream(
self, operation_uuid: str, path: str
) -> AsyncGenerator[bytes, None]:
"""Streaming variant of ``inspect_instance_download()``.
Reads through guest RPC without recording file contents in operation
events.
Requires LIST and the permission used to start this instance (SPAWN or
SPAWN_DISPOSABLE). Reads include tmpfs and additional mounts visible to
the guest runtime. procfs, sysfs, devices, sockets, and FIFOs are
unavailable.
Reads do not form a snapshot. The opened inode and initial size are
used;
later growth is excluded. Truncation or VM exit interrupts the response.
A transfer has a 300-second deadline. No result-image fallback is
performed.
Args:
operation_uuid: The UUID of the running instance to inspect
Example: ``12345678-9abc-baba-deda-0123456789ab``.
path: The path of the file to inspect inside the running
instance, e.g. ``/etc/hosts``
"""
spec = operations.build_inspect_instance_download(
operation_uuid=operation_uuid, path=path
)
self.log_request(spec)
async with aclosing(self.stream(spec)) as source:
async for chunk in source:
self.log.debug("stream chunk: %d bytes", len(chunk))
yield chunk
[docs]
async def check_instance_file(self, operation_uuid: str, path: str) -> bool:
"""Check if a file exists in running instance.
Checks if a file exists in the specified running instance without
returning the file content
Args:
operation_uuid: The UUID of the running instance to inspect
Example: ``12345678-9abc-baba-deda-0123456789ab``.
path: The path of the file to check inside the running instance,
e.g. ``/etc/hosts``
"""
spec = operations.build_check_instance_file(
operation_uuid=operation_uuid, path=path
)
self.log_request(spec)
try:
response = await self.call(spec)
except NotFoundError:
return False
self.log_response(spec, response)
return operations.parse_check_instance_file(response)
[docs]
async def inspect_instance_list(
self, operation_uuid: str, path: str
) -> DirectoryList:
"""List files in running instance.
Lists guest files without recording contents in operation events.
Requires LIST and the permission used to start this instance.
Reads do not form a snapshot. A directory can contain at most 10000
entries.
procfs and sysfs cannot be listed.
Args:
operation_uuid: The UUID of the running instance to inspect
Example: ``12345678-9abc-baba-deda-0123456789ab``.
path: The path of the directory to inspect inside the running
instance Example: ``/etc``.
"""
spec = operations.build_inspect_instance_list(
operation_uuid=operation_uuid, path=path
)
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_inspect_instance_list(response)
[docs]
async def inspect_instance_archive(
self, operation_uuid: str, path: str, *, compressed: bool = False
) -> AsyncGenerator[bytes, None]:
"""Download a file or a directory from running instance as tar archive.
Streams the specified path inside the running instance root filesystem
as a POSIX PAX
tar archive. A directory becomes the archive root; a regular file
becomes
a single-entry archive. The response is chunked; total size is not known
upfront. Served as an attachment, ``filename`` is the path with ``/``
replaced
by ``_`` plus ``.tar`` (e.g. ``/bin/true`` -> ``bin_true.tar``).
Requires LIST and the permission used to start this instance.
Contents do not enter operation events. Reads do not form a snapshot.
Traversal skips procfs and sysfs and preserves descendant symlinks.
File changes or VM exit can interrupt the stream. Transfers have a
300-second deadline.
Args:
operation_uuid: The UUID of the running instance to inspect
Example: ``12345678-9abc-baba-deda-0123456789ab``.
path: The path of the file or directory to archive inside the
running instance, e.g. ``/etc``
compressed: disable transparent decompression: the body is
yielded exactly as served - a tar.gz stream when the server
compresses the response, a plain tar otherwise.
"""
spec = operations.build_inspect_instance_archive(
operation_uuid=operation_uuid, path=path
)
self.log_request(spec)
async with aclosing(
self.stream(spec, auto_decompress=not compressed)
) as source:
async for chunk in source:
self.log.debug("stream chunk: %d bytes", len(chunk))
yield chunk
[docs]
async def check_instance_archive(self, operation_uuid: str, path: str) -> bool:
"""Check if a path can be archived from running instance.
Checks if a file or a directory exists in the specified running instance
without streaming the archive
Args:
operation_uuid: The UUID of the running instance to inspect
Example: ``12345678-9abc-baba-deda-0123456789ab``.
path: The path of the file or directory to check inside the
running instance, e.g. ``/etc``
"""
spec = operations.build_check_instance_archive(
operation_uuid=operation_uuid, path=path
)
self.log_request(spec)
try:
response = await self.call(spec)
except NotFoundError:
return False
self.log_response(spec, response)
return operations.parse_check_instance_archive(response)
[docs]
async def inspect_find_image_by_tag(self, tag: str) -> str:
"""Find image by tag.
Redirects to the image inspection endpoint for the specified tag
Args:
tag: The tag of the image to inspect
"""
spec = operations.build_inspect_find_image_by_tag(tag=tag)
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_inspect_find_image_by_tag(response)
[docs]
async def inspect_image(self, image_uuid: str) -> Image:
"""Inspect an image.
Returns image metadata
Args:
image_uuid: The UUID of the image to inspect Example:
``12345678-9abc-baba-deda-0123456789ab``.
"""
spec = operations.build_inspect_image(image_uuid=image_uuid)
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_inspect_image(response)
[docs]
async def inspect_image_download(self, image_uuid: str, path: str) -> bytes:
"""Download a file from image.
Returns file content
Args:
image_uuid: The UUID of the image to inspect Example:
``12345678-9abc-baba-deda-0123456789ab``.
path: The path of the file to inspect inside the image, e.g.
``/etc/hosts``
"""
spec = operations.build_inspect_image_download(image_uuid=image_uuid, path=path)
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_inspect_image_download(response)
[docs]
async def inspect_image_download_stream(
self, image_uuid: str, path: str
) -> AsyncGenerator[bytes, None]:
"""Streaming variant of ``inspect_image_download()``.
Returns file content
Args:
image_uuid: The UUID of the image to inspect Example:
``12345678-9abc-baba-deda-0123456789ab``.
path: The path of the file to inspect inside the image, e.g.
``/etc/hosts``
"""
spec = operations.build_inspect_image_download(image_uuid=image_uuid, path=path)
self.log_request(spec)
async with aclosing(self.stream(spec)) as source:
async for chunk in source:
self.log.debug("stream chunk: %d bytes", len(chunk))
yield chunk
[docs]
async def check_image_file(self, image_uuid: str, path: str) -> bool:
"""Check if a file exists in image.
Checks if a file exists in the specified image without returning the
file content
Args:
image_uuid: The UUID of the image to inspect Example:
``12345678-9abc-baba-deda-0123456789ab``.
path: The path of the file to check inside the image, e.g.
``/etc/hosts``
"""
spec = operations.build_check_image_file(image_uuid=image_uuid, path=path)
self.log_request(spec)
try:
response = await self.call(spec)
except NotFoundError:
return False
self.log_response(spec, response)
return operations.parse_check_image_file(response)
[docs]
async def inspect_image_archive(
self, image_uuid: str, path: str, *, compressed: bool = False
) -> AsyncGenerator[bytes, None]:
"""Download a file or a directory from image as tar archive.
Streams the specified path inside the image root filesystem as a POSIX
PAX
tar archive. A directory becomes the archive root; a regular file
becomes
a single-entry archive. The response is chunked; total size is not known
upfront. Served as an attachment, ``filename`` is the path with ``/``
replaced
by ``_`` plus ``.tar`` (e.g. ``/bin/true`` -> ``bin_true.tar``).
Args:
image_uuid: The UUID of the image to inspect Example:
``12345678-9abc-baba-deda-0123456789ab``.
path: The path of the file or directory to archive inside the
image, e.g. ``/etc``
compressed: disable transparent decompression: the body is
yielded exactly as served - a tar.gz stream when the server
compresses the response, a plain tar otherwise.
"""
spec = operations.build_inspect_image_archive(image_uuid=image_uuid, path=path)
self.log_request(spec)
async with aclosing(
self.stream(spec, auto_decompress=not compressed)
) as source:
async for chunk in source:
self.log.debug("stream chunk: %d bytes", len(chunk))
yield chunk
[docs]
async def check_image_archive(self, image_uuid: str, path: str) -> bool:
"""Check if a path can be archived from image.
Checks if a file or a directory exists in the specified image without
streaming the archive
Args:
image_uuid: The UUID of the image to inspect Example:
``12345678-9abc-baba-deda-0123456789ab``.
path: The path of the file or directory to check inside the
image, e.g. ``/etc``
"""
spec = operations.build_check_image_archive(image_uuid=image_uuid, path=path)
self.log_request(spec)
try:
response = await self.call(spec)
except NotFoundError:
return False
self.log_response(spec, response)
return operations.parse_check_image_archive(response)
[docs]
async def inspect_image_list(self, image_uuid: str, path: str) -> DirectoryList:
"""List files in image.
Returns files list
Args:
image_uuid: The UUID of the image to inspect Example:
``12345678-9abc-baba-deda-0123456789ab``.
path: The path of the directory to inspect inside the image
Example: ``/etc``.
"""
spec = operations.build_inspect_image_list(image_uuid=image_uuid, path=path)
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_inspect_image_list(response)
[docs]
async def inspect_instance_grep(
self,
operation_uuid: str,
pattern: str | Sequence[str],
*,
path: str | Sequence[str] | None = None,
glob: str | Sequence[str] | None = None,
max_count: int | None = None,
max_total: int | None = None,
case: Literal["sensitive", "insensitive", "smart"] | None = None,
before: int | None = None,
after: int | None = None,
) -> GrepResult:
"""Search file contents in running instance.
Regex content search inside the running instance's root filesystem,
through guest RPC.
A Go converter translates supported Rust regex syntax to Go regexp.
Symlinks are never followed during traversal, hidden files are searched,
``.ignore`` and ``.gitignore`` rules within each search root are
respected.
A NUL byte in the first 64 KiB causes a file to be skipped; a later NUL
ends that file's search. Go regexp uses linear-time matching.
The classes \\w/\\W, \\d/\\D, and \\s/\\S use Unicode semantics.
Unicode properties and case folding are pinned to Unicode 16.0.0,
matching the image engine.
Scoped flags, nested class set operations, and bounded expansion of
large repetitions are supported.
Expanded patterns share a 1 MiB limit per request. Unsupported syntax
returns 400 with a pattern
index and byte offset. Unicode \\b/\\B, CRLF mode, non-ASCII byte mode,
and \\Q…\\E are rejected.
Use (?-u:\\b) for an ASCII word boundary. Smart case examines parsed
literals.
Results are a flat, file-ordered list of lines. ``before``/``after``
request extra
``type: context`` lines around each ``type: match`` line, mirroring
ripgrep's
--json message type field.
``path`` may be repeated to search multiple roots in one call, the same
way
``pattern``/``glob`` already can; results are concatenated in the given
order
and share the ``max_total`` budget across all of them.
Results never enter operation events. Reads are live and do not form a
snapshot.
procfs, sysfs, devices, sockets, and FIFOs are not searched.
Requires LIST and the permission used to start this instance.
Searches have a 10-second budget per root and permit two concurrent
searches per instance. Reaching the time, depth, or result limit sets
``truncated``. Context lines count towards ``max_total``. Display text
is
limited to 4096 bytes per line; matching can continue beyond this
window.
Args:
operation_uuid: The UUID of the running instance to inspect
Example: ``12345678-9abc-baba-deda-0123456789ab``.
pattern: Regex pattern to search for. May be repeated (max 16);
patterns are OR-ed. Max 1024 characters each. Example:
``^PermitRootLogin``.
path: File or directory to search inside the running instance.
May be repeated (max 16) to search multiple roots; results
are concatenated in the given order, sharing max_total
across all paths. Defaults to the rootfs root. Example:
``/etc``.
glob: Glob to filter files (ripgrep -g semantics, "!" negates).
May be repeated. Example: ``*.conf``.
max_count: Maximum matches per file (hard cap 10000).
max_total: Maximum total matches across all files (default 1000,
hard cap 10000).
case: Case sensitivity mode.
before: Lines of context to include before each match (ripgrep
-B semantics, hard cap 50). For symmetric context (grep -C
n), pass both before and after yourself.
after: Lines of context to include after each match (ripgrep -A
semantics, hard cap 50).
"""
spec = operations.build_inspect_instance_grep(
operation_uuid=operation_uuid,
pattern=pattern,
path=path,
glob=glob,
max_count=max_count,
max_total=max_total,
case=case,
before=before,
after=after,
)
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_inspect_instance_grep(response)
[docs]
async def inspect_image_grep(
self,
image_uuid: str,
pattern: str | Sequence[str],
*,
path: str | Sequence[str] | None = None,
glob: str | Sequence[str] | None = None,
max_count: int | None = None,
max_total: int | None = None,
case: Literal["sensitive", "insensitive", "smart"] | None = None,
before: int | None = None,
after: int | None = None,
) -> GrepResult:
"""Search file contents in image.
Regex content search inside the image's root filesystem, powered by
ripgrep.
Symlinks are never followed during traversal, hidden files are searched,
``.gitignore``-style files inside the image are ignored, and binary
files
(containing a NUL byte) are skipped. Rust regex syntax, linear-time
matching.
Results are a flat, file-ordered list of lines. ``before``/``after``
request extra
``type: context`` lines around each ``type: match`` line, mirroring
ripgrep's
--json message type field.
``path`` may be repeated to search multiple roots in one call, the same
way
``pattern``/``glob`` already can; results are concatenated in the given
order
and share the ``max_total`` budget across all of them.
Args:
image_uuid: The UUID of the image to inspect Example:
``12345678-9abc-baba-deda-0123456789ab``.
pattern: Regex pattern to search for. May be repeated (max 16);
patterns are OR-ed. Max 1024 characters each. Example:
``^PermitRootLogin``.
path: File or directory to search inside the image. May be
repeated (max 16) to search multiple roots; results are
concatenated in the given order, sharing max_total across
all paths. Defaults to the rootfs root. Example: ``/etc``.
glob: Glob to filter files (ripgrep -g semantics, "!" negates).
May be repeated. Example: ``*.conf``.
max_count: Maximum matches per file (hard cap 10000).
max_total: Maximum total matches across all files (default 1000,
hard cap 10000).
case: Case sensitivity mode.
before: Lines of context to include before each match (ripgrep
-B semantics, hard cap 50). For symmetric context (grep -C
n), pass both before and after yourself.
after: Lines of context to include after each match (ripgrep -A
semantics, hard cap 50).
"""
spec = operations.build_inspect_image_grep(
image_uuid=image_uuid,
pattern=pattern,
path=path,
glob=glob,
max_count=max_count,
max_total=max_total,
case=case,
before=before,
after=after,
)
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_inspect_image_grep(response)
[docs]
async def whoami(self) -> WhoAmIResponse:
"""Get current token information.
Returns information about the current authentication token, including
the token UUID, expiration time, and a map of all known permissions
with their granted status.
"""
spec = operations.build_whoami()
self.log_request(spec)
response = await self.call(spec)
self.log_response(spec, response)
return operations.parse_whoami(response)