Beispiel #1
0
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()
Beispiel #2
0
    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
Beispiel #3
0
    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 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
Beispiel #5
0
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.addSwitch('s1')
	topo.addSwitch('s2')
	topo.addSwitch('s3')
	topo.addHost("r1") #router
	topo.addHost("r2") #router
	topo.addHost("r3") #router
	#Create links
	topo.addLink('h1','s1')	
	topo.addLink('h2','s1')	
	topo.addLink('s1','r1')	
	topo.addLink('h3','s2')	
	topo.addLink('h4','s2')	
	topo.addLink('s2','r2')
	topo.addLink('h5','s3')	
	topo.addLink('h6','s3')	
	topo.addLink('s3','r3')
	topo.addLink('r1','r2')
	topo.addLink('r1','r3')
	topo.addLink('r2','r3')
	return topo
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_new_topology(topology_vector):
    # vector is constructed as:
    # there are n switches (s[0], ..., s[n-1]), where n is the length of topology_vector.
    # the  ith  switch s[i-1] is connected to topology_vector[i-1] end-hosts (h[i-1][0], ..., h[i-1][topology[i-1]-1]).
    newTopo = Topo()
    if topology_vector:  # Verifies there are values in topology_vector before doing any work.
        for ind, switch in enumerate(topology_vector):
            if ind == 0:  # Creates 1st switch of the network.
                newSwitch = 's' + str(ind)
                newTopo.addSwitch(newSwitch)
                i = 0
                while i < int(
                        switch
                ):  # Creates hosts & links to switch per topology_vector value.
                    newHost = 'h' + str(ind) + str(i)
                    newTopo.addHost(newHost)
                    newTopo.addLink(newSwitch, newHost)
                    i += 1
            else:
                newSwitch = 's' + str(ind)
                prevSwitch = 's' + str(ind - 1)
                newTopo.addSwitch(newSwitch)
                newTopo.addLink(newSwitch, prevSwitch)
                i = 0
                while i < int(switch):
                    newHost = 'h' + str(ind) + str(i)
                    newTopo.addHost(newHost)
                    newTopo.addLink(newSwitch, newHost)
                    i += 1

    return newTopo
Beispiel #8
0
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 test_path_rules(self):
        topo = Topo()
        topo.addHost("h1", mac="00:00:00:00:00:01", ip="10.0.0.1/24")
        topo.addHost("h2", mac="00:00:00:00:00:02", ip="10.0.0.2/24")
        topo.addSwitch("s1")
        topo.addSwitch("s2")
        topo.addLink("h1", "s1", bw=10, port1=1, port2=3)
        topo.addLink("s1", "s2", bw=10, port1=2, port2=5)
        topo.addLink("s2", "h2", bw=20, port1=8, port2=10)
        expected_s1_paths = [{
            'src_ip': '10.0.0.1',
            'src_mac': '00:00:00:00:00:01',
            'dst_ip': '10.0.0.2',
            'dst_mac': '00:00:00:00:00:02',
            'out_port': '2'
        }, {
            'src_ip': '10.0.0.2',
            'src_mac': '00:00:00:00:00:02',
            'dst_ip': '10.0.0.1',
            'dst_mac': '00:00:00:00:00:01',
            'out_port': '3'
        }]

        expected_s2_paths = [{
            'src_ip': '10.0.0.1',
            'src_mac': '00:00:00:00:00:01',
            'dst_ip': '10.0.0.2',
            'dst_mac': '00:00:00:00:00:02',
            'out_port': '8'
        }, {
            'src_ip': '10.0.0.2',
            'src_mac': '00:00:00:00:00:02',
            'dst_ip': '10.0.0.1',
            'dst_mac': '00:00:00:00:00:01',
            'out_port': '5'
        }]

        net = Mininet(topo=topo, controller=None, build=True)
        result = GraphConverted.from_mininet(net=net)
        paths = result.path_rules(["h1", "s1", "s2", "h2"])
        s1, s2 = paths["s1"], paths["s2"]
        net.stop()
        for i in s1:
            if i["src_ip"] == '10.0.0.1':
                if i['out_port'] != "2":
                    self.assertTrue(False)
            if i["src_ip"] == '10.0.0.2':
                if i['out_port'] != "3":
                    self.assertTrue(False)

        for i in s2:
            if i["src_ip"] == '10.0.0.1':
                if i['out_port'] != "8":
                    self.assertTrue(False)
            if i["src_ip"] == '10.0.0.2':
                if i['out_port'] != "5":
                    self.assertTrue(False)

        self.assertTrue(True)
 def test_find_min_path(self):
     topo = Topo()
     topo.addHost("h1")
     topo.addHost("h2")
     topo.addSwitch("s1")
     topo.addLink("h1", "s1", bw=10)
     topo.addLink("h2", "s1", bw=20)
     net = Mininet(topo=topo, controller=None, build=True)
     result = GraphConverted.from_mininet(net=net)
     net.stop()
     expected = ['h1', 's1', 'h2']
     self.assertEqual(expected, result.find_min_path("h1", "h2"))
 def test_from_mininet_topo_1(self):
     topo = Topo()
     topo.addHost("h1")
     topo.addHost("h2")
     topo.addSwitch("s1")
     topo.addLink("h1", "s1")
     topo.addLink("h2", "s1")
     net = Mininet(topo=topo, controller=None, build=True)
     result = GraphConverted.from_mininet(net=net)
     result = result.getNetwork()
     g_edges = result.edges.data()
     net.stop()
     self.assertEqual(2, len(g_edges))
