-
Notifications
You must be signed in to change notification settings - Fork 869
Expand file tree
/
Copy pathmain.py
More file actions
384 lines (316 loc) · 12 KB
/
main.py
File metadata and controls
384 lines (316 loc) · 12 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
import logging
from typing import Dict, Optional, overload
import httpx
from e2b.connection_config import ConnectionConfig
from e2b.envd.api import ENVD_API_HEALTH_ROUTE, handle_envd_api_exception
from e2b.exceptions import SandboxException, format_request_timeout_error
from e2b.sandbox.main import SandboxSetup
from e2b.sandbox.utils import class_method_variant
from e2b.sandbox_sync.filesystem.filesystem import Filesystem
from e2b.sandbox_sync.commands.command import Commands
from e2b.sandbox_sync.commands.pty import Pty
from e2b.sandbox_sync.sandbox_api import SandboxApi, SandboxInfo
logger = logging.getLogger(__name__)
class TransportWithLogger(httpx.HTTPTransport):
def handle_request(self, request):
url = f"{request.url.scheme}://{request.url.host}{request.url.path}"
logger.info(f"Request: {request.method} {url}")
response = super().handle_request(request)
# data = connect.GzipCompressor.decompress(response.read()).decode()
logger.info(f"Response: {response.status_code} {url}")
return response
class Sandbox(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 `Sandbox()` to create a new sandbox.
Example:
```python
from e2b import Sandbox
sandbox = Sandbox()
```
"""
@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,
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,
sandbox_id: Optional[str] = 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
"""
super().__init__()
if sandbox_id and (metadata is not None or template is not None):
raise SandboxException(
"Cannot set metadata or timeout when connecting to an existing sandbox. "
"Use Sandbox.connect method instead.",
)
self._connection_config = ConnectionConfig(
api_key=api_key,
domain=domain,
debug=debug,
request_timeout=request_timeout,
)
if self.connection_config.debug:
self._sandbox_id = "debug_sandbox_id"
self._envd_version = None
elif sandbox_id is not None:
self._sandbox_id = sandbox_id
self._envd_version = None
else:
template = template or self.default_template
timeout = timeout or self.default_sandbox_timeout
response = SandboxApi._create_sandbox(
template=template,
api_key=api_key,
timeout=timeout,
metadata=metadata,
env_vars=envs,
domain=domain,
debug=debug,
request_timeout=request_timeout,
)
self._sandbox_id = response.sandbox_id
self._envd_version = response.envd_version
self._envd_api_url = f"{'http' if self.connection_config.debug else 'https'}://{self.get_host(self.envd_port)}"
self._transport = TransportWithLogger(limits=self._limits)
self._envd_api = httpx.Client(
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,
)
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 = Sandbox()
sandbox.is_running() # Returns True
sandbox.kill()
sandbox.is_running() # Returns False
```
"""
try:
r = 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 = handle_envd_api_exception(r)
if err:
raise err
except httpx.TimeoutException:
raise format_request_timeout_error()
return True
@classmethod
def connect(
cls,
sandbox_id: str,
api_key: Optional[str] = None,
domain: Optional[str] = None,
debug: Optional[bool] = None,
):
"""
Connects 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 = Sandbox()
sandbox_id = sandbox.sandbox_id
# Another code block
same_sandbox = Sandbox.connect(sandbox_id)
```
"""
return cls(
sandbox_id=sandbox_id,
api_key=api_key,
domain=domain,
debug=debug,
)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.kill()
@overload
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
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")
def kill(self, request_timeout: Optional[float] = None) -> bool: # type: ignore
"""
Kill the sandbox.
:param request_timeout: Timeout for the request
:return: `True` if the sandbox was killed, `False` if the sandbox was not found
"""
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
SandboxApi._cls_kill(
sandbox_id=self.sandbox_id,
**self.connection_config.__dict__,
)
@overload
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
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 sandbox specified by sandbox ID.
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 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**
"""
...
@class_method_variant("_cls_set_timeout")
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
SandboxApi._cls_set_timeout(
sandbox_id=self.sandbox_id,
timeout=timeout,
**self.connection_config.__dict__,
)
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 SandboxApi.get_info(
sandbox_id=self.sandbox_id,
**self.connection_config.__dict__,
)