def __init__(self, test_param):
        test_input = {}

        test_input["param1"] = test_param
        test_input["param2"] = generate_dummy_string()
        test_input["param3"] = generate_dummy_date()

        super().__init__(test_input)
Example #2
0
class LicenseModel(Resource):
    resource_name = "LICENSE_MODEL"
    spec = {
        "vendor_name": {
            "type": str,
            "required": False,
            "default": generate_dummy_string("test_vendor_"),
        },
        "manufacturer_reference_number": {
            "type": str,
            "required": False,
            "default": generate_dummy_string("mfref"),
        },
        "entitlement_pool_name": {
            "type": str,
            "required": False,
            "default": generate_dummy_string("test_kg_"),
        },
        "key_group_name": {
            "type": str,
            "required": False,
            "default": generate_dummy_string("test_ep_"),
        },
        "feature_group_name": {
            "type": str,
            "required": False,
            "default": generate_dummy_string("test_fg_"),
        },
        "license_agreement_name": {
            "type": str,
            "required": False,
            "default": generate_dummy_string("test_la_"),
        },
        "license_start_date": {
            "type": str,
            "required": False,
            "default": generate_dummy_date(days=1),
        },
        "license_end_date": {
            "type": str,
            "required": False,
            "default": generate_dummy_date(days=365),
        },
    }

    def _create(self, license_input):
        """Creates a license model object in SDC"""
        return create_license_model(license_input, oc=self.oc)

    def _submit(self):
        """Submits the license model in SDC"""

        self.oc.sdc.license_model.submit_license_model(**self.attributes, action="Submit")

        license_model = self.oc.sdc.license_model.get_license_model(**self.attributes)
        self.attributes["tosca"] = license_model.response_data

    def _output(self):
        return self.tosca
