Beispiel #1
0
    def message_in(*args, **kwargs):
        """
        Generic message_in handle function
        Triggers corresponding event
        :param kwargs:
        :return:
        """
        packet = kwargs.get('packet')
        switch = kwargs.get('switch')
        try:
            pkt = Ether(packet.packet.payload)
            try:
                Configuration.get('system_done')
            except ConfigurationNotFound:
                return
            if pkt.type == 0xEE00: # its an port down packet
		Log.info("Port:", pkt[PortDown].port_num, "down", "on ingress", pkt[PortDown].pad1, "on pipe")
                Event.trigger("port_down", pkt=pkt)


            if pkt.type == 0xDD00:  # its an topology packet
                Event.trigger("topology_packet_in", packet=pkt, switch=switch)

            if pkt.type == 0x800 and pkt[IP].proto == 2:  # its an igmp packet
                igmp = pkt.payload
                pkt = proto.connection_pb2.GroupPacket(type=int(igmp.type), mc_address=str(igmp.gaddr), src_ip=str(igmp.src), switch=Configuration.get('name'))
                Event.trigger("igmp_packet_to_controller", pkt=pkt)
                Log.debug("Send igmp packet to controller")

        except Exception as e:  # it's not an ethernet frame
            pass
    def Hello(self, request, context):
        Event.trigger('global_connection')
        GlobalConnection.global_connection = GlobalConnection(ip=request.ip, port=request.port)

        device = TopologyManager.get_device(Configuration.get('name'))

        return proto.connection_pb2.SwitchInfo(name=Configuration.get('name'),
                                               ip=device.get_ip(),
                                               mac=device.get_mac(),
                                               bfr_id=device.get_bfr_id(0))
    def updatePorts(self, pkt=None):
        port = pkt[PortDown].port_num
        device = TopologyManager.get_device(Configuration.get('name'))
        device.remove_port(port=port)
        Event.trigger("topology_change")

        Event.trigger("port_msg_to_controller",
                      info=proto.connection_pb2.PortInfo(
                          switch=Configuration.get('name'),
                          port=port,
                          status=False))
Beispiel #4
0
def main():

    # without this line, no events would be fired, no topology discovered and no entries computed
    Event.activate()

    # base controller
    controller = BaseController(p4info_file_path=Configuration.get('p4info'), bmv2_path=Configuration.get('bmv2_json'),
                                prog_name=Configuration.get('prog_name'), bin_path=Configuration.get('bin_path'), cxt_json_path=Configuration.get('cxt_path'))


    # register event for new switch connections, this will add switches to device list
    Event.on('new_switch_connection', TopologyManager.add_device)

    # register events for static classes
    Event.on("packet_in", MessageInHandler.message_in)  # handles generic packet in
    Event.on("topology_to_controller", GlobalConnection.send_topology_packet)  # triggers the send routine to server
    Event.on("port_msg_to_controller", GlobalConnection.send_port_info) # triggers the send routine to server

    topology = TopologyController(controller)
    
    # Create instances of sub controller
    mac = MacController(controller)
    port = PortController(controller=controller)

    pd = PDSetup()

    # start connection procedure
    init_switches(controller=controller, topology_controller=topology, pd=pd)

    # start grpc server for connection to main controller
    grpc_server = GRPCServer(listen_port=Configuration.get('listen_port'))

    # set controller in local server for table entry
    LocalServer.controller = controller

    # start grpc server
    grpc_server.start()

    # start port monitor
    #threading.Thread(target=port.monitor_messages()).start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        pd.end()
        Log.info("Shutting down")
        os._exit(0)
Beispiel #5
0
    def update(self, *args, **kwargs):
        """
        Update bier tables, bift
        Is called on certain events
        :return:
        """

        if "port_update" in kwargs:
            try:
                d = Configuration.get('update')

                if "bier" not in d:
                    return

                if "sleep" in kwargs:
                    time.sleep(kwargs.get("sleep"))
            except ConfigurationNotFound:
                pass

        srcDevice = kwargs.get('src_device')

        for switch in self._baseController.get_connections():
            self.update_bier_forwarding_entries(switch=switch)

        Log.async_info("Updated BIER entries.")
    def handle_topology_answer(self, pkt=None):
        """
        Handle topology packet
        :param pkt: contains the topology packet
        :return:
        """

        # if the controller is not yet connected to all local controllers
        # don't handle topology packets
        if not Configuration.get('system_done'):
            return

        ip = pkt.ip.encode('utf-8')
        mac = pkt.mac.encode('utf-8')
        name = pkt.name.encode('utf-8')
        port = pkt.port
        switch = pkt.switch.encode('utf-8')

        if name.startswith('h'):  # it's a host
            TopologyManager.add_device(name=name,
                                       device=Host(name=name, ip=ip, mac=mac))
            TopologyManager.get_device(name=name).add_device_to_port(
                device=switch, port=1)

        Log.event("topology packet with identifier", name, "from switch",
                  switch, "on port", port, "with ip", ip)

        if TopologyManager.get_device(name=switch).add_device_to_port(
                device=name, port=int(port)):
            Event.trigger("topology_change",
                          src_device=switch,
                          dst_device=name,
                          port=int(port))
