Exemple #1
0
  def _handle_ConnectionUp (self, event):
	""" On datapath join, create a new LLDP packet per port """
	assert event.dpid not in self._dps

	if self.install_flow:
	  log.debug("Installing flow for %s (%d)", dpidToStr(event.dpid), event.dpid)
	  msg = of.ofp_flow_mod(match = of.ofp_match( dl_type = ethernet.LLDP_TYPE, dl_dst = NDP_MULTICAST))
	  msg.actions.append(of.ofp_action_output(port = of.OFPP_CONTROLLER))								# LC: send to the controller, when it get a LLDP msg
	  event.connection.send(msg) 

	self._dps.add(event.dpid)											# LC: keep track of the sw that install the flows
	
	# LC : printing port information
	premapping = "/tmp/"
	f = open(premapping + "sw-ports.txt", "a")
	print " For ports:"
	for p in event.ofp.ports:
		print "%s %s %s " % (dpidToStr(event.dpid), p.port_no, p.hw_addr)
		print >>f, "%s,%d,%s" % (dpidToStr(event.dpid), p.port_no, p.hw_addr)
	f.close()
	
	#LC: Collecting network topology
	for p in event.ofp.ports:
		info = Discovery.Sinfo(event.dpid, p.port_no, p.hw_addr)
		if info not in self.swinfo:
			self.swinfo[info] = time.time()
		
	#LC: To the sender 'LLDPSender()' add the SW, parsing the dpid and the ports
	#LC: def addSwitch (self, dpid, ports):
	self._sender.addSwitch(event.dpid, [(p.port_no, p.hw_addr)
										for p in event.ofp.ports])
def _handle_FlowStatsReceived(event):
  stats = flow_stats_to_list(event.stats)
  #log.debug("FlowStatsReceived from %s: %s", dpidToStr(event.connection.dpid), stats)
  log.debug("FlowStatsReceived from %s", dpidToStr(self.connection.dpid))
  
  for f in event.stats:

    if tainted_hosts.has_key(str(f.match.dl_src)) or str(f.match.dl_src) in protected_resources:
      print('***** storing statstics ******')
      bytes_count = 0
      flows_count = 0
      packets_count = 0
      dst = str(f.match.dl_dst)
      src = str(f.match.dl_src)
      bytes_count += f.byte_count
      packets_count += f.packet_count
      flows_count += 1

      if src in protected_resources:
        data_recvd_from_protected[dst] = bytes_count

      if not tracked_flows.has_key(src + '-' + dst):
        tracked_flows[src + '-' + dst] = [0,0,0]

      (tracked_flows.get(src + '-' + dst))[0] = bytes_count
      (tracked_flows.get(src + '-' + dst))[1] = packets_count
      (tracked_flows.get(src + '-' + dst))[2] = flows_count
      log.debug("traffic switch %s: %s bytes %s packets  %s flows", dpidToStr(event.connection.dpid), bytes_count, packets_count, flows_count)
Exemple #3
0
def _handle_portstats_received (event):
  stats = flow_stats_to_list(event.stats)
  
  ports_dpid = {}
  ports_list = []

  for p in stats:

    ports = {}   
    ports['recvPackets'] = p['rx_packets']
    ports['transmitPackets'] = p['tx_packets']
    ports['transmitBytes'] = p['tx_bytes']
    ports['PortNumber'] = p['port_no']
    ports['recvBytes'] = p['rx_bytes']

  
    ports_list.append(ports)

  ports_dpid['ports'] = ports_list
  ports_dpid['dpid'] = "00:00:" + dpidToStr(event.connection.dpid).replace('-',':')
  storage_of_ports.append(ports_dpid)


  log.debug("PortStatsReceived from %s: %s", 
    dpidToStr(event.connection.dpid), stats)
def _handle_flowstats_received (event):
  stats = flow_stats_to_list(event.stats)
  log.debug("FlowStatsReceived from %s: %s", 
    dpidToStr(event.connection.dpid), stats)

  # Get number of bytes/packets in flows for web traffic only
  # I have added: Save stats to a text file (output_file, or separate files )
  web_bytes = 0
  web_flows = 0
  web_packet = 0
  output_file=open("output.txt", "a+") #my own: open a text(canbeanyotherformat) file and append the stats in it (r+, w+, a+)
  flows_file=open("flows.txt", "a+")
  bytes_file=open("bytes.txt", "a+")
  packets_file=open("packets.txt","a+")
  for f in event.stats:
    if f.match.tp_dst == 80 or f.match.tp_src == 80:
      web_bytes += f.byte_count
      web_packet += f.packet_count
      web_flows += 1 
  log.info("Web traffic from %s: %s bytes (%s packets) over %s flows", dpidToStr(event.connection.dpid), web_bytes, web_packet, web_flows)
  localtime = time.asctime( time.localtime(time.time()) ) # my own:to display local time
  # my own:print in Output File
  output_file.write( localtime + " Web traffic:" +"  Bytes:"+ str(web_bytes)+ '\t'+"  Packets:" + str(web_packet) +'\t'+"  Flows:"+str(web_flows) +"\n") # my own:print in Output File
   # write stats on separate files
  flows_file.write( str(web_flows)+ "\n")
  bytes_file.write(  str(web_bytes)+ "\n")
  packets_file.write(str(web_packet)+ "\n")
  
  #my own: to close the file
  output_file.close() 
  flows_file.close()
  bytes_file.close()
  packets_file.close()
Exemple #5
0
  def _handle_openflow_ConnectionUp (self, event):
    sw = switches.get(event.dpid)
    print "DPID for",event.dpid," = ",dpidToStr(event.dpid)
    if sw is None:
      # New switch
      sw = Switch()
      sw.dpid = event.dpid
      switches[event.dpid] = sw
      sw.connect(event.connection)
    else:
      sw.connect(event.connection)


    dpids.append(event.dpid)
    ports[dpidToStr(event.dpid)] = {}
    print "Add ports to link status DB"
    dpid_ts[event.dpid] = 0.000
    dpid_latency[event.dpid] = 0.000
    dpid_stats[event.dpid] = []
    for p in event.ofp.ports:
      port = [0.0, 100, 0]
      ports[dpidToStr(event.dpid)][p.port_no] = port

    """
    Tell all switches to forward latency packets to controller
    """
    print "Connected to switch",dpidToStr(event.dpid)
    connection = event.connection
    match = of.ofp_match(dl_type = LAT_TYPE,dl_dst = pkt.ETHERNET.NDP_MULTICAST)
    msg = of.ofp_flow_mod()
    msg.priority = 65000
    msg.match = match
    msg.actions.append(of.ofp_action_output(port = of.OFPP_CONTROLLER))
    connection.send(msg)
Exemple #6
0
def _handle_switchdesc_received (event):
  global switch_desc
  event.connection.dpid
  switch_desc[dpidToStr(event.connection.dpid)]['hw_desc'] = event.stats.hw_desc
  switch_desc[dpidToStr(event.connection.dpid)]['sw_desc'] = event.stats.sw_desc
  switch_desc[dpidToStr(event.connection.dpid)]['mfr_desc'] = event.stats.mfr_desc
  switch_desc[dpidToStr(event.connection.dpid)]['serial_num'] = event.stats.serial_num