Example #3
0
class Service(Resource):
    resource_name = "SERVICE"
    spec = {
        "instantiation_type": {
            "type": str,
            "required": False,
            "default": "A-la-carte",
        },
        "service_name": {
            "type": str,
            "required": False,
            "default": generate_dummy_string("test_service_"),
        },
        "contact_id": {
            "type": str,
            "required": False,
            "default": "cs0008"
        },
        "category_name": {
            "type": str,
            "required": False,
            "default": "Network L1-3"
        },
        "tag": {
            "type": str,
            "required": False,
            "default": "robot-ete"
        },
        "project_code": {
            "type": str,
            "required": False,
            "default": "123456"
        },
        "environment_context": {
            "type": str,
            "required": False,
            "default": "General_Revenue-Bearing",
        },
        "ecomp_generated_naming": {
            "type": str,
            "required": False,
            "default": "true"
        },
        "description": {
            "type": str,
            "required": False,
            "default": "Brand New Service",
        },
        "service_type": {
            "type": str,
            "required": False,
            "default": ""
        },
        "service_role": {
            "type": str,
            "required": False,
            "default": ""
        },
        "naming_policy": {
            "type": str,
            "required": False,
            "default": ""
        },
        "resources": {
            "type": list,
            "list_item": dict,
            "required": False,
            "default": [],
            "nested": {
                "resource_name": {
                    "type": str,
                    "required": True
                },
                "resource_id": {
                    "type": str,
                    "required": False
                },
                "catalog_resource_name": {
                    "type": str,
                    "required": False
                },
                "origin_type": {
                    "type": str,
                    "required": False,
                    "default": "VF"
                },
                "properties": {
                    "type": dict,
                    "required": False,
                    "default": {}
                },
            },
        },
        "allow_update": {
            "type": bool,
            "required": False,
            "default": False
        },
        "wait_for_distribution": {
            "type": bool,
            "required": False,
            "default": False
        },
    }

    def __init__(
        self,
        instantiation_type,
        service_name,
        contact_id,
        category_name,
        tag,
        project_code,
        environment_context,
        ecomp_generated_naming,
        description,
        service_type,
        service_role,
        naming_policy,
        resources=[],
        wait_for_distribution=False,
        allow_update=False,
    ):
        service_input = {}

        category_name_lower = category_name.lower()
        category_name_icon = normalize_category_icon(category_name)
        category_id = "serviceNewCategory.{}".format(category_name_lower)

        service_input["service_name"] = service_name
        service_input["instantiation_type"] = instantiation_type
        service_input["contact_id"] = contact_id
        service_input["category_name"] = category_name
        service_input["category_id"] = category_id
        service_input["category_name_lower"] = category_name_lower
        service_input["category_name_icon"] = category_name_icon
        service_input["tag"] = tag
        service_input["project_code"] = project_code
        service_input["environment_context"] = environment_context
        service_input["ecomp_generated_naming"] = ecomp_generated_naming
        service_input["description"] = description
        service_input["service_type"] = service_type
        service_input["service_role"] = service_role
        service_input["naming_policy"] = naming_policy
        service_input["resources"] = resources
        service_input["wait_for_distribution"] = wait_for_distribution
        service_input["allow_update"] = allow_update

        super().__init__(service_input)

    def _create(self, service_input):
        """Creates a service object in SDC"""
        service = None

        existing = get_service_id(service_input.get("service_name"))
        if existing is None:
            service = create_service(service_input)
        elif service_input.get("allow_update"):
            service = update_service(existing, service_input)
        else:
            raise exceptions.ResourceAlreadyExistsException(
                "Service resource {} already exists".format(
                    service_input.get("service_name")))

        return service

    def _post_create(self):
        resources = self.resources

        for resource in resources:
            resource_name = resource.get("resource_name")
            catalog_resource_name = resource.get("catalog_resource_name")
            resource_id = resource.get("resource_id")
            resource_properties = resource.get("properties")
            if not resource_id:
                resource_id = get_vnf_id(catalog_resource_name)
                if not resource_id:
                    raise exceptions.ResourceIDNotFoundException(
                        "resource ID was not passed, and resource lookup by name was not found {}"
                        .format(resource_name))
            resource_origin = resource.get("origin_type")
            self.add_resource(resource_id,
                              resource_name,
                              origin_type=resource_origin)
            for k, v in resource_properties.items():
                if isinstance(v, dict):
                    v = json.dumps(v).replace('"', '\\"')
                self.add_property_value(resource_name, k, v)

    def _submit(self):
        """Submits the service in SDC and distributes the model"""
        DISTRIBUTION_STEPS = sdc_properties.SERVICE_DISTRIBUTION or []

        service_client.checkin_service(**self.attributes,
                                       user_remarks="checking in")

        if (not DISTRIBUTION_STEPS
                or "request_service_certification" in DISTRIBUTION_STEPS):
            service_client.request_service_certification(
                **self.attributes, user_remarks="requesting certification")

        if (not DISTRIBUTION_STEPS
                or "start_service_certification" in DISTRIBUTION_STEPS):
            service_client.start_service_certification(
                **self.attributes, user_remarks="certifying")

        if (not DISTRIBUTION_STEPS
                or "finish_service_certification" in DISTRIBUTION_STEPS):
            catalog_service = service_client.finish_service_certification(
                **self.attributes, user_remarks="certified")
            self.attributes[
                "catalog_service_id"] = catalog_service.catalog_service_id

        if (not DISTRIBUTION_STEPS
                or "approve_service_certification" in DISTRIBUTION_STEPS):
            service_client.approve_service_certification(
                **self.attributes, user_remarks="approved")
        headers = {"X-TransactionId": str(uuid.uuid4())}
        service_client.distribute_sdc_service(**self.attributes, **headers)

        if self.wait_for_distribution:
            poll_distribution(self.service_name)

        self._refresh()

    def add_resource(self,
                     catalog_resource_id,
                     catalog_resource_name,
                     origin_type="VF"):
        """Attaches a resource to a Service in SDC

        :catalog_resource_id: ID of a resource in the SDC catalog
        :catalog_resource_name: name to give to the resource when attaching to service
        :origin_type: specifies the origin of the attached resource

        """
        milli_timestamp = int(time.time() * 1000)
        component_instances = self.tosca.get("componentInstances", [])
        if component_instances:
            for component in component_instances:
                if component.get("componentName") == catalog_resource_name:
                    service_client.delete_resource_from_service(
                        catalog_service_id=self.catalog_service_id,
                        resource_instance_id=component.get("uniqueId"))
                    break

        resource_instance = service_client.add_resource_instance(
            **self.attributes,
            posX=random.randrange(150, 550),  # nosec
            posY=random.randrange(150, 450),  # nosec
            milli_timestamp=milli_timestamp,
            catalog_resource_id=catalog_resource_id,
            catalog_resource_name=catalog_resource_name,
            originType=origin_type,
        ).response_data

        response = {
            "id": resource_instance.get("uniqueId"),
            "tosca": resource_instance,
        }
        self.attributes[catalog_resource_name] = response

        self._refresh()

    def add_property_value(self, resource_name, property_name, input_value):
        """Updates an property value on a resource attached to a Service

        :resource_name: Name of a resource attached to a service
        :property_name: property name to update
        :input_value: value to update property with

        """
        resource = self.attributes.get(resource_name)
        if not resource:
            raise exceptions.ResourceNotFoundException(
                "Resource {} was not found on Service {}".format(
                    resource_name, self.service_name))
        resource_id = resource["id"]

        instance_inputs = self.tosca.get("componentInstancesProperties",
                                         {}).get(resource_id, [])
        for prop in instance_inputs:
            if prop.get("name") == property_name:
                unique_id = prop.get("uniqueId")
                parent_unique_id = prop.get("parentUniqueId")
                owner_id = prop.get("ownerId")
                schemaType = prop.get("schemaType", "")
                property_type = prop.get("type")
                return service_client.add_catalog_service_property(
                    **self.attributes,
                    unique_id=unique_id,
                    parent_unique_id=parent_unique_id,
                    owner_id=owner_id,
                    catalog_resource_instance_id=resource_id,
                    input_name=property_name,
                    input_value=input_value,
                    schema_type=schemaType,
                    property_type=property_type,
                )

        raise exceptions.PropertyNotFoundException(
            "Property {} was not found in VF Instance {}".format(
                property_name, resource_id))

    def _refresh(self):
        self.tosca = service_client.get_sdc_service(
            catalog_service_id=self.catalog_service_id).response_data
