runtime.py 15 KB

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