runtime.py 22 KB

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