Beispiel #1
0
    def test_switch_vlan_pool_options(self):
        """Test switch with the example from kytos.conf."""
        dpid = "00:00:00:00:00:00:00:01"
        vlan_pool_json = '{"00:00:00:00:00:00:00:01": {"1": [[1, 2], [5, 10]], \
            "4": [[3, 4]]}}'

        switch = Switch(dpid)
        self.controller.switches[dpid] = switch
        self.options.vlan_pool = vlan_pool_json
        switch.connection = Mock()
        switch.connection.protocol.version = 0x04
        self.controller.get_switch_or_create(dpid, switch.connection)

        port_id = 1
        intf = self.controller.switches[dpid].interfaces[port_id]
        tag_values = [tag.value for tag in intf.available_tags]
        self.assertEqual(tag_values, [1, 5, 6, 7, 8, 9])

        port_id = 4
        intf = self.controller.switches[dpid].interfaces[port_id]
        tag_values = [tag.value for tag in intf.available_tags]
        self.assertEqual(tag_values, [3])

        # this port number doesn't exist yet.
        port_7 = 7
        intf = Interface("test", port_7, switch)
        # no attr filters, so should associate as it is
        self.controller.switches[dpid].update_interface(intf)
        intf_obj = self.controller.switches[dpid].interfaces[port_7]
        self.assertEqual(intf_obj, intf)
        # assert default vlan_pool range (1, 4096)
        tag_values = [tag.value for tag in intf_obj.available_tags]
        self.assertEqual(tag_values, list(range(1, 4096)))
Beispiel #2
0
 def _get_v0x04_iface(*args, **kwargs):
     """Create a v0x04 interface object with optional extra arguments."""
     switch = Switch('dpid')
     switch.connection = Mock()
     switch.connection.protocol.version = 0x04
     switch.update_lastseen()
     return Interface('name', 42, switch, *args, **kwargs)
Beispiel #3
0
    def get_switch_or_create(self, dpid, connection):
        """Return switch or create it if necessary.

        Args:
            dpid (|DPID|): dpid object used to identify a switch.
            connection (:class:`~kytos.core.connection.Connection`):
                connection used by switch. If a switch has a connection that
                will be updated.

        Returns:
            :class:`~kytos.core.switch.Switch`: new or existent switch.

        """
        self.create_or_update_connection(connection)
        switch = self.get_switch_by_dpid(dpid)
        event = None

        if switch is None:
            switch = Switch(dpid=dpid)
            self.add_new_switch(switch)

            event = KytosEvent(name='kytos/core.switch.new',
                               content={'switch': switch})

        old_connection = switch.connection
        switch.update_connection(connection)

        if old_connection is not connection:
            self.remove_connection(old_connection)

        if event:
            self.buffers.app.put(event)

        return switch
Beispiel #4
0
def get_link_mocked(**kwargs):
    """Return a link mocked.

    Args:
        link_dict: Python dict returned after call link.as_dict()
    """
    switch_a = kwargs.get('switch_a', Switch('00:00:00:00:00:01'))
    switch_b = kwargs.get('switch_b', Switch('00:00:00:00:00:02'))

    endpoint_a = Interface(kwargs.get('endpoint_a_name', 'eth0'),
                           kwargs.get('endpoint_a_port', 1), switch_a)
    endpoint_b = Interface(kwargs.get('endpoint_b_name', 'eth1'),
                           kwargs.get('endpoint_b_port', 2), switch_b)
    link = Mock(spec=Link, endpoint_a=endpoint_a, endpoint_b=endpoint_b)
    link.as_dict.return_value = kwargs.get('link_dict',
                                           {'id': kwargs.get('link_id', 1)})

    link.status = kwargs.get('status', EntityStatus.DOWN)

    metadata = kwargs.get("metadata", {})

    def side_effect(key):
        """Mock Link get metadata."""
        return Mock(value=metadata.get(key))

    link.get_metadata = Mock(side_effect=side_effect)

    return link
Beispiel #5
0
 def test_switch_initial_lastseen(self):
     """Test lastseen attribute initialization."""
     connection = MagicMock()
     connection.protocol.version = 0x04
     switch = Switch('00:00:00:00:00:00:00:01', connection)
     self.assertEqual(switch.is_active(), False)
     self.assertEqual(switch.lastseen,
                      datetime(1, 1, 1, 0, 0, 0, 0, timezone.utc))
Beispiel #6
0
 def create_switch():
     """Create a new switch."""
     connection = MagicMock()
     connection.address = 'addr'
     connection.port = 'port'
     connection.protocol.version = 0x04
     switch = Switch('00:00:00:00:00:00:00:01', connection)
     switch._enabled = True
     return switch
Beispiel #7
0
def get_switch_mock(of_version,
                    connection_state=ConnectionState.NEW,
                    dpid="00:00:00:00:00:00:00:01"):
    """Return a switch mock."""
    switch = Switch(dpid)
    address = Mock()
    port = Mock()
    socket = Mock()
    switch.connection = Connection(address, port, socket)
    switch.connection.protocol.version = of_version
    switch.connection.state = connection_state
    return switch