Beispiel #7
0
 def setPorts(self, data=None):
     for configuration in data[Configuration.get('name')]:
         p_id = self.pal.pal_port_front_panel_port_to_dev_port_get(0, configuration['port'], configuration['channel'])
         self.pal.pal_port_add(0, p_id, configuration['speed'], pal_fec_type_t.BF_FEC_TYP_NONE)
         self.pal.pal_port_an_set(0, p_id, 2)
         self.pal.pal_port_enable(0, p_id)
         
         if 'loopback' in configuration and configuration['loopback']:
             self.pal.pal_port_loopback_mode_set(0, p_id, 1)
             Log.debug("Set port", p_id, "to loopback")
Beispiel #8
0
def init_switches(controller=None, topology_controller=None, pd=None):
    """
    Connect to switches and set forwarding pipeline
    :param controller: base controller who handles connections
    :param topology_controller: topology controller, who will send topology packets
    :return:
    """
    controller.connect_and_arbitrate(grpc_port=Configuration.get('grpc_port'), device_id=Configuration.get('device_id'))
    controller.set_forwarding_pipeline_config()

    try:
        pd.setPorts(Configuration.get("ports"))
        pd.setFlood(Configuration.get("ports"))
        pd.setPortMonitor(Configuration.get("ports"))
        pd.configureTopologyPackets()
    except Exception as e:
        Log.error(e)

    Configuration.set('system_done', True)
Beispiel #9
0
    def AddEntry(self, request, context):
        """
        Add a table entry to the switch
        """

        if LocalServer.controller.add_entry(entry=request):
            if Configuration.get("name") == "s1":
                Log.log_to_file(round((time.time() * 1000) % 1000000),
                                request.table_name,
                                "\r\n",
                                file="logs/entry_info.txt")
            return proto.connection_pb2.Status(code=1, message="all good")
Beispiel #10
0
    def update_mac_entry(self):
        """
        Add mac rewriting rule for switch->dst_dev via port
        :param switch: switch where rule will be installed
        :param dst_dev: next_hop
        :param port: port which is used towards next_hop
        :return:
        """
        valid_entries = []

        device = TopologyManager.get_device(Configuration.get('name'))

        for device_name in device.get_device_to_port_mapping():
            dev = TopologyManager.get_device(device_name)
            port = device.get_device_to_port(device_name)
            Log.debug("Mac:", Configuration.get('name'), "->", device_name,
                      "via", port)

            entry = TableEntry(
                match_fields={"standard_metadata.egress_port": int(port)},
                action_name="egress.mac_c.set_mac",
                action_params={
                    "srcAddr": device.get_mac(),
                    "dstAddr": dev.get_mac()
                })

            TableEntryManager.handle_table_entry(
                manager=self.table_manager,
                table_name="egress.mac_c.adjust_mac",
                table_entry=entry)

            valid_entries.append(entry.match_fields)

        Log.debug("Installed Mac rewriting rule for",
                  Configuration.get('name'))

        # remove possible old entries
        self.table_manager.remove_invalid_entries(
            table_name="egress.mac_c.adjust_mac", valid_entries=valid_entries)
Beispiel #11
0
    def add_node(self, n):
        """
        Add node to graph
        :param n:
        :return:
        """
        self._graph.add_node(n)

        # if this node is a switch, add it to the switch graph
        for switch in Configuration.get("switches"):
            if switch["name"] == n:
                self._switch_graph.add_node(n)
                return
Beispiel #12
0
    def connect_and_arbitrate(self, grpc_port=0, device_id=0):
        """
        Connect and arbitrate to the switch
        :param grpc_port: grpc port of the p4 switch
        :param device_id: device id of the p4 switch
        :return:
        """

        i = Configuration.get('bfr_id')
        
        try:
            # add connection to switch
            self.__connection = self.__add_switch_connection(name='s{0}'.format(i),
                                                             address='127.0.0.1:{0}'.format(grpc_port),
                                                             device_id=device_id)

            # start packet in thread
            self.__connection.start_thread()

            if self.__connection.MasterArbitrationUpdate():
                base_mac = int('20:00:00:00:00:00'.translate(None, ":,-"), 16)
                real_mac = format(base_mac + i, 'x')
                mac = ":".join(real_mac[i:i + 2] for i in range(0, len(real_mac), 2))

                Configuration.set('name', 's{0}'.format(i).encode('utf-8'))

                Event.trigger("new_switch_connection", name='s{0}'.format(i),
                              device=Switch(name='s{0}'.format(i).encode('utf-8'), ip='20.0.{0}.0'.format(i).encode('utf-8'),
                                            mac=mac.encode('utf-8'), bfr_id=i))

                Log.info("Arbitration done. Connected to swtich")
                Event.trigger("arbitration_done")
            else:
                Log.error("Master arbitration failed")


        except Exception as e:
            Log.error(e)