コード例 #1
0
ファイル: test_vims.py プロジェクト: CN-UPB/Pishahang
def testDeleteVim(api, broker: Connection, reraise):
    id = str(uuid4())

    vimAdaptorResponse = {"request_status": "SUCCESS"}

    # Mock vim adaptor
    def onDeleteVimRequest(message: Message):
        with reraise(catch=True):
            assert {"id": id} == message.payload

        return vimAdaptorResponse

    broker.register_async_endpoint(onDeleteVimRequest,
                                   "infrastructure.management.compute.remove")

    # Test successful deletion
    assert 204 == api.delete("/api/v3/vims/" + id).status_code

    # Test vim adaptor error response
    vimAdaptorResponse = {
        "request_status": "ERROR",
        "message": "error message"
    }
    reply = api.delete("/api/v3/vims/" + id)
    assert 500 == reply.status_code
    assert "error message" == reply.get_json()["detail"]
コード例 #2
0
def connection():
    """
    A loopback broker connection
    """
    connection = ManoBrokerRequestResponseConnection(
        "test-connection", is_loopback=True
    )
    yield connection
    connection.close()
コード例 #3
0
ファイル: terminating.py プロジェクト: CN-UPB/Pishahang
    def __init__(self):

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

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

        self.manoconn = ManoBrokerRequestResponseConnection(self.name)

        self.publish_terminating()
コード例 #4
0
ファイル: onboarding.py プロジェクト: CN-UPB/Pishahang
    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 = ManoBrokerRequestResponseConnection(self.name)

        self.publish_nsd()
コード例 #5
0
    def setUp(self):
        #a new Placement Executive in another process for each test
        self.plex_proc = Process(target=PlacementExecutive)
        self.plex_proc.daemon = True

        if 'broker_man_host' in os.environ:
            self.man_host = os.environ['broker_man_host']
        else:
            self.man_host = 'http://localhost:15672'

        if 'sm_broker_host' in os.environ:
            self.sm_host = os.environ['sm_broker_host']
        else:
            self.sm_host = 'http://localhost:15672'
        url_user = "******".format(self.man_host)
        url_create = '{0}/api/vhosts/ssm-1234'.format(self.man_host)
        url_permission = '{0}/api/permissions/ssm-1234/specific-management'.format(
            self.man_host)
        self.headers = {'content-type': 'application/json'}
        data1 = '{"password":"******","tags":"son-sm"}'
        data2 = '{"configure":".*","write":".*","read":".*"}'
        res = requests.put(url=url_user,
                           headers=self.headers,
                           data=data1,
                           auth=('guest', 'guest'))
        LOG.info(res.content)
        res1 = requests.put(url=url_create,
                            headers=self.headers,
                            auth=('guest', 'guest'))
        LOG.info(res1.content)
        res2 = requests.put(url=url_permission,
                            headers=self.headers,
                            data=data2,
                            auth=('guest', 'guest'))
        LOG.info(res2.content)

        #make a new connection with the broker before each test
        url = "{0}/ssm-1234".format(self.sm_host)
        self.manoconn = ManoBrokerRequestResponseConnection(
            'son-plugin.SonPluginManager')
        self.sm_connection = ManoBrokerRequestResponseConnection(
            'son-plugin.SSM', url=url)

        #Some threading events that can be used during the tests
        self.wait_for_event1 = threading.Event()
        self.wait_for_event1.clear()

        self.wait_for_event2 = threading.Event()
        self.wait_for_event2.clear()
コード例 #6
0
ファイル: test_plugin.py プロジェクト: CN-UPB/Pishahang
def test_registration_and_heartbeat(connection: Connection, reraise):
    registration_request_received = Event()

    def on_registration_request(message: Message):
        """
        When the registration request from the plugin is received, this method replies
        as if it were the plugin manager
        """
        with reraise:
            non_empty_string = All(str, Length(min=1))
            assert (S({
                "name": non_empty_string,
                "version": non_empty_string,
                "description": non_empty_string,
            }) == message.payload)
        return {"status": "OK", "uuid": PLUGIN_UUID}

    heartbeat_received = Event()

    def on_heartbeat(message: Message):
        with reraise:
            assert (S({
                "uuid": PLUGIN_UUID,
                "state": In(("READY", "RUNNING", "PAUSED", "FAILED")),
            }) == message.payload)
        heartbeat_received.set()

    connection.register_async_endpoint(on_registration_request,
                                       "platform.management.plugin.register")
    connection.subscribe(
        on_heartbeat,
        "platform.management.plugin." + PLUGIN_UUID + ".heartbeat",
    )

    plugin = ManoBasePlugin(
        use_loopback_connection=True,
        version="1.2.3",
        description="Test Plugin",
    )

    try:
        registration_request_received.wait(1)
        heartbeat_received.wait(1)

        assert plugin.uuid == PLUGIN_UUID
    finally:
        plugin.conn.close()
