Exemplo n.º 1
0
    def ippart_packet_in(self, switch, inport, packet, buf):
        ARP_TYPE = 0x0806

        if packet.type == ARP_TYPE:
            if ip_to_str(packet.next.protodst) == '10.0.0.5':
                self.myLogger.info('TO 10.0.0.5')
                buf[38] = 10
                buf[39] = 0
                buf[40] = 0
                buf[41] = 3
                self.myIPFlow.ipflow_send(switch, buf, 1, inport)
                #self.myIPFlow.ipflow_dstrule_install(switch, '10.0.0.5', '10.0.0.3', inport, 1, 100)
                #self.myIPFlow.ipflow_rule_install(switch, '10.0.0.2', '10.0.0.5', '10.0.0.3', 2, 1, 100)
                self.ippart_installrule(0x000102030401, '10.0.0.2', '10.0.0.5',
                                        '10.0.0.3', 2, 1, 100)
            elif ip_to_str(packet.next.protosrc) == '10.0.0.3':
                buf[28] = 10
                buf[29] = 0
                buf[30] = 0
                buf[31] = 5
                self.myIPFlow.ipflow_send(switch, buf, 2, inport)
                #self.myIPFlow.ipflow_srcrule_install(switch, '10.0.0.3', '10.0.0.5', inport, 0, 100)
            else:
                self.myLogger.info('NOT TO 10.0.0.5')
                self.ippart_learnnforward(switch, inport, packet, buf)
        else:
            self.myLogger.info('NOT ARP')
            self.ippart_learnnforward(switch, inport, packet, buf)
Exemplo n.º 2
0
    def packet_in_callback(self, dpid, inport, reason, len, bufid, packet):
        IP_TYPE  = 0x0800
        ARP_TYPE = 0x0806 

	if not packet.parsed:
	    logger.debug('Ignoring incomplete packet')

        elif (packet.type == ARP_TYPE):
            if (ip_to_str(packet.next.protodst) == '10.0.0.5'):
                logger.info('THIS IS AN ARP TO 10.0.0.5')
	        self.arpdstrw_and_forward(dpid, inport, packet, packet.arr, bufid)
            elif (ip_to_str(packet.next.protosrc) == '10.0.0.3'):
                logger.info('THIS IS AN ARP FROM 10.0.0.3')
                self.arpsrcrw_and_forward(dpid, inport, packet, packet.arr, bufid)
            else:
	        self.learn_and_forward(dpid, inport, packet, packet.arr, bufid)
        elif (packet.type == IP_TYPE):
            if (ip_to_str(packet.next.dstip) == '10.0.0.5'):
                logger.info('THIS IS IP TO 10.0.0.5')
	        self.ipdstrw_and_forward(dpid, inport, packet, packet.arr, bufid)
            elif (ip_to_str(packet.next.srcip) == '10.0.0.3'):
                logger.info('THIS IS IP FROM 10.0.0.3')
                self.ipsrcrw_and_forward(dpid, inport, packet, packet.arr, bufid)
            else:
	        self.learn_and_forward(dpid, inport, packet, packet.arr, bufid)

	else:
	    self.learn_and_forward(dpid, inport, packet, packet.arr, bufid)
	return CONTINUE
Exemplo n.º 3
0
def delete_flow(flow, replicaNum):
    switchNum = findReplicasSwitch(replicaNum)
    deleteMultipaths = getMultipaths(switchNum)
    for currNode in deleteMultipaths:
        currSwitchNum = currNode['no']
        currMac = currNode['mac']
        flowList = getMultiFlow(flow, len(currNode['nexthops']))
        for i, miniFlow in enumerate(flowList):
            Globals.COMPONENT.delete_strict_datapath_flow(currMac, miniFlow)
            if not flow.has_key(NW_SRC_N_WILD):
                Globals.RULESLOG.write(
                    mac_to_str(currMac) + " Delete Multipath @ " +
                    str(currSwitchNum) + " to dest " + str(switchNum) + ' ' +
                    ip_to_str(flow[NW_SRC]) + '\n')
            else:
                Globals.RULESLOG.write(
                    mac_to_str(currMac) + " Delete Multipath @ " +
                    str(currSwitchNum) + " to dest " + str(switchNum) + ' ' +
                    ip_to_str(flow[NW_SRC]) + '/' + str(flow[NW_SRC_N_WILD]) +
                    '\n')


#    orderDelete = getAllPaths(switchNum)
#    for switch in orderDelete:
#        currMac = getMac(switch)
#        Globals.log.info('Delete Flow: ' + str(flow) + ' at ' + str(switch))
#        Globals.COMPONENT.delete_strict_datapath_flow(currMac, flow)
    Globals.RULESLOG.write('Delete: ' + ip_to_str(flow[NW_SRC]) + '/' +
                           str(flow[NW_SRC_N_WILD]) + '\n')
Exemplo n.º 4
0
def install_microflow_flow(flow, idle_timeout, hard_timeout, actions, bufid,
                           priority, inport, packet, switchMac, outport,
                           rewriteActions):
    switchNum = findMacSwitch(switchMac)
    orderInstall = getAllPaths(switchNum)
    #    Globals.log.info('Order of Install ' + str(orderInstall))
    for currSwitchNum in orderInstall:
        currMac = getMac(currSwitchNum)
        Globals.RULESLOG.write('Switch: ' + str(currSwitchNum) + '\n')
        if currMac == switchMac:
            actions = setMicroflowOutPort(rewriteActions, switchNum,
                                          currSwitchNum, outport)
        else:
            actions = setMicroflowOutPort(actions, switchNum, currSwitchNum,
                                          outport)


#	Globals.log.info('Install Microflow Flow: ' + str(flow) + ' at ' + str(currSwitchNum))
        Globals.COMPONENT.install_datapath_flow(currMac, flow, idle_timeout,
                                                hard_timeout, actions, bufid,
                                                priority, inport, packet)
    if flow.has_key(NW_SRC):
        Globals.RULESLOG.write('Install Microflow SRC: ' +
                               ip_to_str(flow[NW_SRC]) + '\n')
    if flow.has_key(NW_DST):
        Globals.RULESLOG.write('Install Microflow DST: ' +
                               ip_to_str(flow[NW_DST]) + '\n')
Exemplo n.º 5
0
    def packet_in_callback(self, dpid, inport, reason, len, bufid, packet):
        if packet.type == Globals.ARP_TYPE:
	    # ARP Response from replicas for our ARP Requests
            if packet.dst == octstr_to_array(Globals.VMAC):
                self.foundMac(dpid, mac_to_str(packet.src), ip_to_str(packet.next.protosrc), inport)
	    # Request for VIP, respond with ARP Response
            elif packet.next.protodst == ipstr_to_int(Globals.VIP):
		Globals.STATSLOG.write(mac_to_str(dpid) + ' received ' + ip_to_str(packet.next.protosrc) + '\n')
                srcIP = ip_to_str(packet.next.protosrc)
		# Install Rewrite Rules
                (flow, defaultActions, rewriteActions) = IPs.get_forwarding_srcrule(srcIP, mac_to_str(packet.src), Globals.VMAC, Globals.VIP, inport)
                Multipath.install_microflow_flow(flow, openflow.OFP_FLOW_PERMANENT, openflow.OFP_FLOW_PERMANENT, defaultActions, None, openflow.OFP_DEFAULT_PRIORITY + 20, 0, None, dpid, inport, rewriteActions)
		# Response
                arpResponse = Arps.create_virtual_arp_response(packet, octstr_to_array(Globals.VMAC), ipstr_to_int(Globals.VIP))
                Multipath.send(dpid, None, arpResponse, [[openflow.OFPAT_OUTPUT, [0, inport]]], openflow.OFPP_CONTROLLER)
                ip = ip_to_str(packet.next.protosrc)
                for i, switchJ in enumerate(Globals.SWITCHES):
                    if switchJ['mac'] == dpid:
                        found = False
			for i, client in enumerate(switchJ['clients']):
			    if client['ip'] == ip:
 				found = True
			if not found:
   			    Globals.STATSLOG.write(mac_to_str(dpid) + ' found ' + ip + '\n')
                            switchJ['clients'].append({'port': inport, 'ip': ip, 'oldCount': 0L, 'newCount': 0L, 'avg': 0L})
            elif packet.src != octstr_to_array(Globals.VMAC):
		Globals.STATSLOG.write(mac_to_str(dpid) + ' received REQ ' + ip_to_str(packet.next.protosrc) + '\n')
                arpResponse = Arps.create_arp_response(packet)
                Multipath.send(dpid, None, arpResponse, [[openflow.OFPAT_OUTPUT, [0, inport]]], openflow.OFPP_CONTROLLER)
	elif packet.type == Globals.IP_TYPE:
            if reason == openflow.OFPR_ACTION:
                IPTransition.handleControllerAction(packet)
