runtime.py 24 KB

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