Beispiel #12
0
    def processTopo(topoFile):
        config = configparser.ConfigParser(delimiters=' ', allow_no_value=True)
        config.read(topoFile)
        topo = Topo()

        items = config.items('nodes')
        coordinates = []

        for item in items:
            name = item[0].split(':')[0]
            params = {}
            if item[1]:
                if all (x in item[1] for x in ['radius', 'angle']) and item[1] in coordinates:
                    error("FATAL: Duplicate Coordinate, \'{}\' used by multiple nodes\n" \
                        .format(item[1]))
                    sys.exit(1)
                coordinates.append(item[1])

                for param in item[1].split(' '):
                    if param == '_':
                        continue
                    params[param.split('=')[0]] = param.split('=')[1]

            topo.addHost(name, params=params)

        try:
            items = config.items('switches')
            for item in items:
                name = item[0].split(':')[0]
                topo.addSwitch(name)
        except configparser.NoSectionError:
            # Switches are optional
            pass

        items = config.items('links')
        for item in items:
            link = item[0].split(':')

            params = {}
            for param in item[1].split(' '):
                key = param.split('=')[0]
                value = param.split('=')[1]
                if key in ['bw', 'jitter', 'max_queue_size']:
                    value = int(value)
                if key == 'loss':
                    value = float(value)
                params[key] = value

            topo.addLink(link[0], link[1], **params)

        return topo
Beispiel #13
0
def createNet(args):
    topo=Topo()

    h1 = topo.addHost("h1",ip='10.0.1.1/24')
    s1 = topo.addSwitch("s1")
    pep = topo.addHost("pep",ip='10.0.1.90/24')
    s2 = topo.addSwitch("s2")
    h2 = topo.addHost("h2",ip='10.0.2.1/24')

    topo.addLink(h1,s1,cls=TCLink,  bw=args.bw, delay= str((args.rttTotal-args.rttSat)/4)+"ms",loss=0)
    topo.addLink(s1,pep,cls=TCLink, bw=args.bw, delay= str((args.rttTotal-args.rttSat)/4)+"ms",loss=0)
    topo.addLink(pep,s2,cls=TCLink, bw=args.bw, delay= str(args.rttSat/4)+"ms",loss=0)
    topo.addLink(s2,h2,cls=TCLink,  bw=args.bw, delay= str(args.rttSat/4)+"ms",loss=args.loss)

    return Mininet(topo)
