Ejemplo n.º 1
0
class VimAccount(object):
    """Description of VimAccount class"""
    def __init__(self, token):
        """Constructor of VimAccount class"""
        self.__client = Client(verify_ssl_cert=False)
        self.bearer_token = token

    def get_list(self):
        """Get the list of the registered vim accounts in OSM r4

        Returns:
            obj: a requests object

        Examples:
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.vim_account import VimAccount
            >>> from settings import OSM_ADMIN_CREDENTIALS
            >>> token = bearer_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('username'))
            >>> vim_account = VimAccount(token)
            >>> entries = vim_account.get_list()
            >>> print(entries.json())
        """
        endpoint = '{}/osm/admin/v1/vim_accounts'.format(
            OSM_COMPONENTS.get('NBI-API'))
        headers = {
            "Authorization": "Bearer {}".format(self.bearer_token),
            "Accept": "application/json"
        }
        response = self.__client.get(endpoint, headers)
        return response

    def get(self, vim_account_uuid=None):
        """Get details for a project in OSM r4 by given project ID

        Args:
            vim_account_uuid (str): The Vim Account UUID

        Returns:
            obj: a requests object

        Examples:
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.vim_account import VimAccount
            >>> from settings import OSM_ADMIN_CREDENTIALS
            >>> token = bearer_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('username'))
            >>> vim_account = VimAccount(token)
            >>> entry = vim_account.get("66000170-7fe9-4ab0-b113-b60a92ee196c")
            >>> print(entry.json())
        """
        endpoint = '{}/osm/admin/v1/vim_accounts/{}'.format(
            OSM_COMPONENTS.get('NBI-API'), vim_account_uuid)
        headers = {
            "Authorization": "Bearer {}".format(self.bearer_token),
            "Accept": "application/json"
        }
        response = self.__client.get(endpoint, headers)
        return response
Ejemplo n.º 2
0
class User(object):
    """Description of User class"""
    def __init__(self, token):
        """Constructor of User class"""
        self.__client = Client(verify_ssl_cert=False)
        self.bearer_token = token

    def get_list(self):
        """Get the list of the registered users in OSM r4

        Returns:
            obj: a requests object

        Examples:
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.user import User
            >>> from settings import OSM_ADMIN_CREDENTIALS
            >>> token = bearer_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('username'))
            >>> user = User(token)
            >>> response = user.get_list()
            >>> print(response.json())
        """
        endpoint = '{}/osm/admin/v1/users'.format(
            OSM_COMPONENTS.get('NBI-API'))
        headers = {
            "Authorization": "Bearer {}".format(self.bearer_token),
            "Accept": "application/json"
        }
        response = self.__client.get(endpoint, headers)
        return response

    def get(self, username=None):
        """Get details of a user in OSM r4 by given username

        Returns:
            obj: a requests object

        Examples:
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.user import User
            >>> from settings import OSM_ADMIN_CREDENTIALS
            >>> token = bearer_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('username'))
            >>> user = User(token)
            >>> response = user.get(username="******")
            >>> print(response.json())
        """
        endpoint = '{}/osm/admin/v1/users/{}'.format(
            OSM_COMPONENTS.get('NBI-API'), username)
        headers = {
            "Authorization": "Bearer {}".format(self.bearer_token),
            "Accept": "application/json"
        }
        response = self.__client.get(endpoint, headers)
        return response
Ejemplo n.º 3
0
class Project(object):
    """Description of Project class"""
    def __init__(self, token):
        """Constructor of Project class"""
        self.__client = Client(verify_ssl_cert=False)
        self.bearer_token = token

    def get_list(self):
        """Get the list of the registered Projects in OSM r4

        Returns:
            obj: a requests object

        Examples:
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.project import Project
            >>> from settings import OSM_ADMIN_CREDENTIALS
            >>> token = bearer_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('username'))
            >>> project = Project(token)
            >>> entries = project.get_list()
            >>> print(entries.json())
        """
        endpoint = '{}/osm/admin/v1/projects'.format(
            OSM_COMPONENTS.get('NBI-API'))
        headers = {
            "Authorization": "Bearer {}".format(self.bearer_token),
            "Accept": "application/json"
        }
        response = self.__client.get(endpoint, headers)
        return response

    def get(self, project_id=None):
        """Get details for a project in OSM r4 by given project ID

        Returns:
            obj: a requests object

        Examples:
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.project import Project
            >>> from settings import OSM_ADMIN_CREDENTIALS
            >>> token = bearer_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('username'))
            >>> project = Project(token)
            >>> entry = project.get("admin")
            >>> print(entry.json())
        """
        endpoint = '{}/osm/admin/v1/projects/{}'.format(
            OSM_COMPONENTS.get('NBI-API'), project_id)
        headers = {
            "Authorization": "Bearer {}".format(self.bearer_token),
            "Accept": "application/json"
        }
        response = self.__client.get(endpoint, headers)
        return response
class QueryRange(object):
    """QueryRange Class.

    Attributes:
        bearer_token (str, optional): The Prometheus Authorization Token (if any)

    Methods:
        get(query, from_time, to_time, step): perform a query_range request in Prometheus API
    """
    def __init__(self, token=None):
        """Class Constructor."""
        self.__client = Client(verify_ssl_cert=False)
        self.bearer_token = token

    def get(self, query, from_time, to_time, step=14):
        """ Perform a query_range request in Prometheus API (PromQL)

        Args:
            query (str): The query
            from_time (str): The start datetime
            to_time (str): The end datetime
            step (int): The used step in the query. Default value is 14 secs.

        Returns:
            object: A list of NSs as a requests object
        """
        endpoint = 'http://{}:{}/api/v1/query_range'.format(
            PROMETHEUS.get('HOST'), PROMETHEUS.get('PORT'))
        headers = {"Accept": "application/json"}
        endpoint += "?query={}&start={}&end={}&step={}".format(
            query, from_time, to_time, step)
        logger.debug("Prometheus web service: {}".format(endpoint))
        response = self.__client.get(url=endpoint, headers=headers)
        return response
Ejemplo n.º 5
0
class Vnfr(object):
    """Description of Vnfr class"""
    def __init__(self, token):
        """Constructor of Vnfr class"""
        self.__client = Client(verify_ssl_cert=False)
        self.basic_token = token

    def get_list(self):
        """Get the list of the VNF records from the SO-ub container

        Returns:
            obj: a requests object

        Examples:
            >>> from soapi.vnfr import Vnfr
            >>> from soapi.identity import basic_token
            >>> from settings import OSM_ADMIN_CREDENTIALS
            >>> token = basic_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('username'))
            >>> vnfr = Vnfr(token)
            >>> vnfrs = vnfr.get_list()
            >>> print(int(vnfrs.status_code))
            200
        """
        endpoint = '{}/v1/api/operational/project/default/vnfr-catalog/vnfr'.format(
            OSM_COMPONENTS.get('SO-API'))
        headers = {
            "Authorization": "Basic {}".format(self.basic_token),
            "Accept": "application/json"
        }
        response = self.__client.get(endpoint, headers)
        return response
Ejemplo n.º 6
0
class FaaS:

    def __init__(self, osm_host):
        """Constructor

        Args:
            osm_host (str): the host of the OSM (and the FaaS API)
        """
        self.__client = Client()
        self.osm_host = "{}".format(osm_host)
        self.faas_polling_host = self.osm_host
        self.faas_polling_ip = '5001'
        self.ns_instances = []

    def set_ns_instances(self):
        """ Fetch the NN instances in FaaS VIM

        Returns:
            list: the NS instances
        """
        endpoint = 'http://{}:{}/osm/instances_all'.format(self.faas_polling_host,
                                                           self.faas_polling_ip)
        request = self.__client.get(endpoint)
        data = request.json()
        self.ns_instances = data

    def search_vnf(self, container_id):
        """ Search information about a serverless VNF

        Args:
            container_id:

        Returns:
            dict: The NS uuid and name in RO and the vnf name (vnfd name plus vnf index)
        """
        result = {'ro_ns_uuid': None, 'ns_name': None, 'vnf_name': None}

        try:
            for ns in self.ns_instances:
                for vnf in ns['vnfs']:
                    vim_info = vnf.get('vim_info', {})

                    if 'vim-id' not in vim_info.keys():
                        # On-demand serverless VNFs
                        records = vim_info.get('records', [])
                        if len(records) == 0:
                            continue
                        for record in records:
                            if 'vim-id' in record.keys() and record['vim-id'] == container_id:
                                return {'ro_ns_uuid': ns['uuid'], 'ns_name': ns['name'],
                                        'vnf_name': vnf['vnf_name']}
                    else:
                        # core serverless VNFs
                        vim_id = vim_info.get('vim-id', None)
                        if vim_id == container_id:
                            return {'ro_ns_uuid': ns['uuid'], 'ns_name': ns['name'],
                                    'vnf_name': vnf['vnf_name']}
            raise Exception('No match found for container with id {}'.format(container_id))
        except Exception as ex:
            return result
Ejemplo n.º 7
0
class Vim(object):
    """Description of Project class"""

    def __init__(self, token):
        """Constructor of Project class"""
        self.__client = Client(verify_ssl_cert=False)
        self.bearer_token = token

    def get_list(self):
        """Get the list of the registered VIMs in OSM r4

        Returns:
            obj: a requests object

        Examples:
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.vim import Vim
            >>> from settings import OSM_ADMIN_CREDENTIALS
            >>> token = bearer_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('username'))
            >>> vim = Vim(token)
            >>> entries = vim.get_list()
            >>> print(entries.json())
        """
        endpoint = '{}/osm/admin/v1/vim_accounts'.format(OSM_COMPONENTS.get('NBI-API'))
        headers = {"Authorization": "Bearer {}".format(self.bearer_token), "Accept": "application/json"}
        response = self.__client.get(endpoint, headers)
        return response

    def get(self, vim_uuid=None):
        """Get details for a VIM in OSM r4 by given VIM UUID

        Returns:
            obj: a requests object

        Examples:
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.vim import Vim
            >>> from settings import OSM_ADMIN_CREDENTIALS
            >>> token = bearer_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('username'))
            >>> vim = Vim(token)
            >>> vim_account = vim.get("41dab0c0-35f4-4c40-b1cd-13e4a79dab48")
            >>> print(vim_account.json())
        """
        endpoint = '{}/osm/admin/v1/vim_accounts/{}'.format(OSM_COMPONENTS.get('NBI-API'), vim_uuid)
        headers = {"Authorization": "Bearer {}".format(self.bearer_token), "Accept": "application/json"}
        response = self.__client.get(endpoint, headers)
        return response
