3 # This file is part of the GROMACS molecular simulation package.
5 # Copyright (c) 2020, by the GROMACS development team, led by
6 # Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
7 # and including many others, as listed in the AUTHORS file in the
8 # top-level source directory and at http://www.gromacs.org.
10 # GROMACS is free software; you can redistribute it and/or
11 # modify it under the terms of the GNU Lesser General Public License
12 # as published by the Free Software Foundation; either version 2.1
13 # of the License, or (at your option) any later version.
15 # GROMACS is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 # Lesser General Public License for more details.
20 # You should have received a copy of the GNU Lesser General Public
21 # License along with GROMACS; if not, see
22 # http://www.gnu.org/licenses, or write to the Free Software Foundation,
23 # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 # If you want to redistribute modifications to GROMACS, please
26 # consider that scientific software is very special. Version
27 # control is crucial - bugs must be traceable. We will be happy to
28 # consider code for inclusion in the official distribution, but
29 # derived work must not be called official GROMACS. Details are found
30 # in the README & COPYING files - if they are missing, get the
31 # official version at http://www.gromacs.org.
33 # To help us fund GROMACS development, we humbly ask that you cite
34 # the research papers on the package. Check out http://www.gromacs.org.
36 """Building block based Dockerfile generation for CI testing images.
38 Generates a set of docker images used for running GROMACS CI on Gitlab.
39 The images are prepared according to a selection of build configuration targets
40 that hope to cover a broad enough scope of different possible systems,
41 allowing us to check compiler types and versions, as well as libraries used
42 for accelerators and parallel communication systems. Each combinations is
43 described as an entry in the build_configs dictionary, with the script
44 analysing the logic and adding build stages as needed.
46 Based on the example script provided by the NVidia HPCCM repository.
49 `NVidia HPC Container Maker <https://github.com/NVIDIA/hpc-container-maker>`__
52 * Paul Bauer <paul.bauer.q@gmail.com>
53 * Eric Irrgang <ericirrgang@gmail.com>
54 * Joe Jordan <e.jjordan12@gmail.com>
55 * Mark Abraham <mark.j.abraham@gmail.com>
59 $ python3 scripted_gmx_docker_builds.py --help
60 $ python3 scripted_gmx_docker_builds.py --format docker > Dockerfile && docker build .
61 $ python3 scripted_gmx_docker_builds.py | docker build -
71 from distutils.version import StrictVersion
75 from hpccm.building_blocks.base import bb_base
81 'This module assumes availability of supporting modules in the same directory. Add the directory to '
82 'PYTHONPATH or invoke Python from within the module directory so module location can be resolved.')
84 # Basic packages for all final images.
85 _common_packages = ['build-essential',
103 _opencl_extra_packages = [
105 # The following require apt_ppas=['ppa:intel-opencl/intel-opencl']
107 'ocl-icd-libopencl1',
108 'ocl-icd-opencl-dev',
110 # The following require
111 # apt_keys=['http://repo.radeon.com/rocm/apt/debian/rocm.gpg.key'],
112 # apt_repositories=['deb [arch=amd64] http://repo.radeon.com/rocm/apt/debian/ xenial main']
119 # Extra packages needed to build Python installations from source.
120 _python_extra_packages = ['build-essential',
139 # Extra packages needed for images for building documentation.
140 _docs_extra_packages = ['autoconf',
156 'texlive-latex-base',
157 'texlive-latex-extra',
158 'texlive-fonts-recommended',
159 'texlive-fonts-extra']
161 # Parse command line arguments
162 parser = argparse.ArgumentParser(description='GROMACS CI image creation script',
163 parents=[utility.parser])
165 parser.add_argument('--format', type=str, default='docker',
166 choices=['docker', 'singularity'],
167 help='Container specification format (default: docker)')
170 def base_image_tag(args) -> str:
171 # Check if we use CUDA images or plain linux images
172 if args.cuda is not None:
173 cuda_version_tag = 'nvidia/cuda:' + args.cuda + '-devel'
174 if args.centos is not None:
175 cuda_version_tag += '-centos' + args.centos
176 elif args.ubuntu is not None:
177 cuda_version_tag += '-ubuntu' + args.ubuntu
179 raise RuntimeError('Logic error: no Linux distribution selected.')
181 base_image_tag = cuda_version_tag
183 if args.centos is not None:
184 base_image_tag = 'centos:centos' + args.centos
185 elif args.ubuntu is not None:
186 base_image_tag = 'ubuntu:' + args.ubuntu
188 raise RuntimeError('Logic error: no Linux distribution selected.')
189 return base_image_tag
192 def get_llvm_packages(args) -> typing.Iterable[str]:
193 # If we use the package version of LLVM, we need to install extra packages for it.
194 if (args.llvm is not None) and (args.tsan is None):
195 return ['libomp-dev',
197 'clang-format-' + str(args.llvm),
198 'clang-tidy-' + str(args.llvm)]
203 def get_opencl_packages(args) -> typing.Iterable[str]:
204 if (args.doxygen is None) and (args.oneapi is None):
205 return _opencl_extra_packages
210 def get_compiler(args, compiler_build_stage: hpccm.Stage = None) -> bb_base:
212 if args.icc is not None:
213 raise RuntimeError('Intel compiler toolchain recipe not implemented yet')
215 if args.llvm is not None:
216 # Build our own version instead to get TSAN + OMP
217 if args.tsan is not None:
218 if compiler_build_stage is not None:
219 compiler = compiler_build_stage.runtime(_from='tsan')
221 raise RuntimeError('No TSAN compiler build stage!')
222 # Build the default compiler if we don't need special support
224 compiler = hpccm.building_blocks.llvm(extra_repository=True, version=args.llvm)
226 elif args.oneapi is not None:
227 if compiler_build_stage is not None:
228 compiler = compiler_build_stage.runtime(_from='oneapi')
229 # Prepare the toolchain (needed only for builds done within the Dockerfile, e.g.
230 # OpenMPI builds, which don't currently work for other reasons)
231 oneapi_toolchain = hpccm.toolchain(CC='/opt/intel/oneapi/compiler/latest/linux/bin/intel64/icc',
232 CXX='/opt/intel/oneapi/compiler/latest/linux/bin/intel64/icpc')
233 setattr(compiler, 'toolchain', oneapi_toolchain)
236 raise RuntimeError('No oneAPI compiler build stage!')
238 elif args.gcc is not None:
239 compiler = hpccm.building_blocks.gnu(extra_repository=True,
243 raise RuntimeError('Logic error: no compiler toolchain selected.')
247 def get_mpi(args, compiler):
248 # If needed, add MPI to the image
249 if args.mpi is not None:
250 if args.mpi == 'openmpi':
252 if args.cuda is not None:
255 if hasattr(compiler, 'toolchain'):
256 if args.oneapi is not None:
257 raise RuntimeError('oneAPI building OpenMPI is not supported')
258 return hpccm.building_blocks.openmpi(toolchain=compiler.toolchain, cuda=use_cuda, infiniband=False)
260 raise RuntimeError('compiler is not an HPCCM compiler building block!')
262 elif args.mpi == 'impi':
263 # TODO Intel MPI from the oneAPI repo is not working reliably,
264 # reasons are unclear. When solved, add packagages called:
265 # 'intel-oneapi-mpi', 'intel-oneapi-mpi-devel'
266 # during the compiler stage.
267 # TODO also consider hpccm's intel_mpi package if that doesn't need
269 raise RuntimeError('Intel MPI recipe not implemented yet.')
271 raise RuntimeError('Requested unknown MPI implementation.')
277 if (args.clfft is not None):
278 return hpccm.building_blocks.generic_cmake(
279 repository='https://github.com/clMathLibraries/clFFT.git',
280 prefix='/usr/local', recursive=True, branch=args.clfft, directory='clFFT/src')
285 def add_tsan_compiler_build_stage(input_args, output_stages: typing.Mapping[str, hpccm.Stage]):
286 """Isolate the expensive TSAN preparation stage.
288 This is a very expensive stage, but has few and disjoint dependencies, and
289 its output is easily compartmentalized (/usr/local) so we can isolate this
290 build stage to maximize build cache hits and reduce rebuild time, bookkeeping,
291 and final image size.
293 if not isinstance(output_stages, collections.abc.MutableMapping):
294 raise RuntimeError('Need output_stages container.')
295 tsan_stage = hpccm.Stage()
296 tsan_stage += hpccm.primitives.baseimage(image=base_image_tag(input_args), _as='tsan')
298 tsan_stage += hpccm.building_blocks.packages(ospackages=['git', 'ca-certificates', 'build-essential', 'cmake'])
299 # CMake will get duplicated later, but this is an expensive image, and it isn't worth optimizing
300 # out that duplication...
301 tsan_stage += hpccm.building_blocks.python(python3=True, python2=False, devel=False)
303 compiler_branch = 'release_' + str(input_args.llvm) + '0'
304 tsan_stage += hpccm.building_blocks.generic_cmake(
305 repository='https://git.llvm.org/git/llvm.git',
306 prefix='/usr/local', recursive=True, branch=compiler_branch,
307 cmake_opts=['-D CMAKE_BUILD_TYPE=Release', '-D LLVM_ENABLE_PROJECTS="clang;openmp;clang-tools-extra"',
308 '-D LIBOMP_TSAN_SUPPORT=on'],
309 preconfigure=['export branch=' + compiler_branch,
310 '(cd projects; git clone --depth=1 --branch $branch https://git.llvm.org/git/libcxx.git)',
311 '(cd projects; git clone --depth=1 --branch $branch https://git.llvm.org/git/libcxxabi.git)',
312 '(cd projects; git clone --depth=1 --branch $branch https://git.llvm.org/git/compiler-rt.git)',
313 '(cd ..; git clone --depth=1 --branch $branch https://git.llvm.org/git/openmp.git)',
314 '(cd ..; git clone --depth=1 --branch $branch https://git.llvm.org/git/clang.git)',
315 '(cd ..; git clone --depth=1 --branch $branch https://git.llvm.org/git/clang-tools-extra.git)'],
316 postinstall=['ln -s /usr/local/bin/clang++ /usr/local/bin/clang++-' + str(input_args.llvm),
317 'ln -s /usr/local/bin/clang-format /usr/local/bin/clang-format-' + str(input_args.llvm),
318 'ln -s /usr/local/bin/clang-tidy /usr/local/bin/clang-tidy-' + str(input_args.llvm),
319 'ln -s /usr/local/libexec/c++-analyzer /usr/local/bin/c++-analyzer-' + str(input_args.llvm)])
320 output_stages['compiler_build'] = tsan_stage
322 def oneapi_runtime(_from='0'):
323 oneapi_runtime_stage = hpccm.Stage()
324 oneapi_runtime_stage += hpccm.primitives.copy(_from='oneapi-build',
325 files={"/opt/intel": "/opt/intel",
326 "/etc/bash.bashrc": "/etc/bash.bashrc"})
327 return oneapi_runtime_stage
329 def add_oneapi_compiler_build_stage(input_args, output_stages: typing.Mapping[str, hpccm.Stage]):
330 """Isolate the oneAPI preparation stage.
332 This stage is isolated so that its installed components are minimized in the
333 final image (chiefly /opt/intel) and its environment setup script can be
334 sourced. This also helps with rebuild time and final image size.
336 Note that the ICC compiler inside oneAPI on linux also needs
337 gcc to build other components and provide libstdc++.
339 if not isinstance(output_stages, collections.abc.MutableMapping):
340 raise RuntimeError('Need output_stages container.')
341 oneapi_stage = hpccm.Stage()
342 oneapi_stage += hpccm.primitives.baseimage(image=base_image_tag(input_args), _as='oneapi-build')
344 version = str(input_args.oneapi)
346 # Add required components for the next stage (both for hpccm and Intel's setvars.sh script)
347 oneapi_stage += hpccm.building_blocks.packages(ospackages=['wget', 'gnupg2', 'ca-certificates', 'lsb-release'])
348 oneapi_stage += hpccm.building_blocks.packages(
349 apt_keys=['https://apt.repos.intel.com/intel-gpg-keys/GPG-PUB-KEY-INTEL-SW-PRODUCTS-2023.PUB'],
350 apt_repositories=['deb https://apt.repos.intel.com/oneapi all main'],
351 # Add minimal packages (not the whole HPC toolkit!)
352 ospackages=['intel-oneapi-dpcpp-cpp-compiler-pro-{}'.format(version),
353 'intel-oneapi-openmp-{}'.format(version),
354 'intel-oneapi-mkl-{}'.format(version),
355 'intel-oneapi-mkl-devel-{}'.format(version)]
357 # Ensure that all bash shells on the final container will have access to oneAPI
358 oneapi_stage += hpccm.primitives.shell(
359 commands=['echo "source /opt/intel/oneapi/setvars.sh" >> /etc/bash.bashrc']
361 setattr(oneapi_stage, 'runtime', oneapi_runtime)
363 output_stages['compiler_build'] = oneapi_stage
365 def prepare_venv(version: StrictVersion) -> typing.Sequence[str]:
366 """Get shell commands to set up the venv for the requested Python version."""
367 major = version.version[0]
368 minor = version.version[1] # type: int
370 pyenv = '$HOME/.pyenv/bin/pyenv'
372 py_ver = '{}.{}'.format(major, minor)
373 venv_path = '$HOME/venv/py{}'.format(py_ver)
374 commands = ['$({pyenv} prefix `{pyenv} whence python{py_ver}`)/bin/python -m venv {path}'.format(
380 commands.append('{path}/bin/python -m pip install --upgrade pip setuptools'.format(
383 # Install dependencies for building and testing gmxapi Python package.
384 # WARNING: Please keep this list synchronized with python_packaging/requirements-test.txt
385 # TODO: Get requirements.txt from an input argument.
386 commands.append("""{path}/bin/python -m pip install --upgrade \
395 'scikit-build>=0.10'""".format(path=venv_path))
397 # TODO: Remove 'importlib_resources' dependency when Python >=3.7 is required.
399 commands.append("""{path}/bin/python -m pip install --upgrade \
400 'importlib_resources'""".format(path=venv_path))
405 def add_python_stages(building_blocks: typing.Mapping[str, bb_base],
407 output_stages: typing.MutableMapping[str, hpccm.Stage]):
408 """Add the stage(s) necessary for the requested venvs.
410 One intermediate build stage is created for each venv (see --venv option).
412 Each stage partially populates Python installations and venvs in the home
413 directory. The home directory is collected by the 'pyenv' stage for use by
414 the main build stage.
416 if len(input_args.venvs) < 1:
417 raise RuntimeError('No venvs to build...')
418 if output_stages is None or not isinstance(output_stages, collections.abc.Mapping):
419 raise RuntimeError('Need a container for output stages.')
421 # Main Python stage that collects the environments from individual stages.
422 # We collect the stages individually, rather than chaining them, because the
423 # copy is a bit slow and wastes local Docker image space for each filesystem
425 pyenv_stage = hpccm.Stage()
426 pyenv_stage += hpccm.primitives.baseimage(image=base_image_tag(input_args), _as='pyenv')
427 pyenv_stage += building_blocks['compiler']
428 pyenv_stage += building_blocks['mpi']
429 pyenv_stage += hpccm.building_blocks.packages(ospackages=_python_extra_packages)
431 for version in [StrictVersion(py_ver) for py_ver in sorted(input_args.venvs)]:
432 stage_name = 'py' + str(version)
433 stage = hpccm.Stage()
434 stage += hpccm.primitives.baseimage(image=base_image_tag(input_args), _as=stage_name)
435 stage += building_blocks['compiler']
436 stage += building_blocks['mpi']
437 stage += hpccm.building_blocks.packages(ospackages=_python_extra_packages)
439 # TODO: Use a non-root user for testing and Python virtual environments.
440 stage += hpccm.primitives.shell(commands=[
441 'curl https://pyenv.run | bash',
442 """echo 'export PYENV_ROOT="$HOME/.pyenv"' >> $HOME/.bashrc""",
443 """echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> $HOME/.bashrc""",
444 """echo 'eval "$(pyenv init -)"' >> $HOME/.bashrc""",
445 """echo 'eval "$(pyenv virtualenv-init -)"' >> $HOME/.bashrc"""])
446 pyenv = '$HOME/.pyenv/bin/pyenv'
447 commands = ['PYTHON_CONFIGURE_OPTS="--enable-shared" {pyenv} install -s {version}'.format(
449 version=str(version))]
450 stage += hpccm.primitives.shell(commands=commands)
452 commands = prepare_venv(version)
453 stage += hpccm.primitives.shell(commands=commands)
455 # TODO: Update user home directory.
456 pyenv_stage += hpccm.primitives.copy(_from=stage_name, _mkdir=True, src=['/root/'],
459 # Add the intermediate build stage to the sequence
460 output_stages[stage_name] = stage
462 # TODO: If we activate pyenv for login shells, the `global` "version" should be full-featured.
463 # # `version` should be a system installation or pyenv environment (or pyenv-virtualenv)
464 # # with the dependencies for all of the Python aspects of CMake-driven builds.
465 # commands = '{pyenv} global {version}'.format(
468 # pyenv_stage += hpccm.primitives.shell(commands=commands)
470 # Add the aggregating build stage to the sequence. This allows the main stage to copy
471 # the files in a single stage, potentially reducing the overall output image size.
472 output_stages['pyenv'] = pyenv_stage
475 def add_documentation_dependencies(input_args,
476 output_stages: typing.MutableMapping[str, hpccm.Stage]):
477 """Add appropriate layers according to doxygen input arguments."""
478 if input_args.doxygen is None:
480 output_stages['main'] += hpccm.primitives.shell(
481 commands=['sed -i \'/\"XPS\"/d;/\"PDF\"/d;/\"PS\"/d;/\"EPS\"/d;/disable ghostscript format types/d\' /etc/ImageMagick-6/policy.xml'])
482 output_stages['main'] += hpccm.building_blocks.pip(pip='pip3', packages=['sphinx==1.6.1', 'gcovr'])
483 if input_args.doxygen == '1.8.5':
484 doxygen_commit = 'ed4ed873ab0e7f15116e2052119a6729d4589f7a'
485 output_stages['main'] += hpccm.building_blocks.generic_autotools(
486 repository='https://github.com/westes/flex.git',
487 commit='f7788a9a0ecccdc953ed12043ccb59ca25714018',
488 prefix='/tmp/install-of-flex',
489 configure_opts=['--disable-shared'],
490 preconfigure=['./autogen.sh'])
491 output_stages['main'] += hpccm.building_blocks.generic_autotools(
492 repository='https://github.com/doxygen/doxygen.git',
493 commit=doxygen_commit,
496 '--flex /tmp/install-of-flex/bin/flex',
499 version = input_args.doxygen
500 archive_name = 'doxygen-{}.linux.bin.tar.gz'.format(version)
501 archive_url = 'https://sourceforge.net/projects/doxygen/files/rel-{}/{}'.format(
505 binary_path = 'doxygen-{}/bin/doxygen'.format(version)
507 'mkdir doxygen && cd doxygen',
508 'wget {}'.format(archive_url),
509 'tar xf {} {}'.format(archive_name, binary_path),
510 'cp {} /usr/local/bin/'.format(binary_path),
511 'cd .. && rm -rf doxygen'
513 output_stages['main'] += hpccm.primitives.shell(commands=commands)
516 def build_stages(args) -> typing.Iterable[hpccm.Stage]:
517 """Define and sequence the stages for the recipe corresponding to *args*."""
519 # A Dockerfile or Singularity recipe can have multiple build stages.
520 # The main build stage can copy files from previous stages, though only
521 # the last stage is included in the tagged output image. This means that
522 # large or expensive sets of build instructions can be isolated in
523 # local/temporary images, but all of the stages need to be output by this
524 # script, and need to occur in the correct order, so we create a sequence
525 # object early in this function.
526 stages = collections.OrderedDict()
528 # If we need TSAN or oneAPI support the early build is more complex,
529 # so that our compiler images don't have all the cruft needed to get those things
531 if args.llvm is not None and args.tsan is not None:
532 add_tsan_compiler_build_stage(input_args=args, output_stages=stages)
533 if args.oneapi is not None:
534 add_oneapi_compiler_build_stage(input_args=args, output_stages=stages)
536 # Building blocks are chunks of container-builder instructions that can be
537 # copied to any build stage with the addition operator.
538 building_blocks = collections.OrderedDict()
539 building_blocks['base_packages'] = hpccm.building_blocks.packages(
540 ospackages=_common_packages)
542 # These are the most expensive and most reusable layers, so we put them first.
543 building_blocks['compiler'] = get_compiler(args, compiler_build_stage=stages.get('compiler_build'))
544 building_blocks['mpi'] = get_mpi(args, building_blocks['compiler'])
545 for i, cmake in enumerate(args.cmake):
546 building_blocks['cmake' + str(i)] = hpccm.building_blocks.cmake(
548 prefix='/usr/local/cmake-{}'.format(cmake),
551 # Install additional packages early in the build to optimize Docker build layer cache.
552 os_packages = list(get_llvm_packages(args)) + get_opencl_packages(args)
553 if args.doxygen is not None:
554 os_packages += _docs_extra_packages
555 if args.oneapi is not None:
556 os_packages += ['lsb-release']
557 building_blocks['extra_packages'] = hpccm.building_blocks.packages(
558 ospackages=os_packages,
559 apt_ppas=['ppa:intel-opencl/intel-opencl'],
560 apt_keys=['http://repo.radeon.com/rocm/apt/debian/rocm.gpg.key'],
561 apt_repositories=['deb [arch=amd64] http://repo.radeon.com/rocm/apt/debian/ xenial main']
564 building_blocks['clfft'] = get_clfft(args)
566 # Add Python environments to MPI images, only, so we don't have to worry
567 # about whether to install mpi4py.
568 if args.mpi is not None and len(args.venvs) > 0:
569 add_python_stages(building_blocks=building_blocks, input_args=args, output_stages=stages)
571 # Create the stage from which the targeted image will be tagged.
572 stages['main'] = hpccm.Stage()
574 stages['main'] += hpccm.primitives.baseimage(image=base_image_tag(args))
575 for bb in building_blocks.values():
579 # We always add Python3 and Pip
580 stages['main'] += hpccm.building_blocks.python(python3=True, python2=False, devel=True)
581 stages['main'] += hpccm.building_blocks.pip(upgrade=True, pip='pip3',
582 packages=['pytest', 'networkx', 'numpy'])
584 # Add documentation requirements (doxygen and sphinx + misc).
585 if args.doxygen is not None:
586 add_documentation_dependencies(args, stages)
588 if 'pyenv' in stages and stages['pyenv'] is not None:
589 stages['main'] += hpccm.primitives.copy(_from='pyenv', _mkdir=True, src=['/root/.pyenv/'],
591 stages['main'] += hpccm.primitives.copy(_from='pyenv', _mkdir=True, src=['/root/venv/'],
593 # TODO: Update user home directory.
594 # TODO: If we activate pyenv for login shells, the `global` "version" should be full-featured.
595 # stages['main'] += hpccm.primitives.copy(_from='pyenv', src=['/root/.bashrc'],
598 # Make sure that `python` resolves to something.
599 stages['main'] += hpccm.primitives.shell(commands=['test -x /usr/bin/python || '
600 'update-alternatives --install /usr/bin/python python /usr/bin/python3 1 && '
601 '/usr/bin/python --version'])
603 # Note that the list of stages should be sorted in dependency order.
604 for build_stage in stages.values():
605 if build_stage is not None:
609 if __name__ == '__main__':
610 args = parser.parse_args()
612 # Set container specification output format
613 hpccm.config.set_container_format(args.format)
615 container_recipe = build_stages(args)
617 # Output container specification
618 for stage in container_recipe: