exec_box.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. import atexit
  2. import concurrent.futures
  3. import os
  4. import sys
  5. import time
  6. import uuid
  7. import tarfile
  8. from glob import glob
  9. from collections import namedtuple
  10. from typing import Dict, List, Tuple
  11. import docker
  12. from opendevin import config
  13. from opendevin.logger import opendevin_logger as logger
  14. from opendevin.sandbox.sandbox import Sandbox
  15. from opendevin.sandbox.process import Process
  16. from opendevin.sandbox.docker.process import DockerProcess
  17. from opendevin.schema import ConfigType
  18. from opendevin.exceptions import SandboxInvalidBackgroundCommandError
  19. InputType = namedtuple('InputType', ['content'])
  20. OutputType = namedtuple('OutputType', ['content'])
  21. CONTAINER_IMAGE = config.get(ConfigType.SANDBOX_CONTAINER_IMAGE)
  22. SANDBOX_WORKSPACE_DIR = config.get(ConfigType.WORKSPACE_MOUNT_PATH_IN_SANDBOX)
  23. # FIXME: On some containers, the devin user doesn't have enough permission, e.g. to install packages
  24. # How do we make this more flexible?
  25. RUN_AS_DEVIN = config.get(ConfigType.RUN_AS_DEVIN).lower() != 'false'
  26. USER_ID = 1000
  27. if SANDBOX_USER_ID := config.get(ConfigType.SANDBOX_USER_ID):
  28. USER_ID = int(SANDBOX_USER_ID)
  29. elif hasattr(os, 'getuid'):
  30. USER_ID = os.getuid()
  31. class DockerExecBox(Sandbox):
  32. instance_id: str
  33. container_image: str
  34. container_name_prefix = 'opendevin-sandbox-'
  35. container_name: str
  36. container: docker.models.containers.Container
  37. docker_client: docker.DockerClient
  38. cur_background_id = 0
  39. background_commands: Dict[int, Process] = {}
  40. def __init__(
  41. self,
  42. container_image: str | None = None,
  43. timeout: int = 120,
  44. sid: str | None = None,
  45. ):
  46. # Initialize docker client. Throws an exception if Docker is not reachable.
  47. try:
  48. self.docker_client = docker.from_env()
  49. except Exception as ex:
  50. logger.exception(
  51. 'Please check Docker is running using `docker ps`.', exc_info=False)
  52. raise ex
  53. self.instance_id = sid if sid is not None else str(uuid.uuid4())
  54. # TODO: this timeout is actually essential - need a better way to set it
  55. # if it is too short, the container may still waiting for previous
  56. # command to finish (e.g. apt-get update)
  57. # if it is too long, the user may have to wait for a unnecessary long time
  58. self.timeout = timeout
  59. self.container_image = CONTAINER_IMAGE if container_image is None else container_image
  60. self.container_name = self.container_name_prefix + self.instance_id
  61. # always restart the container, cuz the initial be regarded as a new session
  62. self.restart_docker_container()
  63. if RUN_AS_DEVIN:
  64. self.setup_devin_user()
  65. atexit.register(self.close)
  66. def setup_devin_user(self):
  67. cmds = [
  68. f'useradd --shell /bin/bash -u {USER_ID} -o -c "" -m devin',
  69. r"echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers",
  70. 'sudo adduser devin sudo',
  71. ]
  72. for cmd in cmds:
  73. exit_code, logs = self.container.exec_run(
  74. ['/bin/bash', '-c', cmd], workdir=SANDBOX_WORKSPACE_DIR
  75. )
  76. if exit_code != 0:
  77. raise Exception(f'Failed to setup devin user: {logs}')
  78. def get_exec_cmd(self, cmd: str) -> List[str]:
  79. if RUN_AS_DEVIN:
  80. return ['su', 'devin', '-c', cmd]
  81. else:
  82. return ['/bin/bash', '-c', cmd]
  83. def read_logs(self, id) -> str:
  84. if id not in self.background_commands:
  85. raise SandboxInvalidBackgroundCommandError()
  86. bg_cmd = self.background_commands[id]
  87. return bg_cmd.read_logs()
  88. def execute(self, cmd: str) -> Tuple[int, str]:
  89. # TODO: each execute is not stateful! We need to keep track of the current working directory
  90. def run_command(container, command):
  91. return container.exec_run(command, workdir=SANDBOX_WORKSPACE_DIR)
  92. # Use ThreadPoolExecutor to control command and set timeout
  93. with concurrent.futures.ThreadPoolExecutor() as executor:
  94. future = executor.submit(
  95. run_command, self.container, self.get_exec_cmd(cmd)
  96. )
  97. try:
  98. exit_code, logs = future.result(timeout=self.timeout)
  99. except concurrent.futures.TimeoutError:
  100. logger.exception(
  101. 'Command timed out, killing process...', exc_info=False)
  102. pid = self.get_pid(cmd)
  103. if pid is not None:
  104. self.container.exec_run(
  105. f'kill -9 {pid}', workdir=SANDBOX_WORKSPACE_DIR)
  106. return -1, f'Command: "{cmd}" timed out'
  107. return exit_code, logs.decode('utf-8').strip()
  108. def copy_to(self, host_src: str, sandbox_dest: str, recursive: bool = False):
  109. # mkdir -p sandbox_dest if it doesn't exist
  110. exit_code, logs = self.container.exec_run(
  111. ['/bin/bash', '-c', f'mkdir -p {sandbox_dest}'],
  112. workdir=SANDBOX_WORKSPACE_DIR,
  113. )
  114. if exit_code != 0:
  115. raise Exception(
  116. f'Failed to create directory {sandbox_dest} in sandbox: {logs}')
  117. if recursive:
  118. assert os.path.isdir(host_src), 'Source must be a directory when recursive is True'
  119. files = glob(host_src + '/**/*', recursive=True)
  120. srcname = os.path.basename(host_src)
  121. tar_filename = os.path.join(os.path.dirname(host_src), srcname + '.tar')
  122. with tarfile.open(tar_filename, mode='w') as tar:
  123. for file in files:
  124. tar.add(file, arcname=os.path.relpath(file, os.path.dirname(host_src)))
  125. else:
  126. assert os.path.isfile(host_src), 'Source must be a file when recursive is False'
  127. srcname = os.path.basename(host_src)
  128. tar_filename = os.path.join(os.path.dirname(host_src), srcname + '.tar')
  129. with tarfile.open(tar_filename, mode='w') as tar:
  130. tar.add(host_src, arcname=srcname)
  131. with open(tar_filename, 'rb') as f:
  132. data = f.read()
  133. self.container.put_archive(os.path.dirname(sandbox_dest), data)
  134. os.remove(tar_filename)
  135. def execute_in_background(self, cmd: str) -> Process:
  136. result = self.container.exec_run(
  137. self.get_exec_cmd(cmd), socket=True, workdir=SANDBOX_WORKSPACE_DIR
  138. )
  139. result.output._sock.setblocking(0)
  140. pid = self.get_pid(cmd)
  141. bg_cmd = DockerProcess(self.cur_background_id, cmd, result, pid)
  142. self.background_commands[bg_cmd.pid] = bg_cmd
  143. self.cur_background_id += 1
  144. return bg_cmd
  145. def get_pid(self, cmd):
  146. exec_result = self.container.exec_run('ps aux')
  147. processes = exec_result.output.decode('utf-8').splitlines()
  148. cmd = ' '.join(self.get_exec_cmd(cmd))
  149. for process in processes:
  150. if cmd in process:
  151. pid = process.split()[1] # second column is the pid
  152. return pid
  153. return None
  154. def kill_background(self, id: int) -> Process:
  155. if id not in self.background_commands:
  156. raise SandboxInvalidBackgroundCommandError()
  157. bg_cmd = self.background_commands[id]
  158. if bg_cmd.pid is not None:
  159. self.container.exec_run(
  160. f'kill -9 {bg_cmd.pid}', workdir=SANDBOX_WORKSPACE_DIR)
  161. assert isinstance(bg_cmd, DockerProcess)
  162. bg_cmd.result.output.close()
  163. self.background_commands.pop(id)
  164. return bg_cmd
  165. def stop_docker_container(self):
  166. try:
  167. container = self.docker_client.containers.get(self.container_name)
  168. container.stop()
  169. container.remove()
  170. elapsed = 0
  171. while container.status != 'exited':
  172. time.sleep(1)
  173. elapsed += 1
  174. if elapsed > self.timeout:
  175. break
  176. container = self.docker_client.containers.get(
  177. self.container_name)
  178. except docker.errors.NotFound:
  179. pass
  180. def is_container_running(self):
  181. try:
  182. container = self.docker_client.containers.get(self.container_name)
  183. if container.status == 'running':
  184. self.container = container
  185. return True
  186. return False
  187. except docker.errors.NotFound:
  188. return False
  189. def restart_docker_container(self):
  190. try:
  191. self.stop_docker_container()
  192. logger.info('Container stopped')
  193. except docker.errors.DockerException as e:
  194. logger.exception('Failed to stop container', exc_info=False)
  195. raise e
  196. try:
  197. # start the container
  198. mount_dir = config.get(ConfigType.WORKSPACE_MOUNT_PATH)
  199. self.container = self.docker_client.containers.run(
  200. self.container_image,
  201. command='tail -f /dev/null',
  202. network_mode='host',
  203. working_dir=SANDBOX_WORKSPACE_DIR,
  204. name=self.container_name,
  205. detach=True,
  206. volumes={mount_dir: {
  207. 'bind': SANDBOX_WORKSPACE_DIR, 'mode': 'rw'}},
  208. )
  209. logger.info('Container started')
  210. except Exception as ex:
  211. logger.exception('Failed to start container', exc_info=False)
  212. raise ex
  213. # wait for container to be ready
  214. elapsed = 0
  215. while self.container.status != 'running':
  216. if self.container.status == 'exited':
  217. logger.info('container exited')
  218. logger.info('container logs:')
  219. logger.info(self.container.logs())
  220. break
  221. time.sleep(1)
  222. elapsed += 1
  223. self.container = self.docker_client.containers.get(
  224. self.container_name)
  225. if elapsed > self.timeout:
  226. break
  227. if self.container.status != 'running':
  228. raise Exception('Failed to start container')
  229. # clean up the container, cannot do it in __del__ because the python interpreter is already shutting down
  230. def close(self):
  231. containers = self.docker_client.containers.list(all=True)
  232. for container in containers:
  233. try:
  234. if container.name.startswith(self.container_name_prefix):
  235. container.remove(force=True)
  236. except docker.errors.NotFound:
  237. pass
  238. def get_working_directory(self):
  239. return SANDBOX_WORKSPACE_DIR
  240. if __name__ == '__main__':
  241. try:
  242. exec_box = DockerExecBox()
  243. except Exception as e:
  244. logger.exception('Failed to start Docker container: %s', e)
  245. sys.exit(1)
  246. logger.info(
  247. "Interactive Docker container started. Type 'exit' or use Ctrl+C to exit.")
  248. bg_cmd = exec_box.execute_in_background(
  249. "while true; do echo -n '.' && sleep 1; done"
  250. )
  251. sys.stdout.flush()
  252. try:
  253. while True:
  254. try:
  255. user_input = input('>>> ')
  256. except EOFError:
  257. logger.info('Exiting...')
  258. break
  259. if user_input.lower() == 'exit':
  260. logger.info('Exiting...')
  261. break
  262. if user_input.lower() == 'kill':
  263. exec_box.kill_background(bg_cmd.pid)
  264. logger.info('Background process killed')
  265. continue
  266. exit_code, output = exec_box.execute(user_input)
  267. logger.info('exit code: %d', exit_code)
  268. logger.info(output)
  269. if bg_cmd.pid in exec_box.background_commands:
  270. logs = exec_box.read_logs(bg_cmd.pid)
  271. logger.info('background logs: %s', logs)
  272. sys.stdout.flush()
  273. except KeyboardInterrupt:
  274. logger.info('Exiting...')
  275. exec_box.close()