def _handle_flowstats_received (event):
  stats = flow_stats_to_list(event.stats)
  log.debug("FlowStatsReceived from %s: %s", 
    dpidToStr(event.connection.dpid), stats)
  # print >> the_file, "FlowStatsReceived from " + dpidToStr(event.connection.dpid) ": " + stats
  
  the_file.write("Time: " + time.asctime(time.localtime(time.time())) + "\n")
  the_file.write("FlowStatsReceived from " + dpidToStr(event.connection.dpid) + ": " + str(stats) + "\n\n")

  # for f in event.stats:
  #   if str(f.match.dl_dst) == "00:00:00:00:00:11":
  #     the_file.write("FlowStatsReceived from " + dpidToStr(event.connection.dpid) + ": " + str(f.match.dl_dst) + "\n")
  #   else:
  #     the_file.write("Mac removed from flow table" + "\n\n")
  
  # Get number of bytes/packets in flows for web traffic only
  web_bytes = 0
  web_flows = 0
  web_packet = 0
  for f in event.stats:
    if f.match.tp_dst == 80 or f.match.tp_src == 80:
      web_bytes += f.byte_count
      web_packet += f.packet_count
      web_flows += 1
  log.info("Web traffic from %s: %s bytes (%s packets) over %s flows", 
    dpidToStr(event.connection.dpid), web_bytes, web_packet, web_flows)
Exemple #8
0
def find_latency(dpid):
  for key in ports[dpidToStr(dpid)]:
    if(key != 65534):
      packet = of.ofp_packet_out(action = of.ofp_action_output(port = key))
      packet.data = create_lat_pkt(dpid,key,ports[dpidToStr(dpid)][key][0])
      #print "Sending to ",dpid," key ", key
      core.openflow.sendToDPID(dpid, packet)
	def handle_flows_redirection(cls, dpid, connections, switch_addresss, message):

		""" Sends flow mod messages to redirect flows to created queues """
		#print 'message from ' + str(switch_addresss)
		#print 'Connections ' + str(dir(connections))

		dpid = dpid[:len(dpid)-1]
		dpid = dpid[len(dpid)-12:]
		#print 'Received dpid: ' + str(dpid)

		#print "message to be used for redirection" + str(message)

		msg = of.ofp_flow_mod(command=of.OFPFC_DELETE)
		msg.priority = 65535

		#print "dpid parameter: " + str(dpid)
		for connection in connections:
			connection_dpid = connection.dpid
			dpid_str = dpidToStr(connection_dpid)
			dpid_str = dpid_str.replace("-", "")
			#print 'Real dpid_str: ' + dpid_str
			if dpid == dpid_str:
				connection.send(msg)
				#print 'Sent to: ' + str(connection)
				#print 'Well...done'

		for i in range(len(message['bw_list'])):

			# We only want to redirect outgoing flows
			if message['bw_list'][i]['action'] != 'OFPP_LOCAL':

				my_match = of.ofp_match(dl_type = 0x800,nw_src=message['bw_list'][i]['nw_src'],nw_dst=message['bw_list'][i]['nw_dst'])

				#print "Flow Match: " + str(my_match)
				msg = of.ofp_flow_mod()
				msg.match = my_match
				msg.priority = 65535
				msg.idle_timeout = 0
    				msg.hard_timeout = 0
				msg.actions.append(of.ofp_action_enqueue(port=int(message['bw_list'][i]['action']), queue_id=int(message['queue_list'][i]['queueId'])))

				#print "Flow mod message: " + str(msg)

	  	              	#toDo: Check a better way to do this
				#print "dpid parameter: " + str(dpid)
	                	for connection in connections:
        	        		connection_dpid=connection.dpid
					#print "Connection dpid: " + str(connection_dpid)
                			dpid_str=dpidToStr(connection_dpid)
	                		dpid_str=dpid_str.replace("-", "")
        	        		#print 'Real dpid_str: ' + dpid_str

	                		if dpid == dpid_str:
        	        			connection.send(msg)
						global flow_mod_time
						flow_mod_time = time.time() 
						print "Notification time: " + str(notification_time)
						print "Flow stats reply: " + str(flow_stats_reply_time)
						print "Queues done time: " + str(queues_done_time)
						print "Flow mode time :" + str(flow_mod_time) 
Exemple #10
0
def _handle_PacketIn (event):
  packet = event.parsed
  if packet.effective_ethertype == LAT_TYPE:
    """
    Handle incoming latency packets
    """
    #print dpidToStr(event.dpid)
    port = packet.src
    [prevtime, swdpdest, swdpsrc] = packet.payload.split(',')
    prevtime = float(prevtime)
    currtime = time.time()
    #print "PrevTime = ", prevtime, "    CurrTime = ", currtime
    dest_dpid = dpidToStr(event.dpid)
    if dest_dpid == swdpdest:
      #print "DPID matched"
      latency = round((((currtime - prevtime)*1000) - dpid_latency[strToDPID(swdpsrc)] - dpid_latency[event.dpid]), 4)
      #print "Latency =",latency
      #swd = ports[dpidToStr(self.dpid)]
      swd = ports[swdpsrc]
      #for k in swd:
      #  if swd[k][0] == mac:
      #    break
      k = 0
      for p in switch_adjacency[strToDPID(swdpsrc)]:
        if swdebug:
          print swdpsrc,"\n",switch_adjacency[strToDPID(swdpsrc)]
        if switch_adjacency[strToDPID(swdpsrc)][p] is event.dpid:
          if swdebug:
            print "matches with",dpidToStr(event.dpid)," when p = ",p
          k = p
      if latency >=0:
        if k in ports[swdpsrc]:
          ports[swdpsrc][k][0] = latency
    return
Exemple #11
0
    def _handle_PacketIn(self, event):
        packet = event.parsed

        if packet.dst.is_multicast:
                return

        # Learn the source and fill up routing table
        # self.table[(event.connection,packet.src)] = event.port
        # dst_port = self.table.get((event.connection,packet.dst))

        print("Switch {} has no flow for dst {} or src {}".format(
            dpidToStr(event.dpid),packet.dst,packet.src))

        # setup reverse flow:
        # "Every packet with dst=packet.src should go out event.port of
        # event.connection"

        # arp = packet.find('arp')

        dst_port = self.find_edge_port(event.dpid)

        if not dst_port:
            log.warning("Switch {} could not find edge port".format(
                dpidToStr(event.dpid)))
            return

        self.install_flow(event.dpid, dst_port, src=packet.src)

        self.send_packet(event, dst_port)
    def _handle_ConnectionUp(self, event):
        
        # Use dpid to differentiate between switches (datapath-id)
        # Each switch has its own flow table. As we'll see in this 
        # example we need to write different rules in different tables.
	dpid = dpidToStr(event.dpid)
        log.debug("Switch %s has come up.", dpid)
        """ Add your logic here """
	# We load openflow entries depending of the switch dpid.
	# rememeber that this function is trigered every time a switch is connected to the controller.
        if ( dpid == '00-00-00-00-00-01' ):
            msg_1p1 = of.ofp_flow_mod()
            msg_1p1.match.in_port = 1
            msg_1p1.actions.append(of.ofp_action_output(port = 3))
            log.info("Rule for %s and port %i", dpidToStr(event.dpid), msg_1p1.match.in_port)	
	    # send the rule to the switch
            event.connection.send(msg_1p1)

	    # inPort - 3
            # we also are able to declare everything in one line as follow:
            msg_1p3 = of.ofp_flow_mod(	match = of.ofp_match ( in_port = 3), 
					action = of.ofp_action_output (port = 1))
            event.connection.send(msg_1p3)
	    # inPort - 2
  	    msg_1p2 = of.ofp_flow_mod(	match = of.ofp_match ( in_port = 2),
					action = of.ofp_action_output (port = 4))
            event.connection.send(msg_1p2)
	    # inPort - 4
            msg_1p4 = of.ofp_flow_mod(	match = of.ofp_match ( in_port = 4),
					action = of.ofp_action_output(port = 2))
            event.connection.send(msg_1p4)
        elif ( event.dpid == 4 ):	# I can also use dpid as Integer
	    # 1 to 3
            msg_4p1 = of.ofp_flow_mod(	match = of.ofp_match ( in_port = 1), 
					action = of.ofp_action_output (port = 3))
            event.connection.send(msg_4p1)
	    # 3 to 1
            msg_4p3 = of.ofp_flow_mod(	match = of.ofp_match ( in_port = 3), 
					action = of.ofp_action_output (port = 1))
            event.connection.send(msg_4p3)
            # 2 to 4
            msg_4p2 = of.ofp_flow_mod(	match = of.ofp_match ( in_port = 2), 
					action = of.ofp_action_output (port = 4))
            event.connection.send(msg_4p2)
	    # 4 to 2
            msg_4p4 = of.ofp_flow_mod(	match = of.ofp_match ( in_port = 4), 
					action = of.ofp_action_output (port = 2))
            event.connection.send(msg_4p4)