コード例 #7
0
ファイル: updating.py プロジェクト: CN-UPB/Pishahang
class fakeslm_updating(object):
    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 = ManoBrokerRequestResponseConnection(self.name)

        self.publish_updating()

    def publish_updating(self):

        LOG.info("Sending updating request")
        with open("test/test_descriptors/nsdu.yml") as nsd:
            self.manoconn.call_async(
                self._on_publish_ins_response,
                "specific.manager.registry.ssm.update",
                {
                    "NSD": yaml.load(nsd),
                    "UUID": "937213ae-890b-413c-a11e-45c62c4eee3f",
                },
            )

        with open("test/test_descriptors/vnfdu.yml") as vnfd1:
            self.manoconn.call_async(
                self._on_publish_ins_response,
                "specific.manager.registry.fsm.update",
                {
                    "VNFD": yaml.load(vnfd1),
                    "UUID": "754fe4fe-96c9-484d-9683-1a1e8b9a31a3",
                },
            )

    def _on_publish_ins_response(self, message: Message):

        response = message.payload
        if type(response) == dict:
            try:
                print(response)
            except BaseException as error:
                print(error)
コード例 #8
0
ファイル: test_smr.py プロジェクト: hadik3r/Pishahang
    def setUpClass(self):

        self.smr_proc = Process(target=SpecificManagerRegistry)

        self.smr_proc.daemon = True

        self.manoconn = ManoBrokerRequestResponseConnection(
            'son-plugin.SpecificManagerRegistry')

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

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

        self.event1 = False
        self.event2 = False

        self.smr_proc.start()
        time.sleep(4)
コード例 #9
0
ファイル: test_vims.py プロジェクト: CN-UPB/Pishahang
def testGetVims(api, broker: Connection):
    # Mock vim adaptor
    broker.register_async_endpoint(
        lambda message: [{
            "id": "id",
            "name": "name",
            "country": "country",
            "city": "city",
            "type": "type",
            "cores": {
                "total": 4,
                "used": 3
            },
            "memory": {
                "total": 2,
                "used": 1
            },
        }],
        "infrastructure.management.compute.list",
    )

    response = api.get("/api/v3/vims")
    assert 200 == response.status_code
    assert [{
        "id": "id",
        "name": "name",
        "country": "country",
        "city": "city",
        "type": "type",
        "cores": {
            "total": 4,
            "used": 3
        },
        "memory": {
            "total": 2,
            "used": 1
        },
    }] == response.get_json()
コード例 #10
0
ファイル: onboarding.py プロジェクト: CN-UPB/Pishahang
class fakeslm_onboarding(object):
    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 = ManoBrokerRequestResponseConnection(self.name)

        self.publish_nsd()

    def publish_nsd(self):

        LOG.info("Sending onboard request")
        with open("test/test_descriptors/nsd.yml") as nsd:
            self.manoconn.call_async(
                self._on_publish_nsd_response,
                "specific.manager.registry.ssm.on-board",
                {"NSD": yaml.load(nsd)},
            )

        with open("test/test_descriptors/vnfd1.yml") as vnfd1:
            self.manoconn.call_async(
                self._on_publish_nsd_response,
                "specific.manager.registry.fsm.on-board",
                {"VNFD": yaml.load(vnfd1)},
            )

        with open("test/test_descriptors/vnfd2.yml") as vnfd2:
            self.manoconn.call_async(
                self._on_publish_nsd_response,
                "specific.manager.registry.fsm.on-board",
                {"VNFD": yaml.load(vnfd2)},
            )

    def _on_publish_nsd_response(self, message: Message):

        response = message.payload
        if type(response) == dict:
            print(response)
コード例 #11
0
ファイル: test_vims.py プロジェクト: CN-UPB/Pishahang
def testAddVim(api, broker: Connection, reraise):
    id = str(uuid4())  # VIM uuid returned by the vim-adaptor mock

    baseVimData = {
        "city": "my city",
        "country": "my country",
        "name": "my name",
    }

    vimData = {
        "aws": {
            **baseVimData,
            "type": "aws",
            "accessKey": "access key",
            "secretKey": "secret key",
            "region": "region",
        },
        "kubernetes": {
            **baseVimData,
            "type": "kubernetes",
            "serviceToken": "service token",
            "address": "address",
            "port": 1234,
            "ccc": "ccc",
        },
        "openstack": {
            **baseVimData,
            "type": "openstack",
            "address": "address",
            "tenant": {
                "id": "tenant id",
                "externalNetworkId": "tenant external network id",
                "externalRouterId": "tenant external router id",
            },
            "username": "******",
            "password": "******",
        },
    }

    vimAdaptorResponse = {"request_status": "COMPLETED", "id": id}

    # Mock vim adaptor
    def onAddVimRequest(message: Message):
        with reraise(catch=True):
            # baseVimData should be contained in the payload
            assert S(baseVimData) <= message.payload

        return vimAdaptorResponse

    broker.register_async_endpoint(onAddVimRequest,
                                   "infrastructure.management.compute.add")

    # Add all types of vims
    for data in vimData.values():
        reply = api.post("/api/v3/vims", json=data)
        assert 201 == reply.status_code
        assert {"id": id} == reply.get_json()

    # Let the mock vim adaptor reply with an error
    vimAdaptorResponse = {
        "request_status": "ERROR",
        "message": "error message"
    }
    reply = api.post("/api/v3/vims", json=vimData["aws"])
    assert 500 == reply.status_code
    assert "error message" == reply.get_json()["detail"]
