示例#1
0
def main():
    lg.setLogLevel('info')

    net = Mininet(SingleSwitchTopo(k=5))
    net.start()

    h1 = net.get('h1')
    h2 = net.get('h2')
    h3 = net.get('h3')

    p1 = h1.popen('python fun_probe.py --host %s --port %s' %
                  (h1.IP(), '9030'))
    p2 = h2.popen('python fun_probe.py --host %s --port %s' %
                  (h2.IP(), '9031'))
    p3 = h3.popen('python fun_collector.py --host %s --devicehosts %s ' %
                  (h3.IP(), [h1.IP(), h2.IP()]))

    popens = {h1: p1, h2: p2, h3: p3}
    for h, line in popens:
        print h + " " + line
    for h, line in pmonitor(popens):
        print "Monitoring output..."
        if h:
            print '%s: %s' % (h.name, line)
    CLI(net)
示例#2
0
def testIperf( net, server='h0', clients=('h1', 'h2') ):
    popens = {}
    tperf = 20
    tout = ( tperf + 1 ) * 4
    stopPerf = time() + tout + 5
    inv = 4

    popens[ net[ server ] ] = net[ server ].popen( 'iperf -s -t '+str( tout ) )
    for client in clients:
        popens[ net[ client ] ] = net[ client ].popen( 'iperf -c '+net[ server ].IP()+' -i '+str(inv)+' -t '+str( tperf ) )
    
    logserver = logclient1 = logclient2 = ""

    for host, line in pmonitor(popens, timeoutms=(tperf + tout) * 4):
    	if host:
            if host.name == server: logserver += (host.name +": "+line)
            elif host.name == clients[0]: logclient1 += (host.name +": "+line)
            elif host.name == clients[1]: logclient2 += (host.name +": "+line)


    	if time() >= stopPerf:
    		for p in popens.values(): p.send_signal(SIGINT)

    print(logserver)
    print(logclient1)
    print(logclient2)
 def iperf(self, client_host, server_host, server_ip, port, seconds):
     iperf_base_cmd = 'iperf -f M -p %u' % port
     if server_ip.version == 6:
         iperf_base_cmd += ' -V'
     iperf_server_cmd = '%s -s' % iperf_base_cmd
     iperf_server_cmd = self.timeout_cmd(iperf_server_cmd,
                                         (seconds * 3) + 5)
     iperf_client_cmd = self.timeout_cmd(
         '%s -y c -c %s -t %u' % (iperf_base_cmd, server_ip, seconds),
         seconds + 5)
     server_start_exp = r'Server listening on TCP port %u' % port
     for _ in range(3):
         server_out = server_host.popen(iperf_server_cmd,
                                        stderr=subprocess.STDOUT)
         popens = {server_host: server_out}
         lines = []
         for host, line in pmonitor(popens):
             if host == server_host:
                 lines.append(line)
                 if re.search(server_start_exp, line):
                     self.wait_for_tcp_listen(server_host,
                                              port,
                                              ipv=server_ip.version)
                     iperf_mbps = self.iperf_client(client_host,
                                                    iperf_client_cmd)
                     self.signal_proc_on_port(server_host, port, 9)
                     return iperf_mbps
         time.sleep(1)
     self.fail('%s never started (%s, %s)' %
               (iperf_server_cmd, server_start_exp, ' '.join(lines)))
示例#4
0
    def _exec_test(self, targets, int_hosts, ext_hosts, int_switches,
                   ext_switches, int_routers, ext_routers):

        popens = {}

        popens[ext_hosts[0]] = ext_hosts[0].popen(
            'hping3 -c 10000000 --faster 192.168.2.112')
        popens[ext_hosts[1]] = ext_hosts[1].popen(
            'hping3 -c 10000000 --faster 192.168.3.114')
        popens[ext_hosts[2]] = ext_hosts[2].popen(
            'hping3 -c 10000000 --faster 192.168.1.103')
        popens[ext_hosts[3]] = ext_hosts[3].popen(
            'hping3 -c 10000000 --faster 192.168.2.109')
        popens[ext_hosts[4]] = ext_hosts[4].popen(
            'hping3 -c 10000000 --faster 192.168.4.119')
        popens[ext_hosts[5]] = ext_hosts[5].popen(
            'hping3 -c 10000000 --faster 192.168.5.122')

        popens[int_hosts[0]] = int_hosts[0].popen(
            'tcpreplay --topspeed -i h1-eth0 /media/sf_ids-sdn/pcap/testbed-15jun.pcap'
        )

        for host, line in pmonitor(popens):
            if host:
                info('<%s>: %s' % (host.name, line))
示例#5
0
文件: run.py 项目: alanefl/jellyfish
def monitor_throughput(popens, P, rounds, host_throughput):
    """
    Prints process information from different network hosts.
    See: https://github.com/mininet/mininet/blob/master/examples/popen.py

    The purpose of this is to catch the throughput measurements of
    the various iperf tasks.
    """
    host_lines = {}
    for host, line in pmonitor(popens):
        if host:

            # Catch the lines of output we care about.  Namely
            # the ones that contain the Bandwith readings of
            # Mbits/sec or Gbits / sec
            if P == 1:
                if 'Bytes' in line:
                    host_lines[host.name] = line.strip()
            else:
                if '[SUM]' in line:
                    host_lines[host.name] = line.strip()
            #print("<%s>: %s" % (host.name, line.strip()))

    # Update the per-server throughput values after each round.
    update_server_throughputs(host_lines, host_throughput, rounds)
示例#6
0
def execute_command_ping(network, hosts, command, time_between_commands = 1, single_command_timeoutms=1000, kill_wait_sec=15):
    """Args:
        hosts: List of hosts to execute the command.
        command: string of command to execute.
        single_command_timeoutms: timeout in ms for the command.
        kill_wait_sec: Time to wait in sec before sending SIGINT.
    Returns:
        A list of stdout line by line.
    """
    popens = { }
    output = [ ]
    for hostname in hosts:
        host = network.get(hostname)
        print "Pinging from host:", hostname, " with command:" ,command
        popens[ hostname ] = host.popen(command, stdout=subprocess.PIPE) # Does not work on FatTree
        time.sleep(time_between_commands)
    print "Monitoring output for", kill_wait_sec, "seconds"
    endTime = time.time() + kill_wait_sec
    print endTime
    print popens
    for h, line in pmonitor( popens, timeoutms=single_command_timeoutms ):
        if h:
            if len(line) > 10: # This is due to a bug where new lines are printed.
                output.append( '<%s>: %s' % ( h,  line )),
        if time.time() >= endTime:
            for p in popens.values():
                p.send_signal( SIGINT )
            break
    print output
    for line in output:
        if len(line) > 10:
            print line,
    print '\n'
    return output
示例#7
0
def test_ping_with_background_traffice(network, round_count=1, round_duration=5, ping_interval=1.0, background=True):
    """
    h1 执行 ping 测试延时
    h2 执行 netperf 测试带宽利用率
    :param background:
    :param network: mininet class
    :param round_count:    循环次数
    :param round_duration: 循环时间每轮
    :param ping_interval:  ping包采样间隔
    :return:
    """
    result = ""
    h1 = network.get("h1")
    popens = {}
    if background:  # backgroud traffice, 每轮增加10秒时延
        h1.cmd("netperf -H h3 -l %s &" % (round_count * (round_duration + 5)))
    sleep(3)  # wait 2 second to reach tcp max output
    for r in range(round_count):
        print ("*** ROUND %s" % r)
        for h in [h1]:
            ping_cmd = "ping -c%s -i%s h3 " % (int(round_duration / ping_interval), ping_interval)
            info("<%s>: popen cmd: %s \n" % (h.name, ping_cmd))
            popens[h] = h.popen(ping_cmd)

        # Monitor them and print output
        for host, line in pmonitor(popens):
            if host:
                if line.find("icmp_seq") != -1:
                    debug("<%s>: %s\n" % (host.name, line.strip()))  # suppressed ping output to debug level
                else:
                    info("<%s>: %s\n" % (host.name, line.strip()))
                    result += "<%s>: %s\n" % (host.name, line.strip())

    debug("\n".join(os.popen('tc -s -d qdisc show dev s1-eth3').readlines()))
    return result
示例#8
0
def runMapReduceWordCount(hosts, args):
    try:
        popens = {}

        print hosts

        # Start the master
        print "Running cmd: python ./mr_wordcount.py -m ", str(
            args.map), " -r ", str(args.reduce), " -p ", str(
                args.masterport
            ), " ", args.datafile, " on host: ", hosts[0].IP()
        # popens [ master ] = master.popen ('ping', '-c3', master.IP() )
        popens[hosts[0]] = hosts[0].popen('python',
                                          './mr_wordcount.py',
                                          '-m',
                                          str(args.map),
                                          '-r',
                                          str(args.reduce),
                                          '-p',
                                          str(args.masterport),
                                          args.datafile,
                                          stdout=subprocess.PIPE)

        # next run the Map workers
        # do this for as many map jobs as there are. Note that the hosts are organized as follows:
        # 0th entry is master, followed by map hosts, followed by reduce hosts
        for i in range(args.map):
            # the positional arguments for map process are its ID, master's IP addr, master's port
            print "Running cmd: python ./mr_mapworker.py ", str(
                i), " ", hosts[0].IP(), " ", str(
                    args.masterport), " on host: ", hosts[i + 1].IP()
            popens[hosts[i + 1]] = hosts[i + 1].popen('python',
                                                      './mr_map.py',
                                                      str(i),
                                                      hosts[0].IP(),
                                                      str(args.masterport),
                                                      stdout=subprocess.PIPE)

        # next run the Reduce workers

        print "Length of popens = ", len(popens.values())
        print "values = ", popens.values()
        info("Monitoring output for 10 seconds\n")
        endTime = time() + 10
        # for h, line in pmonitor( popens, timeoutms=500 ):
        for host, line in pmonitor(popens):
            if host:
                info('<%s>: %s' % (host.name, line))

                # if time() >= endTime:
                # for p in popens.values():
                # p.send_signal( SIGINT )
                # outval = p.communicate ()[0]
                # print "stdout = ", repr (outval)

    except:
        print "Unexpected error in run mininet:", sys.exc_info()[0]
        raise
