testflows.machine 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.
Potentially problematic release.
This version of testflows.machine might be problematic. Click here for more details.
- testflows/machine/v1/__init__.py +278 -0
- testflows/machine/v1/_args.py +528 -0
- testflows/machine/v1/_requires.py +103 -0
- testflows/machine/v1/_service.py +109 -0
- testflows/machine/v1/_version.py +16 -0
- testflows/machine/v1/_when.py +55 -0
- testflows/machine/v1/client.py +1924 -0
- testflows/machine/v1/disks.py +669 -0
- testflows/machine/v1/errors.py +255 -0
- testflows/machine/v1/login.py +107 -0
- testflows/machine/v1/ping.py +70 -0
- testflows/machine/v1/results.py +3231 -0
- testflows/machine/v1/runs.py +7648 -0
- testflows/machine/v1/sessions.py +751 -0
- testflows_machine-0.1.0.dist-info/METADATA +116 -0
- testflows_machine-0.1.0.dist-info/RECORD +20 -0
- testflows_machine-0.1.0.dist-info/WHEEL +5 -0
- testflows_machine-0.1.0.dist-info/licenses/LICENSE +203 -0
- testflows_machine-0.1.0.dist-info/licenses/NOTICE +7 -0
- testflows_machine-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,751 @@
|
|
|
1
|
+
# Copyright 2026 Katteli Inc.
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
"""Sessions: cloud machines that host runs, as `machine sessions`."""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import builtins
|
|
19
|
+
from typing import TYPE_CHECKING, Any, Generator, Literal, Optional, overload
|
|
20
|
+
|
|
21
|
+
from testflows.machine._core import api
|
|
22
|
+
from testflows.machine._core import sessions as _sessions
|
|
23
|
+
|
|
24
|
+
from . import _args
|
|
25
|
+
from .errors import ApiError, InvalidArgument, NotFound, _translated
|
|
26
|
+
|
|
27
|
+
if TYPE_CHECKING:
|
|
28
|
+
from .client import Client
|
|
29
|
+
|
|
30
|
+
#: The state of a session that was deleted.
|
|
31
|
+
_DELETED = "terminated"
|
|
32
|
+
|
|
33
|
+
#: MB in a GB: `create` takes storage in GB, the service in MB.
|
|
34
|
+
_MB_PER_GB = 1024
|
|
35
|
+
|
|
36
|
+
#: The fields a session exposes, in the order `as_json` lists them.
|
|
37
|
+
FIELDS: tuple[str, ...] = (
|
|
38
|
+
"id",
|
|
39
|
+
"name",
|
|
40
|
+
"state",
|
|
41
|
+
"cpus",
|
|
42
|
+
"mem_mb",
|
|
43
|
+
"storage_mb",
|
|
44
|
+
"instance_type",
|
|
45
|
+
"error",
|
|
46
|
+
"created_at",
|
|
47
|
+
"started_at",
|
|
48
|
+
"stopped_at",
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class Session:
|
|
53
|
+
"""One session: a machine the account rents, with its own CPUs,
|
|
54
|
+
memory and storage, where runs execute.
|
|
55
|
+
|
|
56
|
+
Not created directly: `Client.sessions` creates, lists and shows
|
|
57
|
+
sessions. `client.sessions.use(session)` makes one the client's current
|
|
58
|
+
session, where its commands go. The attributes are what the last read
|
|
59
|
+
returned; `refresh` reads them again.
|
|
60
|
+
|
|
61
|
+
A session uses credits from the moment it is created until it stops. Used
|
|
62
|
+
in a `with` block, it is deleted when the block exits, however it exits.
|
|
63
|
+
Without `with`, it lives until `delete`, or until it has been idle for
|
|
64
|
+
its plan's idle time: no command for that long, `keep` aside.
|
|
65
|
+
|
|
66
|
+
Example:
|
|
67
|
+
>>> with client.sessions.create("ci-1", cpus=4) as session:
|
|
68
|
+
... client.sessions.use(session)
|
|
69
|
+
... run = client.create(disk="app")
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
def __init__(self, client: "Client", row: dict[str, Any]) -> None:
|
|
73
|
+
self._client = client
|
|
74
|
+
self._row = row
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def id(self) -> str:
|
|
78
|
+
"""str: The session's id, which never changes."""
|
|
79
|
+
return str(self._row["session_id"])
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def name(self) -> str:
|
|
83
|
+
"""str: The session's name, unique in the account; `rename` changes
|
|
84
|
+
it."""
|
|
85
|
+
return str(self._row.get("name") or self.id)
|
|
86
|
+
|
|
87
|
+
@property
|
|
88
|
+
def state(self) -> str:
|
|
89
|
+
"""str: `provisioning` while its machine is prepared, `running` once
|
|
90
|
+
runs can execute there, then `stopping`, and `terminated` once it is
|
|
91
|
+
gone; `failed` when it could not start, with `error` saying why."""
|
|
92
|
+
return str(self._row.get("state") or "")
|
|
93
|
+
|
|
94
|
+
@property
|
|
95
|
+
def cpus(self) -> Optional[int]:
|
|
96
|
+
"""int: vCPUs reserved for the session and shared by its runs."""
|
|
97
|
+
return _int_or_none(self._row.get("cpus"))
|
|
98
|
+
|
|
99
|
+
@property
|
|
100
|
+
def mem_mb(self) -> Optional[int]:
|
|
101
|
+
"""int: Memory reserved for the session in MB, shared by its runs."""
|
|
102
|
+
return _int_or_none(self._row.get("mem_mb"))
|
|
103
|
+
|
|
104
|
+
@property
|
|
105
|
+
def storage_mb(self) -> Optional[int]:
|
|
106
|
+
"""int: Storage reserved for the session in MB, for the runs and disks
|
|
107
|
+
copied there."""
|
|
108
|
+
return _int_or_none(self._row.get("storage_mb"))
|
|
109
|
+
|
|
110
|
+
@property
|
|
111
|
+
def storage_gb(self) -> Optional[int]:
|
|
112
|
+
"""int: The disk in GB, the unit `Sessions.create` takes; rounded
|
|
113
|
+
down when the service gave an uneven number of MB."""
|
|
114
|
+
megabytes = self.storage_mb
|
|
115
|
+
return None if megabytes is None else megabytes // _MB_PER_GB
|
|
116
|
+
|
|
117
|
+
@property
|
|
118
|
+
def instance_type(self) -> Optional[str]:
|
|
119
|
+
"""str: The class of machine the session runs on."""
|
|
120
|
+
value = self._row.get("instance_type")
|
|
121
|
+
return None if value is None else str(value)
|
|
122
|
+
|
|
123
|
+
@property
|
|
124
|
+
def error(self) -> Optional[str]:
|
|
125
|
+
"""str: Why the session failed; None unless `state` is `failed`."""
|
|
126
|
+
value = self._row.get("error")
|
|
127
|
+
return None if value is None else str(value)
|
|
128
|
+
|
|
129
|
+
@property
|
|
130
|
+
def created_at(self) -> Optional[str]:
|
|
131
|
+
"""str: When the session was created, ISO 8601."""
|
|
132
|
+
return _str_or_none(self._row.get("created_at"))
|
|
133
|
+
|
|
134
|
+
@property
|
|
135
|
+
def started_at(self) -> Optional[str]:
|
|
136
|
+
"""str: When the session first reached `running`, ISO 8601; None
|
|
137
|
+
before then."""
|
|
138
|
+
return _str_or_none(self._row.get("started_at"))
|
|
139
|
+
|
|
140
|
+
@property
|
|
141
|
+
def stopped_at(self) -> Optional[str]:
|
|
142
|
+
"""str: When the session stopped, ISO 8601; None while it runs."""
|
|
143
|
+
return _str_or_none(self._row.get("stopped_at"))
|
|
144
|
+
|
|
145
|
+
def refresh(self) -> "Session":
|
|
146
|
+
"""Read the session again, so its attributes are current.
|
|
147
|
+
|
|
148
|
+
Returns:
|
|
149
|
+
Session: This session.
|
|
150
|
+
|
|
151
|
+
Raises:
|
|
152
|
+
NotFound: The session no longer exists.
|
|
153
|
+
"""
|
|
154
|
+
client, creds = self._client._account()
|
|
155
|
+
with _translated():
|
|
156
|
+
self._row = _sessions.get(client, creds, self.id)
|
|
157
|
+
return self
|
|
158
|
+
|
|
159
|
+
def wait(
|
|
160
|
+
self, state: str = "running", *, timeout: Optional[float] = None
|
|
161
|
+
) -> "Session":
|
|
162
|
+
"""Wait until the session is in `state`, as `machine sessions create`
|
|
163
|
+
waits for `running`.
|
|
164
|
+
|
|
165
|
+
A new session takes minutes to reach `running` while its machine is
|
|
166
|
+
prepared. Waiting for `running` ends at once when the session can no
|
|
167
|
+
longer get there, such as one that failed.
|
|
168
|
+
|
|
169
|
+
Example:
|
|
170
|
+
>>> session = client.sessions.create(cpus=4, wait=False)
|
|
171
|
+
>>> session.wait("running", timeout=900)
|
|
172
|
+
|
|
173
|
+
Args:
|
|
174
|
+
state (str, optional): The state to wait for. Defaults to
|
|
175
|
+
`running`.
|
|
176
|
+
timeout (float, optional): Seconds to wait; None waits without a
|
|
177
|
+
limit.
|
|
178
|
+
|
|
179
|
+
Returns:
|
|
180
|
+
Session: This session, read in `state`.
|
|
181
|
+
|
|
182
|
+
Raises:
|
|
183
|
+
NotRunning: Waiting for `running` and the session failed or
|
|
184
|
+
stopped; `error` says why.
|
|
185
|
+
Timeout: The session was not in `state` within `timeout`.
|
|
186
|
+
"""
|
|
187
|
+
client, creds = self._client._account()
|
|
188
|
+
with _translated():
|
|
189
|
+
self._row = _sessions.wait_until(
|
|
190
|
+
client, creds, self.id, state, timeout_s=timeout
|
|
191
|
+
)
|
|
192
|
+
return self
|
|
193
|
+
|
|
194
|
+
def rename(self, new_name: str) -> "Session":
|
|
195
|
+
"""Rename the session, as `machine sessions rename` does.
|
|
196
|
+
|
|
197
|
+
Its machine, its runs and its id are unchanged.
|
|
198
|
+
|
|
199
|
+
Args:
|
|
200
|
+
new_name (str): The new name: up to 64 letters, digits, dots,
|
|
201
|
+
dashes and underscores, starting with a letter or digit.
|
|
202
|
+
|
|
203
|
+
Returns:
|
|
204
|
+
Session: This session, renamed.
|
|
205
|
+
|
|
206
|
+
Raises:
|
|
207
|
+
InvalidArgument: `new_name` is not a valid session name.
|
|
208
|
+
AlreadyExists: Another session has this name.
|
|
209
|
+
"""
|
|
210
|
+
_require_valid_name(new_name)
|
|
211
|
+
client, creds = self._client._account()
|
|
212
|
+
with _translated():
|
|
213
|
+
api.auth.authed(
|
|
214
|
+
creds, lambda t: client.session_rename(t, self.id, new_name)
|
|
215
|
+
)
|
|
216
|
+
self._row = {**self._row, "name": new_name}
|
|
217
|
+
return self
|
|
218
|
+
|
|
219
|
+
def keep(self, minutes: int) -> "Session":
|
|
220
|
+
"""Keep the session running while it is idle, as `machine sessions keep` does.
|
|
221
|
+
|
|
222
|
+
A session is idle while it serves no command. An idle session stops
|
|
223
|
+
after the plan's idle time. Keep holds it for `minutes`, up to the
|
|
224
|
+
plan's limit. A later keep replaces the hold.
|
|
225
|
+
|
|
226
|
+
Args:
|
|
227
|
+
minutes (int): How long to hold the session, in minutes.
|
|
228
|
+
|
|
229
|
+
Returns:
|
|
230
|
+
Session: This session, kept.
|
|
231
|
+
|
|
232
|
+
Raises:
|
|
233
|
+
InvalidArgument: `minutes` is less than 1.
|
|
234
|
+
Forbidden: `minutes` is more than the plan allows.
|
|
235
|
+
NotFound: The session is not running.
|
|
236
|
+
"""
|
|
237
|
+
if minutes < 1:
|
|
238
|
+
raise InvalidArgument(f"Keep for at least 1 minute, not {minutes}.")
|
|
239
|
+
client, creds = self._client._account()
|
|
240
|
+
with _translated():
|
|
241
|
+
self._row = _sessions.keep(client, creds, self.id, minutes)
|
|
242
|
+
return self
|
|
243
|
+
|
|
244
|
+
def delete(self, *, wait: bool = True, timeout: Optional[float] = None) -> None:
|
|
245
|
+
"""Delete the session, as `machine sessions delete` does.
|
|
246
|
+
|
|
247
|
+
Its machines stop, their runs are published to shared storage, and
|
|
248
|
+
the session stops using credits. A session already gone is not an error,
|
|
249
|
+
so cleanup code can call this unconditionally. When it is the
|
|
250
|
+
client's current session, the client has none after.
|
|
251
|
+
|
|
252
|
+
Example:
|
|
253
|
+
>>> try:
|
|
254
|
+
... run_tests(client)
|
|
255
|
+
... finally:
|
|
256
|
+
... session.delete()
|
|
257
|
+
|
|
258
|
+
Args:
|
|
259
|
+
wait (bool, optional): Return once the session is gone. Defaults
|
|
260
|
+
to True.
|
|
261
|
+
timeout (float, optional): Seconds to wait; None waits without a
|
|
262
|
+
limit.
|
|
263
|
+
|
|
264
|
+
Raises:
|
|
265
|
+
Timeout: The session was not gone within `timeout`.
|
|
266
|
+
"""
|
|
267
|
+
client, creds = self._client._account()
|
|
268
|
+
with _translated():
|
|
269
|
+
_sessions.delete(client, creds, self.id)
|
|
270
|
+
if wait:
|
|
271
|
+
_sessions.wait_until_gone(client, creds, self.id, timeout_s=timeout)
|
|
272
|
+
api.store.clear_session(self.id)
|
|
273
|
+
self._client._forget(self.id)
|
|
274
|
+
|
|
275
|
+
def as_json(self) -> dict[str, Any]:
|
|
276
|
+
"""The session's attributes as a JSON-serializable dict.
|
|
277
|
+
|
|
278
|
+
Returns:
|
|
279
|
+
dict[str, Any]: One key per attribute, `id` through `stopped_at`.
|
|
280
|
+
"""
|
|
281
|
+
return {field: getattr(self, field) for field in FIELDS}
|
|
282
|
+
|
|
283
|
+
def __enter__(self) -> "Session":
|
|
284
|
+
return self
|
|
285
|
+
|
|
286
|
+
def __exit__(self, *exc: object) -> None:
|
|
287
|
+
self.delete()
|
|
288
|
+
|
|
289
|
+
def __eq__(self, other: object) -> bool:
|
|
290
|
+
return isinstance(other, Session) and other.id == self.id
|
|
291
|
+
|
|
292
|
+
def __hash__(self) -> int:
|
|
293
|
+
return hash(self.id)
|
|
294
|
+
|
|
295
|
+
def __repr__(self) -> str:
|
|
296
|
+
return f"Session(name={self.name!r}, id={self.id!r}, state={self.state!r})"
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
class Sessions:
|
|
300
|
+
"""The account's sessions, as `Client.sessions`; not created directly.
|
|
301
|
+
|
|
302
|
+
Call it to list them, as `machine sessions` does. A session named by
|
|
303
|
+
`session` is a `Session`, or its name, id or unique id prefix; where it
|
|
304
|
+
may be left out, the account's only session is meant.
|
|
305
|
+
|
|
306
|
+
Example:
|
|
307
|
+
>>> [s.name for s in client.sessions()]
|
|
308
|
+
['ci-1', 'ci-2']
|
|
309
|
+
>>> client.sessions.use("ci-1")
|
|
310
|
+
"""
|
|
311
|
+
|
|
312
|
+
def __init__(self, client: "Client") -> None:
|
|
313
|
+
self._client = client
|
|
314
|
+
|
|
315
|
+
@overload
|
|
316
|
+
def __call__(
|
|
317
|
+
self, *, watch: Literal[False] = ..., timeout: Optional[float] = ...
|
|
318
|
+
) -> builtins.list[Session]: ...
|
|
319
|
+
|
|
320
|
+
@overload
|
|
321
|
+
def __call__(
|
|
322
|
+
self, *, watch: Literal[True], timeout: Optional[float] = ...
|
|
323
|
+
) -> Generator[builtins.list[Session], None, None]: ...
|
|
324
|
+
|
|
325
|
+
def __call__(
|
|
326
|
+
self, *, watch: bool = False, timeout: Optional[float] = None
|
|
327
|
+
) -> "builtins.list[Session] | Generator[builtins.list[Session], None, None]":
|
|
328
|
+
"""List the account's sessions, as `machine sessions` does; the
|
|
329
|
+
same as `list`.
|
|
330
|
+
|
|
331
|
+
Args:
|
|
332
|
+
watch (bool, optional): Yield the list each time it changes.
|
|
333
|
+
Defaults to False.
|
|
334
|
+
timeout (float, optional): With `watch`, end the generator after
|
|
335
|
+
this many seconds, without raising; None watches until the
|
|
336
|
+
caller leaves the loop.
|
|
337
|
+
|
|
338
|
+
Returns:
|
|
339
|
+
list[Session]: The sessions; with `watch`, an iterator of such
|
|
340
|
+
lists.
|
|
341
|
+
"""
|
|
342
|
+
return _args.watched(self._rows, self._sessions, watch, timeout)
|
|
343
|
+
|
|
344
|
+
@overload
|
|
345
|
+
def list(
|
|
346
|
+
self, *, watch: Literal[False] = ..., timeout: Optional[float] = ...
|
|
347
|
+
) -> builtins.list[Session]: ...
|
|
348
|
+
|
|
349
|
+
@overload
|
|
350
|
+
def list(
|
|
351
|
+
self, *, watch: Literal[True], timeout: Optional[float] = ...
|
|
352
|
+
) -> Generator[builtins.list[Session], None, None]: ...
|
|
353
|
+
|
|
354
|
+
def list(
|
|
355
|
+
self, *, watch: bool = False, timeout: Optional[float] = None
|
|
356
|
+
) -> "builtins.list[Session] | Generator[builtins.list[Session], None, None]":
|
|
357
|
+
"""List the account's sessions, as `machine sessions list` does.
|
|
358
|
+
|
|
359
|
+
Deleted sessions are left out. With `watch`, it yields the list at
|
|
360
|
+
once, then again each time it changes: a session created, deleted,
|
|
361
|
+
or changing state. Leave the loop, or pass `timeout`, to stop.
|
|
362
|
+
|
|
363
|
+
Example:
|
|
364
|
+
>>> for sessions in client.sessions.list(watch=True, timeout=900):
|
|
365
|
+
... if all(s.state == "running" for s in sessions):
|
|
366
|
+
... break
|
|
367
|
+
|
|
368
|
+
Args:
|
|
369
|
+
watch (bool, optional): Yield the list each time it changes.
|
|
370
|
+
Defaults to False.
|
|
371
|
+
timeout (float, optional): With `watch`, end the generator after
|
|
372
|
+
this many seconds, without raising; None watches until the
|
|
373
|
+
caller leaves the loop.
|
|
374
|
+
|
|
375
|
+
Returns:
|
|
376
|
+
list[Session]: The sessions; with `watch`, an iterator of such
|
|
377
|
+
lists.
|
|
378
|
+
|
|
379
|
+
Raises:
|
|
380
|
+
NotSignedIn: There are no credentials.
|
|
381
|
+
"""
|
|
382
|
+
return _args.watched(self._rows, self._sessions, watch, timeout)
|
|
383
|
+
|
|
384
|
+
def create(
|
|
385
|
+
self,
|
|
386
|
+
name: Optional[str] = None,
|
|
387
|
+
*,
|
|
388
|
+
cpus: int = 1,
|
|
389
|
+
mem: Optional[int] = None,
|
|
390
|
+
storage: Optional[int] = None,
|
|
391
|
+
class_: Optional[str] = None,
|
|
392
|
+
wait: bool = True,
|
|
393
|
+
timeout: Optional[float] = None,
|
|
394
|
+
) -> Session:
|
|
395
|
+
"""Create a session, as `machine sessions create` does.
|
|
396
|
+
|
|
397
|
+
The session uses credits from the moment it is created until it
|
|
398
|
+
stops. Create it in a `with` block to have it deleted when the
|
|
399
|
+
block exits, however it exits; without `with`, it lives until
|
|
400
|
+
`Session.delete`, or until it has been idle for its plan's idle time. Its memory and storage default to what `cpus` buys
|
|
401
|
+
on the account's hardware class. `use` makes it the client's current
|
|
402
|
+
session.
|
|
403
|
+
|
|
404
|
+
Example:
|
|
405
|
+
>>> with client.sessions.create("ci-1", cpus=4) as session:
|
|
406
|
+
... client.sessions.use(session)
|
|
407
|
+
... run = client.create(disk="app")
|
|
408
|
+
|
|
409
|
+
Args:
|
|
410
|
+
name (str, optional): The session's name: up to 64 letters,
|
|
411
|
+
digits, dots, dashes and underscores, starting with a letter
|
|
412
|
+
or digit. One is generated when omitted.
|
|
413
|
+
cpus (int, optional): vCPUs to reserve. Defaults to 1.
|
|
414
|
+
mem (int, optional): Memory to reserve in MB.
|
|
415
|
+
storage (int, optional): Disk to reserve, in GB; the session
|
|
416
|
+
reports it as `storage_mb`, and `storage_gb` in these terms.
|
|
417
|
+
class_ (str, optional): The hardware class to run on; defaults
|
|
418
|
+
to the plan's. The trailing underscore avoids the Python
|
|
419
|
+
keyword.
|
|
420
|
+
wait (bool, optional): Return once the session is running.
|
|
421
|
+
Defaults to True.
|
|
422
|
+
timeout (float, optional): Seconds to wait; None waits without a
|
|
423
|
+
limit.
|
|
424
|
+
|
|
425
|
+
Returns:
|
|
426
|
+
Session: The new session.
|
|
427
|
+
|
|
428
|
+
Raises:
|
|
429
|
+
InvalidArgument: `name` is not a valid session name.
|
|
430
|
+
AlreadyExists: A session has this name.
|
|
431
|
+
Forbidden: The account may not create sessions, such as one that
|
|
432
|
+
is not active or over its plan's limits, or the class is not
|
|
433
|
+
sold to the account's plan.
|
|
434
|
+
NoCapacity: No host of the class has room for the session now.
|
|
435
|
+
Retry later, ask for less, or pick another class.
|
|
436
|
+
ClassUnavailable: No machine of the class is in service. Pick
|
|
437
|
+
another class.
|
|
438
|
+
NotRunning: The session failed to start; `error` says why.
|
|
439
|
+
Timeout: It was not running within `timeout`.
|
|
440
|
+
"""
|
|
441
|
+
if name is not None:
|
|
442
|
+
_require_valid_name(name)
|
|
443
|
+
client, creds = self._client._account()
|
|
444
|
+
with _translated():
|
|
445
|
+
row = _sessions.create(
|
|
446
|
+
client,
|
|
447
|
+
creds,
|
|
448
|
+
cpus,
|
|
449
|
+
name,
|
|
450
|
+
class_,
|
|
451
|
+
mem,
|
|
452
|
+
None if storage is None else storage * _MB_PER_GB,
|
|
453
|
+
)
|
|
454
|
+
session = Session(self._client, row)
|
|
455
|
+
if wait:
|
|
456
|
+
session.wait("running", timeout=timeout)
|
|
457
|
+
return session
|
|
458
|
+
|
|
459
|
+
def use(
|
|
460
|
+
self,
|
|
461
|
+
session: "Session | str | None" = None,
|
|
462
|
+
*,
|
|
463
|
+
wait: bool = True,
|
|
464
|
+
timeout: Optional[float] = None,
|
|
465
|
+
) -> Session:
|
|
466
|
+
"""Make a session the client's current session, as `machine sessions
|
|
467
|
+
use` does.
|
|
468
|
+
|
|
469
|
+
A session this machine already holds a tunnel to is RECHECKED, not
|
|
470
|
+
trusted: the tunnel outlives a daemon that has gone silent, so `use`
|
|
471
|
+
tests it and reconnects through a fresh tunnel when it does not
|
|
472
|
+
answer. Otherwise it connects, waiting while the session is still
|
|
473
|
+
provisioning. Only this client changes: the CLI's current session is
|
|
474
|
+
left as it is.
|
|
475
|
+
|
|
476
|
+
Example:
|
|
477
|
+
>>> session = client.sessions.use("ci-1")
|
|
478
|
+
>>> client.session == session
|
|
479
|
+
True
|
|
480
|
+
|
|
481
|
+
Args:
|
|
482
|
+
session (Session or str, optional): The session; defaults to the
|
|
483
|
+
only one.
|
|
484
|
+
wait (bool, optional): Wait while the session is provisioning;
|
|
485
|
+
False refuses a session that is not running yet. Defaults to
|
|
486
|
+
True.
|
|
487
|
+
timeout (float, optional): Seconds to wait; None waits without a
|
|
488
|
+
limit.
|
|
489
|
+
|
|
490
|
+
Returns:
|
|
491
|
+
Session: The session, now current.
|
|
492
|
+
|
|
493
|
+
Raises:
|
|
494
|
+
NotFound: No session matches.
|
|
495
|
+
InvalidArgument: The prefix matches more than one session, or
|
|
496
|
+
none is named and there are several.
|
|
497
|
+
NotRunning: The session is not running and `wait` is False, or it
|
|
498
|
+
failed.
|
|
499
|
+
ServiceUnavailable: The session does not respond.
|
|
500
|
+
"""
|
|
501
|
+
known = self.show(session)
|
|
502
|
+
with _translated():
|
|
503
|
+
if api.store.session_connected(known.id) and _sessions.recheck(known.id):
|
|
504
|
+
self._client._use(known)
|
|
505
|
+
return known
|
|
506
|
+
return self.connect(known, wait=wait, timeout=timeout)
|
|
507
|
+
|
|
508
|
+
def show(self, session: "Session | str | None" = None) -> Session:
|
|
509
|
+
"""Read a session, as `machine sessions show` does.
|
|
510
|
+
|
|
511
|
+
Args:
|
|
512
|
+
session (Session or str, optional): The session; defaults to the
|
|
513
|
+
only one.
|
|
514
|
+
|
|
515
|
+
Returns:
|
|
516
|
+
Session: The session, read now.
|
|
517
|
+
|
|
518
|
+
Raises:
|
|
519
|
+
NotFound: No session matches; a deleted session is not found.
|
|
520
|
+
InvalidArgument: The prefix matches more than one session, or
|
|
521
|
+
none is named and there are several.
|
|
522
|
+
"""
|
|
523
|
+
client, creds = self._client._account()
|
|
524
|
+
ref = _ref(session)
|
|
525
|
+
with _translated():
|
|
526
|
+
session_id = _sessions.resolve_ref_or_sole(self._rows(), ref)
|
|
527
|
+
row = _sessions.get(client, creds, session_id)
|
|
528
|
+
if row.get("state") == _DELETED:
|
|
529
|
+
raise NotFound(f"No such session: {ref!r}.")
|
|
530
|
+
return Session(self._client, row)
|
|
531
|
+
|
|
532
|
+
def delete(
|
|
533
|
+
self,
|
|
534
|
+
session: "Session | str | None" = None,
|
|
535
|
+
*,
|
|
536
|
+
all: bool = False,
|
|
537
|
+
wait: bool = True,
|
|
538
|
+
timeout: Optional[float] = None,
|
|
539
|
+
) -> builtins.list[Session]:
|
|
540
|
+
"""Delete a session, or every session, as `machine sessions delete`
|
|
541
|
+
does.
|
|
542
|
+
|
|
543
|
+
Its machines stop, their runs are published to shared storage, and
|
|
544
|
+
the session stops costing. Already gone is not an error. A prune is
|
|
545
|
+
refused while any session is live, so `all` is what
|
|
546
|
+
`storage.prune` needs.
|
|
547
|
+
|
|
548
|
+
Example:
|
|
549
|
+
>>> client.sessions.delete("ci-1")
|
|
550
|
+
>>> client.sessions.delete(all=True)
|
|
551
|
+
|
|
552
|
+
Args:
|
|
553
|
+
session (Session or str, optional): The session; defaults to the
|
|
554
|
+
only one.
|
|
555
|
+
all (bool, optional): Delete every session. Defaults to False.
|
|
556
|
+
wait (bool, optional): Return once the sessions are gone; with
|
|
557
|
+
`all` they are asked one after another and waited for after
|
|
558
|
+
that, so N sessions cost one wait. False returns once each
|
|
559
|
+
request is accepted, as `machine sessions delete -a` does.
|
|
560
|
+
Defaults to True.
|
|
561
|
+
timeout (float, optional): Seconds to wait; None waits without a
|
|
562
|
+
limit.
|
|
563
|
+
|
|
564
|
+
Returns:
|
|
565
|
+
list[Session]: The sessions deleted.
|
|
566
|
+
|
|
567
|
+
Raises:
|
|
568
|
+
InvalidArgument: A session is named with `all`.
|
|
569
|
+
NotFound: No session matches.
|
|
570
|
+
ApiError: With `all`, some sessions could not be deleted; the
|
|
571
|
+
message names the first.
|
|
572
|
+
"""
|
|
573
|
+
if all:
|
|
574
|
+
if session is not None:
|
|
575
|
+
raise InvalidArgument("Name a session or pass all=True, not both.")
|
|
576
|
+
return self._delete_all(wait=wait, timeout=timeout)
|
|
577
|
+
doomed = session if isinstance(session, Session) else self.show(session)
|
|
578
|
+
doomed.delete(wait=wait, timeout=timeout)
|
|
579
|
+
return [doomed]
|
|
580
|
+
|
|
581
|
+
def rename(self, session: "Session | str", new_name: str) -> Session:
|
|
582
|
+
"""Rename a session, as `machine sessions rename` does.
|
|
583
|
+
|
|
584
|
+
Its machine and its runs are unchanged.
|
|
585
|
+
|
|
586
|
+
Args:
|
|
587
|
+
session (Session or str): The session.
|
|
588
|
+
new_name (str): The new name: up to 64 letters, digits, dots,
|
|
589
|
+
dashes and underscores, starting with a letter or digit.
|
|
590
|
+
|
|
591
|
+
Returns:
|
|
592
|
+
Session: The session, renamed.
|
|
593
|
+
|
|
594
|
+
Raises:
|
|
595
|
+
InvalidArgument: `new_name` is not a valid session name.
|
|
596
|
+
NotFound: No session matches.
|
|
597
|
+
AlreadyExists: Another session has this name.
|
|
598
|
+
"""
|
|
599
|
+
target = session if isinstance(session, Session) else self.show(session)
|
|
600
|
+
return target.rename(new_name)
|
|
601
|
+
|
|
602
|
+
def keep(self, session: "Session | str", minutes: int) -> Session:
|
|
603
|
+
"""Keep a session running while it is idle, as `machine sessions keep` does.
|
|
604
|
+
|
|
605
|
+
Args:
|
|
606
|
+
session (Session or str): The session.
|
|
607
|
+
minutes (int): How long to hold it, in minutes, up to the plan's
|
|
608
|
+
limit.
|
|
609
|
+
|
|
610
|
+
Returns:
|
|
611
|
+
Session: The session, kept.
|
|
612
|
+
|
|
613
|
+
Raises:
|
|
614
|
+
InvalidArgument: `minutes` is less than 1.
|
|
615
|
+
Forbidden: `minutes` is more than the plan allows.
|
|
616
|
+
NotFound: No session matches, or it is not running.
|
|
617
|
+
"""
|
|
618
|
+
target = session if isinstance(session, Session) else self.show(session)
|
|
619
|
+
return target.keep(minutes)
|
|
620
|
+
|
|
621
|
+
def connect(
|
|
622
|
+
self,
|
|
623
|
+
session: "Session | str | None" = None,
|
|
624
|
+
*,
|
|
625
|
+
wait: bool = True,
|
|
626
|
+
timeout: Optional[float] = None,
|
|
627
|
+
) -> Session:
|
|
628
|
+
"""Connect to a session and make it the client's current session, as
|
|
629
|
+
`machine sessions connect` does.
|
|
630
|
+
|
|
631
|
+
Opens this machine's tunnel to the session, waiting while it is
|
|
632
|
+
still provisioning. `use` is the everyday verb.
|
|
633
|
+
|
|
634
|
+
Args:
|
|
635
|
+
session (Session or str, optional): The session; defaults to the
|
|
636
|
+
only one.
|
|
637
|
+
wait (bool, optional): Wait while the session is provisioning;
|
|
638
|
+
False refuses a session that is not running yet. Defaults to
|
|
639
|
+
True.
|
|
640
|
+
timeout (float, optional): Seconds to wait; None waits without a
|
|
641
|
+
limit.
|
|
642
|
+
|
|
643
|
+
Returns:
|
|
644
|
+
Session: The session, now current.
|
|
645
|
+
|
|
646
|
+
Raises:
|
|
647
|
+
NotFound: No session matches.
|
|
648
|
+
NotRunning: The session is not running and `wait` is False, or it
|
|
649
|
+
failed.
|
|
650
|
+
ServiceUnavailable: The session does not respond.
|
|
651
|
+
"""
|
|
652
|
+
client, creds = self._client._account()
|
|
653
|
+
with _translated():
|
|
654
|
+
row = _sessions.connect(
|
|
655
|
+
client, creds, _ref(session), wait=wait, timeout_s=timeout
|
|
656
|
+
)
|
|
657
|
+
made = Session(self._client, row)
|
|
658
|
+
self._client._use(made)
|
|
659
|
+
return made
|
|
660
|
+
|
|
661
|
+
def disconnect(self, session: "Session | str | None" = None) -> bool:
|
|
662
|
+
"""Close this machine's tunnel to a session, as `machine sessions
|
|
663
|
+
disconnect` does.
|
|
664
|
+
|
|
665
|
+
The session keeps running. The tunnel is shared on this machine, so
|
|
666
|
+
the CLI and every other program lose it too; the next command that
|
|
667
|
+
needs it opens it again.
|
|
668
|
+
|
|
669
|
+
Args:
|
|
670
|
+
session (Session or str, optional): The session; defaults to the
|
|
671
|
+
client's current one.
|
|
672
|
+
|
|
673
|
+
Returns:
|
|
674
|
+
bool: True when a tunnel was closed.
|
|
675
|
+
|
|
676
|
+
Raises:
|
|
677
|
+
InvalidArgument: None is named and the client has no session.
|
|
678
|
+
NotFound: No session matches.
|
|
679
|
+
"""
|
|
680
|
+
target = self._client.session if session is None else None
|
|
681
|
+
if session is not None:
|
|
682
|
+
target = session if isinstance(session, Session) else self.show(session)
|
|
683
|
+
if target is None:
|
|
684
|
+
raise InvalidArgument("No session. Name the session to disconnect.")
|
|
685
|
+
with _translated():
|
|
686
|
+
closed = _sessions.tunnel_stop(target.id)
|
|
687
|
+
self._client._forget(target.id)
|
|
688
|
+
return closed
|
|
689
|
+
|
|
690
|
+
def _list(self) -> builtins.list[Session]:
|
|
691
|
+
return self._sessions(self._rows())
|
|
692
|
+
|
|
693
|
+
def _sessions(self, rows: builtins.list[dict[str, Any]]) -> builtins.list[Session]:
|
|
694
|
+
return [Session(self._client, row) for row in rows]
|
|
695
|
+
|
|
696
|
+
def _rows(self) -> builtins.list[dict[str, Any]]:
|
|
697
|
+
"""The account's sessions, less the deleted ones: the service's list can
|
|
698
|
+
trail a deletion that has already completed."""
|
|
699
|
+
client, creds = self._client._account()
|
|
700
|
+
with _translated():
|
|
701
|
+
rows = api.auth.authed(creds, client.session_list)
|
|
702
|
+
return [row for row in rows if row.get("state") != _DELETED]
|
|
703
|
+
|
|
704
|
+
def _delete_all(
|
|
705
|
+
self, *, wait: bool, timeout: Optional[float]
|
|
706
|
+
) -> builtins.list[Session]:
|
|
707
|
+
"""Delete every session, each in turn, reporting the first failure
|
|
708
|
+
after trying them all.
|
|
709
|
+
|
|
710
|
+
Asked one after another rather than waited for one after another: the
|
|
711
|
+
wait, when there is one, comes after every session has been told to
|
|
712
|
+
go, so N sessions cost one wait and not N.
|
|
713
|
+
"""
|
|
714
|
+
done: builtins.list[Session] = []
|
|
715
|
+
errors: builtins.list[str] = []
|
|
716
|
+
for session in self._list():
|
|
717
|
+
try:
|
|
718
|
+
session.delete(wait=False)
|
|
719
|
+
done.append(session)
|
|
720
|
+
except Exception as exc:
|
|
721
|
+
errors.append(f"{session.name}: {exc}")
|
|
722
|
+
if errors:
|
|
723
|
+
raise ApiError(
|
|
724
|
+
f"Deleted {len(done)}, {len(errors)} failed; first {errors[0]}"
|
|
725
|
+
)
|
|
726
|
+
if wait:
|
|
727
|
+
for session in done:
|
|
728
|
+
with _translated():
|
|
729
|
+
client, creds = self._client._account()
|
|
730
|
+
_sessions.wait_until_gone(
|
|
731
|
+
client, creds, session.id, timeout_s=timeout
|
|
732
|
+
)
|
|
733
|
+
return done
|
|
734
|
+
|
|
735
|
+
|
|
736
|
+
def _ref(session: "Session | str | None") -> Optional[str]:
|
|
737
|
+
"""What names `session` to the service: its id, or the text given."""
|
|
738
|
+
return session.id if isinstance(session, Session) else session
|
|
739
|
+
|
|
740
|
+
|
|
741
|
+
def _require_valid_name(name: str) -> None:
|
|
742
|
+
if not _sessions.valid_name(name):
|
|
743
|
+
raise InvalidArgument(f"Invalid session name {name!r}: {_sessions.NAME_RULE}.")
|
|
744
|
+
|
|
745
|
+
|
|
746
|
+
def _int_or_none(value: Any) -> Optional[int]:
|
|
747
|
+
return None if value is None else int(value)
|
|
748
|
+
|
|
749
|
+
|
|
750
|
+
def _str_or_none(value: Any) -> Optional[str]:
|
|
751
|
+
return None if value is None else str(value)
|