コード例 #12
0
ファイル: test_plugin.py プロジェクト: CN-UPB/Pishahang
def connection():
    connection = Connection("test-connection", is_loopback=True)

    yield connection
    connection.close()
コード例 #13
0
class testPLEXRegistration(unittest.TestCase):
    """
    Tests the registration process of the Placement Executive to the broker
    and the plugin manager, and the heartbeat process.
    """
    def setUp(self):
        #a new Placement Executive in another process for each test
        self.plex_proc = Process(target=PlacementExecutive)
        self.plex_proc.daemon = True

        if 'broker_man_host' in os.environ:
            self.man_host = os.environ['broker_man_host']
        else:
            self.man_host = 'http://localhost:15672'

        if 'sm_broker_host' in os.environ:
            self.sm_host = os.environ['sm_broker_host']
        else:
            self.sm_host = 'http://localhost:15672'
        url_user = "******".format(self.man_host)
        url_create = '{0}/api/vhosts/ssm-1234'.format(self.man_host)
        url_permission = '{0}/api/permissions/ssm-1234/specific-management'.format(
            self.man_host)
        self.headers = {'content-type': 'application/json'}
        data1 = '{"password":"******","tags":"son-sm"}'
        data2 = '{"configure":".*","write":".*","read":".*"}'
        res = requests.put(url=url_user,
                           headers=self.headers,
                           data=data1,
                           auth=('guest', 'guest'))
        LOG.info(res.content)
        res1 = requests.put(url=url_create,
                            headers=self.headers,
                            auth=('guest', 'guest'))
        LOG.info(res1.content)
        res2 = requests.put(url=url_permission,
                            headers=self.headers,
                            data=data2,
                            auth=('guest', 'guest'))
        LOG.info(res2.content)

        #make a new connection with the broker before each test
        url = "{0}/ssm-1234".format(self.sm_host)
        self.manoconn = ManoBrokerRequestResponseConnection(
            'son-plugin.SonPluginManager')
        self.sm_connection = ManoBrokerRequestResponseConnection(
            'son-plugin.SSM', url=url)

        #Some threading events that can be used during the tests
        self.wait_for_event1 = threading.Event()
        self.wait_for_event1.clear()

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

    def tearDown(self):
        #Killing the Placement Executive
        if self.plex_proc is not None:
            self.plex_proc.terminate()
        del self.plex_proc

        #Killing the connection with the broker
        try:
            self.manoconn.stop_connection()
            self.sm_connection.stop_connection()
        except Exception as e:
            LOG.exception("Stop connection exception.")

        #Clearing the threading helpers
        del self.wait_for_event1
        del self.wait_for_event2

        url_user = "******".format(self.man_host)
        url_vhost = "{0}/api/vhosts/ssm-1234".format(self.man_host)
        res1 = requests.delete(url=url_user,
                               headers=self.headers,
                               auth=('guest', 'guest'))
        LOG.info(res1.content)
        res1 = requests.delete(url=url_vhost,
                               headers=self.headers,
                               auth=('guest', 'guest'))
        LOG.info(res1.content)

    #Method that terminates the timer that waits for an event
    def eventFinished1(self):
        self.wait_for_event1.set()

    def eventFinished2(self):
        self.wait_for_event2.set()

    #Method that starts a timer, waiting for an event
    def waitForEvent1(self, timeout=5, msg="Event timed out."):
        if not self.wait_for_event1.wait(timeout):
            self.assertEqual(True, False, msg=msg)

    def waitForEvent2(self, timeout=5, msg="Event timed out."):
        if not self.wait_for_event2.wait(timeout):
            self.assertEqual(True, False, msg=msg)

    def test_1_PLEX_Registration(self):
        """
        TEST: This test verifies whether the Placement Executive is sending out a message,
        and whether it contains all the needed info on the
        platform.management.plugin.register topic to register to the plugin
        manager.
        """

        #STEP3a: When receiving the message, we need to check whether all fields present.
        def on_register_receive(ch, method, properties, message):

            msg = yaml.load(message)
            #CHECK: The message should be a dictionary.
            self.assertTrue(isinstance(msg, dict),
                            msg='message is not a dictionary')
            #CHECK: The dictionary should have a key 'name'.
            self.assertIn('name',
                          msg.keys(),
                          msg='No name provided in message.')
            if isinstance(msg['name'], str):
                #CHECK: The value of 'name' should not be an empty string.
                self.assertTrue(len(msg['name']) > 0,
                                msg='empty name provided.')
            else:
                #CHECK: The value of 'name' should be a string
                self.assertEqual(True, False, msg='name is not a string')
            #CHECK: The dictionary should have a key 'version'.
            self.assertIn('version',
                          msg.keys(),
                          msg='No version provided in message.')
            if isinstance(msg['version'], str):
                #CHECK: The value of 'version' should not be an empty string.
                self.assertTrue(len(msg['version']) > 0,
                                msg='empty version provided.')
            else:
                #CHECK: The value of 'version' should be a string
                self.assertEqual(True, False, msg='version is not a string')
            #CHECK: The dictionary should have a key 'description'
            self.assertIn('description',
                          msg.keys(),
                          msg='No description provided in message.')
            if isinstance(msg['description'], str):
                #CHECK: The value of 'description' should not be an empty string.
                self.assertTrue(len(msg['description']) > 0,
                                msg='empty description provided.')
            else:
                #CHECK: The value of 'description' should be a string
                self.assertEqual(True,
                                 False,
                                 msg='description is not a string')

            # stop waiting
            self.eventFinished1()

        #STEP1: Listen to the platform.management.plugin.register topic
        self.manoconn.subscribe(on_register_receive,
                                'platform.management.plugin.register')

        #STEP2: Start the Placement Executive
        self.plex_proc.start()

        #STEP3b: When not receiving the message, the test failed
        self.waitForEvent1(timeout=5, msg="message not received.")

    def test_2_PLEX_request_response(self):
        def on_request_send(ch, method, properties, message):

            if properties.app_id == "son-plugin.PlacementExecutive":
                msg = yaml.load(message)

                self.assertTrue(isinstance(msg, dict),
                                msg='message is not a dictionary')

                self.assertIn('uuid',
                              msg.keys(),
                              msg='No uuid provided in message.')
                if isinstance(msg['uuid'], str):
                    self.assertTrue(msg['uuid'] == '1234',
                                    msg='empty uuid provided.')

                self.assertNotIn('place', msg.keys(), msg='wrong message.')

                res_payload = yaml.dump({'uuid': '1234', 'place': '2'})

                self.eventFinished1()
                return res_payload

        def on_response_send(ch, method, properties, message):
            if properties.app_id == "son-plugin.PlacementExecutive":
                msg = yaml.load(message)

                self.assertTrue(isinstance(msg, dict),
                                msg='message is not a dictionary')

                self.assertIn('uuid',
                              msg.keys(),
                              msg='No uuid provided in message.')
                if isinstance(msg['uuid'], str):
                    self.assertTrue(msg['uuid'] == '1234',
                                    msg='empty uuid provided.')

                self.assertIn('place',
                              msg.keys(),
                              msg='No place provided in message.')
                if isinstance(msg['place'], str):
                    self.assertTrue(msg['place'] == '2',
                                    msg='empty uuid provided.')

                self.eventFinished2()

        self.plex_proc.start()

        time.sleep(2)

        self.manoconn.subscribe(on_response_send,
                                'placement.executive.request')
        self.sm_connection.register_async_endpoint(on_request_send,
                                                   'placement.ssm.1234')

        req_payload = yaml.dump({'uuid': '1234'})
        self.manoconn.publish("placement.executive.request",
                              message=req_payload)

        self.waitForEvent1(timeout=5, msg="response message not received.")
        self.waitForEvent2(timeout=5, msg="request message not received.")
