Пример #1
0
    def __init__(self):

        self.name = 'fake-slm'
        self.version = '0.1-dev'
        self.description = 'description'

        LOG.info("Starting SLM Test:...")

        # create and initialize broker connection
        self.manoconn = messaging.ManoBrokerRequestResponseConnection(
            self.name)
        self.path_descriptors = "/home/hadi/son-mano-framework/plugins/son-mano-service-lifecycle-management/test/test_descriptors/"
        self.test_records = "/home/hadi/son-mano-framework/plugins/son-mano-service-lifecycle-management/test/test_records/"
        self.nsd_descriptor = open(self.path_descriptors + 'sonata-demo.yml',
                                   'r')
        self.vnfd1_descriptor = open(
            self.path_descriptors + 'firewall-vnfd.yml', 'r')
        self.vnfd2_descriptor = open(self.path_descriptors + 'iperf-vnfd.yml',
                                     'r')
        self.vnfd3_descriptor = open(
            self.path_descriptors + 'tcpdump-vnfd.yml', 'r')
        self.end = False
        self.manoconn.register_async_endpoint(
            self.check1, 'infrastructure.management.compute.list')
        self.manoconn.register_async_endpoint(self.check2,
                                              'infrastructure.service.deploy')
        self.publish_nsd()
        time.sleep(50)
        self.update()
        self.run()
Пример #2
0
    def setUp(self):
        current_dir = os.getcwd()
        self.slm_proc = Process(target=fakeflm)
        self.smr_proc = Process(target=fake_smr.main)
        os.chdir('../vpn-config')
        self.con_proc = Process(
            target=vpn_css.vpn_css.main,
            kwargs={'working_dir': os.path.realpath('../vpn-config')})
        os.chdir('../firewall-config')
        self.fw_proc = Process(
            target=firewall.firewall.main,
            kwargs={'working_dir': os.path.realpath('../firewall-config')})
        self.cache_proc = Process(
            target=sonfsmvprxsquidconfiguration1.sonfsmvprxsquidconfiguration1.
            main,
            kwargs={'working_dir': os.path.realpath('../cache-config')})
        os.chdir(current_dir)

        self.slm_proc.daemon = True
        self.smr_proc.daemon = True
        # self.con_proc.daemon = True

        self.manoconn = messaging.ManoBrokerRequestResponseConnection(
            'ConfTest')

        self.wait_for_reg_event = threading.Event()
        self.wait_for_reg_event.clear()

        self.wait_for_res_event = threading.Event()
        self.wait_for_res_event.clear()
Пример #3
0
    def __init__(self,
                 specific_manager_type=None,
                 service_name=None,
                 function_name=None,
                 specific_manager_name=None,
                 id_number=None,
                 update_version='false',
                 version=None,
                 description=None):
        """
        :param specific_manager_type: specifies the type of specific manager that could be either fsm or ssm.
        :param service_name: the name of the service that this specific manager belongs to.
        :param function_name: the name of the function that this specific manager belongs to, will be null in SSM case
        :param specific_manager_name: the actual name of specific manager (e.g., scaling, placement)
        :param id_number: the specific manager id number which is used to distinguish between multiple SSM/FSM
        that are created for the same objective (e.g., scaling with algorithm 1 and 2)
        :param updated_version: specifies whether this SM is developed to update a current version or not,should be
        filled either by 'true' or 'false'
        :param version: version
        :param description: description
        """
        #checks if the chosen name by develeopr is correct format
        self.name_validation(specific_manager_type, service_name,
                             function_name, specific_manager_name, id_number)

        #Populating SSM-FSM fileds
        self.specific_manager_type = specific_manager_type
        self.service_name = service_name
        self.function_name = function_name
        self.specific_manager_name = specific_manager_name
        self.id_number = id_number
        if self.specific_manager_type == 'fsm':
            self.specific_manager_id = "son{0}{1}{2}{3}{4}".\
                format(specific_manager_type, service_name, function_name, specific_manager_name, id_number)
        else:
            self.specific_manager_id = "son{0}{1}{2}{3}".\
                format(specific_manager_type, service_name, specific_manager_name, id_number)
        self.version = version
        self.description = description
        self.update_version = update_version
        self.uuid = None
        self.sfuuid = None
        self.private_key = None

        LOG.info("Starting {0} ...".format(self.specific_manager_id))

        # create and initialize broker connection
        self.manoconn = messaging.ManoBrokerRequestResponseConnection(
            self.specific_manager_id)

        self.wait_for_event = threading.Event()
        self.wait_for_event.clear()

        self.registration()

        self.infinity_loop()
