blob: 80e830136f76ea069c68d4de20cad2db08f7b9f6 [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):
Patrick Williamsac13d5f2023-11-24 18:59:46 -060046 def __init__(self, exclusions):
Brad Bishop15ae2502019-06-18 21:44:24 -040047 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()
Patrick Williamsac13d5f2023-11-24 18:59:46 -060053 exclude_packages.extend((exclusions or "").split())
Brad Bishop15ae2502019-06-18 21:44:24 -040054
55 def add_result(self, r):
56 self.total.append(r)
57 if r.status == MISSING:
58 self.missing.append(r)
59 elif r.status == DIFFERENT:
Andrew Geissler9b4d8b02021-02-19 12:26:16 -060060 exclusion = is_excluded(r.reference)
61 if exclusion:
Andrew Geisslerd1e89492021-02-12 15:35:20 -060062 self.different_excluded.append(r)
Andrew Geissler9b4d8b02021-02-19 12:26:16 -060063 self.active_exclusions.add(exclusion)
Andrew Geisslerd1e89492021-02-12 15:35:20 -060064 else:
65 self.different.append(r)
Brad Bishop15ae2502019-06-18 21:44:24 -040066 else:
67 self.same.append(r)
68
69 def sort(self):
70 self.total.sort()
71 self.missing.sort()
72 self.different.sort()
Andrew Geisslerd1e89492021-02-12 15:35:20 -060073 self.different_excluded.sort()
Brad Bishop15ae2502019-06-18 21:44:24 -040074 self.same.sort()
75
76 def __str__(self):
Andrew Geissler9b4d8b02021-02-19 12:26:16 -060077 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())
78
79 def unused_exclusions(self):
80 return sorted(set(exclude_packages) - self.active_exclusions)
Brad Bishop15ae2502019-06-18 21:44:24 -040081
82def compare_file(reference, test, diffutils_sysroot):
83 result = CompareResult()
84 result.reference = reference
85 result.test = test
86
87 if not os.path.exists(reference):
88 result.status = MISSING
89 return result
90
Andrew Geissler90fd73c2021-03-05 15:25:55 -060091 r = runCmd(['cmp', '--quiet', reference, test], native_sysroot=diffutils_sysroot, ignore_status=True, sync=False)
Brad Bishop15ae2502019-06-18 21:44:24 -040092
93 if r.status:
94 result.status = DIFFERENT
95 return result
96
97 result.status = SAME
98 return result
99
Andrew Geissler595f6302022-01-24 19:11:47 +0000100def run_diffoscope(a_dir, b_dir, html_dir, max_report_size=0, **kwargs):
101 return runCmd(['diffoscope', '--no-default-limits', '--max-report-size', str(max_report_size),
102 '--exclude-directory-metadata', 'yes', '--html-dir', html_dir, a_dir, b_dir],
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500103 **kwargs)
104
105class DiffoscopeTests(OESelftestTestCase):
106 diffoscope_test_files = os.path.join(os.path.dirname(os.path.abspath(__file__)), "diffoscope")
107
108 def test_diffoscope(self):
109 bitbake("diffoscope-native -c addto_recipe_sysroot")
110 diffoscope_sysroot = get_bb_var("RECIPE_SYSROOT_NATIVE", "diffoscope-native")
111
112 # Check that diffoscope doesn't return an error when the files compare
113 # the same (a general check that diffoscope is working)
114 with tempfile.TemporaryDirectory() as tmpdir:
115 run_diffoscope('A', 'A', tmpdir,
116 native_sysroot=diffoscope_sysroot, cwd=self.diffoscope_test_files)
117
118 # Check that diffoscope generates an index.html file when the files are
119 # different
120 with tempfile.TemporaryDirectory() as tmpdir:
121 r = run_diffoscope('A', 'B', tmpdir,
122 native_sysroot=diffoscope_sysroot, ignore_status=True, cwd=self.diffoscope_test_files)
123
124 self.assertNotEqual(r.status, 0, msg="diffoscope was successful when an error was expected")
125 self.assertTrue(os.path.exists(os.path.join(tmpdir, 'index.html')), "HTML index not found!")
126
Brad Bishop15ae2502019-06-18 21:44:24 -0400127class ReproducibleTests(OESelftestTestCase):
Andrew Geissler90fd73c2021-03-05 15:25:55 -0600128 # Test the reproducibility of whatever is built between sstate_targets and targets
129
Andrew Geissler220dafd2023-10-04 10:18:08 -0500130 package_classes = ['deb', 'ipk', 'rpm']
Andrew Geissler90fd73c2021-03-05 15:25:55 -0600131
Andrew Geissler595f6302022-01-24 19:11:47 +0000132 # Maximum report size, in bytes
133 max_report_size = 250 * 1024 * 1024
134
Andrew Geissler90fd73c2021-03-05 15:25:55 -0600135 # targets are the things we want to test the reproducibility of
Andrew Geissler220dafd2023-10-04 10:18:08 -0500136 targets = ['core-image-minimal', 'core-image-sato', 'core-image-full-cmdline', 'core-image-weston', 'world']
137
Andrew Geissler90fd73c2021-03-05 15:25:55 -0600138 # sstate targets are things to pull from sstate to potentially cut build/debugging time
Andrew Geissler220dafd2023-10-04 10:18:08 -0500139 sstate_targets = []
140
Brad Bishop1d80a2e2019-11-15 16:35:03 -0500141 save_results = False
Andrew Geissler82c905d2020-04-13 13:39:40 -0500142 if 'OEQA_DEBUGGING_SAVED_OUTPUT' in os.environ:
143 save_results = os.environ['OEQA_DEBUGGING_SAVED_OUTPUT']
144
145 # This variable controls if one of the test builds is allowed to pull from
146 # an sstate cache/mirror. The other build is always done clean as a point of
147 # comparison.
148 # If you know that your sstate archives are reproducible, enabling this
149 # will test that and also make the test run faster. If your sstate is not
150 # reproducible, disable this in your derived test class
151 build_from_sstate = True
Brad Bishop15ae2502019-06-18 21:44:24 -0400152
153 def setUpLocal(self):
154 super().setUpLocal()
Patrick Williamsac13d5f2023-11-24 18:59:46 -0600155 needed_vars = [
156 'TOPDIR',
157 'TARGET_PREFIX',
158 'BB_NUMBER_THREADS',
159 'BB_HASHSERVE',
160 'OEQA_REPRODUCIBLE_TEST_PACKAGE',
161 'OEQA_REPRODUCIBLE_TEST_TARGET',
162 'OEQA_REPRODUCIBLE_TEST_SSTATE_TARGETS',
163 'OEQA_REPRODUCIBLE_EXCLUDED_PACKAGES',
164 ]
Brad Bishop15ae2502019-06-18 21:44:24 -0400165 bb_vars = get_bb_vars(needed_vars)
166 for v in needed_vars:
167 setattr(self, v.lower(), bb_vars[v])
168
Andrew Geissler220dafd2023-10-04 10:18:08 -0500169 if bb_vars['OEQA_REPRODUCIBLE_TEST_PACKAGE']:
170 self.package_classes = bb_vars['OEQA_REPRODUCIBLE_TEST_PACKAGE'].split()
171
172 if bb_vars['OEQA_REPRODUCIBLE_TEST_TARGET']:
173 self.targets = bb_vars['OEQA_REPRODUCIBLE_TEST_TARGET'].split()
174
175 if bb_vars['OEQA_REPRODUCIBLE_TEST_SSTATE_TARGETS']:
176 self.sstate_targets = bb_vars['OEQA_REPRODUCIBLE_TEST_SSTATE_TARGETS'].split()
177
Andrew Geissler82c905d2020-04-13 13:39:40 -0500178 self.extraresults = {}
179 self.extraresults.setdefault('reproducible.rawlogs', {})['log'] = ''
180 self.extraresults.setdefault('reproducible', {}).setdefault('files', {})
Brad Bishop15ae2502019-06-18 21:44:24 -0400181
182 def append_to_log(self, msg):
Andrew Geissler82c905d2020-04-13 13:39:40 -0500183 self.extraresults['reproducible.rawlogs']['log'] += msg
Brad Bishop15ae2502019-06-18 21:44:24 -0400184
185 def compare_packages(self, reference_dir, test_dir, diffutils_sysroot):
Patrick Williamsac13d5f2023-11-24 18:59:46 -0600186 result = PackageCompareResults(self.oeqa_reproducible_excluded_packages)
Brad Bishop15ae2502019-06-18 21:44:24 -0400187
188 old_cwd = os.getcwd()
189 try:
190 file_result = {}
191 os.chdir(test_dir)
192 with multiprocessing.Pool(processes=int(self.bb_number_threads or 0)) as p:
193 for root, dirs, files in os.walk('.'):
194 async_result = []
195 for f in files:
196 reference_path = os.path.join(reference_dir, root, f)
197 test_path = os.path.join(test_dir, root, f)
198 async_result.append(p.apply_async(compare_file, (reference_path, test_path, diffutils_sysroot)))
199
200 for a in async_result:
201 result.add_result(a.get())
202
203 finally:
204 os.chdir(old_cwd)
205
206 result.sort()
207 return result
208
Brad Bishop79641f22019-09-10 07:20:22 -0400209 def write_package_list(self, package_class, name, packages):
Andrew Geissler82c905d2020-04-13 13:39:40 -0500210 self.extraresults['reproducible']['files'].setdefault(package_class, {})[name] = [
Brad Bishop79641f22019-09-10 07:20:22 -0400211 {'reference': p.reference, 'test': p.test} for p in packages]
212
Brad Bishop1d80a2e2019-11-15 16:35:03 -0500213 def copy_file(self, source, dest):
214 bb.utils.mkdirhier(os.path.dirname(dest))
215 shutil.copyfile(source, dest)
216
Andrew Geissler82c905d2020-04-13 13:39:40 -0500217 def do_test_build(self, name, use_sstate):
Brad Bishop15ae2502019-06-18 21:44:24 -0400218 capture_vars = ['DEPLOY_DIR_' + c.upper() for c in self.package_classes]
219
Andrew Geissler82c905d2020-04-13 13:39:40 -0500220 tmpdir = os.path.join(self.topdir, name, 'tmp')
221 if os.path.exists(tmpdir):
222 bb.utils.remove(tmpdir, recurse=True)
223
224 config = textwrap.dedent('''\
Andrew Geissler82c905d2020-04-13 13:39:40 -0500225 PACKAGE_CLASSES = "{package_classes}"
Andrew Geissler82c905d2020-04-13 13:39:40 -0500226 TMPDIR = "{tmpdir}"
Andrew Geissler7e0e3c02022-02-25 20:34:39 +0000227 LICENSE_FLAGS_ACCEPTED = "commercial"
Patrick Williams2a254922023-08-11 09:48:11 -0500228 DISTRO_FEATURES:append = ' pam'
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600229 USERADDEXTENSION = "useradd-staticids"
230 USERADD_ERROR_DYNAMIC = "skip"
231 USERADD_UID_TABLES += "files/static-passwd"
232 USERADD_GID_TABLES += "files/static-group"
Andrew Geissler82c905d2020-04-13 13:39:40 -0500233 ''').format(package_classes=' '.join('package_%s' % c for c in self.package_classes),
234 tmpdir=tmpdir)
235
236 if not use_sstate:
Andrew Geissler90fd73c2021-03-05 15:25:55 -0600237 if self.sstate_targets:
238 self.logger.info("Building prebuild for %s (sstate allowed)..." % (name))
239 self.write_config(config)
240 bitbake(' '.join(self.sstate_targets))
241
Andrew Geissler82c905d2020-04-13 13:39:40 -0500242 # This config fragment will disable using shared and the sstate
243 # mirror, forcing a complete build from scratch
244 config += textwrap.dedent('''\
245 SSTATE_DIR = "${TMPDIR}/sstate"
Patrick Williamsb542dec2023-06-09 01:26:37 -0500246 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 -0500247 ''')
248
Andrew Geissler9b4d8b02021-02-19 12:26:16 -0600249 self.logger.info("Building %s (sstate%s allowed)..." % (name, '' if use_sstate else ' NOT'))
Andrew Geissler82c905d2020-04-13 13:39:40 -0500250 self.write_config(config)
251 d = get_bb_vars(capture_vars)
Andrew Geissler90fd73c2021-03-05 15:25:55 -0600252 # targets used to be called images
253 bitbake(' '.join(getattr(self, 'images', self.targets)))
Andrew Geissler82c905d2020-04-13 13:39:40 -0500254 return d
255
256 def test_reproducible_builds(self):
257 def strip_topdir(s):
258 if s.startswith(self.topdir):
259 return s[len(self.topdir):]
260 return s
Brad Bishop1d80a2e2019-11-15 16:35:03 -0500261
Brad Bishop15ae2502019-06-18 21:44:24 -0400262 # Build native utilities
Brad Bishop79641f22019-09-10 07:20:22 -0400263 self.write_config('')
Andrew Geissler82c905d2020-04-13 13:39:40 -0500264 bitbake("diffoscope-native diffutils-native jquery-native -c addto_recipe_sysroot")
Brad Bishop15ae2502019-06-18 21:44:24 -0400265 diffutils_sysroot = get_bb_var("RECIPE_SYSROOT_NATIVE", "diffutils-native")
Andrew Geissler82c905d2020-04-13 13:39:40 -0500266 diffoscope_sysroot = get_bb_var("RECIPE_SYSROOT_NATIVE", "diffoscope-native")
267 jquery_sysroot = get_bb_var("RECIPE_SYSROOT_NATIVE", "jquery-native")
Brad Bishop15ae2502019-06-18 21:44:24 -0400268
Andrew Geissler82c905d2020-04-13 13:39:40 -0500269 if self.save_results:
270 os.makedirs(self.save_results, exist_ok=True)
271 datestr = datetime.datetime.now().strftime('%Y%m%d')
272 save_dir = tempfile.mkdtemp(prefix='oe-reproducible-%s-' % datestr, dir=self.save_results)
273 os.chmod(save_dir, stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
274 self.logger.info('Non-reproducible packages will be copied to %s', save_dir)
Brad Bishop79641f22019-09-10 07:20:22 -0400275
Andrew Geissler82c905d2020-04-13 13:39:40 -0500276 vars_A = self.do_test_build('reproducibleA', self.build_from_sstate)
Andrew Geissler9b4d8b02021-02-19 12:26:16 -0600277
Andrew Geissler82c905d2020-04-13 13:39:40 -0500278 vars_B = self.do_test_build('reproducibleB', False)
Brad Bishop79641f22019-09-10 07:20:22 -0400279
280 # NOTE: The temp directories from the reproducible build are purposely
281 # kept after the build so it can be diffed for debugging.
282
Andrew Geissler82c905d2020-04-13 13:39:40 -0500283 fails = []
284
Brad Bishop15ae2502019-06-18 21:44:24 -0400285 for c in self.package_classes:
Brad Bishop79641f22019-09-10 07:20:22 -0400286 with self.subTest(package_class=c):
287 package_class = 'package_' + c
Brad Bishop15ae2502019-06-18 21:44:24 -0400288
Brad Bishop79641f22019-09-10 07:20:22 -0400289 deploy_A = vars_A['DEPLOY_DIR_' + c.upper()]
290 deploy_B = vars_B['DEPLOY_DIR_' + c.upper()]
Brad Bishop15ae2502019-06-18 21:44:24 -0400291
Andrew Geissler9b4d8b02021-02-19 12:26:16 -0600292 self.logger.info('Checking %s packages for differences...' % c)
Brad Bishop79641f22019-09-10 07:20:22 -0400293 result = self.compare_packages(deploy_A, deploy_B, diffutils_sysroot)
Brad Bishop15ae2502019-06-18 21:44:24 -0400294
Brad Bishop79641f22019-09-10 07:20:22 -0400295 self.logger.info('Reproducibility summary for %s: %s' % (c, result))
Brad Bishop15ae2502019-06-18 21:44:24 -0400296
Brad Bishop79641f22019-09-10 07:20:22 -0400297 self.append_to_log('\n'.join("%s: %s" % (r.status, r.test) for r in result.total))
Brad Bishop15ae2502019-06-18 21:44:24 -0400298
Brad Bishop79641f22019-09-10 07:20:22 -0400299 self.write_package_list(package_class, 'missing', result.missing)
300 self.write_package_list(package_class, 'different', result.different)
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600301 self.write_package_list(package_class, 'different_excluded', result.different_excluded)
Brad Bishop79641f22019-09-10 07:20:22 -0400302 self.write_package_list(package_class, 'same', result.same)
303
Brad Bishop1d80a2e2019-11-15 16:35:03 -0500304 if self.save_results:
305 for d in result.different:
Andrew Geissler82c905d2020-04-13 13:39:40 -0500306 self.copy_file(d.reference, '/'.join([save_dir, 'packages', strip_topdir(d.reference)]))
307 self.copy_file(d.test, '/'.join([save_dir, 'packages', strip_topdir(d.test)]))
Brad Bishop1d80a2e2019-11-15 16:35:03 -0500308
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600309 for d in result.different_excluded:
310 self.copy_file(d.reference, '/'.join([save_dir, 'packages-excluded', strip_topdir(d.reference)]))
311 self.copy_file(d.test, '/'.join([save_dir, 'packages-excluded', strip_topdir(d.test)]))
312
Andrew Geisslerfc113ea2023-03-31 09:59:46 -0500313 if result.different:
314 fails.append("The following %s packages are different and not in exclusion list:\n%s" %
315 (c, '\n'.join(r.test for r in (result.different))))
316
317 if result.missing and len(self.sstate_targets) == 0:
318 fails.append("The following %s packages are missing and not in exclusion list:\n%s" %
319 (c, '\n'.join(r.test for r in (result.missing))))
Andrew Geissler82c905d2020-04-13 13:39:40 -0500320
321 # Clean up empty directories
322 if self.save_results:
323 if not os.listdir(save_dir):
324 os.rmdir(save_dir)
325 else:
326 self.logger.info('Running diffoscope')
327 package_dir = os.path.join(save_dir, 'packages')
328 package_html_dir = os.path.join(package_dir, 'diff-html')
329
330 # Copy jquery to improve the diffoscope output usability
331 self.copy_file(os.path.join(jquery_sysroot, 'usr/share/javascript/jquery/jquery.min.js'), os.path.join(package_html_dir, 'jquery.js'))
332
Andrew Geissler595f6302022-01-24 19:11:47 +0000333 run_diffoscope('reproducibleA', 'reproducibleB', package_html_dir, max_report_size=self.max_report_size,
Andrew Geissler82c905d2020-04-13 13:39:40 -0500334 native_sysroot=diffoscope_sysroot, ignore_status=True, cwd=package_dir)
335
336 if fails:
337 self.fail('\n'.join(fails))
Brad Bishop15ae2502019-06-18 21:44:24 -0400338