Exemple #1
0
    def get(self, request, project_id):
        """获取项目下所有的secrets"""
        params = dict(request.GET.items())
        is_decode = str2bool(request.GET.get('decode'))

        cluster_id = params['cluster_id']

        code, cluster_secrets = self.get_secrets_by_cluster_id(request, params, project_id, cluster_id)
        if code != ErrorCode.NoError:
            return Response({'code': code, 'message': cluster_secrets})

        self.handle_data(
            cluster_secrets,
            self.cate,
            cluster_id,
            is_decode,
            namespace_dict=app_utils.get_ns_id_map(request.user.token.access_token, project_id),
        )

        # 按时间倒序排列
        cluster_secrets.sort(key=lambda x: x.get('createTime', ''), reverse=True)

        return PermsResponse(
            cluster_secrets,
            NamespaceRequest(project_id=project_id, cluster_id=cluster_id),
        )
Exemple #2
0
    def get(self, request, project_id):
        """获取项目下的所有Ingress"""
        cluster_id = request.query_params.get("cluster_id")

        code, cluster_ingress = self.get_ingress_by_cluser_id(
            request, {}, project_id, cluster_id)
        # 单个集群错误时,不抛出异常信息
        if code != ErrorCode.NoError:
            return Response({'code': code, 'message': cluster_ingress})

        self.handle_data(
            cluster_ingress,
            self.cate,
            cluster_id,
            False,
            namespace_dict=app_utils.get_ns_id_map(
                request.user.token.access_token, project_id),
        )

        # 按时间倒序排列
        cluster_ingress.sort(key=lambda x: x.get('createTime', ''),
                             reverse=True)

        return PermsResponse(
            cluster_ingress,
            NamespaceRequest(project_id=project_id, cluster_id=cluster_id))
Exemple #3
0
    def get(self, request, project_id):
        """ 获取项目下所有的ConfigMap """
        cluster_dicts = self.get_project_cluster_info(request, project_id)
        cluster_data = cluster_dicts.get('results', {}) or {}

        data = []
        params = dict(request.GET.items())
        is_decode = request.GET.get('decode')
        is_decode = True if is_decode == '1' else False
        # get project namespace info
        namespace_dict = app_utils.get_ns_id_map(
            request.user.token.access_token, project_id)

        for cluster_info in cluster_data:
            cluster_id = cluster_info.get('cluster_id')
            # 当参数中集群ID存在时,判断集群ID匹配成功后,继续后续逻辑
            if params.get('cluster_id') and params['cluster_id'] != cluster_id:
                continue
            cluster_env = cluster_info.get('environment')
            code, cluster_configmaps = self.get_configmaps_by_cluster_id(
                request, params, project_id, cluster_id)
            # 单个集群错误时,不抛出异常信息
            if code != ErrorCode.NoError:
                continue
            self.handle_data(
                request,
                cluster_configmaps,
                self.cate,
                project_id,
                cluster_id,
                is_decode,
                cluster_env,
                cluster_info.get('name', ''),
                namespace_dict=namespace_dict,
            )
            data += cluster_configmaps

        # 按时间倒序排列
        data.sort(key=lambda x: x.get('createTime', ''), reverse=True)
        return APIResponse({
            "code": ErrorCode.NoError,
            "data": {
                "data": data,
                "length": len(data)
            },
            "message": "ok"
        })
Exemple #4
0
    def get(self, request, project_id):
        """获取项目下的所有Ingress"""
        cluster_dicts = self.get_project_cluster_info(request, project_id)
        cluster_data = cluster_dicts.get('results', {}) or {}

        # 获取命名空间的id
        namespace_dict = app_utils.get_ns_id_map(request.user.token.access_token, project_id)

        is_decode = False
        params = {}
        data = []
        # 如果请求参数中cluster_id存在,根据cluster_id过滤集群信息
        query_cluster_id = request.query_params.get("cluster_id")
        if query_cluster_id:
            cluster_data = [info for info in cluster_data if query_cluster_id == info.get('cluster_id')]

        for cluster_info in cluster_data:
            cluster_id = cluster_info.get('cluster_id')
            cluster_env = cluster_info.get('environment')
            code, cluster_data = self.get_ingress_by_cluser_id(request, params, project_id, cluster_id)
            # 单个集群错误时,不抛出异常信息
            if code != ErrorCode.NoError:
                continue
            self.handle_data(
                request,
                cluster_data,
                self.cate,
                project_id,
                cluster_id,
                is_decode,
                cluster_env,
                cluster_info.get('name', ''),
                namespace_dict=namespace_dict,
            )
            data += cluster_data

        # 按时间倒序排列
        data.sort(key=lambda x: x.get('createTime', ''), reverse=True)

        return APIResponse({"code": ErrorCode.NoError, "data": {"data": data, "length": len(data)}, "message": "ok"})
