runtime.py 25 KB

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