• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mozilla / mozregression / 11571809808

29 Oct 2024 10:19AM UTC coverage: 86.158%. First build
11571809808

Pull #1450

github

web-flow
Merge 9ae3bea93 into f558f7daa
Pull Request #1450: Bug 1763188 - Add Snap support using TC builds

96 of 217 new or added lines in 8 files covered. (44.24%)

2608 of 3027 relevant lines covered (86.16%)

13.07 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

89.23
/mozregression/main.py
1
"""
2
Entry point for the mozregression command line.
3
"""
4

5
from __future__ import absolute_import
14✔
6

7
import atexit
14✔
8
import os
14✔
9
import pipes
14✔
10
import sys
14✔
11

12
import colorama
14✔
13
import mozfile
14✔
14
import requests
14✔
15
from mozlog import get_proxy_logger
14✔
16
from requests.exceptions import HTTPError, RequestException
14✔
17

18
from mozregression import __version__
14✔
19
from mozregression.approx_persist import ApproxPersistChooser
14✔
20
from mozregression.bisector import (
14✔
21
    Bisection,
22
    Bisector,
23
    IntegrationHandler,
24
    NightlyHandler,
25
    SnapHandler,
26
)
27
from mozregression.bugzilla import bug_url, find_bugids_in_push
14✔
28
from mozregression.cli import cli
14✔
29
from mozregression.config import DEFAULT_EXPAND, TC_CREDENTIALS_FNAME
14✔
30
from mozregression.download_manager import BuildDownloadManager
14✔
31
from mozregression.errors import GoodBadExpectationError, MozRegressionError
14✔
32
from mozregression.fetch_build_info import IntegrationInfoFetcher, NightlyInfoFetcher
14✔
33
from mozregression.json_pushes import JsonPushes
14✔
34
from mozregression.launchers import REGISTRY as APP_REGISTRY
14✔
35
from mozregression.network import set_http_session
14✔
36
from mozregression.persist_limit import PersistLimit
14✔
37
from mozregression.telemetry import UsageMetrics, get_system_info, send_telemetry_ping_oop
14✔
38
from mozregression.tempdir import safe_mkdtemp
14✔
39
from mozregression.test_runner import CommandTestRunner, ManualTestRunner
14✔
40

41
LOG = get_proxy_logger("main")
14✔
42

43

44
class Application(object):
14✔
45
    def __init__(self, fetch_config, options):
14✔
46
        self.fetch_config = fetch_config
14✔
47
        self.options = options
14✔
48
        self._test_runner = None
14✔
49
        self._bisector = None
14✔
50
        self._build_download_manager = None
14✔
51
        self._download_dir = options.persist
14✔
52
        self._rm_download_dir = False
14✔
53
        if not options.persist:
14✔
54
            self._download_dir = safe_mkdtemp()
14✔
55
            self._rm_download_dir = True
14✔
56
        launcher_class = APP_REGISTRY.get(fetch_config.app_name)
14✔
57
        launcher_class.check_is_runnable()
14✔
58
        # init global profile if required
59
        self._global_profile = None
14✔
60
        if options.profile_persistence in ("clone-first", "reuse"):
14✔
61
            self._global_profile = launcher_class.create_profile(
×
62
                profile=options.profile,
63
                addons=options.addons,
64
                preferences=options.preferences,
65
                clone=options.profile_persistence == "clone-first",
66
            )
67
            options.cmdargs = options.cmdargs + ["--allow-downgrade"]
×
68
        elif options.profile:
14✔
69
            options.cmdargs = options.cmdargs + ["--allow-downgrade"]
14✔
70

71
    def clear(self):
14✔
72
        if self._build_download_manager:
14✔
73
            # cancel all possible downloads
74
            self._build_download_manager.cancel()
14✔
75
        if self._rm_download_dir:
14✔
76
            if self._build_download_manager:
14✔
77
                # we need to wait explicitly for downloading threads completion
78
                # here because it may remove a file in the download dir - and
79
                # in that case we could end up with a race condition when
80
                # we will remove the download dir. See
81
                # https://bugzilla.mozilla.org/show_bug.cgi?id=1231745
82
                self._build_download_manager.wait(raise_if_error=False)