Exemplo n.º 6
0
	def ippart_packet_in(self, switch, inport, packet, buf):
		ARP_TYPE = 0x0806

		if packet.type == ARP_TYPE:
			if ip_to_str(packet.next.protodst) == '10.0.0.5':
				self.myLogger.info('TO 10.0.0.5')
				buf[38] = 10
				buf[39] = 0
				buf[40] = 0
				buf[41] = 3
				self.myIPFlow.ipflow_send(switch, buf, 1, inport)
				#self.myIPFlow.ipflow_dstrule_install(switch, '10.0.0.5', '10.0.0.3', inport, 1, 100)
				#self.myIPFlow.ipflow_rule_install(switch, '10.0.0.2', '10.0.0.5', '10.0.0.3', 2, 1, 100)
				self.ippart_installrule(0x000102030401, '10.0.0.2', '10.0.0.5', '10.0.0.3', 2, 1, 100)
			elif ip_to_str(packet.next.protosrc) == '10.0.0.3':
				buf[28] = 10
				buf[29] = 0
				buf[30] = 0
				buf[31] = 5
				self.myIPFlow.ipflow_send(switch, buf, 2, inport)
				#self.myIPFlow.ipflow_srcrule_install(switch, '10.0.0.3', '10.0.0.5', inport, 0, 100)
			else:
				self.myLogger.info('NOT TO 10.0.0.5')
				self.ippart_learnnforward(switch, inport, packet, buf)
		else:
			self.myLogger.info('NOT ARP')
			self.ippart_learnnforward(switch, inport, packet, buf)
Exemplo n.º 7
0
    def packet_in_callback(self, dpid, inport, reason, len, bufid, packet):
        IP_TYPE = 0x0800
        ARP_TYPE = 0x0806

        if not packet.parsed:
            logger.debug('Ignoring incomplete packet')

        elif (packet.type == ARP_TYPE):
            if (ip_to_str(packet.next.protodst) == '10.0.0.5'):
                logger.info('THIS IS AN ARP TO 10.0.0.5')
                self.arpdstrw_and_forward(dpid, inport, packet, packet.arr,
                                          bufid)
            elif (ip_to_str(packet.next.protosrc) == '10.0.0.3'):
                logger.info('THIS IS AN ARP FROM 10.0.0.3')
                self.arpsrcrw_and_forward(dpid, inport, packet, packet.arr,
                                          bufid)
            else:
                self.learn_and_forward(dpid, inport, packet, packet.arr, bufid)
        elif (packet.type == IP_TYPE):
            if (ip_to_str(packet.next.dstip) == '10.0.0.5'):
                logger.info('THIS IS IP TO 10.0.0.5')
                self.ipdstrw_and_forward(dpid, inport, packet, packet.arr,
                                         bufid)
            elif (ip_to_str(packet.next.srcip) == '10.0.0.3'):
                logger.info('THIS IS IP FROM 10.0.0.3')
                self.ipsrcrw_and_forward(dpid, inport, packet, packet.arr,
                                         bufid)
            else:
                self.learn_and_forward(dpid, inport, packet, packet.arr, bufid)

        else:
            self.learn_and_forward(dpid, inport, packet, packet.arr, bufid)
        return CONTINUE
Exemplo n.º 8
0
    def packet_in_handler(self, dpid, inport, reason, length, bufid, packet):
        """ Handler for packet_in event """
        assert length is not None
        assert packet is not None
        # checks packet consistency
        if not packet.parsed:
            LOG.warning("Ignoring incomplete packet")
            return CONTINUE

        if packet.type == ethernet.LLDP_TYPE:
            return CONTINUE

        dpid_ = dpid_from_host(dpid)
        if not dpid_: return CONTINUE

        LOG.debug("dpid=%s, inport=%s, reason=%s, len=%s, bufid=%s, p=%s",
                  dpid_, inport, reason, length, str(bufid), str(packet))

        # Handle ARP packets
        if packet.type == ethernet.ARP_TYPE or\
           (packet.type == ethernet.VLAN_TYPE and\
            packet.find('vlan').eth_type == ethernet.ARP_TYPE):
            LOG.debug("Received ARP packet " + str(packet.find('arp')))
            if not dpid_ in self.switches:
                LOG.debug("Registering new switch %s" % dpid_)
                self.switches[dpid_] = {}

            self.__do_l2_learning(dpid_, inport, packet)
            self.__forward_l2_packet(dpid_, inport, packet, packet.arr, bufid)

        # switch over ethernet type
        if packet.type == ethernet.IP_TYPE or\
           (packet.type == ethernet.VLAN_TYPE and\
            packet.find('vlan').eth_type == ethernet.IP_TYPE):
            ip_addr = packet.find('ipv4')
            LOG.info("IPv4 packet: " + str(ip_addr))
            #  XXX FIXME: Remove the following check in order to be generic...
            if ip_addr.protocol == ipv4.ICMP_PROTOCOL:
                flow = extract_flow(packet)
                LOG.debug("Sending path request for flow: %s" % str(flow))
                payload = {"dst_port": flow[core.TP_DST],
                           "src_port": flow[core.TP_SRC],
                           "ip_dst"  : pkt_utils.ip_to_str(ip_addr.dstip),
                           "ip_src"  : pkt_utils.ip_to_str(ip_addr.srcip),
                           "ip_proto": flow[core.NW_PROTO],
                           "vlan_id" : flow[core.DL_VLAN]}

                LOG.debug("Payload=%s" % str(payload))
                if self.allow_ping == 'True':
                    req = requests.post(url=self.url + "pckt_host_path",
                                        headers=self.hs, data=json.dumps(payload))
                    LOG.debug("URL=%s, response=%s", req.url, req.text)

        return CONTINUE
Exemplo n.º 9
0
def handleControllerAction(packet):
    if packet.type == packet.IP_TYPE and packet.next.TCP_PROTOCOL:
        Globals.log.info('Controller Action ' + ip_to_str(packet.next.srcip))
        (newReplica, oldReplica) = findReplicaAssignment(ip_to_str(packet.next.srcip), Globals.TARGETRULES, Globals.TRANSITRULES)
        tcpFlag = packet.next.arr[33]
        # SYN Flag Set
        if tcpFlag == 2:
            actionInstallMicroflow(packet, newReplica)
	else:
            actionInstallMicroflow(packet, oldReplica)
    else:
	Globals.log.info('Unknown Flow handled by controller')
