sandbox.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. import os
  2. import tarfile
  3. from glob import glob
  4. from e2b import Sandbox as E2BSandbox
  5. from e2b.sandbox.exception import (
  6. TimeoutException,
  7. )
  8. from opendevin.core.config import config
  9. from opendevin.core.logger import opendevin_logger as logger
  10. from opendevin.runtime.e2b.process import E2BProcess
  11. from opendevin.runtime.process import Process
  12. from opendevin.runtime.sandbox import Sandbox
  13. class E2BBox(Sandbox):
  14. closed = False
  15. cur_background_id = 0
  16. background_commands: dict[int, Process] = {}
  17. _cwd: str = '/home/user'
  18. def __init__(
  19. self,
  20. template: str = 'open-devin',
  21. timeout: int = 120,
  22. ):
  23. self.sandbox = E2BSandbox(
  24. api_key=config.e2b_api_key,
  25. template=template,
  26. # It's possible to stream stdout and stderr from sandbox and from each process
  27. on_stderr=lambda x: logger.info(f'E2B sandbox stderr: {x}'),
  28. on_stdout=lambda x: logger.info(f'E2B sandbox stdout: {x}'),
  29. cwd=self._cwd, # Default workdir inside sandbox
  30. )
  31. self.timeout = timeout
  32. logger.info(f'Started E2B sandbox with ID "{self.sandbox.id}"')
  33. super().__init__()
  34. @property
  35. def filesystem(self):
  36. return self.sandbox.filesystem
  37. def _archive(self, host_src: str, recursive: bool = False):
  38. if recursive:
  39. assert os.path.isdir(
  40. host_src
  41. ), 'Source must be a directory when recursive is True'
  42. files = glob(host_src + '/**/*', recursive=True)
  43. srcname = os.path.basename(host_src)
  44. tar_filename = os.path.join(os.path.dirname(host_src), srcname + '.tar')
  45. with tarfile.open(tar_filename, mode='w') as tar:
  46. for file in files:
  47. tar.add(
  48. file, arcname=os.path.relpath(file, os.path.dirname(host_src))
  49. )
  50. else:
  51. assert os.path.isfile(
  52. host_src
  53. ), 'Source must be a file when recursive is False'
  54. srcname = os.path.basename(host_src)
  55. tar_filename = os.path.join(os.path.dirname(host_src), srcname + '.tar')
  56. with tarfile.open(tar_filename, mode='w') as tar:
  57. tar.add(host_src, arcname=srcname)
  58. return tar_filename
  59. # TODO: This won't work if we didn't wait for the background process to finish
  60. def read_logs(self, process_id: int) -> str:
  61. proc = self.background_commands.get(process_id)
  62. if proc is None:
  63. raise ValueError(f'Process {process_id} not found')
  64. assert isinstance(proc, E2BProcess)
  65. return '\n'.join([m.line for m in proc.output_messages])
  66. def execute(self, cmd: str, timeout: int | None = None) -> tuple[int, str]:
  67. timeout = timeout if timeout is not None else self.timeout
  68. process = self.sandbox.process.start(cmd, env_vars=self._env)
  69. try:
  70. process_output = process.wait(timeout=timeout)
  71. except TimeoutException:
  72. logger.info('Command timed out, killing process...')
  73. process.kill()
  74. return -1, f'Command: "{cmd}" timed out'
  75. logs = [m.line for m in process_output.messages]
  76. logs_str = '\n'.join(logs)
  77. if process.exit_code is None:
  78. return -1, logs_str
  79. assert process_output.exit_code is not None
  80. return process_output.exit_code, logs_str
  81. def copy_to(self, host_src: str, sandbox_dest: str, recursive: bool = False):
  82. """Copies a local file or directory to the sandbox."""
  83. tar_filename = self._archive(host_src, recursive)
  84. # Prepend the sandbox destination with our sandbox cwd
  85. sandbox_dest = os.path.join(self._cwd, sandbox_dest.removeprefix('/'))
  86. with open(tar_filename, 'rb') as tar_file:
  87. # Upload the archive to /home/user (default destination that always exists)
  88. uploaded_path = self.sandbox.upload_file(tar_file)
  89. # Check if sandbox_dest exists. If not, create it.
  90. process = self.sandbox.process.start_and_wait(f'test -d {sandbox_dest}')
  91. if process.exit_code != 0:
  92. self.sandbox.filesystem.make_dir(sandbox_dest)
  93. # Extract the archive into the destination and delete the archive
  94. process = self.sandbox.process.start_and_wait(
  95. f'sudo tar -xf {uploaded_path} -C {sandbox_dest} && sudo rm {uploaded_path}'
  96. )
  97. if process.exit_code != 0:
  98. raise Exception(
  99. f'Failed to extract {uploaded_path} to {sandbox_dest}: {process.stderr}'
  100. )
  101. # Delete the local archive
  102. os.remove(tar_filename)
  103. def execute_in_background(self, cmd: str) -> Process:
  104. process = self.sandbox.process.start(cmd)
  105. e2b_process = E2BProcess(process, cmd)
  106. self.cur_background_id += 1
  107. self.background_commands[self.cur_background_id] = e2b_process
  108. return e2b_process
  109. def kill_background(self, process_id: int):
  110. process = self.background_commands.get(process_id)
  111. if process is None:
  112. raise ValueError(f'Process {process_id} not found')
  113. assert isinstance(process, E2BProcess)
  114. process.kill()
  115. return process
  116. def close(self):
  117. self.sandbox.close()
  118. def get_working_directory(self):
  119. return self.sandbox.cwd