nebius-serverless 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.
- nebius_serverless/__init__.py +54 -0
- nebius_serverless/_version.py +12 -0
- nebius_serverless/account.py +189 -0
- nebius_serverless/aliases.py +154 -0
- nebius_serverless/cli.py +175 -0
- nebius_serverless/endpoint.py +719 -0
- nebius_serverless/endpoint_recipe.py +364 -0
- nebius_serverless/endpoint_spec.py +580 -0
- nebius_serverless/errors.py +230 -0
- nebius_serverless/job.py +475 -0
- nebius_serverless/job_spec.py +521 -0
- nebius_serverless/log.py +287 -0
- nebius_serverless/loop.py +22 -0
- nebius_serverless/output.py +1223 -0
- nebius_serverless/poll.py +279 -0
- nebius_serverless/profile.py +121 -0
- nebius_serverless/py.typed +0 -0
- nebius_serverless/recipe.py +738 -0
- nebius_serverless/sdk_transport.py +962 -0
- nebius_serverless/session.py +177 -0
- nebius_serverless/status.py +45 -0
- nebius_serverless/transport.py +314 -0
- nebius_serverless/yaml_job.py +327 -0
- nebius_serverless-0.1.0.dist-info/METADATA +121 -0
- nebius_serverless-0.1.0.dist-info/RECORD +29 -0
- nebius_serverless-0.1.0.dist-info/WHEEL +5 -0
- nebius_serverless-0.1.0.dist-info/licenses/LICENSE +201 -0
- nebius_serverless-0.1.0.dist-info/licenses/NOTICE +7 -0
- nebius_serverless-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Unofficial client for Nebius Serverless AI Jobs and Endpoints.
|
|
2
|
+
|
|
3
|
+
Not an official Nebius product, and Nebius does not support it. The
|
|
4
|
+
official Python SDK is https://github.com/nebius/pysdk.
|
|
5
|
+
|
|
6
|
+
``JobSpec`` and ``EndpointSpec`` are local recipes. ``create()`` on one
|
|
7
|
+
returns a ``Job`` or an ``Endpoint``: the cloud resource with that id.
|
|
8
|
+
Constructing a recipe does not import the Nebius SDK. The SDK is
|
|
9
|
+
imported on the call that resolves a profile or contacts Nebius.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from ._version import __version__ as __version__
|
|
13
|
+
from .account import whoami, whoami_async
|
|
14
|
+
from .endpoint import Endpoint, endpoints
|
|
15
|
+
from .endpoint_spec import EndpointSpec
|
|
16
|
+
from .errors import (
|
|
17
|
+
AccessError,
|
|
18
|
+
CapacityError,
|
|
19
|
+
Error,
|
|
20
|
+
KeyConflict,
|
|
21
|
+
SubmissionUncertain,
|
|
22
|
+
TransportError,
|
|
23
|
+
UnsupportedFeature,
|
|
24
|
+
ValidationError,
|
|
25
|
+
WaitTimeout,
|
|
26
|
+
)
|
|
27
|
+
from .job import Job, jobs
|
|
28
|
+
from .job_spec import JobSpec
|
|
29
|
+
from .log import configure_logging, diagnostics
|
|
30
|
+
from .session import close, configure
|
|
31
|
+
|
|
32
|
+
__all__ = [
|
|
33
|
+
"AccessError",
|
|
34
|
+
"CapacityError",
|
|
35
|
+
"Endpoint",
|
|
36
|
+
"EndpointSpec",
|
|
37
|
+
"Error",
|
|
38
|
+
"Job",
|
|
39
|
+
"JobSpec",
|
|
40
|
+
"KeyConflict",
|
|
41
|
+
"SubmissionUncertain",
|
|
42
|
+
"TransportError",
|
|
43
|
+
"UnsupportedFeature",
|
|
44
|
+
"ValidationError",
|
|
45
|
+
"WaitTimeout",
|
|
46
|
+
"close",
|
|
47
|
+
"configure",
|
|
48
|
+
"configure_logging",
|
|
49
|
+
"diagnostics",
|
|
50
|
+
"endpoints",
|
|
51
|
+
"jobs",
|
|
52
|
+
"whoami",
|
|
53
|
+
"whoami_async",
|
|
54
|
+
]
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""The package version, read once from the installed distribution."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
DISTRIBUTION = "nebius-serverless"
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
__version__ = version(DISTRIBUTION)
|
|
9
|
+
except PackageNotFoundError: # a source tree that was never installed
|
|
10
|
+
__version__ = "0+unknown"
|
|
11
|
+
|
|
12
|
+
USER_AGENT = f"{DISTRIBUTION}/{__version__}"
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"""``ns.whoami()``: who the credentials belong to, and where jobs go."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
|
|
5
|
+
from .errors import (
|
|
6
|
+
AccessError,
|
|
7
|
+
Error,
|
|
8
|
+
ValidationError,
|
|
9
|
+
exposed_request_id,
|
|
10
|
+
exposed_trace_id,
|
|
11
|
+
)
|
|
12
|
+
from .loop import reject_running_loop
|
|
13
|
+
from .output import Progress, call_progress, call_progress_async, report
|
|
14
|
+
from .status import Status
|
|
15
|
+
|
|
16
|
+
_LOG = "nebius_serverless.account"
|
|
17
|
+
_RECOVERY = (
|
|
18
|
+
"Run `nebius profile create` or `nebius profile activate`, or check "
|
|
19
|
+
"NEBIUS_IAM_TOKEN / ns.configure(credentials_file=...)."
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def whoami(
|
|
24
|
+
*,
|
|
25
|
+
profile: str | None = None,
|
|
26
|
+
project: str | None = None,
|
|
27
|
+
quiet: bool = False,
|
|
28
|
+
) -> dict[str, object]:
|
|
29
|
+
"""Check the credentials and where ``create()`` would put a job.
|
|
30
|
+
|
|
31
|
+
One read-only call (IAM ``GetProfile``) through the shared SDK, then
|
|
32
|
+
the same project and region resolution as ``create()``. Nothing is
|
|
33
|
+
created, listed or changed. Returns::
|
|
34
|
+
|
|
35
|
+
{"account": {"kind": "user" | "service_account" | "anonymous",
|
|
36
|
+
"id": ..., "name": ..., "email": ...},
|
|
37
|
+
"auth": {"source": "profile" | "env" | "credentials_file" | "sdk",
|
|
38
|
+
"detail": ...},
|
|
39
|
+
"project": ..., "region": ..., "problem": None | "..."}
|
|
40
|
+
|
|
41
|
+
and prints a one-line summary on stderr (``quiet=True`` suppresses
|
|
42
|
+
it). Failed authentication raises ``AccessError`` with what to do.
|
|
43
|
+
No token or credential appears in the result or the output.
|
|
44
|
+
"""
|
|
45
|
+
reject_running_loop("whoami_async")
|
|
46
|
+
|
|
47
|
+
def work(progress: Progress) -> dict[str, object]:
|
|
48
|
+
return _whoami(profile, project, progress)
|
|
49
|
+
|
|
50
|
+
return call_progress(quiet=quiet, logger_name=_LOG, work=work)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
async def whoami_async(
|
|
54
|
+
*,
|
|
55
|
+
profile: str | None = None,
|
|
56
|
+
project: str | None = None,
|
|
57
|
+
quiet: bool = False,
|
|
58
|
+
) -> dict[str, object]:
|
|
59
|
+
"""Await the same check as ``whoami``."""
|
|
60
|
+
|
|
61
|
+
def work(progress: Progress) -> dict[str, object]:
|
|
62
|
+
return _whoami(profile, project, progress)
|
|
63
|
+
|
|
64
|
+
return await call_progress_async(
|
|
65
|
+
quiet=quiet,
|
|
66
|
+
logger_name=_LOG,
|
|
67
|
+
work=work,
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _whoami(
|
|
72
|
+
profile: str | None,
|
|
73
|
+
project: str | None,
|
|
74
|
+
progress: Progress,
|
|
75
|
+
) -> dict[str, object]:
|
|
76
|
+
from .profile import resolve_location
|
|
77
|
+
from .session import auth_source, get_sdk, settings
|
|
78
|
+
|
|
79
|
+
chosen = profile if profile is not None else settings().profile
|
|
80
|
+
kind, detail = auth_source(chosen)
|
|
81
|
+
account = _account(get_sdk(chosen))
|
|
82
|
+
found: dict[str, object] = {
|
|
83
|
+
"account": account,
|
|
84
|
+
"auth": {"source": kind, "detail": detail},
|
|
85
|
+
"project": None,
|
|
86
|
+
"region": None,
|
|
87
|
+
"problem": None,
|
|
88
|
+
}
|
|
89
|
+
try:
|
|
90
|
+
project_id, region_id = resolve_location(
|
|
91
|
+
profile=chosen, project=project, region=None
|
|
92
|
+
)
|
|
93
|
+
found["project"] = project_id
|
|
94
|
+
found["region"] = region_id
|
|
95
|
+
except ValidationError as exc:
|
|
96
|
+
found["problem"] = str(exc)
|
|
97
|
+
report(Status(kind="account", message=_summary(found)), progress)
|
|
98
|
+
return found
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _account(sdk: object) -> dict[str, object]:
|
|
102
|
+
try:
|
|
103
|
+
from nebius.aio.service_error import RequestError
|
|
104
|
+
except ImportError:
|
|
105
|
+
raise ValidationError(
|
|
106
|
+
"The Nebius SDK is required to check the account.",
|
|
107
|
+
operation="whoami",
|
|
108
|
+
) from None
|
|
109
|
+
try:
|
|
110
|
+
response = sdk.whoami().wait() # type: ignore[attr-defined]
|
|
111
|
+
payload = json.loads(
|
|
112
|
+
response.to_json(preserving_proto_field_name=True)
|
|
113
|
+
)
|
|
114
|
+
except RequestError as exc:
|
|
115
|
+
status = getattr(exc, "status", None)
|
|
116
|
+
code = getattr(getattr(status, "code", None), "name", None)
|
|
117
|
+
raise AccessError(
|
|
118
|
+
"Nebius did not accept these credentials.",
|
|
119
|
+
operation="whoami",
|
|
120
|
+
request_id=exposed_request_id(exc),
|
|
121
|
+
trace_id=exposed_trace_id(exc),
|
|
122
|
+
status_code=code,
|
|
123
|
+
recovery=_RECOVERY,
|
|
124
|
+
) from None
|
|
125
|
+
except Error:
|
|
126
|
+
raise
|
|
127
|
+
except Exception as exc:
|
|
128
|
+
raise AccessError(
|
|
129
|
+
"Could not authenticate with Nebius.",
|
|
130
|
+
operation="whoami",
|
|
131
|
+
request_id=exposed_request_id(exc),
|
|
132
|
+
recovery=_RECOVERY,
|
|
133
|
+
) from None
|
|
134
|
+
return _parse_account(payload if isinstance(payload, dict) else {})
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _parse_account(payload: dict[str, object]) -> dict[str, object]:
|
|
138
|
+
user = payload.get("user_profile")
|
|
139
|
+
if isinstance(user, dict):
|
|
140
|
+
attributes = user.get("attributes")
|
|
141
|
+
attrs = attributes if isinstance(attributes, dict) else {}
|
|
142
|
+
return {
|
|
143
|
+
"kind": "user",
|
|
144
|
+
"id": user.get("id"),
|
|
145
|
+
"name": attrs.get("name") or attrs.get("preferred_username"),
|
|
146
|
+
"email": attrs.get("email"),
|
|
147
|
+
}
|
|
148
|
+
service = payload.get("service_account_profile")
|
|
149
|
+
if isinstance(service, dict):
|
|
150
|
+
info = service.get("info")
|
|
151
|
+
metadata = info.get("metadata") if isinstance(info, dict) else None
|
|
152
|
+
meta = metadata if isinstance(metadata, dict) else {}
|
|
153
|
+
return {
|
|
154
|
+
"kind": "service_account",
|
|
155
|
+
"id": meta.get("id"),
|
|
156
|
+
"name": meta.get("name"),
|
|
157
|
+
"email": None,
|
|
158
|
+
}
|
|
159
|
+
return {"kind": "anonymous", "id": None, "name": None, "email": None}
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _summary(found: dict[str, object]) -> str:
|
|
163
|
+
account = found["account"]
|
|
164
|
+
auth = found["auth"]
|
|
165
|
+
assert isinstance(account, dict) and isinstance(auth, dict)
|
|
166
|
+
parts = [account.get("name"), account.get("email")]
|
|
167
|
+
who = " ".join(dict.fromkeys(str(part) for part in parts if part))
|
|
168
|
+
ident = f" ({account['id']})" if account.get("id") else ""
|
|
169
|
+
kind = str(account.get("kind")).replace("_", " ")
|
|
170
|
+
line = " ".join(f"Signed in as {kind} {who}{ident}".split())
|
|
171
|
+
line += f" via {_via(auth)}."
|
|
172
|
+
if found["project"]:
|
|
173
|
+
line += f" Jobs go to {found['project']} in {found['region']}."
|
|
174
|
+
else:
|
|
175
|
+
line += f" {found['problem']}"
|
|
176
|
+
return line
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _via(auth: dict[str, object]) -> str:
|
|
180
|
+
source, detail = auth["source"], auth["detail"]
|
|
181
|
+
if source == "profile":
|
|
182
|
+
if detail == "active profile":
|
|
183
|
+
return "the active CLI profile"
|
|
184
|
+
return f"CLI profile {detail!r}"
|
|
185
|
+
if source == "env":
|
|
186
|
+
return str(detail)
|
|
187
|
+
if source == "credentials_file":
|
|
188
|
+
return f"credentials file {detail}"
|
|
189
|
+
return "a configured SDK"
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""Machine selection: GPU/CPU selectors, an explicit platform, or CPU.
|
|
2
|
+
|
|
3
|
+
``gpu="h100"`` / ``"h100:8"`` and ``cpu="amd:16"`` are sent as the API's
|
|
4
|
+
selectors, and Nebius picks the platform and preset in the project's
|
|
5
|
+
region. ``platform=`` / ``preset=`` stay as explicit overrides. With none
|
|
6
|
+
of them the client sends the smallest CPU machine.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
|
|
12
|
+
from .errors import ValidationError
|
|
13
|
+
|
|
14
|
+
# Public regions, used to read a region out of a profile endpoint.
|
|
15
|
+
REGIONS = (
|
|
16
|
+
"eu-north1",
|
|
17
|
+
"eu-north2",
|
|
18
|
+
"eu-south1",
|
|
19
|
+
"eu-west1",
|
|
20
|
+
"eu-west2",
|
|
21
|
+
"me-west1",
|
|
22
|
+
"uk-south1",
|
|
23
|
+
"uk-south2",
|
|
24
|
+
"us-central1",
|
|
25
|
+
"us-north1",
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
CPU_PLATFORM = "cpu-d3"
|
|
29
|
+
CPU_PRESET = "2vcpu-8gb"
|
|
30
|
+
|
|
31
|
+
# The smallest preset of known platforms, used for platform= without
|
|
32
|
+
# preset=. Nebius validates both on create.
|
|
33
|
+
PRESETS: dict[str, str] = {
|
|
34
|
+
"gpu-h100-sxm": "1gpu-16vcpu-200gb",
|
|
35
|
+
"gpu-h200-sxm": "1gpu-16vcpu-200gb",
|
|
36
|
+
"gpu-b300-sxm": "1gpu-24vcpu-346gb",
|
|
37
|
+
"gpu-b200-sxm": "1gpu-20vcpu-224gb",
|
|
38
|
+
"gpu-b200-sxm-a": "1gpu-20vcpu-224gb",
|
|
39
|
+
"gpu-l40s-a": "1gpu-8vcpu-32gb",
|
|
40
|
+
"gpu-rtx6000": "1gpu-24vcpu-218gb",
|
|
41
|
+
"gpu-rtx6000-a": "1gpu-24vcpu-218gb",
|
|
42
|
+
CPU_PLATFORM: CPU_PRESET,
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
_NAME = r"[A-Za-z0-9][A-Za-z0-9._-]*"
|
|
46
|
+
_GPU = re.compile(rf"^({_NAME})(?::([0-9]+))?$")
|
|
47
|
+
_CPU = re.compile(rf"^({_NAME}):([0-9]+)$")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True)
|
|
51
|
+
class Machine:
|
|
52
|
+
"""What create sends: a selector, or a platform and preset."""
|
|
53
|
+
|
|
54
|
+
platform: str | None
|
|
55
|
+
preset: str | None
|
|
56
|
+
gpu: str | None = None
|
|
57
|
+
cpu_selector: str | None = None
|
|
58
|
+
cpu: bool = False
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def validate_gpu(gpu: object, *, operation: str = "JobSpec") -> str | None:
|
|
62
|
+
"""``MODEL[:COUNT]``, e.g. ``"h100"`` or ``"h100:8"``; count >= 1."""
|
|
63
|
+
if gpu is None:
|
|
64
|
+
return None
|
|
65
|
+
if gpu == "cpu":
|
|
66
|
+
raise ValidationError(
|
|
67
|
+
"gpu='cpu' is invalid. Omit gpu for the default CPU machine, "
|
|
68
|
+
"or pass cpu='amd:16'.",
|
|
69
|
+
operation=operation,
|
|
70
|
+
)
|
|
71
|
+
match = _GPU.fullmatch(gpu) if isinstance(gpu, str) else None
|
|
72
|
+
count = None if match is None else match.group(2)
|
|
73
|
+
if match is None or (count is not None and int(count) < 1):
|
|
74
|
+
raise ValidationError(
|
|
75
|
+
"gpu must be MODEL or MODEL:COUNT with COUNT of at least 1, "
|
|
76
|
+
"such as 'h100' or 'h100:8'.",
|
|
77
|
+
operation=operation,
|
|
78
|
+
)
|
|
79
|
+
return match.group(0)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def validate_cpu(cpu: object, *, operation: str = "JobSpec") -> str | None:
|
|
83
|
+
"""``FAMILY:VCPUS``, e.g. ``"amd:16"``; vCPUs >= 1."""
|
|
84
|
+
if cpu is None:
|
|
85
|
+
return None
|
|
86
|
+
match = _CPU.fullmatch(cpu) if isinstance(cpu, str) else None
|
|
87
|
+
if match is None or int(match.group(2)) < 1:
|
|
88
|
+
raise ValidationError(
|
|
89
|
+
"cpu must be FAMILY:VCPUS, such as 'amd:16'.",
|
|
90
|
+
operation=operation,
|
|
91
|
+
)
|
|
92
|
+
return match.group(0)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def check_machine(
|
|
96
|
+
gpu: str | None,
|
|
97
|
+
cpu: str | None,
|
|
98
|
+
platform: str | None,
|
|
99
|
+
preset: str | None,
|
|
100
|
+
*,
|
|
101
|
+
operation: str = "JobSpec",
|
|
102
|
+
) -> None:
|
|
103
|
+
"""Selectors exclude each other and an explicit platform or preset."""
|
|
104
|
+
if gpu is not None and cpu is not None:
|
|
105
|
+
raise ValidationError(
|
|
106
|
+
"Set gpu or cpu, not both.",
|
|
107
|
+
operation=operation,
|
|
108
|
+
)
|
|
109
|
+
if (gpu is not None or cpu is not None) and (
|
|
110
|
+
platform is not None or preset is not None
|
|
111
|
+
):
|
|
112
|
+
raise ValidationError(
|
|
113
|
+
"gpu and cpu let Nebius pick the platform and preset. "
|
|
114
|
+
"Omit them to set platform and preset yourself.",
|
|
115
|
+
operation=operation,
|
|
116
|
+
)
|
|
117
|
+
if platform is not None and platform not in PRESETS and not preset:
|
|
118
|
+
raise ValidationError(
|
|
119
|
+
f"Unknown platform {platform!r} requires preset.",
|
|
120
|
+
operation=operation,
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def known_cpu(
|
|
125
|
+
gpu: str | None,
|
|
126
|
+
cpu: str | None,
|
|
127
|
+
platform: str | None,
|
|
128
|
+
) -> bool:
|
|
129
|
+
"""Whether the recipe is known to run on a CPU machine."""
|
|
130
|
+
if cpu is not None:
|
|
131
|
+
return True
|
|
132
|
+
if platform is not None:
|
|
133
|
+
return platform.startswith("cpu")
|
|
134
|
+
return gpu is None
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def resolve_machine(
|
|
138
|
+
gpu: str | None,
|
|
139
|
+
cpu: str | None,
|
|
140
|
+
platform: str | None,
|
|
141
|
+
preset: str | None,
|
|
142
|
+
) -> Machine:
|
|
143
|
+
"""The selector, or the platform and preset, that create sends."""
|
|
144
|
+
if gpu is not None:
|
|
145
|
+
return Machine(None, None, gpu=gpu)
|
|
146
|
+
if cpu is not None:
|
|
147
|
+
return Machine(None, None, cpu_selector=cpu, cpu=True)
|
|
148
|
+
if platform is not None:
|
|
149
|
+
return Machine(
|
|
150
|
+
platform,
|
|
151
|
+
preset or PRESETS[platform],
|
|
152
|
+
cpu=platform.startswith("cpu"),
|
|
153
|
+
)
|
|
154
|
+
return Machine(CPU_PLATFORM, preset or CPU_PRESET, cpu=True)
|
nebius_serverless/cli.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""Print the ``nebius ai job|endpoint create`` command a recipe stands for.
|
|
2
|
+
|
|
3
|
+
``FLAGS`` maps each recipe argument to its CLI flag. The same table is
|
|
4
|
+
checked against the CLI and API map in ``docs/reference.md``, so the
|
|
5
|
+
printer and the docs cannot drift apart.
|
|
6
|
+
|
|
7
|
+
Nothing secret is printed: env values become ``"$KEY"`` placeholders,
|
|
8
|
+
secrets appear by id, and a token is never written out.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import shlex
|
|
12
|
+
from collections.abc import Sequence
|
|
13
|
+
|
|
14
|
+
from .aliases import resolve_machine
|
|
15
|
+
from .recipe import DISK_DEFAULT, resolve_shm
|
|
16
|
+
|
|
17
|
+
FLAGS: dict[str, str] = {
|
|
18
|
+
"command": "--container-command",
|
|
19
|
+
"image": "--image",
|
|
20
|
+
"port": "--container-port",
|
|
21
|
+
"ports": "--container-port",
|
|
22
|
+
"gpu": "--gpu",
|
|
23
|
+
"cpu": "--cpu",
|
|
24
|
+
"platform": "--platform",
|
|
25
|
+
"preset": "--preset",
|
|
26
|
+
"pricing": "--preemptible",
|
|
27
|
+
"spot_policy": "--spot-pricing-policy-id",
|
|
28
|
+
"auth": "--auth",
|
|
29
|
+
"token": "--token",
|
|
30
|
+
"token_secret": "--token-secret",
|
|
31
|
+
"subnet_id": "--subnet-id",
|
|
32
|
+
"volumes": "--volume",
|
|
33
|
+
"inject_files": "--inject-file",
|
|
34
|
+
"env": "--env",
|
|
35
|
+
"secrets": "--env-secret",
|
|
36
|
+
"name": "--name",
|
|
37
|
+
"disk": "--disk-size",
|
|
38
|
+
"shm": "--shm-size",
|
|
39
|
+
"project": "--parent-id",
|
|
40
|
+
"profile": "--profile",
|
|
41
|
+
"working_dir": "--working-dir",
|
|
42
|
+
"registry_secret": "--registry-secret",
|
|
43
|
+
"restart_attempts": "--restart-policy",
|
|
44
|
+
"timeout": "--timeout",
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
Flag = tuple[str, str | None]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def job_command(
|
|
51
|
+
spec: object,
|
|
52
|
+
*,
|
|
53
|
+
name: str,
|
|
54
|
+
project: str | None,
|
|
55
|
+
) -> str:
|
|
56
|
+
"""The ``nebius ai job create`` command for a ``JobSpec``."""
|
|
57
|
+
flags = _common(spec, name=name, project=project)
|
|
58
|
+
after_image = 1 + next(
|
|
59
|
+
i for i, (flag, _value) in enumerate(flags) if flag == "--image"
|
|
60
|
+
)
|
|
61
|
+
timeout = _duration(spec.timeout_seconds) # type: ignore[attr-defined]
|
|
62
|
+
flags.insert(after_image, ("--timeout", timeout))
|
|
63
|
+
notes: list[str] = []
|
|
64
|
+
restarts = spec.restart_attempts # type: ignore[attr-defined]
|
|
65
|
+
if restarts == -1:
|
|
66
|
+
flags.append(("--restart-policy", "on-failure"))
|
|
67
|
+
elif restarts > 0:
|
|
68
|
+
notes.append(
|
|
69
|
+
f"restart_attempts={restarts} has no CLI flag: "
|
|
70
|
+
"--restart-policy on-failure restarts without limit."
|
|
71
|
+
)
|
|
72
|
+
return _render("nebius ai job create", flags, notes)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def endpoint_command(
|
|
76
|
+
spec: object,
|
|
77
|
+
*,
|
|
78
|
+
name: str,
|
|
79
|
+
project: str | None,
|
|
80
|
+
) -> str:
|
|
81
|
+
"""The ``nebius ai endpoint create`` command for an ``EndpointSpec``."""
|
|
82
|
+
flags = _common(spec, name=name, project=project)
|
|
83
|
+
for port in spec.ports: # type: ignore[attr-defined]
|
|
84
|
+
flags.append(("--container-port", port))
|
|
85
|
+
flags.append(("--auth", spec.auth)) # type: ignore[attr-defined]
|
|
86
|
+
notes: list[str] = []
|
|
87
|
+
if spec.token_secret is not None: # type: ignore[attr-defined]
|
|
88
|
+
flags.append(("--token-secret", spec.token_secret)) # type: ignore[attr-defined]
|
|
89
|
+
elif spec.token is not None: # type: ignore[attr-defined]
|
|
90
|
+
notes.append(
|
|
91
|
+
"token= is not printed: add --token yourself, or the CLI "
|
|
92
|
+
"generates one."
|
|
93
|
+
)
|
|
94
|
+
return _render("nebius ai endpoint create", flags, notes)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _common(spec: object, *, name: str, project: str | None) -> list[Flag]:
|
|
98
|
+
s = spec
|
|
99
|
+
machine = resolve_machine(
|
|
100
|
+
s.gpu, s.cpu, s.platform, s.preset # type: ignore[attr-defined]
|
|
101
|
+
)
|
|
102
|
+
flags: list[Flag] = []
|
|
103
|
+
if s.profile is not None: # type: ignore[attr-defined]
|
|
104
|
+
flags.append(("--profile", s.profile)) # type: ignore[attr-defined]
|
|
105
|
+
chosen_project = project or s.project # type: ignore[attr-defined]
|
|
106
|
+
if chosen_project is not None:
|
|
107
|
+
flags.append(("--parent-id", chosen_project))
|
|
108
|
+
flags.append(("--name", name))
|
|
109
|
+
flags.append(("--image", s.image)) # type: ignore[attr-defined]
|
|
110
|
+
command: Sequence[str] | None = s.command # type: ignore[attr-defined]
|
|
111
|
+
if command:
|
|
112
|
+
flags.append(("--container-command", command[0]))
|
|
113
|
+
if len(command) > 1:
|
|
114
|
+
flags.append(("--args", shlex.join(command[1:])))
|
|
115
|
+
if machine.gpu is not None:
|
|
116
|
+
flags.append(("--gpu", machine.gpu))
|
|
117
|
+
elif machine.cpu_selector is not None:
|
|
118
|
+
flags.append(("--cpu", machine.cpu_selector))
|
|
119
|
+
else:
|
|
120
|
+
# The CLI's own default is a GPU; say CPU explicitly.
|
|
121
|
+
flags.append(("--platform", machine.platform))
|
|
122
|
+
flags.append(("--preset", machine.preset))
|
|
123
|
+
if s.pricing == "spot": # type: ignore[attr-defined]
|
|
124
|
+
flags.append(("--preemptible", None))
|
|
125
|
+
if s.spot_policy is not None: # type: ignore[attr-defined]
|
|
126
|
+
flags.append(("--spot-pricing-policy-id", s.spot_policy)) # type: ignore[attr-defined]
|
|
127
|
+
else:
|
|
128
|
+
flags.append(("--follows-spot-price", None))
|
|
129
|
+
flags.append(("--disk-size", s.disk or DISK_DEFAULT)) # type: ignore[attr-defined]
|
|
130
|
+
shm = resolve_shm(s.shm, cpu=machine.cpu) # type: ignore[attr-defined]
|
|
131
|
+
if shm is not None:
|
|
132
|
+
flags.append(("--shm-size", shm))
|
|
133
|
+
if s.subnet_id is not None: # type: ignore[attr-defined]
|
|
134
|
+
flags.append(("--subnet-id", s.subnet_id)) # type: ignore[attr-defined]
|
|
135
|
+
for volume in s.volumes: # type: ignore[attr-defined]
|
|
136
|
+
flags.append(("--volume", volume))
|
|
137
|
+
for item in s.inject_files: # type: ignore[attr-defined]
|
|
138
|
+
flags.append(("--inject-file", item))
|
|
139
|
+
for key, _value in s.env: # type: ignore[attr-defined]
|
|
140
|
+
flags.append(("--env", f'{key}="${key}"'))
|
|
141
|
+
for key, ref in s.secrets: # type: ignore[attr-defined]
|
|
142
|
+
flags.append(("--env-secret", f"{key}={ref}"))
|
|
143
|
+
if s.working_dir is not None: # type: ignore[attr-defined]
|
|
144
|
+
flags.append(("--working-dir", s.working_dir)) # type: ignore[attr-defined]
|
|
145
|
+
if s.registry_secret is not None: # type: ignore[attr-defined]
|
|
146
|
+
flags.append(("--registry-secret", s.registry_secret)) # type: ignore[attr-defined]
|
|
147
|
+
return flags
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _render(head: str, flags: list[Flag], notes: list[str]) -> str:
|
|
151
|
+
lines = [head]
|
|
152
|
+
for flag, value in flags:
|
|
153
|
+
if value is None:
|
|
154
|
+
lines.append(f" {flag}")
|
|
155
|
+
elif flag == "--env":
|
|
156
|
+
# KEY="$KEY": the shell expands the value; it is never printed.
|
|
157
|
+
lines.append(f" {flag} {value}")
|
|
158
|
+
else:
|
|
159
|
+
lines.append(f" {flag} {shlex.quote(str(value))}")
|
|
160
|
+
text = " \\\n".join(lines)
|
|
161
|
+
for note in notes:
|
|
162
|
+
text += f"\n# {note}"
|
|
163
|
+
return text + "\n"
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _duration(seconds: float) -> str:
|
|
167
|
+
whole = int(round(seconds))
|
|
168
|
+
hours, rest = divmod(whole, 3600)
|
|
169
|
+
minutes, secs = divmod(rest, 60)
|
|
170
|
+
text = "".join(
|
|
171
|
+
f"{value}{unit}"
|
|
172
|
+
for value, unit in ((hours, "h"), (minutes, "m"), (secs, "s"))
|
|
173
|
+
if value
|
|
174
|
+
)
|
|
175
|
+
return text or "0s"
|