Ejemplo n.º 8
0
class Instance(object):
    """ Class for Instance API
    See more: https://osm.etsi.org/wikipub/index.php/RO_Northbound_Interface#Instances
    """
    def __init__(self):
        self.__client = Client(verify_ssl_cert=True)

    def get_list(self, openmano_tenant_id, headers=None, query_params=None):
        """Fetch the list of Openmano instances by given tenant ID

        Args:
            openmano_tenant_id (str): The tenant UUID
            headers (dict, optional): the required HTTP headers, e.g., Accept: application/json
            query_params (dict, optional): Additional arguments will be passed to the request.

        Returns:
            obj: a requests object

        Examples:
            >>> from httpclient.client import Client
            >>> from openmanoapi.instances import Instance
            >>> obj = Instance()
            >>> instances = obj.get_list('f35d06af-ed24-40ca-87c1-4e6ae81008b4')
            >>> print(int(instances.status_code))
            200
            >>> print(instances.json())

        Openmano cli:
            $ openmano instance-scenario-list -a -d
        """
        endpoint = '{}/{}/instances'.format(BASE_URL, openmano_tenant_id)
        response = self.__client.get(endpoint,
                                     headers=headers,
                                     query_params=query_params)
        logger.debug(
            "Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
            "".format(response.url, response.status_code, response.headers,
                      response.text))
        return response

    def get(self,
            openmano_tenant_id,
            instance_id,
            headers=None,
            query_params=None):
        """Fetch details for an Openmano instance by given tenant ID and instance ID

        Args:
            openmano_tenant_id (str): The tenant UUID
            instance_id (str): The instance UUID
            headers (dict, optional): the required HTTP headers, e.g., Accept: application/json
            query_params (dict, optional): Additional arguments will be passed to the request.

        Returns:
            obj: a requests object

        Examples:
            >>> from httpclient.client import Client
            >>> from openmanoapi.instances import Instance
            >>> obj = Instance()
            >>> instance = obj.get('f35d06af-ed24-40ca-87c1-4e6ae81008b4', '661d343f-740a-4a98-9e7b-bbfd31ff24ef')
            >>> print(int(instance.status_code))
            200
            >>> print(instance.json())

        Openmano cli:
            $ openmano instance-scenario-list {instance_id} -d
        """
        endpoint = '{}/{}/instances/{}'.format(BASE_URL, openmano_tenant_id,
                                               instance_id)
        response = self.__client.get(endpoint,
                                     headers=headers,
                                     query_params=query_params)
        logger.debug(
            "Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
            "".format(response.url, response.status_code, response.headers,
                      response.text))
        return response
Ejemplo n.º 9
0
class NsLcmOperation(object):
    """NsLcmOperation Class.

    Attributes:
        bearer_token (str): The OSM Authorization Token

    Args:
        token (str): The OSM Authorization Token
    """
    def __init__(self, token):
        """NS LCM Class Constructor."""
        self.__client = Client(verify_ssl_cert=False)
        self.bearer_token = token

    def get_list(self):
        """Fetch the list of operations

        Returns:
            object: A requests object

        Examples:
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.operation import NsLcmOperation
            >>> from settings import OSM_ADMIN_CREDENTIALS
            >>> token = bearer_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('username'))
            >>> ns_operation = NsLcmOperation(token)
            >>> request = ns_operation.get_list()
            >>> print(request.status_code)
            200

        """
        endpoint = '{}/osm/nslcm/v1/ns_lcm_op_occs'.format(
            OSM_COMPONENTS.get('NBI-API'))
        headers = {
            "Authorization": "Bearer {}".format(self.bearer_token),
            "Accept": "application/json",
            "Content-Type": "application/json"
        }
        response = self.__client.list(endpoint, headers)
        logger.debug(
            "Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
            .format(response.url, response.status_code, response.headers,
                    response.text))
        return response

    def get(self, operation_uuid=None):
        """Fetch details of a specific operation

        Args:
            operation_uuid (str): The UUID of the performed operation

        Returns:
            object: A requests object

        Examples:
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.operation import NsLcmOperation
            >>> from settings import OSM_ADMIN_CREDENTIALS
            >>> token = bearer_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('username'))
            >>> ns_operation = NsLcmOperation(token)
            >>> request = ns_operation.get(operation_uuid='7a1bd53e-af29-40d6-bbde-ee8be69ddc3e')
            >>> print(request.status_code)
            200

        """
        endpoint = '{}/osm/nslcm/v1/ns_lcm_op_occs/{}'.format(
            OSM_COMPONENTS.get('NBI-API'), operation_uuid)
        headers = {
            "Authorization": "Bearer {}".format(self.bearer_token),
            "Accept": "application/json",
            "Content-Type": "application/json"
        }
        response = self.__client.get(endpoint, headers)
        logger.debug(
            "Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
            .format(response.url, response.status_code, response.headers,
                    response.text))
        return response
Ejemplo n.º 10
0
class Nsr(object):
    """Description of Nsr class"""
    def __init__(self, token):
        """Constructor of Nsr class"""
        self.__client = Client(verify_ssl_cert=False)
        self.basic_token = token

    def get_list(self):
        """Get the list of the NS records from the SO-ub container

        Returns:
            obj: a requests object

        Examples:
            >>> from soapi.nsr import Nsr
            >>> from soapi.identity import basic_token
            >>> from settings import OSM_ADMIN_CREDENTIALS
            >>> token = basic_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('username'))
            >>> ns = Nsr(token)
            >>> ns_records = ns.get_list()
            >>> print(int(ns_records.status_code))
            200
        """
        endpoint = '{}/api/running/project/default/ns-instance-config'.format(
            OSM_COMPONENTS.get('SO-API'))
        headers = {
            "Authorization": "Basic {}".format(self.basic_token),
            "Accept": "application/json"
        }
        response = self.__client.get(endpoint, headers)
        return response

    def get(self, ns_uuid):
        """Get details for a NS record from the SO-ub container

        Args:
            ns_uuid (str): The ID of the network service

        Returns:
            obj: a requests object

        Examples:
            >>> from soapi.nsr import Nsr
            >>> from soapi.identity import basic_token
            >>> from settings import OSM_ADMIN_CREDENTIALS
            >>> token = basic_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('username'))
            >>> ns = Nsr(token)
            >>> ns_record = ns.get('xxx')
            >>> print(int(ns_record.status_code))
            200
        """
        endpoint = '{}/api/operational/project/default/ns-instance-opdata/nsr/{}?deep'.format(
            OSM_COMPONENTS.get('SO-API'), ns_uuid)
        headers = {
            "Authorization": "Basic {}".format(self.basic_token),
            "Accept": "application/json"
        }
        response = self.__client.get(endpoint, headers)
        return response

    def instantiate(self,
                    ns_descriptor,
                    nsr_name,
                    vim_account_name,
                    admin_status="ENABLED"):
        """Instantiate a new NS based on NS descriptor and considering the given (by user) NS name and VIM name

        Args:
            ns_descriptor (dict): The NS descriptor
            nsr_name (str): The NS name
            vim_account_name (str): The VIM name

        Returns:
            obj: a requests object

        Examples:
            >>> from soapi.nsr import Nsr
            >>> from soapi.identity import basic_token
            >>> from settings import OSM_ADMIN_CREDENTIALS
            >>> token = basic_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('username'))
            >>> ns = Nsr(token)
            >>> ns_descriptor = {"name": "cirros_2vnf_ns", "constituent-vnfd": [{"member-vnf-index": 1, "vnfd-id-ref": "cirros_vnfd", "start-by-default": "true"}, {"member-vnf-index": 2, "vnfd-id-ref": "cirros_vnfd", "start-by-default": "true"} ], "description": "Generated by OSM pacakage generator", "short-name": "cirros_2vnf_ns", "id": "cirros_2vnf_nsd", "version": "1.0", "vld": [{"name": "cirros_2vnf_nsd_vld1", "vnfd-connection-point-ref": [{"vnfd-connection-point-ref": "eth0", "vnfd-id-ref": "cirros_vnfd", "member-vnf-index-ref": 1 }, {"vnfd-connection-point-ref": "eth0", "vnfd-id-ref": "cirros_vnfd", "member-vnf-index-ref": 2 } ], "short-name": "cirros_2vnf_nsd_vld1", "mgmt-network": "true", "id": "cirros_2vnf_nsd_vld1", "type": "ELAN"} ], "logo": "osm_2x.png", "vendor": "OSM"}
            >>> ns_instance = ns.instantiate(ns_descriptor, "cirros_2vnf_ns_test", "devstack-ocata")
            >>> print(int(ns_instance.status_code))
            >>> print(ns_instance.text)
        """
        endpoint = '{}/api/config/project/default/ns-instance-config/nsr'.format(
            OSM_COMPONENTS.get('SO-API'))
        headers = {
            "Authorization": "Basic {}".format(self.basic_token),
            "Accept": "application/json",
            "Content-Type": "application/json"
        }
        nsr_id = str(uuid.uuid1())
        payload = {
            "nsr": [{
                "short-name": nsr_name,
                "datacenter": vim_account_name,
                "description": nsr_name,
                "resource-orchestrator": "osmopenmano",
                "nsd": ns_descriptor,
                "admin-status": admin_status,
                "id": nsr_id,
                "name": nsr_name
            }]
        }
        response = self.__client.post(endpoint,
                                      headers=headers,
                                      payload=json.dumps(payload))
        return response

    def terminate(self, ns_uuid):
        """Terminate a running NS

        Args:
            ns_uuid (str, uuid): The ID of the network service

        Returns:
            obj: a requests object

        Examples:
            >>> from soapi.nsr import Nsr
            >>> from soapi.identity import basic_token
            >>> from settings import OSM_ADMIN_CREDENTIALS
            >>> token = basic_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('username'))
            >>> ns = Nsr(token)
            >>> ns_instance = ns.terminate("32798fec-b042-11e8-a05b-fa163e682738")
            >>> print(ns_instance.status_code)
            201
            >>> print(ns_instance.text)
            {"success":""}
        """
        endpoint = '{}/api/config/project/default/ns-instance-config/nsr/{}'.format(
            OSM_COMPONENTS.get('SO-API'), ns_uuid)
        headers = {
            "Authorization": "Basic {}".format(self.basic_token),
            "Accept": "application/json"
        }
        response = self.__client.delete(endpoint, headers=headers)
        return response

    def scale(self, ns_uuid, scaling_group_id, index):
        """Scale a NS record by given NS ID and scaling group ID

        Args:
            ns_uuid (str): The ID of the network service
            scaling_group_id (str): The ID of the scaling group as defined in the NS descriptor
            index (str): The ID of the triggered vnf

        Returns:
            obj: a requests object

        Examples:
            >>> from soapi.nsr import Nsr
            >>> from soapi.identity import basic_token
            >>> from settings import OSM_ADMIN_CREDENTIALS
            >>> token = basic_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('username'))
            >>> ns = Nsr(token)
            >>> scaled_ns = ns.scale('xxx', 'scaling-group-1', '2134')
            >>> print(int(scaled_ns.status_code))
            200
        """
        endpoint = '{}/v1/api/config/project/default/ns-instance-config/nsr/{}/scaling-group/{}/instance'.format(
            OSM_COMPONENTS.get('SO-API'), ns_uuid, scaling_group_id)
        headers = {
            "Authorization": "Basic {}".format(self.basic_token),
            "Accept": "application/json",
            "Content-Type": "application/json"
        }
        payload = json.dumps({"instance": [{"id": str(index)}]})
        response = self.__client.post(endpoint, headers, payload)
        return response
