def _compile_rule_vlan(self, rule): """Compile rule.""" _, preds = self._compute_spanning_tree(rule.ttp_dpid) for pred in preds: if not preds[pred]: datapath = get_switch(self, rule.ttp_dpid)[0].dp port = rule.ttp_port else: datapath = get_switch(self, pred)[0].dp port = preds[pred][1] parser = datapath.ofproto_parser actions = [parser.OFPActionVlanVid(rule.match['dl_vlan'])] actions.append(parser.OFPActionOutput(port)) for in_port in datapath.ports: if in_port == port: continue if in_port == 65534: continue if pred == rule.stp_dpid and in_port == rule.stp_port: match = OFPMatch(in_port=in_port, dl_src=rule.match['dl_src']) self.update_flow_mod(datapath, rule, match, actions) continue elif pred == rule.ttp_dpid: if len(self.lvnf_info) == 1: if rule.stp_dpid != None: rule.match['in_port'] = in_port match = OFPMatch(**rule.match) del rule.match['in_port'] else: match = OFPMatch(in_port=in_port, dl_src=rule.match['dl_src']) else: #prev = len(self.lvnf_info) - 2 match = OFPMatch( in_port=self.lvnf_info.values()[0]['ttp_port'], dl_src=rule.match['dl_src'], dl_vlan=self.lvnf_info.values()[0]['dl_vlan'], dl_type=rule.match['dl_type'], nw_proto=rule.match['nw_proto']) self.update_flow_mod(datapath, rule, match, actions) continue else: match = OFPMatch(dl_src=rule.match['dl_src'], dl_vlan=rule.match['dl_vlan']) self.update_flow_mod(datapath, rule, match, actions)
def calculate_path_to_server(self, src, dst, balanced): """ Returns the path of the flow Args: src: dpid of switch next to source host dst: mac address of destination host balanced: Indicates if the load on the links should be balanced Returns: list of hops (dict of dpid and outport) {'dp': XXX, 'port': YYY} """ path_out = [] # Use QoS path for both Homer and Homer controller if balanced: # Load balanced routing for HOMER path_tmp = nx.shortest_path(self.graph, src, dst, weight="weight") path_index = 0 for dpid in path_tmp[:-1]: dp = topo_api.get_switch(self, dpid)[0].dp port = self.graph.edges[(dpid, path_tmp[path_index + 1])]['port'] path_index += 1 path_out.append({'dp': dp, 'port': port, 'dpid': dp.id}) else: # Determine path to destination using nx.shortest_path. path_tmp = nx.shortest_path(self.graph, src, dst, weight=None) # weight = 1, Path weight = # Hops path_index = 0 for dpid in path_tmp[:-1]: dp = topo_api.get_switch(self, dpid)[0].dp port = self.graph.edges[(dpid, path_tmp[path_index + 1])]['port'] path_index += 1 path_out.append({'dp': dp, 'port': port, 'dpid': dp.id}) self.logger.debug("Path: %s" % path_out) if len(path_out) == 0: raise PathCalculationError() return path_out
def _port_status_handler(self, ev): msg = ev.msg reason = msg.reason port_no = msg.desc.port_no ofproto = msg.datapath.ofproto if ev.msg.desc.hw_addr == '00:0e:c6:bf:83:cc': if reason == ofproto.OFPPR_ADD: print("button interface added") links = get_link(self) print(links) for link in links: mod = ev.msg.datapath.ofproto_parser.OFPPortMod( datapath=ev.msg.datapath, port_no=link.src.port_no, hw_addr=link.src.hw_addr, config=0, mask=ofproto.OFPPC_PORT_DOWN ) ev.msg.datapath.send_msg(mod) mod = ev.msg.datapath.ofproto_parser.OFPPortMod( datapath=ev.msg.datapath, port_no=link.dst.port_no, hw_addr=link.dst.hw_addr, config=ofproto.OFPPC_PORT_DOWN, mask=ofproto.OFPPC_PORT_DOWN ) ev.msg.datapath.send_msg(mod) elif reason == ofproto.OFPPR_DELETE: print("button interface removed\nlinks:") links = get_link(self) print(links) print("switches:") switches = get_switch(self) for switch in switches: for port in switch.ports: if port._state != ofproto_v1_3.OFPPS_LIVE: mod = ev.msg.datapath.ofproto_parser.OFPPortMod( datapath=ev.msg.datapath, port_no=port.port_no, hw_addr=port.hw_addr, config=0, mask=( ofproto.OFPPC_PORT_DOWN | ofproto.OFPPC_NO_RECV | ofproto.OFPPC_NO_FWD | ofproto.OFPPC_NO_PACKET_IN ) ) ev.msg.datapath.send_msg(mod) print(switches) else: print("links:") links = get_link(self) print(links) print("switches:") switches = get_switch(self) print(switches) print(" [", end='') for switch in switches: print(switch.dp.id, end='') print(",", end='') print("]")
def get_topology_data(self, ev): switch_list = get_switch(self.topology_api_app, None) switches = [switch.dp.id for switch in switch_list] self.net.add_nodes_from(switches) #datapath = self.get_datapath(1) #pprint(datapath.id) #print "**********List of switches" #for switch in switch_list: #self.ls(switch) #print switch #self.nodes[self.no_of_nodes] = switch #self.no_of_nodes += 1 links_list = get_link(self.topology_api_app, None) #print links_list links = [(link.src.dpid, link.dst.dpid, { 'port': link.src.port_no }) for link in links_list] print links self.net.add_edges_from(links) links = [(link.dst.dpid, link.src.dpid, { 'port': link.dst.port_no }) for link in links_list] print link self.net.add_edges_from(links) self.create_intent(self.filter_data)
def get_datapath(self, dpid): if dpid not in self.dps: switch = topo_api.get_switch(self, dpid)[0] self.dps[dpid] = switch.dp return switch.dp return self.dps[dpid]
def get_topology_data(self, ev): switch_list = get_switch(self.topology_api_app, None) switches = [switch.dp.id for switch in switch_list] global sws # assign mac for swtich to easy read sws = [ '00-00-00-00-00-0' + str(switch.dp.id) for switch in switch_list ] print("sws ->", str(sws)) global links # time delay before sensing links time.sleep(0.1) links_list = get_link(self.topology_api_app, None) links = [(link.src.dpid, link.dst.dpid, { 'port': link.src.port_no }) for link in links_list] print("links", links) print("switches", switches) for link in links_list: sw_src = '00-00-00-00-00-0' + str(link.src.dpid) sw_dst = '00-00-00-00-00-0' + str(link.dst.dpid) adjacency[sw_src][sw_dst] = link.src.port_no print(" Adjacency Data ") for i in adjacency: print(str(i) + " : " + str(adjacency[i]))
def _handler_port_add(self, ev): """ Overwrite the legacy Ryu Event. """ try: switch = self.switches[ev.port.dpid] if self._check_if_ap_port(ev.port): ap_conf = self._get_ap_conf(switch, ev.port) switch.is_ap = True switch.ap_conf = ap_conf self.accesspoints[ev.port.dpid] = switch elif self._check_if_gw_port(ev.port): gw_conf = self._get_gw_conf(switch, ev.port) switch.is_gw = True switch.gw_conf = gw_conf self.gateways[ev.port.dpid] = switch switch.switch = get_switch(self, ev.port.dpid)[0] ev_tu = EventSwitchUpdate(switch) self.send_event_to_observers(ev_tu) self.logger.info("Port add: " + str(ev.port)) except KeyError: pass
def delete_meter(self, bandwidth, id): switch_list = get_switch(self.topology_api_app, None) for switch in switch_list: datapath = switch.dp parser = datapath.ofproto_parser ofp_helper.del_meter(datapath, bandwidth, id) self._request_meter_config_stats(datapath)
def get_topology_data(self, ev): self.logger.debug("get_topology_data()") self._update_switch_dpid_list() switch_list = get_switch(self.topology_data_app, None) switches = [switch.dp.id for switch in switch_list] # print "switches: ", switches self.net.add_nodes_from(switches) # print "~~~~~ FRONT ~~~~~~~" # print "switches:", [self._hostname_Check(s) for s in switches] # print "self.link_port: ", self.link_port # print "self.net.nodes():", self.net.nodes() # print "self.net.edges():", self.net.edges() # print "net nodes: ", self.net.nodes() for node in self.net.nodes(): self.link_port.setdefault(node, {}) # with open(OFP_LINK_PORT, 'w') as outp: # src_dpid dst_dpid src_dpid_output_port dst_dpid_input_port links_list = get_link(self.topology_data_app, None) # print "links_list: ", links_list # add link from one direction links = [(link.src.dpid, link.dst.dpid, { 'out_port': link.src.port_no }) for link in links_list] # print "links:", links self.net.add_edges_from(links) for link in links: # self.logger.info("%s %s %s\n" % (self._hostname_Check(link[0]), # self._hostname_Check(link[1]), link[2]['out_port'])) # self.logger.info("%s %s %s\n" % (link[0], link[1], link[2]['out_port'])) # outp.write("%s %s %s\n" % (link[0], link[1], link[2]['out_port'])) self.link_port[link[0]][link[1]] = link[2]['out_port']
def get_topology_data(self,ev): switch_list = get_switch(self.topology_api_app, None) switches = [switch.dp.id for switch in switch_list] links_list = get_link(self.topology_api_app, None) links = [(link.src.dpid, link.dst.dpid, {'port':(link.src.hw_addr,link.dst.hw_addr)}) for link in links_list] print len(switches) print "total links",len(links)
def internet_to_host_route_handler(self, ev): msg = ev.msg dp = msg.datapath dpid = dp.id ofproto = dp.ofproto pkt = packet.Packet(msg.data) ipv4_header = pkt.get_protocol(ipv4.ipv4) src_ip = ipv4_header.src dst_ip = ipv4_header.dst # 若目的主机不是本地主机,不处理 if not self.cfg_mgr.is_internal_host(dst_ip): return #获取目的主机信息,若目的主机不存在,不处理 dst_host = self.fwd_util.get_host(dst_ip) if dst_host is None: return #到本地主机的数据路径 host_match = \ dp.ofproto_parser.OFPMatch(ipv4_dst=dst_ip, eth_type=2048) pre_actions = [ dp.ofproto_parser.OFPActionSetField(eth_dst=dst_host.mac) ] self.logger.info("daoneineinei") self.fwd_util.setup_shortest_path(dpid, dst_host.port.dpid, dst_host.port.port_no, host_match, pre_actions) # 将首个数据包直接递交给目的主机,防止首包丢失 switch = topo_api.get_switch(self, dst_host.port.dpid)[0] self.fwd_util.packet_out(switch.dp, msg, dst_host.port.port_no)
def addflowsql(self, dst, dpid, in_port, out_port, flag): print 'add flow sql !!!!!!!!!!!!!!!!!!!!!!!!!!!' print dpid,in_port,out_port data_path=get_switch(self,dpid)#TODO test print type(data_path) print '!!!!!!!!!!!!!!!!!!!' print data_path datapath=data_path[0].dp#TODO test print 'datapath = ' print datapath ofproto = datapath.ofproto parser = datapath.ofproto_parser print 'dst = '+str(dst) print 'dpid = '+str(dpid) print 'in_port = '+str(in_port) print 'out port = '+str(out_port) actions=[parser.OFPActionOutput(out_port)] match=parser.OFPMatch(in_port=in_port,eth_dst=dst) f='ff:ff:ff:ff:ff:ff' if 1==flag: self.delete_flow(datapath, match)#TODO test delete flow!! #TODO delete the ff:ff:ff:ff:ff:ff flow matchf=parser.OFPMatch(in_port=in_port,eth_dst=f) self.delete_flow(datapath, matchf) print '!!!!!!!!!!!!!!!!!!add flow!!!!!!!!!!!!!!!!!!!!in_port='+str(in_port)+' dst='+str(dst)+' out_port='+str(out_port)+' dpid='+str(dpid) self.add_flow(datapath, 1, match, actions)
def get_topology_data(self): if not self.topo_stable: return self.topo_stable = False print 'get_topoloty_data' self.switch_list = get_switch(self.topology_api_app, None) self.mSwitches = [switch.dp.id for switch in self.switch_list] # switch.dp.id self.mDataPaths = [switch.dp for switch in self.switch_list] print type(self.mDataPaths[0]) self.links_list = get_link(self.topology_api_app, None) self.links = [(1, link.src.dpid, link.dst.dpid, link.src.port_no, link.dst.port_no) for link in self.links_list] self.links.sort() # print 'links : ', self.links print '\n\nlinks:' for lk in self.links: print 'switch ', lk[1], ', port ', lk[3], '--> switch ', lk[2], ', port', lk[4] print 'switches : ', self.mSwitches self.constructing_stp_krustal() # Delete all flows in all datapaths for dpid in self.mSwitches: self.delete_flow(dpid) # Install new flows for block in self.ports_to_block: if block in self.ports_to_enable: continue dpid = block[0] port = block[1] self.block_port(dpid, port) # for enable in self.ports_to_enable: # pass self.start_learning = True
def arp_forwarding(self, msg, src_ip, dst_ip): datapath = msg.datapath src_dpid = datapath.id ofproto = datapath.ofproto parser = datapath.ofproto_parser in_port = msg.match['in_port'] #1. get dst location by ip # 1.1 dst location not found,flood dport = self.topo_manager.get_host_location(dst_ip) if not dport: LOG.info("arp processing: can not find dst in local,flooding to peer and local.... ") #tell other controllers to flood flow_info = DFlow(self.cid,None, None, None, None, None, None, FLOOD, msg.data) self.topo_manager.add_flowinfo(flow_info) #flood in local domain self.flood_local(msg.data) return # 1.2 dst location found, packet-out switch_list = get_switch(self.topology_api_app, dport.dpid) if len(switch_list) > 0: out = self._build_packet_out(switch_list[0].dp, ofproto.OFP_NO_BUFFER, ofproto.OFPP_CONTROLLER, dport.port_no, msg.data) switch_list[0].dp.send_msg(out) else: #TODO send to peer flow_info = DFlow(self.cid,dport.dpid,None,None,dport.port_no,None,None,PACKET_OUT,msg.data) self.topo_manager.add_flowinfo(flow_info)
def get_topology_data(self, ev): switch_list = get_switch(self.topology_api_app, None) switches=[switch.dp.id for switch in switch_list] links_list = get_link(self.topology_api_app, None) links=[(link.src.dpid,link.dst.dpid,{'port':link.src.port_no}) for link in links_list] print links print switches
def get_topology_data(self, ev): # """ # Get topology data. Links and switches. # """ switch_list = get_switch(self.topology_api_app, None) switches=[switch.dp.id for switch in switch_list] for s in switches: print(get_datapath(self,s)) self.net.add_nodes_from(switches) print("Switches: ", switches) links_list = get_link(self.topology_api_app, None) print("Links_list from ryu: ",links_list) links = [(link.src.dpid,link.dst.dpid,{'port':link.src.port_no}) for link in links_list] print("Linky: ",links) self.net.add_edges_from(links) links=[(link.dst.dpid,link.src.dpid,{'port':link.dst.port_no}) for link in links_list] print("Linky znova: ",links) self.net.add_edges_from(links) print("Linky z programu: ",self.net.edges()) print("Nodes z programu: ",self.net.nodes())
def get_topology_data(self, ev): switch_list = get_switch(self.topology_data_app, None) switches = [switch.dp.id for switch in switch_list] self.net.add_nodes_from(switches) with open(OFP_LINK_PORT, 'w') as outp: # src_dpid dst_dpid src_dpid_output_port dst_dpid_input_port links_list = get_link(self.topology_data_app, None) # print links_list # add link from one direction links = [(self._hostname_Check(link.src.dpid), self._hostname_Check(link.dst.dpid), {'out_port': link.src.port_no}) for link in links_list] # print links self.net.add_edges_from(links) for link in links: outp.write("%s %s %s\n" % (self._hostname_Check(link[0]), self._hostname_Check(link[1]), link[2]['out_port'])) # add links from oppsite direction links = [(link.dst.dpid, link.src.dpid, {'out_port': link.dst.port_no}) for link in links_list] # print links self.net.add_edges_from(links) for link in links: outp.write("%s %s %s\n" % (self._hostname_Check(link[0]), self._hostname_Check(link[1]), link[2]['out_port']))
def get_topology_data(self, ev): """ Called when a new switch connects to the controller. Creates switches and ports in the db (if the do not already exist) :param ev: """ switch_list = get_switch(self, None) # .topology_api_app # switches = [switch.dp.id for switch in switch_list] # print "switches: ", switches # links_list = get_link(self, switches[0]) # .topology_api_app ,None # links = [(link.src.dpid, link.dst.dpid, {'port': link.src.port_no}) for link in links_list] # print "links_list: ", links_list # [0] # print "links", links # update load monitoring override_load_file(load=len(switch_list)) for switch in switch_list: self.create_switch(switch) for p in switch.ports: #print 'create port {}'.format(p) self.create_port(switch.dp.id, "", p.port_no, p.hw_addr) print("L2 App: Switch ENTER Done")
def _alert_to_block(self, ev): msg = ev.msg # Get all dpid from switches sw_dpid = [s.dp.id for s in get_switch(self.topology_api_app, None)] # Get datapath by dpid datapath = ryu.app.ofctl.api.get_datapath(self.topology_api_app, sw_dpid[0]) # Use datapath to do OFPFlowMod DROP action here ofproto = datapath.ofproto parser = datapath.ofproto_parser pkt = packet.Packet(array.array('B', msg.pkt)) _ipv4 = pkt.get_protocol(ipv4.ipv4) _tcp = pkt.get_protocol(tcp.tcp) if _ipv4: c_and_c_IP = _ipv4.src c_and_c_port = _tcp.src_port print ("C&C Server: ", c_and_c_IP, c_and_c_port) print ("Victim: ", _ipv4.dst, _tcp.dst_port) match_malicious = parser.OFPMatch(eth_type=ether.ETH_TYPE_IP, ip_proto=inet.IPPROTO_TCP, ipv4_src=c_and_c_IP, tcp_src=c_and_c_port) actions_drop = [] self.add_flow(datapath, 0, 100, match_malicious, actions_drop) print "Block C&C Server at %s:%d" % (_ipv4.src, _tcp.src_port)
def get_topology_data(self, ev): switch_list = get_switch(self.topology_api_app, None) switches = [switch.dp.id for switch in switch_list] links_list = get_link(self.topology_api_app, None) links = [(link.src.dpid, link.dst.dpid, { 'port': link.src.port_no }) for link in links_list]
def get_topology_data(self): switch_list = get_switch(self.topology_api_app, None) switches = [switch.dp.id for switch in switch_list] links_list = get_link(self.topology_api_app, None) #print links_list links = [(link.src.dpid,link.dst.dpid,{'port':[link.src.port_no,link.dst.port_no]}) for link in links_list] return switches, links
def get_topology(self, ev): """ Get topology info and calculate shortest paths. Note: In looped network, we should get the topology a few seconds after the network went up. """ present_time = time.time() if present_time - self.start_time < setting.initiation_delay: return switch_list = get_switch(self.topology_api_app, None) self.create_port_map(switch_list) self.switches = [sw.dp.id for sw in switch_list] links = get_link(self.topology_api_app, None) self.create_interior_links(links) self.create_access_ports() self.graph = self.get_graph(self.link_to_port.keys()) if not self.best_paths_computed: compute_start_time = time.time() self.shortest_paths = self.all_shortest_paths(self.graph) self.best_paths = self.get_best_paths(self.shortest_paths) elapsed_time = time.time() - compute_start_time print "elapsed_time:", elapsed_time print "self.best_paths:", self.best_paths self.logger.info("[GET NETWORK TOPOLOGY]") self.logger.info("[BEST PATHS ARE READY]") self.best_paths_computed = True
def _monitor(self): if self.mode == "MODE_0": mode_string = "MODE_0 | SPC" else: mode_string = "MODE_0 | MPC" print "\n--------STARTING CONTROLLER---------" print " mode = " + repr(mode_string) print " Resetting switches (wait 5 seconds..)" while time.time() - self.bugTimer[1] < 5: hub.sleep(0.1) if self.bugTimer[0] == 0: while True: print " Error: Restart controller (or no mininet available)" time.sleep(0.5) print " Done!" print " Starting createLinkMatrix, numberOfSwitches = " + repr( self.bugTimer[0]) for i in range(0, self.bugTimer[0]): self.createLinkMatrix(get_switch(self, None), get_link(self, None)) print "-----------------------------------\n" return while True: hub.sleep(2) for dp in self.switches: self._request_stats(dp)
def get_topology_data(self, ev): switch_list = get_switch(self.topology_api_app, None) switches = [switch.dp.id for switch in switch_list] self.net.add_nodes_from(switches) print '#### The Switches added are ###' for switch in switch_list: print switch links_list = get_link(self.topology_api_app, None) links=[(link.src.dpid,link.dst.dpid,{'port':link.src.port_no}) for link in links_list] #print links self.net.add_edges_from(links) links=[(link.dst.dpid,link.src.dpid,{'port':link.dst.port_no}) for link in links_list] #print links self.net.add_edges_from(links) print "**********List of links" print self.net.edges()
def get_topology_data(self, ev): global switches # getting list of switches switch_list = get_switch(self.topology_api_app, None) switches = [switch.dp.id for switch in switch_list] # getting list of datapaths corresponding to the switches self.datapath_list = [switch.dp for switch in switch_list] # print "self.datapath_list=", self.datapath_list print 'switches=', switches # getting list of links links_list = get_link(self.topology_api_app, None) mylinks = [(link.src.dpid, link.dst.dpid, link.src.port_no, link.dst.port_no) for link in links_list] # filling the adjacency matrix for (s1, s2, port1, port2) in mylinks: adjacency[s1][s2] = port1 adjacency[s2][s1] = port2 print "s{0}:{1} connected to s{2}:{3}".format(s1, port1, s2, port2)
def add_mirror_rule(self, rule_action, mirror_port, host_port): switch_list = get_switch(self.topology_api_app, None) for switch in switch_list: datapath = switch.dp parser = datapath.ofproto_parser if rule_action == 'add': #add mirror flow by host port for i in range(len(mirror_data.mirror_table)): if host_port == mirror_data.mirror_table[i]['out_port']: match_del = parser.OFPMatch(eth_dst=mirror_data.mirror_table[i]['dst']) self.del_flow(datapath, match_del, mirror_data.mirror_table[i]['priority']) mirror_data.mirror_table[i]['mirror_port'] = mirror_port mirror_data.mirror_table[i]['priority'] = 100 match_add = parser.OFPMatch(eth_dst=mirror_data.mirror_table[i]['dst']) actions = [parser.OFPActionOutput(mirror_data.mirror_table[i]['out_port']), parser.OFPActionOutput(mirror_data.mirror_table[i]['mirror_port'])] self.add_flow(datapath, mirror_data.mirror_table[i]['priority'], match_add, actions) #refresh mirror get higher priority print mirror_data.mirror_table elif rule_action == 'delete': for i in range(len(mirror_data.mirror_table)): if host_port == mirror_data.mirror_table[i]['out_port']: match_del = parser.OFPMatch(eth_dst=mirror_data.mirror_table[i]['dst']) self.del_flow(datapath, match_del, mirror_data.mirror_table[i]['priority']) mirror_data.mirror_table[i]['mirror_port'] = mirror_data.default_mirror_port mirror_data.mirror_table[i]['priority'] = 1 match_add = parser.OFPMatch(eth_dst=mirror_data.mirror_table[i]['dst']) actions = [parser.OFPActionOutput(mirror_data.mirror_table[i]['out_port']), parser.OFPActionOutput(mirror_data.mirror_table[i]['mirror_port'])] self.add_flow(datapath, mirror_data.mirror_table[i]['priority'], match_add, actions) #refresh mirror get higher priority self._request_stats(datapath) # update flow list in data.py
def _switches(self, req, **kwargs): dpid = None if 'dpid' in kwargs: dpid = dpid_lib.str_to_dpid(kwargs['dpid']) switches = get_switch(self.topology_api_app, dpid) body = json.dumps([switch.to_dict() for switch in switches]) return Response(content_type='application/json', body=body)
def add_block_rule(self, rule_action, src_ip, dst_ip, trans_proto, port): switch_list = get_switch(self.topology_api_app, None) for switch in switch_list: datapath = switch.dp parser = datapath.ofproto_parser actions = [] # drop # initial match field match_dict = {'eth_type': ether.ETH_TYPE_IP} # fill into the layer3 and layer 4 protocol # if port == 0, means block all protocol if port >= 0: if trans_proto == inet.IPPROTO_TCP: match_dict.update({'ip_proto': trans_proto, 'tcp_dst': port}) else: # udp match_dict.update({'ip_proto': trans_proto, 'udp_dst': port}) if len(src_ip) > 0: # not '' match_dict.update({'ipv4_src': src_ip}) if len(dst_ip) > 0: # not '' match_dict.update({'ipv4_dst': dst_ip}) match = parser.OFPMatch(**match_dict) fw_priority = settings.firewall_priority if rule_action == 'add': self.add_flow(datapath, fw_priority, match, actions) elif rule_action == 'delete': # 'off' self.del_flow(datapath, match) self._request_stats(datapath) # update flow list in data.py
def init_table_miss(self, datapath): switch_list = get_switch(self.topology_api_app, None) parser = datapath.ofproto_parser match = parser.OFPMatch() experiment_action = [parser.OFPActionOutput(4)] # outside - inside (Table 0) # ofp_helper.add_flow_with_next(datapath, table_id=0, # priority=self.goto_table_priority, match=match, # actions=experiment_action, idle_timeout=0) ofp_helper.add_flow_goto_next(datapath, 0, self.goto_table_priority, match) ofp_helper.add_flow_goto_next(datapath, 1, self.goto_table_priority, match) # ofp_helper.add_flow_with_next(datapath, table_id=1, # priority=self.goto_table_priority, match=match, # actions=experiment_action, idle_timeout=0) ofp_helper.add_flow_goto_next(datapath, 2, self.goto_table_priority, match) # ofp_helper.add_flow_goto_next(datapath, 3, self.goto_table_priority, match) ofp_helper.add_flow_with_next( datapath, table_id=service_config.service_sequence['mirror'], priority=self.goto_table_priority, match=match, actions=experiment_action, idle_timeout=0) ofp_helper.add_flow_goto_next(datapath, 4, self.goto_table_priority, match)
def get_topology_data(self, ev): switch_list = get_switch(self.topology_api_app, None) switches=[switch.dp.id for switch in switch_list] self.net.add_nodes_from(switches) #print "**********List of switches" #for switch in switch_list: #self.ls(switch) #print switch # self.nodes[self.no_of_nodes] = switch # self.no_of_nodes += 1 links_list = get_link(self.topology_api_app, None) #print links_list #links=[(link.src.dpid,link.dst.dpid,port=link.src.port_no) for link in links_list] #print links #self.net.add_edges_from(links) #links=[(link.dst.dpid,link.src.dpid,port=link.dst.port_no) for link in links_list] #print links #self.net.add_edges_from(links) for link in links_list: if (link.src.dpid,link.dst.dpid,link.src.port_no) not in list(self.net.edges_iter(data='port')): self.net.add_edge(link.src.dpid,link.dst.dpid,port=link.src.port_no) if (link.dst.dpid,link.src.dpid,link.dst.port_no) not in list(self.net.edges_iter(data='port')): self.net.add_edge(link.dst.dpid,link.src.dpid,port=link.dst.port_no) print "List of links" print self.net.edges(data=True, keys=True)
def get_topology_data(self, ev): switch_list = get_switch(self.topology_api_app, None) switches = [switch.dp.id for switch in switch_list] self.net.add_nodes_from(switches) print "**********List of switches" for switch in switch_list: #self.ls(switch) print switch #self.nodes[self.no_of_nodes] = switch #self.no_of_nodes += 1 links_list = get_link(self.topology_api_app, None) #print links_list links = [(link.src.dpid, link.dst.dpid, { 'port': link.src.port_no }) for link in links_list] #print links self.net.add_edges_from(links) links = [(link.dst.dpid, link.src.dpid, { 'port': link.dst.port_no }) for link in links_list] #print link self.net.add_edges_from(links) print "**********List of links" print self.net.edges()
def get_topology_for_swadd(self, ev): """Switch add.""" print "EventSwitchEnter" self.get_topology_data() if constant.Capacity > 0: switch_list = get_switch(self.topology_api_app, None) rate_setup.init_meter_setup(constant.Capacity, switch_list)
def reset_links(self, req, **kwargs): simple_switch = self.simple_switch_app switch_list = get_switch(simple_switch) for switch in switch_list: parser = switch.dp.ofproto_parser # Removing flow via method: # https://sourceforge.net/p/ryu/mailman/message/32333352/ empty_match = parser.OFPMatch() # remove_table_flows() is in our main controller class flow_mod = simple_switch.remove_table_flows( switch.dp, 0, empty_match, []) switch.dp.send_msg(flow_mod) port_list = switch.ports for port in port_list: ofproto = switch.dp.ofproto mod = parser.OFPPortMod( datapath=switch.dp, port_no=port.port_no, hw_addr=port.hw_addr, config=0, mask=(ofproto.OFPPC_PORT_DOWN | ofproto.OFPPC_NO_RECV | ofproto.OFPPC_NO_FWD | ofproto.OFPPC_NO_PACKET_IN)) switch.dp.send_msg(mod) print("PORT DOWN:") print(ofproto.OFPPC_PORT_DOWN)
def del_flow(self, req, **kwargs): datapath = None switches = get_switch(self.gateway_app, None) for switch in switches: if str(switch.dp.id) == str(req.json.get('dpid')): datapath = switch.dp self._del_output_flow(datapath, match=req.json.get('match'))
def get_nodes(self, req, **kwargs): switches = get_switch(self.gateway_app, None) body = [{ 'dpid': hex(switch.dp.id)[2:].zfill(16), 'ip': switch.dp.socket.getpeername()[0] } for switch in switches] return Response(content_type='application/json', json=body)
def refresh_topology_data(self): switch_list = get_switch(self, None) switches = [switch.dp.id for switch in switch_list] self.net.add_nodes_from(switches) links_list = get_link(self, None) for link in links_list: try: weight = abs(self.monitor.port_upload[(link.src.dpid, link.src.port_no)][-1]) except: weight = 0 self.net.add_edge(link.src.dpid, link.dst.dpid, {'port': link.src.port_no}, weight=weight) try: hosts = [host.mac for host in get_host(self)] for (src, dst, data) in self.net.edges(data=True): try: if dst in hosts: weight = abs( self.monitor.port_upload[(src, data['port'])][-1]) self.net.add_edge(src, dst, {'port': data['port']}, weight=weight) except: self.logger.debug("error %s ", src) return except: self.logger.debug("error")
def get_topology_data(self, ev): self.logger.info("get_topology_data()") self._update_switch_dpid_list() switch_list = get_switch(self.topology_data_app, None) switches = [switch.dp.id for switch in switch_list] # print "switches: ", switches self.net.add_nodes_from(switches) # print "~~~~~ FRONT ~~~~~~~" # print "switches:", [self._hostname_Check(s) for s in switches] # print "self.link_port: ", self.link_port # print "self.net.nodes():", self.net.nodes() # print "self.net.edges():", self.net.edges() # print "net nodes: ", self.net.nodes() for node in self.net.nodes(): self.link_port.setdefault(node, {}) # with open(OFP_LINK_PORT, 'w') as outp: # src_dpid dst_dpid src_dpid_output_port dst_dpid_input_port links_list = get_link(self.topology_data_app, None) # print "links_list: ", links_list # add link from one direction links = [(link.src.dpid, link.dst.dpid, {'out_port': link.src.port_no}) for link in links_list] # print "links:", links self.net.add_edges_from(links) for link in links: # self.logger.info("%s %s %s\n" % (self._hostname_Check(link[0]), # self._hostname_Check(link[1]), link[2]['out_port'])) # self.logger.info("%s %s %s\n" % (link[0], link[1], link[2]['out_port'])) # outp.write("%s %s %s\n" % (link[0], link[1], link[2]['out_port'])) self.link_port[link[0]][link[1]] = link[2]['out_port']
def get_topology_data(self, ev): switch_list = get_switch(self, None) switches=[switch.dp.id for switch in switch_list] for sw in switch_list: self.dpid_to_dp[sw.dp.id] = sw.dp self.net.add_nodes_from(switches) links_list = get_link(self, None) links=[(link.src.dpid,link.dst.dpid,{'port':link.src.port_no}) for link in links_list] self.net.add_edges_from(links) links=[(link.dst.dpid,link.src.dpid,{'port':link.dst.port_no}) for link in links_list] self.net.add_edges_from(links) self.dp_host_ports = defaultdict(list) for sw in switch_list: for p in sw.ports: self.dp_host_ports[sw.dp.id].append(p.port_no) srcset = set([(link.src.dpid, link.src.port_no) for link in links_list]) dstset = set([(link.dst.dpid, link.dst.port_no) for link in links_list]) for dpid, port in (srcset | dstset): if port in self.dp_host_ports[dpid]: idx = self.dp_host_ports[dpid].index(port) del self.dp_host_ports[dpid][idx]
def get_topology(self, ev): #获取网络相关信息,以及需要的一些数据结构 """ Get topology info and calculate shortest paths. Note: In looped network, we should get the topology 20 or 30 seconds after the network went up. """ present_time = time.time() if present_time - self.start_time < setting.get_topology_delay: return self.logger.info("[GET NETWORK TOPOLOGY]") switch_list = get_switch(self.topology_api_app, None) #由ryu的topo获取api获得底层网络的交换机列表 self.create_port_map(switch_list) self.switches = [sw.dp.id for sw in switch_list] links = get_link(self.topology_api_app, None) #由ryu的topo获取api获得底层网络的链路信息 self.create_interior_links(links) self.create_access_ports() self.graph = self.get_graph( self.link_to_port.keys()) #由networkX根据交换机和链路信息获得网络的图结构 self.shortest_paths = self.all_k_shortest_paths( #获得图结构后,就可以根据最短路径算法(如dijkstra)计算最短路径啦 self.graph, weight='weight', k=CONF.k_paths)
def _switch_enter_handler(self, ev): # get_switch(self, None) outputs the list of switches object. self.topo_switches = get_switch(self, None) # get_link(self, None) outputs the list of links object. self.topo_links = get_link(self, None) """ Now you have saved the links and switches of the topo. But they are object, we need to use to_dict() to trans them """ # print '*'*40,"Switch_set",'*'*40 for switch in self.topo_switches: dp = switch.dp dp_no = dpid_to_str(dp.id) if (Switch_set.has_key(dp_no) == False): ports = switch.ports Switch_set[dp_no] = [port.to_dict() for port in ports] # pprint.pprint(Switch_set) Switch_set_json = json.dumps(Switch_set, indent=4) Ssj_file = open('./Info/Static/Switch_json.json','w+') Ssj_file.write(Switch_set_json) Ssj_file.close() # print '*'*40,"Link_set",'*'*40 Link_set = [ link.to_dict() for link in self.topo_links ] # pprint.pprint(Link_set) Link_set_json = json.dumps(Link_set, indent=4) Lsj_file = open('./Info/Static/Link_json.json','w+') Lsj_file.write(Link_set_json) Lsj_file.close() self.logger.info("******_switch_enter_handler, Switch_set & Link_set******")
def trace_flow(self, req, **kwargs): ## insert trace flow ret = get_switch(self.response_app) for sw in ret: datapath = sw.dp ofproto = datapath.ofproto parser = datapath.ofproto_parser actions = [ parser.OFPActionOutput(ofproto.OFPP_CONTROLLER, ofproto.OFPCML_NO_BUFFER) ] # data = sw.to_dict() # for port in data['ports']: # match = parser.OFPMatch(vlan_vid=(0x1000, 0x1000), in_port=str_to_port_no(port['port_no'])) # self.response_app.add_flow(datapath, 12345, match, actions) if datapath.id == 1: match = parser.OFPMatch(vlan_vid=(0x1000 | 2)) else: match = parser.OFPMatch(vlan_vid=(0x1000 | 1)) self.response_app.add_flow(datapath, 12345, match, actions) ## create host's ip mac table hosts = get_host(self.response_app) for host in hosts: try: self.response_app.host_ip_mac[host.ipv4[0]] = host.mac self.response_app.host_ip_dpid[host.ipv4[0]] = host.port.dpid self.response_app.host_ip_port[ host.ipv4[0]] = host.port.port_no except: pass return "trace flow"
def get_topology(self, ev): switch_list = get_switch(self.topology_api_app, None) self.create_port_map(switch_list) self.switches = self.switch_port_table.keys() links = get_link(self.topology_api_app, None) self.create_inter_links(links) self.create_access_ports() self.get_graph(self.link_to_port.keys())
def remove_flow(self, identifier): print "Removing Flow: ", identifier for f in SFC_flows.keys(): if SFC_flows[f] == identifier: del SFC_flows[f] switch_list = get_switch(self.topology_api_app, None) for switch in switch_list: self.remove_flow_rule(switch.dp,identifier)
def topology(self): #TODO add the topology collecting periodically self.edgenum=0 start = time.time() print start self.switches = get_switch(self) self.links = get_link(self) self.topo_col_num = self.topo_col_num + 1 end = time.time() print end print 'topology collecting time:' print end-start self.topo_col_period = self.topo_col_period + end-start #n=len(self.switches) #m=len(self.links) ## self.startnum=0 ## self.dpids_to_nums={} ## self.nums_to_dpids={} print 'dpids nums:' for switch in self.switches:#TODO this may has error if self.dpids_to_nums.get(switch.dp.id)==None: self.nums_to_dpids[self.startnum] = switch.dp.id self.dpids_to_nums[switch.dp.id] = self.startnum print str(switch.dp.id)+' '+str(self.startnum) self.startnum = self.startnum + 1 print self.dpids_to_nums self.n=self.startnum print 'edges:' self.linkgraph=[] for i in xrange(self.switch_num): self.linkgraph.append([]) for j in xrange(self.switch_num): self.linkgraph[i].append(0) for link in self.links: self.edgenum=self.edgenum+1 srcnum = self.dpids_to_nums[link.src.dpid] dstnum = self.dpids_to_nums[link.dst.dpid] self.linkgraph[srcnum][dstnum]=1 if self.graph[srcnum][dstnum]==0 and self.graph[dstnum][srcnum]==0: print str(srcnum)+' '+str(dstnum) self.dpid_to_port[(link.src.dpid, link.dst.dpid)] = (link.src.port_no, link.dst.port_no) self.dpid_to_port[(link.dst.dpid, link.src.dpid)]=(link.dst.port_no, link.src.port_no) #print>>devicegraph, str(srcnum)+' '+str(dstnum) self.graph[srcnum][dstnum] = 1 self.graph[dstnum][srcnum] = 1 self.undirected[srcnum][dstnum] = 1 self.m=self.m+1 self.G={} for i in xrange(self.switch_num): self.G[i]={} for j in xrange(self.switch_num): if self.linkgraph[i][j]==1 and self.linkgraph[j][i]==1:#TODO if only one way is ok then regard it as not ok self.G[i][j]=1 print self.G print self.linkgraph print self.graph print self.undirected
def get_switches(self): switches = [] for switch in get_switch(self, None): if switch.dp.id in self.LSwitches: switches.append(switch) return switches
def get_topology_data(self, ev): switch_list = get_switch(self.my_topology_api_app, None) all_switches = [switch.dp.id for switch in switch_list] # links_list = get_link(self.topology_api_app, None) links_list = get_link(self.my_topology_api_app) links = [(link.src.dpid, link.dst.dpid, {'port': link.src.port_no}) for link in links_list] print ">> switches: ", all_switches print ">> links: ", links
def _routing_adjust(self, ev): datapath_list = ev.msg self.load = ev.load self.sw_stat = dict((k, v) for k, v in data_collection.switch_stat.items()) switch_list = get_switch(self.topology_api_app, None) for datapath in switch_list: flow_list_in_dp = flowutils.get_flow_in_dp(datapath.dp.id) for key_tuples in flow_list_in_dp.keys(): flow = data_collection.flow_list.get(key_tuples) if flow.r_limited > 3: flow.r_limited = 0 elif flow.r_limited >= 1 and flow.r_limited <= 3: flow.r_limited += 1 for datapath_id in datapath_list: datapath = get_switch(self.topology_api_app, dpid=datapath_id) flow_list_in_dp = flowutils.get_flow_in_dp(datapath[0].dp.id) self._adjustment_handler(flow_list_in_dp, datapath[0].dp.id)
def get_topology_data(self, ev): switch_list = get_switch(self.topology_api_app, None) switches = [switch.dp.id for switch in switch_list] link_list = get_link(self.topology_api_app, None) self.net.add_nodes_from(switches) links=[(link.src.dpid,link.dst.dpid, {'port':link.src.port_no}) for link in links_list] self.ned_add_edges_from(links) self.logger.info('******************************** List of links') self.logger.info(self.net.edges())
def _request_stats(self): switch_list = get_switch(self.topology_api_app, None) for switch in switch_list: datapath = switch.dp self.logger.debug('send stats request: %016x', datapath.id) parser = datapath.ofproto_parser req = parser.OFPFlowStatsRequest(datapath) datapath.send_msg(req)
def get_topology(self, ev): switch_list = get_switch(self.topology_api_app, None) self.create_port_map(switch_list) self.switches = self.switch_port_table.keys() links = get_link(self.topology_api_app, None) self.create_interior_links(links) self.create_access_ports() self.get_graph(self.link_to_port.keys()) self.shortest_paths = self.all_k_shortest_paths( self.graph, weight='weight', k=CONF.k_paths)
def _monitor(self): while True: switch_list = get_switch(self.topology_api_app, None) for datapath in switch_list: if self.sw_port_stat.get(datapath.dp.id) is None: port_stat = {} self.sw_port_stat.update({datapath.dp.id: port_stat}) # print 'rate:', self.current_rate self._request_stats(datapath.dp) hub.sleep(5)
def get_topology(self, ev): print("HELLOOOOOO WORLD") switch_list = copy.copy(get_switch(self, None)) links = copy.copy(get_link(self, None)) edges_list=[] for link in links: src = link.src dst = link.src edges_list.append((src.dpid, dst.dpid, {'port': link.src.port_no})) print(links)
def get_topology_data(self, ev): switch_list = get_switch(self.topology_api_app, None) self.switches=[switch.dp.id for switch in switch_list] print '************Switch List*********************' # print self.switches links_list = get_link(self.topology_api_app, None) self.links=[(link.src.dpid,link.dst.dpid,{'port':link.src.port_no}) for link in links_list] self.switches_nodes=[switch.dp for switch in switch_list] self.net.add_nodes_from(self.switches) self.net.add_edges_from(self.links)
def get_topology_data(self, ev): print "Beep!" switch_list = get_switch(self.topology_api_app, None) switches = [switch.dp.id for switch in switch_list] links_list = get_link(self.topology_api_app, None) links = [(link.src.dpid, link.dst.dpid, {'port': link.src.port_no}) for link in links_list] # host_list = get_host(self.topology_api_app, None) # hosts = [host.dp.id for host in host_list] # print i print switches print links
def set_meter_to_switches(self, meterid, bandwdith, command): """Save Member data to database method.""" switch_list = get_switch(self.topology_api_app, None) for dp in switch_list: print dp.dp.id, type(meterid), type(bandwdith), int(bandwdith), int(meterid) ofputils.set_meter_entry(dp.dp, int(bandwdith), int(meterid), command) if command == 'ADD': data_collection.meter_list.update({bandwdith: meterid}) elif command == 'DELETE': data_collection.meter_list.pop(bandwdith)
def get_dp(app, dpid): """ :type dpid: datapath id :param dpid: :rtype: ryu.controller.controller.Datapath :returns: datapath corresponding to dpid """ switches = topo_api.get_switch(app, dpid) if not switches: return None assert len(switches) == 1 return switches[0].dp