Exemplo n.º 1
0
def _install_shortestpath_arp(match):
    try:
        cross_path=s_ct_lsps[(str(match.nw_src),str(match.nw_dst))]
        src = match.nw_src
        dst = match.nw_dst
    except KeyError:
        cross_path=s_ct_lsps[(str(match.nw_dst),str(match.nw_src))]
        src = match.nw_dst
        dst = match.nw_src
    for i in range(0,len(cross_path)-2,3):
        msg = of.ofp_flow_mod()

        msg.match = of.ofp_match(in_port=match.in_port, dl_type =0x0806, nw_src = src, nw_dst = dst)
        msg.idle_timeout = 500
        msg.flags = of.OFPFF_SEND_FLOW_REM    
        msg.actions.append(of.ofp_action_output(port = cross_path[i+1]))
        log.debug("CROSS_TRAFFIC: Installing forward from switch %s to output port %s", cross_path[i], cross_path[i+1])
        poxcore.openflow.sendToDPID(poxutil.str_to_dpid(cross_path[i]),msg)
        
        rev_msg = of.ofp_flow_mod()

        rev_msg.match = of.ofp_match(in_port=cross_path[i+1], dl_type =0x0806, nw_src = dst, nw_dst = src)
        rev_msg.idle_timeout = 500
        rev_msg.flags = of.OFPFF_SEND_FLOW_REM    
        rev_msg.actions.append(of.ofp_action_output(port = cross_path[i+2]))
        log.debug("CROSS_TRAFFIC: Installing reverse from switch %s to output port %s", cross_path[i], cross_path[i+2])
        poxcore.openflow.sendToDPID(poxutil.str_to_dpid(cross_path[i]),rev_msg)
Exemplo n.º 2
0
 def removeFlowBytes(self, byte_count, sw1, port1, sw2, port2 = None):
     l = self.findLink(sw1 = str_to_dpid(sw1), port1 = port1, sw2 = str_to_dpid(sw2))
     if l is not None:
         log.debug("Found link that i need to decrease prev counter for. From %s to %s", sw1, sw2)
         # log.debug("%s | %s Link Counters before removing FlowRemoved stats--> Prev: %i", l.sw1, l.sw2, l.prev_counter)
         l.prev_counter = l.prev_counter - byte_count # remove total flow removed byte count from counter
         # l.cashed_flrmv_count=f.byte_count # cache value for future use
         log.debug("Decreased prev counter by %i bytes. New counter value is %i", byte_count, l.prev_counter)
Exemplo n.º 3
0
	def _install_flow_bcast(self, mhst):
		for v in mhst._adj_matrix:
			if is_host(v):
				continue
			for u in mhst._adj_matrix[v]:
				# create flow for bcast packet 
				match = of.ofp_match()
				match.dl_type = pkt.ethernet.IP_TYPE
				match.in_port = mhst._adj_matrix[v][u]
				#match.dl_src = EthAddr("00:00:00:FF:FF:FF")
				match.dl_dst = EthAddr("00:00:00:FF:FF:FF")

				msg = of.ofp_flow_mod()
				msg.priority = 40000
				msg.match = match
				#msg.actions.append(of.ofp_action_dl_addr.set_src(EthAddr("00:00:00:FF:FF:FF")))
				for w in mhst._adj_matrix[v]:
					if w != u:
						out_port = mhst._adj_matrix[v][w]
						# if output link to host change dst mac addr to that machine
						#if is_host(w):
						#	dl_dst = self._host_list[w].mac_address
						#	msg.actions.append(of.ofp_action_dl_addr.set_dst(dl_dst))
						msg.actions.append(of.ofp_action_output(port = out_port))

				self._datapath_list[str_to_dpid(v)].connection.send(msg)
def launch (transparent=False, hold_down=_flood_delay, ignore = None):

  url = 'amqp://*****:*****@dinosaur.rmq.cloudamqp.com/cuvzmrst'

  params = pika.URLParameters(url)
  connection = pika.BlockingConnection(params)
  threading._start_new_thread(subs,())
  threading._start_new_thread(pub,())
  channel = connection.channel()
  channel.queue_declare(queue='pub2', durable=True)
  print('')
  message = "Controller 1 aktif"
  channel.basic_publish(exchange='',
                      routing_key='pub2',
                      body=message,
                      properties=pika.BasicProperties(
                         delivery_mode = 2, # make message persistent
                      ))
  print("%r" % message)

  """
  Starts an L2 learning switch.
  """
  try:
    global _flood_delay
    _flood_delay = int(str(hold_down), 10)
    assert _flood_delay >= 0
  except:
    raise RuntimeError("Expected hold-down to be a number")

  if ignore:
    ignore = ignore.replace(',', ' ').split()
    ignore = set(str_to_dpid(dpid) for dpid in ignore)
  print('')
  core.registerNew(l2_learning, str_to_bool(transparent), ignore)
