def _exec_cmd_set_table(self, event): try: msg = event.msg dpid = strToDPID(msg["dpid"]) con = core.openflow.getConnection(dpid) if con is None: raise RuntimeError("No such switch") xid = of.generate_xid() fm = of.ofp_flow_mod() fm.xid = xid fm.command = of.OFPFC_DELETE con.send(fm) bar = of.ofp_barrier_request() bar.xid = xid con.send(bar) for flow in msg.get("flows", []): fm = dict_to_flow_mod(flow) fm.xid = xid con.send(fm) # con.send(of.ofp_barrier_request(xid=xid)) con.send(of.ofp_barrier_request(xid=xid)) self.reply(event, **{"type": "set_table", "xid": xid}) except: # log.exception("Exception in set_table") log.debug("Exception in set_table - %s:%s", sys.exc_info()[0].__name__, sys.exc_info()[1]) self.reply( event, exception="%s: %s" % (sys.exc_info()[0], sys.exc_info()[1]), traceback=traceback.format_exc() )
def flood(event, ini, fim): id = 77770 lista_ip = listaIp(ini,fim) global tempoEnv tempoEnv = time.time()-t event.connection.send(of.ofp_barrier_request(xid=id)) #0x88880001 #log.info("Barrier Request enviado em: "+str(time.time()-t)+" ID:"+str(id)) time.sleep(1) for i in range (ini,fim): msg3 = of.ofp_flow_mod() #msg3.match = of.ofp_match() msg3.match.in_port = 1 #msg3.match.dl_src = EthAddr("48:5b:39:f9:3a:0f") #msg3.match.dl_dst = EthAddr("74:d0:2b:81:6c:0f") msg3.match.dl_type = 0x0800 #msg3.match.dl_vlan = 1 #msg3.match.dl_vlan_pcp = 0 msg3.match.nw_src = IPAddr(lista_ip[i-ini]) #msg3.match.nw_src = IPAddr("192.168.56.106") msg3.match.nw_dst = IPAddr("192.168.56.102") #msg3.match.nw_proto = 17 # tcp = 6 e udp = 17 #msg3.match.nw_tos = 0 #msg3.match.tp_src = i+1 #msg3.match.tp_dst = i+2 msg3.actions.append(of.ofp_action_output(port = 2)) event.connection.send(msg3) id += 1 tempoEnv = time.time()-t event.connection.send(of.ofp_barrier_request(xid=id)) log.info("Barrier Request enviado em: "+str(time.time()-t)+" ID:"+str(id)) #event.connection.send(of.ofp_stats_request()) log.info("Funcao de flood finalizada. Aguardando barrier reply ID 77771.")
def modificaRegras(event, ini, fim): global tempoEnv tempoEnv = time.time() - t event.connection.send(of.ofp_barrier_request(xid=66660)) for i in range(ini, fim): event.connection.send( of.ofp_flow_mod(match=of.ofp_match(in_port=1), command=of.OFPFC_MODIFY, actions=[of.ofp_action_output(port=3)])) tempoEnv = time.time() - t event.connection.send(of.ofp_barrier_request(xid=66661))
def remove(event): global tempoEnv tempoEnv = time.time() - t event.connection.send(of.ofp_barrier_request(xid=55550)) event.connection.send( of.ofp_flow_mod(match=of.ofp_match(in_port=1), command=of.OFPFC_DELETE)) log.info("Barrier Request enviado em: " + str(time.time() - t) + " ID:" + str(id)) tempoEnv = time.time() - t event.connection.send(of.ofp_barrier_request(xid=55551))
def removeRegras(event, ini, fim): global tempoEnv tempoEnv = time.time() - t event.connection.send(of.ofp_barrier_request(xid=66660)) for i in range(ini, fim): event.connection.send( of.ofp_flow_mod(match=of.ofp_match(in_port=1, dl_type=0x0800, nw_src=IPAddr(lista_ip[i - ini])), command=of.OFPFC_DELETE)) tempoEnv = time.time() - t event.connection.send(of.ofp_barrier_request(xid=66661))
def _install_path_mod_src (self, p, match, target_ip, packet_in=None): wp = WaitingPath(p, packet_in) _sw, _in_port, _out_port = p[0] self._install_mod_nw(_sw, _in_port, _out_port, match, target_ip, reverse=True) msg = of.ofp_barrier_request() _sw.connection.send(msg) wp.add_xid(_sw.dpid,msg.xid) for sw,in_port,out_port in p[1:]: self._install(sw, in_port, out_port, match) msg = of.ofp_barrier_request() sw.connection.send(msg) wp.add_xid(sw.dpid,msg.xid)
def _install_path (self, p, match, packet_in=None): wp = WaitingPath(p, packet_in) for sw,in_port,out_port in p: self._install(sw, in_port, out_port, match) msg = of.ofp_barrier_request() sw.connection.send(msg) wp.add_xid(sw.dpid,msg.xid)
def handle_FEATURES_REPLY (con, msg): con.features = msg con.dpid = msg.datapath_id openflowHub._connections[con.dpid] = con if openflowHub.miss_send_len is not None: con.send(of.ofp_switch_config(miss_send_len = openflowHub.miss_send_len)) if openflowHub.clear_flows_on_connect: con.send(of.ofp_flow_mod(match=of.ofp_match(), command=of.OFPFC_DELETE)) barrier = of.ofp_barrier_request() con.send(barrier) def finish_connecting (event): if event.xid != barrier.xid: con.dpid = None con.err("Failed connect for " + pox.lib.util.dpidToStr(msg.datapath_id)) con.disconnect() else: con.info("Connected to " + pox.lib.util.dpidToStr(msg.datapath_id)) #for p in msg.ports: print(p.show()) openflowHub.raiseEventNoErrors(ConnectionUp, con, msg) con.raiseEventNoErrors(ConnectionUp, con, msg) return EventHaltAndRemove con.addListener(BarrierIn, finish_connecting)
def _remove_hop (self, hop): if hop.status != RouteHop.INSTALLED: log.error("route (%s): cannot remove hop from sw (%s)", hop.route_id, hop.dpid) return msg = hop.get_flow_mod() msg.command = of.OFPFC_DELETE_STRICT con = pox.core.core.openflow.getConnection(hop.dpid) if not con: # we could be more clever here. Now, we assume the sw has # already been shut down. hop.status = RouteHop.REMOVED return con.send(msg) # send the barrier barrier_xid = self._xid_generator() # Save the pending RoutHop to change the state later self._pending_barriers[barrier_xid] = hop # Set the RouteHop status hop.status = RouteHop.SENT_REMOVE con.send(of.ofp_barrier_request(xid=barrier_xid)) log.debug('_remove_hop:route_id(%s),dpid(%s),barrier(%s)', hop.route_id, hop.dpid, barrier_xid)
def _install_hop (self, hop): route = self._routes[hop.route_id] first = ( route.hops[0] == hop ) if first and not route._is_tail_ready(): return # send the flow_mod msg = hop.get_flow_mod() con = pox.core.core.openflow.getConnection(hop.dpid) if not con: # switch hasn't connected yet. # _handle_ConnectionUp will take care of the installation later return con.send(msg) # send the barrier barrier_xid = self._xid_generator() # Save the pending RoutHop to change the state later self._pending_barriers[barrier_xid] = hop # Set the RouteHop status hop.status = RouteHop.SENT con.send(of.ofp_barrier_request(xid=barrier_xid)) log.debug('_install_hop:route_id(%s),dpid(%s),barrier(%s)', hop.route_id, hop.dpid, barrier_xid)
def handle_FEATURES_REPLY(con, msg): connecting = con.connect_time == None con.features = msg con.dpid = msg.datapath_id if not connecting: con.ofnexus._connect(con) return nexus = core.OpenFlowConnectionArbiter.getNexus(con) if nexus is None: # Cancel connection con.info("No OpenFlow nexus for " + pox.lib.util.dpidToStr(msg.datapath_id)) con.disconnect() return con.ofnexus = nexus con.ofnexus._connect(con) #connections[con.dpid] = con barrier = of.ofp_barrier_request() listeners = [] def finish_connecting(event): if event.xid != barrier.xid: con.dpid = None con.err("Failed connect for " + pox.lib.util.dpidToStr(msg.datapath_id)) con.disconnect() else: con.info("Connected to " + pox.lib.util.dpidToStr(msg.datapath_id)) import time con.connect_time = time.time() #for p in msg.ports: print(p.show()) con.ofnexus.raiseEventNoErrors(ConnectionUp, con, msg) con.raiseEventNoErrors(ConnectionUp, con, msg) con.removeListeners(listeners) listeners.append(con.addListener(BarrierIn, finish_connecting)) def also_finish_connecting(event): if event.xid != barrier.xid: return if event.ofp.type != of.OFPET_BAD_REQUEST: return if event.ofp.code != of.OFPBRC_BAD_TYPE: return # Okay, so this is probably an HP switch that doesn't support barriers # (ugh). We'll just assume that things are okay. finish_connecting(event) listeners.append(con.addListener(ErrorIn, also_finish_connecting)) #TODO: Add a timeout for finish_connecting if con.ofnexus.miss_send_len is not None: con.send(of.ofp_switch_config(miss_send_len=con.ofnexus.miss_send_len)) if con.ofnexus.clear_flows_on_connect: con.send(of.ofp_flow_mod(match=of.ofp_match(), command=of.OFPFC_DELETE)) con.send(barrier)
def handle_FEATURES_REPLY(self, con, msg): connecting = con.connect_time == None con.features = msg con.original_ports._ports = set(msg.ports) con.ports._reset() con.dpid = msg.datapath_id nexus = core.OpenFlowConnectionArbiter.getNexus(con) if nexus is None: # Cancel connection con.info("No OpenFlow nexus for " + pox.lib.util.dpidToStr(msg.datapath_id)) con.disconnect() return con.ofnexus = nexus con.ofnexus._connect(con) #TODO: Add a timeout for finish_connecting if con.ofnexus.miss_send_len is not None: con.send( of.ofp_set_config(miss_send_len=con.ofnexus.miss_send_len)) if con.ofnexus.clear_flows_on_connect: con.send( of.ofp_flow_mod(match=of.ofp_match(), command=of.OFPFC_DELETE)) self._barrier = of.ofp_barrier_request() con.send(self._barrier)
def _install_hop(self, hop): route = self._routes[hop.route_id] first = (route.hops[0] == hop) if first and not route._is_tail_ready(): return # send the flow_mod msg = hop.get_flow_mod() con = pox.core.core.openflow.getConnection(hop.dpid) if not con: # switch hasn't connected yet. # _handle_ConnectionUp will take care of the installation later return con.send(msg) # send the barrier barrier_xid = self._xid_generator() # Save the pending RoutHop to change the state later self._pending_barriers[barrier_xid] = hop # Set the RouteHop status hop.status = RouteHop.SENT con.send(of.ofp_barrier_request(xid=barrier_xid)) log.debug('_install_hop:route_id(%s),dpid(%s),barrier(%s)', hop.route_id, hop.dpid, barrier_xid)
def handle_FEATURES_REPLY(con, msg): con.features = msg con.dpid = msg.datapath_id openflowHub._connections[con.dpid] = con if openflowHub.miss_send_len is not None: con.send(of.ofp_switch_config(miss_send_len=openflowHub.miss_send_len)) if openflowHub.clear_flows_on_connect: con.send(of.ofp_flow_mod(match=of.ofp_match(), command=of.OFPFC_DELETE)) barrier = of.ofp_barrier_request() con.send(barrier) def finish_connecting(event): if event.xid != barrier.xid: con.dpid = None con.err("Failed connect for " + pox.lib.util.dpidToStr(msg.datapath_id)) con.disconnect() else: con.info("Connected to " + pox.lib.util.dpidToStr(msg.datapath_id)) #for p in msg.ports: print(p.show()) openflowHub.raiseEventNoErrors(ConnectionUp, con, msg) con.raiseEventNoErrors(ConnectionUp, con, msg) return EventHaltAndRemove con.addListener(BarrierIn, finish_connecting)
def _remove_hop(self, hop): if hop.status != RouteHop.INSTALLED: log.error("route (%s): cannot remove hop from sw (%s)", hop.route_id, hop.dpid) return msg = hop.get_flow_mod() msg.command = of.OFPFC_DELETE_STRICT con = pox.core.core.openflow.getConnection(hop.dpid) if not con: # we could be more clever here. Now, we assume the sw has # already been shut down. hop.status = RouteHop.REMOVED return con.send(msg) # send the barrier barrier_xid = self._xid_generator() # Save the pending RoutHop to change the state later self._pending_barriers[barrier_xid] = hop # Set the RouteHop status hop.status = RouteHop.SENT_REMOVE con.send(of.ofp_barrier_request(xid=barrier_xid)) log.debug('_remove_hop:route_id(%s),dpid(%s),barrier(%s)', hop.route_id, hop.dpid, barrier_xid)
def _modify_flow(self, command_type): global Barrier_Modifyxid msg = of.ofp_flow_mod() if command_type == "MOD_ST": msg.command = of.OFPFC_MODIFY_STRICT elif command_type == "MOD": msg.command = of.OFPFC_MODIFY self._match_field(msg) for connection in core.openflow._connections.values(): if str(dpidToStr(connection.dpid)) == self.dpid: """match actions""" self._match_action(msg) connection.send(msg) barrier = of.ofp_barrier_request() barrier.xid = of.generate_xid() Barrier_Modifyxid = barrier.xid connection.send(barrier) # for recover self._record_rules(dpid=self.dpid, msg=msg)
def pushRulesToSwitch(connection, rulelist): "install a set of rules using a connection to a switch" log.debug("Installing %d rules on switch %s" % (len(rulelist), connection.sock.getpeername()[0])) for rule in rulelist: connection.send(rule) connection.send(of.ofp_barrier_request())
def handle_FEATURES_REPLY (self, con, msg): connecting = con.connect_time == None con.features = msg con.original_ports._ports = set(msg.ports) con.ports._reset() con.dpid = msg.datapath_id # If any port status messages come between now and when the connection is # actually up, buffer them to raise later. con._deferred_port_status = [] nexus = core.OpenFlowConnectionArbiter.getNexus(con) if nexus is None: # Cancel connection con.info("No OpenFlow nexus for " + pox.lib.util.dpidToStr(msg.datapath_id)) con.disconnect() return con.ofnexus = nexus #TODO: Add a timeout for finish_connecting if con.ofnexus.miss_send_len is not None: con.send(of.ofp_set_config(miss_send_len = con.ofnexus.miss_send_len)) if con.ofnexus.clear_flows_on_connect: con.send(of.ofp_flow_mod(match=of.ofp_match(),command=of.OFPFC_DELETE)) self._barrier = of.ofp_barrier_request() con.send(self._barrier)
def _handle_BarrierIn(event): #numRegras = [250,500,750,1000,1250,1500,1750,2000,2250] #max=2611 numRegras = [250,500,750] #max=2611 global pos global tempoEnv if (event.xid == 77777): event.connection.send(of.ofp_barrier_request(xid=77771)) tempoEnv = time.time()-t temporec = time.time()-t if (event.xid == 77771): vRecebido.append(temporec) log.info("Barrier Reply recebido em: "+str(temporec)+" ID:"+str(event.xid)) if (event.xid == 77771 and pos < len(numRegras)): event.connection.send(of.ofp_flow_mod(match=of.ofp_match(in_port=1),command=of.OFPFC_DELETE)) log.info("Regras port=1 removidas") time.sleep(2) log.info("Instalando " + str(numRegras[pos]) + " regras") flood(event,0,numRegras[pos]) vRegras.append(numRegras[pos]) vEnviado.append(tempoEnv) pos += 1 elif(event.xid == 77771 and pos == len(numRegras)): log.info("Finalizado. Removendo regras port=1") event.connection.send(of.ofp_flow_mod(match=of.ofp_match(in_port=1),command=of.OFPFC_DELETE)) for i in range(len(vRegras)): print "1 "+str(vRegras[i])+' '+str(vEnviado[i])+' '+str(vRecebido[i+1])
def handle_FEATURES_REPLY (self, con, msg): connecting = con.connect_time == None con.features = msg con.original_ports._ports = set(msg.ports) con.ports._reset() con.dpid = msg.datapath_id nexus = core.OpenFlowConnectionArbiter.getNexus(con) if nexus is None: # Cancel connection con.info("No OpenFlow nexus for " + pox.lib.util.dpidToStr(msg.datapath_id)) con.disconnect() return con.ofnexus = nexus con.ofnexus._connect(con) #TODO: Add a timeout for finish_connecting if con.ofnexus.miss_send_len is not None: con.send(of.ofp_set_config(miss_send_len = con.ofnexus.miss_send_len)) if con.ofnexus.clear_flows_on_connect: con.send(of.ofp_flow_mod(match=of.ofp_match(),command=of.OFPFC_DELETE)) self._barrier = of.ofp_barrier_request() con.send(self._barrier)
def barrier(self,switch): b = of.ofp_barrier_request() try: self.switches[switch]['connection'].send(b) except KeyError, e: print "WARNING: couldn't send barrier to switch %s (%s)" % ( str(switch), e)
def _install_path(self, p, match, packet_in=None): wp = WaitingPath(p, packet_in) for sw, in_port, out_port in p: self._install(sw, in_port, out_port, match) msg = of.ofp_barrier_request() sw.connection.send(msg) wp.add_xid(sw.dpid, msg.xid)
def _modify_flow(self,command_type): global Modifyxid Modifyxid = of.generate_xid() msg = of.ofp_flow_mod() # print "====mod payload ====\n",self.payload if command_type == "MOD_ST": msg.command = of.OFPFC_MODIFY_STRICT elif command_type == "MOD": msg.command = of.OFPFC_MODIFY self._match_field(msg) for connection in core.openflow._connections.values() : if str(dpidToStr(connection.dpid)) == self.dpid: """match actions""" self._match_action(msg) connection.send(msg) barrier = of.ofp_barrier_request() barrier.xid = xid connection.send(barrier) # for recover self._record_rules(dpid = self.dpid , msg = msg)
def _handle_BarrierIn(event): global tempoEnv if (event.xid == 77777): event.connection.send(of.ofp_barrier_request(xid=77771)) tempoEnv = time.time() - t temporec = time.time() - t if (event.xid == 55550): vEnviado.append(tempoEnv) elif (event.xid == 55551): vRecebido.append(temporec) print "1 " + str(vRegras[0]) + ' ' + str(vEnviado[0]) + ' ' + str( vRecebido[0]) numRegras = [500, 500] #max=2611 global pos log.info("Barrier Reply recebido em: " + str(time.time() - t) + " ID:" + str(event.xid)) if (event.xid == 77771 and pos < len(numRegras)): log.info("Instalando " + str(numRegras[pos]) + " regras") flood(event, 0, numRegras[pos], pos + 1) vRegras.append(numRegras[pos]) pos += 1 elif (event.xid == 77771 and pos == len(numRegras)): remove(event) log.info("Finalizado. Removendo regras port=1")
def clear_table(self, xid=None): fm = of.ofp_flow_mod() fm.xid = xid fm.command = of.OFPFC_DELETE self._con.send(fm) bar = of.ofp_barrier_request() bar.xid = xid self._con.send(bar)
def _send_msg(self, con, msgs): for msg in msgs: msg.xid = self.xid con.send(msg) self.count += 1 con.send(of.ofp_barrier_request(xid=self.xid)) con.addListenerByName("BarrierIn", self._handle_BarrierIn)
def clear_table (self, xid = None): fm = of.ofp_flow_mod() fm.xid = xid fm.command = of.OFPFC_DELETE self._con.send(fm) bar = of.ofp_barrier_request() bar.xid = xid self._con.send(bar)
def handle_FEATURES_REPLY (con, msg): connecting = con.connect_time == None con.features = msg con.dpid = msg.datapath_id if not connecting: con.ofnexus._connect(con) return nexus = core.OpenFlowConnectionArbiter.getNexus(con) if nexus is None: # Cancel connection con.info("No OpenFlow nexus for " + pox.lib.util.dpidToStr(msg.datapath_id)) con.disconnect() return con.ofnexus = nexus con.ofnexus._connect(con) #connections[con.dpid] = con barrier = of.ofp_barrier_request() listeners = [] def finish_connecting (event): if event.xid != barrier.xid: con.dpid = None con.err("Failed connect for " + pox.lib.util.dpidToStr( msg.datapath_id)) con.disconnect() else: con.info("Connected to " + pox.lib.util.dpidToStr(msg.datapath_id)) import time con.connect_time = time.time() #for p in msg.ports: print(p.show()) con.ofnexus.raiseEventNoErrors(ConnectionUp, con, msg) con.raiseEventNoErrors(ConnectionUp, con, msg) con.removeListeners(listeners) listeners.append(con.addListener(BarrierIn, finish_connecting)) def also_finish_connecting (event): if event.xid != barrier.xid: return if event.ofp.type != of.OFPET_BAD_REQUEST: return if event.ofp.code != of.OFPBRC_BAD_TYPE: return # Okay, so this is probably an HP switch that doesn't support barriers # (ugh). We'll just assume that things are okay. finish_connecting(event) listeners.append(con.addListener(ErrorIn, also_finish_connecting)) #TODO: Add a timeout for finish_connecting if con.ofnexus.miss_send_len is not None: con.send(of.ofp_switch_config(miss_send_len = con.ofnexus.miss_send_len)) if con.ofnexus.clear_flows_on_connect: con.send(of.ofp_flow_mod(match=of.ofp_match(), command=of.OFPFC_DELETE)) con.send(barrier)
def _check_ports (dpid): """ Sends a features request to the given dpid """ _dirty_switches.pop(dpid,None) con = core.openflow.getConnection(dpid) if con is None: return con.send(of.ofp_barrier_request()) con.send(of.ofp_features_request()) log.debug("Requested switch features for %s", str(con))
def _handle_ConnectionUp(self, event): log.info("Connection from {}".format(dpid_to_mac(event.connection.dpid))) log.info("Clearing all flows from switch") msg = of.ofp_flow_mod(command=of.OFPFC_DELETE) event.connection.send(msg) msg = of.ofp_barrier_request() event.connection.send(msg) self.state = "Loading"
def clear_table (self, xid = None): "As modificações em um tabela de fluxo do controlador é feito com a mensagem OFPT_FLOW_MOD" fm = of.ofp_flow_mod() fm.xid = xid "OFPFC_DELETE: Exclui todos os fluxos correspondentes .." fm.command = of.OFPFC_DELETE self._con.send(fm) bar = of.ofp_barrier_request() bar.xid = xid self._con.send(bar)
def connect (self, connection): if connection is None: self.log.warn("Can't connect to nothing") return if self.dpid is None: self.dpid = connection.dpid assert self.dpid == connection.dpid if self.ports is None: self.ports = connection.features.ports self.disconnect() self.connection = connection self._listeners = self.listenTo(connection) self._connected_at = time.time() label = dpid_to_str(connection.dpid) self.log = log.getChild(label) self.log.debug("Connect %s" % (connection,)) if self._id is None: if self.dpid not in switches_by_id and self.dpid <= 254: self._id = self.dpid else: self._id = TopoSwitch._next_id TopoSwitch._next_id += 1 switches_by_id[self._id] = self self.network = IPAddr("10.%s.0.0" % (self._id,)) self.mac = dpid_to_mac(self.dpid) con = connection log.debug("Disabling flooding for %i ports", len(con.ports)) for p in con.ports.itervalues(): if p.port_no >= of.OFPP_MAX: continue pm = of.ofp_port_mod(port_no=p.port_no, hw_addr=p.hw_addr, config = of.OFPPC_NO_FLOOD, mask = of.OFPPC_NO_FLOOD) con.send(pm) con.send(of.ofp_barrier_request()) con.send(of.ofp_features_request()) self.send_table() def fix_addr (addr, backup): if addr is None: return None if addr is (): return IPAddr(backup) return IPAddr(addr) self.ip_addr = IPAddr("10.%s.0.1" % (self._id,)) self.router_addr = None self.dns_addr = None self.subnet = IPAddr("255.0.0.0") self.pools = {} for p in connection.ports: if p < 0 or p >= of.OFPP_MAX: continue self.pools[p] = [IPAddr("10.%s.%s.%s" % (self._id,p,n)) for n in range(1,255)] self.lease_time = 60 * 60 self.offers = {} self.leases = {}
def _install_tree (self, s, R, tree, match, packet_in=None): wp = WaitingTree(s, tree, packet_in) for sw in tree.keys(): match.in_port = None in_port, out_port = tree[sw] if sw not in R: self._install(sw, in_port, out_port, match, tree = True) else: self._install(sw, in_port, out_port, match, tree = True, mod_eth = True) msg = of.ofp_barrier_request() sw.connection.send(msg) wp.add_xid(sw.dpid,msg.xid)
def _exec_cmd_set_table (self, event): try: msg = event.msg dpid = strToDPID(msg['dpid']) con = core.openflow.getConnection(dpid) if con is None: raise RuntimeError("No such switch") xid = of.generate_xid() """ As modificações em um tabela de fluxo do controlador é feito com a mensagem OFPT_FLOW_MOD """ fm = of.ofp_flow_mod() fm.xid = xid "OFPFC_DELETE: Exclui todos os fluxos correspondentes .." fm.command = of.OFPFC_DELETE con.send(fm) bar = of.ofp_barrier_request() bar.xid = xid con.send(bar) for flow in msg.get('flows',[]): fm = dict_to_flow_mod(flow) fm.xid = xid con.send(fm) #con.send(of.ofp_barrier_request(xid=xid)) con.send(of.ofp_barrier_request(xid=xid)) self.reply(event,**{'type':'set_table','xid':xid}) except: #log.exception("Exception in set_table") log.debug("Exception in set_table - %s:%s", sys.exc_info()[0].__name__, sys.exc_info()[1]) self.reply(event, exception="%s: %s" % (sys.exc_info()[0],sys.exc_info()[1]), traceback=traceback.format_exc())
def sendBarrier(self, dpid): """Send a barrier message dpid: datapath id of the switch to receive the barrier""" dpid = int(dpid) if dpid in self.datapaths: dp = self.datapaths[dpid] msg = of.ofp_barrier_request() dp.send(msg) self.perfcounter.start() self.log.debug("dpid {0} sent barrier".format(dpid)) else: self.log.debug("dpid {0} not in datapath list".format(dpid)) return True
def flood(event, ini, fim): id = 77770 global tempoEnv tempoEnv = time.time() - t event.connection.send(of.ofp_barrier_request(xid=id)) #0x88880001 #log.info("Barrier Request enviado em: "+str(time.time()-t)+" ID:"+str(id)) time.sleep(1) for i in range(ini, fim): msg3 = of.ofp_flow_mod() msg3.match.in_port = 1 msg3.match.dl_type = 0x0800 msg3.match.nw_src = IPAddr(lista_ip[i - ini]) msg3.table = 1 msg3.actions.append(of.ofp_action_output(port=2)) event.connection.send(msg3) id += 1 tempoEnv = time.time() - t event.connection.send(of.ofp_barrier_request(xid=id)) log.info("Barrier Request enviado em: " + str(time.time() - t) + " ID:" + str(id)) #event.connection.send(of.ofp_stats_request()) log.info("Funcao de flood finalizada. Aguardando barrier reply ID 77771.")
def _insert_flow_entries(event): stats = flow_stats_to_list(event.stats) for connection in core.openflow._connections.values(): log.debug("connection dpid: %s", connection.dpid) if connection.dpid == newswitch_dpid: log.debug("install rule on switch %s", connection.dpid) for flow in stats: # log.debug("flow: %s", flow) msg = _flow_stats_to_flow_mod(flow) connection.send(msg) # send barrier message to ensure all flows has been installed connection.send(of.ofp_barrier_request(xid=0x80000000)) connection.addListenerByName("BarrierIn", _handle_flow_ready)
def start_migration(self): log.info("start copying flow tables...") for connection in core.openflow._connections.values(): if connection.dpid == ovs1_dpid or connection.dpid == ovs2_dpid or connection.dpid == ovs3_dpid: connection.send(of.ofp_stats_request(body=of.ofp_flow_stats_request())) log.debug("Sent %i flow/port stats request(s)", len(core.openflow._connections)) # send barrier message to ensure all flows has been installed connection.send(of.ofp_barrier_request(xid=copy_barrier_id)) connection.addListenerByName("BarrierIn", _handle_flow_ready) global barrier_count barrier_count += 1
def send_table (self): if self.connection is None: self.log.debug("Can't send table: disconnected") return clear = of.ofp_flow_mod(command=of.OFPFC_DELETE) self.connection.send(clear) self.connection.send(of.ofp_barrier_request()) msg = of.ofp_flow_mod() msg.match = of.ofp_match() msg.match.dl_type = pkt.ethernet.IP_TYPE msg.match.nw_proto = pkt.ipv4.UDP_PROTOCOL msg.match.tp_src = pkt.dhcp.CLIENT_PORT msg.match.tp_dst = pkt.dhcp.SERVER_PORT msg.actions.append(of.ofp_action_output(port = of.OFPP_CONTROLLER)) self.connection.send(msg) core.openflow_discovery.install_flow(self.connection) src = self for dst in switches_by_dpid.itervalues(): if dst is src: continue p = _get_path(src, dst) if p is None: continue msg = of.ofp_flow_mod() msg.match = of.ofp_match() msg.match.dl_type = pkt.ethernet.IP_TYPE msg.match.nw_dst = "%s/%s" % (dst.network, "255.255.0.0") msg.actions.append(of.ofp_action_output(port=p[0][1])) self.connection.send(msg) for ip,mac in self.ip_to_mac.iteritems(): self._send_rewrite_rule(ip, mac) flood_ports = [] for port in self.ports: p = port.port_no if p < 0 or p >= of.OFPP_MAX: continue if core.openflow_discovery.is_edge_port(self.dpid, p): flood_ports.append(p) msg = of.ofp_flow_mod() msg.priority -= 1 msg.match = of.ofp_match() msg.match.dl_type = pkt.ethernet.IP_TYPE msg.match.nw_dst = "10.%s.%s.0/255.255.255.0" % (self._id,p) msg.actions.append(of.ofp_action_output(port=of.OFPP_CONTROLLER)) self.connection.send(msg) msg = of.ofp_flow_mod() msg.priority -= 1 msg.match = of.ofp_match() msg.match.dl_type = pkt.ethernet.IP_TYPE msg.match.nw_dst = "255.255.255.255" for p in flood_ports: msg.actions.append(of.ofp_action_output(port=p)) self.connection.send(msg)
def _exec_cmd_set_table(self, event): try: msg = event.msg dpid = strToDPID(msg['dpid']) con = core.openflow.getConnection(dpid) if con is None: raise RuntimeError("No such switch") xid = of.generate_xid() fm = of.ofp_flow_mod() fm.xid = xid fm.command = of.OFPFC_DELETE con.send(fm) bar = of.ofp_barrier_request() bar.xid = xid con.send(bar) for flow in msg.get('flows', []): fm = dict_to_flow_mod(flow) fm.xid = xid con.send(fm) #con.send(of.ofp_barrier_request(xid=xid)) con.send(of.ofp_barrier_request(xid=xid)) self.reply(event, **{'type': 'set_table', 'xid': xid}) except: #log.exception("Exception in set_table") log.debug("Exception in set_table - %s:%s", sys.exc_info()[0].__name__, sys.exc_info()[1]) self.reply(event, exception="%s: %s" % (sys.exc_info()[0], sys.exc_info()[1]), traceback=traceback.format_exc())
def _init(self, flows=[]): self.done = False xid = of.generateXID() self.xid = xid self.clear_table(xid=xid) self.count = 1 + len(flows) for flow in flows: fm = dict_to_flow_mod(flow) fm.xid = xid self._con.send(fm) self._con.send(of.ofp_barrier_request(xid=xid))
def _init (self, flows = []): self.done = False xid = of.generateXID() self.xid = xid self.clear_table(xid=xid) self.count = 1 + len(flows) for flow in flows: fm = dict_to_flow_mod(flow) fm.xid = xid self._con.send(fm) self._con.send(of.ofp_barrier_request(xid=xid))
def _handle_flowstats_received (event): stats = flow_stats_to_list(event.stats) log.debug("FlowStatsReceived from %s: %s", dpidToStr(event.connection.dpid), stats) #store flow tables in local flow_table[event.connection.dpid] = stats #insert the flow enries into the new switches _insert_flow_entries(event) _set_tunnel_rule(event) # send barrier message to ensure all flows has been installed event.connection.send(of.ofp_barrier_request(xid=0x80000000)) event.connection.addListenerByName("BarrierIn", _handle_flow_ready)
def handle_FEATURES_REPLY (con, msg): connecting = con.connect_time == None con.features = msg con.dpid = msg.datapath_id if not connecting: con.ofnexus._connect(con) return nexus = core.OpenFlowConnectionArbiter.getNexus(con) if nexus is None: # Cancel connection con.info("No OpenFlow nexus for " + pox.lib.util.dpidToStr(msg.datapath_id)) con.disconnect() return con.ofnexus = nexus con.ofnexus._connect(con) #connections[con.dpid] = con barrier = of.ofp_barrier_request() def finish_connecting (event): if event.xid != barrier.xid: con.dpid = None con.err("Failed connect for " + pox.lib.util.dpidToStr( msg.datapath_id)) con.disconnect() else: con.info("Connected to " + pox.lib.util.dpidToStr(msg.datapath_id)) import time con.connect_time = time.time() #for p in msg.ports: print(p.show()) con.ofnexus.raiseEventNoErrors(ConnectionUp, con, msg) con.raiseEventNoErrors(ConnectionUp, con, msg) return EventHaltAndRemove con.addListener(BarrierIn, finish_connecting) if con.ofnexus.miss_send_len is not None: con.send(of.ofp_switch_config(miss_send_len = con.ofnexus.miss_send_len)) if con.ofnexus.clear_flows_on_connect: con.send(of.ofp_flow_mod(match=of.ofp_match(), command=of.OFPFC_DELETE)) con.send(barrier)
def start_migration(): print "Start migration..." # bring down the interfaces at ovs-1 and ovs-3 '''print 'bring down the interfaces in ovs-1' remote_cmd.ssh_run_cmd(ovs1_IP,'sudo sh interface-down.sh') remote_cmd.ssh_run_cmd(ovs3_IP,'sudo sh interface-down.sh')''' for connection in core.openflow._connections.values(): if connection.dpid == ovs1_dpid or connection.dpid == ovs2_dpid or connection.dpid == ovs3_dpid: connection.send(of.ofp_stats_request(body=of.ofp_flow_stats_request())) log.debug("Sent %i flow/port stats request(s)", len(core.openflow._connections)) # send barrier message to ensure all flows has been installed connection.send(of.ofp_barrier_request(xid=0x80000000)) connection.addListenerByName("BarrierIn", _handle_flow_ready)
def _install_tree(self, s, R, tree, match, packet_in=None): wp = WaitingTree(s, tree, packet_in) for sw in tree.keys(): match.in_port = None in_port, out_port = tree[sw] if sw not in R: self._install(sw, in_port, out_port, match, tree=True) else: self._install(sw, in_port, out_port, match, tree=True, mod_eth=True) msg = of.ofp_barrier_request() sw.connection.send(msg) wp.add_xid(sw.dpid, msg.xid)
def _handle_BarrierIn(event): global tempoEnv if (event.xid == 77777): event.connection.send(of.ofp_barrier_request(xid=77771)) tempoEnv = time.time() - t temporec = time.time() - t if (event.xid == 66661): vRecebido.append(temporec) elif (event.xid == 66660): tempoEnv = time.time() - t vEnviado.append(tempoEnv) numRegras = [250, 500, 750, 1000, 1250, 1500, 1750, 2000, 2250] #max=2611 #numRegras = [250,500,750] #max=2611 global pos log.info("Barrier Reply recebido em: " + str(time.time() - t) + " ID:" + str(event.xid)) if (event.xid == 66661 and pos > len(numRegras)): log.info("Salvando resultados") for i in range(len(vRegras)): print "1 " + str(vRegras[i]) + ' ' + str(vEnviado[i]) + ' ' + str( vRecebido[i]) log.info("Removendo regras port=1") event.connection.send( of.ofp_flow_mod(match=of.ofp_match(in_port=1), command=of.OFPFC_DELETE)) log.info("Finalizado.") if (event.xid == 77771 and pos < len(numRegras)): event.connection.send( of.ofp_flow_mod(match=of.ofp_match(in_port=1), command=of.OFPFC_DELETE)) log.info("Regras port=1 anteriores removidas") log.info("Instalando " + str(numRegras[pos]) + " regras") flood(event, 0, numRegras[pos]) vRegras.append(numRegras[pos]) log.info("Removendo " + str(numRegras[pos]) + " regras") removeRegras(event, 0, numRegras[pos]) pos += 1 elif (event.xid == 77771 and pos == len(numRegras)): log.info("Esperando ultimo BarrierReply ID 66661") pos += 1
def connect (self, connection): if connection is None: self.log.warn("Can't connect to nothing") return if self.dpid is None: self.dpid = connection.dpid #reises an exception if not true assert self.dpid == connection.dpid if self.ports is None: self.ports = connection.features.ports self.disconnect() self.connection = connection self._listeners = self.listenTo(connection) self._connected_at = time.time() label = dpid_to_str(connection.dpid) self.log = log.getChild(label) self.log.debug("Connect %s" % (connection,)) #assign an ID to the switch if self._id is None: if self.dpid not in switches_by_id and self.dpid <= 254: self._id = self.dpid else: self._id = RoutingSwitch._next_id RoutingSwitch._next_id += 1 switches_by_id[self._id] = self #assign network address self.network = IPAddr("10.%s.0.0" % (self._id,)) self.mac = dpid_to_mac(self.dpid) # Disable flooding con = connection log.debug("Disabling flooding for %i ports", len(con.ports)) for p in con.ports.itervalues(): if p.port_no >= of.OFPP_MAX: continue msg = of.ofp_port_mod(port_no=p.port_no, hw_addr=p.hw_addr, config = of.OFPPC_NO_FLOOD, mask = of.OFPPC_NO_FLOOD) con.send(msg) con.send(of.ofp_barrier_request()) con.send(of.ofp_features_request()) # Send thee initial forwarding table to the switch self.send_table() # Set IP address of the switch self.ip_addr = IPAddr("10.%s.0.1" % (self._id,))
def _process_arp_packet_in(event): ''' if its an arp msg(note, arp src hw adrs is the org eth hw adrs) assuming its from edge host, if its a req:check if we know the src mac. if we dont, its a new host so update table. if you know the ip->pmac, respond. if not, do a bcast. fr nw do flood on all edge switches. bad soln. have bcast semantics instead ''' eth_pkt = event.parsed arp_pkt = event.parsed.payload org_mac = eth_pkt.src.toStr() if org_mac not in actual_pmac:#new host. assign pmac, insert flow table in switch and add to table, mean we dont have arp entry also fr this ip = arp_pkt.protosrc.toStr() pmac = _handle_new_host(org_mac, ip, event.dpid, event.port) handler_id = event.connection.addListenerByName("BarrierIn", _handle_BarrierIn) barrier = of.ofp_barrier_request() events[barrier.xid] = (handler_id, event, pmac, ip) event.connection.send(barrier) else: _handle_arp(event)
def _of_test_once(): log.info("get connections...") for connection in core.openflow._connections.values(): if connection.dpid == g1_dpid: global start_time start_time = time.time() msg = of.ofp_flow_mod() msg.match.in_port = 1 msg.xid = of.generate_xid() global xid xid = msg.xid connection.send(msg) connection.send(of.ofp_barrier_request(xid=msg.xid)) connection.addListenerByName("BarrierIn", _handle_BarrierIn)
def flow_patch2port (mn1,mn2): global barrier_xid_mn1 global barrier_xid_mn2 log.info(" Start adding flow at: %s", str(datetime.now())) msg1 = of.ofp_flow_mod() msg1.priority = 100 msg1.match.dl_type = 0x800 msg1.match.nw_dst = listener_ip msg1.match.nw_proto = pkt.ipv4.UDP_PROTOCOL msg1.match.tp_dst = iperf_dst_port #msg1.match.tp_dst = vlc_dst_port if mn1: msg1.match.in_port = patchPort_n_mn1 msg1.actions.append(of.ofp_action_dl_addr.set_src(dl_addr=mn1_ath1)) msg1.actions.append(of.ofp_action_dl_addr.set_dst(dl_addr=ap1_ath)) msg1.actions.append(of.ofp_action_output(port = 1)) dpid_1 = mn1_br1_dpid elif mn2: msg1.match.in_port = patchPort_n_mn2 msg1.actions.append(of.ofp_action_dl_addr.set_src(dl_addr=mn2_ath1)) msg1.actions.append(of.ofp_action_dl_addr.set_dst(dl_addr=ap3_ath)) msg1.actions.append(of.ofp_action_output(port = 1)) dpid_1 = mn2_br1_dpid else: return # pre-handover (patch -> athX) core.openflow.sendToDPID(dpid_1,msg1) log.debug("[ Flow for br1: %s ] at [ %s ]", dpid_to_str(dpid_1),str(datetime.now())) #Make sure that 1st flow_mod was implemented b=of.ofp_barrier_request() if mn1: barrier_xid_mn1=b.xid elif mn2: barrier_xid_mn2=b.xid else: return core.openflow.sendToDPID(dpid_1,b) log.debug("Sent Barrier at: %s", str(datetime.now()))
def _handle_ConnectionUp (event): # Set up this switch. # After setting up, we send a barrier and wait for the response # before starting to listen to packet_ins for this switch -- before # the switch is set up, the packet_ins may not be what we expect, # and our responses may not work! # Turn on Nicira packet_ins msg = nx.nx_packet_in_format() event.connection.send(msg) # Turn on ability to specify table in flow_mods msg = nx.nx_flow_mod_table_id() event.connection.send(msg) # Clear second table msg = nx.nx_flow_mod(command=of.OFPFC_DELETE, table_id = 1) event.connection.send(msg) # Fallthrough rule for table 0: flood and send to controller msg = nx.nx_flow_mod() msg.priority = 1 # Low priority msg.actions.append(of.ofp_action_output(port = of.OFPP_CONTROLLER)) msg.actions.append(nx.nx_action_resubmit.resubmit_table(table = 1)) event.connection.send(msg) # Fallthrough rule for table 1: flood msg = nx.nx_flow_mod() msg.table_id = 1 msg.actions.append(of.ofp_action_output(port = of.OFPP_FLOOD)) event.connection.send(msg) def ready (event): if event.ofp.xid != 0x80000000: # Not the right barrier return log.info("%s ready", event.connection) event.connection.addListenerByName("PacketIn", _handle_PacketIn) return EventRemove event.connection.send(of.ofp_barrier_request(xid=0x80000000)) event.connection.addListenerByName("BarrierIn", ready)
def check_socket(self): pkt_count = 0 while True: pkt_count += 1 buff = self.s.recv(100) pkt = of.ofp_header() pkt.unpack(buff) #print('[{}][check_socket]recved: ', len(buff)) print('\n[{0}] received [{1}]byte data.'.format(pkt_count, len(buff))) print(pkt.show()) if pkt.header_type == gini_of.OFPT_HELLO: # OFPT_HELLO print("OFPT_HELLO msg: ") pkt = of.ofp_hello() pkt.unpack(buff) self.process_hello(pkt) elif pkt.header_type == gini_of.OFPT_ECHO_REQUEST: print("OFPT_ECHO_REPLY msg: ") pkt = of.ofp_echo_request() pkt.unpack(buff) self.process_echo_request(pkt) elif pkt.header_type == gini_of.OFPT_FEATURES_REQUEST: print("OFPT_FEATURES_REQUEST msg: ") pkt = of.ofp_features_request() pkt.unpack(buff) self.process_features_request(pkt) elif pkt.header_type == gini_of.OFPT_SET_CONFIG: print("OFPT_SET_CONFIG msg: ") pkt = of.ofp_set_config() pkt.unpack(buff) self.process_set_config(pkt) elif pkt.header_type == gini_of.OFPT_FLOW_MOD: print("OFPT_FLOW_MOD msg: ") pkt = giniclass_flow_mod() pkt.unpack(buff) self.process_flow_mod(pkt) elif pkt.header_type == gini_of.OFPT_BARRIER_REQUEST: print("OFPT_BARRIER_REQUEST msg: ") pkt = of.ofp_barrier_request() pkt.unpack(buff) self.process_barrier_request(pkt) else: print("Unknown type!: ", pkt.header_type, "details: ") print(pkt.show())
def _handle_BarrierIn(self, event): log.debug("Got barrier.") if self.state == "Loading": self.mods = [] for i in range(5000): msg = of.ofp_flow_mod() msg.priority = random.randint(0x8000, 0xffff) msg.command = of.OFPFC_ADD matcher = of.ofp_match() matcher.dl_type = 0x0800 matcher.nw_src = IPAddr(random.randint(1,2**32-1)) matcher.nw_dst = '10.{}.{}.0/24'.format(i/256, i%256) msg.match = matcher # msg.idle_timeout = OFP_FLOW_PERMANENT msg.hard_timeout = of.OFP_FLOW_PERMANENT msg.buffer_id = None msg.flags = of.OFPFF_CHECK_OVERLAP | of.OFPFF_SEND_FLOW_REM msg.actions.append(of.ofp_action_output(port = 13)) self.mods.append(msg) event.connection.send(msg) if i % 100 == 0: log.debug("Sent mod message {}".format(i)) time.sleep(1) self.state = "Removing" msg = of.ofp_barrier_request() event.connection.send(msg) log.debug("Sending post-add barrier") elif self.state == "Removing": while len(self.mods): i = random.randint(0, len(self.mods)-1) msg = self.mods.pop(i) msg.command = of.OFPFC_DELETE event.connection.send(msg) if len(self.mods) % 25: log.debug("Remaining mods to remove: {}".format(len(self.mods)))
def _add_flow(self,command_type): global Barrier_Addxid msg = of.ofp_flow_mod() msg.command = of.OFPFC_ADD self._match_field(msg) for connection in core.openflow._connections.values() : if str(dpidToStr(connection.dpid)) == self.dpid: """match actions""" self._match_action(msg) connection.send(msg) barrier = of.ofp_barrier_request() barrier.xid = of.generate_xid() Barrier_Addxid = barrier.xid connection.send(barrier) # for recover self._record_rules(dpid = self.dpid , msg = msg)
def flow_mn_2 (): global barrier_xid print "-----Start add flow---- %s", str(datetime.now()) log.info("[ mn_br0_dpid = %s ] UP", dpid_to_str(mn_br0_dpid)) log.info("[ mn_br1_dpid = %s ] UP", dpid_to_str(mn_br1_dpid)) # MN.br0 (patch -> ath1) msg0 = of.ofp_flow_mod() msg0.priority = 100 msg0.match.in_port = 3 msg0.match.dl_type = 0x800 msg0.match.nw_dst = "192.168.10.1" msg0.actions.append(of.ofp_action_dl_addr.set_src(dl_addr="00:80:48:62:4e:7c")) msg0.actions.append(of.ofp_action_dl_addr.set_dst(dl_addr="00:80:48:62:4e:78")) msg0.actions.append(of.ofp_action_output(port = 1)) core.openflow.sendToDPID(mn_br1_dpid,msg0) print "FLOW_MOD 1: %s", str(datetime.now()) #Make sure that 1st flow_mod was implemented b=of.ofp_barrier_request() barrier_xid=b.xid core.openflow.sendToDPID(mn_br1_dpid,b) print "BARRIER: %s", str(datetime.now())