blob: 5042c11d8ebc4da01f4d414e247155e58821c4e9 [file] [log] [blame]
Brad Bishop15ae2502019-06-18 21:44:24 -04001#
2# SPDX-License-Identifier: MIT
3#
Andrew Geissler82c905d2020-04-13 13:39:40 -05004# Copyright 2019-2020 by Garmin Ltd. or its subsidiaries
Brad Bishop15ae2502019-06-18 21:44:24 -04005
6from oeqa.selftest.case import OESelftestTestCase
7from oeqa.utils.commands import runCmd, bitbake, get_bb_var, get_bb_vars
Brad Bishop1d80a2e2019-11-15 16:35:03 -05008import bb.utils
Brad Bishop15ae2502019-06-18 21:44:24 -04009import functools
10import multiprocessing
11import textwrap
Brad Bishop1d80a2e2019-11-15 16:35:03 -050012import tempfile
13import shutil
14import stat
15import os
Andrew Geissler82c905d2020-04-13 13:39:40 -050016import datetime
Brad Bishop15ae2502019-06-18 21:44:24 -040017
Andrew Geisslerd1e89492021-02-12 15:35:20 -060018exclude_packages = [
Andrew Geisslerd1e89492021-02-12 15:35:20 -060019 ]
20
21def is_excluded(package):
22 package_name = os.path.basename(package)
23 for i in exclude_packages:
24 if package_name.startswith(i):
Andrew Geissler9b4d8b02021-02-19 12:26:16 -060025 return i
26 return None
Andrew Geisslerd1e89492021-02-12 15:35:20 -060027
Brad Bishop15ae2502019-06-18 21:44:24 -040028MISSING = 'MISSING'
29DIFFERENT = 'DIFFERENT'
30SAME = 'SAME'
31
32@functools.total_ordering
33class CompareResult(object):
34 def __init__(self):
35 self.reference = None
36 self.test = None
37 self.status = 'UNKNOWN'
38
39 def __eq__(self, other):
40 return (self.status, self.test) == (other.status, other.test)
41
42 def __lt__(self, other):
43 return (self.status, self.test) < (other.status, other.test)
44
45class PackageCompareResults(object):
46 def __init__(self):
47 self.total = []
48 self.missing = []
49 self.different = []
Andrew Geisslerd1e89492021-02-12 15:35:20 -060050 self.different_excluded = []
Brad Bishop15ae2502019-06-18 21:44:24 -040051 self.same = []
Andrew Geissler9b4d8b02021-02-19 12:26:16 -060052 self.active_exclusions = set()
Brad Bishop15ae2502019-06-18 21:44:24 -040053
54 def add_result(self, r):
55 self.total.append(r)
56 if r.status == MISSING:
57 self.missing.append(r)
58 elif r.status == DIFFERENT:
Andrew Geissler9b4d8b02021-02-19 12:26:16 -060059 exclusion = is_excluded(r.reference)
60 if exclusion:
Andrew Geisslerd1e89492021-02-12 15:35:20 -060061 self.different_excluded.append(r)
Andrew Geissler9b4d8b02021-02-19 12:26:16 -060062 self.active_exclusions.add(exclusion)
Andrew Geisslerd1e89492021-02-12 15:35:20 -060063 else:
64 self.different.append(r)
Brad Bishop15ae2502019-06-18 21:44:24 -040065 else:
66 self.same.append(r)
67
68 def sort(self):
69 self.total.sort()
70 self.missing.sort()
71 self.different.sort()
Andrew Geisslerd1e89492021-02-12 15:35:20 -060072 self.different_excluded.sort()
Brad Bishop15ae2502019-06-18 21:44:24 -040073 self.same.sort()
74
75 def __str__(self):
Andrew Geissler9b4d8b02021-02-19 12:26:16 -060076 return 'same=%i different=%i different_excluded=%i missing=%i total=%i\nunused_exclusions=%s' % (len(self.same), len(self.different), len(self.different_excluded), len(self.missing), len(self.total), self.unused_exclusions())
77
78 def unused_exclusions(self):
79 return sorted(set(exclude_packages) - self.active_exclusions)
Brad Bishop15ae2502019-06-18 21:44:24 -040080
81def compare_file(reference, test, diffutils_sysroot):
82 result = CompareResult()
83 result.reference = reference
84 result.test = test
85
86 if not os.path.exists(reference):
87 result.status = MISSING
88 return result
89
Andrew Geissler90fd73c2021-03-05 15:25:55 -060090 r = runCmd(['cmp', '--quiet', reference, test], native_sysroot=diffutils_sysroot, ignore_status=True, sync=False)
Brad Bishop15ae2502019-06-18 21:44:24 -040091
92 if r.status:
93 result.status = DIFFERENT
94 return result
95
96 result.status = SAME
97 return result
98
Andrew Geissler595f6302022-01-24 19:11:47 +000099def run_diffoscope(a_dir, b_dir, html_dir, max_report_size=0, **kwargs):
100 return runCmd(['diffoscope', '--no-default-limits', '--max-report-size', str(max_report_size),
101 '--exclude-directory-metadata', 'yes', '--html-dir', html_dir, a_dir, b_dir],
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500102 **kwargs)
103
104class DiffoscopeTests(OESelftestTestCase):
105 diffoscope_test_files = os.path.join(os.path.dirname(os.path.abspath(__file__)), "diffoscope")
106
107 def test_diffoscope(self):
108 bitbake("diffoscope-native -c addto_recipe_sysroot")
109 diffoscope_sysroot = get_bb_var("RECIPE_SYSROOT_NATIVE", "diffoscope-native")
110
111 # Check that diffoscope doesn't return an error when the files compare
112 # the same (a general check that diffoscope is working)
113 with tempfile.TemporaryDirectory() as tmpdir:
114 run_diffoscope('A', 'A', tmpdir,
115 native_sysroot=diffoscope_sysroot, cwd=self.diffoscope_test_files)
116
117 # Check that diffoscope generates an index.html file when the files are
118 # different
119 with tempfile.TemporaryDirectory() as tmpdir:
120 r = run_diffoscope('A', 'B', tmpdir,
121 native_sysroot=diffoscope_sysroot, ignore_status=True, cwd=self.diffoscope_test_files)
122
123 self.assertNotEqual(r.status, 0, msg="diffoscope was successful when an error was expected")
124 self.assertTrue(os.path.exists(os.path.join(tmpdir, 'index.html')), "HTML index not found!")
125
Brad Bishop15ae2502019-06-18 21:44:24 -0400126class ReproducibleTests(OESelftestTestCase):
Andrew Geissler90fd73c2021-03-05 15:25:55 -0600127 # Test the reproducibility of whatever is built between sstate_targets and targets
128
129 package_classes = ['deb', 'ipk', 'rpm']
130
Andrew Geissler595f6302022-01-24 19:11:47 +0000131 # Maximum report size, in bytes
132 max_report_size = 250 * 1024 * 1024
133
Andrew Geissler90fd73c2021-03-05 15:25:55 -0600134 # targets are the things we want to test the reproducibility of
135 targets = ['core-image-minimal', 'core-image-sato', 'core-image-full-cmdline', 'core-image-weston', 'world']
136 # sstate targets are things to pull from sstate to potentially cut build/debugging time
137 sstate_targets = []
Brad Bishop1d80a2e2019-11-15 16:35:03 -0500138 save_results = False
Andrew Geissler82c905d2020-04-13 13:39:40 -0500139 if 'OEQA_DEBUGGING_SAVED_OUTPUT' in os.environ:
140 save_results = os.environ['OEQA_DEBUGGING_SAVED_OUTPUT']
141
142 # This variable controls if one of the test builds is allowed to pull from
143 # an sstate cache/mirror. The other build is always done clean as a point of
144 # comparison.
145 # If you know that your sstate archives are reproducible, enabling this
146 # will test that and also make the test run faster. If your sstate is not
147 # reproducible, disable this in your derived test class
148 build_from_sstate = True
Brad Bishop15ae2502019-06-18 21:44:24 -0400149
150 def setUpLocal(self):
151 super().setUpLocal()
152 needed_vars = ['TOPDIR', 'TARGET_PREFIX', 'BB_NUMBER_THREADS']
153 bb_vars = get_bb_vars(needed_vars)
154 for v in needed_vars:
155 setattr(self, v.lower(), bb_vars[v])
156
Andrew Geissler82c905d2020-04-13 13:39:40 -0500157 self.extraresults = {}
158 self.extraresults.setdefault('reproducible.rawlogs', {})['log'] = ''
159 self.extraresults.setdefault('reproducible', {}).setdefault('files', {})
Brad Bishop15ae2502019-06-18 21:44:24 -0400160
161 def append_to_log(self, msg):
Andrew Geissler82c905d2020-04-13 13:39:40 -0500162 self.extraresults['reproducible.rawlogs']['log'] += msg
Brad Bishop15ae2502019-06-18 21:44:24 -0400163
164 def compare_packages(self, reference_dir, test_dir, diffutils_sysroot):
165 result = PackageCompareResults()
166
167 old_cwd = os.getcwd()
168 try:
169 file_result = {}
170 os.chdir(test_dir)
171 with multiprocessing.Pool(processes=int(self.bb_number_threads or 0)) as p:
172 for root, dirs, files in os.walk('.'):
173 async_result = []
174 for f in files:
175 reference_path = os.path.join(reference_dir, root, f)
176 test_path = os.path.join(test_dir, root, f)
177 async_result.append(p.apply_async(compare_file, (reference_path, test_path, diffutils_sysroot)))
178
179 for a in async_result:
180 result.add_result(a.get())
181
182 finally:
183 os.chdir(old_cwd)
184
185 result.sort()
186 return result
187
Brad Bishop79641f22019-09-10 07:20:22 -0400188 def write_package_list(self, package_class, name, packages):
Andrew Geissler82c905d2020-04-13 13:39:40 -0500189 self.extraresults['reproducible']['files'].setdefault(package_class, {})[name] = [
Brad Bishop79641f22019-09-10 07:20:22 -0400190 {'reference': p.reference, 'test': p.test} for p in packages]
191
Brad Bishop1d80a2e2019-11-15 16:35:03 -0500192 def copy_file(self, source, dest):
193 bb.utils.mkdirhier(os.path.dirname(dest))
194 shutil.copyfile(source, dest)
195
Andrew Geissler82c905d2020-04-13 13:39:40 -0500196 def do_test_build(self, name, use_sstate):
Brad Bishop15ae2502019-06-18 21:44:24 -0400197 capture_vars = ['DEPLOY_DIR_' + c.upper() for c in self.package_classes]
198
Andrew Geissler82c905d2020-04-13 13:39:40 -0500199 tmpdir = os.path.join(self.topdir, name, 'tmp')
200 if os.path.exists(tmpdir):
201 bb.utils.remove(tmpdir, recurse=True)
202
203 config = textwrap.dedent('''\
Andrew Geissler82c905d2020-04-13 13:39:40 -0500204 PACKAGE_CLASSES = "{package_classes}"
205 INHIBIT_PACKAGE_STRIP = "1"
206 TMPDIR = "{tmpdir}"
Andrew Geissler7e0e3c02022-02-25 20:34:39 +0000207 LICENSE_FLAGS_ACCEPTED = "commercial"
Patrick Williams213cb262021-08-07 19:21:33 -0500208 DISTRO_FEATURES:append = ' systemd pam'
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600209 USERADDEXTENSION = "useradd-staticids"
210 USERADD_ERROR_DYNAMIC = "skip"
211 USERADD_UID_TABLES += "files/static-passwd"
212 USERADD_GID_TABLES += "files/static-group"
Andrew Geissler82c905d2020-04-13 13:39:40 -0500213 ''').format(package_classes=' '.join('package_%s' % c for c in self.package_classes),
214 tmpdir=tmpdir)
215
216 if not use_sstate:
Andrew Geissler90fd73c2021-03-05 15:25:55 -0600217 if self.sstate_targets:
218 self.logger.info("Building prebuild for %s (sstate allowed)..." % (name))
219 self.write_config(config)
220 bitbake(' '.join(self.sstate_targets))
221
Andrew Geissler82c905d2020-04-13 13:39:40 -0500222 # This config fragment will disable using shared and the sstate
223 # mirror, forcing a complete build from scratch
224 config += textwrap.dedent('''\
225 SSTATE_DIR = "${TMPDIR}/sstate"
Andrew Geissler9b4d8b02021-02-19 12:26:16 -0600226 SSTATE_MIRRORS = ""
Andrew Geissler82c905d2020-04-13 13:39:40 -0500227 ''')
228
Andrew Geissler9b4d8b02021-02-19 12:26:16 -0600229 self.logger.info("Building %s (sstate%s allowed)..." % (name, '' if use_sstate else ' NOT'))
Andrew Geissler82c905d2020-04-13 13:39:40 -0500230 self.write_config(config)
231 d = get_bb_vars(capture_vars)
Andrew Geissler90fd73c2021-03-05 15:25:55 -0600232 # targets used to be called images
233 bitbake(' '.join(getattr(self, 'images', self.targets)))
Andrew Geissler82c905d2020-04-13 13:39:40 -0500234 return d
235
236 def test_reproducible_builds(self):
237 def strip_topdir(s):
238 if s.startswith(self.topdir):
239 return s[len(self.topdir):]
240 return s
Brad Bishop1d80a2e2019-11-15 16:35:03 -0500241
Brad Bishop15ae2502019-06-18 21:44:24 -0400242 # Build native utilities
Brad Bishop79641f22019-09-10 07:20:22 -0400243 self.write_config('')
Andrew Geissler82c905d2020-04-13 13:39:40 -0500244 bitbake("diffoscope-native diffutils-native jquery-native -c addto_recipe_sysroot")
Brad Bishop15ae2502019-06-18 21:44:24 -0400245 diffutils_sysroot = get_bb_var("RECIPE_SYSROOT_NATIVE", "diffutils-native")
Andrew Geissler82c905d2020-04-13 13:39:40 -0500246 diffoscope_sysroot = get_bb_var("RECIPE_SYSROOT_NATIVE", "diffoscope-native")
247 jquery_sysroot = get_bb_var("RECIPE_SYSROOT_NATIVE", "jquery-native")
Brad Bishop15ae2502019-06-18 21:44:24 -0400248
Andrew Geissler82c905d2020-04-13 13:39:40 -0500249 if self.save_results:
250 os.makedirs(self.save_results, exist_ok=True)
251 datestr = datetime.datetime.now().strftime('%Y%m%d')
252 save_dir = tempfile.mkdtemp(prefix='oe-reproducible-%s-' % datestr, dir=self.save_results)
253 os.chmod(save_dir, stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
254 self.logger.info('Non-reproducible packages will be copied to %s', save_dir)
Brad Bishop79641f22019-09-10 07:20:22 -0400255
Andrew Geissler82c905d2020-04-13 13:39:40 -0500256 vars_A = self.do_test_build('reproducibleA', self.build_from_sstate)
Andrew Geissler9b4d8b02021-02-19 12:26:16 -0600257
Andrew Geissler82c905d2020-04-13 13:39:40 -0500258 vars_B = self.do_test_build('reproducibleB', False)
Brad Bishop79641f22019-09-10 07:20:22 -0400259
260 # NOTE: The temp directories from the reproducible build are purposely
261 # kept after the build so it can be diffed for debugging.
262
Andrew Geissler82c905d2020-04-13 13:39:40 -0500263 fails = []
264
Brad Bishop15ae2502019-06-18 21:44:24 -0400265 for c in self.package_classes:
Brad Bishop79641f22019-09-10 07:20:22 -0400266 with self.subTest(package_class=c):
267 package_class = 'package_' + c
Brad Bishop15ae2502019-06-18 21:44:24 -0400268
Brad Bishop79641f22019-09-10 07:20:22 -0400269 deploy_A = vars_A['DEPLOY_DIR_' + c.upper()]
270 deploy_B = vars_B['DEPLOY_DIR_' + c.upper()]
Brad Bishop15ae2502019-06-18 21:44:24 -0400271
Andrew Geissler9b4d8b02021-02-19 12:26:16 -0600272 self.logger.info('Checking %s packages for differences...' % c)
Brad Bishop79641f22019-09-10 07:20:22 -0400273 result = self.compare_packages(deploy_A, deploy_B, diffutils_sysroot)
Brad Bishop15ae2502019-06-18 21:44:24 -0400274
Brad Bishop79641f22019-09-10 07:20:22 -0400275 self.logger.info('Reproducibility summary for %s: %s' % (c, result))
Brad Bishop15ae2502019-06-18 21:44:24 -0400276
Brad Bishop79641f22019-09-10 07:20:22 -0400277 self.append_to_log('\n'.join("%s: %s" % (r.status, r.test) for r in result.total))
Brad Bishop15ae2502019-06-18 21:44:24 -0400278
Brad Bishop79641f22019-09-10 07:20:22 -0400279 self.write_package_list(package_class, 'missing', result.missing)
280 self.write_package_list(package_class, 'different', result.different)
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600281 self.write_package_list(package_class, 'different_excluded', result.different_excluded)
Brad Bishop79641f22019-09-10 07:20:22 -0400282 self.write_package_list(package_class, 'same', result.same)
283
Brad Bishop1d80a2e2019-11-15 16:35:03 -0500284 if self.save_results:
285 for d in result.different:
Andrew Geissler82c905d2020-04-13 13:39:40 -0500286 self.copy_file(d.reference, '/'.join([save_dir, 'packages', strip_topdir(d.reference)]))
287 self.copy_file(d.test, '/'.join([save_dir, 'packages', strip_topdir(d.test)]))
Brad Bishop1d80a2e2019-11-15 16:35:03 -0500288
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600289 for d in result.different_excluded:
290 self.copy_file(d.reference, '/'.join([save_dir, 'packages-excluded', strip_topdir(d.reference)]))
291 self.copy_file(d.test, '/'.join([save_dir, 'packages-excluded', strip_topdir(d.test)]))
292
Brad Bishop79641f22019-09-10 07:20:22 -0400293 if result.missing or result.different:
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600294 fails.append("The following %s packages are missing or different and not in exclusion list: %s" %
Andrew Geissler82c905d2020-04-13 13:39:40 -0500295 (c, '\n'.join(r.test for r in (result.missing + result.different))))
296
297 # Clean up empty directories
298 if self.save_results:
299 if not os.listdir(save_dir):
300 os.rmdir(save_dir)
301 else:
302 self.logger.info('Running diffoscope')
303 package_dir = os.path.join(save_dir, 'packages')
304 package_html_dir = os.path.join(package_dir, 'diff-html')
305
306 # Copy jquery to improve the diffoscope output usability
307 self.copy_file(os.path.join(jquery_sysroot, 'usr/share/javascript/jquery/jquery.min.js'), os.path.join(package_html_dir, 'jquery.js'))
308
Andrew Geissler595f6302022-01-24 19:11:47 +0000309 run_diffoscope('reproducibleA', 'reproducibleB', package_html_dir, max_report_size=self.max_report_size,
Andrew Geissler82c905d2020-04-13 13:39:40 -0500310 native_sysroot=diffoscope_sysroot, ignore_status=True, cwd=package_dir)
311
312 if fails:
313 self.fail('\n'.join(fails))
Brad Bishop15ae2502019-06-18 21:44:24 -0400314