示例#9
0
 def set_OF_version(self, net):
     popens = {}
     print(len(net.switches))
     for switch in net.switches:
         switch.popen("ovs-vsctl set Bridge " + switch.name +
                      " -O openflow13")
     for switch, line in pmonitor(popens):
         if switch:
             print("<%s>: %s" % (switch.name, line))
示例#10
0
def execute_iperf_command(network, hosts, single_command_timeoutms, total_time_sec, links_to_fail):
    """Args:
	network: Mininet network object
        hosts: source destination pair list
        single_command_timeoutms: timeout in ms for the command. 
		                  It should > the total time of iperf command.
        total_time_sec: Number of seconds to run the iperf command.
    Returns:
        A list of stdout line by line.
    """
    popens_client = { }
    popens_server = { }
    output = [ ]
    start_port_num = 11000
    for host_pair in hosts:
	start_port_num += 1
	#Client should be running on source.
	src = host_pair[0]
	# Server should be running on the destination.
	dst = host_pair[1]
	# Build the command
	interval_sec = 1
	proto = ""
	bandwidth = 1 # Bandwidth is in mbps.
	"""Total duration of iperf command."""
    	server_command = get_iperf_server_command(start_port_num, interval_sec, proto)
    	client_command = get_iperf_client_command(dst, total_time_sec, start_port_num, bandwidth, interval_sec, proto)
    	print dst.name, server_command
    	print src.name, client_command
        popens_server[ dst.name ] = dst.popen(server_command, shell=False)
        popens_client[ src.name ] = src.popen(client_command, shell=False)
    print "Monitoring output for ", total_time_sec+10, " seconds"
    # total_time_sec is the time to make the iperf run and we wait for extra 5 seconds to be sure.
    endTime = time.time() + total_time_sec + 10
    #perform_link_failures(network, links_to_fail)
    # We only need the output from the server to get any loss rate.
    for h, line in pmonitor( popens_server, timeoutms=single_command_timeoutms ):
        if h:
            if len(line) > 10: # This is due to a bug where new lines are printed.
                output.append( '<%s>: %s' % ( h,  line )),
        if time.time() >= endTime:
	    # Close both client and server.
            for ps in popens_server.values():
                ps.send_signal( SIGINT )
            for pc in popens_client.values():
                pc.send_signal( SIGINT )
    f = open('output/workfile', 'w')
    for item in output:
        f.write(item)
    f.close()
    # Debug
    for line in output:
        if len(line) > 10:
            print line,
    print '\n'
    return output
示例#11
0
文件: jellyfish.py 项目: vmehmeri/SDN
def monitorOutput(popens, duration):
	endTime = time.time() + duration
	for host, line in pmonitor( popens ):
		if host:
			logger.debug( "<%s>: %s" % ( host, line.strip() ) )
		if time.time() >= endTime:
			logger.debug("*** One or more connections timed out ***")
			for p in popens.values():
				p.send_signal( SIGINT )
			break
示例#12
0
def Test3():
    print "Beginning Test 3: Testing whether TCP traffic initiated from Internet gets dropped"    
    topo = MyTopo(2)
    net = Mininet(topo, controller=RemoteController)

    net.start()
    leftHost = net['h1']
    rightHost = net['h2']
    switch = net['s3']

    popens = {}

    popens[leftHost] = leftHost.popen('iperf -s -p 80')
    popens[rightHost] = rightHost.popen('iperf -c 10.0.0.1 -p 80')    

    seconds = 20
 
    endTime = time() + seconds   
    num = 0
    value = 0
    output_1 = '' 
	
    # line contains the results of executions
    for h, line in pmonitor(popens, timeoutms=1000 ):
       if h:
       	  output_1 += line 
          num = num + 1
   
       if num == 2:
       	   text = "Server listening on TCP port 80\n"
     	   if text == line:
	      value = 1
	   else:
	      value = 0 	    
		   	

       if time() >= endTime:
	    for p in popens.values():
		 p.send_signal( SIGINT )

    out = _parseIperf(output_1)
		 
    #print output_1
    if num > 4 or value == 0:
		print "Test 3 Failed"
    else:
		if out == '':
			print "Test 3 Passed"
		else:
			print "Test 3 Failed"

    print "------------------------------------------------------"
    net.stop()
示例#13
0
def my_test(topo_name, topo_instance):
    os.system('mn -c')
    os.system('sysctl -w net.ipv4.tcp_congestion_control=reno')
    #You can add os.system code here
    #Note that the configuration in this python script will affect your mininet.
    #Therefore, please make sure that you restore the configuration to the default values.
    switches = {  # 'reference kernel': KernelSwitch,
        #'reference user': UserSwitch,
        'Open vSwitch kernel': OVSKernelSwitch
    }
    for name in switches:
        switch = switches[name]
        # 10 runs for each topology
        for iter in range(0, 10):
            for sID in topo_instance.expIDs():
                sName = 'h%d' % sID
                fname = '%s-%02d-%s' % (topo_name, (iter + 1), sName)
                fobj = open(fname, 'w')
                #fobj.write('*+#@$-*+#@$-*+#@$-*+#@$-*+#@$-*+#@$-*+#@$-*+#@$-\n')
                fobj.write('@Test for topology "%s" begins:\n' % topo_name)
                fobj.write('\n>>Iteration %d<<\n' % (iter + 1))
                #topo = SingleSwitchTopo(0)
                network = Mininet(topo=topo_instance,
                                  host=CPULimitedHost,
                                  link=TCLink,
                                  switch=switch)
                network.start()
                popens = {}
                hosts = network.hosts
                switches = network.switches
                for hs in hosts:
                    if sName == hs.name:
                        popens[(hs, 'server')] = hs.popen('iperf -s')
                        for hc in hosts:
                            if hc.name != hs.name:
                                popens[(hc, 'client')] = hc.popen(
                                    'iperf -c {} -t {}'.format(
                                        hs.IP(), str(Ex_seconds)))
                                print 'Client %s -> Server %s' % (hc.name,
                                                                  hs.name)
                        break  #only one server
                fobj.write('Monitoring output for %d seconds\n' % Mo_seconds)
                endTime = time() + Mo_seconds
                for h, line in pmonitor(popens, timeoutms=500):
                    if h:
                        fobj.write('%s %s: %s' % (h[0].name, h[1], line))
                    if time() >= endTime:
                        for p in popens.values():
                            p.send_signal(SIGINT)
                network.stop()
                fobj.write('\n@Test for topology "%s" ends.\n' % topo_name)
                fobj.close()
示例#14
0
 def get_consumed_events(self, expected_number):
     from mininet.util import pmonitor
     events = []
     log = FuseKafkaLog()
     popens = {}
     popens[self.client] = self.consumer
     for host, line in pmonitor(popens):
         self.consumer.poll()
         events.append(log.load_fuse_kafka_event(line))
         if len(events) >= expected_number:
             break
     self.assertEqual(expected_number, len(events))
     return events
示例#15
0
def httpTest( N=2 ):
    "Run pings and monitor multiple hosts using pmonitor"

    ## SET LOGGING AND CLEANUP PREVIOUS MININET STATE, IF ANY
    lg.setLogLevel('info')
    cleanup()

    ## INSTEAD OF RUNNING PYRETIC HUB, UNCOMMENT LINE 
    ## TO SEE THAT THIS WORKS FINE WHEN RUNNING REFERENCE CONTROLLER
#    call('controller ptcp: &', shell=True)

    ## SET UP TOPOLOGY
    topo = LinearTopo( N )        ## (tcp parse) warning TCP data offset too long or too short
#    topo = SingleSwitchTopo( N ) ## SILENT STALL


    ## SET UP MININET INSTANCE AND START
    net = Mininet( topo, switch=OVSKernelSwitch, host=Host, controller=RemoteController )
    net.start()

    print "Starting test..."

    ## GET THE HOST AND SERVER NAMES
    hosts = net.hosts
    client = hosts[ 0 ]
    server = hosts[ 1 ]
    
    ## DICTS FOR USE W/ PMONITOR
    spopens = {}
    cpopens = {}

    ## WARMUP SERVER 
    spopens[server] = server.popen('python', '-m', 'SimpleHTTPServer', '80')
    sleep(1)

    ## CLIENT REQUEST
    cpopens[client] = client.popen('wget', '-O', '-', server.IP(), stdout=PIPE, stderr=STDOUT)

    ## MONITOR OUTPUT
    for h, line in pmonitor( cpopens, timeoutms=5000 ):
        if h and line:
            print '%s: %s' % ( h.name, line ),

    ## TO USE THE COMMAND LINE INTERFACE, BEFORE FINISHING, UNCOMMENT
#    CLI( net )

    ## SHUTDOWN SERVER
    spopens[server].send_signal( SIGINT )
    
    ## SHUTDOWN MININET
    net.stop()
