runtime.py 15 KB

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