Exemplo n.º 10
0
def install_replica_flow(flow, idle_timeout, hard_timeout, actions, bufid,
                         priority, inport, packet, replicaNum, rewriteActions):
    switchNum = findReplicasSwitch(replicaNum)
    orderMultipaths = getMultipaths(switchNum)
    Globals.log.info("Order Multipaths")
    Globals.log.info(str(orderMultipaths))
    for currNode in orderMultipaths:
        currSwitchNum = currNode['no']
        currMac = currNode['mac']
        if flow.has_key(NW_SRC_N_WILD):
            flowList = getMultiFlow(flow, len(currNode['nexthops']))
            for i, miniFlow in enumerate(flowList):
                if switchNum == currSwitchNum:
                    nextHop = 0
                    actions = setReplicaOutPort(rewriteActions, switchNum,
                                                currSwitchNum, nextHop,
                                                replicaNum)
                else:
                    nextHop = currNode['nexthops'][i %
                                                   len(currNode['nexthops'])]
                    actions = setReplicaOutPort(actions, switchNum,
                                                currSwitchNum, nextHop,
                                                replicaNum)
                Globals.COMPONENT.install_datapath_flow(
                    currMac, miniFlow, idle_timeout, hard_timeout, actions,
                    bufid, priority, inport, packet)
                Globals.RULESLOG.write(
                    mac_to_str(currMac) + " Install Multipath @ " +
                    str(currSwitchNum) + " to dest " + str(switchNum) + ' ' +
                    ip_to_str(miniFlow[NW_SRC]) + '/' +
                    str(miniFlow[NW_SRC_N_WILD]) + '\n')
        else:
            if switchNum == currSwitchNum:
                nextHop = 0
                actions = setReplicaOutPort(rewriteActions, switchNum,
                                            currSwitchNum, nextHop, replicaNum)
            else:
                nextHopIndex = random.randint(0, len(currNode['nexthops']) - 1)
                nextHop = currNode['nexthops'][nextHopIndex]
                #		nextHop = Globals.FORWARDINGTABLE[switchNum][currSwitchNum]['prevhop']
                actions = setReplicaOutPort(actions, switchNum, currSwitchNum,
                                            nextHop, replicaNum)
            Globals.COMPONENT.install_datapath_flow(currMac, flow,
                                                    idle_timeout, hard_timeout,
                                                    actions, bufid, priority,
                                                    inport, packet)
            Globals.RULESLOG.write(
                mac_to_str(currMac) + " Install Multipath @ " +
                str(currSwitchNum) + " to dest " + str(switchNum) + ' ' +
                ip_to_str(flow[NW_SRC]) + '\n')
    Globals.RULESLOG.write('Install Wildcard: ' + ip_to_str(flow[NW_SRC]) +
                           '\n')
Exemplo n.º 11
0
def handleControllerAction(packet):
    if packet.type == packet.IP_TYPE and packet.next.TCP_PROTOCOL:
        Globals.log.info('Controller Action ' + ip_to_str(packet.next.srcip))
        (newReplica,
         oldReplica) = findReplicaAssignment(ip_to_str(packet.next.srcip),
                                             Globals.TARGETRULES,
                                             Globals.TRANSITRULES)
        tcpFlag = packet.next.arr[33]
        # SYN Flag Set
        if tcpFlag == 2:
            actionInstallMicroflow(packet, newReplica)
        else:
            actionInstallMicroflow(packet, oldReplica)
    else:
        Globals.log.info('Unknown Flow handled by controller')
Exemplo n.º 12
0
    def hardTimeoutExpiration(self):
	rule = self.TimeoutQueue.pop()
	Globals.RULESLOG.write('\n-------------------------------\nHARD TIMEOUT!!!\n')
	Globals.RULESLOG.write('Timeout Rule: ' + ip_to_str(rule['IP']) + ':' + str(rule['NumWild']) + ':' + str(rule['Replica']) + '\n')
	
	foundInTransitParentPairs = self.childToRuleInList(rule, self.InTransitionRules)
	foundInTransitChildPair = self.parentToRuleInList(rule, self.InTransitionRules)
	Globals.RULESLOG.write('Transit Parent: \n')
	self.printRules(foundInTransitParentPairs)
	Globals.RULESLOG.write('Transit Child: \n')
	self.printRules(foundInTransitChildPair)

	# Part of a Big list
	if foundInTransitParentPairs != []:
	    if len(foundInTransitParentPairs) > 1:
		Globals.log.info('Warning! Shouldnt be more than one parent')

	    parent = foundInTransitParentPairs[0]
	    for i in range(0, len(parent['OldRuleList'])):
		if parent['OldRuleList'][i]['IP'] == rule['IP']:
		    self.deleteRule(parent['OldRuleList'][i])
		    parent['OldRuleList'].remove(parent['OldRuleList'][i])
		    rule['Replica'] = parent['NewRule']['Replica']
		    parent['OldRuleList'].append(rule)
		    self.installPermRule(rule)
	    
	    done = True
	    for i in range(0, len(parent['OldRuleList'])):
		if parent['OldRuleList'][i]['Replica'] != parent['NewRule']['Replica']:
		    done = False

	    if done == True:
		if len(parent['OldRuleList']) == 1:
		    self.InTransitionRules.remove(parent)
		    self.InstalledRules.append({'NewRule': parent['NewRule'], 'OldRuleList': []})
		else:
		    for i in range(0, len(parent['OldRuleList'])):
		        self.deleteRule(parent['OldRuleList'][i])
		    self.InTransitionRules.remove(parent)
		    self.installPermRule(parent['NewRule'])
		    self.InstalledRules.append({'NewRule': parent['NewRule'], 'OldRuleList': []})		    

	# Broken into smaller pieces 
	elif foundInTransitChildPair != []:
	    for i in range(0, len(foundInTransitChildPair)):
		child = foundInTransitChildPair[i]
		self.InTransitionRules.remove(child)
		for j in range(0, len(child['OldRuleList'])):
		    childRule = child['OldRuleList'][j]
		    self.deleteRule(childRule)

		rule = {'NewRule': child['NewRule'], 'OldRuleList': []}
		self.InstalledRules.append(rule)
		self.installPermRule(rule['NewRule'])
	   
        Globals.RULESLOG.write('*** Installed Rules: \n')
      	self.printRules(self.InstalledRules)
        Globals.RULESLOG.write('*** InTransition Rules: \n')
        self.printRules(self.InTransitionRules)
	Globals.RULESLOG.flush()
Exemplo n.º 13
0
def install_replica_flow(flow, idle_timeout, hard_timeout, actions, bufid, priority, inport, packet, replicaNum, rewriteActions):
    switchNum = findReplicasSwitch(replicaNum)
    orderMultipaths = getMultipaths(switchNum)
    Globals.log.info("Order Multipaths")
    Globals.log.info(str(orderMultipaths))
    for currNode in orderMultipaths:
        currSwitchNum = currNode['no']
	currMac = currNode['mac']
	if flow.has_key(NW_SRC_N_WILD):
	    flowList = getMultiFlow(flow, len(currNode['nexthops']))
            for i, miniFlow in enumerate(flowList):
                if switchNum == currSwitchNum:
		    nextHop = 0
      	            actions = setReplicaOutPort(rewriteActions, switchNum, currSwitchNum, nextHop, replicaNum)
                else:
	            nextHop = currNode['nexthops'][i % len(currNode['nexthops'])]
    	            actions = setReplicaOutPort(actions, switchNum, currSwitchNum, nextHop, replicaNum)
	        Globals.COMPONENT.install_datapath_flow(currMac, miniFlow, idle_timeout, hard_timeout, actions, bufid, priority, inport, packet)
	        Globals.RULESLOG.write(mac_to_str(currMac) + " Install Multipath @ " + str(currSwitchNum) + " to dest " + str(switchNum) + ' ' + ip_to_str(miniFlow[NW_SRC]) + '/' + str(miniFlow[NW_SRC_N_WILD]) + '\n')
	else:
	    if switchNum == currSwitchNum:
		nextHop = 0
		actions = setReplicaOutPort(rewriteActions, switchNum, currSwitchNum, nextHop, replicaNum)
	    else:
		nextHopIndex = random.randint(0, len(currNode['nexthops']) - 1)
		nextHop = currNode['nexthops'][nextHopIndex]
#		nextHop = Globals.FORWARDINGTABLE[switchNum][currSwitchNum]['prevhop']
		actions = setReplicaOutPort(actions, switchNum, currSwitchNum, nextHop, replicaNum)
	    Globals.COMPONENT.install_datapath_flow(currMac, flow, idle_timeout, hard_timeout, actions, bufid, priority, inport, packet)
	    Globals.RULESLOG.write(mac_to_str(currMac) + " Install Multipath @ " + str(currSwitchNum) + " to dest " + str(switchNum) + ' ' + ip_to_str(flow[NW_SRC]) + '\n')
    Globals.RULESLOG.write('Install Wildcard: ' + ip_to_str(flow[NW_SRC]) + '\n')
    def __build_fentry_db(self, ingress):
        flow = {"dl_type"       : None,
                "dl_src"        : None,
                "dl_dst"        : None,
                "dl_vlan"       : None,
                "dl_vlan_pcp"   : None,
                "nw_src"        : None,
                "nw_dst"        : None,
                "nw_proto"      : None,
                "in_port"       : None,
                "nw_src_n_wild" : None,
                "nw_dst_n_wild" : None,
                "tp_src"        : None,
                "tp_dst"        : None,
                }
        # update flow with not null received values
        for key in ingress:
            # conversions for mac_addr and nw_addr
            if (key == "dl_src") or (key == "dl_dst"):
                flow[key] = pkt_utils.mac_to_str(ingress[key])
            elif (key == "nw_src") or (key == "nw_dst"):
                flow[key] = pkt_utils.ip_to_str(ingress[key])
            else:
                flow[key] = ingress[key]

        return flow