Ejemplo n.º 11
0
class Vnf(object):
    """VNF Class.

    Attributes:
        bearer_token (str): The OSM Authorization Token

    Args:
        token (str): The OSM Authorization Token

    """

    def __init__(self, token):
        """NS LCM Class Constructor."""
        self.__client = Client(verify_ssl_cert=False)
        self.bearer_token = token

    def get_list(self):
        """Fetch a list of all VNFs.

        Returns:
            object: A requests object

        Examples:
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.vnf import Vnf
            >>> from settings import OSM_ADMIN_CREDENTIALS
            >>> token = bearer_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('username'))
            >>> vnf = Vnf(token)
            >>> response = vnf.get_list()

        OSM Cli:
            $ osm vnf-list
        """
        endpoint = '{}/osm/nslcm/v1/vnf_instances'.format(OSM_COMPONENTS.get('NBI-API'))
        headers = {"Authorization": "Bearer {}".format(self.bearer_token), "Accept": "application/json"}
        response = self.__client.get(endpoint, headers)
        logger.debug("Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
                     .format(response.url, response.status_code, response.headers, response.text))
        return response

    def get_list_by_ns(self, ns_uuid=None):
        """Fetch list of VNFs for specific NS Instance.

        Args:
            ns_uuid (str): The UUID of the NS to fetch VNFs for.

        Returns:
            object: A requests object.

        Examples:
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.vnf import Vnf
            >>> from settings import OSM_ADMIN_CREDENTIALS
            >>> token = bearer_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('username'))
            >>> vnf = Vnf(token)
            >>> response = vnf.get_list_by_ns(ns_uuid='a5f506e9-45c7-42fd-b12d-b5c657ed87fb')

        """
        endpoint = '{}/osm/nslcm/v1/vnf_instances?nsr-id-ref={}'.format(OSM_COMPONENTS.get('NBI-API'), ns_uuid)
        headers = {"Authorization": "Bearer {}".format(self.bearer_token), "Accept": "application/json"}
        response = self.__client.get(endpoint, headers)
        logger.debug("Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
                     .format(response.url, response.status_code, response.headers, response.text))
        return response

    def get(self, vnf_uuid=None):
        """Fetch details of a specific VNF

        Args:
            vnf_uuid (str): The UUID of the VNF to fetch details for

        Returns:
            object: A requests object

        Examples:
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.vnf import Vnf
            >>> from settings import OSM_ADMIN_CREDENTIALS
            >>> token = bearer_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('username'))
            >>> vnf = Vnf(token)
            >>> response = vnf.get(vnf_uuid='a5f506e9-45c7-42fd-b12d-b5c657ed87fb')

        OSM Cli:
            $ osm vnf-show a5f506e9-45c7-42fd-b12d-b5c657ed87fb
        """
        endpoint = '{}/osm/nslcm/v1/vnf_instances/{}'.format(OSM_COMPONENTS.get('NBI-API'), vnf_uuid)
        headers = {"Authorization": "Bearer {}".format(self.bearer_token), "Accept": "application/json"}
        response = self.__client.get(endpoint, headers)
        logger.debug("Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
                     .format(response.url, response.status_code, response.headers, response.text))
        return response
Ejemplo n.º 12
0
class NsiLcm(object):
    """NSI LCM Class.

    This class serves as a wrapper for the Network Slice Instance Lifecycle Management (NSILCM) part
    of the Northbound Interface (NBI) offered by OSM. The methods defined in this class help
    retrieve the NSI-related entities of OSM, and instantiate or terminate an NSI.

    Attributes:
        bearer_token (str): The OSM Authorization Token

    Args:
        token (str): The OSM Authorization Token

    """

    def __init__(self, token):
        """NSI LCM Class Constructor."""
        self.__client = Client(verify_ssl_cert=False)
        self.bearer_token = token

    def get_netslice_list(self):
        """Fetch a list of all Netslice Instances

        Returns:
            nsi_list_obj (Response): A list of Netslice Instances as a requests object

        Examples:
            >>> from django.conf import settings
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.nsilcm import NsiLcm
            >>> token = bearer_token(settings.OSM_ADMIN_CREDENTIALS.get('username'), settings.OSM_ADMIN_CREDENTIALS.get('password'))
            >>> nsilcm = NsiLcm(token)
            >>> nsi_list_obj = nsilcm.get_netslice_list()

        OSM Cli:
            $ osm nsi-list

        """
        endpoint = '{}/osm/nsilcm/v1/netslice_instances'.format(settings.OSM_COMPONENTS.get('NBI-API'))
        headers = {"Authorization": "Bearer {}".format(self.bearer_token), "Accept": "application/json"}
        response = self.__client.get(endpoint, headers)
        logger.debug("Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
                     .format(response.url, response.status_code, response.headers, response.text))
        return response

    def get_netslice(self, nsi_uuid):
        """Fetch details of a specific Netslice Instance

        Args:
            nsi_uuid (str): The UUID of the NS to fetch details for

        Returns:
            nsi_obj (Response): A NS as a requests object

        Examples:
            >>> from django.conf import settings
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.nsilcm import NsiLcm
            >>> token = bearer_token(settings.OSM_ADMIN_CREDENTIALS.get('username'), settings.OSM_ADMIN_CREDENTIALS.get('password'))
            >>> nsilcm = NsiLcm(token)
            >>> nsi_obj = nsilcm.get_netslice('07048175-660b-404f-bbc9-5be7581e74de')

        OSM Cli:
            $ osm nsi-show 07048175-660b-404f-bbc9-5be7581e74de

        """
        endpoint = '{}/osm/nsilcm/v1/netslice_instances/{}'.format(settings.OSM_COMPONENTS.get('NBI-API'), nsi_uuid)
        headers = {"Authorization": "Bearer {}".format(self.bearer_token), "Accept": "application/json"}
        response = self.__client.get(endpoint, headers)
        logger.debug("Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
                     .format(response.url, response.status_code, response.headers, response.text))
        return response
Ejemplo n.º 13
0
class Tenant(object):
    """ Class for Tenant API
    See more: https://osm.etsi.org/wikipub/index.php/RO_Northbound_Interface#Tenants
    """
    def __init__(self):
        self.__client = Client(verify_ssl_cert=True)

    def get_list(self, headers=None, query_params=None):
        """Fetch the list of Openmano tenants

        Args:
            headers (dict, optional): the required HTTP headers, e.g., Accept: application/json
            query_params (dict, optional): Additional arguments will be passed to the request.

        Returns:
            obj: a requests object

        Examples:
            >>> from httpclient.client import Client
            >>> from openmanoapi.tenants import Tenant
            >>> tn = Tenant()
            >>> tenants = tn.get_list()
            >>> print(int(tenants.status_code))
            200
            >>> print(tenants.json())
            {"tenants": [{"created_at": "2018-05-03T16:00:04", "description": null, "uuid": "f35d06af-ed24-40ca-87c1-4e6ae81008b4", "name": "osm"} ] }

        Openmano cli:
            $ openmano tenant-list -d
        """
        endpoint = '{}/tenants'.format(BASE_URL)
        response = self.__client.get(endpoint,
                                     headers=headers,
                                     query_params=query_params)
        logger.debug(
            "Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
            "".format(response.url, response.status_code, response.headers,
                      response.text))
        return response

    def get(self, openmano_tenant_id, headers=None, query_params=None):
        """Fetch details for an Openmano tenant by given tenant ID

        Args:
            openmano_tenant_id (str): The tenant UUID
            headers (dict, optional): the required HTTP headers, e.g., Accept: application/json
            query_params (dict, optional): Additional arguments will be passed to the request.

        Returns:
            obj: a requests object

        Examples:
            >>> from httpclient.client import Client
            >>> from openmanoapi.tenants import Tenant
            >>> tn = Tenant()
            >>> tenant = tn.get('f35d06af-ed24-40ca-87c1-4e6ae81008b4')
            >>> print(int(tenant.status_code))
            200
            >>> print(tenant.json())

        Openmano cli:
            $ openmano tenant-list {openmano_tenant_id} -d
        """
        endpoint = '{}/tenants/{}'.format(BASE_URL, openmano_tenant_id)
        response = self.__client.get(endpoint,
                                     headers=headers,
                                     query_params=query_params)
        logger.debug(
            "Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
            "".format(response.url, response.status_code, response.headers,
                      response.text))
        return response
