Exemple #1
0
    def _hosts(self, req, **kwargs):
        body = None
        db = database(DB_PATH)

        if 'dpid' in kwargs:
            dpid = dpid_lib.str_to_dpid(kwargs['dpid'])
            rcd_dpid = selectDPID(dpid=dpid)
            host_of_dpid = []
            tmp = {'mac':'a', 'port':0,'ip':'a', 'slave':1}
            for x in rcd_dpid:
                tmp['mac'], tmp['port'], tmp['ip'], tmp['slave'] = x[0].encode('utf-8'), x[1], x[2].encode('utf-8'), x[3]
                hosts_of_dpid.append(dict(tmp))
            body = json.dumps(hosts_of_dpid)
        else:
            rcd_dev = db.selectDEVICE()    
            hosts = []
            tmp = {'user_id':0, 'dpid':0,'mac':'a', 'vlan':0, 'ip': 'a', 'port':0}
            #add gateway
            tmp['mac'] = db.selectGATEWAY()[0][0].encode('utf-8')
            tmp['ip'] = db.selectGATEWAY()[0][1].encode('utf-8')
            gw_dpid = db.getDPIDBySlave(mac_addr=tmp['mac'])
            if None != gw_dpid:
                tmp['port'] = db.findDPIDByX(gw_dpid,'MAC_ADDR',tmp['mac'])[0][0]
                tmp['dpid'] = dpid_lib.dpid_to_str(gw_dpid)
                hosts.append(dict(tmp))
            #add host
            for dev in rcd_dev:
                tmp['mac'], tmp['vlan'], tmp['user_id'] = dev[0].encode('utf-8'), dev[1], dev[2]
                dpid = db.getDPIDBySlave(mac_addr=tmp['mac'])
                tmp['dpid'] = dpid_lib.dpid_to_str(dpid)
                rcd_host = db.findDPIDByX(dpid,'MAC_ADDR',tmp['mac'])
                tmp['port'], tmp['ip'] = rcd_host[0][0], rcd_host[0][1].encode('utf-8')
                hosts.append(dict(tmp))
            body = json.dumps(hosts)
        return Response(content_type='application/json', body=body)
Exemple #2
0
 def __str__(self):
     return "EventTunnelPort<dpid %s port_no %d remote_dpid %s " "add_del %s>" % (
         dpid_lib.dpid_to_str(self.dpid),
         self.port_no,
         dpid_lib.dpid_to_str(self.remote_dpid),
         self.add_del,
     )
Exemple #3
0
    def __init__(self):
        super(OfTester, self).__init__()
        self._set_logger()

        self.target_dpid = self._convert_dpid(CONF['test-switch']['target'])
        self.tester_dpid = self._convert_dpid(CONF['test-switch']['tester'])
        self.logger.info('target_dpid=%s',
                         dpid_lib.dpid_to_str(self.target_dpid))
        self.logger.info('tester_dpid=%s',
                         dpid_lib.dpid_to_str(self.tester_dpid))
        test_dir = CONF['test-switch']['dir']
        self.logger.info('Test files directory = %s', test_dir)

        self.target_sw = OpenFlowSw(DummyDatapath(), self.logger)
        self.tester_sw = OpenFlowSw(DummyDatapath(), self.logger)
        self.state = STATE_INIT_FLOW
        self.sw_waiter = None
        self.waiter = None
        self.send_msg_xids = []
        self.rcv_msgs = []
        self.ingress_event = None
        self.ingress_threads = []
        self.thread_msg = None
        self.test_thread = hub.spawn(
            self._test_sequential_execute, test_dir)
Exemple #4
0
    def port_status_handler(self, ev):
        msg = ev.msg
        reason = msg.reason
        datapath = msg.datapath
        port = msg.desc
        ofproto = datapath.ofproto

        if reason == ofproto.OFPPR_ADD:
            LOG.debug('DPSET: A port was added.' +
                      '(datapath id = %s, port number = %s)',
                      dpid_to_str(datapath.id), port.port_no)
            self._port_added(datapath, port)
            self.send_event_to_observers(EventPortAdd(datapath, port))
        elif reason == ofproto.OFPPR_DELETE:
            LOG.debug('DPSET: A port was deleted.' +
                      '(datapath id = %s, port number = %s)',
                      dpid_to_str(datapath.id), port.port_no)
            self._port_deleted(datapath, port)
            self.send_event_to_observers(EventPortDelete(datapath, port))
        else:
            assert reason == ofproto.OFPPR_MODIFY
            LOG.debug('DPSET: A port was modified.' +
                      '(datapath id = %s, port number = %s)',
                      dpid_to_str(datapath.id), port.port_no)
            self.port_state[datapath.id].modify(port.port_no, port)
            self.send_event_to_observers(EventPortModify(datapath, port))
    def switch_desc_handler(self, ev):
        switch_str = ""
        stats = ev.msg.body

        dp_desc = stats.dp_desc
        hw_desc = stats.hw_desc
        mfr_desc = stats.mfr_desc
        serial_num = stats.serial_num
        sw_desc = stats.sw_desc


        switch_str = "\n\n==========================================\n"
        switch_str += " Switch Description: \n"
        switch_str += "==========================================\n"
        switch_str += "* Manufacturer description: \t" + mfr_desc + "\n" 
        switch_str += "* Hardware description: \t" + hw_desc + "\n"
        switch_str += "* Software description: \t" + sw_desc + "\n"
        switch_str += "* Serial number:         \t" + serial_num + "\n"
        switch_str += "* Datapath description: \t" + dp_desc + "\n"
        switch_str += "==========================================\n\n"

        # Save 
        fd = open("./results/switch_" + dpidlib.dpid_to_str(ev.msg.datapath.id) + "_v10_extra.txt", 'a+')
        fd.write(switch_str)
        fd.close()

        # Combined
        self.combined_str += (switch_str)

        # Last handle.. So save combined string
        fd = open("./results/switch_" + dpidlib.dpid_to_str(ev.msg.datapath.id) + "_v10_combined.txt", 'a+')
        fd.write(self.combined_str)
        fd.close()
Exemple #6
0
 def to_dict(self):
     return {'dpid': dpid_to_str(self.dp.id),
             'name': self.name,
             'neighbors': [dpid_to_str(switch.dp.id) for switch in self.neighbors],
             'ports': [port.to_dict() for (port_no, port) in self.ports.items()],
             'arp_table': self.get_arp_list(),
             'routing_table': self.get_routing_table()}
    def packet_in_handler(self, ev):
        self.logger.debug('packet_in_handler')
        msg = ev.msg
        datapath = msg.datapath
        ofproto = datapath.ofproto

        # TODO: subscribe only the designated datapath
        dpid = datapath.id
        if dpid != self.interface.dpid:
            self.logger.debug('packet_in_handler dpid %s %s',
                              dpid_lib.dpid_to_str(dpid),
                              dpid_lib.dpid_to_str(self.interface.dpid))
            return

        in_port = None
        for field in msg.match.fields:
            if field.header == ofproto.OXM_OF_IN_PORT:
                in_port = field.value
                break

        if in_port != self.interface.port_no:
            self.logger.debug('packet_in_handler in_port %s %s',
                              in_port, self.interface.port_no)
            return

        self._send_vrrp_packet_received(msg.data)