Exemplo n.º 15
0
def install_microflow_flow(flow, idle_timeout, hard_timeout, actions, bufid, priority, inport, packet, switchMac, outport, rewriteActions):
    switchNum = findMacSwitch(switchMac)
    orderInstall = getAllPaths(switchNum)
#    Globals.log.info('Order of Install ' + str(orderInstall))
    for currSwitchNum in orderInstall:
        currMac = getMac(currSwitchNum)
	Globals.RULESLOG.write('Switch: ' + str(currSwitchNum) + '\n')
	if currMac == switchMac:
	    actions = setMicroflowOutPort(rewriteActions, switchNum, currSwitchNum, outport)
	else:
	    actions = setMicroflowOutPort(actions, switchNum, currSwitchNum, outport)
#	Globals.log.info('Install Microflow Flow: ' + str(flow) + ' at ' + str(currSwitchNum))
	Globals.COMPONENT.install_datapath_flow(currMac, flow, idle_timeout, hard_timeout, actions, bufid, priority, inport, packet)
    if flow.has_key(NW_SRC):
        Globals.RULESLOG.write('Install Microflow SRC: ' + ip_to_str(flow[NW_SRC]) + '\n')
    if flow.has_key(NW_DST):
        Globals.RULESLOG.write('Install Microflow DST: ' + ip_to_str(flow[NW_DST]) + '\n')
Exemplo n.º 16
0
def install_controller_flow(flow, idle_timeout, hard_timeout, actions, bufid, priority, inport, packet, replicaNum, rewriteActions):
    switchNum = findReplicasSwitch(replicaNum)
    orderInstall = getAllPaths(switchNum)
    for currSwitchNum in orderInstall:
        currMac = getMac(currSwitchNum)
#        Globals.log.info('Install Controller Flow: ' + str(flow) + ' at ' + str(currSwitchNum))
        Globals.COMPONENT.install_datapath_flow(currMac, flow, idle_timeout, hard_timeout, actions, bufid, priority, inport, packet)
    Globals.RULESLOG.write('Install Controller: ' + ip_to_str(flow[NW_SRC]) + str(flow[NW_SRC_N_WILD]) + '\n')
Exemplo n.º 17
0
def actionInstallMicroflow(packet, replica):
    Globals.INSTALLLOG.write("***Microflow " + ip_to_str(packet.next.srcip) +
                             " to replica " + str(replica) + '\n')
    for i in range(0, Globals.NUMREPLICAS):
        if Globals.REPLICAS[i]['no'] == replica:
            (flow, defaultActions, rewriteActions) = IPs.get_microflow_dstrule(
                packet, Globals.REPLICAS[i]['mac'], Globals.REPLICAS[i]['ip'],
                replica)
            Multipath.install_replica_flow(flow, Globals.SOFT_TIMEOUT,
                                           openflow.OFP_FLOW_PERMANENT,
                                           defaultActions, None,
                                           openflow.OFP_DEFAULT_PRIORITY + 10,
                                           0, None, replica, rewriteActions)
Exemplo n.º 18
0
def install_controller_flow(flow, idle_timeout, hard_timeout, actions, bufid,
                            priority, inport, packet, replicaNum,
                            rewriteActions):
    switchNum = findReplicasSwitch(replicaNum)
    orderInstall = getAllPaths(switchNum)
    for currSwitchNum in orderInstall:
        currMac = getMac(currSwitchNum)
        #        Globals.log.info('Install Controller Flow: ' + str(flow) + ' at ' + str(currSwitchNum))
        Globals.COMPONENT.install_datapath_flow(currMac, flow, idle_timeout,
                                                hard_timeout, actions, bufid,
                                                priority, inport, packet)
    Globals.RULESLOG.write('Install Controller: ' + ip_to_str(flow[NW_SRC]) +
                           str(flow[NW_SRC_N_WILD]) + '\n')
Exemplo n.º 19
0
    def pkt_in_handler(self, dp_id, inport, ofp_reason, total_frame_len, buffer_id, packet):
        attrs = util.extract_flow(packet)
        print "Pakcet in received "+str(inport)+ " " +packet_utils.ip_to_str(attrs['nw_dst'])
        # print attrs

        # print ("type:%s %s > %s  %s:%d > %s:%d "%(
        #         packet_utils.ethtype_to_str(attrs['dl_type']),
        #         packet_utils.mac_to_str(attrs['dl_src']),
        #         packet_utils.mac_to_str(attrs['dl_dst']),
        #         packet_utils.ip_to_str(attrs['nw_src']), attrs['tp_src'],
        #         packet_utils.ip_to_str(attrs['nw_dst']), attrs['tp_dst']
        #         ))
        return CONTINUE
    def packet_in_handler(self, dpid, inport, reason, length, bufid, packet):
        """ Handler for packet_in event """
        assert length is not None
        assert packet is not None
        # checks packet consistency
        if not packet.parsed:
            LOG.warning("Ignoring incomplete packet")
            return CONTINUE

        if packet.type == ethernet.LLDP_TYPE:
            LOG.debug("Ignoring received LLDP packet...")
            return CONTINUE

        # Handle ARP packets
        if packet.type == ethernet.ARP_TYPE:
            LOG.debug("Received ARP packet " + str(packet.find('arp')))
            if not dpid in self.switches:
                LOG.debug("Registering new switch %s" % str(dpid))
                self.switches[dpid] = {}

            self.__do_l2_learning(dpid, inport, packet)
            self.__forward_l2_packet(dpid, inport, packet, packet.arr, bufid)

        LOG.debug("dpid=%s, inport=%s, reason=%s, len=%s, bufid=%s, p=%s",
                  str(dpid), str(inport), str(reason), str(len),
                  str(bufid), str(packet))

        # switch over ethernet type
        if packet.type == ethernet.IP_TYPE:
            ip_addr = packet.find('ipv4')
            LOG.info("IPv4 packet: " + str(ip_addr))
            # XXX FIXME: Remove the following check in order to be generic...
            if ip_addr.protocol == ipv4.ICMP_PROTOCOL:
                self.__resolve_path(pkt_utils.ip_to_str(ip_addr.srcip),
                                    pkt_utils.ip_to_str(ip_addr.dstip),
                                    packet)

        return CONTINUE
    def start_poll_snmp_thread(self):
        lg.info("Starting gathering statistics... ")
        if len(threading.enumerate()) >= len(self.switchesIP):
            self.post_callback(self.SNMP_CHECK_PERIOD, lambda : snmp_stats.start_poll_snmp_thread(self))
            return

        for host in self.switchesIP:
            t = threading.Thread(target=self.poll_switch, args = (host,))
            t.start()
            print "Ended gathering for node ", ip_to_str(host)
        lg.info("Ended gathering statistics...")

        self.buildNetGraph()
        #reschedule the statistics gatheringTypeError: poll_switch() argument after * must be a sequence, not int  
        self.post_callback(self.SNMP_CHECK_PERIOD, lambda : snmp_stats.start_poll_snmp_thread(self))  