Exemple #5
0
    def batch_delete_resource(self, request, project_id):
        """批量删除资源"""
        username = request.user.username

        slz = BatchResourceSLZ(data=request.data)
        slz.is_valid(raise_exception=True)
        data = slz.data['data']

        namespace_list = [(ns['cluster_id'], ns.get('namespace'))
                          for ns in data]
        namespace_list = set(namespace_list)

        # 检查用户是否有命名空间的使用权限
        app_utils.can_use_namespaces(request, project_id, namespace_list)

        # namespace_dict format: {(cluster_id, ns_name): ns_id}
        namespace_dict = app_utils.get_ns_id_map(
            request.user.token.access_token, project_id)

        success_list = []
        failed_list = []
        for _d in data:
            cluster_id = _d.get('cluster_id')
            name = _d.get('name')
            namespace = _d.get('namespace')
            namespace_id = namespace_dict.get((cluster_id, namespace))
            # 删除service
            resp = self.delete_single_resource(request, project_id, cluster_id,
                                               namespace, namespace_id, name)
            # 处理已经删除,但是storage上报数据延迟的问题
            message = resp.get('message', '')
            is_delete_before = True if 'node does not exist' in message or 'not found' in message else False
            if resp.get("code") == ErrorCode.NoError:
                success_list.append({
                    'name':
                    name,
                    'desc':
                    self.desc.format(cluster_id=cluster_id,
                                     namespace=namespace,
                                     resource_name=self.category,
                                     name=name),
                })
            else:
                if is_delete_before:
                    message = _('已经被删除,请手动刷新数据')
                desc = self.desc.format(cluster_id=cluster_id,
                                        namespace=namespace,
                                        resource_name=self.category,
                                        name=name)
                failed_list.append({
                    'name': name,
                    'desc': f'{desc}, message: {message}',
                })
        code = 0
        message = ''
        # 添加操作审计
        if success_list:
            name_list = [_s.get('name') for _s in success_list]
            desc_list = [_s.get('desc') for _s in success_list]
            message = _("以下{}删除成功:{}").format(self.category,
                                              ";".join(desc_list))
            activity_client.ContextActivityLogClient(
                project_id=project_id,
                user=username,
                resource_type="instance",
                resource=';'.join(name_list),
                resource_id=0,
                extra=json.dumps({}),
                description=";".join(desc_list),
            ).log_modify(activity_status="succeed")

        if failed_list:
            name_list = [_s.get('name') for _s in failed_list]
            desc_list = [_s.get('desc') for _s in failed_list]

            code = 4004
            message = _("以下{}删除失败:{}").format(self.category,
                                              ";".join(desc_list))
            activity_client.ContextActivityLogClient(
                project_id=project_id,
                user=username,
                resource_type="instance",
                resource=';'.join(name_list),
                resource_id=0,
                extra=json.dumps({}),
                description=message,
            ).log_modify(activity_status="failed")

        return Response({"code": code, "message": message, "data": {}})
Exemple #6
0
    def get(self, request, project_id):
        """获取项目下所有的服务"""
        params = dict(request.GET.items())
        params['env'] = 'k8s'

        # 获取命名空间的id
        namespace_dict = app_utils.get_ns_id_map(
            request.user.token.access_token, project_id)

        # 项目下的所有模板集id
        all_template_id_list = Template.objects.filter(
            project_id=project_id,
            edit_mode=TemplateEditMode.PageForm.value).values_list('id',
                                                                   flat=True)
        all_template_id_list = [
            str(template_id) for template_id in all_template_id_list
        ]
        skip_namespace_list = list(K8S_SYS_NAMESPACE)
        skip_namespace_list.extend(K8S_PLAT_NAMESPACE)

        cluster_id = params['cluster_id']
        code, cluster_services = self.get_services_by_cluster_id(
            request, params, project_id, cluster_id)
        if code != ErrorCode.NoError:
            return Response({'code': code, 'message': cluster_services})

        for _s in cluster_services:
            # NOTE: 兼容处理,因为key: clusterId已被前端使用;通过非bcs创建的service,不一定包含cluster_id
            _s["clusterId"] = cluster_id
            _s["cluster_id"] = cluster_id
            _config = _s.get('data', {})
            annotations = _config.get('metadata', {}).get('annotations', {})
            _s['update_time'] = annotations.get(ANNOTATIONS_UPDATE_TIME, '')
            _s['updator'] = annotations.get(ANNOTATIONS_UPDATOR, '')
            _s['status'] = 'Running'

            _s['can_update'] = True
            _s['can_update_msg'] = ''
            _s['can_delete'] = True
            _s['can_delete_msg'] = ''

            namespace_id = namespace_dict.get(
                (cluster_id, _s['namespace'])) if namespace_dict else None
            _s['namespace_id'] = namespace_id
            _s['iam_ns_id'] = calc_iam_ns_id(cluster_id, _s['namespace'])

            labels = _config.get('metadata', {}).get('labels', {})
            template_id = labels.get(LABLE_TEMPLATE_ID)
            # 资源来源
            source_type = labels.get(SOURCE_TYPE_LABEL_KEY)
            if not source_type:
                source_type = "template" if template_id else "other"
            _s['source_type'] = SOURCE_TYPE_MAP.get(source_type)
            extended_routes = get_svc_extended_routes(project_id,
                                                      _s['clusterId'])
            _s['access_info'] = get_svc_access_info(_config, _s['clusterId'],
                                                    extended_routes)
            # 处理 k8s 的系统命名空间的数据
            if _s['namespace'] in skip_namespace_list:
                _s['can_update'] = _s['can_delete'] = False
                _s['can_update_msg'] = _s['can_delete_msg'] = _("不允许操作系统命名空间")
                continue

            # 非模板集创建,可以删除但是不可以更新
            _s['can_update'] = False
            _s['can_update_msg'] = _("所属模板集不存在,无法操作")
            if template_id and template_id in all_template_id_list:
                _s['can_update'] = True
                _s['can_update_msg'] = ''

        # 按时间倒序排列
        cluster_services.sort(key=lambda x: x.get('createTime', ''),
                              reverse=True)

        return PermsResponse(
            cluster_services,
            NamespaceRequest(project_id=project_id,
                             cluster_id=params['cluster_id']))
