runtime_build.py 17 KB

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