Exemplo n.º 1
0
    def namespace_info(self):
        """
        return:
        {
            cluster_id: "BCS-K8S-15007"
            name: "helm1"
            project_id: "b37778ec757544868a01e1f01f07037f"
        }
        """
        if not self.access_token and self.ignore_empty_access_token:
            return {
                "name": self.namespace,
                "cluster_id": self.cluster_id,
                "project_id": self.project_id,
            }

        resp = paas_cc.get_namespace(self.access_token, self.project_id, self.namespace_id)
        if resp.get('code') != 0:
            logger.error(
                "查询命名空间的信息出错(namespace_id:{project_id}-{namespace_id}):{message}".format(
                    namespace_id=self.namespace_id, project_id=self.project_id, message=resp.get('message')
                )
            )
            return None

        return resp.get('data')
Exemplo n.º 2
0
    def get_ns_info(self, request, ns_id):
        result = paas_cc.get_namespace(request.user.token.access_token,
                                       request.project["project_id"], ns_id)
        if result.get("code") != 0:
            raise error_codes.APIError.f(result.get("message"), replace=True)

        return result["data"]
Exemplo n.º 3
0
    def delete(self, request, project_id, namespace_id, is_validate_perm=True):
        access_token = request.user.token.access_token

        # TODO 重构
        # namespace exist
        ns_resp = paas_cc.get_namespace(access_token, project_id, namespace_id)
        ns_data = ns_resp['data']
        if ns_resp.get('code') != ErrorCode.NoError or not ns_data:
            raise error_codes.APIError(
                f'query namespace exist error, {ns_resp.get("message")}')
        # get namespace info
        cluster_id, ns_name = ns_data.get('cluster_id'), ns_data.get('name')

        perm_ctx = NamespacePermCtx(username=request.user.username,
                                    project_id=project_id,
                                    cluster_id=cluster_id,
                                    name=ns_name)
        self.iam_perm.can_delete(perm_ctx)

        client = Namespace(access_token, project_id, request.project.kind)
        resp = client.delete(namespace_id,
                             cluster_id=cluster_id,
                             ns_name=ns_name)

        request.audit_ctx.update_fields(resource=f"{cluster_id}/{ns_name}",
                                        description=_("删除命名空间"))
        return response.Response(resp)
Exemplo n.º 4
0
 def _get_namespace_info(self, access_token, project_id, namespace_id):
     resp = paas_cc.get_namespace(access_token, project_id, namespace_id)
     if resp.get("code") != 0:
         raise error_codes.APIError(
             f"get namespace(id:{namespace_id}) info error: {resp.get('message')}"
         )
     return resp.get("data")
Exemplo n.º 5
0
    def can_use_instance(cls,
                         request,
                         project_id,
                         ns_id,
                         tmpl_set_id=None,
                         source_type=SourceType.TEMPLATE):
        # 继承命名空间的权限
        resp = paas_cc.get_namespace(request.user.token.access_token,
                                     project_id, ns_id)
        data = resp.get('data')
        perm_ctx = NamespaceScopedPermCtx(
            username=request.user.username,
            project_id=project_id,
            cluster_id=data.get('cluster_id'),
            name=data.get('name'),
        )
        NamespaceScopedPermission().can_use(perm_ctx)

        if source_type == SourceType.TEMPLATE:
            tmpl_set_info = Template.objects.filter(id=tmpl_set_id).first()
            if not tmpl_set_info:
                raise error_codes.CheckFailed(
                    f"template:{tmpl_set_id} not found")
            # 继承模板集的权限
            perm_ctx = TemplatesetPermCtx(username=request.user.username,
                                          project_id=project_id,
                                          template_id=tmpl_set_id)
            TemplatesetPermission().can_instantiate(perm_ctx)
