exec_box.py 12 KB

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