Пример #4
0
    def __init__(self):

        self.name = 'fake-smr'
        self.version = '0.1-dev'
        self.description = 'description'

        LOG.info("Start SMR:...")

        # create and initialize broker connection
        self.manoconn = messaging.ManoBrokerRequestResponseConnection(self.name)

        self.declare_subscriptions()
Пример #5
0
    def on_placement_request(self, ch, method, properties, payload):
        if properties.app_id != self.name:
            message = yaml.load(payload)
            LOG.info('Placement request received')

            #topic = 'placement.ssm.{0}'.format(message['uuid'])
            topic = 'placement.ssm.' + message['uuid']

            LOG.info(topic)
            req = yaml.dump(message)
            url = "{0}/ssm-{1}".format(self.sm_broker_host, message['uuid'])
            connection = messaging.ManoBrokerRequestResponseConnection(app_id=self.name, url=url)
            connection.call_async(self.on_placement_result, topic=topic, msg=req, correlation_id= properties.correlation_id)
            LOG.info("Placement request forwarded to SSM on topic: {0}".format(topic))
Пример #6
0
    def __init__(self,
                 name="son-plugin",
                 version=None,
                 description=None,
                 auto_register=True,
                 wait_for_registration=True,
                 start_running=True,
                 auto_heartbeat_rate=0.5):
        """
        Performs plugin initialization steps, e.g., connection setup
        :param name: Plugin name prefix
        :param version: Plugin version
        :param description: A description string
        :param auto_register: Automatically register on init
        :param wait_for_registration: Wait for registration before returning from init
        :param auto_heartbeat_rate: rate of automatic heartbeat notifications 1/n seconds. 0=deactivated
        :return:
        """
        self.name = "%s.%s" % (name, self.__class__.__name__)
        self.version = version
        self.description = description
        self.uuid = None  # uuid given by plugin manager on registration
        self.state = None  # the state of this plugin READY/RUNNING/PAUSED/FAILED

        LOG.info(
            "Starting MANO Plugin: %r ..." % self.name)
        # create and initialize broker connection
        while True:
            try:
                self.manoconn = messaging.ManoBrokerRequestResponseConnection(self.name)
                break
            except:
                time.sleep(1)
        # register subscriptions
        LOG.info("Plugin connected to broker.")

        self.declare_subscriptions()
        # register to plugin manager
        if auto_register:
            while self.uuid is None:
                self.register()
                if wait_for_registration:
                    self._wait_for_registration()
        # kick-off automatic heartbeat mechanism
        self._auto_heartbeat(auto_heartbeat_rate)
        # jump to run
        if start_running:
            LOG.info("Plugin running...")
            self.run()
Пример #7
0
 def on_scaling_request(self, ch, method, properties, payload):
     if properties.app_id != self.name:
         LOG.info('Scaling request received')
         message = yaml.load(payload)
         req = yaml.dump(message)
         topic = 'scaling.fsm.{0}'.format(message['uuid'])
         url = "{0}/fsm-{1}".format(self.sm_broker_host, message['uuid'])
         connection = messaging.ManoBrokerRequestResponseConnection(
             app_id=self.name, url=url)
         connection.call_async(self.on_scaling_result,
                               topic=topic,
                               msg=req,
                               correlation_id=properties.correlation_id)
         LOG.info(
             "Scaling request forwarded to FSM on topic: {0}".format(topic))