Exemplo n.º 6
0
    def delete(self, namespace_id):
        # namespace exist
        ns_resp = paas_cc.get_namespace(self.access_token, self.project_id,
                                        namespace_id)
        ns_data = ns_resp['data']
        if ns_resp.get('code') != ErrorCode.NoError or not ns_data:
            raise error_codes.APIError(
                f'query namespace exist error, {ns_resp.get("message")}')
        # get namespace info
        cluster_id, ns_name = ns_data.get('cluster_id'), ns_data.get('name')

        self.client.delete(self.access_token, self.project_id, cluster_id,
                           ns_name)
        # delete db resource record
        InstanceConfig.objects.filter(namespace=namespace_id).delete()
        NameSpaceVariable.objects.filter(ns_id=namespace_id).delete()

        # delete bcs cc record
        ns_resp = paas_cc.delete_namespace(self.access_token, self.project_id,
                                           cluster_id, namespace_id)
        if ns_resp.get('code') != ErrorCode.NoError:
            raise error_codes.APIError(
                f'delete bcs cc namespace error, {ns_resp.get("message")}')

        return ns_resp
Exemplo n.º 7
0
    def validate_view_perms(self,
                            request,
                            project_id,
                            muster_id,
                            ns_id,
                            source_type="模板集"):
        """查询资源时, 校验用户的查询权限"""
        resp = paas_cc.get_namespace(request.user.token.access_token,
                                     project_id, ns_id)
        data = resp.get('data')
        perm_ctx = NamespaceScopedPermCtx(
            username=request.user.username,
            project_id=project_id,
            cluster_id=data.get('cluster_id'),
            name=data.get('name'),
        )
        NamespaceScopedPermission().can_view(perm_ctx)

        if source_type == "模板集":
            muster_info = Template.objects.filter(id=muster_id,
                                                  is_deleted=False).first()
            if not muster_info:
                raise error_codes.CheckFailed(_("没有查询到模板集信息"))
            perm_ctx = TemplatesetPermCtx(username=request.user.username,
                                          project_id=project_id,
                                          template_id=muster_id)
            TemplatesetPermission().can_view(perm_ctx)
Exemplo n.º 8
0
    def bcs_single_app_perm_handler(self,
                                    request,
                                    project_id,
                                    muster_id,
                                    ns_id,
                                    source_type="模板集"):
        """针对具体资源的权限处理"""
        # 继承命名空间的权限
        resp = paas_cc.get_namespace(request.user.token.access_token,
                                     project_id, ns_id)
        data = resp.get('data')
        perm_ctx = NamespaceScopedPermCtx(
            username=request.user.username,
            project_id=project_id,
            cluster_id=data.get('cluster_id'),
            name=data.get('name'),
        )
        NamespaceScopedPermission().can_use(perm_ctx)

        if source_type == "模板集":
            muster_info = Template.objects.filter(id=muster_id,
                                                  is_deleted=False).first()
            if not muster_info:
                raise error_codes.CheckFailed(_("没有查询到模板集信息"))
            # 继承模板集的权限
            perm_ctx = TemplatesetPermCtx(username=request.user.username,
                                          project_id=project_id,
                                          template_id=muster_id)
            TemplatesetPermission().can_instantiate(perm_ctx)
Exemplo n.º 9
0
    def get_ns_info_by_id(self, namespace_id):
        result = paas_cc.get_namespace(self.access_token, self.project_id, namespace_id)
        if result.get('code') != 0:
            raise error_codes.APIError.f(result.get('message', ''))

        namespace_info = result["data"]
        return namespace_info
Exemplo n.º 10
0
 def get_ns(self, request, project_id, namespace_id):
     """获取单个命名空间的信息
     """
     access_token = request.user.token.access_token
     result = paas_cc.get_namespace(access_token, project_id, namespace_id)
     if result.get('code') != 0:
         raise error_codes.APIError.f(result.get('message', ''))
     return response.Response(result)
