runtime_build.py 18 KB

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