Exemplo n.º 22
0
    def packet_in_callback(self, dpid, inport, reason, len, bufid, packet):
        """Packet-in handler""" 
        if not packet.parsed:
            log.debug('Ignoring incomplete packet')
        else:
            if packet.type == packet.LLDP_TYPE:
                #ignoring lldp packet.
                pass
            #elif packet.find('ip'):
            else:
                
                try:
                    ip = ip_to_str(packet.next.dstip)
                except AttributeError:
                    return CONTINUE
                if ip == '10.0.2.254': print 'blaaaa' 
                if ip == me.multicast_ip:
                    
                    if not self.overmind.fix_switch(dpid):
                        event = packet.next.next.payload[0]
                        if event == ADD_HOST:
                            self.overmind.add_host(dpid,inport,mac_to_int(packet.src))
                        elif event == REM_HOST:
                            self.overmind.remove_host(dpid, mac_to_int(packet.src))
                        elif event == SOURCE_EVENT:
                            self.overmind.change_src(dpid, inport)
                        else:
                            print 'Unknown event, discarding packet'
                        
            #print 'Packet-in no router', dpid, '--Fonte:', mac_to_str(packet.src), '--Destino:', mac_to_str(packet.dst)
            #print 'In-Port:', inport
            pass

        """if self.im == None:
            #self.im = InstallationManager(self.topology)
            self.im.nox = self
            #self.im.samples_number = 10
            self.im.collect_begin_installs()
            self.install_routes()
            self.im.collect_end_installs()
            self.im.start()     
 #       else:
 #           self.install_routes()
        """

        return CONTINUE
Exemplo n.º 23
0
def delete_flow(flow, replicaNum):
    switchNum = findReplicasSwitch(replicaNum)
    deleteMultipaths = getMultipaths(switchNum)
    for currNode in deleteMultipaths:
        currSwitchNum = currNode['no']
        currMac = currNode['mac']
        flowList = getMultiFlow(flow, len(currNode['nexthops']))
        for i, miniFlow in enumerate(flowList):
            Globals.COMPONENT.delete_strict_datapath_flow(currMac, miniFlow)
	    if not flow.has_key(NW_SRC_N_WILD):
	        Globals.RULESLOG.write(mac_to_str(currMac) + " Delete Multipath @ " + str(currSwitchNum) + " to dest " + str(switchNum) + ' ' + ip_to_str(flow[NW_SRC]) + '\n')
	    else:
	        Globals.RULESLOG.write(mac_to_str(currMac) + " Delete Multipath @ " + str(currSwitchNum) + " to dest " + str(switchNum) + ' ' + ip_to_str(flow[NW_SRC]) + '/' + str(flow[NW_SRC_N_WILD]) + '\n')

#    orderDelete = getAllPaths(switchNum)
#    for switch in orderDelete:
#        currMac = getMac(switch)
#        Globals.log.info('Delete Flow: ' + str(flow) + ' at ' + str(switch))
#        Globals.COMPONENT.delete_strict_datapath_flow(currMac, flow)
    Globals.RULESLOG.write('Delete: ' + ip_to_str(flow[NW_SRC]) + '/' + str(flow[NW_SRC_N_WILD]) + '\n')
Exemplo n.º 24
0
def actionInstallMicroflow(packet, replica):
    Globals.INSTALLLOG.write("***Microflow " + ip_to_str(packet.next.srcip) + " to replica " + str(replica) + '\n')
    for i in range(0, Globals.NUMREPLICAS):
        if Globals.REPLICAS[i]['no'] == replica:
            (flow, defaultActions, rewriteActions) = IPs.get_microflow_dstrule(packet, Globals.REPLICAS[i]['mac'], Globals.REPLICAS[i]['ip'], replica)
	    Multipath.install_replica_flow(flow, Globals.SOFT_TIMEOUT, openflow.OFP_FLOW_PERMANENT, defaultActions, None, openflow.OFP_DEFAULT_PRIORITY + 10, 0, None, replica, rewriteActions)
Exemplo n.º 25
0
 def ruleToString(self, rule):
     return 'IP: ' + ip_to_str(rule['IP']) + ' NumWild: ' + str(rule['NumWild']) + ' Replica: ' + str(rule['Replica'])
Exemplo n.º 26
0
 def pkt_in_handler(self, dp_id, inport, ofp_reason, total_frame_len, buffer_id, packet):
     attrs = util.extract_flow(packet)
     print "Pakcet in received "+str(inport)+ " " +packet_utils.ip_to_str(attrs['nw_dst'])
     return CONTINUE
Exemplo n.º 27
0
 def ruleToString(self, rule):
     return 'IP: ' + ip_to_str(rule['IP']) + ' NumWild: ' + str(
         rule['NumWild']) + ' Replica: ' + str(rule['Replica'])
Exemplo n.º 28
0
	def learn_and_forward(self, dpid, inport, packet, buf, bufid):
		"""Learn MAC src port mapping, then flood or send unicast."""
		ip_header = packet.find('ipv4')
		idle_timeout = 600
		hard_timeout = 3600
		attrs = extract_flow(packet)
		attrs[core.IN_PORT] = inport
		attrs[core.DL_DST] = packet.dst
		if dpid == 1:
		# policies for switch 1
			if ip_header is not None:
				ipstr = ip_to_str(ip_header.dstip)
				if ipstr == "10.0.0.4":
					outport = 1
					actions = [[openflow.OFPAT_OUTPUT, [0, outport]]]
					self.send_openflow(dpid, bufid, buf, actions, inport)
					#self.install_datapath_flow(dpid, attrs, idle_timeout, hard_timeout, actions, bufid, openflow.OFP_DEFAULT_PRIORITY, inport, buf)
				elif ipstr == "10.0.0.5":
					outport = 2
					actions = [[openflow.OFPAT_OUTPUT, [0, outport]]]
					self.send_openflow(dpid, bufid, buf, actions, inport)
					#self.install_datapath_flow(dpid, attrs, idle_timeout, hard_timeout, actions, bufid, openflow.OFP_DEFAULT_PRIORITY, inport, buf)	
				elif ipstr == "10.0.0.6":
					outport = 3
					actions = [[openflow.OFPAT_OUTPUT, [0, outport]]]
					self.send_openflow(dpid, bufid, buf, actions, inport)
					#self.install_datapath_flow(dpid, attrs, idle_timeout, hard_timeout, actions, bufid, openflow.OFP_DEFAULT_PRIORITY, inport, buf)
				elif ipstr == "10.0.0.7":
					outport = 4
					actions = [[openflow.OFPAT_OUTPUT, [0, outport]]]
					self.send_openflow(dpid, bufid, buf, actions, inport)
					#self.install_datapath_flow(dpid, attrs, idle_timeout, hard_timeout, actions, bufid, openflow.OFP_DEFAULT_PRIORITY, inport, buf)
			else:
				if mac_to_int(packet.src) == 4:
					outport = [2,3]
					actions = [[openflow.OFPAT_OUTPUT, [0, 2]],[openflow.OFPAT_OUTPUT, [0, 3]]]
				elif mac_to_int(packet.src) == 5:
					outport = [1,3]
					actions = [[openflow.OFPAT_OUTPUT, [0, 1]],[openflow.OFPAT_OUTPUT, [0, 3]]]
				else: 			
					outport = [1,2]
					actions = [[openflow.OFPAT_OUTPUT, [0, 1]],[openflow.OFPAT_OUTPUT, [0, 2]]]	
				self.send_openflow(dpid, bufid, buf, actions, inport)

		if dpid == 2:
		# policies for switch 2
			if mac_to_int(packet.src) == 7:
				if ip_header is not None:
					ipstr = ip_to_str(ip_header.dstip)
					if ipstr == "10.0.0.4" or ipstr == "10.0.0.5":	
						outport = 1
						actions = [[openflow.OFPAT_OUTPUT, [0, outport]]]
						self.send_openflow(dpid, bufid, buf, actions, inport)
						#self.install_datapath_flow(dpid, attrs, idle_timeout, hard_timeout, actions, bufid, openflow.OFP_DEFAULT_PRIORITY, inport, buf)
					elif ipstr == "10.0.0.6":
						outport = 3
						actions = [[openflow.OFPAT_OUTPUT, [0, outport]]]
						self.send_openflow(dpid, bufid, buf, actions, inport)
						#self.install_datapath_flow(dpid, attrs, idle_timeout, hard_timeout, actions, bufid, openflow.OFP_DEFAULT_PRIORITY, inport, buf)
				else:
					actions = [[openflow.OFPAT_OUTPUT, [0, 1]], [openflow.OFPAT_OUTPUT, [0, 3]]]
					outport = [1,3]
					self.send_openflow(dpid, bufid, buf, actions, inport)

			else:
				if ip_header is not None:
					ipstr = ip_to_str(ip_header.dstip)
					if ipstr == "10.0.0.4" or ipstr == "10.0.0.5":	
						outport = 1
						actions = [[openflow.OFPAT_OUTPUT, [0, outport]]]
						self.send_openflow(dpid, bufid, buf, actions, inport)
						#self.install_datapath_flow(dpid, attrs, idle_timeout, hard_timeout, actions, bufid, openflow.OFP_DEFAULT_PRIORITY, inport, buf)
					elif ipstr == "10.0.0.6":
						outport = 3
						actions = [[openflow.OFPAT_OUTPUT, [0, outport]]]
						self.send_openflow(dpid, bufid, buf, actions, inport)
						#self.install_datapath_flow(dpid, attrs, idle_timeout, hard_timeout, actions, bufid, openflow.OFP_DEFAULT_PRIORITY, inport, buf)
					elif ipstr == "10.0.0.7":
						outport = 4
						actions = [[openflow.OFPAT_OUTPUT, [0, outport]]]
						self.send_openflow(dpid, bufid, buf, actions, inport)
						#self.install_datapath_flow(dpid, attrs, idle_timeout, hard_timeout, actions, bufid, openflow.OFP_DEFAULT_PRIORITY, inport, buf)
				else:
					if mac_to_int(packet.src) == 4 or mac_to_int(packet.src) == 5: 
						actions = [[openflow.OFPAT_OUTPUT, [0, 3]], [openflow.OFPAT_OUTPUT, [0, 4]]]
						outport = [3,4]
					elif mac_to_int(packet.src) == 6:
						actions = [[openflow.OFPAT_OUTPUT, [0, 1]], [openflow.OFPAT_OUTPUT, [0, 4]]]	
						outport = [1,4]
					self.send_openflow(dpid, bufid, buf, actions, inport)
				
		if dpid == 3:
		# policies for switch 3
			ipstr = ip_to_str(ip_header.dstip)
			if ipstr == "10.0.0.4" or ipstr == "10.0.0.5":	
				outport = 2
				actions = [[openflow.OFPAT_OUTPUT, [0, outport]]]
				self.send_openflow(dpid, bufid, buf, actions, inport)
				#self.install_datapath_flow(dpid, attrs, idle_timeout, hard_timeout, actions, bufid, openflow.OFP_DEFAULT_PRIORITY, inport, buf)
			else:
				outport = 1
				actions = [[openflow.OFPAT_OUTPUT, [0, outport]]]
				self.send_openflow(dpid, bufid, buf, actions, inport)
				#self.install_datapath_flow(dpid, attrs, idle_timeout, hard_timeout, actions, bufid, openflow.OFP_DEFAULT_PRIORITY, inport, buf)
		
		message = " packet to host " + str(mac_to_int(packet.dst)) + " from host " + str(mac_to_int(packet.src)) + " go to port " + str(outport) + " of switch " + str(dpid)
		log.info(message)		
