armnet-client 0.1.0__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 +85 -0
- armnet_client/_config.py +41 -0
- armnet_client/_credential_cache.py +94 -0
- armnet_client/cli.py +236 -0
- armnet_client/client.py +237 -0
- armnet_client/execute.py +300 -0
- armnet_client/groot_eval.py +186 -0
- armnet_client/image.py +449 -0
- armnet_client/lerobot_eval.py +186 -0
- armnet_client/lerobot_record.py +286 -0
- armnet_client/lerobot_teleop.py +234 -0
- armnet_client/lerobot_train.py +375 -0
- armnet_client/local.py +171 -0
- armnet_client/local_container.py +659 -0
- armnet_client/openpi_eval.py +217 -0
- armnet_client/policy_eval.py +143 -0
- armnet_client/rerun_stream.py +207 -0
- armnet_client/runtime_groot_eval/Dockerfile +57 -0
- armnet_client/runtime_groot_eval/groot_eval_runtime.py +855 -0
- armnet_client/runtime_lerobot_eval/Dockerfile +58 -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 +608 -0
- armnet_client/runtime_lerobot_record/Dockerfile +31 -0
- armnet_client/runtime_lerobot_record/lerobot_record_runtime.py +632 -0
- armnet_client/runtime_lerobot_teleop/Dockerfile +31 -0
- armnet_client/runtime_lerobot_teleop/lerobot_teleop_runtime.py +206 -0
- armnet_client/runtime_openpi_eval/Dockerfile +73 -0
- armnet_client/runtime_openpi_eval/openpi_eval_runtime.py +714 -0
- armnet_client/teleop_stream.py +363 -0
- armnet_client/volume.py +197 -0
- armnet_client-0.1.0.dist-info/METADATA +59 -0
- armnet_client-0.1.0.dist-info/RECORD +35 -0
- armnet_client-0.1.0.dist-info/WHEEL +4 -0
- armnet_client-0.1.0.dist-info/entry_points.txt +8 -0
|
@@ -0,0 +1,85 @@
|
|
|
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 armnet_core import (
|
|
16
|
+
CellRuntimeStatus,
|
|
17
|
+
CellStatus,
|
|
18
|
+
CellStatusSummary,
|
|
19
|
+
Embodiment,
|
|
20
|
+
Job,
|
|
21
|
+
JobResult,
|
|
22
|
+
JobSpec,
|
|
23
|
+
JobStatus,
|
|
24
|
+
RegistryCredentials,
|
|
25
|
+
RemoteExecutionError,
|
|
26
|
+
SecretCreateRequest,
|
|
27
|
+
SecretInfo,
|
|
28
|
+
SecretList,
|
|
29
|
+
Task,
|
|
30
|
+
TerminalStatus,
|
|
31
|
+
WhoAmI,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
from armnet_client.client import OrchestratorClient, OrchestratorError
|
|
35
|
+
from armnet_client.execute import execute, execute_many
|
|
36
|
+
from armnet_client.image import (
|
|
37
|
+
Image,
|
|
38
|
+
ImageBuildError,
|
|
39
|
+
ImagePushError,
|
|
40
|
+
RegistryCredentialsUnavailableError,
|
|
41
|
+
)
|
|
42
|
+
from armnet_client.local import execute_local
|
|
43
|
+
from armnet_client.local_container import LocalContext, execute_local_container
|
|
44
|
+
from armnet_client.rerun_stream import init_rerun
|
|
45
|
+
from armnet_client.teleop_stream import (
|
|
46
|
+
TeleoperatorConfig,
|
|
47
|
+
start_recording_key_listener,
|
|
48
|
+
stream_job_teleop,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
__all__ = [
|
|
52
|
+
"Embodiment",
|
|
53
|
+
"CellRuntimeStatus",
|
|
54
|
+
"CellStatus",
|
|
55
|
+
"CellStatusSummary",
|
|
56
|
+
"Image",
|
|
57
|
+
"ImageBuildError",
|
|
58
|
+
"ImagePushError",
|
|
59
|
+
"Job",
|
|
60
|
+
"JobResult",
|
|
61
|
+
"JobSpec",
|
|
62
|
+
"JobStatus",
|
|
63
|
+
"LocalContext",
|
|
64
|
+
"OrchestratorClient",
|
|
65
|
+
"OrchestratorError",
|
|
66
|
+
"RegistryCredentials",
|
|
67
|
+
"RegistryCredentialsUnavailableError",
|
|
68
|
+
"RemoteExecutionError",
|
|
69
|
+
"SecretCreateRequest",
|
|
70
|
+
"SecretInfo",
|
|
71
|
+
"SecretList",
|
|
72
|
+
"Task",
|
|
73
|
+
"TeleoperatorConfig",
|
|
74
|
+
"TerminalStatus",
|
|
75
|
+
"WhoAmI",
|
|
76
|
+
"execute",
|
|
77
|
+
"execute_local",
|
|
78
|
+
"execute_local_container",
|
|
79
|
+
"execute_many",
|
|
80
|
+
"init_rerun",
|
|
81
|
+
"start_recording_key_listener",
|
|
82
|
+
"stream_job_teleop",
|
|
83
|
+
]
|
|
84
|
+
|
|
85
|
+
__version__ = "0.1.0"
|
armnet_client/_config.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""SDK configuration.
|
|
2
|
+
|
|
3
|
+
The orchestrator URL the client SDK targets is hard-coded into the SDK
|
|
4
|
+
build; customers do not pass it explicitly. A single env-var override is
|
|
5
|
+
provided for development and CI.
|
|
6
|
+
|
|
7
|
+
For the SDK as it lives in this repo (M0.5 / pre-release) the default
|
|
8
|
+
points at ``http://localhost:8000`` so that example scripts work
|
|
9
|
+
out-of-the-box when paired with a locally-running orchestrator. When we
|
|
10
|
+
publish to PyPI we'll replace the constant with the real Cloud Run URL
|
|
11
|
+
(or, more likely, inject it at build time).
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
|
|
18
|
+
from armnet_core import API_KEY_ENV
|
|
19
|
+
|
|
20
|
+
# TODO(armnet M1+): replace with the real orchestrator URL before
|
|
21
|
+
# publishing the SDK to PyPI. Consider sourcing from a build-time constant
|
|
22
|
+
# baked in by hatch (env var read at build, written into a generated
|
|
23
|
+
# module).
|
|
24
|
+
DEFAULT_ORCHESTRATOR_URL = "https://armnet-orchestrator-240868335442.europe-west2.run.app"
|
|
25
|
+
|
|
26
|
+
DEBUG_OVERRIDE_ENV = "DEBUG_ARMNET_ORCHESTRATOR_URI"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def orchestrator_url() -> str:
|
|
30
|
+
"""Resolve the orchestrator base URL.
|
|
31
|
+
|
|
32
|
+
Returns the env-var override if set, otherwise the SDK default.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
return os.environ.get(DEBUG_OVERRIDE_ENV) or DEFAULT_ORCHESTRATOR_URL
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def api_key() -> str | None:
|
|
39
|
+
"""Resolve the API key used for authenticated orchestrator requests."""
|
|
40
|
+
|
|
41
|
+
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
|
armnet_client/cli.py
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
"""Command-line interface for armnet."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from dotenv import load_dotenv
|
|
10
|
+
|
|
11
|
+
from armnet_core import JobStatus
|
|
12
|
+
from armnet_client._config import orchestrator_url
|
|
13
|
+
from armnet_client.client import OrchestratorClient, OrchestratorError
|
|
14
|
+
|
|
15
|
+
_ANSI_RED = "\033[31m"
|
|
16
|
+
_ANSI_RESET = "\033[0m"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _colorize(text: str, *, red: bool) -> str:
|
|
20
|
+
"""Wrap ``text`` in red when it's a failure and we're writing to a terminal.
|
|
21
|
+
|
|
22
|
+
Successes stay the terminal's default colour; colour codes are skipped when
|
|
23
|
+
stdout isn't a TTY (so piped/redirected output stays clean).
|
|
24
|
+
"""
|
|
25
|
+
if red and sys.stdout.isatty():
|
|
26
|
+
return f"{_ANSI_RED}{text}{_ANSI_RESET}"
|
|
27
|
+
return text
|
|
28
|
+
from armnet_client.volume import (
|
|
29
|
+
delete_from_cloud_volume,
|
|
30
|
+
download_from_cloud_volume,
|
|
31
|
+
upload_to_cloud_volume,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def main(argv: list[str] | None = None) -> int:
|
|
36
|
+
_load_dotenv()
|
|
37
|
+
parser = _build_parser()
|
|
38
|
+
args = parser.parse_args(argv)
|
|
39
|
+
try:
|
|
40
|
+
return args.func(args)
|
|
41
|
+
except OrchestratorError as exc:
|
|
42
|
+
print(exc, file=sys.stderr)
|
|
43
|
+
return 1
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
47
|
+
parser = argparse.ArgumentParser(prog="armnet")
|
|
48
|
+
subparsers = parser.add_subparsers(dest="command")
|
|
49
|
+
subparsers.required = True
|
|
50
|
+
|
|
51
|
+
whoami = subparsers.add_parser("whoami", help="Print the authenticated username")
|
|
52
|
+
whoami.set_defaults(func=_whoami)
|
|
53
|
+
|
|
54
|
+
jobs = subparsers.add_parser("jobs", help="Inspect your jobs")
|
|
55
|
+
jobs_sub = jobs.add_subparsers(dest="jobs_command")
|
|
56
|
+
jobs_sub.required = True
|
|
57
|
+
|
|
58
|
+
jobs_list = jobs_sub.add_parser("list", help="List your most recent jobs")
|
|
59
|
+
jobs_list.add_argument(
|
|
60
|
+
"--limit", type=int, default=10, help="Number of jobs to show (default 10)."
|
|
61
|
+
)
|
|
62
|
+
jobs_list.set_defaults(func=_jobs_list)
|
|
63
|
+
|
|
64
|
+
jobs_get = jobs_sub.add_parser(
|
|
65
|
+
"get", help="Show a job's details, status transitions, and result"
|
|
66
|
+
)
|
|
67
|
+
jobs_get.add_argument("job_id")
|
|
68
|
+
jobs_get.set_defaults(func=_jobs_get)
|
|
69
|
+
|
|
70
|
+
secret = subparsers.add_parser("secret", help="Manage user secrets")
|
|
71
|
+
secret_sub = secret.add_subparsers(dest="secret_command")
|
|
72
|
+
secret_sub.required = True
|
|
73
|
+
|
|
74
|
+
list_cmd = secret_sub.add_parser("list", help="List secret names")
|
|
75
|
+
list_cmd.set_defaults(func=_secret_list)
|
|
76
|
+
|
|
77
|
+
create_cmd = secret_sub.add_parser("create", help="Create or replace a secret")
|
|
78
|
+
create_cmd.add_argument("name")
|
|
79
|
+
create_cmd.add_argument("value")
|
|
80
|
+
create_cmd.set_defaults(func=_secret_create)
|
|
81
|
+
|
|
82
|
+
delete_cmd = secret_sub.add_parser("delete", help="Delete a secret")
|
|
83
|
+
delete_cmd.add_argument("name")
|
|
84
|
+
delete_cmd.set_defaults(func=_secret_delete)
|
|
85
|
+
|
|
86
|
+
volume = subparsers.add_parser("volume", help="Manage local armnet volumes")
|
|
87
|
+
volume_sub = volume.add_subparsers(dest="volume_command")
|
|
88
|
+
volume_sub.required = True
|
|
89
|
+
|
|
90
|
+
upload_cmd = volume_sub.add_parser("upload", help="Upload data into the current user's cloud volume")
|
|
91
|
+
upload_cmd.add_argument("local_path")
|
|
92
|
+
upload_cmd.add_argument("volume_path")
|
|
93
|
+
upload_cmd.add_argument("--overwrite", action="store_true")
|
|
94
|
+
upload_cmd.set_defaults(func=_volume_upload)
|
|
95
|
+
|
|
96
|
+
cp_cmd = volume_sub.add_parser("cp", help="Download data from the current user's cloud volume")
|
|
97
|
+
cp_cmd.add_argument("volume_path")
|
|
98
|
+
cp_cmd.add_argument("local_path")
|
|
99
|
+
cp_cmd.set_defaults(func=_volume_cp)
|
|
100
|
+
|
|
101
|
+
delete_cmd = volume_sub.add_parser("delete", help="Delete data from the current user's cloud volume")
|
|
102
|
+
delete_cmd.add_argument("volume_path")
|
|
103
|
+
delete_cmd.set_defaults(func=_volume_delete)
|
|
104
|
+
|
|
105
|
+
return parser
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _whoami(_args: argparse.Namespace) -> int:
|
|
109
|
+
with OrchestratorClient(orchestrator_url()) as client:
|
|
110
|
+
print(client.whoami().username)
|
|
111
|
+
return 0
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _jobs_list(args: argparse.Namespace) -> int:
|
|
115
|
+
with OrchestratorClient(orchestrator_url()) as client:
|
|
116
|
+
jobs = client.list_jobs(limit=args.limit)
|
|
117
|
+
if not jobs:
|
|
118
|
+
print("No jobs found.")
|
|
119
|
+
return 0
|
|
120
|
+
print(f"{'JOB ID':36} {'STATUS':11} {'EMBODIMENT':22} {'TASK':16} SUBMITTED")
|
|
121
|
+
for job in jobs:
|
|
122
|
+
submitted = job.created_at.strftime("%Y-%m-%d %H:%M:%S") if job.created_at else "-"
|
|
123
|
+
print(
|
|
124
|
+
f"{job.id:36} {job.status.value:11} "
|
|
125
|
+
f"{(job.spec.embodiment or '-'):22} {(job.spec.task or '-'):16} {submitted}"
|
|
126
|
+
)
|
|
127
|
+
return 0
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _jobs_get(args: argparse.Namespace) -> int:
|
|
131
|
+
with OrchestratorClient(orchestrator_url()) as client:
|
|
132
|
+
job = client.get(args.job_id)
|
|
133
|
+
transitions = client.get_status_transitions(args.job_id)
|
|
134
|
+
|
|
135
|
+
print(f"Job {job.id}")
|
|
136
|
+
print(f" status: {job.status.value}")
|
|
137
|
+
print(f" embodiment: {job.spec.embodiment}")
|
|
138
|
+
print(f" task: {job.spec.task or '-'}")
|
|
139
|
+
print(f" image: {job.spec.image}")
|
|
140
|
+
if job.created_at:
|
|
141
|
+
print(f" submitted: {job.created_at.strftime('%Y-%m-%d %H:%M:%S')}")
|
|
142
|
+
|
|
143
|
+
print("\nStatus transitions:")
|
|
144
|
+
if transitions:
|
|
145
|
+
for t in transitions:
|
|
146
|
+
ts = t.timestamp.strftime("%Y-%m-%d %H:%M:%S") if t.timestamp else "-"
|
|
147
|
+
detail = f" ({t.detail})" if t.detail else ""
|
|
148
|
+
print(f" {ts} {t.status}{detail}")
|
|
149
|
+
else:
|
|
150
|
+
print(" (none recorded)")
|
|
151
|
+
|
|
152
|
+
print()
|
|
153
|
+
# Print the result the same way a armnet-client script does — in red for
|
|
154
|
+
# a failure, default terminal colour for a success.
|
|
155
|
+
if job.result is not None:
|
|
156
|
+
print(_colorize(str(job.result), red=(job.status != JobStatus.SUCCEEDED)))
|
|
157
|
+
else:
|
|
158
|
+
print(f"(no result yet; status={job.status.value})")
|
|
159
|
+
return 0
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _secret_list(_args: argparse.Namespace) -> int:
|
|
163
|
+
with OrchestratorClient(orchestrator_url()) as client:
|
|
164
|
+
secrets = client.list_secrets().secrets
|
|
165
|
+
for secret in secrets:
|
|
166
|
+
print(secret.name)
|
|
167
|
+
return 0
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _secret_create(args: argparse.Namespace) -> int:
|
|
171
|
+
with OrchestratorClient(orchestrator_url()) as client:
|
|
172
|
+
secret = client.create_secret(args.name, args.value)
|
|
173
|
+
print(secret.name)
|
|
174
|
+
return 0
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _secret_delete(args: argparse.Namespace) -> int:
|
|
178
|
+
with OrchestratorClient(orchestrator_url()) as client:
|
|
179
|
+
client.delete_secret(args.name)
|
|
180
|
+
return 0
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _volume_upload(args: argparse.Namespace) -> int:
|
|
184
|
+
with OrchestratorClient(orchestrator_url()) as client:
|
|
185
|
+
username = client.whoami().username
|
|
186
|
+
creds = client.get_volume_credentials()
|
|
187
|
+
uploaded = upload_to_cloud_volume(
|
|
188
|
+
credentials=creds,
|
|
189
|
+
username=username,
|
|
190
|
+
local_path=args.local_path,
|
|
191
|
+
volume_path=args.volume_path,
|
|
192
|
+
overwrite=args.overwrite,
|
|
193
|
+
)
|
|
194
|
+
if uploaded:
|
|
195
|
+
for item in uploaded:
|
|
196
|
+
print(item)
|
|
197
|
+
else:
|
|
198
|
+
print("already up to date")
|
|
199
|
+
return 0
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _volume_cp(args: argparse.Namespace) -> int:
|
|
203
|
+
with OrchestratorClient(orchestrator_url()) as client:
|
|
204
|
+
username = client.whoami().username
|
|
205
|
+
creds = client.get_volume_credentials()
|
|
206
|
+
dest = download_from_cloud_volume(
|
|
207
|
+
credentials=creds,
|
|
208
|
+
username=username,
|
|
209
|
+
volume_path=args.volume_path,
|
|
210
|
+
local_path=args.local_path,
|
|
211
|
+
)
|
|
212
|
+
print(dest)
|
|
213
|
+
return 0
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _volume_delete(args: argparse.Namespace) -> int:
|
|
217
|
+
with OrchestratorClient(orchestrator_url()) as client:
|
|
218
|
+
creds = client.get_volume_credentials()
|
|
219
|
+
delete_from_cloud_volume(credentials=creds, volume_path=args.volume_path)
|
|
220
|
+
return 0
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _load_dotenv() -> None:
|
|
224
|
+
cwd = Path.cwd()
|
|
225
|
+
candidates = [
|
|
226
|
+
cwd / ".env",
|
|
227
|
+
cwd.parent / ".env",
|
|
228
|
+
]
|
|
229
|
+
for path in candidates:
|
|
230
|
+
if path.exists():
|
|
231
|
+
load_dotenv(path)
|
|
232
|
+
return
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
if __name__ == "__main__":
|
|
236
|
+
raise SystemExit(main())
|
armnet_client/client.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
"""HTTP client for the orchestrator.
|
|
2
|
+
|
|
3
|
+
Thin wrapper around the two M0.5 endpoints. Used internally by
|
|
4
|
+
:func:`armnet_client.execute`; exposed publicly for power users that
|
|
5
|
+
need fine-grained control (custom polling, fire-and-forget submissions,
|
|
6
|
+
etc.).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import time
|
|
12
|
+
from typing import Optional
|
|
13
|
+
|
|
14
|
+
import httpx
|
|
15
|
+
|
|
16
|
+
from armnet_core import (
|
|
17
|
+
API_KEY_HEADER,
|
|
18
|
+
DEFAULT_EMBODIMENT,
|
|
19
|
+
CellStatusSummary,
|
|
20
|
+
Job,
|
|
21
|
+
JobSpec,
|
|
22
|
+
JobStatusTransition,
|
|
23
|
+
RegistryCredentials,
|
|
24
|
+
SecretCreateRequest,
|
|
25
|
+
SecretInfo,
|
|
26
|
+
SecretList,
|
|
27
|
+
TerminalStatus,
|
|
28
|
+
VolumeCredentials,
|
|
29
|
+
WhoAmI,
|
|
30
|
+
)
|
|
31
|
+
from armnet_client._config import api_key as default_api_key
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class OrchestratorError(RuntimeError):
|
|
35
|
+
"""Raised when the orchestrator returns a non-2xx response.
|
|
36
|
+
|
|
37
|
+
``status_code`` is the HTTP status returned by the orchestrator;
|
|
38
|
+
``None`` if the request never got a response (e.g. connection refused).
|
|
39
|
+
Callers can branch on it to distinguish e.g. "endpoint not implemented"
|
|
40
|
+
(404) or "configured-but-unavailable" (503) from real failures.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
def __init__(self, message: str, *, status_code: Optional[int] = None) -> None:
|
|
44
|
+
super().__init__(message)
|
|
45
|
+
self.status_code = status_code
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class OrchestratorClient:
|
|
49
|
+
"""Synchronous client for the orchestrator HTTP API.
|
|
50
|
+
|
|
51
|
+
No auth in M0.5 (design doc explicitly defers it). When auth lands
|
|
52
|
+
we'll add an ``api_key`` arg here and inject it as a header.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
def __init__(
|
|
56
|
+
self,
|
|
57
|
+
base_url: str = "http://localhost:8000",
|
|
58
|
+
timeout: float = 30.0,
|
|
59
|
+
api_key: Optional[str] = None,
|
|
60
|
+
) -> None:
|
|
61
|
+
key = api_key if api_key is not None else default_api_key()
|
|
62
|
+
headers = {API_KEY_HEADER: key} if key else None
|
|
63
|
+
self._client = httpx.Client(
|
|
64
|
+
base_url=base_url.rstrip("/"),
|
|
65
|
+
timeout=timeout,
|
|
66
|
+
headers=headers,
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
def close(self) -> None:
|
|
70
|
+
self._client.close()
|
|
71
|
+
|
|
72
|
+
def __enter__(self) -> "OrchestratorClient":
|
|
73
|
+
return self
|
|
74
|
+
|
|
75
|
+
def __exit__(self, *_exc) -> None:
|
|
76
|
+
self.close()
|
|
77
|
+
|
|
78
|
+
def submit(self, spec: JobSpec, *, allow_queue: bool = True) -> Job:
|
|
79
|
+
"""POST /jobs — create a new job.
|
|
80
|
+
|
|
81
|
+
The returned :class:`Job` carries ``dispatched``: True if it was sent to
|
|
82
|
+
a cell immediately, False if it was accepted but queued.
|
|
83
|
+
|
|
84
|
+
``allow_queue`` (default True): when no matching cell is free, queue the
|
|
85
|
+
job (True) or have the orchestrator refuse it with HTTP 409 (False, for
|
|
86
|
+
callers that only make sense running immediately).
|
|
87
|
+
"""
|
|
88
|
+
resp = self._client.post(
|
|
89
|
+
"/jobs",
|
|
90
|
+
json=spec.model_dump(mode="json"),
|
|
91
|
+
params={"allow_queue": "true" if allow_queue else "false"},
|
|
92
|
+
)
|
|
93
|
+
_raise_for_status(resp)
|
|
94
|
+
return Job.model_validate(resp.json())
|
|
95
|
+
|
|
96
|
+
def get(self, job_id: str) -> Job:
|
|
97
|
+
"""GET /jobs/{id} \u2014 fetch the current state of a job."""
|
|
98
|
+
resp = self._client.get(f"/jobs/{job_id}")
|
|
99
|
+
_raise_for_status(resp)
|
|
100
|
+
return Job.model_validate(resp.json())
|
|
101
|
+
|
|
102
|
+
def list_jobs(self, *, limit: int = 10) -> list[Job]:
|
|
103
|
+
"""GET /jobs — the current user's most-recent jobs (newest first)."""
|
|
104
|
+
resp = self._client.get("/jobs", params={"limit": limit})
|
|
105
|
+
_raise_for_status(resp)
|
|
106
|
+
return [Job.model_validate(item) for item in resp.json()]
|
|
107
|
+
|
|
108
|
+
def get_status_transitions(self, job_id: str) -> list[JobStatusTransition]:
|
|
109
|
+
"""GET /jobs/{id}/status-transitions — a job's status-change audit trail."""
|
|
110
|
+
resp = self._client.get(f"/jobs/{job_id}/status-transitions")
|
|
111
|
+
_raise_for_status(resp)
|
|
112
|
+
return [JobStatusTransition.model_validate(item) for item in resp.json()]
|
|
113
|
+
|
|
114
|
+
def stop_job(self, job_id: str, *, reason: str = "client requested stop") -> Job:
|
|
115
|
+
"""POST /jobs/{id}/stop \u2014 request an immediate stop of a running job.
|
|
116
|
+
|
|
117
|
+
Used when the operator intentionally aborts (e.g. Ctrl-C): this cancels
|
|
118
|
+
the job now rather than waiting out the orchestrator's log-disconnect
|
|
119
|
+
grace window.
|
|
120
|
+
"""
|
|
121
|
+
resp = self._client.post(f"/jobs/{job_id}/stop", params={"reason": reason})
|
|
122
|
+
_raise_for_status(resp)
|
|
123
|
+
return Job.model_validate(resp.json())
|
|
124
|
+
|
|
125
|
+
def get_cell_status(
|
|
126
|
+
self,
|
|
127
|
+
*,
|
|
128
|
+
embodiment: str = DEFAULT_EMBODIMENT,
|
|
129
|
+
task: Optional[str] = None,
|
|
130
|
+
) -> CellStatusSummary:
|
|
131
|
+
"""GET /cells/status \u2014 fetch current availability for a task."""
|
|
132
|
+
|
|
133
|
+
params = {"embodiment": embodiment}
|
|
134
|
+
if task is not None:
|
|
135
|
+
params["task"] = task
|
|
136
|
+
resp = self._client.get("/cells/status", params=params)
|
|
137
|
+
_raise_for_status(resp)
|
|
138
|
+
return CellStatusSummary.model_validate(resp.json())
|
|
139
|
+
|
|
140
|
+
def get_registry_credentials(self) -> RegistryCredentials:
|
|
141
|
+
"""POST /registry/credentials \u2014 fetch fresh image-registry credentials.
|
|
142
|
+
|
|
143
|
+
Used by :meth:`armnet_client.Image.push` to get a short-lived
|
|
144
|
+
OAuth2 token for pushing customer images to the platform's
|
|
145
|
+
Artifact Registry repo. The orchestrator returns 503 if it isn't
|
|
146
|
+
configured for credential issuance (typical for local dev).
|
|
147
|
+
"""
|
|
148
|
+
resp = self._client.post("/registry/credentials")
|
|
149
|
+
_raise_for_status(resp)
|
|
150
|
+
return RegistryCredentials.model_validate(resp.json())
|
|
151
|
+
|
|
152
|
+
def whoami(self) -> WhoAmI:
|
|
153
|
+
"""GET /whoami — fetch the username for the current API key."""
|
|
154
|
+
|
|
155
|
+
resp = self._client.get("/whoami")
|
|
156
|
+
_raise_for_status(resp)
|
|
157
|
+
return WhoAmI.model_validate(resp.json())
|
|
158
|
+
|
|
159
|
+
def list_secrets(self) -> SecretList:
|
|
160
|
+
"""GET /secrets — list secret names for the current user."""
|
|
161
|
+
|
|
162
|
+
resp = self._client.get("/secrets")
|
|
163
|
+
_raise_for_status(resp)
|
|
164
|
+
return SecretList.model_validate(resp.json())
|
|
165
|
+
|
|
166
|
+
def create_secret(self, name: str, value: str) -> SecretInfo:
|
|
167
|
+
"""POST /secrets — create or replace one secret value."""
|
|
168
|
+
|
|
169
|
+
resp = self._client.post(
|
|
170
|
+
"/secrets",
|
|
171
|
+
json=SecretCreateRequest(name=name, value=value).model_dump(mode="json"),
|
|
172
|
+
)
|
|
173
|
+
_raise_for_status(resp)
|
|
174
|
+
return SecretInfo.model_validate(resp.json())
|
|
175
|
+
|
|
176
|
+
def delete_secret(self, name: str) -> None:
|
|
177
|
+
"""DELETE /secrets/{name} — delete one user secret if it exists."""
|
|
178
|
+
|
|
179
|
+
resp = self._client.delete(f"/secrets/{name}")
|
|
180
|
+
_raise_for_status(resp)
|
|
181
|
+
|
|
182
|
+
def get_volume_credentials(self) -> VolumeCredentials:
|
|
183
|
+
"""POST /volume/credentials — fetch short-lived GCS volume credentials."""
|
|
184
|
+
|
|
185
|
+
resp = self._client.post("/volume/credentials")
|
|
186
|
+
_raise_for_status(resp)
|
|
187
|
+
return VolumeCredentials.model_validate(resp.json())
|
|
188
|
+
|
|
189
|
+
def wait(
|
|
190
|
+
self,
|
|
191
|
+
job_id: str,
|
|
192
|
+
poll_interval_seconds: float = 1.0,
|
|
193
|
+
deadline_seconds: Optional[float] = None,
|
|
194
|
+
) -> Job:
|
|
195
|
+
"""Poll ``GET /jobs/{id}`` until the job reaches a terminal state.
|
|
196
|
+
|
|
197
|
+
Returns the final :class:`Job`. Raises :class:`TimeoutError` if
|
|
198
|
+
``deadline_seconds`` elapses first.
|
|
199
|
+
"""
|
|
200
|
+
start = time.monotonic()
|
|
201
|
+
try:
|
|
202
|
+
while True:
|
|
203
|
+
job = self.get(job_id)
|
|
204
|
+
if job.status in TerminalStatus:
|
|
205
|
+
return job
|
|
206
|
+
if (
|
|
207
|
+
deadline_seconds is not None
|
|
208
|
+
and (time.monotonic() - start) >= deadline_seconds
|
|
209
|
+
):
|
|
210
|
+
raise TimeoutError(
|
|
211
|
+
f"Job {job_id} did not reach a terminal state within "
|
|
212
|
+
f"{deadline_seconds}s (last status: {job.status})."
|
|
213
|
+
)
|
|
214
|
+
time.sleep(poll_interval_seconds)
|
|
215
|
+
except KeyboardInterrupt:
|
|
216
|
+
# Operator intentionally aborted: stop the job now instead of leaving
|
|
217
|
+
# it to the orchestrator's log-disconnect grace window. Best-effort —
|
|
218
|
+
# always re-raise so the interrupt still propagates.
|
|
219
|
+
try:
|
|
220
|
+
self.stop_job(job_id, reason="client interrupted (KeyboardInterrupt)")
|
|
221
|
+
except Exception: # noqa: BLE001
|
|
222
|
+
pass
|
|
223
|
+
raise
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _raise_for_status(resp: httpx.Response) -> None:
|
|
227
|
+
if resp.is_success:
|
|
228
|
+
return
|
|
229
|
+
try:
|
|
230
|
+
body = resp.json()
|
|
231
|
+
except ValueError:
|
|
232
|
+
body = resp.text
|
|
233
|
+
raise OrchestratorError(
|
|
234
|
+
f"Orchestrator returned HTTP {resp.status_code} for {resp.request.method} "
|
|
235
|
+
f"{resp.request.url}: {body!r}",
|
|
236
|
+
status_code=resp.status_code,
|
|
237
|
+
)
|