Ejemplo n.º 14
0
class OsmAdmin(object):
    """OSM Admin Class.

    This class serves as a wrapper for the Admin part of the Northbound Interface (NBI) offered
    by OSM. The methods defined in this class help to retrieve the administrative entities of OSM,
    i.e. VIM accounts, users, projects, tokens and SDNs as lists or single objects.

    Attributes:
        bearer_token (str): The OSM Authorization Token

    Args:
        token (str): The OSM Authorization Token

    """

    def __init__(self, token):
        """NsInstance Class Constructor."""
        self.__client = Client(verify_ssl_cert=False)
        self.bearer_token = token

    def get_vim_list(self):
        """Fetch a list of all VIM accounts.

        Returns:
            vim_list_obj (Response): A list of VIMs as a requests object

        Examples:
            >>> from django.conf import settings
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.osm_admin import OsmAdmin
            >>> token = bearer_token(settings.OSM_ADMIN_CREDENTIALS.get('username'), settings.OSM_ADMIN_CREDENTIALS.get('password'))
            >>> osm_admin = OsmAdmin(token)
            >>> vim_list_obj = osm_admin.get_vim_list()

        OSM Cli:
            $ osm vim-list

        """
        endpoint = '{}/osm/admin/v1/vim_accounts'.format(settings.OSM_COMPONENTS.get('NBI-API'))
        headers = {"Authorization": "Bearer {}".format(self.bearer_token), "Accept": "application/json"}
        response = self.__client.get(endpoint, headers)
        logger.debug("Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
                     .format(response.url, response.status_code, response.headers, response.text))
        return response

    def get_vim(self, vim_uuid):
        """Fetch details of a specific VIM account

        Args:
            vim_uuid (str): The UUID of the VIM to fetch

        Returns:
            vim_obj (Response): A VIM as a requests object

        Examples:
            >>> from django.conf import settings
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.osm_admin import OsmAdmin
            >>> token = bearer_token(settings.OSM_ADMIN_CREDENTIALS.get('username'), settings.OSM_ADMIN_CREDENTIALS.get('password'))
            >>> osm_admin = OsmAdmin(token)
            >>> vim_obj = osm_admin.get_vim('27183ec9-55f9-47b4-a850-fd0c528dc9fc')

        OSM Cli:
            $ osm vim-show 27183ec9-55f9-47b4-a850-fd0c528dc9fc

        """
        endpoint = '{}/osm/admin/v1/vim_accounts/{}'.format(settings.OSM_COMPONENTS.get('NBI-API'), vim_uuid)
        headers = {"Authorization": "Bearer {}".format(self.bearer_token), "Accept": "application/json"}
        response = self.__client.get(endpoint, headers)
        logger.debug("Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
                     .format(response.url, response.status_code, response.headers, response.text))
        return response

    def get_user_list(self):
        """Fetch a list of all users

        Returns:
            user_list_obj (Response): A list of users as a requests object

        Examples:
            >>> from django.conf import settings
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.osm_admin import OsmAdmin
            >>> token = bearer_token(settings.OSM_ADMIN_CREDENTIALS.get('username'), settings.OSM_ADMIN_CREDENTIALS.get('password'))
            >>> osm_admin = OsmAdmin(token)
            >>> user_list_obj = osm_admin.get_user_list()

        """
        endpoint = '{}/osm/admin/v1/users'.format(settings.OSM_COMPONENTS.get('NBI-API'))
        headers = {"Authorization": "Bearer {}".format(self.bearer_token), "Accept": "application/json"}
        response = self.__client.get(endpoint, headers)
        logger.debug("Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
                     .format(response.url, response.status_code, response.headers, response.text))
        return response

    def get_user(self, user_name):
        """Fetch details of a user

        Args:
            user_name (str) : The name of the user to fetch details for

        Returns:
            user_obj (Response): A user as a requests object

        Examples:
            >>> from django.conf import settings
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.osm_admin import OsmAdmin
            >>> token = bearer_token(settings.OSM_ADMIN_CREDENTIALS.get('username'), settings.OSM_ADMIN_CREDENTIALS.get('password'))
            >>> osm_admin = OsmAdmin(token)
            >>> user_obj = osm_admin.get_user('user5gmedia')

        """
        endpoint = '{}/osm/admin/v1/users/{}'.format(settings.OSM_COMPONENTS.get('NBI-API'), user_name)
        headers = {"Authorization": "Bearer {}".format(self.bearer_token), "Accept": "application/json"}
        response = self.__client.get(endpoint, headers)
        logger.debug("Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
                     .format(response.url, response.status_code, response.headers, response.text))
        return response

    def get_project_list(self):
        """Fetch a list of all projects

        Returns:
            project_list_obj (Response): A list of projects as a requests object

        Examples:
            >>> from django.conf import settings
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.osm_admin import OsmAdmin
            >>> token = bearer_token(settings.OSM_ADMIN_CREDENTIALS.get('username'), settings.OSM_ADMIN_CREDENTIALS.get('password'))
            >>> osm_admin = OsmAdmin(token)
            >>> project_list_obj = osm_admin.get_project_list()

        """
        endpoint = '{}/osm/admin/v1/projects'.format(settings.OSM_COMPONENTS.get('NBI-API'))
        headers = {"Authorization": "Bearer {}".format(self.bearer_token), "Accept": "application/json"}
        response = self.__client.get(endpoint, headers)
        logger.debug("Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
                     .format(response.url, response.status_code, response.headers, response.text))
        return response

    def get_project(self, project_name):
        """Fetch details of a specific project

        Args:
            project_name (str): The name of the project to fetch details for

        Returns:
            project_obj (Response): A project as a requests object

        Examples:
            >>> from django.conf import settings
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.osm_admin import OsmAdmin
            >>> token = bearer_token(settings.OSM_ADMIN_CREDENTIALS.get('username'), settings.OSM_ADMIN_CREDENTIALS.get('password'))
            >>> osm_admin = OsmAdmin(token)
            >>> project_obj = osm_admin.get_project('5gmedia')

        """
        endpoint = '{}/osm/admin/v1/projects/{}'.format(settings.OSM_COMPONENTS.get('NBI-API'), project_name)
        headers = {"Authorization": "Bearer {}".format(self.bearer_token), "Accept": "application/json"}
        response = self.__client.get(endpoint, headers)
        logger.debug("Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
                     .format(response.url, response.status_code, response.headers, response.text))
        return response

    def get_token_list(self):
        """Fetch a list of all authorization tokens.

        Returns:
            token_list_obj (Response): A list of tokens as a requests object

        Examples:
            >>> from django.conf import settings
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.osm_admin import OsmAdmin
            >>> token = bearer_token(settings.OSM_ADMIN_CREDENTIALS.get('username'), settings.OSM_ADMIN_CREDENTIALS.get('password'))
            >>> osm_admin = OsmAdmin(token)
            >>> token_list_obj = osm_admin.get_token_list()

        """
        endpoint = '{}/osm/admin/v1/tokens'.format(settings.OSM_COMPONENTS.get('NBI-API'))
        headers = {"Authorization": "Bearer {}".format(self.bearer_token), "Accept": "application/json"}
        response = self.__client.get(endpoint, headers)
        logger.debug("Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
                     .format(response.url, response.status_code, response.headers, response.text))
        return response

    def get_token(self, token):
        """Fetch details of a token.

        Args:
            token (str): An OSM authorization token

        Returns:
            token_list_obj (Response): A list of tokens as a requests object

        Examples:
            >>> from django.conf import settings
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.osm_admin import OsmAdmin
            >>> token = bearer_token(settings.OSM_ADMIN_CREDENTIALS.get('username'), settings.OSM_ADMIN_CREDENTIALS.get('password'))
            >>> osm_admin = OsmAdmin(token)
            >>> token_obj = osm_admin.get_token('HESHId7l6HHwURmLGm4hnuGxa6njLABE')

        """
        endpoint = '{}/osm/admin/v1/tokens/{}'.format(settings.OSM_COMPONENTS.get('NBI-API'), token)
        headers = {"Authorization": "Bearer {}".format(self.bearer_token), "Accept": "application/json"}
        response = self.__client.get(endpoint, headers)
        logger.debug("Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
                     .format(response.url, response.status_code, response.headers, response.text))
        return response

    def get_sdn_list(self):
        """Fetch a list of all SDNs.

        Returns:
            sdn_list_obj (Response): A list of SDNs as a requests object

        Examples:
            >>> from django.conf import settings
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.osm_admin import OsmAdmin
            >>> token = bearer_token(settings.OSM_ADMIN_CREDENTIALS.get('username'), settings.OSM_ADMIN_CREDENTIALS.get('password'))
            >>> osm_admin = OsmAdmin(token)
            >>> sdn_list_obj = osm_admin.get_sdn_list()

        OSM Cli:
            $ osm sdnc-list

        """
        endpoint = '{}/osm/admin/v1/sdns'.format(settings.OSM_COMPONENTS.get('NBI-API'))
        headers = {"Authorization": "Bearer {}".format(self.bearer_token), "Accept": "application/json"}
        response = self.__client.get(endpoint, headers)
        logger.debug("Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
                     .format(response.url, response.status_code, response.headers, response.text))
        return response

    def get_sdn(self, sdn_uuid):
        """Fetch details of a specific SDN.

        Args:
            sdn_uuid (str): The UUID of the SDN to fetch details for

        Returns:
            sdn_obj (Response): An SDN as a requests object

        Examples:
            >>> from django.conf import settings
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.osm_admin import OsmAdmin
            >>> token = bearer_token(settings.OSM_ADMIN_CREDENTIALS.get('username'), settings.OSM_ADMIN_CREDENTIALS.get('password'))
            >>> osm_admin = OsmAdmin(token)
            >>> sdn_obj = osm_admin.get_sdn('n1u9k3l1-55f9-47b4-a850-fd0c5780c9fc')

        OSM Cli:
            $ osm sdnc-show n1u9k3l1-55f9-47b4-a850-fd0c5780c9fc

        """
        endpoint = '{}/osm/admin/v1/sdns/{}'.format(settings.OSM_COMPONENTS.get('NBI-API'), sdn_uuid)
        headers = {"Authorization": "Bearer {}".format(self.bearer_token), "Accept": "application/json"}
        response = self.__client.get(endpoint, headers)
        logger.debug("Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
                     .format(response.url, response.status_code, response.headers, response.text))
        return response
Ejemplo n.º 15
0
class AccountingClient(object):
    """Accounting Client Class.

    This class serves as a wrapper for the Accounting/Billing services of 5G-MEDIA project,
    as they are deployed in ENG's cloud. The methods implemented in this class are intended
    for logging in to the services and opening/closing of NS, VNF and VDU sessions.

    """

    __instance = None

    def __init__(self):
        """Accounting Client Class Constructor."""
        self.__client = Client(verify_ssl_cert=True)
        self.__headers = {'Content-Type': 'application/json'}
        self.login()

    # Singleton Class
    def __new__(cls):
        if cls.__instance is not None:
            return cls.__instance
        else:
            cls.__instance = super(AccountingClient, cls).__new__(cls)
            return cls.__instance

    def login(self):
        """Login to the Accounting/Billing Service."""
        payload = {
            'username': ACCOUNTING_USERNAME,
            'password': ACCOUNTING_PASSWORD
        }
        response = self.__client.post(url=AUTH_URL,
                                      headers=self.__headers,
                                      payload=json.dumps(payload))
        if response.status_code == HTTP_200_OK:
            self.__headers['Authorization'] = 'Bearer {}'.format(
                json.loads(response.text)['id_token'])
            logger.info('Successfully logged on the accounting service')

    def available_user_resource_list(self):
        """Get the available user resource list.

        Returns:
            user_resource_obj (object): A user resource list as a requests objects

        """
        url = BASE_URL + '/availableUserResourceList'
        response = self.__client.get(url=url, headers=self.__headers)
        if response.status_code == HTTP_200_OK:
            return response
        return None

    def open_session_retrial(self, url, payload):
        """Retry opening a session after the authorization token has expired.

        Args:
            url (str): The url for the session opening request
            payload (dict): The essential data to post for session opening

        Returns:
            session_id (int): The ID of the session that was opened

        """
        self.login()
        response = self.__client.post(url=url,
                                      headers=self.__headers,
                                      payload=json.dumps(payload))
        if response.status_code == HTTP_200_OK:
            session_id = int(response.text)
            logger.info('Opened session with id {}'.format(session_id))
            return session_id

    def open_ns_session(self, ns):
        """Open a Network Service (NS) Session.

        Args:
            ns (obj): An NS Instance object

        Returns:
            ns_session_id (int): The ID of the opened NS session

        """
        url = BASE_URL + '/openNsSession'
        payload = {
            'timestamp_sec': time(),
            'catalog_tenant': ns.catalog_tenant,
            'catalog_user': ns.catalog_user,
            'mano_id': ns.mano_id,
            'mano_project': ns.mano_project,
            'mano_user': ns.mano_user,
            'nfvipop_id': ns.nfvipop_id,
            'ns_id': ns.uuid,
            'ns_name': ns.name
        }
        logger.info(
            'Attempting to open ns session with payload {}'.format(payload))
        response = self.__client.post(url=url,
                                      headers=self.__headers,
                                      payload=json.dumps(payload))
        logger.debug('Open ns session response: {}, Status code: {}'.format(
            response.text, response.status_code))
        if response.status_code == HTTP_200_OK:
            ns_session_id = int(response.text)
            logger.info('Opened ns session with id {}'.format(ns_session_id))
            return ns_session_id
        elif response.status_code in [
                HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN
        ]:
            logger.warning(
                'Token has expired  and open_ns_sesion failed; retrying')
            return self.open_session_retrial(url, payload)

    def open_vnf_session(self, ns_session_id, vnf_uuid, vnf_name):
        """Open a Virtual Network Function (VNF) Session.

        Args:
            ns_session_id (int): The id of the NS session where the VNF belongs
            vnf_uuid (str): The UUID of the VNF
            vnf_name (str): The name of the VNF

        Returns:
            vnf_session_id (int): The ID of the opened VNF session

        """
        url = BASE_URL + '/openVnfSession'
        payload = {
            'timestamp_sec': time(),
            'ns_session_id': ns_session_id,
            'vnf_id': vnf_uuid,
            'vnf_name': vnf_name
        }
        logger.info(
            'Attempting to open vnf session with payload {}'.format(payload))
        response = self.__client.post(url=url,
                                      headers=self.__headers,
                                      payload=json.dumps(payload))
        logger.debug('Open vnf session response: {}, Status code: {}'.format(
            response.text, response.status_code))
        if response.status_code == HTTP_200_OK:
            vnf_session_id = int(response.text)
            logger.info('Opened vnf session with id {}'.format(vnf_session_id))
            return vnf_session_id
        elif response.status_code in [
                HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN
        ]:
            logger.warning(
                'Token has expired  and open_vnf_sesion failed; retrying')
            return self.open_session_retrial(url, payload)

    def open_vdu_session(self, vnf_session_id, vdu):
        """Open a Virtual Deployment Unit (VDU) session.

        Args:
            vnf_session_id (int): The id of the VNF session where the VDU belongs.
            vdu (obj): A VDU object

        Returns:
            vdu_session_id (int): The VDU session id.

        """
        url = BASE_URL + '/openVduSession'
        payload = {
            'timestamp_sec': time(),
            'flavorCpuCount': vdu.vcpu,
            'flavorDiskGb': vdu.vdisk,
            'flavorMemoryMb': vdu.vram,
            'nfvipop_id': vdu.nfvipop_id,
            'vdu_id': vdu.uuid,
            'vdu_type':
            'FAAS_VNF' if 'faas' in vdu.nfvipop_id.lower() else 'PLAIN_VNF',
            'vnf_session_id': vnf_session_id
        }
        logger.info(
            'Attempting to open vdu session with payload {}'.format(payload))
        response = self.__client.post(url=url,
                                      headers=self.__headers,
                                      payload=json.dumps(payload))
        logger.debug('Open vdu session response: {}, Status code: {}'.format(
            response.text, response.status_code))
        if response.status_code == HTTP_200_OK:
            vdu_session_id = int(response.text)
            logger.info('Opened vdu session with id {}'.format(vdu_session_id))
            return vdu_session_id
        elif response.status_code in [
                HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN
        ]:
            logger.warning(
                'Token has expired  and open_vdu_sesion failed; retrying')
            return self.open_session_retrial(url, payload)

    def log_vdu_consumption(self, metric_type, metric_value, vdu_session_id):
        """Send measurement of VDU consumption for logging.

        Args:
            metric_type (str): The type of metric
            metric_value (double): The value of metric
            vdu_session_id (int): The id of the VDU session that the metric refers to

        """
        url = BASE_URL + '/logVduConsumption'
        payload = {
            'timestamp': time(),
            'consumption_type': metric_type,
            'consumption_value': metric_value,
            'vdu_session_id': vdu_session_id
        }
        logger.info('Sending vdu consumption with payload {}'.format(payload))
        response = self.__client.post(url=url,
                                      headers=self.__headers,
                                      payload=json.dumps(payload))
        logger.debug(
            'Log vdu consumption response: {}, Status code: {}'.format(
                response.text, response.status_code))
        if response.status_code == HTTP_200_OK:
            logger.info('Vdu consumption logged successfully')
            return
        elif response.status_code in [
                HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN
        ]:
            logger.warning(
                'Token has expired and log_vdu_consumption failed; retrying')
            self.login()
            response = self.__client.post(url=url,
                                          headers=self.__headers,
                                          payload=json.dumps(payload))
            if response.status_code == HTTP_200_OK:
                logger.info('Vdu consumption logged successfully')
                return json.loads(response.text)['id']

    def close_session_retrial(self, url, payload):
        """Retry closing a session after the authorization token has expired.

        Args:
            url (str): The url of the API call
            payload (dict): The payload to send to the API call

        """
        self.login()
        response = self.__client.post(url=url,
                                      headers=self.__headers,
                                      payload=json.dumps(payload))
        if response.status_code == HTTP_200_OK:
            logger.warning('Session was closed')
            return
        return

    def close_session(self, session_id, session_type):
        """Close a NS, VNF or VDU session.

        Args:
            session_id (int): The ID of the session
            session_type (str): The type of the session

        """
        url = BASE_URL + CLOSE_SESSIONS[session_type]
        payload = {'id': session_id}
        logger.info('Closing {} session with id {}'.format(
            session_type, session_id))
        response = self.__client.post(url=url,
                                      headers=self.__headers,
                                      payload=json.dumps(payload))
        logger.debug('Close {} session response: {}, Status code: {}'.format(
            session_type, response.text, response.status_code))
        if response.status_code == HTTP_200_OK:
            logger.info('Successfully closed {} session'.format(session_type))
            return
        elif response.status_code in [
                HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN
        ]:
            logger.warning(
                'Token has expired and close_session failed; retrying')
            self.close_session_retrial(url, payload)
