blob: 4d5fb1b31ac426f82adac27e07041d97ea98e571 [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.
20# http_proxy The HTTP address of the proxy server to connect to.
21# Default: "", proxy is not setup if this is not set
22
23import os
24import sys
Patrick Williamsb16f3e22021-02-06 08:16:47 -060025import threading
Patrick Williamsa18d9c52021-02-05 09:52:26 -060026from datetime import date
27from hashlib import sha256
Patrick Williamsee3c9ee2021-02-12 20:56:01 -060028from sh import docker, git, nproc, uname # type: ignore
29from typing import Any, Callable, Dict, Iterable, Optional
Patrick Williams02871c92021-02-01 20:57:19 -060030
Patrick Williamsee3c9ee2021-02-12 20:56:01 -060031try:
32 # Python before 3.8 doesn't have TypedDict, so reroute to standard 'dict'.
33 from typing import TypedDict
34except:
35
36 class TypedDict(dict): # type: ignore
37 # We need to do this to eat the 'total' argument.
38 def __init_subclass__(cls, **kwargs):
39 super().__init_subclass__()
40
41
42# Declare some variables used in package definitions.
Patrick Williamsaae36d12021-02-04 16:30:04 -060043prefix = "/usr/local"
Patrick Williams02871c92021-02-01 20:57:19 -060044proc_count = nproc().strip()
Patrick Williams02871c92021-02-01 20:57:19 -060045
Patrick Williamsee3c9ee2021-02-12 20:56:01 -060046
47class PackageDef(TypedDict, total=False):
48 """ Package Definition for packages dictionary. """
49
50 # rev [optional]: Revision of package to use.
51 rev: str
52 # url [optional]: lambda function to create URL: (package, rev) -> url.
53 url: Callable[[str, str], str]
54 # depends [optional]: List of package dependencies.
55 depends: Iterable[str]
56 # build_type [required]: Build type used for package.
57 # Currently supported: autoconf, cmake, custom, make, meson
58 build_type: str
59 # build_steps [optional]: Steps to run for 'custom' build_type.
60 build_steps: Iterable[str]
61 # config_flags [optional]: List of options to pass configuration tool.
62 config_flags: Iterable[str]
63 # config_env [optional]: List of environment variables to set for config.
64 config_env: Iterable[str]
65 # custom_post_dl [optional]: List of steps to run after download, but
66 # before config / build / install.
67 custom_post_dl: Iterable[str]
Patrick Williams6bce2ca2021-02-12 21:13:37 -060068 # custom_post_install [optional]: List of steps to run after install.
69 custom_post_install: Iterable[str]
Patrick Williamsee3c9ee2021-02-12 20:56:01 -060070
71 # __tag [private]: Generated Docker tag name for package stage.
72 __tag: str
73 # __package [private]: Package object associated with this package.
74 __package: Any # Type is Package, but not defined yet.
75
Patrick Williams02871c92021-02-01 20:57:19 -060076
Patrick Williams72043242021-02-02 10:31:45 -060077# Packages to include in image.
78packages = {
Patrick Williams9a85a042021-12-14 12:55:22 -060079 # Install OpenSSL 3.x.
80 # Generally we want to rely on the version of OpenSSL from the OS, but v3.x
81 # was a major API change. It is included in Yocto but not Ubuntu until
82 # 22.04. Install it manually so that our CI can target the OpenSSL 3.x
83 # APIs.
84 "openssl/openssl": PackageDef(
85 rev="openssl-3.0.1",
86 build_type="custom",
87 build_steps=[
88 f"./Configure --prefix={prefix} --libdir=lib",
89 f"make -j{proc_count}",
90 f"make -j{proc_count} install"
91 ],
92 ),
Patrick Williamsee3c9ee2021-02-12 20:56:01 -060093 "boost": PackageDef(
Ed Tanousef7bca42022-02-04 09:13:20 -080094 rev="1.78.0",
Patrick Williamsee3c9ee2021-02-12 20:56:01 -060095 url=(
Patrick Williams5f2549e2021-04-12 12:05:10 -050096 lambda pkg, rev: f"https://downloads.yoctoproject.org/mirror/sources/{pkg}_{rev.replace('.', '_')}.tar.bz2"
Patrick Williams2abc4a42021-02-03 06:11:40 -060097 ),
Patrick Williamsee3c9ee2021-02-12 20:56:01 -060098 build_type="custom",
99 build_steps=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600100 f"./bootstrap.sh --prefix={prefix} --with-libraries=context,coroutine",
101 "./b2",
102 f"./b2 install --prefix={prefix}",
103 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600104 ),
105 "USCiLab/cereal": PackageDef(
Patrick Williams3f8b5292021-04-30 10:30:05 -0500106 rev="3e4d1b84cab4891368d2179a61a7ba06a5693e7f",
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600107 build_type="custom",
108 build_steps=[f"cp -a include/cereal/ {prefix}/include/"],
109 ),
110 "catchorg/Catch2": PackageDef(
William A. Kennington III96b43452021-05-15 03:35:12 -0700111 rev="v2.13.6",
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600112 build_type="cmake",
113 config_flags=["-DBUILD_TESTING=OFF", "-DCATCH_INSTALL_DOCS=OFF"],
114 ),
115 "CLIUtils/CLI11": PackageDef(
116 rev="v1.9.1",
117 build_type="cmake",
118 config_flags=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600119 "-DBUILD_TESTING=OFF",
120 "-DCLI11_BUILD_DOCS=OFF",
121 "-DCLI11_BUILD_EXAMPLES=OFF",
122 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600123 ),
124 "fmtlib/fmt": PackageDef(
Willy Tu63075012022-02-08 11:20:25 -0800125 rev="8.1.1",
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600126 build_type="cmake",
127 config_flags=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600128 "-DFMT_DOC=OFF",
129 "-DFMT_TEST=OFF",
130 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600131 ),
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600132 "Naios/function2": PackageDef(
William A. Kennington III96b43452021-05-15 03:35:12 -0700133 rev="4.1.0",
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600134 build_type="custom",
135 build_steps=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600136 f"mkdir {prefix}/include/function2",
137 f"cp include/function2/function2.hpp {prefix}/include/function2/",
138 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600139 ),
Michael Shen5202d8e2022-03-02 21:50:09 +0800140 # Release 2021-06-12
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600141 "google/googletest": PackageDef(
Michael Shen5202d8e2022-03-02 21:50:09 +0800142 rev="release-1.11.0",
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600143 build_type="cmake",
William A. Kennington III4dd32c02021-05-28 01:58:13 -0700144 config_env=["CXXFLAGS=-std=c++20"],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600145 config_flags=["-DTHREADS_PREFER_PTHREAD_FLAG=ON"],
146 ),
Patrick Williams02871c92021-02-01 20:57:19 -0600147 # Release 2020-08-06
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600148 "nlohmann/json": PackageDef(
Ed Tanous7d1b2a12021-11-03 09:13:57 -0700149 rev="v3.10.4",
Patrick Williams6bce2ca2021-02-12 21:13:37 -0600150 build_type="cmake",
151 config_flags=["-DJSON_BuildTests=OFF"],
152 custom_post_install=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600153 f"ln -s {prefix}/include/nlohmann/json.hpp {prefix}/include/json.hpp",
154 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600155 ),
Patrick Williams02871c92021-02-01 20:57:19 -0600156 # Snapshot from 2019-05-24
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600157 "linux-test-project/lcov": PackageDef(
158 rev="v1.15",
159 build_type="make",
160 ),
Patrick Williams0eedeed2021-02-06 19:06:09 -0600161 # dev-5.8 2021-01-11
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600162 "openbmc/linux": PackageDef(
163 rev="3cc95ae40716e56f81b69615781f54c78079042d",
164 build_type="custom",
165 build_steps=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600166 f"make -j{proc_count} defconfig",
167 f"make INSTALL_HDR_PATH={prefix} headers_install",
168 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600169 ),
Patrick Williams0eedeed2021-02-06 19:06:09 -0600170 # Snapshot from 2020-06-13
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600171 "LibVNC/libvncserver": PackageDef(
172 rev="LibVNCServer-0.9.13",
173 build_type="cmake",
174 ),
175 "martinmoene/span-lite": PackageDef(
William A. Kennington III96b43452021-05-15 03:35:12 -0700176 rev="v0.9.2",
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600177 build_type="cmake",
178 config_flags=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600179 "-DSPAN_LITE_OPT_BUILD_TESTS=OFF",
180 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600181 ),
Patrick Williams0eedeed2021-02-06 19:06:09 -0600182 # version from meta-openembedded/meta-oe/recipes-support/libtinyxml2/libtinyxml2_8.0.0.bb
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600183 "leethomason/tinyxml2": PackageDef(
184 rev="8.0.0",
185 build_type="cmake",
186 ),
Patrick Williams02871c92021-02-01 20:57:19 -0600187 # version from /meta-openembedded/meta-oe/recipes-devtools/boost-url/boost-url_git.bb
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600188 "CPPAlliance/url": PackageDef(
Ed Tanousab640cd2022-02-03 16:33:27 -0800189 rev="d740a92d38e3a8f4d5b2153f53b82f1c98e312ab",
Ed Tanouseed466e2021-09-20 10:04:55 -0700190 build_type="custom",
191 build_steps=[f"cp -a include/** {prefix}/include/"],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600192 ),
Patrick Williams68992892021-10-06 16:25:12 -0500193 # version from meta-openembedded/meta-oe/dynamic-layers/networking-layer/recipes-devools/valijson/valijson_0.6.bb
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600194 "tristanpenman/valijson": PackageDef(
Patrick Williams68992892021-10-06 16:25:12 -0500195 rev="v0.6",
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600196 build_type="cmake",
197 config_flags=[
Patrick Williams0eedeed2021-02-06 19:06:09 -0600198 "-Dvalijson_BUILD_TESTS=0",
199 "-Dvalijson_INSTALL_HEADERS=1",
Patrick Williamsaae36d12021-02-04 16:30:04 -0600200 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600201 ),
Patrick Williams02871c92021-02-01 20:57:19 -0600202 # version from meta-openembedded/meta-oe/recipes-devtools/nlohmann-fifo/nlohmann-fifo_git.bb
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600203 "nlohmann/fifo_map": PackageDef(
204 rev="0dfbf5dacbb15a32c43f912a7e66a54aae39d0f9",
205 build_type="custom",
206 build_steps=[f"cp src/fifo_map.hpp {prefix}/include/"],
207 ),
Patrick Williams51224162021-12-08 11:09:24 -0600208 # version from meta-openembedded/meta-oe/recipes-devtools/unifex/unifex_git.bb
209 "facebookexperimental/libunifex": PackageDef(
210 rev="9df21c58d34ce8a1cd3b15c3a7347495e29417a0",
211 build_type="cmake",
212 config_flags=[
213 "-DBUILD_SHARED_LIBS=ON",
214 "-DBUILD_TESTING=OFF",
215 "-DCMAKE_CXX_STANDARD=20",
216 "-DUNIFEX_BUILD_EXAMPLES=OFF",
217 ],
218 ),
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600219 "open-power/pdbg": PackageDef(build_type="autoconf"),
220 "openbmc/gpioplus": PackageDef(
221 depends=["openbmc/stdplus"],
222 build_type="meson",
223 config_flags=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600224 "-Dexamples=false",
225 "-Dtests=disabled",
226 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600227 ),
228 "openbmc/phosphor-dbus-interfaces": PackageDef(
229 depends=["openbmc/sdbusplus"],
230 build_type="meson",
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600231 ),
232 "openbmc/phosphor-logging": PackageDef(
233 depends=[
Patrick Williams83394612021-02-03 07:12:50 -0600234 "USCiLab/cereal",
235 "nlohmann/fifo_map",
236 "openbmc/phosphor-dbus-interfaces",
237 "openbmc/sdbusplus",
238 "openbmc/sdeventplus",
Patrick Williamsaae36d12021-02-04 16:30:04 -0600239 ],
Patrick Williamsf79ce4c2021-04-30 16:00:49 -0500240 build_type="meson",
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600241 config_flags=[
Patrick Williamsf79ce4c2021-04-30 16:00:49 -0500242 f"-Dyaml_dir={prefix}/share/phosphor-dbus-yaml/yaml",
Patrick Williamsaae36d12021-02-04 16:30:04 -0600243 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600244 ),
245 "openbmc/phosphor-objmgr": PackageDef(
246 depends=[
Patrick Williams83394612021-02-03 07:12:50 -0600247 "boost",
248 "leethomason/tinyxml2",
249 "openbmc/phosphor-logging",
250 "openbmc/sdbusplus",
Patrick Williamsaae36d12021-02-04 16:30:04 -0600251 ],
Brad Bishop1197e352021-08-03 19:25:46 -0400252 build_type="meson",
253 config_flags=[
254 "-Dtests=disabled",
255 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600256 ),
257 "openbmc/pldm": PackageDef(
258 depends=[
Patrick Williams83394612021-02-03 07:12:50 -0600259 "CLIUtils/CLI11",
260 "boost",
261 "nlohmann/json",
262 "openbmc/phosphor-dbus-interfaces",
263 "openbmc/phosphor-logging",
264 "openbmc/sdbusplus",
265 "openbmc/sdeventplus",
Patrick Williamsaae36d12021-02-04 16:30:04 -0600266 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600267 build_type="meson",
268 config_flags=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600269 "-Dlibpldm-only=enabled",
270 "-Doem-ibm=enabled",
271 "-Dtests=disabled",
272 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600273 ),
274 "openbmc/sdbusplus": PackageDef(
Patrick Williams51224162021-12-08 11:09:24 -0600275 depends=[
276 "facebookexperimental/libunifex",
277 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600278 build_type="meson",
279 custom_post_dl=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600280 "cd tools",
281 f"./setup.py install --root=/ --prefix={prefix}",
282 "cd ..",
283 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600284 config_flags=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600285 "-Dexamples=disabled",
286 "-Dtests=disabled",
287 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600288 ),
289 "openbmc/sdeventplus": PackageDef(
290 depends=["Naios/function2", "openbmc/stdplus"],
291 build_type="meson",
292 config_flags=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600293 "-Dexamples=false",
294 "-Dtests=disabled",
295 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600296 ),
297 "openbmc/stdplus": PackageDef(
298 depends=["fmtlib/fmt", "martinmoene/span-lite"],
299 build_type="meson",
300 config_flags=[
Patrick Williamsaae36d12021-02-04 16:30:04 -0600301 "-Dexamples=false",
302 "-Dtests=disabled",
303 ],
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600304 ),
305} # type: Dict[str, PackageDef]
Patrick Williams02871c92021-02-01 20:57:19 -0600306
307# Define common flags used for builds
Patrick Williams02871c92021-02-01 20:57:19 -0600308configure_flags = " ".join(
309 [
310 f"--prefix={prefix}",
311 ]
312)
313cmake_flags = " ".join(
314 [
Patrick Williams02871c92021-02-01 20:57:19 -0600315 "-DBUILD_SHARED_LIBS=ON",
Patrick Williams0f2086b2021-02-05 06:49:49 -0600316 "-DCMAKE_BUILD_TYPE=RelWithDebInfo",
Patrick Williams02871c92021-02-01 20:57:19 -0600317 f"-DCMAKE_INSTALL_PREFIX:PATH={prefix}",
Patrick Williams0f2086b2021-02-05 06:49:49 -0600318 "-GNinja",
319 "-DCMAKE_MAKE_PROGRAM=ninja",
Patrick Williams02871c92021-02-01 20:57:19 -0600320 ]
321)
322meson_flags = " ".join(
323 [
324 "--wrap-mode=nodownload",
325 f"-Dprefix={prefix}",
326 ]
327)
328
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600329
330class Package(threading.Thread):
331 """Class used to build the Docker stages for each package.
332
333 Generally, this class should not be instantiated directly but through
334 Package.generate_all().
335 """
336
337 # Copy the packages dictionary.
338 packages = packages.copy()
339
340 # Lock used for thread-safety.
341 lock = threading.Lock()
342
343 def __init__(self, pkg: str):
344 """ pkg - The name of this package (ex. foo/bar ) """
345 super(Package, self).__init__()
346
347 self.package = pkg
348 self.exception = None # type: Optional[Exception]
349
350 # Reference to this package's
351 self.pkg_def = Package.packages[pkg]
352 self.pkg_def["__package"] = self
353
354 def run(self) -> None:
355 """ Thread 'run' function. Builds the Docker stage. """
356
357 # In case this package has no rev, fetch it from Github.
358 self._update_rev()
359
360 # Find all the Package objects that this package depends on.
361 # This section is locked because we are looking into another
362 # package's PackageDef dict, which could be being modified.
363 Package.lock.acquire()
364 deps: Iterable[Package] = [
365 Package.packages[deppkg]["__package"]
366 for deppkg in self.pkg_def.get("depends", [])
367 ]
368 Package.lock.release()
369
370 # Wait until all the depends finish building. We need them complete
371 # for the "COPY" commands.
372 for deppkg in deps:
373 deppkg.join()
374
375 # Generate this package's Dockerfile.
376 dockerfile = f"""
377FROM {docker_base_img_name}
378{self._df_copycmds()}
379{self._df_build()}
380"""
381
382 # Generate the resulting tag name and save it to the PackageDef.
383 # This section is locked because we are modifying the PackageDef,
384 # which can be accessed by other threads.
385 Package.lock.acquire()
386 tag = Docker.tagname(self._stagename(), dockerfile)
387 self.pkg_def["__tag"] = tag
388 Package.lock.release()
389
390 # Do the build / save any exceptions.
391 try:
392 Docker.build(self.package, tag, dockerfile)
393 except Exception as e:
394 self.exception = e
395
396 @classmethod
397 def generate_all(cls) -> None:
398 """Ensure a Docker stage is created for all defined packages.
399
400 These are done in parallel but with appropriate blocking per
401 package 'depends' specifications.
402 """
403
404 # Create a Package for each defined package.
405 pkg_threads = [Package(p) for p in cls.packages.keys()]
406
407 # Start building them all.
Patrick Williams6dbd7802021-02-20 08:34:10 -0600408 # This section is locked because threads depend on each other,
409 # based on the packages, and they cannot 'join' on a thread
410 # which is not yet started. Adding a lock here allows all the
411 # threads to start before they 'join' their dependencies.
412 Package.lock.acquire()
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600413 for t in pkg_threads:
414 t.start()
Patrick Williams6dbd7802021-02-20 08:34:10 -0600415 Package.lock.release()
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600416
417 # Wait for completion.
418 for t in pkg_threads:
419 t.join()
420 # Check if the thread saved off its own exception.
421 if t.exception:
422 print(f"Package {t.package} failed!", file=sys.stderr)
423 raise t.exception
424
425 @staticmethod
426 def df_all_copycmds() -> str:
427 """Formulate the Dockerfile snippet necessary to copy all packages
428 into the final image.
429 """
430 return Package.df_copycmds_set(Package.packages.keys())
431
432 @classmethod
433 def depcache(cls) -> str:
434 """Create the contents of the '/tmp/depcache'.
435 This file is a comma-separated list of "<pkg>:<rev>".
436 """
437
438 # This needs to be sorted for consistency.
439 depcache = ""
440 for pkg in sorted(cls.packages.keys()):
441 depcache += "%s:%s," % (pkg, cls.packages[pkg]["rev"])
442 return depcache
443
444 def _update_rev(self) -> None:
445 """ Look up the HEAD for missing a static rev. """
446
447 if "rev" in self.pkg_def:
448 return
449
Patrick Williams65b21fb2021-02-12 21:21:14 -0600450 # Check if Jenkins/Gerrit gave us a revision and use it.
451 if gerrit_project == self.package and gerrit_rev:
452 print(
453 f"Found Gerrit revision for {self.package}: {gerrit_rev}",
454 file=sys.stderr,
455 )
456 self.pkg_def["rev"] = gerrit_rev
457 return
458
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600459 # Ask Github for all the branches.
460 lookup = git("ls-remote", "--heads", f"https://github.com/{self.package}")
461
462 # Find the branch matching {branch} (or fallback to master).
463 # This section is locked because we are modifying the PackageDef.
464 Package.lock.acquire()
465 for line in lookup.split("\n"):
466 if f"refs/heads/{branch}" in line:
467 self.pkg_def["rev"] = line.split()[0]
468 elif f"refs/heads/master" in line and "rev" not in self.pkg_def:
469 self.pkg_def["rev"] = line.split()[0]
470 Package.lock.release()
471
472 def _stagename(self) -> str:
473 """ Create a name for the Docker stage associated with this pkg. """
474 return self.package.replace("/", "-").lower()
475
476 def _url(self) -> str:
477 """ Get the URL for this package. """
478 rev = self.pkg_def["rev"]
479
480 # If the lambda exists, call it.
481 if "url" in self.pkg_def:
482 return self.pkg_def["url"](self.package, rev)
483
484 # Default to the github archive URL.
485 return f"https://github.com/{self.package}/archive/{rev}.tar.gz"
486
487 def _cmd_download(self) -> str:
488 """Formulate the command necessary to download and unpack to source."""
489
490 url = self._url()
491 if ".tar." not in url:
492 raise NotImplementedError(
493 f"Unhandled download type for {self.package}: {url}"
494 )
495
496 cmd = f"curl -L {url} | tar -x"
497
498 if url.endswith(".bz2"):
499 cmd += "j"
500 elif url.endswith(".gz"):
501 cmd += "z"
502 else:
503 raise NotImplementedError(
504 f"Unknown tar flags needed for {self.package}: {url}"
505 )
506
507 return cmd
508
509 def _cmd_cd_srcdir(self) -> str:
510 """ Formulate the command necessary to 'cd' into the source dir. """
511 return f"cd {self.package.split('/')[-1]}*"
512
513 def _df_copycmds(self) -> str:
514 """ Formulate the dockerfile snippet necessary to COPY all depends. """
515
516 if "depends" not in self.pkg_def:
517 return ""
518 return Package.df_copycmds_set(self.pkg_def["depends"])
519
520 @staticmethod
521 def df_copycmds_set(pkgs: Iterable[str]) -> str:
522 """Formulate the Dockerfile snippet necessary to COPY a set of
523 packages into a Docker stage.
524 """
525
526 copy_cmds = ""
527
528 # Sort the packages for consistency.
529 for p in sorted(pkgs):
530 tag = Package.packages[p]["__tag"]
531 copy_cmds += f"COPY --from={tag} {prefix} {prefix}\n"
532 # Workaround for upstream docker bug and multiple COPY cmds
533 # https://github.com/moby/moby/issues/37965
534 copy_cmds += "RUN true\n"
535
536 return copy_cmds
537
538 def _df_build(self) -> str:
539 """Formulate the Dockerfile snippet necessary to download, build, and
540 install a package into a Docker stage.
541 """
542
543 # Download and extract source.
544 result = f"RUN {self._cmd_download()} && {self._cmd_cd_srcdir()} && "
545
546 # Handle 'custom_post_dl' commands.
547 custom_post_dl = self.pkg_def.get("custom_post_dl")
548 if custom_post_dl:
549 result += " && ".join(custom_post_dl) + " && "
550
551 # Build and install package based on 'build_type'.
552 build_type = self.pkg_def["build_type"]
553 if build_type == "autoconf":
554 result += self._cmd_build_autoconf()
555 elif build_type == "cmake":
556 result += self._cmd_build_cmake()
557 elif build_type == "custom":
558 result += self._cmd_build_custom()
559 elif build_type == "make":
560 result += self._cmd_build_make()
561 elif build_type == "meson":
562 result += self._cmd_build_meson()
563 else:
564 raise NotImplementedError(
565 f"Unhandled build type for {self.package}: {build_type}"
566 )
567
Patrick Williams6bce2ca2021-02-12 21:13:37 -0600568 # Handle 'custom_post_install' commands.
569 custom_post_install = self.pkg_def.get("custom_post_install")
570 if custom_post_install:
571 result += " && " + " && ".join(custom_post_install)
572
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600573 return result
574
575 def _cmd_build_autoconf(self) -> str:
576 options = " ".join(self.pkg_def.get("config_flags", []))
577 env = " ".join(self.pkg_def.get("config_env", []))
578 result = "./bootstrap.sh && "
579 result += f"{env} ./configure {configure_flags} {options} && "
580 result += f"make -j{proc_count} && make install"
581 return result
582
583 def _cmd_build_cmake(self) -> str:
584 options = " ".join(self.pkg_def.get("config_flags", []))
585 env = " ".join(self.pkg_def.get("config_env", []))
586 result = "mkdir builddir && cd builddir && "
587 result += f"{env} cmake {cmake_flags} {options} .. && "
588 result += "cmake --build . --target all && "
589 result += "cmake --build . --target install && "
590 result += "cd .."
591 return result
592
593 def _cmd_build_custom(self) -> str:
594 return " && ".join(self.pkg_def.get("build_steps", []))
595
596 def _cmd_build_make(self) -> str:
597 return f"make -j{proc_count} && make install"
598
599 def _cmd_build_meson(self) -> str:
600 options = " ".join(self.pkg_def.get("config_flags", []))
601 env = " ".join(self.pkg_def.get("config_env", []))
602 result = f"{env} meson builddir {meson_flags} {options} && "
603 result += "ninja -C builddir && ninja -C builddir install"
604 return result
605
606
607class Docker:
608 """Class to assist with Docker interactions. All methods are static."""
609
610 @staticmethod
611 def timestamp() -> str:
612 """ Generate a timestamp for today using the ISO week. """
613 today = date.today().isocalendar()
614 return f"{today[0]}-W{today[1]:02}"
615
616 @staticmethod
617 def tagname(pkgname: str, dockerfile: str) -> str:
618 """ Generate a tag name for a package using a hash of the Dockerfile. """
619 result = docker_image_name
620 if pkgname:
621 result += "-" + pkgname
622
623 result += ":" + Docker.timestamp()
624 result += "-" + sha256(dockerfile.encode()).hexdigest()[0:16]
625
626 return result
627
628 @staticmethod
629 def build(pkg: str, tag: str, dockerfile: str) -> None:
630 """Build a docker image using the Dockerfile and tagging it with 'tag'."""
631
632 # If we're not forcing builds, check if it already exists and skip.
633 if not force_build:
634 if docker.image.ls(tag, "--format", '"{{.Repository}}:{{.Tag}}"'):
635 print(f"Image {tag} already exists. Skipping.", file=sys.stderr)
636 return
637
638 # Build it.
639 # Capture the output of the 'docker build' command and send it to
640 # stderr (prefixed with the package name). This allows us to see
641 # progress but not polute stdout. Later on we output the final
642 # docker tag to stdout and we want to keep that pristine.
643 #
644 # Other unusual flags:
645 # --no-cache: Bypass the Docker cache if 'force_build'.
646 # --force-rm: Clean up Docker processes if they fail.
647 docker.build(
648 proxy_args,
649 "--network=host",
650 "--force-rm",
651 "--no-cache=true" if force_build else "--no-cache=false",
652 "-t",
653 tag,
654 "-",
655 _in=dockerfile,
656 _out=(
657 lambda line: print(
658 pkg + ":", line, end="", file=sys.stderr, flush=True
659 )
660 ),
661 )
662
663
664# Read a bunch of environment variables.
665docker_image_name = os.environ.get("DOCKER_IMAGE_NAME", "openbmc/ubuntu-unit-test")
666force_build = os.environ.get("FORCE_DOCKER_BUILD")
667is_automated_ci_build = os.environ.get("BUILD_URL", False)
Patrick Williams3b6bfe42021-10-22 14:01:25 -0500668distro = os.environ.get("DISTRO", "ubuntu:impish")
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600669branch = os.environ.get("BRANCH", "master")
670ubuntu_mirror = os.environ.get("UBUNTU_MIRROR")
671http_proxy = os.environ.get("http_proxy")
672
Patrick Williams65b21fb2021-02-12 21:21:14 -0600673gerrit_project = os.environ.get("GERRIT_PROJECT")
674gerrit_rev = os.environ.get("GERRIT_PATCHSET_REVISION")
675
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600676# Set up some common variables.
677username = os.environ.get("USER", "root")
678homedir = os.environ.get("HOME", "/root")
679gid = os.getgid()
680uid = os.getuid()
681
682# Determine the architecture for Docker.
683arch = uname("-m").strip()
684if arch == "ppc64le":
685 docker_base = "ppc64le/"
686elif arch == "x86_64":
687 docker_base = ""
Thang Q. Nguyen051b05b2021-12-10 08:30:35 +0000688elif arch == "aarch64":
Thang Q. Nguyenf98f1a82021-12-22 01:59:19 +0000689 docker_base = "arm64v8/"
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600690else:
691 print(
692 f"Unsupported system architecture({arch}) found for docker image",
693 file=sys.stderr,
694 )
695 sys.exit(1)
696
Patrick Williams02871c92021-02-01 20:57:19 -0600697# Special flags if setting up a deb mirror.
698mirror = ""
699if "ubuntu" in distro and ubuntu_mirror:
700 mirror = f"""
701RUN echo "deb {ubuntu_mirror} $(. /etc/os-release && echo $VERSION_CODENAME) main restricted universe multiverse" > /etc/apt/sources.list && \\
702 echo "deb {ubuntu_mirror} $(. /etc/os-release && echo $VERSION_CODENAME)-updates main restricted universe multiverse" >> /etc/apt/sources.list && \\
703 echo "deb {ubuntu_mirror} $(. /etc/os-release && echo $VERSION_CODENAME)-security main restricted universe multiverse" >> /etc/apt/sources.list && \\
704 echo "deb {ubuntu_mirror} $(. /etc/os-release && echo $VERSION_CODENAME)-proposed main restricted universe multiverse" >> /etc/apt/sources.list && \\
705 echo "deb {ubuntu_mirror} $(. /etc/os-release && echo $VERSION_CODENAME)-backports main restricted universe multiverse" >> /etc/apt/sources.list
706"""
707
708# Special flags for proxying.
709proxy_cmd = ""
Adrian Ambrożewicz34ec77e2021-06-02 10:23:38 +0200710proxy_keyserver = ""
Patrick Williams02871c92021-02-01 20:57:19 -0600711proxy_args = []
712if http_proxy:
713 proxy_cmd = f"""
714RUN echo "[http]" >> {homedir}/.gitconfig && \
715 echo "proxy = {http_proxy}" >> {homedir}/.gitconfig
716"""
Adrian Ambrożewicz34ec77e2021-06-02 10:23:38 +0200717 proxy_keyserver = f"--keyserver-options http-proxy={http_proxy}"
718
Patrick Williams02871c92021-02-01 20:57:19 -0600719 proxy_args.extend(
720 [
721 "--build-arg",
722 f"http_proxy={http_proxy}",
723 "--build-arg",
Lei YUd461cd62021-02-18 14:25:49 +0800724 f"https_proxy={http_proxy}",
Patrick Williams02871c92021-02-01 20:57:19 -0600725 ]
726 )
727
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600728# Create base Dockerfile.
Patrick Williamsa18d9c52021-02-05 09:52:26 -0600729dockerfile_base = f"""
730FROM {docker_base}{distro}
Patrick Williams02871c92021-02-01 20:57:19 -0600731
732{mirror}
733
734ENV DEBIAN_FRONTEND noninteractive
735
Andrew Geisslerabace2c2022-03-14 17:43:38 -0500736ENV PYTHONPATH "/usr/local/lib/python3.9/site-packages/"
Patrick Williams02871c92021-02-01 20:57:19 -0600737
Patrick Williamsbb16ac12021-04-12 12:23:51 -0500738# Sometimes the ubuntu key expires and we need a way to force an execution
739# of the apt-get commands for the dbgsym-keyring. When this happens we see
740# an error like: "Release: The following signatures were invalid:"
741# Insert a bogus echo that we can change here when we get this error to force
742# the update.
743RUN echo "ubuntu keyserver rev as of 2021-04-21"
744
Patrick Williams02871c92021-02-01 20:57:19 -0600745# We need the keys to be imported for dbgsym repos
746# New releases have a package, older ones fall back to manual fetching
747# https://wiki.ubuntu.com/Debug%20Symbol%20Packages
Patrick Williams50837432021-02-06 12:24:05 -0600748RUN apt-get update && apt-get dist-upgrade -yy && \
Patrick Williamsf79ce4c2021-04-30 16:00:49 -0500749 ( apt-get install gpgv ubuntu-dbgsym-keyring || \
Patrick Williams50837432021-02-06 12:24:05 -0600750 ( apt-get install -yy dirmngr && \
751 apt-key adv --keyserver keyserver.ubuntu.com \
Adrian Ambrożewicz34ec77e2021-06-02 10:23:38 +0200752 {proxy_keyserver} \
Patrick Williams50837432021-02-06 12:24:05 -0600753 --recv-keys F2EDC64DC5AEE1F6B9C621F0C8CAB6595FDFF622 ) )
Patrick Williams02871c92021-02-01 20:57:19 -0600754
755# Parse the current repo list into a debug repo list
756RUN sed -n '/^deb /s,^deb [^ ]* ,deb http://ddebs.ubuntu.com ,p' /etc/apt/sources.list >/etc/apt/sources.list.d/debug.list
757
758# Remove non-existent debug repos
759RUN sed -i '/-\(backports\|security\) /d' /etc/apt/sources.list.d/debug.list
760
761RUN cat /etc/apt/sources.list.d/debug.list
762
763RUN apt-get update && apt-get dist-upgrade -yy && apt-get install -yy \
William A. Kennington IIIb84d59d2021-05-15 03:23:58 -0700764 gcc-11 \
765 g++-11 \
Patrick Williams02871c92021-02-01 20:57:19 -0600766 libc6-dbg \
767 libc6-dev \
768 libtool \
769 bison \
770 libdbus-1-dev \
771 flex \
772 cmake \
773 python3 \
774 python3-dev\
775 python3-yaml \
776 python3-mako \
777 python3-pip \
778 python3-setuptools \
779 python3-git \
780 python3-socks \
781 pkg-config \
782 autoconf \
783 autoconf-archive \
784 libsystemd-dev \
785 systemd \
786 libssl-dev \
787 libevdev-dev \
Patrick Williams02871c92021-02-01 20:57:19 -0600788 libjpeg-dev \
789 libpng-dev \
790 ninja-build \
791 sudo \
792 curl \
793 git \
794 dbus \
795 iputils-ping \
Patrick Williamsf89c8502021-10-01 11:50:09 -0500796 clang-13 \
797 clang-format-13 \
798 clang-tidy-13 \
799 clang-tools-13 \
Patrick Williams02871c92021-02-01 20:57:19 -0600800 shellcheck \
801 npm \
802 iproute2 \
803 libnl-3-dev \
804 libnl-genl-3-dev \
805 libconfig++-dev \
806 libsnmp-dev \
807 valgrind \
808 valgrind-dbg \
809 libpam0g-dev \
810 xxd \
811 libi2c-dev \
812 wget \
813 libldap2-dev \
814 libprotobuf-dev \
William A. Kennington IIIdafe7522021-05-28 01:51:06 -0700815 liburing-dev \
816 liburing1-dbgsym \
Patrick Williams02871c92021-02-01 20:57:19 -0600817 libperlio-gzip-perl \
818 libjson-perl \
819 protobuf-compiler \
820 libgpiod-dev \
821 device-tree-compiler \
822 cppcheck \
823 libpciaccess-dev \
824 libmimetic-dev \
825 libxml2-utils \
Patrick Williams0eedeed2021-02-06 19:06:09 -0600826 libxml-simple-perl \
John Wedig9adf68d2021-11-16 14:00:39 -0800827 rsync \
828 libcryptsetup-dev
Patrick Williams02871c92021-02-01 20:57:19 -0600829
Manojkiran Eda87111bb2021-08-14 11:26:16 +0530830RUN npm install -g eslint@latest eslint-plugin-json@latest
831
William A. Kennington IIIb84d59d2021-05-15 03:23:58 -0700832RUN update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-11 11 \
833 --slave /usr/bin/g++ g++ /usr/bin/g++-11 \
834 --slave /usr/bin/gcov gcov /usr/bin/gcov-11 \
835 --slave /usr/bin/gcov-dump gcov-dump /usr/bin/gcov-dump-11 \
836 --slave /usr/bin/gcov-tool gcov-tool /usr/bin/gcov-tool-11
Patrick Williams02871c92021-02-01 20:57:19 -0600837
Patrick Williamsf89c8502021-10-01 11:50:09 -0500838RUN update-alternatives --install /usr/bin/clang clang /usr/bin/clang-13 1000 \
839 --slave /usr/bin/clang++ clang++ /usr/bin/clang++-13 \
840 --slave /usr/bin/clang-tidy clang-tidy /usr/bin/clang-tidy-13 \
841 --slave /usr/bin/clang-format clang-format /usr/bin/clang-format-13 \
842 --slave /usr/bin/run-clang-tidy run-clang-tidy.py /usr/bin/run-clang-tidy-13 \
843 --slave /usr/bin/scan-build scan-build /usr/bin/scan-build-13
Patrick Williams02871c92021-02-01 20:57:19 -0600844
Patrick Williams50837432021-02-06 12:24:05 -0600845"""
846
847if is_automated_ci_build:
848 dockerfile_base += f"""
849# Run an arbitrary command to polute the docker cache regularly force us
850# to re-run `apt-get update` daily.
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600851RUN echo {Docker.timestamp()}
Patrick Williams50837432021-02-06 12:24:05 -0600852RUN apt-get update && apt-get dist-upgrade -yy
853
854"""
855
856dockerfile_base += f"""
Patrick Williams02871c92021-02-01 20:57:19 -0600857RUN pip3 install inflection
858RUN pip3 install pycodestyle
859RUN pip3 install jsonschema
Patrick Williamsb3e88fb2021-10-01 11:50:26 -0500860RUN pip3 install meson==0.58.1
Patrick Williams02871c92021-02-01 20:57:19 -0600861RUN pip3 install protobuf
Manojkiran Edae6f120a2021-03-20 11:13:43 +0530862RUN pip3 install codespell
Ed Tanousca8c4a82022-02-08 13:58:22 -0800863RUN pip3 install requests
Patrick Williamsa18d9c52021-02-05 09:52:26 -0600864"""
Patrick Williams02871c92021-02-01 20:57:19 -0600865
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600866# Build the base and stage docker images.
867docker_base_img_name = Docker.tagname("base", dockerfile_base)
868Docker.build("base", docker_base_img_name, dockerfile_base)
869Package.generate_all()
Patrick Williams02871c92021-02-01 20:57:19 -0600870
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600871# Create the final Dockerfile.
Patrick Williamsa18d9c52021-02-05 09:52:26 -0600872dockerfile = f"""
Patrick Williams02871c92021-02-01 20:57:19 -0600873# Build the final output image
Patrick Williamsa18d9c52021-02-05 09:52:26 -0600874FROM {docker_base_img_name}
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600875{Package.df_all_copycmds()}
Patrick Williams02871c92021-02-01 20:57:19 -0600876
877# Some of our infrastructure still relies on the presence of this file
878# even though it is no longer needed to rebuild the docker environment
879# NOTE: The file is sorted to ensure the ordering is stable.
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600880RUN echo '{Package.depcache()}' > /tmp/depcache
Patrick Williams02871c92021-02-01 20:57:19 -0600881
882# Final configuration for the workspace
883RUN grep -q {gid} /etc/group || groupadd -g {gid} {username}
884RUN mkdir -p "{os.path.dirname(homedir)}"
885RUN grep -q {uid} /etc/passwd || useradd -d {homedir} -m -u {uid} -g {gid} {username}
886RUN sed -i '1iDefaults umask=000' /etc/sudoers
887RUN echo "{username} ALL=(ALL) NOPASSWD: ALL" >>/etc/sudoers
888
Andrew Geissler305a9a52021-04-07 11:08:40 -0500889# Ensure user has ability to write to /usr/local for different tool
890# and data installs
Andrew Geissler7bb00b12021-05-10 15:12:08 -0500891RUN chown -R {username}:{username} /usr/local/share
Andrew Geissler305a9a52021-04-07 11:08:40 -0500892
Patrick Williams02871c92021-02-01 20:57:19 -0600893{proxy_cmd}
894
895RUN /bin/bash
896"""
897
Patrick Williamsa18d9c52021-02-05 09:52:26 -0600898# Do the final docker build
Patrick Williamsee3c9ee2021-02-12 20:56:01 -0600899docker_final_img_name = Docker.tagname(None, dockerfile)
900Docker.build("final", docker_final_img_name, dockerfile)
901
Patrick Williams00536fb2021-02-11 14:28:49 -0600902# Print the tag of the final image.
903print(docker_final_img_name)