-
Notifications
You must be signed in to change notification settings - Fork 880
Expand file tree
/
Copy pathmain.py
More file actions
395 lines (321 loc) · 12.3 KB
/
main.py
File metadata and controls
395 lines (321 loc) · 12.3 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
import logging
import httpx
from typing import Dict, Optional, TypedDict, overload
from typing_extensions import Unpack
from e2b.connection_config import ConnectionConfig
from e2b.envd.api import ENVD_API_HEALTH_ROUTE, ahandle_envd_api_exception
from e2b.exceptions import format_request_timeout_error
from e2b.sandbox.main import SandboxSetup
from e2b.sandbox.utils import class_method_variant
from e2b.sandbox_async.filesystem.filesystem import Filesystem
from e2b.sandbox_async.commands.command import Commands
from e2b.sandbox_async.commands.pty import Pty
from e2b.sandbox_async.sandbox_api import SandboxApi, SandboxInfo
logger = logging.getLogger(__name__)
class AsyncTransportWithLogger(httpx.AsyncHTTPTransport):
async def handle_async_request(self, request):
url = f"{request.url.scheme}://{request.url.host}{request.url.path}"
logger.info(f"Request: {request.method} {url}")
response = await super().handle_async_request(request)
# data = connect.GzipCompressor.decompress(response.read()).decode()
logger.info(f"Response: {response.status_code} {url}")
return response
class AsyncSandboxOpts(TypedDict):
sandbox_id: str
envd_version: Optional[str]
connection_config: ConnectionConfig
class AsyncSandbox(SandboxSetup, SandboxApi):
"""
E2B cloud sandbox is a secure and isolated cloud environment.
The sandbox allows you to:
- Access Linux OS
- Create, list, and delete files and directories
- Run commands
- Run isolated code
- Access the internet
Check docs [here](https://e2b.dev/docs).
Use the `AsyncSandbox.create()` to create a new sandbox.
Example:
```python
from e2b import AsyncSandbox
sandbox = await AsyncSandbox.create()
```
"""
@property
def files(self) -> Filesystem:
"""
Module for interacting with the sandbox filesystem.
"""
return self._filesystem
@property
def commands(self) -> Commands:
"""
Module for running commands in the sandbox.
"""
return self._commands
@property
def pty(self) -> Pty:
"""
Module for interacting with the sandbox pseudo-terminal.
"""
return self._pty
@property
def sandbox_id(self) -> str:
"""
Unique identifier of the sandbox.
"""
return self._sandbox_id
@property
def envd_api_url(self) -> str:
return self._envd_api_url
@property
def connection_config(self) -> ConnectionConfig:
return self._connection_config
def __init__(self, **opts: Unpack[AsyncSandboxOpts]):
"""
Use `AsyncSandbox.create()` to create a new sandbox instead.
"""
super().__init__()
self._sandbox_id = opts["sandbox_id"]
self._connection_config = opts["connection_config"]
self._envd_api_url = f"{'http' if self.connection_config.debug else 'https'}://{self.get_host(self.envd_port)}"
self._envd_version = opts["envd_version"]
self._transport = AsyncTransportWithLogger(limits=self._limits)
self._envd_api = httpx.AsyncClient(
base_url=self.envd_api_url,
transport=self._transport,
)
self._filesystem = Filesystem(
self.envd_api_url,
self._envd_version,
self.connection_config,
self._transport._pool,
self._envd_api,
)
self._commands = Commands(
self.envd_api_url,
self.connection_config,
self._transport._pool,
)
self._pty = Pty(
self.envd_api_url,
self.connection_config,
self._transport._pool,
)
async def is_running(self, request_timeout: Optional[float] = None) -> bool:
"""
Check if the sandbox is running.
:param request_timeout: Timeout for the request in **seconds**
:return: `True` if the sandbox is running, `False` otherwise
Example
```python
sandbox = await AsyncSandbox.create()
await sandbox.is_running() # Returns True
await sandbox.kill()
await sandbox.is_running() # Returns False
```
"""
try:
r = await self._envd_api.get(
ENVD_API_HEALTH_ROUTE,
timeout=self.connection_config.get_request_timeout(request_timeout),
)
if r.status_code == 502:
return False
err = await ahandle_envd_api_exception(r)
if err:
raise err
except httpx.TimeoutException:
raise format_request_timeout_error()
return True
@classmethod
async def create(
cls,
template: Optional[str] = None,
timeout: Optional[int] = None,
metadata: Optional[Dict[str, str]] = None,
envs: Optional[Dict[str, str]] = None,
api_key: Optional[str] = None,
domain: Optional[str] = None,
debug: Optional[bool] = None,
request_timeout: Optional[float] = None,
):
"""
Create a new sandbox.
By default, the sandbox is created from the default `base` sandbox template.
:param template: Sandbox template name or ID
:param timeout: Timeout for the sandbox in **seconds**, default to 300 seconds. Maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users.
:param metadata: Custom metadata for the sandbox
:param envs: Custom environment variables for the sandbox
:param api_key: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable
:param request_timeout: Timeout for the request in **seconds**
:return: sandbox instance for the new sandbox
Use this method instead of using the constructor to create a new sandbox.
"""
connection_config = ConnectionConfig(
api_key=api_key,
domain=domain,
debug=debug,
request_timeout=request_timeout,
)
if connection_config.debug:
sandbox_id = "debug_sandbox_id"
envd_version = None
else:
response = await SandboxApi._create_sandbox(
template=template or cls.default_template,
api_key=api_key,
timeout=timeout or cls.default_sandbox_timeout,
metadata=metadata,
domain=domain,
debug=debug,
request_timeout=request_timeout,
env_vars=envs,
)
sandbox_id = response.sandbox_id
envd_version = response.envd_version
return cls(
sandbox_id=sandbox_id,
envd_version=envd_version,
connection_config=connection_config,
)
@classmethod
async def connect(
cls,
sandbox_id: str,
api_key: Optional[str] = None,
domain: Optional[str] = None,
debug: Optional[bool] = None,
):
"""
Connect to an existing sandbox.
With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc).
:param sandbox_id: Sandbox ID
:param api_key: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable
:return: sandbox instance for the existing sandbox
@example
```python
sandbox = await AsyncSandbox.create()
sandbox_id = sandbox.sandbox_id
# Another code block
same_sandbox = await AsyncSandbox.connect(sandbox_id)
"""
connection_config = ConnectionConfig(
api_key=api_key,
domain=domain,
debug=debug,
)
return cls(
sandbox_id=sandbox_id,
envd_version=None,
connection_config=connection_config,
)
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc_value, traceback):
await self.kill()
@overload
async def kill(self, request_timeout: Optional[float] = None) -> bool:
"""
Kill the sandbox.
:param request_timeout: Timeout for the request in **seconds**
:return: `True` if the sandbox was killed, `False` if the sandbox was not found
"""
...
@overload
@staticmethod
async def kill(
sandbox_id: str,
api_key: Optional[str] = None,
domain: Optional[str] = None,
debug: Optional[bool] = None,
request_timeout: Optional[float] = None,
) -> bool:
"""
Kill the sandbox specified by sandbox ID.
:param sandbox_id: Sandbox ID
:param api_key: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable
:param request_timeout: Timeout for the request in **seconds**
:return: `True` if the sandbox was killed, `False` if the sandbox was not found
"""
...
@class_method_variant("_cls_kill")
async def kill(self, request_timeout: Optional[float] = None) -> bool: # type: ignore
config_dict = self.connection_config.__dict__
config_dict.pop("access_token", None)
config_dict.pop("api_url", None)
if request_timeout:
config_dict["request_timeout"] = request_timeout
await SandboxApi._cls_kill(
sandbox_id=self.sandbox_id,
**self.connection_config.__dict__,
)
@overload
async def set_timeout(
self,
timeout: int,
request_timeout: Optional[float] = None,
) -> None:
"""
Set the timeout of the sandbox.
After the timeout expires the sandbox will be automatically killed.
This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`.
Maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users.
:param timeout: Timeout for the sandbox in **seconds**
:param request_timeout: Timeout for the request in **seconds**
"""
...
@overload
@staticmethod
async def set_timeout(
sandbox_id: str,
timeout: int,
api_key: Optional[str] = None,
domain: Optional[str] = None,
debug: Optional[bool] = None,
request_timeout: Optional[float] = None,
) -> None:
"""
Set the timeout of the specified sandbox.
After the timeout expires the sandbox will be automatically killed.
This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`.
Maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users.
:param sandbox_id: Sandbox ID
:param timeout: Timeout for the sandbox in **seconds**
:param request_timeout: Timeout for the request in **seconds**
"""
...
@class_method_variant("_cls_set_timeout")
async def set_timeout( # type: ignore
self,
timeout: int,
request_timeout: Optional[float] = None,
) -> None:
config_dict = self.connection_config.__dict__
config_dict.pop("access_token", None)
config_dict.pop("api_url", None)
if request_timeout:
config_dict["request_timeout"] = request_timeout
await SandboxApi._cls_set_timeout(
sandbox_id=self.sandbox_id,
timeout=timeout,
**self.connection_config.__dict__,
)
async def get_info( # type: ignore
self,
request_timeout: Optional[float] = None,
) -> SandboxInfo:
"""
Get sandbox information like sandbox id, template, metadata, started at/end at date.
:param request_timeout: Timeout for the request in **seconds**
:return: Sandbox info
"""
config_dict = self.connection_config.__dict__
config_dict.pop("access_token", None)
config_dict.pop("api_url", None)
if request_timeout:
config_dict["request_timeout"] = request_timeout
return await SandboxApi.get_info(
sandbox_id=self.sandbox_id,
**self.connection_config.__dict__,
)