Пример #8
0
    def __init__(self):

        self.name = 'fake-slm'
        self.version = '0.1-dev'
        self.description = 'description'

        LOG.info("Starting SLM1:...")

        # create and initialize broker connection
        self.manoconn = messaging.ManoBrokerRequestResponseConnection(self.name)

        self.end = False

        self.publish_sid()

        self.run()
Пример #9
0
    def __init__(self):

        self.name = 'fake-slm'
        self.version = '0.1-dev'
        self.description = 'description'

        LOG.info("Starting SLM1:...")

        # create and initialize broker connection
        self.manoconn = messaging.ManoBrokerRequestResponseConnection(
            self.name)

        self.publish_nsd()
        #self.manoconn.subscribe(self.publish_nsd, "specific.manager.registry.ssm.instantiate")
        self.end = False

        self.run()
Пример #10
0
    def setUp(self):

        self.slm_proc = Process(target= fakeflm)
        self.smr_proc = Process(target= fakesmr)
        self.con_proc = Process(target= faceFSM)

        self.slm_proc.daemon = True
        self.smr_proc.daemon = True
        self.con_proc.daemon = True

        self.manoconn = messaging.ManoBrokerRequestResponseConnection('ConfTest')

        self.wait_for_reg_event = threading.Event()
        self.wait_for_reg_event.clear()

        self.wait_for_res_event = threading.Event()
        self.wait_for_res_event.clear()
Пример #11
0
    def __init__(self):

        self.name = 'fake-alert'
        self.version = '0.1-dev'
        self.description = 'description'

        LOG.info("Starting alert:...")

        # create and initialize broker connection
        self.manoconn = messaging.ManoBrokerRequestResponseConnection(self.name)

        self.path_descriptors = 'test/test_descriptors/'
        self.end = False

        self.publish_nsd()

        self.run()
Пример #12
0
    def __init__(self):

        self.name = 'placement-trigger'
        self.version = '0.1'
        self.description = 'description'

        LOG.info("Starting triggering placement SSM:...")

        # create and initialize broker connection
        self.manoconn = messaging.ManoBrokerRequestResponseConnection(
            self.name)

        self.path_descriptors = 'test/test_descriptors/'
        self.end = False

        self.publish_nsd()

        self.run()
Пример #13
0
    def __init__(self):

        self.name = 'fake-flm'
        self.version = '0.1-dev'
        self.description = 'description'

        LOG.info("Start sending VNFR:...")

        # create and initialize broker connection
        self.manoconn = messaging.ManoBrokerRequestResponseConnection(self.name)

        self.manoconn.subscribe(self._on_publish,'son.configuration')

        self.end = False

        self.publish_nsd()

        self.run()
Пример #14
0
    def __init__(self):

        self.name = 'fake-slm'
        self.version = '0.1-dev'
        self.description = 'description'

        LOG.info("Starting SLM1:...")

        # create and initialize broker connection
        self.manoconn = messaging.ManoBrokerRequestResponseConnection(
            self.name)

        self.path_descriptors = '/home/hadi/son-mano-framework/son-mano-specificmanager/son-mano-specific-manager-registry/test/test_descriptors/'

        self.end = False

        self.publish_sid()

        self.run()
Пример #15
0
    def __init__(self,
                 sm_id=None,
                 sm_version=None,
                 description=None,
                 connect_to_broker=True,
                 register=True):
        """
        :param specific_manager_type: specifies the type of specific manager that could be either fsm or ssm.
        :param service_name: the name of the service that this specific manager belongs to.
        :param function_name: the name of the function that this specific manager belongs to, will be null in SSM case
        :param specific_manager_name: the actual name of specific manager (e.g., scaling, placement)
        :param id_number: the specific manager id number which is used to distinguish between multiple SSM/FSM
        that are created for the same objective (e.g., scaling with algorithm 1 and 2)
        :param updated_version: specifies whether this SM is developed to update a current version or not,should be
        filled either by 'true' or 'false'
        :param version: version
        :param description: description
        """

        #Populating SSM-FSM fields
        self.sm_id = sm_id
        self.sm_version = sm_version
        self.description = description
        self.sfuuid = ''

        if 'sf_uuid' in os.environ:
            self.sfuuid = os.environ['sf_uuid']

        LOG.info("Starting specific manager with name: " + self.sm_id)
        LOG.info("Starting specific manager with sfuuid: " + self.sfuuid)

        # create and initialize broker connection
        if connect_to_broker:
            self.manoconn = messaging.ManoBrokerRequestResponseConnection(
                self.sm_id + '-' + str(self.sfuuid))
            LOG.info("Specific manager connected to broker.")

        # register only of there is a broker connection
        if connect_to_broker and register:
            self.wait_for_event = threading.Event()
            self.wait_for_event.clear()

            self.registration()