Ejemplo n.º 16
0
class Nsd(object):
    """NS Descriptor Class.

    This class serves as a wrapper for the Network Service Descriptor (NSD) part
    of the Northbound Interface (NBI) offered by OSM. The methods defined in this
    class help retrieve the NSDs of OSM.

    Attributes:
        bearer_token (str): The OSM Authorization Token.

    Args:
        token (str): The OSM Authorization Token.

    """
    def __init__(self, token):
        """NS Descriptor Class Constructor."""
        self.__client = Client(verify_ssl_cert=False)
        self.bearer_token = token

    def get_nsd_list(self):
        """Fetch a list of all NS descriptors.

        Returns:
            nsd_list_obj (Response): A list of NSDs as a requests object.

        Examples:
            >>> from django.conf import settings
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.nsd import Nsd
            >>> token = bearer_token(settings.OSM_ADMIN_CREDENTIALS.get('username'), settings.OSM_ADMIN_CREDENTIALS.get('password'))
            >>> nsd = Nsd(token)
            >>> nsd_list_obj = nsd.get_nsd_list()

        OSM Cli:
            $ osm nsd-list

        """
        endpoint = '{}/osm/nsd/v1/ns_descriptors'.format(
            settings.OSM_COMPONENTS.get('NBI-API'))
        headers = {
            "Authorization": "Bearer {}".format(self.bearer_token),
            "Accept": "application/json"
        }
        response = self.__client.get(endpoint, headers)
        logger.debug(
            "Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
            .format(response.url, response.status_code, response.headers,
                    response.text))
        return response

    def get_nsd(self, nsd_uuid):
        """Fetch details of a specific NS descriptor.

        Args:
            nsd_uuid (str): The UUID of the NSD to fetch details for.

        Returns:
            nsd_obj (Response): A NSD as a requests object.

        Examples:
            >>> from django.conf import settings
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.nsd import Nsd
            >>> token = bearer_token(settings.OSM_ADMIN_CREDENTIALS.get('username'), settings.OSM_ADMIN_CREDENTIALS.get('password'))
            >>> nsd = Nsd(token)
            >>> nsd_obj = nsd.get_nsd('9c4a8f58-8317-40a1-b9fe-1db18cff6965')

        OSM Cli:
            $ osm nsd-show cirros_2vnf_ns

        """
        endpoint = '{}/osm/nsd/v1/ns_descriptors/{}'.format(
            settings.OSM_COMPONENTS.get('NBI-API'), nsd_uuid)
        headers = {
            "Authorization": "Bearer {}".format(self.bearer_token),
            "Accept": "application/json"
        }
        response = self.__client.get(endpoint, headers)
        logger.debug(
            "Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
            .format(response.url, response.status_code, response.headers,
                    response.text))
        return response
Ejemplo n.º 17
0
class Vim(object):
    """ Class for VIMs API
    See more: https://osm.etsi.org/wikipub/index.php/RO_Northbound_Interface#VIMs
    """
    def __init__(self):
        self.__client = Client(verify_ssl_cert=True)

    def get_networks(self,
                     openmano_tenant_id,
                     datacenter_id,
                     headers=None,
                     query_params=None):
        """Fetch the list of VIM networks by given tenant ID and datacenter ID

        Args:
            openmano_tenant_id (str): The tenant UUID
            datacenter_id (str): The tenant UUID
            headers (dict, optional): the required HTTP headers, e.g., Accept: application/json
            query_params (dict, optional): Additional arguments will be passed to the request.

        Returns:
            obj: a requests object

        Examples:
            >>> from httpclient.client import Client
            >>> from openmanoapi.vims import Vim
            >>> vim = Vim()
            >>> networks = vim.get_networks('f35d06af-ed24-40ca-87c1-4e6ae81008b4', '8e430688-4f7a-11e8-b3e2-00163edc3180')
            >>> print(int(networks.status_code))
            200
            >>> print(networks.json())

        Openmano cli:
            $ openmano vim-net-list --datacenter {datacenter_id} -d
        """
        endpoint = '{}/{}/vim/{}/networks'.format(BASE_URL, openmano_tenant_id,
                                                  datacenter_id)
        response = self.__client.get(endpoint,
                                     headers=headers,
                                     query_params=query_params)
        logger.debug(
            "Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
            "".format(response.url, response.status_code, response.headers,
                      response.text))
        return response

    def get_network(self,
                    openmano_tenant_id,
                    datacenter_id,
                    vim_network_id,
                    headers=None,
                    query_params=None):
        """Fetch details for a VIM datacenter by given tenant ID, datacenter ID and VIM network ID

        Args:
            openmano_tenant_id (str): The tenant UUID
            datacenter_id (str): The tenant UUID
            vim_network_id (str): The VIM network UUID
            headers (dict, optional): the required HTTP headers, e.g., Accept: application/json
            query_params (dict, optional): Additional arguments will be passed to the request.

        Returns:
            obj: a requests object

        Examples:
            >>> from httpclient.client import Client
            >>> from openmanoapi.vims import Vim
            >>> vim = Vim()
            >>> network = vim.get_network('f35d06af-ed24-40ca-87c1-4e6ae81008b4', '8e430688-4f7a-11e8-b3e2-00163edc3180', 'deed712a-8a90-42a7-ba8c-98f4c116fca7')
            >>> print(int(network.status_code))
            200
            >>> print(network.json())

        Openmano cli:
            $ openmano vim-net-list --datacenter {datacenter_id} {vim_network_id} -d
        """
        endpoint = '{}/{}/vim/{}/networks/{}'.format(BASE_URL,
                                                     openmano_tenant_id,
                                                     datacenter_id,
                                                     vim_network_id)
        response = self.__client.get(endpoint,
                                     headers=headers,
                                     query_params=query_params)
        logger.debug(
            "Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
            "".format(response.url, response.status_code, response.headers,
                      response.text))
        return response

    def get_tenants(self,
                    openmano_tenant_id,
                    datacenter_id,
                    headers=None,
                    query_params=None):
        """Fetch the list of VIM tenants (ie. admin, demo, alt_demo in devstack) by given openmano tenant ID and datacenter ID

        Args:
            openmano_tenant_id (str): The openmano tenant UUID
            datacenter_id (str): The tenant UUID
            headers (dict, optional): the required HTTP headers, e.g., Accept: application/json
            query_params (dict, optional): Additional arguments will be passed to the request.

        Returns:
            obj: a requests object

        Examples:
            >>> from httpclient.client import Client
            >>> from openmanoapi.vims import Vim
            >>> vim = Vim()
            >>> network = vim.get_tenants('f35d06af-ed24-40ca-87c1-4e6ae81008b4', '8e430688-4f7a-11e8-b3e2-00163edc3180')
            >>> print(int(network.status_code))
            200
            >>> print(network.json())

        Openmano cli:
            $ openmano vim-tenant-list --datacenter {datacenter_id} -d
        """
        endpoint = '{}/{}/vim/{}/tenants'.format(BASE_URL, openmano_tenant_id,
                                                 datacenter_id)
        response = self.__client.get(endpoint,
                                     headers=headers,
                                     query_params=query_params)
        logger.debug(
            "Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
            "".format(response.url, response.status_code, response.headers,
                      response.text))
        return response
Ejemplo n.º 18
0
class Scenario(object):
    """ Class for Scenario API
    See more: https://osm.etsi.org/wikipub/index.php/RO_Northbound_Interface#GET_.2Fopenmano.2F.7Btenant_id.7D.2Fscenarios
    """
    def __init__(self):
        self.__client = Client(verify_ssl_cert=True)

    def get_list(self, openmano_tenant_id, headers=None, query_params=None):
        """Fetch the list of Openmano scenarios by given tenant ID

        Args:
            openmano_tenant_id (str): The tenant UUID
            headers (dict, optional): the required HTTP headers, e.g., Accept: application/json
            query_params (dict, optional): Additional arguments will be passed to the request.

        Returns:
            obj: a requests object

        Examples:
            >>> from httpclient.client import Client
            >>> from openmanoapi.scenarios import Scenario
            >>> sc = Scenario()
            >>> scenarios = sc.get_list('f35d06af-ed24-40ca-87c1-4e6ae81008b4')
            >>> print(int(scenarios.status_code))
            200
            >>> print(scenarios.json())

        Openmano cli:
            $ openmano scenario-list -a --debug
        """
        endpoint = '{}/{}/scenarios'.format(BASE_URL, openmano_tenant_id)
        response = self.__client.get(endpoint,
                                     headers=headers,
                                     query_params=query_params)
        logger.debug(
            "Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
            "".format(response.url, response.status_code, response.headers,
                      response.text))
        return response

    def get(self,
            openmano_tenant_id,
            scenario_id,
            headers=None,
            query_params=None):
        """Fetch details for an Openmano scenario by given tenant ID and scenario ID

        Args:
            openmano_tenant_id (str): The tenant UUID
            scenario_id (str): The scenario UUID
            headers (dict, optional): the required HTTP headers, e.g., Accept: application/json
            query_params (dict, optional): Additional arguments will be passed to the request.

        Returns:
            obj: a requests object

        Examples:
            >>> from httpclient.client import Client
            >>> from openmanoapi.scenarios import Scenario
            >>> sc = Scenario()
            >>> scenario = sc.get('f35d06af-ed24-40ca-87c1-4e6ae81008b4', '577185b4-45dc-4a94-980a-72e1f0068022')
            >>> print(int(scenario.status_code))
            200
            >>> print(scenario.json())

        Openmano cli:
            $ openmano scenario-list {scenario_id} --debug
        """
        endpoint = '{}/{}/scenarios/{}'.format(BASE_URL, openmano_tenant_id,
                                               scenario_id)
        response = self.__client.get(endpoint,
                                     headers=headers,
                                     query_params=query_params)
        logger.debug(
            "Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
            "".format(response.url, response.status_code, response.headers,
                      response.text))
        return response
Ejemplo n.º 19
0
class Datacenter(object):
    """ Class for Datacenter API
    See more: https://osm.etsi.org/wikipub/index.php/RO_Northbound_Interface#Datacenters
    """
    def __init__(self):
        self.__client = Client(verify_ssl_cert=True)

    def get_list(self, openmano_tenant_id, headers=None, query_params=None):
        """Fetch the list of Openmano datacenter entities by given tenant ID

        Args:
            openmano_tenant_id (str): The tenant UUID
            headers (dict, optional): the required HTTP headers, e.g., Accept: application/json
            query_params (dict, optional): Additional arguments will be passed to the request.

        Returns:
            obj: a requests object

        Examples:
            >>> from httpclient.client import Client
            >>> from openmanoapi.datacenters import Datacenter
            >>> dc = Datacenter()
            >>> datacenters = dc.get_list('f35d06af-ed24-40ca-87c1-4e6ae81008b4')
            >>> print(int(datacenters.status_code))
            200
            >>> print(datacenters.json())
            {"datacenters": [{"vim_url": "http://192.168.1.194/identity/v2.0", "created_at": "2018-05-04T09:07:22", "type": "openstack", "uuid": "8e430688-4f7a-11e8-b3e2-00163edc3180", "name": "devstack-pike"} ] }

        Openmano cli:
            $ openmano datacenter-list -a --debug
        """
        endpoint = '{}/{}/datacenters'.format(BASE_URL, openmano_tenant_id)
        response = self.__client.get(endpoint,
                                     headers=headers,
                                     query_params=query_params)
        logger.debug(
            "Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
            "".format(response.url, response.status_code, response.headers,
                      response.text))
        return response

    def get(self,
            openmano_tenant_id,
            datacenter_id,
            headers=None,
            query_params=None):
        """Fetch details for an Openmano datacenter by given tenant ID and datacenter ID

        Args:
            openmano_tenant_id (str): The tenant UUID
            datacenter_id (str): The datacenter UUID
            headers (dict, optional): the required HTTP headers, e.g., Accept: application/json
            query_params (dict, optional): Additional arguments will be passed to the request.

        Returns:
            obj: a requests object

        Examples:
            >>> from httpclient.client import Client
            >>> from openmanoapi.datacenters import Datacenter
            >>> dc = Datacenter()
            >>> datacenters = dc.get('f35d06af-ed24-40ca-87c1-4e6ae81008b4', '8e430688-4f7a-11e8-b3e2-00163edc3180')
            >>> print(int(datacenters.status_code))
            200
            >>> print(datacenters.json())

        Openmano cli:
            $ openmano datacenter-list {datacenter_id} -d
        """
        endpoint = '{}/{}/datacenters/{}'.format(BASE_URL, openmano_tenant_id,
                                                 datacenter_id)
        response = self.__client.get(endpoint,
                                     headers=headers,
                                     query_params=query_params)
        logger.debug(
            "Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
            "".format(response.url, response.status_code, response.headers,
                      response.text))
        return response
Ejemplo n.º 20
0
class Vnfd(object):
    """ Class for VNF API
    See more: https://osm.etsi.org/wikipub/index.php/RO_Northbound_Interface#VNFs
    """
    def __init__(self):
        self.__client = Client(verify_ssl_cert=True)

    def get_list(self, openmano_tenant_id, headers=None, query_params=None):
        """Fetch the list of Openmano VNF descriptors by given tenant ID

        Args:
            openmano_tenant_id (str): The tenant UUID
            headers (dict, optional): the required HTTP headers, e.g., Accept: application/json
            query_params (dict, optional): Additional arguments will be passed to the request.

        Returns:
            obj: a requests object

        Examples:
            >>> from httpclient.client import Client
            >>> from openmanoapi.vnfds import Vnfd
            >>> vnfd = Vnfd()
            >>> vnfds = vnfd.get_list('f35d06af-ed24-40ca-87c1-4e6ae81008b4')
            >>> print(int(vnfds.status_code))
            200
            >>> print(vnfds.json())

        Openmano cli:
            $ openmano vnf-list -a -d
        """
        endpoint = '{}/{}/vnfs'.format(BASE_URL, openmano_tenant_id)
        response = self.__client.get(endpoint,
                                     headers=headers,
                                     query_params=query_params)
        logger.debug(
            "Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
            "".format(response.url, response.status_code, response.headers,
                      response.text))
        return response

    def get(self,
            openmano_tenant_id,
            vnfd_id,
            headers=None,
            query_params=None):
        """Fetch details for an Openmano datacenter by given tenant ID and VNF descriptor ID

        Args:
            openmano_tenant_id (str): The tenant UUID
            vnfd_id (str): The VNF descriptor UUID
            headers (dict, optional): the required HTTP headers, e.g., Accept: application/json
            query_params (dict, optional): Additional arguments will be passed to the request.

        Returns:
            obj: a requests object

        Examples:
            >>> from httpclient.client import Client
            >>> from openmanoapi.vnfds import Vnfd
            >>> vnfd = Vnfd()
            >>> vnfd_entity = vnfd.get('f35d06af-ed24-40ca-87c1-4e6ae81008b4', 'cfa284c1-a6de-48d4-ac10-1d943ee279c8')
            >>> print(int(vnfd_entity.status_code))
            200
            >>> print(vnfd_entity.json())

        Openmano cli:
            $ openmano vnf-list {vnfd_id} -d
        """
        endpoint = '{}/{}/vnfs/{}'.format(BASE_URL, openmano_tenant_id,
                                          vnfd_id)
        response = self.__client.get(endpoint,
                                     headers=headers,
                                     query_params=query_params)
        logger.debug(
            "Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
            "".format(response.url, response.status_code, response.headers,
                      response.text))
        return response
Ejemplo n.º 21
0
class Nsd(object):
    """Description of Nsd class"""

    def __init__(self, token):
        """Constructor of Nsr class"""
        self.__client = Client(verify_ssl_cert=False)
        self.basic_token = token

    def get_list(self):
        """Get the list of the NS descriptors from the SO-ub container

        Returns:
            obj: a requests object

        Examples:
            >>> from soapi.nsd import Nsd
            >>> from soapi.identity import basic_token
            >>> from settings import OSM_ADMIN_CREDENTIALS
            >>> token = basic_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('username'))
            >>> nsd = Nsd(token)
            >>> nsd_records = nsd.get_list()
            >>> print(int(nsd_records.status_code))
            200
        """
        endpoint = '{}/api/running/project/default/nsd-catalog/nsd'.format(OSM_COMPONENTS.get('SO-API'))
        headers = {"Authorization": "Basic {}".format(self.basic_token), "Accept": "application/json"}
        response = self.__client.get(endpoint, headers)
        return response

    def search(self, nsd_name):
        """Get the NS descriptor from the SO-ub container

        Args:
            nsd_name (str): The name of the network service's descriptor

        Returns:
            obj: a requests object

        Examples:
            >>> from soapi.nsd import Nsd
            >>> from soapi.identity import basic_token
            >>> from settings import OSM_ADMIN_CREDENTIALS
            >>> token = basic_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('username'))
            >>> nsd = Nsd(token)
            >>> nsd_record = nsd.search('cirros_2vnf_ns')
            >>> print(nsd_record)

        Descriptor sample:
        --
        {
            "name": "cirros_2vnf_ns",
            "constituent-vnfd": [
                {
                    "member-vnf-index": 1,
                    "vnfd-id-ref": "cirros_vnfd",
                    "start-by-default": "true"
                },
                {
                    "member-vnf-index": 2,
                    "vnfd-id-ref": "cirros_vnfd",
                    "start-by-default": "true"
                }
            ],
            "description": "Generated by OSM pacakage generator",
            "short-name": "cirros_2vnf_ns",
            "id": "cirros_2vnf_nsd",
            "version": "1.0",
            "vld": [
                {
                    "name": "cirros_2vnf_nsd_vld1",
                    "vnfd-connection-point-ref": [
                        {
                            "vnfd-connection-point-ref": "eth0",
                            "vnfd-id-ref": "cirros_vnfd",
                            "member-vnf-index-ref": 1
                        },
                        {
                            "vnfd-connection-point-ref": "eth0",
                            "vnfd-id-ref": "cirros_vnfd",
                            "member-vnf-index-ref": 2
                        }
                    ],
                    "short-name": "cirros_2vnf_nsd_vld1",
                    "mgmt-network": "true",
                    "id": "cirros_2vnf_nsd_vld1",
                    "type": "ELAN"
                }
            ],
            "logo": "osm_2x.png",
            "vendor": "OSM"
        }
        """
        descriptor = {}
        try:
            # Get the list of NSDs
            nsd_response = self.get_list()
            nsd_records = nsd_response.json()
            actual_records =  nsd_records.get('project-nsd:nsd', [])
            # Search for the NSD by given NSD name
            for record in actual_records:
                record_name = record.get("name", None)
                if record_name is not None and record_name == nsd_name:
                    descriptor = record
                    break
        except Exception as e:
            logger.exception(e)
        finally:
            return descriptor
Ejemplo n.º 22
0
class NetworkServicePolling:

    def __init__(self, osm_host, osm_faas_host, osm_faas_port, ns_name):
        """ Initialize the object

        Args:
            osm_host (str): The OSM host
            osm_faas_host (str): The FaaS VIM host (normally it is the same with OSM host)
            osm_faas_port (str): The FaaS VIM port
            ns_name (str): The NS name
        """
        self.__client = Client()
        self.osm_host = osm_host
        self.faas_polling_host = osm_faas_host
        self.faas_polling_ip = osm_faas_port
        self.bootstrap_ingress_url = None
        self.ns_name = ns_name

    def get_vnfs_info(self):
        """ Get information about the involved VNFs

        Returns:
            dict:

        Response Example:
        [
          {
            "vnf_name": "vcdn_bootstrap_vnfd.1",
            "status": "ACTIVE",
            "records": 0,
            "ip_address": "0.0.0.0"
          },
          {
            "vnf_name": "vcache_vnfd.2",
            "status": "ACTIVE",
            "records": 2,
            "ip_address": "0.0.0.0"
          },
          {
            "vnf_name": "vCache_mid_UC3_5GMEDIA.3",
            "status": "ACTIVE",
            "records": 0,
            "ip_address": "192.168.111.19"
          },
          {
            "vnf_name": "vCache_edge_UC3_5GMEDIA.4",
            "status": "ACTIVE",
            "records": 0,
            "ip_address": "192.168.111.27"
          }
        ]
        """
        vnfs_list = []
        endpoint = 'http://{}:{}/osm/{}'.format(self.faas_polling_host, self.faas_polling_ip,
                                                self.ns_name)
        request = self.__client.get(endpoint)
        response_status = request.status_code
        data = request.json()

        for vnf in data['vnfs']:
            vnf_name = vnf.get('vnf_name', None)
            ip_address = vnf.get('ip_address', None)
            status = vnf.get('status', None)
            vim_info = vnf.get('vim_info', {})
            records = 0
            if 'records' in vim_info.keys():
                records = len(vim_info['records'])
            vnf_entry = {'vnf_name': vnf_name, 'ip_address': ip_address, 'status': status,
                         'records': records}
            vnfs_list.append(vnf_entry)
        return vnfs_list

    def get_bootstrap_ingress_url(self):
        """ Get the Ingress Url of the bootstrap serverless VNF

        Returns:
            str: the Ingress Url of the bootstrap serverless VNF
        """
        bootstrap_ingress_url = None
        endpoint = 'http://{}:{}/osm/{}'.format(self.faas_polling_host, self.faas_polling_ip,
                                                self.ns_name)
        request = self.__client.get(endpoint)
        response_status = request.status_code
        data = request.json()

        if response_status != 200:
            return bootstrap_ingress_url

        for vnf in data['vnfs']:
            ingress_url = vnf.get('vim_info', {}).get('IngressUrl', None)
            if ingress_url is not None:
                bootstrap_ingress_url = ingress_url
                break
        return bootstrap_ingress_url

    def set_bootstrap_ingress_url(self, bootstrap_ingress_url):
        """
        Set the Ingress Url of the bootstrap serverless VNF
        """
        self.bootstrap_ingress_url = bootstrap_ingress_url
Ejemplo n.º 23
0
class NsLcm(object):
    """NS LCM Class.

    This class serves as a wrapper for the Network Service Lifecycle Management (NSLCM) part
    of the Northbound Interface (NBI) offered by OSM. The methods defined in this class help
    retrieve the NS-related entities of OSM, i.e. NS and VNFs or terminate an NS instance.

    Attributes:
        bearer_token (str): The OSM Authorization Token

    Args:
        token (str): The OSM Authorization Token

    """

    def __init__(self, token):
        """NS LCM Class Constructor."""
        self.__client = Client(verify_ssl_cert=False)
        self.bearer_token = token

    def get_ns_list(self):
        """Fetch a list of all NS Instances

        Returns:
            ns_list_obj (Response): A list of NSs as a requests object

        Examples:
            >>> from django.conf import settings
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.nslcm import NsLcm
            >>> token = bearer_token(settings.OSM_ADMIN_CREDENTIALS.get('username'), settings.OSM_ADMIN_CREDENTIALS.get('password'))
            >>> nslcm = NsLcm(token)
            >>> ns_list_obj = nslcm.get_ns_list()

        OSM Cli:
            $ osm ns-list

        """
        endpoint = '{}/osm/nslcm/v1/ns_instances'.format(settings.OSM_COMPONENTS.get('NBI-API'))
        headers = {"Authorization": "Bearer {}".format(self.bearer_token), "Accept": "application/json"}
        response = self.__client.get(endpoint, headers)
        logger.debug("Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
                     .format(response.url, response.status_code, response.headers, response.text))
        return response

    def get_ns(self, ns_uuid):
        """Fetch details of a specific NS Instance

        Args:
            ns_uuid (str): The UUID of the NS to fetch details for

        Returns:
            ns_obj (Response): A NS as a requests object

        Examples:
            >>> from django.conf import settings
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.nslcm import NsLcm
            >>> token = bearer_token(settings.OSM_ADMIN_CREDENTIALS.get('username'), settings.OSM_ADMIN_CREDENTIALS.get('password'))
            >>> nslcm = NsLcm(token)
            >>> ns_obj = nslcm.get_ns('07048175-660b-404f-bbc9-5be7581e74de')

        OSM Cli:
            $ osm ns-show 07048175-660b-404f-bbc9-5be7581e74de

        """
        endpoint = '{}/osm/nslcm/v1/ns_instances/{}'.format(settings.OSM_COMPONENTS.get('NBI-API'), ns_uuid)
        headers = {"Authorization": "Bearer {}".format(self.bearer_token), "Accept": "application/json"}
        response = self.__client.get(endpoint, headers)
        logger.debug("Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
                     .format(response.url, response.status_code, response.headers, response.text))
        return response

    def terminate_ns(self, ns_uuid):
        """Terminate a NS Instance.

        Args:
            ns_uuid (str): The UUID of the NS to terminate

        Returns:
            response (Response): A requests object

        Examples:
            >>> from django.conf import settings
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.nslcm import NsLcm
            >>> token = bearer_token(settings.OSM_ADMIN_CREDENTIALS.get('username'), settings.OSM_ADMIN_CREDENTIALS.get('password'))
            >>> nslcm = NsLcm(token)
            >>> response = nslcm.terminate_ns('07048175-660b-404f-bbc9-5be7581e74de')

        """
        endpoint = '{}/osm/nslcm/v1/ns_instances/{}/terminate'.format(settings.OSM_COMPONENTS.get('NBI-API'), ns_uuid)
        headers = {"Authorization": "Bearer {}".format(self.bearer_token), "Accept": "application/json"}
        response = self.__client.post(endpoint, headers)
        logger.debug("Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
                     .format(response.url, response.status_code, response.headers, response.text))
        return response

    def get_vnf_list(self):
        """Fetch a list of all VNFs.

        Returns:
            vnf_list_obj (Response): A list of VNFs as a requests object

        Examples:
            >>> from django.conf import settings
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.nslcm import NsLcm
            >>> token = bearer_token(settings.OSM_ADMIN_CREDENTIALS.get('username'), settings.OSM_ADMIN_CREDENTIALS.get('password'))
            >>> nslcm = NsLcm(token)
            >>> vnf_list_obj = nslcm.get_vnf_list()

        OSM Cli:
            $ osm vnf-list

        """
        endpoint = '{}/osm/nslcm/v1/vnf_instances'.format(settings.OSM_COMPONENTS.get('NBI-API'))
        headers = {"Authorization": "Bearer {}".format(self.bearer_token), "Accept": "application/json"}
        response = self.__client.get(endpoint, headers)
        logger.debug("Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
                     .format(response.url, response.status_code, response.headers, response.text))
        return response

    def get_vnf(self, vnf_uuid):
        """Fetch details of a specific VNF

        Args:
            vnf_uuid (str): The UUID of the VNF to fetch details for

        Returns:
            vnf_obj (Response): A VNF as a requests object

        Examples:
            >>> from django.conf import settings
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.nslcm import NsLcm
            >>> token = bearer_token(settings.OSM_ADMIN_CREDENTIALS.get('username'), settings.OSM_ADMIN_CREDENTIALS.get('password'))
            >>> nslcm = NsLcm(token)
            >>> vnf_obj = nslcm.get_vnf('a5f506e9-45c7-42fd-b12d-b5c657ed87fb')

        OSM Cli:
            $ osm vnf-show a5f506e9-45c7-42fd-b12d-b5c657ed87fb
        """
        endpoint = '{}/osm/nslcm/v1/vnf_instances/{}'.format(settings.OSM_COMPONENTS.get('NBI-API'), vnf_uuid)
        headers = {"Authorization": "Bearer {}".format(self.bearer_token), "Accept": "application/json"}
        response = self.__client.get(endpoint, headers)
        logger.debug("Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
                     .format(response.url, response.status_code, response.headers, response.text))
        return response

    def get_vnf_list_by_ns(self, ns_uuid):
        """Fetch list of VNFs for specific NS Instance.

        Args:
            ns_uuid (str): The UUID of the NS to fetch VNFs for.

        Returns:
            vnf_list_obj (Response): A list of VNFs as a requests object.

        Examples:
            >>> from django.conf import settings
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.nslcm import NsLcm
            >>> token = bearer_token(settings.OSM_ADMIN_CREDENTIALS.get('username'), settings.OSM_ADMIN_CREDENTIALS.get('password'))
            >>> nslcm = NsLcm(token)
            >>> vnf_list_obj = nslcm.get_vnf('a5f506e9-45c7-42fd-b12d-b5c657ed87fb')

        """
        endpoint = '{}/osm/nslcm/v1/vnf_instances?nsr-id-ref={}'.format(settings.OSM_COMPONENTS.get('NBI-API'), ns_uuid)
        headers = {"Authorization": "Bearer {}".format(self.bearer_token), "Accept": "application/json"}
        response = self.__client.get(endpoint, headers)
        logger.debug("Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
                     .format(response.url, response.status_code, response.headers, response.text))
        return response
Ejemplo n.º 24
0
class Action(object):
    """ Class for Action API
    """

    def __init__(self):
        self.__client = Client(verify_ssl_cert=True)

    def get_any(self, tenant_id, headers=None, query_params=None):
        """Fetch the list of actions for an instance by given tenant ID

        Args:
            tenant_id (str): The tenant UUID
            headers (dict, optional): the required HTTP headers, e.g., Accept: application/json
            query_params (dict, optional): Additional arguments will be passed to the request.

        Returns:
            obj: a requests object

        Examples:
            >>> from httpclient.client import Client
            >>> from openmanoapi.actions import Action
            >>> obj = Action()
            >>> actions = obj.get_any('f35d06af-ed24-40ca-87c1-4e6ae81008b4')
            >>> print(int(actions.status_code))
            200
            >>> print(actions.json())

        Openmano cli:
            $ openmano action-list --all ALL --debug
        """
        endpoint = '{}/{}/instances/any/action'.format(BASE_URL, tenant_id)
        response = self.__client.get(endpoint, headers=headers, query_params=query_params)
        logger.debug("Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
                     "".format(response.url, response.status_code, response.headers, response.text))
        return response

    def get_list(self, tenant_id, instance_id, headers=None, query_params=None):
        """Fetch the list of actions by given tenant ID and instance ID

        Args:
            tenant_id (str): The tenant UUID
            instance_id (str): The instance UUID
            headers (dict, optional): the required HTTP headers, e.g., Accept: application/json
            query_params (dict, optional): Additional arguments will be passed to the request.

        Returns:
            obj: a requests object

        Examples:
            >>> from httpclient.client import Client
            >>> from openmanoapi.actions import Action
            >>> obj = Action()
            >>> actions = obj.get_list('f35d06af-ed24-40ca-87c1-4e6ae81008b4', '22bbb91d-51a6-43ba-9850-d9697915921b')
            >>> print(int(actions.status_code))
            200
            >>> print(actions.json())

        Openmano cli:
            $ openmano action-list --instance {instance_id} --debug
        """
        endpoint = '{}/{}/instances/{}/action'.format(BASE_URL, tenant_id, instance_id)
        response = self.__client.get(endpoint, headers=headers, query_params=query_params)
        logger.debug("Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
                     "".format(response.url, response.status_code, response.headers, response.text))
        return response
