blob: d6e2405f4932de1d59d2c99b024373128e2e4a60 [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 Williamsaae36d12021-02-04 16:30:04 -0600221 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600222 ),
223 "openbmc/phosphor-objmgr": PackageDef(
224 depends=[
Brad Bishop11e57622022-09-14 16:10:25 -0400225 "CLIUtils/CLI11",
Patrick Williams70af95c2022-09-27 16:55:41 -0500226 "boost",
Patrick Williams83394612021-02-03 07:12:50 -0600227 "leethomason/tinyxml2",
Patrick Williams70af95c2022-09-27 16:55:41 -0500228 "openbmc/phosphor-dbus-interfaces",
Patrick Williams83394612021-02-03 07:12:50 -0600229 "openbmc/phosphor-logging",
230 "openbmc/sdbusplus",
Patrick Williamsaae36d12021-02-04 16:30:04 -0600231 ],
Brad Bishop1197e352021-08-03 19:25:46 -0400232 build_type="meson",
233 config_flags=[
234 "-Dtests=disabled",
235 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600236 ),
Jason M. Billsc02ff272023-08-02 10:55:22 -0700237 "openbmc/libpeci": PackageDef(
238 build_type="meson",
239 config_flags=[
240 "-Draw-peci=disabled",
241 ],
242 ),
Manojkiran Eda1c19e452022-10-03 11:01:59 +0530243 "openbmc/libpldm": PackageDef(
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600244 build_type="meson",
Andrew Jeffery29163972024-12-06 17:01:56 +1030245 config_flags=[
246 "-Dabi=deprecated,stable",
247 "-Dtests=false",
248 "-Dabi-compliance-check=false",
249 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600250 ),
251 "openbmc/sdbusplus": PackageDef(
Patrick Williams54d01da2024-09-25 06:40:25 -0400252 depends=[
253 "nlohmann/json",
254 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600255 build_type="meson",
256 custom_post_dl=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600257 "cd tools",
258 f"./setup.py install --root=/ --prefix={prefix}",
259 "cd ..",
260 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600261 config_flags=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600262 "-Dexamples=disabled",
263 "-Dtests=disabled",
264 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600265 ),
266 "openbmc/sdeventplus": PackageDef(
Patrick Williams70af95c2022-09-27 16:55:41 -0500267 depends=[
Patrick Williams70af95c2022-09-27 16:55:41 -0500268 "openbmc/stdplus",
269 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600270 build_type="meson",
271 config_flags=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600272 "-Dexamples=false",
273 "-Dtests=disabled",
274 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600275 ),
276 "openbmc/stdplus": PackageDef(
Patrick Williams70af95c2022-09-27 16:55:41 -0500277 depends=[
Patrick Williams70af95c2022-09-27 16:55:41 -0500278 "fmtlib/fmt",
William A. Kennington IIIca1bf0c2022-10-05 02:23:30 -0700279 "google/googletest",
280 "Naios/function2",
Patrick Williams70af95c2022-09-27 16:55:41 -0500281 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600282 build_type="meson",
283 config_flags=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600284 "-Dexamples=false",
285 "-Dtests=disabled",
William A. Kennington IIIca1bf0c2022-10-05 02:23:30 -0700286 "-Dgtest=enabled",
Patrick Williamsaae36d12021-02-04 16:30:04 -0600287 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600288 ),
289} # type: Dict[str, PackageDef]
Patrick Williams02871c92021-02-01 20:57:19 -0600290
291# Define common flags used for builds
Patrick Williams02871c92021-02-01 20:57:19 -0600292configure_flags = " ".join(
293 [
294 f"--prefix={prefix}",
295 ]
296)
297cmake_flags = " ".join(
298 [
Patrick Williams02871c92021-02-01 20:57:19 -0600299 "-DBUILD_SHARED_LIBS=ON",
Patrick Williams0f2086b2021-02-05 06:49:49 -0600300 "-DCMAKE_BUILD_TYPE=RelWithDebInfo",
Patrick Williams02871c92021-02-01 20:57:19 -0600301 f"-DCMAKE_INSTALL_PREFIX:PATH={prefix}",
Patrick Williams0f2086b2021-02-05 06:49:49 -0600302 "-GNinja",
303 "-DCMAKE_MAKE_PROGRAM=ninja",
Patrick Williams02871c92021-02-01 20:57:19 -0600304 ]
305)
306meson_flags = " ".join(
307 [
308 "--wrap-mode=nodownload",
309 f"-Dprefix={prefix}",
310 ]
311)
312
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600313
314class Package(threading.Thread):
315 """Class used to build the Docker stages for each package.
316
317 Generally, this class should not be instantiated directly but through
318 Package.generate_all().
319 """
320
321 # Copy the packages dictionary.
322 packages = packages.copy()
323
324 # Lock used for thread-safety.
325 lock = threading.Lock()
326
327 def __init__(self, pkg: str):
Patrick Williams05fb2a02022-10-11 17:22:33 -0500328 """pkg - The name of this package (ex. foo/bar )"""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600329 super(Package, self).__init__()
330
331 self.package = pkg
332 self.exception = None # type: Optional[Exception]
333
334 # Reference to this package's
335 self.pkg_def = Package.packages[pkg]
336 self.pkg_def["__package"] = self
337
338 def run(self) -> None:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500339 """Thread 'run' function. Builds the Docker stage."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600340
341 # In case this package has no rev, fetch it from Github.
342 self._update_rev()
343
344 # Find all the Package objects that this package depends on.
345 # This section is locked because we are looking into another
346 # package's PackageDef dict, which could be being modified.
347 Package.lock.acquire()
348 deps: Iterable[Package] = [
349 Package.packages[deppkg]["__package"]
350 for deppkg in self.pkg_def.get("depends", [])
351 ]
352 Package.lock.release()
353
354 # Wait until all the depends finish building. We need them complete
355 # for the "COPY" commands.
356 for deppkg in deps:
357 deppkg.join()
358
359 # Generate this package's Dockerfile.
360 dockerfile = f"""
361FROM {docker_base_img_name}
362{self._df_copycmds()}
363{self._df_build()}
364"""
365
366 # Generate the resulting tag name and save it to the PackageDef.
367 # This section is locked because we are modifying the PackageDef,
368 # which can be accessed by other threads.
369 Package.lock.acquire()
370 tag = Docker.tagname(self._stagename(), dockerfile)
371 self.pkg_def["__tag"] = tag
372 Package.lock.release()
373
374 # Do the build / save any exceptions.
375 try:
376 Docker.build(self.package, tag, dockerfile)
377 except Exception as e:
378 self.exception = e
379
380 @classmethod
381 def generate_all(cls) -> None:
382 """Ensure a Docker stage is created for all defined packages.
383
384 These are done in parallel but with appropriate blocking per
385 package 'depends' specifications.
386 """
387
388 # Create a Package for each defined package.
389 pkg_threads = [Package(p) for p in cls.packages.keys()]
390
391 # Start building them all.
Patrick Williams6dbd7802021-02-20 08:34:10 -0600392 # This section is locked because threads depend on each other,
393 # based on the packages, and they cannot 'join' on a thread
394 # which is not yet started. Adding a lock here allows all the
395 # threads to start before they 'join' their dependencies.
396 Package.lock.acquire()
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600397 for t in pkg_threads:
398 t.start()
Patrick Williams6dbd7802021-02-20 08:34:10 -0600399 Package.lock.release()
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600400
401 # Wait for completion.
402 for t in pkg_threads:
403 t.join()
404 # Check if the thread saved off its own exception.
405 if t.exception:
406 print(f"Package {t.package} failed!", file=sys.stderr)
407 raise t.exception
408
409 @staticmethod
410 def df_all_copycmds() -> str:
411 """Formulate the Dockerfile snippet necessary to copy all packages
412 into the final image.
413 """
414 return Package.df_copycmds_set(Package.packages.keys())
415
416 @classmethod
417 def depcache(cls) -> str:
418 """Create the contents of the '/tmp/depcache'.
419 This file is a comma-separated list of "<pkg>:<rev>".
420 """
421
422 # This needs to be sorted for consistency.
423 depcache = ""
424 for pkg in sorted(cls.packages.keys()):
425 depcache += "%s:%s," % (pkg, cls.packages[pkg]["rev"])
426 return depcache
427
Patrick Williams276bd0e2024-10-02 10:34:32 -0400428 def _check_gerrit_topic(self) -> bool:
429 if not gerrit_topic:
430 return False
431 if not self.package.startswith("openbmc/"):
432 return False
433 if gerrit_project == self.package and gerrit_rev:
434 return False
435
436 try:
437 commits = json.loads(
438 urllib.request.urlopen(
439 f"https://gerrit.openbmc.org/changes/?q=status:open+project:{self.package}+topic:{gerrit_topic}"
440 )
441 .read()
442 .splitlines()[-1]
443 )
444
445 if len(commits) == 0:
446 return False
447 if len(commits) > 1:
448 print(
449 f"{self.package} has more than 1 commit under {gerrit_topic}; using lastest upstream: {len(commits)}",
450 file=sys.stderr,
451 )
452 return False
453
454 change_id = commits[0]["id"]
455
456 commit = json.loads(
457 urllib.request.urlopen(
458 f"https://gerrit.openbmc.org/changes/{change_id}/revisions/current/commit"
459 )
460 .read()
461 .splitlines()[-1]
462 )["commit"]
463
464 print(
465 f"Using {commit} from {gerrit_topic} for {self.package}",
466 file=sys.stderr,
467 )
468 self.pkg_def["rev"] = commit
469 return True
470
471 except urllib.error.HTTPError as e:
472 print(
473 f"Error loading topic {gerrit_topic} for {self.package}: ",
474 e,
475 file=sys.stderr,
476 )
477 return False
478
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600479 def _update_rev(self) -> None:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500480 """Look up the HEAD for missing a static rev."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600481
482 if "rev" in self.pkg_def:
483 return
484
Patrick Williams276bd0e2024-10-02 10:34:32 -0400485 if self._check_gerrit_topic():
486 return
487
Patrick Williams65b21fb2021-02-12 21:21:14 -0600488 # Check if Jenkins/Gerrit gave us a revision and use it.
489 if gerrit_project == self.package and gerrit_rev:
490 print(
491 f"Found Gerrit revision for {self.package}: {gerrit_rev}",
492 file=sys.stderr,
493 )
494 self.pkg_def["rev"] = gerrit_rev
495 return
496
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600497 # Ask Github for all the branches.
Patrick Williams05fb2a02022-10-11 17:22:33 -0500498 lookup = git(
499 "ls-remote", "--heads", f"https://github.com/{self.package}"
500 )
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600501
502 # Find the branch matching {branch} (or fallback to master).
503 # This section is locked because we are modifying the PackageDef.
504 Package.lock.acquire()
505 for line in lookup.split("\n"):
Andrew Geisslerf3d27e62024-04-09 15:24:49 -0500506 if re.fullmatch(f".*{branch}$", line.strip()):
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600507 self.pkg_def["rev"] = line.split()[0]
Andrew Geisslerf3d27e62024-04-09 15:24:49 -0500508 break
Patrick Williamsc7d73642022-10-11 17:22:06 -0500509 elif (
510 "refs/heads/master" in line or "refs/heads/main" in line
511 ) and "rev" not in self.pkg_def:
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600512 self.pkg_def["rev"] = line.split()[0]
513 Package.lock.release()
514
515 def _stagename(self) -> str:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500516 """Create a name for the Docker stage associated with this pkg."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600517 return self.package.replace("/", "-").lower()
518
519 def _url(self) -> str:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500520 """Get the URL for this package."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600521 rev = self.pkg_def["rev"]
522
523 # If the lambda exists, call it.
524 if "url" in self.pkg_def:
525 return self.pkg_def["url"](self.package, rev)
526
527 # Default to the github archive URL.
528 return f"https://github.com/{self.package}/archive/{rev}.tar.gz"
529
530 def _cmd_download(self) -> str:
531 """Formulate the command necessary to download and unpack to source."""
532
533 url = self._url()
534 if ".tar." not in url:
535 raise NotImplementedError(
536 f"Unhandled download type for {self.package}: {url}"
537 )
538
539 cmd = f"curl -L {url} | tar -x"
540
541 if url.endswith(".bz2"):
542 cmd += "j"
543 elif url.endswith(".gz"):
544 cmd += "z"
545 else:
546 raise NotImplementedError(
547 f"Unknown tar flags needed for {self.package}: {url}"
548 )
549
550 return cmd
551
552 def _cmd_cd_srcdir(self) -> str:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500553 """Formulate the command necessary to 'cd' into the source dir."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600554 return f"cd {self.package.split('/')[-1]}*"
555
556 def _df_copycmds(self) -> str:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500557 """Formulate the dockerfile snippet necessary to COPY all depends."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600558
559 if "depends" not in self.pkg_def:
560 return ""
561 return Package.df_copycmds_set(self.pkg_def["depends"])
562
563 @staticmethod
564 def df_copycmds_set(pkgs: Iterable[str]) -> str:
565 """Formulate the Dockerfile snippet necessary to COPY a set of
566 packages into a Docker stage.
567 """
568
569 copy_cmds = ""
570
571 # Sort the packages for consistency.
572 for p in sorted(pkgs):
573 tag = Package.packages[p]["__tag"]
574 copy_cmds += f"COPY --from={tag} {prefix} {prefix}\n"
575 # Workaround for upstream docker bug and multiple COPY cmds
576 # https://github.com/moby/moby/issues/37965
577 copy_cmds += "RUN true\n"
578
579 return copy_cmds
580
581 def _df_build(self) -> str:
582 """Formulate the Dockerfile snippet necessary to download, build, and
583 install a package into a Docker stage.
584 """
585
586 # Download and extract source.
587 result = f"RUN {self._cmd_download()} && {self._cmd_cd_srcdir()} && "
588
589 # Handle 'custom_post_dl' commands.
590 custom_post_dl = self.pkg_def.get("custom_post_dl")
591 if custom_post_dl:
592 result += " && ".join(custom_post_dl) + " && "
593
594 # Build and install package based on 'build_type'.
595 build_type = self.pkg_def["build_type"]
596 if build_type == "autoconf":
597 result += self._cmd_build_autoconf()
598 elif build_type == "cmake":
599 result += self._cmd_build_cmake()
600 elif build_type == "custom":
601 result += self._cmd_build_custom()
602 elif build_type == "make":
603 result += self._cmd_build_make()
604 elif build_type == "meson":
605 result += self._cmd_build_meson()
606 else:
607 raise NotImplementedError(
608 f"Unhandled build type for {self.package}: {build_type}"
609 )
610
Patrick Williams6bce2ca2021-02-12 21:13:37 -0600611 # Handle 'custom_post_install' commands.
612 custom_post_install = self.pkg_def.get("custom_post_install")
613 if custom_post_install:
614 result += " && " + " && ".join(custom_post_install)
615
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600616 return result
617
618 def _cmd_build_autoconf(self) -> str:
619 options = " ".join(self.pkg_def.get("config_flags", []))
620 env = " ".join(self.pkg_def.get("config_env", []))
621 result = "./bootstrap.sh && "
622 result += f"{env} ./configure {configure_flags} {options} && "
623 result += f"make -j{proc_count} && make install"
624 return result
625
626 def _cmd_build_cmake(self) -> str:
627 options = " ".join(self.pkg_def.get("config_flags", []))
628 env = " ".join(self.pkg_def.get("config_env", []))
629 result = "mkdir builddir && cd builddir && "
630 result += f"{env} cmake {cmake_flags} {options} .. && "
631 result += "cmake --build . --target all && "
632 result += "cmake --build . --target install && "
633 result += "cd .."
634 return result
635
636 def _cmd_build_custom(self) -> str:
637 return " && ".join(self.pkg_def.get("build_steps", []))
638
639 def _cmd_build_make(self) -> str:
640 return f"make -j{proc_count} && make install"
641
642 def _cmd_build_meson(self) -> str:
643 options = " ".join(self.pkg_def.get("config_flags", []))
644 env = " ".join(self.pkg_def.get("config_env", []))
Andrew Jefferye2da11a2023-06-15 10:16:37 +0930645 result = f"{env} meson setup builddir {meson_flags} {options} && "
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600646 result += "ninja -C builddir && ninja -C builddir install"
647 return result
648
649
650class Docker:
651 """Class to assist with Docker interactions. All methods are static."""
652
653 @staticmethod
654 def timestamp() -> str:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500655 """Generate a timestamp for today using the ISO week."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600656 today = date.today().isocalendar()
657 return f"{today[0]}-W{today[1]:02}"
658
659 @staticmethod
Patrick Williams41d86212022-11-25 18:28:43 -0600660 def tagname(pkgname: Optional[str], dockerfile: str) -> str:
Patrick Williams05fb2a02022-10-11 17:22:33 -0500661 """Generate a tag name for a package using a hash of the Dockerfile."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600662 result = docker_image_name
663 if pkgname:
664 result += "-" + pkgname
665
666 result += ":" + Docker.timestamp()
667 result += "-" + sha256(dockerfile.encode()).hexdigest()[0:16]
668
669 return result
670
671 @staticmethod
672 def build(pkg: str, tag: str, dockerfile: str) -> None:
Andrew Geissler22e61102023-02-14 14:44:00 -0600673 """Build a docker image using the Dockerfile and tagging it with 'tag'."""
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600674
675 # If we're not forcing builds, check if it already exists and skip.
676 if not force_build:
Andrew Geissler8f7146f2024-12-11 14:20:47 -0600677 if container.image.ls(
678 tag, "--format", '"{{.Repository}}:{{.Tag}}"'
679 ):
Patrick Williams05fb2a02022-10-11 17:22:33 -0500680 print(
681 f"Image {tag} already exists. Skipping.", file=sys.stderr
682 )
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600683 return
684
685 # Build it.
686 # Capture the output of the 'docker build' command and send it to
687 # stderr (prefixed with the package name). This allows us to see
Manojkiran Edaa6ebc6e2024-06-17 11:51:45 +0530688 # progress but not pollute stdout. Later on we output the final
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600689 # docker tag to stdout and we want to keep that pristine.
690 #
691 # Other unusual flags:
692 # --no-cache: Bypass the Docker cache if 'force_build'.
693 # --force-rm: Clean up Docker processes if they fail.
Andrew Geissler8f7146f2024-12-11 14:20:47 -0600694 container.build(
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600695 proxy_args,
696 "--network=host",
697 "--force-rm",
698 "--no-cache=true" if force_build else "--no-cache=false",
699 "-t",
700 tag,
701 "-",
702 _in=dockerfile,
703 _out=(
704 lambda line: print(
705 pkg + ":", line, end="", file=sys.stderr, flush=True
706 )
707 ),
Jonathan Doman88dd7922024-05-02 10:34:21 -0700708 _err_to_out=True,
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600709 )
710
711
712# Read a bunch of environment variables.
Patrick Williams05fb2a02022-10-11 17:22:33 -0500713docker_image_name = os.environ.get(
714 "DOCKER_IMAGE_NAME", "openbmc/ubuntu-unit-test"
715)
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600716force_build = os.environ.get("FORCE_DOCKER_BUILD")
717is_automated_ci_build = os.environ.get("BUILD_URL", False)
Patrick Williams917b1772024-12-11 15:15:44 -0500718distro = os.environ.get("DISTRO", "ubuntu:oracular")
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600719branch = os.environ.get("BRANCH", "master")
720ubuntu_mirror = os.environ.get("UBUNTU_MIRROR")
Andrew Geissler23ec3322024-10-02 10:45:32 -0400721docker_reg = os.environ.get("DOCKER_REG", "public.ecr.aws/ubuntu")
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600722http_proxy = os.environ.get("http_proxy")
723
Patrick Williams65b21fb2021-02-12 21:21:14 -0600724gerrit_project = os.environ.get("GERRIT_PROJECT")
725gerrit_rev = os.environ.get("GERRIT_PATCHSET_REVISION")
Patrick Williams276bd0e2024-10-02 10:34:32 -0400726gerrit_topic = os.environ.get("GERRIT_TOPIC")
Patrick Williams65b21fb2021-02-12 21:21:14 -0600727
Andrew Geisslerd0dabc32023-04-04 08:09:21 -0600728# Ensure appropriate docker build output to see progress and identify
729# any issues
730os.environ["BUILDKIT_PROGRESS"] = "plain"
731
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600732# Set up some common variables.
733username = os.environ.get("USER", "root")
734homedir = os.environ.get("HOME", "/root")
735gid = os.getgid()
736uid = os.getuid()
737
Josh Lehan6825a012022-03-17 18:31:39 -0700738# Use well-known constants if user is root
739if username == "root":
740 homedir = "/root"
741 gid = 0
742 uid = 0
743
Patrick Williams02871c92021-02-01 20:57:19 -0600744# Special flags if setting up a deb mirror.
745mirror = ""
746if "ubuntu" in distro and ubuntu_mirror:
747 mirror = f"""
Patrick Williamse08ffba2022-12-05 10:33:46 -0600748RUN echo "deb {ubuntu_mirror} \
749 $(. /etc/os-release && echo $VERSION_CODENAME) \
750 main restricted universe multiverse" > /etc/apt/sources.list && \\
751 echo "deb {ubuntu_mirror} \
752 $(. /etc/os-release && echo $VERSION_CODENAME)-updates \
753 main restricted universe multiverse" >> /etc/apt/sources.list && \\
754 echo "deb {ubuntu_mirror} \
755 $(. /etc/os-release && echo $VERSION_CODENAME)-security \
756 main restricted universe multiverse" >> /etc/apt/sources.list && \\
757 echo "deb {ubuntu_mirror} \
758 $(. /etc/os-release && echo $VERSION_CODENAME)-proposed \
759 main restricted universe multiverse" >> /etc/apt/sources.list && \\
760 echo "deb {ubuntu_mirror} \
761 $(. /etc/os-release && echo $VERSION_CODENAME)-backports \
762 main restricted universe multiverse" >> /etc/apt/sources.list
Patrick Williams02871c92021-02-01 20:57:19 -0600763"""
764
765# Special flags for proxying.
766proxy_cmd = ""
Adrian Ambrożewicz34ec77e2021-06-02 10:23:38 +0200767proxy_keyserver = ""
Patrick Williams02871c92021-02-01 20:57:19 -0600768proxy_args = []
769if http_proxy:
770 proxy_cmd = f"""
771RUN echo "[http]" >> {homedir}/.gitconfig && \
772 echo "proxy = {http_proxy}" >> {homedir}/.gitconfig
773"""
Adrian Ambrożewicz34ec77e2021-06-02 10:23:38 +0200774 proxy_keyserver = f"--keyserver-options http-proxy={http_proxy}"
775
Patrick Williams02871c92021-02-01 20:57:19 -0600776 proxy_args.extend(
777 [
778 "--build-arg",
779 f"http_proxy={http_proxy}",
780 "--build-arg",
Lei YUd461cd62021-02-18 14:25:49 +0800781 f"https_proxy={http_proxy}",
Patrick Williams02871c92021-02-01 20:57:19 -0600782 ]
783 )
784
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600785# Create base Dockerfile.
Patrick Williamsa18d9c52021-02-05 09:52:26 -0600786dockerfile_base = f"""
Andrew Geisslerfe2768c2024-10-02 10:10:29 -0400787FROM {docker_reg}/{distro}
Patrick Williams02871c92021-02-01 20:57:19 -0600788
789{mirror}
790
791ENV DEBIAN_FRONTEND noninteractive
792
Patrick Williams8949d3c2022-04-27 16:41:27 -0500793ENV PYTHONPATH "/usr/local/lib/python3.10/site-packages/"
Patrick Williams02871c92021-02-01 20:57:19 -0600794
Patrick Williamsbb16ac12021-04-12 12:23:51 -0500795# Sometimes the ubuntu key expires and we need a way to force an execution
796# of the apt-get commands for the dbgsym-keyring. When this happens we see
797# an error like: "Release: The following signatures were invalid:"
798# Insert a bogus echo that we can change here when we get this error to force
799# the update.
800RUN echo "ubuntu keyserver rev as of 2021-04-21"
801
Patrick Williams02871c92021-02-01 20:57:19 -0600802# We need the keys to be imported for dbgsym repos
803# New releases have a package, older ones fall back to manual fetching
804# https://wiki.ubuntu.com/Debug%20Symbol%20Packages
Jagpal Singh Gill575b5e42023-04-14 15:52:10 -0700805# Known issue with gpg to get keys via proxy -
806# https://bugs.launchpad.net/ubuntu/+source/gnupg2/+bug/1788190, hence using
807# curl to get keys.
Patrick Williams50837432021-02-06 12:24:05 -0600808RUN apt-get update && apt-get dist-upgrade -yy && \
Jian Zhang938d3032023-07-05 13:35:35 +0800809 ( apt-get install -yy gpgv ubuntu-dbgsym-keyring || \
Jagpal Singh Gill575b5e42023-04-14 15:52:10 -0700810 ( apt-get install -yy dirmngr curl && \
811 curl -sSL \
812 'https://keyserver.ubuntu.com/pks/lookup?op=get&search=0xF2EDC64DC5AEE1F6B9C621F0C8CAB6595FDFF622' \
813 | apt-key add - ))
Patrick Williams02871c92021-02-01 20:57:19 -0600814
815# Parse the current repo list into a debug repo list
Patrick Williamse08ffba2022-12-05 10:33:46 -0600816RUN sed -n '/^deb /s,^deb [^ ]* ,deb http://ddebs.ubuntu.com ,p' \
817 /etc/apt/sources.list >/etc/apt/sources.list.d/debug.list
Patrick Williams02871c92021-02-01 20:57:19 -0600818
819# Remove non-existent debug repos
Patrick Williams41d86212022-11-25 18:28:43 -0600820RUN sed -i '/-\\(backports\\|security\\) /d' /etc/apt/sources.list.d/debug.list
Patrick Williams02871c92021-02-01 20:57:19 -0600821
822RUN cat /etc/apt/sources.list.d/debug.list
823
824RUN apt-get update && apt-get dist-upgrade -yy && apt-get install -yy \
Andrew Jeffery58f19152023-05-22 16:41:32 +0930825 abi-compliance-checker \
Andrew Jeffery8b112062023-05-22 20:49:11 +0930826 abi-dumper \
Patrick Williams02871c92021-02-01 20:57:19 -0600827 autoconf \
828 autoconf-archive \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600829 bison \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600830 cmake \
831 curl \
832 dbus \
833 device-tree-compiler \
834 flex \
Andrew Jefferydbce9762024-12-06 11:12:19 +1030835 g++-14 \
836 gcc-14 \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600837 git \
Patrick Williamsb4eec872024-10-04 10:49:50 -0400838 glib-2.0 \
Patrick Williams6968e832024-08-16 17:43:24 -0400839 gnupg \
Patrick Williams02871c92021-02-01 20:57:19 -0600840 iproute2 \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600841 iputils-ping \
Manojkiran Eda524a3312023-04-05 15:37:47 +0530842 libaudit-dev \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600843 libc6-dbg \
844 libc6-dev \
Patrick Williamsc7bc4d12024-10-04 11:22:02 -0400845 libcjson-dev \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600846 libconfig++-dev \
847 libcryptsetup-dev \
Anirban Banerjeea7a30552024-12-20 19:12:42 -0800848 libcurl4-openssl-dev \
Andrew Geissleraf49ed52022-12-14 11:41:35 -0600849 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 Williams759c0092024-12-18 14:25:37 -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 \
Ewelina Walkuszfb6653c2024-07-15 16:01:27 +0200945 meson==1.5.1 \
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)