test_runtime_build.py 17 KB

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