Exemplo n.º 11
0
    def preview_or_apply(self, request, project_id, template_id,
                         show_version_id):
        """
        request.data = {
            'is_preview': True,
            'namespace_id': 'test',
            'template_files': [{
                'resource_name': 'Deployment',
                'files': [{'name': 'nginx.yaml', 'id': 3}]
            }],
            'template_variables': {}
        }
        """
        data = self._request_data(request,
                                  project_id=project_id,
                                  template_id=template_id,
                                  show_version_id=show_version_id)
        serializer = serializers.TemplateReleaseSLZ(data=data)
        serializer.is_valid(raise_exception=True)
        validated_data = serializer.validated_data

        template = validated_data["show_version"]["template"]
        self.can_use_template(request, template)

        resp = paas_cc.get_namespace(request.user.token.access_token,
                                     project_id,
                                     validated_data["namespace_id"])
        if resp.get('code') != 0:
            return Response({
                'code':
                400,
                'message':
                f"查询命名空间(namespace_id:{project_id}-{validated_data['namespace_id']})出错:{resp.get('message')}",
            })

        namespace_info = resp['data']
        perm_ctx = NamespaceScopedPermCtx(
            username=request.user.username,
            project_id=project_id,
            cluster_id=namespace_info['cluster_id'],
            name=namespace_info['name'],
        )
        NamespaceScopedPermission().can_use(perm_ctx)

        processor = ReleaseDataProcessor(
            user=self.request.user,
            raw_release_data=self._raw_release_data(project_id,
                                                    validated_data))
        release_data = processor.release_data()

        if validated_data["is_preview"]:
            return Response(release_data.template_files)

        controller = DeployController(user=self.request.user,
                                      release_data=release_data)
        controller.apply()

        return Response()
Exemplo n.º 12
0
def get_namespace_name(access_token, project_id, data_dict):
    """获取命名空间名称"""
    ns_id = data_dict.get('namespace_id') or data_dict.get('namespace')
    if ns_id != -1:
        ns_resp = paas_cc.get_namespace(access_token, project_id, ns_id)
        namespace = ns_resp.get('data', {}).get('name')
    else:
        namespace = MESOS_LB_NAMESPACE
    return namespace
Exemplo n.º 13
0
    def get_namespace_info(self, request, project_id, ns_id):
        """获取单个namespace"""
        resp = paas_cc.get_namespace(request.user.token.access_token, project_id, ns_id)
        if resp.get("code") != ErrorCode.NoError:
            return False, APIResponse({"code": resp.get("code") or DEFAULT_ERROR_CODE, "message": resp.get("message")})
        if not resp.get("data"):
            return False, APIResponse({"code": 400, "message": _("查询记录为空!")})

        return True, resp["data"]
Exemplo n.º 14
0
    def delete(self, request, project_id, namespace_id, is_validate_perm=True):
        """删除集群
        """
        access_token = request.user.token.access_token

        # 检查权限
        perm = bcs_perm.Namespace(request, project_id, namespace_id)
        perm.can_delete(raise_exception=is_validate_perm)

        access_token = request.user.token.access_token
        ns_result = paas_cc.get_namespace(access_token, project_id,
                                          namespace_id)
        if ns_result.get('code') != 0:
            raise error_codes.APIError.f(ns_result.get('message', ''))
        ns_data = ns_result.get('data')
        cluster_id = ns_data.get('cluster_id')
        name = ns_data.get('name')

        project_kind = request.project.kind
        if project_kind == K8S_PROJECT_KIND:
            client = K8SClient(access_token, project_id, cluster_id, env=None)
        elif project_kind == MESOS_PROJECT_KIND:
            client = MesosClient(access_token,
                                 project_id,
                                 cluster_id,
                                 env=None)
        else:
            raise ValidationError("项目编排类型不正确")

        # 删除 namespace
        result = client.delete_namespace(name)
        if result.get('code') != 0:
            raise error_codes.ComponentError.f("删除Namespace失败,%s, 请联系管理员解决" %
                                               result.get('message'))

        result = paas_cc.delete_namespace(access_token, project_id,
                                          namespace_id)
        if result.get('code') != 0:
            raise error_codes.APIError.f(result.get('message'))

        # 删除资源
        perm.delete()

        return response.Response(result)