def ip_to_str_reversed( ipToConvert ):
    ipSplitted = ip_to_str(ipToConvert).split(".")
    ip =  ipSplitted[3]+"."+  ipSplitted[2]+"."+ipSplitted[1]+"."+ipSplitted[0]
    return ip        
    def poll_switch(self,host):
        lg.info("IP: "+ip_to_str(host))
                   
        cmdGen = cmdgen.CommandGenerator()
        lg.info("IP 2: "+ip_to_str(host))       
        mibBuilder = cmdGen.snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder
        #print str(mibBuilder.getMibSources())

        mibSources = mibBuilder.getMibSources() + (
                builder.DirMibSource('/hosthome/OF/controller_utils/pymib'),
                )

        mibBuilder.setMibSources(*mibSources)
        mibBuilder.loadModules('ETHTOOL-MIB',)
        #print builder.MibBuilder().getMibPath()

        lg.info("Probing IP: "+ip_to_str_reversed(host))

        errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd(
                    cmdgen.CommunityData('public'),
                    cmdgen.UdpTransportTarget((ip_to_str_reversed(host), 161)),
                    #cmdgen.MibVariable('SNMPv2-MIB', 'sysDescr', 0),
                    (1,3,6,1,4,1,39178,100,1,1),
                    #(1,3,6,1,2,1,31,1,1,1,1),
                    lookupNames=True, lookupValues=True,
                )

        # Check for errors and print out results
        if errorIndication:
            print(errorIndication)
            return
        if errorStatus:
            print(errorStatus)
            return

        oldId="-1"
        switchStats ={}
        oldStats ={}
        if self.totalStats.has_key(ip_to_str_reversed(host)) :
            oldStats = deepcopy(self.totalStats[ip_to_str_reversed(host)])

        self.totalStats[ip_to_str_reversed(host)]=switchStats
        for varBindTableRow in varBindTable:
            for name, val in varBindTableRow:
                print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))        
                statPrettified = name.prettyPrint().replace("ETHTOOL-MIB::ethtoolStat.\"","")
                #this is a progressive number starting from 1 given by the snmpwalk on the oid
                idStat = statPrettified[:statPrettified.find(".")].replace("\"","")
                statPrettified = name.prettyPrint().replace("ETHTOOL-MIB::ethtoolStat.\"" + idStat + 
                                                            "\".\"","").replace("\"","")
                #here there will be the name of the stat
                print (statPrettified)
                                        
                if oldId != idStat:         
                    #if i received stat for a new interface i have to initialize the dictionary
                    switchStats[idStat]= {} 
                    oldId = idStat                                                     

                if (statPrettified != "rxbytes" and statPrettified != "ts_milliseconds" and
                    statPrettified != "ts_openflow" and statPrettified != "txbytes" and
                    statPrettified != "ts_seconds"): #if is the ifName

                    switchStats[idStat]["ifName"]= statPrettified #store the name of the iface
                else:
                    #store the stat if it's not the ifname
                    switchStats[idStat][statPrettified]= long(val.prettyPrint()) 

                if statPrettified == "txbytes":
                    if (switchStats.has_key(idStat) and 
                        oldStats.has_key(idStat) and
                        oldStats[idStat].has_key("ts_openflow") and 
                        ((switchStats[idStat]["ts_openflow"] -
                          oldStats[idStat]["ts_openflow"])/1000000)>0):

                        print switchStats[idStat]["ifName"]
                        #print "Elapsed Time on: "+ip_to_str_reversed(host)+" : "+str((switchStats[idStat]["ts_openflow"]-oldStats[idStat]["ts_openflow"]))
                        switchStats[idStat]["txavg"] = ((switchStats[idStat]["txbytes"] -
                                                         oldStats[idStat]["txbytes"]) /
                                                         ((switchStats[idStat]["ts_openflow"] -
                                                         oldStats[idStat]["ts_openflow"])/1000000))
                        #print switchStats[idStat]["txavg"]

                        switchStats[idStat]["rxavg"] = ((switchStats[idStat]["rxbytes"] -
                                                         oldStats[idStat]["rxbytes"]) /
                                                         ((switchStats[idStat]["ts_openflow"] -
                                                         oldStats[idStat]["ts_openflow"])/1000000))
                        #print switchStats[idStat]["rxavg"]
                    else:
                        switchStats[idStat]["txavg"] = 0
                        switchStats[idStat]["rxavg"] = 0