14✔
83
            mozfile.remove(self._download_dir)
14✔
84
        if self._global_profile and self.options.profile_persistence == "clone-first":
14✔
85
            self._global_profile.cleanup()
×
86

87
    @property
14✔
88
    def test_runner(self):
14✔
89
        if self._test_runner is None:
14✔
90
            if self.options.command is None:
14✔
91
                self._test_runner = ManualTestRunner(
14✔
92
                    launcher_kwargs=dict(
93
                        addons=self.options.addons,
94
                        profile=self._global_profile or self.options.profile,
95
                        cmdargs=self.options.cmdargs,
96
                        preferences=self.options.preferences,
97
                        adb_profile_dir=self.options.adb_profile_dir,
98
                        allow_sudo=self.options.allow_sudo,
99
                        disable_snap_connect=self.options.disable_snap_connect,
100
                    )
101
                )
102
            else:
103
                self._test_runner = CommandTestRunner(self.options.command)
14✔
104
        return self._test_runner
14✔
105

106
    @property
14✔
107
    def bisector(self):
14✔
108
        if self._bisector is None:
14✔
109
            self._bisector = Bisector(
14✔
110
                self.fetch_config,
111
                self.test_runner,
112
                self.build_download_manager,
113
                dl_in_background=self.options.background_dl,
114
                approx_chooser=(
115
                    None if self.options.approx_policy != "auto" else ApproxPersistChooser(7)
116
                ),
117
            )
118
        return self._bisector
14✔
119

120
    @property
14✔
121
    def build_download_manager(self):
14✔
122
        if self._build_download_manager is None:
14✔
123
            background_dl_policy = self.options.background_dl_policy
14✔
124
            if not self.options.persist:
14✔
125
                # cancel background downloads forced
126
                background_dl_policy = "cancel"
14✔
127
            self._build_download_manager = BuildDownloadManager(
14✔
128
                self._download_dir,
129
                background_dl_policy=background_dl_policy,
130
                persist_limit=PersistLimit(self.options.persist_size_limit),
131
            )
132
        return self._build_download_manager
14✔
133

134
    def bisect_nightlies(self):
14✔
135
        good_date, bad_date = self.options.good, self.options.bad
14✔
136
        handler = NightlyHandler(
14✔
137
            find_fix=self.options.find_fix,
138
            ensure_good_and_bad=self.options.mode != "no-first-check",
139
        )
140
        result = self._do_bisect(handler, good_date, bad_date)
14✔
141
        if result == Bisection.FINISHED:
14✔
142
            LOG.info("Got as far as we can go bisecting nightlies...")
14✔
143
            handler.print_range()
14✔
144
            if self.fetch_config.can_go_integration():
14✔
145
                LOG.info("Switching bisection method to taskcluster")
14✔
146
                self.fetch_config.set_repo(self.fetch_config.get_nightly_repo(handler.bad_date))
14✔
147
                return self._bisect_integration(
14✔
148
                    handler.good_revision, handler.bad_revision, expand=DEFAULT_EXPAND
149
                )
150
        elif result == Bisection.USER_EXIT:
14✔
151
            self._print_resume_info(handler)
14✔
152
        else:
153
            # NO_DATA
154
            LOG.info(
14✔
155
                "Unable to get valid builds within the given"
156
                " range. You should try to launch mozregression"
157
                " again with a larger date range."
158
            )
159
            return 1
14✔
160
        return 0
14✔
161

162
    def bisect_integration(self):
14✔
163
        return self._bisect_integration(
14✔
164
            self.options.good,
165
            self.options.bad,
166
            ensure_good_and_bad=self.options.mode != "no-first-check",
167
        )
168

169
    def _bisect_integration(self, good_rev, bad_rev, ensure_good_and_bad=False, expand=0):
14✔
170
        LOG.info(
14✔
171
            "Getting %s builds between %s and %s"
172
            % (self.fetch_config.integration_branch, good_rev, bad_rev)
173
        )
174
        if self.options.app == "firefox-snap":
14✔
NEW
175
            handler = SnapHandler(
×
176
                find_fix=self.options.find_fix, ensure_good_and_bad=ensure_good_and_bad
177
            )
178
        else:
