Example #1
0
def poll_request(request_id, oc=None):
    """Poll an SO request until completion"""
    if not oc:
        oc = Client()

    poll_interval = oc.config.so.POLL_INTERVAL or 30
    request = None
    x = 0
    while x < 30:
        request = oc.so.service_instantiation.get_request_status(
            request_id=request_id).response_data
        status = request.get("request", {}).get("requestStatus",
                                                {}).get("requestState")
        if not status:
            raise SORequestStatusUnavailable(
                "Could not determine request for {}".format(request_id))
        if status == "FAILED":
            failure_message = (request.get("request",
                                           {}).get("requestStatus",
                                                   {}).get("statusMessage"))
            raise SORequestFailed("Request {} failed with message {}".format(
                request_id, failure_message))
        elif status == "COMPLETE":
            return request

        x += 1

        sleep(poll_interval)

    raise SORequestTimeout(
        "Request {} timed out polling for status".format(request_id))
Example #2
0
def get_vsp_model(vsp_id, vsp_version_id):
    oc = Client()

    return oc.sdc.vsp.get_software_product(
        software_product_id=vsp_id,
        software_product_version_id=vsp_version_id,
    ).response_data
Example #3
0
def delete_vnf_instance(service_instance_name, vnf_instance_name, api_type="GR_API"):
    """Delete a VNF Instance from SO"""
    oc = Client()
    si = so.service_instance.get_service_instance(service_instance_name)
    si_id = si.get("service-instance-id")
    for vnfi in si.get("service-data", {}).get("vnfs", {}).get("vnf", []):
        vnfi_id = vnfi.get("vnf-id")
        if vnfi.get("vnf-data", {}).get("vnf-request-input", {}).get("vnf-name") == vnf_instance_name:
            invariant_id = vnfi.get("vnf-data").get("vnf-information").get("onap-model-information").get("model-invariant-uuid")
            vnf_version = vnfi.get("vnf-data").get("vnf-information").get("onap-model-information").get("model-version")
            tenant_id = vnfi.get("vnf-data").get("vnf-request-input").get("tenant")
            cloud_owner = vnfi.get("vnf-data").get("vnf-request-input").get("cloud-owner")
            cloud_region = vnfi.get("vnf-data").get("vnf-request-input").get("aic-cloud-region")
            return oc.so.service_instantiation.delete_vnf_instance(
                vnf_invariant_id=invariant_id,
                vnf_version=vnf_version,
                vnf_name=vnf_instance_name,
                cloud_region=cloud_region,
                cloud_owner=cloud_owner,
                tenant_id=tenant_id,
                vnf_instance_id=vnfi_id,
                service_instance_id=si_id,
                api_type=api_type,
            ).response_data

    raise VNFInstanceNotFound("VNF Instance was not found: {} {}".format(service_instance_name, vnf_instance_name))
Example #4
0
def create_preload(preload_path, api_type):
    oc = Client()

    if api_type == "GR_API":
        oc.sdnc.operations.gr_api_preload(preload_path=preload_path)
    elif api_type == "VNF_API":
        oc.sdnc.operations.vnf_api_preload(preload_path=preload_path)
Example #5
0
def poll_distribution(service_name):
    """Polls a distributed service until distribution is complete"""
    oc = Client()

    poll_interval = oc.config.sdc.POLL_INTERVAL or 30
    x = 0
    while x < 30:
        distribution = get_service_distribution(service_name)
        if not distribution:
            raise exceptions.DistributionNotFound(
                "Could not determine distribution status for {}".format(
                    service_name))
        distribution_list = distribution.get("distributionStatusList")
        for component in distribution_list:
            status = component.get("status")
            component_name = component.get("omfComponentID")
            if status == "DISTRIBUTION_COMPLETE_ERROR":
                raise exceptions.DistributionFailure(
                    "Distribution failure for service {}, component details {}"
                    .format(service_name, component))
            elif status == "COMPONENT_DONE_ERROR" and component_name == "aai-ml":
                raise exceptions.DistributionFailure(
                    "Distribution failure for service {}, component details {}"
                    .format(service_name, component))
            elif status == "DISTRIBUTION_COMPLETE_OK":
                return "Distribution Successful"
        x += 1
        time.sleep(poll_interval)

    raise exceptions.DistributionTimeout(
        "Distribution polling timed out waiting for {}".format(service_name))
