Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

Implement reconnecting in Python

Jakub Novak84a54c1203fc
diff --git a/packages/python-sdk/e2b/sandbox/main.py b/packages/python-sdk/e2b/sandbox/main.py
index b21d10ab1..4cee61f25 100644
--- a/packages/python-sdk/e2b/sandbox/main.py
+++ b/packages/python-sdk/e2b/sandbox/main.py
@@ -5,6 +5,7 @@ import requests
from os import path
from typing import Any, Callable, List, Literal, Optional, IO
+from e2b.api.v2.client import models
from e2b.constants import TIMEOUT, ENVD_PORT, FILE_ROUTE
from e2b.sandbox.code_snippet import CodeSnippetManager, OpenPort
from e2b.sandbox.env_vars import EnvVars
@@ -63,6 +64,7 @@ class Sandbox(SandboxConnection):
on_stderr: Optional[Callable[[ProcessMessage], Any]] = None,
on_exit: Optional[Callable[[int], Any]] = None,
timeout: Optional[float] = TIMEOUT,
+ _sandbox: Optional[models.Instance] = None,
_debug_hostname: Optional[str] = None,
_debug_port: Optional[int] = None,
_debug_dev_env: Optional[Literal["remote", "local"]] = None,
@@ -104,6 +106,7 @@ class Sandbox(SandboxConnection):
api_key=api_key,
cwd=cwd,
env_vars=env_vars,
+ _sandbox=_sandbox,
_debug_hostname=_debug_hostname,
_debug_port=_debug_port,
_debug_dev_env=_debug_dev_env,
@@ -111,7 +114,7 @@ class Sandbox(SandboxConnection):
timeout=timeout,
)
- def _open(self, timeout: Optional[float] = TIMEOUT) -> None:
+ def _open(self,timeout: Optional[float] = TIMEOUT) -> None:
"""
Open the sandbox.
@@ -128,6 +131,37 @@ class Sandbox(SandboxConnection):
self._terminal._close()
self._process._close()
+ @classmethod
+ def reconnect(
+ cls,
+ sandbox_id: str,
+ api_key: Optional[str] = None,
+ cwd: Optional[str] = None,
+ env_vars: Optional[EnvVars] = None,
+ on_scan_ports: Optional[Callable[[List[OpenPort]], Any]] = None,
+ on_stdout: Optional[Callable[[ProcessMessage], Any]] = None,
+ on_stderr: Optional[Callable[[ProcessMessage], Any]] = None,
+ timeout: Optional[float] = TIMEOUT,
+ _debug_hostname: Optional[str] = None,
+ _debug_port: Optional[int] = None,
+ _debug_dev_env: Optional[Literal["remote", "local"]] = None,
+ ):
+ instance_id, client_id = sandbox_id.split("-")
+ return cls(
+ id="unknown",
+ api_key=api_key,
+ cwd=cwd,
+ env_vars=env_vars,
+ on_scan_ports=on_scan_ports,
+ on_stdout=on_stdout,
+ on_stderr=on_stderr,
+ timeout=timeout,
+ _sandbox=models.Instance(instance_id=instance_id, client_id=client_id, env_id=getattr(cls, "sandbox_template_id", "unknown")),
+ _debug_hostname=_debug_hostname,
+ _debug_port=_debug_port,
+ _debug_dev_env=_debug_dev_env,
+ )
+
def close(self) -> None:
"""
Close the sandbox.
diff --git a/packages/python-sdk/e2b/sandbox/sandbox_connection.py b/packages/python-sdk/e2b/sandbox/sandbox_connection.py
index b304a73e7..b68e92e4a 100644
--- a/packages/python-sdk/e2b/sandbox/sandbox_connection.py
+++ b/packages/python-sdk/e2b/sandbox/sandbox_connection.py
@@ -11,6 +11,7 @@ from pydantic import BaseModel
from urllib3.exceptions import ReadTimeoutError, MaxRetryError, ConnectTimeoutError
from e2b.api import E2BApiClient, exceptions, models, client
+from e2b.api.v2.client import InstancesInstanceIDRefreshesPostRequest
from e2b.constants import (
SANDBOX_DOMAIN,
SANDBOX_REFRESH_PERIOD,
@@ -42,6 +43,15 @@ class Subscription(BaseModel):
class SandboxConnection:
_refresh_retries = 4
+ @property
+ def id(self) -> str:
+ """
+ The sandbox ID.
+ """
+ if not self._sandbox:
+ raise SandboxException("Sandbox is not running.")
+ return f"{self._sandbox.instance_id}-{self._sandbox.client_id}"
+
@property
def finished(self):
"""
@@ -64,6 +74,7 @@ class SandboxConnection:
env_vars: Optional[EnvVars] = None,
on_close: Optional[Callable[[], Any]] = None,
timeout: Optional[float] = TIMEOUT,
+ _sandbox: Optional[models.Instance] = None,
_debug_hostname: Optional[str] = None,
_debug_port: Optional[int] = None,
_debug_dev_env: Optional[Literal["remote", "local"]] = None,
@@ -83,8 +94,8 @@ class SandboxConnection:
self._debug_port = _debug_port
self._debug_dev_env = _debug_dev_env
self._on_close_child = on_close
+ self._sandbox = _sandbox
- self._sandbox: Optional[models.Instance] = None
self._is_open = False
self._process_cleanup: List[Callable[[], Any]] = []
self._refreshing_task: Optional[Future] = None
@@ -92,7 +103,7 @@ class SandboxConnection:
self._rpc: Optional[SandboxRpc] = None
self._finished = DeferredFuture(self._process_cleanup)
- logger.info(f"Sandbox for code snippet {self._id} initialized")
+ logger.info(f"Sandbox for template {self._id} initialized")
self._open(timeout=timeout)
@@ -120,13 +131,30 @@ class SandboxConnection:
else:
return self._debug_hostname
- hostname = (
- f"{self._sandbox.instance_id}-{self._sandbox.client_id}.{SANDBOX_DOMAIN}"
- )
+ hostname = f"{self.id}.{SANDBOX_DOMAIN}"
if port:
return f"{port}-{hostname}"
return hostname
+ def keep_alive(self, duration: int) -> None:
+ with E2BApiClient(api_key=self._api_key) as api_client:
+ api = client.InstancesApi(api_client)
+ try:
+ api.instances_instance_id_refreshes_post(
+ self._sandbox.instance_id,
+ InstancesInstanceIDRefreshesPostRequest(duration=duration),
+ )
+ logger.debug(
+ f"Sandbox will be kept alive without connection for next {duration} seconds."
+ )
+ except exceptions.ApiException as e:
+ if e.status == 404:
+ raise SandboxException(
+ f"Sandbox {self._sandbox.instance_id} failed because it cannot be found"
+ ) from e
+ else:
+ raise e
+
def close(self) -> None:
"""
Close the sandbox and unsubscribe from all the subscriptions.
@@ -158,63 +186,67 @@ class SandboxConnection:
You must call this method before using the sandbox.
"""
- if self._is_open or self._sandbox:
+ if self._is_open:
raise SandboxException("Sandbox connect was already called")
else:
self._is_open = True
- try:
- with E2BApiClient(api_key=self._api_key) as api_client:
- api = client.InstancesApi(api_client)
-
- self._sandbox = api.instances_post(
- models.NewInstance(envID=self._id),
- _request_timeout=timeout,
- )
- logger.info(
- f"Sandbox {self._sandbox.env_id} created (id:{self._sandbox.instance_id})"
- )
-
- executor = ThreadPoolExecutor(thread_name_prefix="e2b-refresh")
- self._refreshing_task = executor.submit(
- self._refresh, self._sandbox.instance_id
- )
-
- self._process_cleanup.append(self._refreshing_task.cancel)
- self._process_cleanup.append(lambda: shutdown_executor(executor))
-
- except ReadTimeoutError as e:
- logger.error(f"Failed to acquire sandbox")
- self._close()
- raise TimeoutException(
- f"Failed to acquire sandbox: {e}",
- ) from e
- except MaxRetryError as e:
- if isinstance(e.reason, ConnectTimeoutError):
+ if not self._sandbox:
+ try:
+ with E2BApiClient(api_key=self._api_key) as api_client:
+ api = client.InstancesApi(api_client)
+
+ self._sandbox = api.instances_post(
+ models.NewInstance(envID=self._id),
+ _request_timeout=timeout,
+ )
+ logger.info(
+ f"Sandbox {self._sandbox.env_id} created (id:{self._sandbox.instance_id})"
+ )
+ except ReadTimeoutError as e:
+ logger.error(f"Failed to acquire sandbox")
+ self._close()
raise TimeoutException(
f"Failed to acquire sandbox: {e}",
) from e
- raise e
+ except MaxRetryError as e:
+ if isinstance(e.reason, ConnectTimeoutError):
+ raise TimeoutException(
+ f"Failed to acquire sandbox: {e}",
+ ) from e
+ raise e
+ except Exception as e:
+ logger.error(f"Failed to acquire sandbox")
+ self._close()
+ raise e
+
+ self._start_refreshing()
+ try:
+ self._connect_rpc(timeout)
except Exception as e:
- logger.error(f"Failed to acquire sandbox")
+ print(e)
self._close()
raise e
+ def _connect_rpc(self, timeout: Optional[float] = TIMEOUT):
hostname = self.get_hostname(self._debug_port or ENVD_PORT)
protocol = "ws" if self._debug_dev_env == "local" else "wss"
sandbox_url = f"{protocol}://{hostname}{WS_ROUTE}"
+ self._rpc = SandboxRpc(
+ url=sandbox_url,
+ on_message=self._handle_notification,
+ )
+ self._rpc.connect(timeout=timeout)
- try:
- self._rpc = SandboxRpc(
- url=sandbox_url,
- on_message=self._handle_notification,
- )
- self._rpc.connect(timeout=timeout)
- except Exception as e:
- print(e)
- self._close()
- raise e
+ def _start_refreshing(self):
+ executor = ThreadPoolExecutor(thread_name_prefix="e2b-refresh")
+ self._refreshing_task = executor.submit(
+ self._refresh, self._sandbox.instance_id
+ )
+
+ self._process_cleanup.append(self._refreshing_task.cancel)
+ self._process_cleanup.append(lambda: shutdown_executor(executor))
def _call(
self,
diff --git a/packages/python-sdk/example.py b/packages/python-sdk/example.py
index 65708ef2a..4cbe6753e 100644
--- a/packages/python-sdk/example.py
+++ b/packages/python-sdk/example.py
@@ -1,5 +1,6 @@
import logging
from os import getenv
+from time import sleep
from dotenv import load_dotenv
@@ -14,12 +15,14 @@ logging.basicConfig(level=logging.ERROR)
def main():
s = Sandbox(api_key=E2B_API_KEY)
- a = s.process.start("ls -la /var ")
+ a = s.process.start("ls -la /home/user")
+ s.filesystem.write("/home/user/test.txt", "Hello World!")
a.wait()
- print(a.stdout)
- print(a.stderr)
+ s.keep_alive(60)
s.close()
- return
-
+ sleep(20)
+ s2 = Sandbox.reconnect(s.id, api_key=E2B_API_KEY)
+ print(s2.filesystem.read("/home/user/test.txt"))
+ s2.close()
main()