Exemple #8
0
    def _setup_data_fwd_flows(self, src_mac, dst_mac):
        """
        Given two MAC addresses, set up flows on their connected switches
        towards each other, so that they can forward packets between each other
        """
        (src_dpid, src_port) = (self.inception.
                                      mac_to_dpid_port[src_mac])
        (dst_dpid, dst_port) = (self.inception.
                                      mac_to_dpid_port[dst_mac])

        # If src_dpid == dst_dpid, no need to set up flows
        if src_dpid == dst_dpid:
            return

        src_ip = self.inception.dpid_to_ip[src_dpid]
        dst_ip = self.inception.dpid_to_ip[dst_dpid]
        src_fwd_port = self.inception.dpid_to_conns[src_dpid][dst_ip]
        dst_fwd_port = self.inception.dpid_to_conns[dst_dpid][src_ip]
        src_datapath = self.inception.dpset.get(src_dpid)
        dst_datapath = self.inception.dpset.get(dst_dpid)
        src_ofproto = src_datapath.ofproto
        dst_ofproto = dst_datapath.ofproto
        src_ofproto_parser = src_datapath.ofproto_parser
        dst_ofproto_parser = dst_datapath.ofproto_parser
        if (src_dpid, dst_mac) not in self.inception.unicast_rules:
            actions_fwd = [src_ofproto_parser.OFPActionOutput(src_fwd_port)]
            instructions_fwd = [src_datapath.ofproto_parser.
                                OFPInstructionActions(
                                src_ofproto.OFPIT_APPLY_ACTIONS, actions_fwd)]
            src_datapath.send_msg(src_ofproto_parser.OFPFlowMod(
                        datapath=src_datapath,
                        match=src_ofproto_parser.OFPMatch(eth_dst=dst_mac),
                        cookie=0, command=src_ofproto.OFPFC_ADD,
                        priority=priority.DATA_FWD,
                        flags=src_ofproto.OFPFF_SEND_FLOW_REM,
                        instructions=instructions_fwd
                        ))
            self.inception.unicast_rules.append((src_dpid, dst_mac))
            LOGGER.info("Setup forward flow on switch=%s"
                        "towards mac=%s", dpid_to_str(src_dpid), dst_mac)

        if (dst_dpid, src_mac) not in self.inception.unicast_rules:
            actions_dst = [dst_ofproto_parser.OFPActionOutput(dst_fwd_port)]
            instructions_dst = [dst_datapath.ofproto_parser.
                                OFPInstructionActions(
                                dst_ofproto.OFPIT_APPLY_ACTIONS, actions_dst)]
            dst_datapath.send_msg(dst_ofproto_parser.OFPFlowMod(
                        datapath=dst_datapath,
                        match=dst_ofproto_parser.OFPMatch(eth_dst=src_mac),
                        cookie=0, command=dst_ofproto.OFPFC_ADD,
                        priority=priority.DATA_FWD,
                        flags=dst_ofproto.OFPFF_SEND_FLOW_REM,
                        instructions=instructions_dst
                        ))
            self.inception.unicast_rules.append((dst_dpid, src_mac))
            LOGGER.info("Setup forward flow on switch=%s"
                        "towards mac=%s", dpid_to_str(dst_dpid), src_mac)
Exemple #9
0
    def _do_lacp(self, req_lacp, src, msg):
        """packet-in process when the received packet is LACP."""
        datapath = msg.datapath
        dpid = datapath.id
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser
        if ofproto.OFP_VERSION == ofproto_v1_0.OFP_VERSION:
            port = msg.in_port
        else:
            port = msg.match['in_port']

        self.logger.info("SW=%s PORT=%d LACP received.",
                         dpid_to_str(dpid), port)
        self.logger.debug(str(req_lacp))

        # when LACP arrived at disabled port, update the status of
        # the slave i/f to enabled, and send a event.
        if not self._get_slave_enabled(dpid, port):
            self.logger.info(
                "SW=%s PORT=%d the slave i/f has just been up.",
                dpid_to_str(dpid), port)
            self._set_slave_enabled(dpid, port, True)
            self.send_event_to_observers(
                EventSlaveStateChanged(datapath, port, True))

        # set the idle_timeout time using the actor state of the
        # received packet.
        if req_lacp.LACP_STATE_SHORT_TIMEOUT == \
           req_lacp.actor_state_timeout:
            idle_timeout = req_lacp.SHORT_TIMEOUT_TIME
        else:
            idle_timeout = req_lacp.LONG_TIMEOUT_TIME

        # when the timeout time has changed, update the timeout time of
        # the slave i/f and re-enter a flow entry for the packet from
        # the slave i/f with idle_timeout.
        if idle_timeout != self._get_slave_timeout(dpid, port):
            self.logger.info(
                "SW=%s PORT=%d the timeout time has changed.",
                dpid_to_str(dpid), port)
            self._set_slave_timeout(dpid, port, idle_timeout)
            func = self._add_flow.get(ofproto.OFP_VERSION)
            assert func
            func(src, port, idle_timeout, datapath)

        # create a response packet.
        res_pkt = self._create_response(datapath, port, req_lacp)

        # packet-out the response packet.
        out_port = ofproto.OFPP_IN_PORT
        actions = [parser.OFPActionOutput(out_port)]
        out = datapath.ofproto_parser.OFPPacketOut(
            datapath=datapath, buffer_id=ofproto.OFP_NO_BUFFER,
            data=res_pkt.data, in_port=port, actions=actions)
        datapath.send_msg(out)
Exemple #10
0
 def create_switch_to_switch_links(self):
     for link in self.links:
         src_port = link.src.port_no
         dst_port = link.dst.port_no
         src_dpid = format_dpid_str(dpid_to_str(link.src.dpid))
         dst_dpid = format_dpid_str(dpid_to_str(link.dst.dpid))
         src_port_id = src_dpid + str(src_port)
         dst_port_id = dst_dpid + str(dst_port)
         src_port_vertex  = self.get_unique_port_vertex(src_port_id)
         dst_port_vertex  = self.get_unique_port_vertex(dst_port_id)
         self.create_link_edge(src_port_vertex,dst_port_vertex)
Exemple #11
0
 def _get_bridge_name(self):
     """ get Bridge name of a given 'datapath_id' """
     command = ovs_vsctl.VSCtlCommand(
         'find',
         ('Bridge',
          'datapath_id=%s' % dpid_lib.dpid_to_str(self.datapath_id)))
     self.run_command([command])
     if not isinstance(command.result, list) or len(command.result) != 1:
         raise OVSBridgeNotFound(
             datapath_id=dpid_lib.dpid_to_str(self.datapath_id))
     return command.result[0].name
