runtime_build.py 17 KB

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