xref: /openbmc/openbmc-build-scripts/scripts/build-unit-test-docker (revision 54d01da45eded8a9d8e736e46c7c275039e09ca8)
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.
2002871c91SPatrick Williams#   http_proxy        The HTTP address of the proxy server to connect to.
2102871c91SPatrick Williams#                     Default: "", proxy is not setup if this is not set
2202871c91SPatrick Williams
2302871c91SPatrick Williamsimport os
24f3d27e64SAndrew Geisslerimport re
2502871c91SPatrick Williamsimport sys
26b16f3e20SPatrick Williamsimport threading
27a18d9c57SPatrick Williamsfrom datetime import date
28a18d9c57SPatrick Williamsfrom hashlib import sha256
29e08ffba8SPatrick Williams
30e08ffba8SPatrick Williams# typing.Dict is used for type-hints.
31e08ffba8SPatrick Williamsfrom typing import Any, Callable, Dict, Iterable, Optional  # noqa: F401
3202871c91SPatrick Williams
3341d86218SPatrick Williamsfrom sh import docker, git, nproc, uname  # type: ignore
3441d86218SPatrick Williams
35ee3c9eebSPatrick Williamstry:
36ee3c9eebSPatrick Williams    # Python before 3.8 doesn't have TypedDict, so reroute to standard 'dict'.
37ee3c9eebSPatrick Williams    from typing import TypedDict
3841d86218SPatrick Williamsexcept Exception:
39ee3c9eebSPatrick Williams
40ee3c9eebSPatrick Williams    class TypedDict(dict):  # type: ignore
41ee3c9eebSPatrick Williams        # We need to do this to eat the 'total' argument.
4241d86218SPatrick Williams        def __init_subclass__(cls, **kwargs: Any) -> None:
43ee3c9eebSPatrick Williams            super().__init_subclass__()
44ee3c9eebSPatrick Williams
45ee3c9eebSPatrick Williams
46ee3c9eebSPatrick Williams# Declare some variables used in package definitions.
47aae36d18SPatrick Williamsprefix = "/usr/local"
4802871c91SPatrick Williamsproc_count = nproc().strip()
4902871c91SPatrick Williams
50ee3c9eebSPatrick Williams
51ee3c9eebSPatrick Williamsclass PackageDef(TypedDict, total=False):
52ee3c9eebSPatrick Williams    """Package Definition for packages dictionary."""
53ee3c9eebSPatrick Williams
54ee3c9eebSPatrick Williams    # rev [optional]: Revision of package to use.
55ee3c9eebSPatrick Williams    rev: str
56ee3c9eebSPatrick Williams    # url [optional]: lambda function to create URL: (package, rev) -> url.
57ee3c9eebSPatrick Williams    url: Callable[[str, str], str]
58ee3c9eebSPatrick Williams    # depends [optional]: List of package dependencies.
59ee3c9eebSPatrick Williams    depends: Iterable[str]
60ee3c9eebSPatrick Williams    # build_type [required]: Build type used for package.
61ee3c9eebSPatrick Williams    #   Currently supported: autoconf, cmake, custom, make, meson
62ee3c9eebSPatrick Williams    build_type: str
63ee3c9eebSPatrick Williams    # build_steps [optional]: Steps to run for 'custom' build_type.
64ee3c9eebSPatrick Williams    build_steps: Iterable[str]
65ee3c9eebSPatrick Williams    # config_flags [optional]: List of options to pass configuration tool.
66ee3c9eebSPatrick Williams    config_flags: Iterable[str]
67ee3c9eebSPatrick Williams    # config_env [optional]: List of environment variables to set for config.
68ee3c9eebSPatrick Williams    config_env: Iterable[str]
69ee3c9eebSPatrick Williams    # custom_post_dl [optional]: List of steps to run after download, but
70ee3c9eebSPatrick Williams    #   before config / build / install.
71ee3c9eebSPatrick Williams    custom_post_dl: Iterable[str]
726bce2ca1SPatrick Williams    # custom_post_install [optional]: List of steps to run after install.
736bce2ca1SPatrick Williams    custom_post_install: Iterable[str]
74ee3c9eebSPatrick Williams
75ee3c9eebSPatrick Williams    # __tag [private]: Generated Docker tag name for package stage.
76ee3c9eebSPatrick Williams    __tag: str
77ee3c9eebSPatrick Williams    # __package [private]: Package object associated with this package.
78ee3c9eebSPatrick Williams    __package: Any  # Type is Package, but not defined yet.
79ee3c9eebSPatrick Williams
8002871c91SPatrick Williams
817204324cSPatrick Williams# Packages to include in image.
827204324cSPatrick Williamspackages = {
83ee3c9eebSPatrick Williams    "boost": PackageDef(
8405806f5eSAndrew Geissler        rev="1.84.0",
85ee3c9eebSPatrick Williams        url=(
8638b46870SAndrew Geissler            lambda pkg, rev: f"https://github.com/boostorg/{pkg}/releases/download/{pkg}-{rev}/{pkg}-{rev}.tar.gz"
872abc4a48SPatrick Williams        ),
88ee3c9eebSPatrick Williams        build_type="custom",
89ee3c9eebSPatrick Williams        build_steps=[
90e08ffba8SPatrick Williams            (
91e08ffba8SPatrick Williams                "./bootstrap.sh"
9242ff4328SEd Tanous                f" --prefix={prefix} --with-libraries=context,coroutine,url"
93e08ffba8SPatrick Williams            ),
94aae36d18SPatrick Williams            "./b2",
9504770ccdSMichal Orzel            f"./b2 install --prefix={prefix} valgrind=on",
96aae36d18SPatrick Williams        ],
97ee3c9eebSPatrick Williams    ),
98ee3c9eebSPatrick Williams    "USCiLab/cereal": PackageDef(
99c1977839SPatrick Williams        rev="v1.3.2",
100ee3c9eebSPatrick Williams        build_type="custom",
101ee3c9eebSPatrick Williams        build_steps=[f"cp -a include/cereal/ {prefix}/include/"],
102ee3c9eebSPatrick Williams    ),
103c7198558SEd Tanous    "danmar/cppcheck": PackageDef(
10451021786SPatrick Williams        rev="2.12.1",
105c7198558SEd Tanous        build_type="cmake",
106c7198558SEd Tanous    ),
107ee3c9eebSPatrick Williams    "CLIUtils/CLI11": PackageDef(
108fc39733aSPatrick Williams        rev="v2.3.2",
109ee3c9eebSPatrick Williams        build_type="cmake",
110ee3c9eebSPatrick Williams        config_flags=[
111aae36d18SPatrick Williams            "-DBUILD_TESTING=OFF",
112aae36d18SPatrick Williams            "-DCLI11_BUILD_DOCS=OFF",
113aae36d18SPatrick Williams            "-DCLI11_BUILD_EXAMPLES=OFF",
114aae36d18SPatrick Williams        ],
115ee3c9eebSPatrick Williams    ),
116ee3c9eebSPatrick Williams    "fmtlib/fmt": PackageDef(
117c061e07bSPatrick Williams        rev="10.1.1",
118ee3c9eebSPatrick Williams        build_type="cmake",
119ee3c9eebSPatrick Williams        config_flags=[
120aae36d18SPatrick Williams            "-DFMT_DOC=OFF",
121aae36d18SPatrick Williams            "-DFMT_TEST=OFF",
122aae36d18SPatrick Williams        ],
123ee3c9eebSPatrick Williams    ),
124ee3c9eebSPatrick Williams    "Naios/function2": PackageDef(
125cb09974cSPatrick Williams        rev="4.2.4",
126ee3c9eebSPatrick Williams        build_type="custom",
127ee3c9eebSPatrick Williams        build_steps=[
128aae36d18SPatrick Williams            f"mkdir {prefix}/include/function2",
129aae36d18SPatrick Williams            f"cp include/function2/function2.hpp {prefix}/include/function2/",
130aae36d18SPatrick Williams        ],
131ee3c9eebSPatrick Williams    ),
132ee3c9eebSPatrick Williams    "google/googletest": PackageDef(
133d11e9c75SPatrick Williams        rev="v1.15.2",
134ee3c9eebSPatrick Williams        build_type="cmake",
1354dd32c02SWilliam A. Kennington III        config_env=["CXXFLAGS=-std=c++20"],
136ee3c9eebSPatrick Williams        config_flags=["-DTHREADS_PREFER_PTHREAD_FLAG=ON"],
137ee3c9eebSPatrick Williams    ),
138178b4b29SEd Tanous    "nghttp2/nghttp2": PackageDef(
139abb106a9SEd Tanous        rev="v1.61.0",
140178b4b29SEd Tanous        build_type="cmake",
141178b4b29SEd Tanous        config_env=["CXXFLAGS=-std=c++20"],
142178b4b29SEd Tanous        config_flags=[
143178b4b29SEd Tanous            "-DENABLE_LIB_ONLY=ON",
144178b4b29SEd Tanous            "-DENABLE_STATIC_LIB=ON",
145178b4b29SEd Tanous        ],
146178b4b29SEd Tanous    ),
147ee3c9eebSPatrick Williams    "nlohmann/json": PackageDef(
148c1977839SPatrick Williams        rev="v3.11.2",
1496bce2ca1SPatrick Williams        build_type="cmake",
1506bce2ca1SPatrick Williams        config_flags=["-DJSON_BuildTests=OFF"],
1516bce2ca1SPatrick Williams        custom_post_install=[
152e08ffba8SPatrick Williams            (
153e08ffba8SPatrick Williams                f"ln -s {prefix}/include/nlohmann/json.hpp"
154e08ffba8SPatrick Williams                f" {prefix}/include/json.hpp"
155e08ffba8SPatrick Williams            ),
156aae36d18SPatrick Williams        ],
157ee3c9eebSPatrick Williams    ),
158058e3a34SPrzemyslaw Czarnowski    "json-c/json-c": PackageDef(
159eee65beeSPatrick Williams        rev="json-c-0.17-20230812",
160058e3a34SPrzemyslaw Czarnowski        build_type="cmake",
161058e3a34SPrzemyslaw Czarnowski    ),
162ee3c9eebSPatrick Williams    "LibVNC/libvncserver": PackageDef(
163c042132cSPatrick Williams        rev="LibVNCServer-0.9.14",
164ee3c9eebSPatrick Williams        build_type="cmake",
165ee3c9eebSPatrick Williams    ),
166ee3c9eebSPatrick Williams    "leethomason/tinyxml2": PackageDef(
167c1977839SPatrick Williams        rev="9.0.0",
168ee3c9eebSPatrick Williams        build_type="cmake",
169ee3c9eebSPatrick Williams    ),
170ee3c9eebSPatrick Williams    "tristanpenman/valijson": PackageDef(
1715a2c113cSPatrick Williams        rev="v1.0.1",
172ee3c9eebSPatrick Williams        build_type="cmake",
173ee3c9eebSPatrick Williams        config_flags=[
1740eedeedaSPatrick Williams            "-Dvalijson_BUILD_TESTS=0",
1750eedeedaSPatrick Williams            "-Dvalijson_INSTALL_HEADERS=1",
176aae36d18SPatrick Williams        ],
177ee3c9eebSPatrick Williams    ),
178ee3c9eebSPatrick Williams    "open-power/pdbg": PackageDef(build_type="autoconf"),
179ee3c9eebSPatrick Williams    "openbmc/gpioplus": PackageDef(
180ee3c9eebSPatrick Williams        build_type="meson",
181ee3c9eebSPatrick Williams        config_flags=[
182aae36d18SPatrick Williams            "-Dexamples=false",
183aae36d18SPatrick Williams            "-Dtests=disabled",
184aae36d18SPatrick Williams        ],
185ee3c9eebSPatrick Williams    ),
186ee3c9eebSPatrick Williams    "openbmc/phosphor-dbus-interfaces": PackageDef(
187ee3c9eebSPatrick Williams        depends=["openbmc/sdbusplus"],
188ee3c9eebSPatrick Williams        build_type="meson",
1894fe87776SWilliam A. Kennington III        config_flags=["-Dgenerate_md=false"],
190ee3c9eebSPatrick Williams    ),
191ee3c9eebSPatrick Williams    "openbmc/phosphor-logging": PackageDef(
192ee3c9eebSPatrick Williams        depends=[
19383394610SPatrick Williams            "USCiLab/cereal",
19483394610SPatrick Williams            "openbmc/phosphor-dbus-interfaces",
19583394610SPatrick Williams            "openbmc/sdbusplus",
19683394610SPatrick Williams            "openbmc/sdeventplus",
197aae36d18SPatrick Williams        ],
198f79ce4c4SPatrick Williams        build_type="meson",
199ee3c9eebSPatrick Williams        config_flags=[
2006c98f280SWilliam A. Kennington III            "-Dlibonly=true",
2016c98f280SWilliam A. Kennington III            "-Dtests=disabled",
2025eabdae9SPatrick Williams            f"-Dyamldir={prefix}/share/phosphor-dbus-yaml/yaml",
203aae36d18SPatrick Williams        ],
204ee3c9eebSPatrick Williams    ),
205ee3c9eebSPatrick Williams    "openbmc/phosphor-objmgr": PackageDef(
206ee3c9eebSPatrick Williams        depends=[
20711e5762cSBrad Bishop            "CLIUtils/CLI11",
20870af95caSPatrick Williams            "boost",
20983394610SPatrick Williams            "leethomason/tinyxml2",
21070af95caSPatrick Williams            "openbmc/phosphor-dbus-interfaces",
21183394610SPatrick Williams            "openbmc/phosphor-logging",
21283394610SPatrick Williams            "openbmc/sdbusplus",
213aae36d18SPatrick Williams        ],
2141197e359SBrad Bishop        build_type="meson",
2151197e359SBrad Bishop        config_flags=[
2161197e359SBrad Bishop            "-Dtests=disabled",
2171197e359SBrad Bishop        ],
218ee3c9eebSPatrick Williams    ),
219c02ff271SJason M. Bills    "openbmc/libpeci": PackageDef(
220c02ff271SJason M. Bills        build_type="meson",
221c02ff271SJason M. Bills        config_flags=[
222c02ff271SJason M. Bills            "-Draw-peci=disabled",
223c02ff271SJason M. Bills        ],
224c02ff271SJason M. Bills    ),
2251c19e453SManojkiran Eda    "openbmc/libpldm": PackageDef(
226ee3c9eebSPatrick Williams        build_type="meson",
227ee3c9eebSPatrick Williams        config_flags=[
22829d69bb0SAndrew Jeffery            "-Dabi=deprecated,stable",
229aae36d18SPatrick Williams            "-Doem-ibm=enabled",
230aae36d18SPatrick Williams            "-Dtests=disabled",
231aae36d18SPatrick Williams        ],
232ee3c9eebSPatrick Williams    ),
233ee3c9eebSPatrick Williams    "openbmc/sdbusplus": PackageDef(
234*54d01da4SPatrick Williams        depends=[
235*54d01da4SPatrick Williams            "nlohmann/json",
236*54d01da4SPatrick Williams        ],
237ee3c9eebSPatrick Williams        build_type="meson",
238ee3c9eebSPatrick Williams        custom_post_dl=[
239aae36d18SPatrick Williams            "cd tools",
240aae36d18SPatrick Williams            f"./setup.py install --root=/ --prefix={prefix}",
241aae36d18SPatrick Williams            "cd ..",
242aae36d18SPatrick Williams        ],
243ee3c9eebSPatrick Williams        config_flags=[
244aae36d18SPatrick Williams            "-Dexamples=disabled",
245aae36d18SPatrick Williams            "-Dtests=disabled",
246aae36d18SPatrick Williams        ],
247b16f3e20SPatrick Williams    ),
248ee3c9eebSPatrick Williams    "openbmc/sdeventplus": PackageDef(
24970af95caSPatrick Williams        depends=[
25070af95caSPatrick Williams            "openbmc/stdplus",
25170af95caSPatrick Williams        ],
252ee3c9eebSPatrick Williams        build_type="meson",
253ee3c9eebSPatrick Williams        config_flags=[
254ee3c9eebSPatrick Williams            "-Dexamples=false",
255ee3c9eebSPatrick Williams            "-Dtests=disabled",
256ee3c9eebSPatrick Williams        ],
257ee3c9eebSPatrick Williams    ),
258ee3c9eebSPatrick Williams    "openbmc/stdplus": PackageDef(
25970af95caSPatrick Williams        depends=[
26070af95caSPatrick Williams            "fmtlib/fmt",
261ca1bf0c0SWilliam A. Kennington III            "google/googletest",
262ca1bf0c0SWilliam A. Kennington III            "Naios/function2",
26370af95caSPatrick Williams        ],
264ee3c9eebSPatrick Williams        build_type="meson",
265ee3c9eebSPatrick Williams        config_flags=[
266ee3c9eebSPatrick Williams            "-Dexamples=false",
267ee3c9eebSPatrick Williams            "-Dtests=disabled",
268ca1bf0c0SWilliam A. Kennington III            "-Dgtest=enabled",
269ee3c9eebSPatrick Williams        ],
270ee3c9eebSPatrick Williams    ),
271ee3c9eebSPatrick Williams}  # type: Dict[str, PackageDef]
27202871c91SPatrick Williams
27302871c91SPatrick Williams# Define common flags used for builds
27402871c91SPatrick Williamsconfigure_flags = " ".join(
27502871c91SPatrick Williams    [
27602871c91SPatrick Williams        f"--prefix={prefix}",
27702871c91SPatrick Williams    ]
27802871c91SPatrick Williams)
27902871c91SPatrick Williamscmake_flags = " ".join(
28002871c91SPatrick Williams    [
28102871c91SPatrick Williams        "-DBUILD_SHARED_LIBS=ON",
2820f2086b3SPatrick Williams        "-DCMAKE_BUILD_TYPE=RelWithDebInfo",
28302871c91SPatrick Williams        f"-DCMAKE_INSTALL_PREFIX:PATH={prefix}",
2840f2086b3SPatrick Williams        "-GNinja",
2850f2086b3SPatrick Williams        "-DCMAKE_MAKE_PROGRAM=ninja",
28602871c91SPatrick Williams    ]
28702871c91SPatrick Williams)
28802871c91SPatrick Williamsmeson_flags = " ".join(
28902871c91SPatrick Williams    [
29002871c91SPatrick Williams        "--wrap-mode=nodownload",
29102871c91SPatrick Williams        f"-Dprefix={prefix}",
29202871c91SPatrick Williams    ]
29302871c91SPatrick Williams)
29402871c91SPatrick Williams
295ee3c9eebSPatrick Williams
296ee3c9eebSPatrick Williamsclass Package(threading.Thread):
297ee3c9eebSPatrick Williams    """Class used to build the Docker stages for each package.
298ee3c9eebSPatrick Williams
299ee3c9eebSPatrick Williams    Generally, this class should not be instantiated directly but through
300ee3c9eebSPatrick Williams    Package.generate_all().
301ee3c9eebSPatrick Williams    """
302ee3c9eebSPatrick Williams
303ee3c9eebSPatrick Williams    # Copy the packages dictionary.
304ee3c9eebSPatrick Williams    packages = packages.copy()
305ee3c9eebSPatrick Williams
306ee3c9eebSPatrick Williams    # Lock used for thread-safety.
307ee3c9eebSPatrick Williams    lock = threading.Lock()
308ee3c9eebSPatrick Williams
309ee3c9eebSPatrick Williams    def __init__(self, pkg: str):
310ee3c9eebSPatrick Williams        """pkg - The name of this package (ex. foo/bar )"""
311ee3c9eebSPatrick Williams        super(Package, self).__init__()
312ee3c9eebSPatrick Williams
313ee3c9eebSPatrick Williams        self.package = pkg
314ee3c9eebSPatrick Williams        self.exception = None  # type: Optional[Exception]
315ee3c9eebSPatrick Williams
316ee3c9eebSPatrick Williams        # Reference to this package's
317ee3c9eebSPatrick Williams        self.pkg_def = Package.packages[pkg]
318ee3c9eebSPatrick Williams        self.pkg_def["__package"] = self
319ee3c9eebSPatrick Williams
320ee3c9eebSPatrick Williams    def run(self) -> None:
321ee3c9eebSPatrick Williams        """Thread 'run' function.  Builds the Docker stage."""
322ee3c9eebSPatrick Williams
323ee3c9eebSPatrick Williams        # In case this package has no rev, fetch it from Github.
324ee3c9eebSPatrick Williams        self._update_rev()
325ee3c9eebSPatrick Williams
326ee3c9eebSPatrick Williams        # Find all the Package objects that this package depends on.
327ee3c9eebSPatrick Williams        #   This section is locked because we are looking into another
328ee3c9eebSPatrick Williams        #   package's PackageDef dict, which could be being modified.
329ee3c9eebSPatrick Williams        Package.lock.acquire()
330ee3c9eebSPatrick Williams        deps: Iterable[Package] = [
331ee3c9eebSPatrick Williams            Package.packages[deppkg]["__package"]
332ee3c9eebSPatrick Williams            for deppkg in self.pkg_def.get("depends", [])
333ee3c9eebSPatrick Williams        ]
334ee3c9eebSPatrick Williams        Package.lock.release()
335ee3c9eebSPatrick Williams
336ee3c9eebSPatrick Williams        # Wait until all the depends finish building.  We need them complete
337ee3c9eebSPatrick Williams        # for the "COPY" commands.
338ee3c9eebSPatrick Williams        for deppkg in deps:
339ee3c9eebSPatrick Williams            deppkg.join()
340ee3c9eebSPatrick Williams
341ee3c9eebSPatrick Williams        # Generate this package's Dockerfile.
342ee3c9eebSPatrick Williams        dockerfile = f"""
343ee3c9eebSPatrick WilliamsFROM {docker_base_img_name}
344ee3c9eebSPatrick Williams{self._df_copycmds()}
345ee3c9eebSPatrick Williams{self._df_build()}
346ee3c9eebSPatrick Williams"""
347ee3c9eebSPatrick Williams
348ee3c9eebSPatrick Williams        # Generate the resulting tag name and save it to the PackageDef.
349ee3c9eebSPatrick Williams        #   This section is locked because we are modifying the PackageDef,
350ee3c9eebSPatrick Williams        #   which can be accessed by other threads.
351ee3c9eebSPatrick Williams        Package.lock.acquire()
352ee3c9eebSPatrick Williams        tag = Docker.tagname(self._stagename(), dockerfile)
353ee3c9eebSPatrick Williams        self.pkg_def["__tag"] = tag
354ee3c9eebSPatrick Williams        Package.lock.release()
355ee3c9eebSPatrick Williams
356ee3c9eebSPatrick Williams        # Do the build / save any exceptions.
357ee3c9eebSPatrick Williams        try:
358ee3c9eebSPatrick Williams            Docker.build(self.package, tag, dockerfile)
359ee3c9eebSPatrick Williams        except Exception as e:
360ee3c9eebSPatrick Williams            self.exception = e
361ee3c9eebSPatrick Williams
362ee3c9eebSPatrick Williams    @classmethod
363ee3c9eebSPatrick Williams    def generate_all(cls) -> None:
364ee3c9eebSPatrick Williams        """Ensure a Docker stage is created for all defined packages.
365ee3c9eebSPatrick Williams
366ee3c9eebSPatrick Williams        These are done in parallel but with appropriate blocking per
367ee3c9eebSPatrick Williams        package 'depends' specifications.
368ee3c9eebSPatrick Williams        """
369ee3c9eebSPatrick Williams
370ee3c9eebSPatrick Williams        # Create a Package for each defined package.
371ee3c9eebSPatrick Williams        pkg_threads = [Package(p) for p in cls.packages.keys()]
372ee3c9eebSPatrick Williams
373ee3c9eebSPatrick Williams        # Start building them all.
3746dbd7807SPatrick Williams        #   This section is locked because threads depend on each other,
3756dbd7807SPatrick Williams        #   based on the packages, and they cannot 'join' on a thread
3766dbd7807SPatrick Williams        #   which is not yet started.  Adding a lock here allows all the
3776dbd7807SPatrick Williams        #   threads to start before they 'join' their dependencies.
3786dbd7807SPatrick Williams        Package.lock.acquire()
379ee3c9eebSPatrick Williams        for t in pkg_threads:
380ee3c9eebSPatrick Williams            t.start()
3816dbd7807SPatrick Williams        Package.lock.release()
382ee3c9eebSPatrick Williams
383ee3c9eebSPatrick Williams        # Wait for completion.
384ee3c9eebSPatrick Williams        for t in pkg_threads:
385ee3c9eebSPatrick Williams            t.join()
386ee3c9eebSPatrick Williams            # Check if the thread saved off its own exception.
387ee3c9eebSPatrick Williams            if t.exception:
388ee3c9eebSPatrick Williams                print(f"Package {t.package} failed!", file=sys.stderr)
389ee3c9eebSPatrick Williams                raise t.exception
390ee3c9eebSPatrick Williams
391ee3c9eebSPatrick Williams    @staticmethod
392ee3c9eebSPatrick Williams    def df_all_copycmds() -> str:
393ee3c9eebSPatrick Williams        """Formulate the Dockerfile snippet necessary to copy all packages
394ee3c9eebSPatrick Williams        into the final image.
395ee3c9eebSPatrick Williams        """
396ee3c9eebSPatrick Williams        return Package.df_copycmds_set(Package.packages.keys())
397ee3c9eebSPatrick Williams
398ee3c9eebSPatrick Williams    @classmethod
399ee3c9eebSPatrick Williams    def depcache(cls) -> str:
400ee3c9eebSPatrick Williams        """Create the contents of the '/tmp/depcache'.
401ee3c9eebSPatrick Williams        This file is a comma-separated list of "<pkg>:<rev>".
402ee3c9eebSPatrick Williams        """
403ee3c9eebSPatrick Williams
404ee3c9eebSPatrick Williams        # This needs to be sorted for consistency.
405ee3c9eebSPatrick Williams        depcache = ""
406ee3c9eebSPatrick Williams        for pkg in sorted(cls.packages.keys()):
407ee3c9eebSPatrick Williams            depcache += "%s:%s," % (pkg, cls.packages[pkg]["rev"])
408ee3c9eebSPatrick Williams        return depcache
409ee3c9eebSPatrick Williams
410ee3c9eebSPatrick Williams    def _update_rev(self) -> None:
411ee3c9eebSPatrick Williams        """Look up the HEAD for missing a static rev."""
412ee3c9eebSPatrick Williams
413ee3c9eebSPatrick Williams        if "rev" in self.pkg_def:
414ee3c9eebSPatrick Williams            return
415ee3c9eebSPatrick Williams
41665b21fb9SPatrick Williams        # Check if Jenkins/Gerrit gave us a revision and use it.
41765b21fb9SPatrick Williams        if gerrit_project == self.package and gerrit_rev:
41865b21fb9SPatrick Williams            print(
41965b21fb9SPatrick Williams                f"Found Gerrit revision for {self.package}: {gerrit_rev}",
42065b21fb9SPatrick Williams                file=sys.stderr,
42165b21fb9SPatrick Williams            )
42265b21fb9SPatrick Williams            self.pkg_def["rev"] = gerrit_rev
42365b21fb9SPatrick Williams            return
42465b21fb9SPatrick Williams
425ee3c9eebSPatrick Williams        # Ask Github for all the branches.
42605fb2a0aSPatrick Williams        lookup = git(
42705fb2a0aSPatrick Williams            "ls-remote", "--heads", f"https://github.com/{self.package}"
42805fb2a0aSPatrick Williams        )
429ee3c9eebSPatrick Williams
430ee3c9eebSPatrick Williams        # Find the branch matching {branch} (or fallback to master).
431ee3c9eebSPatrick Williams        #   This section is locked because we are modifying the PackageDef.
432ee3c9eebSPatrick Williams        Package.lock.acquire()
433ee3c9eebSPatrick Williams        for line in lookup.split("\n"):
434f3d27e64SAndrew Geissler            if re.fullmatch(f".*{branch}$", line.strip()):
435ee3c9eebSPatrick Williams                self.pkg_def["rev"] = line.split()[0]
436f3d27e64SAndrew Geissler                break
437c7d73646SPatrick Williams            elif (
438c7d73646SPatrick Williams                "refs/heads/master" in line or "refs/heads/main" in line
439c7d73646SPatrick Williams            ) and "rev" not in self.pkg_def:
440ee3c9eebSPatrick Williams                self.pkg_def["rev"] = line.split()[0]
441ee3c9eebSPatrick Williams        Package.lock.release()
442ee3c9eebSPatrick Williams
443ee3c9eebSPatrick Williams    def _stagename(self) -> str:
444ee3c9eebSPatrick Williams        """Create a name for the Docker stage associated with this pkg."""
445ee3c9eebSPatrick Williams        return self.package.replace("/", "-").lower()
446ee3c9eebSPatrick Williams
447ee3c9eebSPatrick Williams    def _url(self) -> str:
448ee3c9eebSPatrick Williams        """Get the URL for this package."""
449ee3c9eebSPatrick Williams        rev = self.pkg_def["rev"]
450ee3c9eebSPatrick Williams
451ee3c9eebSPatrick Williams        # If the lambda exists, call it.
452ee3c9eebSPatrick Williams        if "url" in self.pkg_def:
453ee3c9eebSPatrick Williams            return self.pkg_def["url"](self.package, rev)
454ee3c9eebSPatrick Williams
455ee3c9eebSPatrick Williams        # Default to the github archive URL.
456ee3c9eebSPatrick Williams        return f"https://github.com/{self.package}/archive/{rev}.tar.gz"
457ee3c9eebSPatrick Williams
458ee3c9eebSPatrick Williams    def _cmd_download(self) -> str:
459ee3c9eebSPatrick Williams        """Formulate the command necessary to download and unpack to source."""
460ee3c9eebSPatrick Williams
461ee3c9eebSPatrick Williams        url = self._url()
462ee3c9eebSPatrick Williams        if ".tar." not in url:
463ee3c9eebSPatrick Williams            raise NotImplementedError(
464ee3c9eebSPatrick Williams                f"Unhandled download type for {self.package}: {url}"
465ee3c9eebSPatrick Williams            )
466ee3c9eebSPatrick Williams
467ee3c9eebSPatrick Williams        cmd = f"curl -L {url} | tar -x"
468ee3c9eebSPatrick Williams
469ee3c9eebSPatrick Williams        if url.endswith(".bz2"):
470ee3c9eebSPatrick Williams            cmd += "j"
471ee3c9eebSPatrick Williams        elif url.endswith(".gz"):
472ee3c9eebSPatrick Williams            cmd += "z"
473ee3c9eebSPatrick Williams        else:
474ee3c9eebSPatrick Williams            raise NotImplementedError(
475ee3c9eebSPatrick Williams                f"Unknown tar flags needed for {self.package}: {url}"
476ee3c9eebSPatrick Williams            )
477ee3c9eebSPatrick Williams
478ee3c9eebSPatrick Williams        return cmd
479ee3c9eebSPatrick Williams
480ee3c9eebSPatrick Williams    def _cmd_cd_srcdir(self) -> str:
481ee3c9eebSPatrick Williams        """Formulate the command necessary to 'cd' into the source dir."""
482ee3c9eebSPatrick Williams        return f"cd {self.package.split('/')[-1]}*"
483ee3c9eebSPatrick Williams
484ee3c9eebSPatrick Williams    def _df_copycmds(self) -> str:
485ee3c9eebSPatrick Williams        """Formulate the dockerfile snippet necessary to COPY all depends."""
486ee3c9eebSPatrick Williams
487ee3c9eebSPatrick Williams        if "depends" not in self.pkg_def:
488ee3c9eebSPatrick Williams            return ""
489ee3c9eebSPatrick Williams        return Package.df_copycmds_set(self.pkg_def["depends"])
490ee3c9eebSPatrick Williams
491ee3c9eebSPatrick Williams    @staticmethod
492ee3c9eebSPatrick Williams    def df_copycmds_set(pkgs: Iterable[str]) -> str:
493ee3c9eebSPatrick Williams        """Formulate the Dockerfile snippet necessary to COPY a set of
494ee3c9eebSPatrick Williams        packages into a Docker stage.
495ee3c9eebSPatrick Williams        """
496ee3c9eebSPatrick Williams
497ee3c9eebSPatrick Williams        copy_cmds = ""
498ee3c9eebSPatrick Williams
499ee3c9eebSPatrick Williams        # Sort the packages for consistency.
500ee3c9eebSPatrick Williams        for p in sorted(pkgs):
501ee3c9eebSPatrick Williams            tag = Package.packages[p]["__tag"]
502ee3c9eebSPatrick Williams            copy_cmds += f"COPY --from={tag} {prefix} {prefix}\n"
503ee3c9eebSPatrick Williams            # Workaround for upstream docker bug and multiple COPY cmds
504ee3c9eebSPatrick Williams            # https://github.com/moby/moby/issues/37965
505ee3c9eebSPatrick Williams            copy_cmds += "RUN true\n"
506ee3c9eebSPatrick Williams
507ee3c9eebSPatrick Williams        return copy_cmds
508ee3c9eebSPatrick Williams
509ee3c9eebSPatrick Williams    def _df_build(self) -> str:
510ee3c9eebSPatrick Williams        """Formulate the Dockerfile snippet necessary to download, build, and
511ee3c9eebSPatrick Williams        install a package into a Docker stage.
512ee3c9eebSPatrick Williams        """
513ee3c9eebSPatrick Williams
514ee3c9eebSPatrick Williams        # Download and extract source.
515ee3c9eebSPatrick Williams        result = f"RUN {self._cmd_download()} && {self._cmd_cd_srcdir()} && "
516ee3c9eebSPatrick Williams
517ee3c9eebSPatrick Williams        # Handle 'custom_post_dl' commands.
518ee3c9eebSPatrick Williams        custom_post_dl = self.pkg_def.get("custom_post_dl")
519ee3c9eebSPatrick Williams        if custom_post_dl:
520ee3c9eebSPatrick Williams            result += " && ".join(custom_post_dl) + " && "
521ee3c9eebSPatrick Williams
522ee3c9eebSPatrick Williams        # Build and install package based on 'build_type'.
523ee3c9eebSPatrick Williams        build_type = self.pkg_def["build_type"]
524ee3c9eebSPatrick Williams        if build_type == "autoconf":
525ee3c9eebSPatrick Williams            result += self._cmd_build_autoconf()
526ee3c9eebSPatrick Williams        elif build_type == "cmake":
527ee3c9eebSPatrick Williams            result += self._cmd_build_cmake()
528ee3c9eebSPatrick Williams        elif build_type == "custom":
529ee3c9eebSPatrick Williams            result += self._cmd_build_custom()
530ee3c9eebSPatrick Williams        elif build_type == "make":
531ee3c9eebSPatrick Williams            result += self._cmd_build_make()
532ee3c9eebSPatrick Williams        elif build_type == "meson":
533ee3c9eebSPatrick Williams            result += self._cmd_build_meson()
534ee3c9eebSPatrick Williams        else:
535ee3c9eebSPatrick Williams            raise NotImplementedError(
536ee3c9eebSPatrick Williams                f"Unhandled build type for {self.package}: {build_type}"
537ee3c9eebSPatrick Williams            )
538ee3c9eebSPatrick Williams
5396bce2ca1SPatrick Williams        # Handle 'custom_post_install' commands.
5406bce2ca1SPatrick Williams        custom_post_install = self.pkg_def.get("custom_post_install")
5416bce2ca1SPatrick Williams        if custom_post_install:
5426bce2ca1SPatrick Williams            result += " && " + " && ".join(custom_post_install)
5436bce2ca1SPatrick Williams
544ee3c9eebSPatrick Williams        return result
545ee3c9eebSPatrick Williams
546ee3c9eebSPatrick Williams    def _cmd_build_autoconf(self) -> str:
547ee3c9eebSPatrick Williams        options = " ".join(self.pkg_def.get("config_flags", []))
548ee3c9eebSPatrick Williams        env = " ".join(self.pkg_def.get("config_env", []))
549ee3c9eebSPatrick Williams        result = "./bootstrap.sh && "
550ee3c9eebSPatrick Williams        result += f"{env} ./configure {configure_flags} {options} && "
551ee3c9eebSPatrick Williams        result += f"make -j{proc_count} && make install"
552ee3c9eebSPatrick Williams        return result
553ee3c9eebSPatrick Williams
554ee3c9eebSPatrick Williams    def _cmd_build_cmake(self) -> str:
555ee3c9eebSPatrick Williams        options = " ".join(self.pkg_def.get("config_flags", []))
556ee3c9eebSPatrick Williams        env = " ".join(self.pkg_def.get("config_env", []))
557ee3c9eebSPatrick Williams        result = "mkdir builddir && cd builddir && "
558ee3c9eebSPatrick Williams        result += f"{env} cmake {cmake_flags} {options} .. && "
559ee3c9eebSPatrick Williams        result += "cmake --build . --target all && "
560ee3c9eebSPatrick Williams        result += "cmake --build . --target install && "
561ee3c9eebSPatrick Williams        result += "cd .."
562ee3c9eebSPatrick Williams        return result
563ee3c9eebSPatrick Williams
564ee3c9eebSPatrick Williams    def _cmd_build_custom(self) -> str:
565ee3c9eebSPatrick Williams        return " && ".join(self.pkg_def.get("build_steps", []))
566ee3c9eebSPatrick Williams
567ee3c9eebSPatrick Williams    def _cmd_build_make(self) -> str:
568ee3c9eebSPatrick Williams        return f"make -j{proc_count} && make install"
569ee3c9eebSPatrick Williams
570ee3c9eebSPatrick Williams    def _cmd_build_meson(self) -> str:
571ee3c9eebSPatrick Williams        options = " ".join(self.pkg_def.get("config_flags", []))
572ee3c9eebSPatrick Williams        env = " ".join(self.pkg_def.get("config_env", []))
573e2da11adSAndrew Jeffery        result = f"{env} meson setup builddir {meson_flags} {options} && "
574ee3c9eebSPatrick Williams        result += "ninja -C builddir && ninja -C builddir install"
575ee3c9eebSPatrick Williams        return result
576ee3c9eebSPatrick Williams
577ee3c9eebSPatrick Williams
578ee3c9eebSPatrick Williamsclass Docker:
579ee3c9eebSPatrick Williams    """Class to assist with Docker interactions.  All methods are static."""
580ee3c9eebSPatrick Williams
581ee3c9eebSPatrick Williams    @staticmethod
582ee3c9eebSPatrick Williams    def timestamp() -> str:
583ee3c9eebSPatrick Williams        """Generate a timestamp for today using the ISO week."""
584ee3c9eebSPatrick Williams        today = date.today().isocalendar()
585ee3c9eebSPatrick Williams        return f"{today[0]}-W{today[1]:02}"
586ee3c9eebSPatrick Williams
587ee3c9eebSPatrick Williams    @staticmethod
58841d86218SPatrick Williams    def tagname(pkgname: Optional[str], dockerfile: str) -> str:
589ee3c9eebSPatrick Williams        """Generate a tag name for a package using a hash of the Dockerfile."""
590ee3c9eebSPatrick Williams        result = docker_image_name
591ee3c9eebSPatrick Williams        if pkgname:
592ee3c9eebSPatrick Williams            result += "-" + pkgname
593ee3c9eebSPatrick Williams
594ee3c9eebSPatrick Williams        result += ":" + Docker.timestamp()
595ee3c9eebSPatrick Williams        result += "-" + sha256(dockerfile.encode()).hexdigest()[0:16]
596ee3c9eebSPatrick Williams
597ee3c9eebSPatrick Williams        return result
598ee3c9eebSPatrick Williams
599ee3c9eebSPatrick Williams    @staticmethod
600ee3c9eebSPatrick Williams    def build(pkg: str, tag: str, dockerfile: str) -> None:
60122e6110bSAndrew Geissler        """Build a docker image using the Dockerfile and tagging it with 'tag'."""
602ee3c9eebSPatrick Williams
603ee3c9eebSPatrick Williams        # If we're not forcing builds, check if it already exists and skip.
604ee3c9eebSPatrick Williams        if not force_build:
605ee3c9eebSPatrick Williams            if docker.image.ls(tag, "--format", '"{{.Repository}}:{{.Tag}}"'):
60605fb2a0aSPatrick Williams                print(
60705fb2a0aSPatrick Williams                    f"Image {tag} already exists.  Skipping.", file=sys.stderr
60805fb2a0aSPatrick Williams                )
609ee3c9eebSPatrick Williams                return
610ee3c9eebSPatrick Williams
611ee3c9eebSPatrick Williams        # Build it.
612ee3c9eebSPatrick Williams        #   Capture the output of the 'docker build' command and send it to
613ee3c9eebSPatrick Williams        #   stderr (prefixed with the package name).  This allows us to see
614a6ebc6e2SManojkiran Eda        #   progress but not pollute stdout.  Later on we output the final
615ee3c9eebSPatrick Williams        #   docker tag to stdout and we want to keep that pristine.
616ee3c9eebSPatrick Williams        #
617ee3c9eebSPatrick Williams        #   Other unusual flags:
618ee3c9eebSPatrick Williams        #       --no-cache: Bypass the Docker cache if 'force_build'.
619ee3c9eebSPatrick Williams        #       --force-rm: Clean up Docker processes if they fail.
620ee3c9eebSPatrick Williams        docker.build(
621ee3c9eebSPatrick Williams            proxy_args,
622ee3c9eebSPatrick Williams            "--network=host",
623ee3c9eebSPatrick Williams            "--force-rm",
624ee3c9eebSPatrick Williams            "--no-cache=true" if force_build else "--no-cache=false",
625ee3c9eebSPatrick Williams            "-t",
626ee3c9eebSPatrick Williams            tag,
627ee3c9eebSPatrick Williams            "-",
628ee3c9eebSPatrick Williams            _in=dockerfile,
629ee3c9eebSPatrick Williams            _out=(
630ee3c9eebSPatrick Williams                lambda line: print(
631ee3c9eebSPatrick Williams                    pkg + ":", line, end="", file=sys.stderr, flush=True
632ee3c9eebSPatrick Williams                )
633ee3c9eebSPatrick Williams            ),
63488dd7929SJonathan Doman            _err_to_out=True,
635ee3c9eebSPatrick Williams        )
636ee3c9eebSPatrick Williams
637ee3c9eebSPatrick Williams
638ee3c9eebSPatrick Williams# Read a bunch of environment variables.
63905fb2a0aSPatrick Williamsdocker_image_name = os.environ.get(
64005fb2a0aSPatrick Williams    "DOCKER_IMAGE_NAME", "openbmc/ubuntu-unit-test"
64105fb2a0aSPatrick Williams)
642ee3c9eebSPatrick Williamsforce_build = os.environ.get("FORCE_DOCKER_BUILD")
643ee3c9eebSPatrick Williamsis_automated_ci_build = os.environ.get("BUILD_URL", False)
6447c95a37cSPatrick Williamsdistro = os.environ.get("DISTRO", "ubuntu:noble")
645ee3c9eebSPatrick Williamsbranch = os.environ.get("BRANCH", "master")
646ee3c9eebSPatrick Williamsubuntu_mirror = os.environ.get("UBUNTU_MIRROR")
647ee3c9eebSPatrick Williamshttp_proxy = os.environ.get("http_proxy")
648ee3c9eebSPatrick Williams
64965b21fb9SPatrick Williamsgerrit_project = os.environ.get("GERRIT_PROJECT")
65065b21fb9SPatrick Williamsgerrit_rev = os.environ.get("GERRIT_PATCHSET_REVISION")
65165b21fb9SPatrick Williams
652d0dabc3eSAndrew Geissler# Ensure appropriate docker build output to see progress and identify
653d0dabc3eSAndrew Geissler# any issues
654d0dabc3eSAndrew Geissleros.environ["BUILDKIT_PROGRESS"] = "plain"
655d0dabc3eSAndrew Geissler
656ee3c9eebSPatrick Williams# Set up some common variables.
657ee3c9eebSPatrick Williamsusername = os.environ.get("USER", "root")
658ee3c9eebSPatrick Williamshomedir = os.environ.get("HOME", "/root")
659ee3c9eebSPatrick Williamsgid = os.getgid()
660ee3c9eebSPatrick Williamsuid = os.getuid()
661ee3c9eebSPatrick Williams
6626825a018SJosh Lehan# Use well-known constants if user is root
6636825a018SJosh Lehanif username == "root":
6646825a018SJosh Lehan    homedir = "/root"
6656825a018SJosh Lehan    gid = 0
6666825a018SJosh Lehan    uid = 0
6676825a018SJosh Lehan
668ee3c9eebSPatrick Williams# Determine the architecture for Docker.
669ee3c9eebSPatrick Williamsarch = uname("-m").strip()
670ee3c9eebSPatrick Williamsif arch == "ppc64le":
671ee3c9eebSPatrick Williams    docker_base = "ppc64le/"
672ee3c9eebSPatrick Williamselif arch == "x86_64":
673ee3c9eebSPatrick Williams    docker_base = ""
674051b05b7SThang Q. Nguyenelif arch == "aarch64":
675f98f1a8dSThang Q. Nguyen    docker_base = "arm64v8/"
676ee3c9eebSPatrick Williamselse:
677ee3c9eebSPatrick Williams    print(
678ee3c9eebSPatrick Williams        f"Unsupported system architecture({arch}) found for docker image",
679ee3c9eebSPatrick Williams        file=sys.stderr,
680ee3c9eebSPatrick Williams    )
681ee3c9eebSPatrick Williams    sys.exit(1)
682ee3c9eebSPatrick Williams
68302871c91SPatrick Williams# Special flags if setting up a deb mirror.
68402871c91SPatrick Williamsmirror = ""
68502871c91SPatrick Williamsif "ubuntu" in distro and ubuntu_mirror:
68602871c91SPatrick Williams    mirror = f"""
687e08ffba8SPatrick WilliamsRUN echo "deb {ubuntu_mirror} \
688e08ffba8SPatrick Williams        $(. /etc/os-release && echo $VERSION_CODENAME) \
689e08ffba8SPatrick Williams        main restricted universe multiverse" > /etc/apt/sources.list && \\
690e08ffba8SPatrick Williams    echo "deb {ubuntu_mirror} \
691e08ffba8SPatrick Williams        $(. /etc/os-release && echo $VERSION_CODENAME)-updates \
692e08ffba8SPatrick Williams            main restricted universe multiverse" >> /etc/apt/sources.list && \\
693e08ffba8SPatrick Williams    echo "deb {ubuntu_mirror} \
694e08ffba8SPatrick Williams        $(. /etc/os-release && echo $VERSION_CODENAME)-security \
695e08ffba8SPatrick Williams            main restricted universe multiverse" >> /etc/apt/sources.list && \\
696e08ffba8SPatrick Williams    echo "deb {ubuntu_mirror} \
697e08ffba8SPatrick Williams        $(. /etc/os-release && echo $VERSION_CODENAME)-proposed \
698e08ffba8SPatrick Williams            main restricted universe multiverse" >> /etc/apt/sources.list && \\
699e08ffba8SPatrick Williams    echo "deb {ubuntu_mirror} \
700e08ffba8SPatrick Williams        $(. /etc/os-release && echo $VERSION_CODENAME)-backports \
701e08ffba8SPatrick Williams            main restricted universe multiverse" >> /etc/apt/sources.list
70202871c91SPatrick Williams"""
70302871c91SPatrick Williams
70402871c91SPatrick Williams# Special flags for proxying.
70502871c91SPatrick Williamsproxy_cmd = ""
70634ec77e8SAdrian Ambrożewiczproxy_keyserver = ""
70702871c91SPatrick Williamsproxy_args = []
70802871c91SPatrick Williamsif http_proxy:
70902871c91SPatrick Williams    proxy_cmd = f"""
71002871c91SPatrick WilliamsRUN echo "[http]" >> {homedir}/.gitconfig && \
71102871c91SPatrick Williams    echo "proxy = {http_proxy}" >> {homedir}/.gitconfig
71202871c91SPatrick Williams"""
71334ec77e8SAdrian Ambrożewicz    proxy_keyserver = f"--keyserver-options http-proxy={http_proxy}"
71434ec77e8SAdrian Ambrożewicz
71502871c91SPatrick Williams    proxy_args.extend(
71602871c91SPatrick Williams        [
71702871c91SPatrick Williams            "--build-arg",
71802871c91SPatrick Williams            f"http_proxy={http_proxy}",
71902871c91SPatrick Williams            "--build-arg",
720d461cd6aSLei YU            f"https_proxy={http_proxy}",
72102871c91SPatrick Williams        ]
72202871c91SPatrick Williams    )
72302871c91SPatrick Williams
724ee3c9eebSPatrick Williams# Create base Dockerfile.
725a18d9c57SPatrick Williamsdockerfile_base = f"""
726a18d9c57SPatrick WilliamsFROM {docker_base}{distro}
72702871c91SPatrick Williams
72802871c91SPatrick Williams{mirror}
72902871c91SPatrick Williams
73002871c91SPatrick WilliamsENV DEBIAN_FRONTEND noninteractive
73102871c91SPatrick Williams
7328949d3c3SPatrick WilliamsENV PYTHONPATH "/usr/local/lib/python3.10/site-packages/"
73302871c91SPatrick Williams
734bb16ac14SPatrick Williams# Sometimes the ubuntu key expires and we need a way to force an execution
735bb16ac14SPatrick Williams# of the apt-get commands for the dbgsym-keyring.  When this happens we see
736bb16ac14SPatrick Williams# an error like: "Release: The following signatures were invalid:"
737bb16ac14SPatrick Williams# Insert a bogus echo that we can change here when we get this error to force
738bb16ac14SPatrick Williams# the update.
739bb16ac14SPatrick WilliamsRUN echo "ubuntu keyserver rev as of 2021-04-21"
740bb16ac14SPatrick Williams
74102871c91SPatrick Williams# We need the keys to be imported for dbgsym repos
74202871c91SPatrick Williams# New releases have a package, older ones fall back to manual fetching
74302871c91SPatrick Williams# https://wiki.ubuntu.com/Debug%20Symbol%20Packages
744575b5e4cSJagpal Singh Gill# Known issue with gpg to get keys via proxy -
745575b5e4cSJagpal Singh Gill# https://bugs.launchpad.net/ubuntu/+source/gnupg2/+bug/1788190, hence using
746575b5e4cSJagpal Singh Gill# curl to get keys.
74750837436SPatrick WilliamsRUN apt-get update && apt-get dist-upgrade -yy && \
748938d303fSJian Zhang    ( apt-get install -yy gpgv ubuntu-dbgsym-keyring || \
749575b5e4cSJagpal Singh Gill        ( apt-get install -yy dirmngr curl && \
750575b5e4cSJagpal Singh Gill          curl -sSL \
751575b5e4cSJagpal Singh Gill          'https://keyserver.ubuntu.com/pks/lookup?op=get&search=0xF2EDC64DC5AEE1F6B9C621F0C8CAB6595FDFF622' \
752575b5e4cSJagpal Singh Gill          | apt-key add - ))
75302871c91SPatrick Williams
75402871c91SPatrick Williams# Parse the current repo list into a debug repo list
755e08ffba8SPatrick WilliamsRUN sed -n '/^deb /s,^deb [^ ]* ,deb http://ddebs.ubuntu.com ,p' \
756e08ffba8SPatrick Williams        /etc/apt/sources.list >/etc/apt/sources.list.d/debug.list
75702871c91SPatrick Williams
75802871c91SPatrick Williams# Remove non-existent debug repos
75941d86218SPatrick WilliamsRUN sed -i '/-\\(backports\\|security\\) /d' /etc/apt/sources.list.d/debug.list
76002871c91SPatrick Williams
76102871c91SPatrick WilliamsRUN cat /etc/apt/sources.list.d/debug.list
76202871c91SPatrick Williams
76302871c91SPatrick WilliamsRUN apt-get update && apt-get dist-upgrade -yy && apt-get install -yy \
76458f1915eSAndrew Jeffery    abi-compliance-checker \
7658b112068SAndrew Jeffery    abi-dumper \
76602871c91SPatrick Williams    autoconf \
76702871c91SPatrick Williams    autoconf-archive \
768af49ed51SAndrew Geissler    bison \
769af49ed51SAndrew Geissler    cmake \
770af49ed51SAndrew Geissler    curl \
771af49ed51SAndrew Geissler    dbus \
772af49ed51SAndrew Geissler    device-tree-compiler \
773af49ed51SAndrew Geissler    flex \
774961f148bSPatrick Williams    g++-13 \
775961f148bSPatrick Williams    gcc-13 \
776af49ed51SAndrew Geissler    git \
7776968e83eSPatrick Williams    gnupg \
77802871c91SPatrick Williams    iproute2 \
779af49ed51SAndrew Geissler    iputils-ping \
780524a331cSManojkiran Eda    libaudit-dev \
781af49ed51SAndrew Geissler    libc6-dbg \
782af49ed51SAndrew Geissler    libc6-dev \
783af49ed51SAndrew Geissler    libconfig++-dev \
784af49ed51SAndrew Geissler    libcryptsetup-dev \
785af49ed51SAndrew Geissler    libdbus-1-dev \
786af49ed51SAndrew Geissler    libevdev-dev \
787af49ed51SAndrew Geissler    libgpiod-dev \
788af49ed51SAndrew Geissler    libi2c-dev \
789af49ed51SAndrew Geissler    libjpeg-dev \
790af49ed51SAndrew Geissler    libjson-perl \
791af49ed51SAndrew Geissler    libldap2-dev \
792af49ed51SAndrew Geissler    libmimetic-dev \
79302871c91SPatrick Williams    libnl-3-dev \
79402871c91SPatrick Williams    libnl-genl-3-dev \
79502871c91SPatrick Williams    libpam0g-dev \
79602871c91SPatrick Williams    libpciaccess-dev \
797af49ed51SAndrew Geissler    libperlio-gzip-perl \
798af49ed51SAndrew Geissler    libpng-dev \
799af49ed51SAndrew Geissler    libprotobuf-dev \
800af49ed51SAndrew Geissler    libsnmp-dev \
801af49ed51SAndrew Geissler    libssl-dev \
802af49ed51SAndrew Geissler    libsystemd-dev \
803af49ed51SAndrew Geissler    libtool \
804af49ed51SAndrew Geissler    liburing-dev \
80502871c91SPatrick Williams    libxml2-utils \
8060eedeedaSPatrick Williams    libxml-simple-perl \
8076968e83eSPatrick Williams    lsb-release \
808af49ed51SAndrew Geissler    ninja-build \
809af49ed51SAndrew Geissler    npm \
810af49ed51SAndrew Geissler    pkg-config \
811af49ed51SAndrew Geissler    protobuf-compiler \
812af49ed51SAndrew Geissler    python3 \
813af49ed51SAndrew Geissler    python3-dev\
814af49ed51SAndrew Geissler    python3-git \
815af49ed51SAndrew Geissler    python3-mako \
816af49ed51SAndrew Geissler    python3-pip \
81725ba1e2fSWilliam A. Kennington III    python3-protobuf \
818af49ed51SAndrew Geissler    python3-setuptools \
819af49ed51SAndrew Geissler    python3-socks \
820af49ed51SAndrew Geissler    python3-yaml \
8219adf68d6SJohn Wedig    rsync \
822af49ed51SAndrew Geissler    shellcheck \
8238dd1bfe6SEwelina Walkusz    socat \
8246968e83eSPatrick Williams    software-properties-common \
825af49ed51SAndrew Geissler    sudo \
826af49ed51SAndrew Geissler    systemd \
827af49ed51SAndrew Geissler    valgrind \
828b565f825SAndrew Geissler    vim \
829af49ed51SAndrew Geissler    wget \
830af49ed51SAndrew Geissler    xxd
83102871c91SPatrick Williams
832961f148bSPatrick WilliamsRUN update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-13 13 \
833961f148bSPatrick Williams  --slave /usr/bin/g++ g++ /usr/bin/g++-13 \
834961f148bSPatrick Williams  --slave /usr/bin/gcov gcov /usr/bin/gcov-13 \
835961f148bSPatrick Williams  --slave /usr/bin/gcov-dump gcov-dump /usr/bin/gcov-dump-13 \
836961f148bSPatrick Williams  --slave /usr/bin/gcov-tool gcov-tool /usr/bin/gcov-tool-13
837961f148bSPatrick WilliamsRUN update-alternatives --remove cpp /usr/bin/cpp && \
838961f148bSPatrick Williams    update-alternatives --install /usr/bin/cpp cpp /usr/bin/cpp-13 13
83902871c91SPatrick Williams
8406968e83eSPatrick Williams# Set up LLVM apt repository.
8416968e83eSPatrick WilliamsRUN bash -c "$(wget -O - https://apt.llvm.org/llvm.sh)" 18
8426968e83eSPatrick Williams
8436968e83eSPatrick Williams# Install extra clang tools
8446968e83eSPatrick WilliamsRUN apt-get install \
8456968e83eSPatrick Williams        clang-18 \
8466968e83eSPatrick Williams        clang-format-18 \
8476968e83eSPatrick Williams        clang-tidy-18
8486968e83eSPatrick Williams
849b84e29c0SEd TanousRUN update-alternatives --install /usr/bin/clang clang /usr/bin/clang-18 1000 \
850b84e29c0SEd Tanous  --slave /usr/bin/clang++ clang++ /usr/bin/clang++-18 \
851b84e29c0SEd Tanous  --slave /usr/bin/clang-tidy clang-tidy /usr/bin/clang-tidy-18 \
852b84e29c0SEd Tanous  --slave /usr/bin/clang-format clang-format /usr/bin/clang-format-18 \
853e08ffba8SPatrick Williams  --slave /usr/bin/run-clang-tidy run-clang-tidy.py \
854b84e29c0SEd Tanous        /usr/bin/run-clang-tidy-18 \
855b84e29c0SEd Tanous  --slave /usr/bin/scan-build scan-build /usr/bin/scan-build-18
85602871c91SPatrick Williams
85750837436SPatrick Williams"""
85850837436SPatrick Williams
85950837436SPatrick Williamsif is_automated_ci_build:
86050837436SPatrick Williams    dockerfile_base += f"""
861a6ebc6e2SManojkiran Eda# Run an arbitrary command to pollute the docker cache regularly force us
86250837436SPatrick Williams# to re-run `apt-get update` daily.
863ee3c9eebSPatrick WilliamsRUN echo {Docker.timestamp()}
86450837436SPatrick WilliamsRUN apt-get update && apt-get dist-upgrade -yy
86550837436SPatrick Williams
86650837436SPatrick Williams"""
86750837436SPatrick Williams
86841d86218SPatrick Williamsdockerfile_base += """
8695e4d8402SPatrick WilliamsRUN pip3 install --break-system-packages \
870818023dfSPatrick Williams        beautysh \
871818023dfSPatrick Williams        black \
872818023dfSPatrick Williams        codespell \
873818023dfSPatrick Williams        flake8 \
8742d8c551fSEwelina Walkusz        gcovr \
875818023dfSPatrick Williams        gitlint \
876818023dfSPatrick Williams        inflection \
877818023dfSPatrick Williams        isort \
878818023dfSPatrick Williams        jsonschema \
87916baaf73SPatrick Williams        meson==1.3.0 \
880818023dfSPatrick Williams        requests
881b08ddf77SPatrick Williams
882b08ddf77SPatrick WilliamsRUN npm install -g \
883d0757deaSXinnan Xie        eslint@v8.56.0 eslint-plugin-json@v3.1.0 \
8847d41f6d2SPatrick Williams        markdownlint-cli@latest \
885b08ddf77SPatrick Williams        prettier@latest
886fb9948a3SEd Tanous"""
887fb9948a3SEd Tanous
888ee3c9eebSPatrick Williams# Build the base and stage docker images.
889ee3c9eebSPatrick Williamsdocker_base_img_name = Docker.tagname("base", dockerfile_base)
890ee3c9eebSPatrick WilliamsDocker.build("base", docker_base_img_name, dockerfile_base)
891ee3c9eebSPatrick WilliamsPackage.generate_all()
89202871c91SPatrick Williams
893ee3c9eebSPatrick Williams# Create the final Dockerfile.
894a18d9c57SPatrick Williamsdockerfile = f"""
89502871c91SPatrick Williams# Build the final output image
896a18d9c57SPatrick WilliamsFROM {docker_base_img_name}
897ee3c9eebSPatrick Williams{Package.df_all_copycmds()}
89802871c91SPatrick Williams
89902871c91SPatrick Williams# Some of our infrastructure still relies on the presence of this file
90002871c91SPatrick Williams# even though it is no longer needed to rebuild the docker environment
90102871c91SPatrick Williams# NOTE: The file is sorted to ensure the ordering is stable.
902ee3c9eebSPatrick WilliamsRUN echo '{Package.depcache()}' > /tmp/depcache
90302871c91SPatrick Williams
90467cc0616SPatrick Williams# Ensure the group, user, and home directory are created (or rename them if
90567cc0616SPatrick Williams# they already exist).
90667cc0616SPatrick WilliamsRUN if grep -q ":{gid}:" /etc/group ; then \
90767cc0616SPatrick Williams        groupmod -n {username} $(awk -F : '{{ if ($3 == {gid}) {{ print $1 }} }}' /etc/group) ; \
90867cc0616SPatrick Williams    else \
90967cc0616SPatrick Williams        groupadd -f -g {gid} {username} ; \
91067cc0616SPatrick Williams    fi
91102871c91SPatrick WilliamsRUN mkdir -p "{os.path.dirname(homedir)}"
91267cc0616SPatrick WilliamsRUN if grep -q ":{uid}:" /etc/passwd ; then \
91373b3ee91SPatrick Williams        usermod -l {username} -d {homedir} -m $(awk -F : '{{ if ($3 == {uid}) {{ print $1 }} }}' /etc/passwd) ; \
91467cc0616SPatrick Williams    else \
91567cc0616SPatrick Williams        useradd -d {homedir} -m -u {uid} -g {gid} {username} ; \
91667cc0616SPatrick Williams    fi
91702871c91SPatrick WilliamsRUN sed -i '1iDefaults umask=000' /etc/sudoers
91802871c91SPatrick WilliamsRUN echo "{username} ALL=(ALL) NOPASSWD: ALL" >>/etc/sudoers
91902871c91SPatrick Williams
920305a9a5dSAndrew Geissler# Ensure user has ability to write to /usr/local for different tool
921305a9a5dSAndrew Geissler# and data installs
9227bb00b13SAndrew GeisslerRUN chown -R {username}:{username} /usr/local/share
923305a9a5dSAndrew Geissler
924ab4fee83SJonathan Doman# Update library cache
925ab4fee83SJonathan DomanRUN ldconfig
926ab4fee83SJonathan Doman
92702871c91SPatrick Williams{proxy_cmd}
92802871c91SPatrick Williams
92902871c91SPatrick WilliamsRUN /bin/bash
93002871c91SPatrick Williams"""
93102871c91SPatrick Williams
932a18d9c57SPatrick Williams# Do the final docker build
933ee3c9eebSPatrick Williamsdocker_final_img_name = Docker.tagname(None, dockerfile)
934ee3c9eebSPatrick WilliamsDocker.build("final", docker_final_img_name, dockerfile)
935ee3c9eebSPatrick Williams
93600536fbeSPatrick Williams# Print the tag of the final image.
93700536fbeSPatrick Williamsprint(docker_final_img_name)
938