runtime.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. import os
  2. import tempfile
  3. import threading
  4. import uuid
  5. from typing import Callable, Optional
  6. from zipfile import ZipFile
  7. import requests
  8. from requests.exceptions import Timeout
  9. from tenacity import (
  10. retry,
  11. retry_if_exception_type,
  12. stop_after_attempt,
  13. wait_exponential,
  14. )
  15. from openhands.core.config import AppConfig
  16. from openhands.core.logger import openhands_logger as logger
  17. from openhands.events import EventStream
  18. from openhands.events.action import (
  19. BrowseInteractiveAction,
  20. BrowseURLAction,
  21. CmdRunAction,
  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. )
  32. from openhands.events.serialization import event_to_dict, observation_from_dict
  33. from openhands.events.serialization.action import ACTION_TYPE_TO_CLASS
  34. from openhands.runtime.builder.remote import RemoteRuntimeBuilder
  35. from openhands.runtime.plugins import PluginRequirement
  36. from openhands.runtime.runtime import Runtime
  37. from openhands.runtime.utils.request import (
  38. DEFAULT_RETRY_EXCEPTIONS,
  39. is_404_error,
  40. send_request,
  41. )
  42. from openhands.runtime.utils.runtime_build import build_runtime_image
  43. from openhands.utils.tenacity_stop import stop_if_should_exit
  44. class RemoteRuntime(Runtime):
  45. """This runtime will connect to a remote oh-runtime-client."""
  46. port: int = 60000 # default port for the remote runtime client
  47. def __init__(
  48. self,
  49. config: AppConfig,
  50. event_stream: EventStream,
  51. sid: str = 'default',
  52. plugins: list[PluginRequirement] | None = None,
  53. env_vars: dict[str, str] | None = None,
  54. status_message_callback: Optional[Callable] = None,
  55. ):
  56. self.config = config
  57. if self.config.sandbox.api_key is None:
  58. raise ValueError(
  59. 'API key is required to use the remote runtime. '
  60. 'Please set the API key in the config (config.toml) or as an environment variable (SANDBOX_API_KEY).'
  61. )
  62. self.session = requests.Session()
  63. self.session.headers.update({'X-API-Key': self.config.sandbox.api_key})
  64. self.action_semaphore = threading.Semaphore(1)
  65. if self.config.workspace_base is not None:
  66. logger.warning(
  67. 'Setting workspace_base is not supported in the remote runtime.'
  68. )
  69. self.runtime_builder = RemoteRuntimeBuilder(
  70. self.config.sandbox.remote_runtime_api_url, self.config.sandbox.api_key
  71. )
  72. self.runtime_id: str | None = None
  73. self.runtime_url: str | None = None
  74. self.instance_id = (
  75. sid + str(uuid.uuid4()) if sid is not None else str(uuid.uuid4())
  76. )
  77. self.container_name = 'oh-remote-runtime-' + self.instance_id
  78. if self.config.sandbox.runtime_container_image is not None:
  79. logger.info(
  80. f'Running remote runtime with image: {self.config.sandbox.runtime_container_image}'
  81. )
  82. self.container_image = self.config.sandbox.runtime_container_image
  83. else:
  84. logger.info(
  85. f'Building remote runtime with base image: {self.config.sandbox.base_container_image}'
  86. )
  87. logger.debug(f'RemoteRuntime `{sid}` config:\n{self.config}')
  88. response = send_request(
  89. self.session,
  90. 'GET',
  91. f'{self.config.sandbox.remote_runtime_api_url}/registry_prefix',
  92. )
  93. response_json = response.json()
  94. registry_prefix = response_json['registry_prefix']
  95. os.environ['OH_RUNTIME_RUNTIME_IMAGE_REPO'] = (
  96. registry_prefix.rstrip('/') + '/runtime'
  97. )
  98. logger.info(
  99. f'Runtime image repo: {os.environ["OH_RUNTIME_RUNTIME_IMAGE_REPO"]}'
  100. )
  101. if self.config.sandbox.runtime_extra_deps:
  102. logger.info(
  103. f'Installing extra user-provided dependencies in the runtime image: {self.config.sandbox.runtime_extra_deps}'
  104. )
  105. # Build the container image
  106. self.container_image = build_runtime_image(
  107. self.config.sandbox.base_container_image,
  108. self.runtime_builder,
  109. extra_deps=self.config.sandbox.runtime_extra_deps,
  110. )
  111. response = send_request(
  112. self.session,
  113. 'GET',
  114. f'{self.config.sandbox.remote_runtime_api_url}/image_exists',
  115. params={'image': self.container_image},
  116. )
  117. if response.status_code != 200 or not response.json()['exists']:
  118. raise RuntimeError(
  119. f'Container image {self.container_image} does not exist'
  120. )
  121. # Prepare the request body for the /start endpoint
  122. plugin_arg = ''
  123. if plugins is not None and len(plugins) > 0:
  124. plugin_arg = f'--plugins {" ".join([plugin.name for plugin in plugins])} '
  125. browsergym_arg = (
  126. f'--browsergym-eval-env {self.config.sandbox.browsergym_eval_env}'
  127. if self.config.sandbox.browsergym_eval_env is not None
  128. else ''
  129. )
  130. start_request = {
  131. 'image': self.container_image,
  132. 'command': (
  133. f'/openhands/miniforge3/bin/mamba run --no-capture-output -n base '
  134. 'PYTHONUNBUFFERED=1 poetry run '
  135. f'python -u -m openhands.runtime.client.client {self.port} '
  136. f'--working-dir {self.config.workspace_mount_path_in_sandbox} '
  137. f'{plugin_arg}'
  138. f'--username {"openhands" if self.config.run_as_openhands else "root"} '
  139. f'--user-id {self.config.sandbox.user_id} '
  140. f'{browsergym_arg}'
  141. ),
  142. 'working_dir': '/openhands/code/',
  143. 'name': self.container_name,
  144. 'environment': {'DEBUG': 'true'} if self.config.debug else {},
  145. }
  146. # Start the sandbox using the /start endpoint
  147. response = send_request(
  148. self.session,
  149. 'POST',
  150. f'{self.config.sandbox.remote_runtime_api_url}/start',
  151. json=start_request,
  152. )
  153. if response.status_code != 201:
  154. raise RuntimeError(f'Failed to start sandbox: {response.text}')
  155. start_response = response.json()
  156. self.runtime_id = start_response['runtime_id']
  157. self.runtime_url = start_response['url']
  158. logger.info(
  159. f'Sandbox started. Runtime ID: {self.runtime_id}, URL: {self.runtime_url}'
  160. )
  161. # Initialize the eventstream and env vars
  162. super().__init__(
  163. config, event_stream, sid, plugins, env_vars, status_message_callback
  164. )
  165. logger.info(
  166. f'Runtime initialized with plugins: {[plugin.name for plugin in self.plugins]}'
  167. )
  168. logger.info(f'Runtime initialized with env vars: {env_vars}')
  169. assert (
  170. self.runtime_id is not None
  171. ), 'Runtime ID is not set. This should never happen.'
  172. assert (
  173. self.runtime_url is not None
  174. ), 'Runtime URL is not set. This should never happen.'
  175. @retry(
  176. stop=stop_after_attempt(10) | stop_if_should_exit(),
  177. wait=wait_exponential(multiplier=1, min=4, max=60),
  178. retry=retry_if_exception_type(RuntimeError),
  179. reraise=True,
  180. )
  181. def _wait_until_alive(self):
  182. logger.info(f'Waiting for runtime to be alive at url: {self.runtime_url}')
  183. response = send_request(
  184. self.session,
  185. 'GET',
  186. f'{self.runtime_url}/alive',
  187. # Retry 404 errors for the /alive endpoint
  188. # because the runtime might just be starting up
  189. # and have not registered the endpoint yet
  190. retry_fns=[is_404_error],
  191. # leave enough time for the runtime to start up
  192. timeout=600,
  193. )
  194. if response.status_code != 200:
  195. msg = f'Runtime is not alive yet (id={self.runtime_id}). Status: {response.status_code}.'
  196. logger.warning(msg)
  197. raise RuntimeError(msg)
  198. def close(self):
  199. if self.runtime_id:
  200. try:
  201. response = send_request(
  202. self.session,
  203. 'POST',
  204. f'{self.config.sandbox.remote_runtime_api_url}/stop',
  205. json={'runtime_id': self.runtime_id},
  206. )
  207. if response.status_code != 200:
  208. logger.error(f'Failed to stop sandbox: {response.text}')
  209. else:
  210. logger.info(f'Sandbox stopped. Runtime ID: {self.runtime_id}')
  211. except Exception as e:
  212. raise e
  213. finally:
  214. self.session.close()
  215. def run_action(self, action: Action) -> Observation:
  216. if action.timeout is None:
  217. action.timeout = self.config.sandbox.timeout
  218. with self.action_semaphore:
  219. if not action.runnable:
  220. return NullObservation('')
  221. action_type = action.action # type: ignore[attr-defined]
  222. if action_type not in ACTION_TYPE_TO_CLASS:
  223. return ErrorObservation(f'Action {action_type} does not exist.')
  224. if not hasattr(self, action_type):
  225. return ErrorObservation(
  226. f'Action {action_type} is not supported in the current runtime.'
  227. )
  228. self._wait_until_alive()
  229. assert action.timeout is not None
  230. try:
  231. logger.info('Executing action')
  232. request_body = {'action': event_to_dict(action)}
  233. logger.debug(f'Request body: {request_body}')
  234. response = send_request(
  235. self.session,
  236. 'POST',
  237. f'{self.runtime_url}/execute_action',
  238. json=request_body,
  239. timeout=action.timeout,
  240. retry_exceptions=list(
  241. filter(lambda e: e != TimeoutError, DEFAULT_RETRY_EXCEPTIONS)
  242. ),
  243. # Retry 404 errors for the /execute_action endpoint
  244. # because the runtime might just be starting up
  245. # and have not registered the endpoint yet
  246. retry_fns=[is_404_error],
  247. )
  248. if response.status_code == 200:
  249. output = response.json()
  250. obs = observation_from_dict(output)
  251. obs._cause = action.id # type: ignore[attr-defined]
  252. return obs
  253. else:
  254. error_message = response.text
  255. logger.error(f'Error from server: {error_message}')
  256. obs = ErrorObservation(f'Action execution failed: {error_message}')
  257. except Timeout:
  258. logger.error('No response received within the timeout period.')
  259. obs = ErrorObservation('Action execution timed out')
  260. except Exception as e:
  261. logger.error(f'Error during action execution: {e}')
  262. obs = ErrorObservation(f'Action execution failed: {str(e)}')
  263. return obs
  264. def run(self, action: CmdRunAction) -> Observation:
  265. return self.run_action(action)
  266. def run_ipython(self, action: IPythonRunCellAction) -> Observation:
  267. return self.run_action(action)
  268. def read(self, action: FileReadAction) -> Observation:
  269. return self.run_action(action)
  270. def write(self, action: FileWriteAction) -> Observation:
  271. return self.run_action(action)
  272. def browse(self, action: BrowseURLAction) -> Observation:
  273. return self.run_action(action)
  274. def browse_interactive(self, action: BrowseInteractiveAction) -> Observation:
  275. return self.run_action(action)
  276. def copy_to(
  277. self, host_src: str, sandbox_dest: str, recursive: bool = False
  278. ) -> None:
  279. if not os.path.exists(host_src):
  280. raise FileNotFoundError(f'Source file {host_src} does not exist')
  281. self._wait_until_alive()
  282. try:
  283. if recursive:
  284. with tempfile.NamedTemporaryFile(
  285. suffix='.zip', delete=False
  286. ) as temp_zip:
  287. temp_zip_path = temp_zip.name
  288. with ZipFile(temp_zip_path, 'w') as zipf:
  289. for root, _, files in os.walk(host_src):
  290. for file in files:
  291. file_path = os.path.join(root, file)
  292. arcname = os.path.relpath(
  293. file_path, os.path.dirname(host_src)
  294. )
  295. zipf.write(file_path, arcname)
  296. upload_data = {'file': open(temp_zip_path, 'rb')}
  297. else:
  298. upload_data = {'file': open(host_src, 'rb')}
  299. params = {'destination': sandbox_dest, 'recursive': str(recursive).lower()}
  300. response = send_request(
  301. self.session,
  302. 'POST',
  303. f'{self.runtime_url}/upload_file',
  304. files=upload_data,
  305. params=params,
  306. retry_exceptions=list(
  307. filter(lambda e: e != TimeoutError, DEFAULT_RETRY_EXCEPTIONS)
  308. ),
  309. )
  310. if response.status_code == 200:
  311. logger.info(
  312. f'Copy completed: host:{host_src} -> runtime:{sandbox_dest}. Response: {response.text}'
  313. )
  314. return
  315. else:
  316. error_message = response.text
  317. raise Exception(f'Copy operation failed: {error_message}')
  318. except TimeoutError:
  319. raise TimeoutError('Copy operation timed out')
  320. except Exception as e:
  321. raise RuntimeError(f'Copy operation failed: {str(e)}')
  322. finally:
  323. if recursive:
  324. os.unlink(temp_zip_path)
  325. logger.info(f'Copy completed: host:{host_src} -> runtime:{sandbox_dest}')
  326. def list_files(self, path: str | None = None) -> list[str]:
  327. self._wait_until_alive()
  328. try:
  329. data = {}
  330. if path is not None:
  331. data['path'] = path
  332. response = send_request(
  333. self.session,
  334. 'POST',
  335. f'{self.runtime_url}/list_files',
  336. json=data,
  337. retry_exceptions=list(
  338. filter(lambda e: e != TimeoutError, DEFAULT_RETRY_EXCEPTIONS)
  339. ),
  340. )
  341. if response.status_code == 200:
  342. response_json = response.json()
  343. assert isinstance(response_json, list)
  344. return response_json
  345. else:
  346. error_message = response.text
  347. raise Exception(f'List files operation failed: {error_message}')
  348. except TimeoutError:
  349. raise TimeoutError('List files operation timed out')
  350. except Exception as e:
  351. raise RuntimeError(f'List files operation failed: {str(e)}')