Пример #16
0
    def __init__(self,
                 smtype=None,
                 name=None,
                 id=None,
                 version=None,
                 description=None):
        """
        # FSM/SSM name consists of son,smtype(either ssm or fsm), name (a-z), and an id (0-9)

        :param smtype: specific management type: either fsm or ssm
        :param name: the name of the FSM/SSM
        :param id: the Id of the FSM/SSM
        :param version: version
        :param description: a description on what does FSM/SSM do
        """
        #checks if the chosen name by develeopr is correct
        self.name_checker(self.smtype, self.name, self.id)

        self.smtype = smtype
        self.id = id
        self.name = "son{0}{1}{2}".format(smtype, name, id)
        self.version = version
        self.description = description
        self.uuid = None

        LOG.info("Starting {0} ...".format(self.name))

        # create and initialize broker connection
        self.manoconn = messaging.ManoBrokerRequestResponseConnection(
            self.name)

        self.tLock = threading.Lock()
        t1 = threading.Thread(target=self.registeration)
        t2 = threading.Thread(target=self.run)

        # register to Specific Manager Registry
        t1.start()

        # locks the registration thread
        self.tLock.acquire()

        # jump to run
        t2.start()
Пример #17
0
    def resp_instant(self, ch, method, prop, payload):
        """
        This method handles responses to a request to onboard the fsms
        of a new function.
        """

        # Retrieve the function uuid
        func_id = tools.funcid_from_corrid(self.functions, prop.correlation_id)
        msg = ": Instantiating response received from SMR."
        LOG.info("Function " + func_id + msg)
        LOG.debug(payload)

        message = yaml.load(payload)
        for fsm_type in self.functions[func_id]['fsm'].keys():
            fsm = self.functions[func_id]['fsm'][fsm_type]
            response = message[fsm['id']]
            fsm['instantiated'] = False
            if response['error'] == 'None':
                LOG.info("Function " + func_id + ": FSM instantiated correct.")
                fsm['instantiated'] = True
            else:
                msg = ": FSM instantiation failed: " + response['error']
                LOG.info("Function " + func_id + msg)
                self.flm_error(func_id, error=response['error'])

            fsm['uuid'] = response['uuid']

        # Setup broker connection with the SSMs of this service.
        url = self.fsm_url_base + 'fsm-' + func_id
        fsm_conn = messaging.ManoBrokerRequestResponseConnection(self.name,
                                                                 url=url)

        self.fsm_connections[func_id] = fsm_conn

        # Continue with the scheduled tasks
        self.start_next_task(func_id)
