Example #1
0
                                    mac='00:00:00:00:00:0%s' %
                                    (ls * fanout + f + 1))  # ,
                # cls=IpHost,
                # gateway='10.0.%s.254' % ((ls + 1)),
                # ip='10.0.%s.%s/24' % ((ls + 1), (f + 1)))

                self.addLink(host, leafSwitch, **linkopts2)


#topos = { 'leaf_spine' : ( lambda: LeafAndSpine(2,3,2) ) }
if __name__ == '__main__':
    topo = LeafAndSpine(2, 2, 1)
    controllerIp = "128.10.135.42"
    net = Mininet(topo,
                  autoSetMacs=True,
                  xterms=False,
                  controller=RemoteController,
                  switch=OVSKernelSwitch,
                  link=TCLink)
    net.addController(
        'c', ip='128.10.135.42', port=6680
    )  # localhost:127.0.0.1 vm-to-mac:10.0.2.2 server-to-mac:128.112.93.28

    #net = Mininet(topo, link=TCLink, switch=OVSKernelSwitch)
    print "\nHosts configured with IPs, switches pointing to OpenVirteX at 128.112.93.28 port 6633\n"

    interval = 10
    net.start()
    time.sleep(4)
    net.pingAll()
    time.sleep(15)
    hosts = net.hosts
Example #2
0
def main():

    rtopo = RTopo()
    net = Mininet(topo=rtopo)

    net.start()

    r = net['r']
    IF = 'r-eth3'

    r.cmd('tc qdisc add dev ' + IF + ' root handle 1: netem delay ' +
          str(delay) + 'ms')
    r.cmd('tc qdisc add dev ' + IF + ' parent 1: handle 10: tbf rate ' + str(bw) + 'mbit' + \
                ' burst ' + str(burst) + ' limit ' + str(limit))

    h1 = net['h1']
    h2 = net['h2']
    h3 = net['h3']

    h3Log1 = expName + '-h3_1.log'
    h3Log2 = expName + '-h3_2.log'
    h1Log = expName + '-h1.log'
    h2Log = expName + '-h2.log'

    print('Starting receiver h3..')
    h3.cmd('iperf3 -s -p 5001 | tee ' + h3Log1 + ' &')
    h3.cmd('iperf3 -s -p 5002 | tee ' + h3Log2 + ' &')

    # Start RTT sampling
    proc = multiprocessing.Process(target=sampleRTT,
                                   args=([('bbr', h1),
                                          ('cubic', h2)], logFile))
    proc.start()

    print('Starting senders h1/h2..')
    h1.cmd('iperf3 -c 10.0.3.10 -t ' + str(duration) + ' -i 1 -p 5001 -C ' +
           cc1 + ' | tee ' + h1Log + ' &')
    h2.cmd('iperf3 -c 10.0.3.10 -t ' + str(duration) + ' -i 1 -p 5002 -C ' +
           cc2 + ' | tee ' + h2Log + ' &')

    time.sleep(duration + 5)
    proc.terminate()

    net.stop()

    # Process the results
    # Get h1's goodput from h3Log1; h2's goodput from h3Log2; h1's retr from h1Log; h2's retr from h2Log
    with open(h3Log1, 'r') as file:
        data = file.read()
        h1_goodput = float(data.splitlines()[-1].split()[-3])
        unit = data.splitlines()[-1].split()[-2]

    with open(h3Log2, 'r') as file:
        data = file.read()
        h2_goodput = float(data.splitlines()[-1].split()[-3])
        unit = data.splitlines()[-1].split()[-2]

    with open(h1Log, 'r') as file:
        data = file.read()
        h1_retr = data.splitlines()[-4].split()[8]

    with open(h2Log, 'r') as file:
        data = file.read()
        h2_retr = data.splitlines()[-4].split()[8]

    record = [convertSize(limit), h1_goodput, h2_goodput, h1_retr, h2_retr]
    record = ','.join(list(map(str, record)))
    print('\n' + record, file=logFile)
from mininet.net import Mininet
from mininet.topolib import TreeTopo
from mininet.node import Controller, RemoteController,OVSSwitch

import random
import threading

# Create and start mininet topology
tree_topo = TreeTopo(depth=3, fanout=2)
net = Mininet(topo=tree_topo, controller=RemoteController,switch=OVSSwitch)
net.start()

episode_count = 100
episode_length = 10
no_of_hosts = 8
victim_host_ip = '10.0.0.' + str(no_of_hosts)
spoofed_ip = '10.1.1.1'

# Command line tool hping3 is used to simulate DDoS
def ddos_flood(host):
    # Attack the last host with IP 10.0.0.4
    # timout command is used to abort the hping3 command after the attack was performed for the specifed time
    host.cmd('timeout ' + str(episode_length) + 's hping3 --flood ' + ' -a '+ spoofed_ip +' '+ victim_host_ip)
    host.cmd('killall hping3')


def ddos_benign(host):
    # Send benign packets to victim
    host.cmd('timeout ' + str(episode_length) + 's hping3 ' + victim_host_ip)
    host.cmd('killall hping3')
Example #4
0
    prompt = "Link capacity? >>  "
    capa = raw_input(prompt)
    capa = int(capa)

    bw_core_aggr = capa  # Mbps
    bw_aggr_edge = capa

    fat_topo = FatTreeTraffic(int(k))
    # topo = MyTopo()
    ip = '10.0.0.4'
    port = 6633
    c = RemoteController('c', ip=ip, port=port)
    # MobilitySwitch = partial( OVSSwitch, protocols='OpenFlow13')
    net = Mininet(topo=fat_topo,
                  autoSetMacs=True,
                  controller=None,
                  autoStaticArp=True,
                  link=TCLink)
    net.addController(c)
    net.start()

    info(
        "[Link capacitiy] core-aggr: %d Mbps, aggr-edge: %d Mbps, edge-host: %d Mbps \n"
        % (bw_core_aggr, bw_aggr_edge, bw_edge_host))
    hosts = [0]
    hosts.extend(net.hosts)

    # Add iperf3 directory to each host's $PATH
    for i in range(1, 17):
        cmd_result = hosts[i].cmd("PATH=$PATH:/home/mininet/iperf-3.7/src")
        # print(cmd_result)
Example #5
0
def dynamicTest(hps):
    num = hps.num_clients
    topo = BigTopo(num)
    net = Mininet(topo, link=TCLink)
    net.start()
    server, command = net.get('server', 'command')
    server.cmd('nohup python -u startServer.py > server_log.txt &')
    clients = []
    for i in range(num):
        client = net.get('client{}'.format(i + 1))
        off = np.random.randint(0, 50)
        if i < 6:
            print('starting {}'.format(i))
            client.cmd(
                'nohup python -u startClient.py {0} {1} > client{2}_log.txt  &'
                .format(server.IP(), off, i))
            time.sleep(1)
        clients.append(client)
    time.sleep(5)

    for i, client in enumerate(clients[:3]):

        print(client)
        output = command.cmd('python startCommander.py {0} {1}'.format(
            client.IP(), 'startNTP'))
        print("starting ntp {}".format(i + 1))
        print(output)

        time.sleep(2)

    print('second batch of NTP')
    leaving_clients = clients[:3]
    joining_clients = clients[6:]
    for i, client in enumerate(clients[3:6]):
        print(client)
        if len(leaving_clients) != 0:
            j = np.random.choice(leaving_clients, replace=False)
            print("closing client {}".format(j))
            command.cmd('python startCommander.py {0} {1} &'.format(
                j.IP(), 'close'))
            leaving_clients.remove(j)

            print("starting ntp {}".format(client))
            output2 = command.cmd('python startCommander.py {0} {1}'.format(
                client.IP(), 'startNTP'))

    times_ = getTimesMultiple(command, server, clients[:6])
    print(times_)

    if os.path.isfile('dynamic_leave'):
        times = pkl.load(open('dynamic_leave', 'rb'))
    else:
        times = []

    times.append(times_)

    pkl.dump(times, open('dynamic_leave', 'wb'))

    for i, client in enumerate(clients[3:6]):
        print(client)
        if len(joining_clients) != 0:
            j = np.random.choice(joining_clients, replace=False)
            print("joining client {}".format(j))
            off = np.random.randint(0, 50)
            j.cmd('nohup python -u startClient.py {0} {1} &'.format(
                server.IP(), off))
            print("starting ntp {}".format(client))
            output2 = command.cmd('python startCommander.py {0} {1}'.format(
                client.IP(), 'startNTP'))
            joining_clients.remove(j)
            time.sleep(2)

    times_ = getTimesMultiple(command, server, clients[:6])
    print(times_)

    if os.path.isfile('dynamic_join'):
        times = pkl.load(open('dynamic_join', 'rb'))
    else:
        times = []

    times.append(times_)

    pkl.dump(times, open('dynamic_join', 'wb'))