179
            handler = IntegrationHandler(
14✔
180
                find_fix=self.options.find_fix, ensure_good_and_bad=ensure_good_and_bad
181
            )
182
        result = self._do_bisect(handler, good_rev, bad_rev, expand=expand)
14✔
183
        if result == Bisection.FINISHED:
14✔
184
            LOG.info("No more integration revisions, bisection finished.")
14✔
185
            handler.print_range()
14✔
186
            if handler.good_revision == handler.bad_revision:
14✔
187
                LOG.warning(
14✔
188
                    "It seems that you used two changesets that are in"
189
                    " the same push. Check the pushlog url."
190
                )
191
            elif len(handler.build_range) == 2:
×
192
                # range reduced to 2 pushes (at least ones with builds):
193
                # one good, one bad.
194
                result = handler.handle_merge()
×
195
                if result:
×
196
                    branch, good_rev, bad_rev = result
×
197
                    self.fetch_config.set_repo(branch)
×
198
                    return self._bisect_integration(good_rev, bad_rev, expand=DEFAULT_EXPAND)
×
199
                else:
200
                    # This code is broken, it prints out the message even when
201
                    # there are multiple bug numbers or commits in the range.
202
                    # Somebody should fix it before re-enabling it.
203
                    return 0
×
204
                    # print a bug if:
205
                    # (1) there really is only one bad push (and we're not
206
                    # just missing the builds for some intermediate builds)
207
                    # (2) there is only one bug number in that push
208
                    jp = JsonPushes(handler.build_range[1].repo_name)
209
                    num_pushes = len(
210
                        jp.pushes_within_changes(
211
                            handler.build_range[0].changeset,
212
                            handler.build_range[1].changeset,
213
                        )
214
                    )
215
                    if num_pushes == 2:
216
                        bugids = find_bugids_in_push(
217
                            handler.build_range[1].repo_name,
218
                            handler.build_range[1].changeset,
219
                        )
220
                        if len(bugids) == 1:
221
                            word = "fix" if handler.find_fix else "regression"
222
                            LOG.info(
223
                                "Looks like the following bug has the "
224
                                " changes which introduced the"
225
                                " {}:\n{}".format(word, bug_url(bugids[0]))
226
                            )
227
        elif result == Bisection.USER_EXIT:
14✔
228
            self._print_resume_info(handler)
14✔
229
        else:
230
            # NO_DATA. With integration branches, this can not happen if changesets
231
            # are incorrect - so builds are probably too old
232
            LOG.info(
14✔
233
                "There are no build artifacts for these changesets (they are probably too old)."
234
            )
235
            return 1
14✔
236
        return 0
14✔
237

238
    def _do_bisect(self, handler, good, bad, **kwargs):
14✔
239
        try:
14✔
240
            return self.bisector.bisect(handler, good, bad, **kwargs)
14✔
241
        except (KeyboardInterrupt, MozRegressionError, RequestException) as exc:
14✔
242
            if (
14✔
243
                handler.good_revision is not None
244
                and handler.bad_revision is not None
245
                and not isinstance(exc, GoodBadExpectationError)
246
            ):
247
                atexit.register(self._on_exit_print_resume_info, handler)
14✔
248
            raise
14✔
249

250
    def _print_resume_info(self, handler):
14✔
251
        # copy sys.argv, remove every --good/--bad/--repo related argument,
252
        # then add our own
253
        argv = sys.argv[:]
14✔
254
        args = ("--good", "--bad", "-g", "-b", "--good-rev", "--bad-rev", "--repo")
14✔
255
        indexes_to_remove = []
14✔
256
        for i, arg in enumerate(argv):
14✔
257
            if i in indexes_to_remove:
14✔
258
                continue
14✔
259
            for karg in args:
14✔
260
                if karg == arg:
14✔
261
                    # handle '--good 2015-01-01'
262
                    indexes_to_remove.extend((i, i + 1))
14✔
263
                    break
14✔
264
                elif arg.startswith(karg + "="):
14✔
265
                    # handle '--good=2015-01-01'
266
                    indexes_to_remove.append(i)
×
267
                    break
×
268
        for i in reversed(indexes_to_remove):
14✔
269
            del argv[i]
