Exemple #1
0
    def create_release(self, release_data):
        release_result = instantiate_resources(self.access_token,
                                               self.username,
                                               release_data,
                                               project_kind=self.project_kind)

        template_name = release_data["template_name"]

        log_params = {
            "project_id": release_data["project_id"],
            "user": self.username,
            "resource": template_name,
            "resource_id": release_data["template_id"],
            "extra": {
                "variable_info": release_data["variable_info"],
                "instance_entity": release_data["instance_entity"],
                "ns_list": release_data["ns_list"],
            },
            'activity_type': ActivityType.Add,
        }

        # only one namespace
        if release_result["success"]:
            ret = release_result["success"][0]
            release_id = ret["instance_id"]
            log_params["description"] = "实例化模板集[{}]到命名空间[{}]".format(
                template_name, ret["ns_name"])
            log_params['activity_status'] = ActivityStatus.Succeed
            TemplatesetAuditor(AuditContext(**log_params)).log_raw()
            return release_id

        ret = release_result["failed"][0]
        release_id = ret["instance_id"]
        if ret["res_type"]:
            description = "实例化模板集[{template_name}]到命名空间[{namespace}]时,实例化{res_name}失败," "错误消息:{err_msg}".format(
                template_name=template_name,
                namespace=ret["ns_name"],
                res_name=ret["res_type"],
                err_msg=ret["err_msg"])
        else:
            description = "实例化模板集[{template_name}]到命名空间[{namespace}]失败,错误消息:{err_msg}".format(
                template_name=template_name,
                namespace=ret["ns_name"],
                err_msg=ret["err_msg"])

        log_params["description"] = description
        log_params['activity_status'] = ActivityStatus.Failed
        TemplatesetAuditor(AuditContext(**log_params)).log_raw()
        return release_id
Exemple #2
0
    def update_release(self, release_data):
        project_id = release_data["project_id"]
        namespace_id = release_data["namespace_id"]
        namespace_info = get_namespace_by_id(self.access_token, project_id,
                                             namespace_id)

        release_id = release_data["release_id"]
        log_params = {
            "project_id": project_id,
            "user": self.username,
            "resource": release_data["name"],
            "resource_id": release_id,
            "extra": {
                "namespace": namespace_info["name"],
                "variable_info": release_data["variable_info"]
            },
            'activity_type': ActivityType.Modify,
        }
        try:
            update_resources(self.access_token, self.username, release_data,
                             namespace_info)
        except Exception as e:
            log_params["description"] = f"rollupdate failed: {e}"
            log_params['activity_status'] = ActivityStatus.Failed
            InstanceAuditor(AuditContext(**log_params)).log_raw()
            update_inst_params = {"ins_state": InsState.UPDATE_FAILED.value}
        else:
            log_params["description"] = f"rollupdate success"
            log_params['activity_status'] = ActivityStatus.Succeed
            InstanceAuditor(AuditContext(**log_params)).log_raw()
            update_inst_params = {"ins_state": InsState.UPDATE_SUCCESS.value}

        update_inst_params.update({
            "oper_type": ROLLING_UPDATE_INSTANCE,
            "variables": release_data["variable_info"].get(namespace_id) or {}
        })

        InstanceConfig.objects.filter(
            instance_id=release_id,
            category=release_data["resource_name"],
            name=release_data["name"],
            namespace=namespace_id,
        ).update(**update_inst_params)

        return release_id
Exemple #3
0
def update_template_with_perm_check(request, template, tmpl_args):
    validate_template_locked(template, request.user.username)
    # 验证用户是否有编辑权限
    perm = bcs_perm.Templates(request, template.project_id, template.id, template.name)
    perm.can_edit(raise_exception=True)

    audit_ctx = AuditContext(user=request.user.username, project_id=template.project_id)
    template = update_template(audit_ctx, request.user.username, template, tmpl_args)
    if template.name != tmpl_args.get('name'):
        perm.update_name(template.name)
    return template
Exemple #4
0
def create_template_with_perm_check(request, project_id, tmpl_args):
    # 验证用户是否有创建的权限
    perm = bcs_perm.Templates(request, project_id, bcs_perm.NO_RES)
    # 如果没有权限,会抛出异常
    perm.can_create(raise_exception=True)

    audit_ctx = AuditContext(user=request.user.username, project_id=project_id)
    template = create_template(audit_ctx, request.user.username, project_id, tmpl_args)
    # 注册资源到权限中心
    perm.register(template.id, tmpl_args['name'])
    return template
Exemple #5
0
def update_template_with_perm_check(request, template, tmpl_args):
    validate_template_locked(template, request.user.username)

    # 验证用户是否有编辑权限
    perm_ctx = TemplatesetPermCtx(username=request.user.username,
                                  project_id=template.project_id,
                                  template_id=template.id)
    TemplatesetPermission().can_update(perm_ctx)

    audit_ctx = AuditContext(user=request.user.username,
                             project_id=template.project_id)
    template = update_template(audit_ctx, request.user.username, template,
                               tmpl_args)
    return template
Exemple #6
0
    def has_permission(self, request, view):
        project_id_or_code = view.kwargs.get('project_id') or view.kwargs.get(
            'project_id_or_code')
        project = self._get_enabled_project(request.user.token.access_token,
                                            project_id_or_code)
        if project:
            request.project = project
            self._set_ctx_project_cluster(request, project.project_id,
                                          view.kwargs.get('cluster_id', ''))
            # 设置操作审计 context
            request.audit_ctx = AuditContext(user=request.user.username,
                                             project_id=project.project_id)
            return True

        return False