class ServiceInstance(Resource):
    resource_name = "SERVICE_INSTANCE"
    spec = {
        "service_instance_name": {
            "type": str,
            "required": False,
            "default": generate_dummy_string("SI_"),
        },
        "requestor_id": {"type": str, "required": False, "default": "cs0008"},
        "model_name": {"type": str, "required": True},
        "model_version": {"type": str, "required": False, "default": "1.0"},
        "tenant_name": {"type": str, "required": True},
        "cloud_owner": {"type": str, "required": True},
        "cloud_region": {"type": str, "required": True},
        "api_type": {"type": str, "required": False, "default": "GR_API"},
        "service_type": {"type": str, "required": True},
        "customer_name": {"type": str, "required": True},
        "project_name": {"type": str, "required": True},
        "owning_entity_name": {"type": str, "required": True},
    }

    def __init__(
        self,
        service_instance_name,
        requestor_id,
        model_name,
        model_version,
        tenant_name,
        cloud_owner,
        cloud_region,
        api_type,
        service_type,
        customer_name,
        project_name,
        owning_entity_name,
    ):
        instance_input = {}

        tenant_id = get_tenant_id(cloud_region, cloud_owner, tenant_name)

        instance_input["service_instance_name"] = service_instance_name
        instance_input["requestor_id"] = requestor_id
        instance_input["model_name"] = model_name
        instance_input["model_version"] = model_version
        instance_input["tenant_id"] = tenant_id
        instance_input["cloud_owner"] = cloud_owner
        instance_input["cloud_region"] = cloud_region
        instance_input["api_type"] = api_type
        instance_input["service_type"] = service_type
        instance_input["customer_id"] = customer_name
        instance_input["project_name"] = project_name
        instance_input["owning_entity_name"] = owning_entity_name

        super().__init__(instance_input)

    def _create(self, instance_input):
        service_model = sdc_client.service.get_sdc_service(
            catalog_service_id=sdc.service.get_service_id(
                instance_input.get("model_name")
            )
        ).response_data

        instance_input["model_invariant_id"] = service_model["invariantUUID"]
        instance_input["model_version_id"] = service_model["uniqueId"]

        category_parameters = vid_client.maintenance.get_category_parameters().response_data
        for entity in category_parameters.get("categoryParameters", {}).get("owningEntity", []):
            if entity.get("name") == instance_input.get("owning_entity_name"):
                instance_input["owning_entity_id"] = entity.get("id")
                break

        return create_service_instance(instance_input)

    def _post_create(self):
        pass

    def _submit(self):
        pass
class VNFInstance(Resource):
    resource_name = "VNF_INSTANCE"
    spec = {
        "vnf_instance_name": {
            "type": str,
            "required": False,
            "default": generate_dummy_string("VNF_"),
        },
        "service_instance_name": {
            "type": str,
            "required": True
        },
        "requestor_id": {
            "type": str,
            "required": False,
            "default": "cs0008"
        },
        "model_name": {
            "type": str,
            "required": True
        },
        "tenant_name": {
            "type": str,
            "required": True
        },
        "cloud_owner": {
            "type": str,
            "required": True
        },
        "cloud_region": {
            "type": str,
            "required": True
        },
        "api_type": {
            "type": str,
            "required": False,
            "default": "GR_API"
        },
        "platform": {
            "type": str,
            "required": True
        },
        "line_of_business": {
            "type": str,
            "required": True
        },
    }

    def __init__(
        self,
        vnf_instance_name,
        service_instance_name,
        requestor_id,
        model_name,
        tenant_name,
        cloud_owner,
        cloud_region,
        api_type,
        platform,
        line_of_business,
    ):
        instance_input = {}

        tenant_id = so.service_instance.get_tenant_id(cloud_region,
                                                      cloud_owner, tenant_name)

        instance_input["vnf_instance_name"] = vnf_instance_name
        instance_input["service_instance_name"] = service_instance_name
        instance_input["requestor_id"] = requestor_id
        instance_input["model_name"] = model_name
        instance_input["tenant_id"] = tenant_id
        instance_input["cloud_owner"] = cloud_owner
        instance_input["cloud_region"] = cloud_region
        instance_input["api_type"] = api_type
        instance_input["platform"] = platform
        instance_input["line_of_business"] = line_of_business

        super().__init__(instance_input)

    def _create(self, instance_input):
        service_instance = get_service_instance(
            instance_input.get("service_instance_name"))
        if not service_instance:
            raise ServiceInstanceNotFound(
                "No service instance found for {}".format(
                    instance_input.get("service_instance_name")))
        service_instance_id = service_instance.get("service-instance-id")
        model_information = (service_instance.get("service-data").get(
            "service-information").get("onap-model-information"))
        service_invariant_id = model_information["model-invariant-uuid"]
        service_model_id = model_information["model-uuid"]
        service_model_version = model_information["model-version"]
        service_model_name = model_information["model-name"]

        vnf_component = get_vnf_model_component(
            service_model_name, instance_input.get("model_name"))
        if not vnf_component:
            raise VNFComponentNotFound("No component found for {}".format(
                instance_input.get("model_name")))
        vnf_model_customization_id = vnf_component["customizationUUID"]
        vnf_model_version_id = vnf_component["actualComponentUid"]
        vnf_model_version = vnf_component["componentVersion"]

        vnf_model = sdc_client.vnf.get_catalog_resource(
            catalog_resource_id=vnf_model_version_id, ).response_data
        vnf_model_invariant_id = vnf_model["invariantUUID"]

        instance_input["model_invariant_id"] = vnf_model_invariant_id
        instance_input["model_version_id"] = vnf_model_version_id
        instance_input["model_customization_id"] = vnf_model_customization_id
        instance_input["model_version"] = vnf_model_version
        instance_input["service_model_name"] = service_model_name
        instance_input["service_model_invariant_id"] = service_invariant_id
        instance_input["service_model_version"] = service_model_version
        instance_input["service_model_version_id"] = service_model_id
        instance_input["service_instance_id"] = service_instance_id

        return create_vnf_instance(instance_input)

    def _post_create(self):
        pass

    def _submit(self):
        pass