#        elif ( dpid == '00-00-00-00-00-02' ) or ( dpid == '00-00-00-00-00-03' ):
	else:
           msg = of.ofp_flow_mod()
           msg.match.in_port = 1
           msg.actions.append(of.ofp_action_output(port = 2))
           event.connection.send(msg)

           msg = of.ofp_flow_mod()
           msg.match.in_port = 2
           msg.actions.append(of.ofp_action_output(port = 1))
           event.connection.send(msg)
Exemple #13
0
def create_lat_pkt(dpid, port):
  pkt1 = pkt.ethernet(type=LAT_TYPE)
  for l in core.openflow_discovery.adjacency:
      if ((l.dpid1 == dpid) and (l.port1 == port)):
        #print "Sending for",l
        pkt1.dst = pkt.ETHERNET.NDP_MULTICAST #need to decide
        pkt1.payload = str(time.time()) + ',' + dpidToStr(l.dpid2) + ',' + dpidToStr(l.dpid1)
        return pkt1.pack()
def DeleteRule (event, dl_type=0x800, nw_proto=1, port=0, src_port=of.OFPP_ALL):
  try:
    del firewall[(event.connection,dl_type,nw_proto,port,src_port)]
    log.debug("Deleting firewall rule in %s: %s %s %s %s" %
      dpidToStr(event.connection.dpid), dl_type, nw_proto, port, src_port)
  except KeyError:
    log.error("Cannot find in %s: %s %s %s %s" %
      dpidToStr(event.connection.dpid), dl_type, nw_proto, port, src_port)
 def _handle_PacketIn (self, event):
   #Parsing Incoming packet
   packet = event.parsed
   #Updating mac-table to port-mapping
   self.macToPortMap[packet.src] = event.port
   #Flooding Function
   def flood():
     print "[+] Debug: Flooding"
     msg = of.ofp_packet_out()
     msg.actions.append(of.ofp_action_output(port = of.OFPP_FLOOD))
     msg.in_port = event.port
     msg.buffer_id = event.ofp.buffer_id
     self.connection.send(msg)
   #Dropping Function
   def drop():
     print "[+] Debug: Dropping Packets"
     msg = of.ofp_flow_mod()
     msg.match = of.ofp_match.from_packet(packet)
     msg.idle_timeout = 10
     msg.hard_timeout = 30
     msg.buffer_id = event.ofp.buffer_id
     self.connection.send(msg)
   #Forwarding Function
   def forward():
     print "[+] Debug: Forwarding"
     #TODO - WILL CODE
     msg = of.ofp_flow_mod()
     msg.match.dl_src = packet.src
     msg.match.dl_dst = packet.dst
     msg.idle_timeout = 10
     msg.hard_timeout = 30
     msg.actions.append(of.ofp_action_output(port = outport))
     msg.buffer_id = event.ofp.buffer_id
     self.connection.send(msg)
   #Check if Packet has not been mapped
   if packet.dst not in self.macToPortMap:
     #switch does not know egress port
     #Flood the packet
     log.debug("[-] Debug: Port for %s unknown -- Flooding" % (packet.dst,))
     print "[+] Debug: Port for %s unknown -- Flooding" % (packet.dst,)
     flood()
   #If it has then forward the packet unless its destination is the same port its been received on
   else:
     #Forward packet if SW knows outprt
     outport = self.macToPortMap[packet.dst]
     if outport == event.port:
       log.warning("[-] Same port for packet from %s -> %s on %s/ Drop." %
                 (packet.src, packet.dst, outport), dpidToStr(event.dpid))
       print "[-] Same port for packet from %s -> %s on %s/ Drop." % (packet.src, packet.dst, outport)
       drop()
       return
     log.debug("[F] Installing flow for %s port:%i -> %sport:%i" % 
             (packet.src, event.port, packet.dst, outport), dpidToStr(event.dpid))
     print "[F] Debug: Installing flow:\n    %s port:%i -> %s port:%i \n    on Switch:" % (packet.src, event.port, packet.dst, outport), dpidToStr(event.dpid)
     log.debug("[+] Port for %s known -- Forwarding" % (packet.dst,))
     print "[+] Debug: Port for %s known -- Forwarding" % (packet.dst,)
     #Forward the packet if in MacToPortMap map
     forward()
Exemple #16
0
 def _handle_openflow_ConnectionDown (self, event):
   #print "CD"
   #Remove Host when Switch gets down
   for l in self.links:
     if l[0] == dpidToStr(event.dpid):
       print 'l:',l
       self.hosts.remove(l[1])
   self.switches.remove(dpidToStr(event.dpid))
   self.send_table()
def _calc_paths ():
  ####### CHANGED PART ########
  # access monitoring server and get distance_map
  import xmlrpclib
  # TODO change the Server IP and Port to the command line option
  monitoring_server = xmlrpclib.ServerProxy("http://133.1.134.225:8000")
  distance_map = monitoring_server.request_link_distance()
  ##############################

  """
  Essentially Floyd-Warshall algorithm
  """
  sws = switches.values()

  # return list of values to sws [dpid1,dpid2,dpid3,dpid3]
  path_map.clear()
  for k in sws:
    # pick up the [sw1][sw2] , port_number
    for j,port in adjacency[k].iteritems():
      if port is None: continue
      ####### CHANGED PART #############
      k_dpid = (dpidToStr(k.dpid)).replace("-","")
      j_dpid = (dpidToStr(j.dpid)).replace("-","")
      if j_dpid not in distance_map[k_dpid]:
        path_distance = distance_map[j_dpid][k_dpid]
      else:
        path_distance = distance_map[k_dpid][j_dpid]
      path_map[k][j] = (path_distance, None)
      ####################################
  path_map[k][k] = (0,None) # distance, intermediate

  """
  for i in sws:
    for j in sws:
      a = path_map[i][j][0]
      #a = adjacency[i][j]
      if a is None: a = "*"
      print a,
    print
  """

  for k in sws:
    for i in sws:
      for j in sws:
        if path_map[i][k][0] is not None:
          if path_map[k][j][0] is not None:
            # i -> k -> j exists
            ikj_dist = path_map[i][k][0]+path_map[k][j][0]
            if path_map[i][j][0] is None or ikj_dist < path_map[i][j][0]:
              # i -> k -> j is better than existing
              path_map[i][j] = (ikj_dist, k)

  print "--------------------"
  for i in sws:
    for j in sws:
      print path_map[i][j][0],
    print