コード例 #14
0
ファイル: test_smr.py プロジェクト: hadik3r/Pishahang
class test_SMR_functionalities(unittest.TestCase):
    @classmethod
    def setUpClass(self):

        self.smr_proc = Process(target=SpecificManagerRegistry)

        self.smr_proc.daemon = True

        self.manoconn = ManoBrokerRequestResponseConnection(
            'son-plugin.SpecificManagerRegistry')

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

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

        self.event1 = False
        self.event2 = False

        self.smr_proc.start()
        time.sleep(4)

    @classmethod
    def tearDownClass(self):

        if self.smr_proc is not None:
            self.smr_proc.terminate()
        del self.smr_proc

        try:
            self.manoconn.stop_connection()
        except Exception as e:
            LOG.exception("Stop connection exception.")

        del self.wait_for_fsm_event
        del self.wait_for_ssm_event

    def ssm_eventFinished(self):
        self.wait_for_ssm_event.set()

    def waitForSSMEvent(self, timeout=5, msg="Event timed out."):
        if not self.wait_for_ssm_event.wait(timeout):
            self.assertEqual(True, False, msg=msg)

    def fsm_eventFinished(self):
        self.wait_for_fsm_event.set()

    def waitForFSMEvent(self, timeout=5, msg="Event timed out."):
        if not self.wait_for_fsm_event.wait(timeout):
            self.assertEqual(True, False, msg=msg)

    def test_1_SMR_onboard(self):

        self.event1 = False
        self.event2 = False

        def on_ssm_onboarding_result(ch, method, properties, message):

            if properties.app_id == 'son-plugin.SpecificManagerRegistry':
                result = yaml.load(message)

                self.assertTrue(
                    list(result.keys())
                    == ['sonssmservice1dumb1', 'sonssmservice1placement1']
                    or list(result.keys())
                    == ['sonssmservice1placement1', 'sonssmservice1dumb1'],
                    msg='not all SSMs results received')

                self.assertTrue(
                    result['sonssmservice1dumb1']['status'] == 'On-boarded',
                    msg='error in onbording sonssmservice1dumb1')

                self.assertTrue(
                    result['sonssmservice1dumb1']['error'] == 'None',
                    msg='error in onbording sonssmservice1dumb1')

                self.assertTrue(result['sonssmservice1placement1']['status'] ==
                                'On-boarded',
                                msg='error in onbording sonssmservice1dumb1')

                self.assertTrue(
                    result['sonssmservice1placement1']['error'] == 'None',
                    msg='error in onbording sonssmservice1placement1')

                self.ssm_eventFinished()

        def on_fsm_onboarding_result(ch, method, properties, message):

            if properties.app_id == 'son-plugin.SpecificManagerRegistry':

                result = yaml.load(message)
                if list(result.keys()) == ['sonfsmservice1function1dumb1']:

                    self.assertTrue(
                        list(
                            result.keys()) == ['sonfsmservice1function1dumb1'],
                        msg='not all FSMs results in VNFD1 received')

                    self.assertTrue(
                        result['sonfsmservice1function1dumb1']['status'] ==
                        'On-boarded',
                        msg='error in onbording sonssmservice1dumb1')

                    self.assertTrue(
                        result['sonfsmservice1function1dumb1']['error'] ==
                        'None',
                        msg='error in onbording sonfsmservice1function1dumb1')

                    self.event1 = True
                else:
                    self.assertTrue(
                        list(result.keys()) == [
                            'sonfsmservice1function1monitoring1',
                            'sonfsmservice1firewallconfiguration1'
                        ] or list(result.keys()) == [
                            'sonfsmservice1firewallconfiguration1',
                            'sonfsmservice1function1monitoring1'
                        ],
                        msg='not all FSMs results in VNFD2 received')

                    self.assertTrue(
                        result['sonfsmservice1function1monitoring1']['status']
                        == 'On-boarded',
                        msg='error in onbording sonssmservice1dumb1')

                    self.assertTrue(
                        result['sonfsmservice1function1monitoring1']['error']
                        == 'None',
                        msg=
                        'error in onbording sonfsmservice1function1monitoring1'
                    )

                    self.assertTrue(
                        result['sonfsmservice1firewallconfiguration1']
                        ['status'] == 'On-boarded',
                        msg='error in onbording sonssmservice1dumb1')

                    self.assertTrue(
                        result['sonfsmservice1firewallconfiguration1']['error']
                        == 'None',
                        msg=
                        'error in onbording sonfsmservice1firewallconfiguration1'
                    )

                    self.event2 = True

                if self.event1 and self.event2 == True:
                    self.fsm_eventFinished()

        self.manoconn.subscribe(on_ssm_onboarding_result,
                                'specific.manager.registry.ssm.on-board')
        self.manoconn.subscribe(on_fsm_onboarding_result,
                                'specific.manager.registry.fsm.on-board')

        onboaring_proc = Process(target=fakeslm_onboarding)
        onboaring_proc.daemon = True

        onboaring_proc.start()

        self.waitForSSMEvent(timeout=70,
                             msg='SSM Onboarding request not received.')
        self.waitForFSMEvent(timeout=70,
                             msg='FSM Onboarding request not received.')

        self.wait_for_fsm_event.clear()
        self.wait_for_ssm_event.clear()

        onboaring_proc.terminate()
        del onboaring_proc

    def test_2_SMR_instantiation(self):

        self.event1 = False
        self.event2 = False

        def on_ssm_instantiation_result(ch, method, properties, message):

            if properties.app_id == 'son-plugin.SpecificManagerRegistry':
                result = yaml.load(message)
                self.assertTrue(
                    list(result.keys())
                    == ['sonssmservice1dumb1', 'sonssmservice1placement1']
                    or list(result.keys())
                    == ['sonssmservice1placement1', 'sonssmservice1dumb1'],
                    msg='not all SSMs results received')

                self.assertTrue(
                    result['sonssmservice1dumb1']['status'] == 'Instantiated',
                    msg='error in instantiation sonssmservice1dumb1')

                self.assertTrue(
                    result['sonssmservice1dumb1']['error'] == 'None',
                    msg='error in instantiation sonssmservice1dumb1')

                self.assertTrue(
                    result['sonssmservice1placement1']['status'] ==
                    'Instantiated',
                    msg='error in instantiation sonssmservice1placement1')

                self.assertTrue(
                    result['sonssmservice1placement1']['error'] == 'None',
                    msg='error in instantiation sonssmservice1placement1')

                self.ssm_eventFinished()

        def on_fsm_instantiation_result(ch, method, properties, message):

            if properties.app_id == 'son-plugin.SpecificManagerRegistry':

                result = yaml.load(message)
                if list(result.keys()) == ['sonfsmservice1function1dumb1']:

                    self.assertTrue(
                        list(
                            result.keys()) == ['sonfsmservice1function1dumb1'],
                        msg=
                        'not all FSMs instantiation results in VNFD1 received')

                    self.assertTrue(
                        result['sonfsmservice1function1dumb1']['status'] ==
                        'Instantiated',
                        msg=
                        'error in instantiation sonfsmservice1function1dumb1')

                    self.assertTrue(
                        result['sonfsmservice1function1dumb1']['error'] ==
                        'None',
                        msg=
                        'error in instantiation sonfsmservice1function1dumb1')

                    self.event1 = True
                else:
                    self.assertTrue(
                        list(result.keys()) == [
                            'sonfsmservice1function1monitoring1',
                            'sonfsmservice1firewallconfiguration1'
                        ] or list(result.keys()) == [
                            'sonfsmservice1firewallconfiguration1',
                            'sonfsmservice1function1monitoring1'
                        ],
                        msg=
                        'not all FSMs instantiation results in VNFD2 received')

                    self.assertTrue(
                        result['sonfsmservice1function1monitoring1']['status']
                        == 'Instantiated',
                        msg=
                        'error in instantiation sonfsmservice1function1monitoring1'
                    )

                    self.assertTrue(
                        result['sonfsmservice1function1monitoring1']['error']
                        == 'None',
                        msg=
                        'error in instantiation sonfsmservice1function1monitoring1'
                    )

                    self.assertTrue(
                        result['sonfsmservice1firewallconfiguration1']
                        ['status'] == 'Instantiated',
                        msg=
                        'error in instantiation sonfsmservice1firewallconfiguration1'
                    )

                    self.assertTrue(
                        result['sonfsmservice1firewallconfiguration1']['error']
                        == 'None',
                        msg=
                        'error in instantiation sonfsmservice1firewallconfiguration1'
                    )

                    self.event2 = True

                if self.event1 and self.event2:
                    self.fsm_eventFinished()

        self.manoconn.subscribe(on_ssm_instantiation_result,
                                'specific.manager.registry.ssm.instantiate')
        self.manoconn.subscribe(on_fsm_instantiation_result,
                                'specific.manager.registry.fsm.instantiate')

        instantiation_proc = Process(target=fakeslm_instantiation)
        instantiation_proc.daemon = True

        instantiation_proc.start()

        self.waitForSSMEvent(timeout=70,
                             msg='SSM instantiation request not received.')
        self.waitForFSMEvent(timeout=70,
                             msg='FSM instantiation request not received.')

        self.wait_for_ssm_event.clear()
        self.wait_for_fsm_event.clear()

        instantiation_proc.terminate()
        del instantiation_proc

    def test_3_SMR_update(self):
        def on_ssm_updating_result(ch, method, properties, message):

            if properties.app_id == 'son-plugin.SpecificManagerRegistry':
                result = yaml.load(message)
                self.assertTrue(list(result.keys()) == ['sonssmservice1dumb1'],
                                msg='not all SSMs results received')

                self.assertTrue(
                    result['sonssmservice1dumb1']['status'] == 'Updated',
                    msg='error in updating status filed sonssmservice1dumb1')

                self.assertTrue(
                    result['sonssmservice1dumb1']['error'] == 'None',
                    msg='error in updating error filed sonssmservice1dumb1')

                self.ssm_eventFinished()

        def on_fsm_updating_result(ch, method, properties, message):

            if properties.app_id == 'son-plugin.SpecificManagerRegistry':

                result = yaml.load(message)
                self.assertTrue(
                    list(result.keys()) == [
                        'sonfsmservice1function1updateddumb1'
                    ],
                    msg='not all FSMs updating results in VNFD2 received')

                self.assertTrue(
                    result['sonfsmservice1function1updateddumb1']['status'] ==
                    'Updated',
                    msg='error in updating sonfsmservice1function1monitoring1')

                self.assertTrue(
                    result['sonfsmservice1function1updateddumb1']['error'] ==
                    'None',
                    msg='error in updating sonfsmservice1function1monitoring1')

                self.fsm_eventFinished()

        self.manoconn.subscribe(on_ssm_updating_result,
                                'specific.manager.registry.ssm.update')
        self.manoconn.subscribe(on_fsm_updating_result,
                                'specific.manager.registry.fsm.update')

        updating_proc = Process(target=fakeslm_updating)
        updating_proc.daemon = True
        updating_proc.start()

        self.waitForSSMEvent(timeout=70,
                             msg='SSM updating request not received.')
        self.waitForFSMEvent(timeout=70,
                             msg='FSM updating request not received.')

        self.wait_for_fsm_event.clear()
        self.wait_for_ssm_event.clear()

        updating_proc.terminate()
        del updating_proc

    def test_4_SMR_terminate(self):

        self.event1 = False
        self.event2 = False

        def on_ssm_termination_result(ch, method, properties, message):

            if properties.app_id == 'son-plugin.SpecificManagerRegistry':
                result = yaml.load(message)
                self.assertTrue(
                    list(result.keys())
                    == ['sonssmservice1dumb1', 'sonssmservice1placement1']
                    or ['sonssmservice1placement1', 'sonssmservice1dumb1'],
                    msg='not all SSMs results received')

                self.assertTrue(
                    result['sonssmservice1dumb1']['status'] == 'Terminated',
                    msg='error in termination status field sonssmservice1dumb1'
                )

                self.assertTrue(
                    result['sonssmservice1dumb1']['error'] == 'None',
                    msg='error in termination error field sonssmservice1dumb1')

                self.assertTrue(
                    result['sonssmservice1placement1']['status'] ==
                    'Terminated',
                    msg=
                    'error in termination status field sonssmservice1placement1'
                )

                self.assertTrue(
                    result['sonssmservice1placement1']['error'] == 'None',
                    msg=
                    'error in termination error field sonssmservice1placement1'
                )

                self.ssm_eventFinished()

        def on_fsm_termination_result(ch, method, properties, message):

            if properties.app_id == 'son-plugin.SpecificManagerRegistry':

                result = yaml.load(message)

                if list(result.keys()) == ['sonfsmservice1function1dumb1']:

                    self.assertTrue(
                        result['sonfsmservice1function1dumb1']['status'] ==
                        'Terminated',
                        msg=
                        'error in termination status field sonfsmservice1function1dumb1'
                    )

                    self.assertTrue(
                        result['sonfsmservice1function1dumb1']['error'] ==
                        'None',
                        msg=
                        'error in termination error field sonfsmservice1function1dumb1'
                    )

                    self.event1 = True

                else:
                    self.assertTrue(
                        list(result.keys()) == [
                            'sonfsmservice1function1monitoring1',
                            'sonfsmservice1function1updateddumb1'
                        ] or list(result.keys()) == [
                            'sonfsmservice1function1updateddumb1',
                            'sonfsmservice1function1monitoring1'
                        ],
                        msg=
                        'not all FSMs Termination results in vnfdt2 received')

                    self.assertTrue(
                        result['sonfsmservice1function1monitoring1']['status']
                        == 'Terminated',
                        msg=
                        'error in termination status field sonfsmservice1function1monitoring1'
                    )

                    self.assertTrue(
                        result['sonfsmservice1function1monitoring1']['error']
                        == 'None',
                        msg=
                        'error in termination error field sonfsmservice1function1monitoring1'
                    )

                    self.assertTrue(
                        result['sonfsmservice1function1updateddumb1']['status']
                        == 'Terminated',
                        msg=
                        'error in termination status field sonfsmservice1function1updateddumb1'
                    )

                    self.assertTrue(
                        result['sonfsmservice1function1updateddumb1']['error']
                        == 'None',
                        msg=
                        'error in termination error field sonfsmservice1function1updateddumb1'
                    )

                    self.event2 = True

                self.fsm_eventFinished()

            if self.event1 and self.event2:
                self.fsm_eventFinished()

        self.manoconn.subscribe(on_ssm_termination_result,
                                'specific.manager.registry.ssm.terminate')
        self.manoconn.subscribe(on_fsm_termination_result,
                                'specific.manager.registry.fsm.terminate')

        termination_proc = Process(target=fakeslm_termination)
        termination_proc.daemon = True
        termination_proc.start()

        self.waitForSSMEvent(timeout=70,
                             msg='SSM termination request not received.')
        self.waitForFSMEvent(timeout=70,
                             msg='FSM termination request not received.')

        self.wait_for_fsm_event.clear()
        self.wait_for_ssm_event.clear()

        termination_proc.terminate()
        del termination_proc