Exemple #12
0
 def _get_bridge_name(self):
     """ get Bridge name of a given 'datapath_id' """
     command = ovs_vsctl.VSCtlCommand(
         'find',
         ('Bridge',
          'datapath_id=%s' % dpid_lib.dpid_to_str(self.datapath_id)))
     self.run_command([command])
     result = command.result
     if len(result) == 0 or len(result) > 1:
         raise OVSBridgeNotFound(
             datapath_id=dpid_lib.dpid_to_str(self.datapath_id))
     return result[0].name
 def unregist_ofs(dp):
     if dp.id in FirewallController._OFS_LIST:
         del FirewallController._OFS_LIST[dp.id]
         dpid_str = dpid_lib.dpid_to_str(dp.id)
         try:
             http_request_test(dpid_str, 'leave')
         except:
             print "DrawBridge controller is not enabled"
         #http_request_test(dpid_str, 'leave')
         # again, make a POST request to the DrawBridge controller.
         FirewallController._LOGGER.info('dpid=%s: Leave firewall.',
                                         dpid_lib.dpid_to_str(dp.id))
    def table_features_handler(self, ev):

        feature_str = ""
        prop_str = ""

        ## Fields
        print ev.msg.datapath
        table_list = ev.msg.body
        for t in table_list:

            table_id = t.table_id
            name = t.name
            metadata_match = t.metadata_match
            metadata_write = t.metadata_write
            # config = t.config   ## Bitmap that is provided for backward compability in OF.
            max_entries = t.max_entries
            properties = t.properties

            #
            feature_str = "\n\n==========================================\n"
            feature_str += " Table Feature: " + str(table_id) + "\n"
            feature_str += "==========================================\n"

            feature_str += (
                "Table Id:             "
                + str(table_id)
                + "\n"
                + "Name:                 "
                + str(name)
                + "\n"
                + "Metadata_match:       "
                + str(hex(metadata_match))
                + "\n"
                + "Metadata_write:       "
                + str(hex(metadata_write))
                + "\n"
                + "Max entries:          "
                + str(max_entries)
                + "\n"
            )

            prop_str = self.property_parser(properties)

        # Save
        fd = open("./results/switch_" + dpidlib.dpid_to_str(ev.msg.datapath.id) + "_v13_table.txt", "a+")
        fd.write(feature_str + prop_str)
        fd.close()

        # Combined
        #        self.combined_str += (feature_str + prop_str)
        self.combined_str_map[dpidlib.dpid_to_str(ev.msg.datapath.id)] += feature_str + prop_str
    def port_stats_reply_handler(self, ev):
        dpid = dpidlib.dpid_to_str(ev.msg.datapath.id)

        if self.looped[dpid] is True:
            # Last handle.. So save combined string
            fd = open("./results/switch_" + dpidlib.dpid_to_str(ev.msg.datapath.id) + "_v13_combined.txt", "a+")
            fd.write(self.combined_str_map[dpidlib.dpid_to_str(ev.msg.datapath.id)])
            fd.close()
            return

        ports = []
        port_num_list = []
        for stat in ev.msg.body:
            ports.append(
                "port_no=%d "
                "rx_packets=%d tx_packets=%d "
                "rx_bytes=%d tx_bytes=%d "
                "rx_dropped=%d tx_dropped=%d "
                "rx_errors=%d tx_errors=%d "
                "rx_frame_err=%d rx_over_err=%d rx_crc_err=%d "
                "collisions=%d duration_sec=%d duration_nsec=%d"
                % (
                    stat.port_no,
                    stat.rx_packets,
                    stat.tx_packets,
                    stat.rx_bytes,
                    stat.tx_bytes,
                    stat.rx_dropped,
                    stat.tx_dropped,
                    stat.rx_errors,
                    stat.tx_errors,
                    stat.rx_frame_err,
                    stat.rx_over_err,
                    stat.rx_crc_err,
                    stat.collisions,
                    stat.duration_sec,
                    stat.duration_nsec,
                )
            )
            # 	    print stat.port_no
            port_num_list.append(stat.port_no)

        # Add to Overview
        fd = open("./results/switch_" + dpid + "_v13_overview.txt", "a")
        fd.write("\n\n" + "Port number list (shown to controller): " + str(port_num_list) + "\n")
        fd.close()

        # Add to combined
        self.combined_str_map[dpid] += "\n\n" + "Port number list (shown to controller): " + str(port_num_list) + "\n"
        self.looped[dpid] = True
Exemple #16
0
 def _create_lacp(self, datapath, port, req):
     """create a LACP packet."""
     actor_system = datapath.ports[datapath.ofproto.OFPP_LOCAL].hw_addr
     res = slow.lacp(
         actor_system_priority=0xffff,
         actor_system=actor_system,
         actor_key=req.actor_key,
         actor_port_priority=0xff,
         actor_port=port,
         actor_state_activity=req.LACP_STATE_PASSIVE,
         actor_state_timeout=req.actor_state_timeout,
         actor_state_aggregation=req.actor_state_aggregation,
         actor_state_synchronization=req.actor_state_synchronization,
         actor_state_collecting=req.actor_state_collecting,
         actor_state_distributing=req.actor_state_distributing,
         actor_state_defaulted=req.LACP_STATE_OPERATIONAL_PARTNER,
         actor_state_expired=req.LACP_STATE_NOT_EXPIRED,
         partner_system_priority=req.actor_system_priority,
         partner_system=req.actor_system,
         partner_key=req.actor_key,
         partner_port_priority=req.actor_port_priority,
         partner_port=req.actor_port,
         partner_state_activity=req.actor_state_activity,
         partner_state_timeout=req.actor_state_timeout,
         partner_state_aggregation=req.actor_state_aggregation,
         partner_state_synchronization=req.actor_state_synchronization,
         partner_state_collecting=req.actor_state_collecting,
         partner_state_distributing=req.actor_state_distributing,
         partner_state_defaulted=req.actor_state_defaulted,
         partner_state_expired=req.actor_state_expired,
         collector_max_delay=0)
     self.logger.info("SW=%s PORT=%d LACP sent.",
                      dpid_to_str(datapath.id), port)
     self.logger.debug(str(res))
     return res
Exemple #17
0
 def to_dict(self):
     return {
         "dpid": dpid_to_str(self.dpid),
         "port_no": port_no_to_str(self.port_no),
         "hw_addr": self.hw_addr,
         "name": self.name.rstrip("\0"),
     }
    def packet_in_handler(self, ev):
        msg = ev.msg
        datapath = msg.datapath
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser
        in_port = msg.match['in_port']

        pkt = packet.Packet(msg.data)
        eth = pkt.get_protocols(ethernet.ethernet)[0]

        if eth.ethertype == ether.ETH_TYPE_ARP:
            arp_pkt = pkt.get_protocols(arp.arp)[0]
            srcMac = arp_pkt.src_mac
            srcIP = arp_pkt.src_ip
        elif eth.ethertype == ether.ETH_TYPE_IP:
            ip = pkt.get_protocols(ipv4.ipv4)[0]
            srcMac = eth.src
            srcIP = ip.src
        else:
            return

        ##from srcIP to inport
        """
        if self.isRouter(srcMac):
            return
        """

        if srcIP not in self.hosts:
            self.hosts[srcIP] = {}

        # Always update MAC and switch-port location, just in case
        # DHCP reassigned the IP or the host moved
        self.hosts[srcIP]['mac'] = srcMac
        self.updateHostTable(srcIP, dpid_lib.dpid_to_str(datapath.id), in_port)
Exemple #19
0
    def get_rules(self, waiters, vlan_id):
        rules = {}
        msgs = self.ofctl.get_flow_stats(self.dp, waiters)

        if str(self.dp.id) in msgs:
            flow_stats = msgs[str(self.dp.id)]
            for flow_stat in flow_stats:
                if (flow_stat[REST_PRIORITY] != STATUS_FLOW_PRIORITY
                        and flow_stat[REST_PRIORITY] != ARP_FLOW_PRIORITY):
                    vid = flow_stat[REST_MATCH][REST_DL_VLAN]
                    if vlan_id == REST_ALL or vlan_id == vid:
                        rule = self._to_rest_rule(flow_stat)
                        rules.setdefault(vid, {})
                        rules[vid].update(rule)

        get_data = []
        for vid, rule in rules.items():
            if vid == VLANID_NONE:
                get_data.append(rule)
            else:
                vid = '%s: %d' % (REST_VLANID, vid)
                get_data.append({vid: rule})

        switch_id = '%s: %s' % (REST_SWITCHID,
                                dpid_lib.dpid_to_str(self.dp.id))
        return {switch_id: get_data}
Exemple #20
0
 def regist_ofs(dp):
     try:
         f_ofs = Firewall(dp)
     except OFPUnknownVersion, message:
         mes = 'dpid=%s : %s' % (dpid_lib.dpid_to_str(dp.id), message)
         LOG.info(mes)
         return