Example #6
0
#!/usr/bin/env python
from mininet.cli import CLI
from mininet.net import Mininet
from mininet.node import RemoteController
from mininet.term import makeTerm

if '__main__' == __name__:
    #create net with a remote controller
    net = Mininet(controller=RemoteController)
    #add controller and set the controller port
    c0 = net.addController('c0', port=6633)
    #adding switch
    s1 = net.addSwitch('s1')
    s2 = net.addSwitch('s2')
    s3 = net.addSwitch('s3')
    s4 = net.addSwitch('s4')
    s5 = net.addSwitch('s5')
    s6 = net.addSwitch('s6')
    s7 = net.addSwitch('s7')
    s8 = net.addSwitch('s8')
    s9 = net.addSwitch('s9')
    #adding hosts
    h1 = net.addHost('h1', ip='10.0.0.1/24', mac='00:00:00:00:00:01')
    h2 = net.addHost('h2', ip='10.0.0.2/24', mac='00:00:00:00:00:02')
    h3 = net.addHost('h3', ip='10.0.0.3/24', mac='00:00:00:00:00:03')
    h4 = net.addHost('h4', ip='10.0.0.4/24', mac='00:00:00:00:00:04')
    h5 = net.addHost('h5', ip='10.0.0.5/24', mac='00:00:00:00:00:05')
    h6 = net.addHost('h6', ip='10.0.0.6/24', mac='00:00:00:00:00:06')
    h7 = net.addHost('h7', ip='10.0.0.7/24', mac='00:00:00:00:00:07')
    h8 = net.addHost('h8', ip='10.0.0.8/24', mac='00:00:00:00:00:08')
    h9 = net.addHost('h9', ip='10.0.0.9/24', mac='00:00:00:00:00:09')
def Start(GI=False, MCS=2, Bandwidth=20, UDP=True, TP=20, PCAP=False):
    setLogLevel('info')
    #info( '*** ns-3 network demo\n' )
    net = Mininet()

    #info( '*** Creating Network\n' )
    h0 = net.addHost('h0')
    #h1 = net.addHost( 'h1' )
    h2 = net.addHost('h2')

    wifi = WIFISegment()

    #CONFIGURATION
    udp = UDP
    gi = GI  #0,1
    bandwidth = Bandwidth  #20,40,80
    mcs = MCS  #2,4,7

    if udp == False:
        #TCP
        payloadSize = 1448  #bytes
        ns.core.Config.SetDefault("ns3::TcpSocket::SegmentSize",
                                  ns.core.UintegerValue(payloadSize))
    else:
        payloadSize = 1472

    wifi.wifihelper.SetStandard(ns.wifi.WIFI_PHY_STANDARD_80211ac)

    # Enabling Shor guard intervals:
    wifi.phyhelper.Set("ShortGuardEnabled", ns.core.BooleanValue(gi))

    DataRate = ns.wifi.VhtWifiMacHelper.DataRateForMcs(mcs)
    #DataRate = ns.core.StringValue("VhtMcs3")

    # set datarate for node h0
    wifi.wifihelper.SetRemoteStationManager("ns3::ConstantRateWifiManager",
                                            "DataMode", DataRate,
                                            "ControlMode", DataRate)

    wifi.machelper = ns.wifi.VhtWifiMacHelper.Default()

    Sssid = "wifi-80211ac"

    wifi.addSta(h0, ssid=Sssid)

    wifi.addAp(h2, ssid=Sssid)

    # set channel bandwidth
    ns.core.Config.Set(
        "/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Phy/ChannelWidth",
        ns.core.UintegerValue(bandwidth))

    if PCAP == True:
        wifi.phyhelper.EnablePcap("80211ac_Sta1.pcap", h0.nsNode.GetDevice(0),
                                  True, True)
        #wifi.phyhelper.EnablePcap( "Ap-h1.pcap", h1.nsNode.GetDevice( 1 ), True, True );
        wifi.phyhelper.EnablePcap("80211ac_Ap.pcap", h2.nsNode.GetDevice(0),
                                  True, True)

    #info( '*** Configuring hosts\n' )
    h0.setIP('192.168.123.1/24')
    #h1.setIP('192.168.123.2/24')
    h2.setIP('192.168.123.3/24')

    mininet.ns3.start()

    #info( '\n *** Testing network connectivity\n' )
    net.pingFull([h0, h2])
    h0.cmdPrint("ping 192.168.123.3 -c 10")
    info(
        '*** Testing bandwidth between h0 and h2 while h1 is not transmitting\n'
    )
    h2.sendCmd("iperf -s -i 1 -u")
    val = "iperf -c 192.168.123.3 -u -b " + str(TP) + "M"
    h0.cmdPrint(val)
 def topology(self, Link):
     print('\nCreating Mininet network...\n')
     self.net = Mininet(host=RemoteHost,
                        link=eval(Link),
                        switch=RemoteOVSSwitch)
Example #9
0
def TreeNet(depth=1, fanout=2, **kwargs):
    "Convenience function for creating tree networks."
    topo = TreeTopo(depth, fanout)
    return Mininet(topo, **kwargs)
Example #10
0
def myNetwork():

    net = Mininet( topo=None,
                   build=False,
                   ipBase='10.0.0.0/8')

    info( '*** Adding controller\n' )
    c0=net.addController(name='c0',
                      controller=Controller,
                      protocol='tcp',
                      port=6633)

    info( '*** Add switches\n')
    s1 = net.addSwitch('s1', cls=OVSKernelSwitch)
    s2 = net.addSwitch('s2', cls=OVSKernelSwitch)
    s3 = net.addSwitch('s3', cls=OVSKernelSwitch)

    info( '*** Add hosts\n')
    h7 = net.addHost('h7', cls=Host, ip='10.0.0.7', defaultRoute=None)
    h10 = net.addHost('h10', cls=Host, ip='10.0.0.10', defaultRoute=None)
    h5 = net.addHost('h5', cls=Host, ip='10.0.0.5', defaultRoute=None)
    h4 = net.addHost('h4', cls=Host, ip='10.0.0.4', defaultRoute=None)
    h1 = net.addHost('h1', cls=Host, ip='10.0.0.1', defaultRoute=None)
    h3 = net.addHost('h3', cls=Host, ip='10.0.0.3', defaultRoute=None)
    h8 = net.addHost('h8', cls=Host, ip='10.0.0.8', defaultRoute=None)
    h6 = net.addHost('h6', cls=Host, ip='10.0.0.6', defaultRoute=None)
    h2 = net.addHost('h2', cls=Host, ip='10.0.0.2', defaultRoute=None)
    h11 = net.addHost('h11', cls=Host, ip='10.0.0.11', defaultRoute=None)
    h9 = net.addHost('h9', cls=Host, ip='10.0.0.9', defaultRoute=None)

    info( '*** Add links\n')
    net.addLink(h4, s3)
    net.addLink(h5, s3)
    net.addLink(h6, s3)
    net.addLink(s2, h11)
    net.addLink(s2, h9)
    net.addLink(s2, h8)
    net.addLink(s2, h7)
    net.addLink(s1, s2)
    net.addLink(s1, s3)
    net.addLink(s2, s3)
    net.addLink(h1, s1)
    net.addLink(h2, s1)
    net.addLink(h3, s1)
    net.addLink(h10, s1)

    info( '*** Starting network\n')
    net.build()
    info( '*** Starting controllers\n')
    for controller in net.controllers:
        controller.start()

    info( '*** Starting switches\n')
    net.get('s1').start([c0])
    net.get('s2').start([c0])
    net.get('s3').start([c0])

    info( '*** Post configure switches and hosts\n')

    CLI(net)
    net.stop()
Example #11
0
#!/usr/bin/python

'This example runs stations in AP mode'

from mininet.net import Mininet
from mininet.cli import CLI
from mininet.log import setLogLevel
from mininet.link import TCLink
import sys

net = Mininet(link=TCLink)