Exemplo n.º 15
0
def get_ns_variable(access_token, project_id, namespace_id):
    """获取命名空间相关的变量信息"""
    context = {}
    # 获取命名空间的信息
    resp = paas_cc.get_namespace(access_token, project_id, namespace_id)
    if resp.get('code') != 0:
        raise ValidationError('{}(namespace_id:{}):{}'.format(_("查询命名空间的信息出错"), namespace_id, resp.get('message')))
    data = resp.get('data')
    cluster_id = data.get('cluster_id')
    context['SYS_CLUSTER_ID'] = cluster_id
    context['SYS_NAMESPACE'] = data.get('name')
    has_image_secret = data.get('has_image_secret')
    # 获取镜像地址
    context['SYS_JFROG_DOMAIN'] = paas_cc.get_jfrog_domain(access_token, project_id, context['SYS_CLUSTER_ID'])
    context['SYS_IMAGE_REGISTRY_LIST'] = paas_cc.get_image_registry_list(access_token, cluster_id)
    bcs_context = get_bcs_context(access_token, project_id)
    context.update(bcs_context)
    # k8s 集群获取集群版本信息
    cluster_version = get_cluster_version(access_token, project_id, cluster_id)
    return has_image_secret, cluster_version, context
Exemplo n.º 16
0
def collect_system_variable(access_token, project_id, namespace_id):
    sys_variables = {}

    # 获取标准日志采集的dataid
    data_info = get_data_id_by_project_id(project_id)
    sys_variables['SYS_STANDARD_DATA_ID'] = data_info.get('standard_data_id')
    sys_variables['SYS_NON_STANDARD_DATA_ID'] = data_info.get('non_standard_data_id')

    resp = paas_cc.get_project(access_token, project_id)
    if resp.get('code') != 0:
        logger.error(
            "查询project的信息出错(project_id:{project_id}):{message}".format(
                project_id=project_id, message=resp.get('message')
            )
        )
    project_info = resp["data"]
    sys_variables["SYS_CC_APP_ID"] = project_info["cc_app_id"]
    sys_variables['SYS_PROJECT_KIND'] = project_info["kind"]
    sys_variables['SYS_PROJECT_CODE'] = project_info["english_name"]

    resp = paas_cc.get_namespace(access_token, project_id, namespace_id)
    if resp.get('code') != 0:
        logger.error(
            "查询命名空间的信息出错(namespace_id:{project_id}-{namespace_id}):{message}".format(
                namespace_id=namespace_id, project_id=project_id, message=resp.get('message')
            )
        )
    namespace_info = resp["data"]

    sys_variables["SYS_NAMESPACE"] = namespace_info["name"]
    sys_variables["SYS_CLUSTER_ID"] = namespace_info["cluster_id"]
    sys_variables["SYS_PROJECT_ID"] = namespace_info["project_id"]
    # SYS_JFROG_DOMAIN
    # SYS_NON_STANDARD_DATA_ID

    # 获取镜像地址
    jfrog_domain = paas_cc.get_jfrog_domain(access_token, project_id, sys_variables['SYS_CLUSTER_ID'])
    sys_variables['SYS_JFROG_DOMAIN'] = jfrog_domain

    return sys_variables
Exemplo n.º 17
0
    def get_ns_variable(self):
        """获取命名空间相关的变量信息"""
        # 获取命名空间的信息
        resp = paas_cc.get_namespace(self.access_token, self.project_id,
                                     self.namespace_id)
        if resp.get("code") != 0:
            raise ValidationError("{}(namespace_id:{}):{}".format(
                _("查询命名空间的信息出错"), self.namespace_id, resp.get("message")))
        data = resp.get("data")
        self.context["SYS_CLUSTER_ID"] = data.get("cluster_id")
        self.context["SYS_NAMESPACE"] = data.get("name")
        self.has_image_secret = data.get("has_image_secret")
        # 获取镜像地址
        self.context["SYS_JFROG_DOMAIN"] = paas_cc.get_jfrog_domain(
            self.access_token, self.project_id, self.context["SYS_CLUSTER_ID"])

        self.context[
            "SYS_IMAGE_REGISTRY_LIST"] = paas_cc.get_image_registry_list(
                self.access_token, self.context["SYS_CLUSTER_ID"])

        bcs_context = get_bcs_context(self.access_token, self.project_id)
        self.context.update(bcs_context)