Exemple #21
0
    def packet_in_handler(self, req_pkt, req_igmp, msg):
        """the process when the snooper received IGMP."""
        dpid = msg.datapath.id
        ofproto = msg.datapath.ofproto
        if ofproto.OFP_VERSION == ofproto_v1_0.OFP_VERSION:
            in_port = msg.in_port
        else:
            in_port = msg.match['in_port']

        log = "SW=%s PORT=%d IGMP received. " % (
            dpid_to_str(dpid), in_port)
        self.logger.debug(str(req_igmp))
        if igmp.IGMP_TYPE_QUERY == req_igmp.msgtype:
            self.logger.info(log + "[QUERY]")
            (req_ipv4, ) = req_pkt.get_protocols(ipv4.ipv4)
            (req_eth, ) = req_pkt.get_protocols(ethernet.ethernet)
            self._do_query(req_igmp, req_ipv4, req_eth, in_port, msg)
        elif (igmp.IGMP_TYPE_REPORT_V1 == req_igmp.msgtype or
              igmp.IGMP_TYPE_REPORT_V2 == req_igmp.msgtype):
            self.logger.info(log + "[REPORT]")
            self._do_report(req_igmp, in_port, msg)
        elif igmp.IGMP_TYPE_LEAVE == req_igmp.msgtype:
            self.logger.info(log + "[LEAVE]")
            self._do_leave(req_igmp, in_port, msg)
        elif igmp.IGMP_TYPE_REPORT_V3 == req_igmp.msgtype:
            self.logger.info(log + "V3 is not supported yet.")
            self._do_flood(in_port, msg)
        else:
            self.logger.info(log + "[unknown type:%d]",
                             req_igmp.msgtype)
            self._do_flood(in_port, msg)
    def _vm_port_del(self, network_id, dpid):
        self.logger.debug('_vm_port_del %s %s', network_id,
                          dpid_lib.dpid_to_str(dpid))
        if len(self.nw.get_ports(dpid, network_id)) > 0:
            return

        tunnel_networks = set(p.network_id
                              for p in self.nw.get_networks(dpid))
        tunnel_networks.discard(network_id)
        tunnel_networks.difference_update(rest_nw_id.RESERVED_NETWORK_IDS)
        dpids = self.nw.get_dpids(network_id).copy()
        dpids.discard(dpid)
        del_dpids = []
        for remote_dpid in dpids:
            remote_networks = set(p.network_id
                                  for p in self.nw.get_networks(remote_dpid))
            if tunnel_networks & remote_networks:
                continue
            self.tunnel_requests.remove(dpid, remote_dpid)
            del_dpids.append(remote_dpid)

        tunnel_dp = self.tunnel_dpset.get(dpid)
        if tunnel_dp is None:
            return
        for remote_dpid in del_dpids:
            remote_dp = self.tunnel_dpset.get(remote_dpid)
            if remote_dp is None:
                continue
            tunnel_dp.request_del_tunnel_port(remote_dp.tunnel_ip)
            remote_dp.request_del_tunnel_port(tunnel_dp.tunnel_ip)
Exemple #23
0
    def lldp_packet(dpid, port_no, dl_addr, ttl):
        pkt = packet.Packet()

        dst = lldp.LLDP_MAC_NEAREST_BRIDGE
        src = dl_addr
        ethertype = ETH_TYPE_LLDP
        eth_pkt = ethernet.ethernet(dst, src, ethertype)
        pkt.add_protocol(eth_pkt)

        tlv_chassis_id = lldp.ChassisID(
            subtype=lldp.ChassisID.SUB_LOCALLY_ASSIGNED,
            chassis_id=(LLDPPacket.CHASSIS_ID_FMT %
                        dpid_to_str(dpid)).encode('ascii'))

        tlv_port_id = lldp.PortID(subtype=lldp.PortID.SUB_PORT_COMPONENT,
                                  port_id=struct.pack(
                                      LLDPPacket.PORT_ID_STR,
                                      port_no))

        tlv_ttl = lldp.TTL(ttl=ttl)
        tlv_end = lldp.End()

        tlvs = (tlv_chassis_id, tlv_port_id, tlv_ttl, tlv_end)
        lldp_pkt = lldp.lldp(tlvs)
        pkt.add_protocol(lldp_pkt)

        pkt.serialize()
        return pkt.data
Exemple #24
0
    def set_ovsdb_addr(self, dpid, ovsdb_addr):
        # easy check if the address format valid
        self.logger.debug("set_ovsdb_addr dpid %s ovsdb_addr %s", dpid_lib.dpid_to_str(dpid), ovsdb_addr)
        _proto, _host, _port = ovsdb_addr.split(":")

        old_address = self.ovsdb_addr
        if old_address == ovsdb_addr:
            return
        if ovsdb_addr is None:
            # TODO: clean up this ovs switch
            if self.ovs_bridge:
                self.ovs_bridge.del_controller()
                self.ovs_bridge = None
            return
        self.ovsdb_addr = ovsdb_addr
        if self.ovs_bridge is None:
            self.logger.debug("ovsdb: adding ports %s", self.ports)
            ovs_bridge = bridge.OVSBridge(dpid, ovsdb_addr)
            self.ovs_bridge = ovs_bridge
            ovs_bridge.init()
            # TODO: for multi-controller
            #       not overwrite controllers, but append this controller
            ovs_bridge.set_controller([self.ctrl_addr])
            for port in self.ports.values():
                self.logger.debug("adding port %s", port)
                self.update_port(port.ofport, port.name, True)
Exemple #25
0
    def _configure_vrrp_router(self, vrrp_version, priority, ip_addr,
                               switch_index, vrid):
        switches = self.switches
        self.logger.debug('%s', switches.dps)
        dpid = sorted(switches.dps.keys())[switch_index]
        self.logger.debug('%s', lib_dpid.dpid_to_str(dpid))
        self.logger.debug('%s', switches.port_state)
        # hack: use the smallest port no to avoid picking OVS local port
        port_no = sorted(switches.port_state[dpid].keys())[0]
        self.logger.debug('%d', port_no)
        port = switches.port_state[dpid][port_no]
        self.logger.debug('%s', port)
        mac = port.hw_addr
        self.logger.debug('%s', mac)

        interface = vrrp_event.VRRPInterfaceOpenFlow(mac, ip_addr, None, dpid,
                                                     port_no)
        self.logger.debug('%s', interface)

        config = vrrp_event.VRRPConfig(
            version=vrrp_version,
            vrid=vrid,
            priority=priority,
            ip_addresses=[ip_addr])
        self.logger.debug('%s', config)

        rep = vrrp_api.vrrp_config(self, interface, config)
        self.logger.debug('%s', rep)
        return rep
Exemple #26
0
    def update_port_link(self, dpid, port):
        """
            Fulfill neighbor information for specific port.
        """
        switch = self.switches[dpid]
        try:
            p = switch.ports[port.port_no]
            p.neighbor_switch_dpid = port.neighbor_switch_dpid
            p.neighbor_port_no = port.neighbor_port_no
        except KeyError:
            switch.ports[port.port_no] = port

        neighbor_switch = self.switches[port.neighbor_switch_dpid]
        switch.neighbors[neighbor_switch] = port.port_no

        logger.info('link connected: %s->%s', dpid_lib.dpid_to_str(switch.dp.id), dpid_lib.dpid_to_str(neighbor_switch.dp.id))