Beispiel #14
0
def hello_world():
    topo = Topo()
    topo.addHost("h1", cls=Docker, ip="10.0.0.251", dimage="ubuntu:trusty")
    topo.addHost("h2", cls=Docker, ip="10.0.0.252", dimage="ubuntu:trusty")
    topo.addSwitch("s1", dpid=Tools.makeDPID(1))
    topo.addLink("h1", "s1")
    topo.addLink("h2", "s1")

    # start cluster
    cluster = maxinet.Cluster(minWorkers=1, maxWorkers=2)

    # start experiment with OVSSwitch on cluster
    exp = maxinet.Experiment(cluster, topo, switch=OVSSwitch)
    exp.setup()
    return 'Welcome to our Library!'
 def test_update_path_weights(self):
     topo = Topo()
     topo.addHost("h1")
     topo.addHost("h2")
     topo.addSwitch("s1")
     topo.addLink("h1", "s1", bw=10)
     topo.addLink("h2", "s1", bw=20)
     net = Mininet(topo=topo, controller=None, build=True)
     result = GraphConverted.from_mininet(net=net)
     result.update_path_weights(["h1", "s1", "h2"], weight=5)
     result = result.getSupport()
     g_edges = result.edges.data('weight', default=1)
     sum_weigths = sum([edge[2] for edge in g_edges])
     net.stop()
     self.assertEqual(12, sum_weigths)
 def test_from_mininet_topo(self):
     topo = Topo()
     topo.addHost("h1")
     topo.addHost("h2")
     topo.addSwitch("s1")
     topo.addLink("h1", "s1", bw=10)
     topo.addLink("h2", "s1", bw=20)
     net = Mininet(topo=topo, controller=None, build=True)
     weigths = sorted([0, 0])
     result = GraphConverted.from_mininet(net=net)
     result = result.getTotalBwNetwork()
     g_edges = result.edges.data('weight', default=1)
     g_weigths = sorted([edge[2] for edge in g_edges])
     net.stop()
     self.assertEqual(weigths, g_weigths)
class MininetTopology(object):
    def __init__(self, topology):
        self.topology = topology
        self.mininet_topology = Topo()

        self.add_hosts()
        self.add_switches()
        self.add_links()

        self.mininet = Mininet(topo=self.mininet_topology,
                               switch=partial(OVSSwitch, datapath='user'),
                               controller=None)
        self.add_controllers()
        self.add_interfaces()

    def add_hosts(self):
        for host in self.topology.hosts:
            mac = None if 'mac' not in host else host['mac']
            self.mininet_topology.addHost(host['name'], ip=host['ip'], defaultRoute='via ' + host['gw'], mac=mac)

    def add_switches(self):
        for switch in self.topology.switches:
            if 'type' not in switch or switch['type'] == 'ovs':
                self.mininet_topology.addSwitch(switch['name'], dpid=switch['dpid'], protocols=switch['protocol'])

    def add_links(self):
        for link in self.topology.links:
            if link['source'] in self.mininet_topology.nodes() \
                    and link['destination'] in self.mininet_topology.nodes():
                self.mininet_topology.addLink(link['source'], link['destination'])

    def add_controllers(self):
        for controller in self.topology.controllers:
            self.mininet.addController(RemoteController(controller['name'], ip=controller['ip']))

    def add_interfaces(self):
        for interface in self.topology.interfaces:
            Intf(interface['name'], node=self.mininet.nameToNode[interface['switch']])

    def start(self):
        self.mininet.start()

    def cli(self):
        CLI(self.mininet)

    def stop(self):
        self.mininet.stop()
        cleanup()
def test_mininet_conversion_to_logical():
    """Test the conversion from a mininet logical network to a logical one."""

    import networkx as nx
    from distriopt import VirtualNetwork
    from mininet.topo import Topo

    virt_topo_mn = Topo()

    # Add nodes
    u = virt_topo_mn.addHost("u", cores=2, memory=1000)
    v = virt_topo_mn.addHost("v", cores=2, memory=1000)
    z = virt_topo_mn.addSwitch("z", cores=2, memory=1000)
    # Add links
    virt_topo_mn.addLink(u, v, rate=1000)
    virt_topo_mn.addLink(v, z, rate=1000)
    virt_topo_mn.addLink(u, z, rate=1000)

    virtual_topo = VirtualNetwork.from_mininet(virt_topo_mn)

    assert virtual_topo.number_of_nodes() == 3
    assert len(virtual_topo.edges()) == 3
    assert nx.is_connected(virtual_topo.g)

    for node in virtual_topo.nodes():
        assert virtual_topo.req_cores(node) == 2
        assert virtual_topo.req_memory(node) == 1000
    for i, j in virtual_topo.edges():
        assert virtual_topo.req_rate(i, j) == 1000
def test_mininet_conversion_to_physical():
    """Test the conversion from a mininet physical network to a PhysicalNetwork one."""

    import networkx as nx
    from distriopt.embedding import PhysicalNetwork
    from mininet.topo import Topo

    phy_topo_mn = Topo()

    # Add nodes
    master1 = phy_topo_mn.addHost("Master1", cores=2, memory=1000)
    node1 = phy_topo_mn.addHost("Node1", cores=2, memory=1000)
    sw = phy_topo_mn.addSwitch("SW")
    # Add links
    phy_topo_mn.addLink(master1, sw, port1="eth0", port2="eth0", rate=1000)
    phy_topo_mn.addLink(master1, sw, port1="eth1", port2="eth2", rate=1000)
    phy_topo_mn.addLink(node1, sw, port1="eth0", port2="eth1", rate=1000)

    phy_topo = PhysicalNetwork.from_mininet(phy_topo_mn)
    assert len(phy_topo.compute_nodes) == 2
    assert phy_topo.number_of_nodes() == 3
    assert len(phy_topo.edges()) == 3
    assert nx.is_connected(phy_topo.g)
    for node in phy_topo.compute_nodes:
        assert phy_topo.cores(node) == 2
        assert phy_topo.memory(node) == 1000
    for i, j, device in phy_topo.edges(keys=True):
        assert phy_topo.rate(i, j, device) == 1000
