armnet-client 0.3.5__1-py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- armnet_client/__init__.py +95 -0
- armnet_client/_config.py +31 -0
- armnet_client/_credential_cache.py +94 -0
- armnet_client/camera_aim.py +62 -0
- armnet_client/cli.py +396 -0
- armnet_client/client.py +243 -0
- armnet_client/current_gate.py +354 -0
- armnet_client/current_gate_datasets.json +4 -0
- armnet_client/current_gate_profile.json +76 -0
- armnet_client/eval_support/__init__.py +47 -0
- armnet_client/eval_support/dataset.py +240 -0
- armnet_client/eval_support/engage.py +84 -0
- armnet_client/eval_support/recovery.py +90 -0
- armnet_client/eval_support/robot.py +117 -0
- armnet_client/eval_support/rollout.py +15 -0
- armnet_client/execute.py +427 -0
- armnet_client/groot_eval.py +249 -0
- armnet_client/image.py +753 -0
- armnet_client/instrumentation.py +78 -0
- armnet_client/keypoint_capture.py +33 -0
- armnet_client/lerobot_eval.py +444 -0
- armnet_client/lerobot_record.py +627 -0
- armnet_client/lerobot_teleop.py +657 -0
- armnet_client/lerobot_train.py +375 -0
- armnet_client/local.py +194 -0
- armnet_client/local_container.py +670 -0
- armnet_client/openpi_eval.py +344 -0
- armnet_client/policy_eval.py +176 -0
- armnet_client/rerun_stream.py +211 -0
- armnet_client/robot_telemetry/__init__.py +21 -0
- armnet_client/robot_telemetry/inspect.py +296 -0
- armnet_client/robot_telemetry/schema.py +666 -0
- armnet_client/robot_telemetry/session.py +810 -0
- armnet_client/robot_telemetry/writer.py +356 -0
- armnet_client/runtime_build.py +210 -0
- armnet_client/runtime_groot_eval/Dockerfile +63 -0
- armnet_client/runtime_groot_eval/groot_eval_runtime.py +854 -0
- armnet_client/runtime_lerobot_eval/.dockerignore +15 -0
- armnet_client/runtime_lerobot_eval/Dockerfile +86 -0
- armnet_client/runtime_lerobot_eval/diffusion_resolution_patch.py +126 -0
- armnet_client/runtime_lerobot_eval/install_molmoact2_plugin.py +287 -0
- armnet_client/runtime_lerobot_eval/lerobot_eval_runtime.py +986 -0
- armnet_client/runtime_lerobot_eval/state_guard.py +210 -0
- armnet_client/runtime_lerobot_record/Dockerfile +62 -0
- armnet_client/runtime_lerobot_record/lerobot_record_runtime.py +1069 -0
- armnet_client/runtime_lerobot_teleop/Dockerfile +58 -0
- armnet_client/runtime_lerobot_teleop/lerobot_teleop_runtime.py +351 -0
- armnet_client/runtime_openpi_eval/Dockerfile +90 -0
- armnet_client/runtime_openpi_eval/openpi_eval_runtime.py +728 -0
- armnet_client/runtime_openpi_eval/state_guard.py +216 -0
- armnet_client/teleop_stream.py +642 -0
- armnet_client/variation.py +225 -0
- armnet_client/volume.py +105 -0
- armnet_client-0.3.5.dist-info/METADATA +69 -0
- armnet_client-0.3.5.dist-info/RECORD +58 -0
- armnet_client-0.3.5.dist-info/WHEEL +6 -0
- armnet_client-0.3.5.dist-info/entry_points.txt +9 -0
- armnet_client-0.3.5.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""armnet client SDK \u2014 submit jobs to the platform.
|
|
2
|
+
|
|
3
|
+
Top-level surface:
|
|
4
|
+
|
|
5
|
+
- :func:`execute` \u2014 submit one job, block until done.
|
|
6
|
+
- :func:`execute_many` \u2014 submit many in parallel, stream results.
|
|
7
|
+
- :func:`execute_local` \u2014 run a `@main` script in the current Python
|
|
8
|
+
process; bypasses Docker, NATS, and the orchestrator.
|
|
9
|
+
- :class:`Image` \u2014 build a Docker image with content-hash caching.
|
|
10
|
+
- :class:`OrchestratorClient` \u2014 lower-level HTTP wrapper.
|
|
11
|
+
|
|
12
|
+
Wire types are re-exported from :mod:`armnet_core` for ergonomics.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from importlib.metadata import PackageNotFoundError as _PackageNotFound
|
|
16
|
+
from importlib.metadata import version as _package_version
|
|
17
|
+
|
|
18
|
+
from armnet_core import (
|
|
19
|
+
CellRuntimeStatus,
|
|
20
|
+
CellStatus,
|
|
21
|
+
CellStatusSummary,
|
|
22
|
+
Embodiment,
|
|
23
|
+
Job,
|
|
24
|
+
JobResult,
|
|
25
|
+
JobSpec,
|
|
26
|
+
JobStatus,
|
|
27
|
+
RegistryCredentials,
|
|
28
|
+
RemoteExecutionError,
|
|
29
|
+
SecretCreateRequest,
|
|
30
|
+
SecretInfo,
|
|
31
|
+
SecretList,
|
|
32
|
+
Task,
|
|
33
|
+
TerminalStatus,
|
|
34
|
+
WhoAmI,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
from armnet_client.client import OrchestratorClient, OrchestratorError
|
|
38
|
+
from armnet_client.execute import execute, execute_many
|
|
39
|
+
from armnet_client.image import (
|
|
40
|
+
Image,
|
|
41
|
+
ImageBuildError,
|
|
42
|
+
ImageOwnershipError,
|
|
43
|
+
ImagePushError,
|
|
44
|
+
RegistryCredentialsUnavailableError,
|
|
45
|
+
)
|
|
46
|
+
from armnet_client.local import execute_local
|
|
47
|
+
from armnet_client.local_container import LocalContext, execute_local_container
|
|
48
|
+
from armnet_client.rerun_stream import init_rerun
|
|
49
|
+
from armnet_client.teleop_stream import (
|
|
50
|
+
TeleoperatorConfig,
|
|
51
|
+
start_recording_key_listener,
|
|
52
|
+
stream_job_teleop,
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
__all__ = [
|
|
56
|
+
"Embodiment",
|
|
57
|
+
"CellRuntimeStatus",
|
|
58
|
+
"CellStatus",
|
|
59
|
+
"CellStatusSummary",
|
|
60
|
+
"Image",
|
|
61
|
+
"ImageBuildError",
|
|
62
|
+
"ImageOwnershipError",
|
|
63
|
+
"ImagePushError",
|
|
64
|
+
"Job",
|
|
65
|
+
"JobResult",
|
|
66
|
+
"JobSpec",
|
|
67
|
+
"JobStatus",
|
|
68
|
+
"LocalContext",
|
|
69
|
+
"OrchestratorClient",
|
|
70
|
+
"OrchestratorError",
|
|
71
|
+
"RegistryCredentials",
|
|
72
|
+
"RegistryCredentialsUnavailableError",
|
|
73
|
+
"RemoteExecutionError",
|
|
74
|
+
"SecretCreateRequest",
|
|
75
|
+
"SecretInfo",
|
|
76
|
+
"SecretList",
|
|
77
|
+
"Task",
|
|
78
|
+
"TeleoperatorConfig",
|
|
79
|
+
"TerminalStatus",
|
|
80
|
+
"WhoAmI",
|
|
81
|
+
"execute",
|
|
82
|
+
"execute_local",
|
|
83
|
+
"execute_local_container",
|
|
84
|
+
"execute_many",
|
|
85
|
+
"init_rerun",
|
|
86
|
+
"start_recording_key_listener",
|
|
87
|
+
"stream_job_teleop",
|
|
88
|
+
]
|
|
89
|
+
|
|
90
|
+
# Read from installed metadata so the version lives in pyproject.toml only; a
|
|
91
|
+
# second hand-edited copy here is one more thing to forget on a release.
|
|
92
|
+
try:
|
|
93
|
+
__version__ = _package_version("armnet-client")
|
|
94
|
+
except _PackageNotFound: # running from a source tree with nothing installed
|
|
95
|
+
__version__ = "0.0.0+unknown"
|
armnet_client/_config.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""SDK configuration.
|
|
2
|
+
|
|
3
|
+
The production orchestrator URL is built into the public SDK so normal users do
|
|
4
|
+
not configure infrastructure endpoints. ``DEBUG_ARMNET_ORCHESTRATOR_URI`` is
|
|
5
|
+
the single development/CI override for a locally running stack.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
|
|
12
|
+
from armnet_core import API_KEY_ENV
|
|
13
|
+
|
|
14
|
+
DEFAULT_ORCHESTRATOR_URL = "https://armnet-orchestrator-240868335442.europe-west2.run.app"
|
|
15
|
+
|
|
16
|
+
DEBUG_OVERRIDE_ENV = "DEBUG_ARMNET_ORCHESTRATOR_URI"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def orchestrator_url() -> str:
|
|
20
|
+
"""Resolve the orchestrator base URL.
|
|
21
|
+
|
|
22
|
+
Returns the env-var override if set, otherwise the SDK default.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
return os.environ.get(DEBUG_OVERRIDE_ENV) or DEFAULT_ORCHESTRATOR_URL
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def api_key() -> str | None:
|
|
29
|
+
"""Resolve the API key used for authenticated orchestrator requests."""
|
|
30
|
+
|
|
31
|
+
return os.environ.get(API_KEY_ENV)
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""On-disk cache for image-registry credentials.
|
|
2
|
+
|
|
3
|
+
The orchestrator mints OAuth2 access tokens that are valid for ~1 hour.
|
|
4
|
+
Re-fetching one on every ``Image.push()`` call would be wasteful (extra
|
|
5
|
+
round-trip; rate limits when iterating quickly). This module caches the
|
|
6
|
+
last fetched :class:`RegistryCredentials` at
|
|
7
|
+
``~/.cache/remoterobo/registry-credentials.json`` (or
|
|
8
|
+
``$XDG_CACHE_HOME/armnet/...``) with mode 0600 since the token is
|
|
9
|
+
sensitive.
|
|
10
|
+
|
|
11
|
+
Keep the cache simple and process-safe-by-pessimism: every reader
|
|
12
|
+
re-validates expiry, so the worst race (two writers clobbering each
|
|
13
|
+
other) just means an extra fetch.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import logging
|
|
19
|
+
import os
|
|
20
|
+
from datetime import datetime, timedelta, timezone
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from typing import Optional
|
|
23
|
+
|
|
24
|
+
from armnet_core import RegistryCredentials
|
|
25
|
+
|
|
26
|
+
logger = logging.getLogger(__name__)
|
|
27
|
+
|
|
28
|
+
# Refresh credentials when this close to expiring.
|
|
29
|
+
_REFRESH_MARGIN = timedelta(minutes=5)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _cache_dir() -> Path:
|
|
33
|
+
base = os.environ.get("XDG_CACHE_HOME")
|
|
34
|
+
return Path(base) / "armnet" if base else Path.home() / ".cache" / "armnet"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _cache_path() -> Path:
|
|
38
|
+
return _cache_dir() / "registry-credentials.json"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def load() -> Optional[RegistryCredentials]:
|
|
42
|
+
"""Return the cached credentials, or ``None`` if missing / malformed /
|
|
43
|
+
expiring within :data:`_REFRESH_MARGIN`.
|
|
44
|
+
|
|
45
|
+
Never raises \u2014 a corrupt cache file is treated as a cache miss.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
path = _cache_path()
|
|
49
|
+
if not path.exists():
|
|
50
|
+
return None
|
|
51
|
+
|
|
52
|
+
try:
|
|
53
|
+
creds = RegistryCredentials.model_validate_json(path.read_text())
|
|
54
|
+
except Exception as exc: # noqa: BLE001
|
|
55
|
+
logger.debug("ignoring malformed credential cache at %s: %s", path, exc)
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
expires_at = creds.expires_at
|
|
59
|
+
if expires_at.tzinfo is None:
|
|
60
|
+
expires_at = expires_at.replace(tzinfo=timezone.utc)
|
|
61
|
+
if expires_at - datetime.now(timezone.utc) < _REFRESH_MARGIN:
|
|
62
|
+
return None
|
|
63
|
+
|
|
64
|
+
return creds
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def save(creds: RegistryCredentials) -> None:
|
|
68
|
+
"""Persist ``creds`` to the cache file with 0600 permissions.
|
|
69
|
+
|
|
70
|
+
Best-effort \u2014 on systems where ``chmod`` doesn't apply (Windows) the
|
|
71
|
+
permission step is silently skipped. We write to a temp file in the
|
|
72
|
+
same directory and rename so partial writes can't corrupt the cache.
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
path = _cache_path()
|
|
76
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
77
|
+
|
|
78
|
+
tmp = path.with_suffix(path.suffix + ".tmp")
|
|
79
|
+
tmp.write_text(creds.model_dump_json())
|
|
80
|
+
try:
|
|
81
|
+
tmp.chmod(0o600)
|
|
82
|
+
except OSError:
|
|
83
|
+
pass
|
|
84
|
+
tmp.replace(path)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def clear() -> None:
|
|
88
|
+
"""Remove the cache file. No-op if it doesn't exist."""
|
|
89
|
+
|
|
90
|
+
path = _cache_path()
|
|
91
|
+
try:
|
|
92
|
+
path.unlink()
|
|
93
|
+
except FileNotFoundError:
|
|
94
|
+
pass
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Client side of the per-job camera aim override.
|
|
2
|
+
|
|
3
|
+
``top.pan=0.55,front.tilt=0.4`` becomes the job's ``camera_aim`` arg. Values
|
|
4
|
+
are a fraction of each axis's travel, the same 0–1 scale as ``--armnet.rail``:
|
|
5
|
+
0 is the low stopper, 1 is the high stopper. Only the shape and that range are
|
|
6
|
+
checked here. The cell maps the fraction onto that mount's own unit (encoder
|
|
7
|
+
steps or hobby degrees) at job start, before anything moves. An axis left out
|
|
8
|
+
stays on its calibrated centre.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import math
|
|
14
|
+
from typing import Any, Mapping, Optional
|
|
15
|
+
|
|
16
|
+
_AXES = ("pan", "tilt")
|
|
17
|
+
_FORMAT = "<camera>.<pan|tilt>=<0-1>[,...], e.g. top.pan=0.55,front.tilt=0.4"
|
|
18
|
+
_EPSILON = 1e-9
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def camera_aim_job_args(
|
|
22
|
+
spec: Optional[str], job_args: Optional[Mapping[str, Any]] = None
|
|
23
|
+
) -> dict[str, Any]:
|
|
24
|
+
"""Parse a camera aim spec into job args; an axis left out stays centred.
|
|
25
|
+
|
|
26
|
+
``job_args`` are the eval's scene-variation args. An aim is refused
|
|
27
|
+
alongside camera variation, which re-aims every camera each episode around
|
|
28
|
+
its calibrated centre and would silently discard it.
|
|
29
|
+
"""
|
|
30
|
+
if spec is None or not spec.strip():
|
|
31
|
+
return {}
|
|
32
|
+
job_args = job_args or {}
|
|
33
|
+
if job_args.get("variation_cameras", job_args.get("variation", False)):
|
|
34
|
+
raise ValueError(
|
|
35
|
+
"--armnet.camera-aim cannot be combined with camera variation, which "
|
|
36
|
+
"re-aims the cameras every episode; drop one or set "
|
|
37
|
+
"--armnet.variation-cameras=false"
|
|
38
|
+
)
|
|
39
|
+
aim: dict[str, dict[str, float]] = {}
|
|
40
|
+
for item in spec.split(","):
|
|
41
|
+
item = item.strip()
|
|
42
|
+
if not item:
|
|
43
|
+
continue
|
|
44
|
+
key, separator, raw_value = item.partition("=")
|
|
45
|
+
camera, dot, axis = key.strip().rpartition(".")
|
|
46
|
+
if not separator or not dot or not camera or axis not in _AXES:
|
|
47
|
+
raise ValueError(f"invalid camera aim {item!r}; expected {_FORMAT}")
|
|
48
|
+
try:
|
|
49
|
+
value = float(raw_value)
|
|
50
|
+
except ValueError as exc:
|
|
51
|
+
raise ValueError(
|
|
52
|
+
f"invalid camera aim {item!r}: {raw_value!r} is not a number in 0 to 1"
|
|
53
|
+
) from exc
|
|
54
|
+
if not math.isfinite(value) or value < -_EPSILON or value > 1.0 + _EPSILON:
|
|
55
|
+
raise ValueError(
|
|
56
|
+
f"invalid camera aim {item!r}: expected a fraction from 0 to 1"
|
|
57
|
+
)
|
|
58
|
+
axes = aim.setdefault(camera, {})
|
|
59
|
+
if axis in axes:
|
|
60
|
+
raise ValueError(f"camera aim sets {camera}.{axis} twice")
|
|
61
|
+
axes[axis] = min(1.0, max(0.0, value))
|
|
62
|
+
return {"camera_aim": aim} if aim else {}
|
armnet_client/cli.py
ADDED
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
"""Command-line interface for armnet."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import sys
|
|
7
|
+
import threading
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from uuid import UUID
|
|
10
|
+
|
|
11
|
+
from dotenv import load_dotenv
|
|
12
|
+
|
|
13
|
+
from armnet_core import API_KEY_ENV, Job, JobStatus
|
|
14
|
+
from armnet_client._config import api_key, orchestrator_url
|
|
15
|
+
from armnet_client.client import OrchestratorClient, OrchestratorError
|
|
16
|
+
from armnet_client.execute import LogStreamResult, _stream_job_logs
|
|
17
|
+
|
|
18
|
+
_ANSI_RED = "\033[31m"
|
|
19
|
+
_ANSI_RESET = "\033[0m"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _colorize(text: str, *, red: bool) -> str:
|
|
23
|
+
"""Wrap ``text`` in red when it's a failure and we're writing to a terminal.
|
|
24
|
+
|
|
25
|
+
Successes stay the terminal's default colour; colour codes are skipped when
|
|
26
|
+
stdout isn't a TTY (so piped/redirected output stays clean).
|
|
27
|
+
"""
|
|
28
|
+
if red and sys.stdout.isatty():
|
|
29
|
+
return f"{_ANSI_RED}{text}{_ANSI_RESET}"
|
|
30
|
+
return text
|
|
31
|
+
from armnet_client.volume import (
|
|
32
|
+
delete_from_cloud_volume,
|
|
33
|
+
download_from_cloud_volume,
|
|
34
|
+
list_cloud_volume,
|
|
35
|
+
upload_to_cloud_volume,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def main(argv: list[str] | None = None) -> int:
|
|
40
|
+
_load_dotenv()
|
|
41
|
+
parser = _build_parser()
|
|
42
|
+
args = parser.parse_args(argv)
|
|
43
|
+
try:
|
|
44
|
+
return args.func(args)
|
|
45
|
+
except OrchestratorError as exc:
|
|
46
|
+
print(exc, file=sys.stderr)
|
|
47
|
+
return 1
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
51
|
+
parser = argparse.ArgumentParser(prog="armnet")
|
|
52
|
+
subparsers = parser.add_subparsers(dest="command")
|
|
53
|
+
subparsers.required = True
|
|
54
|
+
|
|
55
|
+
whoami = subparsers.add_parser("whoami", help="Print the authenticated username")
|
|
56
|
+
whoami.set_defaults(func=_whoami)
|
|
57
|
+
|
|
58
|
+
jobs = subparsers.add_parser("jobs", help="Inspect your jobs")
|
|
59
|
+
jobs_sub = jobs.add_subparsers(dest="jobs_command")
|
|
60
|
+
jobs_sub.required = True
|
|
61
|
+
|
|
62
|
+
jobs_list = jobs_sub.add_parser("list", help="List your most recent jobs")
|
|
63
|
+
jobs_list.add_argument(
|
|
64
|
+
"--limit", type=int, default=10, help="Number of jobs to show (default 10)."
|
|
65
|
+
)
|
|
66
|
+
jobs_list.set_defaults(func=_jobs_list)
|
|
67
|
+
|
|
68
|
+
jobs_get = jobs_sub.add_parser(
|
|
69
|
+
"get", help="Show a job's details, status transitions, and result"
|
|
70
|
+
)
|
|
71
|
+
jobs_get.add_argument("job_id")
|
|
72
|
+
jobs_get.set_defaults(func=_jobs_get)
|
|
73
|
+
|
|
74
|
+
jobs_logs = jobs_sub.add_parser(
|
|
75
|
+
"logs",
|
|
76
|
+
help="Stream live logs for one of your jobs",
|
|
77
|
+
description=(
|
|
78
|
+
"Follow stdout (blue) and stderr (red) for one of your jobs. "
|
|
79
|
+
"You can connect to a job that is already running, including from "
|
|
80
|
+
"more than one machine. The job stays up while a log stream is "
|
|
81
|
+
"connected; closing the last stream of a non-detached job asks the "
|
|
82
|
+
"cell to stop it after a short grace period, same as closing the "
|
|
83
|
+
"terminal that submitted it. Lines from before you connect are not "
|
|
84
|
+
"stored yet."
|
|
85
|
+
),
|
|
86
|
+
)
|
|
87
|
+
jobs_logs.add_argument("job_id")
|
|
88
|
+
jobs_logs.set_defaults(func=_jobs_logs)
|
|
89
|
+
|
|
90
|
+
secret = subparsers.add_parser("secret", help="Manage user secrets")
|
|
91
|
+
secret_sub = secret.add_subparsers(dest="secret_command")
|
|
92
|
+
secret_sub.required = True
|
|
93
|
+
|
|
94
|
+
list_cmd = secret_sub.add_parser("list", help="List secret names")
|
|
95
|
+
list_cmd.set_defaults(func=_secret_list)
|
|
96
|
+
|
|
97
|
+
create_cmd = secret_sub.add_parser("create", help="Create or replace a secret")
|
|
98
|
+
create_cmd.add_argument("name")
|
|
99
|
+
create_cmd.add_argument("value")
|
|
100
|
+
create_cmd.set_defaults(func=_secret_create)
|
|
101
|
+
|
|
102
|
+
delete_cmd = secret_sub.add_parser("delete", help="Delete a secret")
|
|
103
|
+
delete_cmd.add_argument("name")
|
|
104
|
+
delete_cmd.set_defaults(func=_secret_delete)
|
|
105
|
+
|
|
106
|
+
volume = subparsers.add_parser("volume", help="Manage local armnet volumes")
|
|
107
|
+
volume_sub = volume.add_subparsers(dest="volume_command")
|
|
108
|
+
volume_sub.required = True
|
|
109
|
+
|
|
110
|
+
upload_cmd = volume_sub.add_parser("upload", help="Upload data into the current user's cloud volume")
|
|
111
|
+
upload_cmd.add_argument("local_path")
|
|
112
|
+
upload_cmd.add_argument("volume_path")
|
|
113
|
+
upload_cmd.add_argument("--overwrite", action="store_true")
|
|
114
|
+
upload_cmd.set_defaults(func=_volume_upload)
|
|
115
|
+
|
|
116
|
+
cp_cmd = volume_sub.add_parser("cp", help="Download data from the current user's cloud volume")
|
|
117
|
+
cp_cmd.add_argument("volume_path")
|
|
118
|
+
cp_cmd.add_argument("local_path")
|
|
119
|
+
cp_cmd.set_defaults(func=_volume_cp)
|
|
120
|
+
|
|
121
|
+
delete_cmd = volume_sub.add_parser("delete", help="Delete data from the current user's cloud volume")
|
|
122
|
+
delete_cmd.add_argument("volume_path")
|
|
123
|
+
delete_cmd.set_defaults(func=_volume_delete)
|
|
124
|
+
|
|
125
|
+
ls_cmd = volume_sub.add_parser("ls", help="List the contents of the current user's cloud volume")
|
|
126
|
+
ls_cmd.add_argument(
|
|
127
|
+
"volume_path", nargs="?", default=None, help="Optional sub-path to list (defaults to the whole volume)."
|
|
128
|
+
)
|
|
129
|
+
ls_cmd.set_defaults(func=_volume_ls)
|
|
130
|
+
|
|
131
|
+
return parser
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _whoami(_args: argparse.Namespace) -> int:
|
|
135
|
+
with OrchestratorClient(orchestrator_url()) as client:
|
|
136
|
+
print(client.whoami().username)
|
|
137
|
+
return 0
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _jobs_list(args: argparse.Namespace) -> int:
|
|
141
|
+
with OrchestratorClient(orchestrator_url()) as client:
|
|
142
|
+
jobs = client.list_jobs(limit=args.limit)
|
|
143
|
+
if not jobs:
|
|
144
|
+
print("No jobs found.")
|
|
145
|
+
return 0
|
|
146
|
+
print(
|
|
147
|
+
f"{'JOB ID':36} {'STATUS':11} {'EMBODIMENT':22} {'TASK':16} "
|
|
148
|
+
f"{'CELL':20} SUBMITTED"
|
|
149
|
+
)
|
|
150
|
+
for job in jobs:
|
|
151
|
+
submitted = job.created_at.strftime("%Y-%m-%d %H:%M:%S") if job.created_at else "-"
|
|
152
|
+
print(
|
|
153
|
+
f"{job.id:36} {job.status.value:11} "
|
|
154
|
+
f"{(job.spec.embodiment or '-'):22} {(job.spec.task or '-'):16} "
|
|
155
|
+
f"{_cell_label(job):20} {submitted}"
|
|
156
|
+
)
|
|
157
|
+
return 0
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _cell_label(job: Job) -> str:
|
|
161
|
+
"""Where the job ran, else the cell it is waiting for."""
|
|
162
|
+
if job.cell_id:
|
|
163
|
+
return job.cell_id
|
|
164
|
+
if job.spec.cell:
|
|
165
|
+
return f"{job.spec.cell} (requested)"
|
|
166
|
+
return "-"
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _jobs_get(args: argparse.Namespace) -> int:
|
|
170
|
+
with OrchestratorClient(orchestrator_url()) as client:
|
|
171
|
+
job = client.get(args.job_id)
|
|
172
|
+
transitions = client.get_status_transitions(args.job_id)
|
|
173
|
+
|
|
174
|
+
print(f"Job {job.id}")
|
|
175
|
+
print(f" status: {job.status.value}")
|
|
176
|
+
print(f" embodiment: {job.spec.embodiment}")
|
|
177
|
+
print(f" task: {job.spec.task or '-'}")
|
|
178
|
+
requested = f" (requested {job.spec.cell})" if job.spec.cell else ""
|
|
179
|
+
print(f" cell: {job.cell_id or '-'}{requested}")
|
|
180
|
+
print(f" image: {job.spec.image}")
|
|
181
|
+
if job.created_at:
|
|
182
|
+
print(f" submitted: {job.created_at.strftime('%Y-%m-%d %H:%M:%S')}")
|
|
183
|
+
|
|
184
|
+
print("\nStatus transitions:")
|
|
185
|
+
if transitions:
|
|
186
|
+
for t in transitions:
|
|
187
|
+
ts = t.timestamp.strftime("%Y-%m-%d %H:%M:%S") if t.timestamp else "-"
|
|
188
|
+
detail = f" ({t.detail})" if t.detail else ""
|
|
189
|
+
print(f" {ts} {t.status}{detail}")
|
|
190
|
+
else:
|
|
191
|
+
print(" (none recorded)")
|
|
192
|
+
|
|
193
|
+
print()
|
|
194
|
+
# Print the result the same way a armnet-client script does — in red for
|
|
195
|
+
# a failure, default terminal colour for a success.
|
|
196
|
+
if job.result is not None:
|
|
197
|
+
print(_colorize(str(job.result), red=(job.status != JobStatus.SUCCEEDED)))
|
|
198
|
+
else:
|
|
199
|
+
print(f"(no result yet; status={job.status.value})")
|
|
200
|
+
return 0
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _jobs_logs(args: argparse.Namespace) -> int:
|
|
204
|
+
if not api_key():
|
|
205
|
+
print(f"{API_KEY_ENV} is not set", file=sys.stderr)
|
|
206
|
+
return 1
|
|
207
|
+
# Decide before opening the log stream. The stream's status line otherwise
|
|
208
|
+
# treats a missing id as "waiting" and someone else's running job as
|
|
209
|
+
# "initialising", and a rejected stream is what asks a live job to stop.
|
|
210
|
+
if not _job_logs_visible(args.job_id):
|
|
211
|
+
print(f"job {args.job_id} not found", file=sys.stderr)
|
|
212
|
+
return 1
|
|
213
|
+
stop = threading.Event()
|
|
214
|
+
try:
|
|
215
|
+
result = _stream_job_logs(args.job_id, stop)
|
|
216
|
+
except KeyboardInterrupt:
|
|
217
|
+
return 0
|
|
218
|
+
return _log_stream_exit(args.job_id, result)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _job_logs_visible(job_id: str) -> bool:
|
|
222
|
+
"""True when this API key may follow ``job_id``.
|
|
223
|
+
|
|
224
|
+
Anything else is reported as not found: a missing id, an id that isn't a
|
|
225
|
+
job id, and another user's job. The last one must not be described
|
|
226
|
+
differently, or the message would confirm that the job exists.
|
|
227
|
+
"""
|
|
228
|
+
with OrchestratorClient(orchestrator_url()) as client:
|
|
229
|
+
me = client.whoami().username
|
|
230
|
+
try:
|
|
231
|
+
job = client.get(job_id)
|
|
232
|
+
except OrchestratorError as exc:
|
|
233
|
+
if exc.status_code == 404 or (
|
|
234
|
+
exc.status_code is not None and not _is_uuid(job_id)
|
|
235
|
+
):
|
|
236
|
+
return False
|
|
237
|
+
raise
|
|
238
|
+
return job.spec.username == me
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _is_uuid(value: str) -> bool:
|
|
242
|
+
try:
|
|
243
|
+
UUID(value)
|
|
244
|
+
except ValueError:
|
|
245
|
+
return False
|
|
246
|
+
return True
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _log_stream_exit(job_id: str, result: LogStreamResult) -> int:
|
|
250
|
+
"""Print why a log stream ended. Log lines themselves already went to stdout."""
|
|
251
|
+
if result.error == "unauthorized":
|
|
252
|
+
print(f"{API_KEY_ENV} was rejected", file=sys.stderr)
|
|
253
|
+
return 1
|
|
254
|
+
if result.error in ("forbidden", "not_found"):
|
|
255
|
+
print(f"job {job_id} not found", file=sys.stderr)
|
|
256
|
+
return 1
|
|
257
|
+
if result.error:
|
|
258
|
+
print(result.error, file=sys.stderr)
|
|
259
|
+
return 1
|
|
260
|
+
if result.terminal_status and not result.saw_log:
|
|
261
|
+
print(
|
|
262
|
+
f"job {job_id} is already {result.terminal_status}; earlier logs are not stored",
|
|
263
|
+
file=sys.stderr,
|
|
264
|
+
)
|
|
265
|
+
return 0
|
|
266
|
+
if result.terminal_status:
|
|
267
|
+
print(f"job {job_id} {result.terminal_status}", file=sys.stderr)
|
|
268
|
+
return 0
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _secret_list(_args: argparse.Namespace) -> int:
|
|
272
|
+
with OrchestratorClient(orchestrator_url()) as client:
|
|
273
|
+
secrets = client.list_secrets().secrets
|
|
274
|
+
for secret in secrets:
|
|
275
|
+
print(secret.name)
|
|
276
|
+
return 0
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _secret_create(args: argparse.Namespace) -> int:
|
|
280
|
+
with OrchestratorClient(orchestrator_url()) as client:
|
|
281
|
+
secret = client.create_secret(args.name, args.value)
|
|
282
|
+
print(secret.name)
|
|
283
|
+
return 0
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def _secret_delete(args: argparse.Namespace) -> int:
|
|
287
|
+
with OrchestratorClient(orchestrator_url()) as client:
|
|
288
|
+
client.delete_secret(args.name)
|
|
289
|
+
return 0
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _volume_upload(args: argparse.Namespace) -> int:
|
|
293
|
+
with OrchestratorClient(orchestrator_url()) as client:
|
|
294
|
+
username = client.whoami().username
|
|
295
|
+
creds = client.get_volume_credentials()
|
|
296
|
+
uploaded = upload_to_cloud_volume(
|
|
297
|
+
credentials=creds,
|
|
298
|
+
username=username,
|
|
299
|
+
local_path=args.local_path,
|
|
300
|
+
volume_path=args.volume_path,
|
|
301
|
+
overwrite=args.overwrite,
|
|
302
|
+
)
|
|
303
|
+
if uploaded:
|
|
304
|
+
for item in uploaded:
|
|
305
|
+
print(item)
|
|
306
|
+
else:
|
|
307
|
+
print("already up to date")
|
|
308
|
+
return 0
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _volume_cp(args: argparse.Namespace) -> int:
|
|
312
|
+
with OrchestratorClient(orchestrator_url()) as client:
|
|
313
|
+
username = client.whoami().username
|
|
314
|
+
creds = client.get_volume_credentials()
|
|
315
|
+
dest = download_from_cloud_volume(
|
|
316
|
+
credentials=creds,
|
|
317
|
+
username=username,
|
|
318
|
+
volume_path=args.volume_path,
|
|
319
|
+
local_path=args.local_path,
|
|
320
|
+
)
|
|
321
|
+
print(dest)
|
|
322
|
+
return 0
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _volume_delete(args: argparse.Namespace) -> int:
|
|
326
|
+
with OrchestratorClient(orchestrator_url()) as client:
|
|
327
|
+
creds = client.get_volume_credentials()
|
|
328
|
+
delete_from_cloud_volume(credentials=creds, volume_path=args.volume_path)
|
|
329
|
+
return 0
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _volume_ls(args: argparse.Namespace) -> int:
|
|
333
|
+
with OrchestratorClient(orchestrator_url()) as client:
|
|
334
|
+
username = client.whoami().username
|
|
335
|
+
creds = client.get_volume_credentials()
|
|
336
|
+
entries = list_cloud_volume(credentials=creds, volume_path=args.volume_path)
|
|
337
|
+
root_label = f"{username}/{args.volume_path}" if args.volume_path else f"{username}/"
|
|
338
|
+
if not entries:
|
|
339
|
+
print(f"{root_label} (empty)")
|
|
340
|
+
return 0
|
|
341
|
+
for line in _render_tree(entries):
|
|
342
|
+
print(line)
|
|
343
|
+
total = sum(size for _, size in entries)
|
|
344
|
+
print(f"\n{len(entries)} file(s), {_human_bytes(total)}")
|
|
345
|
+
return 0
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def _render_tree(entries: list[tuple[str, int]]) -> list[str]:
|
|
349
|
+
"""Render ``(path, size)`` pairs as an indented directory tree."""
|
|
350
|
+
tree: dict = {}
|
|
351
|
+
for rel, size in entries:
|
|
352
|
+
node = tree
|
|
353
|
+
parts = rel.split("/")
|
|
354
|
+
for part in parts[:-1]:
|
|
355
|
+
node = node.setdefault(part, {}) # type: ignore[assignment]
|
|
356
|
+
node[parts[-1]] = size
|
|
357
|
+
|
|
358
|
+
lines: list[str] = []
|
|
359
|
+
|
|
360
|
+
def walk(node: dict, prefix: str) -> None:
|
|
361
|
+
items = sorted(node.items(), key=lambda kv: (isinstance(kv[1], int), kv[0]))
|
|
362
|
+
for index, (name, value) in enumerate(items):
|
|
363
|
+
last = index == len(items) - 1
|
|
364
|
+
connector = "└── " if last else "├── "
|
|
365
|
+
if isinstance(value, dict):
|
|
366
|
+
lines.append(f"{prefix}{connector}{name}/")
|
|
367
|
+
walk(value, prefix + (" " if last else "│ "))
|
|
368
|
+
else:
|
|
369
|
+
lines.append(f"{prefix}{connector}{name} ({_human_bytes(value)})")
|
|
370
|
+
|
|
371
|
+
walk(tree, "")
|
|
372
|
+
return lines
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def _human_bytes(num: float) -> str:
|
|
376
|
+
for unit in ("B", "KB", "MB", "GB", "TB"):
|
|
377
|
+
if num < 1024 or unit == "TB":
|
|
378
|
+
return f"{num:.0f} {unit}" if unit == "B" else f"{num:.1f} {unit}"
|
|
379
|
+
num /= 1024
|
|
380
|
+
return f"{num:.1f} TB"
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def _load_dotenv() -> None:
|
|
384
|
+
cwd = Path.cwd()
|
|
385
|
+
candidates = [
|
|
386
|
+
cwd / ".env",
|
|
387
|
+
cwd.parent / ".env",
|
|
388
|
+
]
|
|
389
|
+
for path in candidates:
|
|
390
|
+
if path.exists():
|
|
391
|
+
load_dotenv(path)
|
|
392
|
+
return
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
if __name__ == "__main__":
|
|
396
|
+
raise SystemExit(main())
|