DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Mercurial (dcc6d7a0dc00)

VCS Links

Line Code
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 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
"""
Module for performing gaia-specific tasks
"""

import json
import os
import re

from mozharness.base.errors import HgErrorList, BaseErrorList, ZipErrorList
from mozharness.base.log import ERROR, FATAL

gaia_config_options = [
    [["--gaia-dir"],
    {"action": "store",
     "dest": "gaia_dir",
     "help": "directory where gaia repo should be cloned"
     }],
    [["--gaia-repo"],
    {"action": "store",
     "dest": "gaia_repo",
     "help": "url of gaia repo to clone"
    }],
    [["--gaia-branch"],
    {"action": "store",
     "dest": "gaia_branch",
     "default": "default",
     "help": "branch of gaia repo to clone"
    }],
]

class GaiaMixin(object):

    npm_error_list = BaseErrorList + [
        {'substr': r'''npm ERR! Error:''', 'level': ERROR}
    ]

    # This requires self to inherit a VCSMixin.
    def clone_gaia(self, dest, repo, use_gaia_json=False):
        """
        Clones an hg mirror of gaia.

        repo: a dict containing 'repo_path', 'revision', and optionally
              'branch' parameters
        use_gaia_json: if True, the repo parameter is used to retrieve
              a gaia.json file from a gecko repo, which in turn is used to
              clone gaia; if False, repo represents a gaia repo to clone.
        """

        repo_path = repo.get('repo_path')
        revision = repo.get('revision')
        branch = repo.get('branch')
        gaia_json_path = self.config.get("gaia_json_path", "{repo_path}/raw-file/{revision}/b2g/config/gaia.json")
        git = False
        pr_git_revision = None
        pr_remote = None

        self.info('dest: %s' % dest)

        if use_gaia_json:
            url = gaia_json_path.format(
                repo_path=repo_path,
                revision=revision)
            contents = self.retry(self.load_json_from_url, args=(url,))
            if contents.get('git') and contents['git'].get('remote'):
                git = True
                remote = contents['git']['remote']
                branch = contents['git'].get('branch')
                revision = contents['git'].get('git_revision')
                pr_git_revision = contents['git'].get('pr_git_revision')
                pr_remote = contents['git'].get('pr_remote')
                if pr_remote or pr_git_revision:
                    if not (pr_remote and pr_git_revision):
                        self.fatal('Pull request mode requres rev *and* remote')
                if not (branch or revision):
                    self.fatal('Must specify branch or revision for git repo')
            elif contents.get('repo_path') and contents.get('revision'):
                repo_path = 'https://hg.mozilla.org/%s' % contents['repo_path']
                revision = contents['revision']
                branch = None

        if git:
            git_cmd = self.query_exe('git')
            needs_clobber = True

            # For pull requests, we only want to clobber when we can't find the
            # two exact commit ids that we'll be working with.  As long as we
            # have those two commits, we don't care about the rest of the repo
            def has_needed_commit(commit, fatal=False):
                cmd = [git_cmd, 'rev-parse', '--quiet', '--verify', '%s^{commit}' % commit]
                rc = self.run_command(cmd, cwd=dest, halt_on_failure=False, success_codes=[1,0])
                if rc != 0:
                    return False
                return True

            if not pr_remote and os.path.exists(dest) and os.path.exists(os.path.join(dest, '.git')):
                cmd = [git_cmd, 'remote', '-v']
                output = self.get_output_from_command(cmd, cwd=dest)
                for line in output:
                    if remote in line:
                        needs_clobber = False


            # We want to do some cleanup logic differently for pull requests
            if pr_git_revision and pr_remote:
                needs_clobber = False
                if os.path.exists(dest) and os.path.exists(os.path.join(dest, '.git')):
                    cmd = [git_cmd, 'clean', '-f', '-f', '-x', '-d']
                    self.run_command(cmd, cwd=dest, halt_on_failure=True,
                                     fatal_exit_code=3)
                    if not has_needed_commit(revision):
                        cmd = [git_cmd, 'fetch', 'origin']
                        self.run_command(cmd, cwd=dest, halt_on_failure=True,
                                         fatal_exit_code=3)
                    if not has_needed_commit(revision):
                        self.warn('Repository does not contain required revisions, clobbering')
                        needs_clobber = True

            # In pull request mode, we don't want to clone because we're satisfied
            # that the base directory is good enough because
            needs_clone = True
            if pr_git_revision and pr_remote:
                if os.path.exists(dest):
                    if os.path.exists(os.path.join(dest, '.git')):
                        needs_clone = False
                    else:
                        needs_clobber = True

            if needs_clobber:
                self.rmtree(dest)
                needs_clone = True

            if needs_clone:
                # git clone
                cmd = [git_cmd,
                       'clone',
                       remote]
                self.run_command(cmd,
                                 cwd=os.path.dirname(dest),
                                 output_timeout=1760,
                                 halt_on_failure=True,
                                 fatal_exit_code=3)

            self.run_command([git_cmd, 'status'], cwd=dest);


            # handle pull request magic
            if pr_git_revision and pr_remote:
                # Optimization opportunity: instead of fetching all remote references,
                # pull only the single commit.  I don't know how to right now

                # If the 'other' remote exists, get rid of it
                cmd = [git_cmd, 'remote']
                output = self.get_output_from_command(cmd, cwd=dest)
                for line in output.split('\n'):
                  if 'other' in line:
                    cmd = [git_cmd, 'remote', 'rm', 'other']
                    self.run_command(cmd, cwd=dest, halt_on_failure=True,
                                     fatal_exit_code=3)
                    break;
                # Set the correct remote
                cmd = [git_cmd, 'remote', 'add', 'other', pr_remote]
                self.run_command(cmd, cwd=dest, halt_on_failure=True,
                                 fatal_exit_code=3)
                if not has_needed_commit(pr_git_revision):
                    cmd = [git_cmd, 'fetch', 'other']
                    self.run_command(cmd, cwd=dest, halt_on_failure=True,
                                     fatal_exit_code=3)
                if not has_needed_commit(pr_git_revision):
                    self.fatal('Missing the Pull Request target revision')

                # With these environment variables we should have deterministic
                # merge commit identifiers
                self.info('If you want to prove that this merge commit is the same')
                self.info('you get, use this environment while doing the merge')
                env = {
                  'GIT_COMMITTER_DATE': "Wed Feb 16 14:00 2037 +0100",
                  'GIT_AUTHOR_DATE': "Wed Feb 16 14:00 2037 +0100",
                  'GIT_AUTHOR_NAME': 'automation',
                  'GIT_AUTHOR_EMAIL': 'auto@mati.on',
                  'GIT_COMMITTER_NAME': 'automation',
                  'GIT_COMMITTER_EMAIL': 'auto@mati.on'
                }
                cmd = [git_cmd, 'reset', '--hard', revision or branch]
                self.run_command(cmd, cwd=dest, halt_on_failure=True,
                                 fatal_exit_code=3)
                cmd = [git_cmd, 'clean', '-f', '-f', '-x', '-d']
                self.run_command(cmd, cwd=dest, halt_on_failure=True,
                                 fatal_exit_code=3)
                cmd = [git_cmd, 'merge', '--no-ff', pr_git_revision]
                self.run_command(cmd, cwd=dest, env=env, halt_on_failure=True,
                                 fatal_exit_code=3)
                # So that people can verify that their merge commit is identical
                cmd = [git_cmd, 'rev-parse', 'HEAD']
                self.run_command(cmd, cwd=dest, halt_on_failure=True,
                                 fatal_exit_code=3)

            else:
                # checkout git branch
                cmd = [git_cmd,
                       'checkout',
                       revision or branch]
                self.run_command(cmd, cwd=dest, halt_on_failure=True,
                                 fatal_exit_code=3)


            # verify
            for cmd in ([git_cmd, 'rev-parse', 'HEAD'], [git_cmd, 'branch']):
                self.run_command(cmd, cwd=dest, halt_on_failure=True,
                                 fatal_exit_code=3)

        else:
            # purge the repo if it already exists
            if os.path.exists(dest):
                if os.path.exists(os.path.join(dest, '.hg')):
                    # this is an hg dir, so do an hg clone
                    cmd = [self.query_exe('hg'),
                           '--config',
                           'extensions.purge=',
                           'purge']
                    if self.run_command(cmd, cwd=dest, error_list=HgErrorList):
                        self.fatal("Unable to purge %s!" % dest)
                else:
                    # there's something here, but it isn't hg; just delete it
                    self.rmtree(dest)

            repo = {
                'repo': repo_path,
                'revision': revision,
                'branch': branch,
                'dest': dest,
            }

            self.vcs_checkout_repos([repo], parent_dir=os.path.dirname(dest))

    def preflight_pull(self):
        if not self.buildbot_config:
            if not self.config.get('gaia_repo'):
                # gaia_branch by default is set to default
                self.fatal("You're trying to run this outside of buildbot, " \
                    "therefore, you need to specify --gaia-repo.")
            if not self.config.get('gaia_branch'):
                # gaia_branch by default is set to default
                self.fatal("You're trying to run this outside of buildbot, " \
                    "therefore, you need to specify --gaia-branch.")

    def extract_xre(self, xre_url, xre_path=None, parent_dir=None):
        if not xre_path:
            xre_path = self.config.get('xre_path')
        xulrunner_bin = os.path.join(parent_dir,
                                     xre_path,
                                     'bin', 'xpcshell')
        if os.access(xulrunner_bin, os.F_OK):
            return

        filename = self.download_file(xre_url, parent_dir=parent_dir)
        m = re.search('\.tar\.(bz2|gz)$', filename)
        if m:
            # a xulrunner archive, which has a top-level 'xulrunner-sdk' dir
            command = self.query_exe('tar', return_type='list')
            tar_cmd = "jxf"
            if m.group(1) == "gz":
                tar_cmd = "zxf"
            command.extend([tar_cmd, filename])
            self.run_command(command,
                             cwd=parent_dir,
                             error_list=TarErrorList,
                             halt_on_failure=True,
                             fatal_exit_code=3)
        else:
            # a tooltool xre.zip
            command = self.query_exe('unzip', return_type='list')
            command.extend(['-q', '-o', filename])
            # Gaia assumes that xpcshell is in a 'xulrunner-sdk' dir, but
            # xre.zip doesn't have a top-level directory name, so we'll
            # create it.
            parent_dir = os.path.join(parent_dir,
                                      self.config.get('xre_path'))
            if not os.access(parent_dir, os.F_OK):
                self.mkdir_p(parent_dir, error_level=FATAL)
            self.run_command(command,
                             cwd=parent_dir,
                             error_list=ZipErrorList,
                             halt_on_failure=True,
                             fatal_exit_code=3)

    def pull(self, **kwargs):
        '''
        Two ways of using this function:
        - The user specifies --gaia-repo or in a config file
        - The buildbot propeties exist and we query the gaia json url
          for the current gecko tree
        '''
        dirs = self.query_abs_dirs()
        dest = dirs['abs_gaia_dir']
        repo = {}

        if self.buildbot_config is not None:
            # get gaia commit via hgweb (gecko's gaia.json)
            repo = {
                'revision': self.buildbot_config['properties']['revision'],
                'repo_path': 'https://hg.mozilla.org/%s' % self.buildbot_config['properties']['repo_path'],
                'branch': None,
            }
        else:
            repo = {
                'repo_path': self.config['gaia_repo'],
                'revision': 'default',
                'branch': self.config['gaia_branch']
            }

        self.clone_gaia(dest, repo,
                        use_gaia_json=self.buildbot_config is not None)

    def make_gaia(self, gaia_dir, xre_dir, debug=False, noftu=True,
                  xre_url=None, build_config_path=None):
        if xre_url:
            self.extract_xre(xre_url, xre_path=xre_dir, parent_dir=gaia_dir)

        env = {'DEBUG': '1' if debug else '0',
               'NOFTU': '1' if noftu else '0',
               'DESKTOP': '0',
               'DESKTOP_SHIMS': '1',
               'USE_LOCAL_XULRUNNER_SDK': '1',
               'XULRUNNER_DIRECTORY': xre_dir
              }

        # if tbpl_build_config.json exists, load it
        if build_config_path:
            if os.path.exists(build_config_path):
                with self.opened(build_config_path) as (f, err):
                    if err:
                        self.fatal("Error while reading %s, aborting" %
                                   build_config_path)
                    else:
                        contents = f.read()
                        config = json.loads(contents)
                        env.update(config.get('env', {}))

        self.info('Sending environment as make vars because of bug 1028816')

        cmd = self.query_exe('make', return_type="list")
        for key, value in env.iteritems():
            cmd.append('%s=%s' % (key, value))
        self.run_command(cmd,
                         cwd=gaia_dir,
                         halt_on_failure=True)

    def make_node_modules(self):

        dirs = self.query_abs_dirs()

        def cleanup_node_modules():
            node_dir = os.path.join(dirs['abs_gaia_dir'], 'node_modules')
            self.rmtree(node_dir)

        self.run_command(['npm', 'cache', 'clean'])

        # get the node modules first from the node module cache, if this fails it will 
        # install the node modules from npmjs.org.
        cmd = ['taskcluster-npm-cache-get',
               '--namespace',
               'gaia.npm_cache',
               'package.json']
        kwargs = {
            'output_timeout': 300
        }
        code = self.retry(self.run_command, attempts=3, good_statuses=(0,),
                          args=[cmd, dirs['abs_gaia_dir']], cleanup=cleanup_node_modules, kwargs=kwargs)
        if code:
            self.fatal('Error occurred fetching node modules from cache',
                       exit_code=code)

        # run 'make node_modules' second, so we can separately handle
        # errors that occur here
        cmd = ['make',
               'node_modules',
               'NODE_MODULES_SRC=npm-cache',
               'VIRTUALENV_EXISTS=1']
        kwargs = {
            'output_timeout': 300,
            'error_list': self.npm_error_list
        }
        code = self.retry(self.run_command, attempts=3, good_statuses=(0,),
                          args=[cmd, dirs['abs_gaia_dir']], cleanup=cleanup_node_modules, kwargs=kwargs)
        if code:
            # Dump npm-debug.log, if it exists
            npm_debug = os.path.join(dirs['abs_gaia_dir'], 'npm-debug.log')
            if os.access(npm_debug, os.F_OK):
                self.info('dumping npm-debug.log')
                self.run_command(['cat', npm_debug])
            else:
                self.info('npm-debug.log doesn\'t exist, not dumping')
            self.fatal('Errors during \'npm install\'', exit_code=code)

        cmd = ['make',
               'update-common']
        kwargs = {
            'output_timeout': 300
        }
        code = self.retry(self.run_command, attempts=3, good_statuses=(0,),
                          args=[cmd, dirs['abs_gaia_dir']], kwargs=kwargs)
        if code:
            self.fatal('Errors during make update-common')

    def node_setup(self):
        """
        Set up environment for node-based Gaia tests.
        """
        dirs = self.query_abs_dirs()

        # Set-up node modules for project first. They must be older than 
        # the b2g build we copy into place. Otherwise the b2g build will
        # be considered an out of date target and we don't want that! It
        # can cause our desired b2g-desktop build to be overwritten!
        self.make_node_modules()

        # Copy the b2g desktop we built to the gaia directory so that it
        # gets used by the marionette-js-runner.
        b2g_dest = os.path.join(dirs['abs_gaia_dir'], 'b2g')
        self.copytree(
            os.path.join(os.path.dirname(self.binary_path)),
            b2g_dest,
            overwrite='clobber'
        )
        # Ensure modified time is more recent than node_modules!
        self.run_command(['touch', '-c', b2g_dest])