Exemplo n.º 1
0
    def get(self, api_version, id):
        id_flag = request.args.get("id")
        if id_flag:
            endpoint = request.endpoint.split("s_list")[0]
            raise ValidationError(
                'The "id" query option is invalid. Did you mean to go to "{0}"?'
                .format(url_for(endpoint, api_version=api_version,
                                id=id_flag)))
        verbose_flag = request.args.get("verbose", "false").lower()
        short_flag = request.args.get("short", "false").lower()
        json_func_kwargs = {}
        json_func_name = "json"

        if id is None:
            # Lists all tracked builds
            p_query = self.query_filter(request)
            json_data = {
                "meta": pagination_metadata(p_query, api_version, request.args)
            }

            if verbose_flag == "true" or verbose_flag == "1":
                json_func_name = "extended_json"
                json_func_kwargs["show_state_url"] = True
                json_func_kwargs["api_version"] = api_version
            elif short_flag == "true" or short_flag == "1":
                if p_query.items and hasattr(p_query.items[0], "short_json"):
                    json_func_name = "short_json"
            if json_func_name == "json" or json_func_name == "extended_json":
                # Only ModuleBuild.json and ModuleBuild.extended_json has argument db_session
                json_func_kwargs["db_session"] = db.session
            json_data["items"] = [
                getattr(item, json_func_name)(**json_func_kwargs)
                for item in p_query.items
            ]

            return jsonify(json_data), 200
        else:
            # Lists details for the specified build
            instance = self.model.query.filter_by(id=id).first()
            if instance:
                if verbose_flag == "true" or verbose_flag == "1":
                    json_func_name = "extended_json"
                    json_func_kwargs["show_state_url"] = True
                    json_func_kwargs["api_version"] = api_version
                elif short_flag == "true" or short_flag == "1":
                    if getattr(instance, "short_json", None):
                        json_func_name = "short_json"
                if json_func_name == "json" or json_func_name == "extended_json":
                    # Only ModuleBuild.json and ModuleBuild.extended_json has argument db_session
                    json_func_kwargs["db_session"] = db.session
                return jsonify(
                    getattr(instance, json_func_name)(**json_func_kwargs)), 200
            else:
                raise NotFound("No such %s found." % self.kind)
Exemplo n.º 2
0
    def post(self, api_version):
        # disable this API endpoint if no groups are defined
        if not conf.allowed_groups_to_import_module:
            log.error(
                "Import module API is disabled. Set 'ALLOWED_GROUPS_TO_IMPORT_MODULE'"
                " configuration value first.")
            raise Forbidden("Import module API is disabled.")

        # auth checks
        username, groups = module_build_service.web.auth.get_user(request)
        ModuleBuildAPI.check_groups(
            username,
            groups,
            allowed_groups=conf.allowed_groups_to_import_module)

        # process request using SCM handler
        handler = SCMHandler(request)
        handler.validate(skip_branch=True, skip_optional_params=True)

        mmd, _ = fetch_mmd(handler.data["scmurl"], mandatory_checks=False)
        build, messages = import_mmd(db.session, mmd)
        json_data = {
            "module": build.json(db.session, show_tasks=False),
            "messages": messages
        }

        # return 201 Created if we reach this point
        return jsonify(json_data), 201
Exemplo n.º 3
0
    def get(self, api_version):
        items = []
        # Sort the items list by name
        for strategy in sorted(models.ModuleBuild.rebuild_strategies.keys()):
            default = False
            if strategy == conf.rebuild_strategy:
                default = True
                allowed = True
            elif (conf.rebuild_strategy_allow_override
                  and strategy in conf.rebuild_strategies_allowed):
                allowed = True
            else:
                allowed = False
            items.append({
                "name":
                strategy,
                "description":
                models.ModuleBuild.rebuild_strategies[strategy],
                "allowed":
                allowed,
                "default":
                default,
            })

        return jsonify({"items": items}), 200