Exemple #27
0
    def __init__(self, dp, logger, config, send_ev_func):
        super(Bridge, self).__init__()
        self.dp = dp
        self.logger = logger
        self.dpid_str = {'dpid': dpid_to_str(dp.id)}
        self.send_event = send_ev_func

        # Bridge data
        bridge_conf = config.get('bridge', {})
        values = self._DEFAULT_VALUE
        for key, value in bridge_conf.items():
            values[key] = value
        system_id = list(dp.ports.values())[0].hw_addr

        self.bridge_id = BridgeId(values['priority'],
                                  values['sys_ext_id'],
                                  system_id)
        self.bridge_times = Times(0,  # message_age
                                  values['max_age'],
                                  values['hello_time'],
                                  values['fwd_delay'])
        # Root bridge data
        self.root_priority = Priority(self.bridge_id, 0, None, None)
        self.root_times = self.bridge_times
        # Ports
        self.ports = {}
        self.ports_conf = config.get('ports', {})
        for ofport in dp.ports.values():
            self.port_add(ofport)

        # Install BPDU PacketIn flow. (OpenFlow 1.2/1.3)
        if dp.ofproto == ofproto_v1_2 or dp.ofproto == ofproto_v1_3:
            ofctl = OfCtl_v1_2later(self.dp)
            ofctl.add_bpdu_pkt_in_flow()
Exemple #28
0
    def handle_arp_reply(self, msg, pkt, arp_pkt):
        """
            called when receiving ARP reply from hosts.
            the host will send their MAC address back to switch.
            (1) save the MAC address information in ARP table.
            (2) try to resend the packet in the buffer.
            (3) remove the sent packet from the buffer queue.
        """
        switch = self.switches[msg.datapath.id]
        in_port_no = msg.in_port
        gateway = switch.ports[in_port_no].gateway
        replied_buffer = []

        logger.info('receive ARP reply: from %s (dpid=%s)', str(arp_pkt.src_ip), dpid_lib.dpid_to_str(msg.datapath.id))

        if gateway and gateway.ipv4 == netaddr.IPAddress(arp_pkt.dst_ip):
            self.update_arp_entry(switch, pkt)
            # try to resend the buffered packets
            for i in xrange(len(switch.msg_buffer)):
                msg, pkt, outport_no = switch.msg_buffer[i]
                if self.deliver_to_host(msg, pkt, outport_no):
                    replied_buffer.append(i)

            replied_buffer.sort(reverse = True)
            for i in replied_buffer:
                switch.msg_buffer.pop(i)
    def _switch_enter_handler(self, ev):
        # get_switch(self, None) outputs the list of switches object.
        self.topo_switches = get_switch(self, None)
        # get_link(self, None) outputs the list of links object.
        self.topo_links = get_link(self, None)

        """
        Now you have saved the links and switches of the topo. But they are object, we need to use to_dict() to trans them  
        """
        # print '*'*40,"Switch_set",'*'*40
        for switch in self.topo_switches:
            dp = switch.dp
            dp_no = dpid_to_str(dp.id)
            if (Switch_set.has_key(dp_no) == False):
                ports = switch.ports
                Switch_set[dp_no] = [port.to_dict() for port in ports]
        # pprint.pprint(Switch_set)
        Switch_set_json = json.dumps(Switch_set, indent=4)
        Ssj_file = open('./Info/Static/Switch_json.json','w+')
        Ssj_file.write(Switch_set_json)
        Ssj_file.close()

        # print '*'*40,"Link_set",'*'*40
        Link_set = [ link.to_dict() for link in self.topo_links ]
        # pprint.pprint(Link_set)
        Link_set_json = json.dumps(Link_set, indent=4)
        Lsj_file = open('./Info/Static/Link_json.json','w+')
        Lsj_file.write(Link_set_json)
        Lsj_file.close()
        self.logger.info("******_switch_enter_handler, Switch_set & Link_set******")
Exemple #30
0
    def _register(self, dp):
        LOG.debug('DPSET: register datapath %s', dp)
        assert dp.id is not None

        # while dpid should be unique, we need to handle duplicates here
        # because it's entirely possible for a switch to reconnect us
        # before we notice the drop of the previous connection.
        # in that case,
        # - forget the older connection as it likely will disappear soon
        # - do not send EventDP leave/enter events
        # - keep the PortState for the dpid
        if dp.id in self.dps:
            self.logger.warning('DPSET: Multiple connections from %s',
                                dpid_to_str(dp.id))
            self.logger.debug('DPSET: Forgetting datapath %s', self.dps[dp.id])
            self.logger.debug('DPSET: New datapath %s', dp)
        self.dps[dp.id] = dp
        if dp.id not in self.port_state:
            self.port_state[dp.id] = PortState()
            ev = EventDP(dp, True)
            with warnings.catch_warnings():
                warnings.simplefilter('ignore')
                for port in dp.ports.values():
                    self._port_added(dp, port)
                    ev.ports.append(port)
            self.send_event_to_observers(ev)
Exemple #31
0
    def get(self, _req, dpid, port_id, **_kwargs):
        dpid = dpid_lib.str_to_dpid(dpid)
        port_id = int(port_id)
        try:
            remote_dpid = self.tunnels.get_remote_dpid(dpid, port_id)
        except ryu_exc.PortNotFound:
            return Response(status=404)
        body = json.dumps(dpid_lib.dpid_to_str(remote_dpid))

        return Response(content_type='application/json', body=body)
Exemple #32
0
    def _add_tunnel_port(self, remote_dpid, remote_ip):
        self.logger.debug('add_tunnel_port local %s %s remote %s %s',
                          dpid_lib.dpid_to_str(self.dpid), self.tunnel_ip,
                          dpid_lib.dpid_to_str(remote_dpid), remote_ip)
        if self._tunnel_port_exists(remote_dpid, remote_ip):
            self.logger.debug('add_tunnel_port nop')
            return

        self.logger.debug('add_tunnel_port creating port')
        port_name = self._port_name(self.tunnel_ip, remote_ip)
        self.ovs_bridge.add_tunnel_port(port_name, self.tunnel_type,
                                        self.tunnel_ip, remote_ip, 'flow')

        tp = self.ovs_bridge.get_tunnel_port(port_name, self.tunnel_type)
        self.tunnels[tp.ofport] = TunnelPort(self.dpid, tp.ofport, tp.local_ip,
                                             tp.remote_ip, remote_dpid)
        self.network_api.create_port(self.tunnel_nw_id, self.dpid, tp.ofport)
        self.tunnel_api.create_remote_dpid(self.dpid, tp.ofport, remote_dpid)
        return tp
    def _topology_change_handler(self, ev):
        dp = ev.dp
        dpid_str = dpid_lib.dpid_to_str(dp.id)
        msg = 'Receive topology change event. Flush MAC table.'
        #self.logger.info("[time="+str((datetime.datetime.now()-self.start_time).seconds)+" secs]"
        #    +"[dpid="+str(dpid_str)+"] "+msg)

        if dp.id in self.mac_to_port:
            del self.mac_to_port[dp.id]
        self.flush_mac(dp)
    def _do_switch(dpid, func, ret_func):
        dpid = dpid_lib.str_to_dpid(dpid)
        try:
            ret = func(dpid)
        except KeyError:
            return Response(status=httplib.NOT_FOUND,
                            body='no dpid is found %s' %
                            dpid_lib.dpid_to_str(dpid))

        return ret_func(ret)
Exemple #35
0
    def dpid_state_from_mininet(self, name):
      if 'h' in name:
        return (0,0,0)
      dpid = dpid_to_str(int(name[1:]))


      query = "SELECT * FROM charge_state WHERE dpid = \'%s\'" % dpid 
      self.cursor.execute(query)
      rv = self.cursor.fetchall() 
      return rv[0]