Пример #18
0
    def recreate_ledger(self, payload, corr_id, func_id, topic):
        """
        This method adds already existing functions with their specifics
        back to the ledger, so other methods can use this information.

        :param payload: the payload of the received message
        :param corr_id: the correlation id of the received message
        :param func_id: the instance uuid of the function defined by SLM.
        """

        # Add the function to the ledger and add instance ids
        self.functions[func_id] = {}
        self.functions[func_id]['act_corr_id'] = None
        self.functions[func_id]['error'] = None

        # Get VNFR
        get_vnfr = tools.getRestData(t.vnfr_path + '/', func_id)
        if get_vnfr['error'] is not None:
            error = get_vnfr['error'] + ': ' + get_vnfr['content']
            self.functions[func_id]['error'] = error
            return False
        self.functions[func_id]['vnfr'] = get_vnfr['content']
        self.functions[func_id]['vnfr']['id'] = func_id
        del self.functions[func_id]['vnfr']['created_at']
        del self.functions[func_id]['vnfr']['updated_at']
        del self.functions[func_id]['vnfr']['uuid']

        # GET VNFD
        vnfd_id = self.functions[func_id]['vnfr']['descriptor_reference']
        LOG.info(str(t.vnfd_path + '/' + vnfd_id))
        head = {"Content-type": "application/json"}
        get_vnfd = tools.getRestData(t.vnfd_path + '/', vnfd_id, head=head)
        if get_vnfd['error'] is not None:
            error = str(get_vnfd['error']) + ': ' + str(get_vnfd['content'])
            LOG.info(str(error))
            self.functions[func_id]['error'] = error
            return False
        self.functions[func_id]['vnfd'] = get_vnfd['content']['vnfd']
        LOG.info(str(self.functions[func_id]['vnfd']))

        self.functions[func_id]['id'] = func_id

        # Add the topic of the call
        self.functions[func_id]['topic'] = topic

        # Add to correlation id to the ledger
        self.functions[func_id]['orig_corr_id'] = corr_id

        # Add payload to the ledger
        self.functions[func_id]['payload'] = payload

        # Add the service uuid that this function belongs to
        self.functions[func_id]['serv_id'] = payload['serv_id']

        # Add the VIM uuid
        if 'vim_id' in payload.keys():
            self.functions[func_id]['vim_uuid'] = payload['vim_id']
        else:
            vdus = self.functions[func_id]['vnfr']['virtual_deployment_units']
            vim_id = vdus[0]['vnfc_instance'][0]['vim_id']
            self.functions[func_id]['vim_uuid'] = vim_id

        # Create the function schedule
        self.functions[func_id]['schedule'] = []

        # Create the FSM dict if FSMs are defined in VNFD
        fsm_dict = tools.get_fsm_from_vnfd(self.functions[func_id]['vnfd'])
        LOG.info(str(fsm_dict))
        self.functions[func_id]['fsm'] = fsm_dict

        # Setup broker connection with the SSMs of this service.
        if bool(fsm_dict) and func_id not in self.fsm_connections.keys():
            url = self.fsm_url_base + 'fsm-' + func_id
            fsm_conn = messaging.ManoBrokerRequestResponseConnection(self.name,
                                                                     url=url)

            self.fsm_connections[func_id] = fsm_conn

        # Create the chain pause and kill flag

        self.functions[func_id]['pause_chain'] = False
        self.functions[func_id]['kill_chain'] = False

        # Create payload fields for FSMs
        self.functions[func_id]['start'] = None
        self.functions[func_id]['stop'] = None
        self.functions[func_id]['configure'] = None
        self.functions[func_id]['message'] = None

        return True
