test_runtime_build.py 17 KB

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