blob: 4840848520cdebe0eb80395ff05a013a9978d8f2 [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 ),
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600126 "CLIUtils/CLI11": PackageDef(
Patrick Williamsfc397332023-07-17 11:35:43 -0500127 rev="v2.3.2",
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600128 build_type="cmake",
129 config_flags=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600130 "-DBUILD_TESTING=OFF",
131 "-DCLI11_BUILD_DOCS=OFF",
132 "-DCLI11_BUILD_EXAMPLES=OFF",
133 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600134 ),
135 "fmtlib/fmt": PackageDef(
Patrick Williamse4b761f2025-07-23 11:34:07 -0400136 rev="11.2.0",
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600137 build_type="cmake",
138 config_flags=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600139 "-DFMT_DOC=OFF",
140 "-DFMT_TEST=OFF",
141 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600142 ),
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600143 "Naios/function2": PackageDef(
Patrick Williamscb099742023-12-05 19:12:09 -0600144 rev="4.2.4",
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600145 build_type="custom",
146 build_steps=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600147 f"mkdir {prefix}/include/function2",
148 f"cp include/function2/function2.hpp {prefix}/include/function2/",
149 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600150 ),
151 "google/googletest": PackageDef(
Patrick Williamse4b761f2025-07-23 11:34:07 -0400152 rev="v1.16.0",
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600153 build_type="cmake",
William A. Kennington III4dd32c02021-05-28 01:58:13 -0700154 config_env=["CXXFLAGS=-std=c++20"],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600155 config_flags=["-DTHREADS_PREFER_PTHREAD_FLAG=ON"],
156 ),
Ed Tanous178b4b22023-06-15 09:03:11 -0700157 "nghttp2/nghttp2": PackageDef(
Patrick Williamse4b761f2025-07-23 11:34:07 -0400158 rev="v1.65.0",
Ed Tanous178b4b22023-06-15 09:03:11 -0700159 build_type="cmake",
160 config_env=["CXXFLAGS=-std=c++20"],
161 config_flags=[
162 "-DENABLE_LIB_ONLY=ON",
163 "-DENABLE_STATIC_LIB=ON",
164 ],
165 ),
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600166 "nlohmann/json": PackageDef(
Patrick Williamse4b761f2025-07-23 11:34:07 -0400167 rev="v3.12.0",
Patrick Williams6bce2ca2021-02-12 21:13:37 -0600168 build_type="cmake",
169 config_flags=["-DJSON_BuildTests=OFF"],
170 custom_post_install=[
Patrick Williamse08ffba2022-12-05 10:33:46 -0600171 (
172 f"ln -s {prefix}/include/nlohmann/json.hpp"
173 f" {prefix}/include/json.hpp"
174 ),
Patrick Williamsaae36d12021-02-04 16:30:04 -0600175 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600176 ),
Przemyslaw Czarnowski058e3a32022-12-21 14:13:23 +0100177 "json-c/json-c": PackageDef(
Patrick Williamse4b761f2025-07-23 11:34:07 -0400178 rev="json-c-0.18-20240915",
Przemyslaw Czarnowski058e3a32022-12-21 14:13:23 +0100179 build_type="cmake",
180 ),
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600181 "LibVNC/libvncserver": PackageDef(
Patrick Williamsc0421322023-12-05 19:18:57 -0600182 rev="LibVNCServer-0.9.14",
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600183 build_type="cmake",
184 ),
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600185 "leethomason/tinyxml2": PackageDef(
Patrick Williamse4b761f2025-07-23 11:34:07 -0400186 rev="11.0.0",
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600187 build_type="cmake",
188 ),
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600189 "tristanpenman/valijson": PackageDef(
Patrick Williamse4b761f2025-07-23 11:34:07 -0400190 rev="v1.0.5",
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600191 build_type="cmake",
192 config_flags=[
Patrick Williams0eedeed2021-02-06 19:06:09 -0600193 "-Dvalijson_BUILD_TESTS=0",
194 "-Dvalijson_INSTALL_HEADERS=1",
Patrick Williamsaae36d12021-02-04 16:30:04 -0600195 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600196 ),
Patrick Williamsc7e719f2025-07-24 16:51:57 -0400197 "libgpiod": PackageDef(
198 rev="1.6.5",
199 url=(
200 lambda pkg, rev: f"https://git.kernel.org/pub/scm/libs/{pkg}/{pkg}.git/snapshot/{pkg}-{rev}.tar.gz"
201 ),
202 build_type="autogen",
203 config_flags=["--enable-bindings-cxx"],
204 ),
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600205 "open-power/pdbg": PackageDef(build_type="autoconf"),
206 "openbmc/gpioplus": PackageDef(
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600207 build_type="meson",
208 config_flags=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600209 "-Dexamples=false",
210 "-Dtests=disabled",
211 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600212 ),
213 "openbmc/phosphor-dbus-interfaces": PackageDef(
214 depends=["openbmc/sdbusplus"],
215 build_type="meson",
William A. Kennington III4fe87772022-02-11 15:44:29 -0800216 config_flags=["-Dgenerate_md=false"],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600217 ),
218 "openbmc/phosphor-logging": PackageDef(
219 depends=[
Patrick Williams83394612021-02-03 07:12:50 -0600220 "USCiLab/cereal",
Patrick Williams83394612021-02-03 07:12:50 -0600221 "openbmc/phosphor-dbus-interfaces",
222 "openbmc/sdbusplus",
223 "openbmc/sdeventplus",
Patrick Williamsaae36d12021-02-04 16:30:04 -0600224 ],
Patrick Williamsf79ce4c2021-04-30 16:00:49 -0500225 build_type="meson",
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600226 config_flags=[
William A. Kennington III6c98f282022-10-05 13:37:04 -0700227 "-Dlibonly=true",
228 "-Dtests=disabled",
Patrick Williamsaae36d12021-02-04 16:30:04 -0600229 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600230 ),
231 "openbmc/phosphor-objmgr": PackageDef(
232 depends=[
Brad Bishop11e57622022-09-14 16:10:25 -0400233 "CLIUtils/CLI11",
Patrick Williams70af95c2022-09-27 16:55:41 -0500234 "boost",
Patrick Williams83394612021-02-03 07:12:50 -0600235 "leethomason/tinyxml2",
Patrick Williams70af95c2022-09-27 16:55:41 -0500236 "openbmc/phosphor-dbus-interfaces",
Patrick Williams83394612021-02-03 07:12:50 -0600237 "openbmc/phosphor-logging",
238 "openbmc/sdbusplus",
Patrick Williamsaae36d12021-02-04 16:30:04 -0600239 ],
Brad Bishop1197e352021-08-03 19:25:46 -0400240 build_type="meson",
241 config_flags=[
242 "-Dtests=disabled",
243 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600244 ),
Jason M. Billsc02ff272023-08-02 10:55:22 -0700245 "openbmc/libpeci": PackageDef(
246 build_type="meson",
247 config_flags=[
248 "-Draw-peci=disabled",
249 ],
250 ),
Manojkiran Eda1c19e452022-10-03 11:01:59 +0530251 "openbmc/libpldm": PackageDef(
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600252 build_type="meson",
Andrew Jeffery29163972024-12-06 17:01:56 +1030253 config_flags=[
254 "-Dabi=deprecated,stable",
255 "-Dtests=false",
256 "-Dabi-compliance-check=false",
257 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600258 ),
259 "openbmc/sdbusplus": PackageDef(
Patrick Williams54d01da2024-09-25 06:40:25 -0400260 depends=[
261 "nlohmann/json",
262 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600263 build_type="meson",
264 custom_post_dl=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600265 "cd tools",
266 f"./setup.py install --root=/ --prefix={prefix}",
267 "cd ..",
268 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600269 config_flags=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600270 "-Dexamples=disabled",
271 "-Dtests=disabled",
272 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600273 ),
274 "openbmc/sdeventplus": PackageDef(
Patrick Williams70af95c2022-09-27 16:55:41 -0500275 depends=[
Patrick Williams70af95c2022-09-27 16:55:41 -0500276 "openbmc/stdplus",
277 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600278 build_type="meson",
279 config_flags=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600280 "-Dexamples=false",
281 "-Dtests=disabled",
282 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600283 ),
284 "openbmc/stdplus": PackageDef(
Patrick Williams70af95c2022-09-27 16:55:41 -0500285 depends=[
Patrick Williams70af95c2022-09-27 16:55:41 -0500286 "fmtlib/fmt",
William A. Kennington IIIca1bf0c2022-10-05 02:23:30 -0700287 "google/googletest",
288 "Naios/function2",
Patrick Williams70af95c2022-09-27 16:55:41 -0500289 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600290 build_type="meson",
291 config_flags=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600292 "-Dexamples=false",
293 "-Dtests=disabled",
William A. Kennington IIIca1bf0c2022-10-05 02:23:30 -0700294 "-Dgtest=enabled",
Patrick Williamsaae36d12021-02-04 16:30:04 -0600295 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600296 ),
297} # type: Dict[str, PackageDef]
Patrick Williams02871c92021-02-01 20:57:19 -0600298
299# Define common flags used for builds
Patrick Williams02871c92021-02-01 20:57:19 -0600300configure_flags = " ".join(
301 [
302 f"--prefix={prefix}",
303 ]
304)
305cmake_flags = " ".join(
306 [
Patrick Williams02871c92021-02-01 20:57:19 -0600307 "-DBUILD_SHARED_LIBS=ON",
Patrick Williams0f2086b2021-02-05 06:49:49 -0600308 "-DCMAKE_BUILD_TYPE=RelWithDebInfo",
Patrick Williams02871c92021-02-01 20:57:19 -0600309 f"-DCMAKE_INSTALL_PREFIX:PATH={prefix}",
Patrick Williams0f2086b2021-02-05 06:49:49 -0600310 "-GNinja",
311 "-DCMAKE_MAKE_PROGRAM=ninja",
Patrick Williams02871c92021-02-01 20:57:19 -0600312 ]
313)
314meson_flags = " ".join(
315 [
316 "--wrap-mode=nodownload",
317 f"-Dprefix={prefix}",
318 ]
319)
320
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600321
322class Package(threading.Thread):
323 """Class used to build the Docker stages for each package.
324
325 Generally, this class should not be instantiated directly but through
326 Package.generate_all().
327 """
328
329 # Copy the packages dictionary.
330 packages = packages.copy()
331
332 # Lock used for thread-safety.
333 lock = threading.Lock()
334
335 def __init__(self, pkg: str):
Patrick Williams05fb2a02022-10-11 17:22:33 -0500336 """pkg - The name of this package (ex. foo/bar )"""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600337 super(Package, self).__init__()
338
339 self.package = pkg
340 self.exception = None # type: Optional[Exception]
341
342 # Reference to this package's
343 self.pkg_def = Package.packages[pkg]
344 self.pkg_def["__package"] = self
345
346 def run(self) -> None:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500347 """Thread 'run' function. Builds the Docker stage."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600348
349 # In case this package has no rev, fetch it from Github.
350 self._update_rev()
351
352 # Find all the Package objects that this package depends on.
353 # This section is locked because we are looking into another
354 # package's PackageDef dict, which could be being modified.
355 Package.lock.acquire()
356 deps: Iterable[Package] = [
357 Package.packages[deppkg]["__package"]
358 for deppkg in self.pkg_def.get("depends", [])
359 ]
360 Package.lock.release()
361
362 # Wait until all the depends finish building. We need them complete
363 # for the "COPY" commands.
364 for deppkg in deps:
365 deppkg.join()
366
367 # Generate this package's Dockerfile.
368 dockerfile = f"""
369FROM {docker_base_img_name}
370{self._df_copycmds()}
371{self._df_build()}
372"""
373
374 # Generate the resulting tag name and save it to the PackageDef.
375 # This section is locked because we are modifying the PackageDef,
376 # which can be accessed by other threads.
377 Package.lock.acquire()
378 tag = Docker.tagname(self._stagename(), dockerfile)
379 self.pkg_def["__tag"] = tag
380 Package.lock.release()
381
382 # Do the build / save any exceptions.
383 try:
384 Docker.build(self.package, tag, dockerfile)
385 except Exception as e:
386 self.exception = e
387
388 @classmethod
389 def generate_all(cls) -> None:
390 """Ensure a Docker stage is created for all defined packages.
391
392 These are done in parallel but with appropriate blocking per
393 package 'depends' specifications.
394 """
395
396 # Create a Package for each defined package.
397 pkg_threads = [Package(p) for p in cls.packages.keys()]
398
399 # Start building them all.
Patrick Williams6dbd7802021-02-20 08:34:10 -0600400 # This section is locked because threads depend on each other,
401 # based on the packages, and they cannot 'join' on a thread
402 # which is not yet started. Adding a lock here allows all the
403 # threads to start before they 'join' their dependencies.
404 Package.lock.acquire()
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600405 for t in pkg_threads:
406 t.start()
Patrick Williams6dbd7802021-02-20 08:34:10 -0600407 Package.lock.release()
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600408
409 # Wait for completion.
410 for t in pkg_threads:
411 t.join()
412 # Check if the thread saved off its own exception.
413 if t.exception:
414 print(f"Package {t.package} failed!", file=sys.stderr)
415 raise t.exception
416
417 @staticmethod
418 def df_all_copycmds() -> str:
419 """Formulate the Dockerfile snippet necessary to copy all packages
420 into the final image.
421 """
422 return Package.df_copycmds_set(Package.packages.keys())
423
424 @classmethod
425 def depcache(cls) -> str:
426 """Create the contents of the '/tmp/depcache'.
427 This file is a comma-separated list of "<pkg>:<rev>".
428 """
429
430 # This needs to be sorted for consistency.
431 depcache = ""
432 for pkg in sorted(cls.packages.keys()):
433 depcache += "%s:%s," % (pkg, cls.packages[pkg]["rev"])
434 return depcache
435
Patrick Williams276bd0e2024-10-02 10:34:32 -0400436 def _check_gerrit_topic(self) -> bool:
437 if not gerrit_topic:
438 return False
439 if not self.package.startswith("openbmc/"):
440 return False
441 if gerrit_project == self.package and gerrit_rev:
442 return False
443
444 try:
445 commits = json.loads(
446 urllib.request.urlopen(
447 f"https://gerrit.openbmc.org/changes/?q=status:open+project:{self.package}+topic:{gerrit_topic}"
448 )
449 .read()
450 .splitlines()[-1]
451 )
452
453 if len(commits) == 0:
454 return False
455 if len(commits) > 1:
456 print(
457 f"{self.package} has more than 1 commit under {gerrit_topic}; using lastest upstream: {len(commits)}",
458 file=sys.stderr,
459 )
460 return False
461
462 change_id = commits[0]["id"]
463
464 commit = json.loads(
465 urllib.request.urlopen(
466 f"https://gerrit.openbmc.org/changes/{change_id}/revisions/current/commit"
467 )
468 .read()
469 .splitlines()[-1]
470 )["commit"]
471
472 print(
473 f"Using {commit} from {gerrit_topic} for {self.package}",
474 file=sys.stderr,
475 )
476 self.pkg_def["rev"] = commit
477 return True
478
479 except urllib.error.HTTPError as e:
480 print(
481 f"Error loading topic {gerrit_topic} for {self.package}: ",
482 e,
483 file=sys.stderr,
484 )
485 return False
486
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600487 def _update_rev(self) -> None:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500488 """Look up the HEAD for missing a static rev."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600489
490 if "rev" in self.pkg_def:
491 return
492
Patrick Williams276bd0e2024-10-02 10:34:32 -0400493 if self._check_gerrit_topic():
494 return
495
Patrick Williams65b21fb2021-02-12 21:21:14 -0600496 # Check if Jenkins/Gerrit gave us a revision and use it.
497 if gerrit_project == self.package and gerrit_rev:
498 print(
499 f"Found Gerrit revision for {self.package}: {gerrit_rev}",
500 file=sys.stderr,
501 )
502 self.pkg_def["rev"] = gerrit_rev
503 return
504
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600505 # Ask Github for all the branches.
Patrick Williams05fb2a02022-10-11 17:22:33 -0500506 lookup = git(
507 "ls-remote", "--heads", f"https://github.com/{self.package}"
508 )
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600509
510 # Find the branch matching {branch} (or fallback to master).
511 # This section is locked because we are modifying the PackageDef.
512 Package.lock.acquire()
513 for line in lookup.split("\n"):
Andrew Geisslerf3d27e62024-04-09 15:24:49 -0500514 if re.fullmatch(f".*{branch}$", line.strip()):
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600515 self.pkg_def["rev"] = line.split()[0]
Andrew Geisslerf3d27e62024-04-09 15:24:49 -0500516 break
Patrick Williamsc7d73642022-10-11 17:22:06 -0500517 elif (
518 "refs/heads/master" in line or "refs/heads/main" in line
519 ) and "rev" not in self.pkg_def:
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600520 self.pkg_def["rev"] = line.split()[0]
521 Package.lock.release()
522
523 def _stagename(self) -> str:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500524 """Create a name for the Docker stage associated with this pkg."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600525 return self.package.replace("/", "-").lower()
526
527 def _url(self) -> str:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500528 """Get the URL for this package."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600529 rev = self.pkg_def["rev"]
530
531 # If the lambda exists, call it.
532 if "url" in self.pkg_def:
533 return self.pkg_def["url"](self.package, rev)
534
535 # Default to the github archive URL.
536 return f"https://github.com/{self.package}/archive/{rev}.tar.gz"
537
538 def _cmd_download(self) -> str:
539 """Formulate the command necessary to download and unpack to source."""
540
541 url = self._url()
542 if ".tar." not in url:
543 raise NotImplementedError(
544 f"Unhandled download type for {self.package}: {url}"
545 )
546
547 cmd = f"curl -L {url} | tar -x"
548
549 if url.endswith(".bz2"):
550 cmd += "j"
551 elif url.endswith(".gz"):
552 cmd += "z"
553 else:
554 raise NotImplementedError(
555 f"Unknown tar flags needed for {self.package}: {url}"
556 )
557
558 return cmd
559
560 def _cmd_cd_srcdir(self) -> str:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500561 """Formulate the command necessary to 'cd' into the source dir."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600562 return f"cd {self.package.split('/')[-1]}*"
563
564 def _df_copycmds(self) -> str:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500565 """Formulate the dockerfile snippet necessary to COPY all depends."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600566
567 if "depends" not in self.pkg_def:
568 return ""
569 return Package.df_copycmds_set(self.pkg_def["depends"])
570
571 @staticmethod
572 def df_copycmds_set(pkgs: Iterable[str]) -> str:
573 """Formulate the Dockerfile snippet necessary to COPY a set of
574 packages into a Docker stage.
575 """
576
577 copy_cmds = ""
578
579 # Sort the packages for consistency.
580 for p in sorted(pkgs):
581 tag = Package.packages[p]["__tag"]
582 copy_cmds += f"COPY --from={tag} {prefix} {prefix}\n"
583 # Workaround for upstream docker bug and multiple COPY cmds
584 # https://github.com/moby/moby/issues/37965
585 copy_cmds += "RUN true\n"
586
587 return copy_cmds
588
589 def _df_build(self) -> str:
590 """Formulate the Dockerfile snippet necessary to download, build, and
591 install a package into a Docker stage.
592 """
593
594 # Download and extract source.
595 result = f"RUN {self._cmd_download()} && {self._cmd_cd_srcdir()} && "
596
597 # Handle 'custom_post_dl' commands.
598 custom_post_dl = self.pkg_def.get("custom_post_dl")
599 if custom_post_dl:
600 result += " && ".join(custom_post_dl) + " && "
601
602 # Build and install package based on 'build_type'.
603 build_type = self.pkg_def["build_type"]
604 if build_type == "autoconf":
605 result += self._cmd_build_autoconf()
Patrick Williamsc7e719f2025-07-24 16:51:57 -0400606 elif build_type == "autogen":
607 result += self._cmd_build_autogen()
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600608 elif build_type == "cmake":
609 result += self._cmd_build_cmake()
610 elif build_type == "custom":
611 result += self._cmd_build_custom()
612 elif build_type == "make":
613 result += self._cmd_build_make()
614 elif build_type == "meson":
615 result += self._cmd_build_meson()
616 else:
617 raise NotImplementedError(
618 f"Unhandled build type for {self.package}: {build_type}"
619 )
620
Patrick Williams6bce2ca2021-02-12 21:13:37 -0600621 # Handle 'custom_post_install' commands.
622 custom_post_install = self.pkg_def.get("custom_post_install")
623 if custom_post_install:
624 result += " && " + " && ".join(custom_post_install)
625
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600626 return result
627
628 def _cmd_build_autoconf(self) -> str:
629 options = " ".join(self.pkg_def.get("config_flags", []))
630 env = " ".join(self.pkg_def.get("config_env", []))
631 result = "./bootstrap.sh && "
632 result += f"{env} ./configure {configure_flags} {options} && "
633 result += f"make -j{proc_count} && make install"
634 return result
635
Patrick Williamsc7e719f2025-07-24 16:51:57 -0400636 def _cmd_build_autogen(self) -> str:
637 options = " ".join(self.pkg_def.get("config_flags", []))
638 env = " ".join(self.pkg_def.get("config_env", []))
639 result = f"{env} ./autogen.sh {configure_flags} {options} && "
640 result += "make && make install"
641 return result
642
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600643 def _cmd_build_cmake(self) -> str:
644 options = " ".join(self.pkg_def.get("config_flags", []))
645 env = " ".join(self.pkg_def.get("config_env", []))
646 result = "mkdir builddir && cd builddir && "
647 result += f"{env} cmake {cmake_flags} {options} .. && "
648 result += "cmake --build . --target all && "
649 result += "cmake --build . --target install && "
650 result += "cd .."
651 return result
652
653 def _cmd_build_custom(self) -> str:
654 return " && ".join(self.pkg_def.get("build_steps", []))
655
656 def _cmd_build_make(self) -> str:
657 return f"make -j{proc_count} && make install"
658
659 def _cmd_build_meson(self) -> str:
660 options = " ".join(self.pkg_def.get("config_flags", []))
661 env = " ".join(self.pkg_def.get("config_env", []))
Andrew Jefferye2da11a2023-06-15 10:16:37 +0930662 result = f"{env} meson setup builddir {meson_flags} {options} && "
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600663 result += "ninja -C builddir && ninja -C builddir install"
664 return result
665
666
667class Docker:
668 """Class to assist with Docker interactions. All methods are static."""
669
670 @staticmethod
671 def timestamp() -> str:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500672 """Generate a timestamp for today using the ISO week."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600673 today = date.today().isocalendar()
674 return f"{today[0]}-W{today[1]:02}"
675
676 @staticmethod
Patrick Williams41d86212022-11-25 18:28:43 -0600677 def tagname(pkgname: Optional[str], dockerfile: str) -> str:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500678 """Generate a tag name for a package using a hash of the Dockerfile."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600679 result = docker_image_name
680 if pkgname:
681 result += "-" + pkgname
682
683 result += ":" + Docker.timestamp()
684 result += "-" + sha256(dockerfile.encode()).hexdigest()[0:16]
685
686 return result
687
688 @staticmethod
689 def build(pkg: str, tag: str, dockerfile: str) -> None:
Andrew Geissler22e61102023-02-14 14:44:00 -0600690 """Build a docker image using the Dockerfile and tagging it with 'tag'."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600691
692 # If we're not forcing builds, check if it already exists and skip.
693 if not force_build:
Andrew Geissler8f7146f2024-12-11 14:20:47 -0600694 if container.image.ls(
695 tag, "--format", '"{{.Repository}}:{{.Tag}}"'
696 ):
Patrick Williams05fb2a02022-10-11 17:22:33 -0500697 print(
698 f"Image {tag} already exists. Skipping.", file=sys.stderr
699 )
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600700 return
701
702 # Build it.
703 # Capture the output of the 'docker build' command and send it to
704 # stderr (prefixed with the package name). This allows us to see
Manojkiran Edaa6ebc6e2024-06-17 11:51:45 +0530705 # progress but not pollute stdout. Later on we output the final
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600706 # docker tag to stdout and we want to keep that pristine.
707 #
708 # Other unusual flags:
709 # --no-cache: Bypass the Docker cache if 'force_build'.
710 # --force-rm: Clean up Docker processes if they fail.
Andrew Geissler8f7146f2024-12-11 14:20:47 -0600711 container.build(
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600712 proxy_args,
713 "--network=host",
714 "--force-rm",
715 "--no-cache=true" if force_build else "--no-cache=false",
716 "-t",
717 tag,
718 "-",
719 _in=dockerfile,
720 _out=(
721 lambda line: print(
722 pkg + ":", line, end="", file=sys.stderr, flush=True
723 )
724 ),
Jonathan Doman88dd7922024-05-02 10:34:21 -0700725 _err_to_out=True,
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600726 )
727
728
729# Read a bunch of environment variables.
Patrick Williams05fb2a02022-10-11 17:22:33 -0500730docker_image_name = os.environ.get(
731 "DOCKER_IMAGE_NAME", "openbmc/ubuntu-unit-test"
732)
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600733force_build = os.environ.get("FORCE_DOCKER_BUILD")
734is_automated_ci_build = os.environ.get("BUILD_URL", False)
Patrick Williams6b141902025-07-23 11:24:11 -0400735distro = os.environ.get("DISTRO", "ubuntu:plucky")
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600736branch = os.environ.get("BRANCH", "master")
737ubuntu_mirror = os.environ.get("UBUNTU_MIRROR")
Andrew Geissler23ec3322024-10-02 10:45:32 -0400738docker_reg = os.environ.get("DOCKER_REG", "public.ecr.aws/ubuntu")
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600739http_proxy = os.environ.get("http_proxy")
740
Patrick Williams65b21fb2021-02-12 21:21:14 -0600741gerrit_project = os.environ.get("GERRIT_PROJECT")
742gerrit_rev = os.environ.get("GERRIT_PATCHSET_REVISION")
Patrick Williams276bd0e2024-10-02 10:34:32 -0400743gerrit_topic = os.environ.get("GERRIT_TOPIC")
Patrick Williams65b21fb2021-02-12 21:21:14 -0600744
Andrew Geisslerd0dabc32023-04-04 08:09:21 -0600745# Ensure appropriate docker build output to see progress and identify
746# any issues
747os.environ["BUILDKIT_PROGRESS"] = "plain"
748
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600749# Set up some common variables.
750username = os.environ.get("USER", "root")
751homedir = os.environ.get("HOME", "/root")
752gid = os.getgid()
753uid = os.getuid()
754
Josh Lehan6825a012022-03-17 18:31:39 -0700755# Use well-known constants if user is root
756if username == "root":
757 homedir = "/root"
758 gid = 0
759 uid = 0
760
Patrick Williams02871c92021-02-01 20:57:19 -0600761# Special flags if setting up a deb mirror.
762mirror = ""
763if "ubuntu" in distro and ubuntu_mirror:
764 mirror = f"""
Patrick Williamse08ffba2022-12-05 10:33:46 -0600765RUN echo "deb {ubuntu_mirror} \
766 $(. /etc/os-release && echo $VERSION_CODENAME) \
767 main restricted universe multiverse" > /etc/apt/sources.list && \\
768 echo "deb {ubuntu_mirror} \
769 $(. /etc/os-release && echo $VERSION_CODENAME)-updates \
770 main restricted universe multiverse" >> /etc/apt/sources.list && \\
771 echo "deb {ubuntu_mirror} \
772 $(. /etc/os-release && echo $VERSION_CODENAME)-security \
773 main restricted universe multiverse" >> /etc/apt/sources.list && \\
774 echo "deb {ubuntu_mirror} \
775 $(. /etc/os-release && echo $VERSION_CODENAME)-proposed \
776 main restricted universe multiverse" >> /etc/apt/sources.list && \\
777 echo "deb {ubuntu_mirror} \
778 $(. /etc/os-release && echo $VERSION_CODENAME)-backports \
779 main restricted universe multiverse" >> /etc/apt/sources.list
Patrick Williams02871c92021-02-01 20:57:19 -0600780"""
781
782# Special flags for proxying.
783proxy_cmd = ""
Adrian Ambrożewicz34ec77e2021-06-02 10:23:38 +0200784proxy_keyserver = ""
Patrick Williams02871c92021-02-01 20:57:19 -0600785proxy_args = []
786if http_proxy:
787 proxy_cmd = f"""
788RUN echo "[http]" >> {homedir}/.gitconfig && \
789 echo "proxy = {http_proxy}" >> {homedir}/.gitconfig
Tan Siewert3aa71c82025-01-24 15:26:55 +0100790COPY <<EOF_WGETRC {homedir}/.wgetrc
791https_proxy = {http_proxy}
792http_proxy = {http_proxy}
793use_proxy = on
Lei YUf7e52612025-01-08 11:06:59 +0000794EOF_WGETRC
Patrick Williams02871c92021-02-01 20:57:19 -0600795"""
Adrian Ambrożewicz34ec77e2021-06-02 10:23:38 +0200796 proxy_keyserver = f"--keyserver-options http-proxy={http_proxy}"
797
Patrick Williams02871c92021-02-01 20:57:19 -0600798 proxy_args.extend(
799 [
800 "--build-arg",
801 f"http_proxy={http_proxy}",
802 "--build-arg",
Lei YUd461cd62021-02-18 14:25:49 +0800803 f"https_proxy={http_proxy}",
Patrick Williams02871c92021-02-01 20:57:19 -0600804 ]
805 )
806
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600807# Create base Dockerfile.
Patrick Williamsa18d9c52021-02-05 09:52:26 -0600808dockerfile_base = f"""
Andrew Geisslerfe2768c2024-10-02 10:10:29 -0400809FROM {docker_reg}/{distro}
Patrick Williams02871c92021-02-01 20:57:19 -0600810
811{mirror}
812
813ENV DEBIAN_FRONTEND noninteractive
814
Patrick Williams8949d3c2022-04-27 16:41:27 -0500815ENV PYTHONPATH "/usr/local/lib/python3.10/site-packages/"
Patrick Williams02871c92021-02-01 20:57:19 -0600816
Patrick Williamsbb16ac12021-04-12 12:23:51 -0500817# Sometimes the ubuntu key expires and we need a way to force an execution
818# of the apt-get commands for the dbgsym-keyring. When this happens we see
819# an error like: "Release: The following signatures were invalid:"
820# Insert a bogus echo that we can change here when we get this error to force
821# the update.
Patrick Williamsa1cbd402025-06-25 10:23:50 -0400822RUN echo "ubuntu keyserver rev as of 2025-06-25"
Patrick Williamsbb16ac12021-04-12 12:23:51 -0500823
Patrick Williams02871c92021-02-01 20:57:19 -0600824# We need the keys to be imported for dbgsym repos
825# New releases have a package, older ones fall back to manual fetching
826# https://wiki.ubuntu.com/Debug%20Symbol%20Packages
Jagpal Singh Gill575b5e42023-04-14 15:52:10 -0700827# Known issue with gpg to get keys via proxy -
828# https://bugs.launchpad.net/ubuntu/+source/gnupg2/+bug/1788190, hence using
829# curl to get keys.
Patrick Williams50837432021-02-06 12:24:05 -0600830RUN apt-get update && apt-get dist-upgrade -yy && \
Jian Zhang938d3032023-07-05 13:35:35 +0800831 ( apt-get install -yy gpgv ubuntu-dbgsym-keyring || \
Jagpal Singh Gill575b5e42023-04-14 15:52:10 -0700832 ( apt-get install -yy dirmngr curl && \
833 curl -sSL \
834 'https://keyserver.ubuntu.com/pks/lookup?op=get&search=0xF2EDC64DC5AEE1F6B9C621F0C8CAB6595FDFF622' \
835 | apt-key add - ))
Patrick Williams02871c92021-02-01 20:57:19 -0600836
837# Parse the current repo list into a debug repo list
Patrick Williamse08ffba2022-12-05 10:33:46 -0600838RUN sed -n '/^deb /s,^deb [^ ]* ,deb http://ddebs.ubuntu.com ,p' \
839 /etc/apt/sources.list >/etc/apt/sources.list.d/debug.list
Patrick Williams02871c92021-02-01 20:57:19 -0600840
841# Remove non-existent debug repos
Patrick Williams41d86212022-11-25 18:28:43 -0600842RUN sed -i '/-\\(backports\\|security\\) /d' /etc/apt/sources.list.d/debug.list
Patrick Williams02871c92021-02-01 20:57:19 -0600843
844RUN cat /etc/apt/sources.list.d/debug.list
845
846RUN apt-get update && apt-get dist-upgrade -yy && apt-get install -yy \
Andrew Jeffery58f19152023-05-22 16:41:32 +0930847 abi-compliance-checker \
Andrew Jeffery8b112062023-05-22 20:49:11 +0930848 abi-dumper \
Patrick Williams02871c92021-02-01 20:57:19 -0600849 autoconf \
850 autoconf-archive \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600851 bison \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600852 cmake \
853 curl \
854 dbus \
855 device-tree-compiler \
Andrew Jeffery1c28d962025-05-09 14:17:29 +0930856 doxygen \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600857 flex \
Patrick Williamsea1bfb22025-07-23 10:46:34 -0400858 g++-15 \
859 gcc-15 \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600860 git \
Patrick Williamsb4eec872024-10-04 10:49:50 -0400861 glib-2.0 \
Patrick Williams6968e832024-08-16 17:43:24 -0400862 gnupg \
Patrick Williams02871c92021-02-01 20:57:19 -0600863 iproute2 \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600864 iputils-ping \
Manojkiran Eda524a3312023-04-05 15:37:47 +0530865 libaudit-dev \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600866 libc6-dbg \
867 libc6-dev \
Patrick Williamsc7bc4d12024-10-04 11:22:02 -0400868 libcjson-dev \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600869 libconfig++-dev \
870 libcryptsetup-dev \
Anirban Banerjeea7a30552024-12-20 19:12:42 -0800871 libcurl4-openssl-dev \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600872 libdbus-1-dev \
873 libevdev-dev \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600874 libi2c-dev \
875 libjpeg-dev \
876 libjson-perl \
877 libldap2-dev \
878 libmimetic-dev \
Ewelina Walkusz3ee62fb2025-02-25 16:04:52 +0100879 libmpfr-dev \
Patrick Williams02871c92021-02-01 20:57:19 -0600880 libnl-3-dev \
881 libnl-genl-3-dev \
Patrick Williams02871c92021-02-01 20:57:19 -0600882 libpam0g-dev \
Patrick Williams02871c92021-02-01 20:57:19 -0600883 libpciaccess-dev \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600884 libperlio-gzip-perl \
885 libpng-dev \
886 libprotobuf-dev \
887 libsnmp-dev \
888 libssl-dev \
889 libsystemd-dev \
890 libtool \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600891 liburing-dev \
Patrick Williams02871c92021-02-01 20:57:19 -0600892 libxml2-utils \
Patrick Williams0eedeed2021-02-06 19:06:09 -0600893 libxml-simple-perl \
Patrick Williams6968e832024-08-16 17:43:24 -0400894 lsb-release \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600895 ninja-build \
896 npm \
897 pkg-config \
898 protobuf-compiler \
899 python3 \
900 python3-dev\
901 python3-git \
902 python3-mako \
903 python3-pip \
William A. Kennington III25ba1e22024-03-24 15:47:51 -0700904 python3-protobuf \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600905 python3-setuptools \
906 python3-socks \
907 python3-yaml \
John Wedig9adf68d2021-11-16 14:00:39 -0800908 rsync \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600909 shellcheck \
Ewelina Walkusz8dd1bfe2024-05-27 09:34:50 +0200910 socat \
Patrick Williams6968e832024-08-16 17:43:24 -0400911 software-properties-common \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600912 sudo \
913 systemd \
Patrick Williams917b1772024-12-11 15:15:44 -0500914 systemd-dev \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600915 valgrind \
Andrew Geisslerb565f822022-12-14 11:43:25 -0600916 vim \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600917 wget \
918 xxd
Patrick Williams02871c92021-02-01 20:57:19 -0600919
Patrick Williamsea1bfb22025-07-23 10:46:34 -0400920RUN update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-15 15 \
921 --slave /usr/bin/g++ g++ /usr/bin/g++-15 \
922 --slave /usr/bin/gcov gcov /usr/bin/gcov-15 \
923 --slave /usr/bin/gcov-dump gcov-dump /usr/bin/gcov-dump-15 \
924 --slave /usr/bin/gcov-tool gcov-tool /usr/bin/gcov-tool-15
Patrick Williams961f1482023-05-30 09:24:16 -0500925RUN update-alternatives --remove cpp /usr/bin/cpp && \
Patrick Williamsea1bfb22025-07-23 10:46:34 -0400926 update-alternatives --install /usr/bin/cpp cpp /usr/bin/cpp-15 15
Patrick Williams02871c92021-02-01 20:57:19 -0600927
Patrick Williams6968e832024-08-16 17:43:24 -0400928# Set up LLVM apt repository.
Patrick Williams412b2812025-05-08 15:19:46 -0400929RUN bash -c "$(wget -O - https://apt.llvm.org/llvm.sh)" -- 20
Patrick Williams6968e832024-08-16 17:43:24 -0400930
931# Install extra clang tools
Patrick Williamsed8aeca2024-12-18 11:08:29 -0500932RUN apt-get install -y \
Patrick Williams412b2812025-05-08 15:19:46 -0400933 clang-20 \
934 clang-format-20 \
Ed Tanousd7133492025-07-24 12:20:11 -0700935 clang-tidy-20 \
936 lld-20
Patrick Williams6968e832024-08-16 17:43:24 -0400937
Patrick Williams412b2812025-05-08 15:19:46 -0400938RUN update-alternatives --install /usr/bin/clang clang /usr/bin/clang-20 1000 \
939 --slave /usr/bin/clang++ clang++ /usr/bin/clang++-20 \
940 --slave /usr/bin/clang-tidy clang-tidy /usr/bin/clang-tidy-20 \
941 --slave /usr/bin/clang-format clang-format /usr/bin/clang-format-20 \
Patrick Williamse08ffba2022-12-05 10:33:46 -0600942 --slave /usr/bin/run-clang-tidy run-clang-tidy.py \
Patrick Williams412b2812025-05-08 15:19:46 -0400943 /usr/bin/run-clang-tidy-20 \
Ed Tanousd7133492025-07-24 12:20:11 -0700944 --slave /usr/bin/scan-build scan-build /usr/bin/scan-build-20 \
945 --slave /usr/bin/lld lld /usr/bin/lld-20
Patrick Williams02871c92021-02-01 20:57:19 -0600946
Patrick Williams50837432021-02-06 12:24:05 -0600947"""
948
949if is_automated_ci_build:
950 dockerfile_base += f"""
Manojkiran Edaa6ebc6e2024-06-17 11:51:45 +0530951# Run an arbitrary command to pollute the docker cache regularly force us
Patrick Williams50837432021-02-06 12:24:05 -0600952# to re-run `apt-get update` daily.
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600953RUN echo {Docker.timestamp()}
Patrick Williams50837432021-02-06 12:24:05 -0600954RUN apt-get update && apt-get dist-upgrade -yy
955
956"""
957
Patrick Williams41d86212022-11-25 18:28:43 -0600958dockerfile_base += """
Patrick Williams5e4d8402023-04-11 22:19:30 -0500959RUN pip3 install --break-system-packages \
Patrick Williams818023d2023-04-10 13:07:15 -0500960 beautysh \
961 black \
962 codespell \
963 flake8 \
Ewelina Walkusz2d8c5512024-07-02 10:49:38 +0200964 gcovr \
Patrick Williams818023d2023-04-10 13:07:15 -0500965 gitlint \
966 inflection \
Arya K Padmanf7381ad2024-10-14 02:29:53 -0500967 isoduration \
Patrick Williams818023d2023-04-10 13:07:15 -0500968 isort \
969 jsonschema \
Patrick Williamsbcc78d32025-07-23 11:29:11 -0400970 meson==1.8.2 \
Patrick Williams9fdba2d2025-05-14 12:36:55 -0400971 referencing \
Patrick Williams818023d2023-04-10 13:07:15 -0500972 requests
Patrick Williamsb08ddf72022-12-06 08:56:31 -0600973
974RUN npm install -g \
Xinnan Xied0757de2024-05-27 14:22:58 +0800975 eslint@v8.56.0 eslint-plugin-json@v3.1.0 \
Patrick Williams7d41f6d2022-12-06 10:19:43 -0600976 markdownlint-cli@latest \
Patrick Williamsb08ddf72022-12-06 08:56:31 -0600977 prettier@latest
Ed Tanousfb9948a2022-06-21 09:10:24 -0700978"""
979
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600980# Build the base and stage docker images.
981docker_base_img_name = Docker.tagname("base", dockerfile_base)
982Docker.build("base", docker_base_img_name, dockerfile_base)
983Package.generate_all()
Patrick Williams02871c92021-02-01 20:57:19 -0600984
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600985# Create the final Dockerfile.
Patrick Williamsa18d9c52021-02-05 09:52:26 -0600986dockerfile = f"""
Patrick Williams02871c92021-02-01 20:57:19 -0600987# Build the final output image
Patrick Williamsa18d9c52021-02-05 09:52:26 -0600988FROM {docker_base_img_name}
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600989{Package.df_all_copycmds()}
Patrick Williams02871c92021-02-01 20:57:19 -0600990
991# Some of our infrastructure still relies on the presence of this file
992# even though it is no longer needed to rebuild the docker environment
993# NOTE: The file is sorted to ensure the ordering is stable.
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600994RUN echo '{Package.depcache()}' > /tmp/depcache
Patrick Williams02871c92021-02-01 20:57:19 -0600995
Patrick Williams67cc0612023-04-11 22:16:46 -0500996# Ensure the group, user, and home directory are created (or rename them if
997# they already exist).
998RUN if grep -q ":{gid}:" /etc/group ; then \
999 groupmod -n {username} $(awk -F : '{{ if ($3 == {gid}) {{ print $1 }} }}' /etc/group) ; \
1000 else \
1001 groupadd -f -g {gid} {username} ; \
1002 fi
Patrick Williams02871c92021-02-01 20:57:19 -06001003RUN mkdir -p "{os.path.dirname(homedir)}"
Patrick Williams67cc0612023-04-11 22:16:46 -05001004RUN if grep -q ":{uid}:" /etc/passwd ; then \
Patrick Williams73b3ee92023-04-24 10:11:01 -05001005 usermod -l {username} -d {homedir} -m $(awk -F : '{{ if ($3 == {uid}) {{ print $1 }} }}' /etc/passwd) ; \
Patrick Williams67cc0612023-04-11 22:16:46 -05001006 else \
1007 useradd -d {homedir} -m -u {uid} -g {gid} {username} ; \
1008 fi
Patrick Williams02871c92021-02-01 20:57:19 -06001009RUN sed -i '1iDefaults umask=000' /etc/sudoers
1010RUN echo "{username} ALL=(ALL) NOPASSWD: ALL" >>/etc/sudoers
1011
Andrew Geissler305a9a52021-04-07 11:08:40 -05001012# Ensure user has ability to write to /usr/local for different tool
1013# and data installs
Andrew Geissler7bb00b12021-05-10 15:12:08 -05001014RUN chown -R {username}:{username} /usr/local/share
Andrew Geissler305a9a52021-04-07 11:08:40 -05001015
Jonathan Domanab4fee82024-01-31 15:39:20 -08001016# Update library cache
1017RUN ldconfig
1018
Patrick Williams02871c92021-02-01 20:57:19 -06001019{proxy_cmd}
1020
1021RUN /bin/bash
1022"""
1023
Patrick Williamsa18d9c52021-02-05 09:52:26 -06001024# Do the final docker build
Patrick Williamsee3c9ee2021-02-12 20:56:01 -06001025docker_final_img_name = Docker.tagname(None, dockerfile)
1026Docker.build("final", docker_final_img_name, dockerfile)
1027
Patrick Williams00536fb2021-02-11 14:28:49 -06001028# Print the tag of the final image.
1029print(docker_final_img_name)