예제 #1
0
    def __init__(self):

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

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

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

        self.publish_nsd()
예제 #2
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))
예제 #3
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))
예제 #4
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(5)
        # 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:
            self.run()
예제 #5
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_updating()

        self.run()
예제 #6
0
파일: main.py 프로젝트: CN-UPB/Pishahang
    def resp_instant(self, message: Message):
        """
        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,
                                           message.correlation_id)
        msg = ": Instantiating response received from SMR."
        LOG.info("Function %s%s", func_id, msg)
        LOG.debug(message.payload)

        for fsm_type in self.functions[func_id]["fsm"].keys():
            fsm = self.functions[func_id]["fsm"][fsm_type]
            response = message.payload[fsm["id"]]
            fsm["instantiated"] = False
            if response["error"] == "None":
                LOG.info("Function %s: FSM instantiated correctly.", func_id)
                fsm["instantiated"] = True
            else:
                msg = ": FSM instantiation failed: " + response["error"]
                LOG.info("Function %s%s", 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.osm_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)
예제 #7
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)
예제 #8
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
예제 #9
0
    def instantiate(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 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))
                sm_repo_name = "{0}{1}".format(m_id, 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=[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': 'Instantiated',
                                'uuid': self.ssm_repo[sm_repo_name]['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
예제 #10
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 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:
                # 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
예제 #11
0
    def instantiate(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 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))
                sm_repo_name = "{0}{1}".format(m_id, 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=[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": "Instantiated",
                                "uuid": self.ssm_repo[sm_repo_name]["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