eventstream_runtime.py 25 KB

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