class VNFInstance(Resource):
    resource_name = "VNF_INSTANCE"
    spec = {
        "vnf_instance_name": {
            "type": str,
            "required": False,
            "default": generate_dummy_string("VNF_"),
        },
        "service_instance_name": {
            "type": str,
            "required": True
        },
        "requestor_id": {
            "type": str,
            "required": False,
            "default": "cs0008"
        },
        "model_name": {
            "type": str,
            "required": True
        },
        "tenant_name": {
            "type": str,
            "required": True
        },
        "cloud_owner": {
            "type": str,
            "required": True
        },
        "cloud_region": {
            "type": str,
            "required": True
        },
        "api_type": {
            "type": str,
            "required": False,
            "default": "GR_API"
        },
        "platform": {
            "type": str,
            "required": True
        },
        "line_of_business": {
            "type": str,
            "required": True
        },
    }

    def _create(self, instance_input):
        tenant_id = so.service_instance.get_tenant_id(
            instance_input.get("cloud_region"),
            instance_input.get("cloud_owner"),
            instance_input.get("tenant_name"),
            oc=self.oc)
        instance_input["tenant_id"] = tenant_id

        service_instance = so.service_instance.get_service_instance(
            instance_input.get("service_instance_name"), oc=self.oc)
        service_instance_id = service_instance.get("service-instance-id")
        model_information = (service_instance.get("service-data").get(
            "service-information").get("onap-model-information"))
        service_invariant_id = model_information["model-invariant-uuid"]
        service_model_id = model_information["model-uuid"]
        service_model_version = model_information["model-version"]
        service_model_name = model_information["model-name"]

        vnf_component = get_vnf_model_component(
            service_model_name, instance_input.get("model_name"), oc=self.oc)
        if not vnf_component:
            raise VNFComponentNotFound("No component found for {}".format(
                instance_input.get("model_name")))
        vnf_model_customization_id = vnf_component["customizationUUID"]
        vnf_model_version_id = vnf_component["actualComponentUid"]
        vnf_model_version = vnf_component["componentVersion"]

        vnf_model = self.oc.sdc.vnf.get_catalog_resource(
            catalog_resource_id=vnf_model_version_id, ).response_data
        vnf_model_invariant_id = vnf_model["invariantUUID"]

        instance_input["model_invariant_id"] = vnf_model_invariant_id
        instance_input["model_version_id"] = vnf_model_version_id
        instance_input["model_customization_id"] = vnf_model_customization_id
        instance_input["model_version"] = vnf_model_version
        instance_input["service_model_name"] = service_model_name
        instance_input["service_model_invariant_id"] = service_invariant_id
        instance_input["service_model_version"] = service_model_version
        instance_input["service_model_version_id"] = service_model_id
        instance_input["service_instance_id"] = service_instance_id

        return create_vnf_instance(instance_input, oc=self.oc)

    def _delete(self, instance_input):
        request = delete_vnf_instance(
            instance_input.get("service_instance_name"),
            instance_input.get("vnf_instance_name"),
            instance_input.get("api_type"),
            oc=self.oc)
        request_id = request.get("requestReferences", {}).get("requestId")
        so.service_instance.poll_request(request_id, oc=self.oc)