Exemple #7
0
    def get(self, request, project_id):
        """ 获取项目下所有的服务 """
        cluster_dicts = self.get_project_cluster_info(request, project_id)
        cluster_data = cluster_dicts.get('results', {}) or {}

        project_kind = request.project.kind
        params = dict(request.GET.items())
        params['env'] = 'k8s'

        # 获取命名空间的id
        namespace_dict = app_utils.get_ns_id_map(
            request.user.token.access_token, project_id)

        # 项目下的所有模板集id
        all_template_id_list = Template.objects.filter(
            project_id=project_id,
            edit_mode=TemplateEditMode.PageForm.value).values_list('id',
                                                                   flat=True)
        all_template_id_list = [
            str(template_id) for template_id in all_template_id_list
        ]
        skip_namespace_list = list(K8S_SYS_NAMESPACE)
        skip_namespace_list.extend(K8S_PLAT_NAMESPACE)

        data = []
        for cluster_info in cluster_data:
            cluster_id = cluster_info.get('cluster_id')
            if params.get('cluster_id') and params['cluster_id'] != cluster_id:
                continue
            cluster_name = cluster_info.get('name')
            code, cluster_services = self.get_services_by_cluster_id(
                request, params, project_id, cluster_id)
            if code != ErrorCode.NoError:
                continue
            for _s in cluster_services:
                # NOTE: 兼容处理,因为key: clusterId已被前端使用;通过非bcs创建的service,不一定包含cluster_id
                _s["clusterId"] = cluster_id
                _s["cluster_id"] = cluster_id
                _config = _s.get('data', {})
                annotations = _config.get('metadata',
                                          {}).get('annotations', {})
                _s['update_time'] = annotations.get(ANNOTATIONS_UPDATE_TIME,
                                                    '')
                _s['updator'] = annotations.get(ANNOTATIONS_UPDATOR, '')
                _s['cluster_name'] = cluster_name
                _s['status'] = 'Running'
                _s['environment'] = cluster_info.get('environment')

                _s['can_update'] = True
                _s['can_update_msg'] = ''
                _s['can_delete'] = True
                _s['can_delete_msg'] = ''

                namespace_id = namespace_dict.get(
                    (cluster_id, _s['namespace'])) if namespace_dict else None
                _s['namespace_id'] = namespace_id

                labels = _config.get('metadata', {}).get('labels', {})
                template_id = labels.get(LABLE_TEMPLATE_ID)
                # 资源来源
                source_type = labels.get(SOURCE_TYPE_LABEL_KEY)
                if not source_type:
                    source_type = "template" if template_id else "other"
                _s['source_type'] = SOURCE_TYPE_MAP.get(source_type)
                extended_routes = get_svc_extended_routes(
                    project_id, _s['clusterId'])
                _s['access_info'] = get_svc_access_info(
                    _config, _s['clusterId'], extended_routes)
                # 处理 k8s 的系统命名空间的数据
                if _s['namespace'] in skip_namespace_list:
                    _s['can_update'] = _s['can_delete'] = False
                    _s['can_update_msg'] = _s['can_delete_msg'] = _(
                        "不允许操作系统命名空间")
                    continue

                # 非模板集创建,可以删除但是不可以更新
                _s['can_update'] = False
                _s['can_update_msg'] = _("所属模板集不存在,无法操作")
                if template_id and template_id in all_template_id_list:
                    _s['can_update'] = True
                    _s['can_update_msg'] = ''

            data += cluster_services
        # 按时间倒序排列
        data.sort(key=lambda x: x.get('createTime', ''), reverse=True)

        if data:
            # 检查是否用命名空间的使用权限
            perm = bcs_perm.Namespace(request, project_id, bcs_perm.NO_RES)
            data = perm.hook_perms(data,
                                   ns_id_flag='namespace_id',
                                   cluster_id_flag='clusterId',
                                   ns_name_flag='namespace')
        return APIResponse({
            "code": ErrorCode.NoError,
            "data": {
                "data": data,
                "length": len(data)
            },
            "message": "ok"
        })