remote.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. import base64
  2. import io
  3. import tarfile
  4. import time
  5. import requests
  6. from openhands.core.logger import openhands_logger as logger
  7. from openhands.runtime.builder import RuntimeBuilder
  8. from openhands.runtime.utils.request import send_request
  9. from openhands.runtime.utils.shutdown_listener import should_exit, sleep_if_should_continue
  10. class RemoteRuntimeBuilder(RuntimeBuilder):
  11. """This class interacts with the remote Runtime API for building and managing container images."""
  12. def __init__(self, api_url: str, api_key: str):
  13. self.api_url = api_url
  14. self.api_key = api_key
  15. self.session = requests.Session()
  16. self.session.headers.update({'X-API-Key': self.api_key})
  17. def build(self, path: str, tags: list[str]) -> str:
  18. """Builds a Docker image using the Runtime API's /build endpoint."""
  19. # Create a tar archive of the build context
  20. tar_buffer = io.BytesIO()
  21. with tarfile.open(fileobj=tar_buffer, mode='w:gz') as tar:
  22. tar.add(path, arcname='.')
  23. tar_buffer.seek(0)
  24. # Encode the tar file as base64
  25. base64_encoded_tar = base64.b64encode(tar_buffer.getvalue()).decode('utf-8')
  26. # Prepare the multipart form data
  27. files = [
  28. ('context', ('context.tar.gz', base64_encoded_tar)),
  29. ('target_image', (None, tags[0])),
  30. ]
  31. # Add additional tags if present
  32. for tag in tags[1:]:
  33. files.append(('tags', (None, tag)))
  34. # Send the POST request to /build
  35. response = send_request(
  36. self.session, 'POST', f'{self.api_url}/build', files=files
  37. )
  38. if response.status_code != 202:
  39. logger.error(f'Build initiation failed: {response.text}')
  40. raise RuntimeError(f'Build initiation failed: {response.text}')
  41. build_data = response.json()
  42. build_id = build_data['build_id']
  43. logger.info(f'Build initiated with ID: {build_id}')
  44. # Poll /build_status until the build is complete
  45. start_time = time.time()
  46. timeout = 30 * 60 # 20 minutes in seconds
  47. while True:
  48. if should_exit() or time.time() - start_time > timeout:
  49. logger.error('Build timed out after 30 minutes')
  50. raise RuntimeError('Build timed out after 30 minutes')
  51. status_response = send_request(
  52. self.session,
  53. 'GET',
  54. f'{self.api_url}/build_status',
  55. params={'build_id': build_id},
  56. )
  57. if status_response.status_code != 200:
  58. logger.error(f'Failed to get build status: {status_response.text}')
  59. raise RuntimeError(
  60. f'Failed to get build status: {status_response.text}'
  61. )
  62. status_data = status_response.json()
  63. status = status_data['status']
  64. logger.info(f'Build status: {status}')
  65. if status == 'SUCCESS':
  66. logger.info(f"Successfully built {status_data['image']}")
  67. return status_data['image']
  68. elif status in [
  69. 'FAILURE',
  70. 'INTERNAL_ERROR',
  71. 'TIMEOUT',
  72. 'CANCELLED',
  73. 'EXPIRED',
  74. ]:
  75. error_message = status_data.get(
  76. 'error', f'Build failed with status: {status}'
  77. )
  78. logger.error(error_message)
  79. raise RuntimeError(error_message)
  80. # Wait before polling again
  81. sleep_if_should_continue(30)
  82. def image_exists(self, image_name: str, pull_from_repo: bool = True) -> bool:
  83. """Checks if an image exists in the remote registry using the /image_exists endpoint."""
  84. params = {'image': image_name}
  85. response = send_request(
  86. self.session, 'GET', f'{self.api_url}/image_exists', params=params
  87. )
  88. if response.status_code != 200:
  89. logger.error(f'Failed to check image existence: {response.text}')
  90. raise RuntimeError(f'Failed to check image existence: {response.text}')
  91. result = response.json()
  92. if result['exists']:
  93. logger.info(
  94. f"Image {image_name} exists. "
  95. f"Uploaded at: {result['image']['upload_time']}, "
  96. f"Size: {result['image']['image_size_bytes'] / 1024 / 1024:.2f} MB"
  97. )
  98. else:
  99. logger.info(f'Image {image_name} does not exist.')
  100. return result['exists']