runtime_build.py 16 KB

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