test_runtime_build.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. import os
  2. import tempfile
  3. import uuid
  4. from importlib.metadata import version
  5. from unittest.mock import ANY, MagicMock, call, patch
  6. import docker
  7. import pytest
  8. import toml
  9. from pytest import TempPathFactory
  10. from openhands import __version__ as oh_version
  11. from openhands.core.logger import openhands_logger as logger
  12. from openhands.runtime.builder.docker import DockerRuntimeBuilder
  13. from openhands.runtime.utils.runtime_build import (
  14. _generate_dockerfile,
  15. _put_source_code_to_dir,
  16. build_runtime_image,
  17. get_runtime_image_repo,
  18. get_runtime_image_repo_and_tag,
  19. prep_docker_build_folder,
  20. )
  21. OH_VERSION = f'oh_v{oh_version}'
  22. DEFAULT_BASE_IMAGE = 'nikolaik/python-nodejs:python3.11-nodejs22'
  23. @pytest.fixture
  24. def temp_dir(tmp_path_factory: TempPathFactory) -> str:
  25. return str(tmp_path_factory.mktemp('test_runtime_build'))
  26. @pytest.fixture
  27. def mock_docker_client():
  28. mock_client = MagicMock(spec=docker.DockerClient)
  29. mock_client.version.return_value = {
  30. 'Version': '19.03'
  31. } # Ensure version is >= 18.09
  32. return mock_client
  33. @pytest.fixture
  34. def docker_runtime_builder():
  35. client = docker.from_env()
  36. return DockerRuntimeBuilder(client)
  37. def _check_source_code_in_dir(temp_dir):
  38. # assert there is a folder called 'code' in the temp_dir
  39. code_dir = os.path.join(temp_dir, 'code')
  40. assert os.path.exists(code_dir)
  41. assert os.path.isdir(code_dir)
  42. # check the source file is the same as the current code base
  43. assert os.path.exists(os.path.join(code_dir, 'pyproject.toml'))
  44. # The source code should only include the `openhands` folder, but not the other folders
  45. assert set(os.listdir(code_dir)) == {
  46. 'agenthub',
  47. 'openhands',
  48. 'pyproject.toml',
  49. 'poetry.lock',
  50. 'LICENSE',
  51. 'README.md',
  52. 'PKG-INFO',
  53. }
  54. assert os.path.exists(os.path.join(code_dir, 'openhands'))
  55. assert os.path.isdir(os.path.join(code_dir, 'openhands'))
  56. # make sure the version from the pyproject.toml is the same as the current version
  57. with open(os.path.join(code_dir, 'pyproject.toml'), 'r') as f:
  58. pyproject = toml.load(f)
  59. _pyproject_version = pyproject['tool']['poetry']['version']
  60. assert _pyproject_version == version('openhands-ai')
  61. def test_put_source_code_to_dir(temp_dir):
  62. _put_source_code_to_dir(temp_dir)
  63. _check_source_code_in_dir(temp_dir)
  64. def test_docker_build_folder(temp_dir):
  65. prep_docker_build_folder(
  66. temp_dir,
  67. base_image=DEFAULT_BASE_IMAGE,
  68. skip_init=False,
  69. )
  70. # check the source code is in the folder
  71. _check_source_code_in_dir(temp_dir)
  72. # Now check dockerfile is in the folder
  73. dockerfile_path = os.path.join(temp_dir, 'Dockerfile')
  74. assert os.path.exists(dockerfile_path)
  75. assert os.path.isfile(dockerfile_path)
  76. # check the folder only contains the source code and the Dockerfile
  77. assert set(os.listdir(temp_dir)) == {'code', 'Dockerfile'}
  78. def test_hash_folder_same(temp_dir):
  79. dir_hash_1 = prep_docker_build_folder(
  80. temp_dir,
  81. base_image=DEFAULT_BASE_IMAGE,
  82. skip_init=False,
  83. )
  84. with tempfile.TemporaryDirectory() as temp_dir_2:
  85. dir_hash_2 = prep_docker_build_folder(
  86. temp_dir_2,
  87. base_image=DEFAULT_BASE_IMAGE,
  88. skip_init=False,
  89. )
  90. assert dir_hash_1 == dir_hash_2
  91. def test_hash_folder_diff_init(temp_dir):
  92. dir_hash_1 = prep_docker_build_folder(
  93. temp_dir,
  94. base_image=DEFAULT_BASE_IMAGE,
  95. skip_init=False,
  96. )
  97. with tempfile.TemporaryDirectory() as temp_dir_2:
  98. dir_hash_2 = prep_docker_build_folder(
  99. temp_dir_2,
  100. base_image=DEFAULT_BASE_IMAGE,
  101. skip_init=True,
  102. )
  103. assert dir_hash_1 != dir_hash_2
  104. def test_hash_folder_diff_image(temp_dir):
  105. dir_hash_1 = prep_docker_build_folder(
  106. temp_dir,
  107. base_image=DEFAULT_BASE_IMAGE,
  108. skip_init=False,
  109. )
  110. with tempfile.TemporaryDirectory() as temp_dir_2:
  111. dir_hash_2 = prep_docker_build_folder(
  112. temp_dir_2,
  113. base_image='debian:11',
  114. skip_init=False,
  115. )
  116. assert dir_hash_1 != dir_hash_2
  117. def test_generate_dockerfile_scratch():
  118. base_image = 'debian:11'
  119. dockerfile_content = _generate_dockerfile(
  120. base_image,
  121. skip_init=False,
  122. )
  123. assert base_image in dockerfile_content
  124. assert 'apt-get update' in dockerfile_content
  125. assert 'apt-get install -y wget sudo apt-utils' in dockerfile_content
  126. assert (
  127. 'RUN /openhands/miniforge3/bin/mamba install conda-forge::poetry python=3.11 -y'
  128. in dockerfile_content
  129. )
  130. # Check the update command
  131. assert 'COPY ./code /openhands/code' in dockerfile_content
  132. assert (
  133. '/openhands/miniforge3/bin/mamba run -n base poetry install'
  134. in dockerfile_content
  135. )
  136. def test_generate_dockerfile_skip_init():
  137. base_image = 'debian:11'
  138. dockerfile_content = _generate_dockerfile(
  139. base_image,
  140. skip_init=True,
  141. )
  142. # These commands SHOULD NOT include in the dockerfile if skip_init is True
  143. assert 'RUN apt update && apt install -y wget sudo' not in dockerfile_content
  144. assert (
  145. 'RUN /openhands/miniforge3/bin/mamba install conda-forge::poetry python=3.11 -y'
  146. not in dockerfile_content
  147. )
  148. # These update commands SHOULD still in the dockerfile
  149. assert 'COPY ./code /openhands/code' in dockerfile_content
  150. assert (
  151. '/openhands/miniforge3/bin/mamba run -n base poetry install'
  152. in dockerfile_content
  153. )
  154. def test_get_runtime_image_repo_and_tag_eventstream():
  155. base_image = 'debian:11'
  156. img_repo, img_tag = get_runtime_image_repo_and_tag(base_image)
  157. assert (
  158. img_repo == f'{get_runtime_image_repo()}'
  159. and img_tag == f'{OH_VERSION}_image_debian_tag_11'
  160. )
  161. img_repo, img_tag = get_runtime_image_repo_and_tag(DEFAULT_BASE_IMAGE)
  162. assert (
  163. img_repo == f'{get_runtime_image_repo()}'
  164. and img_tag
  165. == f'{OH_VERSION}_image_nikolaik_s_python-nodejs_tag_python3.11-nodejs22'
  166. )
  167. base_image = 'ubuntu'
  168. img_repo, img_tag = get_runtime_image_repo_and_tag(base_image)
  169. assert (
  170. img_repo == f'{get_runtime_image_repo()}'
  171. and img_tag == f'{OH_VERSION}_image_ubuntu_tag_latest'
  172. )
  173. def test_build_runtime_image_from_scratch(temp_dir):
  174. base_image = 'debian:11'
  175. from_scratch_hash = prep_docker_build_folder(
  176. temp_dir,
  177. base_image,
  178. skip_init=False,
  179. )
  180. mock_runtime_builder = MagicMock()
  181. mock_runtime_builder.image_exists.return_value = False
  182. mock_runtime_builder.build.return_value = (
  183. f'{get_runtime_image_repo()}:{from_scratch_hash}'
  184. )
  185. image_name = build_runtime_image(base_image, mock_runtime_builder)
  186. mock_runtime_builder.build.assert_called_once_with(
  187. path=ANY,
  188. tags=[
  189. f'{get_runtime_image_repo()}:{from_scratch_hash}',
  190. f'{get_runtime_image_repo()}:{OH_VERSION}_image_debian_tag_11',
  191. ],
  192. )
  193. assert image_name == f'{get_runtime_image_repo()}:{from_scratch_hash}'
  194. def test_build_runtime_image_exact_hash_exist(temp_dir):
  195. base_image = 'debian:11'
  196. from_scratch_hash = prep_docker_build_folder(
  197. temp_dir,
  198. base_image,
  199. skip_init=False,
  200. )
  201. mock_runtime_builder = MagicMock()
  202. mock_runtime_builder.image_exists.return_value = True
  203. mock_runtime_builder.build.return_value = (
  204. f'{get_runtime_image_repo()}:{from_scratch_hash}'
  205. )
  206. image_name = build_runtime_image(base_image, mock_runtime_builder)
  207. assert image_name == f'{get_runtime_image_repo()}:{from_scratch_hash}'
  208. mock_runtime_builder.build.assert_not_called()
  209. @patch('openhands.runtime.utils.runtime_build._build_sandbox_image')
  210. def test_build_runtime_image_exact_hash_not_exist(mock_build_sandbox_image, temp_dir):
  211. base_image = 'debian:11'
  212. repo, latest_image_tag = get_runtime_image_repo_and_tag(base_image)
  213. latest_image_name = f'{repo}:{latest_image_tag}'
  214. from_scratch_hash = prep_docker_build_folder(
  215. temp_dir,
  216. base_image,
  217. skip_init=False,
  218. )
  219. with tempfile.TemporaryDirectory() as temp_dir_2:
  220. non_from_scratch_hash = prep_docker_build_folder(
  221. temp_dir_2,
  222. base_image,
  223. skip_init=True,
  224. )
  225. mock_runtime_builder = MagicMock()
  226. # Set up mock_runtime_builder.image_exists to return False then True
  227. mock_runtime_builder.image_exists.side_effect = [False, True]
  228. with patch(
  229. 'openhands.runtime.utils.runtime_build.prep_docker_build_folder'
  230. ) as mock_prep_docker_build_folder:
  231. mock_prep_docker_build_folder.side_effect = [
  232. from_scratch_hash,
  233. non_from_scratch_hash,
  234. ]
  235. image_name = build_runtime_image(base_image, mock_runtime_builder)
  236. mock_prep_docker_build_folder.assert_has_calls(
  237. [
  238. call(ANY, base_image=base_image, skip_init=False, extra_deps=None),
  239. call(
  240. ANY, base_image=latest_image_name, skip_init=True, extra_deps=None
  241. ),
  242. ]
  243. )
  244. mock_build_sandbox_image.assert_called_once_with(
  245. docker_folder=ANY,
  246. runtime_builder=mock_runtime_builder,
  247. target_image_repo=repo,
  248. target_image_hash_tag=from_scratch_hash,
  249. target_image_tag=latest_image_tag,
  250. )
  251. assert image_name == f'{repo}:{from_scratch_hash}'
  252. # ==============================
  253. # DockerRuntimeBuilder Tests
  254. # ==============================
  255. def test_output_progress(docker_runtime_builder):
  256. with patch('sys.stdout.isatty', return_value=True):
  257. with patch('sys.stdout.write') as mock_write, patch('sys.stdout.flush'):
  258. docker_runtime_builder._output_logs('new log line')
  259. mock_write.assert_any_call('\033[F' * 10)
  260. mock_write.assert_any_call('\033[2Knew log line\n')
  261. def test_output_build_progress(docker_runtime_builder):
  262. with patch('sys.stdout.isatty', return_value=True):
  263. with patch('sys.stdout.write') as mock_write, patch('sys.stdout.flush'):
  264. layers = {}
  265. docker_runtime_builder._output_build_progress(
  266. {
  267. 'id': 'layer1',
  268. 'status': 'Downloading',
  269. 'progressDetail': {'current': 50, 'total': 100},
  270. },
  271. layers,
  272. 0,
  273. )
  274. mock_write.assert_any_call('\033[F' * 0)
  275. mock_write.assert_any_call('\033[2K\r')
  276. assert layers['layer1']['status'] == 'Downloading'
  277. assert layers['layer1']['progress'] == ''
  278. assert layers['layer1']['last_logged'] == 50.0
  279. @pytest.fixture(scope='function')
  280. def live_docker_image():
  281. client = docker.from_env()
  282. unique_id = str(uuid.uuid4())[:8] # Use first 8 characters of a UUID
  283. unique_prefix = f'test_image_{unique_id}'
  284. dockerfile_content = f"""
  285. # syntax=docker/dockerfile:1.4
  286. FROM {DEFAULT_BASE_IMAGE} AS base
  287. RUN apt-get update && apt-get install -y wget sudo apt-utils
  288. FROM base AS intermediate
  289. RUN mkdir -p /openhands
  290. FROM intermediate AS final
  291. RUN echo "Hello, OpenHands!" > /openhands/hello.txt
  292. """
  293. with tempfile.TemporaryDirectory() as temp_dir:
  294. dockerfile_path = os.path.join(temp_dir, 'Dockerfile')
  295. with open(dockerfile_path, 'w') as f:
  296. f.write(dockerfile_content)
  297. try:
  298. image, logs = client.images.build(
  299. path=temp_dir,
  300. tag=f'{unique_prefix}:final',
  301. buildargs={'DOCKER_BUILDKIT': '1'},
  302. labels={'test': 'true'},
  303. rm=True,
  304. forcerm=True,
  305. )
  306. # Tag intermediary stages
  307. client.api.tag(image.id, unique_prefix, 'base')
  308. client.api.tag(image.id, unique_prefix, 'intermediate')
  309. all_tags = [
  310. f'{unique_prefix}:final',
  311. f'{unique_prefix}:base',
  312. f'{unique_prefix}:intermediate',
  313. ]
  314. print(f'\nImage ID: {image.id}')
  315. print(f'Image tags: {all_tags}\n')
  316. yield image
  317. finally:
  318. # Clean up all tagged images
  319. for tag in all_tags:
  320. try:
  321. client.images.remove(tag, force=True)
  322. print(f'Removed image: {tag}')
  323. except Exception as e:
  324. print(f'Error removing image {tag}: {str(e)}')
  325. def test_init(docker_runtime_builder):
  326. assert isinstance(docker_runtime_builder.docker_client, docker.DockerClient)
  327. assert docker_runtime_builder.max_lines == 10
  328. assert docker_runtime_builder.log_lines == [''] * 10
  329. def test_build_image_from_scratch(docker_runtime_builder, tmp_path):
  330. context_path = str(tmp_path)
  331. tags = ['test_build:latest']
  332. # Create a minimal Dockerfile in the context path
  333. with open(os.path.join(context_path, 'Dockerfile'), 'w') as f:
  334. f.write("""FROM php:latest
  335. CMD ["sh", "-c", "echo 'Hello, World!'"]
  336. """)
  337. built_image_name = None
  338. container = None
  339. client = docker.from_env()
  340. try:
  341. with patch('sys.stdout.isatty', return_value=False):
  342. built_image_name = docker_runtime_builder.build(
  343. context_path,
  344. tags,
  345. use_local_cache=False,
  346. )
  347. assert built_image_name == f'{tags[0]}'
  348. # Verify the image was created
  349. image = client.images.get(tags[0])
  350. assert image is not None
  351. except docker.errors.ImageNotFound:
  352. pytest.fail('test_build_image_from_scratch: test image not found!')
  353. except Exception as e:
  354. pytest.fail(f'test_build_image_from_scratch: Build failed with error: {str(e)}')
  355. finally:
  356. # Clean up the container
  357. if container:
  358. try:
  359. container.remove(force=True)
  360. logger.info(f'Removed test container: `{container.id}`')
  361. except Exception as e:
  362. logger.warning(
  363. f'Failed to remove test container `{container.id}`: {str(e)}'
  364. )
  365. # Clean up the image
  366. if built_image_name:
  367. try:
  368. client.images.remove(built_image_name, force=True)
  369. logger.info(f'Removed test image: `{built_image_name}`')
  370. except Exception as e:
  371. logger.warning(
  372. f'Failed to remove test image `{built_image_name}`: {str(e)}'
  373. )
  374. else:
  375. logger.warning('No image was built, so no image cleanup was necessary.')
  376. def _format_size_to_gb(bytes_size):
  377. """Convert bytes to gigabytes with two decimal places."""
  378. return round(bytes_size / (1024**3), 2)
  379. def test_list_dangling_images():
  380. client = docker.from_env()
  381. dangling_images = client.images.list(filters={'dangling': True})
  382. if dangling_images and len(dangling_images) > 0:
  383. for image in dangling_images:
  384. if 'Size' in image.attrs and isinstance(image.attrs['Size'], int):
  385. size_gb = _format_size_to_gb(image.attrs['Size'])
  386. logger.info(f'Dangling image: {image.tags}, Size: {size_gb} GB')
  387. else:
  388. logger.info(f'Dangling image: {image.tags}, Size: n/a')
  389. else:
  390. logger.info('No dangling images found')
  391. def test_build_image_from_repo(docker_runtime_builder, tmp_path):
  392. context_path = str(tmp_path)
  393. tags = ['alpine:latest']
  394. # Create a minimal Dockerfile in the context path
  395. with open(os.path.join(context_path, 'Dockerfile'), 'w') as f:
  396. f.write(f"""FROM {DEFAULT_BASE_IMAGE}
  397. CMD ["sh", "-c", "echo 'Hello, World!'"]
  398. """)
  399. built_image_name = None
  400. container = None
  401. client = docker.from_env()
  402. try:
  403. with patch('sys.stdout.isatty', return_value=False):
  404. built_image_name = docker_runtime_builder.build(
  405. context_path,
  406. tags,
  407. use_local_cache=False,
  408. )
  409. assert built_image_name == f'{tags[0]}'
  410. image = client.images.get(tags[0])
  411. assert image is not None
  412. except docker.errors.ImageNotFound:
  413. pytest.fail('test_build_image_from_repo: test image not found!')
  414. finally:
  415. # Clean up the container
  416. if container:
  417. try:
  418. container.remove(force=True)
  419. logger.info(f'Removed test container: `{container.id}`')
  420. except Exception as e:
  421. logger.warning(
  422. f'Failed to remove test container `{container.id}`: {str(e)}'
  423. )
  424. # Clean up the image
  425. if built_image_name:
  426. try:
  427. client.images.remove(built_image_name, force=True)
  428. logger.info(f'Removed test image: `{built_image_name}`')
  429. except Exception as e:
  430. logger.warning(
  431. f'Failed to remove test image `{built_image_name}`: {str(e)}'
  432. )
  433. else:
  434. logger.warning('No image was built, so no image cleanup was necessary.')
  435. def test_image_exists_local(docker_runtime_builder, live_docker_image):
  436. image_name = live_docker_image.tags[0] if live_docker_image.tags else None
  437. assert image_name, 'Image has no tags'
  438. assert docker_runtime_builder.image_exists(image_name)
  439. def test_image_exists_not_found(docker_runtime_builder):
  440. assert not docker_runtime_builder.image_exists('nonexistent:image')