Example #1
0
    def get(cls, name: str, subcategory: str = None) -> "ResourceCategory":  # pylint: disable=arguments-differ
        """Get resource category with given name.

        It returns resource category with all subcategories by default. You can
            get resource category with only one subcategory if you provide it's
            name as `subcategory` parameter.

        Args:
            name (str): Resource category name.
            subcategory (str, optional): Name of subcategory. Defaults to None.

        Raises:
            ResourceNotFound: Subcategory with given name does not exist

        Returns:
            BaseCategory: BaseCategory instance

        """
        category_obj: "ResourceCategory" = super().get(name=name)
        if not subcategory:
            return category_obj
        filtered_subcategories: Dict[str, str] = list(
            filter(lambda x: x["name"] == subcategory,
                   category_obj.subcategories))
        if not filtered_subcategories:
            raise ResourceNotFound(
                f"Subcategory {subcategory} does not exist.")
        category_obj.subcategories = filtered_subcategories
        return category_obj
    def create_from_request_response(cls, request_response: dict) -> "VnfInstantiation":
        """Create VNF instantiation object based on request details.

        Raises:
            ResourceNotFound: Service related with given object doesn't exist
            ResourceNotFound: No ServiceInstantiation related with given VNF instantiation
            ResourceNotFound: VNF related with given object doesn't exist
            InvalidResponse: Invalid dictionary - couldn't create VnfInstantiation object

        Returns:
            VnfInstantiation: VnfInstantiation object

        """
        if request_response.get("request", {}).get("requestScope") == "vnf" and \
            request_response.get("request", {}).get("requestType") == "createInstance":
            service: SdcService = None
            for related_instance in request_response.get("request", {}).get("requestDetails", {})\
                    .get("relatedInstanceList", []):
                if related_instance.get("relatedInstance", {}).get("modelInfo", {})\
                        .get("modelType") == "service":
                    service = SdcService(related_instance.get("relatedInstance", {})\
                        .get("modelInfo", {}).get("modelName"))
            if not service:
                raise ResourceNotFound("No related service in Vnf instance details response")
            vnf: Vnf = None
            for service_vnf in service.vnfs:
                if service_vnf.name == request_response.get("request", {})\
                    .get("requestDetails", {}).get("modelInfo", {}).get("modelCustomizationName"):
                    vnf = service_vnf
            if not vnf:
                raise ResourceNotFound("No vnf in service vnfs list")
            return cls(
                name=request_response.get("request", {})\
                    .get("instanceReferences", {}).get("vnfInstanceName"),
                request_id=request_response.get("request", {}).get("requestId"),
                instance_id=request_response.get("request", {})\
                    .get("instanceReferences", {}).get("vnfInstanceId"),
                line_of_business=request_response.get("request", {})\
                    .get("requestDetails", {}).get("lineOfBusiness", {}).get("lineOfBusinessName"),
                platform=request_response.get("request", {})\
                    .get("requestDetails", {}).get("platform", {}).get("platformName"),
                vnf=vnf
            )
        raise InvalidResponse("Invalid vnf instantions in response dictionary's requestList")
Example #3
0
    def get_by_unique_uuid(cls, unique_uuid: str) -> "Service":
        """Get the service model using unique uuid.

        Returns:
            Service: object with provided unique_uuid

        Raises:
            ResourceNotFound: No service with given unique_uuid exists

        """
        services: List["Service"] = cls.get_all()
        for service in services:
            if service.unique_uuid == unique_uuid:
                return service
        raise ResourceNotFound("Service with given unique uuid doesn't exist")
Example #4
0
    def get(cls, name: str) -> "BaseCategory":
        """Get category with given name.

        Raises:
            ResourceNotFound: Category with given name does not exist

        Returns:
            BaseCategory: BaseCategory instance

        """
        category_obj: "BaseCategory" = cls(name)
        if category_obj.exists():
            return category_obj
        msg = f"{cls.category_name()} with \"{name}\" name does not exist."
        raise ResourceNotFound(msg)
