runloop_runtime.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. import logging
  2. import threading
  3. import time
  4. from typing import Callable
  5. import requests
  6. import tenacity
  7. from runloop_api_client import Runloop
  8. from runloop_api_client.types import DevboxView
  9. from runloop_api_client.types.shared_params import LaunchParameters
  10. from openhands.core.config import AppConfig
  11. from openhands.core.logger import openhands_logger as logger
  12. from openhands.events import EventStream
  13. from openhands.runtime.impl.eventstream.eventstream_runtime import (
  14. EventStreamRuntime,
  15. LogBuffer,
  16. )
  17. from openhands.runtime.plugins import PluginRequirement
  18. from openhands.runtime.utils.command import get_remote_startup_command
  19. from openhands.runtime.utils.request import send_request
  20. from openhands.utils.tenacity_stop import stop_if_should_exit
  21. CONTAINER_NAME_PREFIX = 'openhands-runtime-'
  22. class RunloopLogBuffer(LogBuffer):
  23. """Synchronous buffer for Runloop devbox logs.
  24. This class provides a thread-safe way to collect, store, and retrieve logs
  25. from a Docker container. It uses a list to store log lines and provides methods
  26. for appending, retrieving, and clearing logs.
  27. """
  28. def __init__(self, runloop_api_client: Runloop, devbox_id: str):
  29. self.client_ready = False
  30. self.init_msg = 'Runtime client initialized.'
  31. self.buffer: list[str] = []
  32. self.lock = threading.Lock()
  33. self._stop_event = threading.Event()
  34. self.runloop_api_client = runloop_api_client
  35. self.devbox_id = devbox_id
  36. self.log_index = 0
  37. self.log_stream_thread = threading.Thread(target=self.stream_logs)
  38. self.log_stream_thread.daemon = True
  39. self.log_stream_thread.start()
  40. def stream_logs(self):
  41. """Stream logs from the Docker container in a separate thread.
  42. This method runs in its own thread to handle the blocking
  43. operation of reading log lines from the Docker SDK's synchronous generator.
  44. """
  45. try:
  46. # TODO(Runloop) Replace with stream
  47. while True:
  48. raw_logs = self.runloop_api_client.devboxes.logs.list(
  49. self.devbox_id
  50. ).logs[self.log_index :]
  51. logs = [
  52. log.message
  53. for log in raw_logs
  54. if log.message and log.cmd_id is None
  55. ]
  56. self.log_index += len(raw_logs)
  57. if self._stop_event.is_set():
  58. break
  59. if logs:
  60. for log_line in logs:
  61. self.append(log_line)
  62. if self.init_msg in log_line:
  63. self.client_ready = True
  64. time.sleep(1)
  65. except Exception as e:
  66. logger.error(f'Error streaming runloop logs: {e}')
  67. # NB: Match LogBuffer behavior on below methods
  68. def get_and_clear(self) -> list[str]:
  69. with self.lock:
  70. logs = list(self.buffer)
  71. self.buffer.clear()
  72. return logs
  73. def append(self, log_line: str):
  74. with self.lock:
  75. self.buffer.append(log_line)
  76. def close(self, timeout: float = 5.0):
  77. self._stop_event.set()
  78. self.log_stream_thread.join(timeout)
  79. class RunloopRuntime(EventStreamRuntime):
  80. """The RunloopRuntime class is an EventStreamRuntime that utilizes Runloop Devbox as a runtime environment."""
  81. _sandbox_port: int = 4444
  82. def __init__(
  83. self,
  84. config: AppConfig,
  85. event_stream: EventStream,
  86. sid: str = 'default',
  87. plugins: list[PluginRequirement] | None = None,
  88. env_vars: dict[str, str] | None = None,
  89. status_callback: Callable | None = None,
  90. attach_to_existing: bool = False,
  91. ):
  92. assert config.runloop_api_key is not None, 'Runloop API key is required'
  93. self.devbox: DevboxView | None = None
  94. self.config = config
  95. self.runloop_api_client = Runloop(
  96. bearer_token=config.runloop_api_key,
  97. )
  98. self.session = requests.Session()
  99. self.container_name = CONTAINER_NAME_PREFIX + sid
  100. self.action_semaphore = threading.Semaphore(1) # Ensure one action at a time
  101. self.init_base_runtime(
  102. config,
  103. event_stream,
  104. sid,
  105. plugins,
  106. env_vars,
  107. status_callback,
  108. attach_to_existing,
  109. )
  110. # Buffer for container logs
  111. self.log_buffer: LogBuffer | None = None
  112. @tenacity.retry(
  113. stop=tenacity.stop_after_attempt(120),
  114. wait=tenacity.wait_fixed(1),
  115. )
  116. def _wait_for_devbox(self, devbox: DevboxView) -> DevboxView:
  117. """Pull devbox status until it is running"""
  118. if devbox == 'running':
  119. return devbox
  120. devbox = self.runloop_api_client.devboxes.retrieve(id=devbox.id)
  121. if devbox.status != 'running':
  122. raise ConnectionRefusedError('Devbox is not running')
  123. # Devbox is connected and running
  124. logging.debug(f'devbox.id={devbox.id} is running')
  125. return devbox
  126. def _create_new_devbox(self) -> DevboxView:
  127. # Note: Runloop connect
  128. sandbox_workspace_dir = self.config.workspace_mount_path_in_sandbox
  129. plugin_args = []
  130. if self.plugins is not None and len(self.plugins) > 0:
  131. plugin_args.append('--plugins')
  132. plugin_args.extend([plugin.name for plugin in self.plugins])
  133. browsergym_args = []
  134. if self.config.sandbox.browsergym_eval_env is not None:
  135. browsergym_args = [
  136. '-browsergym-eval-env',
  137. self.config.sandbox.browsergym_eval_env,
  138. ]
  139. # Copied from EventstreamRuntime
  140. start_command = get_remote_startup_command(
  141. self._sandbox_port,
  142. sandbox_workspace_dir,
  143. 'openhands' if self.config.run_as_openhands else 'root',
  144. self.config.sandbox.user_id,
  145. plugin_args,
  146. browsergym_args,
  147. is_root=not self.config.run_as_openhands, # is_root=True when running as root
  148. )
  149. # Add some additional commands based on our image
  150. # NB: start off as root, action_execution_server will ultimately choose user but expects all context
  151. # (ie browser) to be installed as root
  152. start_command = (
  153. 'export MAMBA_ROOT_PREFIX=/openhands/micromamba && '
  154. 'cd /openhands/code && '
  155. + '/openhands/micromamba/bin/micromamba run -n openhands poetry config virtualenvs.path /openhands/poetry && '
  156. + ' '.join(start_command)
  157. )
  158. entrypoint = f"sudo bash -c '{start_command}'"
  159. devbox = self.runloop_api_client.devboxes.create(
  160. entrypoint=entrypoint,
  161. setup_commands=[f'mkdir -p {self.config.workspace_mount_path_in_sandbox}'],
  162. name=self.sid,
  163. environment_variables={'DEBUG': 'true'} if self.config.debug else {},
  164. prebuilt='openhands',
  165. launch_parameters=LaunchParameters(
  166. available_ports=[self._sandbox_port],
  167. resource_size_request='LARGE',
  168. ),
  169. metadata={'container-name': self.container_name},
  170. )
  171. return self._wait_for_devbox(devbox)
  172. async def connect(self):
  173. self.send_status_message('STATUS$STARTING_RUNTIME')
  174. if self.attach_to_existing:
  175. active_devboxes = self.runloop_api_client.devboxes.list(
  176. status='running'
  177. ).devboxes
  178. self.devbox = next(
  179. (devbox for devbox in active_devboxes if devbox.name == self.sid), None
  180. )
  181. if self.devbox is None:
  182. self.devbox = self._create_new_devbox()
  183. # Create tunnel - this will return a stable url, so is safe to call if we are attaching to existing
  184. tunnel = self.runloop_api_client.devboxes.create_tunnel(
  185. id=self.devbox.id,
  186. port=self._sandbox_port,
  187. )
  188. # Hook up logs
  189. self.log_buffer = RunloopLogBuffer(self.runloop_api_client, self.devbox.id)
  190. self.api_url = f'https://{tunnel.url}'
  191. logger.info(f'Container started. Server url: {self.api_url}')
  192. # End Runloop connect
  193. # NOTE: Copied from EventStreamRuntime
  194. logger.info('Waiting for client to become ready...')
  195. self.send_status_message('STATUS$WAITING_FOR_CLIENT')
  196. self._wait_until_alive()
  197. if not self.attach_to_existing:
  198. self.setup_initial_env()
  199. logger.info(
  200. f'Container initialized with plugins: {[plugin.name for plugin in self.plugins]}'
  201. )
  202. self.send_status_message(' ')
  203. @tenacity.retry(
  204. stop=tenacity.stop_after_delay(120) | stop_if_should_exit(),
  205. wait=tenacity.wait_fixed(1),
  206. reraise=(ConnectionRefusedError,),
  207. )
  208. def _wait_until_alive(self):
  209. # NB(Runloop): Remote logs are not guaranteed realtime, removing client_ready check from logs
  210. self._refresh_logs()
  211. if not self.log_buffer:
  212. raise RuntimeError('Runtime client is not ready.')
  213. response = send_request(
  214. self.session,
  215. 'GET',
  216. f'{self.api_url}/alive',
  217. timeout=5,
  218. )
  219. if response.status_code == 200:
  220. return
  221. else:
  222. msg = f'Action execution API is not alive. Response: {response}'
  223. logger.error(msg)
  224. raise RuntimeError(msg)
  225. def close(self, rm_all_containers: bool = True):
  226. if self.log_buffer:
  227. self.log_buffer.close()
  228. if self.session:
  229. self.session.close()
  230. if self.attach_to_existing:
  231. return
  232. if self.devbox:
  233. self.runloop_api_client.devboxes.shutdown(self.devbox.id)