from typing import Any
import semver
from idem_vra.helpers.mapper import add_properties
from idem_vra.helpers.mapper import omit_properties
from idem_vra.helpers.models import StateReturn
__contracts__ = ["resource"]
TREQ = {"present": {"require": ["vra.iaas.project.present"]}, "absent": {"require": []}}
[docs]async def present(
hub, ctx, name: str, definition: Any, id: Any, projectId: Any, **kwargs
):
"""
:param Any definition: (required in body)
:param string id: (required in body) Entitlement id
:param string projectId: (required in body) Project id
:param string apiVersion: (optional in query) The version of the API in yyyy-MM-dd format (UTC). If you do not
specify explicitly an exact version, you will be calling the latest
supported API version.
:param boolean migrated: (optional in body) Migrated flag for entitlements
"""
try:
state = CatalogEntitlementsStateImpl(hub, ctx)
return await state.present(hub, ctx, name, definition, id, projectId, **kwargs)
except Exception as error:
hub.log.error("Error during enforcing present state: catalogentitlements")
hub.log.error(str(error))
raise error
[docs]async def absent(hub, ctx, name: str, **kwargs):
"""
:param string p_id: (required in path) Entitlement id
:param string apiVersion: (optional in query) The version of the API in yyyy-MM-dd format (UTC). If you do not
specify explicitly an exact version, you will be calling the latest
supported API version.
"""
"""
:param string name: (required) name of the resource
"""
try:
state = CatalogEntitlementsStateImpl(hub, ctx)
return await state.absent(hub, ctx, name, **kwargs)
except Exception as error:
hub.log.error("Error during enforcing absent state: catalogentitlements")
hub.log.error(str(error))
raise error
[docs]async def describe(hub, ctx):
try:
state = CatalogEntitlementsStateImpl(hub, ctx)
return await state.describe(hub, ctx)
except Exception as error:
hub.log.error("Error during describe: catalogentitlements")
hub.log.error(str(error))
raise error
[docs]def is_pending(hub, ret: dict, state: str = None, **pending_kwargs):
try:
state = CatalogEntitlementsStateImpl(hub, None)
return state.is_pending(hub, ret, state, **pending_kwargs)
except Exception as error:
hub.log.error("Error during is_pending: catalogentitlements")
hub.log.error(str(error))
raise error
[docs]class CatalogentitlementsState:
def __init__(self, hub, ctx):
self.hub = hub
self.ctx = ctx
[docs] async def present(
self, hub, ctx, name: str, definition: Any, id: Any, projectId: Any, **kwargs
):
# version check
if "vra_version" in ctx.acct and (
semver.compare(ctx.acct.vra_version, "8.0.0") == -1
or semver.compare("8.8.1", ctx.acct.vra_version) == -1
):
hub.log.warning(
f"Unsupported version min:8.0.0 max:8.8.1 target:{ctx.acct.vra_version} for resource:catalogentitlements"
)
return StateReturn(
result=True,
comment=f"State present is not available for resource catalogentitlements.",
old=None,
new=None,
)
search_result = (await self.paginate_find(hub, ctx))["ret"]
for s in search_result.content:
if name == s["name"] and True:
hub.log.info(
f'Returning resource catalogentitlements "{s["name"]}" due to existing resource "{name}"'
)
s = await self.remap_resource_structure(hub, ctx, s)
return StateReturn(
result=True,
comment=f"Resource catalogentitlements {name} already exists.",
old=s,
new=s,
)
res = (
await hub.exec.vra.catalog.catalogentitlements.create_entitlement_using_post2(
ctx, definition, id, projectId, **kwargs
)
)["ret"]
res = await self.remap_resource_structure(hub, ctx, res)
return StateReturn(
result=True,
comment=f"Creation of catalogentitlements {name} success.",
old=None,
new=res,
)
[docs] async def absent(self, hub, ctx, name: str, **kwargs):
# version check
if "vra_version" in ctx.acct and (
semver.compare(ctx.acct.vra_version, "8.0.0") == -1
or semver.compare("8.8.1", ctx.acct.vra_version) == -1
):
hub.log.warning(
f"Unsupported version min:8.0.0 max:8.8.1 target:{ctx.acct.vra_version} for resource:catalogentitlements"
)
return StateReturn(
result=True,
comment=f"State absent is not available for resource catalogentitlements.",
old=None,
new=None,
)
search_result = (await self.paginate_find(hub, ctx))["ret"]
resource = None
for s in search_result.content:
if name == s["name"] and True:
hub.log.info(
f'Found resource catalogentitlements "{s["name"]}" due to existing resource "{name}"'
)
s = await self.remap_resource_structure(hub, ctx, s)
resource = s
if resource:
# it exists!
delete_kwargs = {}
delete_kwargs["p_id"] = resource.get("id")
hub.log.debug(
f"catalogentitlements with name = {resource.get('name')} already exists"
)
await hub.exec.vra.catalog.catalogentitlements.delete_entitlement_using_delete2(
ctx, **delete_kwargs
)
return StateReturn(
result=True,
comment=f"Resource with name = {resource.get('name')} deleted.",
old=resource,
new=None,
)
return StateReturn(
result=True,
comment=f"Resource with name = {name} is already absent.",
old=None,
new=None,
)
[docs] async def describe(self, hub, ctx):
# version check
if "vra_version" in ctx.acct and (
semver.compare(ctx.acct.vra_version, "8.0.0") == -1
or semver.compare("8.8.1", ctx.acct.vra_version) == -1
):
hub.log.warning(
f"Unsupported version min:8.0.0 max:8.8.1 target:{ctx.acct.vra_version} for resource:catalogentitlements"
)
return {}
result = {}
res = await self.paginate_find(hub, ctx)
for obj in res.get("ret", {}).get("content", []):
# Keep track of name and id properties as they may get remapped
obj_name = obj.get("name", "unknown")
obj_id = obj.get("id", "unknown")
obj = await self.remap_resource_structure(hub, ctx, obj)
# Define props
props = [{key: value} for key, value in obj.items()]
# Build result
result[f"{obj_name}-{obj_id.split('-')[-1]}"] = {
"vra.catalog.catalogentitlements.present": props
}
return result
[docs] async def paginate_find(self, hub, ctx, **kwargs):
"""
Paginate through all resources using their 'find' method.
"""
res = (
await hub.exec.vra.catalog.catalogentitlements.get_entitlements_using_get2(
ctx, **kwargs
)
)
numberOfElements = res.get("ret", {}).get("numberOfElements", 0)
totalElements = res.get("ret", {}).get("totalElements", 0)
initialElements = numberOfElements
if numberOfElements != totalElements and totalElements != 0:
while initialElements < totalElements:
hub.log.debug(
f"Requesting catalogentitlements with offset={initialElements} out of {totalElements}"
)
pres = await hub.exec.vra.catalog.catalogentitlements.get_entitlements_using_get2(
ctx, skip=initialElements
)
initialElements += pres.get("ret", {}).get("numberOfElements", 0)
aggO = res.get("ret", {}).get("content", [])
aggN = pres.get("ret", {}).get("content", [])
res["ret"]["content"] = [*aggO, *aggN]
res["ret"]["numberOfElements"] = initialElements
return res
[docs] def is_pending(self, hub, ret: dict, state: str = None, **pending_kwargs):
"""
State reconciliation
"""
hub.log.debug(f'Running is_pending for resource: {ret.get("__id__", None)}...')
is_pending_result = False
hub.log.debug(
f'is_pending_result for resource "{ret.get("__id__", None)}": {is_pending_result}'
)
return is_pending_result
[docs] async def remap_resource_structure(self, hub, ctx, obj: dict) -> dict:
schema_mapper = None
# Perform resource mapping by adding properties and omitting properties.
# Property renaming is addition followed by omission.
if schema_mapper:
resource_name = "catalogentitlements"
hub.log.debug(f"Remapping resource {resource_name}...")
obj = await add_properties(obj, schema_mapper.get("add", []))
obj = omit_properties(obj, schema_mapper.get("omit", []))
return obj
# ====================================
# State override
# ====================================
from idem_vra.helpers.query import query
[docs]class CatalogEntitlementsStateImpl(CatalogentitlementsState):
[docs] async def describe(self, hub, ctx):
# version check
if "vra_version" in ctx.acct and (
semver.compare(ctx.acct.vra_version, "8.0.0") == -1
or semver.compare("8.8.1", ctx.acct.vra_version) == -1
):
hub.log.warning(
f"Unsupported version min:8.0.0 max:8.8.1 target:{ctx.acct.vra_version} for resource:catalogentitlements"
)
return {}
result = {}
# Retrieve list of all projects
projects = await hub.states.vra.iaas.project.describe(ctx)
project_ids = query("*.*[?(@.id)].id", projects)
# Build a list of all entitlements
entitlements = []
for project_id in project_ids:
hub.log.debug(f"Requesting catalogentitlements for project {project_id}")
res = await hub.exec.vra.catalog.catalogentitlements.get_entitlements_using_get2(
ctx, project_id=project_id
)
entitlements += res.get("ret", [])
for obj in entitlements:
# Keep track of name and id properties as they may get remapped
obj_name = obj.get("name", "unknown")
obj_id = obj.get("id", "unknown")
obj = await self.remap_resource_structure(hub, ctx, obj)
# Define props
props = [{key: value} for key, value in obj.items()]
# Build result
result[f"{obj_name}-{obj_id.split('-')[-1]}"] = {
"vra.catalog.catalogentitlements.present": props
}
return result