1# 2# SPDX-License-Identifier: MIT 3# 4# Copyright 2019-2020 by Garmin Ltd. or its subsidiaries 5 6from oeqa.selftest.case import OESelftestTestCase 7from oeqa.utils.commands import runCmd, bitbake, get_bb_var, get_bb_vars 8import bb.utils 9import functools 10import multiprocessing 11import textwrap 12import tempfile 13import shutil 14import stat 15import os 16import datetime 17 18exclude_packages = [ 19 ] 20 21def is_excluded(package): 22 package_name = os.path.basename(package) 23 for i in exclude_packages: 24 if package_name.startswith(i): 25 return i 26 return None 27 28MISSING = '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, exclusions): 47 self.total = [] 48 self.missing = [] 49 self.different = [] 50 self.different_excluded = [] 51 self.same = [] 52 self.active_exclusions = set() 53 exclude_packages.extend((exclusions or "").split()) 54 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: 60 exclusion = is_excluded(r.reference) 61 if exclusion: 62 self.different_excluded.append(r) 63 self.active_exclusions.add(exclusion) 64 else: 65 self.different.append(r) 66 else: 67 self.same.append(r) 68 69 def sort(self): 70 self.total.sort() 71 self.missing.sort() 72 self.different.sort() 73 self.different_excluded.sort() 74 self.same.sort() 75 76 def __str__(self): 77 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) 81 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 91 r = runCmd(['cmp', '--quiet', reference, test], native_sysroot=diffutils_sysroot, ignore_status=True, sync=False) 92 93 if r.status: 94 result.status = DIFFERENT 95 return result 96 97 result.status = SAME 98 return result 99 100def 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], 103 **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 127class ReproducibleTests(OESelftestTestCase): 128 # Test the reproducibility of whatever is built between sstate_targets and targets 129 130 package_classes = ['deb', 'ipk', 'rpm'] 131 132 # Maximum report size, in bytes 133 max_report_size = 250 * 1024 * 1024 134 135 # targets are the things we want to test the reproducibility of 136 # Have to add the virtual targets manually for now as builds may or may not include them as they're exclude from world 137 targets = ['core-image-minimal', 'core-image-sato', 'core-image-full-cmdline', 'core-image-weston', 'world', 'virtual/librpc', 'virtual/libsdl2', 'virtual/crypt'] 138 139 # sstate targets are things to pull from sstate to potentially cut build/debugging time 140 sstate_targets = [] 141 142 save_results = False 143 if 'OEQA_DEBUGGING_SAVED_OUTPUT' in os.environ: 144 save_results = os.environ['OEQA_DEBUGGING_SAVED_OUTPUT'] 145 146 # This variable controls if one of the test builds is allowed to pull from 147 # an sstate cache/mirror. The other build is always done clean as a point of 148 # comparison. 149 # If you know that your sstate archives are reproducible, enabling this 150 # will test that and also make the test run faster. If your sstate is not 151 # reproducible, disable this in your derived test class 152 build_from_sstate = True 153 154 def setUpLocal(self): 155 super().setUpLocal() 156 needed_vars = [ 157 'TOPDIR', 158 'TARGET_PREFIX', 159 'BB_NUMBER_THREADS', 160 'BB_HASHSERVE', 161 'OEQA_REPRODUCIBLE_TEST_PACKAGE', 162 'OEQA_REPRODUCIBLE_TEST_TARGET', 163 'OEQA_REPRODUCIBLE_TEST_SSTATE_TARGETS', 164 'OEQA_REPRODUCIBLE_EXCLUDED_PACKAGES', 165 'OEQA_REPRODUCIBLE_TEST_LEAF_TARGETS', 166 ] 167 bb_vars = get_bb_vars(needed_vars) 168 for v in needed_vars: 169 setattr(self, v.lower(), bb_vars[v]) 170 171 if bb_vars['OEQA_REPRODUCIBLE_TEST_PACKAGE']: 172 self.package_classes = bb_vars['OEQA_REPRODUCIBLE_TEST_PACKAGE'].split() 173 174 if bb_vars['OEQA_REPRODUCIBLE_TEST_TARGET'] or bb_vars['OEQA_REPRODUCIBLE_TEST_LEAF_TARGETS']: 175 self.targets = (bb_vars['OEQA_REPRODUCIBLE_TEST_TARGET'] or "").split() + (bb_vars['OEQA_REPRODUCIBLE_TEST_LEAF_TARGETS'] or "").split() 176 177 if bb_vars['OEQA_REPRODUCIBLE_TEST_SSTATE_TARGETS']: 178 self.sstate_targets = bb_vars['OEQA_REPRODUCIBLE_TEST_SSTATE_TARGETS'].split() 179 180 if bb_vars['OEQA_REPRODUCIBLE_TEST_LEAF_TARGETS']: 181 # Setup to build every DEPENDS of leaf recipes using sstate 182 for leaf_recipe in bb_vars['OEQA_REPRODUCIBLE_TEST_LEAF_TARGETS'].split(): 183 self.sstate_targets.extend(get_bb_var('DEPENDS', leaf_recipe).split()) 184 185 self.extraresults = {} 186 self.extraresults.setdefault('reproducible', {}).setdefault('files', {}) 187 188 def compare_packages(self, reference_dir, test_dir, diffutils_sysroot): 189 result = PackageCompareResults(self.oeqa_reproducible_excluded_packages) 190 191 old_cwd = os.getcwd() 192 try: 193 file_result = {} 194 os.chdir(test_dir) 195 with multiprocessing.Pool(processes=int(self.bb_number_threads or 0)) as p: 196 for root, dirs, files in os.walk('.'): 197 async_result = [] 198 for f in files: 199 reference_path = os.path.join(reference_dir, root, f) 200 test_path = os.path.join(test_dir, root, f) 201 async_result.append(p.apply_async(compare_file, (reference_path, test_path, diffutils_sysroot))) 202 203 for a in async_result: 204 result.add_result(a.get()) 205 206 finally: 207 os.chdir(old_cwd) 208 209 result.sort() 210 return result 211 212 def write_package_list(self, package_class, name, packages): 213 self.extraresults['reproducible']['files'].setdefault(package_class, {})[name] = [ 214 p.reference.split("/./")[1] for p in packages] 215 216 def copy_file(self, source, dest): 217 bb.utils.mkdirhier(os.path.dirname(dest)) 218 shutil.copyfile(source, dest) 219 220 def do_test_build(self, name, use_sstate): 221 capture_vars = ['DEPLOY_DIR_' + c.upper() for c in self.package_classes] 222 223 tmpdir = os.path.join(self.topdir, name, 'tmp') 224 if os.path.exists(tmpdir): 225 bb.utils.remove(tmpdir, recurse=True) 226 config = textwrap.dedent('''\ 227 PACKAGE_CLASSES = "{package_classes}" 228 TMPDIR = "{tmpdir}" 229 LICENSE_FLAGS_ACCEPTED = "commercial" 230 DISTRO_FEATURES:append = ' pam' 231 USERADDEXTENSION = "useradd-staticids" 232 USERADD_ERROR_DYNAMIC = "skip" 233 USERADD_UID_TABLES += "files/static-passwd" 234 USERADD_GID_TABLES += "files/static-group" 235 ''').format(package_classes=' '.join('package_%s' % c for c in self.package_classes), 236 tmpdir=tmpdir) 237 238 # Export BB_CONSOLELOG to the calling function and make it constant to 239 # avoid a case where bitbake would get a timestamp-based filename but 240 # oe-selftest would, later, get another. 241 capture_vars.append("BB_CONSOLELOG") 242 config += 'BB_CONSOLELOG = "${LOG_DIR}/cooker/${MACHINE}/console.log"\n' 243 244 # We want different log files for each build, but a persistent bitbake 245 # may reuse the previous log file so restart the bitbake server. 246 bitbake("--kill-server") 247 248 def print_condensed_error_log(logs, context_lines=10, tail_lines=20): 249 """Prints errors with context and the end of the log.""" 250 251 logs = logs.split("\n") 252 for i, line in enumerate(logs): 253 if line.startswith("ERROR"): 254 self.logger.info("Found ERROR (line %d):" % (i + 1)) 255 for l in logs[i-context_lines:i+context_lines]: 256 self.logger.info(" " + l) 257 258 self.logger.info("End of log:") 259 for l in logs[-tail_lines:]: 260 self.logger.info(" " + l) 261 262 bitbake_failure_count = 0 263 if not use_sstate: 264 if self.sstate_targets: 265 self.logger.info("Building prebuild for %s (sstate allowed)..." % (name)) 266 self.write_config(config) 267 try: 268 bitbake("--continue "+' '.join(self.sstate_targets)) 269 except AssertionError as e: 270 bitbake_failure_count += 1 271 self.logger.error("Bitbake failed! but keep going... Log:") 272 print_condensed_error_log(str(e)) 273 274 # This config fragment will disable using shared and the sstate 275 # mirror, forcing a complete build from scratch 276 config += textwrap.dedent('''\ 277 SSTATE_DIR = "${TMPDIR}/sstate" 278 SSTATE_MIRRORS = "file://.*/.*-native.* http://sstate.yoctoproject.org/all/PATH;downloadfilename=PATH file://.*/.*-cross.* http://sstate.yoctoproject.org/all/PATH;downloadfilename=PATH" 279 ''') 280 281 self.logger.info("Building %s (sstate%s allowed)..." % (name, '' if use_sstate else ' NOT')) 282 self.write_config(config) 283 d = get_bb_vars(capture_vars) 284 try: 285 # targets used to be called images 286 bitbake("--continue "+' '.join(getattr(self, 'images', self.targets))) 287 except AssertionError as e: 288 bitbake_failure_count += 1 289 self.logger.error("Bitbake failed! but keep going... Log:") 290 print_condensed_error_log(str(e)) 291 292 # The calling function expects the existence of the deploy 293 # directories containing the packages. 294 # If bitbake failed to create them, do it manually 295 for c in self.package_classes: 296 deploy = d['DEPLOY_DIR_' + c.upper()] 297 if not os.path.exists(deploy): 298 self.logger.info("Manually creating %s" % deploy) 299 bb.utils.mkdirhier(deploy) 300 301 return (d, bitbake_failure_count) 302 303 def test_reproducible_builds(self): 304 def strip_topdir(s): 305 if s.startswith(self.topdir): 306 return s[len(self.topdir):] 307 return s 308 309 # Build native utilities 310 self.write_config('') 311 bitbake("diffoscope-native diffutils-native jquery-native -c addto_recipe_sysroot") 312 diffutils_sysroot = get_bb_var("RECIPE_SYSROOT_NATIVE", "diffutils-native") 313 diffoscope_sysroot = get_bb_var("RECIPE_SYSROOT_NATIVE", "diffoscope-native") 314 jquery_sysroot = get_bb_var("RECIPE_SYSROOT_NATIVE", "jquery-native") 315 316 if self.save_results: 317 os.makedirs(self.save_results, exist_ok=True) 318 datestr = datetime.datetime.now().strftime('%Y%m%d') 319 save_dir = tempfile.mkdtemp(prefix='oe-reproducible-%s-' % datestr, dir=self.save_results) 320 os.chmod(save_dir, stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH) 321 self.logger.info('Non-reproducible packages will be copied to %s', save_dir) 322 323 # The below bug shows that a few reproducible issues are depends on build dir path length. 324 # https://bugzilla.yoctoproject.org/show_bug.cgi?id=15554 325 # So, the reproducibleA & reproducibleB directories are changed to reproducibleA & reproducibleB-extended to have different size. 326 327 fails = [] 328 vars_list = [None, None] 329 330 for i, (name, use_sstate) in enumerate( 331 (('reproducibleA', self.build_from_sstate), 332 ('reproducibleB-extended', False))): 333 (variables, bitbake_failure_count) = self.do_test_build(name, use_sstate) 334 if bitbake_failure_count > 0: 335 self.logger.error('%s build failed. Trying to compute built packages differences but the test will fail.' % name) 336 fails.append("Bitbake %s failure" % name) 337 if self.save_results: 338 failure_log_path = os.path.join(save_dir, "bitbake-%s.log" % name) 339 self.logger.info('Failure log for %s will be copied to %s'% (name, failure_log_path)) 340 self.copy_file(variables["BB_CONSOLELOG"], failure_log_path) 341 vars_list[i] = variables 342 343 vars_A, vars_B = vars_list 344 # NOTE: The temp directories from the reproducible build are purposely 345 # kept after the build so it can be diffed for debugging. 346 347 for c in self.package_classes: 348 with self.subTest(package_class=c): 349 package_class = 'package_' + c 350 351 deploy_A = vars_A['DEPLOY_DIR_' + c.upper()] 352 deploy_B = vars_B['DEPLOY_DIR_' + c.upper()] 353 354 self.logger.info('Checking %s packages for differences...' % c) 355 result = self.compare_packages(deploy_A, deploy_B, diffutils_sysroot) 356 357 self.logger.info('Reproducibility summary for %s: %s' % (c, result)) 358 359 self.write_package_list(package_class, 'missing', result.missing) 360 self.write_package_list(package_class, 'different', result.different) 361 self.write_package_list(package_class, 'different_excluded', result.different_excluded) 362 self.write_package_list(package_class, 'same', result.same) 363 364 if self.save_results: 365 for d in result.different: 366 self.copy_file(d.reference, '/'.join([save_dir, 'packages', strip_topdir(d.reference)])) 367 self.copy_file(d.test, '/'.join([save_dir, 'packages', strip_topdir(d.test)])) 368 369 for d in result.different_excluded: 370 self.copy_file(d.reference, '/'.join([save_dir, 'packages-excluded', strip_topdir(d.reference)])) 371 self.copy_file(d.test, '/'.join([save_dir, 'packages-excluded', strip_topdir(d.test)])) 372 373 if result.different: 374 fails.append("The following %s packages are different and not in exclusion list:\n%s" % 375 (c, '\n'.join(r.test for r in (result.different)))) 376 377 if result.missing and len(self.sstate_targets) == 0: 378 fails.append("The following %s packages are missing and not in exclusion list:\n%s" % 379 (c, '\n'.join(r.test for r in (result.missing)))) 380 381 # Clean up empty directories 382 if self.save_results: 383 if not os.listdir(save_dir): 384 os.rmdir(save_dir) 385 else: 386 self.logger.info('Running diffoscope') 387 package_dir = os.path.join(save_dir, 'packages') 388 package_html_dir = os.path.join(package_dir, 'diff-html') 389 390 # Copy jquery to improve the diffoscope output usability 391 self.copy_file(os.path.join(jquery_sysroot, 'usr/share/javascript/jquery/jquery.min.js'), os.path.join(package_html_dir, 'jquery.js')) 392 393 run_diffoscope('reproducibleA', 'reproducibleB-extended', package_html_dir, max_report_size=self.max_report_size, 394 native_sysroot=diffoscope_sysroot, ignore_status=True, cwd=package_dir) 395 396 if fails: 397 self.fail('\n'.join(fails)) 398 399