示例#16
0
文件: execute_mn.py 项目: hyunW3/3-2
def runMininet():
    Cleanup.cleanup()  #Cleaning up the Mininet before start

    "You can change the bottleneck link property by modifing these parameter"
    myTopo = Assignment3Topo(bw_v=10, delay_v="10ms",
                             loss_v=0)  #make test network topology
    net = Mininet(topo=myTopo, link=TCLink)  #make Mininet instance
    net.start()  #start Mininet

    "Get Host and host's ip address"
    hosts = net.hosts
    print("Starting test...")
    receiver = hosts[0]
    sender = hosts[1]
    recvAddr = receiver.IP()
    sendAddr = sender.IP()

    "Get parameter to run the test"
    windowSize = int(sys.argv[1])
    srcFilename = sys.argv[2]
    dstFilename = sys.argv[3]

    "execute ping for establish switching table"
    net.pingAll(timeout="30ms")  #This code must not be removed

    "If you want to test with ping and iperf, uncomment this"
    """
    net.pingFull([receiver,sender])
    net.iperf([receiver,sender],seconds=10)
    """

    popens = {}
    "If your code is python, uncomment this"
    """
    popens[receiver] = receiver.popen('python3','receiver.py')
    popens[sender] = sender.popen('python3','sender.py',recvAddr, str(windowSize), srcFilename, dstFilename)
    """

    endTime = time() + 180  #after 3 minutes mininet test will be shut

    "If sender or receiver print something, pmonitor will let you to see it"
    for h, line in pmonitor(popens, timeoutms=500):
        if h:
            print('<%s>: %s' % (h.name, line))  #,
        if time() >= endTime:
            for p in popens.values():
                p.send_signal(SIGINT)
    net.stop()  #stop Mininet

    print("Testing fininshed")
def testPing(net, node1, node2):
    print "\n\n#############################################"
    print "######## Pinging between %s and %s ##########" % (node1, node2)
    print "#############################################\n"

    popens = {}
    srcH, dstH = net.get(node1, node2)

    numberOfPings = 5

    popens[dstH] = srcH.popen("ping -c5 %s" % dstH.IP())
    aux = 1
    for h, line in pmonitor(popens):
        if (h):
            print line,
示例#18
0
    def send_and_rcv_traffic(self,
                             source_host,
                             recv_hosts,
                             mcast_group,
                             timeout=15):
        """
        This method will start multicast traffic from the source to all other hosts listed.
        :param source_host:
        :param recv_hosts:
        :return: if 0 packets were lost and no issues were found.
        """
        results = {}
        for host in recv_hosts:
            results[host] = False

        if (not isinstance(recv_hosts, list)):
            recv_hosts = [recv_hosts]

        source_host = self.mininet.nameToNode[source_host]

        sip = source_host.IP()

        recv_threads = {}
        for host in recv_hosts:
            h = self.mininet.nameToNode[host]
            recv_threads[h] = self.rx_traffic(h, mcast_group[0:-3], sip)

        self.logger.info('<%s>: %s' % (source_host.name, source_host.pid))

        self.tx_traffic(source_host, mcast_group[0:-3])

        start_time = time()
        for h, line in pmonitor(recv_threads):  #, timeoutms=500):

            if h:
                self.logger.info('<%s>: %s' % (h.name, line))
                if "lost: 0 dups: 0 out of order: 0" in line:
                    results[h.name] = True

            time_running = time() - start_time
            if time_running > timeout:
                break

        success = True
        for boolean in results.values():
            success = success and boolean

        return success, results
示例#19
0
文件: fattree.py 项目: vmehmeri/SDN
def runPingTest(net, topo, servers, clients):
	"""
	Rung concurrent ping tests for delay measurement
	:param net: mininet network
	:param topo: mininet topology
	:return:
	"""

	"""
	====================== CLIENTS AND SERVERS IN THE SAME POD ==========================
	"""
	
	logger.info(">>> Starting PING test for servers and clients in the same pod")

	popens = {}
	
	#Start PING 
	for index in range(0, len(clients)):
		clientHost = net.get(topo.hostList[clients[index]])
		serverHost = net.get(topo.hostList[servers[index]])
		logger.debug("%s --> %s" %(clientHost.IP(), serverHost.IP()))
		popens[index] = clientHost.popen('ping -q -n -c 6 %s >> results/%s_ping_results_same_pod ' %(serverHost.IP(), FILE_PREFIX), shell=True)
				
	logger.debug(">>> Waiting for PING test to finish...")
	
	for host, line in pmonitor( popens ):
		if host:
			logger.debug( "<%s>: %s" % ( host, line.strip() ) )
			
	"""
	====================== CLIENTS AND SERVERS IN DIFFERENT PODS ==========================
	"""
	
	# k must be even!
	logger.info(">>> Starting PING test for servers and clients in different pods")
	
	popens = {}
	
	#Start PING
	for index in range(0, len(clients)):
		clientHost = net.get(topo.hostList[clients[index]])
		serverHost = net.get(topo.hostList[servers[len(clients) - 1 - index]])
		logger.debug("%s --> %s" %(clientHost.IP(), serverHost.IP()))
		popens[index] = clientHost.popen('ping -q -n -c 6 %s >> results/%s_ping_results_different_pod ' %(serverHost.IP(), FILE_PREFIX), shell=True)
			
	logger.debug("Waiting for PING test to finish...")
	
	monitorOutput(popens, 300)
示例#20
0
def test():
    os.system('mn -c')
    #os.system code goes here
    os.system('sysctl -w net.ipv4.tcp_congestion_control=cubic')
    os.system('sysctl -w net.ipv4.tcp_sack=0')
    #os.system('sysctl -w net.ipv4.tcp_reordering=31')
    #Note that the configuration in this python script will affect mininet.
    #Therefore, please make sure that you restore the configuration to the default value.
    switch = OVSKernelSwitch
    topo = SingleSwitchTopo(0)
    network = Mininet(topo=topo,
                      host=CPULimitedHost,
                      link=TCLink,
                      switch=switch)
    network.start()
    #CLI(network)
    #If you want to implement your assignment on the command line, use CLI(network).
    #CLI description can be found at
    #   http://mininet.org/walkthrough/#part-3-mininet-command-line-interface-cli-commands
    #Or use popen features to trigger the system calls on specific hosts.
    #popen description can be found at
    #   https://docs.python.org/2/library/subprocess.html
    #hl = network.hosts[0]
    #hr = network.hosts[2]

    hl = network.get('hl')
    hr = network.get('hr')
    #ht = network.get('ht')
    #print hl.name
    #print hr.name

    popens = {}
    hl.popen("iperf -s")
    popens[hr] = hr.popen("iperf -c " + hl.IP() + " -t 120")
    #hl.popen("iperf -s -u")
    #popens[ht] = ht.popen("iperf -c "+ hl.IP() + " -t 120" + " -u -b 20m")
    print "Monitoring output for"
    for h, line in pmonitor(popens, timeoutms=5000):
        if h:
            print '%s: %s' % (h.name, line)

#output =network.hosts[0].popen("iperf -s")
#print output
#output =network.hosts[1].popen("iperf -c 10.0.0.2")
#print output
#popens = {}

    network.stop()
示例#21
0
def testMonitorSimple(net, n = 3, seconds = 10):
    hosts = net.hosts
    server = hosts[0]
    popens = {}
    for h in hosts:
        popens[h] = h.popen('ping', server.IP())

    print 'Monitoring output for', seconds, 'seconds'
    endTime = time() + seconds
    for h, line in pmonitor(popens, timeoutms = 500):
        if h:
            print '%s: %s' % (h.name, line)
        if time() >= endTime:
            for proc in popens.values():
                proc.send_signal(SIGINT)
    net.stop()
示例#22
0
def encryptionTest(link_obj, encryption=True):
    "Create a client server network and do a simple security test"
    topo = ClientServerTopo(link_obj)
    net = Mininet(topo=topo, 
                  host=CPULimitedHost, link=TCLink)
    print "Conducting encryptionTest between client and server for a %s link" % link_obj
    net.start()
    print "Dumping host connections"
    dumpNodeConnections(net.hosts)
    print "Conducting ze test"
    client, server = net.get('h1', 's1')
    procs = {}
    print "Executing server process on %s" % server.name
    if encryption:
        procs[server] = server.popen([sys.executable, '/home/mininet/minerva/src/minerva/server/server.py', str(server.IP())])
    else:
        procs[server] = server.popen([sys.executable, 
                                  '/home/mininet/minerva/src/minerva/server/server.py', 
                                  str(server.IP()), 
                                      'False'])
    #sleep to ensure that the server is running before we execute the client
    time.sleep(2)
    print "Executing client process on %s" % client.name
    if encryption:
        log_file = link_obj.__str__() + "_" + 'encryption'
        procs[client] = server.popen([sys.executable, 
                                      '/home/mininet/minerva/src/minerva/tests/client_tests.py', 
                                      str(server.IP()),
                                      log_file])
    else:
        log_file = link_obj.__str__() + "_" + 'noencryption'
        procs[client] = server.popen([sys.executable, 
                                  '/home/mininet/minerva/src/minerva/tests/client_tests.py', 
                                  str(server.IP()),
                                  log_file,
                                      'False'])
        
    for h, line in pmonitor(procs, timeoutms=500):
        if h is None:
            break
    #wait for the processes to get their work done
    time.sleep(2)
    #the client is done. I keeel the server!
    print "Cleaning up"
    for p in procs.values():
        p.send_signal(SIGKILL)
    net.stop()
示例#23
0
def monitorhosts( hosts=5 ):
    "Start a bunch of pings and monitor them using popen"
    mytopo = SingleSwitchTopo( hosts )
    net = Mininet( topo=mytopo, waitConnected=True )
    net.start()
    # Start a bunch of pings
    popens = {}
    last = net.hosts[ -1 ]
    for host in net.hosts:
        popens[ host ] = host.popen( "ping -c5 %s" % last.IP() )
        last = host
    # Monitor them and print output
    for host, line in pmonitor( popens ):
        if host:
            info( "<%s>: %s" % ( host.name, line ) )
    # Done
    net.stop()
