runtime_build.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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(
  149. f'Force rebuild: [{runtime_image_repo}:{source_tag}] from scratch.'
  150. )
  151. prep_build_folder(
  152. build_folder,
  153. base_image,
  154. build_from=BuildFromImageType.SCRATCH,
  155. extra_deps=extra_deps,
  156. )
  157. if not dry_run:
  158. _build_sandbox_image(
  159. build_folder,
  160. runtime_builder,
  161. runtime_image_repo,
  162. source_tag,
  163. lock_tag,
  164. versioned_tag,
  165. platform,
  166. )
  167. return hash_image_name
  168. lock_image_name = f'{runtime_image_repo}:{lock_tag}'
  169. build_from = BuildFromImageType.SCRATCH
  170. # If the exact image already exists, we do not need to build it
  171. if runtime_builder.image_exists(hash_image_name, False):
  172. logger.debug(f'Reusing Image [{hash_image_name}]')
  173. return hash_image_name
  174. # We look for an existing image that shares the same lock_tag. If such an image exists, we
  175. # can use it as the base image for the build and just copy source files. This makes the build
  176. # much faster.
  177. if runtime_builder.image_exists(lock_image_name):
  178. logger.debug(f'Build [{hash_image_name}] from lock image [{lock_image_name}]')
  179. build_from = BuildFromImageType.LOCK
  180. base_image = lock_image_name
  181. elif runtime_builder.image_exists(versioned_image_name):
  182. logger.info(
  183. f'Build [{hash_image_name}] from versioned image [{versioned_image_name}]'
  184. )
  185. build_from = BuildFromImageType.VERSIONED
  186. base_image = versioned_image_name
  187. else:
  188. logger.debug(f'Build [{hash_image_name}] from scratch')
  189. prep_build_folder(build_folder, base_image, build_from, extra_deps)
  190. if not dry_run:
  191. _build_sandbox_image(
  192. build_folder,
  193. runtime_builder,
  194. runtime_image_repo,
  195. source_tag=source_tag,
  196. lock_tag=lock_tag,
  197. # Only tag the versioned image if we are building from scratch.
  198. # This avoids too much layers when you lay one image on top of another multiple times
  199. versioned_tag=versioned_tag
  200. if build_from == BuildFromImageType.SCRATCH
  201. else None,
  202. platform=platform,
  203. )
  204. return hash_image_name
  205. def prep_build_folder(
  206. build_folder: Path,
  207. base_image: str,
  208. build_from: BuildFromImageType,
  209. extra_deps: str | None,
  210. ):
  211. # Copy the source code to directory. It will end up in build_folder/code
  212. # If package is not found, build from source code
  213. openhands_source_dir = Path(openhands.__file__).parent
  214. project_root = openhands_source_dir.parent
  215. logger.debug(f'Building source distribution using project root: {project_root}')
  216. # Copy the 'openhands' directory (Source code)
  217. shutil.copytree(
  218. openhands_source_dir,
  219. Path(build_folder, 'code', 'openhands'),
  220. ignore=shutil.ignore_patterns(
  221. '.*/',
  222. '__pycache__/',
  223. '*.pyc',
  224. '*.md',
  225. ),
  226. )
  227. # Copy pyproject.toml and poetry.lock files
  228. for file in ['pyproject.toml', 'poetry.lock']:
  229. src = Path(openhands_source_dir, file)
  230. if not src.exists():
  231. src = Path(project_root, file)
  232. shutil.copy2(src, Path(build_folder, 'code', file))
  233. # Create a Dockerfile and write it to build_folder
  234. dockerfile_content = _generate_dockerfile(
  235. base_image,
  236. build_from=build_from,
  237. extra_deps=extra_deps,
  238. )
  239. with open(Path(build_folder, 'Dockerfile'), 'w') as file: # type: ignore
  240. file.write(dockerfile_content) # type: ignore
  241. _ALPHABET = string.digits + string.ascii_lowercase
  242. def truncate_hash(hash: str) -> str:
  243. """Convert the base16 hash to base36 and truncate at 16 characters."""
  244. value = int(hash, 16)
  245. result: List[str] = []
  246. while value > 0 and len(result) < 16:
  247. value, remainder = divmod(value, len(_ALPHABET))
  248. result.append(_ALPHABET[remainder])
  249. return ''.join(result)
  250. def get_hash_for_lock_files(base_image: str):
  251. openhands_source_dir = Path(openhands.__file__).parent
  252. md5 = hashlib.md5()
  253. md5.update(base_image.encode())
  254. for file in ['pyproject.toml', 'poetry.lock']:
  255. src = Path(openhands_source_dir, file)
  256. if not src.exists():
  257. src = Path(openhands_source_dir.parent, file)
  258. with open(src, 'rb') as f:
  259. for chunk in iter(lambda: f.read(4096), b''):
  260. md5.update(chunk)
  261. # We get away with truncation because we want something that is unique
  262. # rather than something that is cryptographically secure
  263. result = truncate_hash(md5.hexdigest())
  264. return result
  265. def get_tag_for_versioned_image(base_image: str):
  266. return base_image.replace('/', '_s_').replace(':', '_t_').lower()[-96:]
  267. def get_hash_for_source_files():
  268. openhands_source_dir = Path(openhands.__file__).parent
  269. dir_hash = dirhash(
  270. openhands_source_dir,
  271. 'md5',
  272. ignore=[
  273. '.*/', # hidden directories
  274. '__pycache__/',
  275. '*.pyc',
  276. ],
  277. )
  278. # We get away with truncation because we want something that is unique
  279. # rather than something that is cryptographically secure
  280. result = truncate_hash(dir_hash)
  281. return result
  282. def _build_sandbox_image(
  283. build_folder: Path,
  284. runtime_builder: RuntimeBuilder,
  285. runtime_image_repo: str,
  286. source_tag: str,
  287. lock_tag: str,
  288. versioned_tag: str | None,
  289. platform: str | None = None,
  290. ):
  291. """Build and tag the sandbox image. The image will be tagged with all tags that do not yet exist"""
  292. names = [
  293. f'{runtime_image_repo}:{source_tag}',
  294. f'{runtime_image_repo}:{lock_tag}',
  295. ]
  296. if versioned_tag is not None:
  297. names.append(f'{runtime_image_repo}:{versioned_tag}')
  298. names = [name for name in names if not runtime_builder.image_exists(name, False)]
  299. image_name = runtime_builder.build(
  300. path=str(build_folder), tags=names, platform=platform
  301. )
  302. if not image_name:
  303. raise RuntimeError(f'Build failed for image {names}')
  304. return image_name
  305. if __name__ == '__main__':
  306. parser = argparse.ArgumentParser()
  307. parser.add_argument(
  308. '--base_image', type=str, default='nikolaik/python-nodejs:python3.12-nodejs22'
  309. )
  310. parser.add_argument('--build_folder', type=str, default=None)
  311. parser.add_argument('--force_rebuild', action='store_true', default=False)
  312. parser.add_argument('--platform', type=str, default=None)
  313. args = parser.parse_args()
  314. if args.build_folder is not None:
  315. # If a build_folder is provided, we do not actually build the Docker image. We copy the necessary source code
  316. # and create a Dockerfile dynamically and place it in the build_folder only. This allows the Docker image to
  317. # then be created using the Dockerfile (most likely using the containers/build.sh script)
  318. build_folder = args.build_folder
  319. assert os.path.exists(
  320. build_folder
  321. ), f'Build folder {build_folder} does not exist'
  322. logger.debug(
  323. f'Copying the source code and generating the Dockerfile in the build folder: {build_folder}'
  324. )
  325. runtime_image_repo, runtime_image_tag = get_runtime_image_repo_and_tag(
  326. args.base_image
  327. )
  328. logger.debug(
  329. f'Runtime image repo: {runtime_image_repo} and runtime image tag: {runtime_image_tag}'
  330. )
  331. with tempfile.TemporaryDirectory() as temp_dir:
  332. # dry_run is true so we only prepare a temp_dir containing the required source code and the Dockerfile. We
  333. # then obtain the MD5 hash of the folder and return <image_repo>:<temp_dir_md5_hash>
  334. runtime_image_hash_name = build_runtime_image(
  335. args.base_image,
  336. runtime_builder=DockerRuntimeBuilder(docker.from_env()),
  337. build_folder=temp_dir,
  338. dry_run=True,
  339. force_rebuild=args.force_rebuild,
  340. platform=args.platform,
  341. )
  342. _runtime_image_repo, runtime_image_source_tag = (
  343. runtime_image_hash_name.split(':')
  344. )
  345. # Move contents of temp_dir to build_folder
  346. shutil.copytree(temp_dir, build_folder, dirs_exist_ok=True)
  347. logger.debug(
  348. f'Build folder [{build_folder}] is ready: {os.listdir(build_folder)}'
  349. )
  350. # We now update the config.sh in the build_folder to contain the required values. This is used in the
  351. # containers/build.sh script which is called to actually build the Docker image
  352. with open(os.path.join(build_folder, 'config.sh'), 'a') as file:
  353. file.write(
  354. (
  355. f'\n'
  356. f'DOCKER_IMAGE_TAG={runtime_image_tag}\n'
  357. f'DOCKER_IMAGE_SOURCE_TAG={runtime_image_source_tag}\n'
  358. )
  359. )
  360. logger.debug(
  361. f'`config.sh` is updated with the image repo[{runtime_image_repo}] and tags [{runtime_image_tag}, {runtime_image_source_tag}]'
  362. )
  363. logger.debug(
  364. f'Dockerfile, source code and config.sh are ready in {build_folder}'
  365. )
  366. else:
  367. # If a build_folder is not provided, after copying the required source code and dynamically creating the
  368. # Dockerfile, we actually build the Docker image
  369. logger.debug('Building image in a temporary folder')
  370. docker_builder = DockerRuntimeBuilder(docker.from_env())
  371. image_name = build_runtime_image(
  372. args.base_image, docker_builder, platform=args.platform
  373. )
  374. logger.debug(f'\nBuilt image: {image_name}\n')