Example #6
0
def update_vsp(existing_vsp, vsp_input, oc=None):
    if not oc:
        oc = Client()

    existing_vsp_id = existing_vsp.get("id")
    existing_vsp_version_id = existing_vsp.get("version")

    if get_vsp_version_id(existing_vsp_id, search_key="status",
                          oc=oc) == "Certified":
        oc.sdc.vsp.update_software_product(
            software_product_id=existing_vsp_id,
            software_product_version_id=existing_vsp_version_id,
            description=vsp_input.get("update_message", "New VSP Version"))

    vsp_input["software_product_id"] = existing_vsp_id
    vsp_input["software_product_version_id"] = get_vsp_version_id(
        existing_vsp_id, oc=oc)

    oc.sdc.vsp.upload_heat_package(**vsp_input)
    oc.sdc.vsp.validate_software_product(**vsp_input)

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

    return vsp_input
Example #7
0
def add_resource(parent_resource_id, catalog_resource_id, catalog_resource_name, origin_type="VF"):
    """Attaches a resource to a VNF 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 vnf
    :origin_type: specifies the origin of the attached resource

    """
    oc = Client()

    milli_timestamp = int(time.time() * 1000)

    resource_instance = oc.sdc.vnf.add_resource_instance(
        catalog_resource_id=parent_resource_id,
        posX=random.randrange(150, 550),  # nosec
        posY=random.randrange(150, 450),  # nosec
        milli_timestamp=milli_timestamp,
        new_catalog_resource_id=catalog_resource_id,
        new_catalog_resource_name=catalog_resource_name,
        originType=origin_type,
    )

    response = {
        "id": resource_instance.catalog_resource_instance_id,
        "tosca": resource_instance.response_data,
    }

    return response
Example #8
0
def update_vnf(catalog_resource_id, vnf_input):
    oc = Client()

    existing_vnf = oc.sdc.vnf.get_catalog_resource(
        catalog_resource_id=catalog_resource_id
    ).response_data

    if existing_vnf.get("lifecycleState") != "NOT_CERTIFIED_CHECKOUT":
        vnf = oc.sdc.vnf.checkout_catalog_resource(catalog_resource_id=catalog_resource_id).response_data
    else:
        vnf = oc.sdc.vnf.get_catalog_resource_metadata(catalog_resource_id=catalog_resource_id).response_data.get("metadata", {})

    new_vnf_metadata = oc.sdc.vnf.get_catalog_resource_metadata(catalog_resource_id=vnf.get("uniqueId")).response_data.get("metadata", {})

    csar_version = vsp.get_vsp_version_id(vnf.get("csarUUID"), search_key="name")

    vnf["csarVersion"] = csar_version
    vnf["componentMetadata"] = new_vnf_metadata

    updated_vnf = oc.sdc.vnf.update_catalog_resource(catalog_resource_id=vnf.get("uniqueId"), payload_data=json.dumps(vnf)).response_data

    vnf_input["catalog_resource_id"] = updated_vnf.get("uniqueId")
    vnf_input["tosca"] = updated_vnf

    return vnf_input
Example #9
0
def get_vnf(vnf_name):
    """Queries SDC for the TOSCA model for a VNF"""
    oc = Client()

    return oc.sdc.vnf.get_catalog_resource(
        catalog_resource_id=get_vnf_id(vnf_name)
    ).response_data
Example #10
0
def get_resource_category(category_name):
    oc = Client()
    resource_categories = oc.sdc.get_resource_categories().response_data
    for category in resource_categories:
        if category.get("uniqueId").lower() == category_name.lower():
            return category
    return None
Example #11
0
def get_vsp_owner(vsp_id):
    oc = Client()
    vsps = oc.sdc.vsp.get_software_products().response_data.get("results", [])
    for vsp in vsps:
        if vsp.get("id") == vsp_id:
            return vsp.get("owner")
    return None
