Beispiel #1
0
        def query(self, changenumber):
            """
                Run gerrit query and return the data result
            """
            cmd = self._gerritCmd(
                "query --format json --patch-sets limit:1 change:%s" %
                (changenumber, ))
            result = yield getProcessOutputAndValue(cmd[0], cmd[1:])
            (out, err, status) = result

            if status != 0:
                log.msg("forcegerritrebuild: gerrit status error: %d %s" %
                        (status, err))
                raise ValidationError("Error response from Gerrit %s" %
                                      (self.gerrit_server, ))
            try:
                out = out.strip()
                reslist = [
                    json.loads(bytes2unicode(_.strip()))
                    for _ in out.split(b"\n")
                ]

                qstatus = reslist[-1]
                if qstatus['rowCount'] != 1:
                    return None

                dataresult = reslist[0]
            except Exception as e:
                raise ValidationError(
                    "Error processing response from Gerrit: %s" % (e, ))
            return dataresult
Beispiel #2
0
 def add_missing_revisions(sourcestamps):
     for _, sourcestamp in sourcestamps.items():
         if not sourcestamp['revision']:
             # Retrieve revision from branch for sourcestamps without one
             res = yield threads.deferToThread(
                 subprocess.check_output,
                 [
                     'git', 'ls-remote', sourcestamp['repository'],
                     sourcestamp['branch']
                 ],
                 stderr=subprocess.PIPE,
             )
             try:
                 sourcestamp['revision'] = res.split()[0].decode('utf-8')
             except IndexError:
                 raise ValidationError("'%s' branch not found" %
                                       sourcestamp['branch'])
Beispiel #3
0
 def f():
     return defer.fail(ValidationError('Invalid pizza'))
Beispiel #4
0
    def force(self, owner, builderNames=None, builderid=None, **kwargs):
        """
        We check the parameters, and launch the build, if everything is correct
        """

        # Currently the validation code expects all kwargs to be lists
        # I don't want to refactor that now so much sure we comply...
        kwargs = dict((k, [v]) if not isinstance(v, list) else (k, v)
                      for k, v in kwargs.items())

        # probably need to clean that out later as the IProperty is already a
        # validation mechanism
        collector = self.LocalValidationErrorCollector()
        reason = yield collector.collectValidationErrors(
            self.reason.fullName, self.reason.getFromKwargs, kwargs)
        if owner is None or owner == "anonymous":
            owner = yield collector.collectValidationErrors(
                self.username.fullName, self.username.getFromKwargs, kwargs)

        properties, changeids, sourcestamps = yield self.gatherPropertiesAndChanges(
            collector, **kwargs)

        try:
            # Retrieve the gerrit change
            collector.setFieldName("changenumber")
            UI_changenum = str(properties.getProperty("changenumber"))

            gerritinfo = yield self.gerrit.query(UI_changenum)

            if gerritinfo is None or str(gerritinfo['number']) != UI_changenum:
                raise ValidationError("Unable to retrieve gerrit issue %s" %
                                      (UI_changenum, ))

            # Get the requested patchset
            collector.setFieldName("patchsetnumber")
            UI_patchset = properties.getProperty("patchsetnumber")
            patchsets = gerritinfo['patchSets']
            patchset = max(patchsets, key=lambda item: item['number'])

            if UI_patchset is not None and UI_patchset != '':
                patchset = None
                UI_patchset = int(UI_patchset)
                for ps in gerritinfo['patchSets']:
                    if int(ps['number']) == UI_patchset:
                        patchset = ps

                if patchset is None:
                    raise ValidationError("Invalid patchset '%d'" %
                                          (UI_patchset, ))

            # Prepare the values needed for the GerritStatusPush reporter
            collector.setFieldName("changenumber")
            branch = gerritinfo['branch']
            changeid = gerritinfo['id']
            project = gerritinfo['project']

            # Make sure there are some workers available to build this branch
            if branch not in self.branchbuilders:
                log.msg(
                    "forcegerritbuild: branch %s does not have any configured builders"
                    % (branch, ))
                raise ValidationError(
                    "Branch %s does not have any configured builders" %
                    (branch, ))

            builderNames = self.branchbuilders[branch]
            if not builderNames:
                log.msg("forcegerritbuild: empty builders for branch: %s" (
                    branch, ))
                raise ValidationError("Empty builders for branch %s" %
                                      (branch, ))

            # Set the properties neede by GerritStatusPush reporter
            properties.setProperty("event.change.id", changeid,
                                   "ForceGerritBuild")
            properties.setProperty("event.patchSet.number",
                                   str(patchset['number']), "ForceGerritBuild")
            properties.setProperty("event.change.project", project,
                                   "ForceGerritBuild")
            properties.setProperty("event.patchSet.revision",
                                   patchset['revision'], "ForceGerritBuild")

            if self.gerrit_url:
                url = self.gerrit_url % {
                    "project": project,
                    "changenumber": str(gerritinfo['number']),
                    "patchsetnumber": str(patchset['number'])
                }
                properties.setProperty("event.change.url", url,
                                       "GerritForceBuild")

        except Exception as e:
            collector.setError(str(e))

        collector.maybeRaiseCollectedErrors()

        properties.setProperty("reason", reason, "ForceGerritBuild")
        properties.setProperty("owner", owner, "ForceGerritBuild")

        reason = self.reasonString % {'owner': owner, 'reason': reason}

        # Create the sourcestamps
        sourcestamps = [{
            'codebase': '',
            'repository': '',
            'branch': patchset['ref'],
            'revision': patchset['revision'],
            'project': project
        }]
        log.msg(
            "forcegerritbuild: rebuilding branch[%s] revision[%s] project[%s] event.change.id[%s]"
            % (patchset['ref'], patchset['revision'], project, changeid))
        # everything is set and validated, we can create our source stamp, and
        # buildrequest
        res = yield self.addBuildsetForSourceStampsWithDefaults(
            reason=reason,
            sourcestamps=sourcestamps,
            properties=properties,
            builderNames=builderNames,
        )

        return res