Exemplo n.º 18
0
def get_ns_variable(access_token, project_id, namespace_id):
    """获取命名空间相关的变量信息
    """
    context = {}
    # 获取命名空间的信息
    resp = paas_cc.get_namespace(access_token, project_id, namespace_id)
    if resp.get('code') != 0:
        raise ValidationError(u"查询命名空间的信息出错(namespace_id:%s):%s" %
                              (namespace_id, resp.get('message')))
    data = resp.get('data')
    cluster_id = data.get('cluster_id')
    context['SYS_CLUSTER_ID'] = cluster_id
    context['SYS_NAMESPACE'] = data.get('name')
    has_image_secret = data.get('has_image_secret')
    # 获取镜像地址
    jfrog_domain = paas_cc.get_jfrog_domain(access_token, project_id,
                                            context['SYS_CLUSTER_ID'])
    context['SYS_JFROG_DOMAIN'] = jfrog_domain

    bcs_context = get_bcs_context(access_token, project_id)
    context.update(bcs_context)
    # k8s 集群获取集群版本信息
    cluster_version = get_cluster_version(access_token, project_id, cluster_id)
    return has_image_secret, cluster_version, context
Exemplo n.º 19
0
def get_namespace_by_id(access_token, project_id, namespace_id):
    return paas_cc.get_namespace(access_token, project_id, namespace_id)
Exemplo n.º 20
0
def get_namespace_by_id(access_token, project_id, namespace_id):
    resp = paas_cc.get_namespace(access_token, project_id, namespace_id)
    if resp.get('code') != ErrorCode.NoError:
        raise error_codes.APIError(
            f"get namespace error, {resp.get('message')}")
    return resp.get("data") or {}
Exemplo n.º 21
0
    def preview_config(self, request, project_id):
        project_kind = request.project.kind
        serializer = PreviewInstanceSLZ(data=request.data,
                                        context={'project_kind': project_kind})
        serializer.is_valid(raise_exception=True)
        slz_data = serializer.data

        # 验证 version_id 是否属于该项目
        version_id = slz_data['version_id']
        show_version_id = slz_data['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)

        template_id = version_entity.template_id
        version = version_entity.version
        tem_instance_entity = version_entity.get_version_instance_resource_ids

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

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

        namespace_id = slz_data['namespace']
        lb_info = slz_data.get('lb_info', {})

        resp = paas_cc.get_namespace(access_token, project_id, namespace_id)
        if resp.get('code') != 0:
            return Response({
                'code':
                400,
                'message':
                f"查询命名空间(namespace_id:{project_id}-{namespace_id})出错:{resp.get('message')}",
            })

        namespace_info = resp['data']
        perm_ctx = NamespaceScopedPermCtx(
            username=username,
            project_id=project_id,
            cluster_id=namespace_info['cluster_id'],
            name=namespace_info['name'],
        )
        NamespaceScopedPermission().can_use(perm_ctx)

        # 查询当前命名空间的变量信息
        variable_dict = slz_data.get('variable_info',
                                     {}).get(namespace_id) or {}
        params = {
            "instance_id": "instanceID",
            "version_id": version_id,
            "show_version_id": show_version_id,
            "template_id": template_id,
            "version": version,
            "project_id": project_id,
            "access_token": access_token,
            "username": username,
            "lb_info": lb_info,
            "variable_dict": variable_dict,
            "is_preview": True,
        }
        data = preview_config_json(namespace_id, instance_entity, **params)
        return Response({"code": 0, "message": "OK", "data": data})
Exemplo n.º 22
0
 def get_namespace_info(self, namespace_id):
     namespace = paas_cc.get_namespace(self.access_token, self.project_id,
                                       namespace_id)
     cluster_id = namespace['data']['cluster_id']
     namespace_name = namespace['data']['name']
     return cluster_id, namespace_name