Example #5
0
    def vf_module(self) -> "VfModule":
        """Vf module associated with that vf module instance.

        Returns:
            VfModule: VfModule object associated with vf module instance

        """
        if not self._vf_module:
            for vf_module in self.vnf_instance.vnf.vf_modules:
                if vf_module.model_version_id == self.model_version_id:
                    self._vf_module = vf_module
                    return self._vf_module

            msg = (f'Could not find VF modules for the VF Module instance'
                   f' with model version ID "{self.model_version_id}"')
            raise ResourceNotFound(msg)
        return self._vf_module
Example #6
0
    def get_input(self, input_name: str) -> Input:
        """Get input by it's name.

        Args:
            input_name (str): Input name

        Raises:
            ResourceNotFound: Resource doesn't have input with given name

        Returns:
            Input: Found input object

        """
        for input_obj in self.inputs:
            if input_obj.name == input_name:
                return input_obj
        raise ResourceNotFound(f"SDC resource has no {input_name} input")
Example #7
0
    def get_by_owning_entity_name(cls,
                                  owning_entity_name: str) -> "OwningEntity":
        """Get owning entity resource by it's name.

        Raises:
            ResourceNotFound: Owning entity requested by a name does not exist.

        Returns:
            OwningEntity: Owning entity requested by a name.

        """
        for owning_entity in cls.get_all():
            if owning_entity.name == owning_entity_name:
                return owning_entity

        msg = f'Owning entity "{owning_entity_name}" does not exist.'
        raise ResourceNotFound(msg)
Example #8
0
    def __init__(self, name: str, version: str = None, sdc_values: Dict[str, str] = None):
        """Initialize Vl object.

        Vl has to exists in SDC.

        Args:
            name (str): Vl name
            version (str): Vl version
            sdc_values (Dict[str, str], optional): Sdc values of existing Vl. Defaults to None.

        Raises:
            ResourceNotFound: Vl doesn't exist in SDC

        """
        super().__init__(name=name, version=version, sdc_values=sdc_values)
        if not sdc_values and not self.exists():
            raise ResourceNotFound(
                "This Vl has to exist prior to object initialization.")
    def get_by_name_and_version(cls, blueprint_name: str,
                                blueprint_version: str) -> "BlueprintModel":
        """Retrieve blueprint model with provided name and version.

        Args:
            blueprint_name (str): Blueprint model name
            blueprint_version (str): Blueprint model version

        Returns:
            BlueprintModel: Blueprint model object

        Raises:
            ResourceNotFound: Blueprint model with provided name and version doesn't exist

        """
        try:
            blueprint_model = cls.send_message_json(
                "GET",
                "Retrieve blueprint",
                f"{cls._url}/api/v1/blueprint-model/by-name/{blueprint_name}"
                f"/version/{blueprint_version}",
                auth=cls.auth)

            return cls(
                blueprint_model_id=blueprint_model["blueprintModel"]['id'],
                artifact_uuid=blueprint_model["blueprintModel"]
                ['artifactUUId'],
                artifact_type=blueprint_model["blueprintModel"]
                ['artifactType'],
                artifact_version=blueprint_model["blueprintModel"]
                ['artifactVersion'],
                internal_version=blueprint_model["blueprintModel"]
                ['internalVersion'],
                created_date=blueprint_model["blueprintModel"]['createdDate'],
                artifact_name=blueprint_model["blueprintModel"]
                ['artifactName'],
                published=blueprint_model["blueprintModel"]['published'],
                updated_by=blueprint_model["blueprintModel"]['updatedBy'],
                tags=blueprint_model["blueprintModel"]['tags'])

        except ResourceNotFound:
            raise ResourceNotFound(
                f"BlueprintModel blueprint_name='{blueprint_name}"
                f" and blueprint_version='{blueprint_version}' not found")
