Skip to content

Commit

Permalink
Add ensure_exists to resource (#1857)
Browse files Browse the repository at this point in the history
  • Loading branch information
myakove authored May 29, 2024
1 parent e7c6c7a commit e6f670a
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions ocp_resources/resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
MethodNotAllowedError,
NotFoundError,
ForbiddenError,
ResourceNotFoundError,
)
from kubernetes.dynamic.resource import ResourceField
from packaging.version import Version
Expand Down Expand Up @@ -365,6 +366,7 @@ def __init__(
timeout_seconds: int = TIMEOUT_1MINUTE,
api_group: str = "",
hash_log_data: bool = True,
ensure_exists: bool = False,
):
"""
Create an API resource
Expand All @@ -387,6 +389,7 @@ def __init__(
api_group (str): Resource API group; will overwrite API group definition in resource class
hash_log_data (bool): Hash resource content based on resource keys_to_hash property
(example: Secret resource)
ensure_exists (bool): Whether to check if the resource exists before when initializing the resource, raise if not.
"""

self.name = name
Expand Down Expand Up @@ -427,9 +430,19 @@ def __init__(
self.yaml_file_contents: str = ""
self.initial_resource_version: str = ""
self.logger = self._set_logger()

if ensure_exists:
self._ensure_exists()

# self._set_client_and_api_version() must be last init line
self._set_client_and_api_version()

def _ensure_exists(self) -> None:
self.logger.error(self.namespace)
if not self.exists:
_name_for_raise = self.name if not self.namespace else f"{self.namespace}/{self.name}"
raise ResourceNotFoundError(f"Resource `{self.kind}` `{_name_for_raise}` does not exist")

def _set_logger(self) -> logging.Logger:
log_level = os.environ.get("OPENSHIFT_PYTHON_WRAPPER_LOG_LEVEL", "INFO")
log_file = os.environ.get("OPENSHIFT_PYTHON_WRAPPER_LOG_FILE", "")
Expand Down Expand Up @@ -1188,6 +1201,7 @@ def __init__(
delete_timeout: int = TIMEOUT_4MINUTES,
client: DynamicClient | None = None,
privileged_client: DynamicClient | None = None,
ensure_exists: bool = True,
**kwargs: Any,
):
super().__init__(
Expand All @@ -1204,6 +1218,9 @@ def __init__(
if not (self.name and self.namespace) and not self.yaml_file:
raise MissingRequiredArgumentError(argument="'name' and 'namespace'")

if ensure_exists:
self._ensure_exists()

@classmethod
def get(
cls,
Expand Down

0 comments on commit e6f670a

Please sign in to comment.