Beispiel #20
0
 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')
Beispiel #21
0
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 test_getports(self):
     topo = Topo()
     topo.addHost("h1")
     topo.addHost("h2")
     topo.addSwitch("s1")
     topo.addLink("h1", "s1", port1=20, port2=30)
     topo.addLink("h2", "s1", port1=10, port2=40)
     net = Mininet(topo=topo, controller=None, build=True)
     expected = {
         ('h1', 's1'): ('20', '30'),
         ('s1', 'h1'): ('30', '20'),
         ('h2', 's1'): ('10', '40'),
         ('s1', 'h2'): ('40', '10')
     }
     result = sorted(GraphConverted.getNetworkPorts(net=net).items())
     net.stop()
     self.assertEqual(sorted(expected.items()), result)
 def test_update_path_weights_1(self):
     topo = Topo()
     topo.addHost("h1")
     topo.addHost("h2")
     topo.addSwitch("s1")
     topo.addLink("h1", "s1", bw=10)
     topo.addLink("h2", "s1", bw=20)
     net = Mininet(topo=topo, controller=None, build=True)
     result = GraphConverted.from_mininet(net=net)
     try:
         result.update_path_weights(["h1"], weight=5)
     except ValueError:
         net.stop()
         self.assertTrue(True)
     else:
         net.stop()
         self.assertTrue(False)
Beispiel #24
0
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')
    topo.addLink('s1', 's3')
    topo.addLink('h1', 's2')
    topo.addLink('h2', 's2')
    topo.addLink('h3', 's3')
    topo.addLink('h4', 's3')
    return topo
Beispiel #25
0
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
Beispiel #26
0
    def processTopo(topoFile):
        config = configparser.ConfigParser(delimiters=' ')
        config.read(topoFile)
        topo = Topo()

        items = config.items('nodes')
        for item in items:
            name = item[0].split(':')[0]

            params = {}
            for param in item[1].split(' '):
                if param == '_':
                    continue
                params[param.split('=')[0]] = param.split('=')[1]

            topo.addHost(name, params=params)

        try:
            items = config.items('switches')
            for item in items:
                name = item[0].split(':')[0]
                topo.addSwitch(name)
        except configparser.NoSectionError:
            # Switches are optional
            pass

        items = config.items('links')
        for item in items:
            link = item[0].split(':')

            params = {}
            for param in item[1].split(' '):
                key = param.split('=')[0]
                value = param.split('=')[1]
                if key in ['bw', 'jitter', 'max_queue_size']:
                    value = int(value)
                if key == 'loss':
                    value = float(value)
                params[key] = value

            topo.addLink(link[0], link[1], **params)

        return topo
Beispiel #27
0
def createNet(args):
    topo = Topo()
    h1 = topo.addHost("h1", ip='10.0.1.1/24')
    s1 = topo.addSwitch("s1")
    h2 = topo.addHost("h2", ip='10.0.1.2/24')

    topo.addLink(h1, s1, cls=TCLink, bw=10, delay="10ms", loss=1)
    topo.addLink(s1, h2, cls=TCLink, bw=10, delay="10ms", loss=1)

    return Mininet(topo)
Beispiel #28
0
 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 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.addSwitch('s3')

        #Create links
        topo.addLink('s1','s2')
        topo.addLink('s1','s3')
        topo.addLink('h1','s2')
        topo.addLink('h2','s2')
        topo.addLink('h3','s3')
        topo.addLink('h4','h3')
        return topo
Beispiel #31
0
 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')
Beispiel #32
0
def createHost(Topo, host_name, host_ip, gw, m_router, m_interface,
               host_number):
    s = Topo.addSwitch('s' + str(host_number))
    Topo.addLink(s,
                 m_router,
                 intfName2=m_interface,
                 params2={'ip': host_ip + '/24'},
                 cls=TCLink)
    h = Topo.addHost(name=host_name, ip=host_ip, defaultRoute=gw)
    Topo.addLink(h, s, cls=TCLink)
    #net[r].cmd("ifconfigs"+str(host_number)+"-router "+host_ip+"/24")
    return h