def topology(mobility):

	"Create a network."
	if mobility:
		sta1 = net.addStation('sta1', mac='00:00:00:00:00:01', ip='10.0.0.1/8', range='20')
	else:
		sta1 = net.addStation('sta1', mac='00:00:00:00:00:01', ip='10.0.0.1/8', range='20', position='20,60,0')
	sta2 = net.addStation('sta2', mac='00:00:00:00:00:02', ip='10.0.0.2/8', range='20', position='90,60,0')
	ap1 = net.addAPAdhoc('ap1', mac='02:00:00:00:01:00', ip='10.0.0.11/8', ssid="apadhoc-ssid", mode="g", channel="1", position='40,60,0', range='30')
	ap2 = net.addAPAdhoc('ap2', mac='02:00:00:00:02:00', ip='10.0.0.12/8', ssid="apadhoc-ssid", mode="g", channel="6", position='80,60,0', range='30')

	print "*** Configuring wifi nodes"
	net.configureWifiNodes()

	net.plotGraph(max_x=120, max_y=120)

	print "*** Adding Link"
	net.addLink(ap1, ap2)  # wired connection
Example #12
0
        #zone connnections
        self.addLink(sw1, fw1, port1 = 3, port2 = 1)
        self.addLink(sw2, fw1, port1 = 1, port2 = 2)
        self.addLink(sw2, fw2, port1 = 2, port2 = 1)
        self.addLink(fw2, napt, port1 = 2, port2 = 1)
        self.addLink(napt, sw3, port1 = 2, port2 = 3)

if __name__ == "__main__":

    ctrl = RemoteController('c0', ip = '127.0.0.1', port = 6633)
    topo = MyTopo()

    net = Mininet (
        topo = topo,
        switch = OVSSwitch,
        controller = ctrl,
        autoSetMacs = True,
        autoStaticArp = True
    )

    # add defalut gateway
    net.get("h3").cmd("ip route add default via 10.0.0.1")
    net.get("h4").cmd("ip route add default via 10.0.0.1")

    net.start()


    # #test

    pingCount = 0
    pingCorrect = 0
