runtime_build.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. import argparse
  2. import hashlib
  3. import os
  4. import shutil
  5. import subprocess
  6. import tempfile
  7. import docker
  8. from dirhash import dirhash
  9. from jinja2 import Environment, FileSystemLoader
  10. import openhands
  11. from openhands import __version__ as oh_version
  12. from openhands.core.logger import openhands_logger as logger
  13. from openhands.runtime.builder import DockerRuntimeBuilder, RuntimeBuilder
  14. def get_runtime_image_repo():
  15. return os.getenv('OH_RUNTIME_RUNTIME_IMAGE_REPO', 'ghcr.io/all-hands-ai/runtime')
  16. def _put_source_code_to_dir(temp_dir: str):
  17. """Builds the project source tarball directly in temp_dir and unpacks it.
  18. The OpenHands source code ends up in the temp_dir/code directory.
  19. Parameters:
  20. - temp_dir (str): The directory to put the source code in
  21. """
  22. if not os.path.isdir(temp_dir):
  23. raise RuntimeError(f'Temp directory {temp_dir} does not exist')
  24. project_root = os.path.dirname(os.path.dirname(os.path.abspath(openhands.__file__)))
  25. logger.info(f'Building source distribution using project root: {project_root}')
  26. # Fetch the correct version from pyproject.toml
  27. package_version = oh_version
  28. tarball_filename = f'openhands_ai-{package_version}.tar.gz'
  29. tarball_path = os.path.join(temp_dir, tarball_filename)
  30. # Run "python -m build -s" on project_root to create project tarball directly in temp_dir
  31. _cleaned_project_root = project_root.replace(
  32. ' ', r'\ '
  33. ) # escape spaces in the project root
  34. result = subprocess.run(
  35. f'python -m build -s -o "{temp_dir}" {_cleaned_project_root}',
  36. shell=True,
  37. stdout=subprocess.PIPE,
  38. stderr=subprocess.PIPE,
  39. )
  40. logger.info(result.stdout.decode())
  41. err_logs = result.stderr.decode()
  42. if err_logs:
  43. logger.error(err_logs)
  44. if result.returncode != 0:
  45. logger.error(f'Image build failed:\n{result}')
  46. raise RuntimeError(f'Image build failed:\n{result}')
  47. if not os.path.exists(tarball_path):
  48. logger.error(f'Source distribution not found at {tarball_path}. (Do you need to run `make build`?)')
  49. raise RuntimeError(f'Source distribution not found at {tarball_path}')
  50. logger.info(f'Source distribution created at {tarball_path}')
  51. # Unzip the tarball
  52. shutil.unpack_archive(tarball_path, temp_dir)
  53. # Remove the tarball
  54. os.remove(tarball_path)
  55. # Rename the directory containing the code to 'code'
  56. os.rename(
  57. os.path.join(temp_dir, f'openhands_ai-{package_version}'),
  58. os.path.join(temp_dir, 'code'),
  59. )
  60. logger.info(f'Unpacked source code directory: {os.path.join(temp_dir, "code")}')
  61. def _generate_dockerfile(
  62. base_image: str,
  63. skip_init: bool = False,
  64. extra_deps: str | None = None,
  65. ) -> str:
  66. """Generate the Dockerfile content for the runtime image based on the base image.
  67. Parameters:
  68. - base_image (str): The base image provided for the runtime image
  69. - skip_init (boolean):
  70. - extra_deps (str):
  71. Returns:
  72. - str: The resulting Dockerfile content
  73. """
  74. env = Environment(
  75. loader=FileSystemLoader(
  76. searchpath=os.path.join(os.path.dirname(__file__), 'runtime_templates')
  77. )
  78. )
  79. template = env.get_template('Dockerfile.j2')
  80. dockerfile_content = template.render(
  81. base_image=base_image,
  82. skip_init=skip_init,
  83. extra_deps=extra_deps if extra_deps is not None else '',
  84. )
  85. return dockerfile_content
  86. def prep_docker_build_folder(
  87. dir_path: str,
  88. base_image: str,
  89. skip_init: bool = False,
  90. extra_deps: str | None = None,
  91. ) -> str:
  92. """Prepares a docker build folder by copying the source code and generating the Dockerfile
  93. Parameters:
  94. - dir_path (str): The build folder to place the source code and Dockerfile
  95. - base_image (str): The base Docker image to use for the Dockerfile
  96. - skip_init (str):
  97. - extra_deps (str):
  98. Returns:
  99. - str: The MD5 hash of the build folder directory (dir_path)
  100. """
  101. # Copy the source code to directory. It will end up in dir_path/code
  102. _put_source_code_to_dir(dir_path)
  103. # Create a Dockerfile and write it to dir_path
  104. dockerfile_content = _generate_dockerfile(
  105. base_image,
  106. skip_init=skip_init,
  107. extra_deps=extra_deps,
  108. )
  109. if os.getenv('SKIP_CONTAINER_LOGS', 'false') != 'true':
  110. logger.debug(
  111. (
  112. f'===== Dockerfile content start =====\n'
  113. f'{dockerfile_content}\n'
  114. f'===== Dockerfile content end ====='
  115. )
  116. )
  117. with open(os.path.join(dir_path, 'Dockerfile'), 'w') as file:
  118. file.write(dockerfile_content)
  119. # Get the MD5 hash of the dir_path directory
  120. dir_hash = dirhash(
  121. dir_path,
  122. 'md5',
  123. ignore=[
  124. '.*/', # hidden directories
  125. '__pycache__/',
  126. '*.pyc',
  127. ],
  128. )
  129. hash = f'v{oh_version}_{dir_hash}'
  130. logger.info(
  131. f'Input base image: {base_image}\n'
  132. f'Skip init: {skip_init}\n'
  133. f'Extra deps: {extra_deps}\n'
  134. f'Hash for docker build directory [{dir_path}] (contents: {os.listdir(dir_path)}): {hash}\n'
  135. )
  136. return hash
  137. def get_runtime_image_repo_and_tag(base_image: str) -> tuple[str, str]:
  138. """Retrieves the Docker repo and tag associated with the Docker image.
  139. Parameters:
  140. - base_image (str): The name of the base Docker image
  141. Returns:
  142. - tuple[str, str]: The Docker repo and tag of the Docker image
  143. """
  144. if get_runtime_image_repo() in base_image:
  145. logger.info(
  146. f'The provided image [{base_image}] is already a valid runtime image.\n'
  147. f'Will try to reuse it as is.'
  148. )
  149. if ':' not in base_image:
  150. base_image = base_image + ':latest'
  151. repo, tag = base_image.split(':')
  152. return repo, tag
  153. else:
  154. if ':' not in base_image:
  155. base_image = base_image + ':latest'
  156. [repo, tag] = base_image.split(':')
  157. # Hash the repo if it's too long
  158. if len(repo) > 32:
  159. repo_hash = hashlib.md5(repo[:-24].encode()).hexdigest()[:8]
  160. repo = f'{repo_hash}_{repo[-24:]}' # Use 8 char hash + last 24 chars
  161. else:
  162. repo = repo.replace('/', '_s_')
  163. new_tag = f'oh_v{oh_version}_image_{repo}_tag_{tag}'
  164. # if it's still too long, hash the entire image name
  165. if len(new_tag) > 128:
  166. new_tag = f'oh_v{oh_version}_image_{hashlib.md5(new_tag.encode()).hexdigest()[:64]}'
  167. logger.warning(
  168. f'The new tag [{new_tag}] is still too long, so we use an hash of the entire image name: {new_tag}'
  169. )
  170. return get_runtime_image_repo(), new_tag
  171. def build_runtime_image(
  172. base_image: str,
  173. runtime_builder: RuntimeBuilder,
  174. extra_deps: str | None = None,
  175. docker_build_folder: str | None = None,
  176. dry_run: bool = False,
  177. force_rebuild: bool = False,
  178. ) -> str:
  179. """Prepares the final docker build folder.
  180. If dry_run is False, it will also build the OpenHands runtime Docker image using the docker build folder.
  181. Parameters:
  182. - base_image (str): The name of the base Docker image to use
  183. - runtime_builder (RuntimeBuilder): The runtime builder to use
  184. - extra_deps (str):
  185. - docker_build_folder (str): The directory to use for the build. If not provided a temporary directory will be used
  186. - dry_run (bool): if True, it will only ready the build folder. It will not actually build the Docker image
  187. - force_rebuild (bool): if True, it will create the Dockerfile which uses the base_image
  188. Returns:
  189. - str: <image_repo>:<MD5 hash>. Where MD5 hash is the hash of the docker build folder
  190. See https://docs.all-hands.dev/modules/usage/architecture/runtime for more details.
  191. """
  192. # Calculate the hash for the docker build folder (source code and Dockerfile)
  193. with tempfile.TemporaryDirectory() as temp_dir:
  194. from_scratch_hash = prep_docker_build_folder(
  195. temp_dir,
  196. base_image=base_image,
  197. skip_init=False,
  198. extra_deps=extra_deps,
  199. )
  200. runtime_image_repo, runtime_image_tag = get_runtime_image_repo_and_tag(base_image)
  201. # The image name in the format <image repo>:<hash>
  202. hash_runtime_image_name = f'{runtime_image_repo}:{from_scratch_hash}'
  203. # non-hash generic image name, it could contain *similar* dependencies
  204. # but *might* not exactly match the state of the source code.
  205. # It resembles the "latest" tag in the docker image naming convention for
  206. # a particular {repo}:{tag} pair (e.g., ubuntu:latest -> runtime:ubuntu_tag_latest)
  207. # we will build from IT to save time if the `from_scratch_hash` is not found
  208. generic_runtime_image_name = f'{runtime_image_repo}:{runtime_image_tag}'
  209. # Scenario 1: If we already have an image with the exact same hash, then it means the image is already built
  210. # with the exact same source code and Dockerfile, so we will reuse it. Building it is not required.
  211. if not force_rebuild and runtime_builder.image_exists(
  212. hash_runtime_image_name, False
  213. ):
  214. logger.info(
  215. f'Image [{hash_runtime_image_name}] already exists so we will reuse it.'
  216. )
  217. return hash_runtime_image_name
  218. # Scenario 2: If a Docker image with the exact hash is not found, we will FIRST try to re-build it
  219. # by leveraging the `generic_runtime_image_name` to save some time
  220. # from re-building the dependencies (e.g., poetry install, apt install)
  221. if not force_rebuild and runtime_builder.image_exists(generic_runtime_image_name):
  222. logger.info(
  223. f'Could not find docker image [{hash_runtime_image_name}]\n'
  224. f'Will try to re-build it from latest [{generic_runtime_image_name}] image to potentially save '
  225. f'time for dependencies installation.\n'
  226. )
  227. cur_docker_build_folder = docker_build_folder or tempfile.mkdtemp()
  228. _skip_init_hash = prep_docker_build_folder(
  229. cur_docker_build_folder,
  230. # we want to use the existing generic image as base
  231. # so that we can leverage existing dependencies already installed in the image
  232. base_image=generic_runtime_image_name,
  233. skip_init=True, # skip init since we are re-using the existing image
  234. extra_deps=extra_deps,
  235. )
  236. assert (
  237. _skip_init_hash != from_scratch_hash
  238. ), f'The skip_init hash [{_skip_init_hash}] should not match the existing hash [{from_scratch_hash}]'
  239. if not dry_run:
  240. _build_sandbox_image(
  241. docker_folder=cur_docker_build_folder,
  242. runtime_builder=runtime_builder,
  243. target_image_repo=runtime_image_repo,
  244. # NOTE: WE ALWAYS use the "from_scratch_hash" tag for the target image
  245. # otherwise, even if the source code is exactly the same, the image *might* be re-built
  246. # because the same source code will generate different hash when skip_init=True/False
  247. # since the Dockerfile is slightly different
  248. target_image_hash_tag=from_scratch_hash,
  249. target_image_tag=runtime_image_tag,
  250. )
  251. else:
  252. logger.info(
  253. f'Dry run: Skipping image build for [{generic_runtime_image_name}]'
  254. )
  255. if docker_build_folder is None:
  256. shutil.rmtree(cur_docker_build_folder)
  257. # Scenario 3: If the Docker image with the required hash is not found AND we cannot re-use the latest
  258. # relevant image, we will build it completely from scratch
  259. else:
  260. if force_rebuild:
  261. logger.info(
  262. f'Force re-build: Will try to re-build image [{generic_runtime_image_name}] from scratch.\n'
  263. )
  264. cur_docker_build_folder = docker_build_folder or tempfile.mkdtemp()
  265. _new_from_scratch_hash = prep_docker_build_folder(
  266. cur_docker_build_folder,
  267. base_image,
  268. skip_init=False,
  269. extra_deps=extra_deps,
  270. )
  271. assert (
  272. _new_from_scratch_hash == from_scratch_hash
  273. ), f'The new from scratch hash [{_new_from_scratch_hash}] does not match the existing hash [{from_scratch_hash}]'
  274. if not dry_run:
  275. _build_sandbox_image(
  276. docker_folder=cur_docker_build_folder,
  277. runtime_builder=runtime_builder,
  278. target_image_repo=runtime_image_repo,
  279. # NOTE: WE ALWAYS use the "from_scratch_hash" tag for the target image
  280. target_image_hash_tag=from_scratch_hash,
  281. target_image_tag=runtime_image_tag,
  282. )
  283. else:
  284. logger.info(
  285. f'Dry run: Skipping image build for [{generic_runtime_image_name}]'
  286. )
  287. if docker_build_folder is None:
  288. shutil.rmtree(cur_docker_build_folder)
  289. return f'{runtime_image_repo}:{from_scratch_hash}'
  290. def _build_sandbox_image(
  291. docker_folder: str,
  292. runtime_builder: RuntimeBuilder,
  293. target_image_repo: str,
  294. target_image_hash_tag: str,
  295. target_image_tag: str,
  296. ) -> str:
  297. """Build and tag the sandbox image.
  298. The image will be tagged as both:
  299. - target_image_hash_tag
  300. - target_image_tag
  301. Parameters:
  302. - docker_folder (str): the path to the docker build folder
  303. - runtime_builder (RuntimeBuilder): the runtime builder instance
  304. - target_image_repo (str): the repository name for the target image
  305. - target_image_hash_tag (str): the *hash* tag for the target image that is calculated based
  306. on the contents of the docker build folder (source code and Dockerfile)
  307. e.g. 1234567890abcdef
  308. -target_image_tag (str): the tag for the target image that's generic and based on the base image name
  309. e.g. oh_v0.9.3_image_ubuntu_tag_22.04
  310. """
  311. target_image_hash_name = f'{target_image_repo}:{target_image_hash_tag}'
  312. target_image_generic_name = f'{target_image_repo}:{target_image_tag}'
  313. tags_to_add = [target_image_hash_name]
  314. # Only add the generic tag if the image does not exist
  315. # so it does not get overwritten & only points to the earliest version
  316. # to avoid "too many layers" after many re-builds
  317. if not runtime_builder.image_exists(target_image_generic_name):
  318. tags_to_add.append(target_image_generic_name)
  319. try:
  320. image_name = runtime_builder.build(path=docker_folder, tags=tags_to_add)
  321. if not image_name:
  322. raise RuntimeError(f'Build failed for image {target_image_hash_name}')
  323. except Exception as e:
  324. logger.error(f'Sandbox image build failed: {str(e)}')
  325. raise
  326. return image_name
  327. if __name__ == '__main__':
  328. parser = argparse.ArgumentParser()
  329. parser.add_argument(
  330. '--base_image', type=str, default='nikolaik/python-nodejs:python3.12-nodejs22'
  331. )
  332. parser.add_argument('--build_folder', type=str, default=None)
  333. parser.add_argument('--force_rebuild', action='store_true', default=False)
  334. args = parser.parse_args()
  335. if args.build_folder is not None:
  336. # If a build_folder is provided, we do not actually build the Docker image. We copy the necessary source code
  337. # and create a Dockerfile dynamically and place it in the build_folder only. This allows the Docker image to
  338. # then be created using the Dockerfile (most likely using the containers/build.sh script)
  339. build_folder = args.build_folder
  340. assert os.path.exists(
  341. build_folder
  342. ), f'Build folder {build_folder} does not exist'
  343. logger.info(
  344. f'Copying the source code and generating the Dockerfile in the build folder: {build_folder}'
  345. )
  346. runtime_image_repo, runtime_image_tag = get_runtime_image_repo_and_tag(
  347. args.base_image
  348. )
  349. logger.info(
  350. f'Runtime image repo: {runtime_image_repo} and runtime image tag: {runtime_image_tag}'
  351. )
  352. with tempfile.TemporaryDirectory() as temp_dir:
  353. # dry_run is true so we only prepare a temp_dir containing the required source code and the Dockerfile. We
  354. # then obtain the MD5 hash of the folder and return <image_repo>:<temp_dir_md5_hash>
  355. runtime_image_hash_name = build_runtime_image(
  356. args.base_image,
  357. runtime_builder=DockerRuntimeBuilder(docker.from_env()),
  358. docker_build_folder=temp_dir,
  359. dry_run=True,
  360. force_rebuild=args.force_rebuild,
  361. )
  362. _runtime_image_repo, runtime_image_hash_tag = runtime_image_hash_name.split(
  363. ':'
  364. )
  365. # Move contents of temp_dir to build_folder
  366. shutil.copytree(temp_dir, build_folder, dirs_exist_ok=True)
  367. logger.info(
  368. f'Build folder [{build_folder}] is ready: {os.listdir(build_folder)}'
  369. )
  370. # We now update the config.sh in the build_folder to contain the required values. This is used in the
  371. # containers/build.sh script which is called to actually build the Docker image
  372. with open(os.path.join(build_folder, 'config.sh'), 'a') as file:
  373. file.write(
  374. (
  375. f'\n'
  376. f'DOCKER_IMAGE_TAG={runtime_image_tag}\n'
  377. f'DOCKER_IMAGE_HASH_TAG={runtime_image_hash_tag}\n'
  378. )
  379. )
  380. logger.info(
  381. f'`config.sh` is updated with the image repo[{runtime_image_repo}] and tags [{runtime_image_tag}, {runtime_image_hash_tag}]'
  382. )
  383. logger.info(
  384. f'Dockerfile, source code and config.sh are ready in {build_folder}'
  385. )
  386. else:
  387. # If a build_folder is not provided, after copying the required source code and dynamically creating the
  388. # Dockerfile, we actually build the Docker image
  389. logger.info('Building image in a temporary folder')
  390. docker_builder = DockerRuntimeBuilder(docker.from_env())
  391. image_name = build_runtime_image(args.base_image, docker_builder)
  392. print(f'\nBUILT Image: {image_name}\n')