Example #10
0
    def get_property(self, property_name: str) -> Property:
        """Get resource property by it's name.

        Args:
            property_name (str): property name

        Raises:
            ResourceNotFound: Resource has no property with given name

        Returns:
            Property: Resource's property object

        """
        for property_obj in self.properties:
            if property_obj.name == property_name:
                return property_obj

        msg = f"Resource has no property with {property_name} name"
        raise ResourceNotFound(msg)
Example #11
0
    def vnf(self) -> "Vnf":
        """Vnf associated with that vnf instance.

        Raises:
            ResourceNotFound: Could not find VNF for that VNF instance

        Returns:
            Vnf: Vnf object associated with vnf instance

        """
        if not self._vnf:
            for vnf in self.service_instance.sdc_service.vnfs:
                if vnf.model_version_id == self.model_version_id:
                    self._vnf = vnf
                    return self._vnf

            msg = (f'Could not find VNF for the VNF instance'
                   f' with model version ID "{self.model_version_id}"')
            raise ResourceNotFound(msg)
        return self._vnf
Example #12
0
    def pnf(self) -> "Pnf":
        """Pnf associated with that pnf instance.

        Raises:
            ResourceNotFound: Could not find PNF for that PNF instance

        Returns:
            Pnf: Pnf object associated with Pnf instance

        """
        if not self._pnf:
            for pnf in self.service_instance.sdc_service.pnfs:
                if pnf.model_version_id == self.model_version_id:
                    self._pnf = pnf
                    return self._pnf

            msg = (f'Could not find PNF for the PNF instance'
                   f' with model version ID "{self.model_version_id}"')
            raise ResourceNotFound(msg)
        return self._pnf
Example #13
0
    def get_component_by_name(self, component_name: str) -> Component:
        """Get resource's component by it's name.

        Get component by name.

        Args:
            component_name (str): Component's name

        Raises:
            ResourceNotFound: Component with given name does not exist

        Returns:
            Component: Component object

        """
        for component in self.components:
            if component.sdc_resource.name == component_name:
                return component
        msg = f"SDC resource {component_name} is not a component"
        raise ResourceNotFound(msg)
Example #14
0
    def get_component(self, sdc_resource: "SdcResource") -> Component:
        """Get resource's component.

        Get component by SdcResource object.

        Args:
            sdc_resource (SdcResource): Component's SdcResource

        Raises:
            ResourceNotFound: Component with given SdcResource does not exist

        Returns:
            Component: Component object

        """
        for component in self.components:
            if component.sdc_resource.name == sdc_resource.name:
                return component
        msg = f"SDC resource {sdc_resource.name} is not a component"
        raise ResourceNotFound(msg)
    def check_loop_template(cls, service: Service) -> str:
        """
        Return loop template name if exists.

        Args:
            service (Service): the distributed sdc service with tca blueprint artifact

        Raises:
            ResourceNotFound: Template not found.

        Returns:
            if required template exists in CLAMP or not

        """
        url = f"{cls.base_url()}/templates/"
        for template in cls.send_message_json('GET',
                                              'Get Loop Templates',
                                              url):
            if template["modelService"]["serviceDetails"]["name"] == service.name:
                return template["name"]
        raise ResourceNotFound("Template not found.")
Example #16
0
    def get_by_id(cls, cloud_owner: str, cloud_region_id: str) -> "CloudRegion":
        """Get CloudRegion object by cloud_owner and cloud-region-id field value.

        This method calls A&AI cloud region API filtering them by cloud_owner and
        cloud-region-id field value.

        Raises:
            ResourceNotFound: Cloud region with given id does not exist.

        Returns:
            CloudRegion: CloudRegion object with given cloud-region-id.

        """
        try:
            return next(cls.get_all(cloud_owner=cloud_owner, cloud_region_id=cloud_region_id))
        except StopIteration:
            msg = (
                f'CloudRegion with {cloud_owner}, '
                f'{cloud_region_id} cloud-id not found. '
            )
            raise ResourceNotFound(msg)