Exemplo n.º 5
0
	def _install_flow_shortest_path(self, src_host, dst_host):
		src_host = str(src_host)
		dst_host = str(dst_host)

		(path, out_ports, in_ports) = self._host_host_path[src_host][dst_host]
		for dp, out_port, in_port in zip(path, out_ports, in_ports):
			
			#nw_tos|tp_dst|dl_dst|dl_src|in_port|dl_vlan_pcp|nw_proto|dl_vlan|tp_src|dl_type|nw_src(/0)|nw_dst(/0)

			# create flow for send src to dst in shortest path
			match = of.ofp_match()
			match.dl_type = pkt.ethernet.IP_TYPE
			match.in_port = in_port
			match.nw_src = IPAddr(src_host)
			match.nw_dst = IPAddr(dst_host)

			msg = of.ofp_flow_mod()
			msg.priority = 30000
			msg.match = match
			msg.actions.append(of.ofp_action_output(port = out_port))

			self._datapath_list[str_to_dpid(dp)].connection.send(msg)

			# special match that check source MAC address
			"""
Exemplo n.º 6
0
def launch(ip, servers, ignore_dpid):
    servers = servers.replace(",", " ").split()
    servers = [IPAddr(x) for x in servers]
    ip = IPAddr(ip)
    ignore_dpid = str_to_dpid(ignore_dpid)

    # Boot up ARP Responder
    from proto.arp_responder import launch as arp_launch
    arp_launch(eat_packets=False, **{str(ip): True})
    import logging
    logging.getLogger("proto.arp_responder").setLevel(logging.WARN)

    def _handle_ConnectionUp(event):
        global _dpid
        if _dpid is None:
            log.info("IP Load Balancer Ready.")
            core.registerNew(iplb, event.connection, IPAddr(ip), servers)
            _dpid = event.dpid
        if event.dpid != ignore_dpid:
            core.getLogger().info("Connection %s" % (event.connection, ))
            LearningSwitch(event.connection, False)

        if _dpid != event.dpid:
            log.warn("Ignoring switch %s", event.connection)
        else:
            log.info("Load Balancing on %s", event.connection)

            # Gross hack
            core.iplb.con = event.connection
            event.connection.addListeners(core.iplb)

    core.openflow.addListenerByName("ConnectionUp", _handle_ConnectionUp)
Exemplo n.º 7
0
def Ping(s1,s2):
	global t1
	port1 = 0
	port2 = 0
	mac1 = 0
	mac2 = 0
	ip1 = 0
	ip2 = 0
	for item in Switch_set:
		if s1 == item:
			for item1 in Switch_set[item]:
				if s2 == Switch_set[item][item1][0]:
					port1 = item1
					port2 = Switch_set[item][item1][1]
					break
				else:
					continue
	# print s1,s2
	for dpid in ArpTable:
		if s1 == dpid:
			for ip in ArpTable[dpid]:
				if ArpTable[dpid][ip][0] == port1:
					ip1 = ip
					mac1 = ArpTable[dpid][ip][1]
					break
		elif s2 == dpid:
			for ip in ArpTable[dpid]:
				if ArpTable[dpid][ip][0] == port2:
					ip2 = ip
					mac2 = ArpTable[dpid][ip][1]
					break
	for i in [ip1,ip2,mac1,mac2]:
		if not i:
			return False
	icmp = pkt.icmp()
	icmp.type = pkt.ICMP.TYPE_ECHO_REQUEST
	icmp.payload = "PingPing" * 6

	ipp = pkt.ipv4()
	ipp.protocol = ipv4.ICMP_PROTOCOL
	ipp.srcip = IPAddr(ip1)
	ipp.dstip = IPAddr(ip2)
	ipp.payload = icmp

	e = pkt.ethernet()
	e.src = mac1
	e.dst = mac2
	e.type = ethernet.IP_TYPE
	e.payload = ipp
	# print "Send Packets!"
	# print mac1,mac2,ip1,ip2
	for i in range(10):
		msg = of.ofp_packet_out()
		msg.actions.append(of.ofp_action_output(port = port2))
		msg.data = e.pack()
		core.openflow.sendToDPID(str_to_dpid(s2), msg)
		t1[(s1,s2)]+=time.time()
		# print t1
	return True
Exemplo n.º 8
0
def launch (mss_dpid = "00-00-00-01-00-00|1", mss_ip = None,
            mcs_dpid = "00-00-00-02-00-00|2",
            dcs_dpids = ["00-00-00-01-01-00|101", "00-00-00-01-02-00|102",
                       "00-00-00-01-03-00|103"],
            dcs_load=[(1.0/3, [1.0/3, 1.0/3, 1.0/3]),
                      (1.0/3, [1.0/3, 1.0/3, 1.0/3]),
                      (1.0/3, [1.0/3, 1.0/3, 1.0/3])]):

    if mss_ip is None:
        mss_ip = IPAddr("10.254.254.254")

    mss_dpid = poxutil.str_to_dpid(mss_dpid)
    mcs_dpid = poxutil.str_to_dpid(mcs_dpid)
    for i in range(len(dcs_dpids)):
        dcs_dpids[i] = poxutil.str_to_dpid(dcs_dpids[i])

    core.registerNew(PSIKComponent, mss_dpid, mss_ip, mcs_dpid, dcs_dpids, DecisionType.DEC_STATIC, dcs_load)
Exemplo n.º 9
0
def do_launch(cls,
              address='127.0.0.1',
              port=6633,
              max_retry_delay=16,
              dpid=None,
              extra_args=None,
              **kw):
    """
  Used for implementing custom switch launching functions

  cls is the class of the switch you want to add.

  Returns switch instance.
  """
    print(" DATAPATH : IN DO LAUNCH")
    if extra_args is not None:
        import ast
        extra_args = ast.literal_eval('{%s}' % (extra_args, ))
        kw.update(extra_args)

    from pox.core import core
    if not core.hasComponent('datapaths'):
        core.register("datapaths", {})
    _switches = core.datapaths

    if dpid is None:
        for dpid in range(1, 256):
            if dpid not in _switches: break
        if dpid in _switches:
            raise RuntimeError("Out of DPIDs")
    else:
        dpid = str_to_dpid(dpid)

    switch = cls(dpid=dpid, name="sw" + str(dpid), **kw)
    _switches[dpid] = switch

    switches[dpid] = switch

    port = int(port)
    max_retry_delay = int(max_retry_delay)

    def up(event):
        import pox.lib.ioworker
        global loop
        loop = pox.lib.ioworker.RecocoIOLoop()
        #loop.more_debugging = True
        loop.start()
        OpenFlowWorker.begin(loop=loop,
                             addr=address,
                             port=port,
                             max_retry_delay=max_retry_delay,
                             switch=switch)

    from pox.core import core

    core.addListenerByName("UpEvent", up)

    return switch
Exemplo n.º 10
0
def launch(transparent=False, ignore=None):
    """
    Main entrance of this component.
    """
    if ignore:
        ignore = ignore.replace(',', ' ').split()
        ignore = set(str_to_dpid(dpid) for dpid in ignore)

    core.registerNew(DirectLivestreaming, str_to_bool(transparent), ignore)
def launch(ip, servers, dpid=None):

    disable_flood = False

    global all_ports
    if disable_flood:
        all_ports = of.OFPP_ALL

    #core.openflow.addListenerByName("PacketIn", _handle_PacketIn)

    log.info("Pair-Learning switch running.")
    global _dpid
    if dpid is not None:
        _dpid = str_to_dpid(dpid)

    servers = servers.replace(",", " ").split()
    servers = [IPAddr(x) for x in servers]
    ip = IPAddr(ip)

    # We only want to enable ARP Responder *only* on the load balancer switch,
    # so we do some disgusting hackery and then boot it up.
    from proto.arp_responder import ARPResponder
    old_pi = ARPResponder._handle_PacketIn

    def new_pi(self, event):
        if event.dpid == _dpid:
            # Yes, the packet-in is on the right switch
            return old_pi(self, event)

    ARPResponder._handle_PacketIn = new_pi

    # Hackery done.  Now start it.
    from proto.arp_responder import launch as arp_launch
    arp_launch(eat_packets=False, **{str(ip): True})
    import logging
    logging.getLogger("proto.arp_responder").setLevel(logging.WARN)

    def _handle_ConnectionUp(event):
        global _dpid
        if _dpid is None:
            _dpid = event.dpid

        if _dpid != event.dpid:
            log.warn("Ignoring switch %s", event.connection)
        else:
            if not core.hasComponent('iplb'):
                # Need to initialize first...
                core.registerNew(iplb, event.connection, IPAddr(ip), servers)
                log.info("IP Load Balancer Ready.")
            log.info("Load Balancing on %s", event.connection)

            # Gross hack
            core.iplb.con = event.connection
            event.connection.addListeners(core.iplb)

    core.openflow.addListenerByName("ConnectionUp", _handle_ConnectionUp)
Exemplo n.º 12
0
 def _send_arp_buffer(self,dpid,dst_ip,mac,outport):
     if (dpid,dst_ip) in self.arp_buffers:
         log.debug("[%s] Send buffered arp packets to %s",dpid,dst_ip)
         buffers = self.arp_buffers[(dpid,dst_ip)]
         del self.arp_buffers[(dpid,dst_ip)]
         for entry in buffers:
             msg = of.ofp_packet_out(buffer_id=entry[1],in_port=entry[2])
             msg.actions.append(of.ofp_action_dl_addr.set_dst(mac))
             msg.actions.append(of.ofp_action_output(port=outport))
             core.openflow.sendToDPID(str_to_dpid(dpid),msg)
Exemplo n.º 13
0
def launch (ignore = None):
  #Inicializa o controlador
  if ignore:
    ignore = ignore.replace(',', ' ').split()
    ignore = set(str_to_dpid(dpid) for dpid in ignore)
  #Cria arquivo de estatisticas
  f = open("info_sw.txt", "a+")
  f.write ("Tempo Switch RegrasInstaladas RegrasAceitas VezesBloqueado BytesEnviados\n")
  f.close()
  core.registerNew(l2_learning, ignore)
Exemplo n.º 14
0
 def get_sw(arg, fail=True):
     r = _switches.get(arg)
     if r is not None: return r
     try:
         dpid = str_to_dpid(arg)
     except Exception:
         raise RuntimeError("No such switch as %s" % (arg, ))
     r = core.datapaths.get(dpid)
     if r is None and fail:
         raise RuntimeError("No such switch as %s" % (dpid_to_str(dpid), ))
     return r
Exemplo n.º 15
0
        def _get_config():
            log.debug('Config Module is loaded!')

            self.arp_table = ARPTableSet()
            for dpid in core.SRPConfig.tor_list:
                self.arp_table[dpid] = ARPTable()
                ip = IPAddr(parse_cidr(core.SRPConfig.get_tor_lan_addr(dpid))[0])
                self.arp_table[dpid][ip] = Entry(_dpid_to_mac(str_to_dpid(dpid)), static=True)
                for k, v in kwargs.iteritems():
                    self.arp_table[dpid][IPAddr(k)] = Entry(v, static=True)
            core.Interactive.variables['arp'] = self.arp_table
Exemplo n.º 16
0
 def updateLinkCounters(self, sw, port, byte_count): # called by monitoring module to update link info after polling
     l = self.findLinkByReceiver(sw2 = str_to_dpid(sw), port2 = port)
     if l is not None:
         log.debug("Found link that i need to increment current counter for. From %s, port:%i to %s, port:%i", l.sw1, l.port1, l.sw2, l.port2)
         if l.first_poll is True:
             l.cur_counter = byte_count
             l.prev_counter = byte_count
             l.first_poll = False
         else:
             l.cur_counter = byte_count # calculate accumulated byte count for this polling period
             log.debug("Updated current counter by %i bytes. New counter value is %i", byte_count, l.cur_counter)
Exemplo n.º 17
0
def launch(transparent=False, hold_down=_flood_delay, ignore=None):
    try:
        global _flood_delay
        _flood_delay = int(str(hold_down), 10)
        assert _flood_delay >= 0
    except:
        raise RuntimeError("Expected hold-down to be a number")
    if ignore:
        ignore = ignore.replace(',', ' ').split()
        ignore = set(str_to_dpid(dpid) for dpid in ignore)
    core.registerNew(l2_learning, str_to_bool(transparent), ignore)
Exemplo n.º 18
0
Arquivo: util.py Projeto: voidcc/PCTRL
 def _add_dpid (self, dpid):
     if dpid is True:
         # Special case -- everything!
         self._dpids = True
         return
     elif self._dpids is True:
         self._dpids = set()
     try:
         dpid = int(dpid)
     except:
         dpid = str_to_dpid(dpid)
     self._dpids.add(dpid)
Exemplo n.º 19
0
Arquivo: util.py Projeto: kingfs/PCTRL
 def _add_dpid(self, dpid):
     if dpid is True:
         # Special case -- everything!
         self._dpids = True
         return
     elif self._dpids is True:
         self._dpids = set()
     try:
         dpid = int(dpid)
     except:
         dpid = str_to_dpid(dpid)
     self._dpids.add(dpid)
Exemplo n.º 20
0
def do_launch(cls, standalone, address='127.0.0.1', port=6633, max_retry_delay=16,
              dpid=None, extra_args=None, **kw):
    """
    Used for implementing custom switch launching functions

    cls is the class of the switch you want to add.

    Returns switch instance.
    """

    if extra_args is not None:
        import ast

        extra_args = ast.literal_eval('{%s}' % (extra_args,))
        kw.update(extra_args)

    from pox.core import core

    if not core.hasComponent('datapaths'):
        core.register("datapaths", {})
    _switches = core.datapaths

    if dpid is None:
        for dpid in range(1, 256):
            if dpid not in _switches: break
        if dpid in _switches:
            raise RuntimeError("Out of DPIDs")
    else:
        dpid = str_to_dpid(dpid)

    switch = cls(dpid=dpid, name="sw" + str(dpid), **kw)
    _switches[dpid] = switch

    port = int(port)
    max_retry_delay = int(max_retry_delay)

    def up(event):
        import pox.lib.ioworker

        global loop
        loop = pox.lib.ioworker.RecocoIOLoop()
        # loop.more_debugging = True
        loop.start()
        OpenFlowWorker.begin(loop=loop, addr=address, port=port,
                             max_retry_delay=max_retry_delay, switch=switch)

    from pox.core import core

    if not standalone:
        core.addListenerByName("UpEvent", up)

    return switch
Exemplo n.º 21
0
def launch(dpid, outside_port, subnet='172.16.1.0/24', inside_ip='172.16.1.1'):

    import pox.proto.dhcp_client as dc
    dc.launch(dpid=dpid, port=outside_port, port_eth=True)

    import pox.proto.arp_helper as ah
    ah.launch(use_port_mac=True)

    dpid = str_to_dpid(dpid)
    inside_ip = IPAddr(inside_ip)

    pool = SimpleAddressPool(network=subnet, first=100, last=199)

    core.registerNew(NATDHCPD,
                     install_flow=True,
                     pool=pool,
                     ip_address=inside_ip,
                     router_address=inside_ip,
                     dns_address=inside_ip,
                     dpid=dpid,
                     outside_port=outside_port)

    def got_lease(event):
        outside_ip = event.lease.address

        if not event.lease.routers:
            log.error(
                "Can't start NAT because we didn't get an upstream gateway")
            return
        gateway_ip = event.lease.routers[0]

        if event.lease.dns_servers:
            dns_ip = event.lease.dns_servers[0]
        else:
            dns_ip = None

        log.debug('Starting NAT')

        n = NAT(inside_ip,
                outside_ip,
                gateway_ip,
                dns_ip,
                outside_port,
                dpid,
                subnet=subnet)
        core.register(n)

    def init():
        log.debug('Waiting for DHCP lease on port %s', outside_port)
        core.DHCPClient.addListenerByName('DHCPLeased', got_lease)

    core.call_when_ready(init, ['DHCPClient'])
Exemplo n.º 22
0
 def _handle_ipv4_buffer_expiration(self):
     empty = []
     for k, v in self.ipv4_buffers.iteritems():
         dpid, ip = k
         for item in list(v):
             expires_at, buffer_id, in_port = item
             if expires_at < time.time():
                 v.remove(item)
                 #不为packet out消息指定outport action,则默认使DPID丢弃该报文
                 msg = of.ofp_packet_out(buffer_id=buffer_id, in_port=in_port)
                 core.openflow.sendToDPID(str_to_dpid(dpid), msg)
         if len(v) == 0:
             empty.append(k)
     for k in empty:
         del self.ipv4_buffers[k]
def recv_manager_command():  #thread
    s = socket(AF_INET, SOCK_STREAM)
    s.bind(('', ManagerPort))
    s.listen(5)
    while True:
        conn, addr = s.accept()
        message = conn.recv(1024)
        command = message.split('->')
        if command[0] == 'server':
            core.l2_multi.raiseEvent(RtpFromServer, IPAddr(command[1]),
                                     int(command[2]))
        elif command[0] == 'switch':
            core.l2_multi.raiseEvent(RtpFromSwitch, str_to_dpid(command[1]),
                                     IPAddr(command[2]), int(command[3]))
        elif command[0] == 'init':
            threading.Thread(target=send_path_map, args=()).start()
    def _handle_RtpFromServer(self, event):

        clientMac = clientIP_mac[event.clientIP]
        dest = mac_map[clientMac]
        serverswitch = switches[str_to_dpid(ServerSwitchDpid)]
        p = _get_path(serverswitch, dest[0], ServerPort, dest[1])

        match = of.ofp_match()
        match.dl_type = pkt.ethernet.IP_TYPE
        match.dl_src = EthAddr(ServerMac)
        match.dl_dst = clientMac
        match.nw_proto = pkt.ipv4.UDP_PROTOCOL
        match.nw_src = IPAddr(ServerIP)
        match.nw_dst = event.clientIP

        _install_rtp_path(p, match, event.dumpPort)
Exemplo n.º 25
0
def launch (transparent=False, hold_down=_flood_delay, ignore = None):
  """
  Starts an L2 learning switch.
  """
  try:
    global _flood_delay
    _flood_delay = int(str(hold_down), 10)
    assert _flood_delay >= 0
  except:
    raise RuntimeError("Expected hold-down to be a number")

  if ignore:
    ignore = ignore.replace(',', ' ').split()
    ignore = set(str_to_dpid(dpid) for dpid in ignore)

  core.registerNew(l2_learning, str_to_bool(transparent), ignore)
Exemplo n.º 26
0
def launch (ip, servers, dpid = None):
  global _dpid
  if dpid is not None:
    _dpid = str_to_dpid(dpid)

  servers = servers.replace(","," ").split()
  servers = [IPAddr(x) for x in servers]
  ip = IPAddr(ip)
  

  from proto.arp_responder import ARPResponder
  old_pi = ARPResponder._handle_PacketIn
  def new_pi (self, event):
    if event.dpid == _dpid:
      # Yes, the packet-in is on the right switch
      return old_pi(self, event)
  ARPResponder._handle_PacketIn = new_pi

  # Hackery done.  Now start it.
  from proto.arp_responder import launch as arp_launch
  arp_launch(eat_packets=False,**{str(ip):True})
  import logging
  logging.getLogger("proto.arp_responder").setLevel(logging.WARN)


  def _handle_ConnectionUp (event):
    global _dpid
    if _dpid is None:
      _dpid = event.dpid

    if _dpid != event.dpid:
      log.warn("Ignoring switch %s", event.connection)
      LearningSwitch(event.connection, False)
    else:
      if not core.hasComponent('iplb'):
        # Need to initialize first...
        core.registerNew(iplb, event.connection, IPAddr(ip), servers)
	#log.info("DPID:", _dpid)
        log.info("IP Load Balancer Ready.")
      log.info("Load Balancing on %s", event.connection)

      # Gross hack
      core.iplb.con = event.connection
      event.connection.addListeners(core.iplb)


  core.openflow.addListenerByName("ConnectionUp", _handle_ConnectionUp)
Exemplo n.º 27
0
def launch (ip, servers, dpid = None):
  global _dpid
  if dpid is not None:
    _dpid = str_to_dpid(dpid)

  servers = servers.replace(","," ").split()
  servers = [IPAddr(x) for x in servers]
  ip = IPAddr(ip)


  # We only want to enable ARP Responder *only* on the load balancer switch,
  # so we do some disgusting hackery and then boot it up.
  from proto.arp_responder import ARPResponder
  old_pi = ARPResponder._handle_PacketIn
  def new_pi (self, event):
    if event.dpid == _dpid:
      # Yes, the packet-in is on the right switch
      return old_pi(self, event)
  ARPResponder._handle_PacketIn = new_pi

  # Hackery done.  Now start it.
  from proto.arp_responder import launch as arp_launch
  arp_launch(eat_packets=False,**{str(ip):True})
  import logging
  logging.getLogger("proto.arp_responder").setLevel(logging.WARN)


  def _handle_ConnectionUp (event):
    global _dpid
    if _dpid is None:
      _dpid = event.dpid

    if _dpid != event.dpid:
      log.warn("Ignoring switch %s", event.connection)
    else:
      if not core.hasComponent('iplb'):
        # Need to initialize first...
        core.registerNew(iplb, event.connection, IPAddr(ip), servers)
        log.info("IP Load Balancer Ready.")
      log.info("Load Balancing on %s", event.connection)

      # Gross hack
      core.iplb.con = event.connection
      event.connection.addListeners(core.iplb)


  core.openflow.addListenerByName("ConnectionUp", _handle_ConnectionUp)
def launch(transparent=False, hold_down=gFloodDelay, ignore=None):
    #
    # Now let's get started
    #
    try:
        global gFloodDelay
        # class int(x)->int or int(x, base=10)
        gFloodDelay = int(str(hold_down))
        assert gFloodDelay >= 0
    except:
        raise RuntimeError("Hold-down should be a real number")

    if ignore:
        ignore = ignore.replace(',', ' ').split()
        ignore = set(str_to_dpid(dpid) for dpid in ignore)

    core.registerNew(l2_learning, str_to_bool(transparent), ignore)
Exemplo n.º 29
0
    def __init__(self):
        core.openflow_discovery.addListeners(self)
        core.openflow.addListeners(self)

        self.brid = {}
        self.connections = defaultdict(lambda:None)
        for i in range(1,5):
            self.brid['br{}'.format(i)] = str_to_dpid("fe-fe-00-0a-ff-0{}".format(i))

        # Dict of dicts. [sw1][sw2] return port of sw1 connected to sw2
        # Also used for port location of adjacent mac addrs:
        # [sw][mac] -> port of switch connected to mac
        # self.switch_adjacency = defaultdict(lambda:defaultdict(lambda:None))

        # self.table = dict()

        self.switches = dict()
Exemplo n.º 30
0
def launch (dpid, outside_port, subnet = '172.16.1.0/24',
            inside_ip = '172.16.1.1'):

  import pox.proto.dhcp_client as dc
  dc.launch(dpid = dpid, port = outside_port, port_eth = True)

  import pox.proto.arp_helper as ah
  ah.launch(use_port_mac = True)

  dpid = str_to_dpid(dpid)
  inside_ip = IPAddr(inside_ip)

  pool = SimpleAddressPool(network = subnet, first = 100, last = 199)

  core.registerNew(NATDHCPD, install_flow = True, pool = pool,
                   ip_address = inside_ip, router_address = inside_ip,
                   dns_address = inside_ip, dpid = dpid,
                   outside_port = outside_port)


  def got_lease (event):
    outside_ip = event.lease.address

    if not event.lease.routers:
      log.error("Can't start NAT because we didn't get an upstream gateway")
      return
    gateway_ip = event.lease.routers[0]

    if event.lease.dns_servers:
      dns_ip = event.lease.dns_servers[0]
    else:
      dns_ip = None

    log.debug('Starting NAT')

    n = NAT(inside_ip, outside_ip, gateway_ip, dns_ip, outside_port, dpid,
            subnet=subnet)
    core.register(n)


  def init ():
    log.debug('Waiting for DHCP lease on port %s', outside_port)
    core.DHCPClient.addListenerByName('DHCPLeased', got_lease)

  core.call_when_ready(init, ['DHCPClient'])
Exemplo n.º 31
0
def launch(ip, servers, lb_dpid, weights=None):
    global _dpid, LBinitDone
    try:

        servers = servers.replace(",", " ").split()
        servers = [IPAddr(x) for x in servers]
        if weights is not None:
            weights = weights.replace(",", " ").split()
            weights = [int(x) for x in weights]
        ip = IPAddr(ip)
        _dpid = str_to_dpid(lb_dpid)

        # Boot up ARP Responder
        from proto.arp_responder import launch as arp_launch
        arp_launch(eat_packets=False, **{str(ip): True})
        import logging
        logging.getLogger("proto.arp_responder").setLevel(logging.WARN)

        def _handle_ConnectionUp(event):
            global _dpid, LBinitDone

            # if event.dpid is not same as provided LB's dpid, start learning switch
            if _dpid != event.dpid:
                log.warn("NOT LB switch %s. Will run learning mode",
                         event.connection)
                LearningSwitch(event.connection, False)
            else:
                # this is LB's switch. init if not done already
                if (LBinitDone != 1):
                    log.info("IP Load Balancer Ready.")
                    core.registerNew(iplb, event.connection, IPAddr(ip),
                                     servers, weights)
                    LBinitDone = 1

                log.info("Load Balancing on %s", event.connection)

                # Gross hack
                core.iplb.con = event.connection
                event.connection.addListeners(core.iplb)

    except Exception as ex:
        print ex

    core.openflow.addListenerByName("ConnectionUp", _handle_ConnectionUp)
Exemplo n.º 32
0
def launch(transparent=False,
           hold_down=_flood_delay,
           ignore=None,
           droplist_client=[],
           droplist_server=[]):
    """
    Starts an L2 droplist switch.
    """
    try:
        global _flood_delay
        _flood_delay = int(str(hold_down), 10)
        assert _flood_delay >= 0
    except:
        raise RuntimeError("Expected hold-down to be a number")

    if ignore:
        ignore = ignore.replace(',', ' ').split()
        ignore = set(str_to_dpid(dpid) for dpid in ignore)

    core.registerNew(l2_dropper, str_to_bool(transparent), ignore,
                     droplist_client, droplist_server)
Exemplo n.º 33
0
 def subscribe(stream):
     """
 Runs as a separate thread, and listen to connection up/down messages published on kafka.
 :param stream: ip address and port of kafka or zookeeper host e.g 192.168.56.1:9092
 """
     consumer = KafkaConsumer('of_connections', bootstrap_servers=stream)
     for msg in consumer:
         msg = msg.value
         action, dpid = msg.split('#')
         if action == 'add':
             dpid = str_to_dpid(dpid)
             if dpid not in core.openflow.connections:
                 # new connection
                 con = hctrl.__conn(dpid)
                 core.openflow._connect(con)
                 log.info("subscriber: new connection from {}".format(
                     dpid_to_str(con.dpid)))
         else:
             # delete connection
             core.openflow._disconnect(dpid)
             log.info("subscriber: connection down from {}".format(dpid))
     log.info("subscriber: shutting down...")
Exemplo n.º 34
0
def launch (dpid, port, port_eth = None, name = None, __INSTANCE__ = None):
  """
  Launch

  port_eth unspecified: "DPID MAC"
  port_eth enabled: Port MAC
  port_eth specified: Use that
  """
  if port_eth in (True, None):
    pass
  else:
    port_eth = EthAddr(port_eth)

  dpid = str_to_dpid(dpid)
  try:
    port = int(port)
  except:
    pass

  def dhcpclient_init ():
    n = name
    if n is None:
      s = ''
      while True:
        if not core.hasComponent("DHCPClient" + s):
          n = "DHCPClient" + s
          break
        s = str(int('0' + s) + 1)
    else:
      if core.hasComponent(n):
        self.log.error("Already have component %s", n)
        return

    client = DHCPClient(port=port, dpid=dpid, name=n, port_eth=port_eth)
    core.register(n, client)

  core.call_when_ready(dhcpclient_init, ['openflow'])
Exemplo n.º 35
0
def launch(dpid, port, port_eth=None, name=None, __INSTANCE__=None):
    """
  Launch

  port_eth unspecified: "DPID MAC"
  port_eth enabled: Port MAC
  port_eth specified: Use that
  """
    if port_eth in (True, None):
        pass
    else:
        port_eth = EthAddr(port_eth)

    dpid = str_to_dpid(dpid)
    try:
        port = int(port)
    except:
        pass

    def dhcpclient_init():
        n = name
        if n is None:
            s = ''
            while True:
                if not core.hasComponent("DHCPClient" + s):
                    n = "DHCPClient" + s
                    break
                s = str(int('0' + s) + 1)
        else:
            if core.hasComponent(n):
                self.log.error("Already have component %s", n)
                return

        client = DHCPClient(port=port, dpid=dpid, name=n, port_eth=port_eth)
        core.register(n, client)

    core.call_when_ready(dhcpclient_init, ['openflow'])
Exemplo n.º 36
0
def launch (ip, servers, dpid = None):
  global _dpid
  if dpid is not None:
    _dpid = str_to_dpid(dpid)

  servers = servers.replace(","," ").split()
  servers = [IPAddr(x) for x in servers]
  ip = IPAddr(ip)


  # We only want to enable ARP Responder *only* on the load balancer switch,
  # so we do some disgusting hackery and then boot it up.
  from proto.arp_responder import ARPResponder
  old_pi = ARPResponder._handle_PacketIn
  def new_pi (self, event):

   if event.dpid == _dpid:
      # Yes, the packet-in is on the right switch
      return old_pi(self, event)
  ARPResponder._handle_PacketIn = new_pi

  # Hackery done.  Now start it.
  from proto.arp_responder import launch as arp_launch
  arp_launch(eat_packets=False,**{str(ip):True})
  import logging
  logging.getLogger("proto.arp_responder").setLevel(logging.WARN)


  def _handle_ConnectionUp (event):
    global _dpid
    if _dpid is None:
      _dpid = event.dpid

    if _dpid != event.dpid:
      log.warn("Ignoring switch %s", event.connection)
   else:
Exemplo n.º 37
0
def launch (topo):
  """
  Launch the Megaswitch component

  This is called to intialize this component.  Commandline arguments to this
  component show up as arguments to this function.  We take "topo", which
  should be the filename of a topology file.
  """
  # We're given a topology file.  Quite possibly the same exact one as used by
  # garnet.  Let's load it and then do a little processing of the graph here to
  # remove hosts and convert any string-format DPIDs to numeric DPIDs.
  g = gutil.get_graph(topo)

  bad_nodes = set() # Things that aren't usable switches
  g.names = {}

  for n,info in g.nodes(data=True):
    if info.get('entity_type','').lower() == 'host':
      # Skip hosts
      bad_nodes.add(n)
      continue
    if 'dpid' not in info:
      # Our switches need DPIDs!
      bad_nodes.add(n)
      continue

    # Fix string DPIDs
    dpid = info['dpid']
    if isinstance(dpid, str):
      info['dpid'] = str_to_dpid(dpid)
    g.names[info['dpid']] = n

  g.remove_nodes_from(bad_nodes)  

  # Create the component and "register" it on the POX core object
  core.registerNew(Megaswitch, topo_graph=g)
Exemplo n.º 38
0
 def updateLinkCounters(self, byte_count, sw1, port1, sw2, port2 = None): # called by monitoring module to update link info after polling
     l = self.findLink(sw1 = str_to_dpid(sw1), port1 = port1, sw2 = str_to_dpid(sw2))
     if l is not None:
         log.debug("Found link that i need to increment current counter for. From %s to %s", sw1, sw2)
         l.cur_counter = l.cur_counter + byte_count # calculate accumulated byte count for this polling period
         log.debug("Incremented current counter by %i bytes. New counter value is %i", byte_count, l.cur_counter)
Exemplo n.º 39
0
def _install_path(conn_dpid, match, init_event, src, ofp_in_port):
    global ct_called
    #log.debug("CROSSTRAFFIC: check port %d", match.tp_dst)
    #log.debug("CROSSTRAFFIC_MATCH: check port %s", match)
    
    #if match.nw_dst != "10.10.10.3" and match.nw_src== "10.10.10.2" and match.nw_src == "10.10.10.4" or match.nw_src == "10.10.10.6" or match.nw_src == "10.10.10.11" or match.nw_src == "10.10.10.7":
    if match.nw_dst in cross_list and match.nw_src in cross_list:
            _install_shortestpath(match)
            log.debug("Calling Cross Traffic %s"%match.nw_src)
            ct_called = True
            return 0
    
    #best_bw=0
    log.debug("****************SOURCE %s and DESTINATION %s******************\n"%(match.nw_src,match.nw_dst))
    #if str(match.nw_src) in client_list and str(match.nw_src) not in server_list:
     # if str(match.nw_dst) not in client_list and str(match.nw_dst) not in server_list:

    print "***************Programmed Path*************\n"
    for i in client_list:
        print i
    if ((match.nw_dst in client_port.keys() and match.nw_src in server_list) or (match.nw_dst in server_list and match.nw_src in client_port.keys())) :
        if match.nw_dst in server_list:
            serv_index = server_list.index(match.nw_dst)
            #print server_list[serv_index]
        elif match.nw_dst in client_port.keys():
            client_index = clientip_list.index((str(match.nw_dst)[0:10]))
            client_ip_new = str(match.nw_dst)
            #print clientip_list[client_index]
        if match.nw_src in server_list:
            serv_index = server_list.index(match.nw_src)
            #print server_list[serv_index]
        elif match.nw_src in client_port.keys():
            client_index = clientip_list.index((str(match.nw_src)[0:10]))
            client_ip_new = str(match.nw_src)
            #print clientip_list[client_index]
        log.debug("Client Index is %d and Server Index is %d and CLient IP %s",client_index,serv_index,client_ip_new)
        best_path = s_keys[client_index][serv_index]
    best_bw = s_lsps[s_keys[client_index][serv_index]][0]
    '''   
    for j in range (len(s_keys[client_index])):
       print s_keys[i][j] 
       for k in range (len(s_lsps[s_keys[i][j]][2])):
        print s_lsps[s_keys[i][j]][0]
        if best_bw > s_lsps[s_keys[i][j]][0]:
            best_path, best_bw = s_keys[i][j], s_lsps[s_keys[i][j]][0]
       log.debug("BESTPATH: %s and BESTBW = %d", best_path, best_bw)
    '''
    packet = init_event.parsed
    first_in  = init_event.port
    #s_lsps[best_path][2][2] = client_port[client_ip_new]
    for i in range(0,len(s_lsps[best_path][2])-2,3): #for switch in path.keys():  
        #log.debug("INSTALLING : VALUE OF i %d and Length %d", i, len(s_lsps[best_path][2]))
        cur_sw = s_lsps[best_path][2][i]


        #rev_msg = of.ofp_flow_mod()
        '''
        rev_msg.match = match
        rev_msg.match.nw_dst, rev_msg.match.nw_src = rev_msg.match.nw_src , rev_msg.match.nw_dst
        rev_msg.match.dl_dst, rev_msg.match.dl_src = rev_msg.match.dl_src, rev_msg.match.dl_dst
        rev_msg.match.tp_src, rev_msg.match.tp_dst = rev_msg.match.tp_dst, rev_msg.match.tp_src
        '''
        '''
        if i==0:
            rev_port = first_in
            
            src_sw = "client"
            dst_sw = s_lsps[best_path][2][i]
            msg.match = of.ofp_match(in_port = first_in, dl_type=0x0800, nw_src = match.nw_src, nw_dst = match.nw_dst, tp_src = match.tp_src, tp_dst= match.tp_dst, nw_proto = match.nw_proto)
        
        else:
        '''
        #msg.in_port = s_lsps[best_path][2][i+2]
        src_sw = s_lsps[best_path][2][i]
        if i<(len(s_lsps[best_path][2])-3):
            dst_sw = s_lsps[best_path][2][i+3]
        else:
            dst_sw ="last"
        if i==0:
                cl_port=client_port[client_ip_new]
        else:
                cl_port=s_lsps[best_path][2][i+2]
        if str(match.nw_src) in client_port.keys():
                msg = of.ofp_flow_mod()
                msg.idle_timeout =10
                msg.flags = of.OFPFF_SEND_FLOW_REM
                msg.match = of.ofp_match(in_port = cl_port,dl_type =0x0800, nw_src = match.nw_src, nw_dst = match.nw_dst)
                log.debug("Installing Forward from switch %s to switch %s: output port %s", src_sw, dst_sw, s_lsps[best_path][2][i+1])
                msg.actions.append(of.ofp_action_output(port = s_lsps[best_path][2][i+1]))
                #rev_msg.match.in_port = s_lsps[best_path][2][i+1]
        #if src_sw != "client":
                log.debug("*************CLIENT FLOW: DPID OF CURRENT SWITCH*************%s",cur_sw)
                poxcore.openflow.sendToDPID(poxutil.str_to_dpid(cur_sw),msg)
                '''
                rev_msg = of.ofp_flow_mod()
                rev_msg.idle_timeout = 10
                rev_msg.flags = of.OFPFF_SEND_FLOW_REM
                rev_msg.match = of.ofp_match(in_port = s_lsps[best_path][2][i+1],dl_type =0x0800, nw_src = match.nw_dst, nw_dst = match.nw_src)

                rev_msg.out_port = cl_port
                log.debug("Installing Reverse from switch %s to switch %s : input port %s and output port %s", src_sw, dst_sw, msg.match.in_port,msg.out_port)
                rev_msg.actions.append(of.ofp_action_output(port = cl_port))
                poxcore.openflow.sendToDPID(poxutil.str_to_dpid(cur_sw),rev_msg)
                '''
        elif str(match.nw_dst) in client_port.keys():
                msg = of.ofp_flow_mod()
                msg.idle_timeout = 10
                msg.flags = of.OFPFF_SEND_FLOW_REM
                msg.match = of.ofp_match(in_port = s_lsps[best_path][2][i+1],dl_type =0x0800, nw_src = match.nw_src, nw_dst = match.nw_dst)

                msg.out_port =cl_port
                log.debug("Installing Reverse from switch %s to switch %s : input port %s and output port %s", src_sw, dst_sw, msg.match.in_port, msg.out_port)
                msg.actions.append(of.ofp_action_output(port = cl_port))
                poxcore.openflow.sendToDPID(poxutil.str_to_dpid(cur_sw),msg)
                '''
                rev_msg = of.ofp_flow_mod()
                rev_msg.idle_timeout = 10
                rev_msg.flags = of.OFPFF_SEND_FLOW_REM
                rev_msg.match = of.ofp_match(in_port = cl_port,dl_type =0x0800, nw_src = match.nw_dst, nw_dst = match.nw_src)

                rev_msg.out_port = s_lsps[best_path][2][i+1]
                log.debug("Installing Reverse from switch %s to switch %s : input port %s and output port %s", src_sw, dst_sw, msg.match.in_port,msg.out_port)
                rev_msg.actions.append(of.ofp_action_output(port = s_lsps[best_path][2][i+1]))
                poxcore.openflow.sendToDPID(poxutil.str_to_dpid(cur_sw),rev_msg)
                '''
        '''
Exemplo n.º 40
0
 def CalculatePath(self, temp_match):
     # method that calculates the path that must be used to forward traffic for this flow
     # search inside the path list and choose primary or backup
     for p in self.Paths: # find the path for this flow
         if p.flow_match.s_ip == temp_match.s_ip and p.flow_match.d_ip == temp_match.d_ip:
             # for every link in the primary path check first if the link exists. Then get the link load
             # and keep the highest link load value
             prim_cost = 0
             for it in p.primary_path:
                 sw1 = p.primary_path[p.primary_path.index(it)][0] # find switch1 of the link
                 port1 = p.primary_path[p.primary_path.index(it)][1] # find port1 of the link
                 try:
                     sw2 = p.primary_path[p.primary_path.index(it)+1][0] # find switch2 of the link
                     # use MyTopology method to get cost for that link
                     # check or change link from dpid to string in MyTopology or use str_to_dpid
                     tmp = core.current_topology.getLinkCost(sw1 = str_to_dpid(sw1), port1 = port1, sw2 = str_to_dpid(sw2))
                     if tmp is None:
                         log.debug("Primary path is broken.")
                         prim_cost = None
                         break
                     if tmp > prim_cost:
                         prim_cost = tmp
                 except IndexError:
                     pass
                     # log.debug("Node is an egress node for this flow. This is a link to the host - not calculating.")
             if (prim_cost is None) or (prim_cost > 50): # MUST change to 50% of capacity value here
                 # for every link in the secondary path check the link load and keep the highest link load value
                 sec_cost = 0
                 for it in p.secondary_path:
                     sw1 = p.secondary_path[p.secondary_path.index(it)][0] # find switch1 of the link
                     port1 = p.secondary_path[p.secondary_path.index(it)][1] # find port1 of the link
                     try:
                         sw2 = p.secondary_path[p.secondary_path.index(it)+1][0] # find switch2 of the link
                         tmp = core.current_topology.getLinkCost(sw1 = str_to_dpid(sw1), port1 = port1, sw2 = str_to_dpid(sw2))
                         if tmp is None:
                               log.debug("Secondary path is broken.")
                               sec_cost = None
                               break
                         if tmp > sec_cost:
                               sec_cost = tmp
                     except IndexError:
                         pass
                         #log.debug("Node is an egress node for this flow. This is a link to the host - not calculating.")
                 # Choose the path that is not broken or the lowest of the values kept
                 if (prim_cost is not None) and (sec_cost is not None): # if both paths are not broken
                     if sec_cost < prim_cost: # return the one with the less loaded link on its path
                         log.debug("Secondary Path less loaded. Forwarding via this one.")
                         return p.secondary_path
                     else:
                         log.debug("Primary Path less loaded. Forwarding via this one.")
                         return p.primary_path
                 elif (prim_cost is not None) and (sec_cost is None): # else if secondary path is broken, return primary irrespective of load
                     log.debug("Secondary Path is broken. Forwarding via Primary.")
                     return p.primary_path
                 elif (prim_cost is None) and (sec_cost is not None): # else if primary path is broken, return secondary irrespective of load
                     log.debug("Primary Path is broken. Forwarding via Secondary.")
                     return p.secondary_path
                 elif (prim_cost is None) and (sec_cost is None): # else if both paths are broken, return None
                     log.debug("Both Paths are broken. Doing nothing and letting packets drop.")
                     return None
             else:
                 log.debug("Using primary path as it is loaded less than 50%.")
                 return p.primary_path # if primary link not broken and loaded less than 50%
Exemplo n.º 41
0
def launch(ip, servers, strategy=RANDON, dpid=None):
    global _dpid, strategy_choosed, server_order, len_server_order
    if dpid is not None:
        _dpid = str_to_dpid(dpid)

    if strategy is not None:
        strategy_choosed = strategy

    if strategy_choosed != RANDON and strategy_choosed != ROUND_ROBIN and strategy_choosed != ROUND_ROBIN_WEIGHT:
        strategy_choosed = RANDON
        log.warning(
            'The strategy {} is not a validy stratery. Random strategy was put in place.'
            .format(strategy))

    log.info('Strategy {} used.'.format(strategy_choosed))

    if strategy_choosed == ROUND_ROBIN_WEIGHT:
        s = servers.replace(",", " ").split()
        servers = []

        for i, server in enumerate(s):
            server = server.split(':')
            servers.append(IPAddr(server[0]))

            if len(server) == 1:
                server_order.append(i)
            else:
                for k in range(0, int(server[1])):
                    server_order.append(i)

        len_server_order = len(server_order)
        log.info('Server ordering {}'.format(server_order))

    else:
        servers = servers.replace(",", " ").split()
        servers = [IPAddr(x) for x in servers]
        ip = IPAddr(ip)

    # We only want to enable ARP Responder *only* on the load balancer switch,
    # so we do some disgusting hackery and then boot it up.
    from proto.arp_responder import ARPResponder
    old_pi = ARPResponder._handle_PacketIn

    def new_pi(self, event):
        if event.dpid == _dpid:
            # Yes, the packet-in is on the right switch
            return old_pi(self, event)

    ARPResponder._handle_PacketIn = new_pi

    # Hackery done.  Now start it.
    from proto.arp_responder import launch as arp_launch
    arp_launch(eat_packets=False, **{str(ip): True})
    import logging
    logging.getLogger("proto.arp_responder").setLevel(logging.WARN)

    def _handle_ConnectionUp(event):
        global _dpid
        if _dpid is None:
            _dpid = event.dpid

        if _dpid != event.dpid:
            log.warn("Ignoring switch %s", event.connection)
        else:
            if not core.hasComponent('iplb'):
                # Need to initialize first...
                core.registerNew(iplb, event.connection, IPAddr(ip), servers)
                log.info("IP Load Balancer Ready.")
            log.info("Load Balancing on %s", event.connection)

            # Gross hack
            core.iplb.con = event.connection
            event.connection.addListeners(core.iplb)

    core.openflow.addListenerByName("ConnectionUp", _handle_ConnectionUp)
Exemplo n.º 42
0
def launch(ip, servers, weights_val=[], dpid=None, algorithm='random'):
    global _dpid
    global _algorithm

    if dpid is not None:
        _dpid = str_to_dpid(dpid)

    if algorithm not in ALGORITHM_LIST:
        log.error("Algorithm %s is not allowed, allowed algorithms: %s",
                  algorithm, ALGORITHM_LIST.keys())
        exit(1)

    # Getting the servers IP.
    servers = servers.replace(",", " ").split()
    servers = [IPAddr(x) for x in servers]

    # Parsing the weights for each server.
    weights = {}
    if len(weights_val) is 0:
        weights_val = ""
        for x in servers:
            weights_val += "1,"

    weights_val = weights_val.replace(",", " ").split()

    if len(weights_val) is not len(servers):
        log.error("Weights array is not the same length than servers array")
        exit(1)

    for i in range(len(servers)):
        weights[servers[i]] = int(weights_val[i])

    # Getting the controller IP.
    ip = IPAddr(ip)

    # We only want to enable ARP Responder *only* on the load balancer switch,
    # so we do some disgusting hackery and then boot it up.
    from proto.arp_responder import ARPResponder
    old_pi = ARPResponder._handle_PacketIn

    def new_pi(self, event):
        if event.dpid == _dpid:
            # Yes, the packet-in is on the right switch
            return old_pi(self, event)

    ARPResponder._handle_PacketIn = new_pi

    # Hackery done.  Now start it.
    from proto.arp_responder import launch as arp_launch
    arp_launch(eat_packets=False, **{str(ip): True})

    import logging
    logging.getLogger("proto.arp_responder").setLevel(logging.WARN)

    def _handle_ConnectionUp(event):
        global _dpid
        if _dpid is None:
            _dpid = event.dpid

        if _dpid != event.dpid:
            log.warn("Ignoring switch %s", event.connection)
        else:
            if not core.hasComponent('iplb'):
                # Need to initialize first...

                core.registerNew(iplb, event.connection, algorithm, IPAddr(ip),
                                 weights, servers)

                log.info("IP Load Balancer Ready.")
            log.info("Load Balancing on %s", event.connection)

            # Gross hack
            core.iplb.con = event.connection
            event.connection.addListeners(core.iplb)

    def _handle_FlowStatsReceived(event):
        for f in event.stats:
            ip_dst = f.match.nw_dst
            ip_src = f.match.nw_src

            if ip_dst != None and IPAddr(ip_dst) in core.iplb.servers:
                core.iplb.data_transferred[IPAddr(ip_dst)] += f.byte_count

            if ip_src != None and IPAddr(ip_src) in core.iplb.servers:
                core.iplb.data_transferred[IPAddr(ip_src)] += f.byte_count

    core.openflow.addListenerByName("FlowStatsReceived",
                                    _handle_FlowStatsReceived)
    core.openflow.addListenerByName("ConnectionUp", _handle_ConnectionUp)

    from pox.lib.recoco import Timer

    # Send the flow stats to all the switches connected to the controller.
    def _timer_func():
        for connection in core.openflow._connections.values():
            connection.send(
                of.ofp_stats_request(body=of.ofp_flow_stats_request()))

    # Request flow stats every FLOW_IDLE_TIMEOUT second.
    Timer(FLOW_IDLE_TIMEOUT, _timer_func, recurring=True)
Exemplo n.º 43
0
    def _handle_PacketIn(self, event):
        #log.debug("Connection packet in %s at switch %s" % (event.connection, dpid_to_str(event.dpid)))

        packet = event.parsed
        '''if isinstance(packet.next, ipv4):
        log.debug("%i %i IP %s => %s", event.dpid,event.port,
                  packet.next.srcip,packet.next.dstip)
        #log.debug("%i %i IP ", event.dpid, event.port)
    elif isinstance(packet.next, arp):
        log.debug("%i %i arp ", event.dpid, event.port)
    elif isinstance(packet.next, icmp):
        log.debug("%i %i icmp ", event.dpid,event.port)
    else:
        log.debug("%i %i not known protocol ", event.dpid, event.port)'''

        #packet is arp
        if isinstance(packet.next, arp):
            '''log.debug("ARP!!!!!!!!!!!!!!!")
        log.debug("destination address is %s" % packet.dst)
        log.debug("source address is %s" % packet.src)
        log.debug("dest ip address %s" %packet.next.protodst)'''
            outport = 0
            switch = switch_dpid_name[dpid_to_str(event.dpid)]
            if packet.next.protodst == fake_ip_address:
                if packet.next.protosrc in client_ip_addresses:
                    outport = total_client_num + 1
                    if dpid_to_str(event.dpid) != "00-00-00-00-00-01":
                        print "wrong switch has arp src is client dst is fake!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
                elif packet.next.protosrc in server_ip_addresses:
                    server_num = server_ip_addresses.index(
                        packet.next.protosrc) + 1
                    switches = servers[server_num].get_path()
                    switch = switch_dpid_name[dpid_to_str(event.dpid)]
                    if switches.index(switch) == 0:
                        outport = total_client_num + 1
                    else:
                        downlink_switch = switches[switches.index(switch) - 1]
                        outport = switch_switch_adjacency[downlink_switch][
                            switch][2]
            elif packet.next.protodst in client_ip_addresses:
                if packet.next.protosrc in client_ip_addresses or packet.next.protosrc == fake_ip_address:
                    client_num = client_ip_addresses.index(
                        packet.next.protodst) + 1
                    outport = switch_client_port[client_num]
                    if dpid_to_str(event.dpid) != "00-00-00-00-00-01":
                        print "wrong switch has arp src is client dst is fake!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
                elif packet.next.protosrc in server_ip_addresses:
                    server_num = server_ip_addresses.index(
                        packet.next.protosrc) + 1
                    switches = servers[server_num].get_path()
                    switch = switch_dpid_name[dpid_to_str(event.dpid)]
                    if switches.index(switch) == 0:
                        client_num = client_ip_addresses.index(
                            packet.next.protodst) + 1
                        outport = switch_client_port[client_num]
                    else:
                        downlink_switch = switches[switches.index(switch) - 1]
                        outport = switch_switch_adjacency[downlink_switch][
                            switch][2]
            elif packet.next.protodst in server_ip_addresses:
                if packet.next.protosrc in client_ip_addresses or packet.next.protosrc == fake_ip_address:
                    server_num = server_ip_addresses.index(
                        packet.next.protodst) + 1
                    switches = servers[server_num].get_path()
                    switch = switch_dpid_name[dpid_to_str(event.dpid)]
                    if switches.index(switch) < len(switches) - 1:
                        downlink_switch = switches[switches.index(switch) + 1]
                        outport = switch_switch_adjacency[switch][
                            downlink_switch][1]
                    else:
                        outport = switch_server_port[server_num][switch]
                '''elif packet.next.protosrc in server_ip_addresses:
                log.debug("wrong arp server -> server!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ")
                #src server -> sw1
                server_num = server_ip_addresses.index(packet.next.protosrc) + 1
                switches = servers[server_num].get_path()
                switch = switch_dpid_name[dpid_to_str(event.dpid)]
                
                downlink_switch = switches[switches.index(switch) - 1]
                outport1 = switch_switch_adjacency[downlink_switch][switch][2]
                if switches.index(switch) < len(switches) - 1:
                   uplink_switch = switches[switches.index(switch) + 1]
                   inport1 = switch_switch_adjacency[switch][uplink_switch][1]
                else:
                   inport1 = switch_server_port[server_num][switch]
                msg = of.ofp_packet_out()
                msg.data = event.ofp
                msg.match = of.ofp_match.from_packet(packet)
                msg.match.in_port = inport1
                msg.idle_timeout =  10
                #msg.in_port = event.port
                msg.actions.append(of.ofp_action_output(port = outport1))
                core.openflow.sendToDPID(str_to_dpid(switch_name_dpid[switch]), msg)
                log.debug("Installing arp at %s" % switch)
                
                #sw1 -> dst server
                server_num = server_ip_addresses.index(packet.next.protodst) + 1
                switches = servers[server_num].get_path()
                switch = switch_dpid_name[dpid_to_str(event.dpid)]
                if switches.index(switch) < len(switches) - 1:
                  downlink_switch = switches[switches.index(switch) + 1]
                  outport2 = switch_switch_adjacency[switch][downlink_switch][1]
                else:
                  outport2 = switch_server_port[server_num][switch]
                
                msg = of.ofp_packet_out()
                msg.data = event.ofp
                msg.match = of.ofp_match.from_packet(packet)
                msg.idle_timeout =  10
               #msg.in_port = event.port
                msg.actions.append(of.ofp_action_output(port = outport))
                event.connection.send(msg)'''

            msg = of.ofp_packet_out()
            msg.data = event.ofp
            msg.match = of.ofp_match.from_packet(packet)
            msg.idle_timeout = 10
            #msg.in_port = event.port
            msg.actions.append(of.ofp_action_output(port=outport))
            core.openflow.sendToDPID(str_to_dpid(switch_name_dpid[switch]),
                                     msg)
            #log.debug("Installing arp at %s" % switch)

        #packet is normal ip
        elif isinstance(packet.next, ipv4):
            #log.debug("IP!!!!!!!!!")
            #print("packet.next.dstip is %s, pack.dst is %s" % (packet.next.dstip.toStr(), packet.dst.toStr()))
            #establish bi-direction flow tables on switches along the shortest path
            #client->server
            if packet.next.dstip == fake_ip_address:

                server_num = self._calc_server(packet)
                print "dst_server_num: " + str(server_num)
                global server_count
                server_count[server_num] += 1
                if load_balancing_path:
                    servers[server_num].update_path()
                switches = servers[server_num].get_path()

                switch = switch_dpid_name[dpid_to_str(event.dpid)]
                if switches.index(switch) < len(switches) - 1:
                    downlink_switch = switches[switches.index(switch) + 1]
                    outport = switch_switch_adjacency[switch][downlink_switch][
                        1]
                else:
                    outport = switch_server_port[server_num][switch]

                new_dl_dst = servers[server_num].macAddr
                new_nw_dst = servers[server_num].ipAddr
                #print ("client->server")
                #rewrite at gateway

                #print ("i is %i, outport is %i, dst is %s, src is %s" % (switches.index(switch), outport, new_dl_dst.toStr(), packet.src.toStr()))
                msg = of.ofp_flow_mod()
                msg.data = event.ofp
                msg.match.dl_dst = packet.dst
                msg.match.dl_src = packet.src
                msg.match.dl_type = packet.type
                msg.idle_timeout = 1
                msg.actions.append(of.ofp_action_dl_addr.set_dst(new_dl_dst))
                msg.actions.append(of.ofp_action_nw_addr.set_dst(new_nw_dst))
                msg.actions.append(of.ofp_action_output(port=outport))

                core.openflow.sendToDPID(str_to_dpid(switch_name_dpid[switch]),
                                         msg)
                #log.debug("Installing at %s" % switch)

            elif packet.next.dstip in server_ip_addresses:
                server_num = server_ip_addresses.index(packet.next.dstip) + 1
                switches = servers[server_num].get_path()
                switch = switch_dpid_name[dpid_to_str(event.dpid)]
                if switches.index(switch) < len(switches) - 1:
                    downlink_switch = switches[switches.index(switch) + 1]
                    outport = switch_switch_adjacency[switch][downlink_switch][
                        1]
                else:
                    outport = switch_server_port[server_num][switch]
                new_dl_dst = servers[server_num].macAddr
                new_nw_dst = servers[server_num].ipAddr
                #print ("client->server")
                #print ("i is %i, outport is %i, dst is %s, src is %s" % (switches.index(switch), outport, new_dl_dst.toStr(), packet.src.toStr()))
                msg = of.ofp_flow_mod()
                msg.data = event.ofp
                msg.match.dl_dst = new_dl_dst
                msg.match.dl_src = packet.src
                msg.match.dl_type = packet.type
                msg.idle_timeout = 1
                msg.actions.append(of.ofp_action_output(port=outport))

                core.openflow.sendToDPID(str_to_dpid(switch_name_dpid[switch]),
                                         msg)
                #log.debug("Installing at %s" % switch)

            #server->client
            elif packet.next.srcip in server_ip_addresses:

                #print ("server->client")
                server_num = server_ip_addresses.index(packet.next.srcip) + 1
                switches = servers[server_num].get_path()
                switch = switch_dpid_name[dpid_to_str(event.dpid)]
                if switches.index(switch) == 0:
                    client_num = self._get_client_num(packet.dst)
                    outport = switch_client_port[client_num]
                else:
                    downlink_switch = switches[switches.index(switch) - 1]
                    outport = switch_switch_adjacency[downlink_switch][switch][
                        2]
                #print ("i is %i, outport is %i, dst is %s, src is %s" % (switches.index(switch), outport, packet.dst, packet.src))
                msg = of.ofp_flow_mod()
                msg.data = event.ofp
                msg.match.dl_dst = packet.dst
                msg.match.dl_src = packet.src
                msg.match.dl_type = packet.type
                msg.idle_timeout = 1
                #rewrite at gateway
                if switches.index(switch) == 0:
                    new_dl_src = fake_mac_address
                    new_nw_src = fake_ip_address
                    msg.actions.append(
                        of.ofp_action_dl_addr.set_src(new_dl_src))
                    msg.actions.append(
                        of.ofp_action_nw_addr.set_src(new_nw_src))
                msg.actions.append(of.ofp_action_output(port=outport))

                core.openflow.sendToDPID(str_to_dpid(switch_name_dpid[switch]),
                                         msg)
                #log.debug("Installing at %s" % switch)

            #drop other packets                                                 ############## if there are other useful packets this might be wrong
            '''else:
Exemplo n.º 44
0
	def _install_loop_terminate_flow(self, connection):

		def install_inout_port(connection, in_port, out_port_list):
			for out_port in out_port_list:
				match = of.ofp_match()
				match.in_port = in_port
				msg = of.ofp_flow_mod()
				msg.priority = 15000
				msg.match = match
				msg.actions.append( of.ofp_action_output(port = out_port) )
				connection.send(msg)

		def install_dst_flow(connection, dst_list, out_port):
			for dst in dst_list:
				match = of.ofp_match()
				match.dl_dst = EthAddr(dst)
				msg = of.ofp_flow_mod()
				msg.priority = 15000
				msg.match = match
				msg.actions.append( of.ofp_action_output(port = out_port) )
				connection.send(msg)

		if connection.dpid == str_to_dpid("96-d0-db-91-0a-44"):
			# 1(gre17), 2(gre18), 3(gre19), 4(gre20)
			install_dst_flow(connection, ["b6:75:f6:00:77:73","da:01:2e:66:f5:b9","fe:40:67:e8:f2:f3","2e:90:aa:80:59:16"], 1)
			install_dst_flow(connection, ["9a:9f:fd:c4:c9:57","32:35:2c:82:ae:3d","0e:54:e6:c0:54:6b","82:33:10:71:04:3c"], 2)
			install_dst_flow(connection, ["0e:80:25:28:1c:82","66:e2:51:99:b3:60","f2:0d:f2:5c:ed:7d","72:72:46:ee:26:64"], 3)
			install_dst_flow(connection, ["7e:21:05:b9:c1:35","72:5a:9d:3f:05:be","3a:73:5b:bd:5d:56","22:f7:af:9c:7b:b5"], 4)
		elif connection.dpid == str_to_dpid("3e-25-98-57-0a-4e"):
			# 1(gre21), 2(gre22), 3(gre23), 4(gre24)
			install_dst_flow(connection, ["b6:75:f6:00:77:73","da:01:2e:66:f5:b9","fe:40:67:e8:f2:f3","2e:90:aa:80:59:16"], 1)
			install_dst_flow(connection, ["9a:9f:fd:c4:c9:57","32:35:2c:82:ae:3d","0e:54:e6:c0:54:6b","82:33:10:71:04:3c"], 2)
			install_dst_flow(connection, ["0e:80:25:28:1c:82","66:e2:51:99:b3:60","f2:0d:f2:5c:ed:7d","72:72:46:ee:26:64"], 3)
			install_dst_flow(connection, ["7e:21:05:b9:c1:35","72:5a:9d:3f:05:be","3a:73:5b:bd:5d:56","22:f7:af:9c:7b:b5"], 4)
		elif connection.dpid == str_to_dpid("4e-5d-91-a4-26-4d"):
			# 1(gre1), 2(gre2), 3(gre3), 4(gre4), 5(gre17), 6(gre21)
			install_dst_flow(connection, ["b6:75:f6:00:77:73"], 1)
			install_dst_flow(connection, ["da:01:2e:66:f5:b9"], 2)
			install_dst_flow(connection, ["fe:40:67:e8:f2:f3"], 3)
			install_dst_flow(connection, ["2e:90:aa:80:59:16"], 4)
			install_dst_flow(connection, ["9a:9f:fd:c4:c9:57","32:35:2c:82:ae:3d","0e:54:e6:c0:54:6b","82:33:10:71:04:3c"], 5)
			install_dst_flow(connection, ["0e:80:25:28:1c:82","66:e2:51:99:b3:60","f2:0d:f2:5c:ed:7d","72:72:46:ee:26:64"], 6)
			install_dst_flow(connection, ["7e:21:05:b9:c1:35","72:5a:9d:3f:05:be","3a:73:5b:bd:5d:56","22:f7:af:9c:7b:b5"], 6)
		elif connection.dpid == str_to_dpid("e2-94-27-d5-ef-4e"):
			# 1(gre5), 2(gre6), 3(gre7), 4(gre8), 5(gre18), 6(gre22)
			install_dst_flow(connection, ["9a:9f:fd:c4:c9:57"], 1)
			install_dst_flow(connection, ["32:35:2c:82:ae:3d"], 2)
			install_dst_flow(connection, ["0e:54:e6:c0:54:6b"], 3)
			install_dst_flow(connection, ["82:33:10:71:04:3c"], 4)
			install_dst_flow(connection, ["b6:75:f6:00:77:73","da:01:2e:66:f5:b9","fe:40:67:e8:f2:f3","2e:90:aa:80:59:16"], 5)
			install_dst_flow(connection, ["0e:80:25:28:1c:82","66:e2:51:99:b3:60","f2:0d:f2:5c:ed:7d","72:72:46:ee:26:64"], 6)
			install_dst_flow(connection, ["7e:21:05:b9:c1:35","72:5a:9d:3f:05:be","3a:73:5b:bd:5d:56","22:f7:af:9c:7b:b5"], 6)
		elif connection.dpid == str_to_dpid("2e-7a-18-38-8c-49"):
			# 1(gre9), 2(gre10), 3(gre11), 4(gre12), 5(gre19), 6(gre23)
			install_dst_flow(connection, ["0e:80:25:28:1c:82"], 1)
			install_dst_flow(connection, ["66:e2:51:99:b3:60"], 2)
			install_dst_flow(connection, ["f2:0d:f2:5c:ed:7d"], 3)
			install_dst_flow(connection, ["72:72:46:ee:26:64"], 4)
			install_dst_flow(connection, ["b6:75:f6:00:77:73","da:01:2e:66:f5:b9","fe:40:67:e8:f2:f3","2e:90:aa:80:59:16"], 5)
			install_dst_flow(connection, ["9a:9f:fd:c4:c9:57","32:35:2c:82:ae:3d","0e:54:e6:c0:54:6b","82:33:10:71:04:3c"], 5)
			install_dst_flow(connection, ["7e:21:05:b9:c1:35","72:5a:9d:3f:05:be","3a:73:5b:bd:5d:56","22:f7:af:9c:7b:b5"], 6)
		elif connection.dpid == str_to_dpid("66-5d-a4-6c-ac-41"):
			# 1(gre13), 2(gre14), 3(gre15), 4(gre16), 5(gre20), 6(gre24)
			install_dst_flow(connection, ["7e:21:05:b9:c1:35"], 1)
			install_dst_flow(connection, ["72:5a:9d:3f:05:be"], 2)
			install_dst_flow(connection, ["3a:73:5b:bd:5d:56"], 3)
			install_dst_flow(connection, ["22:f7:af:9c:7b:b5"], 4)
			install_dst_flow(connection, ["b6:75:f6:00:77:73","da:01:2e:66:f5:b9","fe:40:67:e8:f2:f3","2e:90:aa:80:59:16"], 5)
			install_dst_flow(connection, ["9a:9f:fd:c4:c9:57","32:35:2c:82:ae:3d","0e:54:e6:c0:54:6b","82:33:10:71:04:3c"], 5)
			install_dst_flow(connection, ["0e:80:25:28:1c:82","66:e2:51:99:b3:60","f2:0d:f2:5c:ed:7d","72:72:46:ee:26:64"], 6)
		elif connection.dpid == str_to_dpid("2a-db-19-bc-94-4a"):
			# host-01 switch  1(tap0), 2(gre1)
			install_inout_port(connection, 1, [2])
			install_inout_port(connection, 2, [1])
		elif connection.dpid == str_to_dpid("7e-1f-d6-e4-84-4e"):
			# host-02 switch  1(tap0), 2(gre2)
			install_inout_port(connection, 1, [2])
			install_inout_port(connection, 2, [1])
		elif connection.dpid == str_to_dpid("ee-14-c4-6a-d3-4f"):
			# host-03 switch  1(tap0), 2(gre3)
			install_inout_port(connection, 1, [2])
			install_inout_port(connection, 2, [1])
		elif connection.dpid == str_to_dpid("8e-23-ea-7a-73-48"):
			# host-04 switch  1(tap0), 2(gre4)
			install_inout_port(connection, 1, [2])
			install_inout_port(connection, 2, [1])
		elif connection.dpid == str_to_dpid("52-84-05-47-56-4e"):
			# host-05 switch  1(tap0), 2(gre5)
			install_inout_port(connection, 1, [2])
			install_inout_port(connection, 2, [1])
		elif connection.dpid == str_to_dpid("8a-68-d2-8b-e6-41"):
			# host-06 switch  1(tap0), 2(gre6)
			install_inout_port(connection, 1, [2])
			install_inout_port(connection, 2, [1])
		elif connection.dpid == str_to_dpid("ce-b8-5c-71-5e-4f"):
			# host-07 switch  1(tap0), 2(gre7)
			install_inout_port(connection, 1, [2])
			install_inout_port(connection, 2, [1])
		elif connection.dpid == str_to_dpid("4a-84-54-fd-db-43"):
			# host-08 switch  1(tap0), 2(gre8)
			install_inout_port(connection, 1, [2])
			install_inout_port(connection, 2, [1])
		elif connection.dpid == str_to_dpid("6a-59-d5-d4-92-44"):
			# host-09 switch  1(tap0), 2(gre9)
			install_inout_port(connection, 1, [2])
			install_inout_port(connection, 2, [1])
		elif connection.dpid == str_to_dpid("fe-92-3d-be-8c-47"):
			# host-10 switch  1(tap0), 2(gre10)
			install_inout_port(connection, 1, [2])
			install_inout_port(connection, 2, [1])
		elif connection.dpid == str_to_dpid("1a-ab-10-e1-c8-47"):
			# host-11 switch  1(tap0), 2(gre11)
			install_inout_port(connection, 1, [2])
			install_inout_port(connection, 2, [1])
		elif connection.dpid == str_to_dpid("fe-98-29-28-fa-4a"):
			# host-12 switch  1(tap0), 2(gre12)
			install_inout_port(connection, 1, [2])
			install_inout_port(connection, 2, [1])
		elif connection.dpid == str_to_dpid("9a-29-05-08-c0-47"):
			# host-13 switch  1(tap0), 2(gre13)
			install_inout_port(connection, 1, [2])
			install_inout_port(connection, 2, [1])
		elif connection.dpid == str_to_dpid("9a-f2-e1-da-9e-46"):
			# host-14 switch  1(tap0), 2(gre14)
			install_inout_port(connection, 1, [2])
			install_inout_port(connection, 2, [1])
		elif connection.dpid == str_to_dpid("8e-6c-82-fe-89-48"):
			# host-15 switch  1(tap0), 2(gre15)
			install_inout_port(connection, 1, [2])
			install_inout_port(connection, 2, [1])
		elif connection.dpid == str_to_dpid("6a-35-ac-ba-48-46"):
			# host-16 switch  1(tap0), 2(gre16)
			install_inout_port(connection, 1, [2])
			install_inout_port(connection, 2, [1])
Exemplo n.º 45
0
  def _handle_PacketIn (self, event):
    #log.debug("Connection packet in %s at switch %s" % (event.connection, dpid_to_str(event.dpid)))

    packet = event.parsed
    
      
    '''if isinstance(packet.next, ipv4):
        log.debug("%i %i IP %s => %s", event.dpid,event.port,
                  packet.next.srcip,packet.next.dstip)
        #log.debug("%i %i IP ", event.dpid, event.port)
    elif isinstance(packet.next, arp):
        log.debug("%i %i arp ", event.dpid, event.port)
    elif isinstance(packet.next, icmp):
        log.debug("%i %i icmp ", event.dpid,event.port)
    else:
        log.debug("%i %i not known protocol ", event.dpid, event.port)'''

    
    #packet is arp   
    if isinstance(packet.next, arp):
        '''log.debug("ARP!!!!!!!!!!!!!!!")
        log.debug("destination address is %s" % packet.dst)
        log.debug("source address is %s" % packet.src)
        log.debug("dest ip address %s" %packet.next.protodst)'''
        outport = 0
        switch = switch_dpid_name[dpid_to_str(event.dpid)]
        if packet.next.protodst == fake_ip_address:
            if packet.next.protosrc in client_ip_addresses:
                outport = total_client_num + 1
                if dpid_to_str(event.dpid) != "00-00-00-00-00-01":
                    print "wrong switch has arp src is client dst is fake!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
            elif packet.next.protosrc in server_ip_addresses:
                server_num = server_ip_addresses.index(packet.next.protosrc) + 1
                switches = servers[server_num].get_path()
                switch = switch_dpid_name[dpid_to_str(event.dpid)]
                if switches.index(switch) == 0:
                  outport = total_client_num + 1
                else:
                  downlink_switch = switches[switches.index(switch) - 1]
                  outport = switch_switch_adjacency[downlink_switch][switch][2]
        elif packet.next.protodst in client_ip_addresses:
            if packet.next.protosrc in client_ip_addresses or packet.next.protosrc == fake_ip_address:
                client_num = client_ip_addresses.index(packet.next.protodst) + 1
                outport = switch_client_port[client_num]
                if dpid_to_str(event.dpid) != "00-00-00-00-00-01":
                    print "wrong switch has arp src is client dst is fake!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
            elif packet.next.protosrc in server_ip_addresses:
                server_num = server_ip_addresses.index(packet.next.protosrc) + 1
                switches = servers[server_num].get_path()
                switch = switch_dpid_name[dpid_to_str(event.dpid)]
                if switches.index(switch) == 0:
                  client_num = client_ip_addresses.index(packet.next.protodst) + 1
                  outport = switch_client_port[client_num]
                else:
                  downlink_switch = switches[switches.index(switch) - 1]
                  outport = switch_switch_adjacency[downlink_switch][switch][2]                
        elif packet.next.protodst in server_ip_addresses:
             if packet.next.protosrc in client_ip_addresses or packet.next.protosrc == fake_ip_address:
                server_num = server_ip_addresses.index(packet.next.protodst) + 1
                switches = servers[server_num].get_path()
                switch = switch_dpid_name[dpid_to_str(event.dpid)]
                if switches.index(switch) < len(switches) - 1:
                  downlink_switch = switches[switches.index(switch) + 1]
                  outport = switch_switch_adjacency[switch][downlink_switch][1]
                else:
                  outport = switch_server_port[server_num][switch]
             '''elif packet.next.protosrc in server_ip_addresses:
                log.debug("wrong arp server -> server!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ")
                #src server -> sw1
                server_num = server_ip_addresses.index(packet.next.protosrc) + 1
                switches = servers[server_num].get_path()
                switch = switch_dpid_name[dpid_to_str(event.dpid)]
                
                downlink_switch = switches[switches.index(switch) - 1]
                outport1 = switch_switch_adjacency[downlink_switch][switch][2]
                if switches.index(switch) < len(switches) - 1:
                   uplink_switch = switches[switches.index(switch) + 1]
                   inport1 = switch_switch_adjacency[switch][uplink_switch][1]
                else:
                   inport1 = switch_server_port[server_num][switch]
                msg = of.ofp_packet_out()
                msg.data = event.ofp
                msg.match = of.ofp_match.from_packet(packet)
                msg.match.in_port = inport1
                msg.idle_timeout =  10
                #msg.in_port = event.port
                msg.actions.append(of.ofp_action_output(port = outport1))
                core.openflow.sendToDPID(str_to_dpid(switch_name_dpid[switch]), msg)
                log.debug("Installing arp at %s" % switch)
                
                #sw1 -> dst server
                server_num = server_ip_addresses.index(packet.next.protodst) + 1
                switches = servers[server_num].get_path()
                switch = switch_dpid_name[dpid_to_str(event.dpid)]
                if switches.index(switch) < len(switches) - 1:
                  downlink_switch = switches[switches.index(switch) + 1]
                  outport2 = switch_switch_adjacency[switch][downlink_switch][1]
                else:
                  outport2 = switch_server_port[server_num][switch]
                
                msg = of.ofp_packet_out()
                msg.data = event.ofp
                msg.match = of.ofp_match.from_packet(packet)
                msg.idle_timeout =  10
               #msg.in_port = event.port
                msg.actions.append(of.ofp_action_output(port = outport))
                event.connection.send(msg)'''

        msg = of.ofp_packet_out()
        msg.data = event.ofp
        msg.match = of.ofp_match.from_packet(packet)
        msg.idle_timeout =  10
        #msg.in_port = event.port
        msg.actions.append(of.ofp_action_output(port = outport))
        core.openflow.sendToDPID(str_to_dpid(switch_name_dpid[switch]), msg)
        #log.debug("Installing arp at %s" % switch)


    #packet is normal ip
    elif isinstance(packet.next, ipv4):
      #log.debug("IP!!!!!!!!!")
      #print("packet.next.dstip is %s, pack.dst is %s" % (packet.next.dstip.toStr(), packet.dst.toStr()))
      #establish bi-direction flow tables on switches along the shortest path
      #client->server
      if packet.next.dstip == fake_ip_address:
        
        server_num = self._calc_server(packet)
        print "dst_server_num: " + str(server_num)
        global server_count
        server_count[server_num] += 1
        if load_balancing_path:
          servers[server_num].update_path()
        switches = servers[server_num].get_path()

        switch = switch_dpid_name[dpid_to_str(event.dpid)]
        if switches.index(switch) < len(switches) - 1:
          downlink_switch = switches[switches.index(switch) + 1]
          outport = switch_switch_adjacency[switch][downlink_switch][1]
        else:
          outport = switch_server_port[server_num][switch]

        new_dl_dst = servers[server_num].macAddr
        new_nw_dst = servers[server_num].ipAddr
        #print ("client->server")
        #rewrite at gateway
        
        #print ("i is %i, outport is %i, dst is %s, src is %s" % (switches.index(switch), outport, new_dl_dst.toStr(), packet.src.toStr()))
        msg = of.ofp_flow_mod()
        msg.data = event.ofp
        msg.match.dl_dst = packet.dst
        msg.match.dl_src = packet.src
        msg.match.dl_type = packet.type
        msg.idle_timeout =  1
        msg.actions.append(of.ofp_action_dl_addr.set_dst(new_dl_dst))
        msg.actions.append(of.ofp_action_nw_addr.set_dst(new_nw_dst))
        msg.actions.append(of.ofp_action_output(port = outport))
                
        core.openflow.sendToDPID(str_to_dpid(switch_name_dpid[switch]), msg)
        #log.debug("Installing at %s" % switch)

      elif packet.next.dstip in server_ip_addresses:
        server_num = server_ip_addresses.index(packet.next.dstip) + 1
        switches = servers[server_num].get_path()
        switch = switch_dpid_name[dpid_to_str(event.dpid)]
        if switches.index(switch) < len(switches) - 1:
          downlink_switch = switches[switches.index(switch) + 1]
          outport = switch_switch_adjacency[switch][downlink_switch][1]
        else:
          outport = switch_server_port[server_num][switch]
        new_dl_dst = servers[server_num].macAddr
        new_nw_dst = servers[server_num].ipAddr
        #print ("client->server")
        #print ("i is %i, outport is %i, dst is %s, src is %s" % (switches.index(switch), outport, new_dl_dst.toStr(), packet.src.toStr()))
        msg = of.ofp_flow_mod()
        msg.data = event.ofp
        msg.match.dl_dst = new_dl_dst
        msg.match.dl_src = packet.src
        msg.match.dl_type = packet.type
        msg.idle_timeout =  1
        msg.actions.append(of.ofp_action_output(port = outport))
        
        core.openflow.sendToDPID(str_to_dpid(switch_name_dpid[switch]), msg)
        #log.debug("Installing at %s" % switch)
        
      #server->client
      elif packet.next.srcip in server_ip_addresses:
      
        #print ("server->client")
        server_num = server_ip_addresses.index(packet.next.srcip) + 1
        switches = servers[server_num].get_path()
        switch = switch_dpid_name[dpid_to_str(event.dpid)]
        if switches.index(switch) == 0:
          client_num = self._get_client_num(packet.dst)
          outport = switch_client_port[client_num]
        else:
          downlink_switch = switches[switches.index(switch) - 1]
          outport = switch_switch_adjacency[downlink_switch][switch][2]
        #print ("i is %i, outport is %i, dst is %s, src is %s" % (switches.index(switch), outport, packet.dst, packet.src))
        msg = of.ofp_flow_mod()
        msg.data = event.ofp
        msg.match.dl_dst = packet.dst
        msg.match.dl_src = packet.src
        msg.match.dl_type = packet.type
        msg.idle_timeout =  1
        #rewrite at gateway
        if switches.index(switch) == 0:
          new_dl_src = fake_mac_address
          new_nw_src = fake_ip_address
          msg.actions.append(of.ofp_action_dl_addr.set_src(new_dl_src))
          msg.actions.append(of.ofp_action_nw_addr.set_src(new_nw_src))
        msg.actions.append(of.ofp_action_output(port = outport))
        
        core.openflow.sendToDPID(str_to_dpid(switch_name_dpid[switch]), msg)
        #log.debug("Installing at %s" % switch)

                              
      #drop other packets                                                 ############## if there are other useful packets this might be wrong
      '''else:
Exemplo n.º 46
0
def launch (ignore = None):
  #Inicializa o controlador
  if ignore:
    ignore = ignore.replace(',', ' ').split()
    ignore = set(str_to_dpid(dpid) for dpid in ignore)
  core.registerNew(l2_learning, ignore)