Exemple #7
0
def create_template_with_perm_check(request, project_id, tmpl_args):
    permission = TemplatesetPermission()
    perm_ctx = TemplatesetPermCtx(username=request.user.username,
                                  project_id=project_id)
    permission.can_create(perm_ctx)

    audit_ctx = AuditContext(user=request.user.username, project_id=project_id)
    template = create_template(audit_ctx, request.user.username, project_id,
                               tmpl_args)

    permission.grant_resource_creator_actions(
        TemplatesetCreatorAction(template_id=str(template.id),
                                 name=template.name,
                                 project_id=project_id,
                                 creator=request.user.username), )

    return template
 def create(self, request, project_id):
     install_chart(
         AuditContext(user=request.user.username, project_id=project_id))
     return Response()
def install_chart(audit_ctx: AuditContext):
    audit_ctx.update_fields(
        description=f'test {ActivityType.Add} {ResourceType.HelmApp}',
        extra={'chart': 'http://example.chart.com/nginx/nginx1.12.tgz'},
    )
Exemple #10
0
    def post(self, request, project_id):
        """实例化模板"""
        self.project_id = project_id
        version_id = request.data.get('version_id')
        show_version_id = request.data.get('show_version_id')

        template, version_entity = validate_version_id(
            project_id,
            version_id,
            is_return_all=True,
            show_version_id=show_version_id)
        # 验证用户是否有模板集实例化权限
        perm_ctx = TemplatesetPermCtx(username=request.user.username,
                                      project_id=project_id,
                                      template_id=template.id)
        TemplatesetPermission().can_instantiate(perm_ctx)

        self.template_id = version_entity.template_id
        tem_instance_entity = version_entity.get_version_instance_resource_ids

        project_kind = request.project.kind
        self.slz = VersionInstanceCreateOrUpdateSLZ(
            data=request.data, context={'project_kind': project_kind})
        self.slz.is_valid(raise_exception=True)
        slz_data = self.slz.data

        # 验证前端传过了的预览资源是否在该版本的资源
        req_instance_entity = slz_data.get('instance_entity') or {}
        self.instance_entity = validate_instance_entity(
            req_instance_entity, tem_instance_entity)

        namespaces = slz_data['namespaces']
        ns_list = namespaces.split(',') if namespaces else []

        access_token = self.request.user.token.access_token
        username = self.request.user.username

        # 判断 template 下 前台传过来的 namespace 是否已经实例化过
        res, ns_name_list, namespace_dict = validate_ns_by_tempalte_id(
            self.template_id, ns_list, access_token, project_id,
            req_instance_entity)
        if not res:
            return Response({
                "code":
                400,
                "message":
                _("以下命名空间已经实例化过,不能再实例化\n{}").format("\n".join(ns_name_list)),
                "data":
                ns_name_list,
            })

        slz_data['ns_list'] = ns_list
        slz_data['instance_entity'] = self.instance_entity
        slz_data['template_id'] = self.template_id
        slz_data['project_id'] = project_id
        slz_data['version_id'] = version_id
        slz_data['show_version_id'] = show_version_id

        result = handle_all_config(slz_data,
                                   access_token,
                                   username,
                                   project_kind=request.project.kind)
        instance_entity = slz_data.get("instance_entity")
        all_tmpl_name_dict = self.get_tmpl_name(instance_entity)

        # 添加操作记录
        temp_name = version_entity.get_template_name()
        for i in result['success']:
            TemplatesetAuditor(audit_ctx=AuditContext(
                project_id=project_id,
                user=username,
                resource=temp_name,
                resource_id=self.template_id,
                extra=self.instance_entity,
                description=_("实例化模板集[{}]命名空间[{}]").format(
                    temp_name, i['ns_name']),
                activity_type=ActivityType.Add,
                activity_status=ActivityStatus.Succeed,
            )).log_raw()

        failed_ns_name_list = []
        failed_msg = []
        is_show_failed_msg = False
        # 针对createError的触发后台任务轮训
        if result.get('failed'):
            check_instance_status.delay(
                request.user.token.access_token,
                project_id,
                request.project.get("kind"),
                all_tmpl_name_dict,
                result['failed'],
            )
        for i in result['failed']:
            if i['res_type']:
                description = _("实例化模板集[{}]命名空间[{}],在实例化{}时失败,错误消息:{}").format(
                    temp_name, i['ns_name'], i['res_type'], i['err_msg'])
                failed_ns_name_list.append(
                    _("{}(实例化{}时)").format(i['ns_name'], i['res_type']))
            else:
                description = _("实例化模板集[{}]命名空间[{}]失败,错误消息:{}").format(
                    temp_name, i['ns_name'], i['err_msg'])
                failed_ns_name_list.append(i['ns_name'])
                if i.get('show_err_msg'):
                    failed_msg.append(i['err_msg'])
                    is_show_failed_msg = True

            TemplatesetAuditor(audit_ctx=AuditContext(
                project_id=project_id,
                user=username,
                resource=temp_name,
                resource_id=self.template_id,
                extra=self.instance_entity,
                description=description,
                activity_type=ActivityType.Add,
                activity_status=ActivityStatus.Failed,
            )).log_raw()

            if is_show_failed_msg:
                msg = '\n'.join(failed_msg)
            else:
                msg = _("以下命名空间实例化失败,\n{},请联系集群管理员解决").format(
                    "\n".join(failed_ns_name_list))
            if failed_ns_name_list:
                return Response({
                    "code": 400,
                    "message": msg,
                    "data": failed_ns_name_list
                })

        return Response({
            "code": 0,
            "message": "OK",
            "data": {
                "version_id": version_id,
                "template_id": self.template_id,
            },
        })
Exemple #11
0
def install_chart(audit_ctx: AuditContext):
    audit_ctx.update_fields(
        description='test install helm',
        extra={'chart': 'http://example.chart.com/nginx/nginx1.12.tgz'})