blob: 49c6fb47cdcc81e3cff7553fc4ecde18b1d3d0f3 [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(
Jayanth Othayoth96982152024-12-12 05:13:54 -0600103 rev="1.86.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 Williamsc061e072023-12-05 19:11:21 -0600136 rev="10.1.1",
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 Williamsd11e9c72024-08-17 06:44:00 -0400152 rev="v1.15.2",
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(
Ed Tanousabb106a2024-04-04 10:00:02 -0700158 rev="v1.61.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 Williamsc1977832022-09-27 16:54:34 -0500167 rev="v3.11.2",
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 Williamseee65be2023-12-05 19:17:01 -0600178 rev="json-c-0.17-20230812",
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 Williamsc1977832022-09-27 16:54:34 -0500186 rev="9.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 Williams5a2c1132023-12-05 19:20:36 -0600190 rev="v1.0.1",
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 Williamsee3c9ee2021-02-12 20:56:01 -0600197 "open-power/pdbg": PackageDef(build_type="autoconf"),
198 "openbmc/gpioplus": PackageDef(
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600199 build_type="meson",
200 config_flags=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600201 "-Dexamples=false",
202 "-Dtests=disabled",
203 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600204 ),
205 "openbmc/phosphor-dbus-interfaces": PackageDef(
206 depends=["openbmc/sdbusplus"],
207 build_type="meson",
William A. Kennington III4fe87772022-02-11 15:44:29 -0800208 config_flags=["-Dgenerate_md=false"],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600209 ),
210 "openbmc/phosphor-logging": PackageDef(
211 depends=[
Patrick Williams83394612021-02-03 07:12:50 -0600212 "USCiLab/cereal",
Patrick Williams83394612021-02-03 07:12:50 -0600213 "openbmc/phosphor-dbus-interfaces",
214 "openbmc/sdbusplus",
215 "openbmc/sdeventplus",
Patrick Williamsaae36d12021-02-04 16:30:04 -0600216 ],
Patrick Williamsf79ce4c2021-04-30 16:00:49 -0500217 build_type="meson",
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600218 config_flags=[
William A. Kennington III6c98f282022-10-05 13:37:04 -0700219 "-Dlibonly=true",
220 "-Dtests=disabled",
Patrick Williams5eabdae2022-04-14 14:34:34 -0500221 f"-Dyamldir={prefix}/share/phosphor-dbus-yaml/yaml",
Patrick Williamsaae36d12021-02-04 16:30:04 -0600222 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600223 ),
224 "openbmc/phosphor-objmgr": PackageDef(
225 depends=[
Brad Bishop11e57622022-09-14 16:10:25 -0400226 "CLIUtils/CLI11",
Patrick Williams70af95c2022-09-27 16:55:41 -0500227 "boost",
Patrick Williams83394612021-02-03 07:12:50 -0600228 "leethomason/tinyxml2",
Patrick Williams70af95c2022-09-27 16:55:41 -0500229 "openbmc/phosphor-dbus-interfaces",
Patrick Williams83394612021-02-03 07:12:50 -0600230 "openbmc/phosphor-logging",
231 "openbmc/sdbusplus",
Patrick Williamsaae36d12021-02-04 16:30:04 -0600232 ],
Brad Bishop1197e352021-08-03 19:25:46 -0400233 build_type="meson",
234 config_flags=[
235 "-Dtests=disabled",
236 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600237 ),
Jason M. Billsc02ff272023-08-02 10:55:22 -0700238 "openbmc/libpeci": PackageDef(
239 build_type="meson",
240 config_flags=[
241 "-Draw-peci=disabled",
242 ],
243 ),
Manojkiran Eda1c19e452022-10-03 11:01:59 +0530244 "openbmc/libpldm": PackageDef(
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600245 build_type="meson",
Andrew Jeffery29163972024-12-06 17:01:56 +1030246 config_flags=[
247 "-Dabi=deprecated,stable",
248 "-Dtests=false",
249 "-Dabi-compliance-check=false",
250 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600251 ),
252 "openbmc/sdbusplus": PackageDef(
Patrick Williams54d01da2024-09-25 06:40:25 -0400253 depends=[
254 "nlohmann/json",
255 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600256 build_type="meson",
257 custom_post_dl=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600258 "cd tools",
259 f"./setup.py install --root=/ --prefix={prefix}",
260 "cd ..",
261 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600262 config_flags=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600263 "-Dexamples=disabled",
264 "-Dtests=disabled",
265 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600266 ),
267 "openbmc/sdeventplus": PackageDef(
Patrick Williams70af95c2022-09-27 16:55:41 -0500268 depends=[
Patrick Williams70af95c2022-09-27 16:55:41 -0500269 "openbmc/stdplus",
270 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600271 build_type="meson",
272 config_flags=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600273 "-Dexamples=false",
274 "-Dtests=disabled",
275 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600276 ),
277 "openbmc/stdplus": PackageDef(
Patrick Williams70af95c2022-09-27 16:55:41 -0500278 depends=[
Patrick Williams70af95c2022-09-27 16:55:41 -0500279 "fmtlib/fmt",
William A. Kennington IIIca1bf0c2022-10-05 02:23:30 -0700280 "google/googletest",
281 "Naios/function2",
Patrick Williams70af95c2022-09-27 16:55:41 -0500282 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600283 build_type="meson",
284 config_flags=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600285 "-Dexamples=false",
286 "-Dtests=disabled",
William A. Kennington IIIca1bf0c2022-10-05 02:23:30 -0700287 "-Dgtest=enabled",
Patrick Williamsaae36d12021-02-04 16:30:04 -0600288 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600289 ),
290} # type: Dict[str, PackageDef]
Patrick Williams02871c92021-02-01 20:57:19 -0600291
292# Define common flags used for builds
Patrick Williams02871c92021-02-01 20:57:19 -0600293configure_flags = " ".join(
294 [
295 f"--prefix={prefix}",
296 ]
297)
298cmake_flags = " ".join(
299 [
Patrick Williams02871c92021-02-01 20:57:19 -0600300 "-DBUILD_SHARED_LIBS=ON",
Patrick Williams0f2086b2021-02-05 06:49:49 -0600301 "-DCMAKE_BUILD_TYPE=RelWithDebInfo",
Patrick Williams02871c92021-02-01 20:57:19 -0600302 f"-DCMAKE_INSTALL_PREFIX:PATH={prefix}",
Patrick Williams0f2086b2021-02-05 06:49:49 -0600303 "-GNinja",
304 "-DCMAKE_MAKE_PROGRAM=ninja",
Patrick Williams02871c92021-02-01 20:57:19 -0600305 ]
306)
307meson_flags = " ".join(
308 [
309 "--wrap-mode=nodownload",
310 f"-Dprefix={prefix}",
311 ]
312)
313
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600314
315class Package(threading.Thread):
316 """Class used to build the Docker stages for each package.
317
318 Generally, this class should not be instantiated directly but through
319 Package.generate_all().
320 """
321
322 # Copy the packages dictionary.
323 packages = packages.copy()
324
325 # Lock used for thread-safety.
326 lock = threading.Lock()
327
328 def __init__(self, pkg: str):
Patrick Williams05fb2a02022-10-11 17:22:33 -0500329 """pkg - The name of this package (ex. foo/bar )"""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600330 super(Package, self).__init__()
331
332 self.package = pkg
333 self.exception = None # type: Optional[Exception]
334
335 # Reference to this package's
336 self.pkg_def = Package.packages[pkg]
337 self.pkg_def["__package"] = self
338
339 def run(self) -> None:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500340 """Thread 'run' function. Builds the Docker stage."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600341
342 # In case this package has no rev, fetch it from Github.
343 self._update_rev()
344
345 # Find all the Package objects that this package depends on.
346 # This section is locked because we are looking into another
347 # package's PackageDef dict, which could be being modified.
348 Package.lock.acquire()
349 deps: Iterable[Package] = [
350 Package.packages[deppkg]["__package"]
351 for deppkg in self.pkg_def.get("depends", [])
352 ]
353 Package.lock.release()
354
355 # Wait until all the depends finish building. We need them complete
356 # for the "COPY" commands.
357 for deppkg in deps:
358 deppkg.join()
359
360 # Generate this package's Dockerfile.
361 dockerfile = f"""
362FROM {docker_base_img_name}
363{self._df_copycmds()}
364{self._df_build()}
365"""
366
367 # Generate the resulting tag name and save it to the PackageDef.
368 # This section is locked because we are modifying the PackageDef,
369 # which can be accessed by other threads.
370 Package.lock.acquire()
371 tag = Docker.tagname(self._stagename(), dockerfile)
372 self.pkg_def["__tag"] = tag
373 Package.lock.release()
374
375 # Do the build / save any exceptions.
376 try:
377 Docker.build(self.package, tag, dockerfile)
378 except Exception as e:
379 self.exception = e
380
381 @classmethod
382 def generate_all(cls) -> None:
383 """Ensure a Docker stage is created for all defined packages.
384
385 These are done in parallel but with appropriate blocking per
386 package 'depends' specifications.
387 """
388
389 # Create a Package for each defined package.
390 pkg_threads = [Package(p) for p in cls.packages.keys()]
391
392 # Start building them all.
Patrick Williams6dbd7802021-02-20 08:34:10 -0600393 # This section is locked because threads depend on each other,
394 # based on the packages, and they cannot 'join' on a thread
395 # which is not yet started. Adding a lock here allows all the
396 # threads to start before they 'join' their dependencies.
397 Package.lock.acquire()
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600398 for t in pkg_threads:
399 t.start()
Patrick Williams6dbd7802021-02-20 08:34:10 -0600400 Package.lock.release()
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600401
402 # Wait for completion.
403 for t in pkg_threads:
404 t.join()
405 # Check if the thread saved off its own exception.
406 if t.exception:
407 print(f"Package {t.package} failed!", file=sys.stderr)
408 raise t.exception
409
410 @staticmethod
411 def df_all_copycmds() -> str:
412 """Formulate the Dockerfile snippet necessary to copy all packages
413 into the final image.
414 """
415 return Package.df_copycmds_set(Package.packages.keys())
416
417 @classmethod
418 def depcache(cls) -> str:
419 """Create the contents of the '/tmp/depcache'.
420 This file is a comma-separated list of "<pkg>:<rev>".
421 """
422
423 # This needs to be sorted for consistency.
424 depcache = ""
425 for pkg in sorted(cls.packages.keys()):
426 depcache += "%s:%s," % (pkg, cls.packages[pkg]["rev"])
427 return depcache
428
Patrick Williams276bd0e2024-10-02 10:34:32 -0400429 def _check_gerrit_topic(self) -> bool:
430 if not gerrit_topic:
431 return False
432 if not self.package.startswith("openbmc/"):
433 return False
434 if gerrit_project == self.package and gerrit_rev:
435 return False
436
437 try:
438 commits = json.loads(
439 urllib.request.urlopen(
440 f"https://gerrit.openbmc.org/changes/?q=status:open+project:{self.package}+topic:{gerrit_topic}"
441 )
442 .read()
443 .splitlines()[-1]
444 )
445
446 if len(commits) == 0:
447 return False
448 if len(commits) > 1:
449 print(
450 f"{self.package} has more than 1 commit under {gerrit_topic}; using lastest upstream: {len(commits)}",
451 file=sys.stderr,
452 )
453 return False
454
455 change_id = commits[0]["id"]
456
457 commit = json.loads(
458 urllib.request.urlopen(
459 f"https://gerrit.openbmc.org/changes/{change_id}/revisions/current/commit"
460 )
461 .read()
462 .splitlines()[-1]
463 )["commit"]
464
465 print(
466 f"Using {commit} from {gerrit_topic} for {self.package}",
467 file=sys.stderr,
468 )
469 self.pkg_def["rev"] = commit
470 return True
471
472 except urllib.error.HTTPError as e:
473 print(
474 f"Error loading topic {gerrit_topic} for {self.package}: ",
475 e,
476 file=sys.stderr,
477 )
478 return False
479
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600480 def _update_rev(self) -> None:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500481 """Look up the HEAD for missing a static rev."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600482
483 if "rev" in self.pkg_def:
484 return
485
Patrick Williams276bd0e2024-10-02 10:34:32 -0400486 if self._check_gerrit_topic():
487 return
488
Patrick Williams65b21fb2021-02-12 21:21:14 -0600489 # Check if Jenkins/Gerrit gave us a revision and use it.
490 if gerrit_project == self.package and gerrit_rev:
491 print(
492 f"Found Gerrit revision for {self.package}: {gerrit_rev}",
493 file=sys.stderr,
494 )
495 self.pkg_def["rev"] = gerrit_rev
496 return
497
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600498 # Ask Github for all the branches.
Patrick Williams05fb2a02022-10-11 17:22:33 -0500499 lookup = git(
500 "ls-remote", "--heads", f"https://github.com/{self.package}"
501 )
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600502
503 # Find the branch matching {branch} (or fallback to master).
504 # This section is locked because we are modifying the PackageDef.
505 Package.lock.acquire()
506 for line in lookup.split("\n"):
Andrew Geisslerf3d27e62024-04-09 15:24:49 -0500507 if re.fullmatch(f".*{branch}$", line.strip()):
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600508 self.pkg_def["rev"] = line.split()[0]
Andrew Geisslerf3d27e62024-04-09 15:24:49 -0500509 break
Patrick Williamsc7d73642022-10-11 17:22:06 -0500510 elif (
511 "refs/heads/master" in line or "refs/heads/main" in line
512 ) and "rev" not in self.pkg_def:
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600513 self.pkg_def["rev"] = line.split()[0]
514 Package.lock.release()
515
516 def _stagename(self) -> str:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500517 """Create a name for the Docker stage associated with this pkg."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600518 return self.package.replace("/", "-").lower()
519
520 def _url(self) -> str:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500521 """Get the URL for this package."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600522 rev = self.pkg_def["rev"]
523
524 # If the lambda exists, call it.
525 if "url" in self.pkg_def:
526 return self.pkg_def["url"](self.package, rev)
527
528 # Default to the github archive URL.
529 return f"https://github.com/{self.package}/archive/{rev}.tar.gz"
530
531 def _cmd_download(self) -> str:
532 """Formulate the command necessary to download and unpack to source."""
533
534 url = self._url()
535 if ".tar." not in url:
536 raise NotImplementedError(
537 f"Unhandled download type for {self.package}: {url}"
538 )
539
540 cmd = f"curl -L {url} | tar -x"
541
542 if url.endswith(".bz2"):
543 cmd += "j"
544 elif url.endswith(".gz"):
545 cmd += "z"
546 else:
547 raise NotImplementedError(
548 f"Unknown tar flags needed for {self.package}: {url}"
549 )
550
551 return cmd
552
553 def _cmd_cd_srcdir(self) -> str:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500554 """Formulate the command necessary to 'cd' into the source dir."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600555 return f"cd {self.package.split('/')[-1]}*"
556
557 def _df_copycmds(self) -> str:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500558 """Formulate the dockerfile snippet necessary to COPY all depends."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600559
560 if "depends" not in self.pkg_def:
561 return ""
562 return Package.df_copycmds_set(self.pkg_def["depends"])
563
564 @staticmethod
565 def df_copycmds_set(pkgs: Iterable[str]) -> str:
566 """Formulate the Dockerfile snippet necessary to COPY a set of
567 packages into a Docker stage.
568 """
569
570 copy_cmds = ""
571
572 # Sort the packages for consistency.
573 for p in sorted(pkgs):
574 tag = Package.packages[p]["__tag"]
575 copy_cmds += f"COPY --from={tag} {prefix} {prefix}\n"
576 # Workaround for upstream docker bug and multiple COPY cmds
577 # https://github.com/moby/moby/issues/37965
578 copy_cmds += "RUN true\n"
579
580 return copy_cmds
581
582 def _df_build(self) -> str:
583 """Formulate the Dockerfile snippet necessary to download, build, and
584 install a package into a Docker stage.
585 """
586
587 # Download and extract source.
588 result = f"RUN {self._cmd_download()} && {self._cmd_cd_srcdir()} && "
589
590 # Handle 'custom_post_dl' commands.
591 custom_post_dl = self.pkg_def.get("custom_post_dl")
592 if custom_post_dl:
593 result += " && ".join(custom_post_dl) + " && "
594
595 # Build and install package based on 'build_type'.
596 build_type = self.pkg_def["build_type"]
597 if build_type == "autoconf":
598 result += self._cmd_build_autoconf()
599 elif build_type == "cmake":
600 result += self._cmd_build_cmake()
601 elif build_type == "custom":
602 result += self._cmd_build_custom()
603 elif build_type == "make":
604 result += self._cmd_build_make()
605 elif build_type == "meson":
606 result += self._cmd_build_meson()
607 else:
608 raise NotImplementedError(
609 f"Unhandled build type for {self.package}: {build_type}"
610 )
611
Patrick Williams6bce2ca2021-02-12 21:13:37 -0600612 # Handle 'custom_post_install' commands.
613 custom_post_install = self.pkg_def.get("custom_post_install")
614 if custom_post_install:
615 result += " && " + " && ".join(custom_post_install)
616
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600617 return result
618
619 def _cmd_build_autoconf(self) -> str:
620 options = " ".join(self.pkg_def.get("config_flags", []))
621 env = " ".join(self.pkg_def.get("config_env", []))
622 result = "./bootstrap.sh && "
623 result += f"{env} ./configure {configure_flags} {options} && "
624 result += f"make -j{proc_count} && make install"
625 return result
626
627 def _cmd_build_cmake(self) -> str:
628 options = " ".join(self.pkg_def.get("config_flags", []))
629 env = " ".join(self.pkg_def.get("config_env", []))
630 result = "mkdir builddir && cd builddir && "
631 result += f"{env} cmake {cmake_flags} {options} .. && "
632 result += "cmake --build . --target all && "
633 result += "cmake --build . --target install && "
634 result += "cd .."
635 return result
636
637 def _cmd_build_custom(self) -> str:
638 return " && ".join(self.pkg_def.get("build_steps", []))
639
640 def _cmd_build_make(self) -> str:
641 return f"make -j{proc_count} && make install"
642
643 def _cmd_build_meson(self) -> str:
644 options = " ".join(self.pkg_def.get("config_flags", []))
645 env = " ".join(self.pkg_def.get("config_env", []))
Andrew Jefferye2da11a2023-06-15 10:16:37 +0930646 result = f"{env} meson setup builddir {meson_flags} {options} && "
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600647 result += "ninja -C builddir && ninja -C builddir install"
648 return result
649
650
651class Docker:
652 """Class to assist with Docker interactions. All methods are static."""
653
654 @staticmethod
655 def timestamp() -> str:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500656 """Generate a timestamp for today using the ISO week."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600657 today = date.today().isocalendar()
658 return f"{today[0]}-W{today[1]:02}"
659
660 @staticmethod
Patrick Williams41d86212022-11-25 18:28:43 -0600661 def tagname(pkgname: Optional[str], dockerfile: str) -> str:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500662 """Generate a tag name for a package using a hash of the Dockerfile."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600663 result = docker_image_name
664 if pkgname:
665 result += "-" + pkgname
666
667 result += ":" + Docker.timestamp()
668 result += "-" + sha256(dockerfile.encode()).hexdigest()[0:16]
669
670 return result
671
672 @staticmethod
673 def build(pkg: str, tag: str, dockerfile: str) -> None:
Andrew Geissler22e61102023-02-14 14:44:00 -0600674 """Build a docker image using the Dockerfile and tagging it with 'tag'."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600675
676 # If we're not forcing builds, check if it already exists and skip.
677 if not force_build:
Andrew Geissler8f7146f2024-12-11 14:20:47 -0600678 if container.image.ls(
679 tag, "--format", '"{{.Repository}}:{{.Tag}}"'
680 ):
Patrick Williams05fb2a02022-10-11 17:22:33 -0500681 print(
682 f"Image {tag} already exists. Skipping.", file=sys.stderr
683 )
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600684 return
685
686 # Build it.
687 # Capture the output of the 'docker build' command and send it to
688 # stderr (prefixed with the package name). This allows us to see
Manojkiran Edaa6ebc6e2024-06-17 11:51:45 +0530689 # progress but not pollute stdout. Later on we output the final
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600690 # docker tag to stdout and we want to keep that pristine.
691 #
692 # Other unusual flags:
693 # --no-cache: Bypass the Docker cache if 'force_build'.
694 # --force-rm: Clean up Docker processes if they fail.
Andrew Geissler8f7146f2024-12-11 14:20:47 -0600695 container.build(
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600696 proxy_args,
697 "--network=host",
698 "--force-rm",
699 "--no-cache=true" if force_build else "--no-cache=false",
700 "-t",
701 tag,
702 "-",
703 _in=dockerfile,
704 _out=(
705 lambda line: print(
706 pkg + ":", line, end="", file=sys.stderr, flush=True
707 )
708 ),
Jonathan Doman88dd7922024-05-02 10:34:21 -0700709 _err_to_out=True,
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600710 )
711
712
713# Read a bunch of environment variables.
Patrick Williams05fb2a02022-10-11 17:22:33 -0500714docker_image_name = os.environ.get(
715 "DOCKER_IMAGE_NAME", "openbmc/ubuntu-unit-test"
716)
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600717force_build = os.environ.get("FORCE_DOCKER_BUILD")
718is_automated_ci_build = os.environ.get("BUILD_URL", False)
Patrick Williams917b1772024-12-11 15:15:44 -0500719distro = os.environ.get("DISTRO", "ubuntu:oracular")
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600720branch = os.environ.get("BRANCH", "master")
721ubuntu_mirror = os.environ.get("UBUNTU_MIRROR")
Andrew Geissler23ec3322024-10-02 10:45:32 -0400722docker_reg = os.environ.get("DOCKER_REG", "public.ecr.aws/ubuntu")
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600723http_proxy = os.environ.get("http_proxy")
724
Patrick Williams65b21fb2021-02-12 21:21:14 -0600725gerrit_project = os.environ.get("GERRIT_PROJECT")
726gerrit_rev = os.environ.get("GERRIT_PATCHSET_REVISION")
Patrick Williams276bd0e2024-10-02 10:34:32 -0400727gerrit_topic = os.environ.get("GERRIT_TOPIC")
Patrick Williams65b21fb2021-02-12 21:21:14 -0600728
Andrew Geisslerd0dabc32023-04-04 08:09:21 -0600729# Ensure appropriate docker build output to see progress and identify
730# any issues
731os.environ["BUILDKIT_PROGRESS"] = "plain"
732
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600733# Set up some common variables.
734username = os.environ.get("USER", "root")
735homedir = os.environ.get("HOME", "/root")
736gid = os.getgid()
737uid = os.getuid()
738
Josh Lehan6825a012022-03-17 18:31:39 -0700739# Use well-known constants if user is root
740if username == "root":
741 homedir = "/root"
742 gid = 0
743 uid = 0
744
Patrick Williams02871c92021-02-01 20:57:19 -0600745# Special flags if setting up a deb mirror.
746mirror = ""
747if "ubuntu" in distro and ubuntu_mirror:
748 mirror = f"""
Patrick Williamse08ffba2022-12-05 10:33:46 -0600749RUN echo "deb {ubuntu_mirror} \
750 $(. /etc/os-release && echo $VERSION_CODENAME) \
751 main restricted universe multiverse" > /etc/apt/sources.list && \\
752 echo "deb {ubuntu_mirror} \
753 $(. /etc/os-release && echo $VERSION_CODENAME)-updates \
754 main restricted universe multiverse" >> /etc/apt/sources.list && \\
755 echo "deb {ubuntu_mirror} \
756 $(. /etc/os-release && echo $VERSION_CODENAME)-security \
757 main restricted universe multiverse" >> /etc/apt/sources.list && \\
758 echo "deb {ubuntu_mirror} \
759 $(. /etc/os-release && echo $VERSION_CODENAME)-proposed \
760 main restricted universe multiverse" >> /etc/apt/sources.list && \\
761 echo "deb {ubuntu_mirror} \
762 $(. /etc/os-release && echo $VERSION_CODENAME)-backports \
763 main restricted universe multiverse" >> /etc/apt/sources.list
Patrick Williams02871c92021-02-01 20:57:19 -0600764"""
765
766# Special flags for proxying.
767proxy_cmd = ""
Adrian Ambrożewicz34ec77e2021-06-02 10:23:38 +0200768proxy_keyserver = ""
Patrick Williams02871c92021-02-01 20:57:19 -0600769proxy_args = []
770if http_proxy:
771 proxy_cmd = f"""
772RUN echo "[http]" >> {homedir}/.gitconfig && \
773 echo "proxy = {http_proxy}" >> {homedir}/.gitconfig
774"""
Adrian Ambrożewicz34ec77e2021-06-02 10:23:38 +0200775 proxy_keyserver = f"--keyserver-options http-proxy={http_proxy}"
776
Patrick Williams02871c92021-02-01 20:57:19 -0600777 proxy_args.extend(
778 [
779 "--build-arg",
780 f"http_proxy={http_proxy}",
781 "--build-arg",
Lei YUd461cd62021-02-18 14:25:49 +0800782 f"https_proxy={http_proxy}",
Patrick Williams02871c92021-02-01 20:57:19 -0600783 ]
784 )
785
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600786# Create base Dockerfile.
Patrick Williamsa18d9c52021-02-05 09:52:26 -0600787dockerfile_base = f"""
Andrew Geisslerfe2768c2024-10-02 10:10:29 -0400788FROM {docker_reg}/{distro}
Patrick Williams02871c92021-02-01 20:57:19 -0600789
790{mirror}
791
792ENV DEBIAN_FRONTEND noninteractive
793
Patrick Williams8949d3c2022-04-27 16:41:27 -0500794ENV PYTHONPATH "/usr/local/lib/python3.10/site-packages/"
Patrick Williams02871c92021-02-01 20:57:19 -0600795
Patrick Williamsbb16ac12021-04-12 12:23:51 -0500796# Sometimes the ubuntu key expires and we need a way to force an execution
797# of the apt-get commands for the dbgsym-keyring. When this happens we see
798# an error like: "Release: The following signatures were invalid:"
799# Insert a bogus echo that we can change here when we get this error to force
800# the update.
801RUN echo "ubuntu keyserver rev as of 2021-04-21"
802
Patrick Williams02871c92021-02-01 20:57:19 -0600803# We need the keys to be imported for dbgsym repos
804# New releases have a package, older ones fall back to manual fetching
805# https://wiki.ubuntu.com/Debug%20Symbol%20Packages
Jagpal Singh Gill575b5e42023-04-14 15:52:10 -0700806# Known issue with gpg to get keys via proxy -
807# https://bugs.launchpad.net/ubuntu/+source/gnupg2/+bug/1788190, hence using
808# curl to get keys.
Patrick Williams50837432021-02-06 12:24:05 -0600809RUN apt-get update && apt-get dist-upgrade -yy && \
Jian Zhang938d3032023-07-05 13:35:35 +0800810 ( apt-get install -yy gpgv ubuntu-dbgsym-keyring || \
Jagpal Singh Gill575b5e42023-04-14 15:52:10 -0700811 ( apt-get install -yy dirmngr curl && \
812 curl -sSL \
813 'https://keyserver.ubuntu.com/pks/lookup?op=get&search=0xF2EDC64DC5AEE1F6B9C621F0C8CAB6595FDFF622' \
814 | apt-key add - ))
Patrick Williams02871c92021-02-01 20:57:19 -0600815
816# Parse the current repo list into a debug repo list
Patrick Williamse08ffba2022-12-05 10:33:46 -0600817RUN sed -n '/^deb /s,^deb [^ ]* ,deb http://ddebs.ubuntu.com ,p' \
818 /etc/apt/sources.list >/etc/apt/sources.list.d/debug.list
Patrick Williams02871c92021-02-01 20:57:19 -0600819
820# Remove non-existent debug repos
Patrick Williams41d86212022-11-25 18:28:43 -0600821RUN sed -i '/-\\(backports\\|security\\) /d' /etc/apt/sources.list.d/debug.list
Patrick Williams02871c92021-02-01 20:57:19 -0600822
823RUN cat /etc/apt/sources.list.d/debug.list
824
825RUN apt-get update && apt-get dist-upgrade -yy && apt-get install -yy \
Andrew Jeffery58f19152023-05-22 16:41:32 +0930826 abi-compliance-checker \
Andrew Jeffery8b112062023-05-22 20:49:11 +0930827 abi-dumper \
Patrick Williams02871c92021-02-01 20:57:19 -0600828 autoconf \
829 autoconf-archive \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600830 bison \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600831 cmake \
832 curl \
833 dbus \
834 device-tree-compiler \
835 flex \
Andrew Jefferydbce9762024-12-06 11:12:19 +1030836 g++-14 \
837 gcc-14 \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600838 git \
Patrick Williamsb4eec872024-10-04 10:49:50 -0400839 glib-2.0 \
Patrick Williams6968e832024-08-16 17:43:24 -0400840 gnupg \
Patrick Williams02871c92021-02-01 20:57:19 -0600841 iproute2 \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600842 iputils-ping \
Manojkiran Eda524a3312023-04-05 15:37:47 +0530843 libaudit-dev \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600844 libc6-dbg \
845 libc6-dev \
Patrick Williamsc7bc4d12024-10-04 11:22:02 -0400846 libcjson-dev \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600847 libconfig++-dev \
848 libcryptsetup-dev \
849 libdbus-1-dev \
850 libevdev-dev \
851 libgpiod-dev \
852 libi2c-dev \
853 libjpeg-dev \
854 libjson-perl \
855 libldap2-dev \
856 libmimetic-dev \
Patrick Williams02871c92021-02-01 20:57:19 -0600857 libnl-3-dev \
858 libnl-genl-3-dev \
Patrick Williams02871c92021-02-01 20:57:19 -0600859 libpam0g-dev \
Patrick Williams02871c92021-02-01 20:57:19 -0600860 libpciaccess-dev \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600861 libperlio-gzip-perl \
862 libpng-dev \
863 libprotobuf-dev \
864 libsnmp-dev \
865 libssl-dev \
866 libsystemd-dev \
867 libtool \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600868 liburing-dev \
Patrick Williams02871c92021-02-01 20:57:19 -0600869 libxml2-utils \
Patrick Williams0eedeed2021-02-06 19:06:09 -0600870 libxml-simple-perl \
Patrick Williams6968e832024-08-16 17:43:24 -0400871 lsb-release \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600872 ninja-build \
873 npm \
874 pkg-config \
875 protobuf-compiler \
876 python3 \
877 python3-dev\
878 python3-git \
879 python3-mako \
880 python3-pip \
William A. Kennington III25ba1e22024-03-24 15:47:51 -0700881 python3-protobuf \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600882 python3-setuptools \
883 python3-socks \
884 python3-yaml \
John Wedig9adf68d2021-11-16 14:00:39 -0800885 rsync \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600886 shellcheck \
Ewelina Walkusz8dd1bfe2024-05-27 09:34:50 +0200887 socat \
Patrick Williams6968e832024-08-16 17:43:24 -0400888 software-properties-common \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600889 sudo \
890 systemd \
Patrick Williams917b1772024-12-11 15:15:44 -0500891 systemd-dev \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600892 valgrind \
Andrew Geisslerb565f822022-12-14 11:43:25 -0600893 vim \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600894 wget \
895 xxd
Patrick Williams02871c92021-02-01 20:57:19 -0600896
Andrew Jefferydbce9762024-12-06 11:12:19 +1030897RUN update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-14 14 \
898 --slave /usr/bin/g++ g++ /usr/bin/g++-14 \
899 --slave /usr/bin/gcov gcov /usr/bin/gcov-14 \
900 --slave /usr/bin/gcov-dump gcov-dump /usr/bin/gcov-dump-14 \
901 --slave /usr/bin/gcov-tool gcov-tool /usr/bin/gcov-tool-14
Patrick Williams961f1482023-05-30 09:24:16 -0500902RUN update-alternatives --remove cpp /usr/bin/cpp && \
Andrew Jefferydbce9762024-12-06 11:12:19 +1030903 update-alternatives --install /usr/bin/cpp cpp /usr/bin/cpp-14 14
Patrick Williams02871c92021-02-01 20:57:19 -0600904
Patrick Williams6968e832024-08-16 17:43:24 -0400905# Set up LLVM apt repository.
Patrick Williamsed8aeca2024-12-18 11:08:29 -0500906RUN bash -c "$(wget -O - https://apt.llvm.org/llvm.sh)" 19
Patrick Williams6968e832024-08-16 17:43:24 -0400907
908# Install extra clang tools
Patrick Williamsed8aeca2024-12-18 11:08:29 -0500909RUN apt-get install -y \
910 clang-19 \
911 clang-format-19 \
912 clang-tidy-19
Patrick Williams6968e832024-08-16 17:43:24 -0400913
Patrick Williamsed8aeca2024-12-18 11:08:29 -0500914RUN update-alternatives --install /usr/bin/clang clang /usr/bin/clang-19 1000 \
915 --slave /usr/bin/clang++ clang++ /usr/bin/clang++-19 \
916 --slave /usr/bin/clang-tidy clang-tidy /usr/bin/clang-tidy-19 \
917 --slave /usr/bin/clang-format clang-format /usr/bin/clang-format-19 \
Patrick Williamse08ffba2022-12-05 10:33:46 -0600918 --slave /usr/bin/run-clang-tidy run-clang-tidy.py \
Patrick Williamsed8aeca2024-12-18 11:08:29 -0500919 /usr/bin/run-clang-tidy-19 \
920 --slave /usr/bin/scan-build scan-build /usr/bin/scan-build-19
Patrick Williams02871c92021-02-01 20:57:19 -0600921
Patrick Williams50837432021-02-06 12:24:05 -0600922"""
923
924if is_automated_ci_build:
925 dockerfile_base += f"""
Manojkiran Edaa6ebc6e2024-06-17 11:51:45 +0530926# Run an arbitrary command to pollute the docker cache regularly force us
Patrick Williams50837432021-02-06 12:24:05 -0600927# to re-run `apt-get update` daily.
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600928RUN echo {Docker.timestamp()}
Patrick Williams50837432021-02-06 12:24:05 -0600929RUN apt-get update && apt-get dist-upgrade -yy
930
931"""
932
Patrick Williams41d86212022-11-25 18:28:43 -0600933dockerfile_base += """
Patrick Williams5e4d8402023-04-11 22:19:30 -0500934RUN pip3 install --break-system-packages \
Patrick Williams818023d2023-04-10 13:07:15 -0500935 beautysh \
936 black \
937 codespell \
938 flake8 \
Ewelina Walkusz2d8c5512024-07-02 10:49:38 +0200939 gcovr \
Patrick Williams818023d2023-04-10 13:07:15 -0500940 gitlint \
941 inflection \
Arya K Padmanf7381ad2024-10-14 02:29:53 -0500942 isoduration \
Patrick Williams818023d2023-04-10 13:07:15 -0500943 isort \
944 jsonschema \
Patrick Williams16baaf72023-12-05 19:21:51 -0600945 meson==1.3.0 \
Patrick Williams818023d2023-04-10 13:07:15 -0500946 requests
Patrick Williamsb08ddf72022-12-06 08:56:31 -0600947
948RUN npm install -g \
Xinnan Xied0757de2024-05-27 14:22:58 +0800949 eslint@v8.56.0 eslint-plugin-json@v3.1.0 \
Patrick Williams7d41f6d2022-12-06 10:19:43 -0600950 markdownlint-cli@latest \
Patrick Williamsb08ddf72022-12-06 08:56:31 -0600951 prettier@latest
Ed Tanousfb9948a2022-06-21 09:10:24 -0700952"""
953
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600954# Build the base and stage docker images.
955docker_base_img_name = Docker.tagname("base", dockerfile_base)
956Docker.build("base", docker_base_img_name, dockerfile_base)
957Package.generate_all()
Patrick Williams02871c92021-02-01 20:57:19 -0600958
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600959# Create the final Dockerfile.
Patrick Williamsa18d9c52021-02-05 09:52:26 -0600960dockerfile = f"""
Patrick Williams02871c92021-02-01 20:57:19 -0600961# Build the final output image
Patrick Williamsa18d9c52021-02-05 09:52:26 -0600962FROM {docker_base_img_name}
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600963{Package.df_all_copycmds()}
Patrick Williams02871c92021-02-01 20:57:19 -0600964
965# Some of our infrastructure still relies on the presence of this file
966# even though it is no longer needed to rebuild the docker environment
967# NOTE: The file is sorted to ensure the ordering is stable.
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600968RUN echo '{Package.depcache()}' > /tmp/depcache
Patrick Williams02871c92021-02-01 20:57:19 -0600969
Patrick Williams67cc0612023-04-11 22:16:46 -0500970# Ensure the group, user, and home directory are created (or rename them if
971# they already exist).
972RUN if grep -q ":{gid}:" /etc/group ; then \
973 groupmod -n {username} $(awk -F : '{{ if ($3 == {gid}) {{ print $1 }} }}' /etc/group) ; \
974 else \
975 groupadd -f -g {gid} {username} ; \
976 fi
Patrick Williams02871c92021-02-01 20:57:19 -0600977RUN mkdir -p "{os.path.dirname(homedir)}"
Patrick Williams67cc0612023-04-11 22:16:46 -0500978RUN if grep -q ":{uid}:" /etc/passwd ; then \
Patrick Williams73b3ee92023-04-24 10:11:01 -0500979 usermod -l {username} -d {homedir} -m $(awk -F : '{{ if ($3 == {uid}) {{ print $1 }} }}' /etc/passwd) ; \
Patrick Williams67cc0612023-04-11 22:16:46 -0500980 else \
981 useradd -d {homedir} -m -u {uid} -g {gid} {username} ; \
982 fi
Patrick Williams02871c92021-02-01 20:57:19 -0600983RUN sed -i '1iDefaults umask=000' /etc/sudoers
984RUN echo "{username} ALL=(ALL) NOPASSWD: ALL" >>/etc/sudoers
985
Andrew Geissler305a9a52021-04-07 11:08:40 -0500986# Ensure user has ability to write to /usr/local for different tool
987# and data installs
Andrew Geissler7bb00b12021-05-10 15:12:08 -0500988RUN chown -R {username}:{username} /usr/local/share
Andrew Geissler305a9a52021-04-07 11:08:40 -0500989
Jonathan Domanab4fee82024-01-31 15:39:20 -0800990# Update library cache
991RUN ldconfig
992
Patrick Williams02871c92021-02-01 20:57:19 -0600993{proxy_cmd}
994
995RUN /bin/bash
996"""
997
Patrick Williamsa18d9c52021-02-05 09:52:26 -0600998# Do the final docker build
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600999docker_final_img_name = Docker.tagname(None, dockerfile)
1000Docker.build("final", docker_final_img_name, dockerfile)
1001
Patrick Williams00536fb2021-02-11 14:28:49 -06001002# Print the tag of the final image.
1003print(docker_final_img_name)