Exemple #36
0
    def switch_features_handler(self, ev):
        ip_list = []
        port_list = []

        datapath = ev.msg.datapath
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser

        dpid_ = dpid.dpid_to_str(datapath.id)
        print("Switch found with dipid" + dpid_)
        print(datapath)

        # Add flow entries

        pod = int(dpid_[10:12])
        switch_num = int(dpid_[12:14])

        # Check if core switch
        if (pod == k):
            # Handle core switches
            # Push down links
            downLinkFlow, outputPort1 = coreDownLink()
        # Must be aggregation/edge switch
        else:
            downLinkFlow, outputPort1 = downLink(pod, switch_num)
            upLinkFlow, outputPort2 = upLink(pod, switch_num)

        for i in range(len(downLinkFlow)):
            match = parser.OFPMatch(ipv4_dst=downLinkFlow[i], eth_type=0x800)
            actions = [parser.OFPActionOutput(outputPort1[i],ofproto.OFPCML_NO_BUFFER)]
            self.add_flow(datapath, 10, match, actions)

        # Add suffix entries to table since Switch is not Core
        if switch_num != k:
            for i in range(len(upLinkFlow)):
                match = parser.OFPMatch(ipv4_dst=upLinkFlow[i], eth_type=0x800)
                actions = [parser.OFPActionOutput(outputPort2[i],ofproto.OFPCML_NO_BUFFER)]
                self.add_flow(datapath, 1, match, actions)

        # table miss entry
        match = parser.OFPMatch()
        actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,
                                          ofproto.OFPCML_NO_BUFFER)]
        self.add_flow(datapath, 0, match, actions) \


        @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
        def packet_in_handler(self, ev):
            datapath = ev.msg.datapath
            ofproto = datapath.ofproto
            parser = datapath.ofproto_parser
            pkt = packet.Packet(array.array('B', ev.msg.data))

            switchDPID = datapath.id
            dpid_ = dpid.dpid_to_str(datapath.id)
Exemple #37
0
    def table_features_handler(self, ev):

        feature_str = ""
        prop_str = ""

        ## Fields
        print ev.msg.datapath
        table_list = ev.msg.body
        for t in table_list:

            table_id = t.table_id
            name = t.name
            metadata_match = t.metadata_match
            metadata_write = t.metadata_write
            #config = t.config   ## Bitmap that is provided for backward compability in OF.
            max_entries = t.max_entries
            properties = t.properties

            #
            feature_str = "\n\n==========================================\n"
            feature_str += " Table Feature: " + str(table_id) + "\n"
            feature_str += "==========================================\n"

            feature_str +=  "Table Id:             "+str(table_id)+"\n" +          \
                            "Name:                 "+str(name)+"\n"+       \
                            "Metadata_match:       "+str(hex(metadata_match))+"\n"+        \
                            "Metadata_write:       "+str(hex(metadata_write))+"\n"+            \
                            "Max entries:          "+str(max_entries)+"\n"

            prop_str = self.property_parser(properties)

        # Save
        fd = open(
            "./results/switch_" + dpidlib.dpid_to_str(ev.msg.datapath.id) +
            "_v13_table.txt", "a+")
        fd.write(feature_str + prop_str)
        fd.close()

        # Combined
        #        self.combined_str += (feature_str + prop_str)
        self.combined_str_map[dpidlib.dpid_to_str(
            ev.msg.datapath.id)] += (feature_str + prop_str)
Exemple #38
0
    def _topology_change_handler(self, ev):
        dp = ev.dp
        dpid_str = dpid_lib.dpid_to_str(dp.id)
        msg = 'Receive topology change event. Flush MAC table.'

        mac_to_port_dpid = self.G.node[dpid]["mactoport"]

        if dp.id in mac_to_port_dpid:
            self.delete_flow(dp)
            del mac_to_port_dpid[dp.id]
            self.G.node[dpid]["mactoport"] = mac_to_port_dpid
Exemple #39
0
    def _topology_change_handler(self, ev):
        dp = ev.dp
        # print('1:dp:',dp)
        dpid_str = dpid_lib.dpid_to_str(dp.id)
        # print('3:dpid_str:',dpid_str)
        msg = 'Receive topology change event. Flush MAC table.'
        self.logger.debug("[dpid=%s] %s", dpid_str, msg)

        if dp.id in self.mac_to_port:
            self.delete_flow(dp)
            del self.mac_to_port[dp.id]
    def regist_ofs(dp, CONF):
        if dp.id in QoSController._OFS_LIST:
            return

        dpid_str = dpid_lib.dpid_to_str(dp.id)
        try:
            f_ofs = QoS(dp, CONF)
            f_ofs.set_default_flow()
        except OFPUnknownVersion, message:
            QoSController._LOGGER.info('dpid=%s: %s', dpid_str, message)
            return
    def regist_ofs(dp):
        dpid_str = dpid_lib.dpid_to_str(dp.id)
        try:
            f_ofs = Forward(dp)
        except OFPUnknownVersion as message:
            ForwardController._LOGGER.info('dpid=%s: %s', dpid_str, message)
            return

        ForwardController._OFS_LIST.setdefault(dp.id, f_ofs)
        ForwardController._LOGGER.info('dpid=%s: Forwarding module is joined.',
                                       dpid_str)
Exemple #42
0
 def _unregister_sw(self, dp):
     if dp.id == self.target_dpid:
         self.target_sw.dp = DummyDatapath()
         msg = 'Leave target SW.'
     elif dp.id == self.tester_dpid:
         self.tester_sw.dp = DummyDatapath()
         msg = 'Leave tester SW.'
     else:
         msg = 'Disconnect unknown SW.'
     if dp.id:
         self.logger.info('dpid=%s : %s', dpid_lib.dpid_to_str(dp.id), msg)
Exemple #43
0
 def _port_state_change_handler(self, ev):
     dpid_str = dpid_lib.dpid_to_str(ev.dp.id)
     of_state = {
         ofproto_v1_0.OFPPS_LINK_DOWN: 'DISABLE',
         ofproto_v1_0.OFPPS_STP_BLOCK: 'BLOCK',
         ofproto_v1_0.OFPPS_STP_LISTEN: 'LISTEN',
         ofproto_v1_0.OFPPS_STP_LEARN: 'LEARN',
         ofproto_v1_0.OFPPS_STP_FORWARD: 'FORWARD'
     }
     self.logger.debug("[dpid=%s][port=%d] state=%s", dpid_str, ev.port_no,
                       of_state[ev.port_state])
