runtime_build.py 17 KB

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