Beispiel #8
0
    def _get_v0x04_ifaces(*args, **kwargs):
        """Create a pair of v0x04 interfaces with optional extra arguments."""
        switch1 = Switch('dpid1')
        switch1.connection = Mock()
        switch1.connection.protocol.version = 0x04
        iface1 = Interface('interface1', 41, switch1, *args, **kwargs)

        switch2 = Switch('dpid2')
        switch2.connection = Mock()
        switch2.connection.protocol.version = 0x04
        iface2 = Interface('interface2', 42, switch2, *args, **kwargs)

        return iface1, iface2
Beispiel #9
0
 def test_flow_mod(self):
     """Convert a dict to flow and vice-versa."""
     switch = Switch('dpid')
     expected = {
         'id': '1ce5d08a46496fcb856cb603a5bfa00f',
         'switch': switch.id,
         'table_id': 1,
         'match': {
             'dl_src': '11:22:33:44:55:66'
         },
         'priority': 2,
         'idle_timeout': 3,
         'hard_timeout': 4,
         'cookie': 5,
         'actions': [{
             'action_type': 'set_vlan',
             'vlan_id': 6
         }],
         'stats': {}
     }
     for flow_class in Flow01, Flow04:
         with self.subTest(flow_class=flow_class):
             flow = flow_class.from_dict(expected, switch)
             actual = flow.as_dict()
             self.assertDictEqual(expected, actual)
Beispiel #10
0
def get_topology_with_metadata():
    """Create a topology with metadata."""
    switches = {}
    interfaces = {}
    links = {}

    links_to_interfaces, links_to_metadata, switches_to_interface_counts = topology_setting(
    )

    for switch in switches_to_interface_counts:
        switches[switch] = Switch(switch)

    for key, value in switches_to_interface_counts.items():
        switches[key].interfaces = {}
        for i in range(1, value + 1):
            str1 = "{}:{}".format(switches[key].dpid, i)
            interface = Interface(str1, i, switches[key])
            switches[key].update_interface(interface)
            interfaces[interface.id] = interface

    i = 0
    for interfaces_str in links_to_interfaces:
        interface_a = interfaces[interfaces_str[0]]
        interface_b = interfaces[interfaces_str[1]]
        links[str(i)] = Link(interface_a, interface_b)
        links[str(i)].metadata = links_to_metadata[i]
        i += 1

    topology = MagicMock()
    topology.links = links
    topology.switches = switches
    return topology
Beispiel #11
0
    def test_remove_current_flows(self, send_flow_mods_mocked):
        """Test remove current flows."""
        uni_a = get_uni_mocked(interface_port=2, tag_value=82,
                               switch_id="switch_uni_a", is_valid=True)
        uni_z = get_uni_mocked(interface_port=3, tag_value=83,
                               switch_id="switch_uni_z", is_valid=True)

        switch_a = Switch('00:00:00:00:00:01')
        switch_b = Switch('00:00:00:00:00:02')
        switch_c = Switch('00:00:00:00:00:03')

        attributes = {
            "controller": get_controller_mock(),
            "name": "custom_name",
            "uni_a": uni_a,
            "uni_z": uni_z,
            "active": True,
            "enabled": True,
            "primary_links": [
                get_link_mocked(switch_a=switch_a,
                                switch_b=switch_b,
                                endpoint_a_port=9, endpoint_b_port=10,
                                metadata={"s_vlan": 5}),
                get_link_mocked(switch_a=switch_b,
                                switch_b=switch_c,
                                endpoint_a_port=11, endpoint_b_port=12,
                                metadata={"s_vlan": 6})
            ]
        }

        evc = EVC(**attributes)

        # storehouse initialization mock
        evc._storehouse.box = Mock()  # pylint: disable=protected-access
        evc._storehouse.box.data = {}  # pylint: disable=protected-access

        evc.current_path = evc.primary_links
        evc.remove_current_flows()

        self.assertEqual(send_flow_mods_mocked.call_count, 5)
        self.assertFalse(evc.is_active())
        flows = [{'cookie': evc.get_cookie(),
                 'cookie_mask': 18446744073709551615}]
        switch_1 = evc.primary_links[0].endpoint_a.switch
        switch_2 = evc.primary_links[0].endpoint_b.switch
        send_flow_mods_mocked.assert_any_call(switch_1, flows, 'delete')
        send_flow_mods_mocked.assert_any_call(switch_2, flows, 'delete')
Beispiel #12
0
    def get_switch_or_create(self, dpid, connection):
        """Return switch or create it if necessary.

        Args:
            dpid (|DPID|): dpid object used to identify a switch.
            connection (:class:`~kytos.core.connection.Connection`):
                connection used by switch. If a switch has a connection that
                will be updated.

        Returns:
            :class:`~kytos.core.switch.Switch`: new or existent switch.

        """
        self.create_or_update_connection(connection)
        switch = self.get_switch_by_dpid(dpid)
        event_name = 'kytos/core.switch.'

        if switch is None:
            switch = Switch(dpid=dpid)
            self.add_new_switch(switch)
            event_name += 'new'
        else:
            event_name += 'reconnected'

        self.set_switch_options(dpid=dpid)
        event = KytosEvent(name=event_name, content={'switch': switch})

        old_connection = switch.connection
        switch.update_connection(connection)

        if old_connection is not connection:
            self.remove_connection(old_connection)

        self.buffers.app.put(event)

        return switch