Example #7
0
class VNF(Resource):
    resource_name = "VNF"
    spec = {
        "software_product_name": {"type": str, "required": True},
        "description": {"type": str, "required": False, "default": "VNF"},
        "vnf_name": {
            "type": str,
            "required": False,
            "default": generate_dummy_string("test_vnf_"),
        },
        "resource_type": {"type": str, "required": False, "default": "VF"},
        "inputs": {"type": dict, "required": False, "default": {}},
        "vm_types": {
            "type": list,
            "list_item": dict,
            "required": False,
            "default": [],
            "nested": {
                "vm_type": {"type": str, "required": True},
                "properties": {"type": dict, "required": True, "default": {}},
                "resources": {
                    "type": list,
                    "list_item": dict,
                    "required": False,
                    "default": [],
                    "nested": {
                        "resource_name": {"type": str, "required": True},
                        "resource_id": {"type": str, "required": False},
                        "catalog_resource_name": {"type": str, "required": False},
                        "origin_type": {"type": str, "required": False, "default": "VF"},
                        "properties": {"type": dict, "required": False, "default": {}},
                        "relationship": {
                            "type": dict,
                            "required": False,
                            "default": {},
                            "nested": {
                                "relationship_type": {"type": str, "required": True},
                                "requirement": {"type": str, "required": True},
                                "requirement_id": {"type": str, "required": True},
                                "properties": {"type": dict, "required": False, "default": {}},
                            }
                        },
                    },
                },
            },
        },
        "network_roles": {
            "type": list,
            "list_item": dict,
            "required": False,
            "default": [],
            "nested": {
                "network_role_tag": {"type": str, "required": True},
                "network_role": {"type": str, "required": True},
                "related_networks": {
                    "type": list,
                    "list_item": str,
                    "required": False,
                    "default": [],
                },
            },
        },
        "policies": {
            "type": list,
            "list_item": dict,
            "required": False,
            "default": [],
            "nested": {
                "policy_name": {"type": str, "required": True},
                "properties": {"type": dict, "required": False, "default": {}},
            },
        },
        "allow_update": {"type": bool, "required": False, "default": False},
    }

    def _create(self, vnf_input):
        """Creates a vnf object in SDC"""
        vnf = None

        existing = get_vnf_id(vnf_input.get("vnf_name"))
        if not existing:
            vnf = create_vnf(vnf_input)
        elif vnf_input.get("allow_update"):
            vnf = update_vnf(existing, vnf_input)
        else:
            raise exceptions.ResourceAlreadyExistsException(
                "VNF resource {} already exists".format(vnf_input.get("vnf_name"))
            )

        return vnf

    def _post_create(self):
        inputs = self.inputs
        vm_types = self.vm_types
        network_roles = self.network_roles
        policies = self.policies
        model = self.tosca
        vm_type_instances = []

        for vm_type in vm_types:
            vm_type_tag = vm_type.get("vm_type")
            properties = vm_type.get("properties")
            resources = vm_type.get("resources", [])
            instance_ids = instance_ids_for_property(model, "vm_type_tag", vm_type_tag)
            x = 0
            for instance_id in instance_ids:
                name_index = ""
                if x > 0:
                    name_index = x
                vm_type_instances.append(instance_id)
                self._add_instance_properties(instance_id, properties)
                self._add_resources(instance_id, resources, resource_name_index=name_index)
                self._add_vm_type_network_role(instance_id, network_roles)
                x += 1

        for policy in policies:
            policy_name = policy.get("policy_name")
            policy_id = self.policy_exists(policy_name)
            if not policy_id:
                policy_id = self.add_policy_resource(policy_name)
                self.associate_policy(policy_id, vm_type_instances)
            for k, v in policy.get("properties", {}).items():
                self.add_policy_property(policy_id, k, v)

        for k, v in inputs.items():
            self.add_input_value(k, v)

    def _submit(self):
        """Submits the vnf in SDC"""
        certification = self.oc.sdc.vnf.certify_catalog_resource(
            **self.attributes, user_remarks="Ready!"
        )
        self.attributes["catalog_resource_id"] = certification.catalog_resource_id

        vnf = self.oc.sdc.vnf.get_catalog_resource(**self.attributes)

        self.attributes["catalog_resource_name"] = vnf.catalog_resource_name
        self.attributes["tosca"] = vnf.response_data

    def _add_instance_properties(self, instance_id, properties_dict):
        for k, v in properties_dict.items():
            # updating vm_type properties
            self.add_instance_property(instance_id, k, v)

    def _add_resources(self, instance_id, resources_dict, resource_name_index=""):
        for resource in resources_dict:
            resource_name = resource.get("resource_name")
            if resource_name_index:
                resource_name = "{}-{}".format(resource_name, resource_name_index)

            if self.resource_exists(resource_name):
                continue

            catalog_resource_name = resource.get("catalog_resource_name")
            resource_id = resource.get("resource_id")
            resource_origin = resource.get("origin_type")
            resource_relationship = resource.get("relationship", {})

            if not resource_id:
                resource_id = get_vnf_id(catalog_resource_name)
                if not resource_id:
                    raise exceptions.ResourceIDNotFoundException(
                        "resource ID was not passed, and resource lookup by name was not found {}".format(
                            resource_name
                        )
                    )
            new_resource = add_resource(self.catalog_resource_id, resource_id, resource_name, origin_type=resource_origin)
            self._refresh()
            new_resource_id = new_resource["id"]
            if resource_relationship:
                relationship_type = resource_relationship.get("relationship_type")
                relationship_requirement = resource_relationship.get("requirement")
                relationship_requirement_id = resource_relationship.get("requirement_id")
                self.add_resource_relationship(new_resource_id, instance_id, relationship_type, relationship_requirement, relationship_requirement_id)
                for k, v in resource_relationship.get("properties", {}).items():
                    self.add_instance_property_non_vf(new_resource_id, k, v, origin_section="componentInstancesProperties")

    def add_resource_relationship(self, from_node, to_node, relationship_type, relationship_requirement, relationship_requirement_id):
        components = self.tosca.get("componentInstances", [])
        for component in components:
            if component.get("uniqueId") == to_node:
                capabilities = component.get("capabilities", {}).get(relationship_type, [])
                for capability in capabilities:
                    capability_owner_id = capability.get("ownerId")
                    capability_name = capability.get("name")
                    capability_uid = capability.get("uniqueId")

                    self.oc.sdc.vnf.add_resource_relationship(
                        **self.attributes,
                        from_node_resource_id=from_node,
                        to_node_resource_id=to_node,
                        relationship_type=relationship_type,
                        capability_name=capability_name,
                        capability_owner_id=capability_owner_id,
                        capability_id=capability_uid,
                        requirement_name=relationship_requirement,
                        requirement_id=relationship_requirement_id,
                    )

    def _add_vm_type_network_role(self, instance_id, network_roles_dict):
        model = self.tosca
        for network_role in network_roles_dict:
            # checking if abstract node has matching network role,
            # and updating if found
            nrt = network_role.get("network_role_tag")
            nr = network_role.get("network_role")
            related_networks = network_role.get("related_networks")
            instance_properties = network_role_property_for_instance(
                nrt, model, instance_id
            )
            for instance_property in instance_properties:
                self.add_instance_property(instance_id, instance_property, nr)
                if related_networks:
                    property_val = [
                        {"related_network_role": related_network_role}
                        for related_network_role in related_networks
                    ]
                    rnr_instance_property = instance_property.replace(
                        "_network_role", "_related_networks"
                    )
                    self.add_instance_property(
                        instance_id,
                        rnr_instance_property,
                        str(property_val).replace("'", '\\"'),
                    )

    def resource_exists(self, resource_name):
        """Checking the tosca model for a VF to see if a resource
        has already been added"""

        component_instances = self.tosca.get("componentInstances", [])

        for component in component_instances:
            if component.get("name") == resource_name:
                return True

        return False

    def policy_exists(self, policy_name):
        """Checking the tosca model for a VF to see if a resource
        has already been added

        The policy name in the tosca model is all lowercase,
        and if there are dashes in the VNF name they are
        removed in the policy name.
        """

        policies = self.tosca.get("policies", {})

        for p_name, policy in policies.items():
            tosca_policy_name = policy.get("name").lower()
            if tosca_policy_name.find("{}..{}".format(self.vnf_name.lower().replace("-", ""), policy_name.lower())) != -1:
                return policy.get("uniqueId")

        return None

    def add_input_value(self, input_name, input_default_value):
        """Updates an input value on a VNF

        :input_name: input name to update
        :property_value: value to update input with

        """
        inputs = self.tosca.get("inputs", [])
        for item in inputs:
            if item["name"] == input_name:
                unique_id = item["uniqueId"]
                parent_unique_id = item["parentUniqueId"]
                owner_id = item["ownerId"]
                default_value = item.get("defaultValue", "")
                if default_value != input_default_value:
                    return self.oc.sdc.vnf.add_catalog_resource_input(
                        **self.attributes,
                        input_default_value=input_default_value,
                        input_name=input_name,
                        input_parent_unique_id=parent_unique_id,
                        input_unique_id=unique_id,
                        input_owner_id=owner_id,
                    )
                else:
                    return None

        raise exceptions.InputNotFoundException(
            "Input {} was not found in VF".format(input_name)
        )

    # TODO
    # instance, policy, and group properties can probably be merged
    # rn there is a lot of dup

    def add_instance_property(self, instance_id, property_name, property_value, origin_section="componentInstancesInputs"):
        """Updates an instance property on a abstract instance attached to a VNF

        :instance_id: ID of a instance attached to a VNF
        :property_name: property name to update
        :property_value: value to update property with

        """
        instance_inputs = self.tosca.get(origin_section, {}).get(
            instance_id, {}
        )

        for prop in instance_inputs:
            if prop.get("name") == property_name:
                unique_id = prop.get("uniqueId")
                parent_unique_id = prop.get("parentUniqueId")
                owner_id = prop.get("ownerId")
                schemaType = prop.get("schemaType", "")
                property_type = prop.get("type")
                value = prop.get("value", "")
                if value != property_value:
                    return self.oc.sdc.vnf.add_catalog_resource_property(
                        **self.attributes,
                        unique_id=unique_id,
                        parent_unique_id=parent_unique_id,
                        owner_id=owner_id,
                        catalog_resource_instance_id=instance_id,
                        property_name=property_name,
                        property_default_value=property_value,
                        schema_type=schemaType,
                        property_type=property_type,
                    )
                else:
                    return None

        raise exceptions.PropertyNotFoundException(
            "Property {} was not found in Instance {}".format(
                property_name, instance_id
            )
        )

    def add_instance_property_non_vf(self, instance_id, property_name, property_value, origin_section="componentInstancesProperties"):
        """Updates an instance property on a abstract instance attached to a VNF

        :instance_id: ID of a instance attached to a VNF
        :property_name: property name to update
        :property_value: value to update property with

        """
        instance_inputs = self.tosca.get(origin_section, {}).get(
            instance_id, {}
        )

        for prop in instance_inputs:
            if prop.get("name") == property_name:
                unique_id = prop.get("uniqueId")
                parent_unique_id = prop.get("parentUniqueId")
                owner_id = prop.get("ownerId")
                schemaType = prop.get("schemaType", "")
                property_type = prop.get("type")
                value = prop.get("value", "")
                if value != property_value:
                    return self.oc.sdc.vnf.add_catalog_resource_property_non_vf(
                        **self.attributes,
                        unique_id=unique_id,
                        parent_unique_id=parent_unique_id,
                        owner_id=owner_id,
                        catalog_resource_instance_id=instance_id,
                        property_name=property_name,
                        property_default_value=property_value,
                        schema_type=schemaType,
                        property_type=property_type,
                    )
                else:
                    return None

        raise exceptions.PropertyNotFoundException(
            "Property {} was not found in Instance {}".format(
                property_name, instance_id
            )
        )

    def add_policy_property(self, policy_id, property_name, property_value):
        """Updates a policy property on a polic attached to a VNF

        :policy_id: ID of a policy attached to a VNF
        :property_name: property name to update
        :property_value: value to update property with

        """
        policies = (
            self.tosca.get("policies", {}).get(policy_id, {}).get("properties", {})
        )

        for prop in policies:
            if prop.get("name") == property_name:
                unique_id = prop.get("uniqueId")
                property_type = prop.get("type")
                description = prop.get("description")
                value = prop.get("value", "")
                if value != property_value:
                    return self.oc.sdc.vnf.add_catalog_policy_property(
                        catalog_resource_id=self.catalog_resource_id,
                        unique_id=unique_id,
                        catalog_policy_id=policy_id,
                        property_name=property_name,
                        property_default_value=property_value,
                        description=description,
                        property_type=property_type,
                    )
                else:
                    return None

        raise exceptions.PropertyNotFoundException(
            "Property {} was not found in policy {}".format(property_name, policy_id)
        )

    def add_policy_resource(self, policy_name):
        """Adds an SDC policy resource to a VNF

        :policy_name: name of the policy, matching onap-client.conf

        """
        oc = Client()

        policy = oc.config.sdc.POLICIES.get(policy_name)
        if not policy:
            raise exceptions.UnknownPolicyException(
                "Policy {} was not found in configuration file".format(policy_name)
            )

        new_policy = self.oc.sdc.vnf.add_catalog_resource_policy(
            **self.attributes, catalog_policy_name=policy
        )

        self._refresh()

        return new_policy.catalog_resource_id

    def associate_policy(self, policy_id, instance_ids):
        """associates an SDC policy resource to an VNF instance resource

        :policy_id: ID of policy resource from catalog
        :instance_ids: list of instance ids to associate policy with

        """

        return self.oc.sdc.vnf.add_policy_to_instance(
            **self.attributes, catalog_policy_id=policy_id, instance_ids=instance_ids
        )

    def _refresh(self):
        """GETs the VNF model from SDC and updates the VNF object"""
        vnf = self.oc.sdc.vnf.get_catalog_resource(**self.attributes)
        self.attributes["tosca"] = vnf.response_data

    def _output(self):
        return self.tosca