14✔
270

271
        argv.append("--repo=%s" % handler.build_range[0].repo_name)
14✔
272

273
        if hasattr(handler, "good_date"):
14✔
274
            argv.append("--good=%s" % handler.good_date)
14✔
275
            argv.append("--bad=%s" % handler.bad_date)
14✔
276
        else:
277
            argv.append("--good=%s" % handler.good_revision)
14✔
278
            argv.append("--bad=%s" % handler.bad_revision)
14✔
279

280
        LOG.info("To resume, run:")
14✔
281
        LOG.info(" ".join([pipes.quote(arg) for arg in argv]))
14✔
282

283
    def _on_exit_print_resume_info(self, handler):
14✔
284
        handler.print_range()
14✔
285
        self._print_resume_info(handler)
14✔
286

287
    def _launch(self, fetcher_class):
14✔
288
        fetcher = fetcher_class(self.fetch_config)
×
289
        build_info = fetcher.find_build_info(self.options.launch)
×
290
        self.build_download_manager.focus_download(build_info)
×
291
        self.test_runner.run_once(build_info)
×
292

293
    def launch_nightlies(self):
14✔
294
        self._launch(NightlyInfoFetcher)
×
295

296
    def launch_integration(self):
14✔
297
        self._launch(IntegrationInfoFetcher)
×
298

299

300
def pypi_latest_version():
14✔
301
    url = "https://pypi.python.org/pypi/mozregression/json"
14✔
302
    return requests.get(url, timeout=10).json()["info"]["version"]
14✔
303

304

305
def check_mozregression_version():
14✔
306
    try:
14✔
307
        mozregression_version = pypi_latest_version()
14✔
308
    except (RequestException, KeyError, ValueError):
14✔
309
        LOG.critical("Unable to get latest version from pypi.")
14✔
310
        return
14✔
311

312
    if __version__ != mozregression_version:
14✔
313
        LOG.warning(
14✔
314
            "You are using mozregression version %s, "
315
            "however version %s is available." % (__version__, mozregression_version)
316
        )
317

318
        LOG.warning(
14✔
319
            "You should consider upgrading via the 'pip install"
320
            " --upgrade mozregression' command."
321
        )
322

323

324
def main(
14✔
325
    argv=None,
326
    namespace=None,
327
    check_new_version=True,
328
    mozregression_variant="console",
329
):
330
    """
331
    main entry point of mozregression command line.
332
    """
333
    # terminal color support on windows
334
    if os.name == "nt":
14✔
335
        colorama.init()
×
336

337
    config, app = None, None
14✔
338
    try:
14✔
339
        config = cli(argv=argv, namespace=namespace)
14✔
340
        if check_new_version:
14✔
341
            check_mozregression_version()
14✔
342
        config.validate()
14✔
343
        set_http_session(get_defaults={"timeout": config.options.http_timeout})
14✔
344

345
        app = Application(config.fetch_config, config.options)
14✔
346
        send_telemetry_ping_oop(
14✔
347
            UsageMetrics(
348
                variant=mozregression_variant,
349
                appname=config.fetch_config.app_name,
350
                build_type=config.fetch_config.build_type,
351
                good=config.options.good,
352
                bad=config.options.bad,
353
                launch=config.options.launch,
354
                **get_system_info(),
355
            ),
356
            config.enable_telemetry,
357
        )
358

359
        method = getattr(app, config.action)
14✔
360
        sys.exit(method())
14✔
361

362
    except KeyboardInterrupt:
14✔
363
        sys.exit("\nInterrupted.")
14✔
364
    except (MozRegressionError, RequestException) as exc:
14✔
365
        if isinstance(exc, HTTPError) and exc.response.status_code == 401:
14✔
366
            # remove the taskcluster credential file - looks like it's wrong
367
            # anyway. This will force mozregression to ask again next time.
368
            mozfile.remove(TC_CREDENTIALS_FNAME)
×
369
        LOG.error(str(exc)) if config else sys.exit(str(exc))
14✔
370
        sys.exit(1)
14✔
371
    finally:
372
        if app:
14✔
373
            app.clear()
14✔
374

375

376
if __name__ == "__main__":
377
    main()
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc