class OneVMInfo(object):
    """
    See Also: https://docs.opennebula.org/5.6/integration/system_interfaces/api.html
    """
    def __init__(self):
        """Constructor of OneVMInfo class"""
        self.__client = Client(verify_ssl_cert=False)
        self.method = "one.vm.info"
        self.headers = {"Content-Type": "application/xml"}

    def get(self, url, session, vm_id):
        """ Get the VM info

        Args:
            url (str): the url of the XML-RPC API of OpenNebula
            session (str): the OpenNebula session
            vm_id (int): the VM id

        Returns:
            object: the requests object
        """
        payload = """<?xml version='1.0'?>
            <methodCall>
            <methodName>{}</methodName>
            <params>
            <param>
            <value><string>{}</string></value>
            </param>
            <param>
            <value><int>{}</int></value>
            </param>
            </params>
            </methodCall>""".format(self.method, session, vm_id)
        response = self.__client.post(url,
                                      payload=payload,
                                      headers=self.headers)
        return response
Esempio n. 2
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
Esempio n. 3
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
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)
Esempio n. 5
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
Esempio n. 6
0
class Configuration:
    def __init__(self):
        """
        Constructor
        """
        self.__client = HttpClient(verify_ssl_cert=False)
        self.vdns_ip = VDNS_IP
        self.vdns_port = "9999"
        self.headers = {"X-Api-Key": "secret", "Content-Type": "application/json"}

    def add_vcache_entry(self, edge_vcache_ip_user_network, vcache_incremental_counter):
        """ Add an entry for the new vCache after its instantiation

        Args:
            edge_vcache_ip_user_network (str): the IPv4 of edge vCache in User network
            vcache_incremental_counter (int): incremental integer for each vCache edge
                added/scaled in the vCDN

        Returns:
            object: A requests object

        Raises:
            VdnsConfigurationFailed: The The vDNS configuration after the instantiation of a
                new vCache failed.

        Examples:
            >>> from actions.vnf_configuration import vdns
            >>> vcache_ip_user_network ="192.168.252.3"
            >>> vcache_incremental_counter = 2
            >>> vdns_conf = vdns.Configuration()
            >>> vdns_conf.add_vcache_entry(vcache_ip_user_network, vcache_incremental_counter)
        """
        endpoint = 'http://{}:{}/dns'.format(self.vdns_ip, self.vdns_port)

        payload = {
            "hostname": "cdn-uhd.cache{}.5gmedia.lab".format(vcache_incremental_counter),
            "ip": "{}".format(edge_vcache_ip_user_network)
        }
        request = self.__client.post(endpoint, headers=self.headers, payload=json.dumps(payload))
        logger.debug("Request `POST {}` returns HTTP status `{}`, headers `{}` and body `{}`."
                     .format(request.url, request.status_code, request.headers, request.text))

        if request.status_code != 200:
            raise VdnsConfigurationFailed(
                "The vDNS configuration after the instantiation of the vCache with index={} "
                " failed".format(vcache_incremental_counter))
        return request

    def delete_vcache_entry(self, vcache_incremental_counter):
        """ Remove the existing entry of vCache after its deletion

        Args:
            vcache_incremental_counter (int): incremental integer for each vCache edge
                added/scaled in the vCDN

        Returns:
            object: A requests object

        Raises:
            VdnsConfigurationFailed: The The vDNS configuration after the deletion of an
                existing vCache failed.

        Examples:
            >>> from actions.vnf_configuration import vdns
            >>> vcache_ip_user_network ="192.168.252.12"
            >>> vcache_incremental_counter = 2
            >>> vdns_conf = vdns.Configuration(vcache_ip_user_network)
            >>> req = vdns_conf.delete_vcache_entry(vcache_incremental_counter)
            >>> req.status_code
            200
        """
        endpoint = 'http://{}:{}/dns'.format(self.vdns_ip, self.vdns_port)

        payload = {"hostname": "cdn-uhd.cache{}.5gmedia.lab".format(vcache_incremental_counter)}
        request = self.__client.delete(endpoint, headers=self.headers, payload=json.dumps(payload))
        logger.info("Request `DELETE {}` returns HTTP status `{}`, headers `{}` and body `{}`."
                    .format(request.url, request.status_code, request.headers, request.text))
        if request.status_code != 200:
            raise VdnsConfigurationFailed(
                "The vDNS configuration after the deletion of the vCache with index={} "
                "failed".format(vcache_incremental_counter))
        return request

    def delete_faas_vcache_entry(self, vcache_incremental_counter):
        """ Remove the existing entry of vCache after its deletion

        Args:
            vcache_incremental_counter (int): incremental integer for each vCache edge
                added/scaled in the vCDN

        Returns:
            object: A requests object

        Raises:
            VdnsConfigurationFailed: The The vDNS configuration after the deletion of an
                existing faas vCache failed.

        Examples:
            >>> from actions.vnf_configuration import vdns
            >>> vcache_ip_user_network ="192.168.252.12"
            >>> vcache_incremental_counter = 2
            >>> vdns_conf = vdns.Configuration(vcache_ip_user_network)
            >>> req = vdns_conf.delete_faas_vcache_entry(vcache_incremental_counter)
            >>> req.status_code
            200
        """
        endpoint = 'http://{}:{}/dns'.format(self.vdns_ip, self.vdns_port)
        payload = {
            "hostname": "cdn-uhd.cache-faas-{}.5gmedia.lab".format(vcache_incremental_counter)}
        request = self.__client.delete(endpoint, headers=self.headers, payload=json.dumps(payload))

        if request.status_code != 200:
            raise VdnsConfigurationFailed(
                "The vDNS configuration after the deletion of the vCache with index={} "
                "failed".format(vcache_incremental_counter))
        return request
Esempio n. 7
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