Beispiel #13
0
def get_link_mocked(**kwargs):
    """Return a link mocked.

    Args:
        link_dict: Python dict returned after call link.as_dict()
    """
    switch_a = kwargs.get("switch_a", Switch("00:00:00:00:00:01"))
    switch_b = kwargs.get("switch_b", Switch("00:00:00:00:00:02"))

    endpoint_a = Interface(
        kwargs.get("endpoint_a_name", "eth0"),
        kwargs.get("endpoint_a_port", 1),
        switch_a,
    )
    endpoint_b = Interface(
        kwargs.get("endpoint_b_name", "eth1"),
        kwargs.get("endpoint_b_port", 2),
        switch_b,
    )
    link = Mock(spec=Link, endpoint_a=endpoint_a, endpoint_b=endpoint_b)
    link.endpoint_a.link = link
    link.endpoint_b.link = link
    link.as_dict.return_value = kwargs.get("link_dict",
                                           {"id": kwargs.get("link_id", 1)})

    link.status = kwargs.get("status", EntityStatus.DOWN)

    metadata = kwargs.get("metadata", {})

    def side_effect(key):
        """Mock Link get metadata."""
        return Mock(value=metadata.get(key))

    link.get_metadata = Mock(side_effect=side_effect)

    return link
Beispiel #14
0
    def _get_v0x04_ifaces(*args, **kwargs):
        """Create a pair of v0x04 interfaces with optional extra arguments."""
        switch1 = Switch('dpid1')
        switch1.connection = Mock()
        switch1.connection.protocol.version = 0x04
        iface1 = Interface('interface1', 41, switch1, *args, **kwargs)

        switch2 = Switch('dpid2')
        switch2.connection = Mock()
        switch2.connection.protocol.version = 0x04
        iface2 = Interface('interface2', 42, switch2, *args, **kwargs)

        return iface1, iface2
Beispiel #15
0
class TestFlow(unittest.TestCase):
    """Test OF flow abstraction."""

    SWITCH = Switch('dpid')
    EXPECTED = {
        'id': '1ce5d08a46496fcb856cb603a5bfa00f',
        'switch': SWITCH.id,
        'table_id': 1,
        'match': {
            'dl_src': '11:22:33:44:55:66'
        },
        'priority': 2,
        'idle_timeout': 3,
        'hard_timeout': 4,
        'cookie': 5,
        'actions': [{
            'action_type': 'set_vlan',
            'vlan_id': 6
        }],
        'stats': {}
    }

    def test_flow_mod(self):
        """Convert a dict to flow and vice-versa."""
        for flow_class in Flow01, Flow04:
            with self.subTest(flow_class=flow_class):
                flow = flow_class.from_dict(self.EXPECTED, self.SWITCH)
                actual = flow.as_dict()
                self.assertDictEqual(self.EXPECTED, actual)

    def test_of_flow_mod(self):
        """Test convertion from Flow to OFFlow."""
        flow_mod_01 = Flow01.from_dict(self.EXPECTED, self.SWITCH)
        flow_mod_04 = Flow04.from_dict(self.EXPECTED, self.SWITCH)
        of_flow_mod_01 = flow_mod_01.as_of_add_flow_mod()
        of_flow_mod_04 = flow_mod_04.as_of_delete_flow_mod()
        self.assertIsInstance(of_flow_mod_01, OFFlow01)
        self.assertIsInstance(of_flow_mod_04, OFFlow04)
Beispiel #16
0
 def test_repr(self):
     """Test repr() output."""
     switch = Switch('some-dpid')
     self.assertEqual(repr(switch), "Switch('some-dpid')")
Beispiel #17
0
 def setUp(self):
     """Create interface object."""
     switch = Switch('dpid')
     self.iface = Interface('name', 42, switch)
Beispiel #18
0
def get_switch_mock(dpid="00:00:00:00:00:00:00:01"):
    """Return a switch mock."""
    return Switch(dpid)
Beispiel #19
0
 def create_switch(name, switches):
     """Add a new switch to the list of switches"""
     switches[name] = Switch(name)
Beispiel #20
0
 def createSwitch(name,switches):
     switches[name] = Switch(name)
     print("Creating Switch: ", name)
Beispiel #21
0
 def _get_v0x04_iface(*args, **kwargs):
     """Create a v0x04 interface object with optional extra arguments."""
     switch = Switch('dpid')
     switch.connection = Mock()
     switch.connection.protocol.version = 0x04
     return Interface('name', 42, switch, *args, **kwargs)
Beispiel #22
0
 def get_switch_by_dpid(*args, **kwargs):
     return Switch(args[0])
Beispiel #23
0
 def createSwitch(name,switches):
     switches[name] = Switch(name)