def delete_vnf_instance(service_instance_name,
                        vnf_instance_name,
                        api_type="GR_API",
                        oc=None):
    """Delete a VNF Instance from SO"""
    if not oc:
        oc = Client()

    si = so.service_instance.get_service_instance(service_instance_name, oc=oc)
    vnfi = so.service_instance.get_vnf_instance(si, vnf_instance_name)

    si_id = si.get("service-instance-id")
    vnfi_id = vnfi.get("vnf-id")
    invariant_id = vnfi.get("vnf-data").get("vnf-information").get(
        "onap-model-information").get("model-invariant-uuid")
    vnf_version = vnfi.get("vnf-data").get("vnf-information").get(
        "onap-model-information").get("model-version")
    tenant_id = vnfi.get("vnf-data").get("vnf-request-input").get("tenant")
    cloud_owner = vnfi.get("vnf-data").get("vnf-request-input").get(
        "cloud-owner")
    cloud_region = vnfi.get("vnf-data").get("vnf-request-input").get(
        "aic-cloud-region")

    return oc.so.service_instantiation.delete_vnf_instance(
        vnf_invariant_id=invariant_id,
        vnf_version=vnf_version,
        vnf_name=vnf_instance_name,
        cloud_region=cloud_region,
        cloud_owner=cloud_owner,
        tenant_id=tenant_id,
        vnf_instance_id=vnfi_id,
        service_instance_id=si_id,
        api_type=api_type,
    ).response_data
Example #13
0
def test_catalog_item_auth():
    c = Client()

    resource = c.test.catalog_items.get("MAKE_TEST_REQUEST")

    auth = ("abc", "123")

    assert resource.auth == auth
Example #14
0
def get_service(service_name, oc=None):
    """Queries SDC for the TOSCA model for a service"""
    if not oc:
        oc = Client()

    return oc.sdc.service.get_sdc_service(
        catalog_service_id=get_service_id(service_name, oc=oc)
    ).response_data
Example #15
0
def main(*args):
    cli_arguments = list(args)
    request_arguments = {}

    oc = Client()
    configure_logging()

    if len(args) > 0 and args[0] == "spec-engine":
        # use engine cli instead
        spec_cli(cli_arguments[1:])
    elif len(args) > 0 and convert_to_underscores(
            args[0]) in oc.utility_functions:
        # use utility cli instead
        utility_cli(oc, cli_arguments)
    elif len(args) == 0 or args[0] == "--help":
        print(help(oc, extra_clients=["spec-engine"], include_utility=True))
    else:
        while cli_arguments:
            arg = cli_arguments.pop(0)

            if arg == "--help":
                print(help(oc))
                return

            if is_argument(arg):
                arg = convert_to_underscores(arg)
                arg = sanitize_argument(arg)
                try:
                    value = get_value(cli_arguments.pop(0))
                    if is_argument(value):
                        print("No Value passed for argument: {}. Try --help".
                              format(arg))
                        return
                except IndexError:
                    print(
                        "No Value passed for argument: {}. Try --help".format(
                            arg))
                    return

                request_arguments[arg] = value
            else:
                arg = convert_to_underscores(arg)
                oc = getattr(oc, arg, None)
                if not oc:
                    print("Invalid Argument: {}. Try --help".format(arg))
                    return

        if isinstance(oc, Catalog.CallHandle):
            data = oc(**request_arguments)

            output_data = data.response_data

            if isinstance(output_data, dict) or isinstance(output_data, list):
                print(json.dumps(output_data, indent=4))
            else:
                print(output_data)
        else:
            print("Command Invalid: {}. Try --help".format(args))
Example #16
0
def test_request_uri():
    c = Client()

    resource = c.test.catalog_items.get("MAKE_FILES_REQUEST")

    request_object = create_request_object(resource)

    assert request_object.uri == "http://this.is.a.test.com/{}".format(
        DUMMY_PARAM)
Example #17
0
def get_all_infra_requests(oc=None):
    if not oc:
        oc = Client()

    infra_data = oc.so.infra.get_active_requests(size="20").response_data

    total_elements = int(infra_data.get("page", {}).get("totalElements", 20))

    return oc.so.infra.get_active_requests(size=total_elements).response_data
Example #18
0
    def __init__(self, oc=None, **kwargs):
        self.attributes = {}

        if not oc:
            self.oc = Client()
        else:
            self.oc = oc

        self.input_spec = self.validate(kwargs, spec=self.spec)
Example #19
0
def get_vnf_model_component(service_model_name, vnf_model_name):
    oc = Client()
    service_model = oc.sdc.service.get_sdc_service(
        catalog_service_id=sdc.service.get_service_id(service_model_name)
    ).response_data

    for component in service_model.get("componentInstances", []):
        if component["componentName"] == vnf_model_name:
            return component
    return None
