xref: /openbmc/openbmc-build-scripts/scripts/build-unit-test-docker (revision 9698215ec28b6de476f11d03361cfdaf125ae9cb)
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
3864fb4dbaSAndrew Geisslerfrom sh import docker, git, nproc  # type: ignore
3941d86218SPatrick Williams
40ee3c9eebSPatrick Williamstry:
41ee3c9eebSPatrick Williams    # Python before 3.8 doesn't have TypedDict, so reroute to standard 'dict'.
42ee3c9eebSPatrick Williams    from typing import TypedDict
4341d86218SPatrick Williamsexcept Exception:
44ee3c9eebSPatrick Williams
45ee3c9eebSPatrick Williams    class TypedDict(dict):  # type: ignore
46ee3c9eebSPatrick Williams        # We need to do this to eat the 'total' argument.
4741d86218SPatrick Williams        def __init_subclass__(cls, **kwargs: Any) -> None:
48ee3c9eebSPatrick Williams            super().__init_subclass__()
49ee3c9eebSPatrick Williams
50ee3c9eebSPatrick Williams
51ee3c9eebSPatrick Williams# Declare some variables used in package definitions.
52aae36d18SPatrick Williamsprefix = "/usr/local"
5302871c91SPatrick Williamsproc_count = nproc().strip()
5402871c91SPatrick Williams
55ee3c9eebSPatrick Williams
56ee3c9eebSPatrick Williamsclass PackageDef(TypedDict, total=False):
57ee3c9eebSPatrick Williams    """Package Definition for packages dictionary."""
58ee3c9eebSPatrick Williams
59ee3c9eebSPatrick Williams    # rev [optional]: Revision of package to use.
60ee3c9eebSPatrick Williams    rev: str
61ee3c9eebSPatrick Williams    # url [optional]: lambda function to create URL: (package, rev) -> url.
62ee3c9eebSPatrick Williams    url: Callable[[str, str], str]
63ee3c9eebSPatrick Williams    # depends [optional]: List of package dependencies.
64ee3c9eebSPatrick Williams    depends: Iterable[str]
65ee3c9eebSPatrick Williams    # build_type [required]: Build type used for package.
66ee3c9eebSPatrick Williams    #   Currently supported: autoconf, cmake, custom, make, meson
67ee3c9eebSPatrick Williams    build_type: str
68ee3c9eebSPatrick Williams    # build_steps [optional]: Steps to run for 'custom' build_type.
69ee3c9eebSPatrick Williams    build_steps: Iterable[str]
70ee3c9eebSPatrick Williams    # config_flags [optional]: List of options to pass configuration tool.
71ee3c9eebSPatrick Williams    config_flags: Iterable[str]
72ee3c9eebSPatrick Williams    # config_env [optional]: List of environment variables to set for config.
73ee3c9eebSPatrick Williams    config_env: Iterable[str]
74ee3c9eebSPatrick Williams    # custom_post_dl [optional]: List of steps to run after download, but
75ee3c9eebSPatrick Williams    #   before config / build / install.
76ee3c9eebSPatrick Williams    custom_post_dl: Iterable[str]
776bce2ca1SPatrick Williams    # custom_post_install [optional]: List of steps to run after install.
786bce2ca1SPatrick Williams    custom_post_install: Iterable[str]
79ee3c9eebSPatrick Williams
80ee3c9eebSPatrick Williams    # __tag [private]: Generated Docker tag name for package stage.
81ee3c9eebSPatrick Williams    __tag: str
82ee3c9eebSPatrick Williams    # __package [private]: Package object associated with this package.
83ee3c9eebSPatrick Williams    __package: Any  # Type is Package, but not defined yet.
84ee3c9eebSPatrick Williams
8502871c91SPatrick Williams
867204324cSPatrick Williams# Packages to include in image.
877204324cSPatrick Williamspackages = {
88ee3c9eebSPatrick Williams    "boost": PackageDef(
89*9698215eSJayanth Othayoth        rev="1.86.0",
90ee3c9eebSPatrick Williams        url=(
91*9698215eSJayanth Othayoth            lambda pkg, rev: f"https://github.com/boostorg/{pkg}/releases/download/{pkg}-{rev}/{pkg}-{rev}-cmake.tar.gz"
922abc4a48SPatrick Williams        ),
93ee3c9eebSPatrick Williams        build_type="custom",
94ee3c9eebSPatrick Williams        build_steps=[
95e08ffba8SPatrick Williams            (
96e08ffba8SPatrick Williams                "./bootstrap.sh"
97*9698215eSJayanth Othayoth                f" --prefix={prefix} --with-libraries=atomic,context,coroutine,filesystem,process,url"
98e08ffba8SPatrick Williams            ),
99aae36d18SPatrick Williams            "./b2",
10004770ccdSMichal Orzel            f"./b2 install --prefix={prefix} valgrind=on",
101aae36d18SPatrick Williams        ],
102ee3c9eebSPatrick Williams    ),
103ee3c9eebSPatrick Williams    "USCiLab/cereal": PackageDef(
104c1977839SPatrick Williams        rev="v1.3.2",
105ee3c9eebSPatrick Williams        build_type="custom",
106ee3c9eebSPatrick Williams        build_steps=[f"cp -a include/cereal/ {prefix}/include/"],
107ee3c9eebSPatrick Williams    ),
108c7198558SEd Tanous    "danmar/cppcheck": PackageDef(
10951021786SPatrick Williams        rev="2.12.1",
110c7198558SEd Tanous        build_type="cmake",
111c7198558SEd Tanous    ),
112ee3c9eebSPatrick Williams    "CLIUtils/CLI11": PackageDef(
113fc39733aSPatrick Williams        rev="v2.3.2",
114ee3c9eebSPatrick Williams        build_type="cmake",
115ee3c9eebSPatrick Williams        config_flags=[
116aae36d18SPatrick Williams            "-DBUILD_TESTING=OFF",
117aae36d18SPatrick Williams            "-DCLI11_BUILD_DOCS=OFF",
118aae36d18SPatrick Williams            "-DCLI11_BUILD_EXAMPLES=OFF",
119aae36d18SPatrick Williams        ],
120ee3c9eebSPatrick Williams    ),
121ee3c9eebSPatrick Williams    "fmtlib/fmt": PackageDef(
122c061e07bSPatrick Williams        rev="10.1.1",
123ee3c9eebSPatrick Williams        build_type="cmake",
124ee3c9eebSPatrick Williams        config_flags=[
125aae36d18SPatrick Williams            "-DFMT_DOC=OFF",
126aae36d18SPatrick Williams            "-DFMT_TEST=OFF",
127aae36d18SPatrick Williams        ],
128ee3c9eebSPatrick Williams    ),
129ee3c9eebSPatrick Williams    "Naios/function2": PackageDef(
130cb09974cSPatrick Williams        rev="4.2.4",
131ee3c9eebSPatrick Williams        build_type="custom",
132ee3c9eebSPatrick Williams        build_steps=[
133aae36d18SPatrick Williams            f"mkdir {prefix}/include/function2",
134aae36d18SPatrick Williams            f"cp include/function2/function2.hpp {prefix}/include/function2/",
135aae36d18SPatrick Williams        ],
136ee3c9eebSPatrick Williams    ),
137ee3c9eebSPatrick Williams    "google/googletest": PackageDef(
138d11e9c75SPatrick Williams        rev="v1.15.2",
139ee3c9eebSPatrick Williams        build_type="cmake",
1404dd32c02SWilliam A. Kennington III        config_env=["CXXFLAGS=-std=c++20"],
141ee3c9eebSPatrick Williams        config_flags=["-DTHREADS_PREFER_PTHREAD_FLAG=ON"],
142ee3c9eebSPatrick Williams    ),
143178b4b29SEd Tanous    "nghttp2/nghttp2": PackageDef(
144abb106a9SEd Tanous        rev="v1.61.0",
145178b4b29SEd Tanous        build_type="cmake",
146178b4b29SEd Tanous        config_env=["CXXFLAGS=-std=c++20"],
147178b4b29SEd Tanous        config_flags=[
148178b4b29SEd Tanous            "-DENABLE_LIB_ONLY=ON",
149178b4b29SEd Tanous            "-DENABLE_STATIC_LIB=ON",
150178b4b29SEd Tanous        ],
151178b4b29SEd Tanous    ),
152ee3c9eebSPatrick Williams    "nlohmann/json": PackageDef(
153c1977839SPatrick Williams        rev="v3.11.2",
1546bce2ca1SPatrick Williams        build_type="cmake",
1556bce2ca1SPatrick Williams        config_flags=["-DJSON_BuildTests=OFF"],
1566bce2ca1SPatrick Williams        custom_post_install=[
157e08ffba8SPatrick Williams            (
158e08ffba8SPatrick Williams                f"ln -s {prefix}/include/nlohmann/json.hpp"
159e08ffba8SPatrick Williams                f" {prefix}/include/json.hpp"
160e08ffba8SPatrick Williams            ),
161aae36d18SPatrick Williams        ],
162ee3c9eebSPatrick Williams    ),
163058e3a34SPrzemyslaw Czarnowski    "json-c/json-c": PackageDef(
164eee65beeSPatrick Williams        rev="json-c-0.17-20230812",
165058e3a34SPrzemyslaw Czarnowski        build_type="cmake",
166058e3a34SPrzemyslaw Czarnowski    ),
167ee3c9eebSPatrick Williams    "LibVNC/libvncserver": PackageDef(
168c042132cSPatrick Williams        rev="LibVNCServer-0.9.14",
169ee3c9eebSPatrick Williams        build_type="cmake",
170ee3c9eebSPatrick Williams    ),
171ee3c9eebSPatrick Williams    "leethomason/tinyxml2": PackageDef(
172c1977839SPatrick Williams        rev="9.0.0",
173ee3c9eebSPatrick Williams        build_type="cmake",
174ee3c9eebSPatrick Williams    ),
175ee3c9eebSPatrick Williams    "tristanpenman/valijson": PackageDef(
1765a2c113cSPatrick Williams        rev="v1.0.1",
177ee3c9eebSPatrick Williams        build_type="cmake",
178ee3c9eebSPatrick Williams        config_flags=[
1790eedeedaSPatrick Williams            "-Dvalijson_BUILD_TESTS=0",
1800eedeedaSPatrick Williams            "-Dvalijson_INSTALL_HEADERS=1",
181aae36d18SPatrick Williams        ],
182ee3c9eebSPatrick Williams    ),
183ee3c9eebSPatrick Williams    "open-power/pdbg": PackageDef(build_type="autoconf"),
184ee3c9eebSPatrick Williams    "openbmc/gpioplus": PackageDef(
185ee3c9eebSPatrick Williams        build_type="meson",
186ee3c9eebSPatrick Williams        config_flags=[
187aae36d18SPatrick Williams            "-Dexamples=false",
188aae36d18SPatrick Williams            "-Dtests=disabled",
189aae36d18SPatrick Williams        ],
190ee3c9eebSPatrick Williams    ),
191ee3c9eebSPatrick Williams    "openbmc/phosphor-dbus-interfaces": PackageDef(
192ee3c9eebSPatrick Williams        depends=["openbmc/sdbusplus"],
193ee3c9eebSPatrick Williams        build_type="meson",
1944fe87776SWilliam A. Kennington III        config_flags=["-Dgenerate_md=false"],
195ee3c9eebSPatrick Williams    ),
196ee3c9eebSPatrick Williams    "openbmc/phosphor-logging": PackageDef(
197ee3c9eebSPatrick Williams        depends=[
19883394610SPatrick Williams            "USCiLab/cereal",
19983394610SPatrick Williams            "openbmc/phosphor-dbus-interfaces",
20083394610SPatrick Williams            "openbmc/sdbusplus",
20183394610SPatrick Williams            "openbmc/sdeventplus",
202aae36d18SPatrick Williams        ],
203f79ce4c4SPatrick Williams        build_type="meson",
204ee3c9eebSPatrick Williams        config_flags=[
2056c98f280SWilliam A. Kennington III            "-Dlibonly=true",
2066c98f280SWilliam A. Kennington III            "-Dtests=disabled",
2075eabdae9SPatrick Williams            f"-Dyamldir={prefix}/share/phosphor-dbus-yaml/yaml",
208aae36d18SPatrick Williams        ],
209ee3c9eebSPatrick Williams    ),
210ee3c9eebSPatrick Williams    "openbmc/phosphor-objmgr": PackageDef(
211ee3c9eebSPatrick Williams        depends=[
21211e5762cSBrad Bishop            "CLIUtils/CLI11",
21370af95caSPatrick Williams            "boost",
21483394610SPatrick Williams            "leethomason/tinyxml2",
21570af95caSPatrick Williams            "openbmc/phosphor-dbus-interfaces",
21683394610SPatrick Williams            "openbmc/phosphor-logging",
21783394610SPatrick Williams            "openbmc/sdbusplus",
218aae36d18SPatrick Williams        ],
2191197e359SBrad Bishop        build_type="meson",
2201197e359SBrad Bishop        config_flags=[
2211197e359SBrad Bishop            "-Dtests=disabled",
2221197e359SBrad Bishop        ],
223ee3c9eebSPatrick Williams    ),
224c02ff271SJason M. Bills    "openbmc/libpeci": PackageDef(
225c02ff271SJason M. Bills        build_type="meson",
226c02ff271SJason M. Bills        config_flags=[
227c02ff271SJason M. Bills            "-Draw-peci=disabled",
228c02ff271SJason M. Bills        ],
229c02ff271SJason M. Bills    ),
2301c19e453SManojkiran Eda    "openbmc/libpldm": PackageDef(
231ee3c9eebSPatrick Williams        build_type="meson",
23229163971SAndrew Jeffery        config_flags=[
23329163971SAndrew Jeffery            "-Dabi=deprecated,stable",
23429163971SAndrew Jeffery            "-Dtests=false",
23529163971SAndrew Jeffery            "-Dabi-compliance-check=false",
23629163971SAndrew Jeffery        ],
237ee3c9eebSPatrick Williams    ),
238ee3c9eebSPatrick Williams    "openbmc/sdbusplus": PackageDef(
23954d01da4SPatrick Williams        depends=[
24054d01da4SPatrick Williams            "nlohmann/json",
24154d01da4SPatrick Williams        ],
242ee3c9eebSPatrick Williams        build_type="meson",
243ee3c9eebSPatrick Williams        custom_post_dl=[
244aae36d18SPatrick Williams            "cd tools",
245aae36d18SPatrick Williams            f"./setup.py install --root=/ --prefix={prefix}",
246aae36d18SPatrick Williams            "cd ..",
247aae36d18SPatrick Williams        ],
248ee3c9eebSPatrick Williams        config_flags=[
249aae36d18SPatrick Williams            "-Dexamples=disabled",
250aae36d18SPatrick Williams            "-Dtests=disabled",
251aae36d18SPatrick Williams        ],
252b16f3e20SPatrick Williams    ),
253ee3c9eebSPatrick Williams    "openbmc/sdeventplus": PackageDef(
25470af95caSPatrick Williams        depends=[
25570af95caSPatrick Williams            "openbmc/stdplus",
25670af95caSPatrick Williams        ],
257ee3c9eebSPatrick Williams        build_type="meson",
258ee3c9eebSPatrick Williams        config_flags=[
259ee3c9eebSPatrick Williams            "-Dexamples=false",
260ee3c9eebSPatrick Williams            "-Dtests=disabled",
261ee3c9eebSPatrick Williams        ],
262ee3c9eebSPatrick Williams    ),
263ee3c9eebSPatrick Williams    "openbmc/stdplus": PackageDef(
26470af95caSPatrick Williams        depends=[
26570af95caSPatrick Williams            "fmtlib/fmt",
266ca1bf0c0SWilliam A. Kennington III            "google/googletest",
267ca1bf0c0SWilliam A. Kennington III            "Naios/function2",
26870af95caSPatrick Williams        ],
269ee3c9eebSPatrick Williams        build_type="meson",
270ee3c9eebSPatrick Williams        config_flags=[
271ee3c9eebSPatrick Williams            "-Dexamples=false",
272ee3c9eebSPatrick Williams            "-Dtests=disabled",
273ca1bf0c0SWilliam A. Kennington III            "-Dgtest=enabled",
274ee3c9eebSPatrick Williams        ],
275ee3c9eebSPatrick Williams    ),
276ee3c9eebSPatrick Williams}  # type: Dict[str, PackageDef]
27702871c91SPatrick Williams
27802871c91SPatrick Williams# Define common flags used for builds
27902871c91SPatrick Williamsconfigure_flags = " ".join(
28002871c91SPatrick Williams    [
28102871c91SPatrick Williams        f"--prefix={prefix}",
28202871c91SPatrick Williams    ]
28302871c91SPatrick Williams)
28402871c91SPatrick Williamscmake_flags = " ".join(
28502871c91SPatrick Williams    [
28602871c91SPatrick Williams        "-DBUILD_SHARED_LIBS=ON",
2870f2086b3SPatrick Williams        "-DCMAKE_BUILD_TYPE=RelWithDebInfo",
28802871c91SPatrick Williams        f"-DCMAKE_INSTALL_PREFIX:PATH={prefix}",
2890f2086b3SPatrick Williams        "-GNinja",
2900f2086b3SPatrick Williams        "-DCMAKE_MAKE_PROGRAM=ninja",
29102871c91SPatrick Williams    ]
29202871c91SPatrick Williams)
29302871c91SPatrick Williamsmeson_flags = " ".join(
29402871c91SPatrick Williams    [
29502871c91SPatrick Williams        "--wrap-mode=nodownload",
29602871c91SPatrick Williams        f"-Dprefix={prefix}",
29702871c91SPatrick Williams    ]
29802871c91SPatrick Williams)
29902871c91SPatrick Williams
300ee3c9eebSPatrick Williams
301ee3c9eebSPatrick Williamsclass Package(threading.Thread):
302ee3c9eebSPatrick Williams    """Class used to build the Docker stages for each package.
303ee3c9eebSPatrick Williams
304ee3c9eebSPatrick Williams    Generally, this class should not be instantiated directly but through
305ee3c9eebSPatrick Williams    Package.generate_all().
306ee3c9eebSPatrick Williams    """
307ee3c9eebSPatrick Williams
308ee3c9eebSPatrick Williams    # Copy the packages dictionary.
309ee3c9eebSPatrick Williams    packages = packages.copy()
310ee3c9eebSPatrick Williams
311ee3c9eebSPatrick Williams    # Lock used for thread-safety.
312ee3c9eebSPatrick Williams    lock = threading.Lock()
313ee3c9eebSPatrick Williams
314ee3c9eebSPatrick Williams    def __init__(self, pkg: str):
315ee3c9eebSPatrick Williams        """pkg - The name of this package (ex. foo/bar )"""
316ee3c9eebSPatrick Williams        super(Package, self).__init__()
317ee3c9eebSPatrick Williams
318ee3c9eebSPatrick Williams        self.package = pkg
319ee3c9eebSPatrick Williams        self.exception = None  # type: Optional[Exception]
320ee3c9eebSPatrick Williams
321ee3c9eebSPatrick Williams        # Reference to this package's
322ee3c9eebSPatrick Williams        self.pkg_def = Package.packages[pkg]
323ee3c9eebSPatrick Williams        self.pkg_def["__package"] = self
324ee3c9eebSPatrick Williams
325ee3c9eebSPatrick Williams    def run(self) -> None:
326ee3c9eebSPatrick Williams        """Thread 'run' function.  Builds the Docker stage."""
327ee3c9eebSPatrick Williams
328ee3c9eebSPatrick Williams        # In case this package has no rev, fetch it from Github.
329ee3c9eebSPatrick Williams        self._update_rev()
330ee3c9eebSPatrick Williams
331ee3c9eebSPatrick Williams        # Find all the Package objects that this package depends on.
332ee3c9eebSPatrick Williams        #   This section is locked because we are looking into another
333ee3c9eebSPatrick Williams        #   package's PackageDef dict, which could be being modified.
334ee3c9eebSPatrick Williams        Package.lock.acquire()
335ee3c9eebSPatrick Williams        deps: Iterable[Package] = [
336ee3c9eebSPatrick Williams            Package.packages[deppkg]["__package"]
337ee3c9eebSPatrick Williams            for deppkg in self.pkg_def.get("depends", [])
338ee3c9eebSPatrick Williams        ]
339ee3c9eebSPatrick Williams        Package.lock.release()
340ee3c9eebSPatrick Williams
341ee3c9eebSPatrick Williams        # Wait until all the depends finish building.  We need them complete
342ee3c9eebSPatrick Williams        # for the "COPY" commands.
343ee3c9eebSPatrick Williams        for deppkg in deps:
344ee3c9eebSPatrick Williams            deppkg.join()
345ee3c9eebSPatrick Williams
346ee3c9eebSPatrick Williams        # Generate this package's Dockerfile.
347ee3c9eebSPatrick Williams        dockerfile = f"""
348ee3c9eebSPatrick WilliamsFROM {docker_base_img_name}
349ee3c9eebSPatrick Williams{self._df_copycmds()}
350ee3c9eebSPatrick Williams{self._df_build()}
351ee3c9eebSPatrick Williams"""
352ee3c9eebSPatrick Williams
353ee3c9eebSPatrick Williams        # Generate the resulting tag name and save it to the PackageDef.
354ee3c9eebSPatrick Williams        #   This section is locked because we are modifying the PackageDef,
355ee3c9eebSPatrick Williams        #   which can be accessed by other threads.
356ee3c9eebSPatrick Williams        Package.lock.acquire()
357ee3c9eebSPatrick Williams        tag = Docker.tagname(self._stagename(), dockerfile)
358ee3c9eebSPatrick Williams        self.pkg_def["__tag"] = tag
359ee3c9eebSPatrick Williams        Package.lock.release()
360ee3c9eebSPatrick Williams
361ee3c9eebSPatrick Williams        # Do the build / save any exceptions.
362ee3c9eebSPatrick Williams        try:
363ee3c9eebSPatrick Williams            Docker.build(self.package, tag, dockerfile)
364ee3c9eebSPatrick Williams        except Exception as e:
365ee3c9eebSPatrick Williams            self.exception = e
366ee3c9eebSPatrick Williams
367ee3c9eebSPatrick Williams    @classmethod
368ee3c9eebSPatrick Williams    def generate_all(cls) -> None:
369ee3c9eebSPatrick Williams        """Ensure a Docker stage is created for all defined packages.
370ee3c9eebSPatrick Williams
371ee3c9eebSPatrick Williams        These are done in parallel but with appropriate blocking per
372ee3c9eebSPatrick Williams        package 'depends' specifications.
373ee3c9eebSPatrick Williams        """
374ee3c9eebSPatrick Williams
375ee3c9eebSPatrick Williams        # Create a Package for each defined package.
376ee3c9eebSPatrick Williams        pkg_threads = [Package(p) for p in cls.packages.keys()]
377ee3c9eebSPatrick Williams
378ee3c9eebSPatrick Williams        # Start building them all.
3796dbd7807SPatrick Williams        #   This section is locked because threads depend on each other,
3806dbd7807SPatrick Williams        #   based on the packages, and they cannot 'join' on a thread
3816dbd7807SPatrick Williams        #   which is not yet started.  Adding a lock here allows all the
3826dbd7807SPatrick Williams        #   threads to start before they 'join' their dependencies.
3836dbd7807SPatrick Williams        Package.lock.acquire()
384ee3c9eebSPatrick Williams        for t in pkg_threads:
385ee3c9eebSPatrick Williams            t.start()
3866dbd7807SPatrick Williams        Package.lock.release()
387ee3c9eebSPatrick Williams
388ee3c9eebSPatrick Williams        # Wait for completion.
389ee3c9eebSPatrick Williams        for t in pkg_threads:
390ee3c9eebSPatrick Williams            t.join()
391ee3c9eebSPatrick Williams            # Check if the thread saved off its own exception.
392ee3c9eebSPatrick Williams            if t.exception:
393ee3c9eebSPatrick Williams                print(f"Package {t.package} failed!", file=sys.stderr)
394ee3c9eebSPatrick Williams                raise t.exception
395ee3c9eebSPatrick Williams
396ee3c9eebSPatrick Williams    @staticmethod
397ee3c9eebSPatrick Williams    def df_all_copycmds() -> str:
398ee3c9eebSPatrick Williams        """Formulate the Dockerfile snippet necessary to copy all packages
399ee3c9eebSPatrick Williams        into the final image.
400ee3c9eebSPatrick Williams        """
401ee3c9eebSPatrick Williams        return Package.df_copycmds_set(Package.packages.keys())
402ee3c9eebSPatrick Williams
403ee3c9eebSPatrick Williams    @classmethod
404ee3c9eebSPatrick Williams    def depcache(cls) -> str:
405ee3c9eebSPatrick Williams        """Create the contents of the '/tmp/depcache'.
406ee3c9eebSPatrick Williams        This file is a comma-separated list of "<pkg>:<rev>".
407ee3c9eebSPatrick Williams        """
408ee3c9eebSPatrick Williams
409ee3c9eebSPatrick Williams        # This needs to be sorted for consistency.
410ee3c9eebSPatrick Williams        depcache = ""
411ee3c9eebSPatrick Williams        for pkg in sorted(cls.packages.keys()):
412ee3c9eebSPatrick Williams            depcache += "%s:%s," % (pkg, cls.packages[pkg]["rev"])
413ee3c9eebSPatrick Williams        return depcache
414ee3c9eebSPatrick Williams
415276bd0e2SPatrick Williams    def _check_gerrit_topic(self) -> bool:
416276bd0e2SPatrick Williams        if not gerrit_topic:
417276bd0e2SPatrick Williams            return False
418276bd0e2SPatrick Williams        if not self.package.startswith("openbmc/"):
419276bd0e2SPatrick Williams            return False
420276bd0e2SPatrick Williams        if gerrit_project == self.package and gerrit_rev:
421276bd0e2SPatrick Williams            return False
422276bd0e2SPatrick Williams
423276bd0e2SPatrick Williams        try:
424276bd0e2SPatrick Williams            commits = json.loads(
425276bd0e2SPatrick Williams                urllib.request.urlopen(
426276bd0e2SPatrick Williams                    f"https://gerrit.openbmc.org/changes/?q=status:open+project:{self.package}+topic:{gerrit_topic}"
427276bd0e2SPatrick Williams                )
428276bd0e2SPatrick Williams                .read()
429276bd0e2SPatrick Williams                .splitlines()[-1]
430276bd0e2SPatrick Williams            )
431276bd0e2SPatrick Williams
432276bd0e2SPatrick Williams            if len(commits) == 0:
433276bd0e2SPatrick Williams                return False
434276bd0e2SPatrick Williams            if len(commits) > 1:
435276bd0e2SPatrick Williams                print(
436276bd0e2SPatrick Williams                    f"{self.package} has more than 1 commit under {gerrit_topic}; using lastest upstream: {len(commits)}",
437276bd0e2SPatrick Williams                    file=sys.stderr,
438276bd0e2SPatrick Williams                )
439276bd0e2SPatrick Williams                return False
440276bd0e2SPatrick Williams
441276bd0e2SPatrick Williams            change_id = commits[0]["id"]
442276bd0e2SPatrick Williams
443276bd0e2SPatrick Williams            commit = json.loads(
444276bd0e2SPatrick Williams                urllib.request.urlopen(
445276bd0e2SPatrick Williams                    f"https://gerrit.openbmc.org/changes/{change_id}/revisions/current/commit"
446276bd0e2SPatrick Williams                )
447276bd0e2SPatrick Williams                .read()
448276bd0e2SPatrick Williams                .splitlines()[-1]
449276bd0e2SPatrick Williams            )["commit"]
450276bd0e2SPatrick Williams
451276bd0e2SPatrick Williams            print(
452276bd0e2SPatrick Williams                f"Using {commit} from {gerrit_topic} for {self.package}",
453276bd0e2SPatrick Williams                file=sys.stderr,
454276bd0e2SPatrick Williams            )
455276bd0e2SPatrick Williams            self.pkg_def["rev"] = commit
456276bd0e2SPatrick Williams            return True
457276bd0e2SPatrick Williams
458276bd0e2SPatrick Williams        except urllib.error.HTTPError as e:
459276bd0e2SPatrick Williams            print(
460276bd0e2SPatrick Williams                f"Error loading topic {gerrit_topic} for {self.package}: ",
461276bd0e2SPatrick Williams                e,
462276bd0e2SPatrick Williams                file=sys.stderr,
463276bd0e2SPatrick Williams            )
464276bd0e2SPatrick Williams            return False
465276bd0e2SPatrick Williams
466ee3c9eebSPatrick Williams    def _update_rev(self) -> None:
467ee3c9eebSPatrick Williams        """Look up the HEAD for missing a static rev."""
468ee3c9eebSPatrick Williams
469ee3c9eebSPatrick Williams        if "rev" in self.pkg_def:
470ee3c9eebSPatrick Williams            return
471ee3c9eebSPatrick Williams
472276bd0e2SPatrick Williams        if self._check_gerrit_topic():
473276bd0e2SPatrick Williams            return
474276bd0e2SPatrick Williams
47565b21fb9SPatrick Williams        # Check if Jenkins/Gerrit gave us a revision and use it.
47665b21fb9SPatrick Williams        if gerrit_project == self.package and gerrit_rev:
47765b21fb9SPatrick Williams            print(
47865b21fb9SPatrick Williams                f"Found Gerrit revision for {self.package}: {gerrit_rev}",
47965b21fb9SPatrick Williams                file=sys.stderr,
48065b21fb9SPatrick Williams            )
48165b21fb9SPatrick Williams            self.pkg_def["rev"] = gerrit_rev
48265b21fb9SPatrick Williams            return
48365b21fb9SPatrick Williams
484ee3c9eebSPatrick Williams        # Ask Github for all the branches.
48505fb2a0aSPatrick Williams        lookup = git(
48605fb2a0aSPatrick Williams            "ls-remote", "--heads", f"https://github.com/{self.package}"
48705fb2a0aSPatrick Williams        )
488ee3c9eebSPatrick Williams
489ee3c9eebSPatrick Williams        # Find the branch matching {branch} (or fallback to master).
490ee3c9eebSPatrick Williams        #   This section is locked because we are modifying the PackageDef.
491ee3c9eebSPatrick Williams        Package.lock.acquire()
492ee3c9eebSPatrick Williams        for line in lookup.split("\n"):
493f3d27e64SAndrew Geissler            if re.fullmatch(f".*{branch}$", line.strip()):
494ee3c9eebSPatrick Williams                self.pkg_def["rev"] = line.split()[0]
495f3d27e64SAndrew Geissler                break
496c7d73646SPatrick Williams            elif (
497c7d73646SPatrick Williams                "refs/heads/master" in line or "refs/heads/main" in line
498c7d73646SPatrick Williams            ) and "rev" not in self.pkg_def:
499ee3c9eebSPatrick Williams                self.pkg_def["rev"] = line.split()[0]
500ee3c9eebSPatrick Williams        Package.lock.release()
501ee3c9eebSPatrick Williams
502ee3c9eebSPatrick Williams    def _stagename(self) -> str:
503ee3c9eebSPatrick Williams        """Create a name for the Docker stage associated with this pkg."""
504ee3c9eebSPatrick Williams        return self.package.replace("/", "-").lower()
505ee3c9eebSPatrick Williams
506ee3c9eebSPatrick Williams    def _url(self) -> str:
507ee3c9eebSPatrick Williams        """Get the URL for this package."""
508ee3c9eebSPatrick Williams        rev = self.pkg_def["rev"]
509ee3c9eebSPatrick Williams
510ee3c9eebSPatrick Williams        # If the lambda exists, call it.
511ee3c9eebSPatrick Williams        if "url" in self.pkg_def:
512ee3c9eebSPatrick Williams            return self.pkg_def["url"](self.package, rev)
513ee3c9eebSPatrick Williams
514ee3c9eebSPatrick Williams        # Default to the github archive URL.
515ee3c9eebSPatrick Williams        return f"https://github.com/{self.package}/archive/{rev}.tar.gz"
516ee3c9eebSPatrick Williams
517ee3c9eebSPatrick Williams    def _cmd_download(self) -> str:
518ee3c9eebSPatrick Williams        """Formulate the command necessary to download and unpack to source."""
519ee3c9eebSPatrick Williams
520ee3c9eebSPatrick Williams        url = self._url()
521ee3c9eebSPatrick Williams        if ".tar." not in url:
522ee3c9eebSPatrick Williams            raise NotImplementedError(
523ee3c9eebSPatrick Williams                f"Unhandled download type for {self.package}: {url}"
524ee3c9eebSPatrick Williams            )
525ee3c9eebSPatrick Williams
526ee3c9eebSPatrick Williams        cmd = f"curl -L {url} | tar -x"
527ee3c9eebSPatrick Williams
528ee3c9eebSPatrick Williams        if url.endswith(".bz2"):
529ee3c9eebSPatrick Williams            cmd += "j"
530ee3c9eebSPatrick Williams        elif url.endswith(".gz"):
531ee3c9eebSPatrick Williams            cmd += "z"
532ee3c9eebSPatrick Williams        else:
533ee3c9eebSPatrick Williams            raise NotImplementedError(
534ee3c9eebSPatrick Williams                f"Unknown tar flags needed for {self.package}: {url}"
535ee3c9eebSPatrick Williams            )
536ee3c9eebSPatrick Williams
537ee3c9eebSPatrick Williams        return cmd
538ee3c9eebSPatrick Williams
539ee3c9eebSPatrick Williams    def _cmd_cd_srcdir(self) -> str:
540ee3c9eebSPatrick Williams        """Formulate the command necessary to 'cd' into the source dir."""
541ee3c9eebSPatrick Williams        return f"cd {self.package.split('/')[-1]}*"
542ee3c9eebSPatrick Williams
543ee3c9eebSPatrick Williams    def _df_copycmds(self) -> str:
544ee3c9eebSPatrick Williams        """Formulate the dockerfile snippet necessary to COPY all depends."""
545ee3c9eebSPatrick Williams
546ee3c9eebSPatrick Williams        if "depends" not in self.pkg_def:
547ee3c9eebSPatrick Williams            return ""
548ee3c9eebSPatrick Williams        return Package.df_copycmds_set(self.pkg_def["depends"])
549ee3c9eebSPatrick Williams
550ee3c9eebSPatrick Williams    @staticmethod
551ee3c9eebSPatrick Williams    def df_copycmds_set(pkgs: Iterable[str]) -> str:
552ee3c9eebSPatrick Williams        """Formulate the Dockerfile snippet necessary to COPY a set of
553ee3c9eebSPatrick Williams        packages into a Docker stage.
554ee3c9eebSPatrick Williams        """
555ee3c9eebSPatrick Williams
556ee3c9eebSPatrick Williams        copy_cmds = ""
557ee3c9eebSPatrick Williams
558ee3c9eebSPatrick Williams        # Sort the packages for consistency.
559ee3c9eebSPatrick Williams        for p in sorted(pkgs):
560ee3c9eebSPatrick Williams            tag = Package.packages[p]["__tag"]
561ee3c9eebSPatrick Williams            copy_cmds += f"COPY --from={tag} {prefix} {prefix}\n"
562ee3c9eebSPatrick Williams            # Workaround for upstream docker bug and multiple COPY cmds
563ee3c9eebSPatrick Williams            # https://github.com/moby/moby/issues/37965
564ee3c9eebSPatrick Williams            copy_cmds += "RUN true\n"
565ee3c9eebSPatrick Williams
566ee3c9eebSPatrick Williams        return copy_cmds
567ee3c9eebSPatrick Williams
568ee3c9eebSPatrick Williams    def _df_build(self) -> str:
569ee3c9eebSPatrick Williams        """Formulate the Dockerfile snippet necessary to download, build, and
570ee3c9eebSPatrick Williams        install a package into a Docker stage.
571ee3c9eebSPatrick Williams        """
572ee3c9eebSPatrick Williams
573ee3c9eebSPatrick Williams        # Download and extract source.
574ee3c9eebSPatrick Williams        result = f"RUN {self._cmd_download()} && {self._cmd_cd_srcdir()} && "
575ee3c9eebSPatrick Williams
576ee3c9eebSPatrick Williams        # Handle 'custom_post_dl' commands.
577ee3c9eebSPatrick Williams        custom_post_dl = self.pkg_def.get("custom_post_dl")
578ee3c9eebSPatrick Williams        if custom_post_dl:
579ee3c9eebSPatrick Williams            result += " && ".join(custom_post_dl) + " && "
580ee3c9eebSPatrick Williams
581ee3c9eebSPatrick Williams        # Build and install package based on 'build_type'.
582ee3c9eebSPatrick Williams        build_type = self.pkg_def["build_type"]
583ee3c9eebSPatrick Williams        if build_type == "autoconf":
584ee3c9eebSPatrick Williams            result += self._cmd_build_autoconf()
585ee3c9eebSPatrick Williams        elif build_type == "cmake":
586ee3c9eebSPatrick Williams            result += self._cmd_build_cmake()
587ee3c9eebSPatrick Williams        elif build_type == "custom":
588ee3c9eebSPatrick Williams            result += self._cmd_build_custom()
589ee3c9eebSPatrick Williams        elif build_type == "make":
590ee3c9eebSPatrick Williams            result += self._cmd_build_make()
591ee3c9eebSPatrick Williams        elif build_type == "meson":
592ee3c9eebSPatrick Williams            result += self._cmd_build_meson()
593ee3c9eebSPatrick Williams        else:
594ee3c9eebSPatrick Williams            raise NotImplementedError(
595ee3c9eebSPatrick Williams                f"Unhandled build type for {self.package}: {build_type}"
596ee3c9eebSPatrick Williams            )
597ee3c9eebSPatrick Williams
5986bce2ca1SPatrick Williams        # Handle 'custom_post_install' commands.
5996bce2ca1SPatrick Williams        custom_post_install = self.pkg_def.get("custom_post_install")
6006bce2ca1SPatrick Williams        if custom_post_install:
6016bce2ca1SPatrick Williams            result += " && " + " && ".join(custom_post_install)
6026bce2ca1SPatrick Williams
603ee3c9eebSPatrick Williams        return result
604ee3c9eebSPatrick Williams
605ee3c9eebSPatrick Williams    def _cmd_build_autoconf(self) -> str:
606ee3c9eebSPatrick Williams        options = " ".join(self.pkg_def.get("config_flags", []))
607ee3c9eebSPatrick Williams        env = " ".join(self.pkg_def.get("config_env", []))
608ee3c9eebSPatrick Williams        result = "./bootstrap.sh && "
609ee3c9eebSPatrick Williams        result += f"{env} ./configure {configure_flags} {options} && "
610ee3c9eebSPatrick Williams        result += f"make -j{proc_count} && make install"
611ee3c9eebSPatrick Williams        return result
612ee3c9eebSPatrick Williams
613ee3c9eebSPatrick Williams    def _cmd_build_cmake(self) -> str:
614ee3c9eebSPatrick Williams        options = " ".join(self.pkg_def.get("config_flags", []))
615ee3c9eebSPatrick Williams        env = " ".join(self.pkg_def.get("config_env", []))
616ee3c9eebSPatrick Williams        result = "mkdir builddir && cd builddir && "
617ee3c9eebSPatrick Williams        result += f"{env} cmake {cmake_flags} {options} .. && "
618ee3c9eebSPatrick Williams        result += "cmake --build . --target all && "
619ee3c9eebSPatrick Williams        result += "cmake --build . --target install && "
620ee3c9eebSPatrick Williams        result += "cd .."
621ee3c9eebSPatrick Williams        return result
622ee3c9eebSPatrick Williams
623ee3c9eebSPatrick Williams    def _cmd_build_custom(self) -> str:
624ee3c9eebSPatrick Williams        return " && ".join(self.pkg_def.get("build_steps", []))
625ee3c9eebSPatrick Williams
626ee3c9eebSPatrick Williams    def _cmd_build_make(self) -> str:
627ee3c9eebSPatrick Williams        return f"make -j{proc_count} && make install"
628ee3c9eebSPatrick Williams
629ee3c9eebSPatrick Williams    def _cmd_build_meson(self) -> str:
630ee3c9eebSPatrick Williams        options = " ".join(self.pkg_def.get("config_flags", []))
631ee3c9eebSPatrick Williams        env = " ".join(self.pkg_def.get("config_env", []))
632e2da11adSAndrew Jeffery        result = f"{env} meson setup builddir {meson_flags} {options} && "
633ee3c9eebSPatrick Williams        result += "ninja -C builddir && ninja -C builddir install"
634ee3c9eebSPatrick Williams        return result
635ee3c9eebSPatrick Williams
636ee3c9eebSPatrick Williams
637ee3c9eebSPatrick Williamsclass Docker:
638ee3c9eebSPatrick Williams    """Class to assist with Docker interactions.  All methods are static."""
639ee3c9eebSPatrick Williams
640ee3c9eebSPatrick Williams    @staticmethod
641ee3c9eebSPatrick Williams    def timestamp() -> str:
642ee3c9eebSPatrick Williams        """Generate a timestamp for today using the ISO week."""
643ee3c9eebSPatrick Williams        today = date.today().isocalendar()
644ee3c9eebSPatrick Williams        return f"{today[0]}-W{today[1]:02}"
645ee3c9eebSPatrick Williams
646ee3c9eebSPatrick Williams    @staticmethod
64741d86218SPatrick Williams    def tagname(pkgname: Optional[str], dockerfile: str) -> str:
648ee3c9eebSPatrick Williams        """Generate a tag name for a package using a hash of the Dockerfile."""
649ee3c9eebSPatrick Williams        result = docker_image_name
650ee3c9eebSPatrick Williams        if pkgname:
651ee3c9eebSPatrick Williams            result += "-" + pkgname
652ee3c9eebSPatrick Williams
653ee3c9eebSPatrick Williams        result += ":" + Docker.timestamp()
654ee3c9eebSPatrick Williams        result += "-" + sha256(dockerfile.encode()).hexdigest()[0:16]
655ee3c9eebSPatrick Williams
656ee3c9eebSPatrick Williams        return result
657ee3c9eebSPatrick Williams
658ee3c9eebSPatrick Williams    @staticmethod
659ee3c9eebSPatrick Williams    def build(pkg: str, tag: str, dockerfile: str) -> None:
66022e6110bSAndrew Geissler        """Build a docker image using the Dockerfile and tagging it with 'tag'."""
661ee3c9eebSPatrick Williams
662ee3c9eebSPatrick Williams        # If we're not forcing builds, check if it already exists and skip.
663ee3c9eebSPatrick Williams        if not force_build:
664ee3c9eebSPatrick Williams            if docker.image.ls(tag, "--format", '"{{.Repository}}:{{.Tag}}"'):
66505fb2a0aSPatrick Williams                print(
66605fb2a0aSPatrick Williams                    f"Image {tag} already exists.  Skipping.", file=sys.stderr
66705fb2a0aSPatrick Williams                )
668ee3c9eebSPatrick Williams                return
669ee3c9eebSPatrick Williams
670ee3c9eebSPatrick Williams        # Build it.
671ee3c9eebSPatrick Williams        #   Capture the output of the 'docker build' command and send it to
672ee3c9eebSPatrick Williams        #   stderr (prefixed with the package name).  This allows us to see
673a6ebc6e2SManojkiran Eda        #   progress but not pollute stdout.  Later on we output the final
674ee3c9eebSPatrick Williams        #   docker tag to stdout and we want to keep that pristine.
675ee3c9eebSPatrick Williams        #
676ee3c9eebSPatrick Williams        #   Other unusual flags:
677ee3c9eebSPatrick Williams        #       --no-cache: Bypass the Docker cache if 'force_build'.
678ee3c9eebSPatrick Williams        #       --force-rm: Clean up Docker processes if they fail.
679ee3c9eebSPatrick Williams        docker.build(
680ee3c9eebSPatrick Williams            proxy_args,
681ee3c9eebSPatrick Williams            "--network=host",
682ee3c9eebSPatrick Williams            "--force-rm",
683ee3c9eebSPatrick Williams            "--no-cache=true" if force_build else "--no-cache=false",
684ee3c9eebSPatrick Williams            "-t",
685ee3c9eebSPatrick Williams            tag,
686ee3c9eebSPatrick Williams            "-",
687ee3c9eebSPatrick Williams            _in=dockerfile,
688ee3c9eebSPatrick Williams            _out=(
689ee3c9eebSPatrick Williams                lambda line: print(
690ee3c9eebSPatrick Williams                    pkg + ":", line, end="", file=sys.stderr, flush=True
691ee3c9eebSPatrick Williams                )
692ee3c9eebSPatrick Williams            ),
69388dd7929SJonathan Doman            _err_to_out=True,
694ee3c9eebSPatrick Williams        )
695ee3c9eebSPatrick Williams
696ee3c9eebSPatrick Williams
697ee3c9eebSPatrick Williams# Read a bunch of environment variables.
69805fb2a0aSPatrick Williamsdocker_image_name = os.environ.get(
69905fb2a0aSPatrick Williams    "DOCKER_IMAGE_NAME", "openbmc/ubuntu-unit-test"
70005fb2a0aSPatrick Williams)
701ee3c9eebSPatrick Williamsforce_build = os.environ.get("FORCE_DOCKER_BUILD")
702ee3c9eebSPatrick Williamsis_automated_ci_build = os.environ.get("BUILD_URL", False)
7037c95a37cSPatrick Williamsdistro = os.environ.get("DISTRO", "ubuntu:noble")
704ee3c9eebSPatrick Williamsbranch = os.environ.get("BRANCH", "master")
705ee3c9eebSPatrick Williamsubuntu_mirror = os.environ.get("UBUNTU_MIRROR")
70623ec3323SAndrew Geisslerdocker_reg = os.environ.get("DOCKER_REG", "public.ecr.aws/ubuntu")
707ee3c9eebSPatrick Williamshttp_proxy = os.environ.get("http_proxy")
708ee3c9eebSPatrick Williams
70965b21fb9SPatrick Williamsgerrit_project = os.environ.get("GERRIT_PROJECT")
71065b21fb9SPatrick Williamsgerrit_rev = os.environ.get("GERRIT_PATCHSET_REVISION")
711276bd0e2SPatrick Williamsgerrit_topic = os.environ.get("GERRIT_TOPIC")
71265b21fb9SPatrick Williams
713d0dabc3eSAndrew Geissler# Ensure appropriate docker build output to see progress and identify
714d0dabc3eSAndrew Geissler# any issues
715d0dabc3eSAndrew Geissleros.environ["BUILDKIT_PROGRESS"] = "plain"
716d0dabc3eSAndrew Geissler
717ee3c9eebSPatrick Williams# Set up some common variables.
718ee3c9eebSPatrick Williamsusername = os.environ.get("USER", "root")
719ee3c9eebSPatrick Williamshomedir = os.environ.get("HOME", "/root")
720ee3c9eebSPatrick Williamsgid = os.getgid()
721ee3c9eebSPatrick Williamsuid = os.getuid()
722ee3c9eebSPatrick Williams
7236825a018SJosh Lehan# Use well-known constants if user is root
7246825a018SJosh Lehanif username == "root":
7256825a018SJosh Lehan    homedir = "/root"
7266825a018SJosh Lehan    gid = 0
7276825a018SJosh Lehan    uid = 0
7286825a018SJosh Lehan
72902871c91SPatrick Williams# Special flags if setting up a deb mirror.
73002871c91SPatrick Williamsmirror = ""
73102871c91SPatrick Williamsif "ubuntu" in distro and ubuntu_mirror:
73202871c91SPatrick Williams    mirror = f"""
733e08ffba8SPatrick WilliamsRUN echo "deb {ubuntu_mirror} \
734e08ffba8SPatrick Williams        $(. /etc/os-release && echo $VERSION_CODENAME) \
735e08ffba8SPatrick Williams        main restricted universe multiverse" > /etc/apt/sources.list && \\
736e08ffba8SPatrick Williams    echo "deb {ubuntu_mirror} \
737e08ffba8SPatrick Williams        $(. /etc/os-release && echo $VERSION_CODENAME)-updates \
738e08ffba8SPatrick Williams            main restricted universe multiverse" >> /etc/apt/sources.list && \\
739e08ffba8SPatrick Williams    echo "deb {ubuntu_mirror} \
740e08ffba8SPatrick Williams        $(. /etc/os-release && echo $VERSION_CODENAME)-security \
741e08ffba8SPatrick Williams            main restricted universe multiverse" >> /etc/apt/sources.list && \\
742e08ffba8SPatrick Williams    echo "deb {ubuntu_mirror} \
743e08ffba8SPatrick Williams        $(. /etc/os-release && echo $VERSION_CODENAME)-proposed \
744e08ffba8SPatrick Williams            main restricted universe multiverse" >> /etc/apt/sources.list && \\
745e08ffba8SPatrick Williams    echo "deb {ubuntu_mirror} \
746e08ffba8SPatrick Williams        $(. /etc/os-release && echo $VERSION_CODENAME)-backports \
747e08ffba8SPatrick Williams            main restricted universe multiverse" >> /etc/apt/sources.list
74802871c91SPatrick Williams"""
74902871c91SPatrick Williams
75002871c91SPatrick Williams# Special flags for proxying.
75102871c91SPatrick Williamsproxy_cmd = ""
75234ec77e8SAdrian Ambrożewiczproxy_keyserver = ""
75302871c91SPatrick Williamsproxy_args = []
75402871c91SPatrick Williamsif http_proxy:
75502871c91SPatrick Williams    proxy_cmd = f"""
75602871c91SPatrick WilliamsRUN echo "[http]" >> {homedir}/.gitconfig && \
75702871c91SPatrick Williams    echo "proxy = {http_proxy}" >> {homedir}/.gitconfig
75802871c91SPatrick Williams"""
75934ec77e8SAdrian Ambrożewicz    proxy_keyserver = f"--keyserver-options http-proxy={http_proxy}"
76034ec77e8SAdrian Ambrożewicz
76102871c91SPatrick Williams    proxy_args.extend(
76202871c91SPatrick Williams        [
76302871c91SPatrick Williams            "--build-arg",
76402871c91SPatrick Williams            f"http_proxy={http_proxy}",
76502871c91SPatrick Williams            "--build-arg",
766d461cd6aSLei YU            f"https_proxy={http_proxy}",
76702871c91SPatrick Williams        ]
76802871c91SPatrick Williams    )
76902871c91SPatrick Williams
770ee3c9eebSPatrick Williams# Create base Dockerfile.
771a18d9c57SPatrick Williamsdockerfile_base = f"""
772fe2768c7SAndrew GeisslerFROM {docker_reg}/{distro}
77302871c91SPatrick Williams
77402871c91SPatrick Williams{mirror}
77502871c91SPatrick Williams
77602871c91SPatrick WilliamsENV DEBIAN_FRONTEND noninteractive
77702871c91SPatrick Williams
7788949d3c3SPatrick WilliamsENV PYTHONPATH "/usr/local/lib/python3.10/site-packages/"
77902871c91SPatrick Williams
780bb16ac14SPatrick Williams# Sometimes the ubuntu key expires and we need a way to force an execution
781bb16ac14SPatrick Williams# of the apt-get commands for the dbgsym-keyring.  When this happens we see
782bb16ac14SPatrick Williams# an error like: "Release: The following signatures were invalid:"
783bb16ac14SPatrick Williams# Insert a bogus echo that we can change here when we get this error to force
784bb16ac14SPatrick Williams# the update.
785bb16ac14SPatrick WilliamsRUN echo "ubuntu keyserver rev as of 2021-04-21"
786bb16ac14SPatrick Williams
78702871c91SPatrick Williams# We need the keys to be imported for dbgsym repos
78802871c91SPatrick Williams# New releases have a package, older ones fall back to manual fetching
78902871c91SPatrick Williams# https://wiki.ubuntu.com/Debug%20Symbol%20Packages
790575b5e4cSJagpal Singh Gill# Known issue with gpg to get keys via proxy -
791575b5e4cSJagpal Singh Gill# https://bugs.launchpad.net/ubuntu/+source/gnupg2/+bug/1788190, hence using
792575b5e4cSJagpal Singh Gill# curl to get keys.
79350837436SPatrick WilliamsRUN apt-get update && apt-get dist-upgrade -yy && \
794938d303fSJian Zhang    ( apt-get install -yy gpgv ubuntu-dbgsym-keyring || \
795575b5e4cSJagpal Singh Gill        ( apt-get install -yy dirmngr curl && \
796575b5e4cSJagpal Singh Gill          curl -sSL \
797575b5e4cSJagpal Singh Gill          'https://keyserver.ubuntu.com/pks/lookup?op=get&search=0xF2EDC64DC5AEE1F6B9C621F0C8CAB6595FDFF622' \
798575b5e4cSJagpal Singh Gill          | apt-key add - ))
79902871c91SPatrick Williams
80002871c91SPatrick Williams# Parse the current repo list into a debug repo list
801e08ffba8SPatrick WilliamsRUN sed -n '/^deb /s,^deb [^ ]* ,deb http://ddebs.ubuntu.com ,p' \
802e08ffba8SPatrick Williams        /etc/apt/sources.list >/etc/apt/sources.list.d/debug.list
80302871c91SPatrick Williams
80402871c91SPatrick Williams# Remove non-existent debug repos
80541d86218SPatrick WilliamsRUN sed -i '/-\\(backports\\|security\\) /d' /etc/apt/sources.list.d/debug.list
80602871c91SPatrick Williams
80702871c91SPatrick WilliamsRUN cat /etc/apt/sources.list.d/debug.list
80802871c91SPatrick Williams
80902871c91SPatrick WilliamsRUN apt-get update && apt-get dist-upgrade -yy && apt-get install -yy \
81058f1915eSAndrew Jeffery    abi-compliance-checker \
8118b112068SAndrew Jeffery    abi-dumper \
81202871c91SPatrick Williams    autoconf \
81302871c91SPatrick Williams    autoconf-archive \
814af49ed51SAndrew Geissler    bison \
815af49ed51SAndrew Geissler    cmake \
816af49ed51SAndrew Geissler    curl \
817af49ed51SAndrew Geissler    dbus \
818af49ed51SAndrew Geissler    device-tree-compiler \
819af49ed51SAndrew Geissler    flex \
820dbce976dSAndrew Jeffery    g++-14 \
821dbce976dSAndrew Jeffery    gcc-14 \
822af49ed51SAndrew Geissler    git \
823b4eec87bSPatrick Williams    glib-2.0 \
8246968e83eSPatrick Williams    gnupg \
82502871c91SPatrick Williams    iproute2 \
826af49ed51SAndrew Geissler    iputils-ping \
827524a331cSManojkiran Eda    libaudit-dev \
828af49ed51SAndrew Geissler    libc6-dbg \
829af49ed51SAndrew Geissler    libc6-dev \
830c7bc4d1dSPatrick Williams    libcjson-dev \
831af49ed51SAndrew Geissler    libconfig++-dev \
832af49ed51SAndrew Geissler    libcryptsetup-dev \
833af49ed51SAndrew Geissler    libdbus-1-dev \
834af49ed51SAndrew Geissler    libevdev-dev \
835af49ed51SAndrew Geissler    libgpiod-dev \
836af49ed51SAndrew Geissler    libi2c-dev \
837af49ed51SAndrew Geissler    libjpeg-dev \
838af49ed51SAndrew Geissler    libjson-perl \
839af49ed51SAndrew Geissler    libldap2-dev \
840af49ed51SAndrew Geissler    libmimetic-dev \
84102871c91SPatrick Williams    libnl-3-dev \
84202871c91SPatrick Williams    libnl-genl-3-dev \
84302871c91SPatrick Williams    libpam0g-dev \
84402871c91SPatrick Williams    libpciaccess-dev \
845af49ed51SAndrew Geissler    libperlio-gzip-perl \
846af49ed51SAndrew Geissler    libpng-dev \
847af49ed51SAndrew Geissler    libprotobuf-dev \
848af49ed51SAndrew Geissler    libsnmp-dev \
849af49ed51SAndrew Geissler    libssl-dev \
850af49ed51SAndrew Geissler    libsystemd-dev \
851af49ed51SAndrew Geissler    libtool \
852af49ed51SAndrew Geissler    liburing-dev \
85302871c91SPatrick Williams    libxml2-utils \
8540eedeedaSPatrick Williams    libxml-simple-perl \
8556968e83eSPatrick Williams    lsb-release \
856af49ed51SAndrew Geissler    ninja-build \
857af49ed51SAndrew Geissler    npm \
858af49ed51SAndrew Geissler    pkg-config \
859af49ed51SAndrew Geissler    protobuf-compiler \
860af49ed51SAndrew Geissler    python3 \
861af49ed51SAndrew Geissler    python3-dev\
862af49ed51SAndrew Geissler    python3-git \
863af49ed51SAndrew Geissler    python3-mako \
864af49ed51SAndrew Geissler    python3-pip \
86525ba1e2fSWilliam A. Kennington III    python3-protobuf \
866af49ed51SAndrew Geissler    python3-setuptools \
867af49ed51SAndrew Geissler    python3-socks \
868af49ed51SAndrew Geissler    python3-yaml \
8699adf68d6SJohn Wedig    rsync \
870af49ed51SAndrew Geissler    shellcheck \
8718dd1bfe6SEwelina Walkusz    socat \
8726968e83eSPatrick Williams    software-properties-common \
873af49ed51SAndrew Geissler    sudo \
874af49ed51SAndrew Geissler    systemd \
875af49ed51SAndrew Geissler    valgrind \
876b565f825SAndrew Geissler    vim \
877af49ed51SAndrew Geissler    wget \
878af49ed51SAndrew Geissler    xxd
87902871c91SPatrick Williams
880dbce976dSAndrew JefferyRUN update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-14 14 \
881dbce976dSAndrew Jeffery  --slave /usr/bin/g++ g++ /usr/bin/g++-14 \
882dbce976dSAndrew Jeffery  --slave /usr/bin/gcov gcov /usr/bin/gcov-14 \
883dbce976dSAndrew Jeffery  --slave /usr/bin/gcov-dump gcov-dump /usr/bin/gcov-dump-14 \
884dbce976dSAndrew Jeffery  --slave /usr/bin/gcov-tool gcov-tool /usr/bin/gcov-tool-14
885961f148bSPatrick WilliamsRUN update-alternatives --remove cpp /usr/bin/cpp && \
886dbce976dSAndrew Jeffery    update-alternatives --install /usr/bin/cpp cpp /usr/bin/cpp-14 14
88702871c91SPatrick Williams
8886968e83eSPatrick Williams# Set up LLVM apt repository.
8896968e83eSPatrick WilliamsRUN bash -c "$(wget -O - https://apt.llvm.org/llvm.sh)" 18
8906968e83eSPatrick Williams
8916968e83eSPatrick Williams# Install extra clang tools
8926968e83eSPatrick WilliamsRUN apt-get install \
8936968e83eSPatrick Williams        clang-18 \
8946968e83eSPatrick Williams        clang-format-18 \
8956968e83eSPatrick Williams        clang-tidy-18
8966968e83eSPatrick Williams
897b84e29c0SEd TanousRUN update-alternatives --install /usr/bin/clang clang /usr/bin/clang-18 1000 \
898b84e29c0SEd Tanous  --slave /usr/bin/clang++ clang++ /usr/bin/clang++-18 \
899b84e29c0SEd Tanous  --slave /usr/bin/clang-tidy clang-tidy /usr/bin/clang-tidy-18 \
900b84e29c0SEd Tanous  --slave /usr/bin/clang-format clang-format /usr/bin/clang-format-18 \
901e08ffba8SPatrick Williams  --slave /usr/bin/run-clang-tidy run-clang-tidy.py \
902b84e29c0SEd Tanous        /usr/bin/run-clang-tidy-18 \
903b84e29c0SEd Tanous  --slave /usr/bin/scan-build scan-build /usr/bin/scan-build-18
90402871c91SPatrick Williams
90550837436SPatrick Williams"""
90650837436SPatrick Williams
90750837436SPatrick Williamsif is_automated_ci_build:
90850837436SPatrick Williams    dockerfile_base += f"""
909a6ebc6e2SManojkiran Eda# Run an arbitrary command to pollute the docker cache regularly force us
91050837436SPatrick Williams# to re-run `apt-get update` daily.
911ee3c9eebSPatrick WilliamsRUN echo {Docker.timestamp()}
91250837436SPatrick WilliamsRUN apt-get update && apt-get dist-upgrade -yy
91350837436SPatrick Williams
91450837436SPatrick Williams"""
91550837436SPatrick Williams
91641d86218SPatrick Williamsdockerfile_base += """
9175e4d8402SPatrick WilliamsRUN pip3 install --break-system-packages \
918818023dfSPatrick Williams        beautysh \
919818023dfSPatrick Williams        black \
920818023dfSPatrick Williams        codespell \
921818023dfSPatrick Williams        flake8 \
9222d8c551fSEwelina Walkusz        gcovr \
923818023dfSPatrick Williams        gitlint \
924818023dfSPatrick Williams        inflection \
925f7381ad6SArya K Padman        isoduration \
926818023dfSPatrick Williams        isort \
927818023dfSPatrick Williams        jsonschema \
92816baaf73SPatrick Williams        meson==1.3.0 \
929818023dfSPatrick Williams        requests
930b08ddf77SPatrick Williams
931b08ddf77SPatrick WilliamsRUN npm install -g \
932d0757deaSXinnan Xie        eslint@v8.56.0 eslint-plugin-json@v3.1.0 \
9337d41f6d2SPatrick Williams        markdownlint-cli@latest \
934b08ddf77SPatrick Williams        prettier@latest
935fb9948a3SEd Tanous"""
936fb9948a3SEd Tanous
937ee3c9eebSPatrick Williams# Build the base and stage docker images.
938ee3c9eebSPatrick Williamsdocker_base_img_name = Docker.tagname("base", dockerfile_base)
939ee3c9eebSPatrick WilliamsDocker.build("base", docker_base_img_name, dockerfile_base)
940ee3c9eebSPatrick WilliamsPackage.generate_all()
94102871c91SPatrick Williams
942ee3c9eebSPatrick Williams# Create the final Dockerfile.
943a18d9c57SPatrick Williamsdockerfile = f"""
94402871c91SPatrick Williams# Build the final output image
945a18d9c57SPatrick WilliamsFROM {docker_base_img_name}
946ee3c9eebSPatrick Williams{Package.df_all_copycmds()}
94702871c91SPatrick Williams
94802871c91SPatrick Williams# Some of our infrastructure still relies on the presence of this file
94902871c91SPatrick Williams# even though it is no longer needed to rebuild the docker environment
95002871c91SPatrick Williams# NOTE: The file is sorted to ensure the ordering is stable.
951ee3c9eebSPatrick WilliamsRUN echo '{Package.depcache()}' > /tmp/depcache
95202871c91SPatrick Williams
95367cc0616SPatrick Williams# Ensure the group, user, and home directory are created (or rename them if
95467cc0616SPatrick Williams# they already exist).
95567cc0616SPatrick WilliamsRUN if grep -q ":{gid}:" /etc/group ; then \
95667cc0616SPatrick Williams        groupmod -n {username} $(awk -F : '{{ if ($3 == {gid}) {{ print $1 }} }}' /etc/group) ; \
95767cc0616SPatrick Williams    else \
95867cc0616SPatrick Williams        groupadd -f -g {gid} {username} ; \
95967cc0616SPatrick Williams    fi
96002871c91SPatrick WilliamsRUN mkdir -p "{os.path.dirname(homedir)}"
96167cc0616SPatrick WilliamsRUN if grep -q ":{uid}:" /etc/passwd ; then \
96273b3ee91SPatrick Williams        usermod -l {username} -d {homedir} -m $(awk -F : '{{ if ($3 == {uid}) {{ print $1 }} }}' /etc/passwd) ; \
96367cc0616SPatrick Williams    else \
96467cc0616SPatrick Williams        useradd -d {homedir} -m -u {uid} -g {gid} {username} ; \
96567cc0616SPatrick Williams    fi
96602871c91SPatrick WilliamsRUN sed -i '1iDefaults umask=000' /etc/sudoers
96702871c91SPatrick WilliamsRUN echo "{username} ALL=(ALL) NOPASSWD: ALL" >>/etc/sudoers
96802871c91SPatrick Williams
969305a9a5dSAndrew Geissler# Ensure user has ability to write to /usr/local for different tool
970305a9a5dSAndrew Geissler# and data installs
9717bb00b13SAndrew GeisslerRUN chown -R {username}:{username} /usr/local/share
972305a9a5dSAndrew Geissler
973ab4fee83SJonathan Doman# Update library cache
974ab4fee83SJonathan DomanRUN ldconfig
975ab4fee83SJonathan Doman
97602871c91SPatrick Williams{proxy_cmd}
97702871c91SPatrick Williams
97802871c91SPatrick WilliamsRUN /bin/bash
97902871c91SPatrick Williams"""
98002871c91SPatrick Williams
981a18d9c57SPatrick Williams# Do the final docker build
982ee3c9eebSPatrick Williamsdocker_final_img_name = Docker.tagname(None, dockerfile)
983ee3c9eebSPatrick WilliamsDocker.build("final", docker_final_img_name, dockerfile)
984ee3c9eebSPatrick Williams
98500536fbeSPatrick Williams# Print the tag of the final image.
98600536fbeSPatrick Williamsprint(docker_final_img_name)
987