コード例 #15
0
class TestPluginManagerBase(unittest.TestCase):
    """
    Commen functionalities used my many test cases
    """

    pm_proc = None

    @classmethod
    def setUpClass(cls):
        # start the plugin manger in another process so that we can connect to it using its broker interface
        cls.pm_proc = Process(target=SonPluginManager)
        cls.pm_proc.daemon = True
        cls.pm_proc.start()
        time.sleep(1)  # give the plugin manager some time to start

    @classmethod
    def tearDownClass(cls):
        if cls.pm_proc is not None:
            cls.pm_proc.terminate()
            del cls.pm_proc

    def setUp(self):
        # initialize messaging subsystem
        self.m = ManoBrokerRequestResponseConnection("pm-client" + self.id())
        self.wait_for_reply = Event()
        self.plugin_uuid = None

    def tearDown(self):
        self.m.stop_connection()

    def waitForMessage(self, timeout=5):
        self.wait_for_reply.clear()
        if not self.wait_for_reply.wait(timeout):
            raise Exception("Timeout in wait for reply message.")

    def messageReceived(self):
        self.wait_for_reply.set()

    def register(self):
        """
        Helper: We need this in many tests.
        :return:
        """
        # do the registration call
        response = self.m.call_sync(
            "platform.management.plugin.register",
            {
                "name": "test-plugin",
                "version": "v0.01",
                "description": "description"
            },
        )

        assert response is not None
        msg = response.payload
        assert msg["status"] == "OK"
        assert len(msg["uuid"]) > 0
        assert msg["error"] is None
        # set internal state variables
        self.plugin_uuid = msg["uuid"]

    def deregister(self):
        """
        Helper: We need this in many tests.
        :return:
        """
        assert self.plugin_uuid is not None

        response = self.m.call_sync("platform.management.plugin.deregister",
                                    {"uuid": self.plugin_uuid})

        assert response is not None
        assert {"status": "OK"} == response.payload
