remote.py 4.3 KB

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