示例#24
0
def bandwidthTest(link_obj, n_clients, iteration):
    """Create a client server network and check bandwidth by launching
    n_clients number of clients.
    """
    topo = SingleSwitchTopo(n_clients, link_obj, .5)
    net = Mininet(topo=topo, 
                  host=CPULimitedHost, 
                  link=TCLink,
                  controller=Pox)
    print "Conducting bandwidthTest between clients and server for a %s link" % link_obj
    root = connectToInternet(net)
    print "Dumping host connections"
    dumpNodeConnections(net.hosts)
    print "Conducting ze test"
    clients = []
    for i in range(1, n_clients + 1):
        clients.append(net.get('h' + str(i)))
    server = net.get('s1')
    procs = {}
    print "Executing server process on %s" % server.name
    procs[server] = server.popen([sys.executable, 
                                  '/home/mininet/minerva/src/minerva/server/server.py', 
                                  str(server.IP())])
    #sleep to ensure that the server is running before we execute the clients
    time.sleep(2)
    for client in clients:
        print "Executing client process on %s" % client.name
        log_file = link_obj.__str__() + "_" + 'bandwidth' + '_' + str(n_clients) \
        + '_iteration' + str(iteration)
        procs[client] = server.popen([sys.executable, 
                                      '/home/mininet/minerva/src/minerva/tests/client_tests_binary.py', 
                                      str(server.IP()),
                                      log_file])
        
    for h, line in pmonitor(procs, timeoutms=500):
        if h is None:
            break
    #wait for the processes to get their work done
    time.sleep(100)
    #the client is done. I keeel the server!
    print "Cleaning up"
    for p in procs.values():
        p.send_signal(SIGKILL)
    stopNAT(root)
    net.stop()
示例#25
0
def monitorhosts(hosts=5, sched='cfs'):
    "Start a bunch of pings and monitor them using popen"
    mytopo = SingleSwitchTopo(hosts)
    cpu = .5 / hosts
    myhost = custom(CPULimitedHost, cpu=cpu, sched=sched)
    net = Mininet(topo=mytopo, host=myhost)
    net.start()
    # Start a bunch of pings
    popens = {}
    last = net.hosts[-1]
    for host in net.hosts:
        popens[host] = host.popen("ping -c5 %s" % last.IP())
        last = host
    # Monitor them and print output
    for host, line in pmonitor(popens):
        if host:
            print(("<%s>: %s" % (host.name, line.strip())))
    # Done
    net.stop()
示例#26
0
def dumpHost(popens, exec_time):
    beg_time = time.time()

    for host, line in pmonitor(popens):
        if host and line.strip() != '':
            if re.match("Avg", line.strip()) != None:
                print "<%s>: %s" % (host.name, line.strip())
            if re.match("transmission throughput", line.strip()) != None:
                print "<%s>: %s" % (host.name, line.strip())

            sys.stdout.flush()

            if re.match("CLIENT STOP", line.strip()) != None:
                print "<%s>: %s" % (host.name, line.strip())
                print
                sys.stdout.flush()
                return
        if time.time() - beg_time > exec_time:
            return
示例#27
0
文件: popen.py 项目: jhall11/mininet
def monitorhosts( hosts=5, sched='cfs' ):
    "Start a bunch of pings and monitor them using popen"
    mytopo = SingleSwitchTopo( hosts )
    cpu = .5 / hosts
    myhost = custom( CPULimitedHost, cpu=cpu, sched=sched )
    net = Mininet( topo=mytopo, host=myhost )
    net.start()
    # Start a bunch of pings
    popens = {}
    last = net.hosts[ -1 ]
    for host in net.hosts:
        popens[ host ] = host.popen( "ping -c5 %s" % last.IP() )
        last = host
    # Monitor them and print output
    for host, line in pmonitor( popens ):
        if host:
            print( "<%s>: %s" % ( host.name, line.strip() ) )
    # Done
    net.stop()
示例#28
0
def pmonitorTest( N=3, seconds=10 ):
    "Run pings and monitor multiple hosts using pmonitor"
    topo = SingleSwitchTopo( N )
    net = Mininet( topo )
    net.start()
    hosts = net.hosts
    print "Starting test..."
    server = hosts[ 0 ]
    popens = {}
    for h in hosts:
        popens[ h ] = h.popen('ping', server.IP() )
    print "Monitoring output for", seconds, "seconds"
    endTime = time() + seconds
    for h, line in pmonitor( popens, timeoutms=500 ):
        if h:
            print '%s: %s' % ( h.name, line ),
        if time() >= endTime:
            for p in popens.values():
                p.send_signal( SIGINT )
    net.stop()
示例#29
0
def pmonitorTest(N=3, seconds=10):
    "Run pings and monitor multiple hosts using pmonitor"
    topo = SingleSwitchTopo(N)
    net = Mininet(topo)
    net.start()
    hosts = net.hosts
    print "Starting test..."
    server = hosts[0]
    popens = {}
    for h in hosts:
        popens[h] = h.popen('ping', server.IP())
    print "Monitoring output for", seconds, "seconds"
    endTime = time() + seconds
    for h, line in pmonitor(popens, timeoutms=500):
        if h:
            print '<%s>: %s' % (h.name, line),
        if time() >= endTime:
            for p in popens.values():
                p.send_signal(SIGINT)
    net.stop()
示例#30
0
def Test2():
    print "Beginning Test 2: Testing whether UDP packets from Internet get dropped"
    topo = MyTopo(2)
    net = Mininet(topo, controller=RemoteController)

    net.start()

    leftHost = net['h1']
    rightHost = net['h2']
    switch = net['s3']

    popens = {}
    popens[leftHost] = leftHost.popen('iperf -s -u')
    popens[rightHost] = rightHost.popen('iperf -c 10.0.0.1 -u')

    seconds = 20
    endTime = time() + seconds
    num = 0
    output_3 = ''
    
    for h, line in pmonitor(popens, timeoutms=1000 ):
        if h:
 	    output_3 += line
            num += 1
 	  
        if time() >= endTime:
            for p in popens.values():
                p.send_signal( SIGINT )


    #print output_3
    if num > 15:
	print "Test 1 Failed"

#    if output_3.find('Server Report') != -1:
#            print "Test 2 Failed"
    else:
            print "Test 2 Passed"
 
    net.stop()	
    print "-------------------------------------------------"
示例#31
0
def pre_test(net):

    print "Waiting for the controller to complete handshake..."
    sleep(5)

    popens = {}
    hosts = net.hosts

    print "Flow 1: h0 starting to ping h6..."
    popens[hosts[0]] = hosts[0].popen('ping', hosts[6].IP())
    sleep(1)
    print "Flow 2: h1 starting to ping h7..."
    popens[hosts[1]] = hosts[1].popen('ping', hosts[7].IP())

    endTime = time() + 10
    for h, line in pmonitor( popens, timeoutms=500 ):
        if h:
           print 'Flow %d: %s' % ( hosts.index(h) + 1, line ),
        if time() >= endTime:
           for p in popens.values():
             p.send_signal( SIGINT )
示例#32
0
 def test_untagged(self):
     first_host = self.net.hosts[0]
     second_host = self.net.hosts[1]
     mirror_host = self.net.hosts[2]
     mirror_mac = mirror_host.MAC()
     tcpdump_filter = 'not ether src %s and icmp' % mirror_mac
     tcpdump_out = mirror_host.popen(
         'timeout 10s tcpdump -n -v -c 2 -U %s' % tcpdump_filter)
     # wait for tcpdump to start
     time.sleep(1)
     popens = {mirror_host: tcpdump_out}
     first_host.cmd('ping -c1  %s' % second_host.IP())
     tcpdump_txt = ''
     for host, line in pmonitor(popens):
         if host == mirror_host:
             tcpdump_txt += line.strip()
     self.assertFalse(tcpdump_txt == '')
     self.assertTrue(re.search(
         '%s: ICMP echo request' % second_host.IP(), tcpdump_txt))
     self.assertTrue(re.search(
         '%s: ICMP echo reply' % first_host.IP(), tcpdump_txt))
示例#33
0
def pre_test(net):

    print "Waiting for the controller to complete handshake..."
    sleep(5)

    popens = {}
    hosts = net.hosts

    print "Flow 1: h0 starting to ping h6..."
    popens[hosts[0]] = hosts[0].popen('ping', hosts[6].IP())
    sleep(1)
    print "Flow 2: h1 starting to ping h7..."
    popens[hosts[1]] = hosts[1].popen('ping', hosts[7].IP())

    endTime = time() + 10
    for h, line in pmonitor(popens, timeoutms=500):
        if h:
            print 'Flow %d: %s' % (hosts.index(h) + 1, line),
        if time() >= endTime:
            for p in popens.values():
                p.send_signal(SIGINT)
示例#34
0
 def test_untagged(self):
     first_host = self.net.hosts[0]
     second_host = self.net.hosts[1]
     mirror_host = self.net.hosts[2]
     mirror_mac = mirror_host.MAC()
     tcpdump_filter = 'not ether src %s and icmp' % mirror_mac
     tcpdump_out = mirror_host.popen(
         'timeout 10s tcpdump -n -v -c 2 -U %s' % tcpdump_filter)
     # wait for tcpdump to start
     time.sleep(1)
     popens = {mirror_host: tcpdump_out}
     first_host.cmd('ping -c1  %s' % second_host.IP())
     tcpdump_txt = ''
     for host, line in pmonitor(popens):
         if host == mirror_host:
             tcpdump_txt += line.strip()
     self.assertFalse(tcpdump_txt == '')
     self.assertTrue(re.search(
         '%s: ICMP echo request' % second_host.IP(), tcpdump_txt))
     self.assertTrue(re.search(
         '%s: ICMP echo reply' % first_host.IP(), tcpdump_txt))