Example #8
0
class VSP(Resource):
    resource_name = "VSP"
    spec = {
        "vendor_name": {
            "type": str,
            "required": True
        },
        "license_model_name": {
            "type": str,
            "required": True
        },
        "file_path": {
            "type": str,
            "required": True
        },
        "file_type": {
            "type": str,
            "required": False,
            "default": "application/zip"
        },
        "software_product_name": {
            "type": str,
            "required": False,
            "default": generate_dummy_string("test_vsp_"),
        },
        "description": {
            "type": str,
            "required": False,
            "default": "new software product",
        },
        "category": {
            "type": str,
            "required": False,
            "default": "generic"
        },
        "sub_category": {
            "type": str,
            "required": False,
            "default": "abstract"
        },
        "contributers": {
            "type": list,
            "list_item": str,
            "required": False,
            "default": [],
        },
        "allow_update": {
            "type": bool,
            "required": False,
            "default": False
        },
    }

    def __init__(
        self,
        vendor_name,
        license_model_name,
        file_path,
        file_type,
        software_product_name,
        description,
        category,
        sub_category,
        contributers=[],
        allow_update=False,
    ):

        vsp_input = {}

        license_model_id = sdc.license_model.get_license_model_id(
            license_model_name)
        license_model_version_id = sdc.license_model.get_license_model_version_id(
            license_model_id)
        feature_group = sdc.license_model.get_license_model_attribute(
            license_model_id, license_model_version_id, "feature-groups")
        license_agreement = sdc.license_model.get_license_model_attribute(
            license_model_id, license_model_version_id, "license-agreements")

        vsp_input["software_product_name"] = software_product_name
        vsp_input["feature_group_id"] = feature_group["id"]
        vsp_input["license_agreement_id"] = license_agreement["id"]
        vsp_input["vendor_name"] = vendor_name
        vsp_input["license_model_id"] = license_model_id
        vsp_input["license_model_version_id"] = license_model_version_id
        vsp_input["file_path"] = file_path
        vsp_input["file_type"] = file_type
        vsp_input["description"] = description
        vsp_input["category"] = category.lower()
        vsp_input["sub_category"] = sub_category.lower()
        vsp_input["contributers"] = contributers
        vsp_input["allow_update"] = allow_update

        super().__init__(vsp_input)

    def _create(self, kwargs):
        """Creates a vsp object in SDC"""
        vsp = None

        existing = get_vsp(kwargs.get("software_product_name"))
        if not existing:
            vsp = create_vsp(kwargs)
        elif kwargs.get("allow_update"):
            vsp = update_vsp(existing, kwargs)
        else:
            raise ResourceAlreadyExistsException(
                "VSP resource {} already exists".format(
                    kwargs.get("software_product_name")))

        return vsp

    def _post_create(self):
        for contributer in self.contributers:
            vsp_client.add_vsp_contributer(
                user_id=contributer,
                software_product_id=self.software_product_id)

    def _submit(self):
        """Submits the vsp in SDC"""
        vsp_client.submit_software_product(**self.attributes, action="Submit")
        vsp_client.package_software_product(**self.attributes,
                                            action="Create_Package")

        vsp = vsp_client.get_software_product(**self.attributes)
        self.attributes["tosca"] = vsp.response_data
