blob: 0f7e6eb376ef3e24300eb1a090d98981b6d6aee0 [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 = [
Patrick Williams92b42cb2022-09-03 06:53:57 -050019 'rust',
20 'rust-dbg'
Andrew Geisslerd1e89492021-02-12 15:35:20 -060021 ]
22
23def is_excluded(package):
24 package_name = os.path.basename(package)
25 for i in exclude_packages:
26 if package_name.startswith(i):
Andrew Geissler9b4d8b02021-02-19 12:26:16 -060027 return i
28 return None
Andrew Geisslerd1e89492021-02-12 15:35:20 -060029
Brad Bishop15ae2502019-06-18 21:44:24 -040030MISSING = 'MISSING'
31DIFFERENT = 'DIFFERENT'
32SAME = 'SAME'
33
34@functools.total_ordering
35class CompareResult(object):
36 def __init__(self):
37 self.reference = None
38 self.test = None
39 self.status = 'UNKNOWN'
40
41 def __eq__(self, other):
42 return (self.status, self.test) == (other.status, other.test)
43
44 def __lt__(self, other):
45 return (self.status, self.test) < (other.status, other.test)
46
47class PackageCompareResults(object):
48 def __init__(self):
49 self.total = []
50 self.missing = []
51 self.different = []
Andrew Geisslerd1e89492021-02-12 15:35:20 -060052 self.different_excluded = []
Brad Bishop15ae2502019-06-18 21:44:24 -040053 self.same = []
Andrew Geissler9b4d8b02021-02-19 12:26:16 -060054 self.active_exclusions = set()
Brad Bishop15ae2502019-06-18 21:44:24 -040055
56 def add_result(self, r):
57 self.total.append(r)
58 if r.status == MISSING:
59 self.missing.append(r)
60 elif r.status == DIFFERENT:
Andrew Geissler9b4d8b02021-02-19 12:26:16 -060061 exclusion = is_excluded(r.reference)
62 if exclusion:
Andrew Geisslerd1e89492021-02-12 15:35:20 -060063 self.different_excluded.append(r)
Andrew Geissler9b4d8b02021-02-19 12:26:16 -060064 self.active_exclusions.add(exclusion)
Andrew Geisslerd1e89492021-02-12 15:35:20 -060065 else:
66 self.different.append(r)
Brad Bishop15ae2502019-06-18 21:44:24 -040067 else:
68 self.same.append(r)
69
70 def sort(self):
71 self.total.sort()
72 self.missing.sort()
73 self.different.sort()
Andrew Geisslerd1e89492021-02-12 15:35:20 -060074 self.different_excluded.sort()
Brad Bishop15ae2502019-06-18 21:44:24 -040075 self.same.sort()
76
77 def __str__(self):
Andrew Geissler9b4d8b02021-02-19 12:26:16 -060078 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())
79
80 def unused_exclusions(self):
81 return sorted(set(exclude_packages) - self.active_exclusions)
Brad Bishop15ae2502019-06-18 21:44:24 -040082
83def compare_file(reference, test, diffutils_sysroot):
84 result = CompareResult()
85 result.reference = reference
86 result.test = test
87
88 if not os.path.exists(reference):
89 result.status = MISSING
90 return result
91
Andrew Geissler90fd73c2021-03-05 15:25:55 -060092 r = runCmd(['cmp', '--quiet', reference, test], native_sysroot=diffutils_sysroot, ignore_status=True, sync=False)
Brad Bishop15ae2502019-06-18 21:44:24 -040093
94 if r.status:
95 result.status = DIFFERENT
96 return result
97
98 result.status = SAME
99 return result
100
Andrew Geissler595f6302022-01-24 19:11:47 +0000101def run_diffoscope(a_dir, b_dir, html_dir, max_report_size=0, **kwargs):
102 return runCmd(['diffoscope', '--no-default-limits', '--max-report-size', str(max_report_size),
103 '--exclude-directory-metadata', 'yes', '--html-dir', html_dir, a_dir, b_dir],
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500104 **kwargs)
105
106class DiffoscopeTests(OESelftestTestCase):
107 diffoscope_test_files = os.path.join(os.path.dirname(os.path.abspath(__file__)), "diffoscope")
108
109 def test_diffoscope(self):
110 bitbake("diffoscope-native -c addto_recipe_sysroot")
111 diffoscope_sysroot = get_bb_var("RECIPE_SYSROOT_NATIVE", "diffoscope-native")
112
113 # Check that diffoscope doesn't return an error when the files compare
114 # the same (a general check that diffoscope is working)
115 with tempfile.TemporaryDirectory() as tmpdir:
116 run_diffoscope('A', 'A', tmpdir,
117 native_sysroot=diffoscope_sysroot, cwd=self.diffoscope_test_files)
118
119 # Check that diffoscope generates an index.html file when the files are
120 # different
121 with tempfile.TemporaryDirectory() as tmpdir:
122 r = run_diffoscope('A', 'B', tmpdir,
123 native_sysroot=diffoscope_sysroot, ignore_status=True, cwd=self.diffoscope_test_files)
124
125 self.assertNotEqual(r.status, 0, msg="diffoscope was successful when an error was expected")
126 self.assertTrue(os.path.exists(os.path.join(tmpdir, 'index.html')), "HTML index not found!")
127
Brad Bishop15ae2502019-06-18 21:44:24 -0400128class ReproducibleTests(OESelftestTestCase):
Andrew Geissler90fd73c2021-03-05 15:25:55 -0600129 # Test the reproducibility of whatever is built between sstate_targets and targets
130
Patrick Williams520786c2023-06-25 16:20:36 -0500131 package_classes = get_bb_var("OEQA_REPRODUCIBLE_TEST_PACKAGE")
132 if package_classes:
133 package_classes = package_classes.split()
134 else:
135 package_classes = ['deb', 'ipk', 'rpm']
Andrew Geissler90fd73c2021-03-05 15:25:55 -0600136
Andrew Geissler595f6302022-01-24 19:11:47 +0000137 # Maximum report size, in bytes
138 max_report_size = 250 * 1024 * 1024
139
Andrew Geissler90fd73c2021-03-05 15:25:55 -0600140 # targets are the things we want to test the reproducibility of
Patrick Williams520786c2023-06-25 16:20:36 -0500141 targets = get_bb_var("OEQA_REPRODUCIBLE_TEST_TARGET")
142 if targets:
143 targets = targets.split()
144 else:
145 targets = ['core-image-minimal', 'core-image-sato', 'core-image-full-cmdline', 'core-image-weston', 'world']
Andrew Geissler90fd73c2021-03-05 15:25:55 -0600146 # sstate targets are things to pull from sstate to potentially cut build/debugging time
Patrick Williams520786c2023-06-25 16:20:36 -0500147 sstate_targets = (get_bb_var("OEQA_REPRODUCIBLE_TEST_SSTATE_TARGETS") or "").split()
Brad Bishop1d80a2e2019-11-15 16:35:03 -0500148 save_results = False
Andrew Geissler82c905d2020-04-13 13:39:40 -0500149 if 'OEQA_DEBUGGING_SAVED_OUTPUT' in os.environ:
150 save_results = os.environ['OEQA_DEBUGGING_SAVED_OUTPUT']
151
152 # This variable controls if one of the test builds is allowed to pull from
153 # an sstate cache/mirror. The other build is always done clean as a point of
154 # comparison.
155 # If you know that your sstate archives are reproducible, enabling this
156 # will test that and also make the test run faster. If your sstate is not
157 # reproducible, disable this in your derived test class
158 build_from_sstate = True
Brad Bishop15ae2502019-06-18 21:44:24 -0400159
160 def setUpLocal(self):
161 super().setUpLocal()
Patrick Williamsb542dec2023-06-09 01:26:37 -0500162 needed_vars = ['TOPDIR', 'TARGET_PREFIX', 'BB_NUMBER_THREADS', 'BB_HASHSERVE']
Brad Bishop15ae2502019-06-18 21:44:24 -0400163 bb_vars = get_bb_vars(needed_vars)
164 for v in needed_vars:
165 setattr(self, v.lower(), bb_vars[v])
166
Andrew Geissler82c905d2020-04-13 13:39:40 -0500167 self.extraresults = {}
168 self.extraresults.setdefault('reproducible.rawlogs', {})['log'] = ''
169 self.extraresults.setdefault('reproducible', {}).setdefault('files', {})
Brad Bishop15ae2502019-06-18 21:44:24 -0400170
171 def append_to_log(self, msg):
Andrew Geissler82c905d2020-04-13 13:39:40 -0500172 self.extraresults['reproducible.rawlogs']['log'] += msg
Brad Bishop15ae2502019-06-18 21:44:24 -0400173
174 def compare_packages(self, reference_dir, test_dir, diffutils_sysroot):
175 result = PackageCompareResults()
176
177 old_cwd = os.getcwd()
178 try:
179 file_result = {}
180 os.chdir(test_dir)
181 with multiprocessing.Pool(processes=int(self.bb_number_threads or 0)) as p:
182 for root, dirs, files in os.walk('.'):
183 async_result = []
184 for f in files:
185 reference_path = os.path.join(reference_dir, root, f)
186 test_path = os.path.join(test_dir, root, f)
187 async_result.append(p.apply_async(compare_file, (reference_path, test_path, diffutils_sysroot)))
188
189 for a in async_result:
190 result.add_result(a.get())
191
192 finally:
193 os.chdir(old_cwd)
194
195 result.sort()
196 return result
197
Brad Bishop79641f22019-09-10 07:20:22 -0400198 def write_package_list(self, package_class, name, packages):
Andrew Geissler82c905d2020-04-13 13:39:40 -0500199 self.extraresults['reproducible']['files'].setdefault(package_class, {})[name] = [
Brad Bishop79641f22019-09-10 07:20:22 -0400200 {'reference': p.reference, 'test': p.test} for p in packages]
201
Brad Bishop1d80a2e2019-11-15 16:35:03 -0500202 def copy_file(self, source, dest):
203 bb.utils.mkdirhier(os.path.dirname(dest))
204 shutil.copyfile(source, dest)
205
Andrew Geissler82c905d2020-04-13 13:39:40 -0500206 def do_test_build(self, name, use_sstate):
Brad Bishop15ae2502019-06-18 21:44:24 -0400207 capture_vars = ['DEPLOY_DIR_' + c.upper() for c in self.package_classes]
208
Andrew Geissler82c905d2020-04-13 13:39:40 -0500209 tmpdir = os.path.join(self.topdir, name, 'tmp')
210 if os.path.exists(tmpdir):
211 bb.utils.remove(tmpdir, recurse=True)
212
213 config = textwrap.dedent('''\
Andrew Geissler82c905d2020-04-13 13:39:40 -0500214 PACKAGE_CLASSES = "{package_classes}"
215 INHIBIT_PACKAGE_STRIP = "1"
216 TMPDIR = "{tmpdir}"
Andrew Geissler7e0e3c02022-02-25 20:34:39 +0000217 LICENSE_FLAGS_ACCEPTED = "commercial"
Patrick Williams213cb262021-08-07 19:21:33 -0500218 DISTRO_FEATURES:append = ' systemd pam'
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600219 USERADDEXTENSION = "useradd-staticids"
220 USERADD_ERROR_DYNAMIC = "skip"
221 USERADD_UID_TABLES += "files/static-passwd"
222 USERADD_GID_TABLES += "files/static-group"
Andrew Geissler82c905d2020-04-13 13:39:40 -0500223 ''').format(package_classes=' '.join('package_%s' % c for c in self.package_classes),
224 tmpdir=tmpdir)
225
226 if not use_sstate:
Andrew Geissler90fd73c2021-03-05 15:25:55 -0600227 if self.sstate_targets:
228 self.logger.info("Building prebuild for %s (sstate allowed)..." % (name))
229 self.write_config(config)
230 bitbake(' '.join(self.sstate_targets))
231
Andrew Geissler82c905d2020-04-13 13:39:40 -0500232 # This config fragment will disable using shared and the sstate
233 # mirror, forcing a complete build from scratch
234 config += textwrap.dedent('''\
235 SSTATE_DIR = "${TMPDIR}/sstate"
Patrick Williamsb542dec2023-06-09 01:26:37 -0500236 SSTATE_MIRRORS = "file://.*/.*-native.* http://sstate.yoctoproject.org/all/PATH;downloadfilename=PATH file://.*/.*-cross.* http://sstate.yoctoproject.org/all/PATH;downloadfilename=PATH"
Andrew Geissler82c905d2020-04-13 13:39:40 -0500237 ''')
238
Andrew Geissler9b4d8b02021-02-19 12:26:16 -0600239 self.logger.info("Building %s (sstate%s allowed)..." % (name, '' if use_sstate else ' NOT'))
Andrew Geissler82c905d2020-04-13 13:39:40 -0500240 self.write_config(config)
241 d = get_bb_vars(capture_vars)
Andrew Geissler90fd73c2021-03-05 15:25:55 -0600242 # targets used to be called images
243 bitbake(' '.join(getattr(self, 'images', self.targets)))
Andrew Geissler82c905d2020-04-13 13:39:40 -0500244 return d
245
246 def test_reproducible_builds(self):
247 def strip_topdir(s):
248 if s.startswith(self.topdir):
249 return s[len(self.topdir):]
250 return s
Brad Bishop1d80a2e2019-11-15 16:35:03 -0500251
Brad Bishop15ae2502019-06-18 21:44:24 -0400252 # Build native utilities
Brad Bishop79641f22019-09-10 07:20:22 -0400253 self.write_config('')
Andrew Geissler82c905d2020-04-13 13:39:40 -0500254 bitbake("diffoscope-native diffutils-native jquery-native -c addto_recipe_sysroot")
Brad Bishop15ae2502019-06-18 21:44:24 -0400255 diffutils_sysroot = get_bb_var("RECIPE_SYSROOT_NATIVE", "diffutils-native")
Andrew Geissler82c905d2020-04-13 13:39:40 -0500256 diffoscope_sysroot = get_bb_var("RECIPE_SYSROOT_NATIVE", "diffoscope-native")
257 jquery_sysroot = get_bb_var("RECIPE_SYSROOT_NATIVE", "jquery-native")
Brad Bishop15ae2502019-06-18 21:44:24 -0400258
Andrew Geissler82c905d2020-04-13 13:39:40 -0500259 if self.save_results:
260 os.makedirs(self.save_results, exist_ok=True)
261 datestr = datetime.datetime.now().strftime('%Y%m%d')
262 save_dir = tempfile.mkdtemp(prefix='oe-reproducible-%s-' % datestr, dir=self.save_results)
263 os.chmod(save_dir, stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
264 self.logger.info('Non-reproducible packages will be copied to %s', save_dir)
Brad Bishop79641f22019-09-10 07:20:22 -0400265
Andrew Geissler82c905d2020-04-13 13:39:40 -0500266 vars_A = self.do_test_build('reproducibleA', self.build_from_sstate)
Andrew Geissler9b4d8b02021-02-19 12:26:16 -0600267
Andrew Geissler82c905d2020-04-13 13:39:40 -0500268 vars_B = self.do_test_build('reproducibleB', False)
Brad Bishop79641f22019-09-10 07:20:22 -0400269
270 # NOTE: The temp directories from the reproducible build are purposely
271 # kept after the build so it can be diffed for debugging.
272
Andrew Geissler82c905d2020-04-13 13:39:40 -0500273 fails = []
274
Brad Bishop15ae2502019-06-18 21:44:24 -0400275 for c in self.package_classes:
Brad Bishop79641f22019-09-10 07:20:22 -0400276 with self.subTest(package_class=c):
277 package_class = 'package_' + c
Brad Bishop15ae2502019-06-18 21:44:24 -0400278
Brad Bishop79641f22019-09-10 07:20:22 -0400279 deploy_A = vars_A['DEPLOY_DIR_' + c.upper()]
280 deploy_B = vars_B['DEPLOY_DIR_' + c.upper()]
Brad Bishop15ae2502019-06-18 21:44:24 -0400281
Andrew Geissler9b4d8b02021-02-19 12:26:16 -0600282 self.logger.info('Checking %s packages for differences...' % c)
Brad Bishop79641f22019-09-10 07:20:22 -0400283 result = self.compare_packages(deploy_A, deploy_B, diffutils_sysroot)
Brad Bishop15ae2502019-06-18 21:44:24 -0400284
Brad Bishop79641f22019-09-10 07:20:22 -0400285 self.logger.info('Reproducibility summary for %s: %s' % (c, result))
Brad Bishop15ae2502019-06-18 21:44:24 -0400286
Brad Bishop79641f22019-09-10 07:20:22 -0400287 self.append_to_log('\n'.join("%s: %s" % (r.status, r.test) for r in result.total))
Brad Bishop15ae2502019-06-18 21:44:24 -0400288
Brad Bishop79641f22019-09-10 07:20:22 -0400289 self.write_package_list(package_class, 'missing', result.missing)
290 self.write_package_list(package_class, 'different', result.different)
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600291 self.write_package_list(package_class, 'different_excluded', result.different_excluded)
Brad Bishop79641f22019-09-10 07:20:22 -0400292 self.write_package_list(package_class, 'same', result.same)
293
Brad Bishop1d80a2e2019-11-15 16:35:03 -0500294 if self.save_results:
295 for d in result.different:
Andrew Geissler82c905d2020-04-13 13:39:40 -0500296 self.copy_file(d.reference, '/'.join([save_dir, 'packages', strip_topdir(d.reference)]))
297 self.copy_file(d.test, '/'.join([save_dir, 'packages', strip_topdir(d.test)]))
Brad Bishop1d80a2e2019-11-15 16:35:03 -0500298
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600299 for d in result.different_excluded:
300 self.copy_file(d.reference, '/'.join([save_dir, 'packages-excluded', strip_topdir(d.reference)]))
301 self.copy_file(d.test, '/'.join([save_dir, 'packages-excluded', strip_topdir(d.test)]))
302
Andrew Geisslerfc113ea2023-03-31 09:59:46 -0500303 if result.different:
304 fails.append("The following %s packages are different and not in exclusion list:\n%s" %
305 (c, '\n'.join(r.test for r in (result.different))))
306
307 if result.missing and len(self.sstate_targets) == 0:
308 fails.append("The following %s packages are missing and not in exclusion list:\n%s" %
309 (c, '\n'.join(r.test for r in (result.missing))))
Andrew Geissler82c905d2020-04-13 13:39:40 -0500310
311 # Clean up empty directories
312 if self.save_results:
313 if not os.listdir(save_dir):
314 os.rmdir(save_dir)
315 else:
316 self.logger.info('Running diffoscope')
317 package_dir = os.path.join(save_dir, 'packages')
318 package_html_dir = os.path.join(package_dir, 'diff-html')
319
320 # Copy jquery to improve the diffoscope output usability
321 self.copy_file(os.path.join(jquery_sysroot, 'usr/share/javascript/jquery/jquery.min.js'), os.path.join(package_html_dir, 'jquery.js'))
322
Andrew Geissler595f6302022-01-24 19:11:47 +0000323 run_diffoscope('reproducibleA', 'reproducibleB', package_html_dir, max_report_size=self.max_report_size,
Andrew Geissler82c905d2020-04-13 13:39:40 -0500324 native_sysroot=diffoscope_sysroot, ignore_status=True, cwd=package_dir)
325
326 if fails:
327 self.fail('\n'.join(fails))
Brad Bishop15ae2502019-06-18 21:44:24 -0400328