示例#35
0
def run_ping(args, net):
    hosts = net.hosts[::]
    random.shuffle(hosts)  # Pick random pairs of hosts
    assert len(hosts) % 2 == 0
    senders, receivers = hosts[:len(hosts) / 2], hosts[len(hosts) / 2:]
    cmd_t = Template("ping -c 1 $h")
    print("starting %d pings" % len(senders))
    popens = {}
    for s, r in zip(senders, receivers):
        debug("sender: %s, receiver: %s (%s)\n" % (s.name, r.name, r.IP()))
        cmd = cmd_t.substitute(h=r.name, ).split(" ")
        popens[s] = s.popen(cmd)
    print("monitoring for %d seconds" % (args.ttl + 3))
    end_at = time.time() + args.ttl + 3
    results = {h: 0 for h in hosts}
    for h, line in pmonitor(popens, timeoutms=500):
        debug("%s: '%s'\n" % (str(h), line.strip()))
        if h and line.strip():
            results[h] = line.strip()
        if time.time() > end_at:
            break
    for p in popens.values():
        p.send_signal(SIGINT)
    vals = []
    pprint(results)
    for s, r in zip(senders, receivers):
        assert s in results
        vals = results[s].split(" = ").split(" ")[0]
        rmin, ravg, rmax, rmdev = vals.split("/")
        vals.append(rmin)  # they're all the same because we only ping once
    summary = collections.OrderedDict()
    keys = list(rows[0].keys())
    summary["min"] = min(vals)
    summary["avg"] = sum(vals) / float(len(vals))
    summary["max"] = max(vals)
    summary["mdev"] = math.sqrt(
        sum((v - summary["avg"])**2 for v in vals) / len(vals))
    print("-" * 80)
    print_rows([summary])
    return summary
    def runLoadtest(self, sHost=None, cHost=None, nIperfs=4):
        if not sHost:
            sHost = sorted(self.hostmap.items())[0][1]
        if not cHost:
            cHost = sorted(self.hostmap.items())[-1][1]
        dt = 5
        ct = 20
        output("*** Throughput test between %s and %s\n" %
               (sHost.name, cHost.name))
        popens = {}
        # Start iperf server
        server = sHost.popen("iperf -f k -s -p 5001, -P %d" % nIperfs)
        popens['server'] = server
        output(
            "  * This should take at least %d seconds (possibly much longer!)\n"
            % (dt * nIperfs + ct))
        # Start iperf clients
        output("    - Starting flows [%s]" % (" " * nIperfs))
        for i in xrange(1, nIperfs + 1):
            output("%s=%s]" % ("\b" * (nIperfs - i + 2), " " * (nIperfs - i)))
            popens[str(i)] = cHost.popen("iperf -f k -c %s -p 5001 -t %d" %
                                         (sHost.IP(), dt * (nIperfs - i) + ct))
            if i < nIperfs:
                sleep(dt)
        output("\n    - Waiting for flows to terminate...\n")
        # Monitor output
        cout = {}
        sout = ''
        for n, line in pmonitor(popens):
            if n:
                if n == 'server':
                    sout = line.strip()
                else:
                    cout[n] = line.strip()

        output("  * Format:  [ ID] Interval       Transfer     Bandwidth\n")
        for c in sorted(cout.keys()):
            output("  * Flow %2s: %s\n" % (c, cout[c]))
        output("*** Summary: %s\n" % sout)
示例#37
0
def Test4():
    print "Beginning Test 4: Testing whether TCP connection initiated from CS can go through"
    topo = MyTopo(2)
    net = Mininet(topo, controller=RemoteController)

    net.start()
    leftHost = net['h1']
    rightHost = net['h2']
    switch = net['s3']
	
    popens = {}

    popens[rightHost] = rightHost.popen('iperf -s -p 80')
    popens[leftHost] = leftHost.popen('iperf -c 10.0.0.2 -p 80')    

    seconds = 20
    endTime = time() + seconds   
    
    output_2 = ''
    for h, line in pmonitor(popens, timeoutms=1000 ):
        if h:
	  output_2 += line 
		  
        if time() >= endTime:
		for p in popens.values():
			p.send_signal( SIGINT )

    
    #print output_2
    k = _parseIperf(output_2)
    m = parse_iperf(output_2)
    if k != '' and m == [] :
		print "Test 4 passed"
    else:
		print "Test 4 failed"

    #print "Test 4 ends here----------------------------------------------------"
    print "------------------------------------------------------"
    net.stop()
示例#38
0
def Test5():
    print "Beginning Test 5: Testing whether SSH packets from Internet get dropped"
    topo = MyTopo(2)
    net = Mininet(topo, controller=RemoteController)
    #, controller=RemoteController)

    net.start()
    leftHost = net['h1']
    rightHost = net['h2']
    switch = net['s3']
	
    popens = {}

    popens[leftHost] = leftHost.popen('iperf -s -p 22')
    popens[rightHost] = rightHost.popen('iperf -c 10.0.0.1 -p 22')

    seconds = 20
    endTime = time() + seconds   
    output_4 = ''
    
    for h, line in pmonitor(popens, timeoutms=10000 ):
        if h:
 	  output_4 += line 
		  
        if time() >= endTime:
		for p in popens.values():
			p.send_signal( SIGINT )

    
    #print "out:", output_4 
    k = _parseIperf(output_4)
    #print "k", k
    if k == '':
        print "Test 5 Passed"
    else:
        print "Test 5 Failed"
    net.stop()
    print "------------------------------------------------------"
示例#39
0
    def start_tunnel():
        print("Starting udp_tunnel...")

        tun = {}
        tun[h1] = h1.popen(
            '{} --local_ip {} --remote_ip {} --tunnel_ip 10.0.1.1'.format(
                tunnel_binary, h1.IP(), h2.IP()),
            stderr=sys.stdout.fileno())

        tun[h2] = h2.popen(
            '{} --local_ip {} --remote_ip {} --tunnel_ip 10.0.1.2'.format(
                tunnel_binary, h2.IP(), h1.IP()),
            stderr=sys.stdout.fileno())

        for host, line in pmonitor(tun):
            if host:
                print("<{}>: {}".format(host.name, line.strip()))
                sys.stdout.flush()
            if finished:
                tun[h1].kill()
                tun[h2].kill()
                break
        print("udp_tunnel thread finished.")
示例#40
0
def demo():
    "Rogue Webdd server demonstration"
    #checkRequired()
    topo = BeforeBandwidthTestHubDemo()
    net = Mininet(topo=topo,
                  controller=lambda name: RemoteController(
                      name='c0', ip='192.168.56.104'),
                  link=TCLink,
                  switch=OVSKernelSwitch,
                  autoSetMacs=True)

    popens = {}
    server = net.get('h4')

    net.start()
    # (Bandidth before Apply Traffic Priorization)
    popens[server] = server.popen('iperf -s -p 5002 &')
    for client in net.hosts:

        if client.name != server.name:
            print client.name
            popens[client] = client.popen('iperf -c ' + server.IP() +
                                          ' -p 5002')

    try:
        for host, line in util.pmonitor(popens):
            if host:
                print(host.name, line)

    finally:
        # Don't leave things running if this script crashes.
        for process in popens.values():
            if not process.poll():
                process.kill()

    net.stop()
示例#41
0
numberOfAvailableHosts = 0
hostIpAddresses = []
for host in hostList:
    if host['available']:
        numberOfAvailableHosts += 1
        hostIpAddresses.append(host['ip'])

print " Running benchmark on root node ..."
jobServer = rootNode
popens = {}
jobServerCommand = JOB_SERVER_COMMAND + str(numberOfAvailableHosts) + " "
for ipAddress in hostIpAddresses:
    jobServerCommand += ipAddress + " "
# print "jobServerCommand = " + jobServerCommand
jobServerCommand = jobServerCommand[:-1]  # delete trailing space
popens[jobServer] = jobServer.popen(str(jobServerCommand))
benchmarkResultsFile = open(BENCHMARK_RESULTS_FILE_NAME, "w")
for host, line in pmonitor(popens, timeoutms=500):
    if host:
        benchmarkResultsFile.write(line)
        # print line,
        if len(line) == 0:
            break
print "Benchmark done. Results saved to '" + BENCHMARK_RESULTS_FILE_NAME + "'."
print

print "Stopping network..."
virtualNetwork.stop()
print "Network stopped."
print
numberOfAvailableHosts = 0
hostIpAddresses = []
for host in hostList:
	if host['available']:
		numberOfAvailableHosts += 1
		hostIpAddresses.append(host['ip'])

print " Running benchmark on root node ..."
jobServer = rootNode
popens = {}
jobServerCommand = JOB_SERVER_COMMAND + str(numberOfAvailableHosts) + " "
for ipAddress in hostIpAddresses:
	jobServerCommand += ipAddress + " "
# print "jobServerCommand = " + jobServerCommand
jobServerCommand = jobServerCommand[:-1] # delete trailing space
popens[jobServer] = jobServer.popen(str(jobServerCommand))
benchmarkResultsFile = open(BENCHMARK_RESULTS_FILE_NAME, "w")
for host, line in pmonitor(popens, timeoutms=500):
	if host:
		benchmarkResultsFile.write(line)
		# print line,
		if len(line) == 0:
			break
print "Benchmark done. Results saved to '" + BENCHMARK_RESULTS_FILE_NAME + "'."
print

print "Stopping network..."
virtualNetwork.stop()
print "Network stopped."
print
示例#43
0
#!/usr/bin/python
"""
This example monitors a number of hosts using host.popen() and
pmonitor()
"""

from mininet.net import Mininet
from mininet.node import CPULimitedHost
from mininet.topo import SingleSwitchTopo
from mininet.log import setLogLevel
from mininet.util import custom, pmonitor


def monitorhosts(hosts=5, sched='cfs'):
    "Start a bunch of pings and monitor them using popen"
    mytopo = SingleSwitchTopo(hosts)
    cpu = .5 / hosts
    myhost = custom(CPULimitedHost, cpu=cpu, sched=sched)
    net = Mininet(topo=mytopo, host=myhost)
    net.start()
    # Start a bunch of pings
    popens = {}
    last = net.hosts[-1]
    for host in net.hosts:
        popens[host] = host.popen("ping -c5 %s" % last.IP())
        last = host
    # Monitor them and print output
    for host, line in pmonitor(popens):
        if host:
            print(("<%s>: %s" % (host.name, line.strip())))
    # Done