Exemple #18
0
 def _handle_openflow_ConnectionDown(self, event):
     sw = self.topology.getEntityByID(event.dpid)
     if sw is None:
         log.warn("Switch %s disconnected, but... it doesn't exist!" % (dpidToStr(event.dpid),))
     else:
         if sw.connection is None:
             log.warn("Switch %s disconnected, but... it's wasn't connected!" % (dpidToStr(event.dpid),))
         sw.connection = None
         log.info("Switch " + str(event.dpid) + " disconnected")
Exemple #19
0
  def _handle_PacketIn (self, event):
	"""
	Handles packet in messages from the switch.
	"""
	
	return
	#log.debug("incoming package")
	dpid = event.connection.dpid
	inport = event.port
	
	packet = event.parsed # This is the parsed packet data.
	if not packet.parsed:
	  log.warning("Ignoring incomplete packet")
	  return
	
	def flood ():
	  """ Floods the packet """
	  return
	  log.debug("flood was called")
	  if event.ofp.buffer_id == -1:
		log.warning("Not flooding unbuffered packet on %s",
					dpidToStr(event.dpid))
		return
	  msg = of.ofp_packet_out()
	  if time.time() - self.connection.connect_time > FLOOD_DELAY:
		# Only flood if we've been connected for a little while...
		#log.debug("%i: flood %s -> %s", event.dpid, packet.src, packet.dst)
		msg.actions.append(of.ofp_action_output(port = of.OFPP_FLOOD))
	  else:
		pass
		#log.info("Holding down flood for %s", dpidToStr(event.dpid))
	  msg.buffer_id = event.ofp.buffer_id
	  msg.in_port = event.port
	  #self.connection.send(msg)
	
	#packet_in = event.ofp # The actual ofp_packet_in message. 
	# Comment out the following line and uncomment the one after
	# when starting the exercise.
	#self.act_like_hub(packet, packet_in)
	#self.act_like_switch(packet, packet_in)
	#log.warning("Traffic in SW: %s -> %s on %s.  Drop." % (packet.src, packet.dst, event.port), dpidToStr(event.dpid))
	#log.debug("Traffic in SW: %s -> %s on %s.  Drop." % (packet.src, packet.dst, event.port))
	if packet.dst.isMulticast():
	  flood() # 3a
	else:
	 if packet.type == 0x0800:
	   ip_packet = packet.next
	   log.debug("Is Ethernet package")
	   if ip_packet.protocol == 0x01:
		icmp_packet = ip_packet.next
		log.debug("Is ICMP package")
		log.debug("SW:%s InPort:%i IP %s => %s", dpidToStr(event.dpid), inport, str(ip_packet.srcip), str(ip_packet.dstip))
	   if ip_packet.protocol == 0x17:
	   	udp_packet = ip_packet.next
		log.debug("Is UDP package")
		log.debug("SW:%s InPort:%i IP %s => %s", dpidToStr(event.dpid), inport, str(ip_packet.srcip), str(ip_packet.dstip))
	log.debug("SW:%s InPort:%i Eth %s => %s", dpidToStr(event.dpid), inport, str(packet.src), str(packet.dst))
Exemple #20
0
def handle_PortStatsReceived (event):
    
    #Handles port stats event.
    
  #self.stats = event.stats
  print "Switch",dpidToStr(event.dpid)
  log.debug("PortStatsReceived")
  for portStats in event.stats:
    ports[dpidToStr(event.dpid)][portStats.port_no][rx] = portStats.rx_dropped
    ports[dpidToStr(event.dpid)][portStats.port_no][tx] = portStats.tx_dropped
Exemple #21
0
    def perform(self, event):
        print 'Unhandled event: ',

        if isinstance(event, ConnectionUp):
            print 'ConnectionUp from switch %s' % dpidToStr(event.dpid)
        elif isinstance(event, ConnectionDown):
            print 'ConnectionDown from switch %s' % dpidToStr(event.dpid)
        elif isinstance(event, PacketIn):
            print 'PacketIn from switch %s [%d]' % (dpidToStr(event.dpid), event.port)
        else:
            print event
Exemple #22
0
def calculate_PLR(dpid, port_stat):
    port_dropped = port_stat.tx_dropped - ports[dpidToStr(dpid)][port_stat.port_no][PREV_TX_DROPPED]
    port_tx_pkts = port_stat.tx_packets - ports[dpidToStr(dpid)][port_stat.port_no][PREV_TX_PKTS]
    try:
        port_plr = port_dropped / port_tx_pkts * 100
    except ZeroDivisionError:
        print "ERROR: No packets has been sent!!!"
        port_plr = 0
    ports[dpidToStr(dpid)][port_stat.port_no][PREV_TX_DROPPED] = port_stat.tx_dropped
    ports[dpidToStr(dpid)][port_stat.port_no][PREV_TX_PKTS] = port_stat.tx_packets
    ports[dpidToStr(dpid)][port_stat.port_no][TX_PLR] =port_stat.tx_packets
def _handle_ConnectionUp(event):
    global s1_dpid, s2_dpid
    print "ConnectionUp: ",
    dpidToStr(event.connection.dpid)
    # remember the connection dpid for switch
    for m in event.connection.features.ports:
        if m.name == "s1-eth1":
            s1_dpid = event.connection.dpid
            print "s1_dpid=", s1_dpid
        elif m.name == "s2-eth1":
            s2_dpid = event.connection.dpid
            print "s2_dpid=", s2_dpid
Exemple #24
0
 def __init__(self,event):
   self.connection = event.connection
   self.dpid = event.connection.dpid
   dpids.append(self.dpid)
   ports[dpidToStr(event.dpid)] = {}
   print "Add ports to link status DB"
   dpid_ts[self.dpid] = 0.000
   dpid_latency[self.dpid] = 0.000
   dpid_stats[self.dpid] = []
   for p in event.ofp.ports:
     port = [str(p.hw_addr), 0.0, 100, 0, 0]
     ports[dpidToStr(event.dpid)][p.port_no] = port
Exemple #25
0
def handle_QueueStatsReceived (event):
    
    #Handles port stats event.
    
  #self.stats = event.stats
#  print "Switch",dpidToStr(event.dpid)
  log.debug("QueueStatsReceived")
#  print "Queue stats received"
  for qStats in event.stats:
    if qStats.port_no in ports[dpidToStr(event.dpid)]:
      qSt = qStats.tx_errors - ports[dpidToStr(event.dpid)][qStats.port_no][tx]
      ports[dpidToStr(event.dpid)][qStats.port_no][tx] = qSt
