예제 #1
0
 def test_get_existed(self, common_patch):
     """测试获取已经存在的命名空间"""
     client = Namespace(
         CtxCluster.create(TEST_CLUSTER_ID, TEST_PROJECT_ID, token='token'))
     ret = client.get_or_create_cc_namespace(
         'default', 'admin', labels={'test_key': 'test_val'})
     assert ret == {'name': 'default', 'namespace_id': 1}
예제 #2
0
 def test_create_nonexistent(self, common_patch):
     """ 测试获取不存在的命名空间(触发创建逻辑) """
     client = Namespace(
         CtxCluster.create(TEST_CLUSTER_ID, TEST_PROJECT_ID, token='token'))
     ret = client.get_or_create_cc_namespace(self.namespace_for_test,
                                             'admin')
     assert ret == {'name': self.namespace_for_test, 'namespace_id': 2}
     client.delete(name=self.namespace_for_test)
예제 #3
0
파일: k8s.py 프로젝트: penglongli/bk-bcs
 def get_or_create_namespace(self, request, project_id, cluster_id):
     """创建bcs-system命名空间,如果不存在,则创建;如果存在,则直接返回数据"""
     ctx_cluster = CtxCluster.create(token=request.user.token.access_token,
                                     id=cluster_id,
                                     project_id=project_id)
     return Namespace(ctx_cluster).get_or_create_cc_namespace(
         K8S_LB_NAMESPACE, request.user.username)
예제 #4
0
    def update(self, request, project_id_or_code, cluster_id, ns_name):
        if ns_name in BCS_RESERVED_NAMESPACES:
            raise error_codes.ValidateError('不允许更新 BCS 保留的命名空间')
        # 更新操作审计信息
        request.audit_ctx.update_fields(resource_type=ResourceType.Namespace, resource=ns_name)

        params = self.params_validate(UpdateNamespaceSLZ)
        ns_client = Namespace(request.ctx_cluster)
        namespace = ns_client.get(ns_name, is_format=False)
        if not namespace:
            raise error_codes.ResNotFoundError('集群 {} 中不存在命名空间 {}'.format(cluster_id, ns_name))

        manifest = namespace.data.to_dict()
        for key in ['labels', 'annotations']:
            manifest['metadata'][key] = params[key]
        ns_client.replace(name=ns_name, body=manifest)
        return Response(manifest)
예제 #5
0
 def _create_kubernetes_namespace(
     self,
     access_token: str,
     username: str,
     project_id: str,
     cluster_id: str,
     ns_name: str,
 ) -> Dict:
     # TODO: 需要注意需要迁移到权限中心V3,通过注册到V0权限中心的命名空间ID,反查命名空间名称、集群ID及项目ID
     # 连接集群创建命名空间
     ctx_cluster = CtxCluster.create(token=access_token,
                                     id=cluster_id,
                                     project_id=project_id)
     return Namespace(ctx_cluster).get_or_create_cc_namespace(
         ns_name, username)
예제 #6
0
def get_shared_cluster_proj_namespaces(ctx_cluster: CtxCluster,
                                       project_code: str) -> List[str]:
    """
    获取指定项目在共享集群中拥有的命名空间

    :param ctx_cluster: 集群 Context 信息
    :param project_code: 项目英文名
    :return: 命名空间列表
    """
    return [
        getitems(ns, 'metadata.name') for ns in Namespace(ctx_cluster).list(
            is_format=False,
            cluster_type=ClusterType.SHARED,
            project_code=project_code)['items']
    ]
예제 #7
0
def is_proj_ns_in_shared_cluster(ctx_cluster: CtxCluster,
                                 namespace: Optional[str],
                                 project_code: str) -> bool:
    """
    检查命名空间是否在共享集群中且属于指定项目

    :param ctx_cluster: 集群 Context 信息
    :param namespace: 命名空间
    :param project_code: 项目英文名
    :return: True / False
    """
    if not namespace:
        return False
    ns = Namespace(ctx_cluster).get(name=namespace, is_format=False)
    return ns and getitems(ns.metadata,
                           ['annotations', PROJ_CODE_ANNO_KEY]) == project_code
예제 #8
0
    def create(self, request, project_id_or_code, cluster_id):
        project_id = request.project.project_id
        params = self.params_validate(CreateNamespaceSLZ, context={'project_id': project_id})
        ns_name, variables = params['name'], params['variables']
        if ns_name in BCS_RESERVED_NAMESPACES:
            raise error_codes.ValidateError('不允许创建 BCS 保留的命名空间')
        # 更新操作审计信息
        request.audit_ctx.update_fields(resource_type=ResourceType.Namespace, resource=ns_name)

        namespace = Namespace(request.ctx_cluster).get_or_create_cc_namespace(
            ns_name, request.user.username, params['labels'], params['annotations']
        )
        # 创建命名空间下的变量值
        ns_id = namespace['namespace_id']
        namespace['id'] = ns_id
        NameSpaceVariable.batch_save(ns_id, variables)
        namespace['variables'] = variables
        return Response(namespace)
예제 #9
0
def shared_cluster_ns_mgr():
    # 共享集群项目 unittest-proj 独占的命名空间配置
    shared_cluster_ns = f'unittest-proj-{randint(10 ** 5, 10 ** 6)}-ns'
    manifest = {
        "apiVersion": "v1",
        "kind": "Namespace",
        "metadata": {
            "annotations": {
                PROJ_CODE_ANNO_KEY: "unittest-proj"
            },
            "name": shared_cluster_ns
        },
    }

    ctx_cluster = CtxCluster.create(token='access_token',
                                    id=TEST_SHARED_CLUSTER_ID,
                                    project_id=TEST_PROJECT_ID)
    client = Namespace(ctx_cluster)
    client.create(body=manifest)
    # 抛出以在单元测试中使用
    yield shared_cluster_ns
    client.delete_ignore_nonexistent(name=shared_cluster_ns)
예제 #10
0
 def retrieve(self, request, project_id_or_code, cluster_id, ns_name):
     namespace = Namespace(request.ctx_cluster).get(ns_name, is_format=False)
     if not namespace:
         raise error_codes.ResNotFoundError('集群 {} 中不存在命名空间 {}'.format(cluster_id, ns_name))
     return Response(namespace.data.to_dict())