Пример #19
0
    def update(self, message):

        descriptor = None
        manager = None
        result_dict = {}
        sm_type = 'ssm'
        v_host_error = False

        if 'NSD' in message:
            descriptor = 'NSD'
            manager = 'service_specific_managers'
        elif 'VNFD' in message:
            descriptor = 'VNFD'
            manager = 'function_specific_managers'
            sm_type = 'fsm'

        # Create virtual host for the service/function to be used by SSM/FSM
        response = self.smrengine.create_vh(sm_type=sm_type,
                                            uuid=message['UUID'])
        if response == (201, 201) or (0, 0):
            url = "{0}/{1}-{2}".format(self.smrengine.sm_broker_host, sm_type,
                                       message['UUID'])
            connection = messaging.ManoBrokerRequestResponseConnection(
                app_id=self.name, url=url)
            connection.register_async_endpoint(self.on_ssm_register,
                                               topic.SSM_REGISTRATION)
            time.sleep(1)
            if (201, 201):
                LOG.info('Virtual Host: {0}-{1} has been created!'.format(
                    sm_type, message['UUID']))
            else:
                LOG.info('Virtual Host already exists')
        else:
            v_host_error = True

        for i in range(len(message[descriptor][manager])):

            if not v_host_error:
                # retrieve current id and image
                op_list = message[descriptor][manager][i]['options']
                c_id = None
                c_image = None

                for j in range(len(op_list)):
                    if op_list[j]['key'] == 'currentId':
                        c_id = op_list[j]['value']
                        break
                for k in range(len(op_list)):
                    if op_list[k]['key'] == 'currentImage':
                        c_image = op_list[k]['value']
                        break

                if c_id and c_image is not None:

                    LOG.info('Updating request received for: {0}'.format(c_id))
                    m_id = message[descriptor][manager][i]['id']
                    m_image = message[descriptor][manager][i]['image']
                    sm_repo_name = "{0}{1}".format(m_id, message['UUID'])

                    # onboard the new SM
                    LOG.info('On-boarding started for : {0}'.format(m_id))
                    try:
                        result = self.smrengine.pull(image=m_image)
                    except BaseException as error:
                        result_dict.update(
                            {m_id: {
                                'status': 'Failed',
                                'error': str(error)
                            }})
                        LOG.error('On-boarding failed for: {0}'.format(m_id))
                    else:
                        result = yaml.load(result.split("\n")[1])
                        if 'error' in result.keys():
                            LOG.error(
                                'On-boarding failed for: {0}'.format(m_id))
                            result_dict.update({
                                m_id: {
                                    'status': 'Failed',
                                    'error': result['error']
                                }
                            })
                        else:
                            LOG.info(
                                'On-boarding succeeded for: {0}'.format(m_id))

                            if c_id == m_id and self.ssm_repo[sm_repo_name][
                                    'sfuuid'] == message['UUID']:

                                # instantiate the new SM
                                LOG.info(
                                    'Instantiation started for: {0}'.format(
                                        m_id))
                                if 'private_key' in message:
                                    p_key = message['private_key']
                                else:
                                    p_key = None
                                try:
                                    random_id = self.id_generator()
                                    self.smrengine.start(id=random_id,
                                                         image=m_image,
                                                         sm_type=sm_type,
                                                         uuid=message['UUID'],
                                                         p_key=p_key)
                                except BaseException as error:
                                    LOG.error(
                                        'Instantiation failed for: {0}, Error: {1}'
                                        .format(m_id, error))
                                    result_dict.update({
                                        m_id: {
                                            'status': 'Failed',
                                            'uuid': 'None',
                                            'error': str(error)
                                        }
                                    })
                                else:

                                    # Check if update is successfully done.
                                    update = threading.Thread(
                                        target=self._wait_for_update,
                                        args=[sm_repo_name])
                                    update.daemon = True
                                    update.start()
                                    update.join()

                                    if self.ssm_repo[sm_repo_name][
                                            'status'] == 'registered':
                                        LOG.debug(
                                            'Registration & instantiation succeeded for: {0}'
                                            .format(m_id))
                                        self.ssm_repo[sm_repo_name][
                                            'status'] = 'running'
                                        result_dict.update({
                                            m_id: {
                                                'status':
                                                'Updated',
                                                'uuid':
                                                self.ssm_repo[sm_repo_name]
                                                ['uuid'],
                                                'error':
                                                'None'
                                            }
                                        })

                                        # terminate the current SM
                                        try:
                                            self.smrengine.rm(
                                                id=c_id,
                                                image=c_image,
                                                uuid=message['UUID'])
                                        except BaseException as error:
                                            LOG.error(
                                                "Termination failed for: {0} , Error: {1}"
                                                .format(c_id, error))
                                            self.smrengine.rm(
                                                id=random_id,
                                                image=m_image,
                                                uuid=message['UUID'])
                                            result_dict.update({
                                                m_id: {
                                                    'status': 'Failed',
                                                    'error': str(error)
                                                }
                                            })
                                        else:
                                            try:
                                                self.smrengine.rename(
                                                    "{0}{1}".format(
                                                        random_id,
                                                        message['UUID']),
                                                    "{0}{1}".format(
                                                        m_id, message['UUID']))

                                            except BaseException as error:
                                                LOG.error(
                                                    "Rename failed for: {0} , Error: {1}"
                                                    .format(c_id, error))
                                                self.smrengine.rm(
                                                    id=random_id,
                                                    image=m_image,
                                                    uuid=message['UUID'])
                                                result_dict.update({
                                                    m_id: {
                                                        'status': 'Failed',
                                                        'error': str(error)
                                                    }
                                                })
                                            else:
                                                self.ssm_repo[sm_repo_name][
                                                    'status'] = 'updated'
                                                LOG.debug(
                                                    "Termination succeeded for: {0} (old version)"
                                                    .format(c_id))
                                                LOG.debug(
                                                    '{0} updating succeeded'.
                                                    format(m_id))
                                    else:
                                        LOG.error(
                                            "Instantiation failed for: {0}, "
                                            "Error: Registration failed".
                                            format(m_id))
                                        result_dict.update({
                                            m_id: {
                                                'status': 'Failed',
                                                'uuid': 'None',
                                                'error': 'Registration failed'
                                            }
                                        })
                                        self.smrengine.rm(id=m_id,
                                                          image=m_image,
                                                          uuid=message['UUID'])
                            else:
                                # instantiate the new SM
                                LOG.info(
                                    'Instantiation started for: {0}'.format(
                                        m_id))
                                if 'private_key' in message:
                                    p_key = message['private_key']
                                else:
                                    p_key = None
                                try:
                                    self.smrengine.start(id=m_id,
                                                         image=m_image,
                                                         sm_type=sm_type,
                                                         uuid=message['UUID'],
                                                         p_key=p_key)
                                except BaseException as error:
                                    LOG.error(
                                        'Instantiation failed for: {0}, Error: {1}'
                                        .format(m_id, error))
                                    result_dict.update({
                                        m_id: {
                                            'status': 'Failed',
                                            'uuid': 'None',
                                            'error': str(error)
                                        }
                                    })
                                else:

                                    # Check if the registration is successfully done
                                    registration = threading.Thread(
                                        target=self._wait_for_sm_registration,
                                        args=[sm_repo_name, m_id])
                                    registration.daemon = True
                                    registration.start()
                                    registration.join()

                                    if sm_repo_name in self.ssm_repo.keys():
                                        LOG.debug(
                                            'Registration & instantiation succeeded for: {0}'
                                            .format(m_id))
                                        self.ssm_repo[sm_repo_name][
                                            'status'] = 'running'
                                        result_dict.update({
                                            m_id: {
                                                'status':
                                                'Updated',
                                                'uuid':
                                                self.ssm_repo[sm_repo_name]
                                                ['uuid'],
                                                'error':
                                                'None'
                                            }
                                        })

                                        # terminate the current SM
                                        try:
                                            self.smrengine.rm(
                                                id=c_id,
                                                image=c_image,
                                                uuid=message['UUID'])
                                        except BaseException as error:
                                            LOG.error(
                                                "Termination failed for: {0} , Error: {1}"
                                                .format(c_id, error))
                                            self.smrengine.rm(
                                                id=m_id,
                                                image=m_image,
                                                uuid=message['UUID'])
                                            del self.ssm_repo[sm_repo_name]
                                            result_dict.update({
                                                m_id: {
                                                    'status': 'Failed',
                                                    'error': str(error)
                                                }
                                            })
                                        else:
                                            LOG.debug(
                                                "Termination succeeded for: {0} (old version)"
                                                .format(c_id))
                                            self.ssm_repo[sm_repo_name][
                                                'status'] = 'terminated'
                                            LOG.debug(
                                                'Updating succeeded, {0} has replaced by {1}'
                                                .format(c_id, m_id))
                                    else:
                                        LOG.error(
                                            "Instantiation failed for: {0}, Error: Registration failed"
                                            .format(m_id))
                                        result_dict.update({
                                            m_id: {
                                                'status': 'Failed',
                                                'uuid': 'None',
                                                'error': 'Registration failed'
                                            }
                                        })
                                        self.smrengine.rm(id=m_id,
                                                          image=m_image,
                                                          uuid=message['UUID'])
            else:
                LOG.error(
                    'Instantiation failed for: {0}, Error: RabbitMQ virtual host creation failed'
                    .format(m_id))
                result_dict.update({
                    m_id: {
                        'status': 'Failed',
                        'uuid': 'None',
                        'error': 'RabbitMQ virtual host creation failed'
                    }
                })
        return result_dict