示例#44
0
def complexNobelEu():

    if len(sys.argv) < 3:
        info( '*** Specify time [s] of simulation and lambda for poisson generators (requests/60s)! --> python complex-nobel-eu-script.py <time> <lambda>...\n')
        return

    simulationTime = int(sys.argv[1])
    lam = float(sys.argv[2])

    info( '*** Starting controller...\n')
    cmd = "java -jar target/floodlight.jar -cf /home/sszwaczyk/WAT/PhD/impl/floodlight/scenarios/complex-nobel-eu/mininet/floodlightdefault.properties"
    proc = subprocess.Popen(cmd.split(), cwd='/home/sszwaczyk/WAT/PhD/impl/floodlight')

    info( '*** Sleep 5 seconds to let controller start...\n')
    sleep(5)

    net = Mininet( topo=None,
                   build=False,
                   ipBase='10.0.0.0/24',
                   autoSetMacs=True,
                   autoStaticArp=True,
                   host=CPULimitedHost)

    info( '*** Adding controller\n' )
    c0=net.addController(name='c0',
                         controller=RemoteController,
                         ip='127.0.0.1',
                         protocol='tcp',
                         port=6653)

    info( '*** Add switches\n')
    glasgow = net.addSwitch( 'glasgow', dpid='00:00:00:00:00:00:00:01' )
    dublin = net.addSwitch( 'dublin', dpid='00:00:00:00:00:00:00:02' )
    london = net.addSwitch( 'london', dpid='00:00:00:00:00:00:00:03' )
    amsterdam = net.addSwitch( 'amsterdam', dpid='00:00:00:00:00:00:00:04' )
    brussels = net.addSwitch( 'brussels', dpid='00:00:00:00:00:00:00:05' )
    paris = net.addSwitch( 'paris', dpid='00:00:00:00:00:00:00:06' )
    bordeaux = net.addSwitch( 'bordeaux', dpid='00:00:00:00:00:00:00:07' )
    madrid = net.addSwitch( 'madrid', dpid='00:00:00:00:00:00:00:08' )
    barcelona = net.addSwitch( 'barcelona', dpid='00:00:00:00:00:00:00:09' )
    lyon = net.addSwitch( 'lyon', dpid='00:00:00:00:00:00:00:10' )
    hamburg = net.addSwitch( 'hamburg', dpid='00:00:00:00:00:00:00:11' )
    frankfurt = net.addSwitch( 'frankfurt', dpid='00:00:00:00:00:00:00:12' )
    strasbourg = net.addSwitch( 'strasbourg', dpid='00:00:00:00:00:00:00:13' )
    zurich = net.addSwitch( 'zurich', dpid='00:00:00:00:00:00:00:14' )
    milan = net.addSwitch( 'milan', dpid='00:00:00:00:00:00:00:15' )
    oslo = net.addSwitch( 'oslo', dpid='00:00:00:00:00:00:00:16' )
    copenhagen = net.addSwitch( 'copenhagen', dpid='00:00:00:00:00:00:00:17' )
    berlin = net.addSwitch( 'berlin', dpid='00:00:00:00:00:00:00:18' )
    munich = net.addSwitch( 'munich', dpid='00:00:00:00:00:00:00:19' )
    prague = net.addSwitch( 'prague', dpid='00:00:00:00:00:00:00:20' )
    vienna = net.addSwitch( 'vienna', dpid='00:00:00:00:00:00:00:21' )
    zagreb = net.addSwitch( 'zagreb', dpid='00:00:00:00:00:00:00:22' )
    rome = net.addSwitch( 'rome', dpid='00:00:00:00:00:00:00:23' )
    stockholm = net.addSwitch( 'stockholm', dpid='00:00:00:00:00:00:00:24' )
    warsaw = net.addSwitch( 'warsaw', dpid='00:00:00:00:00:00:00:25' )
    budapest = net.addSwitch( 'budapest', dpid='00:00:00:00:00:00:00:26' )
    belgrade = net.addSwitch( 'belgrade', dpid='00:00:00:00:00:00:00:27' )
    athens = net.addSwitch( 'athens', dpid='00:00:00:00:00:00:00:28' )

    info( '*** Add hosts\n')
    hostsNumber = 21
    userOneHost = net.addHost( 'User1', cls=Host, ip='10.0.0.101/24', cpu=.1/hostsNumber )
    userTwoHost = net.addHost( 'User2', cls=Host, ip='10.0.0.102/24', cpu=.1/hostsNumber )
    userThreeHost = net.addHost( 'User3', cls=Host, ip='10.0.0.103/24', cpu=.1/hostsNumber )
    userFourHost = net.addHost( 'User4', cls=Host, ip='10.0.0.104/24', cpu=.1/hostsNumber )
    userFiveHost = net.addHost( 'User5', cls=Host, ip='10.0.0.105/24', cpu=.1/hostsNumber )
    userSixHost = net.addHost( 'User6', cls=Host, ip='10.0.0.106/24', cpu=.1/hostsNumber )
    userSevenHost = net.addHost( 'User7', cls=Host, ip='10.0.0.107/24', cpu=.1/hostsNumber )

    httpLsHost = net.addHost( 'HTTP_LS', cls=Host, ip='10.0.0.1/24', cpu=.1/hostsNumber )
    httpLrHost = net.addHost( 'HTTP_LR', cls=Host, ip='10.0.0.2/24', cpu=.1/hostsNumber )
    httpSsHost = net.addHost( 'HTTP_SS', cls=Host, ip='10.0.0.3/24', cpu=.1/hostsNumber )
    httpSrHost = net.addHost( 'HTTP_SR', cls=Host, ip='10.0.0.4/24', cpu=.1/hostsNumber )
    httpSuHost = net.addHost( 'HTTP_SU', cls=Host, ip='10.0.0.5/24', cpu=.1/hostsNumber )

    info( '*** Add links\n')
    # Add links between switches
    net.addLink( glasgow, dublin, cls=TCLink ,  bw=10 )
    net.addLink( glasgow, amsterdam, cls=TCLink ,  bw=10 )

    net.addLink( dublin, london, cls=TCLink ,  bw=10 )

    net.addLink( london, amsterdam, cls=TCLink ,  bw=10 )
    net.addLink( london, paris, cls=TCLink ,  bw=10 )

    net.addLink( paris, brussels, cls=TCLink ,  bw=10 )
    net.addLink( paris, bordeaux, cls=TCLink ,  bw=10 )
    net.addLink( paris, strasbourg, cls=TCLink ,  bw=10 )
    net.addLink( paris, lyon, cls=TCLink ,  bw=10 )

    net.addLink( bordeaux, madrid, cls=TCLink ,  bw=10 )

    net.addLink( madrid, barcelona, cls=TCLink ,  bw=10 )

    net.addLink( barcelona, lyon, cls=TCLink ,  bw=10 )

    net.addLink( lyon, zurich, cls=TCLink ,  bw=10 )

    net.addLink( amsterdam, brussels, cls=TCLink ,  bw=10 )
    net.addLink( amsterdam, hamburg, cls=TCLink ,  bw=10 )

    net.addLink( brussels, frankfurt, cls=TCLink ,  bw=10 )

    net.addLink( hamburg, frankfurt, cls=TCLink ,  bw=10 )
    net.addLink( hamburg, berlin, cls=TCLink ,  bw=10 )

    net.addLink( frankfurt, strasbourg, cls=TCLink ,  bw=10 )
    net.addLink( frankfurt, munich, cls=TCLink ,  bw=10 )

    net.addLink( strasbourg, zurich, cls=TCLink ,  bw=10 )

    net.addLink( zurich, milan, cls=TCLink ,  bw=10 )

    net.addLink( milan, munich, cls=TCLink ,  bw=10 )
    net.addLink( milan, rome, cls=TCLink ,  bw=10 )

    net.addLink( oslo, stockholm, cls=TCLink ,  bw=10 )
    net.addLink( oslo, copenhagen, cls=TCLink ,  bw=10 )

    net.addLink( copenhagen, berlin, cls=TCLink ,  bw=10 )

    net.addLink( berlin, warsaw, cls=TCLink ,  bw=10 )
    net.addLink( berlin, prague, cls=TCLink ,  bw=10 )
    net.addLink( berlin, munich, cls=TCLink ,  bw=10 )

    net.addLink( munich, vienna, cls=TCLink ,  bw=10 )

    net.addLink( prague, vienna, cls=TCLink ,  bw=10 )
    net.addLink( prague, budapest, cls=TCLink ,  bw=10 )

    net.addLink( vienna, zagreb, cls=TCLink ,  bw=10 )

    net.addLink( zagreb, rome, cls=TCLink ,  bw=10 )
    net.addLink( zagreb, belgrade, cls=TCLink ,  bw=10 )

    net.addLink( rome, athens, cls=TCLink ,  bw=10 )

    net.addLink( stockholm, warsaw, cls=TCLink ,  bw=10 )

    net.addLink( warsaw, budapest, cls=TCLink ,  bw=10 )

    net.addLink( budapest, belgrade, cls=TCLink ,  bw=10 )

    net.addLink( belgrade, athens, cls=TCLink ,  bw=10 )

    # Add links to services
    net.addLink( frankfurt, httpLsHost, cls=TCLink , bw=10 )
    net.addLink( dublin, httpLrHost, cls=TCLink , bw=10 )
    net.addLink( copenhagen, httpSsHost, cls=TCLink , bw=10 )
    net.addLink( belgrade, httpSrHost, cls=TCLink , bw=10 )
    net.addLink( rome, httpSuHost, cls=TCLink , bw=10 )

    #Add links to users
    net.addLink( glasgow, userOneHost, cls=TCLink , bw=10 )
    net.addLink( hamburg, userTwoHost, cls=TCLink , bw=10 )
    net.addLink( warsaw, userThreeHost, cls=TCLink , bw=10 )
    net.addLink( zurich, userFourHost, cls=TCLink , bw=10 )
    net.addLink( lyon, userFiveHost, cls=TCLink , bw=10 )
    net.addLink( madrid, userSixHost, cls=TCLink , bw=10 )
    net.addLink( amsterdam, userSevenHost, cls=TCLink , bw=10 )

    info( '*** Starting network\n')
    net.build()

    info( '*** Starting switches\n')
    net.get('glasgow').start([c0])
    net.get('dublin').start([c0])
    net.get('london').start([c0])
    net.get('amsterdam').start([c0])
    net.get('brussels').start([c0])
    net.get('paris').start([c0])
    net.get('bordeaux').start([c0])
    net.get('madrid').start([c0])
    net.get('barcelona').start([c0])
    net.get('lyon').start([c0])
    net.get('hamburg').start([c0])
    net.get('frankfurt').start([c0])
    net.get('strasbourg').start([c0])
    net.get('zurich').start([c0])
    net.get('milan').start([c0])
    net.get('oslo').start([c0])
    net.get('copenhagen').start([c0])
    net.get('berlin').start([c0])
    net.get('munich').start([c0])
    net.get('prague').start([c0])
    net.get('vienna').start([c0])
    net.get('zagreb').start([c0])
    net.get('rome').start([c0])
    net.get('stockholm').start([c0])
    net.get('warsaw').start([c0])
    net.get('budapest').start([c0])
    net.get('belgrade').start([c0])
    net.get('athens').start([c0])

    info( '*** Sleep 15 seconds to let controller get topology...\n')
    sleep(15)

    popens = {}

    info( '*** Starting services\n')

    httpLsCommand = 'java -jar /home/sszwaczyk/WAT/PhD/impl/http-server/target/http-server-0.0.1-SNAPSHOT.jar --usersFile=/home/sszwaczyk/WAT/PhD/impl/floodlight/scenarios/complex-nobel-eu/users.json --servicesFile=/home/sszwaczyk/WAT/PhD/impl/floodlight/scenarios/complex-nobel-eu/mininet/services.json --logging.file=./http-ls.log --exitStatsFile=./http-ls-exit.xlsx'
    popens[httpLsHost] = httpLsHost.popen(httpLsCommand.split())

    httpLrCommand = 'java -jar /home/sszwaczyk/WAT/PhD/impl/http-server/target/http-server-0.0.1-SNAPSHOT.jar --usersFile=/home/sszwaczyk/WAT/PhD/impl/floodlight/scenarios/complex-nobel-eu/users.json --servicesFile=/home/sszwaczyk/WAT/PhD/impl/floodlight/scenarios/complex-nobel-eu/mininet/services.json --logging.file=./http-lr.log --exitStatsFile=./http-lr-exit.xlsx'
    popens[httpLrHost] = httpLrHost.popen(httpLrCommand.split())

    httpSsCommand = 'java -jar /home/sszwaczyk/WAT/PhD/impl/http-server/target/http-server-0.0.1-SNAPSHOT.jar --usersFile=/home/sszwaczyk/WAT/PhD/impl/floodlight/scenarios/complex-nobel-eu/users.json --servicesFile=/home/sszwaczyk/WAT/PhD/impl/floodlight/scenarios/complex-nobel-eu/mininet/services.json --logging.file=./http-ss.log --exitStatsFile=./http-ss-exit.xlsx'
    popens[httpSsHost] = httpSsHost.popen(httpSsCommand.split())

    httpSrCommand = 'java -jar /home/sszwaczyk/WAT/PhD/impl/http-server/target/http-server-0.0.1-SNAPSHOT.jar --usersFile=/home/sszwaczyk/WAT/PhD/impl/floodlight/scenarios/complex-nobel-eu/users.json --servicesFile=/home/sszwaczyk/WAT/PhD/impl/floodlight/scenarios/complex-nobel-eu/mininet/services.json --logging.file=./http-sr.log --exitStatsFile=./http-sr-exit.xlsx'
    popens[httpSrHost] = httpSrHost.popen(httpSrCommand.split())

    httpSuCommand = 'java -jar /home/sszwaczyk/WAT/PhD/impl/http-server/target/http-server-0.0.1-SNAPSHOT.jar --usersFile=/home/sszwaczyk/WAT/PhD/impl/floodlight/scenarios/complex-nobel-eu/users.json --servicesFile=/home/sszwaczyk/WAT/PhD/impl/floodlight/scenarios/complex-nobel-eu/mininet/services.json --logging.file=./http-su.log --exitStatsFile=./http-su-exit.xlsx'
    popens[httpSuHost] = httpSuHost.popen(httpSuCommand.split())

    info( '*** Sleep 30 seconds to let services start...\n')
    sleep(30)

    info( '*** Starting requests generators...\n')

    userOneCommand = 'java -jar /home/sszwaczyk/WAT/PhD/impl/requests-generator/target/requests-generator-1.0-SNAPSHOT.jar -sf /home/sszwaczyk/WAT/PhD/impl/floodlight/scenarios/complex-nobel-eu/mininet/services.json -lf user-one -st ./user-one-exit.xlsx -er ./user-one-every-request.xlsx -s 11111 -g poisson -l ' + str(lam)
    popens[userOneHost] = userOneHost.popen(userOneCommand.split())

    sleep(1)
    userTwoCommand = 'java -jar /home/sszwaczyk/WAT/PhD/impl/requests-generator/target/requests-generator-1.0-SNAPSHOT.jar -sf /home/sszwaczyk/WAT/PhD/impl/floodlight/scenarios/complex-nobel-eu/mininet/services.json -lf user-two -st ./user-two-exit.xlsx -er ./user-two-every-request.xlsx -s 22222 -g poisson -l ' + str(lam)
    popens[userTwoHost] = userTwoHost.popen(userTwoCommand.split())

    sleep(1)
    userThreeCommand = 'java -jar /home/sszwaczyk/WAT/PhD/impl/requests-generator/target/requests-generator-1.0-SNAPSHOT.jar -sf /home/sszwaczyk/WAT/PhD/impl/floodlight/scenarios/complex-nobel-eu/mininet/services.json -lf user-three -st ./user-three-exit.xlsx -er ./user-three-every-request.xlsx -s 33333 -g poisson -l ' + str(lam)
    popens[userThreeHost] = userThreeHost.popen(userThreeCommand.split())

    sleep(1)
    userFourCommand = 'java -jar /home/sszwaczyk/WAT/PhD/impl/requests-generator/target/requests-generator-1.0-SNAPSHOT.jar -sf /home/sszwaczyk/WAT/PhD/impl/floodlight/scenarios/complex-nobel-eu/mininet/services.json -lf user-four -st ./user-four-exit.xlsx -er ./user-four-every-request.xlsx -s 44444 -g poisson -l ' + str(lam)
    popens[userFourHost] = userFourHost.popen(userFourCommand.split())

    sleep(1)
    userFiveCommand = 'java -jar /home/sszwaczyk/WAT/PhD/impl/requests-generator/target/requests-generator-1.0-SNAPSHOT.jar -sf /home/sszwaczyk/WAT/PhD/impl/floodlight/scenarios/complex-nobel-eu/mininet/services.json -lf user-five -st ./user-five-exit.xlsx -er ./user-five-every-request.xlsx -s 55555 -g poisson -l ' + str(lam)
    popens[userFiveHost] = userFiveHost.popen(userFiveCommand.split())

    sleep(1)
    userSixCommand = 'java -jar /home/sszwaczyk/WAT/PhD/impl/requests-generator/target/requests-generator-1.0-SNAPSHOT.jar -sf /home/sszwaczyk/WAT/PhD/impl/floodlight/scenarios/complex-nobel-eu/mininet/services.json -lf user-six -st ./user-six-exit.xlsx -er ./user-six-every-request.xlsx -s 66666 -g poisson -l ' + str(lam)
    popens[userSixHost] = userSixHost.popen(userSixCommand.split())

    sleep(1)
    userSevenCommand = 'java -jar /home/sszwaczyk/WAT/PhD/impl/requests-generator/target/requests-generator-1.0-SNAPSHOT.jar -sf /home/sszwaczyk/WAT/PhD/impl/floodlight/scenarios/complex-nobel-eu/mininet/services.json -lf user-seven -st ./user-seven-exit.xlsx -er ./user-seven-every-request.xlsx -s 77777 -g poisson -l ' + str(lam)
    popens[userSevenHost] = userSevenHost.popen(userSevenCommand.split())

    info( "Simulating for", simulationTime, "seconds\n" )
    endTime = time() + simulationTime

    for h, line in pmonitor( popens, timeoutms=500 ):
        if h:
            info( '<%s>: %s' % ( h.name, line ) )
        if time() >= endTime:
            for p in popens.values():
                info( '*** Stopping requests generators and services...\n')
                p.send_signal( SIGTERM )

    info( '*** Stopping net...\n')
    net.stop()

    info( '*** Stopping controller...\n')
    os.kill(proc.pid, signal.SIGTERM)
