blob: e5e550d79d6b71e5f09c8f6f3e4fc5b8f0fb34fa [file] [log] [blame]
Patrick Williams02871c92021-02-01 20:57:19 -06001#!/usr/bin/env python3
2#
3# Build the required docker image to run package unit tests
4#
5# Script Variables:
6# DOCKER_IMG_NAME: <optional, the name of the docker image to generate>
7# default is openbmc/ubuntu-unit-test
8# DISTRO: <optional, the distro to build a docker image against>
Patrick Williams50837432021-02-06 12:24:05 -06009# FORCE_DOCKER_BUILD: <optional, a non-zero value with force all Docker
10# images to be rebuilt rather than reusing caches.>
11# BUILD_URL: <optional, used to detect running under CI context
12# (ex. Jenkins)>
Patrick Williams02871c92021-02-01 20:57:19 -060013# BRANCH: <optional, branch to build from each of the openbmc/
14# repositories>
15# default is master, which will be used if input branch not
16# provided or not found
17# UBUNTU_MIRROR: <optional, the URL of a mirror of Ubuntu to override the
18# default ones in /etc/apt/sources.list>
19# default is empty, and no mirror is used.
Andrew Geisslerfe2768c2024-10-02 10:10:29 -040020# DOCKER_REG: <optional, the URL of a docker registry to utilize
Andrew Geissler23ec3322024-10-02 10:45:32 -040021# instead of our default (public.ecr.aws/ubuntu)
22# (ex. docker.io)
Patrick Williams02871c92021-02-01 20:57:19 -060023# http_proxy The HTTP address of the proxy server to connect to.
24# Default: "", proxy is not setup if this is not set
25
Patrick Williams276bd0e2024-10-02 10:34:32 -040026import json
Patrick Williams02871c92021-02-01 20:57:19 -060027import os
Andrew Geisslerf3d27e62024-04-09 15:24:49 -050028import re
Patrick Williams02871c92021-02-01 20:57:19 -060029import sys
Patrick Williamsb16f3e22021-02-06 08:16:47 -060030import threading
Patrick Williams276bd0e2024-10-02 10:34:32 -040031import urllib.request
Patrick Williamsa18d9c52021-02-05 09:52:26 -060032from datetime import date
33from hashlib import sha256
Patrick Williamse08ffba2022-12-05 10:33:46 -060034
35# typing.Dict is used for type-hints.
36from typing import Any, Callable, Dict, Iterable, Optional # noqa: F401
Patrick Williams02871c92021-02-01 20:57:19 -060037
Andrew Geissler8f7146f2024-12-11 14:20:47 -060038from sh import git, nproc # type: ignore
39
40try:
41 # System may have docker or it may have podman, try docker first
42 from sh import docker
43
44 container = docker
45except ImportError:
46 try:
47 from sh import podman
48
49 container = podman
50 except Exception:
51 print("No docker or podman found on system")
52 exit(1)
Patrick Williams41d86212022-11-25 18:28:43 -060053
Patrick Williamsee3c9ee2021-02-12 20:56:01 -060054try:
55 # Python before 3.8 doesn't have TypedDict, so reroute to standard 'dict'.
56 from typing import TypedDict
Patrick Williams41d86212022-11-25 18:28:43 -060057except Exception:
Patrick Williamsee3c9ee2021-02-12 20:56:01 -060058
59 class TypedDict(dict): # type: ignore
60 # We need to do this to eat the 'total' argument.
Patrick Williams41d86212022-11-25 18:28:43 -060061 def __init_subclass__(cls, **kwargs: Any) -> None:
Patrick Williamsee3c9ee2021-02-12 20:56:01 -060062 super().__init_subclass__()
63
64
65# Declare some variables used in package definitions.
Patrick Williamsaae36d12021-02-04 16:30:04 -060066prefix = "/usr/local"
Patrick Williams02871c92021-02-01 20:57:19 -060067proc_count = nproc().strip()
Patrick Williams02871c92021-02-01 20:57:19 -060068
Patrick Williamsee3c9ee2021-02-12 20:56:01 -060069
70class PackageDef(TypedDict, total=False):
Patrick Williams05fb2a02022-10-11 17:22:33 -050071 """Package Definition for packages dictionary."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -060072
73 # rev [optional]: Revision of package to use.
74 rev: str
75 # url [optional]: lambda function to create URL: (package, rev) -> url.
76 url: Callable[[str, str], str]
77 # depends [optional]: List of package dependencies.
78 depends: Iterable[str]
79 # build_type [required]: Build type used for package.
80 # Currently supported: autoconf, cmake, custom, make, meson
81 build_type: str
82 # build_steps [optional]: Steps to run for 'custom' build_type.
83 build_steps: Iterable[str]
84 # config_flags [optional]: List of options to pass configuration tool.
85 config_flags: Iterable[str]
86 # config_env [optional]: List of environment variables to set for config.
87 config_env: Iterable[str]
88 # custom_post_dl [optional]: List of steps to run after download, but
89 # before config / build / install.
90 custom_post_dl: Iterable[str]
Patrick Williams6bce2ca2021-02-12 21:13:37 -060091 # custom_post_install [optional]: List of steps to run after install.
92 custom_post_install: Iterable[str]
Patrick Williamsee3c9ee2021-02-12 20:56:01 -060093
94 # __tag [private]: Generated Docker tag name for package stage.
95 __tag: str
96 # __package [private]: Package object associated with this package.
97 __package: Any # Type is Package, but not defined yet.
98
Patrick Williams02871c92021-02-01 20:57:19 -060099
Patrick Williams72043242021-02-02 10:31:45 -0600100# Packages to include in image.
101packages = {
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600102 "boost": PackageDef(
Patrick Williamse4b761f2025-07-23 11:34:07 -0400103 rev="1.88.0",
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600104 url=(
Jayanth Othayoth96982152024-12-12 05:13:54 -0600105 lambda pkg, rev: f"https://github.com/boostorg/{pkg}/releases/download/{pkg}-{rev}/{pkg}-{rev}-cmake.tar.gz"
Patrick Williams2abc4a42021-02-03 06:11:40 -0600106 ),
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600107 build_type="custom",
108 build_steps=[
Patrick Williamse08ffba2022-12-05 10:33:46 -0600109 (
Andrew Geissler38b46872024-01-07 07:20:27 -0600110 "./bootstrap.sh"
Jayanth Othayoth96982152024-12-12 05:13:54 -0600111 f" --prefix={prefix} --with-libraries=atomic,context,coroutine,filesystem,process,url"
Patrick Williamse08ffba2022-12-05 10:33:46 -0600112 ),
Patrick Williamsaae36d12021-02-04 16:30:04 -0600113 "./b2",
Michal Orzel04770cc2024-06-18 10:38:22 +0200114 f"./b2 install --prefix={prefix} valgrind=on",
Patrick Williamsaae36d12021-02-04 16:30:04 -0600115 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600116 ),
117 "USCiLab/cereal": PackageDef(
Patrick Williamsc1977832022-09-27 16:54:34 -0500118 rev="v1.3.2",
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600119 build_type="custom",
120 build_steps=[f"cp -a include/cereal/ {prefix}/include/"],
121 ),
Ed Tanousc7198552022-07-01 08:15:50 -0700122 "danmar/cppcheck": PackageDef(
Patrick Williams51021782023-12-05 19:10:44 -0600123 rev="2.12.1",
Ed Tanousc7198552022-07-01 08:15:50 -0700124 build_type="cmake",
125 ),
Ratan Gupta3dc37e62025-07-17 16:47:13 +0530126 "DMTF/libspdm": PackageDef(
127 rev="3.7.0",
128 url=lambda pkg, rev: f"https://github.com/DMTF/libspdm/archive/{rev}.tar.gz",
129 build_type="cmake",
130 config_flags=(
131 lambda: (
132 lambda arch_mapping={
133 "x86_64": "x64",
134 "i586": "ia32",
135 "i686": "ia32",
136 "arm": "arm",
137 "aarch64": "aarch64",
138 "arm64": "aarch64",
139 "riscv32": "riscv32",
140 "riscv64": "riscv64",
141 "ppc64le": "ppc64le",
142 }: [
143 f"-DARCH={arch_mapping.get(__import__('platform').machine(), 'x64')}",
144 "-DTOOLCHAIN=GCC",
145 "-DTARGET=Release",
146 "-DCRYPTO=openssl",
147 "-DBUILD_LINUX_SHARED_LIB=ON",
148 "-DENABLE_BINARY_BUILD=1",
149 "-DDISABLE_TESTS=1",
150 f"-DCOMPILED_LIBCRYPTO_PATH={prefix}/lib",
151 f"-DCOMPILED_LIBSSL_PATH={prefix}/lib",
152 ]
153 )()
154 )(),
155 ),
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600156 "CLIUtils/CLI11": PackageDef(
Patrick Williamsfc397332023-07-17 11:35:43 -0500157 rev="v2.3.2",
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600158 build_type="cmake",
159 config_flags=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600160 "-DBUILD_TESTING=OFF",
161 "-DCLI11_BUILD_DOCS=OFF",
162 "-DCLI11_BUILD_EXAMPLES=OFF",
163 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600164 ),
165 "fmtlib/fmt": PackageDef(
Patrick Williamse4b761f2025-07-23 11:34:07 -0400166 rev="11.2.0",
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600167 build_type="cmake",
168 config_flags=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600169 "-DFMT_DOC=OFF",
170 "-DFMT_TEST=OFF",
171 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600172 ),
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600173 "Naios/function2": PackageDef(
Patrick Williamscb099742023-12-05 19:12:09 -0600174 rev="4.2.4",
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600175 build_type="custom",
176 build_steps=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600177 f"mkdir {prefix}/include/function2",
178 f"cp include/function2/function2.hpp {prefix}/include/function2/",
179 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600180 ),
181 "google/googletest": PackageDef(
Patrick Williamse4b761f2025-07-23 11:34:07 -0400182 rev="v1.16.0",
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600183 build_type="cmake",
William A. Kennington III4dd32c02021-05-28 01:58:13 -0700184 config_env=["CXXFLAGS=-std=c++20"],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600185 config_flags=["-DTHREADS_PREFER_PTHREAD_FLAG=ON"],
186 ),
Ed Tanous178b4b22023-06-15 09:03:11 -0700187 "nghttp2/nghttp2": PackageDef(
Patrick Williamse4b761f2025-07-23 11:34:07 -0400188 rev="v1.65.0",
Ed Tanous178b4b22023-06-15 09:03:11 -0700189 build_type="cmake",
190 config_env=["CXXFLAGS=-std=c++20"],
191 config_flags=[
192 "-DENABLE_LIB_ONLY=ON",
193 "-DENABLE_STATIC_LIB=ON",
194 ],
195 ),
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600196 "nlohmann/json": PackageDef(
Patrick Williamse4b761f2025-07-23 11:34:07 -0400197 rev="v3.12.0",
Patrick Williams6bce2ca2021-02-12 21:13:37 -0600198 build_type="cmake",
199 config_flags=["-DJSON_BuildTests=OFF"],
200 custom_post_install=[
Patrick Williamse08ffba2022-12-05 10:33:46 -0600201 (
202 f"ln -s {prefix}/include/nlohmann/json.hpp"
203 f" {prefix}/include/json.hpp"
204 ),
Patrick Williamsaae36d12021-02-04 16:30:04 -0600205 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600206 ),
Przemyslaw Czarnowski058e3a32022-12-21 14:13:23 +0100207 "json-c/json-c": PackageDef(
Patrick Williamse4b761f2025-07-23 11:34:07 -0400208 rev="json-c-0.18-20240915",
Przemyslaw Czarnowski058e3a32022-12-21 14:13:23 +0100209 build_type="cmake",
210 ),
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600211 "LibVNC/libvncserver": PackageDef(
Patrick Williamsc0421322023-12-05 19:18:57 -0600212 rev="LibVNCServer-0.9.14",
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600213 build_type="cmake",
214 ),
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600215 "leethomason/tinyxml2": PackageDef(
Patrick Williamse4b761f2025-07-23 11:34:07 -0400216 rev="11.0.0",
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600217 build_type="cmake",
218 ),
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600219 "tristanpenman/valijson": PackageDef(
Patrick Williamse4b761f2025-07-23 11:34:07 -0400220 rev="v1.0.5",
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600221 build_type="cmake",
222 config_flags=[
Patrick Williams0eedeed2021-02-06 19:06:09 -0600223 "-Dvalijson_BUILD_TESTS=0",
224 "-Dvalijson_INSTALL_HEADERS=1",
Patrick Williamsaae36d12021-02-04 16:30:04 -0600225 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600226 ),
Patrick Williamsc7e719f2025-07-24 16:51:57 -0400227 "libgpiod": PackageDef(
228 rev="1.6.5",
229 url=(
230 lambda pkg, rev: f"https://git.kernel.org/pub/scm/libs/{pkg}/{pkg}.git/snapshot/{pkg}-{rev}.tar.gz"
231 ),
232 build_type="autogen",
233 config_flags=["--enable-bindings-cxx"],
234 ),
Patrick Williams3a7693c2025-12-19 18:28:40 -0500235 "NVIDIA/stdexec": PackageDef(
Patrick Williams3e8e6942026-01-05 15:48:00 -0500236 rev="250f35737790392d666fd157e0af9be16d0c789f",
Patrick Williams3a7693c2025-12-19 18:28:40 -0500237 build_type="meson",
238 ),
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600239 "open-power/pdbg": PackageDef(build_type="autoconf"),
240 "openbmc/gpioplus": PackageDef(
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600241 build_type="meson",
242 config_flags=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600243 "-Dexamples=false",
244 "-Dtests=disabled",
245 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600246 ),
247 "openbmc/phosphor-dbus-interfaces": PackageDef(
248 depends=["openbmc/sdbusplus"],
249 build_type="meson",
William A. Kennington III4fe87772022-02-11 15:44:29 -0800250 config_flags=["-Dgenerate_md=false"],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600251 ),
252 "openbmc/phosphor-logging": PackageDef(
253 depends=[
Patrick Williams83394612021-02-03 07:12:50 -0600254 "USCiLab/cereal",
Patrick Williams83394612021-02-03 07:12:50 -0600255 "openbmc/phosphor-dbus-interfaces",
256 "openbmc/sdbusplus",
257 "openbmc/sdeventplus",
Patrick Williamsaae36d12021-02-04 16:30:04 -0600258 ],
Patrick Williamsf79ce4c2021-04-30 16:00:49 -0500259 build_type="meson",
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600260 config_flags=[
William A. Kennington III6c98f282022-10-05 13:37:04 -0700261 "-Dlibonly=true",
262 "-Dtests=disabled",
Patrick Williamsaae36d12021-02-04 16:30:04 -0600263 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600264 ),
265 "openbmc/phosphor-objmgr": PackageDef(
266 depends=[
Brad Bishop11e57622022-09-14 16:10:25 -0400267 "CLIUtils/CLI11",
Patrick Williams70af95c2022-09-27 16:55:41 -0500268 "boost",
Patrick Williams83394612021-02-03 07:12:50 -0600269 "leethomason/tinyxml2",
Patrick Williams70af95c2022-09-27 16:55:41 -0500270 "openbmc/phosphor-dbus-interfaces",
Patrick Williams83394612021-02-03 07:12:50 -0600271 "openbmc/phosphor-logging",
272 "openbmc/sdbusplus",
Patrick Williamsaae36d12021-02-04 16:30:04 -0600273 ],
Brad Bishop1197e352021-08-03 19:25:46 -0400274 build_type="meson",
275 config_flags=[
276 "-Dtests=disabled",
277 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600278 ),
Jason M. Billsc02ff272023-08-02 10:55:22 -0700279 "openbmc/libpeci": PackageDef(
280 build_type="meson",
281 config_flags=[
282 "-Draw-peci=disabled",
283 ],
284 ),
Manojkiran Eda1c19e452022-10-03 11:01:59 +0530285 "openbmc/libpldm": PackageDef(
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600286 build_type="meson",
Andrew Jeffery29163972024-12-06 17:01:56 +1030287 config_flags=[
288 "-Dabi=deprecated,stable",
289 "-Dtests=false",
290 "-Dabi-compliance-check=false",
291 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600292 ),
293 "openbmc/sdbusplus": PackageDef(
Patrick Williams54d01da2024-09-25 06:40:25 -0400294 depends=[
Patrick Williams3a7693c2025-12-19 18:28:40 -0500295 "NVIDIA/stdexec",
Patrick Williams54d01da2024-09-25 06:40:25 -0400296 "nlohmann/json",
297 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600298 build_type="meson",
299 custom_post_dl=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600300 "cd tools",
Patrick Williams3e9c0072025-08-27 10:45:22 -0400301 "python3 -m pip install --break-system-packages --root-user-action ignore .",
Patrick Williamsaae36d12021-02-04 16:30:04 -0600302 "cd ..",
303 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600304 config_flags=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600305 "-Dexamples=disabled",
306 "-Dtests=disabled",
307 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600308 ),
309 "openbmc/sdeventplus": PackageDef(
Patrick Williams70af95c2022-09-27 16:55:41 -0500310 depends=[
Patrick Williams70af95c2022-09-27 16:55:41 -0500311 "openbmc/stdplus",
312 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600313 build_type="meson",
314 config_flags=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600315 "-Dexamples=false",
316 "-Dtests=disabled",
317 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600318 ),
319 "openbmc/stdplus": PackageDef(
Patrick Williams70af95c2022-09-27 16:55:41 -0500320 depends=[
Patrick Williams70af95c2022-09-27 16:55:41 -0500321 "fmtlib/fmt",
William A. Kennington IIIca1bf0c2022-10-05 02:23:30 -0700322 "google/googletest",
323 "Naios/function2",
Patrick Williams70af95c2022-09-27 16:55:41 -0500324 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600325 build_type="meson",
326 config_flags=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600327 "-Dexamples=false",
328 "-Dtests=disabled",
William A. Kennington IIIca1bf0c2022-10-05 02:23:30 -0700329 "-Dgtest=enabled",
Patrick Williamsaae36d12021-02-04 16:30:04 -0600330 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600331 ),
332} # type: Dict[str, PackageDef]
Patrick Williams02871c92021-02-01 20:57:19 -0600333
334# Define common flags used for builds
Patrick Williams02871c92021-02-01 20:57:19 -0600335configure_flags = " ".join(
336 [
337 f"--prefix={prefix}",
338 ]
339)
340cmake_flags = " ".join(
341 [
Patrick Williams02871c92021-02-01 20:57:19 -0600342 "-DBUILD_SHARED_LIBS=ON",
Patrick Williams0f2086b2021-02-05 06:49:49 -0600343 "-DCMAKE_BUILD_TYPE=RelWithDebInfo",
Patrick Williams02871c92021-02-01 20:57:19 -0600344 f"-DCMAKE_INSTALL_PREFIX:PATH={prefix}",
Patrick Williams0f2086b2021-02-05 06:49:49 -0600345 "-GNinja",
346 "-DCMAKE_MAKE_PROGRAM=ninja",
Patrick Williams02871c92021-02-01 20:57:19 -0600347 ]
348)
349meson_flags = " ".join(
350 [
351 "--wrap-mode=nodownload",
352 f"-Dprefix={prefix}",
353 ]
354)
355
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600356
357class Package(threading.Thread):
358 """Class used to build the Docker stages for each package.
359
360 Generally, this class should not be instantiated directly but through
361 Package.generate_all().
362 """
363
364 # Copy the packages dictionary.
365 packages = packages.copy()
366
367 # Lock used for thread-safety.
368 lock = threading.Lock()
369
370 def __init__(self, pkg: str):
Patrick Williams05fb2a02022-10-11 17:22:33 -0500371 """pkg - The name of this package (ex. foo/bar )"""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600372 super(Package, self).__init__()
373
374 self.package = pkg
375 self.exception = None # type: Optional[Exception]
376
377 # Reference to this package's
378 self.pkg_def = Package.packages[pkg]
379 self.pkg_def["__package"] = self
380
381 def run(self) -> None:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500382 """Thread 'run' function. Builds the Docker stage."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600383
384 # In case this package has no rev, fetch it from Github.
385 self._update_rev()
386
387 # Find all the Package objects that this package depends on.
388 # This section is locked because we are looking into another
389 # package's PackageDef dict, which could be being modified.
390 Package.lock.acquire()
391 deps: Iterable[Package] = [
392 Package.packages[deppkg]["__package"]
393 for deppkg in self.pkg_def.get("depends", [])
394 ]
395 Package.lock.release()
396
397 # Wait until all the depends finish building. We need them complete
398 # for the "COPY" commands.
399 for deppkg in deps:
400 deppkg.join()
401
402 # Generate this package's Dockerfile.
403 dockerfile = f"""
404FROM {docker_base_img_name}
405{self._df_copycmds()}
406{self._df_build()}
407"""
408
409 # Generate the resulting tag name and save it to the PackageDef.
410 # This section is locked because we are modifying the PackageDef,
411 # which can be accessed by other threads.
412 Package.lock.acquire()
413 tag = Docker.tagname(self._stagename(), dockerfile)
414 self.pkg_def["__tag"] = tag
415 Package.lock.release()
416
417 # Do the build / save any exceptions.
418 try:
419 Docker.build(self.package, tag, dockerfile)
420 except Exception as e:
421 self.exception = e
422
423 @classmethod
424 def generate_all(cls) -> None:
425 """Ensure a Docker stage is created for all defined packages.
426
427 These are done in parallel but with appropriate blocking per
428 package 'depends' specifications.
429 """
430
431 # Create a Package for each defined package.
432 pkg_threads = [Package(p) for p in cls.packages.keys()]
433
434 # Start building them all.
Patrick Williams6dbd7802021-02-20 08:34:10 -0600435 # This section is locked because threads depend on each other,
436 # based on the packages, and they cannot 'join' on a thread
437 # which is not yet started. Adding a lock here allows all the
438 # threads to start before they 'join' their dependencies.
439 Package.lock.acquire()
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600440 for t in pkg_threads:
441 t.start()
Patrick Williams6dbd7802021-02-20 08:34:10 -0600442 Package.lock.release()
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600443
444 # Wait for completion.
445 for t in pkg_threads:
446 t.join()
447 # Check if the thread saved off its own exception.
448 if t.exception:
449 print(f"Package {t.package} failed!", file=sys.stderr)
450 raise t.exception
451
452 @staticmethod
453 def df_all_copycmds() -> str:
454 """Formulate the Dockerfile snippet necessary to copy all packages
455 into the final image.
456 """
457 return Package.df_copycmds_set(Package.packages.keys())
458
459 @classmethod
460 def depcache(cls) -> str:
461 """Create the contents of the '/tmp/depcache'.
462 This file is a comma-separated list of "<pkg>:<rev>".
463 """
464
465 # This needs to be sorted for consistency.
466 depcache = ""
467 for pkg in sorted(cls.packages.keys()):
468 depcache += "%s:%s," % (pkg, cls.packages[pkg]["rev"])
469 return depcache
470
Patrick Williams276bd0e2024-10-02 10:34:32 -0400471 def _check_gerrit_topic(self) -> bool:
472 if not gerrit_topic:
473 return False
474 if not self.package.startswith("openbmc/"):
475 return False
476 if gerrit_project == self.package and gerrit_rev:
477 return False
478
Patrick Williams1c847972025-09-12 17:10:31 -0400479 # URL escape any spaces. Gerrit uses pluses.
480 gerrit_topic_escape = urllib.parse.quote_plus(gerrit_topic)
481
Patrick Williams276bd0e2024-10-02 10:34:32 -0400482 try:
483 commits = json.loads(
484 urllib.request.urlopen(
Patrick Williams1c847972025-09-12 17:10:31 -0400485 f'https://gerrit.openbmc.org/changes/?q=status:open+project:{self.package}+topic:"{gerrit_topic_escape}"'
Patrick Williams276bd0e2024-10-02 10:34:32 -0400486 )
487 .read()
488 .splitlines()[-1]
489 )
490
491 if len(commits) == 0:
492 return False
493 if len(commits) > 1:
494 print(
495 f"{self.package} has more than 1 commit under {gerrit_topic}; using lastest upstream: {len(commits)}",
496 file=sys.stderr,
497 )
498 return False
499
500 change_id = commits[0]["id"]
501
502 commit = json.loads(
503 urllib.request.urlopen(
504 f"https://gerrit.openbmc.org/changes/{change_id}/revisions/current/commit"
505 )
506 .read()
507 .splitlines()[-1]
508 )["commit"]
509
510 print(
511 f"Using {commit} from {gerrit_topic} for {self.package}",
512 file=sys.stderr,
513 )
514 self.pkg_def["rev"] = commit
515 return True
516
517 except urllib.error.HTTPError as e:
518 print(
519 f"Error loading topic {gerrit_topic} for {self.package}: ",
520 e,
521 file=sys.stderr,
522 )
523 return False
524
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600525 def _update_rev(self) -> None:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500526 """Look up the HEAD for missing a static rev."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600527
528 if "rev" in self.pkg_def:
529 return
530
Patrick Williams276bd0e2024-10-02 10:34:32 -0400531 if self._check_gerrit_topic():
532 return
533
Patrick Williams65b21fb2021-02-12 21:21:14 -0600534 # Check if Jenkins/Gerrit gave us a revision and use it.
535 if gerrit_project == self.package and gerrit_rev:
536 print(
537 f"Found Gerrit revision for {self.package}: {gerrit_rev}",
538 file=sys.stderr,
539 )
540 self.pkg_def["rev"] = gerrit_rev
541 return
542
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600543 # Ask Github for all the branches.
Patrick Williams05fb2a02022-10-11 17:22:33 -0500544 lookup = git(
545 "ls-remote", "--heads", f"https://github.com/{self.package}"
546 )
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600547
548 # Find the branch matching {branch} (or fallback to master).
549 # This section is locked because we are modifying the PackageDef.
550 Package.lock.acquire()
551 for line in lookup.split("\n"):
Andrew Geisslerf3d27e62024-04-09 15:24:49 -0500552 if re.fullmatch(f".*{branch}$", line.strip()):
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600553 self.pkg_def["rev"] = line.split()[0]
Andrew Geisslerf3d27e62024-04-09 15:24:49 -0500554 break
Patrick Williamsc7d73642022-10-11 17:22:06 -0500555 elif (
556 "refs/heads/master" in line or "refs/heads/main" in line
557 ) and "rev" not in self.pkg_def:
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600558 self.pkg_def["rev"] = line.split()[0]
559 Package.lock.release()
560
561 def _stagename(self) -> str:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500562 """Create a name for the Docker stage associated with this pkg."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600563 return self.package.replace("/", "-").lower()
564
565 def _url(self) -> str:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500566 """Get the URL for this package."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600567 rev = self.pkg_def["rev"]
568
569 # If the lambda exists, call it.
570 if "url" in self.pkg_def:
571 return self.pkg_def["url"](self.package, rev)
572
573 # Default to the github archive URL.
574 return f"https://github.com/{self.package}/archive/{rev}.tar.gz"
575
576 def _cmd_download(self) -> str:
577 """Formulate the command necessary to download and unpack to source."""
578
579 url = self._url()
580 if ".tar." not in url:
581 raise NotImplementedError(
582 f"Unhandled download type for {self.package}: {url}"
583 )
584
585 cmd = f"curl -L {url} | tar -x"
586
587 if url.endswith(".bz2"):
588 cmd += "j"
589 elif url.endswith(".gz"):
590 cmd += "z"
591 else:
592 raise NotImplementedError(
593 f"Unknown tar flags needed for {self.package}: {url}"
594 )
595
596 return cmd
597
598 def _cmd_cd_srcdir(self) -> str:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500599 """Formulate the command necessary to 'cd' into the source dir."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600600 return f"cd {self.package.split('/')[-1]}*"
601
602 def _df_copycmds(self) -> str:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500603 """Formulate the dockerfile snippet necessary to COPY all depends."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600604
605 if "depends" not in self.pkg_def:
606 return ""
607 return Package.df_copycmds_set(self.pkg_def["depends"])
608
609 @staticmethod
610 def df_copycmds_set(pkgs: Iterable[str]) -> str:
611 """Formulate the Dockerfile snippet necessary to COPY a set of
612 packages into a Docker stage.
613 """
614
615 copy_cmds = ""
616
617 # Sort the packages for consistency.
618 for p in sorted(pkgs):
619 tag = Package.packages[p]["__tag"]
620 copy_cmds += f"COPY --from={tag} {prefix} {prefix}\n"
621 # Workaround for upstream docker bug and multiple COPY cmds
622 # https://github.com/moby/moby/issues/37965
623 copy_cmds += "RUN true\n"
624
625 return copy_cmds
626
627 def _df_build(self) -> str:
628 """Formulate the Dockerfile snippet necessary to download, build, and
629 install a package into a Docker stage.
630 """
631
632 # Download and extract source.
633 result = f"RUN {self._cmd_download()} && {self._cmd_cd_srcdir()} && "
634
635 # Handle 'custom_post_dl' commands.
636 custom_post_dl = self.pkg_def.get("custom_post_dl")
637 if custom_post_dl:
638 result += " && ".join(custom_post_dl) + " && "
639
640 # Build and install package based on 'build_type'.
641 build_type = self.pkg_def["build_type"]
642 if build_type == "autoconf":
643 result += self._cmd_build_autoconf()
Patrick Williamsc7e719f2025-07-24 16:51:57 -0400644 elif build_type == "autogen":
645 result += self._cmd_build_autogen()
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600646 elif build_type == "cmake":
647 result += self._cmd_build_cmake()
648 elif build_type == "custom":
649 result += self._cmd_build_custom()
650 elif build_type == "make":
651 result += self._cmd_build_make()
652 elif build_type == "meson":
653 result += self._cmd_build_meson()
654 else:
655 raise NotImplementedError(
656 f"Unhandled build type for {self.package}: {build_type}"
657 )
658
Patrick Williams6bce2ca2021-02-12 21:13:37 -0600659 # Handle 'custom_post_install' commands.
660 custom_post_install = self.pkg_def.get("custom_post_install")
661 if custom_post_install:
662 result += " && " + " && ".join(custom_post_install)
663
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600664 return result
665
666 def _cmd_build_autoconf(self) -> str:
667 options = " ".join(self.pkg_def.get("config_flags", []))
668 env = " ".join(self.pkg_def.get("config_env", []))
669 result = "./bootstrap.sh && "
670 result += f"{env} ./configure {configure_flags} {options} && "
671 result += f"make -j{proc_count} && make install"
672 return result
673
Patrick Williamsc7e719f2025-07-24 16:51:57 -0400674 def _cmd_build_autogen(self) -> str:
675 options = " ".join(self.pkg_def.get("config_flags", []))
676 env = " ".join(self.pkg_def.get("config_env", []))
677 result = f"{env} ./autogen.sh {configure_flags} {options} && "
678 result += "make && make install"
679 return result
680
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600681 def _cmd_build_cmake(self) -> str:
682 options = " ".join(self.pkg_def.get("config_flags", []))
683 env = " ".join(self.pkg_def.get("config_env", []))
684 result = "mkdir builddir && cd builddir && "
685 result += f"{env} cmake {cmake_flags} {options} .. && "
686 result += "cmake --build . --target all && "
687 result += "cmake --build . --target install && "
688 result += "cd .."
689 return result
690
691 def _cmd_build_custom(self) -> str:
692 return " && ".join(self.pkg_def.get("build_steps", []))
693
694 def _cmd_build_make(self) -> str:
695 return f"make -j{proc_count} && make install"
696
697 def _cmd_build_meson(self) -> str:
698 options = " ".join(self.pkg_def.get("config_flags", []))
699 env = " ".join(self.pkg_def.get("config_env", []))
Andrew Jefferye2da11a2023-06-15 10:16:37 +0930700 result = f"{env} meson setup builddir {meson_flags} {options} && "
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600701 result += "ninja -C builddir && ninja -C builddir install"
702 return result
703
704
705class Docker:
706 """Class to assist with Docker interactions. All methods are static."""
707
708 @staticmethod
709 def timestamp() -> str:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500710 """Generate a timestamp for today using the ISO week."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600711 today = date.today().isocalendar()
712 return f"{today[0]}-W{today[1]:02}"
713
714 @staticmethod
Patrick Williams41d86212022-11-25 18:28:43 -0600715 def tagname(pkgname: Optional[str], dockerfile: str) -> str:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500716 """Generate a tag name for a package using a hash of the Dockerfile."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600717 result = docker_image_name
718 if pkgname:
719 result += "-" + pkgname
720
721 result += ":" + Docker.timestamp()
722 result += "-" + sha256(dockerfile.encode()).hexdigest()[0:16]
723
724 return result
725
726 @staticmethod
727 def build(pkg: str, tag: str, dockerfile: str) -> None:
Andrew Geissler22e61102023-02-14 14:44:00 -0600728 """Build a docker image using the Dockerfile and tagging it with 'tag'."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600729
730 # If we're not forcing builds, check if it already exists and skip.
731 if not force_build:
Andrew Geissler8f7146f2024-12-11 14:20:47 -0600732 if container.image.ls(
733 tag, "--format", '"{{.Repository}}:{{.Tag}}"'
734 ):
Patrick Williams05fb2a02022-10-11 17:22:33 -0500735 print(
736 f"Image {tag} already exists. Skipping.", file=sys.stderr
737 )
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600738 return
739
740 # Build it.
741 # Capture the output of the 'docker build' command and send it to
742 # stderr (prefixed with the package name). This allows us to see
Manojkiran Edaa6ebc6e2024-06-17 11:51:45 +0530743 # progress but not pollute stdout. Later on we output the final
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600744 # docker tag to stdout and we want to keep that pristine.
745 #
746 # Other unusual flags:
747 # --no-cache: Bypass the Docker cache if 'force_build'.
748 # --force-rm: Clean up Docker processes if they fail.
Andrew Geissler8f7146f2024-12-11 14:20:47 -0600749 container.build(
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600750 proxy_args,
751 "--network=host",
752 "--force-rm",
753 "--no-cache=true" if force_build else "--no-cache=false",
754 "-t",
755 tag,
756 "-",
757 _in=dockerfile,
758 _out=(
759 lambda line: print(
760 pkg + ":", line, end="", file=sys.stderr, flush=True
761 )
762 ),
Jonathan Doman88dd7922024-05-02 10:34:21 -0700763 _err_to_out=True,
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600764 )
765
766
767# Read a bunch of environment variables.
Patrick Williams05fb2a02022-10-11 17:22:33 -0500768docker_image_name = os.environ.get(
769 "DOCKER_IMAGE_NAME", "openbmc/ubuntu-unit-test"
770)
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600771force_build = os.environ.get("FORCE_DOCKER_BUILD")
772is_automated_ci_build = os.environ.get("BUILD_URL", False)
Patrick Williams6b141902025-07-23 11:24:11 -0400773distro = os.environ.get("DISTRO", "ubuntu:plucky")
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600774branch = os.environ.get("BRANCH", "master")
775ubuntu_mirror = os.environ.get("UBUNTU_MIRROR")
Andrew Geissler23ec3322024-10-02 10:45:32 -0400776docker_reg = os.environ.get("DOCKER_REG", "public.ecr.aws/ubuntu")
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600777http_proxy = os.environ.get("http_proxy")
778
Patrick Williams65b21fb2021-02-12 21:21:14 -0600779gerrit_project = os.environ.get("GERRIT_PROJECT")
780gerrit_rev = os.environ.get("GERRIT_PATCHSET_REVISION")
Patrick Williams276bd0e2024-10-02 10:34:32 -0400781gerrit_topic = os.environ.get("GERRIT_TOPIC")
Patrick Williams65b21fb2021-02-12 21:21:14 -0600782
Andrew Geisslerd0dabc32023-04-04 08:09:21 -0600783# Ensure appropriate docker build output to see progress and identify
784# any issues
785os.environ["BUILDKIT_PROGRESS"] = "plain"
786
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600787# Set up some common variables.
788username = os.environ.get("USER", "root")
789homedir = os.environ.get("HOME", "/root")
790gid = os.getgid()
791uid = os.getuid()
792
Josh Lehan6825a012022-03-17 18:31:39 -0700793# Use well-known constants if user is root
794if username == "root":
795 homedir = "/root"
796 gid = 0
797 uid = 0
798
Patrick Williams02871c92021-02-01 20:57:19 -0600799# Special flags if setting up a deb mirror.
800mirror = ""
801if "ubuntu" in distro and ubuntu_mirror:
802 mirror = f"""
Patrick Williamse08ffba2022-12-05 10:33:46 -0600803RUN echo "deb {ubuntu_mirror} \
804 $(. /etc/os-release && echo $VERSION_CODENAME) \
805 main restricted universe multiverse" > /etc/apt/sources.list && \\
806 echo "deb {ubuntu_mirror} \
807 $(. /etc/os-release && echo $VERSION_CODENAME)-updates \
808 main restricted universe multiverse" >> /etc/apt/sources.list && \\
809 echo "deb {ubuntu_mirror} \
810 $(. /etc/os-release && echo $VERSION_CODENAME)-security \
811 main restricted universe multiverse" >> /etc/apt/sources.list && \\
812 echo "deb {ubuntu_mirror} \
813 $(. /etc/os-release && echo $VERSION_CODENAME)-proposed \
814 main restricted universe multiverse" >> /etc/apt/sources.list && \\
815 echo "deb {ubuntu_mirror} \
816 $(. /etc/os-release && echo $VERSION_CODENAME)-backports \
817 main restricted universe multiverse" >> /etc/apt/sources.list
Patrick Williams02871c92021-02-01 20:57:19 -0600818"""
819
820# Special flags for proxying.
821proxy_cmd = ""
Adrian Ambrożewicz34ec77e2021-06-02 10:23:38 +0200822proxy_keyserver = ""
Patrick Williams02871c92021-02-01 20:57:19 -0600823proxy_args = []
824if http_proxy:
825 proxy_cmd = f"""
826RUN echo "[http]" >> {homedir}/.gitconfig && \
827 echo "proxy = {http_proxy}" >> {homedir}/.gitconfig
Tan Siewert3aa71c82025-01-24 15:26:55 +0100828COPY <<EOF_WGETRC {homedir}/.wgetrc
829https_proxy = {http_proxy}
830http_proxy = {http_proxy}
831use_proxy = on
Lei YUf7e52612025-01-08 11:06:59 +0000832EOF_WGETRC
Patrick Williams02871c92021-02-01 20:57:19 -0600833"""
Adrian Ambrożewicz34ec77e2021-06-02 10:23:38 +0200834 proxy_keyserver = f"--keyserver-options http-proxy={http_proxy}"
835
Patrick Williams02871c92021-02-01 20:57:19 -0600836 proxy_args.extend(
837 [
838 "--build-arg",
839 f"http_proxy={http_proxy}",
840 "--build-arg",
Lei YUd461cd62021-02-18 14:25:49 +0800841 f"https_proxy={http_proxy}",
Patrick Williams02871c92021-02-01 20:57:19 -0600842 ]
843 )
844
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600845# Create base Dockerfile.
Patrick Williamsa18d9c52021-02-05 09:52:26 -0600846dockerfile_base = f"""
Andrew Geisslerfe2768c2024-10-02 10:10:29 -0400847FROM {docker_reg}/{distro}
Patrick Williams02871c92021-02-01 20:57:19 -0600848
849{mirror}
850
851ENV DEBIAN_FRONTEND noninteractive
852
Patrick Williams8949d3c2022-04-27 16:41:27 -0500853ENV PYTHONPATH "/usr/local/lib/python3.10/site-packages/"
Patrick Williams02871c92021-02-01 20:57:19 -0600854
Patrick Williamsbb16ac12021-04-12 12:23:51 -0500855# Sometimes the ubuntu key expires and we need a way to force an execution
856# of the apt-get commands for the dbgsym-keyring. When this happens we see
857# an error like: "Release: The following signatures were invalid:"
858# Insert a bogus echo that we can change here when we get this error to force
859# the update.
James Athappillya4a60c12025-11-17 14:49:12 -0800860RUN echo "ubuntu keyserver rev as of 2025-11-17"
Patrick Williamsbb16ac12021-04-12 12:23:51 -0500861
Patrick Williams02871c92021-02-01 20:57:19 -0600862# We need the keys to be imported for dbgsym repos
863# New releases have a package, older ones fall back to manual fetching
864# https://wiki.ubuntu.com/Debug%20Symbol%20Packages
Jagpal Singh Gill575b5e42023-04-14 15:52:10 -0700865# Known issue with gpg to get keys via proxy -
866# https://bugs.launchpad.net/ubuntu/+source/gnupg2/+bug/1788190, hence using
867# curl to get keys.
Patrick Williams50837432021-02-06 12:24:05 -0600868RUN apt-get update && apt-get dist-upgrade -yy && \
Jian Zhang938d3032023-07-05 13:35:35 +0800869 ( apt-get install -yy gpgv ubuntu-dbgsym-keyring || \
Jagpal Singh Gill575b5e42023-04-14 15:52:10 -0700870 ( apt-get install -yy dirmngr curl && \
871 curl -sSL \
872 'https://keyserver.ubuntu.com/pks/lookup?op=get&search=0xF2EDC64DC5AEE1F6B9C621F0C8CAB6595FDFF622' \
873 | apt-key add - ))
Patrick Williams02871c92021-02-01 20:57:19 -0600874
875# Parse the current repo list into a debug repo list
Patrick Williamse08ffba2022-12-05 10:33:46 -0600876RUN sed -n '/^deb /s,^deb [^ ]* ,deb http://ddebs.ubuntu.com ,p' \
877 /etc/apt/sources.list >/etc/apt/sources.list.d/debug.list
Patrick Williams02871c92021-02-01 20:57:19 -0600878
879# Remove non-existent debug repos
Patrick Williams41d86212022-11-25 18:28:43 -0600880RUN sed -i '/-\\(backports\\|security\\) /d' /etc/apt/sources.list.d/debug.list
Patrick Williams02871c92021-02-01 20:57:19 -0600881
882RUN cat /etc/apt/sources.list.d/debug.list
883
884RUN apt-get update && apt-get dist-upgrade -yy && apt-get install -yy \
Andrew Jeffery58f19152023-05-22 16:41:32 +0930885 abi-compliance-checker \
Andrew Jeffery8b112062023-05-22 20:49:11 +0930886 abi-dumper \
Patrick Williams02871c92021-02-01 20:57:19 -0600887 autoconf \
888 autoconf-archive \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600889 bison \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600890 cmake \
891 curl \
892 dbus \
893 device-tree-compiler \
Andrew Jeffery1c28d962025-05-09 14:17:29 +0930894 doxygen \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600895 flex \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600896 git \
Patrick Williamsb4eec872024-10-04 10:49:50 -0400897 glib-2.0 \
Patrick Williams6968e832024-08-16 17:43:24 -0400898 gnupg \
Patrick Williams02871c92021-02-01 20:57:19 -0600899 iproute2 \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600900 iputils-ping \
Manojkiran Eda524a3312023-04-05 15:37:47 +0530901 libaudit-dev \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600902 libc6-dbg \
903 libc6-dev \
Patrick Williamsc7bc4d12024-10-04 11:22:02 -0400904 libcjson-dev \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600905 libconfig++-dev \
906 libcryptsetup-dev \
Anirban Banerjeea7a30552024-12-20 19:12:42 -0800907 libcurl4-openssl-dev \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600908 libdbus-1-dev \
909 libevdev-dev \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600910 libi2c-dev \
911 libjpeg-dev \
912 libjson-perl \
913 libldap2-dev \
914 libmimetic-dev \
Ewelina Walkusz3ee62fb2025-02-25 16:04:52 +0100915 libmpfr-dev \
Patrick Williams02871c92021-02-01 20:57:19 -0600916 libnl-3-dev \
917 libnl-genl-3-dev \
Patrick Williams02871c92021-02-01 20:57:19 -0600918 libpam0g-dev \
Patrick Williams02871c92021-02-01 20:57:19 -0600919 libpciaccess-dev \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600920 libperlio-gzip-perl \
921 libpng-dev \
922 libprotobuf-dev \
923 libsnmp-dev \
924 libssl-dev \
925 libsystemd-dev \
926 libtool \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600927 liburing-dev \
Patrick Williams02871c92021-02-01 20:57:19 -0600928 libxml2-utils \
Patrick Williams0eedeed2021-02-06 19:06:09 -0600929 libxml-simple-perl \
Patrick Williams6968e832024-08-16 17:43:24 -0400930 lsb-release \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600931 ninja-build \
932 npm \
933 pkg-config \
934 protobuf-compiler \
935 python3 \
936 python3-dev\
937 python3-git \
938 python3-mako \
939 python3-pip \
William A. Kennington III25ba1e22024-03-24 15:47:51 -0700940 python3-protobuf \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600941 python3-setuptools \
942 python3-socks \
943 python3-yaml \
John Wedig9adf68d2021-11-16 14:00:39 -0800944 rsync \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600945 shellcheck \
Ewelina Walkusz8dd1bfe2024-05-27 09:34:50 +0200946 socat \
Patrick Williams6968e832024-08-16 17:43:24 -0400947 software-properties-common \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600948 sudo \
949 systemd \
Patrick Williams917b1772024-12-11 15:15:44 -0500950 systemd-dev \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600951 valgrind \
Andrew Geisslerb565f822022-12-14 11:43:25 -0600952 vim \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600953 wget \
954 xxd
Patrick Williams02871c92021-02-01 20:57:19 -0600955
Patrick Williamse347f822025-07-24 10:00:45 -0400956# Add the ubuntu-toolchain-r repository for later versions of GCC and install.
957RUN add-apt-repository ppa:ubuntu-toolchain-r/ppa && \
958 apt-get update && \
959 apt-get install -y \
960 gcc-15 \
961 g++-15 \
962 libstdc++-15-dev
963
Patrick Williamsea1bfb22025-07-23 10:46:34 -0400964RUN update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-15 15 \
965 --slave /usr/bin/g++ g++ /usr/bin/g++-15 \
966 --slave /usr/bin/gcov gcov /usr/bin/gcov-15 \
967 --slave /usr/bin/gcov-dump gcov-dump /usr/bin/gcov-dump-15 \
968 --slave /usr/bin/gcov-tool gcov-tool /usr/bin/gcov-tool-15
Patrick Williams961f1482023-05-30 09:24:16 -0500969RUN update-alternatives --remove cpp /usr/bin/cpp && \
Patrick Williamsea1bfb22025-07-23 10:46:34 -0400970 update-alternatives --install /usr/bin/cpp cpp /usr/bin/cpp-15 15
Patrick Williams02871c92021-02-01 20:57:19 -0600971
Patrick Williams6968e832024-08-16 17:43:24 -0400972# Set up LLVM apt repository.
Andrew Geisslereae557c2025-10-13 11:29:46 -0500973RUN bash -c "$(wget -O - https://apt.llvm.org/llvm.sh)" -- 21 -m https://apt.llvm.org
Patrick Williams6968e832024-08-16 17:43:24 -0400974
975# Install extra clang tools
Patrick Williamsed8aeca2024-12-18 11:08:29 -0500976RUN apt-get install -y \
Patrick Williamse31ec4e2025-09-03 15:30:22 -0400977 clang-21 \
978 clang-format-21 \
979 clang-tidy-21 \
980 lld-21
Patrick Williams6968e832024-08-16 17:43:24 -0400981
Patrick Williamse31ec4e2025-09-03 15:30:22 -0400982RUN update-alternatives --install /usr/bin/clang clang /usr/bin/clang-21 1000 \
983 --slave /usr/bin/clang++ clang++ /usr/bin/clang++-21 \
984 --slave /usr/bin/clang-tidy clang-tidy /usr/bin/clang-tidy-21 \
Patrick Williamsc5f92c92025-09-26 07:58:40 -0400985 --slave /usr/bin/clang-apply-replacements clang-apply-replacements \
986 /usr/bin/clang-apply-replacements-21 \
Patrick Williamse31ec4e2025-09-03 15:30:22 -0400987 --slave /usr/bin/clang-format clang-format /usr/bin/clang-format-21 \
Patrick Williamse08ffba2022-12-05 10:33:46 -0600988 --slave /usr/bin/run-clang-tidy run-clang-tidy.py \
Patrick Williamse31ec4e2025-09-03 15:30:22 -0400989 /usr/bin/run-clang-tidy-21 \
990 --slave /usr/bin/scan-build scan-build /usr/bin/scan-build-21 \
991 --slave /usr/bin/lld lld /usr/bin/lld-21
Patrick Williams02871c92021-02-01 20:57:19 -0600992
Patrick Williams50837432021-02-06 12:24:05 -0600993"""
994
995if is_automated_ci_build:
996 dockerfile_base += f"""
Manojkiran Edaa6ebc6e2024-06-17 11:51:45 +0530997# Run an arbitrary command to pollute the docker cache regularly force us
Patrick Williams50837432021-02-06 12:24:05 -0600998# to re-run `apt-get update` daily.
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600999RUN echo {Docker.timestamp()}
Patrick Williams50837432021-02-06 12:24:05 -06001000RUN apt-get update && apt-get dist-upgrade -yy
1001
1002"""
1003
Patrick Williams41d86212022-11-25 18:28:43 -06001004dockerfile_base += """
Patrick Williams5e4d8402023-04-11 22:19:30 -05001005RUN pip3 install --break-system-packages \
Patrick Williams1a484322025-11-12 15:12:23 -05001006 beautysh==6.2.1 \
Patrick Williams818023d2023-04-10 13:07:15 -05001007 black \
1008 codespell \
1009 flake8 \
Ewelina Walkusz2d8c5512024-07-02 10:49:38 +02001010 gcovr \
Patrick Williams818023d2023-04-10 13:07:15 -05001011 gitlint \
1012 inflection \
Arya K Padmanf7381ad2024-10-14 02:29:53 -05001013 isoduration \
Patrick Williams818023d2023-04-10 13:07:15 -05001014 isort \
1015 jsonschema \
Patrick Williamsabd1a6a2026-01-27 15:51:53 -05001016 meson==1.10.1 \
Patrick Williams9fdba2d2025-05-14 12:36:55 -04001017 referencing \
Patrick Williams818023d2023-04-10 13:07:15 -05001018 requests
Patrick Williamsb08ddf72022-12-06 08:56:31 -06001019
Patrick Williams58718f82025-12-18 15:03:28 -05001020ENV NODE_PATH="/usr/local/lib/node_modules"
Patrick Williamsb08ddf72022-12-06 08:56:31 -06001021RUN npm install -g \
Patrick Williamscd3d4192025-12-18 10:12:24 -05001022 eslint@latest eslint-plugin-json@latest \
Patrick Williams7d41f6d2022-12-06 10:19:43 -06001023 markdownlint-cli@latest \
Patrick Williamsb08ddf72022-12-06 08:56:31 -06001024 prettier@latest
Ed Tanousfb9948a2022-06-21 09:10:24 -07001025"""
1026
Patrick Williamsee3c9ee2021-02-12 20:56:01 -06001027# Build the base and stage docker images.
1028docker_base_img_name = Docker.tagname("base", dockerfile_base)
1029Docker.build("base", docker_base_img_name, dockerfile_base)
1030Package.generate_all()
Patrick Williams02871c92021-02-01 20:57:19 -06001031
Patrick Williamsee3c9ee2021-02-12 20:56:01 -06001032# Create the final Dockerfile.
Patrick Williamsa18d9c52021-02-05 09:52:26 -06001033dockerfile = f"""
Patrick Williams02871c92021-02-01 20:57:19 -06001034# Build the final output image
Patrick Williamsa18d9c52021-02-05 09:52:26 -06001035FROM {docker_base_img_name}
Patrick Williamsee3c9ee2021-02-12 20:56:01 -06001036{Package.df_all_copycmds()}
Patrick Williams02871c92021-02-01 20:57:19 -06001037
1038# Some of our infrastructure still relies on the presence of this file
1039# even though it is no longer needed to rebuild the docker environment
1040# NOTE: The file is sorted to ensure the ordering is stable.
Patrick Williamsee3c9ee2021-02-12 20:56:01 -06001041RUN echo '{Package.depcache()}' > /tmp/depcache
Patrick Williams02871c92021-02-01 20:57:19 -06001042
Patrick Williams67cc0612023-04-11 22:16:46 -05001043# Ensure the group, user, and home directory are created (or rename them if
1044# they already exist).
1045RUN if grep -q ":{gid}:" /etc/group ; then \
1046 groupmod -n {username} $(awk -F : '{{ if ($3 == {gid}) {{ print $1 }} }}' /etc/group) ; \
1047 else \
1048 groupadd -f -g {gid} {username} ; \
1049 fi
Patrick Williams02871c92021-02-01 20:57:19 -06001050RUN mkdir -p "{os.path.dirname(homedir)}"
Patrick Williams67cc0612023-04-11 22:16:46 -05001051RUN if grep -q ":{uid}:" /etc/passwd ; then \
Patrick Williams73b3ee92023-04-24 10:11:01 -05001052 usermod -l {username} -d {homedir} -m $(awk -F : '{{ if ($3 == {uid}) {{ print $1 }} }}' /etc/passwd) ; \
Patrick Williams67cc0612023-04-11 22:16:46 -05001053 else \
1054 useradd -d {homedir} -m -u {uid} -g {gid} {username} ; \
1055 fi
Patrick Williams02871c92021-02-01 20:57:19 -06001056RUN sed -i '1iDefaults umask=000' /etc/sudoers
1057RUN echo "{username} ALL=(ALL) NOPASSWD: ALL" >>/etc/sudoers
1058
Andrew Geissler305a9a52021-04-07 11:08:40 -05001059# Ensure user has ability to write to /usr/local for different tool
1060# and data installs
Andrew Geissler7bb00b12021-05-10 15:12:08 -05001061RUN chown -R {username}:{username} /usr/local/share
Andrew Geissler305a9a52021-04-07 11:08:40 -05001062
Jonathan Domanab4fee82024-01-31 15:39:20 -08001063# Update library cache
1064RUN ldconfig
1065
Patrick Williams02871c92021-02-01 20:57:19 -06001066{proxy_cmd}
1067
1068RUN /bin/bash
1069"""
1070
Patrick Williamsa18d9c52021-02-05 09:52:26 -06001071# Do the final docker build
Patrick Williamsee3c9ee2021-02-12 20:56:01 -06001072docker_final_img_name = Docker.tagname(None, dockerfile)
1073Docker.build("final", docker_final_img_name, dockerfile)
1074
Patrick Williams00536fb2021-02-11 14:28:49 -06001075# Print the tag of the final image.
1076print(docker_final_img_name)