Exemple #44
0
    def __init__(self, dp, logger, config, send_ev_func, timeout_func,
                 topology_change_func, bridge_id, bridge_times, ofport):
        super(Port, self).__init__()
        self.dp = dp
        self.logger = logger
        self.dpid_str = {'dpid': dpid_to_str(dp.id)}
        self.config_enable = config.get('enable',
                                        self._DEFAULT_VALUE['enable'])
        self.send_event = send_ev_func
        self.wait_bpdu_timeout = timeout_func
        self.topology_change_notify = topology_change_func
        self.ofctl = OfCtl_v1_0(dp)

        # Bridge data
        self.bridge_id = bridge_id
        # Root bridge data
        self.port_priority = None
        self.port_times = None
        # ofproto_v1_0_parser.OFPPhyPort data
        self.ofport = ofport
        # Port data
        values = self._DEFAULT_VALUE
        for rate in sorted(self._PATH_COST.keys(), reverse=True):
            if ofport.curr & rate:
                values['path_cost'] = self._PATH_COST[rate]
                break
        for key, value in values.items():
            values[key] = value
        self.port_id = PortId(values['priority'], ofport.port_no)
        self.path_cost = values['path_cost']
        self.state = (None if self.config_enable else PORT_STATE_DISABLE)
        self.role = None
        # Receive BPDU data
        self.designated_priority = None
        self.designated_times = None
        # BPDU handling threads
        self.send_bpdu_thread = PortThread(self._transmit_config_bpdu)
        self.wait_bpdu_thread = PortThread(self._wait_bpdu_timer)
        self.send_tc_thread = PortThread(self._transmit_tc_bpdu)
        self.send_tcn_thread = PortThread(self._transmit_tcn_bpdu)
        self.send_tc_flg = None
        self.send_tcn_flg = None
        self.wait_timer_event = None
        # State machine thread
        self.state_machine = PortThread(self._state_machine)
        self.state_event = None

        self.up(DESIGNATED_PORT,
                Priority(bridge_id, 0, None, None),
                bridge_times)

        self.state_machine.start()
        self.logger.debug('[port=%d] Start port state machine.',
                          self.ofport.port_no, extra=self.dpid_str)
Exemple #45
0
def add_addresses(addresses, controller_ip):
    for address in addresses:
        ip = address[0]
        router = address[1]
        port = address[2]
        subprocess.call([
            'curl', '-X', 'POST', '-d',
            '{"address": "%s"}' % ip,
            'http://%s:8080/router/%s/%s/address' %
            (controller_ip, dpid_to_str(router), port_no_to_str(port))
        ])
Exemple #46
0
 def _port_flow_add(self, dp, port_no):
     self.logger.debug('ovs_port_update dpid %s port_no %s',
                       dpid_lib.dpid_to_str(dp.id), port_no)
     rule = nx_match.ClsRule()
     rule.set_in_port(port_no)
     ofproto = dp.ofproto
     actions = [dp.ofproto_parser.OFPActionOutput(ofproto.OFPP_NORMAL)]
     dp.send_flow_mod(rule=rule, cookie=self._COOKIE_NORMAL,
                      command=ofproto.OFPFC_ADD,
                      idle_timeout=0, hard_timeout=0,
                      priority=self._PRIORITY_NORMAL, actions=actions)
Exemple #47
0
    def _topology_change_handler(self, ev):
        dp = ev.dp
        dpid_str = dpid_lib.dpid_to_str(dp.id)
        #msg = 'Receive topology change event. Flush MAC table.'
        #self.logger.debug("[dpid=%s] %s", dpid_str, msg)
        print("[DEDALO][Topologia][dpid=" + str(dpid_str) +
              "] Vaciado de TCAM")

        if dp.id in self.mac_to_port:
            del self.mac_to_port[dp.id]
        self.delete_flow(dp)
 def flow_inport_to_outport(self, dp, in_port, out_port):
     ''' Install OF flow to match all traffic from the in_port and forward it to the out_port '''
     parser = dp.ofproto_parser
     if in_port is None or out_port is None:
         self.logger.error(
             'No in_port or out_port specified for DPID:{}'.format(
                 dpid_to_str(dp.id)))
         return
     match = parser.OFPMatch(in_port=in_port)
     action = parser.OFPActionOutput(out_port)
     self.add_flow(dp, 2000, match, [action])
    def update_list(dp, add):
	dpid_str = dpid_lib.dpid_to_str(dp.id)
        if add:
	    MainController.LIST_Nodes[dp.id] = dp
	    MainController._LOGGER.info('Node dpid=%s has joined',dpid_str)
 #      MainController.regist_ofs(ev.dp)
        else:
	    del MainController.LIST_Nodes[dp.id]
	    if ev.dp.id in self.LIST_FW:
		del self.LIST_FW[dp.id]
	    MainController._LOGGER.info('Node dpid=%s has left.',dpid_str)
Exemple #50
0
    def garbage_collect(self):
        """
            iterate the whole routing table and delete routing entries
            with metric=16.
        """
        for subnet, entry in self.items():
            if entry.metric == 16:
                logger.info('GC: route from dpid=%s to %s', dpid_to_str(self.dpid), str(subnet))
                del self[subnet]

        time.sleep(self.gc_interval)
Exemple #51
0
    def to_dict(self):
        r = {}
        if self.receive_port.port_no:
            r['out_port'] = port_no_to_str(self.receive_port.port_no)
        if self.metric != 0:
            r['next_hop'] = dpid_to_str(self.neighbor_port.dpid)
        r['metric'] = self.metric
        r['source'] = self.source
        r['last_update'] = datetime.datetime.fromtimestamp(self.last_update).strftime('%Y-%m-%d %H:%M:%S')

        return r
Exemple #52
0
    def packet_in_handler(self, ev):
        """Check a packet-in message.

           Build and output an arp reply if a packet-in message is
           an arp packet.
        """
        msg = ev.msg
        LOG.debug("packet-in msg %s", msg)
        datapath = msg.datapath
        if self.br is None:
            LOG.info(_LI("No bridge is set"))
            return
        if self.br.datapath.id != datapath.id:
            LOG.info(_LI("Unknown bridge %(dpid)s ours %(ours)s"), {
                "dpid": datapath.id,
                "ours": self.br.datapath.id
            })
            return
        ofp = datapath.ofproto
        port = msg.match['in_port']
        metadata = msg.match.get('metadata')
        pkt = packet.Packet(msg.data)
        LOG.info(_LI("packet-in dpid %(dpid)s in_port %(port)s pkt %(pkt)s"), {
            'dpid': dpid_lib.dpid_to_str(datapath.id),
            'port': port,
            'pkt': pkt
        })

        if metadata is None:
            LOG.info(_LI("drop non tenant packet"))
            return
        network = metadata & meta.NETWORK_MASK
        pkt_ethernet = pkt.get_protocol(ethernet.ethernet)
        if not pkt_ethernet:
            LOG.info(_LI("drop non-ethernet packet"))
            return
        pkt_vlan = pkt.get_protocol(vlan.vlan)
        pkt_arp = pkt.get_protocol(arp.arp)
        if not pkt_arp:
            LOG.info(_LI("drop non-arp packet"))
            return

        arptbl = self._arp_tbl.get(network)
        if arptbl:
            if self._respond_arp(datapath, port, arptbl, pkt_ethernet,
                                 pkt_vlan, pkt_arp):
                return
        else:
            LOG.info(_LI("unknown network %s"), network)

        # add a flow to skip a packet-in to a controller.
        self.br.arp_passthrough(network=network, tpa=pkt_arp.dst_ip)
        # send an unknown arp packet to the table.
        self._send_unknown_packet(msg, port, ofp.OFPP_TABLE)
Exemple #53
0
 def _port_state_change_handler(self, ev):
     dpid_str = dpid_lib.dpid_to_str(ev.dp.id)
     of_state = {
         stplib.PORT_STATE_DISABLE: 'DISABLE',
         stplib.PORT_STATE_BLOCK: 'BLOCK',
         stplib.PORT_STATE_LISTEN: 'LISTEN',
         stplib.PORT_STATE_LEARN: 'LEARN',
         stplib.PORT_STATE_FORWARD: 'FORWARD'
     }
     self.logger.debug("[dpid=%s][port=%d] state=%s", dpid_str, ev.port_no,
                       of_state[ev.port_state])
