summaryrefslogtreecommitdiffstats
path: root/scripts/reproducible-check
blob: 64b6617c4f824239e34d2f9f84d2ebf58c8d7987 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
#!/usr/bin/env python3
#
# Copyright (C) 2017 Chris Lamb <lamby@debian.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import argparse
import bz2
import collections
import json
import logging
import os
import sys
import time

import apt
import requests

try:
    from xdg.BaseDirectory import xdg_cache_home
except ImportError:
    print("This script requires the xdg python3 module.", file=sys.stderr)
    print("Please install the python3-xdg Debian package in order to use"
          "this utility.", file=sys.stderr)
    sys.exit(1)


class ReproducibleCheck:
    HELP = """
        Reports on the reproducible status of installed packages.
        For more details please see <https://reproducible-builds.org>.
    """

    NAME = os.path.basename(__file__)
    VERSION = 1

    STATUS_URL = 'https://tests.reproducible-builds.org/debian/' \
        'reproducible-tracker.json.bz2'

    CACHE = os.path.join(xdg_cache_home, NAME, os.path.basename(STATUS_URL))
    CACHE_AGE_SECONDS = 86400

    @classmethod
    def parse(cls):
        parser = argparse.ArgumentParser(description=cls.HELP)

        parser.add_argument(
            '-d',
            '--debug',
            help="show debugging messages",
            default=False,
            action='store_true',
        )

        parser.add_argument(
            '-r',
            '--raw',
            help="print unreproducible binary packages only (for dd-list -i)",
            default=False,
            action='store_true',
        )

        parser.add_argument(
            '--version',
            help="print version and exit",
            default=False,
            action='store_true',
        )

        return cls(parser.parse_args())

    def __init__(self, args):
        self.args = args

        logging.basicConfig(
            format='%(asctime).19s %(levelname).1s: %(message)s',
            level=logging.DEBUG if args.debug else logging.INFO,
        )

        self.log = logging.getLogger()

    def main(self):
        if self.args.version:
            print("{} version {}".format(self.NAME, self.VERSION))
            return 0

        self.update_cache()

        data = self.get_data()
        installed = self.get_installed_packages()
        unreproducible = {x: y for x, y in installed.items() if x in data}

        if self.args.raw:
            self.output_raw(unreproducible, installed)
        else:
            self.output_by_source(unreproducible, installed)

        return 0

    def update_cache(self):
        self.log.debug("Checking cache file %s ...", self.CACHE)

        try:
            if os.path.getmtime(self.CACHE) >= \
                    time.time() - self.CACHE_AGE_SECONDS:
                self.log.debug("Cache is up to date")
                return
        except OSError:
            pass

        self.log.info("Updating cache...")

        response = requests.get(self.STATUS_URL)

        os.makedirs(os.path.dirname(self.CACHE), exist_ok=True)

        with open(self.CACHE, 'wb+') as f:
            f.write(response.content)

    def get_data(self):
        self.log.debug("Loading data from cache %s", self.CACHE)

        with bz2.open(self.CACHE) as f:
            return {
                (x['package'], y['architecture'], x['version'])
                for x in json.loads(f.read().decode('utf-8'))
                for y in x['architecture_details']
                if y['status'] == 'unreproducible'
            }

    @staticmethod
    def get_installed_packages():
        result = collections.defaultdict(list)

        for x in apt.Cache():
            for y in x.versions:
                if not y.is_installed:
                    continue

                key = (y.source_name, y.architecture, y.version)
                result[key].append(x.shortname)

        return result

    @staticmethod
    def output_by_source(unreproducible, installed):
        num_installed = sum(len(x) for x in installed.keys())
        num_unreproducible = sum(len(x) for x in unreproducible.keys())
        default_architecture = apt.apt_pkg.config.find('APT::Architecture')

        for key, binaries in sorted(unreproducible.items()):
            source, architecture, version = key

            binaries_fmt = '({}) '.format(', '.join(binaries)) \
                if binaries != [source] else ''

            print("{}{} ({}) is unreproducible {}".format(
                source,
                '/{}'.format(architecture)
                if architecture != default_architecture else '',
                version,
                binaries_fmt,
            ), end='')
            print("<https://tests.reproducible-builds.org/debian/{}>".format(
                source,
            ))

        msg = "{}/{} ({:.2f}%) of installed binary packages are unreproducible."
        print(msg.format(
            num_unreproducible,
            num_installed,
            100. * num_unreproducible / num_installed,
        ))

    @staticmethod
    def output_raw(unreproducible, installed):  # pylint: disable=unused-argument
        for x in sorted(x for xs in unreproducible.values() for x in set(xs)):
            print(x)


if __name__ == '__main__':
    try:
        sys.exit(ReproducibleCheck.parse().main())
    except (KeyboardInterrupt, BrokenPipeError):
        sys.exit(1)