-
Notifications
You must be signed in to change notification settings - Fork 887
Expand file tree
/
Copy pathsandbox_api.py
More file actions
418 lines (348 loc) · 12.6 KB
/
sandbox_api.py
File metadata and controls
418 lines (348 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
import datetime
from typing import Any, Dict, List, Optional, cast
from packaging.version import Version
from typing_extensions import Unpack
from e2b.api import SandboxCreateResponse, handle_api_exception
from e2b.api.client.api.sandboxes import (
delete_sandboxes_sandbox_id,
get_sandboxes_sandbox_id,
get_sandboxes_sandbox_id_metrics,
post_sandboxes,
post_sandboxes_sandbox_id_connect,
post_sandboxes_sandbox_id_pause,
post_sandboxes_sandbox_id_snapshots,
post_sandboxes_sandbox_id_timeout,
)
from e2b.api.client.api.templates import delete_templates_template_id
from e2b.api.client.models import (
ConnectSandbox,
Error,
NewSandbox,
PostSandboxesSandboxIDSnapshotsBody,
PostSandboxesSandboxIDTimeoutBody,
Sandbox,
SandboxAutoResumeConfig,
SandboxNetworkConfig,
SandboxVolumeMount as SandboxVolumeMountAPI,
)
from e2b.api.client.types import UNSET
from e2b.api.client_async import get_api_client
from e2b.connection_config import ApiParams, ConnectionConfig
from e2b.exceptions import (
SandboxException,
SandboxNotFoundException,
TemplateException,
)
from e2b.sandbox.main import SandboxBase
from e2b.sandbox.sandbox_api import (
SandboxLifecycle,
get_auto_resume_enabled,
McpServer,
SandboxInfo,
SandboxMetrics,
SandboxNetworkOpts,
SandboxQuery,
SnapshotInfo,
)
from e2b.sandbox_async.paginator import AsyncSandboxPaginator
class SandboxApi(SandboxBase):
@staticmethod
def list(
query: Optional[SandboxQuery] = None,
limit: Optional[int] = None,
next_token: Optional[str] = None,
**opts: Unpack[ApiParams],
) -> AsyncSandboxPaginator:
"""
List all running sandboxes.
:param query: Filter the list of sandboxes by metadata or state, e.g. `SandboxListQuery(metadata={"key": "value"})` or `SandboxListQuery(state=[SandboxState.RUNNING])`
:param limit: Maximum number of sandboxes to return per page
:param next_token: Token for pagination
:return: List of running sandboxes
"""
return AsyncSandboxPaginator(
query=query,
limit=limit,
next_token=next_token,
**opts,
)
@classmethod
async def _cls_get_info(
cls,
sandbox_id: str,
**opts: Unpack[ApiParams],
) -> SandboxInfo:
"""
Get the sandbox info.
:param sandbox_id: Sandbox ID
:return: Sandbox info
"""
config = ConnectionConfig(**opts)
api_client = get_api_client(config)
res = await get_sandboxes_sandbox_id.asyncio_detailed(
sandbox_id,
client=api_client,
)
if res.status_code == 404:
raise SandboxNotFoundException(f"Sandbox {sandbox_id} not found")
if res.status_code >= 300:
raise handle_api_exception(res)
if res.parsed is None:
raise Exception("Body of the request is None")
if isinstance(res.parsed, Error):
raise SandboxException(f"{res.parsed.message}: Request failed")
return SandboxInfo._from_sandbox_detail(res.parsed)
@classmethod
async def _cls_kill(
cls,
sandbox_id: str,
**opts: Unpack[ApiParams],
) -> bool:
config = ConnectionConfig(**opts)
if config.debug:
# Skip killing the sandbox in debug mode
return True
api_client = get_api_client(config)
res = await delete_sandboxes_sandbox_id.asyncio_detailed(
sandbox_id,
client=api_client,
)
if res.status_code == 404:
return False
if res.status_code >= 300:
raise handle_api_exception(res)
return True
@classmethod
async def _cls_set_timeout(
cls,
sandbox_id: str,
timeout: int,
**opts: Unpack[ApiParams],
) -> None:
config = ConnectionConfig(**opts)
if config.debug:
# Skip setting the timeout in debug mode
return
api_client = get_api_client(config)
res = await post_sandboxes_sandbox_id_timeout.asyncio_detailed(
sandbox_id,
client=api_client,
body=PostSandboxesSandboxIDTimeoutBody(timeout=timeout),
)
if res.status_code == 404:
raise SandboxNotFoundException(f"Sandbox {sandbox_id} not found")
if res.status_code >= 300:
raise handle_api_exception(res)
@classmethod
async def _create_sandbox(
cls,
template: str,
timeout: int,
auto_pause: Optional[bool],
allow_internet_access: bool,
metadata: Optional[Dict[str, str]],
env_vars: Optional[Dict[str, str]],
secure: bool,
mcp: Optional[McpServer] = None,
network: Optional[SandboxNetworkOpts] = None,
lifecycle: Optional[SandboxLifecycle] = None,
volume_mounts: Optional[List[SandboxVolumeMountAPI]] = None,
**opts: Unpack[ApiParams],
) -> SandboxCreateResponse:
config = ConnectionConfig(**opts)
should_auto_pause = (
lifecycle["on_timeout"] == "pause" if lifecycle is not None else auto_pause
)
auto_resume_enabled = get_auto_resume_enabled(lifecycle)
body = NewSandbox(
template_id=template,
auto_pause=(should_auto_pause if should_auto_pause is not None else UNSET),
metadata=metadata or {},
timeout=timeout,
env_vars=env_vars or {},
mcp=cast(Any, mcp) or UNSET,
secure=secure,
allow_internet_access=allow_internet_access,
network=SandboxNetworkConfig(**network) if network else UNSET,
volume_mounts=volume_mounts if volume_mounts else UNSET,
)
if auto_resume_enabled is not None:
body.auto_resume = SandboxAutoResumeConfig(enabled=auto_resume_enabled)
api_client = get_api_client(config)
res = await post_sandboxes.asyncio_detailed(
body=body,
client=api_client,
)
if res.status_code >= 300:
raise handle_api_exception(res)
if res.parsed is None:
raise Exception("Body of the request is None")
if isinstance(res.parsed, Error):
raise SandboxException(f"{res.parsed.message}: Request failed")
if Version(res.parsed.envd_version) < Version("0.1.0"):
await SandboxApi._cls_kill(res.parsed.sandbox_id)
raise TemplateException(
"You need to update the template to use the new SDK. "
"You can do this by running `e2b template build` in the directory with the template."
)
domain = res.parsed.domain if isinstance(res.parsed.domain, str) else None
envd_token = (
res.parsed.envd_access_token
if isinstance(res.parsed.envd_access_token, str)
else None
)
traffic_token = (
res.parsed.traffic_access_token
if isinstance(res.parsed.traffic_access_token, str)
else None
)
return SandboxCreateResponse(
sandbox_id=res.parsed.sandbox_id,
sandbox_domain=domain,
envd_version=res.parsed.envd_version,
envd_access_token=envd_token,
traffic_access_token=traffic_token,
)
@classmethod
async def _cls_get_metrics(
cls,
sandbox_id: str,
start: Optional[datetime.datetime] = None,
end: Optional[datetime.datetime] = None,
**opts: Unpack[ApiParams],
) -> List[SandboxMetrics]:
"""
Get the metrics of the sandbox specified by sandbox ID.
:param sandbox_id: Sandbox ID
:param start: Start time for the metrics, defaults to the start of the sandbox
:param end: End time for the metrics, defaults to the current time
:return: List of sandbox metrics containing CPU, memory and disk usage information
"""
config = ConnectionConfig(**opts)
if config.debug:
# Skip getting the metrics in debug mode
return []
api_client = get_api_client(config)
res = await get_sandboxes_sandbox_id_metrics.asyncio_detailed(
sandbox_id,
start=int(start.timestamp()) if start else UNSET,
end=int(end.timestamp()) if end else UNSET,
client=api_client,
)
if res.status_code >= 300:
raise handle_api_exception(res)
if res.parsed is None:
return []
# Check if res.parse is Error
if isinstance(res.parsed, Error):
raise SandboxException(f"{res.parsed.message}: Request failed")
# Convert to typed SandboxMetrics objects
return [
SandboxMetrics(
cpu_count=metric.cpu_count,
cpu_used_pct=metric.cpu_used_pct,
disk_total=metric.disk_total,
disk_used=metric.disk_used,
mem_total=metric.mem_total,
mem_used=metric.mem_used,
timestamp=metric.timestamp,
)
for metric in res.parsed
]
@classmethod
async def _cls_create_snapshot(
cls,
sandbox_id: str,
name: Optional[str] = None,
**opts: Unpack[ApiParams],
) -> SnapshotInfo:
config = ConnectionConfig(**opts)
api_client = get_api_client(config)
res = await post_sandboxes_sandbox_id_snapshots.asyncio_detailed(
sandbox_id,
client=api_client,
body=PostSandboxesSandboxIDSnapshotsBody(name=name if name else UNSET),
)
if res.status_code == 404:
raise SandboxNotFoundException(f"Sandbox {sandbox_id} not found")
if res.status_code >= 300:
raise handle_api_exception(res)
if res.parsed is None:
raise SandboxException("Body of the request is None")
if isinstance(res.parsed, Error):
raise SandboxException(f"{res.parsed.message}: Request failed")
return SnapshotInfo(
snapshot_id=res.parsed.snapshot_id,
names=list(res.parsed.names) if res.parsed.names else [],
)
@classmethod
async def _cls_delete_snapshot(
cls,
snapshot_id: str,
**opts: Unpack[ApiParams],
) -> bool:
config = ConnectionConfig(**opts)
api_client = get_api_client(config)
res = await delete_templates_template_id.asyncio_detailed(
snapshot_id,
client=api_client,
)
if res.status_code == 404:
return False
if res.status_code >= 300:
raise handle_api_exception(res)
return True
@classmethod
async def _cls_pause(
cls,
sandbox_id: str,
**opts: Unpack[ApiParams],
) -> str:
config = ConnectionConfig(**opts)
api_client = get_api_client(config)
res = await post_sandboxes_sandbox_id_pause.asyncio_detailed(
sandbox_id,
client=api_client,
)
if res.status_code == 404:
raise SandboxNotFoundException(f"Sandbox {sandbox_id} not found")
if res.status_code == 409:
return sandbox_id
if res.status_code >= 300:
raise handle_api_exception(res)
# Check if res.parse is Error
if isinstance(res.parsed, Error):
raise SandboxException(f"{res.parsed.message}: Request failed")
return sandbox_id
@classmethod
async def _cls_connect(
cls,
sandbox_id: str,
timeout: Optional[int] = None,
**opts: Unpack[ApiParams],
) -> Sandbox:
timeout = timeout or SandboxBase.default_sandbox_timeout
# Sandbox is not running, resume it
config = ConnectionConfig(**opts)
api_client = get_api_client(
config,
headers={
"E2b-Sandbox-Id": sandbox_id,
"E2b-Sandbox-Port": str(config.envd_port),
},
)
res = await post_sandboxes_sandbox_id_connect.asyncio_detailed(
sandbox_id,
client=api_client,
body=ConnectSandbox(timeout=timeout),
)
if res.status_code == 404:
raise SandboxNotFoundException(f"Paused sandbox {sandbox_id} not found")
if res.status_code >= 300:
raise handle_api_exception(res)
# Check if res.parse is Error
if isinstance(res.parsed, Error):
raise SandboxException(f"{res.parsed.message}: Request failed")
if res.parsed is None:
raise SandboxException("Body of the request is None")
return res.parsed