Exemple #54
0
    def _test_flow_matching_check(self, pkt):
        self.logger.debug("send_packet:[%s]", packet.Packet(pkt[KEY_INGRESS]))
        self.logger.debug("egress:[%s]", packet.Packet(pkt.get(KEY_EGRESS)))
        self.logger.debug("packet_in:[%s]", packet.Packet(pkt.get(KEY_PKT_IN)))

        # 1. send a packet from the OpenFlow Switch.
        xid = self.tester_sw.send_packet_out(pkt[KEY_INGRESS])
        self.send_msg_xids.append(xid)

        # 2. receive a PacketIn message.
        try:
            self._wait()
        except TestTimeout:
            return TIMEOUT

        assert len(self.rcv_msgs) == 1
        msg = self.rcv_msgs[0]
        assert isinstance(msg, ofproto_v1_3_parser.OFPPacketIn)
        self.logger.debug("dpid=%s : receive_packet[%s]",
                          dpid_lib.dpid_to_str(msg.datapath.id),
                          packet.Packet(msg.data))

        # 3. check the SW which sended PacketIn and output packet.
        pkt_in_src_model = (self.tester_sw
                            if KEY_EGRESS in pkt else self.target_sw)
        model_pkt = (pkt[KEY_EGRESS] if KEY_EGRESS in pkt else pkt[KEY_PKT_IN])

        if msg.datapath.id != pkt_in_src_model.dp.id:
            pkt_type = 'packet-in'
            err_msg = 'SW[dpid=%s]' % dpid_lib.dpid_to_str(msg.datapath.id)
        elif msg.reason != ofproto_v1_3.OFPR_ACTION:
            pkt_type = 'packet-in'
            err_msg = 'OFPPacketIn[reason=%d]' % msg.reason
        elif repr(msg.data) != repr(model_pkt):
            pkt_type = 'packet'
            err_msg = self._diff_packets(packet.Packet(model_pkt),
                                         packet.Packet(msg.data))
        else:
            return TEST_OK

        raise TestFailure(self.state, pkt_type=pkt_type, detail=err_msg)
Exemple #55
0
    def _register_bridge(self, dp):
        self._unregister_bridge(dp.id)
        dpid_str = {'dpid': dpid_to_str(dp.id)}
        self.logger.info('Join as rstp bridge.', extra=dpid_str)
        try:
            bridge = Bridge(dp, self.config.get(dp.id, {}), self.logger,
                            self.send_event_to_observers)
        except OFPUnknownVersion as message:
            self.logger.error(str(message), extra=dpid_str)
            return

        self.bridge_list[dp.id] = bridge
Exemple #56
0
    def __init__(self):
        super(OfTester, self).__init__()
        self._set_logger()

        self.target_dpid = self._convert_dpid(CONF['test-switch']['target'])
        self.tester_dpid = self._convert_dpid(CONF['test-switch']['tester'])
        self.logger.info('target_dpid=%s',
                         dpid_lib.dpid_to_str(self.target_dpid))
        self.logger.info('tester_dpid=%s',
                         dpid_lib.dpid_to_str(self.tester_dpid))
        test_dir = CONF['test-switch']['dir']
        self.logger.info('Test files directory = %s', test_dir)

        self.target_sw = None
        self.tester_sw = None
        self.state = STATE_INIT
        self.sw_waiter = None
        self.waiter = None
        self.send_msg_xids = []
        self.rcv_msgs = []
        self.test_thread = hub.spawn(self._test_sequential_execute, test_dir)
Exemple #57
0
 def broadcast_thread(self):
     """
         infinite loop to advertise the routing table to
         all the neighbors. trigger neighbor swtich to update
         routing information instantly.
     """
     while True:
         try:
             logger.info('broadcast routing table (dpid=%s)',
                         dpid_to_str(self.dp.id))
             for port_no, port in self.ports.items():
                 if port.neighbor_switch_dpid:
                     self.switches[port.neighbor_switch_dpid].add_to_queue(
                         (port, self.tbl))
                     self.switches[
                         port.neighbor_switch_dpid].trigger_update()
             time.sleep(self.tbl.advertise_interval)
         except:
             logger.info('broadcast thread of dpid=%s is killed',
                         dpid_to_str(self.dp.id))
             break
Exemple #58
0
    def packet_in_handler(self, ev):
        """Check a packet-in message.

           Build and output an arp reply if a packet-in message is
           an arp packet.
        """
        msg = ev.msg
        LOG.debug("packet-in msg %s", msg)
        datapath = msg.datapath
        ofp = datapath.ofproto
        ofpp = datapath.ofproto_parser
        port = msg.match['in_port']
        pkt = packet.Packet(msg.data)
        LOG.info(_("packet-in dpid %(dpid)s in_port %(port)s pkt %(pkt)s"), {
            'dpid': dpid_lib.dpid_to_str(datapath.id),
            'port': port,
            'pkt': pkt
        })
        pkt_vlan = None
        pkt_arp = None
        pkt_ethernet = pkt.get_protocol(ethernet.ethernet)
        if not pkt_ethernet:
            LOG.info(_("non-ethernet packet"))
        else:
            pkt_vlan = pkt.get_protocol(vlan.vlan)
            if not pkt_vlan:
                LOG.info(_("non-vlan packet"))
        if pkt_vlan:
            network = pkt_vlan.vid
            pkt_arp = pkt.get_protocol(arp.arp)
            if not pkt_arp:
                LOG.info(_("drop non-arp packet"))
                return
        else:
            # drop an unknown packet.
            LOG.info(_("drop unknown packet"))
            return

        arptbl = self._arp_tbl.get(network)
        if arptbl:
            if self._respond_arp(datapath, port, arptbl, pkt_ethernet,
                                 pkt_vlan, pkt_arp):
                return
        else:
            LOG.info(_("unknown network %s"), network)
        # add a flow to skip a packet-in to a controller.
        match = ofpp.OFPMatch(eth_type=ether.ETH_TYPE_ARP,
                              vlan_vid=network | ofp.OFPVID_PRESENT,
                              arp_op=arp.ARP_REQUEST,
                              arp_tpa=pkt_arp.dst_ip)
        self._add_flow_to_avoid_unknown_packet(datapath, match)
        # send an unknown arp packet to the table.
        self._send_unknown_packet(msg, port, ofp.OFPP_TABLE)
Exemple #59
0
def set_qos_queue(dpid, data_share, qos_share, qos_high_rate, ofport):
    dpid_str = dpid_lib.dpid_to_str(dpid)
    url = 'http://localhost:8080/qos/queue/' + dpid_str
    payload = '{"port": %d,"type": "linux-htb", "max_rate": "%d", "queues": [{"min_rate": "%d"}, {"min_rate": "%d"}, {"min_rate": "%d"}]}' % (
                ofport,
                DEFAULT_LINK_CAPACITY,
                DEFAULT_LINK_CAPACITY * data_share,
                DEFAULT_LINK_CAPACITY * qos_share - qos_high_rate,
                qos_high_rate)
    # payload = '{"port_name": "s1-eth1", "type": "linux-htb", "max_rate": "1000000", "queues": [{"max_rate": "500000"}, {"min_rate": "800000"}]}'
    r = requests.post(url, data=payload)
    print "[SET_QUEUE]" , r.text
Exemple #60
0
    def _vm_port_add(self, network_id, dpid):
        self.logger.debug('_vm_port_add %s %s', network_id,
                          dpid_lib.dpid_to_str(dpid))
        dpids = self.nw.get_dpids(network_id)
        dpids.remove(dpid)
        for remote_dpid in dpids:
            self.tunnel_requests.add(dpid, remote_dpid)

        tunnel_dp = self.tunnel_dpset.get(dpid)
        if tunnel_dp is None:
            return
        self._add_tunnel_ports(tunnel_dp, dpids)