Beispiel #33
0
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=1000, delay='2ms')
    topo.addLink("c1", "d2", bw=1000, delay='2ms')

    for x in range(1, 3):
        topo.addLink("d" + str(x), "a" + str(2 * x - 1), bw=100, delay='2ms')
        topo.addLink("d" + str(x), "a" + str(2 * x), bw=100, delay='2ms')

    for x in range(1, 5):
        topo.addLink("a" + str(x), "h" + str(2 * x - 1), bw=10, delay='2ms')
        topo.addLink("a" + str(x), "h" + str(2 * x), bw=10, delay='2ms')
    return topo
Beispiel #34
0
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
def create_topo(topo):
    t = Topo()

    i = 1
    for host in topo['hosts']:
        logger.debug("add host {} to topo".format(host['name']))
        t.addHost(host['name'], ip=Tools.makeIP(i), mac=Tools.makeMAC(i))
        i += 1

    i = 1
    for switch in topo['switches']:
        logger.debug("add switch {} to topo".format(switch['name']))
        t.addSwitch(switch['name'], dpid=Tools.makeDPID(i))
        i += 1

    i = 1
    for link in topo['links']:
        logger.debug("add link from {} to {} to topo".format(
            link['node1']['name'], link['node2']['name']))
        t.addLink(link['node1']['name'], link['node2']['name'])
        i += 1

    return t
Beispiel #36
0
def createNet(args):
    topo = Topo()

    h1 = topo.addHost('h1', ip='10.0.1.1/24')
    pep1 = topo.addHost('pep1', ip='10.0.1.90/24')
    sat = topo.addHost('sat', ip='10.0.3.90/24')
    pep2 = topo.addHost('pep2', ip='10.0.4.1/24')
    h2 = topo.addHost('h2', ip='10.0.2.1/24')
    s1 = topo.addSwitch('s1')
    s2 = topo.addSwitch('s2')
    s3 = topo.addSwitch('s3')
    s4 = topo.addSwitch('s4')

    topo.addLink(h1, s1)
    topo.addLink(s1, pep1)
    topo.addLink(pep1, s3)
    topo.addLink(s3, sat)
    topo.addLink(sat, s4)
    topo.addLink(s4, pep2)
    topo.addLink(pep2, s2)
    topo.addLink(s2, h2)

    return Mininet(topo)
Beispiel #37
0
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
Beispiel #38
0
def createTopo():
    topo = Topo()

    # Create switches
    for switch in ACCESS_SWITCHES + DISTRIBUTION_SWICHES + [CORE_SwITCH]:
        topo.addSwitch(switch)

    # Create hosts
    for host in HOSTS:
        topo.addHost(host)

    # Create core to distribution links
    for idx, distribution in enumerate(DISTRIBUTION_SWICHES):
        topo.addLink(distribution, CORE_SwITCH, bw=CORE_BW, delay=CORE_DELAY)

    # Create distribution to access links
    for idx, access in enumerate(ACCESS_SWITCHES):
        topo.addLink(
            access,
            DISTRIBUTION_SWICHES[idx / 2],
            bw=DISTRIBUTION_BW,
            delay=DISTRIBUTION_DELAY,
        )

    # Create access to host links
    for idx, host in enumerate(HOSTS):
        loss = BAD_LINK_LOSS if host in BAD_LINK_HOSTS else 0

        topo.addLink(
            host,
            ACCESS_SWITCHES[idx / 2],
            bw=ACCESS_BW,
            delay=ACCESS_DELAY,
            loss=loss,
        )

    return topo
Beispiel #39
0
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()
Beispiel #40
0
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()
Beispiel #41
0
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()
Beispiel #42
0
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
Beispiel #43
0
#


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)
Beispiel #44
0
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
Beispiel #45
0
# Start sshd on the emulated hosts and create a specialized host
# emulated at the Frontend which tunnels ssh from the Frontend to the
# emulated hosts.
#

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()
Beispiel #46
0
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
Beispiel #47
0
""" A small example showing the usage of Docker containers.
"""

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)
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
Beispiel #49
0
   h1 --- s1 ---------- s2 ---  h4
         /  \           / \
      h2/    \         /   \ h3
              controller


"""

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)
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