runtime_build.py 16 KB

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