Exemple #26
0
    def _handle_ConnectionUp(self, event):
        
        # Use dpid to differentiate between switches (datapath-id)
        # Each switch has its own flow table. As we'll see in this 
        # example we need to write different rules in different tables.
        dpid = dpidToStr(event.dpid)
        log.debug("Switch %s has come up.", dpid)
        
        """ Add your logic here """
        fms = []
        
        if dpid == "00-00-00-00-00-01" or dpid == "00-00-00-00-00-04":
            fm = of.ofp_flow_mod()
            fm.match.in_port = 3
            fm.actions.append(of.ofp_action_output(port = 1))
            fms.append(fm)
            
            fm = of.ofp_flow_mod()
            fm.match.in_port = 1
            fm.actions.append(of.ofp_action_output(port = 3))
            fms.append(fm)

            fm = of.ofp_flow_mod()
            fm.match.in_port = 4
            fm.actions.append(of.ofp_action_output(port = 2))
            fms.append(fm)

            fm = of.ofp_flow_mod()
            fm.match.in_port = 2
            fm.actions.append(of.ofp_action_output(port = 4))
            fms.append(fm)

        if dpid == "00-00-00-00-00-02" or dpid == "00-00-00-00-00-03":
            """
            fm = of.ofp_flow_mod()
            fm.actions.append(of.ofp_action_output(port = of.OFPP_FLOOD))
            fms.append(fm)
            """
            fm = of.ofp_flow_mod()
            fm.match.in_port = 1
            fm.actions.append(of.ofp_action_output(port = 2))
            fms.append(fm)

            fm = of.ofp_flow_mod()
            fm.match.in_port = 2
            fm.actions.append(of.ofp_action_output(port = 1))
            fms.append(fm)

            

        for fm in fms:
            event.connection.send(fm)
            log.debug("Slicing rules installed on %s", dpidToStr(event.dpid))
Exemple #27
0
	def _handle_LinkEvent (self, event):
		s1 = event.link.dpid1
		s2 = event.link.dpid2
		if s1 > s2: 
			s1,s2 = s2,s1
    		s1 = dpidToStr(s1)
    		s2 = dpidToStr(s2)

    		if event.added:
      			self.links.add((s1,s2))
    		elif event.removed and (s1,s2) in self.links:
      			self.links.remove((s1,s2))
		log.debug("Discovered Link Event between %s and %s.", s1, s2)
Exemple #28
0
  def _handle_openflow_discovery_LinkEvent (self, event):
    #print "LE"
    s1 = event.link.dpid1
    s2 = event.link.dpid2
    if s1 > s2: s1,s2 = s2,s1
    s1 = dpidToStr(s1)
    s2 = dpidToStr(s2)

    if event.added:
      self.links.add((s1,s2))
    elif event.removed and (s2,s2) in self.links:
      self.links.remove((s1,s2))

    self.send_table()
Exemple #29
0
 def _handle_openflow_ConnectionUp(self, event):
     sw = self.topology.getEntityByID(event.dpid)
     add = False
     if sw is None:
         sw = OpenFlowSwitch(event.dpid)
         add = True
     else:
         if sw.connection is not None:
             log.warn("Switch %s connected, but... it's already connected!" % (dpidToStr(event.dpid),))
     sw._setConnection(event.connection, event.ofp)
     log.info("Switch " + dpidToStr(event.dpid) + " connected")
     if add:
         self.topology.addEntity(sw)
         sw.raiseEvent(SwitchJoin, sw)
Exemple #30
0
def create_eco_subnet():
    global phy_topology
    
    switchNum = POD_NUM**3/4 + 1
    p_edge_top = POD_NUM**3/4 + 1 + POD_NUM + POD_NUM**2/2
    p_edge_bottom = p_edge_top + POD_NUM**2/2
    
    all_path = nx.shortest_path(phy_topology,dpidToStr(switchNum))
    for edge_num in range(p_edge_top,p_edge_bottom):
        path = all_path[dpidToStr(edge_num)]
        _init_check_switch(path)
        for s1,s2 in zip(path[:-1],path[1:]):
            if _check_path(s1,s2)==False:
                exit
Exemple #31
0
 def _log_if_first_or_end_node(self, event):
     if event.dpid == 2 and self.switched:
         message = "B-Packet_In DPID:%s Time: %s " % (dpidToStr(
             event.dpid), get_time_now())
     elif event.dpid == 2 and not self.switched:
         message = "A-Packet_In DPID:%s Time: %s " % (dpidToStr(
             event.dpid), get_time_now())
     elif event.dpid == 3 and event.port == 1 and self.switched:
         message = "B-Packet_In DPID:%s Time: %s " % (dpidToStr(
             event.dpid), get_time_now())
     elif event.dpid == 3 and event.port == 1 and not self.switched:
         message = "A-Packet_In DPID:%s Time: %s " % (dpidToStr(
             event.dpid), get_time_now())
     else:
         return
     self.logger(message)
Exemple #32
0
  def _handle_PacketIn (self, event):
    eth_packet = event.parsed
    in_port = event.port
    # assuming that switches do not have any forwarding rule pre-installed
    # so the first packet from a host will travel to controller
    # it is a rough logic to discover host, it can be improved

    if not eth_packet.parsed:
      return
    src_mac = eth_packet.src
    if eth_packet.type == ethernet.ARP_TYPE:
      arp_packet = eth_packet.payload
      if not arp_packet.hwsrc == src_mac:
        return
      src_ip = arp_packet.protosrc
      if src_ip == IP_ANY: 
        return
    elif eth_packet.type == ethernet.IP_TYPE:
      ip_packet = eth_packet.payload
      src_ip = ip_packet.srcip
      if src_ip == IP_ANY: 
        return
    else: 
      return
    if not hosts[str(src_ip)]:
      hosts[str(src_ip)]['mac'] = str(src_mac)
      hosts[str(src_ip)]['switch'] = dpidToStr(event.connection.dpid)
      hosts[str(src_ip)]['last_time_seen'] = int(time.time())
      hosts[str(src_ip)]['in_port'] = in_port
    def _handle_ConnectionUp(self, event):
        def _setup_flow(iport, oport):
            msg = of.ofp_flow_mod()
            msg.match.in_port = iport
            msg.actions.append(of.ofp_action_output(port=oport))
            event.connection.send(msg)

        def _setup_session(s, t):
            _setup_flow(s, t)
            _setup_flow(t, s)

        # Use dpid to differentiate between switches (datapath-id)
        # Each switch has its own flow table. As we'll see in this
        # example we need to write different rules in different tables.
        dpid = dpidToStr(event.dpid)
        log.debug("------------ Switch %s has come up.", dpid)
        """ Add your logic here """
        # Upper Slide
        # h1 <-s1-s2-s4-> h3
        if event.dpid == 1:
            _setup_session(1, 3)
            _setup_session(2, 4)

        if event.dpid == 2:
            _setup_session(1, 2)

        if event.dpid == 3:
            _setup_session(1, 2)

        if event.dpid == 4:
            _setup_session(1, 3)
            _setup_session(2, 4)

        log.debug("------------ Setup Rules for %s done.", dpid)
Exemple #34
0
    def _handle_openflow_PacketIn(self, event):
        dpid = event.dpid
        packet = event.parsed
        port = event.port
        etype = packet.type

        log.debug("PacketIn from %s, EtherType=%#x", dpidToStr(event.dpid),
                  etype)

        if etype == ethernet.IP_TYPE:
            self.raiseEvent(ViroPacketInIP, dpid, port, packet)
        elif etype == ethernet.IPV6_TYPE:
            self.raiseEvent(ViroPacketInIPV6, dpid, port, packet)
        elif etype == ethernet.LLDP_TYPE:
            self.raiseEvent(ViroPacketInLLDP, dpid, port, packet)
        elif etype == ethernet.ARP_TYPE:
            self.raiseEvent(ViroPacketInARP, dpid, port, packet)
        elif etype == viro.VIRO_TYPE:
            packet = viro(packet.raw)
            viro_payload = packet.payload
            if isinstance(viro_payload, viroctrl):
                self.raiseEvent(ViroPacketInVIROCtrl, dpid, port, packet)
            else:
                self.raiseEvent(ViroPacketInVIROData, dpid, port, packet)
        else:
            log.debug("Unknown packet type %#x", etype)
