eventstream_runtime.py 25 KB

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