runloop_runtime.py 9.5 KB

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