def calc_qos_index(traffic_type):
    create_neighbourhood_matrix()
    tos_constants = QOS_weights[traffic_type]
    if swdebug:
        print "Initialized constants. Finding cost now"
    sw_latency_map = {}
    QOS_indices[traffic_type] = {}

    for switch in dpids:
        QOS_indices[switch] = {}
        switchStr = dpidToStr(switch)
        sw_latency_map = ports[switchStr]
        port_list = []
        link_costs = {}
        for port in switch_neighbourhood[switch]:
            port_list = sw_latency_map[port]
            dest_switch = switch_neighbourhood[switch][port]

            l = port_list[latency]
            b = port_list[bw]
            t = port_list[tx]

            n = 0
            if traffic_type is not "best_effort":
                n = 1
            cost = (tos_constants[0] * b) + n * ((tos_constants[1] * l) +
                                                 (tos_constants[2] * t))
            link_costs[dest_switch] = cost
        QOS_indices[traffic_type][switch] = link_costs
    return QOS_indices[traffic_type]
Exemple #36
0
def _handle_port_stats(event):
    global start_time
    global network

    port_stats = flow_stats_to_list(event.stats)
    #log.debug(port_stats)

    for node in network:
        if (dpidToStr(
                event.dpid) == network[node]["MAC"]):  # find which switch
            for link in network[node][
                    "link"]:  # for each link connected to this switch
                try:
                    # calculate updated congestion value
                    link["cong_value"] = MBPS * (
                        port_stats[link["out_port"]]["tx_bytes"] -
                        link["prev_tx_bytes"])

                    # has controller just started up?
                    if ((datetime.now() - start_time).total_seconds() >
                            WAIT_FOR_STARTUP):
                        log.debug("\nBW on node %s, port %s: (Mbps): %s\n",
                                  node, link["out_port"], link["cong_value"])

                        if (link["cong_value"] >
                                CONG_THRESH):  # congestion detected
                            log.debug("\nCongestion on node %s, port %s\n",
                                      node, link["out_port"])

                    # store tx_bytes for next iteration
                    link["prev_tx_bytes"] = port_stats[
                        link["out_port"]]["tx_bytes"]

                except IndexError:
                    pass
Exemple #37
0
 def issue_switch_meas(self, event):
     # TODO:  Maybe consider entire vector to the StateMachine object?
     # Extract the switch id from the event info
     switchId = dpidToStr(event.connection.dpid)
     switchNo = int(switchId[-1])
     # iterate over the event info and generate the flow vector
     # initialize the measurement vector
     #measurement = np.zeros((self.num_flows,1))
     # loop over the flow numbers and write the value to the measurement vector
     for f in event.stats:
         for i in range(8):
             addressFrom = "10.0.0." + str(i)
             for j in range(8):
                 addressTo = "10.0.0." + str(j)
                 #  Should I check for looping back?
                 if f.match.nw_dst == IPAddr(
                         addressFrom) and f.match.nw_src == IPAddr(
                             addressTo):
                     if i != j:
                         #print 'The index = ' + str(self.filter.ComputeFlowNum(i, j))
                         #print 'The switch number = ' + str(switchNo)
                         self.filter.UpdateMeasurement(
                             self.filter.ComputeFlowNum(i, j), switchNo,
                             f.byte_count)
                         #measurement[self.filter.ComputeFlowNum(i, j),1] = f.byte_count
     return switchNo
Exemple #38
0
def handle_aggregateflowstats_received(event):
    agg_stat = event.stats

    log.info(
        "AggregateFlowStatsReceived from %s: %s bytes (%s packets) over %s flows",
        dpidToStr(event.connection.dpid), agg_stat.byte_count,
        agg_stat.packet_count, agg_stat.flow_count)
Exemple #39
0
 def _handle_openflow_ConnectionUp(self, event):
     sw = self.topology.getEntityByID(event.dpid)
     add = False
     if sw is None:
         sw = OpenFlowSwitch(event.dpid)
         add = True
     else:
         if sw._connection is not None:
             log.warn(
                 "Switch %s connected, but... it's already connected!" %
                 (dpidToStr(event.dpid), ))
     sw._setConnection(event.connection, event.ofp)
     log.info("Switch " + dpidToStr(event.dpid) + " connected")
     if add:
         self.topology.addEntity(sw)
         sw.raiseEvent(SwitchJoin, sw)
Exemple #40
0
def flow_flush():
    msg = of.ofp_flow_mod(command=of.OFPFC_DELETE)

    for connection in core.openflow.connections:
        connection.send(msg)
        log.info("-> Clearing all flows from %s!" %
                 (dpidToStr(connection.dpid), ))
Exemple #41
0
def list_switches(ofnexus=None):
    if ofnexus is None:
        from pox.core import core
        ofnexus = core.openflow

    r = []
    for dpid, con in ofnexus._connections.iteritems():
        ports = []
        for p in con.features.ports:
            ports.append({
                'port_no': p.port_no,
                'hw_addr': str(p.hw_addr),
                'name': p.name
            })
        ports.sort(key=lambda item: item['port_no'])

        rr = {
            'dpid': dpidToStr(dpid),
            'n_tables': con.features.n_tables,
            'ports': ports
        }
        r.append(rr)

    r.sort(key=lambda item: item['dpid'])
    return r
Exemple #42
0
 def transform_key(d):
   newd = dict()
   for k,v in d.items():
     if isinstance(v, dict):
       v = transform_key(v)
     newd[dpidToStr(k)] = v
   return newd
Exemple #43
0
def _handle_ConnectionUp(event):
    msg = OutMessage()

    msg.set_policy("netasm.examples.netasm.standalone.hub")
    event.connection.send(msg)

    log.info("netasm.examples.netasm.standalone.hub for %s", dpidToStr(event.dpid))
Exemple #44
0
def list_switches(ofnexus=None):
    #FELIPE TOMM - TCC
    #Lista os Switches em JSON
    if ofnexus is None:
        from pox.core import core
        ofnexus = core.openflow

    r = []
    for dpid, con in ofnexus._connections.iteritems():
        ports = []
        for p in con.ports.values():
            pdict = {
                'port_no': p.port_no,
                'hw_addr': str(p.hw_addr),
                'name': p.name
            }
            for bit, name in of.ofp_port_config_map.items():
                if p.config & bit:
                    pdict[name.split('OFPPC_', 1)[-1].lower()] = True
            for bit, name in of.ofp_port_state_map.items():
                if p.state & bit:
                    pdict[name.split('OFPPS_', 1)[-1].lower()] = True
            ports.append(pdict)
        ports.sort(key=lambda item: item['port_no'])

        rr = {
            'dpid': dpidToStr(dpid),
            'n_tables': con.features.n_tables,
            'ports': ports
        }
        r.append(rr)

    r.sort(key=lambda item: item['dpid'])
    return r
 def _handle_ConnectionUp(self, event):
     current_switch = "s%s" % event.dpid
     for i in range(0, 4):
         # making rules based on MAC addresses
         match = of.ofp_match()
         match.dl_dst = EthAddr(host_MACs[i])
         next_step = next_in_path(current_switch, hosts[i])
         out_port = ports[current_switch][next_step]
         # create a new flow table modification message
         msg = of.ofp_flow_mod()
         # assign this flow table message's match condition to the one above
         msg.match = match
         # make the action for this msg
         msg.actions.append(of.ofp_action_output(port=out_port))
         # send the flow table entry to the switch
         event.connection.send(msg)
         # making rules for ARP packets based on IP addresses
         match = of.ofp_match()
         match.dl_type = 0x806
         match.nw_dst = IPAddr(host_IPs[i])
         next_step = next_in_path(current_switch, hosts[i])
         out_port = ports[current_switch][next_step]
         # create a new flow table modification message
         msg = of.ofp_flow_mod()
         # assign this flow table message's match condition to the one above
         msg.match = match
         # make the action for this msg
         msg.actions.append(of.ofp_action_output(port=out_port))
         # send the flow table entry to the switch
         event.connection.send(msg)
     log.debug("Dijkstra installed on %s", dpidToStr(event.dpid))