Exemplo n.º 31
0
    def hardTimeoutExpiration(self):
        rule = self.TimeoutQueue.pop()
        Globals.RULESLOG.write(
            '\n-------------------------------\nHARD TIMEOUT!!!\n')
        Globals.RULESLOG.write('Timeout Rule: ' + ip_to_str(rule['IP']) + ':' +
                               str(rule['NumWild']) + ':' +
                               str(rule['Replica']) + '\n')

        foundInTransitParentPairs = self.childToRuleInList(
            rule, self.InTransitionRules)
        foundInTransitChildPair = self.parentToRuleInList(
            rule, self.InTransitionRules)
        Globals.RULESLOG.write('Transit Parent: \n')
        self.printRules(foundInTransitParentPairs)
        Globals.RULESLOG.write('Transit Child: \n')
        self.printRules(foundInTransitChildPair)

        # Part of a Big list
        if foundInTransitParentPairs != []:
            if len(foundInTransitParentPairs) > 1:
                Globals.log.info('Warning! Shouldnt be more than one parent')

            parent = foundInTransitParentPairs[0]
            for i in range(0, len(parent['OldRuleList'])):
                if parent['OldRuleList'][i]['IP'] == rule['IP']:
                    self.deleteRule(parent['OldRuleList'][i])
                    parent['OldRuleList'].remove(parent['OldRuleList'][i])
                    rule['Replica'] = parent['NewRule']['Replica']
                    parent['OldRuleList'].append(rule)
                    self.installPermRule(rule)

            done = True
            for i in range(0, len(parent['OldRuleList'])):
                if parent['OldRuleList'][i]['Replica'] != parent['NewRule'][
                        'Replica']:
                    done = False

            if done == True:
                if len(parent['OldRuleList']) == 1:
                    self.InTransitionRules.remove(parent)
                    self.InstalledRules.append({
                        'NewRule': parent['NewRule'],
                        'OldRuleList': []
                    })
                else:
                    for i in range(0, len(parent['OldRuleList'])):
                        self.deleteRule(parent['OldRuleList'][i])
                    self.InTransitionRules.remove(parent)
                    self.installPermRule(parent['NewRule'])
                    self.InstalledRules.append({
                        'NewRule': parent['NewRule'],
                        'OldRuleList': []
                    })

        # Broken into smaller pieces
        elif foundInTransitChildPair != []:
            for i in range(0, len(foundInTransitChildPair)):
                child = foundInTransitChildPair[i]
                self.InTransitionRules.remove(child)
                for j in range(0, len(child['OldRuleList'])):
                    childRule = child['OldRuleList'][j]
                    self.deleteRule(childRule)

                rule = {'NewRule': child['NewRule'], 'OldRuleList': []}
                self.InstalledRules.append(rule)
                self.installPermRule(rule['NewRule'])

        Globals.RULESLOG.write('*** Installed Rules: \n')
        self.printRules(self.InstalledRules)
        Globals.RULESLOG.write('*** InTransition Rules: \n')
        self.printRules(self.InTransitionRules)
        Globals.RULESLOG.flush()
Exemplo n.º 32
0
    def process_packet(self, dpid, inport, packet, buf, bufid):
        """Learn MAC src port mapping, then flood or send unicast."""

        if (packet.type == ethernet.ARP_TYPE):

            # ARP packets are just kind of a hack since they aren't part of
            # our research.  They all get sent to the controller, who looks
            # at the desination IP and sends them the right way.
            arphdr = packet.next
            if (arphdr.prototype != arp.PROTO_TYPE_IP):
                return

            log.debug("GOT ARP PACKET AT DPID " + str(dpid))

            host = ip_to_str(arphdr.protodst)
            dst_node = self.g.getNodeFromClientIP(host)

            log.debug("HOST IS " + str(host) + ", dst_node is " +
                      str(dst_node))

            # Send it on to the host.
            if (dst_node == dpid):
                log.debug("SENDING TO HOST DIRECTLY")
                self.send_openflow(dpid, bufid, buf, self.portmap[dpid][host],
                                   inport)

            # Send it to the right router.
            else:
                log.debug("SENDING TO NODE " +
                          str(self.g.getNextHop(dpid, dst_node)))
                self.send_openflow(
                    dpid, bufid, buf,
                    self.portmap[dpid][self.g.getNextHop(dpid,
                                                         dst_node)], inport)

            return

        elif (packet.type == ethernet.IP_TYPE):
            iphdr = packet.next

            # Look for LEQ registration requests from services.
            if (iphdr.protocol == ipv4.UDP_PROTOCOL):
                udphdr = iphdr.next
                if (udphdr.dstport == 37823):
                    if (udphdr.len != 20):
                        return
                    request = udphdr.payload
                    log.debug("FOUND LEQ REQUEST, REGISTERING")
                    fmt = struct.Struct('! I H H H H')
                    unpacked = fmt.unpack(request)
                    alpha = float(unpacked[3]) / 100
                    x = float(unpacked[4]) / 100

                    log.debug("ALPHA IS " + str(alpha) + ", X IS " + str(x))

                    new_service = LEQ_service(
                        self.next_LEQ_id, unpacked[0], unpacked[1],
                        unpacked[2],
                        self.g.getNodeFromClientIP(ip_to_str(unpacked[0])))
                    self.next_LEQ_id += 1

                    if (new_service.protocol != 6
                            and new_service.protocol != 17):
                        return

                    # Make sure we don't already have this service.
                    for service in self.reg_LEQ_services:
                        if (new_service.ip == service.ip
                                and new_service.protocol == service.protocol
                                and new_service.port == service.port):
                            log.debug("SERVICE IS A DUPLICATE")
                            return

                    # Add the new service to the list.
                    self.reg_LEQ_services.append(new_service)

                    for service in self.reg_LEQ_services:
                        log.debug(
                            str(service.ip) + ', ' + str(service.protocol) +
                            ', ' + str(service.port))

                    # And register with the LEQ algorithm itself.
                    self.eq.registerService(service.dpid, service.id, alpha, x)

                    # Insert flow rules for each switch: whenever a new client tries
                    # to talk to a LEQ service (or vice versa), we will send the packet
                    # to the controller to perform latency equalized routing.
                    actions = [[
                        openflow.OFPAT_OUTPUT, [0, openflow.OFPP_CONTROLLER]
                    ]]

                    flow1 = {}
                    flow1[core.DL_TYPE] = ethernet.IP_TYPE
                    flow1[core.NW_PROTO] = new_service.protocol
                    flow1[NW_DST] = new_service.ip
                    flow1[TP_DST] = new_service.port

                    flow2 = {}
                    flow2[core.DL_TYPE] = ethernet.IP_TYPE
                    flow2[core.NW_PROTO] = new_service.protocol
                    flow2[NW_SRC] = new_service.ip
                    flow2[TP_SRC] = new_service.port

                    for router_id in self.routers:
                        self.install_datapath_flow(router_id,
                                                   flow1,
                                                   openflow.OFP_FLOW_PERMANENT,
                                                   openflow.OFP_FLOW_PERMANENT,
                                                   actions,
                                                   priority=0x8000)
                        self.install_datapath_flow(router_id,
                                                   flow2,
                                                   openflow.OFP_FLOW_PERMANENT,
                                                   openflow.OFP_FLOW_PERMANENT,
                                                   actions,
                                                   priority=0x8000)

                    return

            # Check if this is a packet associated with a LEQ service that is going
            # to or from a new client.
            if (iphdr.protocol == ipv4.UDP_PROTOCOL
                    or iphdr.protocol == ipv4.TCP_PROTOCOL):

                if (iphdr.protocol == ipv4.UDP_PROTOCOL):
                    sport = iphdr.next.srcport
                    dport = iphdr.next.dstport

                # The TCP case seemed to have some weird bug, perhaps in parsing, so we
                # need to get the data ourselves.
                elif (iphdr.protocol == ipv4.TCP_PROTOCOL):
                    dlen = len(iphdr.arr)
                    length = iphdr.iplen
                    if length > dlen:
                        length = dlen
                    tcphdr = tcp(arr=iphdr.arr[iphdr.hl * 4:length],
                                 prev=iphdr)
                    sport = tcphdr.srcport
                    dport = tcphdr.dstport

                log.debug("CHECKING UDP OR TCP PACKET")
                log.debug("srcip: " + str(iphdr.srcip) + ", srcport: " +
                          str(sport) + ", protocol: " + str(iphdr.protocol))
                log.debug("dstip: " + str(iphdr.dstip) + ", dstport: " +
                          str(dport) + ", protocol: " + str(iphdr.protocol))

                serv = None

                for service in self.reg_LEQ_services:
                    if (iphdr.srcip == service.ip
                            and iphdr.protocol == service.protocol
                            and sport == service.port):
                        log.debug("GOT PACKET FROM SERVICE")
                        serv = service
                        client_ip = ip_to_str(iphdr.dstip)
                        client_port = dport
                        is_to_service = False
                        break

                    elif (iphdr.dstip == service.ip
                          and iphdr.protocol == service.protocol
                          and dport == service.port):
                        log.debug("GOT PACKET TO SERVICE")
                        serv = service
                        client_ip = ip_to_str(iphdr.srcip)
                        client_port = sport
                        is_to_service = True
                        break

                if serv is None:
                    return

                if client_ip in serv.clients:
                    return

                # This is a legit new client, so add it to the service's list and
                # compute the new paths.
                log.debug("client: " + str(client_ip) + ", serv " +
                          str(serv.ip))
                serv.clients.append(client_ip)
                self.eq.addClients(serv.dpid, serv.id,
                                   [self.g.getNodeFromClientIP(client_ip)])
                changed_clients = self.eq.getUpdatedClients(serv.dpid, serv.id)

                log.debug("PATHS: " + str(self.eq.paths))

                # Add flow rules for the new paths.
                toserv_flow = {}
                toserv_flow[core.DL_TYPE] = ethernet.IP_TYPE
                toserv_flow[core.NW_PROTO] = serv.protocol
                toserv_flow[core.NW_DST] = serv.ip
                toserv_flow[core.TP_DST] = serv.port

                fromserv_flow = {}
                fromserv_flow[core.DL_TYPE] = ethernet.IP_TYPE
                fromserv_flow[core.NW_PROTO] = serv.protocol
                fromserv_flow[core.NW_SRC] = serv.ip
                fromserv_flow[core.TP_SRC] = serv.port

                for client in serv.clients:
                    client_node = self.g.getNodeFromClientIP(client)

                    # Skip clients whose path has not changed.
                    if (not (client_node in changed_clients)):
                        log.debug("Skipping client " + str(client) +
                                  " due to no change.")
                        continue

                    path = self.eq.paths[(serv.dpid, serv.id)][client_node]
                    log.debug(str(path))
                    for i in range(len(path)):
                        log.debug("path[" + str(i) + "]: " + str(path[i]))

                        # Install the client -> server rule.
                        toserv_flow[core.NW_SRC] = client

                        # to do inport, I need to set different actionsbased on the inport
                        # doesn't look like I can actually use the inport to match. only
                        # so that we don't broadcast to it when we need to

                        if (i == len(path) - 1):
                            outport = self.portmap[path[i]][ip_to_str(serv.ip)]
                            actions = [[openflow.OFPAT_OUTPUT, [0, outport]]]
                            log.debug("toserv port is " + str(outport))
                        else:
                            outport = self.portmap[path[i]][path[i + 1]]
                            actions = [[openflow.OFPAT_OUTPUT, [0, outport]]]
                            log.debug("toserv port is " + str(outport))

                        self.install_datapath_flow(path[i],
                                                   toserv_flow,
                                                   openflow.OFP_FLOW_PERMANENT,
                                                   openflow.OFP_FLOW_PERMANENT,
                                                   actions,
                                                   priority=0x9000)

                        if (client_ip == client and path[i] == dpid
                                and is_to_service == True):
                            cur_outport = outport

                        # Install the server -> client rule.
                        fromserv_flow[core.NW_DST] = client

                        if (i == 0):
                            outport = self.portmap[path[i]][client]
                            actions = [[openflow.OFPAT_OUTPUT, [0, outport]]]
                            log.debug("fromserv port is " + str(outport))
                        else:
                            outport = self.portmap[path[i]][path[i - 1]]
                            actions = [[openflow.OFPAT_OUTPUT, [0, outport]]]
                            log.debug("fromserv port is " + str(outport))

                        self.install_datapath_flow(path[i],
                                                   fromserv_flow,
                                                   openflow.OFP_FLOW_PERMANENT,
                                                   openflow.OFP_FLOW_PERMANENT,
                                                   actions,
                                                   priority=0x9000)

                        if (client_ip == client and path[i] == dpid
                                and is_to_service == False):
                            cur_outport = outport

                # Finally, send the actual packet out.
                self.send_openflow(dpid, bufid, buf, cur_outport, inport)