Ejemplo n.º 25
0
class Ns(object):
    """NS Class.

    Attributes:
        bearer_token (str): The OSM Authorization Token

    Args:
        token (str): The OSM Authorization Token
    """
    def __init__(self, token):
        """NS LCM Class Constructor."""
        self.__client = Client(verify_ssl_cert=False)
        self.bearer_token = token

    def get_list(self):
        """Fetch a list of all NS Instances

        Returns:
            object: A list of NSs as a requests object

        Examples:
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.ns import Ns
            >>> from settings import OSM_ADMIN_CREDENTIALS
            >>> token = bearer_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('username'))
            >>> ns = Ns(token)
            >>> response = ns.get_list()
            >>> print(response.json())

        OSM Cli:
            $ osm ns-list
        """
        endpoint = '{}/osm/nslcm/v1/ns_instances'.format(
            OSM_COMPONENTS.get('NBI-API'))
        headers = {
            "Authorization": "Bearer {}".format(self.bearer_token),
            "Accept": "application/json"
        }
        response = self.__client.get(endpoint, headers)
        logger.debug(
            "Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
            .format(response.url, response.status_code, response.headers,
                    response.text))
        return response

    def get(self, ns_uuid=None):
        """Fetch details of a specific NS Instance

        Args:
            ns_uuid (str): The UUID of the NS to fetch details for

        Returns:
            object: A requests object

        Examples:
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.ns import Ns
            >>> from settings import OSM_ADMIN_CREDENTIALS
            >>> token = bearer_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('username'))
            >>> ns = Ns(token)
            >>> response = ns.get(ns_uuid='07048175-660b-404f-bbc9-5be7581e74de')

        OSM Cli:
            $ osm ns-show 07048175-660b-404f-bbc9-5be7581e74de
        """
        endpoint = '{}/osm/nslcm/v1/ns_instances/{}'.format(
            OSM_COMPONENTS.get('NBI-API'), ns_uuid)
        headers = {
            "Authorization": "Bearer {}".format(self.bearer_token),
            "Accept": "application/json"
        }
        response = self.__client.get(endpoint, headers)
        logger.debug(
            "Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
            .format(response.url, response.status_code, response.headers,
                    response.text))
        return response

    def scale_vnf(self,
                  ns_uuid,
                  vnf_index,
                  scaling_group_name,
                  scale_out=True):
        """ Scale in or out in VNF level

        Args:
            ns_uuid (str): The NS uuid
            vnf_index (int): The VNF index to be scaled
            scaling_group_name (str): The name in the VNF scaling_group_descriptor
            scale_out (bool): Decide scale in or out action. By default, scale out is performed.

        Returns:
            object: A requests object

        Examples:
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.ns import Ns
            >>> from settings import OSM_ADMIN_CREDENTIALS
            >>> token = bearer_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('username'))
            >>> ns = Ns(token)
            >>> response = ns.scale_vnf(ns_uuid="199b1fcd-eb32-4c6f-b149-34410acc2a32", vnf_index=2, scaling_group_name="scale_by_one", scale_out=False)
            # >>> response = ns.scale_vnf(ns_uuid="199b1fcd-eb32-4c6f-b149-34410acc2a32", vnf_index=2, scaling_group_name="scale_by_one", scale_out=False)

        OSM Cli:
            $ osm vnf-scale <ns_uuid> <vnf_index> --scale-in # scale in
            Scaling group: <scaling_group_name>

            $ osm vnf-scale <ns_uuid> <vnf_index> --scale-out # scale out (default)
            Scaling group: <scaling_group_name>
        """
        endpoint = '{}/osm/nslcm/v1/ns_instances/{}/scale'.format(
            OSM_COMPONENTS.get('NBI-API'), ns_uuid)
        headers = {
            "Authorization": "Bearer {}".format(self.bearer_token),
            "Accept": "application/json"
        }

        # Set value based on scale action
        scale_action = "SCALE_IN"
        if scale_out:
            scale_action = "SCALE_OUT"

        payload = {
            "scaleVnfData": {
                "scaleVnfType": scale_action,
                "scaleByStepData": {
                    "member-vnf-index": str(vnf_index),
                    "scaling-group-descriptor": str(scaling_group_name)
                }
            },
            "scaleType": "SCALE_VNF"
        }
        response = self.__client.post(endpoint,
                                      headers,
                                      payload=json.dumps(payload))
        logger.debug(
            "Request `POST {}` returns HTTP status `{}`, headers `{}` and body `{}`."
            .format(response.url, response.status_code, response.headers,
                    response.text))
        return response

    def terminate(self, ns_uuid=None):
        """Terminate a NS Instance.

        Args:
            ns_uuid (str): The UUID of the NS to terminate

        Returns:
            response (object): A requests object

        Examples:
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.ns import Ns
            >>> from settings import OSM_ADMIN_CREDENTIALS
            >>> token = bearer_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('username'))
            >>> ns = Ns(token)
            >>> response = ns.terminate(ns_uuid='07048175-660b-404f-bbc9-5be7581e74de')

        """
        endpoint = '{}/osm/nslcm/v1/ns_instances/{}/terminate'.format(
            OSM_COMPONENTS.get('NBI-API'), ns_uuid)
        headers = {
            "Authorization": "Bearer {}".format(self.bearer_token),
            "Accept": "application/json"
        }
        response = self.__client.post(endpoint, headers)
        logger.debug(
            "Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
            .format(response.url, response.status_code, response.headers,
                    response.text))
        return response
Ejemplo n.º 26
0
class Vnfd(object):
    """VNF Descriptor Class.

    This class serves as a wrapper for the Virtual Network Function Descriptor (VNFD)
    part of the Northbound Interface (NBI) offered by OSM. The methods defined in this
    class help retrieve the VNFDs of OSM.

    Attributes:
        bearer_token (str): The OSM Authorization Token.

    Args:
        token (str): The OSM Authorization Token.
    """
    def __init__(self, token):
        """VNF Descriptor Class Constructor."""
        self.__client = Client(verify_ssl_cert=False)
        self.bearer_token = token

    def get_list(self):
        """Fetch a list of the VNF descriptors.

        Returns:
            object: A requests object that includes the list of VNFDs

        Examples:
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.vnfd import Vnfd
            >>> from settings import OSM_ADMIN_CREDENTIALS
            >>> token = bearer_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('password'))
            >>> vnfd = Vnfd(token)
            >>> response = vnfd.get_list()

        OSM Cli:
            $ osm vnfd-list
        """
        endpoint = '{}/osm/vnfpkgm/v1/vnf_packages'.format(
            OSM_COMPONENTS.get('NBI-API'))
        headers = {
            "Authorization": "Bearer {}".format(self.bearer_token),
            "Accept": "application/json"
        }
        response = self.__client.get(endpoint, headers)
        logger.debug(
            "Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
            .format(response.url, response.status_code, response.headers,
                    response.text))
        return response

    def get(self, vnfd_uuid=None):
        """Fetch details of a specific VNF descriptor.

        Args:
            vnfd_uuid (str): The UUID of the VNFD to fetch details for.

        Returns:
            object: A requests object.

        Examples:
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.vnfd import Vnfd
            >>> from settings import OSM_ADMIN_CREDENTIALS
            >>> token = bearer_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('password'))
            >>> vnfd = Vnfd(token)
            >>> response = vnfd.get(vnfd_uuid='89f66f1b-73b5-4dc1-8226-a473a2615627')

        OSM Cli:
            $ osm vnfd-show cirros_vnf
        """
        endpoint = '{}/osm/vnfpkgm/v1/vnf_packages/{}'.format(
            OSM_COMPONENTS.get('NBI-API'), vnfd_uuid)
        headers = {
            "Authorization": "Bearer {}".format(self.bearer_token),
            "Accept": "application/json"
        }
        response = self.__client.get(endpoint, headers)
        logger.debug(
            "Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
            .format(response.url, response.status_code, response.headers,
                    response.text))
        return response
Ejemplo n.º 27
0
class Ns(object):
    """NS Class.

    Attributes:
        bearer_token (str): The OSM Authorization Token

    Args:
        token (str): The OSM Authorization Token
    """
    def __init__(self, token):
        """NS LCM Class Constructor."""
        self.__client = Client(verify_ssl_cert=False)
        self.bearer_token = token

    def get_list(self):
        """Fetch a list of all NS Instances

        Returns:
            object: A list of NSs as a requests object

        Examples:
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.ns import Ns
            >>> from settings import OSM_ADMIN_CREDENTIALS
            >>> token = bearer_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('username'))
            >>> ns = Ns(token)
            >>> response = ns.get_list()
            >>> print(response.json())

        OSM Cli:
            $ osm ns-list
        """
        endpoint = '{}/osm/nslcm/v1/ns_instances'.format(
            OSM_COMPONENTS.get('NBI-API'))
        headers = {
            "Authorization": "Bearer {}".format(self.bearer_token),
            "Accept": "application/json"
        }
        response = self.__client.get(endpoint, headers)
        logger.debug(
            "Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
            .format(response.url, response.status_code, response.headers,
                    response.text))
        return response

    def get(self, ns_uuid=None):
        """Fetch details of a specific NS Instance

        Args:
            ns_uuid (str): The UUID of the NS to fetch details for

        Returns:
            object: A requests object

        Examples:
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.ns import Ns
            >>> from settings import OSM_ADMIN_CREDENTIALS
            >>> token = bearer_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('username'))
            >>> ns = Ns(token)
            >>> response = ns.get(ns_uuid='07048175-660b-404f-bbc9-5be7581e74de')

        OSM Cli:
            $ osm ns-show 07048175-660b-404f-bbc9-5be7581e74de
        """
        endpoint = '{}/osm/nslcm/v1/ns_instances/{}'.format(
            OSM_COMPONENTS.get('NBI-API'), ns_uuid)
        headers = {
            "Authorization": "Bearer {}".format(self.bearer_token),
            "Accept": "application/json"
        }
        response = self.__client.get(endpoint, headers)
        logger.debug(
            "Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
            .format(response.url, response.status_code, response.headers,
                    response.text))
        return response

    def terminate(self, ns_uuid=None):
        """Terminate a NS Instance.

        Args:
            ns_uuid (str): The UUID of the NS to terminate

        Returns:
            response (object): A requests object

        Examples:
            >>> from nbiapi.identity import bearer_token
            >>> from nbiapi.ns import Ns
            >>> from settings import OSM_ADMIN_CREDENTIALS
            >>> token = bearer_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('username'))
            >>> ns = Ns(token)
            >>> response = ns.terminate(ns_uuid='07048175-660b-404f-bbc9-5be7581e74de')

        """
        endpoint = '{}/osm/nslcm/v1/ns_instances/{}/terminate'.format(
            OSM_COMPONENTS.get('NBI-API'), ns_uuid)
        headers = {
            "Authorization": "Bearer {}".format(self.bearer_token),
            "Accept": "application/json"
        }
        response = self.__client.post(endpoint, headers)
        logger.debug(
            "Request `GET {}` returns HTTP status `{}`, headers `{}` and body `{}`."
            .format(response.url, response.status_code, response.headers,
                    response.text))
        return response