runtime_build.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. import argparse
  2. import hashlib
  3. import os
  4. import shutil
  5. import string
  6. import tempfile
  7. from pathlib import Path
  8. from typing import List
  9. import docker
  10. from dirhash import dirhash
  11. from jinja2 import Environment, FileSystemLoader
  12. import openhands
  13. from openhands import __version__ as oh_version
  14. from openhands.core.logger import openhands_logger as logger
  15. from openhands.runtime.builder import DockerRuntimeBuilder, RuntimeBuilder
  16. def get_runtime_image_repo():
  17. return os.getenv('OH_RUNTIME_RUNTIME_IMAGE_REPO', 'ghcr.io/all-hands-ai/runtime')
  18. def _generate_dockerfile(
  19. base_image: str,
  20. build_from_scratch: bool = True,
  21. extra_deps: str | None = None,
  22. ) -> str:
  23. """Generate the Dockerfile content for the runtime image based on the base image.
  24. Parameters:
  25. - base_image (str): The base image provided for the runtime image
  26. - build_from_scratch (boolean): False implies most steps can be skipped (Base image is another openhands instance)
  27. - extra_deps (str):
  28. Returns:
  29. - str: The resulting Dockerfile content
  30. """
  31. env = Environment(
  32. loader=FileSystemLoader(
  33. searchpath=os.path.join(os.path.dirname(__file__), 'runtime_templates')
  34. )
  35. )
  36. template = env.get_template('Dockerfile.j2')
  37. dockerfile_content = template.render(
  38. base_image=base_image,
  39. build_from_scratch=build_from_scratch,
  40. extra_deps=extra_deps if extra_deps is not None else '',
  41. )
  42. return dockerfile_content
  43. def get_runtime_image_repo_and_tag(base_image: str) -> tuple[str, str]:
  44. """Retrieves the Docker repo and tag associated with the Docker image.
  45. Parameters:
  46. - base_image (str): The name of the base Docker image
  47. Returns:
  48. - tuple[str, str]: The Docker repo and tag of the Docker image
  49. """
  50. if get_runtime_image_repo() in base_image:
  51. logger.info(
  52. f'The provided image [{base_image}] is already a valid runtime image.\n'
  53. f'Will try to reuse it as is.'
  54. )
  55. if ':' not in base_image:
  56. base_image = base_image + ':latest'
  57. repo, tag = base_image.split(':')
  58. return repo, tag
  59. else:
  60. if ':' not in base_image:
  61. base_image = base_image + ':latest'
  62. [repo, tag] = base_image.split(':')
  63. # Hash the repo if it's too long
  64. if len(repo) > 32:
  65. repo_hash = hashlib.md5(repo[:-24].encode()).hexdigest()[:8]
  66. repo = f'{repo_hash}_{repo[-24:]}' # Use 8 char hash + last 24 chars
  67. else:
  68. repo = repo.replace('/', '_s_')
  69. new_tag = f'oh_v{oh_version}_image_{repo}_tag_{tag}'
  70. # if it's still too long, hash the entire image name
  71. if len(new_tag) > 128:
  72. new_tag = f'oh_v{oh_version}_image_{hashlib.md5(new_tag.encode()).hexdigest()[:64]}'
  73. logger.warning(
  74. f'The new tag [{new_tag}] is still too long, so we use an hash of the entire image name: {new_tag}'
  75. )
  76. return get_runtime_image_repo(), new_tag
  77. def build_runtime_image(
  78. base_image: str,
  79. runtime_builder: RuntimeBuilder,
  80. platform: str | None = None,
  81. extra_deps: str | None = None,
  82. build_folder: str | None = None,
  83. dry_run: bool = False,
  84. force_rebuild: bool = False,
  85. ) -> str:
  86. """Prepares the final docker build folder.
  87. If dry_run is False, it will also build the OpenHands runtime Docker image using the docker build folder.
  88. Parameters:
  89. - base_image (str): The name of the base Docker image to use
  90. - runtime_builder (RuntimeBuilder): The runtime builder to use
  91. - platform (str): The target platform for the build (e.g. linux/amd64, linux/arm64)
  92. - extra_deps (str):
  93. - build_folder (str): The directory to use for the build. If not provided a temporary directory will be used
  94. - dry_run (bool): if True, it will only ready the build folder. It will not actually build the Docker image
  95. - force_rebuild (bool): if True, it will create the Dockerfile which uses the base_image
  96. Returns:
  97. - str: <image_repo>:<MD5 hash>. Where MD5 hash is the hash of the docker build folder
  98. See https://docs.all-hands.dev/modules/usage/architecture/runtime for more details.
  99. """
  100. if build_folder is None:
  101. with tempfile.TemporaryDirectory() as temp_dir:
  102. result = build_runtime_image_in_folder(
  103. base_image=base_image,
  104. runtime_builder=runtime_builder,
  105. build_folder=Path(temp_dir),
  106. extra_deps=extra_deps,
  107. dry_run=dry_run,
  108. force_rebuild=force_rebuild,
  109. platform=platform,
  110. )
  111. return result
  112. result = build_runtime_image_in_folder(
  113. base_image=base_image,
  114. runtime_builder=runtime_builder,
  115. build_folder=Path(build_folder),
  116. extra_deps=extra_deps,
  117. dry_run=dry_run,
  118. force_rebuild=force_rebuild,
  119. platform=platform,
  120. )
  121. return result
  122. def build_runtime_image_in_folder(
  123. base_image: str,
  124. runtime_builder: RuntimeBuilder,
  125. build_folder: Path,
  126. extra_deps: str | None,
  127. dry_run: bool,
  128. force_rebuild: bool,
  129. platform: str | None = None,
  130. ) -> str:
  131. runtime_image_repo, _ = get_runtime_image_repo_and_tag(base_image)
  132. lock_tag = f'oh_v{oh_version}_{get_hash_for_lock_files(base_image)}'
  133. hash_tag = f'{lock_tag}_{get_hash_for_source_files()}'
  134. hash_image_name = f'{runtime_image_repo}:{hash_tag}'
  135. if force_rebuild:
  136. logger.info(f'Force rebuild: [{runtime_image_repo}:{hash_tag}] from scratch.')
  137. prep_build_folder(build_folder, base_image, True, extra_deps)
  138. if not dry_run:
  139. _build_sandbox_image(
  140. build_folder,
  141. runtime_builder,
  142. runtime_image_repo,
  143. hash_tag,
  144. lock_tag,
  145. platform,
  146. )
  147. return hash_image_name
  148. lock_image_name = f'{runtime_image_repo}:{lock_tag}'
  149. build_from_scratch = True
  150. # If the exact image already exists, we do not need to build it
  151. if runtime_builder.image_exists(hash_image_name, False):
  152. logger.info(f'Reusing Image [{hash_image_name}]')
  153. return hash_image_name
  154. # We look for an existing image that shares the same lock_tag. If such an image exists, we
  155. # can use it as the base image for the build and just copy source files. This makes the build
  156. # much faster.
  157. if runtime_builder.image_exists(lock_image_name):
  158. logger.info(f'Build [{hash_image_name}] from [{lock_image_name}]')
  159. build_from_scratch = False
  160. base_image = lock_image_name
  161. else:
  162. logger.info(f'Build [{hash_image_name}] from scratch')
  163. prep_build_folder(build_folder, base_image, build_from_scratch, extra_deps)
  164. if not dry_run:
  165. _build_sandbox_image(
  166. build_folder,
  167. runtime_builder,
  168. runtime_image_repo,
  169. hash_tag,
  170. lock_tag,
  171. platform,
  172. )
  173. return hash_image_name
  174. def prep_build_folder(
  175. build_folder: Path,
  176. base_image: str,
  177. build_from_scratch: bool,
  178. extra_deps: str | None,
  179. ):
  180. # Copy the source code to directory. It will end up in build_folder/code
  181. # If package is not found, build from source code
  182. openhands_source_dir = Path(openhands.__file__).parent
  183. project_root = openhands_source_dir.parent
  184. logger.info(f'Building source distribution using project root: {project_root}')
  185. # Copy the 'openhands' directory (Source code)
  186. shutil.copytree(
  187. openhands_source_dir,
  188. Path(build_folder, 'code', 'openhands'),
  189. ignore=shutil.ignore_patterns(
  190. '.*/',
  191. '__pycache__/',
  192. '*.pyc',
  193. '*.md',
  194. ),
  195. )
  196. # Copy pyproject.toml and poetry.lock files
  197. for file in ['pyproject.toml', 'poetry.lock']:
  198. src = Path(openhands_source_dir, file)
  199. if not src.exists():
  200. src = Path(project_root, file)
  201. shutil.copy2(src, Path(build_folder, 'code', file))
  202. # Create a Dockerfile and write it to build_folder
  203. dockerfile_content = _generate_dockerfile(
  204. base_image,
  205. build_from_scratch=build_from_scratch,
  206. extra_deps=extra_deps,
  207. )
  208. with open(Path(build_folder, 'Dockerfile'), 'w') as file: # type: ignore
  209. file.write(dockerfile_content) # type: ignore
  210. _ALPHABET = string.digits + string.ascii_lowercase
  211. def truncate_hash(hash: str) -> str:
  212. """Convert the base16 hash to base36 and truncate at 16 characters."""
  213. value = int(hash, 16)
  214. result: List[str] = []
  215. while value > 0 and len(result) < 16:
  216. value, remainder = divmod(value, len(_ALPHABET))
  217. result.append(_ALPHABET[remainder])
  218. return ''.join(result)
  219. def get_hash_for_lock_files(base_image: str):
  220. openhands_source_dir = Path(openhands.__file__).parent
  221. md5 = hashlib.md5()
  222. md5.update(base_image.encode())
  223. for file in ['pyproject.toml', 'poetry.lock']:
  224. src = Path(openhands_source_dir, file)
  225. if not src.exists():
  226. src = Path(openhands_source_dir.parent, file)
  227. with open(src, 'rb') as f:
  228. for chunk in iter(lambda: f.read(4096), b''):
  229. md5.update(chunk)
  230. # We get away with truncation because we want something that is unique
  231. # rather than something that is cryptographically secure
  232. result = truncate_hash(md5.hexdigest())
  233. return result
  234. def get_hash_for_source_files():
  235. openhands_source_dir = Path(openhands.__file__).parent
  236. dir_hash = dirhash(
  237. openhands_source_dir,
  238. 'md5',
  239. ignore=[
  240. '.*/', # hidden directories
  241. '__pycache__/',
  242. '*.pyc',
  243. ],
  244. )
  245. # We get away with truncation because we want something that is unique
  246. # rather than something that is cryptographically secure
  247. result = truncate_hash(dir_hash)
  248. return result
  249. def _build_sandbox_image(
  250. build_folder: Path,
  251. runtime_builder: RuntimeBuilder,
  252. runtime_image_repo: str,
  253. hash_tag: str,
  254. lock_tag: str,
  255. platform: str | None = None,
  256. ):
  257. """Build and tag the sandbox image. The image will be tagged with all tags that do not yet exist"""
  258. names = [
  259. name
  260. for name in [
  261. f'{runtime_image_repo}:{hash_tag}',
  262. f'{runtime_image_repo}:{lock_tag}',
  263. ]
  264. if not runtime_builder.image_exists(name, False)
  265. ]
  266. image_name = runtime_builder.build(
  267. path=str(build_folder), tags=names, platform=platform
  268. )
  269. if not image_name:
  270. raise RuntimeError(f'Build failed for image {names}')
  271. return image_name
  272. if __name__ == '__main__':
  273. parser = argparse.ArgumentParser()
  274. parser.add_argument(
  275. '--base_image', type=str, default='nikolaik/python-nodejs:python3.12-nodejs22'
  276. )
  277. parser.add_argument('--build_folder', type=str, default=None)
  278. parser.add_argument('--force_rebuild', action='store_true', default=False)
  279. parser.add_argument('--platform', type=str, default=None)
  280. args = parser.parse_args()
  281. if args.build_folder is not None:
  282. # If a build_folder is provided, we do not actually build the Docker image. We copy the necessary source code
  283. # and create a Dockerfile dynamically and place it in the build_folder only. This allows the Docker image to
  284. # then be created using the Dockerfile (most likely using the containers/build.sh script)
  285. build_folder = args.build_folder
  286. assert os.path.exists(
  287. build_folder
  288. ), f'Build folder {build_folder} does not exist'
  289. logger.info(
  290. f'Copying the source code and generating the Dockerfile in the build folder: {build_folder}'
  291. )
  292. runtime_image_repo, runtime_image_tag = get_runtime_image_repo_and_tag(
  293. args.base_image
  294. )
  295. logger.info(
  296. f'Runtime image repo: {runtime_image_repo} and runtime image tag: {runtime_image_tag}'
  297. )
  298. with tempfile.TemporaryDirectory() as temp_dir:
  299. # dry_run is true so we only prepare a temp_dir containing the required source code and the Dockerfile. We
  300. # then obtain the MD5 hash of the folder and return <image_repo>:<temp_dir_md5_hash>
  301. runtime_image_hash_name = build_runtime_image(
  302. args.base_image,
  303. runtime_builder=DockerRuntimeBuilder(docker.from_env()),
  304. build_folder=temp_dir,
  305. dry_run=True,
  306. force_rebuild=args.force_rebuild,
  307. platform=args.platform,
  308. )
  309. _runtime_image_repo, runtime_image_hash_tag = runtime_image_hash_name.split(
  310. ':'
  311. )
  312. # Move contents of temp_dir to build_folder
  313. shutil.copytree(temp_dir, build_folder, dirs_exist_ok=True)
  314. logger.info(
  315. f'Build folder [{build_folder}] is ready: {os.listdir(build_folder)}'
  316. )
  317. # We now update the config.sh in the build_folder to contain the required values. This is used in the
  318. # containers/build.sh script which is called to actually build the Docker image
  319. with open(os.path.join(build_folder, 'config.sh'), 'a') as file:
  320. file.write(
  321. (
  322. f'\n'
  323. f'DOCKER_IMAGE_TAG={runtime_image_tag}\n'
  324. f'DOCKER_IMAGE_HASH_TAG={runtime_image_hash_tag}\n'
  325. )
  326. )
  327. logger.info(
  328. f'`config.sh` is updated with the image repo[{runtime_image_repo}] and tags [{runtime_image_tag}, {runtime_image_hash_tag}]'
  329. )
  330. logger.info(
  331. f'Dockerfile, source code and config.sh are ready in {build_folder}'
  332. )
  333. else:
  334. # If a build_folder is not provided, after copying the required source code and dynamically creating the
  335. # Dockerfile, we actually build the Docker image
  336. logger.info('Building image in a temporary folder')
  337. docker_builder = DockerRuntimeBuilder(docker.from_env())
  338. image_name = build_runtime_image(
  339. args.base_image, docker_builder, platform=args.platform
  340. )
  341. print(f'\nBUILT Image: {image_name}\n')