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.cloudaccount.present"]},
"absent": {"require": []},
}
[docs]async def present(hub, ctx, name: str, **kwargs):
"""
:param string name: (required) name of the resource
"""
try:
state = FabricimagesStateImpl(hub, ctx)
return await state.present(hub, ctx, name, **kwargs)
except Exception as error:
hub.log.error("Error during enforcing present state: fabricimages")
hub.log.error(str(error))
raise error
[docs]async def absent(hub, ctx, name: str, **kwargs):
"""
:param string name: (required) name of the resource
"""
try:
state = FabricimagesStateImpl(hub, ctx)
return await state.absent(hub, ctx, name, **kwargs)
except Exception as error:
hub.log.error("Error during enforcing absent state: fabricimages")
hub.log.error(str(error))
raise error
[docs]async def describe(hub, ctx):
try:
state = FabricimagesStateImpl(hub, ctx)
return await state.describe(hub, ctx)
except Exception as error:
hub.log.error("Error during describe: fabricimages")
hub.log.error(str(error))
raise error
[docs]def is_pending(hub, ret: dict, state: str = None, **pending_kwargs):
try:
state = FabricimagesStateImpl(hub, None)
return state.is_pending(hub, ret, state, **pending_kwargs)
except Exception as error:
hub.log.error("Error during is_pending: fabricimages")
hub.log.error(str(error))
raise error
[docs]class FabricimagesState:
def __init__(self, hub, ctx):
self.hub = hub
self.ctx = ctx
[docs] async def present(self, hub, ctx, name: str, **kwargs):
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 fabricimages "{s["name"]}" due to existing resource "{name}"'
)
s = await self.remap_resource_structure(hub, ctx, s)
return StateReturn(
result=True,
comment=f"Resource fabricimages {name} already exists.",
old=s,
new=s,
)
return StateReturn(
result=False,
comment=f"Resource fabricimages is not present in the environment.",
old=None,
new=None,
)
[docs] async def absent(self, hub, ctx, name: str, **kwargs):
return StateReturn(
result=True,
comment=f"State absent is not available for resource fabricimages.",
old=None,
new=None,
)
[docs] async def describe(self, hub, ctx):
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"ro-{obj_name}-{obj_id.split('-')[-1]}"] = {
"vra.iaas.fabricimages.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.iaas.fabricimages.get_fabric_images(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 fabricimages with offset={initialElements} out of {totalElements}"
)
pres = await hub.exec.vra.iaas.fabricimages.get_fabric_images(
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 = {
"add": [],
"omit": [
"orgId",
"createdAt",
"updatedAt",
"owner",
"_links",
"customProperties",
],
}
# Perform resource mapping by adding properties and omitting properties.
# Property renaming is addition followed by omission.
if schema_mapper:
resource_name = "fabricimages"
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
# ====================================
import asyncio
from idem_vra.helpers.query import query
[docs]class FabricimagesStateImpl(FabricimagesState):
[docs] async def paginate_images(self, hub, ctx):
"""
Paginate through all images.
"""
res = await hub.exec.vra.iaas.images.get_images(
ctx,
)
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 images with offset={initialElements} out of {totalElements}"
)
pres = await hub.exec.vra.iaas.images.get_images(
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] async def get_imagefabric(self, hub, ctx, id):
result = await hub.exec.vra.iaas.fabricimages.get_fabric_image(ctx, p_id=id)
return result.get("ret")
[docs] async def describe(self, hub, ctx):
result = {}
# Retrieve list of all used images
used_images = await self.paginate_images(hub, ctx)
used_image_ids = [
id
for id in list(
set(query("$[*].mapping.*.id", used_images["ret"]["content"]))
)
if id != None
]
fabricimages = await asyncio.gather(
*[self.get_imagefabric(hub, ctx, id) for id in used_image_ids]
)
for obj in fabricimages:
# 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"ro-{obj_name}-{obj_id.split('-')[-1]}"] = {
"vra.iaas.fabricimages.present": props
}
return result