def main(): logger = MininetLogger() logger.setLogLevel(levelname='info') controller_ip = sys.argv[2] topo = Topo() n = int(sys.argv[1]) switches = [topo.addSwitch('s%d' % (i+1), protocols='OpenFlow13') for i in range(n)] host1 = topo.addHost('h%d' % 1, mac="12:34:56:78:00:01") host2 = topo.addHost('h%d' % 2, mac="12:34:56:78:00:02") hosts = [host1, host2] for i in [0, 1]: topo.addLink(hosts[i], switches[i]) for i in range(n): topo.addLink(switches[i], switches[(i+1) % n]) net = Mininet(topo=topo, controller=RemoteController, link=TCLink, build=False) net.addController(ip=controller_ip) net.start() CLI(net) net.stop()
def finalize(self): # make mininet topo topo = Topo() # add nodes for x,d in self.nodes(data=True): if d['isSwitch']: topo.addSwitch(str(x)) else: topo.addHost(str(x)) # add links for src,dst in self.edges(): topo.addLink(str(src),str(dst)) # backpatch ports into original graph for x in self.nodes(): self.node[x]['ports'] = {} self.node[x]['port'] = {} for y in self.neighbors(x): x_port, y_port = topo.port(str(x),str(y)) self.node[x]['ports'][y] = x_port # Support indexing in by port to get neighbor switch/port self.node[x]['port'][x_port] = (y, y_port) self.topo = topo self.finalized = True
def _convert_to_plain_topo(self, topo): r = Topo() for node in topo.nodes(): r.addNode(node,**topo.nodeInfo(node)) for edge in topo.links(): r.addLink(edge[0],edge[1],**topo.linkInfo(edge[0],edge[1])) return r
def createTopology(switch, hosts): setLogLevel('info') topo = Topo() switch = topo.addSwitch(switch) for (hostname, opts) in hosts: host = topo.addHost(hostname, **opts) topo.addLink(host, switch, None) network = Mininet(topo, controller=None) network.start() print "*** Dumping host connections" dumpNodeConnections(network.hosts) CLI(network) network.stop()
def test_from_mininet(self): from mininet.topo import Topo t = Topo() t.addHost("h1") t.addHost("h4") t.addSwitch("s2") t.addSwitch("s3") t.addLink("h1", "s2") t.addLink("s2", "s3") t.addLink("s3", "h4") fnss_topo = fnss.from_mininet(t) self.assertIsNotNone(fnss_topo) for h in "h1", "h4": self.assertEqual(fnss_topo.node[h]['type'], 'host') for s in "s2", "s3": self.assertEqual(fnss_topo.node[s]['type'], 'switch')
def createTopology(switch, hosts): ODL_Controller_IP='172.17.40.4' setLogLevel('info') topo = Topo() switch = topo.addSwitch(switch) for (hostname, opts) in hosts: host = topo.addHost(hostname, **opts) topo.addLink(host, switch, None) network = Mininet(topo, controller=None) #odl_ctrl = network.addController('c0', controller=RemoteController, ip=ODL_Controller_IP, port=6633) network.start() print "*** Dumping host connections" dumpNodeConnections(network.hosts) CLI(network) network.stop()
def test_from_mininet(self): try: from mininet.topo import Topo except ImportError: raise ImportError('You must have Mininet installed to run this test case') t = Topo() t.addHost("h1") t.addHost("h4") t.addSwitch("s2") t.addSwitch("s3") t.addLink("h1", "s2") t.addLink("s2", "s3") t.addLink("s3", "h4") fnss_topo = fnss.from_mininet(t) self.assertIsNotNone(fnss_topo) for h in "h1", "h4": self.assertEqual(fnss_topo.node[h]['type'], 'host') for s in "s2", "s3": self.assertEqual(fnss_topo.node[s]['type'], 'switch')
def _convert_to_plain_topo(self, topo): """Convert topo to mininet.topo.Topo instance. This helper function allows the user to use topologys which are not direct instances of mininet.topo.Topo in MaxiNet. If the topology was not converted to a Topo instance the transfer via pyro most likely fails as the original class might not be available at the pyro remote. Args: topo: Instance which fullfills the interface of mininet.topo.Topo. Returns: Instance of mininet.topo.Topo, """ r = Topo() for node in topo.nodes(): r.addNode(node, **topo.nodeInfo(node)) for edge in topo.links(): r.addLink(**topo.linkInfo(edge[0], edge[1])) return r
def createTopo(): topo=Topo() swCore1 = topo.addSwitch('s1') ## Ajuste do parametro de fanout da rede fanout = 2 # Switches counter lastSW = 2 lastHost = 1 # Aggregation switches loop for i in irange (1, fanout): swAggregL = topo.addSwitch('s%s' % lastSW) topo.addLink(swCore1, swAggregL) lastSW += 1 # Edge switches loop for j in irange (1, fanout): swEdge = topo.addSwitch('s%s' % lastSW) topo.addLink(swAggregL, swEdge) lastSW += 1 # Hosts loop for k in irange (1, fanout): host = topo.addHost('h%s' % lastHost) topo.addLink(swEdge, host) lastHost += 1 return topo
def networkx_to_mininet(G, hosts, switches, mapping): # Conversion from NetworkX topology into FNSS topology fnss_topo = fnss.Topology(G) # G is a NetworkX Graph() and fnss_topo is a FNSS Topology(): hosts and switches are indistinguishable. # We exploit 'mapping' returned from parse_network_xml() for nodes role differentiation. # We can't use fnss.adapters.to_mininet() because we need a customized nodes relabeling. # TODO link capacities!! http://fnss.github.io/doc/core/_modules/fnss/adapters/mn.html # Conversion from FNSS topology into Mininet topology nodes = set(fnss_topo.nodes_iter()) hosts = sorted(set(hosts)) switches = sorted(set(switches)) hosts = set(mapping[v] for v in hosts) switches = set(mapping[v] for v in switches) if not switches.isdisjoint(hosts): raise ValueError('Some nodes are labeled as both host and switch. ' 'Switches and hosts node lists must be disjoint') if hosts.union(switches) != switches.union(hosts): raise ValueError('Some nodes are not labeled as either host or switch ' 'or some nodes listed as switches or hosts do not ' 'belong to the topology') fnss_topo = nx.relabel_nodes(fnss_topo, mapping, copy=True) global mn_topo mn_topo = Topo() for v in switches: mn_topo.addSwitch(str(v)) for v in hosts: mn_topo.addHost(str(v)) for u, v in fnss_topo.edges_iter(): params = {} mn_topo.addLink(str(u), str(v), **params) return mn_topo
class MininetSimulator(object): def __init__(self, graph, controller_addr): self.graph = graph self.mininet_topo = Topo(); self.controller_addr = controller_addr def generate_topo(self): nodes = self.graph["nodes"] edges = self.graph["edges"] for node in nodes: if node["class"] == "circleHClass": if (ip_re.match(node["title"])): self.mininet_topo.addHost(node, ip=node["title"]) else: self.mininet_topo.addHost(node) elif node["class"] == "circleSClass": self.mininet_topo.addSwitch(node) for edge in edges: # set link properties here. # bw(Mbps), delay, loss, max_queue_size # source code is in {mininet_root}/mininet/link.py linkopts = dict() self.mininet_topo.addLink(edge[0], edge[1], **linkopts) def run(self): self.generate_topo() net = Mininet(topo=self.mininet_topo, controller=RemoteController, link=TCLink, build=False, autoStaticArp=True) net.addController(ip=self.controller_addr) net.start() CLI(net) net.stop()
def createTopo(): topo=Topo() #Create Nodes topo.addHost("h1") topo.addHost("h2") topo.addHost("h3") topo.addHost("h4") topo.addSwitch('s1') topo.addSwitch('s2') topo.addSwitch('s3') #Create links topo.addLink('s1','s2',bw=100,delay='100ms',loss=10) topo.addLink('s1','s3') topo.addLink('h1','s2') topo.addLink('h2','s2') topo.addLink('h3','s3') topo.addLink('h4','s3') return topo
def createTopo(): topo=Topo() #Create Nodes topo.addHost("h1") topo.addHost("h2") topo.addHost("h3") topo.addHost("h4") topo.addSwitch('s1') topo.addSwitch('s2') topo.addHost("r1") #router #Create links topo.addLink('h1','s1') topo.addLink('h2','s1') topo.addLink('s1','r1') topo.addLink('s2','r1') topo.addLink('h3','s2') topo.addLink('h4','s2') return topo
from mininet.net import Mininet from mininet.topo import Topo from mininet.node import OVSSwitch , OVSController, Ryu, RemoteController from mininet.cli import CLI topo = Topo() s1 = topo.addSwitch('s1' , cls=OVSSwitch) s2 = topo.addSwitch('s2' , cls=OVSSwitch) h1 = topo.addNode('h1') h2 = topo.addNode('h2') h3 = topo.addNode('h3') h4 = topo.addNode('h4') c1 = RemoteController('c1',port=6633) topo.addLink(s1 , h1) topo.addLink(s1 , h2) topo.addLink(s2 , h3) topo.addLink(s2 , h4) topo.addLink(s1 , s2) net = Mininet(topo=topo, switch=OVSSwitch, build=False) net.addController(c1) net.build() net.start() CLI(net) net.stop()
def createTopo(): topo = Topo() #Create Nodes topo.addHost("h1") topo.addHost("h2") topo.addHost("h3") topo.addHost("h4") topo.addHost("h5") topo.addHost("h6") topo.addHost("h7") topo.addHost("h8") topo.addSwitch('d1') topo.addSwitch('d2') topo.addSwitch('a1') topo.addSwitch('a2') topo.addSwitch('a3') topo.addSwitch('a4') #Create links topo.addLink('d1', 'd2', bw=10000, delay='1ms') topo.addLink('d1', 'a1', bw=1000, delay='3ms') topo.addLink('d1', 'a2', bw=1000, delay='3ms') topo.addLink('d2', 'a3', bw=1000, delay='3ms') topo.addLink('d2', 'a4', bw=1000, delay='3ms') topo.addLink('a1', 'h1', bw=100, delay='5ms') topo.addLink('a1', 'h2', bw=100, delay='5ms') topo.addLink('a2', 'h3', bw=100, delay='5ms') topo.addLink('a2', 'h4', bw=100, delay='5ms') topo.addLink('a3', 'h5', bw=100, delay='5ms') topo.addLink('a3', 'h6', bw=100, delay='5ms') topo.addLink('a4', 'h7', bw=100, delay='5ms') topo.addLink('a4', 'h8', bw=100, delay='5ms', loss=15) return topo
h2 = topo.addHost( 'h2' ) h3 = topo.addHost( 'h3' ) h4 = topo.addHost( 'h4' ) h5 = topo.addHost( 'h5' ) h6 = topo.addHost( 'h6' ) h7 = topo.addHost( 'h7' ) # Add switches s1 = topo.addSwitch( 's1' ) s2 = topo.addSwitch( 's2' ) s3 = topo.addSwitch( 's3' ) s4 = topo.addSwitch( 's4' ) # Add links bw = MyRandom() topo.addLink('h1', 's1', bw=bw, use_htb=True, cls=TCLink) bw = MyRandom() topo.addLink('h2', 's2', bw=bw, use_htb=True, cls=TCLink) bw = MyRandom() topo.addLink('h3', 's3', bw=bw, use_htb=True, cls=TCLink) bw = MyRandom() topo.addLink('h4', 's3', bw=bw, use_htb=True, cls=TCLink) bw = MyRandom() topo.addLink('h5', 's4', bw=bw, use_htb=True, cls=TCLink) bw = MyRandom() topo.addLink('h6', 's4', bw=bw, use_htb=True, cls=TCLink) bw = MyRandom() topo.addLink('h7', 's4', bw=bw, use_htb=True, cls=TCLink) bw = weights[1][2] topo.addLink('s1', 's2', bw=bw, use_htb=True, cls=TCLink)
ip="10.0.0.5", dimage="tasnimul/randompacketgenerator:latest") t6 = topo.addHost("t6", cls=Docker, ip="10.0.0.6", dimage="tasnimul/randompacketgenerator:latest") t7 = topo.addHost("t7", cls=Docker, ip="10.0.0.7", dimage="tasnimul/randompacketgenerator:latest") #Creating Switches s8 = topo.addSwitch("s8") #Connecting hosts to switches topo.addLink(t1, s8) topo.addLink(t2, s8) topo.addLink(t3, s8) topo.addLink(t4, s8) topo.addLink(t5, s8) topo.addLink(t6, s8) topo.addLink(t7, s8) cluster = maxinet.Cluster() exp = maxinet.Experiment(cluster, topo, switch=OVSSwitch) exp.setup() try: print exp.get_node("t1").cmd("ping -c 1 10.0.0.7") print exp.get_node("t2").cmd("ping -c 1 10.0.0.1") print exp.get_node("t3").cmd("ping -c 1 10.0.0.1")
import subprocess from mininet.node import OVSSwitch from mininet.topo import Topo from MaxiNet.Frontend import maxinet from MaxiNet.tools import Tools topo = Topo() topo.addSwitch("s1") topo.addSwitch("s2") topo.addHost("h1", ip=Tools.makeIP(1), mac=Tools.makeMAC(1)) topo.addHost("h2", ip=Tools.makeIP(2), mac=Tools.makeMAC(2)) topo.addLink("h1", "s1") topo.addLink("s1", "s2") topo.addLink("h2", "s2") cluster = maxinet.Cluster() # we need to add the root node after the simulation has started as we do # not know which worker id the frontend machine will get. Therefore we # need a dynamic topology which is only supported in openvswitch exp = maxinet.Experiment(cluster, topo, switch=OVSSwitch) exp.setup() # Start ssh servers h1 = exp.get("h1") h1.cmd("echo \"Welcome to %s at %s\n\" > /tmp/%s.banner" % (h1.name, h1.IP(), h1.name))
import time from MaxiNet.Frontend import maxinet from MaxiNet.Frontend.container import Docker from mininet.topo import Topo from mininet.node import OVSSwitch topo = Topo() d1 = topo.addHost("d1", cls=Docker, ip="10.0.0.251", dimage="ubuntu:trusty") d2 = topo.addHost("d2", cls=Docker, ip="10.0.0.252", dimage="ubuntu:trusty") s1 = topo.addSwitch("s1") s2 = topo.addSwitch("s2") topo.addLink(d1, s1) topo.addLink(s1, s2) topo.addLink(d2, s2) cluster = maxinet.Cluster() exp = maxinet.Experiment(cluster, topo, switch=OVSSwitch) exp.setup() print exp.get_node("d1").cmd("ifconfig") print exp.get_node("d2").cmd("ifconfig") print "waiting 5 seconds for routing algorithms on the controller to converge" time.sleep(5) print exp.get_node("d1").cmd("ping -c 5 10.0.0.252") print exp.get_node("d2").cmd("ping -c 5 10.0.0.251")
# | | # +-----------+-----------+ # | # | # | # | # +-------------+ v +-------------+ # | | | | # | host 1 (h1) +------------------+ host 2 (h2) | # | | | | # +-------------+ +-------------+ # topo = Topo() topo.addHost('h1') topo.addHost('h2') topo.addLink('h1', 'h2', bw=10, delay='5ms', loss=10) # The TCLink is needed for use to set the bandwidth, delay and loss # constraints on the link # # waitConnected net = Mininet(topo=topo, link=TCLink, waitConnected=True) net.start() h1, h2 = net.getNodeByName('h1', 'h2') # Will open the two ping processes on both hosts and read the output popens = {} popens[h1] = h1.popen('ping -c10 {}'.format(h2.IP())) popens[h2] = h2.popen('ping -c10 {}'.format(h1.IP()))
# set options proj_path = os.path.abspath('../../') es_address = '10.0.0.1' num_pubs = 2 num_subs = 6 topics = set(['books','news','compilers','tech','world','sport']) publishers = set([]) subscribers = set([]) topo = Topo() # Create an empty topology topo.addSwitch("s1") # Add switches and hosts to the topology topo.addHost("es") topo.addLink('es','s1') print "adding publishers to the topology" for h in range(num_pubs): publisher = topo.addHost("hp{}".format(h+1)) topo.addLink(publisher, "s1") # Wire the switches and hosts together with links publishers.add(publisher) for h in range(num_subs): subscriber = topo.addHost("hs{}".format(h+1)) topo.addLink(subscriber, "s1") subscribers.add(subscriber) print publishers print subscribers net = Mininet(topo)
my_swlist = [] for key, value in dict.items(data["switches"]): my_swlist.append(key) # Add to list of switches in topology cnt = 1 for value1, value2 in dict.items(data["switches"][key]): tmp = str(key) myglobalTopo.addSwitch(tmp, dpid=Tools.makeDPID(cnt)) cnt = cnt + 1 #hnames = data["hosts"] hnames = data["links"] hlen = len(hnames) for x in range(0, hlen): tmp = str(hnames[x][0]) tmp1 = str(hnames[x][1]) myglobalTopo.addLink(tmp, tmp1) print "Finished Loading Topology..." print "Creating Cluster ..." # start cluster cluster = maxinet.Cluster(minWorkers=1, maxWorkers=num_workers, tk_args=tk_args) # start experiment with P4Switch on cluster exp = maxinet.Experiment(cluster, myglobalTopo, switch=P4Switch) # We can copy experiment.cfg, in_topo.json files to the respective workers
if __name__ == '__main__': setLogLevel('info') argv = sys.argv if len(argv) != 2: print("Usage: {} <path-to-tunnel-binary>".format(argv[0])) sys.exit(0) tunnel_binary = argv[1] topo = Topo() topo.addHost('h1') topo.addHost('h2') topo.addLink('h1', 'h2', bw=3.0, delay='250ms', loss=0.0) # TCLink is needed to set the bandwidth, delay and loss constraints # on the link net = Mininet(topo=topo, link=TCLink, waitConnected=True) net.start() h1, h2 = net.getNodeByName('h1', 'h2') # We launch a separate thread for the tunnel processes, so we can monitor # them while iperf is running finished = False def start_tunnel(): print("Starting udp_tunnel...")
''' Experiment run with default topology, test cases won't work with other topologies # With calculateNPossibleRoutes, 10 # routing = hr, N = All, from A, 3 routes needs to added to NFD. a +++++++ b # a - b -- cost 10 + + # a - c -- cost 10 10 + + 10 # a - d -- cost 20 + + # Same goes for B being a source. c d # ''' topo = Topo() a = topo.addHost('a') b = topo.addHost('b') c = topo.addHost('c') d = topo.addHost('d') topo.addLink(a, b, delay='10ms') topo.addLink(a, c, delay='10ms') topo.addLink(b, d, delay='10ms') ndn = Minindn(parser=parser, topo=topo) ndn.start() info('Starting NFD on nodes\n') nfds = AppManager(ndn, ndn.net.hosts, Nfd) info('Adding static routes to NFD\n') grh = NdnRoutingHelper(ndn.net, ndn.args.faceType, ndn.args.routingType) # For all host, pass ndn.net.hosts or a list, [ndn.net['a'], ..] or [ndn.net.hosts[0],.] grh.addOrigin([ndn.net['a']], ["/example/testApp"]) grh.calculateNPossibleRoutes() '''
import time from mininet.topo import Topo from mininet.node import OVSSwitch from MaxiNet.Frontend import maxinet from MaxiNet.tools import Tools # create topology topo = Topo() topo.addHost("h1", ip=Tools.makeIP(1), mac=Tools.makeMAC(1)) topo.addHost("h2", ip=Tools.makeIP(2), mac=Tools.makeMAC(2)) topo.addSwitch("s1", dpid=Tools.makeDPID(1)) topo.addLink("h1", "s1") topo.addLink("h2", "s1") # start cluster cluster = maxinet.Cluster(minWorkers=5, maxWorkers=5) # start experiment with OVSSwitch on cluster exp = maxinet.Experiment(cluster, topo, switch=OVSSwitch) exp.setup() print "waiting 5 seconds for routing algorithms on the controller to converge" time.sleep(5) print "pinging h2 from h1 to check network connectivity..." print exp.get_node("h1").cmd("ping -c 5 10.0.0.2") # show network connectivity
topo.addHost("h3", ip=Tools.makeIP(3), mac=Tools.makeMAC(3)) topo.addHost("h4", ip=Tools.makeIP(4), mac=Tools.makeMAC(4)) topo.addHost("h5", ip=Tools.makeIP(5), mac=Tools.makeMAC(5)) topo.addHost("h6", ip=Tools.makeIP(6), mac=Tools.makeMAC(6)) topo.addHost("h7", ip=Tools.makeIP(7), mac=Tools.makeMAC(7)) topo.addHost("h8", ip=Tools.makeIP(8), mac=Tools.makeMAC(8)) topo.addSwitch("s1", dpid=Tools.makeDPID(1), wid=0) topo.addSwitch("s2", dpid=Tools.makeDPID(2), wid=1) topo.addSwitch("s3", dpid=Tools.makeDPID(3), wid=2) topo.addSwitch("s4", dpid=Tools.makeDPID(4), wid=3) topo.addSwitch("s5", dpid=Tools.makeDPID(5), wid=4) topo.addSwitch("s6", dpid=Tools.makeDPID(6), wid=5) topo.addSwitch("s7", dpid=Tools.makeDPID(7), wid=6) topo.addLink("h1", "s4") topo.addLink("h2", "s4") topo.addLink("h3", "s5") topo.addLink("h4", "s5") topo.addLink("h5", "s6") topo.addLink("h6", "s6") topo.addLink("h7", "s7") topo.addLink("h8", "s7") topo.addLink("s1", "s2") topo.addLink("s1", "s3") topo.addLink("s2", "s4") topo.addLink("s2", "s5") topo.addLink("s3", "s6") topo.addLink("s3", "s7")
def create_topology(context): topo = Topo() h = '' sfs_per_sff = int(context.sf_number) / int(context.switch_number) # Add the links SFFs - SFs for i in range(len(context.sf_forwarders)): print context.sf_forwarders[i].opts s = topo.addSwitch(context.sf_forwarders[i].name, opts=context.sf_forwarders[i].opts) for j in range(sfs_per_sff): sf_index = (i*int(sfs_per_sff))+j if not context.service_functions[sf_index]: # Add the Loop switches instead of normal hosts sf_loopback_name = '%s-node%d' % (context.sf_forwarders[i].name,j+1) context.sf_loopbacks.append(sf_loopback_name) h = topo.addSwitch(sf_loopback_name, opts='') else: # Add the SFs as normal hosts if context.service_functions[sf_index].vlan_id_ == 0: h = topo.addHost(context.service_functions[sf_index].name, ip=context.service_functions[sf_index].ip_, mac=context.service_functions[sf_index].mac_) else: h = topo.addHost(context.service_functions[sf_index].name, cls=VlanHost, vlan=context.service_functions[sf_index].vlan_id_, ip=context.service_functions[sf_index].ip_, mac=context.service_functions[sf_index].mac_) # Connect the SF to the SFF topo.addLink(node1=h, node2=s) # Add the GWs gw1 = topo.addSwitch(context.gateways[0].name, opts=context.gateways[0].opts) gw2 = topo.addSwitch(context.gateways[1].name, opts=context.gateways[1].opts) if context.topology_tor: # Create the Top-of-Rack switch tor = topo.addSwitch(context.tor_info.name, opts=context.tor_info.opts) # Connect each SFF to the ToR switch for i in range(len(context.sf_forwarders)): topo.addLink(context.tor_info.name, context.sf_forwarders[i].name) # Add the links between the GWs and the tor topo.addLink(context.gateways[0].name, context.tor_info.name) topo.addLink(context.gateways[1].name, context.tor_info.name) else: # Add the links between SFFs for i in range(len(context.sf_forwarders)-1): topo.addLink(context.sf_forwarders[i].name, context.sf_forwarders[i+1].name) # Add the links between SFFs and GWs topo.addLink(context.gateways[0].name, context.sf_forwarders[0].name) topo.addLink(context.gateways[1].name, context.sf_forwarders[len(context.sf_forwarders)-1].name) # Add the link between gw1 and gw2 topo.addLink(context.gateway_client, context.gateway_server ) # Add the clients and their links to GW1 for i in range(int(context.clients_number)): h = topo.addHost(context.clients[i].name, ip=context.clients[i].ip_, mac=context.clients[i].mac_) topo.addLink(node1=h, node2=gw1) # Add the servers and their links to GW2 for i in range(len(context.servers)): h = topo.addHost(context.servers[i].name, ip=context.servers[i].ip_, mac=context.servers[i].mac_) topo.addLink(node1=h, node2=gw2) return topo
for switch in switches: topo.addSwitch(switch.replace('\n', '')) file.close() print('Creating hosts...') with open('./conf/hosts.mxn', 'r') as file: hosts = file.readlines() for host in hosts: topo.addHost(host.replace('\n', '')) file.close() print('Creating connections between Mininet elements...') with open('./conf/connections.mxn', 'r') as file: connections = csv.reader(file) for connection in connections: topo.addLink(connection[0], connection[1]) file.close() print('Setting hostname mapping...') hostnamemapping = {} with open('./conf/hostnamemapping.mxn', 'r') as file: lines = file.read() hostnamemapping = eval('{' + lines + '}') file.close() print('hostnamemapping: %s' % hostnamemapping) print('Setting node mapping...') nodemapping = {} with open('./conf/nodemapping.mxn', 'r') as file: lines = file.read() nodemapping = eval('{' + lines + '}')
class MininetWrapper(object): def __init__(self): self.mininet_client = None self.topology = [] self.delay = None def set_delay(self, delay): delay = str(int(delay)) + 'ms' self.delay = delay def run_mininet(self, topology_string): """ Create and run multiple link network """ self.topo_client = Topo() hosts = set() switches = set() relations = re.sub(r's', '', topology_string) relations = [i.split(':') for i in relations.split(',') if 'h' not in i] relations = [[int(y) - 1 for y in x] for x in relations] builtin.log(relations, 'DEBUG') verticles_count = len(set(list(itertools.chain(*relations)))) builtin.log(self.topology, 'DEBUG') for i in xrange(verticles_count): temp = [] for j in xrange(verticles_count): temp.append(-1) self.topology.append(temp[:]) builtin.log(self.topology, 'DEBUG') for i in relations: self.topology[i[0]][i[1]] = 1 self.topology[i[1]][i[0]] = 1 builtin.log(self.topology, 'DEBUG') for v1, v2 in [x.split(':') for x in str(topology_string).split(',')]: if 'h' in v1 and v1 not in hosts: self.topo_client.addHost(v1) hosts.add(v1) if 'h' in v2 and v2 not in hosts: self.topo_client.addHost(v2) hosts.add(v2) if 's' in v1 and v1 not in switches: self.topo_client.addSwitch(v1) switches.add(v1) if 's' in v2 and v2 not in switches: self.topo_client.addSwitch(v2) switches.add(v2) if self.delay: self.topo_client.addLink(v1, v2, delay=self.delay) else: self.topo_client.addLink(v1, v2) self.mininet_client = Mininet(switch=user_switch, controller=remote_controller, topo=self.topo_client, link=TCLink) self.mininet_client.start() builtin.log('Links info:') for link in self.topo_client.links(withKeys=True, withInfo=True): builtin.log(link) # self.mininet_client.waitConnected(timeout=20) sleep(20) def stop_mininet(self): if self.mininet_client is not None: self.mininet_client.stop() if self.topology: self.topology = [] self.delay = None cleanup() sleep(20) def kill_link(self, host1, host2): host1, host2 = str(host1), str(host2) self.mininet_client.configLinkStatus(host1, host2, 'down') if 'h' not in host1 and 'h' not in host2: num_1 = int(host1[1:]) - 1 num_2 = int(host2[1:]) - 1 self.topology[num_1][num_2] = -1 self.topology[num_2][num_1] = -1 builtin.log(self.topology, 'DEBUG') builtin.log('Down link {0} - {1}'.format(host1, host2), 'DEBUG') def check_link(self, host1, host2): switch = self.mininet_client.getNodeByName(host1) connections = switch.connectionsTo(host2) if connections: return True else: return False def up_link(self, host1, host2): host1, host2 = str(host1), str(host2) self.mininet_client.configLinkStatus(host1, host2, 'up') if 'h' not in host1 and 'h' not in host2: num_1 = int(host1[1:]) - 1 num_2 = int(host2[1:]) - 1 self.topology[num_1][num_2] = 1 self.topology[num_2][num_1] = 1 builtin.log(self.topology, 'DEBUG') builtin.log('Up link {0} - {1}'.format(host1, host2), 'DEBUG') def stop_node(self, name): node = self.mininet_client.getNodeByName(name) node.stop() num_node = int(name[1:]) - 1 self.topology[num_node][num_node] = -1 builtin.log('Node {0} was stoped'.format(name), 'DEBUG') def check_connected_node(self, name): switch = self.mininet_client.getNodeByName(name) return switch.connected() # NOTE(msenin) unstable method - after stoping mininet cant start node # mininet doesn't return exception def start_node(self, name): node = self.mininet_client.getNodeByName(name) # TODO (msenin) add option controller_name controllers = self.mininet_client.controllers builtin.log('Controllers: {0}'.format(controllers), 'DEBUG') node.start([controllers[0]]) def check_rules(self): switches = self.mininet_client.switches results = [] regex = (r'(cookie=[\w\d]+),|(dl_dst=[\w\d:\/]{35})' '|(priority=[\d]+),|(dl_src=[\w\d:\/]{17})') for switch in switches: ans = switch.dpctl('dump-flows -O OpenFlow13') builtin.log( 'Rules on the switch {0}: {1}'.format(switch.name, ans), 'DEBUG') ans_with_regex = "" for m in re.finditer(regex, ans): for i in xrange(1, 5): if m.group(i): ans_with_regex = ans_with_regex + ', ' + m.group(i) builtin.log( 'Rules with regex {0}: {1}'.format(switch.name, ans), 'DEBUG') results.append({switch.name: ans_with_regex}) return results def compare_dumped_flows(self, rules1, rules2): rules_1 = str(rules1) rules_2 = str(rules2) builtin.log('Compare two flow tables(without changing parts): ', 'DEBUG') builtin.log(rules_1, 'DEBUG') builtin.log(rules_2, 'DEBUG') if rules_1 != rules_2: return False return True def ping(self, name1, name2): node1 = self.mininet_client.getNodeByName(name1) node2 = self.mininet_client.getNodeByName(name2) ping = self.mininet_client.ping(hosts=[node1, node2], timeout=10) num1, num2 = name1[1:], name2[1:] cmd1 = node1.cmd('ifconfig') builtin.log('{0}'.format(cmd1), 'DEBUG') cmd1 = node1.cmd('ping -d -c 5 -w 5 10.0.0.' + num2) builtin.log('{0}'.format(cmd1), 'DEBUG') cmd2 = node2.cmd('ifconfig') builtin.log('{0}'.format(cmd2), 'DEBUG') cmd1 = node2.cmd('ping -d -c 5 -w 5 10.0.0.' + num1) builtin.log('{0}'.format(cmd1), 'DEBUG') return int(ping) def check_route_state(self, route): # TODO (msenin) delete method after tests refactoring """Check the state of route :param route: list with verticles (each verticle is switch id) """ route = map(lambda x: int(x) - 1, route) for i in xrange(1, len(route)): prev = route[i - 1] cur = route[i] if (self.topology[prev][prev] == -1 or self.topology[cur][cur] == -1): return False if self.topology[prev][cur] == -1: return False return True def contains_route_in_routes(self, route, routes): builtin.log("route: {0}".format(route), 'DEBUG') builtin.log("routes: {0}".format(routes), 'DEBUG') route = map(lambda x: int(x), route) for i in routes: if i.get('route') and map(lambda x: int(x), i['route']) == route: return True return False def parse_tree(self, resp): """Define and check the routes and links :param resp:json from response """ builtin.log("JSON for parsing: {0}".format(resp), 'DEBUG') source_node_list = set() destination_node_list = set() links_dict = collections.OrderedDict() routes = [] states_dict = dict() route_container = resp.get('route-container') route_list = route_container.get('route-list') route_list_length = len(route_list) # TODO for i in range(0, route_list_length): needed_leaf = i route_leaf = route_list[needed_leaf] leaf_source = route_leaf.get('source') leaf_destination = route_leaf.get('destination') states_dict['source'] = leaf_source states_dict['destination'] = leaf_destination route = route_leaf.get('route', []) for i in range(0, len(route)): route_state = dict() vertexes = set() path = route[i] state = path.get('state') route_state['state'] = state route_state['route'] = vertexes routes.append(route_state) states_dict['routes'] = routes links = path.get('path') links_count = len(links) for j in range(0, links_count): link = links[j] link_source = link.get('source') link_destination = link.get('destination') source_node = link_source.get('source-node') destination_node = link_destination.get('dest-node') source_flow = source_node.split(':')[-1] destination_flow = destination_node.split(':')[-1] vertexes.add(source_flow) vertexes.add(destination_flow) source_node_list.add(source_node) destination_node_list.add(destination_node) links_dict[source_node] = destination_node return states_dict def parse_tree_2(self, resp): """Parse output json from ncn restconfig :param resp:json from response [{'state': 'up', 'destination': '4', 'route': ['1', '4'], 'source': '1', 'id': 100}, .................................................................... {'destination': '3', 'source': '1'}, {'destination': '7', 'source': '1'}] """ builtin.log("JSON for parsing: {0}".format(resp), 'DEBUG') routes = [] route_list = resp.get('route-container').get('route-list') for routes_between_switches in route_list: routes_rest_conf = routes_between_switches.get("route") if routes_rest_conf: # NOTE (msenin) # format of fields 'source' and 'destination': openflow:4 for route_rest in routes_rest_conf: route = {} route['source'] = int(route_rest['source'][9:]) route['destination'] = \ int(route_rest['destination'][9:]) route['state'] = route_rest['state'] pathes = route_rest.get('path') route['id'] = route_rest.get('id') path = [] for link in pathes: link_source = link.get('source') link_destination = link.get('destination') source_node = link_source.get('source-node') destination_node = link_destination.get('dest-node') source_flow = int(source_node[9:]) destination_flow = int(destination_node[9:]) if source_flow not in path: path.append(source_flow) if destination_flow not in path: path.append(destination_flow) route['route'] = path routes.append(route) else: route = {} route['source'] = int(routes_between_switches['source'][9:]) route['destination'] = \ int(routes_between_switches['destination'][9:]) routes.append(route) return routes def check_route_state_by_DOM_tree(self, route, tree): """ return 1 if route up, -1 down and 0 if unexist """ if isinstance(route, str) or isinstance(route, unicode): route = list(route[1:-1].split(',')) route = map(lambda x: int(x), route) builtin.log("route: {0}".format(route), 'DEBUG') tree = self.parse_tree_2(tree) builtin.log("tree: {0}".format(tree), 'DEBUG') filtered_tree = filter(lambda x: x.get('route') == route, tree) if filtered_tree: if filtered_tree[0]['state'] == 'up': return 1 else: return -1 else: return 0 def filter_DOM_tree_by_field(self, condition, tree): # TODO (msenin) add logger tree = self.parse_tree_2(tree) filtered_tree = filter(lambda field: eval(condition), tree) return filtered_tree
def createTopo(): print "Create a topology." topo=Topo() print "Adding switches" NewYork = topo.addSwitch( 's1' ) Chicago = topo.addSwitch( 's2' ) WashingtonDC = topo.addSwitch( 's3' ) Seattle = topo.addSwitch( 's4' ) Sunnyvale = topo.addSwitch( 's5' ) LosAngeles = topo.addSwitch( 's6' ) Denver = topo.addSwitch( 's7' ) KansasCity = topo.addSwitch( 's8' ) Houston = topo.addSwitch( 's9' ) Atlanta = topo.addSwitch( 's10' ) Indianapolis = topo.addSwitch( 's11' ) print "Adding hosts" NewYork_host = topo.addHost( 'h1' ) Chicago_host = topo.addHost( 'h2' ) WashingtonDC_host = topo.addHost( 'h3' ) Seattle_host = topo.addHost( 'h4' ) Sunnyvale_host = topo.addHost( 'h5' ) LosAngeles_host = topo.addHost( 'h6' ) Denver_host = topo.addHost( 'h7' ) KansasCity_host = topo.addHost( 'h8' ) Houston_host = topo.addHost( 'h9' ) Atlanta_host = topo.addHost( 'h10' ) Indianapolis_host = topo.addHost( 'h11' ) print "Adding edges switch <-> host" topo.addLink( NewYork , NewYork_host ) topo.addLink( Chicago , Chicago_host ) topo.addLink( WashingtonDC , WashingtonDC_host ) topo.addLink( Seattle , Seattle_host ) topo.addLink( Sunnyvale , Sunnyvale_host ) topo.addLink( LosAngeles , LosAngeles_host ) topo.addLink( Denver , Denver_host ) topo.addLink( KansasCity , KansasCity_host ) topo.addLink( Houston , Houston_host ) topo.addLink( Atlanta , Atlanta_host ) topo.addLink( Indianapolis , Indianapolis_host ) print "Adding switches <-> switches" topo.addLink( NewYork , Chicago, bw=1000, delay='0.200ms') topo.addLink( NewYork , WashingtonDC, bw=1000, delay='0.200ms') topo.addLink( Chicago , Indianapolis, bw=1000, delay='0.200ms') topo.addLink( WashingtonDC , Atlanta, bw=1000, delay='0.200ms') topo.addLink( Seattle , Sunnyvale, bw=1000, delay='0.200ms') topo.addLink( Seattle , Denver, bw=1000, delay='0.200ms') topo.addLink( Sunnyvale , LosAngeles, bw=1000, delay='0.200ms') topo.addLink( Sunnyvale , Denver, bw=1000, delay='0.200ms') topo.addLink( LosAngeles , Houston, bw=1000, delay='0.200ms') topo.addLink( Denver , KansasCity, bw=1000, delay='0.200ms') topo.addLink( KansasCity , Houston, bw=1000, delay='0.200ms') topo.addLink( KansasCity , Indianapolis, bw=1000, delay='0.200ms') topo.addLink( Houston , Atlanta, bw=1000, delay='0.200ms') topo.addLink( Atlanta , Indianapolis, bw=1000, delay='0.200ms') return topo
def create_topology(context): topo = Topo() h = '' sfs_per_sff = int(context.sf_number) / int(context.switch_number) # Add the links SFFs - SFs for i in range(len(context.sf_forwarders)): print context.sf_forwarders[i].opts s = topo.addSwitch( context.sf_forwarders[i].name, opts=context.sf_forwarders[i].opts) for j in range(sfs_per_sff): sf_index = (i*int(sfs_per_sff))+j if not context.service_functions[sf_index]: # Add the Loop switches instead of normal hosts sf_loopback_name = '%s-node%d' % ( context.sf_forwarders[i].name, j + 1) context.sf_loopbacks.append(sf_loopback_name) h = topo.addSwitch(sf_loopback_name, opts='') else: # Add the SFs as normal hosts if context.service_functions[sf_index].vlan_id_ == 0: h = topo.addHost( context.service_functions[sf_index].name, ip=context.service_functions[sf_index].ip_, mac=context.service_functions[sf_index].mac_) else: h = topo.addHost( context.service_functions[sf_index].name, cls=VlanHost, vlan=context.service_functions[sf_index].vlan_id_, ip=context.service_functions[sf_index].ip_, mac=context.service_functions[sf_index].mac_) # Connect the SF to the SFF topo.addLink(node1=h, node2=s) # Add the GWs gw1 = topo.addSwitch( context.gateways[0].name, opts=context.gateways[0].opts) gw2 = topo.addSwitch( context.gateways[1].name, opts=context.gateways[1].opts) if context.topology_tor: # Create the Top-of-Rack switch topo.addSwitch(context.tor_info.name, opts=context.tor_info.opts) # Connect each SFF to the ToR switch for i in range(len(context.sf_forwarders)): topo.addLink(context.tor_info.name, context.sf_forwarders[i].name) # Add the links between the GWs and the tor topo.addLink(context.gateways[0].name, context.tor_info.name) topo.addLink(context.gateways[1].name, context.tor_info.name) else: # Add the links between SFFs for i in range(len(context.sf_forwarders)-1): topo.addLink( context.sf_forwarders[i].name, context.sf_forwarders[i+1].name) # Add the links between SFFs and GWs topo.addLink( context.gateways[0].name, context.sf_forwarders[0].name) topo.addLink( context.gateways[1].name, context.sf_forwarders[len(context.sf_forwarders)-1].name) # Add the link between gw1 and gw2 topo.addLink(context.gateway_client, context.gateway_server) # Add the clients and their links to GW1 for i in range(int(context.clients_number)): h = topo.addHost(context.clients[i].name, ip=context.clients[i].ip_, mac=context.clients[i].mac_) topo.addLink(node1=h, node2=gw1) # Add the servers and their links to GW2 for i in range(len(context.servers)): h = topo.addHost(context.servers[i].name, ip=context.servers[i].ip_, mac=context.servers[i].mac_) topo.addLink(node1=h, node2=gw2) return topo
def createTopo(): print "Create a topology." topo=Topo() print "Adding switch" masterSwitch = topo.addSwitch( 's1' ) print "Adding servers" server1 = topo.addHost( 'server1' ) server2 = topo.addHost( 'server2' ) print "Adding hosts" host1 = topo.addHost( 'h1' ) host2 = topo.addHost( 'h2' ) host3 = topo.addHost( 'h3' ) host4 = topo.addHost( 'h4' ) host5 = topo.addHost( 'h5' ) host6 = topo.addHost( 'h6' ) host7 = topo.addHost( 'h7' ) host8 = topo.addHost( 'h8' ) host9 = topo.addHost( 'h9' ) host10 = topo.addHost( 'h10' ) print "Adding links" topo.addLink( host1 , masterSwitch, bw=1, delay='0.200ms') topo.addLink( host2 , masterSwitch, bw=1, delay='0.200ms') topo.addLink( host3 , masterSwitch, bw=1, delay='0.200ms') topo.addLink( host4 , masterSwitch, bw=1, delay='0.200ms') topo.addLink( host5 , masterSwitch, bw=1, delay='0.200ms') topo.addLink( host6 , masterSwitch, bw=1, delay='0.200ms') topo.addLink( host7 , masterSwitch, bw=1, delay='0.200ms') topo.addLink( host8 , masterSwitch, bw=1, delay='0.200ms') topo.addLink( host9 , masterSwitch, bw=1, delay='0.200ms') topo.addLink( host10 , masterSwitch, bw=1, delay='0.200ms') topo.addLink( server1 , masterSwitch, bw=10, delay='0.200ms') topo.addLink( server2 , masterSwitch, bw=10, delay='0.200ms') return topo
def to_mininet(topology, switches=None, hosts=None, relabel_nodes=True): """Convert an FNSS topology to Mininet Topo object that can be used to deploy a Mininet network. If the links of the topology are labeled with delays, capacities or buffer sizes, the returned Mininet topology will also include those parameters. However, it should be noticed that buffer sizes are included in the converted topology only if they are expressed in packets. If buffer sizes are expressed in the form of bytes they will be discarded. This is because Mininet only supports buffer sizes expressed in packets. Parameters ---------- topology : Topology, DirectedTopology or DatacenterTopology An FNSS Topology object switches : list, optional List of topology nodes acting as switches hosts : list, optional List of topology nodes acting as hosts relabel_nodes : bool, optional If *True*, rename node labels according to `Mininet conventions <https://github.com/mininet/mininet/wiki/Introduction-to-Mininet#naming-in-mininet>`_. In Mininet all node labels are strings whose values are "h1", "h2", ... if the node is a host or "s1", "s2", ... if the node is a switch. Returns ------- topology : Mininet Topo A Mininet topology object Notes ----- It is not necessary to provide a list of switch and host nodes if the topology object provided are already annotated with a type attribute that can have values *host* or *switch*. This is the case of datacenter topologies generated with FNSS which already include information about which nodes are hosts and which are switches. If switches and hosts are passed as arguments, then the hosts and switches sets must be disjoint and their union must coincide to the set of all topology nodes. In other words, there cannot be nodes labeled as both *host* and *switch* and there cannot be nodes that are neither a *host* nor a *switch*. It is important to point out that if the topology contains loops, it will not work with the *ovs-controller* and *controller* provided by Mininet. It will be necessary to use custom controllers. Further info `here <https://github.com/mininet/mininet/wiki/Introduction-to-Mininet#multipath-routing>`_. """ try: from mininet.topo import Topo except ImportError: raise ImportError('Cannot import mininet.topo package. ' 'Make sure Mininet is installed on this machine.') if hosts is None: hosts = (v for v in topology.nodes_iter() if 'host' in topology.node[v]['type']) if switches is None: switches = (v for v in topology.nodes_iter() if 'switch' in topology.node[v]['type']) nodes = set(topology.nodes_iter()) switches = set(switches) hosts = set(hosts) if not switches.isdisjoint(hosts): raise ValueError('Some nodes are labeled as both host and switch. ' 'Switches and hosts node lists must be disjoint') if nodes != switches.union(hosts): raise ValueError('Some nodes are not labeled as either host or switch ' 'or some nodes listed as switches or hosts do not ' 'belong to the topology') if relabel_nodes: hosts = sorted(hosts) switches = sorted(switches) mapping = dict([(hosts[i], "h%s" % str(i+1)) for i in range(len(hosts))] + [(switches[i], "s%s" % str(i+1)) for i in range(len(switches))]) hosts = set(mapping[v] for v in hosts) switches = set(mapping[v] for v in switches) nodes = hosts.union(switches) topology = nx.relabel_nodes(topology, mapping, copy=True) topo = Topo() for v in switches: topo.addSwitch(str(v)) for v in hosts: topo.addHost(str(v)) delay_unit = topology.graph['delay_unit'] \ if 'delay_unit' in topology.graph else None capacity_unit = topology.graph['capacity_unit'] \ if 'capacity_unit' in topology.graph else None buffer_unit = topology.graph['buffer_unit'] \ if 'buffer_unit' in topology.graph else None if capacity_unit: capacity_conversion = float(capacity_units[capacity_unit]) \ / capacity_units['Mbps'] if delay_unit: delay_conversion = float(time_units[delay_unit]) \ / time_units['us'] for u, v in topology.edges_iter(): params = {} if 'capacity' in topology.edge[u][v] and capacity_unit: params['bw'] = topology.edge[u][v]['capacity'] * capacity_conversion # Use Token Bucket filter to implement rate limit params['use_htb'] = True if 'delay' in topology.edge[u][v] and delay_unit: params['delay'] = '%sus' % str(topology.edge[u][v]['delay'] * delay_conversion) if 'buffer_size' in topology.edge[u][v] and buffer_unit == 'packets': params['max_queue_size'] = topology.edge[u][v]['buffer_size'] topo.addLink(str(u), str(v), **params) return topo
from mininet.net import Mininet from mininet.topo import Topo topo = Topo() # Create an empty topology topo.addSwitch("s1") # Add switches and hosts to the topology topo.addHost("h1") topo.addHost("h2") topo.addLink("h1", "s1") # Wire the switches and hosts together with links topo.addLink("h2", "s1") net = Mininet(topo) # Create the Mininet, start it and try some stuff net.start() net.pingAll() net.iperf() net.stop()
def createTopo(): topo = Topo() #Create Host Nodes for x in range(1, 9): print "h" + str(x) topo.addHost("h" + str(x)) #Create Switch Nodes topo.addSwitch("c1") topo.addSwitch("d1") topo.addSwitch("d2") for x in range(1, 5): print "a" + str(x) topo.addSwitch("a" + str(x)) #Create links topo.addLink("c1", "d1", bw=10000, delay='1ms') topo.addLink("c1", "d2", bw=10000, delay='1ms') for x in range(1, 3): topo.addLink("d" + str(x), "a" + str(2 * x - 1), bw=1000, delay='3ms') topo.addLink("d" + str(x), "a" + str(2 * x), bw=1000, delay='3ms') for x in range(1, 5): topo.addLink("a" + str(x), "h" + str(2 * x - 1), bw=100, delay='5ms') if 2 * x == 8: topo.addLink("a" + str(x), "h" + str(2 * x), bw=100, delay='5ms', loss=15) topo.addLink("a" + str(x), "h" + str(2 * x), bw=100, delay='5ms') return topo
def run(): PREFIX = "/ndn/test/" Minindn.cleanUp() Minindn.verifyDependencies() topo = Topo() # Setup topo print("Setup") c1 = topo.addHost('c1') i1 = topo.addHost('i1') i2 = topo.addHost('i2') i3 = topo.addHost('i3') i4 = topo.addHost('i4') i5 = topo.addHost('i5') i6 = topo.addHost('i6') p1 = topo.addHost('p1') topo.addLink(c1, i1, bw=10) topo.addLink(i1, i2, bw=4, delay='40ms') topo.addLink(i1, i3, bw=4, delay='10ms') topo.addLink(i1, i4, bw=4, delay='40ms') topo.addLink(i1, i5, bw=4, delay='40ms') topo.addLink(i2, i6, bw=7, delay='7ms') topo.addLink(i3, i6, bw=7, delay='7ms') topo.addLink(i4, i6, bw=7, delay='7ms') topo.addLink(i5, i6, bw=7, delay='7ms') topo.addLink(i6, p1, bw=10) ndn = Minindn(topo=topo) ndn.start() nfds = AppManager(ndn, ndn.net.hosts, Nfd) # Setup routes to C2 # This is not functional but I'm saving this as an example for the future :) # for host1 in ndn.net.hosts: # for host2 in ndn.net.hosts: # if 'p' in host1.name and not 'p' in host2.name: # return # elif 'i' in host1.name and 'c' in host2.name: # return # else: # interface = host2.connectionsTo(host1)[0] # interface_ip = interface.IP() # Nfdc.registerRoute(host1, PREFIX, interface_ip) links = {"c1": ["i1", "i2"], "i1": ["p1"], "i2": ["p2"]} for first in links: for second in links[first]: host1 = ndn.net[first] host2 = ndn.net[second] interface = host2.connectionsTo(host1)[0] interface_ip = interface.IP() Nfdc.registerRoute(host1, PREFIX, interface_ip) interface = host2.connectionsTo(host1)[0] interface_ip = interface.IP() Nfdc.registerRoute(host1, PREFIX, interface_ip) # Run small thing before to ensure info caching, large afterwards? # print("Setup round") # getPopen(ndn.net["c1"], "ndn-traffic-client -c 5 cons_conf") # getPopen(ndn.net["p1"], "ndn-traffic-server -c 5 prod_conf") # # TODO: Traffic generator! # sleep(5) # ? # nfds["i3"].stop() # tempshark = Tshark(ndn["c1"]) # tempshark.start() # print("Round 1") # time1 = time() # getPopen(ndn.net["c1"], "ndn-traffic-client -c 20 cons_conf") # getPopen(ndn.net["p1"], "ndn-traffic-server -c 20 prod_conf") # # Wait on processes to close, end # time2 = time() # print("Time elapsed: {} s".format(time2 - time1)) MiniNDNCLI(ndn.net)
def __init__(self, props): self.props = props self.controllers = [] controllers = self.controllers self.hosts = {} hosts = self.hosts self.hosts_ip = {} hosts_ip = self.hosts_ip self.switches = {} switches = self.switches self.switches_openflow_names = {} switches_openflow_names = self.switches_openflow_names self.interfaces = {} interfaces = self.interfaces self.portmap = {} self.openflowportmap = {} self.host_connected_switch = {} self.number_of_swiches_links = 0 self.number_of_switches = 0 #switchClass = UserSwitch #switchClass = OVSSwitch self.switchClass = partial(OVSSwitch, datapath='user') topo = MNTopo() self.topo = topo if 'host' not in props or props['host'] is None: props['host'] = [] for host in props['host']: mac = None if 'mac' not in host else host['mac'] print "adding host {}".format(host['name']) hosts[host['name']] = topo.addHost(host['name'], ip=host['ip'], defaultRoute='via ' + host['gw'], mac=mac) hosts_ip[host['name']] = host['ip'].split('/')[0] if 'switch' not in props or props['switch'] is None: props['switch'] = [] self.number_of_switches = len(props['switch']) for switch in props['switch']: name = switch['name'] if 'type' not in switch: switch['type'] = 'ovs' switches[name] = switch if switch['type'] == 'ovs': print "adding switch {}".format(name) switches[name] = topo.addSwitch(name, dpid=switch['dpid'], protocols=switch['protocols']) else: print "switch {} is not OVS".format(name) switches_openflow_names[name] = "openflow:" + str( int(switch['dpid'], 16)) if 'link' not in props or props['link'] is None: props['link'] = [] # create mininet connections for link in props['link']: src_name = link['source'] dst_name = link['destination'] source = None if src_name in switches: source = switches[src_name] else: source = hosts[src_name] destination = None if dst_name in switches: destination = switches[dst_name] else: destination = hosts[dst_name] if ('type' not in source or source['type'] == 'ovs') and ( 'type' not in destination or destination['type'] == 'ovs'): print "adding link from {} to {}".format(source, destination) topo.addLink(source, destination) else: print "link from {} to {} does not connect two OVS switches".format( source, destination) if src_name in switches and dst_name in switches: self.number_of_swiches_links = self.number_of_swiches_links + 2 # save port mapping ports = {} for link in props['link']: src = link['source'] if src not in ports: ports[src] = 1 src_port = ports[src] ports[src] = ports[src] + 1 dst = link['destination'] if dst not in ports: ports[dst] = 1 dst_port = ports[dst] ports[dst] = ports[dst] + 1 if src not in self.portmap: self.portmap[src] = {} self.portmap[src][dst] = src_port if src in self.switches and dst in self.switches: self.openflowportmap[ self.switches_openflow_names[src] + ':' + str(src_port)] = self.switches_openflow_names[dst] if dst not in self.portmap: self.portmap[dst] = {} self.portmap[dst][src] = dst_port if dst in self.switches and src in self.switches: self.openflowportmap[ self.switches_openflow_names[dst] + ':' + str(dst_port)] = self.switches_openflow_names[src] # skip connections between hosts if src in self.hosts and dst in self.hosts: continue # save the connected switch by host if (src in self.hosts and dst in self.switches): self.host_connected_switch[src] = dst elif (dst in self.hosts and src in self.switches): self.host_connected_switch[dst] = src if 'controller' not in props or props['controller'] is None: props['controller'] = [{'name': 'c0', 'ip': '127.0.0.1'}] for controller in props['controller']: controllers.append( RemoteController(controller['name'], ip=controller['ip']))
import sys sys.path.append("..") # needed to import maxinet.py from parent-folder import maxinet import time from mininet.topo import Topo from maxinet import Tools from mininet.node import OVSSwitch # create topology topo = Topo() topo.addHost("h1",ip=Tools.makeIP(1), mac=Tools.makeMAC(1)) topo.addHost("h2",ip=Tools.makeIP(2), mac=Tools.makeMAC(2)) topo.addSwitch("s1",dpid=Tools.makeDPID(1)) topo.addLink("h1","s1") topo.addLink("h2","s1") # start cluster cluster = maxinet.Cluster() cluster.start() # start experiment with OVSSwitch on cluster exp = maxinet.Experiment(cluster, topo,switch=OVSSwitch) exp.setup() print "waiting 5 seconds for routing algorithms on the controller to converge" time.sleep(5)
h1 = topo.addHost('h1') h2 = topo.addHost('h2') h3 = topo.addHost('h3') h4 = topo.addHost('h4') h5 = topo.addHost('h5') h6 = topo.addHost('h6') h7 = topo.addHost('h7') # Add switches s1 = topo.addSwitch('s1') s2 = topo.addSwitch('s2') s3 = topo.addSwitch('s3') s4 = topo.addSwitch('s4') # Add links topo.addLink('h1', 's1') topo.addLink('h2', 's2') topo.addLink('h3', 's3') topo.addLink('h4', 's3') topo.addLink('h5', 's4') topo.addLink('h6', 's4') topo.addLink('h7', 's4') topo.addLink('s1', 's2') topo.addLink('s2', 's3') topo.addLink('s3', 's1') topo.addLink('s3', 's4') topo.addLink('s2', 's4') # topo.addLink("h1", "s1", bw=20.0, delay='10ms', use_htb=True) net = Mininet(topo=topo, controller=c0)
from mininet.topo import Topo from minindn.minindn import Minindn from minindn.apps.app_manager import AppManager from minindn.apps.nfd import Nfd from minindn.apps.nlsr import Nlsr from nlsr_common import getParser if __name__ == '__main__': setLogLevel('info') topo = Topo() h1 = topo.addHost('h1') h2 = topo.addHost('h2') topo.addLink(h1, h2, delay='10ms') ndn = Minindn(parser=getParser(), topo=topo) args = ndn.args ndn.start() nfds = AppManager(ndn, ndn.net.hosts, Nfd) nlsrs = AppManager(ndn, [], Nlsr) host1 = ndn.net.hosts[0] nlsrs.startOnNode(host1, security=args.security, faceType=args.faceType, nFaces=args.faces, routingType=args.routingType)
def generateTraffic(net): print("Traffic generation :") net.pingAll() print("\n") if __name__ == "__main__": topo = Topo() ##------SUBNET 1 s1 = topo.addSwitch("s1") webServTarg = topo.addHost("wst") tg1 = topo.addHost("tg1") tg2 = topo.addHost("tg2") topo.addLink(webServTarg, s1) topo.addLink(tg1, s1) topo.addLink(tg2, s1) ##------SUBNET 2 s2 = topo.addSwitch("s2") webCli1 = topo.addHost("wc1") webCli2 = topo.addHost("wc2") dosLaunch = topo.addHost("dosL") topo.addLink(s2, webCli1) topo.addLink(s2, webCli2) topo.addLink(s2, dosLaunch) ##--------Switch to Switch topo.addLink(s2, s1)
print('[{}] {} ======'.format(node_name, command)) node.cmd(command) print('[{}] complete, ret:'.format(node_name)) #print ret topo = Topo() d1 = topo.addHost("d1", cls=Docker, ip="10.0.0.251", dimage="kumokay/ubuntu14:latest") d2 = topo.addHost("d2", cls=Docker, ip="10.0.0.252", dimage="kumokay/ubuntu14:latest") s1 = topo.addSwitch("s1") s2 = topo.addSwitch("s2") topo.addLink(d1, s1, cls=TCLink, delay='20ms') topo.addLink(s1, s2) topo.addLink(d2, s2, cls=TCLink, delay='20ms') cluster = maxinet.Cluster() exp = maxinet.Experiment(cluster, topo, switch=OVSSwitch) exp.setup() try: print(exp.get_node("d1").cmd("ifconfig")) print(exp.get_node("d2").cmd("ifconfig")) print('waiting 5 seconds for routing algorithms on the controller to converge') time.sleep(5) #print exp.get_node("d1").cmd("ping -c 5 10.0.0.252")
No exemplo de código 2. criamos uma rede um pouco mais complicada com dois switches e três hosts. Além disso, aproveitamos uma classe especial de links Mininet chamada "TCLink". Esta classe usa as capacidades de controle de tráfego do Linux para nos permitir especificar um limite de banda e atraso para cada link. Isso nos permitirá obter ainda mais informações sobre caminhos em nossas redes emuladas usando ping e iperf. Se você usou o Mininet um pouco, uma coisa que você não gostaria sobre o Exemplo de Código 1 é que você não obtém a CLI do Mininet agradável que facilita picar e testar sua rede. No Exemplo de Código 2 na linha 18, trazemos a linda CLI Mininet. Enquanto você pode inserir o Exemplo de Código 2 linha a linha em um shell python, você pode, mais facilmente, executá-lo na VM Mininet com o comando sudo python Codigo2.py em uma janela de terminal. from mininet.net import Mininet from mininet.topo import Topo from mininet.link import TCLink # So we can rate limit links from mininet.cli import CLI # So we can bring up the Mininet CLI topo = Topo() # Create an empty topology topo.addSwitch("s1") # Add switches and hosts to the topology topo.addSwitch("s2") topo.addHost("h1") topo.addHost("h2") topo.addHost("h3") # Wire the switches and hosts together, links now have bandwidth and delay limits topo.addLink("h1", "s1", bw=20.0, delay='10ms', use_htb=True) topo.addLink("h2", "s1", bw=25.0, delay='10ms', use_htb=True) topo.addLink("s1", "s2", bw=11.0, delay='40ms', use_htb=True) topo.addLink("h3", "s2", bw=15.0, delay='7ms', use_htb=True) net = Mininet(topo=topo, link=TCLink) net.start() CLI(net) # Bring up the mininet CLI net.stop()
s3 = topo.addSwitch("s3") s4 = topo.addSwitch("s4") s5 = topo.addSwitch("s5") s6 = topo.addSwitch("s6") s7 = topo.addSwitch("s7") s8 = topo.addSwitch("s8") s9 = topo.addSwitch("s9") s10 = topo.addSwitch("s10") s11 = topo.addSwitch("s11") # Add Link # Edge topo.addLink(h1, s7, bw=100) topo.addLink(h2, s7, bw=100) topo.addLink(h3, s8, bw=100) topo.addLink(h4, s8, bw=100) topo.addLink(h5, s9, bw=100) topo.addLink(h6, s9, bw=100) topo.addLink(h7, s10, bw=100) topo.addLink(h8, s10, bw=100) # Aggregation topo.addLink(s7, s3, bw=100) topo.addLink(s7, s4, bw=100) topo.addLink(s8, s3, bw=100) topo.addLink(s8, s4, bw=100)
def to_mininet(topology, switches=None, hosts=None): """Convert an FNSS topology to Mininet Topo object that can be used to deploy a Mininet network. If the links of the topology are labeled with delays, capacities or buffer sizes, the returned Mininet topology will also include those parameters. However, it should be noticed that buffer sizes are included in the converted topology only if they are expressed in packets. If buffer sizes are expressed in the form of bytes they will be discarded. This is because Mininet only supports buffer sizes expressed in packets. Parameters ---------- topology : Topology, DirectedTopology or DatacenterTopology An FNSS Topology object switches : list, optional List of topology nodes acting as switches hosts : list, optional List of topology nodes acting as hosts Returns ------- topology : Mininet Topo A Mininet topology object Notes ----- It is not necessary to provide a list of switch and host nodes if the topology object provided are already annotated with a type attribute that can have values *host* or *switch*. This is the case of datacenter topologies generated with FNSS which already include information about which nodes are hosts and which are switches. If switches and hosts are passed as arguments, then the hosts and switches sets must be disjoint and their union must coincide to the set of all topology nodes. In other words, there cannot be nodes labeled as both *host* and *switch* and there cannot be nodes that are neither a *host* nor a *switch*. """ try: from mininet.topo import Topo except ImportError: raise ImportError('Cannot import mininet.topo package. ' 'Make sure Mininet is installed on this machine.') if hosts is None: hosts = (v for v in topology.nodes_iter() if 'host' in topology.node[v]['type']) if switches is None: switches = (v for v in topology.nodes_iter() if 'switch' in topology.node[v]['type']) nodes = set(topology.nodes_iter()) switches = set(switches) hosts = set(hosts) if not switches.isdisjoint(hosts): raise ValueError('Some nodes are labeled as both host and switch. ' 'Switches and hosts node lists must be disjoint') if not nodes == switches.union(hosts): raise ValueError('Some nodes are not labeled as either host or switch ' 'or some nodes listed as switches or hosts do not ' 'belong to the topology') topo = Topo() for v in switches: topo.addSwitch(str(v)) for v in hosts: topo.addHost(str(v)) delay_unit = topology.graph['delay_unit'] \ if 'delay_unit' in topology.graph else None capacity_unit = topology.graph['capacity_unit'] \ if 'capacity_unit' in topology.graph else None buffer_unit = topology.graph['buffer_unit'] \ if 'buffer_unit' in topology.graph else None if capacity_unit is not None: capacity_conversion = float(capacity_units[capacity_unit]) \ / capacity_units['Mbps'] if delay_unit is not None: delay_conversion = float(time_units[delay_unit]) \ / time_units['us'] for u, v in topology.edges_iter(): params = {} if 'capacity' in topology.edge[u][v] and capacity_unit is not None: params['bw'] = topology.edge[u][v]['capacity'] * capacity_conversion # Use Token Bucket filter to implement rate limit params['use_htb'] = True if 'delay' in topology.edge[u][v] and delay_unit is not None: params['delay'] = '%sus' % str(topology.edge[u][v]['delay'] * delay_conversion) if 'buffer_size' in topology.edge[u][v] and buffer_unit == 'packets': params['max_queue_size'] = topology.edge[u][v]['buffer_size'] topo.addLink(str(u), str(v), **params) return topo
def to_mininet(topology, switches=None, hosts=None, relabel_nodes=True): """Convert an FNSS topology to Mininet Topo object that can be used to deploy a Mininet network. If the links of the topology are labeled with delays, capacities or buffer sizes, the returned Mininet topology will also include those parameters. However, it should be noticed that buffer sizes are included in the converted topology only if they are expressed in packets. If buffer sizes are expressed in the form of bytes they will be discarded. This is because Mininet only supports buffer sizes expressed in packets. Parameters ---------- topology : Topology, DirectedTopology or DatacenterTopology An FNSS Topology object switches : list, optional List of topology nodes acting as switches hosts : list, optional List of topology nodes acting as hosts relabel_nodes : bool, optional If *True*, rename node labels according to `Mininet conventions <https://github.com/mininet/mininet/wiki/Introduction-to-Mininet#naming-in-mininet>`_. In Mininet all node labels are strings whose values are "h1", "h2", ... if the node is a host or "s1", "s2", ... if the node is a switch. Returns ------- topology : Mininet Topo A Mininet topology object Notes ----- It is not necessary to provide a list of switch and host nodes if the topology object provided are already annotated with a type attribute that can have values *host* or *switch*. This is the case of datacenter topologies generated with FNSS which already include information about which nodes are hosts and which are switches. If switches and hosts are passed as arguments, then the hosts and switches sets must be disjoint and their union must coincide to the set of all topology nodes. In other words, there cannot be nodes labeled as both *host* and *switch* and there cannot be nodes that are neither a *host* nor a *switch*. It is important to point out that if the topology contains loops, it will not work with the *ovs-controller* and *controller* provided by Mininet. It will be necessary to use custom controllers. Further info `here <https://github.com/mininet/mininet/wiki/Introduction-to-Mininet#multipath-routing>`_. """ try: from mininet.topo import Topo except ImportError: raise ImportError('Cannot import mininet.topo package. ' 'Make sure Mininet is installed on this machine.') if hosts is None: hosts = (v for v in topology.nodes() if 'host' in topology.node[v]['type']) if switches is None: switches = (v for v in topology.nodes() if 'switch' in topology.node[v]['type']) nodes = set(topology.nodes()) switches = set(switches) hosts = set(hosts) if not switches.isdisjoint(hosts): raise ValueError('Some nodes are labeled as both host and switch. ' 'Switches and hosts node lists must be disjoint') if nodes != switches.union(hosts): raise ValueError('Some nodes are not labeled as either host or switch ' 'or some nodes listed as switches or hosts do not ' 'belong to the topology') if relabel_nodes: hosts = sorted(hosts) switches = sorted(switches) mapping = dict([(hosts[i], "h%s" % str(i + 1)) for i in range(len(hosts))] + [(switches[i], "s%s" % str(i + 1)) for i in range(len(switches))]) hosts = set(mapping[v] for v in hosts) switches = set(mapping[v] for v in switches) nodes = hosts.union(switches) topology = nx.relabel_nodes(topology, mapping, copy=True) topo = Topo() for v in switches: topo.addSwitch(str(v)) for v in hosts: topo.addHost(str(v)) delay_unit = topology.graph.get('delay_unit', None) capacity_unit = topology.graph.get('capacity_unit', None) buffer_unit = topology.graph.get('buffer_unit', None) if capacity_unit: capacity_conversion = float(capacity_units[capacity_unit]) \ / capacity_units['Mbps'] if delay_unit: delay_conversion = float(time_units[delay_unit]) / time_units['us'] for u, v in topology.edges(): params = {} if 'capacity' in topology.adj[u][v] and capacity_unit: params['bw'] = topology.adj[u][v]['capacity'] * capacity_conversion # Use Token Bucket filter to implement rate limit params['use_htb'] = True if 'delay' in topology.adj[u][v] and delay_unit: params['delay'] = '%sus' % str( topology.adj[u][v]['delay'] * delay_conversion) if 'buffer_size' in topology.adj[u][v] and buffer_unit == 'packets': params['max_queue_size'] = topology.adj[u][v]['buffer_size'] topo.addLink(str(u), str(v), **params) return topo
class MininetWrapper(object): def __init__(self): self.mininet_client = None self.topology = [] self.delay = None def set_delay(self, delay): delay = str(int(delay)) + 'ms' self.delay = delay def run_mininet(self, topology_string): """ Create and run multiple link network """ self.topo_client = Topo() hosts = set() switches = set() relations = re.sub(r's', '', topology_string) relations = [ i.split(':') for i in relations.split(',') if 'h' not in i ] relations = [[int(y) - 1 for y in x] for x in relations] builtin.log(relations, 'DEBUG') verticles_count = len(set(list(itertools.chain(*relations)))) builtin.log(self.topology, 'DEBUG') for i in xrange(verticles_count): temp = [] for j in xrange(verticles_count): temp.append(-1) self.topology.append(temp[:]) builtin.log(self.topology, 'DEBUG') for i in relations: self.topology[i[0]][i[1]] = 1 self.topology[i[1]][i[0]] = 1 builtin.log(self.topology, 'DEBUG') for v1, v2 in [x.split(':') for x in str(topology_string).split(',')]: if 'h' in v1 and v1 not in hosts: self.topo_client.addHost(v1) hosts.add(v1) if 'h' in v2 and v2 not in hosts: self.topo_client.addHost(v2) hosts.add(v2) if 's' in v1 and v1 not in switches: self.topo_client.addSwitch(v1) switches.add(v1) if 's' in v2 and v2 not in switches: self.topo_client.addSwitch(v2) switches.add(v2) if self.delay: self.topo_client.addLink(v1, v2, delay=self.delay) else: self.topo_client.addLink(v1, v2) self.mininet_client = Mininet(switch=user_switch, controller=remote_controller, topo=self.topo_client, link=TCLink) self.mininet_client.start() builtin.log('Links info:') for link in self.topo_client.links(withKeys=True, withInfo=True): builtin.log(link) # self.mininet_client.waitConnected(timeout=20) sleep(20) def stop_mininet(self): if self.mininet_client is not None: self.mininet_client.stop() if self.topology: self.topology = [] self.delay = None cleanup() sleep(20) def kill_link(self, host1, host2): host1, host2 = str(host1), str(host2) self.mininet_client.configLinkStatus(host1, host2, 'down') if 'h' not in host1 and 'h' not in host2: num_1 = int(host1[1:]) - 1 num_2 = int(host2[1:]) - 1 self.topology[num_1][num_2] = -1 self.topology[num_2][num_1] = -1 builtin.log(self.topology, 'DEBUG') builtin.log('Down link {0} - {1}'.format(host1, host2), 'DEBUG') def check_link(self, host1, host2): switch = self.mininet_client.getNodeByName(host1) connections = switch.connectionsTo(host2) if connections: return True else: return False def up_link(self, host1, host2): host1, host2 = str(host1), str(host2) self.mininet_client.configLinkStatus(host1, host2, 'up') if 'h' not in host1 and 'h' not in host2: num_1 = int(host1[1:]) - 1 num_2 = int(host2[1:]) - 1 self.topology[num_1][num_2] = 1 self.topology[num_2][num_1] = 1 builtin.log(self.topology, 'DEBUG') builtin.log('Up link {0} - {1}'.format(host1, host2), 'DEBUG') def stop_node(self, name): node = self.mininet_client.getNodeByName(name) node.stop() num_node = int(name[1:]) - 1 self.topology[num_node][num_node] = -1 builtin.log('Node {0} was stoped'.format(name), 'DEBUG') def check_connected_node(self, name): switch = self.mininet_client.getNodeByName(name) return switch.connected() # NOTE(msenin) unstable method - after stoping mininet cant start node # mininet doesn't return exception def start_node(self, name): node = self.mininet_client.getNodeByName(name) # TODO (msenin) add option controller_name controllers = self.mininet_client.controllers builtin.log('Controllers: {0}'.format(controllers), 'DEBUG') node.start([controllers[0]]) def check_rules(self): switches = self.mininet_client.switches results = [] regex = (r'(cookie=[\w\d]+),|(dl_dst=[\w\d:\/]{35})' '|(priority=[\d]+),|(dl_src=[\w\d:\/]{17})') for switch in switches: ans = switch.dpctl('dump-flows -O OpenFlow13') builtin.log( 'Rules on the switch {0}: {1}'.format(switch.name, ans), 'DEBUG') ans_with_regex = "" for m in re.finditer(regex, ans): for i in xrange(1, 5): if m.group(i): ans_with_regex = ans_with_regex + ', ' + m.group(i) builtin.log('Rules with regex {0}: {1}'.format(switch.name, ans), 'DEBUG') results.append({switch.name: ans_with_regex}) return results def compare_dumped_flows(self, rules1, rules2): rules_1 = str(rules1) rules_2 = str(rules2) builtin.log('Compare two flow tables(without changing parts): ', 'DEBUG') builtin.log(rules_1, 'DEBUG') builtin.log(rules_2, 'DEBUG') if rules_1 != rules_2: return False return True def ping(self, name1, name2): node1 = self.mininet_client.getNodeByName(name1) node2 = self.mininet_client.getNodeByName(name2) ping = self.mininet_client.ping(hosts=[node1, node2], timeout=10) num1, num2 = name1[1:], name2[1:] cmd1 = node1.cmd('ifconfig') builtin.log('{0}'.format(cmd1), 'DEBUG') cmd1 = node1.cmd('ping -d -c 5 -w 5 10.0.0.' + num2) builtin.log('{0}'.format(cmd1), 'DEBUG') cmd2 = node2.cmd('ifconfig') builtin.log('{0}'.format(cmd2), 'DEBUG') cmd1 = node2.cmd('ping -d -c 5 -w 5 10.0.0.' + num1) builtin.log('{0}'.format(cmd1), 'DEBUG') return int(ping) def check_route_state(self, route): # TODO (msenin) delete method after tests refactoring """Check the state of route :param route: list with verticles (each verticle is switch id) """ route = map(lambda x: int(x) - 1, route) for i in xrange(1, len(route)): prev = route[i - 1] cur = route[i] if (self.topology[prev][prev] == -1 or self.topology[cur][cur] == -1): return False if self.topology[prev][cur] == -1: return False return True def contains_route_in_routes(self, route, routes): builtin.log("route: {0}".format(route), 'DEBUG') builtin.log("routes: {0}".format(routes), 'DEBUG') route = map(lambda x: int(x), route) for i in routes: if i.get('route') and map(lambda x: int(x), i['route']) == route: return True return False def parse_tree(self, resp): """Define and check the routes and links :param resp:json from response """ builtin.log("JSON for parsing: {0}".format(resp), 'DEBUG') source_node_list = set() destination_node_list = set() links_dict = collections.OrderedDict() routes = [] states_dict = dict() route_container = resp.get('route-container') route_list = route_container.get('route-list') route_list_length = len(route_list) # TODO for i in range(0, route_list_length): needed_leaf = i route_leaf = route_list[needed_leaf] leaf_source = route_leaf.get('source') leaf_destination = route_leaf.get('destination') states_dict['source'] = leaf_source states_dict['destination'] = leaf_destination route = route_leaf.get('route', []) for i in range(0, len(route)): route_state = dict() vertexes = set() path = route[i] state = path.get('state') route_state['state'] = state route_state['route'] = vertexes routes.append(route_state) states_dict['routes'] = routes links = path.get('path') links_count = len(links) for j in range(0, links_count): link = links[j] link_source = link.get('source') link_destination = link.get('destination') source_node = link_source.get('source-node') destination_node = link_destination.get('dest-node') source_flow = source_node.split(':')[-1] destination_flow = destination_node.split(':')[-1] vertexes.add(source_flow) vertexes.add(destination_flow) source_node_list.add(source_node) destination_node_list.add(destination_node) links_dict[source_node] = destination_node return states_dict def parse_tree_2(self, resp): """Parse output json from ncn restconfig :param resp:json from response [{'state': 'up', 'destination': '4', 'route': ['1', '4'], 'source': '1', 'id': 100}, .................................................................... {'destination': '3', 'source': '1'}, {'destination': '7', 'source': '1'}] """ builtin.log("JSON for parsing: {0}".format(resp), 'DEBUG') routes = [] route_list = resp.get('route-container').get('route-list') for routes_between_switches in route_list: routes_rest_conf = routes_between_switches.get("route") if routes_rest_conf: # NOTE (msenin) # format of fields 'source' and 'destination': openflow:4 for route_rest in routes_rest_conf: route = {} route['source'] = int(route_rest['source'][9:]) route['destination'] = \ int(route_rest['destination'][9:]) route['state'] = route_rest['state'] pathes = route_rest.get('path') route['id'] = route_rest.get('id') path = [] for link in pathes: link_source = link.get('source') link_destination = link.get('destination') source_node = link_source.get('source-node') destination_node = link_destination.get('dest-node') source_flow = int(source_node[9:]) destination_flow = int(destination_node[9:]) if source_flow not in path: path.append(source_flow) if destination_flow not in path: path.append(destination_flow) route['route'] = path routes.append(route) else: route = {} route['source'] = int(routes_between_switches['source'][9:]) route['destination'] = \ int(routes_between_switches['destination'][9:]) routes.append(route) return routes def check_route_state_by_DOM_tree(self, route, tree): """ return 1 if route up, -1 down and 0 if unexist """ if isinstance(route, str) or isinstance(route, unicode): route = list(route[1:-1].split(',')) route = map(lambda x: int(x), route) builtin.log("route: {0}".format(route), 'DEBUG') tree = self.parse_tree_2(tree) builtin.log("tree: {0}".format(tree), 'DEBUG') filtered_tree = filter(lambda x: x.get('route') == route, tree) if filtered_tree: if filtered_tree[0]['state'] == 'up': return 1 else: return -1 else: return 0 def filter_DOM_tree_by_field(self, condition, tree): # TODO (msenin) add logger tree = self.parse_tree_2(tree) filtered_tree = filter(lambda field: eval(condition), tree) return filtered_tree
def start(self): # ensure all path exists for name in self.switches: switch = self.switches[name] p4src = switch['p4src'] sw_path = switch['sw_path'] compiler = switch['compiler'] cli = switch['cli'] commands = switch['commands'] # ensure all paths exit if p4src is None: raise ValueError( "p4 source file for switch {} not provided".format(name)) if not os.path.isfile(p4src): raise ValueError( "p4 source file {} for switch {} not found".format( p4src, name)) if not which(cli): raise ValueError( "cli command {} for switch {} not found".format(cli, name)) if commands is not None and not os.path.isfile(commands): raise ValueError( "commands file {} for switch {} not found ".format( commands, name)) if not which(sw_path): raise ValueError( "switch path {} for switch {} not found ".format( sw_path, name)) if p4src not in self.p4_src_json: print "compiling source {}".format(p4src) cmd = [switch['compiler'], p4src, "--json", switch['p4json']] print ' '.join(cmd) self.p4_src_json[p4src] = switch['p4json'] try: output = subprocess.check_output(cmd) print output except subprocess.CalledProcessError as e: print e print e.output raise e # create repo topo = Topo() for name in self.hosts: host = self.hosts[name] default_route = None if host['gw'] is not None: default_route = 'via ' + host['gw'] topo.addHost(name, ip=host['ip'], mac=host['mac'], defaultRoute=default_route) for name in self.switches: switch = self.switches[name] topo.addSwitch(name, sw_path=switch['sw_path'], json_path=switch['p4json'], thrift_port=switch['port'], verbose=switch['verbose'], pcap_dump=switch['dump'], device_id=int(switch['id'])) for link in self.links: topo.addLink(link['source'], link['destination']) net = Mininet(topo=topo, host=P4Host, switch=P4Switch, controller=None) net.start() # execute host command parameters for name in self.hosts: host = self.hosts[name] # p4_mininet P4Host rename the interface to eth0 # see: self.defaultIntf().rename("eth0") on P4Host # The host lost the gw after the interface is renamed # so we execute following command to ensure provided # gw is configured in the host if 'gw' in host: net.get(name).cmd("route add default gw {}".format(host['gw'])) if 'command' not in host: continue for cmd in host['command']: print "host ({}) executing {}".format(name, cmd) net.get(name).cmd(cmd) # execute switch command parameters for name in self.switches: switch = self.switches[name] if switch['commands'] is None: continue cmd = [ switch['cli'], "--json", switch['p4json'], "--thrift-port", str(switch['port']) ] print ' '.join(cmd) with open(switch['commands'], "r") as f: wait_for_port(switch['port']) try: output = subprocess.check_output(cmd, stdin=f) print output except subprocess.CalledProcessError as e: print e print e.output CLI(net) net.stop()