class LicenseModel(Resource):
    resource_name = "LICENSE_MODEL"
    spec = {
        "vendor_name": {
            "type": str,
            "required": False,
            "default": generate_dummy_string("test_vendor_"),
        },
        "mfr_ref_number": {
            "type": str,
            "required": False,
            "default": generate_dummy_string("mfref"),
        },
        "entitlement_pool_name": {
            "type": str,
            "required": False,
            "default": generate_dummy_string("test_kg_"),
        },
        "key_group_name": {
            "type": str,
            "required": False,
            "default": generate_dummy_string("test_ep_"),
        },
        "feature_group_name": {
            "type": str,
            "required": False,
            "default": generate_dummy_string("test_fg_"),
        },
        "license_agreement_name": {
            "type": str,
            "required": False,
            "default": generate_dummy_string("test_la_"),
        },
        "license_start_date": {
            "type": str,
            "required": False,
            "default": generate_dummy_date(days=1),
        },
        "license_end_date": {
            "type": str,
            "required": False,
            "default": generate_dummy_date(days=365),
        },
    }

    def __init__(
        self,
        vendor_name,
        mfr_ref_number,
        entitlement_pool_name,
        key_group_name,
        feature_group_name,
        license_agreement_name,
        license_start_date,
        license_end_date,
    ):

        license_input = {}
        license_input["vendor_name"] = vendor_name
        license_input["manufacturer_reference_number"] = mfr_ref_number
        license_input["entitlement_pool_name"] = entitlement_pool_name
        license_input["key_group_name"] = key_group_name
        license_input["feature_group_name"] = feature_group_name
        license_input["license_agreement_name"] = license_agreement_name
        license_input["license_start_date"] = license_start_date
        license_input["license_end_date"] = license_end_date

        super().__init__(license_input)

    def _create(self, license_input):
        """Creates a license model object in SDC"""
        return create_license_model(license_input)

    def _post_create(self):
        pass

    def _submit(self):
        """Submits the license model in SDC"""

        license_model_client.submit_license_model(**self.attributes,
                                                  action="Submit")

        license_model = license_model_client.get_license_model(
            **self.attributes)
        self.attributes["tosca"] = license_model.response_data