示例#45
0
def mesure_ping_and_netperf(network, round_count=1, round_duration=5,
                            ping_interval=1.0, ping=True, netperf=True,
                            ovs_helper=False, qmin=50000,
                            ecn_tcp_flag=False, ovs_helper_wait=10
                            ):
    """
    h1 执行 ping 测试延时
    h2 执行 netperf 测试带宽利用率
    :param qmin:          queue min 监控大小
    :param ovs_helper:  使用 ovs_helper.py 控制 ecn
    :param ecn_tcp_flag : 使用ecn tcp 或 ip 控制
    :param network: mininet class
    :param round_count:    循环次数
    :param round_duration: 循环时间每轮
    :param ping_interval:  ping包采样间隔
    :param ping:        ping测试开关
    :param netperf:     netperf测试开关
    :param ovs_helper_wait:       ovs_helper_wait 时延, 让helper / netperf 的启动时间覆盖整个实验运行
    :return:
    """
    result = ""
    h1 = network.get("h1")
    h2 = network.get("h2")
    s1 = network.get("s1")
    popens = {}

    # 运行时间 ovs_helper > netperf > ping
    ping_cmd = "ping -c%s -i%s h3 " % (int(round_duration / ping_interval), ping_interval)
    netperf_cmd = "netperf -H h3 -l %s " % str(round_duration + ovs_helper_wait / 2)  # 附加wait秒时延, 考虑大于 ping 时延
    if ecn_tcp_flag:
        ecn_sub_cmd = "ecn_tcp"
    else:
        ecn_sub_cmd = "ecn_ip"
    ovs_openflow_cmd = "/opt/mininet/cuc/ecn_ovs_helper.py start %s %s %s" \
                       % (ecn_sub_cmd, qmin, round_duration + ovs_helper_wait)  # 附加wait秒时延, 考虑 netperf 启动
    # rr_cmd = "netperf -H h3 -l %s -t TCPRR " % round_duration
    # cmds = "%s;\n%s;\n%s" % (output_cmd, rr_cmd, ping_cmd)

    sleep(3)  # wait 2 second to reach tcp max output

    # 启动顺序 ovs_helper > netperf > ping
    for r in range(round_count):
        print ("*** ROUND %s" % r)
        if ovs_helper:  # ovs helper 优先
            for h in [s1]:
                this_cmd = "<%s>: popen cmd: %s \n" % (h.name, ovs_openflow_cmd)
                info(this_cmd)
                result += this_cmd
                popens[h] = h.popen(ovs_openflow_cmd)
        if netperf:
            for h in [h2]:  # 背景流量优先
                this_cmd = "<%s>: popen cmd: %s \n" % (h.name, netperf_cmd)
                info(this_cmd)
                result += this_cmd
                popens[h] = h.popen(netperf_cmd)
        if ping:
            for h in [h1]:  # 最后运行ping
                this_cmd = "<%s>: popen cmd: %s \n" % (h.name, ping_cmd)
                info(this_cmd)
                result += this_cmd
                popens[h] = h.popen(ping_cmd)

        log_line_count = 0
        # Monitor them and print output
        # 在 pmoniter中运行的程序,  print 结果会直接回显在屏幕上
        #    而 info / debug 结果则需要在 result 中得到回显
        for host, line in pmonitor(popens):
            if host:
                log_line_count += 1
                if line.find("icmp_seq") != -1:  # debug ping output
                    debug("<%s>: %s\n" % (host.name, line.strip()))  # suppressed ping output to debug level
                    if (log_line_count % (5 / ping_interval)) == 0:  # every 5 second print line 便于在 info 模式下观察
                        info("<%s>: %s\n" % (host.name, line.strip()))
                elif line.find("debug") != -1:  # debug ecn helper output
                    debug("<%s>: %s\n" % (host.name, line.strip()))
                else:
                    info("<%s>: %s\n" % (host.name, line.strip()))
                    result += "<%s>: %s\n" % (host.name, line.strip())

    return result
