Exemplo n.º 1
0
    def update_or_create(
        self,
        resource: Resource,
        body: Optional[Dict] = None,
        name: Optional[str] = None,
        namespace: Optional[str] = None,
        update_method: str = "replace",
        **kwargs,
    ) -> Tuple[ResourceInstance, bool]:
        """创建或修改一个 Kubernetes 资源

        :param update_method: 修改类型,默认为 replace,可选值 patch
        :returns: (instance, created)
        :raises: 当 update_method 不正确时,抛出 ValueError。调用 API 错误时,抛出 ApiException
        """
        if update_method not in ["replace", "patch"]:
            raise ValueError("Invalid update_method {}".format(update_method))

        try:
            update_func_obj = getattr(resource, update_method)
            obj = update_func_obj(body=body,
                                  name=name,
                                  namespace=namespace,
                                  **kwargs)
            return obj, False
        except ApiException as e:
            # Only continue when resource is not found
            if e.status != 404:
                raise

        logger.info(
            f"Updating {resource.kind}:{name} failed, resource not exists, continue creating"
        )
        obj = resource.create(body=body, namespace=namespace, **kwargs)
        return obj, True
Exemplo n.º 2
0
 def delete_ignore_nonexistent(
     self,
     resource: Resource,
     name: Optional[str] = None,
     namespace: Optional[str] = None,
     body: Optional[Dict] = None,
     label_selector: Optional[str] = None,
     field_selector: Optional[str] = None,
     **kwargs,
 ) -> Optional[ResourceInstance]:
     """删除资源,但是当资源不存在时忽略错误"""
     try:
         return resource.delete(
             name=name,
             namespace=namespace,
             body=body,
             label_selector=label_selector,
             field_selector=field_selector,
             **kwargs,
         )
     except ApiException as e:
         if e.status == 404:
             logger.info(
                 f"Delete a non-existent resource {resource.kind}:{name} in namespace:{namespace}, error captured."
             )
             return
         raise
Exemplo n.º 3
0
def mock_processedtemplates():
    return Resource(
        api_version='v1',
        kind='Template',
        name='processedtemplates',
        namespaced=True,
        preferred=True,
        prefix='api',
        shorter_names=[],
        shortNames=[],
        verbs=['create', 'delete', 'get', 'list', 'patch', 'update', 'watch'])
def mock_processedtemplates():
    return Resource(
        api_version="v1",
        kind="Template",
        name="processedtemplates",
        namespaced=True,
        preferred=True,
        prefix="api",
        shorter_names=[],
        shortNames=[],
        verbs=["create", "delete", "get", "list", "patch", "update", "watch"],
    )
Exemplo n.º 5
0
def mock_namespace():
    return Resource(
        api_version='v1',
        kind='Namespace',
        name='namespaces',
        namespaced=False,
        preferred=True,
        prefix='api',
        shorter_names=['ns'],
        shortNames=['ns'],
        singularName='namespace',
        verbs=['create', 'delete', 'get', 'list', 'patch', 'update', 'watch'])
def mock_namespace():
    return Resource(
        api_version="v1",
        kind="Namespace",
        name="namespaces",
        namespaced=False,
        preferred=True,
        prefix="api",
        shorter_names=["ns"],
        shortNames=["ns"],
        singularName="namespace",
        verbs=["create", "delete", "get", "list", "patch", "update", "watch"],
    )
Exemplo n.º 7
0
    def update_or_create(
        self,
        resource: Resource,
        body: Optional[Dict] = None,
        name: Optional[str] = None,
        namespace: Optional[str] = None,
        update_method: str = "replace",
        auto_add_version: bool = False,
        **kwargs,
    ) -> Tuple[ResourceInstance, bool]:
        """创建或修改一个 Kubernetes 资源

        :param update_method: 修改类型,默认为 replace,可选值 patch
        :param auto_add_version: 当 update_method=replace 时,是否自动添加 metadata.resourceVersion 字段,默认为 False
        :returns: (instance, created)
        :raises: 当 update_method 不正确时,抛出 ValueError。调用 API 错误时,抛出 ApiException
        """
        if update_method not in ["replace", "patch"]:
            raise ValueError("Invalid update_method {}".format(update_method))

        obj = self.get_or_none(resource,
                               name=name,
                               namespace=namespace,
                               **kwargs)
        if not obj:
            logger.info(
                f"Resource {resource.kind}:{name} not exists, continue creating"
            )
            return resource.create(body=body, namespace=namespace,
                                   **kwargs), True

        # 资源已存在,执行后续的 update 逻辑
        if update_method == 'replace' and auto_add_version:
            self._add_resource_version(obj, body)

        update_func_obj = getattr(resource, update_method)
        return update_func_obj(body=body,
                               name=name,
                               namespace=namespace,
                               **kwargs), False