Пример #20
0
    def instantiate(self, message):

        descriptor = None
        manager = None
        result_dict = {}
        v_host_error = False

        if 'NSD' in message:
            descriptor = 'NSD'
            manager = 'service_specific_managers'
            sm_type = 'ssm'
        elif 'VNFD' in message:
            descriptor = 'VNFD'
            manager = 'function_specific_managers'
            sm_type = 'fsm'

        # Create virtual host for the service/function to be used by SSM/FSM
        response = self.smrengine.create_vh(sm_type=sm_type,
                                            uuid=message['UUID'])

        if response == (201, 201) or (0, 0):
            url = "{0}/{1}-{2}".format(self.smrengine.sm_broker_host, sm_type,
                                       message['UUID'])
            connection = messaging.ManoBrokerRequestResponseConnection(
                app_id=self.name, url=url)
            connection.register_async_endpoint(self.on_ssm_register,
                                               topic.SSM_REGISTRATION)
            time.sleep(1)
            if response == (201, 201):
                LOG.info('Virtual Host: {0}-{1} has been created!'.format(
                    sm_type, message['UUID']))
            else:
                LOG.info('Virtual Host already exists')
        else:
            v_host_error = True
        for i in range(len(message[descriptor][manager])):
            if not v_host_error:
                m_id = message[descriptor][manager][i]['id']
                m_image = message[descriptor][manager][i]['image']
                if 'private_key' in message:
                    p_key = message['private_key']
                else:
                    p_key = None
                LOG.info(
                    'Instantiation request received for: {0}'.format(m_id))
                sf_uuid = message['UUID']
                try:
                    self.smrengine.start(id=m_id,
                                         image=m_image,
                                         sm_type=sm_type,
                                         uuid=message['UUID'],
                                         p_key=p_key)
                except BaseException as error:
                    LOG.error(
                        'Instantiation failed for: {0}, Error: {1}'.format(
                            m_id, error))
                    result_dict.update({
                        m_id: {
                            'status': 'Failed',
                            'uuid': 'None',
                            'error': str(error)
                        }
                    })
                else:
                    registration = threading.Thread(
                        target=self._wait_for_sm_registration,
                        args=[sf_uuid, m_id])
                    registration.daemon = True
                    registration.start()
                    registration.join()
                    if sf_uuid in self.ssm_repo.keys():
                        LOG.debug(
                            'Registration & instantiation succeeded for: {0}'.
                            format(m_id))
                        self.ssm_repo[sf_uuid]['status'] = 'running'
                        result_dict.update({
                            m_id: {
                                'status': 'Instantiated',
                                'uuid': sf_uuid,
                                'error': 'None'
                            }
                        })
                    else:
                        LOG.error(
                            'Instantiation failed:SSM name {0} not found!'.
                            format(m_id))
                        result_dict.update({
                            m_id: {
                                'status': 'Failed',
                                'uuid': 'None',
                                'error': 'Registration failed'
                            }
                        })
                        self.smrengine.rm(id=m_id,
                                          image=m_image,
                                          uuid=message['UUID'])
            else:
                LOG.error(
                    'Instantiation failed for: {0}, Error: RabbitMQ virtual host creation failed'
                    .format(m_id))
                result_dict.update({
                    m_id: {
                        'status': 'Failed',
                        'uuid': 'None',
                        'error': 'RabbitMQ virtual host creation failed'
                    }
                })

        return result_dict