Example #17
0
    def get_nf_unique_id(self, nf_name: str) -> str:
        """
        Get nf (network function) uniqueID.

        Get nf uniqueID from service nf in sdc.

        Args:
            nf_name (str): the nf from which we extract the unique ID

        Returns:
            the nf unique ID

        Raises:
            ResourceNotFound: Couldn't find NF by name.

        """
        url = f"{self._base_create_url()}/services/{self.unique_identifier}"
        request_return = self.send_message_json('GET', 'Get nf unique ID', url)

        for instance in filter(lambda x: x["componentName"] == nf_name,
                               request_return["componentInstances"]):
            return instance["uniqueId"]

        raise ResourceNotFound(f"NF '{nf_name}'")
Example #18
0
    def send_message(
        cls,
        method: str,
        action: str,
        url: str,  # pylint: disable=too-many-locals
        **kwargs
    ) -> Union[requests.Response, None]:
        """
        Send a message to an ONAP service.

        Args:
            method (str): which method to use (GET, POST, PUT, PATCH, ...)
            action (str): what action are we doing, used in logs strings.
            url (str): the url to use
            exception (Exception, optional): if an error occurs, raise the
                exception given instead of RequestError
            **kwargs: Arbitrary keyword arguments. any arguments used by
                requests can be used here.

        Raises:
            RequestError: if other exceptions weren't caught or didn't raise,
                            or if there was an ambiguous exception by a request
            ResourceNotFound: 404 returned
            APIError: returned an error code within 400 and 599, except 404
            ConnectionFailed: connection can't be established

        Returns:
            the request response if OK

        """
        cert = kwargs.pop('cert', None)
        basic_auth: Dict[str, str] = kwargs.pop('basic_auth', None)
        exception = kwargs.pop('exception', None)
        headers = kwargs.pop('headers', cls.headers).copy()
        if OnapService.permanent_headers:
            for header in OnapService.permanent_headers:
                headers.update(header)
        data = kwargs.get('data', None)
        try:
            # build the request with the requested method
            session = cls.__requests_retry_session()
            if cert:
                session.cert = cert
            OnapService._set_basic_auth_if_needed(basic_auth, session)

            cls._logger.debug("[%s][%s] sent header: %s", cls.server, action,
                              headers)
            cls._logger.debug("[%s][%s] url used: %s", cls.server, action, url)
            cls._logger.debug("[%s][%s] data sent: %s", cls.server, action,
                              data)

            response = session.request(method,
                                       url,
                                       headers=headers,
                                       verify=False,
                                       proxies=cls.proxy,
                                       **kwargs)

            cls._logger.info(
                "[%s][%s] response code: %s", cls.server, action,
                response.status_code if response is not None else "n/a")
            cls._logger.debug(
                "[%s][%s] response: %s",
                cls.server, action,
                response.text if (response is not None and
                                  response.headers.get("Content-Type", "") == \
                                      "application/json") else "n/a")

            response.raise_for_status()
            return response

        except HTTPError as cause:
            cls._logger.error("[%s][%s] API returned and error: %s",
                              cls.server, action, headers)

            msg = f'Code: {cause.response.status_code}. Info: {cause.response.text}.'

            if cause.response.status_code == 404:
                exc = ResourceNotFound(msg)
            else:
                exc = APIError(msg)

            raise exc from cause

        except ConnectionError as cause:
            cls._logger.error("[%s][%s] Failed to connect: %s", cls.server,
                              action, cause)

            msg = f"Can't connect to {url}."
            raise ConnectionFailed(msg) from cause

        except RequestException as cause:
            cls._logger.error("[%s][%s] Request failed: %s", cls.server,
                              action, cause)

        if not exception:
            msg = f"Ambiguous error while requesting {url}."
            raise RequestError(msg)

        raise exception