Exemple #46
0
    def handle_flowstats_received(self, event):
        #global web_bytes, web_packet
        stats = flow_stats_to_list(event.stats)
        log.debug("FlowStatsReceived from %s: %s",
                  dpidToStr(event.connection.dpid), stats)

        #web_flows = 0
        for f in event.stats:
            #    if f.match.tp_dst == 80 or f.match.tp_src == 80:
            #       if f.match.nw_dst == IPAddr("10.0.0.1"):
            self.web_bytes += f.byte_count
            self.web_packet += f.packet_count
            self.web_flows += 1
        log.info("Flow traffic from %s: %s bytes (%s packets) over %s flows",
                 dpidToStr(event.connection.dpid), self.web_bytes,
                 self.web_packet, self.web_flows)
Exemple #47
0
 def _handle_ConnectionUp(self, event):
     print "switch dpid " + str(
         event.dpid
     )  #it prints the switch connection information, on the screen
     print "Hex dpid: " + str(dpidToStr(event.dpid))
     self.myconnections.append(
         event.connection)  # will pass as a reference to above
Exemple #48
0
    def _handle_ConnectionUp(self, event):

        # Use dpid to differentiate between switches (datapath-id)
        # Each switch has its own flow table. As we'll see in this
        # example we need to write different rules in different tables.
        dpid = dpidToStr(event.dpid)
        log.debug("Switch %s has come up.", dpid)

        if dpid in self.portmap:
            # Writing drop rules at edge switches itself should suffice.
            # It's always better to keep the complexity at edge of the network. (recall NVP)
            log.debug("Writing drop rules for switch %s.", dpid)
            for (srcmac, dstmac) in self.portmap[dpid]:
                msg = of.ofp_flow_mod()
                msg.priority = 200
                # We need to drop packets coming from <inport> and destined for <dstmac>
                msg.match.dl_src = srcmac
                msg.match.dl_dst = dstmac
                event.connection.send(msg)
                # No forwarding action implies drop action

        # Write flood rules for rest of the traffic
        log.debug("Writing flood rules for %s.", dpid)
        msg = of.ofp_flow_mod()
        msg.priority = 100
        msg.actions.append(of.ofp_action_output(port=of.OFPP_FLOOD))
        event.connection.send(msg)

        log.debug("Slicing rules installed on %s", dpid)
def sw_HostPorts(
):  ####for ARP requests. Has dpid as key and ports as values.(Function can be relocated)
    create_neighbourhood_matrix()
    for dpid in dpids:
        host_ports[dpid] = []
        for p in ports[dpidToStr(dpid)].keys():
            if p == 65534:
                continue
            flag = False
            for switchp in switch_neighbourhood[dpid].keys():
                if p is switchp:
                    flag = True
            if flag is False:
                host_ports[dpid].append(p)
        if swdebug:
            print "Host port for", dpidToStr(dpid), " = ", host_ports[dpid]
    def _handle_ConnectionUp(self, event):
        log.info("Switch %s has come up.", dpid_to_str(event.dpid))
        csvfile = open('/home/mininet/pox/pox/misc/firewall-policies.csv',
                       'rb')
        black_list = []
        total_row = 0
        for row in csv.reader(csvfile, delimiter=','):
            black_list.append(row)
            total_row = total_row + 1

        for i in range(1, total_row):
            compare = black_list[i][1] + black_list[i][2]
            log.info("TTTT %s", EthAddr(black_list[i][1]))
            msg = of.ofp_flow_mod()
            msg.match.dl_dst = EthAddr(black_list[i][1])
            msg.match.dl_src = EthAddr(black_list[i][2])
            msg.priority = 100
            msg.actions.append(of.ofp_action_output(port=of.OFPP_NONE))
            event.connection.send(msg)
            '''
			msg2 = of.ofp_flow_mod()
			msg2.match.dl_src=EthAddr(black_list[i][1])
			msg2.match.dl_dst=EthAddr(black_list[i][2])
			msg2.idle_timeout = 10
			msg2.hard_timeout = 30
			msg2.priority = 100
			msg2.actions.append(of.ofp_action_output(port = of.OFPP_NONE))
			msg2.data = event.ofp # 6a
			event.connection.send(msg2)
			'''
            log.info("Firewall rules installed on %s", dpidToStr(event.dpid))
Exemple #51
0
    def _handle_ConnectionUp(self, event):
        sw = self.switches.get(event.dpid)
        sw_str = dpidToStr(event.dpid)
        log.info("Saw switch come up: %s", sw_str)
        name_str = self.t.id_gen(dpid=event.dpid).name_str()
        if name_str not in self.t.switches():
            log.warn("Ignoring unknown switch %s" % sw_str)
            return
        if sw is None:
            log.info("Added fresh switch %s" % sw_str)
            sw = Switch()
            self.switches[event.dpid] = sw
            sw.connect(event.connection)
        else:
            log.info("Odd - already saw switch %s come up" % sw_str)
            sw.connect(event.connection)
        sw.connection.send(of.ofp_set_config(miss_send_len=MISS_SEND_LEN))

        if len(self.switches) == len(self.t.switches()):
            log.info("Woo!  All switches up")
            self.all_switches_up = True
            if self.mode == 'proactive':
                self._install_proactive_flows()
            if self.mode == 'hybrid':
                self._install_hybrid_static_flows()
Exemple #52
0
    def _handle_ConnectionUp(self, event):
        sw = self.switches.get(event.dpid)
        sw_str = dpidToStr(event.dpid)
        self.con = event.connection
        self.mac = self.con.eth_addr
        log.info("Saw switch come up: %s", sw_str)
        name_str = self.t.id_gen(dpid=event.dpid).name_str()
        if name_str not in self.t.switches():
            log.warn("Ignoring unknown switch %s" % sw_str)
            return
        if sw is None:
            log.info("Added fresh switch %s" % sw_str)
            sw = Switch()
            self.switches[event.dpid] = sw
            sw.connect(event.connection)
        else:
            log.info("Odd - already saw switch %s come up" % sw_str)
            sw.connect(event.connection)
        sw.connection.send(of.ofp_set_config(miss_send_len=MISS_SEND_LEN))

        if len(self.switches) == len(self.t.switches()):
            log.info("Woo!  All switches up")
            self.all_switches_up = True
            self._get_all_paths()
        if self.all_switches_up == True:
            self._do_probe()
