xref: /openbmc/openbmc-build-scripts/scripts/build-unit-test-docker (revision a4a60c113ba8bb9e3ed7c1ad31aac44e6779091b)
102871c91SPatrick Williams#!/usr/bin/env python3
202871c91SPatrick Williams#
302871c91SPatrick Williams# Build the required docker image to run package unit tests
402871c91SPatrick Williams#
502871c91SPatrick Williams# Script Variables:
602871c91SPatrick Williams#   DOCKER_IMG_NAME:  <optional, the name of the docker image to generate>
702871c91SPatrick Williams#                     default is openbmc/ubuntu-unit-test
802871c91SPatrick Williams#   DISTRO:           <optional, the distro to build a docker image against>
950837436SPatrick Williams#   FORCE_DOCKER_BUILD: <optional, a non-zero value with force all Docker
1050837436SPatrick Williams#                     images to be rebuilt rather than reusing caches.>
1150837436SPatrick Williams#   BUILD_URL:        <optional, used to detect running under CI context
1250837436SPatrick Williams#                     (ex. Jenkins)>
1302871c91SPatrick Williams#   BRANCH:           <optional, branch to build from each of the openbmc/
1402871c91SPatrick Williams#                     repositories>
1502871c91SPatrick Williams#                     default is master, which will be used if input branch not
1602871c91SPatrick Williams#                     provided or not found
1702871c91SPatrick Williams#   UBUNTU_MIRROR:    <optional, the URL of a mirror of Ubuntu to override the
1802871c91SPatrick Williams#                     default ones in /etc/apt/sources.list>
1902871c91SPatrick Williams#                     default is empty, and no mirror is used.
20fe2768c7SAndrew Geissler#   DOCKER_REG:       <optional, the URL of a docker registry to utilize
2123ec3323SAndrew Geissler#                     instead of our default (public.ecr.aws/ubuntu)
2223ec3323SAndrew Geissler#                     (ex. docker.io)
2302871c91SPatrick Williams#   http_proxy        The HTTP address of the proxy server to connect to.
2402871c91SPatrick Williams#                     Default: "", proxy is not setup if this is not set
2502871c91SPatrick Williams
26276bd0e2SPatrick Williamsimport json
2702871c91SPatrick Williamsimport os
28f3d27e64SAndrew Geisslerimport re
2902871c91SPatrick Williamsimport sys
30b16f3e20SPatrick Williamsimport threading
31276bd0e2SPatrick Williamsimport urllib.request
32a18d9c57SPatrick Williamsfrom datetime import date
33a18d9c57SPatrick Williamsfrom hashlib import sha256
34e08ffba8SPatrick Williams
35e08ffba8SPatrick Williams# typing.Dict is used for type-hints.
36e08ffba8SPatrick Williamsfrom typing import Any, Callable, Dict, Iterable, Optional  # noqa: F401
3702871c91SPatrick Williams
388f7146faSAndrew Geisslerfrom sh import git, nproc  # type: ignore
398f7146faSAndrew Geissler
408f7146faSAndrew Geisslertry:
418f7146faSAndrew Geissler    # System may have docker or it may have podman, try docker first
428f7146faSAndrew Geissler    from sh import docker
438f7146faSAndrew Geissler
448f7146faSAndrew Geissler    container = docker
458f7146faSAndrew Geisslerexcept ImportError:
468f7146faSAndrew Geissler    try:
478f7146faSAndrew Geissler        from sh import podman
488f7146faSAndrew Geissler
498f7146faSAndrew Geissler        container = podman
508f7146faSAndrew Geissler    except Exception:
518f7146faSAndrew Geissler        print("No docker or podman found on system")
528f7146faSAndrew Geissler        exit(1)
5341d86218SPatrick Williams
54ee3c9eebSPatrick Williamstry:
55ee3c9eebSPatrick Williams    # Python before 3.8 doesn't have TypedDict, so reroute to standard 'dict'.
56ee3c9eebSPatrick Williams    from typing import TypedDict
5741d86218SPatrick Williamsexcept Exception:
58ee3c9eebSPatrick Williams
59ee3c9eebSPatrick Williams    class TypedDict(dict):  # type: ignore
60ee3c9eebSPatrick Williams        # We need to do this to eat the 'total' argument.
6141d86218SPatrick Williams        def __init_subclass__(cls, **kwargs: Any) -> None:
62ee3c9eebSPatrick Williams            super().__init_subclass__()
63ee3c9eebSPatrick Williams
64ee3c9eebSPatrick Williams
65ee3c9eebSPatrick Williams# Declare some variables used in package definitions.
66aae36d18SPatrick Williamsprefix = "/usr/local"
6702871c91SPatrick Williamsproc_count = nproc().strip()
6802871c91SPatrick Williams
69ee3c9eebSPatrick Williams
70ee3c9eebSPatrick Williamsclass PackageDef(TypedDict, total=False):
71ee3c9eebSPatrick Williams    """Package Definition for packages dictionary."""
72ee3c9eebSPatrick Williams
73ee3c9eebSPatrick Williams    # rev [optional]: Revision of package to use.
74ee3c9eebSPatrick Williams    rev: str
75ee3c9eebSPatrick Williams    # url [optional]: lambda function to create URL: (package, rev) -> url.
76ee3c9eebSPatrick Williams    url: Callable[[str, str], str]
77ee3c9eebSPatrick Williams    # depends [optional]: List of package dependencies.
78ee3c9eebSPatrick Williams    depends: Iterable[str]
79ee3c9eebSPatrick Williams    # build_type [required]: Build type used for package.
80ee3c9eebSPatrick Williams    #   Currently supported: autoconf, cmake, custom, make, meson
81ee3c9eebSPatrick Williams    build_type: str
82ee3c9eebSPatrick Williams    # build_steps [optional]: Steps to run for 'custom' build_type.
83ee3c9eebSPatrick Williams    build_steps: Iterable[str]
84ee3c9eebSPatrick Williams    # config_flags [optional]: List of options to pass configuration tool.
85ee3c9eebSPatrick Williams    config_flags: Iterable[str]
86ee3c9eebSPatrick Williams    # config_env [optional]: List of environment variables to set for config.
87ee3c9eebSPatrick Williams    config_env: Iterable[str]
88ee3c9eebSPatrick Williams    # custom_post_dl [optional]: List of steps to run after download, but
89ee3c9eebSPatrick Williams    #   before config / build / install.
90ee3c9eebSPatrick Williams    custom_post_dl: Iterable[str]
916bce2ca1SPatrick Williams    # custom_post_install [optional]: List of steps to run after install.
926bce2ca1SPatrick Williams    custom_post_install: Iterable[str]
93ee3c9eebSPatrick Williams
94ee3c9eebSPatrick Williams    # __tag [private]: Generated Docker tag name for package stage.
95ee3c9eebSPatrick Williams    __tag: str
96ee3c9eebSPatrick Williams    # __package [private]: Package object associated with this package.
97ee3c9eebSPatrick Williams    __package: Any  # Type is Package, but not defined yet.
98ee3c9eebSPatrick Williams
9902871c91SPatrick Williams
1007204324cSPatrick Williams# Packages to include in image.
1017204324cSPatrick Williamspackages = {
102ee3c9eebSPatrick Williams    "boost": PackageDef(
103e4b761feSPatrick Williams        rev="1.88.0",
104ee3c9eebSPatrick Williams        url=(
1059698215eSJayanth Othayoth            lambda pkg, rev: f"https://github.com/boostorg/{pkg}/releases/download/{pkg}-{rev}/{pkg}-{rev}-cmake.tar.gz"
1062abc4a48SPatrick Williams        ),
107ee3c9eebSPatrick Williams        build_type="custom",
108ee3c9eebSPatrick Williams        build_steps=[
109e08ffba8SPatrick Williams            (
110e08ffba8SPatrick Williams                "./bootstrap.sh"
1119698215eSJayanth Othayoth                f" --prefix={prefix} --with-libraries=atomic,context,coroutine,filesystem,process,url"
112e08ffba8SPatrick Williams            ),
113aae36d18SPatrick Williams            "./b2",
11404770ccdSMichal Orzel            f"./b2 install --prefix={prefix} valgrind=on",
115aae36d18SPatrick Williams        ],
116ee3c9eebSPatrick Williams    ),
117ee3c9eebSPatrick Williams    "USCiLab/cereal": PackageDef(
118c1977839SPatrick Williams        rev="v1.3.2",
119ee3c9eebSPatrick Williams        build_type="custom",
120ee3c9eebSPatrick Williams        build_steps=[f"cp -a include/cereal/ {prefix}/include/"],
121ee3c9eebSPatrick Williams    ),
122c7198558SEd Tanous    "danmar/cppcheck": PackageDef(
12351021786SPatrick Williams        rev="2.12.1",
124c7198558SEd Tanous        build_type="cmake",
125c7198558SEd Tanous    ),
1263dc37e6eSRatan Gupta    "DMTF/libspdm": PackageDef(
1273dc37e6eSRatan Gupta        rev="3.7.0",
1283dc37e6eSRatan Gupta        url=lambda pkg, rev: f"https://github.com/DMTF/libspdm/archive/{rev}.tar.gz",
1293dc37e6eSRatan Gupta        build_type="cmake",
1303dc37e6eSRatan Gupta        config_flags=(
1313dc37e6eSRatan Gupta            lambda: (
1323dc37e6eSRatan Gupta                lambda arch_mapping={
1333dc37e6eSRatan Gupta                    "x86_64": "x64",
1343dc37e6eSRatan Gupta                    "i586": "ia32",
1353dc37e6eSRatan Gupta                    "i686": "ia32",
1363dc37e6eSRatan Gupta                    "arm": "arm",
1373dc37e6eSRatan Gupta                    "aarch64": "aarch64",
1383dc37e6eSRatan Gupta                    "arm64": "aarch64",
1393dc37e6eSRatan Gupta                    "riscv32": "riscv32",
1403dc37e6eSRatan Gupta                    "riscv64": "riscv64",
1413dc37e6eSRatan Gupta                    "ppc64le": "ppc64le",
1423dc37e6eSRatan Gupta                }: [
1433dc37e6eSRatan Gupta                    f"-DARCH={arch_mapping.get(__import__('platform').machine(), 'x64')}",
1443dc37e6eSRatan Gupta                    "-DTOOLCHAIN=GCC",
1453dc37e6eSRatan Gupta                    "-DTARGET=Release",
1463dc37e6eSRatan Gupta                    "-DCRYPTO=openssl",
1473dc37e6eSRatan Gupta                    "-DBUILD_LINUX_SHARED_LIB=ON",
1483dc37e6eSRatan Gupta                    "-DENABLE_BINARY_BUILD=1",
1493dc37e6eSRatan Gupta                    "-DDISABLE_TESTS=1",
1503dc37e6eSRatan Gupta                    f"-DCOMPILED_LIBCRYPTO_PATH={prefix}/lib",
1513dc37e6eSRatan Gupta                    f"-DCOMPILED_LIBSSL_PATH={prefix}/lib",
1523dc37e6eSRatan Gupta                ]
1533dc37e6eSRatan Gupta            )()
1543dc37e6eSRatan Gupta        )(),
1553dc37e6eSRatan Gupta    ),
156ee3c9eebSPatrick Williams    "CLIUtils/CLI11": PackageDef(
157fc39733aSPatrick Williams        rev="v2.3.2",
158ee3c9eebSPatrick Williams        build_type="cmake",
159ee3c9eebSPatrick Williams        config_flags=[
160aae36d18SPatrick Williams            "-DBUILD_TESTING=OFF",
161aae36d18SPatrick Williams            "-DCLI11_BUILD_DOCS=OFF",
162aae36d18SPatrick Williams            "-DCLI11_BUILD_EXAMPLES=OFF",
163aae36d18SPatrick Williams        ],
164ee3c9eebSPatrick Williams    ),
165ee3c9eebSPatrick Williams    "fmtlib/fmt": PackageDef(
166e4b761feSPatrick Williams        rev="11.2.0",
167ee3c9eebSPatrick Williams        build_type="cmake",
168ee3c9eebSPatrick Williams        config_flags=[
169aae36d18SPatrick Williams            "-DFMT_DOC=OFF",
170aae36d18SPatrick Williams            "-DFMT_TEST=OFF",
171aae36d18SPatrick Williams        ],
172ee3c9eebSPatrick Williams    ),
173ee3c9eebSPatrick Williams    "Naios/function2": PackageDef(
174cb09974cSPatrick Williams        rev="4.2.4",
175ee3c9eebSPatrick Williams        build_type="custom",
176ee3c9eebSPatrick Williams        build_steps=[
177aae36d18SPatrick Williams            f"mkdir {prefix}/include/function2",
178aae36d18SPatrick Williams            f"cp include/function2/function2.hpp {prefix}/include/function2/",
179aae36d18SPatrick Williams        ],
180ee3c9eebSPatrick Williams    ),
181ee3c9eebSPatrick Williams    "google/googletest": PackageDef(
182e4b761feSPatrick Williams        rev="v1.16.0",
183ee3c9eebSPatrick Williams        build_type="cmake",
1844dd32c02SWilliam A. Kennington III        config_env=["CXXFLAGS=-std=c++20"],
185ee3c9eebSPatrick Williams        config_flags=["-DTHREADS_PREFER_PTHREAD_FLAG=ON"],
186ee3c9eebSPatrick Williams    ),
187178b4b29SEd Tanous    "nghttp2/nghttp2": PackageDef(
188e4b761feSPatrick Williams        rev="v1.65.0",
189178b4b29SEd Tanous        build_type="cmake",
190178b4b29SEd Tanous        config_env=["CXXFLAGS=-std=c++20"],
191178b4b29SEd Tanous        config_flags=[
192178b4b29SEd Tanous            "-DENABLE_LIB_ONLY=ON",
193178b4b29SEd Tanous            "-DENABLE_STATIC_LIB=ON",
194178b4b29SEd Tanous        ],
195178b4b29SEd Tanous    ),
196ee3c9eebSPatrick Williams    "nlohmann/json": PackageDef(
197e4b761feSPatrick Williams        rev="v3.12.0",
1986bce2ca1SPatrick Williams        build_type="cmake",
1996bce2ca1SPatrick Williams        config_flags=["-DJSON_BuildTests=OFF"],
2006bce2ca1SPatrick Williams        custom_post_install=[
201e08ffba8SPatrick Williams            (
202e08ffba8SPatrick Williams                f"ln -s {prefix}/include/nlohmann/json.hpp"
203e08ffba8SPatrick Williams                f" {prefix}/include/json.hpp"
204e08ffba8SPatrick Williams            ),
205aae36d18SPatrick Williams        ],
206ee3c9eebSPatrick Williams    ),
207058e3a34SPrzemyslaw Czarnowski    "json-c/json-c": PackageDef(
208e4b761feSPatrick Williams        rev="json-c-0.18-20240915",
209058e3a34SPrzemyslaw Czarnowski        build_type="cmake",
210058e3a34SPrzemyslaw Czarnowski    ),
211ee3c9eebSPatrick Williams    "LibVNC/libvncserver": PackageDef(
212c042132cSPatrick Williams        rev="LibVNCServer-0.9.14",
213ee3c9eebSPatrick Williams        build_type="cmake",
214ee3c9eebSPatrick Williams    ),
215ee3c9eebSPatrick Williams    "leethomason/tinyxml2": PackageDef(
216e4b761feSPatrick Williams        rev="11.0.0",
217ee3c9eebSPatrick Williams        build_type="cmake",
218ee3c9eebSPatrick Williams    ),
219ee3c9eebSPatrick Williams    "tristanpenman/valijson": PackageDef(
220e4b761feSPatrick Williams        rev="v1.0.5",
221ee3c9eebSPatrick Williams        build_type="cmake",
222ee3c9eebSPatrick Williams        config_flags=[
2230eedeedaSPatrick Williams            "-Dvalijson_BUILD_TESTS=0",
2240eedeedaSPatrick Williams            "-Dvalijson_INSTALL_HEADERS=1",
225aae36d18SPatrick Williams        ],
226ee3c9eebSPatrick Williams    ),
227c7e719f9SPatrick Williams    "libgpiod": PackageDef(
228c7e719f9SPatrick Williams        rev="1.6.5",
229c7e719f9SPatrick Williams        url=(
230c7e719f9SPatrick Williams            lambda pkg, rev: f"https://git.kernel.org/pub/scm/libs/{pkg}/{pkg}.git/snapshot/{pkg}-{rev}.tar.gz"
231c7e719f9SPatrick Williams        ),
232c7e719f9SPatrick Williams        build_type="autogen",
233c7e719f9SPatrick Williams        config_flags=["--enable-bindings-cxx"],
234c7e719f9SPatrick Williams    ),
235ee3c9eebSPatrick Williams    "open-power/pdbg": PackageDef(build_type="autoconf"),
236ee3c9eebSPatrick Williams    "openbmc/gpioplus": PackageDef(
237ee3c9eebSPatrick Williams        build_type="meson",
238ee3c9eebSPatrick Williams        config_flags=[
239aae36d18SPatrick Williams            "-Dexamples=false",
240aae36d18SPatrick Williams            "-Dtests=disabled",
241aae36d18SPatrick Williams        ],
242ee3c9eebSPatrick Williams    ),
243ee3c9eebSPatrick Williams    "openbmc/phosphor-dbus-interfaces": PackageDef(
244ee3c9eebSPatrick Williams        depends=["openbmc/sdbusplus"],
245ee3c9eebSPatrick Williams        build_type="meson",
2464fe87776SWilliam A. Kennington III        config_flags=["-Dgenerate_md=false"],
247ee3c9eebSPatrick Williams    ),
248ee3c9eebSPatrick Williams    "openbmc/phosphor-logging": PackageDef(
249ee3c9eebSPatrick Williams        depends=[
25083394610SPatrick Williams            "USCiLab/cereal",
25183394610SPatrick Williams            "openbmc/phosphor-dbus-interfaces",
25283394610SPatrick Williams            "openbmc/sdbusplus",
25383394610SPatrick Williams            "openbmc/sdeventplus",
254aae36d18SPatrick Williams        ],
255f79ce4c4SPatrick Williams        build_type="meson",
256ee3c9eebSPatrick Williams        config_flags=[
2576c98f280SWilliam A. Kennington III            "-Dlibonly=true",
2586c98f280SWilliam A. Kennington III            "-Dtests=disabled",
259aae36d18SPatrick Williams        ],
260ee3c9eebSPatrick Williams    ),
261ee3c9eebSPatrick Williams    "openbmc/phosphor-objmgr": PackageDef(
262ee3c9eebSPatrick Williams        depends=[
26311e5762cSBrad Bishop            "CLIUtils/CLI11",
26470af95caSPatrick Williams            "boost",
26583394610SPatrick Williams            "leethomason/tinyxml2",
26670af95caSPatrick Williams            "openbmc/phosphor-dbus-interfaces",
26783394610SPatrick Williams            "openbmc/phosphor-logging",
26883394610SPatrick Williams            "openbmc/sdbusplus",
269aae36d18SPatrick Williams        ],
2701197e359SBrad Bishop        build_type="meson",
2711197e359SBrad Bishop        config_flags=[
2721197e359SBrad Bishop            "-Dtests=disabled",
2731197e359SBrad Bishop        ],
274ee3c9eebSPatrick Williams    ),
275c02ff271SJason M. Bills    "openbmc/libpeci": PackageDef(
276c02ff271SJason M. Bills        build_type="meson",
277c02ff271SJason M. Bills        config_flags=[
278c02ff271SJason M. Bills            "-Draw-peci=disabled",
279c02ff271SJason M. Bills        ],
280c02ff271SJason M. Bills    ),
2811c19e453SManojkiran Eda    "openbmc/libpldm": PackageDef(
282ee3c9eebSPatrick Williams        build_type="meson",
28329163971SAndrew Jeffery        config_flags=[
28429163971SAndrew Jeffery            "-Dabi=deprecated,stable",
28529163971SAndrew Jeffery            "-Dtests=false",
28629163971SAndrew Jeffery            "-Dabi-compliance-check=false",
28729163971SAndrew Jeffery        ],
288ee3c9eebSPatrick Williams    ),
289ee3c9eebSPatrick Williams    "openbmc/sdbusplus": PackageDef(
29054d01da4SPatrick Williams        depends=[
29154d01da4SPatrick Williams            "nlohmann/json",
29254d01da4SPatrick Williams        ],
293ee3c9eebSPatrick Williams        build_type="meson",
294ee3c9eebSPatrick Williams        custom_post_dl=[
295aae36d18SPatrick Williams            "cd tools",
2963e9c007cSPatrick Williams            "python3 -m pip install --break-system-packages --root-user-action ignore .",
297aae36d18SPatrick Williams            "cd ..",
298aae36d18SPatrick Williams        ],
299ee3c9eebSPatrick Williams        config_flags=[
300aae36d18SPatrick Williams            "-Dexamples=disabled",
301aae36d18SPatrick Williams            "-Dtests=disabled",
302aae36d18SPatrick Williams        ],
303b16f3e20SPatrick Williams    ),
304ee3c9eebSPatrick Williams    "openbmc/sdeventplus": PackageDef(
30570af95caSPatrick Williams        depends=[
30670af95caSPatrick Williams            "openbmc/stdplus",
30770af95caSPatrick Williams        ],
308ee3c9eebSPatrick Williams        build_type="meson",
309ee3c9eebSPatrick Williams        config_flags=[
310ee3c9eebSPatrick Williams            "-Dexamples=false",
311ee3c9eebSPatrick Williams            "-Dtests=disabled",
312ee3c9eebSPatrick Williams        ],
313ee3c9eebSPatrick Williams    ),
314ee3c9eebSPatrick Williams    "openbmc/stdplus": PackageDef(
31570af95caSPatrick Williams        depends=[
31670af95caSPatrick Williams            "fmtlib/fmt",
317ca1bf0c0SWilliam A. Kennington III            "google/googletest",
318ca1bf0c0SWilliam A. Kennington III            "Naios/function2",
31970af95caSPatrick Williams        ],
320ee3c9eebSPatrick Williams        build_type="meson",
321ee3c9eebSPatrick Williams        config_flags=[
322ee3c9eebSPatrick Williams            "-Dexamples=false",
323ee3c9eebSPatrick Williams            "-Dtests=disabled",
324ca1bf0c0SWilliam A. Kennington III            "-Dgtest=enabled",
325ee3c9eebSPatrick Williams        ],
326ee3c9eebSPatrick Williams    ),
327ee3c9eebSPatrick Williams}  # type: Dict[str, PackageDef]
32802871c91SPatrick Williams
32902871c91SPatrick Williams# Define common flags used for builds
33002871c91SPatrick Williamsconfigure_flags = " ".join(
33102871c91SPatrick Williams    [
33202871c91SPatrick Williams        f"--prefix={prefix}",
33302871c91SPatrick Williams    ]
33402871c91SPatrick Williams)
33502871c91SPatrick Williamscmake_flags = " ".join(
33602871c91SPatrick Williams    [
33702871c91SPatrick Williams        "-DBUILD_SHARED_LIBS=ON",
3380f2086b3SPatrick Williams        "-DCMAKE_BUILD_TYPE=RelWithDebInfo",
33902871c91SPatrick Williams        f"-DCMAKE_INSTALL_PREFIX:PATH={prefix}",
3400f2086b3SPatrick Williams        "-GNinja",
3410f2086b3SPatrick Williams        "-DCMAKE_MAKE_PROGRAM=ninja",
34202871c91SPatrick Williams    ]
34302871c91SPatrick Williams)
34402871c91SPatrick Williamsmeson_flags = " ".join(
34502871c91SPatrick Williams    [
34602871c91SPatrick Williams        "--wrap-mode=nodownload",
34702871c91SPatrick Williams        f"-Dprefix={prefix}",
34802871c91SPatrick Williams    ]
34902871c91SPatrick Williams)
35002871c91SPatrick Williams
351ee3c9eebSPatrick Williams
352ee3c9eebSPatrick Williamsclass Package(threading.Thread):
353ee3c9eebSPatrick Williams    """Class used to build the Docker stages for each package.
354ee3c9eebSPatrick Williams
355ee3c9eebSPatrick Williams    Generally, this class should not be instantiated directly but through
356ee3c9eebSPatrick Williams    Package.generate_all().
357ee3c9eebSPatrick Williams    """
358ee3c9eebSPatrick Williams
359ee3c9eebSPatrick Williams    # Copy the packages dictionary.
360ee3c9eebSPatrick Williams    packages = packages.copy()
361ee3c9eebSPatrick Williams
362ee3c9eebSPatrick Williams    # Lock used for thread-safety.
363ee3c9eebSPatrick Williams    lock = threading.Lock()
364ee3c9eebSPatrick Williams
365ee3c9eebSPatrick Williams    def __init__(self, pkg: str):
366ee3c9eebSPatrick Williams        """pkg - The name of this package (ex. foo/bar )"""
367ee3c9eebSPatrick Williams        super(Package, self).__init__()
368ee3c9eebSPatrick Williams
369ee3c9eebSPatrick Williams        self.package = pkg
370ee3c9eebSPatrick Williams        self.exception = None  # type: Optional[Exception]
371ee3c9eebSPatrick Williams
372ee3c9eebSPatrick Williams        # Reference to this package's
373ee3c9eebSPatrick Williams        self.pkg_def = Package.packages[pkg]
374ee3c9eebSPatrick Williams        self.pkg_def["__package"] = self
375ee3c9eebSPatrick Williams
376ee3c9eebSPatrick Williams    def run(self) -> None:
377ee3c9eebSPatrick Williams        """Thread 'run' function.  Builds the Docker stage."""
378ee3c9eebSPatrick Williams
379ee3c9eebSPatrick Williams        # In case this package has no rev, fetch it from Github.
380ee3c9eebSPatrick Williams        self._update_rev()
381ee3c9eebSPatrick Williams
382ee3c9eebSPatrick Williams        # Find all the Package objects that this package depends on.
383ee3c9eebSPatrick Williams        #   This section is locked because we are looking into another
384ee3c9eebSPatrick Williams        #   package's PackageDef dict, which could be being modified.
385ee3c9eebSPatrick Williams        Package.lock.acquire()
386ee3c9eebSPatrick Williams        deps: Iterable[Package] = [
387ee3c9eebSPatrick Williams            Package.packages[deppkg]["__package"]
388ee3c9eebSPatrick Williams            for deppkg in self.pkg_def.get("depends", [])
389ee3c9eebSPatrick Williams        ]
390ee3c9eebSPatrick Williams        Package.lock.release()
391ee3c9eebSPatrick Williams
392ee3c9eebSPatrick Williams        # Wait until all the depends finish building.  We need them complete
393ee3c9eebSPatrick Williams        # for the "COPY" commands.
394ee3c9eebSPatrick Williams        for deppkg in deps:
395ee3c9eebSPatrick Williams            deppkg.join()
396ee3c9eebSPatrick Williams
397ee3c9eebSPatrick Williams        # Generate this package's Dockerfile.
398ee3c9eebSPatrick Williams        dockerfile = f"""
399ee3c9eebSPatrick WilliamsFROM {docker_base_img_name}
400ee3c9eebSPatrick Williams{self._df_copycmds()}
401ee3c9eebSPatrick Williams{self._df_build()}
402ee3c9eebSPatrick Williams"""
403ee3c9eebSPatrick Williams
404ee3c9eebSPatrick Williams        # Generate the resulting tag name and save it to the PackageDef.
405ee3c9eebSPatrick Williams        #   This section is locked because we are modifying the PackageDef,
406ee3c9eebSPatrick Williams        #   which can be accessed by other threads.
407ee3c9eebSPatrick Williams        Package.lock.acquire()
408ee3c9eebSPatrick Williams        tag = Docker.tagname(self._stagename(), dockerfile)
409ee3c9eebSPatrick Williams        self.pkg_def["__tag"] = tag
410ee3c9eebSPatrick Williams        Package.lock.release()
411ee3c9eebSPatrick Williams
412ee3c9eebSPatrick Williams        # Do the build / save any exceptions.
413ee3c9eebSPatrick Williams        try:
414ee3c9eebSPatrick Williams            Docker.build(self.package, tag, dockerfile)
415ee3c9eebSPatrick Williams        except Exception as e:
416ee3c9eebSPatrick Williams            self.exception = e
417ee3c9eebSPatrick Williams
418ee3c9eebSPatrick Williams    @classmethod
419ee3c9eebSPatrick Williams    def generate_all(cls) -> None:
420ee3c9eebSPatrick Williams        """Ensure a Docker stage is created for all defined packages.
421ee3c9eebSPatrick Williams
422ee3c9eebSPatrick Williams        These are done in parallel but with appropriate blocking per
423ee3c9eebSPatrick Williams        package 'depends' specifications.
424ee3c9eebSPatrick Williams        """
425ee3c9eebSPatrick Williams
426ee3c9eebSPatrick Williams        # Create a Package for each defined package.
427ee3c9eebSPatrick Williams        pkg_threads = [Package(p) for p in cls.packages.keys()]
428ee3c9eebSPatrick Williams
429ee3c9eebSPatrick Williams        # Start building them all.
4306dbd7807SPatrick Williams        #   This section is locked because threads depend on each other,
4316dbd7807SPatrick Williams        #   based on the packages, and they cannot 'join' on a thread
4326dbd7807SPatrick Williams        #   which is not yet started.  Adding a lock here allows all the
4336dbd7807SPatrick Williams        #   threads to start before they 'join' their dependencies.
4346dbd7807SPatrick Williams        Package.lock.acquire()
435ee3c9eebSPatrick Williams        for t in pkg_threads:
436ee3c9eebSPatrick Williams            t.start()
4376dbd7807SPatrick Williams        Package.lock.release()
438ee3c9eebSPatrick Williams
439ee3c9eebSPatrick Williams        # Wait for completion.
440ee3c9eebSPatrick Williams        for t in pkg_threads:
441ee3c9eebSPatrick Williams            t.join()
442ee3c9eebSPatrick Williams            # Check if the thread saved off its own exception.
443ee3c9eebSPatrick Williams            if t.exception:
444ee3c9eebSPatrick Williams                print(f"Package {t.package} failed!", file=sys.stderr)
445ee3c9eebSPatrick Williams                raise t.exception
446ee3c9eebSPatrick Williams
447ee3c9eebSPatrick Williams    @staticmethod
448ee3c9eebSPatrick Williams    def df_all_copycmds() -> str:
449ee3c9eebSPatrick Williams        """Formulate the Dockerfile snippet necessary to copy all packages
450ee3c9eebSPatrick Williams        into the final image.
451ee3c9eebSPatrick Williams        """
452ee3c9eebSPatrick Williams        return Package.df_copycmds_set(Package.packages.keys())
453ee3c9eebSPatrick Williams
454ee3c9eebSPatrick Williams    @classmethod
455ee3c9eebSPatrick Williams    def depcache(cls) -> str:
456ee3c9eebSPatrick Williams        """Create the contents of the '/tmp/depcache'.
457ee3c9eebSPatrick Williams        This file is a comma-separated list of "<pkg>:<rev>".
458ee3c9eebSPatrick Williams        """
459ee3c9eebSPatrick Williams
460ee3c9eebSPatrick Williams        # This needs to be sorted for consistency.
461ee3c9eebSPatrick Williams        depcache = ""
462ee3c9eebSPatrick Williams        for pkg in sorted(cls.packages.keys()):
463ee3c9eebSPatrick Williams            depcache += "%s:%s," % (pkg, cls.packages[pkg]["rev"])
464ee3c9eebSPatrick Williams        return depcache
465ee3c9eebSPatrick Williams
466276bd0e2SPatrick Williams    def _check_gerrit_topic(self) -> bool:
467276bd0e2SPatrick Williams        if not gerrit_topic:
468276bd0e2SPatrick Williams            return False
469276bd0e2SPatrick Williams        if not self.package.startswith("openbmc/"):
470276bd0e2SPatrick Williams            return False
471276bd0e2SPatrick Williams        if gerrit_project == self.package and gerrit_rev:
472276bd0e2SPatrick Williams            return False
473276bd0e2SPatrick Williams
4741c84797dSPatrick Williams        # URL escape any spaces.  Gerrit uses pluses.
4751c84797dSPatrick Williams        gerrit_topic_escape = urllib.parse.quote_plus(gerrit_topic)
4761c84797dSPatrick Williams
477276bd0e2SPatrick Williams        try:
478276bd0e2SPatrick Williams            commits = json.loads(
479276bd0e2SPatrick Williams                urllib.request.urlopen(
4801c84797dSPatrick Williams                    f'https://gerrit.openbmc.org/changes/?q=status:open+project:{self.package}+topic:"{gerrit_topic_escape}"'
481276bd0e2SPatrick Williams                )
482276bd0e2SPatrick Williams                .read()
483276bd0e2SPatrick Williams                .splitlines()[-1]
484276bd0e2SPatrick Williams            )
485276bd0e2SPatrick Williams
486276bd0e2SPatrick Williams            if len(commits) == 0:
487276bd0e2SPatrick Williams                return False
488276bd0e2SPatrick Williams            if len(commits) > 1:
489276bd0e2SPatrick Williams                print(
490276bd0e2SPatrick Williams                    f"{self.package} has more than 1 commit under {gerrit_topic}; using lastest upstream: {len(commits)}",
491276bd0e2SPatrick Williams                    file=sys.stderr,
492276bd0e2SPatrick Williams                )
493276bd0e2SPatrick Williams                return False
494276bd0e2SPatrick Williams
495276bd0e2SPatrick Williams            change_id = commits[0]["id"]
496276bd0e2SPatrick Williams
497276bd0e2SPatrick Williams            commit = json.loads(
498276bd0e2SPatrick Williams                urllib.request.urlopen(
499276bd0e2SPatrick Williams                    f"https://gerrit.openbmc.org/changes/{change_id}/revisions/current/commit"
500276bd0e2SPatrick Williams                )
501276bd0e2SPatrick Williams                .read()
502276bd0e2SPatrick Williams                .splitlines()[-1]
503276bd0e2SPatrick Williams            )["commit"]
504276bd0e2SPatrick Williams
505276bd0e2SPatrick Williams            print(
506276bd0e2SPatrick Williams                f"Using {commit} from {gerrit_topic} for {self.package}",
507276bd0e2SPatrick Williams                file=sys.stderr,
508276bd0e2SPatrick Williams            )
509276bd0e2SPatrick Williams            self.pkg_def["rev"] = commit
510276bd0e2SPatrick Williams            return True
511276bd0e2SPatrick Williams
512276bd0e2SPatrick Williams        except urllib.error.HTTPError as e:
513276bd0e2SPatrick Williams            print(
514276bd0e2SPatrick Williams                f"Error loading topic {gerrit_topic} for {self.package}: ",
515276bd0e2SPatrick Williams                e,
516276bd0e2SPatrick Williams                file=sys.stderr,
517276bd0e2SPatrick Williams            )
518276bd0e2SPatrick Williams            return False
519276bd0e2SPatrick Williams
520ee3c9eebSPatrick Williams    def _update_rev(self) -> None:
521ee3c9eebSPatrick Williams        """Look up the HEAD for missing a static rev."""
522ee3c9eebSPatrick Williams
523ee3c9eebSPatrick Williams        if "rev" in self.pkg_def:
524ee3c9eebSPatrick Williams            return
525ee3c9eebSPatrick Williams
526276bd0e2SPatrick Williams        if self._check_gerrit_topic():
527276bd0e2SPatrick Williams            return
528276bd0e2SPatrick Williams
52965b21fb9SPatrick Williams        # Check if Jenkins/Gerrit gave us a revision and use it.
53065b21fb9SPatrick Williams        if gerrit_project == self.package and gerrit_rev:
53165b21fb9SPatrick Williams            print(
53265b21fb9SPatrick Williams                f"Found Gerrit revision for {self.package}: {gerrit_rev}",
53365b21fb9SPatrick Williams                file=sys.stderr,
53465b21fb9SPatrick Williams            )
53565b21fb9SPatrick Williams            self.pkg_def["rev"] = gerrit_rev
53665b21fb9SPatrick Williams            return
53765b21fb9SPatrick Williams
538ee3c9eebSPatrick Williams        # Ask Github for all the branches.
53905fb2a0aSPatrick Williams        lookup = git(
54005fb2a0aSPatrick Williams            "ls-remote", "--heads", f"https://github.com/{self.package}"
54105fb2a0aSPatrick Williams        )
542ee3c9eebSPatrick Williams
543ee3c9eebSPatrick Williams        # Find the branch matching {branch} (or fallback to master).
544ee3c9eebSPatrick Williams        #   This section is locked because we are modifying the PackageDef.
545ee3c9eebSPatrick Williams        Package.lock.acquire()
546ee3c9eebSPatrick Williams        for line in lookup.split("\n"):
547f3d27e64SAndrew Geissler            if re.fullmatch(f".*{branch}$", line.strip()):
548ee3c9eebSPatrick Williams                self.pkg_def["rev"] = line.split()[0]
549f3d27e64SAndrew Geissler                break
550c7d73646SPatrick Williams            elif (
551c7d73646SPatrick Williams                "refs/heads/master" in line or "refs/heads/main" in line
552c7d73646SPatrick Williams            ) and "rev" not in self.pkg_def:
553ee3c9eebSPatrick Williams                self.pkg_def["rev"] = line.split()[0]
554ee3c9eebSPatrick Williams        Package.lock.release()
555ee3c9eebSPatrick Williams
556ee3c9eebSPatrick Williams    def _stagename(self) -> str:
557ee3c9eebSPatrick Williams        """Create a name for the Docker stage associated with this pkg."""
558ee3c9eebSPatrick Williams        return self.package.replace("/", "-").lower()
559ee3c9eebSPatrick Williams
560ee3c9eebSPatrick Williams    def _url(self) -> str:
561ee3c9eebSPatrick Williams        """Get the URL for this package."""
562ee3c9eebSPatrick Williams        rev = self.pkg_def["rev"]
563ee3c9eebSPatrick Williams
564ee3c9eebSPatrick Williams        # If the lambda exists, call it.
565ee3c9eebSPatrick Williams        if "url" in self.pkg_def:
566ee3c9eebSPatrick Williams            return self.pkg_def["url"](self.package, rev)
567ee3c9eebSPatrick Williams
568ee3c9eebSPatrick Williams        # Default to the github archive URL.
569ee3c9eebSPatrick Williams        return f"https://github.com/{self.package}/archive/{rev}.tar.gz"
570ee3c9eebSPatrick Williams
571ee3c9eebSPatrick Williams    def _cmd_download(self) -> str:
572ee3c9eebSPatrick Williams        """Formulate the command necessary to download and unpack to source."""
573ee3c9eebSPatrick Williams
574ee3c9eebSPatrick Williams        url = self._url()
575ee3c9eebSPatrick Williams        if ".tar." not in url:
576ee3c9eebSPatrick Williams            raise NotImplementedError(
577ee3c9eebSPatrick Williams                f"Unhandled download type for {self.package}: {url}"
578ee3c9eebSPatrick Williams            )
579ee3c9eebSPatrick Williams
580ee3c9eebSPatrick Williams        cmd = f"curl -L {url} | tar -x"
581ee3c9eebSPatrick Williams
582ee3c9eebSPatrick Williams        if url.endswith(".bz2"):
583ee3c9eebSPatrick Williams            cmd += "j"
584ee3c9eebSPatrick Williams        elif url.endswith(".gz"):
585ee3c9eebSPatrick Williams            cmd += "z"
586ee3c9eebSPatrick Williams        else:
587ee3c9eebSPatrick Williams            raise NotImplementedError(
588ee3c9eebSPatrick Williams                f"Unknown tar flags needed for {self.package}: {url}"
589ee3c9eebSPatrick Williams            )
590ee3c9eebSPatrick Williams
591ee3c9eebSPatrick Williams        return cmd
592ee3c9eebSPatrick Williams
593ee3c9eebSPatrick Williams    def _cmd_cd_srcdir(self) -> str:
594ee3c9eebSPatrick Williams        """Formulate the command necessary to 'cd' into the source dir."""
595ee3c9eebSPatrick Williams        return f"cd {self.package.split('/')[-1]}*"
596ee3c9eebSPatrick Williams
597ee3c9eebSPatrick Williams    def _df_copycmds(self) -> str:
598ee3c9eebSPatrick Williams        """Formulate the dockerfile snippet necessary to COPY all depends."""
599ee3c9eebSPatrick Williams
600ee3c9eebSPatrick Williams        if "depends" not in self.pkg_def:
601ee3c9eebSPatrick Williams            return ""
602ee3c9eebSPatrick Williams        return Package.df_copycmds_set(self.pkg_def["depends"])
603ee3c9eebSPatrick Williams
604ee3c9eebSPatrick Williams    @staticmethod
605ee3c9eebSPatrick Williams    def df_copycmds_set(pkgs: Iterable[str]) -> str:
606ee3c9eebSPatrick Williams        """Formulate the Dockerfile snippet necessary to COPY a set of
607ee3c9eebSPatrick Williams        packages into a Docker stage.
608ee3c9eebSPatrick Williams        """
609ee3c9eebSPatrick Williams
610ee3c9eebSPatrick Williams        copy_cmds = ""
611ee3c9eebSPatrick Williams
612ee3c9eebSPatrick Williams        # Sort the packages for consistency.
613ee3c9eebSPatrick Williams        for p in sorted(pkgs):
614ee3c9eebSPatrick Williams            tag = Package.packages[p]["__tag"]
615ee3c9eebSPatrick Williams            copy_cmds += f"COPY --from={tag} {prefix} {prefix}\n"
616ee3c9eebSPatrick Williams            # Workaround for upstream docker bug and multiple COPY cmds
617ee3c9eebSPatrick Williams            # https://github.com/moby/moby/issues/37965
618ee3c9eebSPatrick Williams            copy_cmds += "RUN true\n"
619ee3c9eebSPatrick Williams
620ee3c9eebSPatrick Williams        return copy_cmds
621ee3c9eebSPatrick Williams
622ee3c9eebSPatrick Williams    def _df_build(self) -> str:
623ee3c9eebSPatrick Williams        """Formulate the Dockerfile snippet necessary to download, build, and
624ee3c9eebSPatrick Williams        install a package into a Docker stage.
625ee3c9eebSPatrick Williams        """
626ee3c9eebSPatrick Williams
627ee3c9eebSPatrick Williams        # Download and extract source.
628ee3c9eebSPatrick Williams        result = f"RUN {self._cmd_download()} && {self._cmd_cd_srcdir()} && "
629ee3c9eebSPatrick Williams
630ee3c9eebSPatrick Williams        # Handle 'custom_post_dl' commands.
631ee3c9eebSPatrick Williams        custom_post_dl = self.pkg_def.get("custom_post_dl")
632ee3c9eebSPatrick Williams        if custom_post_dl:
633ee3c9eebSPatrick Williams            result += " && ".join(custom_post_dl) + " && "
634ee3c9eebSPatrick Williams
635ee3c9eebSPatrick Williams        # Build and install package based on 'build_type'.
636ee3c9eebSPatrick Williams        build_type = self.pkg_def["build_type"]
637ee3c9eebSPatrick Williams        if build_type == "autoconf":
638ee3c9eebSPatrick Williams            result += self._cmd_build_autoconf()
639c7e719f9SPatrick Williams        elif build_type == "autogen":
640c7e719f9SPatrick Williams            result += self._cmd_build_autogen()
641ee3c9eebSPatrick Williams        elif build_type == "cmake":
642ee3c9eebSPatrick Williams            result += self._cmd_build_cmake()
643ee3c9eebSPatrick Williams        elif build_type == "custom":
644ee3c9eebSPatrick Williams            result += self._cmd_build_custom()
645ee3c9eebSPatrick Williams        elif build_type == "make":
646ee3c9eebSPatrick Williams            result += self._cmd_build_make()
647ee3c9eebSPatrick Williams        elif build_type == "meson":
648ee3c9eebSPatrick Williams            result += self._cmd_build_meson()
649ee3c9eebSPatrick Williams        else:
650ee3c9eebSPatrick Williams            raise NotImplementedError(
651ee3c9eebSPatrick Williams                f"Unhandled build type for {self.package}: {build_type}"
652ee3c9eebSPatrick Williams            )
653ee3c9eebSPatrick Williams
6546bce2ca1SPatrick Williams        # Handle 'custom_post_install' commands.
6556bce2ca1SPatrick Williams        custom_post_install = self.pkg_def.get("custom_post_install")
6566bce2ca1SPatrick Williams        if custom_post_install:
6576bce2ca1SPatrick Williams            result += " && " + " && ".join(custom_post_install)
6586bce2ca1SPatrick Williams
659ee3c9eebSPatrick Williams        return result
660ee3c9eebSPatrick Williams
661ee3c9eebSPatrick Williams    def _cmd_build_autoconf(self) -> str:
662ee3c9eebSPatrick Williams        options = " ".join(self.pkg_def.get("config_flags", []))
663ee3c9eebSPatrick Williams        env = " ".join(self.pkg_def.get("config_env", []))
664ee3c9eebSPatrick Williams        result = "./bootstrap.sh && "
665ee3c9eebSPatrick Williams        result += f"{env} ./configure {configure_flags} {options} && "
666ee3c9eebSPatrick Williams        result += f"make -j{proc_count} && make install"
667ee3c9eebSPatrick Williams        return result
668ee3c9eebSPatrick Williams
669c7e719f9SPatrick Williams    def _cmd_build_autogen(self) -> str:
670c7e719f9SPatrick Williams        options = " ".join(self.pkg_def.get("config_flags", []))
671c7e719f9SPatrick Williams        env = " ".join(self.pkg_def.get("config_env", []))
672c7e719f9SPatrick Williams        result = f"{env} ./autogen.sh {configure_flags} {options} && "
673c7e719f9SPatrick Williams        result += "make && make install"
674c7e719f9SPatrick Williams        return result
675c7e719f9SPatrick Williams
676ee3c9eebSPatrick Williams    def _cmd_build_cmake(self) -> str:
677ee3c9eebSPatrick Williams        options = " ".join(self.pkg_def.get("config_flags", []))
678ee3c9eebSPatrick Williams        env = " ".join(self.pkg_def.get("config_env", []))
679ee3c9eebSPatrick Williams        result = "mkdir builddir && cd builddir && "
680ee3c9eebSPatrick Williams        result += f"{env} cmake {cmake_flags} {options} .. && "
681ee3c9eebSPatrick Williams        result += "cmake --build . --target all && "
682ee3c9eebSPatrick Williams        result += "cmake --build . --target install && "
683ee3c9eebSPatrick Williams        result += "cd .."
684ee3c9eebSPatrick Williams        return result
685ee3c9eebSPatrick Williams
686ee3c9eebSPatrick Williams    def _cmd_build_custom(self) -> str:
687ee3c9eebSPatrick Williams        return " && ".join(self.pkg_def.get("build_steps", []))
688ee3c9eebSPatrick Williams
689ee3c9eebSPatrick Williams    def _cmd_build_make(self) -> str:
690ee3c9eebSPatrick Williams        return f"make -j{proc_count} && make install"
691ee3c9eebSPatrick Williams
692ee3c9eebSPatrick Williams    def _cmd_build_meson(self) -> str:
693ee3c9eebSPatrick Williams        options = " ".join(self.pkg_def.get("config_flags", []))
694ee3c9eebSPatrick Williams        env = " ".join(self.pkg_def.get("config_env", []))
695e2da11adSAndrew Jeffery        result = f"{env} meson setup builddir {meson_flags} {options} && "
696ee3c9eebSPatrick Williams        result += "ninja -C builddir && ninja -C builddir install"
697ee3c9eebSPatrick Williams        return result
698ee3c9eebSPatrick Williams
699ee3c9eebSPatrick Williams
700ee3c9eebSPatrick Williamsclass Docker:
701ee3c9eebSPatrick Williams    """Class to assist with Docker interactions.  All methods are static."""
702ee3c9eebSPatrick Williams
703ee3c9eebSPatrick Williams    @staticmethod
704ee3c9eebSPatrick Williams    def timestamp() -> str:
705ee3c9eebSPatrick Williams        """Generate a timestamp for today using the ISO week."""
706ee3c9eebSPatrick Williams        today = date.today().isocalendar()
707ee3c9eebSPatrick Williams        return f"{today[0]}-W{today[1]:02}"
708ee3c9eebSPatrick Williams
709ee3c9eebSPatrick Williams    @staticmethod
71041d86218SPatrick Williams    def tagname(pkgname: Optional[str], dockerfile: str) -> str:
711ee3c9eebSPatrick Williams        """Generate a tag name for a package using a hash of the Dockerfile."""
712ee3c9eebSPatrick Williams        result = docker_image_name
713ee3c9eebSPatrick Williams        if pkgname:
714ee3c9eebSPatrick Williams            result += "-" + pkgname
715ee3c9eebSPatrick Williams
716ee3c9eebSPatrick Williams        result += ":" + Docker.timestamp()
717ee3c9eebSPatrick Williams        result += "-" + sha256(dockerfile.encode()).hexdigest()[0:16]
718ee3c9eebSPatrick Williams
719ee3c9eebSPatrick Williams        return result
720ee3c9eebSPatrick Williams
721ee3c9eebSPatrick Williams    @staticmethod
722ee3c9eebSPatrick Williams    def build(pkg: str, tag: str, dockerfile: str) -> None:
72322e6110bSAndrew Geissler        """Build a docker image using the Dockerfile and tagging it with 'tag'."""
724ee3c9eebSPatrick Williams
725ee3c9eebSPatrick Williams        # If we're not forcing builds, check if it already exists and skip.
726ee3c9eebSPatrick Williams        if not force_build:
7278f7146faSAndrew Geissler            if container.image.ls(
7288f7146faSAndrew Geissler                tag, "--format", '"{{.Repository}}:{{.Tag}}"'
7298f7146faSAndrew Geissler            ):
73005fb2a0aSPatrick Williams                print(
73105fb2a0aSPatrick Williams                    f"Image {tag} already exists.  Skipping.", file=sys.stderr
73205fb2a0aSPatrick Williams                )
733ee3c9eebSPatrick Williams                return
734ee3c9eebSPatrick Williams
735ee3c9eebSPatrick Williams        # Build it.
736ee3c9eebSPatrick Williams        #   Capture the output of the 'docker build' command and send it to
737ee3c9eebSPatrick Williams        #   stderr (prefixed with the package name).  This allows us to see
738a6ebc6e2SManojkiran Eda        #   progress but not pollute stdout.  Later on we output the final
739ee3c9eebSPatrick Williams        #   docker tag to stdout and we want to keep that pristine.
740ee3c9eebSPatrick Williams        #
741ee3c9eebSPatrick Williams        #   Other unusual flags:
742ee3c9eebSPatrick Williams        #       --no-cache: Bypass the Docker cache if 'force_build'.
743ee3c9eebSPatrick Williams        #       --force-rm: Clean up Docker processes if they fail.
7448f7146faSAndrew Geissler        container.build(
745ee3c9eebSPatrick Williams            proxy_args,
746ee3c9eebSPatrick Williams            "--network=host",
747ee3c9eebSPatrick Williams            "--force-rm",
748ee3c9eebSPatrick Williams            "--no-cache=true" if force_build else "--no-cache=false",
749ee3c9eebSPatrick Williams            "-t",
750ee3c9eebSPatrick Williams            tag,
751ee3c9eebSPatrick Williams            "-",
752ee3c9eebSPatrick Williams            _in=dockerfile,
753ee3c9eebSPatrick Williams            _out=(
754ee3c9eebSPatrick Williams                lambda line: print(
755ee3c9eebSPatrick Williams                    pkg + ":", line, end="", file=sys.stderr, flush=True
756ee3c9eebSPatrick Williams                )
757ee3c9eebSPatrick Williams            ),
75888dd7929SJonathan Doman            _err_to_out=True,
759ee3c9eebSPatrick Williams        )
760ee3c9eebSPatrick Williams
761ee3c9eebSPatrick Williams
762ee3c9eebSPatrick Williams# Read a bunch of environment variables.
76305fb2a0aSPatrick Williamsdocker_image_name = os.environ.get(
76405fb2a0aSPatrick Williams    "DOCKER_IMAGE_NAME", "openbmc/ubuntu-unit-test"
76505fb2a0aSPatrick Williams)
766ee3c9eebSPatrick Williamsforce_build = os.environ.get("FORCE_DOCKER_BUILD")
767ee3c9eebSPatrick Williamsis_automated_ci_build = os.environ.get("BUILD_URL", False)
7686b14190fSPatrick Williamsdistro = os.environ.get("DISTRO", "ubuntu:plucky")
769ee3c9eebSPatrick Williamsbranch = os.environ.get("BRANCH", "master")
770ee3c9eebSPatrick Williamsubuntu_mirror = os.environ.get("UBUNTU_MIRROR")
77123ec3323SAndrew Geisslerdocker_reg = os.environ.get("DOCKER_REG", "public.ecr.aws/ubuntu")
772ee3c9eebSPatrick Williamshttp_proxy = os.environ.get("http_proxy")
773ee3c9eebSPatrick Williams
77465b21fb9SPatrick Williamsgerrit_project = os.environ.get("GERRIT_PROJECT")
77565b21fb9SPatrick Williamsgerrit_rev = os.environ.get("GERRIT_PATCHSET_REVISION")
776276bd0e2SPatrick Williamsgerrit_topic = os.environ.get("GERRIT_TOPIC")
77765b21fb9SPatrick Williams
778d0dabc3eSAndrew Geissler# Ensure appropriate docker build output to see progress and identify
779d0dabc3eSAndrew Geissler# any issues
780d0dabc3eSAndrew Geissleros.environ["BUILDKIT_PROGRESS"] = "plain"
781d0dabc3eSAndrew Geissler
782ee3c9eebSPatrick Williams# Set up some common variables.
783ee3c9eebSPatrick Williamsusername = os.environ.get("USER", "root")
784ee3c9eebSPatrick Williamshomedir = os.environ.get("HOME", "/root")
785ee3c9eebSPatrick Williamsgid = os.getgid()
786ee3c9eebSPatrick Williamsuid = os.getuid()
787ee3c9eebSPatrick Williams
7886825a018SJosh Lehan# Use well-known constants if user is root
7896825a018SJosh Lehanif username == "root":
7906825a018SJosh Lehan    homedir = "/root"
7916825a018SJosh Lehan    gid = 0
7926825a018SJosh Lehan    uid = 0
7936825a018SJosh Lehan
79402871c91SPatrick Williams# Special flags if setting up a deb mirror.
79502871c91SPatrick Williamsmirror = ""
79602871c91SPatrick Williamsif "ubuntu" in distro and ubuntu_mirror:
79702871c91SPatrick Williams    mirror = f"""
798e08ffba8SPatrick WilliamsRUN echo "deb {ubuntu_mirror} \
799e08ffba8SPatrick Williams        $(. /etc/os-release && echo $VERSION_CODENAME) \
800e08ffba8SPatrick Williams        main restricted universe multiverse" > /etc/apt/sources.list && \\
801e08ffba8SPatrick Williams    echo "deb {ubuntu_mirror} \
802e08ffba8SPatrick Williams        $(. /etc/os-release && echo $VERSION_CODENAME)-updates \
803e08ffba8SPatrick Williams            main restricted universe multiverse" >> /etc/apt/sources.list && \\
804e08ffba8SPatrick Williams    echo "deb {ubuntu_mirror} \
805e08ffba8SPatrick Williams        $(. /etc/os-release && echo $VERSION_CODENAME)-security \
806e08ffba8SPatrick Williams            main restricted universe multiverse" >> /etc/apt/sources.list && \\
807e08ffba8SPatrick Williams    echo "deb {ubuntu_mirror} \
808e08ffba8SPatrick Williams        $(. /etc/os-release && echo $VERSION_CODENAME)-proposed \
809e08ffba8SPatrick Williams            main restricted universe multiverse" >> /etc/apt/sources.list && \\
810e08ffba8SPatrick Williams    echo "deb {ubuntu_mirror} \
811e08ffba8SPatrick Williams        $(. /etc/os-release && echo $VERSION_CODENAME)-backports \
812e08ffba8SPatrick Williams            main restricted universe multiverse" >> /etc/apt/sources.list
81302871c91SPatrick Williams"""
81402871c91SPatrick Williams
81502871c91SPatrick Williams# Special flags for proxying.
81602871c91SPatrick Williamsproxy_cmd = ""
81734ec77e8SAdrian Ambrożewiczproxy_keyserver = ""
81802871c91SPatrick Williamsproxy_args = []
81902871c91SPatrick Williamsif http_proxy:
82002871c91SPatrick Williams    proxy_cmd = f"""
82102871c91SPatrick WilliamsRUN echo "[http]" >> {homedir}/.gitconfig && \
82202871c91SPatrick Williams    echo "proxy = {http_proxy}" >> {homedir}/.gitconfig
8233aa71c8cSTan SiewertCOPY <<EOF_WGETRC {homedir}/.wgetrc
824f7e52612SLei YUhttps_proxy = {http_proxy}
825f7e52612SLei YUhttp_proxy = {http_proxy}
826f7e52612SLei YUuse_proxy = on
827f7e52612SLei YUEOF_WGETRC
82802871c91SPatrick Williams"""
82934ec77e8SAdrian Ambrożewicz    proxy_keyserver = f"--keyserver-options http-proxy={http_proxy}"
83034ec77e8SAdrian Ambrożewicz
83102871c91SPatrick Williams    proxy_args.extend(
83202871c91SPatrick Williams        [
83302871c91SPatrick Williams            "--build-arg",
83402871c91SPatrick Williams            f"http_proxy={http_proxy}",
83502871c91SPatrick Williams            "--build-arg",
836d461cd6aSLei YU            f"https_proxy={http_proxy}",
83702871c91SPatrick Williams        ]
83802871c91SPatrick Williams    )
83902871c91SPatrick Williams
840ee3c9eebSPatrick Williams# Create base Dockerfile.
841a18d9c57SPatrick Williamsdockerfile_base = f"""
842fe2768c7SAndrew GeisslerFROM {docker_reg}/{distro}
84302871c91SPatrick Williams
84402871c91SPatrick Williams{mirror}
84502871c91SPatrick Williams
84602871c91SPatrick WilliamsENV DEBIAN_FRONTEND noninteractive
84702871c91SPatrick Williams
8488949d3c3SPatrick WilliamsENV PYTHONPATH "/usr/local/lib/python3.10/site-packages/"
84902871c91SPatrick Williams
850bb16ac14SPatrick Williams# Sometimes the ubuntu key expires and we need a way to force an execution
851bb16ac14SPatrick Williams# of the apt-get commands for the dbgsym-keyring.  When this happens we see
852bb16ac14SPatrick Williams# an error like: "Release: The following signatures were invalid:"
853bb16ac14SPatrick Williams# Insert a bogus echo that we can change here when we get this error to force
854bb16ac14SPatrick Williams# the update.
855*a4a60c11SJames AthappillyRUN echo "ubuntu keyserver rev as of 2025-11-17"
856bb16ac14SPatrick Williams
85702871c91SPatrick Williams# We need the keys to be imported for dbgsym repos
85802871c91SPatrick Williams# New releases have a package, older ones fall back to manual fetching
85902871c91SPatrick Williams# https://wiki.ubuntu.com/Debug%20Symbol%20Packages
860575b5e4cSJagpal Singh Gill# Known issue with gpg to get keys via proxy -
861575b5e4cSJagpal Singh Gill# https://bugs.launchpad.net/ubuntu/+source/gnupg2/+bug/1788190, hence using
862575b5e4cSJagpal Singh Gill# curl to get keys.
86350837436SPatrick WilliamsRUN apt-get update && apt-get dist-upgrade -yy && \
864938d303fSJian Zhang    ( apt-get install -yy gpgv ubuntu-dbgsym-keyring || \
865575b5e4cSJagpal Singh Gill        ( apt-get install -yy dirmngr curl && \
866575b5e4cSJagpal Singh Gill          curl -sSL \
867575b5e4cSJagpal Singh Gill          'https://keyserver.ubuntu.com/pks/lookup?op=get&search=0xF2EDC64DC5AEE1F6B9C621F0C8CAB6595FDFF622' \
868575b5e4cSJagpal Singh Gill          | apt-key add - ))
86902871c91SPatrick Williams
87002871c91SPatrick Williams# Parse the current repo list into a debug repo list
871e08ffba8SPatrick WilliamsRUN sed -n '/^deb /s,^deb [^ ]* ,deb http://ddebs.ubuntu.com ,p' \
872e08ffba8SPatrick Williams        /etc/apt/sources.list >/etc/apt/sources.list.d/debug.list
87302871c91SPatrick Williams
87402871c91SPatrick Williams# Remove non-existent debug repos
87541d86218SPatrick WilliamsRUN sed -i '/-\\(backports\\|security\\) /d' /etc/apt/sources.list.d/debug.list
87602871c91SPatrick Williams
87702871c91SPatrick WilliamsRUN cat /etc/apt/sources.list.d/debug.list
87802871c91SPatrick Williams
87902871c91SPatrick WilliamsRUN apt-get update && apt-get dist-upgrade -yy && apt-get install -yy \
88058f1915eSAndrew Jeffery    abi-compliance-checker \
8818b112068SAndrew Jeffery    abi-dumper \
88202871c91SPatrick Williams    autoconf \
88302871c91SPatrick Williams    autoconf-archive \
884af49ed51SAndrew Geissler    bison \
885af49ed51SAndrew Geissler    cmake \
886af49ed51SAndrew Geissler    curl \
887af49ed51SAndrew Geissler    dbus \
888af49ed51SAndrew Geissler    device-tree-compiler \
8891c28d969SAndrew Jeffery    doxygen \
890af49ed51SAndrew Geissler    flex \
891af49ed51SAndrew Geissler    git \
892b4eec87bSPatrick Williams    glib-2.0 \
8936968e83eSPatrick Williams    gnupg \
89402871c91SPatrick Williams    iproute2 \
895af49ed51SAndrew Geissler    iputils-ping \
896524a331cSManojkiran Eda    libaudit-dev \
897af49ed51SAndrew Geissler    libc6-dbg \
898af49ed51SAndrew Geissler    libc6-dev \
899c7bc4d1dSPatrick Williams    libcjson-dev \
900af49ed51SAndrew Geissler    libconfig++-dev \
901af49ed51SAndrew Geissler    libcryptsetup-dev \
902a7a30551SAnirban Banerjee    libcurl4-openssl-dev \
903af49ed51SAndrew Geissler    libdbus-1-dev \
904af49ed51SAndrew Geissler    libevdev-dev \
905af49ed51SAndrew Geissler    libi2c-dev \
906af49ed51SAndrew Geissler    libjpeg-dev \
907af49ed51SAndrew Geissler    libjson-perl \
908af49ed51SAndrew Geissler    libldap2-dev \
909af49ed51SAndrew Geissler    libmimetic-dev \
9103ee62fb5SEwelina Walkusz    libmpfr-dev \
91102871c91SPatrick Williams    libnl-3-dev \
91202871c91SPatrick Williams    libnl-genl-3-dev \
91302871c91SPatrick Williams    libpam0g-dev \
91402871c91SPatrick Williams    libpciaccess-dev \
915af49ed51SAndrew Geissler    libperlio-gzip-perl \
916af49ed51SAndrew Geissler    libpng-dev \
917af49ed51SAndrew Geissler    libprotobuf-dev \
918af49ed51SAndrew Geissler    libsnmp-dev \
919af49ed51SAndrew Geissler    libssl-dev \
920af49ed51SAndrew Geissler    libsystemd-dev \
921af49ed51SAndrew Geissler    libtool \
922af49ed51SAndrew Geissler    liburing-dev \
92302871c91SPatrick Williams    libxml2-utils \
9240eedeedaSPatrick Williams    libxml-simple-perl \
9256968e83eSPatrick Williams    lsb-release \
926af49ed51SAndrew Geissler    ninja-build \
927af49ed51SAndrew Geissler    npm \
928af49ed51SAndrew Geissler    pkg-config \
929af49ed51SAndrew Geissler    protobuf-compiler \
930af49ed51SAndrew Geissler    python3 \
931af49ed51SAndrew Geissler    python3-dev\
932af49ed51SAndrew Geissler    python3-git \
933af49ed51SAndrew Geissler    python3-mako \
934af49ed51SAndrew Geissler    python3-pip \
93525ba1e2fSWilliam A. Kennington III    python3-protobuf \
936af49ed51SAndrew Geissler    python3-setuptools \
937af49ed51SAndrew Geissler    python3-socks \
938af49ed51SAndrew Geissler    python3-yaml \
9399adf68d6SJohn Wedig    rsync \
940af49ed51SAndrew Geissler    shellcheck \
9418dd1bfe6SEwelina Walkusz    socat \
9426968e83eSPatrick Williams    software-properties-common \
943af49ed51SAndrew Geissler    sudo \
944af49ed51SAndrew Geissler    systemd \
945917b1774SPatrick Williams    systemd-dev \
946af49ed51SAndrew Geissler    valgrind \
947b565f825SAndrew Geissler    vim \
948af49ed51SAndrew Geissler    wget \
949af49ed51SAndrew Geissler    xxd
95002871c91SPatrick Williams
951e347f825SPatrick Williams# Add the ubuntu-toolchain-r repository for later versions of GCC and install.
952e347f825SPatrick WilliamsRUN add-apt-repository ppa:ubuntu-toolchain-r/ppa && \
953e347f825SPatrick Williams    apt-get update && \
954e347f825SPatrick Williams    apt-get install -y \
955e347f825SPatrick Williams        gcc-15 \
956e347f825SPatrick Williams        g++-15 \
957e347f825SPatrick Williams        libstdc++-15-dev
958e347f825SPatrick Williams
959ea1bfb27SPatrick WilliamsRUN update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-15 15 \
960ea1bfb27SPatrick Williams  --slave /usr/bin/g++ g++ /usr/bin/g++-15 \
961ea1bfb27SPatrick Williams  --slave /usr/bin/gcov gcov /usr/bin/gcov-15 \
962ea1bfb27SPatrick Williams  --slave /usr/bin/gcov-dump gcov-dump /usr/bin/gcov-dump-15 \
963ea1bfb27SPatrick Williams  --slave /usr/bin/gcov-tool gcov-tool /usr/bin/gcov-tool-15
964961f148bSPatrick WilliamsRUN update-alternatives --remove cpp /usr/bin/cpp && \
965ea1bfb27SPatrick Williams    update-alternatives --install /usr/bin/cpp cpp /usr/bin/cpp-15 15
96602871c91SPatrick Williams
9676968e83eSPatrick Williams# Set up LLVM apt repository.
968eae557cfSAndrew GeisslerRUN bash -c "$(wget -O - https://apt.llvm.org/llvm.sh)" -- 21 -m https://apt.llvm.org
9696968e83eSPatrick Williams
9706968e83eSPatrick Williams# Install extra clang tools
971ed8aecafSPatrick WilliamsRUN apt-get install -y \
972e31ec4e3SPatrick Williams        clang-21 \
973e31ec4e3SPatrick Williams        clang-format-21 \
974e31ec4e3SPatrick Williams        clang-tidy-21 \
975e31ec4e3SPatrick Williams        lld-21
9766968e83eSPatrick Williams
977e31ec4e3SPatrick WilliamsRUN update-alternatives --install /usr/bin/clang clang /usr/bin/clang-21 1000 \
978e31ec4e3SPatrick Williams  --slave /usr/bin/clang++ clang++ /usr/bin/clang++-21 \
979e31ec4e3SPatrick Williams  --slave /usr/bin/clang-tidy clang-tidy /usr/bin/clang-tidy-21 \
980c5f92c9fSPatrick Williams  --slave /usr/bin/clang-apply-replacements clang-apply-replacements \
981c5f92c9fSPatrick Williams        /usr/bin/clang-apply-replacements-21 \
982e31ec4e3SPatrick Williams  --slave /usr/bin/clang-format clang-format /usr/bin/clang-format-21 \
983e08ffba8SPatrick Williams  --slave /usr/bin/run-clang-tidy run-clang-tidy.py \
984e31ec4e3SPatrick Williams        /usr/bin/run-clang-tidy-21 \
985e31ec4e3SPatrick Williams  --slave /usr/bin/scan-build scan-build /usr/bin/scan-build-21 \
986e31ec4e3SPatrick Williams  --slave /usr/bin/lld lld /usr/bin/lld-21
98702871c91SPatrick Williams
98850837436SPatrick Williams"""
98950837436SPatrick Williams
99050837436SPatrick Williamsif is_automated_ci_build:
99150837436SPatrick Williams    dockerfile_base += f"""
992a6ebc6e2SManojkiran Eda# Run an arbitrary command to pollute the docker cache regularly force us
99350837436SPatrick Williams# to re-run `apt-get update` daily.
994ee3c9eebSPatrick WilliamsRUN echo {Docker.timestamp()}
99550837436SPatrick WilliamsRUN apt-get update && apt-get dist-upgrade -yy
99650837436SPatrick Williams
99750837436SPatrick Williams"""
99850837436SPatrick Williams
99941d86218SPatrick Williamsdockerfile_base += """
10005e4d8402SPatrick WilliamsRUN pip3 install --break-system-packages \
10011a484329SPatrick Williams        beautysh==6.2.1 \
1002818023dfSPatrick Williams        black \
1003818023dfSPatrick Williams        codespell \
1004818023dfSPatrick Williams        flake8 \
10052d8c551fSEwelina Walkusz        gcovr \
1006818023dfSPatrick Williams        gitlint \
1007818023dfSPatrick Williams        inflection \
1008f7381ad6SArya K Padman        isoduration \
1009818023dfSPatrick Williams        isort \
1010818023dfSPatrick Williams        jsonschema \
101182425ecaSEd Tanous        meson==1.9.0 \
10129fdba2d2SPatrick Williams        referencing \
1013818023dfSPatrick Williams        requests
1014b08ddf77SPatrick Williams
1015b08ddf77SPatrick WilliamsRUN npm install -g \
1016d0757deaSXinnan Xie        eslint@v8.56.0 eslint-plugin-json@v3.1.0 \
10177d41f6d2SPatrick Williams        markdownlint-cli@latest \
1018b08ddf77SPatrick Williams        prettier@latest
1019fb9948a3SEd Tanous"""
1020fb9948a3SEd Tanous
1021ee3c9eebSPatrick Williams# Build the base and stage docker images.
1022ee3c9eebSPatrick Williamsdocker_base_img_name = Docker.tagname("base", dockerfile_base)
1023ee3c9eebSPatrick WilliamsDocker.build("base", docker_base_img_name, dockerfile_base)
1024ee3c9eebSPatrick WilliamsPackage.generate_all()
102502871c91SPatrick Williams
1026ee3c9eebSPatrick Williams# Create the final Dockerfile.
1027a18d9c57SPatrick Williamsdockerfile = f"""
102802871c91SPatrick Williams# Build the final output image
1029a18d9c57SPatrick WilliamsFROM {docker_base_img_name}
1030ee3c9eebSPatrick Williams{Package.df_all_copycmds()}
103102871c91SPatrick Williams
103202871c91SPatrick Williams# Some of our infrastructure still relies on the presence of this file
103302871c91SPatrick Williams# even though it is no longer needed to rebuild the docker environment
103402871c91SPatrick Williams# NOTE: The file is sorted to ensure the ordering is stable.
1035ee3c9eebSPatrick WilliamsRUN echo '{Package.depcache()}' > /tmp/depcache
103602871c91SPatrick Williams
103767cc0616SPatrick Williams# Ensure the group, user, and home directory are created (or rename them if
103867cc0616SPatrick Williams# they already exist).
103967cc0616SPatrick WilliamsRUN if grep -q ":{gid}:" /etc/group ; then \
104067cc0616SPatrick Williams        groupmod -n {username} $(awk -F : '{{ if ($3 == {gid}) {{ print $1 }} }}' /etc/group) ; \
104167cc0616SPatrick Williams    else \
104267cc0616SPatrick Williams        groupadd -f -g {gid} {username} ; \
104367cc0616SPatrick Williams    fi
104402871c91SPatrick WilliamsRUN mkdir -p "{os.path.dirname(homedir)}"
104567cc0616SPatrick WilliamsRUN if grep -q ":{uid}:" /etc/passwd ; then \
104673b3ee91SPatrick Williams        usermod -l {username} -d {homedir} -m $(awk -F : '{{ if ($3 == {uid}) {{ print $1 }} }}' /etc/passwd) ; \
104767cc0616SPatrick Williams    else \
104867cc0616SPatrick Williams        useradd -d {homedir} -m -u {uid} -g {gid} {username} ; \
104967cc0616SPatrick Williams    fi
105002871c91SPatrick WilliamsRUN sed -i '1iDefaults umask=000' /etc/sudoers
105102871c91SPatrick WilliamsRUN echo "{username} ALL=(ALL) NOPASSWD: ALL" >>/etc/sudoers
105202871c91SPatrick Williams
1053305a9a5dSAndrew Geissler# Ensure user has ability to write to /usr/local for different tool
1054305a9a5dSAndrew Geissler# and data installs
10557bb00b13SAndrew GeisslerRUN chown -R {username}:{username} /usr/local/share
1056305a9a5dSAndrew Geissler
1057ab4fee83SJonathan Doman# Update library cache
1058ab4fee83SJonathan DomanRUN ldconfig
1059ab4fee83SJonathan Doman
106002871c91SPatrick Williams{proxy_cmd}
106102871c91SPatrick Williams
106202871c91SPatrick WilliamsRUN /bin/bash
106302871c91SPatrick Williams"""
106402871c91SPatrick Williams
1065a18d9c57SPatrick Williams# Do the final docker build
1066ee3c9eebSPatrick Williamsdocker_final_img_name = Docker.tagname(None, dockerfile)
1067ee3c9eebSPatrick WilliamsDocker.build("final", docker_final_img_name, dockerfile)
1068ee3c9eebSPatrick Williams
106900536fbeSPatrick Williams# Print the tag of the final image.
107000536fbeSPatrick Williamsprint(docker_final_img_name)
1071