Example #13
0
if __name__ == '__main__':
    simple_linear_2links = GeneratedTopo()

    setLogLevel('info')

    # try to get hw intf from the command line; by default, use server1
    #intfName = sys.argv[ 1 ] if len( sys.argv ) > 1 else 'server1'
    #info( '*** Connecting to hw intf: %s' % intfName )

    #info( '*** Checking', intfName, '\n' )
    #checkIntf( intfName )

    info('*** Creating network\n')
    controller = RemoteController('c0', ip='127.0.0.1', port=6633)
    net = Mininet(simple_linear_2links, controller=controller,
                  link=TCLink)  #topo=TreeTopo( depth=1, fanout=2 ) )

    # s1 = net.switches[0]
    # _intf_linkC = Intf('linkC', node=s1)
    # _intf_linkB = Intf('linkB', node=s1)
    # _intf_linkA = Intf('linkA', node=s1)
    #_intf_link8 = Intf('link8', node=s1)

    #net.addNAT().configDefault()
    #_intf_link8 = Intf('wlan0', node=s1)
    # switch = net.switches[ 0 ]
    # info( '*** Adding hardware interface', intfName, 'to switch',
    #       switch.name, '\n' )
    # _intf = Intf( intfName, node=switch )

    info(
Example #14
0
from mininet.log import setLogLevel
from mininet.net import Mininet
from mininet.topo import Topo


class TestTopology(Topo):
    def __init__(self):
        Topo.__init__(self)
        host1_id = self.addHost('h1')
        host2_id = self.addHost('h2')
        server_id = self.addHost('server')
        self.addLink(server_id, host1_id)
        self.addLink(server_id, host2_id)


def configure_network(network):
    server = network.get('server')
    server.setIP('10.0.0.10', intf='server-eth0')
    server.setMAC('00:00:00:00:00:10', intf='server-eth0')
    server.setIP('10.0.0.11', intf='server-eth1')
    server.setMAC('00:00:00:00:00:11', intf='server-eth1')
    server.cmd("python -m SimpleHTTPServer 8080 &")


# Run 'sudo python *path_to_this_script*' in mininet VM.
if __name__ == '__main__':
    setLogLevel('info')
    net = Mininet(topo=TestTopology())
    configure_network(net)
    net.pingAll()
    CLI(net)
Example #15
0
    parser.add_argument( '--static', action='store_true', \
                         help='pwospf not employed, so generate full rtable.conf\'s for all routers')   # TODO split line
    parser.add_argument( '-s', '--switch', action='store_true', \
                         help="turn forth into a simple tree topology with four hosts and a switch")  # TODO split line
    parser.add_argument( '-n', '--nointernet', action='store_true', \
                         help="don't connect to the internet")
    args, unknown = parser.parse_known_args( argv )
    
    lg.setLogLevel( 'info' )
    
    # Create net
    if (not args.switch):
        humber = Humber()
    else:
        humber = Humber(Mode.SWITCH)
    net = Mininet(topo=humber)

    # Create itable.conf for student's router code, if requested
    if (args.itable is not None):
        info( '*** Creating itable for r0\n' )
        r0_itable = Itable()
        r0_itable.add('r0-eth0', '10.0.1.1', '00:00:00:00:00:01 ', '255.255.255.0')
        r0_itable.add('r0-eth1', '10.0.2.1', '00:00:00:00:00:02 ', '255.255.255.0')
        r0_itable.add('r0-eth2', '10.0.3.1', '00:00:00:00:00:03 ', '255.255.255.0')
        r0_itable.createFile('r0-'+args.itable) 
        info( '*** Creating itable for r1\n' )
        r1_itable = Itable()
        r1_itable.add('r1-eth0', '10.0.2.2', '00:00:00:00:01:01 ', '255.255.255.0')
        r1_itable.add('r1-eth1', '10.0.4.1', '00:00:00:00:01:02 ', '255.255.255.0')
        r1_itable.add('r1-eth2', '10.0.6.1', '00:00:00:00:01:03 ', '255.255.255.0')
        r1_itable.createFile('r1-'+args.itable) 
Example #16
0
def main(args):
    print 'Running Hedera testbed experiments'

    # Shut down iperf processes
    os.system('killall -9 ' + IPERF_PATH)

    # Start mininet
    start = time()
    topo = AsymmetricTopo()
    net = Mininet(topo=topo, link=TCLink)
    net.addController(name='dhrController',
                      controller=RemoteController,
                      ip='127.0.0.1',
                      port=6633)
    net.start()
    # dumpNodeConnections(net.hosts)

    print 'wait 5 secs for installing paths'
    sleep(5)

    # CLI(net)
    # net.pingAll()

    # Start traffic
    # print 'Generating the traffic pattern in "%s"...' % args.traffic
    port_count = 0
    # for i in range(10):
    start_traffic(net, port_count)
    #    port_count += 1
    #    sleep(1)

    # Sample the cumulative # of bytes received for each host, every second.
    # The diff between adjacent samples gives us throughput for that second.
    rxbytes = {}
    sample_durations = []
    for name in HOST_NAMES:
        rxbytes[name] = []

    # sleep(20)

    # CLI(net)

    raw_input("enter 'Enter' to start taking sample...")

    # Take sample
    now = time()
    for i in xrange(N_SAMPLES):
        print 'Taking sample %d of %d...' % (i, N_SAMPLES)
        sample_durations.append(time() - now)
        now = time()
        sample_rxbytes(net, rxbytes)
        sleep(1)

    (agg_mean, agg_var) = aggregate_statistics(rxbytes, sample_durations)
    agg_stddev = sqrt(agg_var)
    mean_gbps = agg_mean / (2**30) * 8
    stddev_gbps = agg_stddev / (2**30) * 8
    print 'Total average throughput: %f bytes/sec (%f Gbps)' %\
          (agg_mean, mean_gbps)
    print 'Standard deviation: %f bytes/sec (%f Gbps)' %\
          (agg_stddev, stddev_gbps)

    save_results(mean_gbps, stddev_gbps)

    # CLI(net)

    # Shut down iperf processes
    os.system('killall -9 ' + IPERF_PATH)

    net.stop()

    print 'All done in %0.2fs!' % (time() - start)
Example #17
0
#!/usr/bin/python

from mininet.log import setLogLevel
from mininet.net import Mininet
from mininet.topolib import TreeTopo
from mininet.cli import CLI

# We assume you are in the same directory as pox.py
# or that it is loadable via PYTHONPATH
from controllers import RYU, POX

setLogLevel('info')
'''
# ENSAYO CON RYU --> ok

net = Mininet( topo=TreeTopo( depth=2, fanout=2 ),
               controller=RYU )
'''

# ENSAYO CON POX --> ok
net = Mininet(topo=TreeTopo(depth=2, fanout=2), controller=POX)

net.start()
CLI(net)
net.stop()
Example #18
0
        r1 = self.addHost('r1')
        r2 = self.addHost('r2')
        r3 = self.addHost('r3')
        r4 = self.addHost('r4')

        self.addLink(h1, r1)
        self.addLink(r1, r2)
        self.addLink(r1, r3)
        self.addLink(r2, r4)
        self.addLink(r3, r4)
        self.addLink(r4, h2)


if __name__ == '__main__':
    topo = MOSPFTopo()
    net = Mininet(topo=topo, controller=None)

    h1, h2, r1, r2, r3, r4 = net.get('h1', 'h2', 'r1', 'r2', 'r3', 'r4')
    h1.cmd('ifconfig h1-eth0 10.0.1.11/24')

    r1.cmd('ifconfig r1-eth0 10.0.1.1/24')
    r1.cmd('ifconfig r1-eth1 10.0.2.1/24')
    r1.cmd('ifconfig r1-eth2 10.0.3.1/24')

    r2.cmd('ifconfig r2-eth0 10.0.2.2/24')
    r2.cmd('ifconfig r2-eth1 10.0.4.2/24')

    r3.cmd('ifconfig r3-eth0 10.0.3.3/24')
    r3.cmd('ifconfig r3-eth1 10.0.5.3/24')

    r4.cmd('ifconfig r4-eth0 10.0.4.4/24')
Example #19
0
def topology():
    if len(sys.argv) != 6:
        print(
            'Usage: qoe-top.py number_of_clients rate_limit delay alg r_number'
        )
        exit()
    number_of_clients = int(sys.argv[1])
    rate_limit = float(sys.argv[2])
    delay = int(sys.argv[3])
    alg = sys.argv[4]
    r_number = sys.argv[5]
    total_rate_limit = number_of_clients * rate_limit

    number_of_hosts = number_of_clients
    subfolder = 'results' + r_number + '/dashc_' + alg + '_' + str(
        number_of_hosts).zfill(3) + '_' + str(rate_limit) + 'Mbps_' + str(
            delay).zfill(3) + 'ms'
    #subfolder = 'results' + r_number
    if (os.path.isdir(subfolder)):
        exit()

    print "Create a network."
    net = Mininet(controller=Controller, link=TCLink, switch=OVSKernelSwitch)

    print "*** Creating nodes"

    h1 = net.addHost('h1', mac='00:00:00:00:00:01', ip='10.0.0.1/8')

    c1 = net.addController('c1', controller=Controller, ip='127.0.0.1')
    s1 = net.addSwitch('s1')

    number_of_hosts = number_of_clients
    hosts = range(number_of_hosts)
    for i in range(number_of_hosts):
        host = 'host' + str(i).zfill(3)
        # hex is wrong here, [:-2] part
        hosts[i] = net.addHost(host,
                               mac='00:00:00:00:00:' + hex(i)[:-2],
                               ip='10.0.0.' + str(i + 2) + '/8')

    print "*** Associating and Creating links"
    queue_size = (total_rate_limit * delay * 1000) / (1500 * 8)
    queue_size = roundup(queue_size)
    link_main = net.addLink(s1,
                            h1,
                            bw=total_rate_limit,
                            delay=(str(delay) + 'ms'),
                            max_queue_size=queue_size)
    #link_main = net.addLink(s1, h1, bw=total_rate_limit, delay=(str(delay) + 'ms'))
    host_links = []
    for i in range(number_of_hosts):
        host_links.append(net.addLink(s1, hosts[i], bw=100))

    print "*** Starting network"
    net.build()
    c1.start()
    s1.start([c1])

    h1.cmdPrint('./caddy -host 10.0.0.1 -port 8080 -root ~/Downloads &')
    #h1.cmdPrint('iperf -s &')

    os.system('sleep 3')

    #alg = 'iperf'

    #subfolder = "results/dashc_bba-2_4_3Mbps_250ms"
    subfolder = 'results' + r_number + '/dashc_' + alg + '_' + str(
        number_of_hosts).zfill(3) + '_' + str(rate_limit) + 'Mbps_' + str(
            delay).zfill(3) + 'ms'
    #subfolder = 'results' + r_number
    os.system('mkdir -p ' + subfolder)
    for i in range(number_of_hosts):
        #hosts[i].cmdPrint('cd ~/Downloads/tapas-master; /usr/bin/time -o results.txt -a python play.py -a conventional -m fake -u http://10.0.0.1:8080/bbb/bbb_enc_10min_x264_dash_old.mpd &')
        #hosts[i].cmdPrint('cd ~/Downloads/tapas-master; /usr/bin/time -f \"%U %S %e %M\" -o results.txt -a python play.py -a conventional -m fake -u http://10.0.0.1:8080/bbb/bbb_enc_10min_x264_dash_old.mpd &')
        #hosts[i].cmdPrint('/usr/bin/time -o results.txt -a ./dashc.native http://10.0.0.1:8080/bbb/bbb_enc_10min_x264_dash.mpd -adapt conv -initb 2 -maxbuf 60 -persist true -lastsegmindex 75 -logname sta1 -v 20 -turnlogon false &')
        #hosts[i].cmdPrint('/usr/bin/time -f \"%U %S %e %M\" -o results.txt -a ./dashc.native http://10.0.0.1:8080/bbb/bbb_enc_10min_x264_dash.mpd -adapt conv -initb 2 -maxbuf 60 -persist true -lastsegmindex 75 -logname sta' + str(i).zfill(3) + ' -v 20 -turnlogon true -subfolder ' + subfolder + ' &')

        #hosts[i].cmdPrint('iperf -c 10.0.0.1 -t 300 | tee -a ' + subfolder + '/results' + str(number_of_clients).zfill(3) + '.txt &')
        #hosts[i].cmdPrint('iperf -c 10.0.0.1 -t 300 | tee -a ' + subfolder + '/' + alg +  '_' + str(number_of_hosts).zfill(3) + '_' + str(rate_limit) + 'Mbps_' + str(delay).zfill(3) + 'ms' + '.txt &')
        hosts[i].cmdPrint(
            './dashc.native play http://10.0.0.1:8080/bbb/bbb_enc_10min_x264_dash.mpd -adapt '
            + alg +
            ' -initb 2 -maxbuf 60 -persist true -segmentlist remote -lastsegmindex 75 -logname sta'
            + str(i).zfill(3) + ' -v 20 -r ' + r_number +
            ' -turnlogon true -subfolder ' + subfolder + ' &')

        #hosts[i].cmdPrint('cd ~/Downloads/tapas-master; python play.py -a conventional -m fake -u http://10.0.0.1:8080/bbb/bbb_enc_10min_x264_dash_old.mpd &')
        #hosts[i].cmdPrint('./dashc.native http://10.0.0.1:8080/bbb/bbb_enc_10min_x264_dash.mpd -adapt conv -initb 2 -maxbuf 60 -persist true -lastsegmindex 75 -logname sta1 -v 20 -turnlogon true &')

    print "*** Sleep for 400 seconds (300 video + 100 for everything else)"
    os.system('sleep 400')

    print "*** Stopping network"
    net.stop()
MAC,IP, Controller, CLI stuff configured
"""

from mininet.topo import Topo
from mininet.net import Mininet
from mininet.log import setLogLevel
from mininet.cli import CLI
from mininet.node import OVSSwitch, Controller, RemoteController

class SingleSwitchTopo(Topo):
    "Single switch connected to n hosts."
    def build(self):
        s1 = self.addSwitch('s1')
        s2 = self.addSwitch('s2')
        h1 = self.addHost('h1', mac="00:00:00:00:11:11", ip="10.0.0.1/24")
        h2 = self.addHost('h2', mac="00:00:00:00:11:12", ip="10.0.0.2/24")

        self.addLink(h1, s1)
        self.addLink(h2, s2)
        self.addLink(s1, s2)

if __name__ == '__main__':
    setLogLevel('info')
    topo = SingleSwitchTopo()
    c1 = RemoteController('c1', ip='127.0.0.1')
    net = Mininet(topo=topo, controller=c1)
    net.start()
    #net.pingAll()
    CLI(net)
    net.stop()
def sdn1net():
    topo = SDNIpModifiedTopo()
    info( '*** Creating network\n' )
    net = Mininet( topo=topo, controller=RemoteController )
    net = Mininet( topo=topo, controller=RemoteController )

    host1, host3, host4, host5 = net.get( 'host1', 'host3', 'host4', 'host5' )
    
        #host100.setIP('1.168.30.' + str(i), 24, str(host100) + "-eth2")  
         
        #host500.setMAC('00:00:00:00:04:%d' % (i-101), 'host%d-eth0' %(i))
        #add IP prefixes
        #for j in range(0,121):
            #host100.cmd('sudo ip addr add %s.0.40.%s/24 dev host%s-eth0' %(i,j,i))

    ## Adding 2nd, 3rd and 4th interface to host1 connected to sw1 (for another BGP peering)
    #sw1 = net.get('sw1')
    host1.setMAC('00:00:00:00:00:01', 'host1-eth0')
    #host1.cmd('ip addr add 192.168.20.101/24 dev host1-eth0')
    #host1.cmd('ip addr add 192.168.30.101/24 dev host1-eth0')
    #host1.cmd('ip addr add 192.168.60.101/24 dev host1-eth0')

    # Net has to be start after adding the above link
    net.start()

    # Set up as6sw as a learning switch as quickly as possible so it 
    # hopefully doesn't connect to the actual controller
    # TODO figure out how to change controller before starting switch
    as6sw = net.get('as6sw')
    as6sw.cmd('ovs-vsctl set-controller as6sw none')
    as6sw.cmd('ovs-vsctl set-fail-mode as6sw standalone')
    
    as6sw.cmd( 'sudo ovs-vsctl set port as6sw-eth1 trunk=60')
    as6sw.cmd( 'sudo ovs-vsctl set port as6sw-eth2 trunk=60')


    sw1 = net.get('sw1')
    sw1.cmd('ovs-vsctl set-controller sw1 tcp:127.0.0.1:6633')
    
    swTestOn = net.get('swTestOn')
    swTestOn.cmd('ovs-vsctl set-controller swTestOn none')
    swTestOn.cmd('ovs-vsctl set-fail-mode swTestOn standalone')

    #host1.defaultIntf().setIP('192.168.10.101/24') 
    
    host1.cmd( 'ifconfig host1-eth0 inet 0')
    host1.cmd( 'vconfig add host1-eth0 10')
    host1.cmd( 'ifconfig host1-eth0.10 inet 192.168.10.101')
    
    host1.cmd( 'vconfig add host1-eth0 20')
    host1.cmd( 'ifconfig host1-eth0.20 inet 192.168.20.101')
    
    host1.cmd( 'vconfig add host1-eth0 30')
    host1.cmd( 'ifconfig host1-eth0.30 inet 192.168.30.101')
    
    host1.cmd( 'vconfig add host1-eth0 60')
    host1.cmd( 'ifconfig host1-eth0.60 inet 192.168.60.101')

    # Run BGPd
    #host1.cmd('%s -d -f %s' % (BGPD, BGPD_CONF))
    #host1.cmd('/sbin/route add default gw 192.168.10.254 dev %s-eth0' % (host1.name))
    
    # Configure new host interfaces
    #host2.defaultIntf().setIP('172.16.10.2/24')
    #host2.defaultIntf().setMAC('00:00:00:00:01:02') 
    #host2.cmd('/sbin/route add default gw 172.16.10.254 dev %s-eth0' % (host2.name))

    # Set up AS2
    # add additional VLAN interface
    host3.cmd( 'ifconfig host3-eth1 inet 0')
    host3.cmd( 'vconfig add host3-eth1 20')
    host3.cmd( 'ifconfig host3-eth1.20 inet 192.168.20.1')
    # change the interface for the sencond connection to sw1 to vlan interface
    newName = "host3-eth1.20"
    secondIntf = host3.intf("host3-eth1")
    secondIntf.name = newName
    host3.nameToIntf[ newName ] = secondIntf
    
    host3.setMAC('00:00:00:00:02:01', 'host3-eth0.10')
    host3.setMAC('00:00:00:00:02:02', 'host3-eth1.20')
    
    #host3.setIP('172.16.20.254', 24, 'host3-eth2')
    host3.setIP('3.0.0.254', 8, 'host3-eth2')
    host3.cmd('sysctl net.ipv4.conf.all.forwarding=1')
    
    host3.setIP('1.168.30.2', 24, 'host3-eth3')   
    host3.cmd('sysctl net.ipv4.conf.all.arp_ignore=1')
    host3.cmd('sysctl net.ipv4.conf.all.arp_announce=1')
    host3.cmd('ip route add default via 192.168.10.101')
    as2host = net.get('as2host')
    #as2host.defaultIntf().setIP('172.16.20.1/24')
    for i in range(0, 20):
        as2host.cmd('sudo ip addr add 3.0.%d.1/24 dev as2host-eth0' %i)
    as2host.setIP('1.168.30.100', 24, 'as2host-eth1')
    
    as2host.cmd('ip route add default via 3.0.0.254')
    
    # Set up AS3
    host4.setMAC('00:00:00:00:03:01', 'host4-eth0.30')
    host4.setIP('4.0.0.254', 8, 'host4-eth1')
    host4.setMAC('00:00:00:00:03:99', 'host4-eth1')
    host4.cmd('sysctl net.ipv4.conf.all.forwarding=1')
    host4.cmd('ip route add default via 192.168.30.101')
    as3host = net.get('as3host')
    for i in range(0, 20):
        as3host.cmd('sudo ip addr add 4.0.%d.1/24 dev as3host-eth0' %i)
    as3host.cmd('ip route add default via 4.0.0.254')
    
    #root space
    host4.setIP('1.168.30.3', 24, 'host4-eth2')
    host4.setMAC('00:00:00:00:03:03', 'host4-eth2')
    
    # Set up AS4
    #as4host = net.get('as4host')
    #as4host.defaultIntf().setIP('172.16.40.1/24')
    #as4host.cmd('ip route add default via 172.16.40.254')
    
    # setup interface address for 100 quagga hosts
    time.sleep(10)
    #for i in range(numHost101, numHost200 + 1):
        #host100 = net.get('host' + str(i))
        #host100.cmd(str(i)+'.0.1.254', 24, 'host'+str(i)+'-eth1')
        #as4host100 = net.get('as4host%s' %(i))
        #as4host100.defaultIntf().setIP(str(i) + '.0.0.1/24')
        #as4host100.cmd('ip route add default via ' + str(i) + '.0.0.254')
        #for j in range(0, 100):
            #as4host100.cmd('sudo ip addr add %d.0.%d.1/24 dev %s-eth0' %(i, j, as4host100))

    # Set up AS6 - This has a router and a route server
    host5 = net.get('host5')
    host5.setMAC('00:00:00:00:06:02', 'host5-eth0.60')
    #as6router.setIP('172.16.60.254', 24, 'as6router-eth1')
    host5.setIP('5.0.0.254', 8, 'host5-eth1')
    host5.cmd('sysctl net.ipv4.conf.all.forwarding=1')
    host5.setIP('1.168.30.5', 24, 'host5-eth2')
    host5.setMAC('00:00:00:00:06:05', 'host5-eth2')
    host5.cmd('ip route add default via 192.168.60.101')
    as6host = net.get('as6host')
    #as6host.defaultIntf().setIP('5.0.0.1/24')
    for i in range(0, 10):
        as6host.cmd('sudo ip addr add 5.0.%d.1/24 dev as6host-eth0' %i)
    as6host.cmd('ip route add default via 5.0.0.254')

    # test the host in the as6
    #for i in range(1, 10):
    #    baseip = (i-1)*4
    #    host = net.get('as6host%d' % i)
    #    host.defaultIntf().setIP('172.16.70.%d/24' % (baseip+1))
    #    host.cmd('ip route add default via 172.16.70.%d' % (baseip+2))
     #   as6router.setIP('172.16.70.%d' % (baseip+2), 30, 'as6router-eth%d' % (i+1))

    # Start Quagga on border routers
    startquagga(host3, 1, QUAGGA_CONFIG_FILE_DIR + '/quagga1.conf')
    startquagga(host4, 2, QUAGGA_CONFIG_FILE_DIR + '/quagga2.conf')
    #for i in range(numHost101, numHost200 + 1):
        #host100=net.get('host%d' % (i))
        #startquaggahost5(host100, i)

    #startquagga(as6rs, 4, 'quagga-as6-rs.conf')
    startquagga(host5, 5, QUAGGA_CONFIG_FILE_DIR + '/quagga-as6.conf')

    #root1, root2, rootTestOn  = net.get( 'root1', 'root2', 'rootTestOn' )
    root1, rootTestOn  = net.get( 'root1', 'rootTestOn' )
    host1.intf('host1-eth1').setIP('1.1.1.1/24')
    root1.intf('root1-eth0').setIP('1.1.1.2/24')
    #host2.intf('host2-eth1').setIP('1.1.2.1/24')
    #root2.intf('root2-eth0').setIP('1.1.2.2/24')
    
    #rootTestOn.cmd('ip addr add 1.168.30.102/24 dev rootTestOn-eth0')
    rootTestOn.cmd('ip addr add 1.168.30.99/24 dev rootTestOn-eth0')
    
    stopsshd()    

    startquagga(host1, 100, QUAGGA_CONFIG_FILE_DIR + '/quagga-sdn-modified.conf')    
    hosts = [ host1, host3, host4, host5, as2host ];
    #sshdHosts = sshdHosts + hosts
    startsshds( hosts )
    #
    onos1 = '127.0.0.1'
    forwarding1 = '%s:2000:%s:2000' % ('1.1.1.2', onos1)
    root1.cmd( 'ssh -nNT -o "PasswordAuthentication no" -o "StrictHostKeyChecking no" -l sdn -L %s %s & ' % (forwarding1, onos1) )

    # Forward 2605 to root namespace for easier access to SDN domain BGPd
    # If root can ssh to itself without a password this should work
    root1.cmd('ssh -N -o "PasswordAuthentication no" -o "StrictHostKeyChecking no" -L 2605:1.1.1.1:2605 1.1.1.1 &')
    #time.sleep(3000000000)
    CLI( net )

    # Close the ssh port forwarding
    #quietRun('sudo pkill -f 1.1.1.1')

    stopsshd()
    stopquagga()
    net.stop()
Example #22
0
from mininet.net import Mininet
from mininet.node import Node, Switch
from mininet.link import Link, Intf
from mininet.log import setLogLevel, info
from mininet.cli import CLI

import mininet.ns3
from mininet.ns3 import SimpleLink

readline.parse_and_bind("tab: complete")

if __name__ == '__main__':
    setLogLevel('info')
    info('*** ns-3 network demo\n')
    net = Mininet()

    info('*** Creating Network\n')
    h0 = Node('h0')
    h1 = Node('h1')

    net.hosts.append(h0)
    net.hosts.append(h1)

    link = SimpleLink(h0, h1)

    mininet.ns3.start()

    info('*** Configuring hosts\n')
    h0.setIP('192.168.123.1/24')
    h1.setIP('192.168.123.2/24')
Example #23
0
def variableDelayBWTest(hps):
    topo = DelayBWTopo(hps)

    net = Mininet(topo, link=TCLink)
    net.start()

    client1, client2, server, command = net.get('client1', 'client2', 'server',
                                                'command')
    net.pingAll()

    print('initializing server and clients')
    output1 = server.cmd('nohup python -u startServer.py > server_log.txt &')
    c1_off = np.random.randint(0, 50)
    c2_off = np.random.randint(0, 50)
    output = client1.cmd(
        'nohup python -u startClient.py {0} {1} > client1_log.txt  &'.format(
            server.IP(), c1_off))
    time.sleep(1)
    output = client2.cmd(
        'nohup python -u startClient.py {0} {1} > client2_log.txt &'.format(
            server.IP(), c2_off))

    time.sleep(3)

    print('run NTP on client 1')
    output = command.cmd('python startCommander.py {0} {1}'.format(
        client1.IP(), 'startNTP'))
    print(output)

    print('run NTP on client 2')
    output = command.cmd('python startCommander.py {0} {1}'.format(
        client2.IP(), 'startNTP'))
    print(output)

    _c1, _c2 = getTimesMultiple(command, server, [client1, client2])

    print(_c1, _c2)

    net.stop()

    # we are testing diff delay
    if os.path.isfile('c1_d{}'.format(hps.delay)):
        c1 = pkl.load(open('c1_d{}'.format(hps.delay), 'rb'))
        c2 = pkl.load(open('c2_d{}'.format(hps.delay), 'rb'))
    else:
        c1 = []
        c2 = []

    c1.append(_c1)
    c2.append(_c2)

    pkl.dump(c1, open('c1_d{}'.format(hps.delay), 'wb'))
    pkl.dump(c2, open('c2_d{}'.format(hps.delay), 'wb'))

    # we are testing diff bandwidth
    if os.path.isfile('c1_bw{}'.format(hps.bw)):
        c1 = pkl.load(open('c1_bw{}'.format(hps.bw), 'rb'))
        c2 = pkl.load(open('c2_bw{}'.format(hps.bw), 'rb'))
    else:
        c1 = []
        c2 = []

    c1.append(_c1)
    c2.append(_c2)

    pkl.dump(c1, open('c1_bw{}'.format(hps.bw), 'wb'))
    pkl.dump(c2, open('c2_bw{}'.format(hps.bw), 'wb'))

    return _c1, _c2
Example #24
0
from mininet.cli import CLI
from mininet.net import Mininet
from mininet.node import RemoteController, OVSSwitch
from mininet.link import TCLink

if '__main__' == __name__:

    net = Mininet(controller=RemoteController,
                  switch=OVSSwitch,
                  link=TCLink,
                  autoSetMacs=True)
    #OVSSwitch
    c0 = net.addController('c0', controller=RemoteController, port=6633)
    h1 = net.addHost('h1', ip='10.0.0.1', MAC='01:01:01:00:00:01')
    h2 = net.addHost('h2', ip='10.0.0.2', MAC='01:01:01:00:00:02')
    h3 = net.addHost('h3', ip='10.0.0.3', MAC='01:01:01:00:00:03')

    s1 = net.addSwitch('s1')

    #add link
    net.addLink(h1, s1, delay='1ms')
    net.addLink(h2, s1, delay='1ms')
    net.addLink(h3, s1, delay='1ms')

    net.build()
    c0.start()
    s1.start([c0])
    s1.cmd('ovs-vsctl set Bridge s1 protocols=OpenFlow13')
    CLI(net)
    net.stop()
Example #25
0
from mininet.net import Mininet
from mininet.node import Controller, RemoteController, UserSwitch
from mininet.clean import cleanup
"""
This script kills local Ryu execution
"""

SERVER_IP = 'localhost'
ryu = RemoteController('ame', ip=SERVER_IP, port=6633)
net = Mininet(controller=ryu)
net.start()
net.stop()
cleanup()
ryu.stop()
def emptyNet():
    switch = partial(OVSSwitch, protocols='OpenFlow13')
    link = partial(TCLink, bw=100)
    topo = SpineLeaf(leaves=3)

    net = Mininet(controller=RemoteController,
                  switch=switch,
                  link=link,
                  topo=topo,
                  build=False,
                  autoSetMacs=True)

    controllers = []

    controllers.append(
        net.addController('c1',
                          controller=RemoteController,
                          ip="192.168.247.212",
                          port=6633))
    controllers.append(
        net.addController('c2',
                          controller=RemoteController,
                          ip="192.168.247.213",
                          port=6633))
    controllers.append(
        net.addController('c3',
                          controller=RemoteController,
                          ip="192.168.247.214",
                          port=6633))

    #    controllers.append(net.addController('c1', controller=RemoteController, ip="192.168.247.210", port=6633))

    #    f = Flows()

    #    capture("captura-3-nodes-odl-magnesium-events","eno1",timeout=180)

    net.build()
    net.start()

    #    h1 = net.getNodeByName("h1")
    #    h3 = net.getNodeByName("h3")

    #    time.sleep(15)

    #    devs = failover()
    #    f.test()

    #   time.sleep(5)

    #   for i in range(5,8):
    #       os.system("ssh [email protected].{0} -p 8101 -o StrictHostKeyChecking=no events -m > log_mastership_{0}.ini".format(str(i)))

    #   os.system("docker kill onos-1")
    #    changeTime(devs)

    #    h1.cmdPrint("ping -c 20 %s" % h3.IP())

    #   time.sleep(5)

    #   for i in range(5,8):
    #       os.system("ssh [email protected].{0} -p 8101 -o StrictHostKeyChecking=no events -m > log_mastership_{0}.end".format(str(i)))

    #    time.sleep(25)

    CLI(net)
    net.stop()
Example #27
0
def bufferbloat():
    if not os.path.exists(args.dir):
        os.makedirs(args.dir)
    os.system("sysctl -w net.ipv4.tcp_congestion_control=%s" % args.cong)
    topo = BBTopo()
    net = Mininet(topo=topo, host=CPULimitedHost, link=AQMLink)
    net.start()
    
    # Hint: The command below invokes a CLI which you can use to
    # debug.  It allows you to run arbitrary commands inside your
    # emulated hosts h1 and h2.
    # Note: It can take a while to pop out xterm windows in GCP.
    # CLI(net)
    
    # This dumps the topology and how nodes are interconnected through
    # links.
    dumpNodeConnections(net.hosts)
    
    # This performs a basic all pairs ping test.
    net.pingAll()

    # Start all the monitoring processes
    start_tcpprobe("%s/cwnd.txt" % (args.dir))

    # TODO: Start monitoring the queue sizes.  Since the switch I
    # created is "s0", I monitor one of the interfaces.  Which
    # interface?  The interface numbering starts with 1 and increases.
    # Depending on the order you add links to your network, this
    # number may be 1 or 2.  Ensure you use the correct number.

    # TODO: Start iperf, webservers, ping.

    # TODO: measure the time it takes to complete webpage transfer
    # from h1 to h2 (say) 3 times.  Hint: check what the following
    # command does: curl -o /dev/null -s -w %{time_total} google.com
    # Now use the curl command to fetch webpage from the webserver you
    # spawned on host h1 (not from google!)
    # Hint: Where is the webserver located?

    # Hint: have a separate function to do this and you may find the
    # loop below useful.
    start_time = time()
    while True:
        # do the measurement (say) 3 times.

        sleep(5)
        now = time()
        delta = now - start_time

        if delta > args.time:
            break
        print "%.1fs left..." % (args.time - delta)

    # TODO: compute average (and standard deviation) of the fetch
    # times.  You don't need to plot them.  Just note it in your
    # README and explain.

    stop_tcpprobe()
    qmon.terminate()
    net.stop()
    # Ensure that all processes you create within Mininet are killed.
    # Sometimes they require manual killing.
    Popen("pgrep -f webserver.py | xargs kill -9", shell=True).wait()
def main():

    with open(args.manifest, 'r') as f:
        manifest = json.load(f)

    conf = manifest['targets'][args.target]
    params = conf['parameters'] if 'parameters' in conf else {}

    os.environ.update(dict(map(lambda (k, v): (k, str(v)),
                               params.iteritems())))

    def formatParams(s):
        for param in params:
            s = re.sub('\$' + param + '(\W|$)', str(params[param]) + r'\1', s)
            s = s.replace('${' + param + '}', str(params[param]))
        return s

    AppTopo = apptopo.AppTopo
    AppController = appcontroller.AppController

    if 'topo_module' in conf:
        sys.path.insert(0, os.path.dirname(args.manifest))
        topo_module = importlib.import_module(conf['topo_module'])
        AppTopo = topo_module.CustomAppTopo

    if 'controller_module' in conf:
        sys.path.insert(0, os.path.dirname(args.manifest))
        controller_module = importlib.import_module(conf['controller_module'])
        AppController = controller_module.CustomAppController

    if not os.path.isdir(args.log_dir):
        if os.path.exists(args.log_dir):
            raise Exception('Log dir exists and is not a dir')
        os.mkdir(args.log_dir)
    os.environ['P4APP_LOGDIR'] = args.log_dir

    links = [l[:2] for l in conf['links']]
    latencies = dict([(''.join(sorted(l[:2])), l[2]) for l in conf['links']
                      if len(l) == 3])

    for host_name in sorted(conf['hosts'].keys()):
        host = conf['hosts'][host_name]
        if 'latency' not in host: continue
        for a, b in links:
            if a != host_name and b != host_name: continue
            other = a if a != host_name else b
            latencies[host_name + other] = host['latency']

    for l in latencies:
        if isinstance(latencies[l], (str, unicode)):
            latencies[l] = formatParams(latencies[l])
        else:
            latencies[l] = str(latencies[l]) + "ms"

    bmv2_log = args.bmv2_log or ('bmv2_log' in conf and conf['bmv2_log'])
    pcap_dump = args.pcap_dump or ('pcap_dump' in conf and conf['pcap_dump'])

    topo = AppTopo(links,
                   latencies,
                   manifest=manifest,
                   target=args.target,
                   log_dir=args.log_dir)
    switchClass = configureP4Switch(sw_path=args.behavioral_exe,
                                    json_path=args.json,
                                    log_console=bmv2_log,
                                    pcap_dump=pcap_dump)
    net = Mininet(topo=topo,
                  link=TCLink,
                  host=P4Host,
                  switch=switchClass,
                  controller=None)
    net.start()

    sleep(1)

    controller = None
    if args.auto_control_plane or 'controller_module' in conf:
        controller = AppController(manifest=manifest,
                                   target=args.target,
                                   topo=topo,
                                   net=net,
                                   links=links)
        controller.start()

    for host in net.hosts:
        if "h1" in host.name:
            h1 = host
        if "h2" in host.name:
            h2 = host
        if "h3" in host.name:
            h3 = host
        if "h4" in host.name:
            h4 = host

    h1.cmd('tc qdisc del dev %s-eth0 root' % host.name, shell=True)
    h1.cmd('ifconfig %s-eth0 mtu 2000 up' % host.name, shell=True)
    h1.cmd(
        'tc qdisc add dev %s-eth0 root tbf rate 16Mbit latency 10ms burst 2000'
        % host.name,
        shell=True)

    subprocess.Popen('sudo ../sink/sink s4-eth2 127.0.0.1 6666 &', shell=True)
    sleep(60)

    def setupLinks(capacity):
        for interface in [
                's1-eth1', 's1-eth2', 's2-eth1', 's2-eth2', 's2-eth3',
                's3-eth1', 's3-eth2', 's3-eth3', 's4-eth1'
        ]:
            call('tc qdisc del dev %s root' % interface, shell=True)
            call('ifconfig %s mtu 2000 up' % interface, shell=True)
            call(
                'tc qdisc add dev %s root tbf rate %skbit latency 10ms burst 2000'
                % (interface, capacity),
                shell=True)

    def runTest(method, nom_cap):
        setupLinks(nom_cap)
        print "Running Factor Test: " + str(method) + "," + str(nom_cap)
        capest = subprocess.Popen(
            'sudo script -c "../sink/capest_visualizer 6666 | grep \'Swid: 3\'" -f ./.capestd &',
            shell=True)
        h1.cmd('sudo killall iperf3')
        h3.cmd('iperf3 -s &')
        h1.cmd('iperf3 -c 10.0.3.10 -t 60 & > ./iperf')
        h2.cmd('iperf3 -s &')
        h3.cmd('iperf3 -c 10.0.2.10 -t 60 & > ./iperf')
        sleep(30)
        h2.cmd('ping 10.0.4.10 -i 0.2 -c 75 -q | tail -n 2 > .pingdata &')
        sleep(30)
        capest.kill()
        call('./gatherFactorData.sh %s %s' % (method, nom_cap), shell=True)
        call('sudo rm -f .capestd', shell=True)
        call('sudo touch .capestd', shell=True)
        call('sudo killall capestd', shell=True)

    def runBatch(repetitions):
        for x in range(0, repetitions):
            runTest("Factor_" + args.json, 8000)
            runTest("Factor_" + args.json, 1000)
            runTest("Factor_" + args.json, 10000)
            runTest("Factor_" + args.json, 2000)
            runTest("Factor_" + args.json, 12000)
            runTest("Factor_" + args.json, 3000)
            runTest("Factor_" + args.json, 14000)
            runTest("Factor_" + args.json, 4000)
            runTest("Factor_" + args.json, 16000)

    runBatch(12)

    #Run Test

    #if args.cli or ('cli' in conf and conf['cli']):
    #    CLI(net)

    stdout_files = dict()
    return_codes = []
    host_procs = []

    def formatCmd(cmd):
        for h in net.hosts:
            cmd = cmd.replace(h.name, h.defaultIntf().updateIP())
        return cmd

    def _wait_for_exit(p, host):
        print p.communicate()
        if p.returncode is None:
            p.wait()
            print p.communicate()
        return_codes.append(p.returncode)
        if host_name in stdout_files:
            stdout_files[host_name].flush()
            stdout_files[host_name].close()

    print '\n'.join(map(lambda (k, v): "%s: %s" %
                        (k, v), params.iteritems())) + '\n'

    for host_name in sorted(conf['hosts'].keys()):
        host = conf['hosts'][host_name]
        if 'cmd' not in host: continue

        h = net.get(host_name)
        stdout_filename = os.path.join(args.log_dir, h.name + '.stdout')
        stdout_files[h.name] = open(stdout_filename, 'w')
        cmd = formatCmd(host['cmd'])
        print h.name, cmd
        p = h.popen(cmd,
                    stdout=stdout_files[h.name],
                    shell=True,
                    preexec_fn=os.setpgrp)
        if 'startup_sleep' in host: sleep(host['startup_sleep'])

        if 'wait' in host and host['wait']:
            _wait_for_exit(p, host_name)
        else:
            host_procs.append((p, host_name))

    for p, host_name in host_procs:
        if 'wait' in conf['hosts'][host_name] and conf['hosts'][host_name][
                'wait']:
            _wait_for_exit(p, host_name)

    for p, host_name in host_procs:
        if 'wait' in conf['hosts'][host_name] and conf['hosts'][host_name][
                'wait']:
            continue
        if p.returncode is None:
            run_command('pkill -INT -P %d' % p.pid)
            sleep(0.2)
            rc = run_command('pkill -0 -P %d' %
                             p.pid)  # check if it's still running
            if rc == 0:  # the process group is still running, send TERM
                sleep(1)  # give it a little more time to exit gracefully
                run_command('pkill -TERM -P %d' % p.pid)
        _wait_for_exit(p, host_name)

    if 'after' in conf and 'cmd' in conf['after']:
        cmds = conf['after']['cmd'] if type(
            conf['after']['cmd']) == list else [conf['after']['cmd']]
        for cmd in cmds:
            os.system(cmd)

    if controller: controller.stop()

    net.stop()

    #    if bmv2_log:
    #        os.system('bash -c "cp /tmp/p4s.s*.log \'%s\'"' % args.log_dir)
    #    if pcap_dump:
    #        os.system('bash -c "cp *.pcap \'%s\'"' % args.log_dir)

    bad_codes = [rc for rc in return_codes if rc != 0]
    if len(bad_codes): sys.exit(1)
from collections import defaultdict
import datetime
from random import randint
import networkx as nx, igraph as ig
import pylab as plt
from collections import Counter
from itertools import tee, izip
import string
import heapq

#-------------------------------------------------------------------------------
#context = zmq.Context()
#socket = context.socket(zmq.REQ)
#socket.connect("tcp://localhost:5556")

net = Mininet( controller=RemoteController, link=TCLink, switch=OVSKernelSwitch, xterms = False )
G = nx.Graph()
Global_Failure_Counter=0  # Global counter to keep the number of all links failure
X_param = 1 # Global counter to avoid the first false failure (division by zero)

def topology():

        global net
        # Add hosts and switches 
        h1 = net.addHost( 'h1', mac= "00:00:00:00:00:01" ) 
        h2 = net.addHost( 'h2', mac= "00:00:00:00:00:02" ) 
        h3 = net.addHost( 'h3', mac= "00:00:00:00:00:03" ) 
        h4 = net.addHost( 'h4', mac= "00:00:00:00:00:04" )
        h5 = net.addHost( 'h5', mac= "00:00:00:00:00:05" ) 
        h6 = net.addHost( 'h6', mac= "00:00:00:00:00:06" ) 
        h7 = net.addHost( 'h7', mac= "00:00:00:00:00:07" ) 
Example #30
0
def four_switches_network():
    net = Mininet(topo=None, build=False, ipBase='10.0.0.0/8', link=TCLink)

    queue_lenght = Config.queue_lenght

    bw_max_dict = Config.bw_max_dict

    # linkarray
    linkArray = []
    split_up_load_levels_flag = Config.split_up_load_levels_flag
    logs = Config.log_path
    # importante! the load levels for measurements
    loadLevels = Config.load_levels
    print("LoadLevel: {}".format(loadLevels))
    timeTotal = min_to_sec(Config.duration_iperf_per_load_level_minutes)
    controllerIP = '127.0.0.1'
    fileName = 'timestamp_changing_load_levels_mininet'
    info('*** Adding controller\n')
    c0 = net.addController(name='c0',
                           controller=RemoteController,
                           ip=controllerIP,
                           protocol='tcp',
                           port=6633)

    info('*** Add switches\n')
    s1 = net.addSwitch('s1', cls=OVSKernelSwitch)
    s2 = net.addSwitch('s2', cls=OVSKernelSwitch)
    s3 = net.addSwitch('s3', cls=OVSKernelSwitch)
    s4 = net.addSwitch('s4', cls=OVSKernelSwitch)

    info('*** Add hosts\n')
    h11 = net.addHost('h11', cls=Host, ip='10.0.0.11', defaultRoute=None)
    h12 = net.addHost('h12', cls=Host, ip='10.0.0.12', defaultRoute=None)
    h13 = net.addHost('h13', cls=Host, ip='10.0.0.13', defaultRoute=None)

    h41 = net.addHost('h41', cls=Host, ip='10.0.0.41', defaultRoute=None)
    h42 = net.addHost('h42', cls=Host, ip='10.0.0.42', defaultRoute=None)
    h43 = net.addHost('h43', cls=Host, ip='10.0.0.43', defaultRoute=None)

    info('*** Add links\n')
    linkArray.append(
        net.addLink(s1,
                    s2,
                    delay='10ms',
                    use_tbf=True,
                    bw=3,
                    max_queue_size=queue_lenght,
                    latency_ms=10000000,
                    burst=1000000))
    linkArray.append(
        net.addLink(s2,
                    s4,
                    delay='10ms',
                    use_tbf=True,
                    bw=3,
                    max_queue_size=queue_lenght,
                    latency_ms=10000000,
                    burst=1000000))
    linkArray.append(
        net.addLink(s1,
                    s3,
                    delay='14ms',
                    use_tbf=True,
                    bw=4,
                    max_queue_size=queue_lenght,
                    latency_ms=10000000,
                    burst=1000000))
    linkArray.append(
        net.addLink(s3,
                    s4,
                    delay='14ms',
                    use_tbf=True,
                    bw=4,
                    max_queue_size=queue_lenght,
                    latency_ms=10000000,
                    burst=1000000))

    net.addLink(h11, s1)
    net.addLink(h12, s1)
    net.addLink(h13, s1)

    net.addLink(h41, s4)
    net.addLink(h42, s4)
    net.addLink(h43, s4)

    info('*** Starting network\n')
    net.build()
    info('*** Starting controllers\n')
    for controller in net.controllers:
        controller.start()

    info('*** Starting switches\n')
    net.get('s1').start([c0])
    net.get('s2').start([c0])
    net.get('s3').start([c0])
    net.get('s4').start([c0])

    iterations = Config.iterations
    if iterations > 1:
        iteration_split_up_flag = True
    else:
        iteration_split_up_flag = False

    # erasing previous file
    if not split_up_load_levels_flag:
        if iteration_split_up_flag:
            clearing_save_file_iterations(fileName, logs, iterations)
        else:
            clearingSaveFile(fileName, logs)

    time.sleep(15)
    # incrementing the load
    for iteration in range(iterations):
        i = 0
        clearing_save_file_iterations(fileName, logs, iterations)
        for loadLevel in loadLevels:
            # iperf threads
            # if the load levels are not split up -> write the load level change
            if split_up_load_levels_flag:
                reset_load_level(loadLevel)
            if not split_up_load_levels_flag:
                write_in_File(fileName, logs, loadLevel,
                              iteration_split_up_flag, iteration)
            # send load level
            print("(Re)starting iperf -- loadLevel:  {}".format(loadLevel))
            start_new_thread(startIperf,
                             (h11, h41, 2.75, 5001, timeTotal, loadLevel))
            start_new_thread(startIperf,
                             (h12, h42, 1.75, 5001, timeTotal, loadLevel))
            start_new_thread(startIperf,
                             (h13, h43, 1.75, 5001, timeTotal, loadLevel))
            i = i + 1
            time.sleep(timeTotal)
            # waiting additional 2 sec to reset states
            if Config.wait_between_load_lavel_change:
                time.sleep(Config.waiting_time)

        # last load level past
        if not split_up_load_levels_flag:
            write_in_File(fileName, logs, -1, iteration_split_up_flag,
                          iteration)
        if iteration_split_up_flag and iteration < iterations - 1:
            reset_iteration(iteration + 1)
            time.sleep(1)
    stop_controller()
    CLI(net)
    net.stop()