runtime.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. import os
  2. import tempfile
  3. import threading
  4. import time
  5. from typing import Callable, Optional
  6. from zipfile import ZipFile
  7. import requests
  8. from requests.exceptions import Timeout
  9. from openhands.core.config import AppConfig
  10. from openhands.core.logger import openhands_logger as logger
  11. from openhands.events import EventStream
  12. from openhands.events.action import (
  13. BrowseInteractiveAction,
  14. BrowseURLAction,
  15. CmdRunAction,
  16. FileReadAction,
  17. FileWriteAction,
  18. IPythonRunCellAction,
  19. )
  20. from openhands.events.action.action import Action
  21. from openhands.events.observation import (
  22. ErrorObservation,
  23. NullObservation,
  24. Observation,
  25. )
  26. from openhands.events.serialization import event_to_dict, observation_from_dict
  27. from openhands.events.serialization.action import ACTION_TYPE_TO_CLASS
  28. from openhands.runtime.builder.remote import RemoteRuntimeBuilder
  29. from openhands.runtime.plugins import PluginRequirement
  30. from openhands.runtime.runtime import Runtime
  31. from openhands.runtime.utils.request import (
  32. DEFAULT_RETRY_EXCEPTIONS,
  33. is_404_error,
  34. send_request_with_retry,
  35. )
  36. from openhands.runtime.utils.runtime_build import build_runtime_image
  37. class RemoteRuntime(Runtime):
  38. """This runtime will connect to a remote oh-runtime-client."""
  39. port: int = 60000 # default port for the remote runtime client
  40. def __init__(
  41. self,
  42. config: AppConfig,
  43. event_stream: EventStream,
  44. sid: str = 'default',
  45. plugins: list[PluginRequirement] | None = None,
  46. env_vars: dict[str, str] | None = None,
  47. status_message_callback: Optional[Callable] = None,
  48. attach_to_existing: bool = False,
  49. ):
  50. self.config = config
  51. self.status_message_callback = status_message_callback
  52. if self.config.sandbox.api_key is None:
  53. raise ValueError(
  54. 'API key is required to use the remote runtime. '
  55. 'Please set the API key in the config (config.toml) or as an environment variable (SANDBOX_API_KEY).'
  56. )
  57. self.session = requests.Session()
  58. self.session.headers.update({'X-API-Key': self.config.sandbox.api_key})
  59. self.action_semaphore = threading.Semaphore(1)
  60. if self.config.workspace_base is not None:
  61. logger.warning(
  62. 'Setting workspace_base is not supported in the remote runtime.'
  63. )
  64. self.runtime_builder = RemoteRuntimeBuilder(
  65. self.config.sandbox.remote_runtime_api_url, self.config.sandbox.api_key
  66. )
  67. self.runtime_id: str | None = None
  68. self.runtime_url: str | None = None
  69. self.sid = sid
  70. self._start_or_attach_to_runtime(plugins, attach_to_existing)
  71. # Initialize the eventstream and env vars
  72. super().__init__(
  73. config,
  74. event_stream,
  75. sid,
  76. plugins,
  77. env_vars,
  78. status_message_callback,
  79. attach_to_existing,
  80. )
  81. self._wait_until_alive()
  82. self.setup_initial_env()
  83. def _start_or_attach_to_runtime(
  84. self, plugins: list[PluginRequirement] | None, attach_to_existing: bool = False
  85. ):
  86. existing_runtime = self._check_existing_runtime()
  87. if existing_runtime:
  88. logger.info(f'Using existing runtime with ID: {self.runtime_id}')
  89. elif attach_to_existing:
  90. raise RuntimeError('Could not find existing runtime to attach to.')
  91. else:
  92. self.send_status_message('STATUS$STARTING_CONTAINER')
  93. if self.config.sandbox.runtime_container_image is None:
  94. logger.info(
  95. f'Building remote runtime with base image: {self.config.sandbox.base_container_image}'
  96. )
  97. self._build_runtime()
  98. else:
  99. logger.info(
  100. f'Running remote runtime with image: {self.config.sandbox.runtime_container_image}'
  101. )
  102. self.container_image = self.config.sandbox.runtime_container_image
  103. self._start_runtime(plugins)
  104. assert (
  105. self.runtime_id is not None
  106. ), 'Runtime ID is not set. This should never happen.'
  107. assert (
  108. self.runtime_url is not None
  109. ), 'Runtime URL is not set. This should never happen.'
  110. self.send_status_message('STATUS$WAITING_FOR_CLIENT')
  111. self._wait_until_alive()
  112. def _check_existing_runtime(self) -> bool:
  113. try:
  114. response = send_request_with_retry(
  115. self.session,
  116. 'GET',
  117. f'{self.config.sandbox.remote_runtime_api_url}/runtime/{self.sid}',
  118. timeout=5,
  119. )
  120. except Exception as e:
  121. logger.debug(f'Error while looking for remote runtime: {e}')
  122. return False
  123. if response.status_code == 200:
  124. data = response.json()
  125. status = data.get('status')
  126. if status == 'running':
  127. self._parse_runtime_response(response)
  128. return True
  129. elif status == 'stopped':
  130. logger.info('Found existing remote runtime, but it is stopped')
  131. return False
  132. elif status == 'paused':
  133. logger.info('Found existing remote runtime, but it is paused')
  134. self._parse_runtime_response(response)
  135. self._resume_runtime()
  136. return True
  137. else:
  138. logger.error(f'Invalid response from runtime API: {data}')
  139. return False
  140. else:
  141. logger.info('Could not find existing remote runtime')
  142. return False
  143. def _build_runtime(self):
  144. logger.debug(f'RemoteRuntime `{self.sid}` config:\n{self.config}')
  145. response = send_request_with_retry(
  146. self.session,
  147. 'GET',
  148. f'{self.config.sandbox.remote_runtime_api_url}/registry_prefix',
  149. timeout=30,
  150. )
  151. response_json = response.json()
  152. registry_prefix = response_json['registry_prefix']
  153. os.environ['OH_RUNTIME_RUNTIME_IMAGE_REPO'] = (
  154. registry_prefix.rstrip('/') + '/runtime'
  155. )
  156. logger.info(
  157. f'Runtime image repo: {os.environ["OH_RUNTIME_RUNTIME_IMAGE_REPO"]}'
  158. )
  159. if self.config.sandbox.runtime_extra_deps:
  160. logger.info(
  161. f'Installing extra user-provided dependencies in the runtime image: {self.config.sandbox.runtime_extra_deps}'
  162. )
  163. # Build the container image
  164. self.container_image = build_runtime_image(
  165. self.config.sandbox.base_container_image,
  166. self.runtime_builder,
  167. extra_deps=self.config.sandbox.runtime_extra_deps,
  168. force_rebuild=self.config.sandbox.force_rebuild_runtime,
  169. )
  170. response = send_request_with_retry(
  171. self.session,
  172. 'GET',
  173. f'{self.config.sandbox.remote_runtime_api_url}/image_exists',
  174. params={'image': self.container_image},
  175. timeout=30,
  176. )
  177. if response.status_code != 200 or not response.json()['exists']:
  178. raise RuntimeError(f'Container image {self.container_image} does not exist')
  179. def _start_runtime(self, plugins: list[PluginRequirement] | None):
  180. # Prepare the request body for the /start endpoint
  181. plugin_arg = ''
  182. if plugins is not None and len(plugins) > 0:
  183. plugin_arg = f'--plugins {" ".join([plugin.name for plugin in plugins])} '
  184. browsergym_arg = (
  185. f'--browsergym-eval-env {self.config.sandbox.browsergym_eval_env}'
  186. if self.config.sandbox.browsergym_eval_env is not None
  187. else ''
  188. )
  189. start_request = {
  190. 'image': self.container_image,
  191. 'command': (
  192. f'/openhands/micromamba/bin/micromamba run -n openhands '
  193. 'poetry run '
  194. f'python -u -m openhands.runtime.client.client {self.port} '
  195. f'--working-dir {self.config.workspace_mount_path_in_sandbox} '
  196. f'{plugin_arg}'
  197. f'--username {"openhands" if self.config.run_as_openhands else "root"} '
  198. f'--user-id {self.config.sandbox.user_id} '
  199. f'{browsergym_arg}'
  200. ),
  201. 'working_dir': '/openhands/code/',
  202. 'environment': {'DEBUG': 'true'} if self.config.debug else {},
  203. 'runtime_id': self.sid,
  204. }
  205. # Start the sandbox using the /start endpoint
  206. response = send_request_with_retry(
  207. self.session,
  208. 'POST',
  209. f'{self.config.sandbox.remote_runtime_api_url}/start',
  210. json=start_request,
  211. timeout=300,
  212. )
  213. if response.status_code != 201:
  214. raise RuntimeError(f'Failed to start sandbox: {response.text}')
  215. self._parse_runtime_response(response)
  216. logger.info(
  217. f'Sandbox started. Runtime ID: {self.runtime_id}, URL: {self.runtime_url}'
  218. )
  219. def _resume_runtime(self):
  220. response = send_request_with_retry(
  221. self.session,
  222. 'POST',
  223. f'{self.config.sandbox.remote_runtime_api_url}/resume',
  224. json={'runtime_id': self.runtime_id},
  225. timeout=30,
  226. )
  227. if response.status_code != 200:
  228. raise RuntimeError(f'Failed to resume sandbox: {response.text}')
  229. logger.info(f'Sandbox resumed. Runtime ID: {self.runtime_id}')
  230. def _parse_runtime_response(self, response: requests.Response):
  231. start_response = response.json()
  232. self.runtime_id = start_response['runtime_id']
  233. self.runtime_url = start_response['url']
  234. if 'session_api_key' in start_response:
  235. self.session.headers.update(
  236. {'X-Session-API-Key': start_response['session_api_key']}
  237. )
  238. def _wait_until_alive(self):
  239. logger.info(f'Waiting for runtime to be alive at url: {self.runtime_url}')
  240. # send GET request to /runtime/<id>
  241. pod_running = False
  242. max_not_found_count = 12 # 2 minutes
  243. not_found_count = 0
  244. while not pod_running:
  245. runtime_info_response = send_request_with_retry(
  246. self.session,
  247. 'GET',
  248. f'{self.config.sandbox.remote_runtime_api_url}/runtime/{self.runtime_id}',
  249. timeout=5,
  250. )
  251. if runtime_info_response.status_code != 200:
  252. raise RuntimeError(
  253. f'Failed to get runtime status: {runtime_info_response.status_code}. Response: {runtime_info_response.text}'
  254. )
  255. runtime_data = runtime_info_response.json()
  256. assert runtime_data['runtime_id'] == self.runtime_id
  257. pod_status = runtime_data['pod_status']
  258. logger.info(
  259. f'Waiting for runtime pod to be active. Current status: {pod_status}'
  260. )
  261. if pod_status == 'Ready':
  262. pod_running = True
  263. break
  264. elif pod_status == 'Not Found' and not_found_count < max_not_found_count:
  265. not_found_count += 1
  266. logger.info(
  267. f'Runtime pod not found. Count: {not_found_count} / {max_not_found_count}'
  268. )
  269. elif (
  270. pod_status == 'Failed'
  271. or pod_status == 'Unknown'
  272. or pod_status == 'Not Found'
  273. ):
  274. # clean up the runtime
  275. self.close()
  276. raise RuntimeError(
  277. f'Runtime pod failed to start. Current status: {pod_status}'
  278. )
  279. # Pending otherwise - add proper sleep
  280. time.sleep(10)
  281. response = send_request_with_retry(
  282. self.session,
  283. 'GET',
  284. f'{self.runtime_url}/alive',
  285. # Retry 404 errors for the /alive endpoint
  286. # because the runtime might just be starting up
  287. # and have not registered the endpoint yet
  288. retry_fns=[is_404_error],
  289. # leave enough time for the runtime to start up
  290. timeout=600,
  291. )
  292. if response.status_code != 200:
  293. msg = f'Runtime is not alive yet (id={self.runtime_id}). Status: {response.status_code}.'
  294. logger.warning(msg)
  295. raise RuntimeError(msg)
  296. def close(self, timeout: int = 10):
  297. if self.config.sandbox.keep_remote_runtime_alive:
  298. self.session.close()
  299. return
  300. if self.runtime_id:
  301. try:
  302. response = send_request_with_retry(
  303. self.session,
  304. 'POST',
  305. f'{self.config.sandbox.remote_runtime_api_url}/stop',
  306. json={'runtime_id': self.runtime_id},
  307. timeout=timeout,
  308. )
  309. if response.status_code != 200:
  310. logger.error(f'Failed to stop sandbox: {response.text}')
  311. else:
  312. logger.info(f'Sandbox stopped. Runtime ID: {self.runtime_id}')
  313. except Exception as e:
  314. raise e
  315. finally:
  316. self.session.close()
  317. def run_action(self, action: Action) -> Observation:
  318. if action.timeout is None:
  319. action.timeout = self.config.sandbox.timeout
  320. with self.action_semaphore:
  321. if not action.runnable:
  322. return NullObservation('')
  323. action_type = action.action # type: ignore[attr-defined]
  324. if action_type not in ACTION_TYPE_TO_CLASS:
  325. return ErrorObservation(f'Action {action_type} does not exist.')
  326. if not hasattr(self, action_type):
  327. return ErrorObservation(
  328. f'Action {action_type} is not supported in the current runtime.'
  329. )
  330. assert action.timeout is not None
  331. try:
  332. logger.info('Executing action')
  333. request_body = {'action': event_to_dict(action)}
  334. logger.debug(f'Request body: {request_body}')
  335. response = send_request_with_retry(
  336. self.session,
  337. 'POST',
  338. f'{self.runtime_url}/execute_action',
  339. json=request_body,
  340. timeout=action.timeout,
  341. retry_exceptions=list(
  342. filter(lambda e: e != TimeoutError, DEFAULT_RETRY_EXCEPTIONS)
  343. ),
  344. # Retry 404 errors for the /execute_action endpoint
  345. # because the runtime might just be starting up
  346. # and have not registered the endpoint yet
  347. retry_fns=[is_404_error],
  348. )
  349. if response.status_code == 200:
  350. output = response.json()
  351. obs = observation_from_dict(output)
  352. obs._cause = action.id # type: ignore[attr-defined]
  353. return obs
  354. else:
  355. error_message = response.text
  356. logger.error(f'Error from server: {error_message}')
  357. obs = ErrorObservation(f'Action execution failed: {error_message}')
  358. except Timeout:
  359. logger.error('No response received within the timeout period.')
  360. obs = ErrorObservation('Action execution timed out')
  361. except Exception as e:
  362. logger.error(f'Error during action execution: {e}')
  363. obs = ErrorObservation(f'Action execution failed: {str(e)}')
  364. return obs
  365. def run(self, action: CmdRunAction) -> Observation:
  366. return self.run_action(action)
  367. def run_ipython(self, action: IPythonRunCellAction) -> Observation:
  368. return self.run_action(action)
  369. def read(self, action: FileReadAction) -> Observation:
  370. return self.run_action(action)
  371. def write(self, action: FileWriteAction) -> Observation:
  372. return self.run_action(action)
  373. def browse(self, action: BrowseURLAction) -> Observation:
  374. return self.run_action(action)
  375. def browse_interactive(self, action: BrowseInteractiveAction) -> Observation:
  376. return self.run_action(action)
  377. def copy_to(
  378. self, host_src: str, sandbox_dest: str, recursive: bool = False
  379. ) -> None:
  380. if not os.path.exists(host_src):
  381. raise FileNotFoundError(f'Source file {host_src} does not exist')
  382. try:
  383. if recursive:
  384. with tempfile.NamedTemporaryFile(
  385. suffix='.zip', delete=False
  386. ) as temp_zip:
  387. temp_zip_path = temp_zip.name
  388. with ZipFile(temp_zip_path, 'w') as zipf:
  389. for root, _, files in os.walk(host_src):
  390. for file in files:
  391. file_path = os.path.join(root, file)
  392. arcname = os.path.relpath(
  393. file_path, os.path.dirname(host_src)
  394. )
  395. zipf.write(file_path, arcname)
  396. upload_data = {'file': open(temp_zip_path, 'rb')}
  397. else:
  398. upload_data = {'file': open(host_src, 'rb')}
  399. params = {'destination': sandbox_dest, 'recursive': str(recursive).lower()}
  400. response = send_request_with_retry(
  401. self.session,
  402. 'POST',
  403. f'{self.runtime_url}/upload_file',
  404. files=upload_data,
  405. params=params,
  406. retry_exceptions=list(
  407. filter(lambda e: e != TimeoutError, DEFAULT_RETRY_EXCEPTIONS)
  408. ),
  409. timeout=300,
  410. )
  411. if response.status_code == 200:
  412. logger.info(
  413. f'Copy completed: host:{host_src} -> runtime:{sandbox_dest}. Response: {response.text}'
  414. )
  415. return
  416. else:
  417. error_message = response.text
  418. raise Exception(f'Copy operation failed: {error_message}')
  419. except TimeoutError:
  420. raise TimeoutError('Copy operation timed out')
  421. except Exception as e:
  422. raise RuntimeError(f'Copy operation failed: {str(e)}')
  423. finally:
  424. if recursive:
  425. os.unlink(temp_zip_path)
  426. logger.info(f'Copy completed: host:{host_src} -> runtime:{sandbox_dest}')
  427. def list_files(self, path: str | None = None) -> list[str]:
  428. try:
  429. data = {}
  430. if path is not None:
  431. data['path'] = path
  432. response = send_request_with_retry(
  433. self.session,
  434. 'POST',
  435. f'{self.runtime_url}/list_files',
  436. json=data,
  437. retry_exceptions=list(
  438. filter(lambda e: e != TimeoutError, DEFAULT_RETRY_EXCEPTIONS)
  439. ),
  440. timeout=30,
  441. )
  442. if response.status_code == 200:
  443. response_json = response.json()
  444. assert isinstance(response_json, list)
  445. return response_json
  446. else:
  447. error_message = response.text
  448. raise Exception(f'List files operation failed: {error_message}')
  449. except TimeoutError:
  450. raise TimeoutError('List files operation timed out')
  451. except Exception as e:
  452. raise RuntimeError(f'List files operation failed: {str(e)}')
  453. def copy_from(self, path: str) -> bytes:
  454. """Zip all files in the sandbox and return as a stream of bytes."""
  455. self._wait_until_alive()
  456. try:
  457. params = {'path': path}
  458. response = send_request_with_retry(
  459. self.session,
  460. 'GET',
  461. f'{self.runtime_url}/download_files',
  462. params=params,
  463. timeout=30,
  464. retry_exceptions=list(
  465. filter(lambda e: e != TimeoutError, DEFAULT_RETRY_EXCEPTIONS)
  466. ),
  467. )
  468. if response.status_code == 200:
  469. return response.content
  470. else:
  471. error_message = response.text
  472. raise Exception(f'Copy operation failed: {error_message}')
  473. except requests.Timeout:
  474. raise TimeoutError('Copy operation timed out')
  475. except Exception as e:
  476. raise RuntimeError(f'Copy operation failed: {str(e)}')
  477. def send_status_message(self, message: str):
  478. """Sends a status message if the callback function was provided."""
  479. if self.status_message_callback:
  480. self.status_message_callback(message)