runtime.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. import os
  2. import tempfile
  3. import threading
  4. import time
  5. import uuid
  6. from zipfile import ZipFile
  7. import docker
  8. import requests
  9. import tenacity
  10. from openhands.core.config import AppConfig
  11. from openhands.core.logger import openhands_logger as logger
  12. from openhands.events import EventStream
  13. from openhands.events.action import (
  14. ActionConfirmationStatus,
  15. BrowseInteractiveAction,
  16. BrowseURLAction,
  17. CmdRunAction,
  18. FileReadAction,
  19. FileWriteAction,
  20. IPythonRunCellAction,
  21. )
  22. from openhands.events.action.action import Action
  23. from openhands.events.observation import (
  24. ErrorObservation,
  25. NullObservation,
  26. Observation,
  27. UserRejectObservation,
  28. )
  29. from openhands.events.serialization import event_to_dict, observation_from_dict
  30. from openhands.events.serialization.action import ACTION_TYPE_TO_CLASS
  31. from openhands.runtime.builder import DockerRuntimeBuilder
  32. from openhands.runtime.plugins import PluginRequirement
  33. from openhands.runtime.runtime import Runtime
  34. from openhands.runtime.utils import find_available_tcp_port
  35. from openhands.runtime.utils.runtime_build import build_runtime_image
  36. class LogBuffer:
  37. """Synchronous buffer for Docker container logs.
  38. This class provides a thread-safe way to collect, store, and retrieve logs
  39. from a Docker container. It uses a list to store log lines and provides methods
  40. for appending, retrieving, and clearing logs.
  41. """
  42. def __init__(self, container: docker.models.containers.Container):
  43. self.client_ready = False
  44. self.init_msg = 'Runtime client initialized.'
  45. self.buffer: list[str] = []
  46. self.lock = threading.Lock()
  47. self._stop_event = threading.Event()
  48. self.log_generator = container.logs(stream=True, follow=True)
  49. self.log_stream_thread = threading.Thread(target=self.stream_logs)
  50. self.log_stream_thread.daemon = True
  51. self.log_stream_thread.start()
  52. def append(self, log_line: str):
  53. with self.lock:
  54. self.buffer.append(log_line)
  55. def get_and_clear(self) -> list[str]:
  56. with self.lock:
  57. logs = list(self.buffer)
  58. self.buffer.clear()
  59. return logs
  60. def stream_logs(self):
  61. """
  62. Stream logs from the Docker container in a separate thread.
  63. This method runs in its own thread to handle the blocking
  64. operation of reading log lines from the Docker SDK's synchronous generator.
  65. """
  66. try:
  67. for log_line in self.log_generator:
  68. if self._stop_event.is_set():
  69. break
  70. if log_line:
  71. decoded_line = log_line.decode('utf-8').rstrip()
  72. self.append(decoded_line)
  73. if self.init_msg in decoded_line:
  74. self.client_ready = True
  75. except Exception as e:
  76. logger.error(f'Error streaming docker logs: {e}')
  77. def __del__(self):
  78. if self.log_stream_thread.is_alive():
  79. logger.warn(
  80. "LogBuffer was not properly closed. Use 'log_buffer.close()' for clean shutdown."
  81. )
  82. self.close(timeout=5)
  83. def close(self, timeout: float = 5.0):
  84. self._stop_event.set()
  85. self.log_stream_thread.join(timeout)
  86. class EventStreamRuntime(Runtime):
  87. """This runtime will subscribe the event stream.
  88. When receive an event, it will send the event to runtime-client which run inside the docker environment.
  89. From the sid also an instance_id is generated in combination with a UID.
  90. Args:
  91. config (AppConfig): The application configuration.
  92. event_stream (EventStream): The event stream to subscribe to.
  93. sid (str, optional): The session ID. Defaults to 'default'.
  94. plugins (list[PluginRequirement] | None, optional): List of plugin requirements. Defaults to None.
  95. env_vars (dict[str, str] | None, optional): Environment variables to set. Defaults to None.
  96. """
  97. container_name_prefix = 'openhands-sandbox-'
  98. def __init__(
  99. self,
  100. config: AppConfig,
  101. event_stream: EventStream,
  102. sid: str = 'default',
  103. plugins: list[PluginRequirement] | None = None,
  104. env_vars: dict[str, str] | None = None,
  105. ):
  106. self.config = config
  107. self._host_port = 30000 # initial dummy value
  108. self._container_port = 30001 # initial dummy value
  109. self.api_url = (
  110. f'http://{self.config.sandbox.api_hostname}:{self._container_port}'
  111. )
  112. self.session = requests.Session()
  113. self.instance_id = (
  114. sid + '_' + str(uuid.uuid4()) if sid is not None else str(uuid.uuid4())
  115. )
  116. self.docker_client: docker.DockerClient = self._init_docker_client()
  117. self.base_container_image = self.config.sandbox.base_container_image
  118. self.runtime_container_image = self.config.sandbox.runtime_container_image
  119. self.container_name = self.container_name_prefix + self.instance_id
  120. self.container = None
  121. self.action_semaphore = threading.Semaphore(1) # Ensure one action at a time
  122. self.runtime_builder = DockerRuntimeBuilder(self.docker_client)
  123. logger.debug(f'EventStreamRuntime `{self.instance_id}`')
  124. # Buffer for container logs
  125. self.log_buffer: LogBuffer | None = None
  126. if self.config.sandbox.runtime_extra_deps:
  127. logger.info(
  128. f'Installing extra user-provided dependencies in the runtime image: {self.config.sandbox.runtime_extra_deps}'
  129. )
  130. self.skip_container_logs = (
  131. os.environ.get('SKIP_CONTAINER_LOGS', 'false').lower() == 'true'
  132. )
  133. if self.runtime_container_image is None:
  134. if self.base_container_image is None:
  135. raise ValueError(
  136. 'Neither runtime container image nor base container image is set'
  137. )
  138. self.runtime_container_image = build_runtime_image(
  139. self.base_container_image,
  140. self.runtime_builder,
  141. extra_deps=self.config.sandbox.runtime_extra_deps,
  142. )
  143. self.container = self._init_container(
  144. sandbox_workspace_dir=self.config.workspace_mount_path_in_sandbox, # e.g. /workspace
  145. mount_dir=self.config.workspace_mount_path, # e.g. /opt/openhands/_test_workspace
  146. plugins=plugins,
  147. )
  148. # will initialize both the event stream and the env vars
  149. super().__init__(config, event_stream, sid, plugins, env_vars)
  150. logger.info(
  151. f'Container initialized with plugins: {[plugin.name for plugin in self.plugins]}'
  152. )
  153. logger.info(f'Container initialized with env vars: {env_vars}')
  154. time.sleep(1)
  155. @staticmethod
  156. def _init_docker_client() -> docker.DockerClient:
  157. try:
  158. return docker.from_env()
  159. except Exception as ex:
  160. logger.error(
  161. 'Launch docker client failed. Please make sure you have installed docker and started docker desktop/daemon.'
  162. )
  163. raise ex
  164. @tenacity.retry(
  165. stop=tenacity.stop_after_attempt(5),
  166. wait=tenacity.wait_exponential(multiplier=1, min=4, max=60),
  167. )
  168. def _init_container(
  169. self,
  170. sandbox_workspace_dir: str,
  171. mount_dir: str | None = None,
  172. plugins: list[PluginRequirement] | None = None,
  173. ):
  174. try:
  175. logger.info(
  176. f'Starting container with image: {self.runtime_container_image} and name: {self.container_name}'
  177. )
  178. plugin_arg = ''
  179. if plugins is not None and len(plugins) > 0:
  180. plugin_arg = (
  181. f'--plugins {" ".join([plugin.name for plugin in plugins])} '
  182. )
  183. self._host_port = self._find_available_port()
  184. self._container_port = (
  185. self._host_port
  186. ) # in future this might differ from host port
  187. self.api_url = (
  188. f'http://{self.config.sandbox.api_hostname}:{self._container_port}'
  189. )
  190. use_host_network = self.config.sandbox.use_host_network
  191. network_mode: str | None = 'host' if use_host_network else None
  192. port_mapping: dict[str, list[dict[str, str]]] | None = (
  193. None
  194. if use_host_network
  195. else {
  196. f'{self._container_port}/tcp': [{'HostPort': str(self._host_port)}]
  197. }
  198. )
  199. if use_host_network:
  200. logger.warn(
  201. 'Using host network mode. If you are using MacOS, please make sure you have the latest version of Docker Desktop and enabled host network feature: https://docs.docker.com/network/drivers/host/#docker-desktop'
  202. )
  203. # Combine environment variables
  204. environment = {
  205. 'port': str(self._container_port),
  206. 'PYTHONUNBUFFERED': 1,
  207. }
  208. if self.config.debug:
  209. environment['DEBUG'] = 'true'
  210. logger.info(f'Workspace Base: {self.config.workspace_base}')
  211. if mount_dir is not None and sandbox_workspace_dir is not None:
  212. # e.g. result would be: {"/home/user/openhands/workspace": {'bind': "/workspace", 'mode': 'rw'}}
  213. volumes = {mount_dir: {'bind': sandbox_workspace_dir, 'mode': 'rw'}}
  214. logger.info(f'Mount dir: {mount_dir}')
  215. else:
  216. logger.warn(
  217. 'Warning: Mount dir is not set, will not mount the workspace directory to the container!\n'
  218. )
  219. volumes = None
  220. logger.info(f'Sandbox workspace: {sandbox_workspace_dir}')
  221. if self.config.sandbox.browsergym_eval_env is not None:
  222. browsergym_arg = (
  223. f'--browsergym-eval-env {self.config.sandbox.browsergym_eval_env}'
  224. )
  225. else:
  226. browsergym_arg = ''
  227. container = self.docker_client.containers.run(
  228. self.runtime_container_image,
  229. command=(
  230. f'/openhands/miniforge3/bin/mamba run --no-capture-output -n base '
  231. f'poetry run '
  232. f'python -u -m openhands.runtime.client.client {self._container_port} '
  233. f'--working-dir "{sandbox_workspace_dir}" '
  234. f'{plugin_arg}'
  235. f'--username {"openhands" if self.config.run_as_openhands else "root"} '
  236. f'--user-id {self.config.sandbox.user_id} '
  237. f'{browsergym_arg}'
  238. ),
  239. network_mode=network_mode,
  240. ports=port_mapping,
  241. working_dir='/openhands/code/', # do not change this!
  242. name=self.container_name,
  243. detach=True,
  244. environment=environment,
  245. volumes=volumes,
  246. )
  247. self.log_buffer = LogBuffer(container)
  248. logger.info(f'Container started. Server url: {self.api_url}')
  249. return container
  250. except Exception as e:
  251. logger.error(
  252. f'Error: Instance {self.instance_id} FAILED to start container!\n'
  253. )
  254. logger.exception(e)
  255. self.close(close_client=False)
  256. raise e
  257. @tenacity.retry(
  258. stop=tenacity.stop_after_attempt(10),
  259. wait=tenacity.wait_exponential(multiplier=2, min=1, max=20),
  260. reraise=(ConnectionRefusedError,),
  261. )
  262. def _wait_until_alive(self):
  263. logger.debug('Getting container logs...')
  264. assert (
  265. self.log_buffer is not None
  266. ), 'Log buffer is expected to be initialized when container is started'
  267. # Always process logs, regardless of client_ready status
  268. logs = self.log_buffer.get_and_clear()
  269. if logs:
  270. formatted_logs = '\n'.join([f' |{log}' for log in logs])
  271. logger.info(
  272. '\n'
  273. + '-' * 35
  274. + 'Container logs:'
  275. + '-' * 35
  276. + f'\n{formatted_logs}'
  277. + '\n'
  278. + '-' * 80
  279. )
  280. if not self.log_buffer.client_ready:
  281. time.sleep(1)
  282. attempts = 0
  283. while not self.log_buffer.client_ready and attempts < 5:
  284. attempts += 1
  285. time.sleep(1)
  286. logs = self.log_buffer.get_and_clear()
  287. if logs:
  288. formatted_logs = '\n'.join([f' |{log}' for log in logs])
  289. logger.info(
  290. '\n'
  291. + '-' * 35
  292. + 'Container logs:'
  293. + '-' * 35
  294. + f'\n{formatted_logs}'
  295. + '\n'
  296. + '-' * 80
  297. )
  298. response = self.session.get(f'{self.api_url}/alive')
  299. if response.status_code == 200:
  300. return
  301. else:
  302. msg = f'Action execution API is not alive. Response: {response}'
  303. logger.error(msg)
  304. raise RuntimeError(msg)
  305. def close(self, close_client: bool = True, rm_all_containers: bool = True):
  306. """Closes the EventStreamRuntime and associated objects
  307. Parameters:
  308. - close_client (bool): Whether to close the DockerClient
  309. - rm_all_containers (bool): Whether to remove all containers with the 'openhands-sandbox-' prefix
  310. """
  311. if self.log_buffer:
  312. self.log_buffer.close()
  313. if self.session:
  314. self.session.close()
  315. try:
  316. containers = self.docker_client.containers.list(all=True)
  317. for container in containers:
  318. try:
  319. # If the app doesn't shut down properly, it can leave runtime containers on the system. This ensures
  320. # that all 'openhands-sandbox-' containers are removed as well.
  321. if rm_all_containers and container.name.startswith(
  322. self.container_name_prefix
  323. ):
  324. container.remove(force=True)
  325. elif container.name == self.container_name:
  326. if not self.skip_container_logs:
  327. logs = container.logs(tail=1000).decode('utf-8')
  328. logger.debug(
  329. f'==== Container logs on close ====\n{logs}\n==== End of container logs ===='
  330. )
  331. container.remove(force=True)
  332. except docker.errors.APIError:
  333. pass
  334. except docker.errors.NotFound:
  335. pass
  336. except docker.errors.NotFound: # yes, this can happen!
  337. pass
  338. if close_client:
  339. self.docker_client.close()
  340. def run_action(self, action: Action) -> Observation:
  341. # set timeout to default if not set
  342. if action.timeout is None:
  343. action.timeout = self.config.sandbox.timeout
  344. with self.action_semaphore:
  345. if not action.runnable:
  346. return NullObservation('')
  347. if (
  348. hasattr(action, 'is_confirmed')
  349. and action.is_confirmed
  350. == ActionConfirmationStatus.AWAITING_CONFIRMATION
  351. ):
  352. return NullObservation('')
  353. action_type = action.action # type: ignore[attr-defined]
  354. if action_type not in ACTION_TYPE_TO_CLASS:
  355. return ErrorObservation(f'Action {action_type} does not exist.')
  356. if not hasattr(self, action_type):
  357. return ErrorObservation(
  358. f'Action {action_type} is not supported in the current runtime.'
  359. )
  360. if (
  361. hasattr(action, 'is_confirmed')
  362. and action.is_confirmed == ActionConfirmationStatus.REJECTED
  363. ):
  364. return UserRejectObservation(
  365. 'Action has been rejected by the user! Waiting for further user input.'
  366. )
  367. logger.info('Awaiting session')
  368. self._wait_until_alive()
  369. assert action.timeout is not None
  370. try:
  371. response = self.session.post(
  372. f'{self.api_url}/execute_action',
  373. json={'action': event_to_dict(action)},
  374. timeout=action.timeout,
  375. )
  376. if response.status_code == 200:
  377. output = response.json()
  378. obs = observation_from_dict(output)
  379. obs._cause = action.id # type: ignore[attr-defined]
  380. else:
  381. logger.debug(f'action: {action}')
  382. logger.debug(f'response: {response}')
  383. error_message = response.text
  384. logger.error(f'Error from server: {error_message}')
  385. obs = ErrorObservation(f'Command execution failed: {error_message}')
  386. except requests.Timeout:
  387. logger.error('No response received within the timeout period.')
  388. obs = ErrorObservation('Command execution timed out')
  389. except Exception as e:
  390. logger.error(f'Error during command execution: {e}')
  391. obs = ErrorObservation(f'Command execution failed: {str(e)}')
  392. # TODO Refresh docker logs or not?
  393. # self._wait_until_alive()
  394. return obs
  395. def run(self, action: CmdRunAction) -> Observation:
  396. return self.run_action(action)
  397. def run_ipython(self, action: IPythonRunCellAction) -> Observation:
  398. return self.run_action(action)
  399. def read(self, action: FileReadAction) -> Observation:
  400. return self.run_action(action)
  401. def write(self, action: FileWriteAction) -> Observation:
  402. return self.run_action(action)
  403. def browse(self, action: BrowseURLAction) -> Observation:
  404. return self.run_action(action)
  405. def browse_interactive(self, action: BrowseInteractiveAction) -> Observation:
  406. return self.run_action(action)
  407. # ====================================================================
  408. # Implement these methods (for file operations) in the subclass
  409. # ====================================================================
  410. def copy_to(
  411. self, host_src: str, sandbox_dest: str, recursive: bool = False
  412. ) -> None:
  413. if not os.path.exists(host_src):
  414. raise FileNotFoundError(f'Source file {host_src} does not exist')
  415. self._wait_until_alive()
  416. try:
  417. if recursive:
  418. # For recursive copy, create a zip file
  419. with tempfile.NamedTemporaryFile(
  420. suffix='.zip', delete=False
  421. ) as temp_zip:
  422. temp_zip_path = temp_zip.name
  423. with ZipFile(temp_zip_path, 'w') as zipf:
  424. for root, _, files in os.walk(host_src):
  425. for file in files:
  426. file_path = os.path.join(root, file)
  427. arcname = os.path.relpath(
  428. file_path, os.path.dirname(host_src)
  429. )
  430. zipf.write(file_path, arcname)
  431. upload_data = {'file': open(temp_zip_path, 'rb')}
  432. else:
  433. # For single file copy
  434. upload_data = {'file': open(host_src, 'rb')}
  435. params = {'destination': sandbox_dest, 'recursive': str(recursive).lower()}
  436. response = self.session.post(
  437. f'{self.api_url}/upload_file', files=upload_data, params=params
  438. )
  439. if response.status_code == 200:
  440. return
  441. else:
  442. error_message = response.text
  443. raise Exception(f'Copy operation failed: {error_message}')
  444. except requests.Timeout:
  445. raise TimeoutError('Copy operation timed out')
  446. except Exception as e:
  447. raise RuntimeError(f'Copy operation failed: {str(e)}')
  448. finally:
  449. if recursive:
  450. os.unlink(temp_zip_path)
  451. logger.info(f'Copy completed: host:{host_src} -> runtime:{sandbox_dest}')
  452. # Refresh docker logs
  453. self._wait_until_alive()
  454. def list_files(self, path: str | None = None) -> list[str]:
  455. """List files in the sandbox.
  456. If path is None, list files in the sandbox's initial working directory (e.g., /workspace).
  457. """
  458. self._wait_until_alive()
  459. try:
  460. data = {}
  461. if path is not None:
  462. data['path'] = path
  463. response = self.session.post(f'{self.api_url}/list_files', json=data)
  464. if response.status_code == 200:
  465. response_json = response.json()
  466. assert isinstance(response_json, list)
  467. return response_json
  468. else:
  469. error_message = response.text
  470. raise Exception(f'List files operation failed: {error_message}')
  471. except requests.Timeout:
  472. raise TimeoutError('List files operation timed out')
  473. except Exception as e:
  474. raise RuntimeError(f'List files operation failed: {str(e)}')
  475. def _is_port_in_use_docker(self, port):
  476. containers = self.docker_client.containers.list()
  477. for container in containers:
  478. container_ports = container.ports
  479. if str(port) in str(container_ports):
  480. return True
  481. return False
  482. def _find_available_port(self, max_attempts=5):
  483. port = 39999
  484. for _ in range(max_attempts):
  485. port = find_available_tcp_port(30000, 39999)
  486. if not self._is_port_in_use_docker(port):
  487. return port
  488. # If no port is found after max_attempts, return the last tried port
  489. return port