runtime_build.py 17 KB

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