Esempio n. 1
0
 def get_clusters_without_ns(self, clusters, cluster_ids_with_ns):
     """获取不带有ns的集群
     TODO: 后续相关的namespace的功能,可以通过K8S/Mesos API获取
     """
     clusters_without_ns = []
     for cluster_id in clusters:
         if cluster_id in cluster_ids_with_ns:
             continue
         cluster = clusters[cluster_id]
         item = {
             "environment_name": get_cluster_env_name(cluster["environment"]),
             "environment": cluster["environment"],
             "cluster_id": cluster_id,
             "name": cluster["name"],
             "results": [],
         }
         clusters_without_ns.append(item)
     return clusters_without_ns
Esempio n. 2
0
    def list(self, request, project_id):
        """命名空间列表
        权限控制: 必须有对应集群的使用权限
        """
        access_token = request.user.token.access_token
        valid_group_by = ['env_type', 'cluster_id', 'cluster_name']

        group_by = request.GET.get('group_by')
        cluster_id = request.GET.get('cluster_id')
        with_lb = request.GET.get('with_lb', 0)

        # 过滤有使用权限的命名空间
        perm_can_use = request.GET.get('perm_can_use')
        if perm_can_use == '1':
            perm_can_use = True
        else:
            perm_can_use = False

        # 获取全部namespace,前台分页
        result = paas_cc.get_namespace_list(access_token,
                                            project_id,
                                            with_lb=with_lb,
                                            limit=constants.ALL_LIMIT)
        if result.get('code') != 0:
            raise error_codes.APIError.f(result.get('message', ''))

        results = result["data"]["results"] or []
        # 针对k8s集群过滤掉系统和平台命名空间
        if request.project.kind == ProjectKind.K8S.value:
            results = self._ignore_ns_for_k8s(results)

        # 是否有创建权限
        perm = bcs_perm.Namespace(request, project_id, bcs_perm.NO_RES)
        can_create = perm.can_create(raise_exception=False)

        # 补充cluster_name字段
        cluster_list = get_clusters(access_token, project_id)
        # TODO: 后续发现cluster_id不存在时,再处理
        cluster_dict = {i["cluster_id"]: i for i in (cluster_list or [])}

        # no_vars=1 不显示变量
        no_vars = request.GET.get('no_vars')
        if no_vars == '1':
            project_var = []
        else:
            project_var = NameSpaceVariable.get_project_ns_vars(project_id)

        for i in results:
            # ns_vars = NameSpaceVariable.get_ns_vars(i['id'], project_id)
            ns_id = i['id']
            ns_vars = []
            for _var in project_var:
                _ns_values = _var['ns_values']
                _ns_value_ids = _ns_values.keys()
                ns_vars.append({
                    'id':
                    _var['id'],
                    'key':
                    _var['key'],
                    'name':
                    _var['name'],
                    'value':
                    _ns_values.get(ns_id)
                    if ns_id in _ns_value_ids else _var['default_value'],
                })
            i['ns_vars'] = ns_vars

            if i['cluster_id'] in cluster_dict:
                i['cluster_name'] = cluster_dict[i['cluster_id']]['name']
                i['environment'] = cluster_dict[i['cluster_id']]['environment']
            else:
                i['cluster_name'] = i['cluster_id']
                i['environment'] = None

        # 添加permissions到数据中
        results = perm.hook_perms(results, perm_can_use)

        if cluster_id:
            results = filter(lambda x: x['cluster_id'] == cluster_id, results)

        if group_by and group_by in valid_group_by:
            # 分组, 排序
            results = [{
                'name':
                k,
                'results':
                sorted(list(v), key=lambda x: x['id'], reverse=True)
            } for k, v in groupby(sorted(results, key=lambda x: x[group_by]),
                                  key=lambda x: x[group_by])]
            if group_by == 'env_type':
                ordering = [i.value for i in constants.EnvType]
                results = sorted(results,
                                 key=lambda x: ordering.index(x['name']))
            else:
                results = sorted(results,
                                 key=lambda x: x['name'],
                                 reverse=True)
                # 过滤带有ns的集群id
                cluster_ids_with_ns = []
                # 按集群分组时,添加集群环境信息
                for r in results:
                    r_ns_list = r.get('results') or []
                    r_ns = r_ns_list[0] if r_ns_list else {}
                    r['environment'] = r_ns.get('environment', '')
                    r['environment_name'] = get_cluster_env_name(
                        r['environment'])
                    r["cluster_id"] = r_ns.get("cluster_id")
                    cluster_ids_with_ns.append(r_ns.get("cluster_id"))

                # 添加无命名空间集群ID
                results.extend(
                    self.get_clusters_without_ns(cluster_dict,
                                                 cluster_ids_with_ns))
        else:
            results = sorted(results, key=lambda x: x['id'], reverse=True)

        permissions = {
            'create': can_create,
            'sync_namespace': enabled_sync_namespace(project_id)
        }

        return APIResult(results, 'success', permissions=permissions)