Exemplo n.º 4
0
    def patch(self, api_version, id):
        username, groups = module_build_service.web.auth.get_user(request)

        try:
            r = json.loads(request.get_data().decode("utf-8"))
        except Exception:
            log.exception("Invalid JSON submitted")
            raise ValidationError("Invalid JSON submitted")

        if "owner" in r:
            if conf.no_auth is not True:
                raise ValidationError(
                    "The request contains 'owner' parameter, however NO_AUTH is not allowed"
                )
            elif username == "anonymous":
                username = r["owner"]

        self.check_groups(username, groups)

        module = models.ModuleBuild.query.filter_by(id=id).first()
        if not module:
            raise NotFound("No such module found.")

        if module.owner != username and not (conf.admin_groups & groups):
            raise Forbidden(
                "You are not owner of this build and therefore cannot modify it."
            )

        if not r.get("state"):
            log.error("Invalid JSON submitted")
            raise ValidationError("Invalid JSON submitted")

        state = r["state"]
        valid_input_states = ("failed", str(models.BUILD_STATES["failed"]))
        if state not in valid_input_states:
            raise ValidationError(
                "An invalid state was submitted. Valid states values are: {}".
                format(", ".join(valid_input_states)))

        valid_states_to_cancel = ("build", "init", "wait")
        module_state_name = models.INVERSE_BUILD_STATES[module.state]
        if module_state_name not in valid_states_to_cancel:
            log.error(
                "The user %s attempted to cancel a build in the %s state",
                username,
                module_state_name,
            )
            raise ValidationError(
                "To cancel a module build, it must be in one of the following states: {}"
                .format(", ".join(valid_states_to_cancel)))

        module.transition(db.session, conf, models.BUILD_STATES["failed"],
                          "Canceled by %s." % username)
        db.session.add(module)
        db.session.commit()

        return jsonify(module.extended_json(db.session, True,
                                            api_version)), 200
Exemplo n.º 5
0
 def get(self, api_version):
     json = {"version": version, "api_version": max_api_version}
     config_items = ["auth_method"]
     for item in config_items:
         config_item = getattr(conf, item)
         # All config items have a default, so if doesn't exist it is a programming error
         if not config_item:
             raise ProgrammingError(
                 'An invalid config item of "{0}" was specified'.format(
                     item))
         json[item] = config_item
     return jsonify(json), 200
Exemplo n.º 6
0
    def get(self, api_version, id):

        module = models.ModuleBuild.get_by_id(db.session, id)
        if not module:
            raise ValidationError("The module could not be found")

        if conf.system == "koji":
            # We are importing KojiContentGenerator here so we can generate the final modulemds.
            # If we imported this regularly we would have gotten a circular import error.
            from module_build_service.builder.KojiContentGenerator import KojiContentGenerator  # noqa
            cg = KojiContentGenerator(module, conf)
            finalmmds = cg.get_final_mmds()
        else:
            raise ValidationError(
                "Configured builder not able to generate final modulemds!")

        return jsonify(finalmmds), 200
Exemplo n.º 7
0
    def get(self, api_version, id, model):

        if not model:
            raise ValidationError(
                "Model is not set for this log messages endpoint")

        query = model.query.filter_by(id=id).first().log_messages.order_by(
            models.LogMessage.time_created.desc())

        page = request.args.get("page", 1, type=int)
        per_page = request.args.get("per_page", 10, type=int)
        p_query = query.paginate(page, per_page, False)

        request_args = {"id": id}
        json_data = {
            "meta": pagination_metadata(p_query, api_version, request_args)
        }
        json_data["messages"] = [
            getattr(message, "json")() for message in p_query.items
        ]

        return jsonify(json_data), 200
Exemplo n.º 8
0
    def post(self, api_version):
        data = _dict_from_request(request)
        if "modulemd" in data or (hasattr(request, "files")
                                  and "yaml" in request.files):
            handler = YAMLFileHandler(request, data)
        else:
            handler = SCMHandler(request, data)

        if conf.no_auth is True and handler.username == "anonymous" and "owner" in handler.data:
            handler.username = handler.data["owner"]

        self.check_groups(handler.username, handler.groups)

        handler.validate()
        modules = handler.post()
        if api_version == 1:
            # Only show the first module build for backwards-compatibility
            rv = modules[0].extended_json(db.session, True, api_version)
        else:
            rv = [
                module.extended_json(db.session, True, api_version)
                for module in modules
            ]
        return jsonify(rv), 201
Exemplo n.º 9
0
def json_error(status, error, message):
    response = jsonify({"status": status, "error": error, "message": message})
    response.status_code = status
    return response