示例#46
0
文件: net.py 项目: john35452/sdn-p2p
def multiControllerNet():
    "Create a network from semi-scratch with multiple controllers."

    NODE1_IP='192.168.144.126'
    NODE2_IP='192.168.144.134'
    CONTROLLER_IP='192.168.144.126'
    #net = Mininet( controller=Controller,host=CPULimitedHost)
    net = Mininet(controller=Controller)
    print "*** Creating (reference) controllers"
    c1 = net.addController( 'c1', port=6633 )
    #c1 = net.addController('c1', controller=RemoteController,ip='127.0.0.1',port=6633)
    #c2 = net.addController( 'c2', port=6634 )
    #c2 = net.addController('c2', controller=RemoteController,ip='127.0.0.1',port=6634)
    #c3 = net.addController( 'c3', port=6635 )
    #c3 = net.addController('c3', controller=RemoteController,ip='127.0.0.1',port=6635)

    layer = 3
    tmp = 1<<layer
    print "*** Creating switches"
    sdn_switch = [net.addSwitch('S%d'%(n)) for n in range(15,16)]
    left_switch = [net.addSwitch('L%d'%(n+1)) for n in range(tmp-1)]
    #right_switch = [net.addSwitch('R%d'%(n+tmp)) for n in range(tmp-1)]
    #f = open('switch_list','w')
    switch_name = [n.name for n in left_switch]
    #switch_name = switch_name + [n.name for n in right_switch]
    switch_name = switch_name + [n.name for n in sdn_switch]
    '''
    with open('switch_list','w') as f:
        f.write(' '.join(switch_name)) 
    print 'Finish writing switch_list'
    '''   
    print "*** Creating hosts"
    hosts1 = [ net.addHost( 'h%d' % (n+1) ,ip='10.0.0.%s'%(n+1)) for n in range(tmp) ]
    #hosts2 = [ net.addHost( 'h%d' % (n+1+tmp) ) for n in range(tmp) ]

    print "*** Creating links"
    for i in range(len(left_switch)/2):
        net.addLink(left_switch[i],left_switch[(i+1)*2-1])
        net.addLink(left_switch[i],left_switch[(i+1)*2])
    #for i in range(len(right_switch)/2):
    #    net.addLink(right_switch[i],right_switch[(i+1)*2-1])
    #    net.addLink(right_switch[i],right_switch[(i+1)*2])
    for i in range(len(sdn_switch)):
        #net.addLink(sdn_switch[i],right_switch[0])
        net.addLink(sdn_switch[i],left_switch[0])
    #net.addLink(sdn_switch[0],sdn_switch[1])
  
    ''' 
    for i in range(4): 
        for j in range(2):
            net.addLink(left_switch[i+3],hosts1[2*i+j])
            net.addLink(right_switch[i+3],hosts2[2*i+j])
    '''
    tmp >>= 1
    for i in range(tmp):
        for j in range(2):
            net.addLink(left_switch[i+tmp-1],hosts1[2*i+j])
            #net.addLink(right_switch[i+tmp-1],hosts2[2*i+j])

    print "*** Starting network"
    net.build()
    net.addNAT(ip='10.0.0.254').configDefault()
    #nat = net.addNAT(connect=None)
    #net.addLink(nat,sdn_switch[0])
    #nat.configDefault()
    #net.build()
    c1.start()
    #c2.start()
    #c3.start()
    for k in left_switch:
        k.start([c1])
    #for k in right_switch:
    #    k.start([c2])
    for k in sdn_switch:
        k.start([c1])
    
    sdn_switch[0].cmdPrint('ovs-vsctl add-port '+sdn_switch[0].name+' '+sdn_switch[0].name+'-gre1 -- set interface '+sdn_switch[0].name+'-gre1 type=gre options:remote_ip='+NODE2_IP)
    for k in hosts1:
        k.cmdPrint('ip link set mtu 1454 dev '+k.name+'-eth0')
    nat = net.get('nat0')
    nat.cmdPrint('ip link set mtu 1454 dev nat0-eth0')
    print "*** Testing network"
    #net.pingAll()
    out = {}
    popens = {}
    count = {}
    for i in range(tmp<<1):
        print 'activate',i
        #popens[hosts1[i]] = hosts1[i].popen('python client.py 1 1 %s user1 > %s &'%(i,'user1'+str(i)))
        popens[hosts1[i]] = hosts1[i].popen('python client.py 1 1 %s user1'%(i))
        #popens[hosts2[i]] = hosts2[i].popen('python client.py 1 2 %s user1 > %s &'%(i,'user2'+str(i)))
        #hosts1[i].cmdPrint('python client.py 1 1 %s user1 > %s &'%(i,'user1'+str(i)))
        #hosts2[i].cmd('python client.py 1 2 %s user1 > %s &'%(i,'user2'+str(i)))
        out[hosts1[i].name] = open('user1'+str(i),'w')
        count[hosts1[i].name] = 0
    
    for host,line in pmonitor(popens):
        if host:
            out[host.name].write(line.strip()+'\n')
            count[host.name] += 1
            print count
            #print "<%s>: %s" % ( host.name, line.strip() )
    
    '''
    print 'host1'
    hosts1[0].cmd('python client.py 1 1 1 user1 > a &')
    print 'host2'
    hosts1[1].cmd('python client.py 1 1 2 user1 > b &')
    print "*** Running CLI"
    '''
    CLI( net )
    print count
    print "*** Stopping network"
    net.stop()
示例#47
0
文件: popen.py 项目: jhall11/mininet
#!/usr/bin/python

"""
This example monitors a number of hosts using host.popen() and
pmonitor()
"""


from mininet.net import Mininet
from mininet.node import CPULimitedHost
from mininet.topo import SingleSwitchTopo
from mininet.log import setLogLevel
from mininet.util import custom, pmonitor

def monitorhosts( hosts=5, sched='cfs' ):
    "Start a bunch of pings and monitor them using popen"
    mytopo = SingleSwitchTopo( hosts )
    cpu = .5 / hosts
    myhost = custom( CPULimitedHost, cpu=cpu, sched=sched )
    net = Mininet( topo=mytopo, host=myhost )
    net.start()
    # Start a bunch of pings
    popens = {}
    last = net.hosts[ -1 ]
    for host in net.hosts:
        popens[ host ] = host.popen( "ping -c5 %s" % last.IP() )
        last = host
    # Monitor them and print output
    for host, line in pmonitor( popens ):
        if host:
            print( "<%s>: %s" % ( host.name, line.strip() ) )