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    targets = ['core-image-minimal', 'core-image-sato', 'core-image-full-cmdline', 'core-image-weston', 'world']
137
138    # sstate targets are things to pull from sstate to potentially cut build/debugging time
139    sstate_targets = []
140
141    save_results = False
142    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
152
153    def setUpLocal(self):
154        super().setUpLocal()
155        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        ]
165        bb_vars = get_bb_vars(needed_vars)
166        for v in needed_vars:
167            setattr(self, v.lower(), bb_vars[v])
168
169        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
178        self.extraresults = {}
179        self.extraresults.setdefault('reproducible.rawlogs', {})['log'] = ''
180        self.extraresults.setdefault('reproducible', {}).setdefault('files', {})
181
182    def append_to_log(self, msg):
183        self.extraresults['reproducible.rawlogs']['log'] += msg
184
185    def compare_packages(self, reference_dir, test_dir, diffutils_sysroot):
186        result = PackageCompareResults(self.oeqa_reproducible_excluded_packages)
187
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
209    def write_package_list(self, package_class, name, packages):
210        self.extraresults['reproducible']['files'].setdefault(package_class, {})[name] = [
211                {'reference': p.reference, 'test': p.test} for p in packages]
212
213    def copy_file(self, source, dest):
214        bb.utils.mkdirhier(os.path.dirname(dest))
215        shutil.copyfile(source, dest)
216
217    def do_test_build(self, name, use_sstate):
218        capture_vars = ['DEPLOY_DIR_' + c.upper() for c in self.package_classes]
219
220        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('''\
225            PACKAGE_CLASSES = "{package_classes}"
226            TMPDIR = "{tmpdir}"
227            LICENSE_FLAGS_ACCEPTED = "commercial"
228            DISTRO_FEATURES:append = ' pam'
229            USERADDEXTENSION = "useradd-staticids"
230            USERADD_ERROR_DYNAMIC = "skip"
231            USERADD_UID_TABLES += "files/static-passwd"
232            USERADD_GID_TABLES += "files/static-group"
233            ''').format(package_classes=' '.join('package_%s' % c for c in self.package_classes),
234                        tmpdir=tmpdir)
235
236        if not use_sstate:
237            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
242            # 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"
246                SSTATE_MIRRORS = "file://.*/.*-native.*  http://sstate.yoctoproject.org/all/PATH;downloadfilename=PATH file://.*/.*-cross.*  http://sstate.yoctoproject.org/all/PATH;downloadfilename=PATH"
247                ''')
248
249        self.logger.info("Building %s (sstate%s allowed)..." % (name, '' if use_sstate else ' NOT'))
250        self.write_config(config)
251        d = get_bb_vars(capture_vars)
252        # targets used to be called images
253        bitbake(' '.join(getattr(self, 'images', self.targets)))
254        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
261
262        # Build native utilities
263        self.write_config('')
264        bitbake("diffoscope-native diffutils-native jquery-native -c addto_recipe_sysroot")
265        diffutils_sysroot = get_bb_var("RECIPE_SYSROOT_NATIVE", "diffutils-native")
266        diffoscope_sysroot = get_bb_var("RECIPE_SYSROOT_NATIVE", "diffoscope-native")
267        jquery_sysroot = get_bb_var("RECIPE_SYSROOT_NATIVE", "jquery-native")
268
269        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)
275
276        vars_A = self.do_test_build('reproducibleA', self.build_from_sstate)
277
278        vars_B = self.do_test_build('reproducibleB', False)
279
280        # NOTE: The temp directories from the reproducible build are purposely
281        # kept after the build so it can be diffed for debugging.
282
283        fails = []
284
285        for c in self.package_classes:
286            with self.subTest(package_class=c):
287                package_class = 'package_' + c
288
289                deploy_A = vars_A['DEPLOY_DIR_' + c.upper()]
290                deploy_B = vars_B['DEPLOY_DIR_' + c.upper()]
291
292                self.logger.info('Checking %s packages for differences...' % c)
293                result = self.compare_packages(deploy_A, deploy_B, diffutils_sysroot)
294
295                self.logger.info('Reproducibility summary for %s: %s' % (c, result))
296
297                self.append_to_log('\n'.join("%s: %s" % (r.status, r.test) for r in result.total))
298
299                self.write_package_list(package_class, 'missing', result.missing)
300                self.write_package_list(package_class, 'different', result.different)
301                self.write_package_list(package_class, 'different_excluded', result.different_excluded)
302                self.write_package_list(package_class, 'same', result.same)
303
304                if self.save_results:
305                    for d in result.different:
306                        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)]))
308
309                    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
313                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))))
320
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
333                run_diffoscope('reproducibleA', 'reproducibleB', package_html_dir, max_report_size=self.max_report_size,
334                        native_sysroot=diffoscope_sysroot, ignore_status=True, cwd=package_dir)
335
336        if fails:
337            self.fail('\n'.join(fails))
338
339