runtime.py 21 KB

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