Example #10
0
class VSP(Resource):
    resource_name = "VSP"
    spec = {
        "owner": {
            "type": str,
            "required": False,
            "default": ""
        },
        "vendor_name": {
            "type": str,
            "required": True
        },
        "license_model_name": {
            "type": str,
            "required": True
        },
        "file_path": {
            "type": str,
            "required": True
        },
        "file_type": {
            "type": str,
            "required": False,
            "default": "application/zip"
        },
        "software_product_name": {
            "type": str,
            "required": False,
            "default": generate_dummy_string("test_vsp_"),
        },
        "description": {
            "type": str,
            "required": False,
            "default": "new software product",
        },
        "update_message": {
            "type": str,
            "required": False,
            "default": "New VSP Version",
        },
        "category": {
            "type": str,
            "required": False,
            "default": "generic"
        },
        "sub_category": {
            "type": str,
            "required": False,
            "default": "abstract"
        },
        "contributers": {
            "type": list,
            "list_item": str,
            "required": False,
            "default": [],
        },
        "allow_update": {
            "type": bool,
            "required": False,
            "default": False
        },
    }

    def _create(self, vsp_input):
        """Creates a vsp object in SDC"""
        vsp = None

        existing = get_vsp(vsp_input.get("software_product_name"), oc=self.oc)
        if not existing:
            vsp = create_vsp(vsp_input, oc=self.oc)
        elif vsp_input.get("allow_update"):
            vsp = update_vsp(existing, vsp_input, oc=self.oc)
        else:
            raise ResourceAlreadyExistsException(
                "VSP resource {} already exists".format(
                    vsp_input.get("software_product_name")))

        return vsp

    def _post_create(self):
        vsp_permissions = self.oc.sdc.vsp.get_vsp_permissions(
            software_product_id=self.software_product_id).response_data.get(
                "results", [])
        requestor_id = self.oc.sdc.vsp.catalog_resources[
            "MODIFY_VSP_OWNER"].get("headers").get("USER_ID")

        if user_exists(requestor_id, vsp_permissions, permission="Owner"):
            for contributer in self.contributers:
                if (not user_exists(
                        contributer, vsp_permissions, permission="Contributor")
                        and contributer != requestor_id):
                    self.oc.sdc.vsp.add_vsp_contributer(
                        user_id=contributer,
                        software_product_id=self.software_product_id)

            if self.owner and self.owner != requestor_id:
                self.oc.sdc.vsp.modify_vsp_owner(
                    user_id=self.owner,
                    software_product_id=self.software_product_id)

    def _submit(self):
        """Submits the vsp in SDC"""
        self.oc.sdc.vsp.submit_software_product(**self.attributes,
                                                action="Submit")
        self.oc.sdc.vsp.package_software_product(**self.attributes,
                                                 action="Create_Package")

        vsp = self.oc.sdc.vsp.get_software_product(**self.attributes)
        self.attributes["tosca"] = vsp.response_data

    def _output(self):
        return self.tosca
Example #11
0
class ServiceInstance(Resource):
    resource_name = "SERVICE_INSTANCE"
    spec = {
        "service_instance_name": {
            "type": str,
            "required": False,
            "default": generate_dummy_string("SI_"),
        },
        "requestor_id": {
            "type": str,
            "required": False,
            "default": "cs0008"
        },
        "model_name": {
            "type": str,
            "required": True
        },
        "model_version": {
            "type": str,
            "required": False,
            "default": "1.0"
        },
        "tenant_name": {
            "type": str,
            "required": True
        },
        "cloud_owner": {
            "type": str,
            "required": True
        },
        "cloud_region": {
            "type": str,
            "required": True
        },
        "api_type": {
            "type": str,
            "required": False,
            "default": "GR_API"
        },
        "service_type": {
            "type": str,
            "required": True
        },
        "customer_name": {
            "type": str,
            "required": True
        },
        "project_name": {
            "type": str,
            "required": True
        },
        "owning_entity_name": {
            "type": str,
            "required": True
        },
    }

    def _create(self, instance_input):
        tenant_id = get_tenant_id(instance_input.get("cloud_region"),
                                  instance_input.get("cloud_owner"),
                                  instance_input.get("tenant_name"),
                                  oc=self.oc)
        instance_input["tenant_id"] = tenant_id
        instance_input["customer_id"] = instance_input.get("customer_name")

        service_model = self.oc.sdc.service.get_sdc_service(
            catalog_service_id=sdc.service.get_service_id(
                instance_input.get("model_name"), oc=self.oc)).response_data

        instance_input["model_invariant_id"] = service_model["invariantUUID"]
        instance_input["model_version_id"] = service_model["uniqueId"]

        category_parameters = self.oc.vid.maintenance.get_category_parameters(
        ).response_data
        for entity in category_parameters.get("categoryParameters",
                                              {}).get("owningEntity", []):
            if entity.get("name") == instance_input.get("owning_entity_name"):
                instance_input["owning_entity_id"] = entity.get("id")
                break

        return create_service_instance(instance_input, oc=self.oc)

    def _delete(self, instance_input):
        request = delete_service_instance(
            instance_input.get("service_instance_name"),
            instance_input.get("api_type"),
            oc=self.oc)
        request_id = request.get("requestReferences", {}).get("requestId")
        poll_request(request_id, oc=self.oc)