Exemple #53
0
    def _handle_ConnectionUp(self, event):
        sw = self.switches.get(event.dpid)
        sw_str = dpidToStr(event.dpid)
        sw_name = self.t.id_gen(dpid=event.dpid).name_str()
        self.macTable.clear()  #clear macTable when there is a new conection

        if sw_name not in self.t.switches():
            log.warn("Ignoring unknown switch %s" % sw_str)
            return

        if sw is None:
            log.info("Added a new switch %s" % sw_name)
            sw = Switch()
            self.switches[event.dpid] = sw
            sw.connect(event.connection)
        else:
            log.debug("Odd - already saw switch %s come up" % sw_str)
            sw.connect(event.connection)

        sw.connection.send(of.ofp_set_config(miss_send_len=MISS_SEND_LEN))

        if len(self.switches) == len(self.t.switches()):
            log.info("All of the switches are up")
            if self.mode == 'proactive':
                self._install_proactive_flows()
                log.info("Routing is complete")
            self.all_switches_up = True
        def _handle_PacketIn (self, event):

                # parsing the input packet
                packet = event.parse()

                # updating out mac to port mapping
                self.macToPort[packet.src] = event.port

                if packet.type == packet.LLDP_TYPE or packet.type == 0x86DD:
                        # Drop LLDP packets
                        # Drop IPv6 packets
                        # send of command without actions

                        msg = of.ofp_packet_out()
                        msg.buffer_id = event.ofp.buffer_id
                        msg.in_port = event.port
                        self.connection.send(msg)
                        return
                if packet.dst not in self.macToPort:
                        # does not know out port
                        # flood the packet
                        log.debug("I am inside the switch %s"% (event.dpid))
                        log.debug("Port for %s unknown -- flooding switch " % (packet.dst,))
                        msg = of.ofp_packet_out()
                        msg.actions.append(of.ofp_action_output(port = of.OFPP_FLOOD))
                        msg.buffer_id = event.ofp.buffer_id
                        msg.in_port = event.port
                        self.connection.send(msg)
                        #log.debug("Still flooding")

                else:
                        # installing flow
                        outport = self.macToPort[packet.dst]
                        if outport == event.port:
                                log.warning("Same port for packet from %s -> %s on %s. Drop." %
                                (packet.src, packet.dst, outport), dpidToStr(event.dpid))
                                return
                        log.debug("installing flow for %s.%i -> %s.%i" % (packet.src, event.port, packet.dst, outport))
                        log.debug("this is dpid %s" % dpidToStr(event.dpid))
                        msg = of.ofp_flow_mod()
                        msg.match.dl_src = packet.src
                        msg.match.dl_dst = packet.dst
                        msg.idle_timeout = IDLE_TIMEOUT
                        msg.hard_timeout = HARD_TIMEOUT
                        msg.actions.append(of.ofp_action_output(port = outport))
                        msg.buffer_id = event.ofp.buffer_id
                        self.connection.send(msg)
def _handle_flowstats_received(event):
    stats = flow_stats_to_list(event.stats)  #get event stats
    log.debug("Flow stats received from %s:%s",
              dpidToStr(event.connection.dpid), stats)
    global flow_bytes_past  # last recording flow bytes
    global max_bytes  # max value
    global max_addr  # max value' address

    flow_bytes_now = 0
    flow_bytes = 0
    flow_bandwidth = 0  # bandwidth

    for f in event.stats:
        if f.match.dl_dst == EthAddr("00:00:00:00:00:01"):
            flow_bytes_now += f.byte_count
            if f.byte_count > max_bytes:
                max_bytes = f.byte_count
                max_addr = f.match.dl_src
    flow_bytes = flow_bytes_now - flow_bytes_past
    #flow_bandwidth = (flow_bytes*8.0/5.0)/1000000.0
    flow_bandwidth = (flow_bytes * 8.0) / 1000000.0
    flow_bytes_past = flow_bytes_now
    #if there is data to h1
    if flow_bandwidth >= 0:
        log.info("Traffic to h1 is %s bytes ", flow_bytes)
        log.info("Traffic to h1 is %s  bandwidth ", flow_bandwidth)
        msg = of.ofp_flow_mod()  # create message object
        msg.match = of.ofp_match()
        threshold = 16  # set threshold 16 here
        if flow_bandwidth > threshold:
            msg.match.dl_src = max_addr
            msg.match.dl_dst = EthAddr("00:00:00:00:00:01")
            event.connection.send(msg)
            #if src address is host 2
            if max_addr == EthAddr("00:00:00:00:00:02"):
                log.info("Overload: Packets from h2 are dropped")
            #if src address is host 3
            if max_addr == EthAddr("00:00:00:00:00:03"):
                log.info("Overload: Packets from h3 are dropped")
            #if src address is host 4
            if max_addr == EthAddr("00:00:00:00:00:04"):
                log.info("Overload: Packets from h4 are dropped")
        else:
            msg.match.dl_src = max_addr
            #set msg match's address
            msg.match.dl_dst = EthAddr("00:00:00:00:00:01")
            event.connection.send(msg)
            #if src address is host 2
            if max_addr == EthAddr("00:00:00:00:00:02"):
                log.info("Packets from h2 are forwarded")
        #if src address is host 3
            if max_addr == EthAddr("00:00:00:00:00:03"):
                log.info("Packets from h3 are forwarded")
        #if src address is host 4
            if max_addr == EthAddr("00:00:00:00:00:04"):
                log.info("Packets from h4 are forwarded")
    else:
        #if not exceed the threshold
        log.info("sending packets successfully")
Exemple #56
0
    def _expireLinks(self):
        '''
    Called periodially by a timer to expire links that haven't been
    refreshed recently.
    '''
        curtime = time.time()

        deleteme = []
        for link, timestamp in self.adjacency.iteritems():
            if curtime - timestamp > LINK_TIMEOUT:
                deleteme.append(link)
                log.info('link timeout: %s.%i -> %s.%i' %
                         (dpidToStr(link.dpid1), link.port1,
                          dpidToStr(link.dpid2), link.port2))

        if deleteme:
            self._deleteLinks(deleteme)
Exemple #57
0
def _handle_ConnectionUp(event):
    """
  Be a proactive hub by telling every connected switch to flood all packets
  """
    msg = of.ofp_flow_mod()
    msg.actions.append(of.ofp_action_output(port=of.OFPP_FLOOD))
    event.connection.send(msg)
    log.info("Hubifying %s", dpidToStr(event.dpid))
def find_HostPorts ():
  #print ports
  create_adjacency()
  for dpid in dpids:
    host_ports[dpid] = []
#    print "Host port for",dpidToStr(dpid)
    for allp in ports[dpidToStr(dpid)].keys():
      if allp == 65534:
        continue
      flag = False
      for corep in switch_adjacency[dpid].keys():
#        print "Compare allp",allp," with corep",corep
        if allp is corep:
          flag = True
      if flag is False:
        host_ports[dpid].append(allp)
    print "Host port for",dpidToStr(dpid)," = ",host_ports[dpid] 
Exemple #59
0
def _handle_flowstats_received(event):
    stats = flow_stats_to_list(event.stats)
    log.debug("FlowStatsReceived from %s: %s",
              dpidToStr(event.connection.dpid), stats)

    # Get number of bytes/packets in flows for web traffic only
    web_bytes = 0
    web_flows = 0
    web_packet = 0
    log.info(event.stats)
    for f in event.stats:
        if f.match.tp_dst == 80 or f.match.tp_src == 80:
            web_bytes += f.byte_count
            web_packet += f.packet_count
            web_flows += 1
    log.info("Web traffic from %s: %s bytes (%s packets) over %s flows",
             dpidToStr(event.connection.dpid), web_bytes, web_packet, web_flows)
Exemple #60
0
 def _handle_ConnectionUp(self, event):
     log.info("Creating port-sec table for DPID %s", dpidToStr(event.dpid))
     self.table[event.dpid] = {}
     # check all the switch ports and initialize MAC address counter to zero
     for port in event.ofp.ports:
         log.debug("Init port number: %d, port name: %s" %
                   (port.port_no, port.name))
         self.table[event.dpid][port.port_no] = []