Exemplo n.º 33
0
    def learn_and_forward(self, dpid, inport, packet, buf, bufid):
	# Flood

	# Find MAC + IP from header
	srcMACaddr = packet.src.tostring()
	ippkt = self.get_ippacket(packet)
	srcIPaddr = '0.0.0.0'
	if (ippkt != None):
	    srcIPaddr = ip_to_str(ippkt.srcip)

	# Does the source MAC + IP need to be learned?
	if (self.mac_to_port.has_key(srcMACaddr)):
	    dstMACaddr = self.mac_to_port[srcMACaddr]
	    if dstMACaddr[0] != inport:
		logger.info('MAC moved from ' + str(dst) + ' to ' + str(inport))
	    elif (dstMACaddr[1] == '0.0.0.0') and (srcIPaddr != None):
		logger.info('IP update')
		self.mac_to_port[srcMACaddr] = (inport, srcIPaddr)
	# If not, update table entry
        else:
	    logger.info('MAC learned ' + mac_to_str(packet.src) + ' on %d %d' % (dpid, inport))
  	    self.mac_to_port[srcMACaddr] = (inport, srcIPaddr)

	# Have we already learned destination MAC + IP?
	dstMACaddr = packet.dst.tostring()
	dstIPaddr = None
	if (ippkt != None):
	    dstIPaddr = ip_to_str(ippkt.dstip)

	logger.info('Sending to destination')

        # Is this server address?
	if ((dstIPaddr != None) and (dstIPaddr == "10.0.0.0")):
	    logger.info('SPECIAL FORWARDING IP\n')
	    for item in self.mac_to_port.items():
		logger.info(str(item) + "\n")
		if (item[1] == "10.0.0.2"):
		    logger.info('Found 10.0.0.2 and sending packet\n');
		    self.send_openflow(dpid, bufid, buf, item[0], inport)
	    	#prt = self.mac_to_port[dstMACaddr] # CHANGE
	    	#self.send_openflow(dpid, bufid, buf, prt[0] ,inport)

	# HARDCODED
	if (isinstance(packet.next, arp.arp) and (ip_to_str(packet.next.protodst) ==  "10.0.0.0")):
            logger.info('SPECIAL FORWARDING ARP\n')
            for item in self.mac_to_port.items():
                logger.info(str(item) + ": " + str(item[1][1]) + "\n")
                if (str(item[1][1]) == '10.0.0.2'):
                    logger.info('Found 10.0.0.2 and sending packet\n');
                    #self.send_openflow(dpid, bufid, buf, item[1][0], inport)

            	    # Install Flow Rule
                    #flow = extract_flow(packet)
                    #flow[core.IN_PORT] = inport
		    #flow = {}
		    #flow[DL_TYPE] = 0x0800
		    #flow[NW_PROTO] = 17
		    #flow[NW_DST] = ippkt.srcip
		    #flow[NW_DST_N_WILD] = 31

                    #actions = [[openflow.OFPAT_OUTPUT, [0, item[1][0]]]]
                    #CACHE_TIMEOUT = 100
                    #self.install_datapath_flow(dpid, flow, CACHE_TIMEOUT,
                    #                   openflow.OFP_FLOW_PERMANENT, actions,
                    #                   bufid, openflow.OFP_DEFAULT_PRIORITY,
                    #                   inport, buf)




	# Otherwise forward appropriately
	elif (self.mac_to_port.has_key(dstMACaddr)):
	    prt = self.mac_to_port[dstMACaddr]
	    #self.send_openflow(dpid, bufid, buf, prt[0] ,inport)

	# If we have not then flood
	else:
	    self.send_openflow(dpid, bufid, buf, openflow.OFPP_FLOOD, inport)

            # Install Flow Rule
            #flow = extract_flow(packet)
            #flow[core.IN_PORT] = inport
            flow = {}
            #flow[DL_TYPE] = 0x0800
            #flow[NW_PROTO] = 17
            #flow[NW_DST] = 
            flow[NW_DST_N_WILD] = 32

            actions = [[openflow.OFPAT_OUTPUT, [0, 1]]]
            CACHE_TIMEOUT = 100
            self.install_datapath_flow(dpid, flow, CACHE_TIMEOUT,
                                       openflow.OFP_FLOW_PERMANENT, actions,
                                       bufid, openflow.OFP_DEFAULT_PRIORITY,
                                       inport, buf)