Source code for idem_vra.states.vra.pipeline.pipelines

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, **kwargs): """ :param string name: (required in body) A human-friendly name used as an identifier in APIs that support this option :param string apiVersion: (optional in query) The version of the API in yyyy-MM-dd format (UTC). For versioning information please refer to /codestream/api/about :param string Authorization: (optional in header) Bearer token :param object _inputMeta: (optional in body) Additional information about Input Properties :param integer concurrency: (optional in body) Number of Executions of the Pipeline that can run concurrently. :param string description: (optional in body) A human-friendly description. :param boolean enabled: (optional in body) Indicates if the Pipeline is in enabled state. :param boolean global: (optional in body) Indicates if the pipeline is shared with all projects in an Org. :param string icon: (optional in body) String description of the icon used for this Pipeline. :param object input: (optional in body) Map representing the Input properties for the Pipeline. :param Any notifications: (optional in body) :param array options: (optional in body) Represents the different options to trigger a Pipeline. Selecting an option auto injects the Input properties needed to execute a Pipeline with that trigger. :param object output: (optional in body) Map representing the Output properties for the Pipeline. :param string project: (optional in body) The project this entity belongs to. :param array rollbacks: (optional in body) Represents the various Rollback Configurations for the Pipeline :param array stageOrder: (optional in body) Represents the order in which Stages will be executed. :param object stages: (optional in body) Map representing the details of the various Stages of the Pipeline. :param Any starred: (optional in body) :param string state: (optional in body) Indicates if the Pipeline is enabled/disabled/released to catalog. :param array tags: (optional in body) A set of tag keys and optional values that were set on on the resource. :param Any workspace: (optional in body) """ try: state = PipelinesStateImpl(hub, ctx) return await state.present(hub, ctx, name, **kwargs) except Exception as error: hub.log.error("Error during enforcing present state: pipelines") hub.log.error(str(error)) raise error
[docs]async def absent(hub, ctx, name: str, **kwargs): """ :param string p_id: (required in path) The ID of the Pipeline :param string apiVersion: (optional in query) The version of the API in yyyy-MM-dd format (UTC). For versioning information please refer to /codestream/api/about :param string Authorization: (optional in header) Bearer token """ """ :param string name: (required) name of the resource """ try: state = PipelinesStateImpl(hub, ctx) return await state.absent(hub, ctx, name, **kwargs) except Exception as error: hub.log.error("Error during enforcing absent state: pipelines") hub.log.error(str(error)) raise error
[docs]async def describe(hub, ctx): try: state = PipelinesStateImpl(hub, ctx) return await state.describe(hub, ctx) except Exception as error: hub.log.error("Error during describe: pipelines") hub.log.error(str(error)) raise error
[docs]def is_pending(hub, ret: dict, state: str = None, **pending_kwargs): try: state = PipelinesStateImpl(hub, None) return state.is_pending(hub, ret, state, **pending_kwargs) except Exception as error: hub.log.error("Error during is_pending: pipelines") hub.log.error(str(error)) raise error
[docs]class PipelinesState: 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 pipelines "{s["name"]}" due to existing resource "{name}"' ) s = await self.remap_resource_structure(hub, ctx, s) return StateReturn( result=True, comment=f"Resource pipelines {name} already exists.", old=s, new=s, ) res = ( await hub.exec.vra.pipeline.pipelines.create_pipeline_using_post( ctx, name, **kwargs ) )["ret"] res = await self.remap_resource_structure(hub, ctx, res) return StateReturn( result=True, comment=f"Creation of pipelines {name} success.", old=None, new=res, )
[docs] async def absent(self, hub, ctx, name: str, **kwargs): 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 pipelines "{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"pipelines with name = {resource.get('name')} already exists" ) await hub.exec.vra.pipeline.pipelines.delete_pipeline_by_id_using_delete( 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): 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.pipeline.pipelines.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.pipeline.pipelines.get_all_pipelines_using_get( 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 pipelines with offset={initialElements} out of {totalElements}" ) pres = ( await hub.exec.vra.pipeline.pipelines.get_all_pipelines_using_get( 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": [ "_createTimeInMicros", "_updateTimeInMicros", "_link", "_warnings", "_projectId", "updatedAt", "updatedBy", "createdAt", "createdBy", "version", ], } # Perform resource mapping by adding properties and omitting properties. # Property renaming is addition followed by omission. if schema_mapper: resource_name = "pipelines" 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 # ====================================
[docs]class PipelinesStateImpl(PipelinesState):
[docs] async def present(self, hub, ctx, name: str, **kwargs): search_result = (await self.paginate_find(hub, ctx))["ret"] for itm in search_result.get("links", []): s = search_result.documents.get(itm) if name == s.get("name", "") and True: hub.log.info( f'Returning resource pipelines "{s["name"]}" due to existing resource "{name}"' ) s = await self.remap_resource_structure(hub, ctx, s) return StateReturn( result=True, comment=f"Resource pipelines {name} already exists.", old=s, new=s, ) res = ( await hub.exec.vra.pipeline.pipelines.create_pipeline_using_post( ctx, name, **kwargs ) )["ret"] res = await self.remap_resource_structure(hub, ctx, res) return StateReturn( result=True, comment=f"Creation of pipelines {name} success.", old=None, new=res, )
[docs] async def absent(self, hub, ctx, name: str, **kwargs): search_result = (await self.paginate_find(hub, ctx))["ret"] resource = None for itm in search_result.get("links", []): s = search_result.documents.get(itm) if name == s["name"] and True: hub.log.info( f'Found resource pipelines "{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"pipelines with name = {resource.get('name')} already exists" ) await hub.exec.vra.pipeline.pipelines.delete_pipeline_by_id_using_delete( 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): result = {} res = await self.paginate_find(hub, ctx) for itm in res.get("ret", {}).get("links", []): # Keep track of name and id properties as they may get remapped obj = res.get("ret", {}).get("documents", {}).get(itm) 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.pipeline.pipelines.present": props } return result