コード例 #16
0
 def setUp(self):
     # initialize messaging subsystem
     self.m = ManoBrokerRequestResponseConnection("pm-client" + self.id())
     self.wait_for_reply = Event()
     self.plugin_uuid = None
コード例 #17
0
class TestPluginManagerBase(unittest.TestCase):
    """
    Commen functionalities used my many test cases
    """
    pm_proc = None

    @classmethod
    def setUpClass(cls):
        # start the plugin manger in another process so that we can connect to it using its broker interface
        cls.pm_proc = Process(target=SonPluginManager)
        cls.pm_proc.daemon = True
        cls.pm_proc.start()
        time.sleep(1)  # give the plugin manager some time to start

    @classmethod
    def tearDownClass(cls):
        if cls.pm_proc is not None:
            cls.pm_proc.terminate()
            del cls.pm_proc

    def setUp(self):
        # initialize messaging subsystem
        self.m = ManoBrokerRequestResponseConnection("pm-client" + self.id())
        self.wait_for_reply = threading.Event()
        self.plugin_uuid = None

    def tearDown(self):
        self.m.stop_connection()
        self.m.stop_threads()
        del self.m

    def waitForMessage(self, timeout=5):
        self.wait_for_reply.clear()
        if not self.wait_for_reply.wait(timeout):
            raise Exception("Timeout in wait for reply message.")

    def messageReceived(self):
        self.wait_for_reply.set()

    def register(self):
        """
        Helper: We need this in many tests.
        :return:
        """
        def on_register_reply(ch, method, properties, message):
            msg = json.loads(str(message))
            assert (msg.get("status") == "OK")
            assert (len(msg.get("uuid")) > 0)
            assert (msg.get("error") is None)
            # set internal state variables
            self.plugin_uuid = msg.get("uuid")
            # stop waiting
            self.messageReceived()

        # create register request message
        msg = dict(name="test-plugin",
                   version="v0.01",
                   description="description")

        # do the registration call
        self.m.call_async(on_register_reply,
                          "platform.management.plugin.register",
                          json.dumps(msg))

        # make our test synchronous: wait
        self.waitForMessage()

    def deregister(self):
        """
        Helper: We need this in many tests.
        :return:
        """
        assert (self.plugin_uuid is not None)

        def on_deregister_reply(ch, method, properties, message):
            msg = json.loads(str(message))
            assert (msg.get("status") == "OK")
            # stop waiting
            self.messageReceived()

        # create register request message
        msg = dict(uuid=self.plugin_uuid)

        # do the registration call
        self.m.call_async(on_deregister_reply,
                          "platform.management.plugin.deregister",
                          json.dumps(msg))

        # make our test synchronous: wait
        self.waitForMessage()