Example #20
0
def get_service_distribution(service_name):
    oc = Client()

    distribution_id = get_distribution_id(service_name)

    if distribution_id:
        return oc.sdc.service.get_service_distribution_details(
            distribution_id=distribution_id).response_data

    return None
Example #21
0
def get_vsp(vsp_name, oc=None):
    """Queries SDC for the tosca model for a VSP"""
    if not oc:
        oc = Client()

    vsp_id = get_vsp_id(vsp_name, oc=oc)
    if vsp_id is None:
        return None
    vsp_version_id = get_vsp_version_id(vsp_id, oc=oc)
    return get_vsp_model(vsp_id, vsp_version_id, oc=oc)
Example #22
0
def test_payload():
    c = Client()

    resource = c.test.catalog_items.get("MAKE_FILES_REQUEST")

    request_object = create_request_object(resource)

    assert json.loads(request_object.payload) == {
        "test_item_parameter": DUMMY_PARAM
    }
Example #23
0
def test_catalog_item_headers():
    c = Client()

    resource = c.test.catalog_items.get("MAKE_TEST_REQUEST")

    headers = {
        "Accept": "application/json",
        "Content-Type": "application/json"
    }

    assert resource.headers == headers
Example #24
0
def get_tenant_id(cloud_region, cloud_owner, tenant_name):
    oc = Client()

    tenants = oc.aai.cloud_infrastructure.get_cloud_region_tenants(
        cloud_owner=cloud_owner, cloud_region=cloud_region).response_data

    for tenant in tenants.get("tenant"):
        if tenant.get("tenant-name") == tenant_name:
            return tenant.get("tenant-id")

    raise TenantNotFound("Tenant {} was not found in AAI".format(tenant_name))
Example #25
0
def get_distribution_id(service_name):
    oc = Client()

    distribution = oc.sdc.service.get_service_distribution(
        distribution_service_id=get_service_uuid(service_name)).response_data
    if distribution:
        details = distribution.get("distributionStatusOfServiceList", [])
        for entry in details:
            return entry.get("distributionID")

    return None
Example #26
0
def get_service_instance(service_instance_name):
    oc = Client()
    service_instances = oc.sdnc.config.get_service_instances().response_data
    for si in service_instances.get("services", {}).get("service", []):
        si_name = (
            si.get("service-data", {})
            .get("service-request-input", {})
            .get("service-instance-name")
        )
        if si_name == service_instance_name:
            return si
    return None
Example #27
0
def configure_logging():
    oc = Client()
    LOG_LEVEL = oc.config.LOG_LEVEL if oc.config.LOG_LEVEL else "INFO"

    LOG = logging.getLogger()
    log_level = getattr(logging, LOG_LEVEL.upper())
    ch = logging.StreamHandler()
    LOG.setLevel(log_level)
    formatter = logging.Formatter(
        '%(levelname)s %(asctime)s %(name)s %(message)s')
    ch.setFormatter(formatter)
    LOG.addHandler(ch)
Example #28
0
def get_vnf_id(vnf_name):
    oc = Client()

    response = oc.sdc.vnf.get_resources()
    results = response.response_data.get("resources", [])
    catalog_resource = {}
    update_time = -1
    for vnf in results:
        if vnf.get("name") == vnf_name and vnf.get("lastUpdateDate") > update_time:
            update_time = vnf.get("lastUpdateDate")
            catalog_resource = vnf

    return catalog_resource.get("uniqueId")
Example #29
0
def test_files():
    c = Client()

    resource = c.test.catalog_items.get("MAKE_FILES_REQUEST")

    request_object = create_request_object(resource)

    file_path = "{}/test.zip".format(THIS_DIR)
    with open(file_path, "rb") as f:
        data = f.read()
    file_name = os.path.basename(file_path)
    files = {"upload": [file_name, data, "application/zip"]}
    assert request_object.files == files
Example #30
0
def create_service_instance(instance_input):
    oc = Client()

    headers = {"X-TransactionId": str(uuid.uuid4())}
    service_instance = oc.so.service_instantiation.create_service_instance(
        **instance_input, **headers)

    request_id = service_instance.response_data.get("requestReferences",
                                                    {}).get("requestId")

    instance_input["request_info"] = poll_request(request_id)

    return instance_input