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

mozilla / mozregression / 11572410622

29 Oct 2024 10:56AM CUT coverage: 35.085%. First build
11572410622

Pull #1450

github

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

63 of 200 new or added lines in 8 files covered. (31.5%)

1055 of 3007 relevant lines covered (35.08%)

1.05 hits per line

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

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

5
from __future__ import absolute_import
×
6

7
import atexit
×
8
import os
×
9
import pipes
×
10
import sys
×
11

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

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

41
LOG = get_proxy_logger("main")
×
42

43

44
class Application(object):
×
45
    def __init__(self, fetch_config, options):
×
46
        self.fetch_config = fetch_config
×
47
        self.options = options
×
48
        self._test_runner = None
×
49
        self._bisector = None
×
50
        self._build_download_manager = None
×
51
        self._download_dir = options.persist
×
52
        self._rm_download_dir = False
×
53
        if not options.persist:
×
54
            self._download_dir = safe_mkdtemp()
×
55
            self._rm_download_dir = True
×
56
        launcher_class = APP_REGISTRY.get(fetch_config.app_name)
×
57
        launcher_class.check_is_runnable()
×
58
        # init global profile if required
59
        self._global_profile = None
×
60
        if options.profile_persistence in ("clone-first", "reuse"):
×
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:
×
69
            options.cmdargs = options.cmdargs + ["--allow-downgrade"]
×
70

71
    def clear(self):
×
72
        if self._build_download_manager:
×
73
            # cancel all possible downloads
74
            self._build_download_manager.cancel()
×
75
        if self._rm_download_dir:
×
76
            if self._build_download_manager:
×
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)
×
83
            mozfile.remove(self._download_dir)
×
84
        if self._global_profile and self.options.profile_persistence == "clone-first":
×
85
            self._global_profile.cleanup()
×
86

87
    @property
×
88
    def test_runner(self):
×
89
        if self._test_runner is None:
×
90
            if self.options.command is None:
×
91
                self._test_runner = ManualTestRunner(
×
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)
×
104
        return self._test_runner
×
105

106
    @property
×
107
    def bisector(self):
×
108
        if self._bisector is None:
×
109
            self._bisector = Bisector(
×
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
×
119

120
    @property
×
121
    def build_download_manager(self):
×
122
        if self._build_download_manager is None:
×
123
            background_dl_policy = self.options.background_dl_policy
×
124
            if not self.options.persist:
×
125
                # cancel background downloads forced
126
                background_dl_policy = "cancel"
×
127
            self._build_download_manager = BuildDownloadManager(
×
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
×
133

134
    def bisect_nightlies(self):
×
135
        good_date, bad_date = self.options.good, self.options.bad
×
136
        handler = NightlyHandler(
×
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)
×
141
        if result == Bisection.FINISHED:
×
142
            LOG.info("Got as far as we can go bisecting nightlies...")
×
143
            handler.print_range()
×
144
            if self.fetch_config.can_go_integration():
×
145
                LOG.info("Switching bisection method to taskcluster")
×
146
                self.fetch_config.set_repo(self.fetch_config.get_nightly_repo(handler.bad_date))
×
147
                return self._bisect_integration(
×
148
                    handler.good_revision, handler.bad_revision, expand=DEFAULT_EXPAND
149
                )
150
        elif result == Bisection.USER_EXIT:
×
151
            self._print_resume_info(handler)
×
152
        else:
153
            # NO_DATA
154
            LOG.info(
×
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
×
160
        return 0
×
161

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

232
    def _do_bisect(self, handler, good, bad, **kwargs):
×
233
        try:
×
234
            return self.bisector.bisect(handler, good, bad, **kwargs)
×
235
        except (KeyboardInterrupt, MozRegressionError, RequestException) as exc:
×
236
            if (
×
237
                handler.good_revision is not None
238
                and handler.bad_revision is not None
239
                and not isinstance(exc, GoodBadExpectationError)
240
            ):
241
                atexit.register(self._on_exit_print_resume_info, handler)
×
242
            raise
×
243

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

265
        argv.append("--repo=%s" % handler.build_range[0].repo_name)
×
266

267
        if hasattr(handler, "good_date"):
×
268
            argv.append("--good=%s" % handler.good_date)
×
269
            argv.append("--bad=%s" % handler.bad_date)
×
270
        else:
271
            argv.append("--good=%s" % handler.good_revision)
×
272
            argv.append("--bad=%s" % handler.bad_revision)
×
273

274
        LOG.info("To resume, run:")
×
275
        LOG.info(" ".join([pipes.quote(arg) for arg in argv]))
×
276

277
    def _on_exit_print_resume_info(self, handler):
×
278
        handler.print_range()
×
279
        self._print_resume_info(handler)
×
280

281
    def _launch(self, fetcher_class):
×
282
        fetcher = fetcher_class(self.fetch_config)
×
283
        build_info = fetcher.find_build_info(self.options.launch)
×
284
        self.build_download_manager.focus_download(build_info)
×
285
        self.test_runner.run_once(build_info)
×
286

287
    def launch_nightlies(self):
×
288
        self._launch(NightlyInfoFetcher)
×
289

290
    def launch_integration(self):
×
291
        self._launch(IntegrationInfoFetcher)
×
292

293

294
def pypi_latest_version():
×
295
    url = "https://pypi.python.org/pypi/mozregression/json"
×
296
    return requests.get(url, timeout=10).json()["info"]["version"]
×
297

298

299
def check_mozregression_version():
×
300
    try:
×
301
        mozregression_version = pypi_latest_version()
×
302
    except (RequestException, KeyError, ValueError):
×
303
        LOG.critical("Unable to get latest version from pypi.")
×
304
        return
×
305

306
    if __version__ != mozregression_version:
×
307
        LOG.warning(
×
308
            "You are using mozregression version %s, "
309
            "however version %s is available." % (__version__, mozregression_version)
310
        )
311

312
        LOG.warning(
×
313
            "You should consider upgrading via the 'pip install"
314
            " --upgrade mozregression' command."
315
        )
316

317

318
def main(
×
319
    argv=None,
320
    namespace=None,
321
    check_new_version=True,
322
    mozregression_variant="console",
323
):
324
    """
325
    main entry point of mozregression command line.
326
    """
327
    # terminal color support on windows
328
    if os.name == "nt":
×
329
        colorama.init()
×
330

331
    config, app = None, None
×
332
    try:
×
333
        config = cli(argv=argv, namespace=namespace)
×
334
        if check_new_version:
×
335
            check_mozregression_version()
×
336
        config.validate()
×
337
        set_http_session(get_defaults={"timeout": config.options.http_timeout})
×
338

339
        app = Application(config.fetch_config, config.options)
×
340
        send_telemetry_ping_oop(
×
341
            UsageMetrics(
342
                variant=mozregression_variant,
343
                appname=config.fetch_config.app_name,
344
                build_type=config.fetch_config.build_type,
345
                good=config.options.good,
346
                bad=config.options.bad,
347
                launch=config.options.launch,
348
                **get_system_info(),
349
            ),
350
            config.enable_telemetry,
351
        )
352

353
        method = getattr(app, config.action)
×
354
        sys.exit(method())
×
355

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

369

370
if __name__ == "__main__":
371
    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