Exemplo n.º 1
0
def UC2_IITS_Network():

	logger.info('=================== Mininet Topology SetUp ===================')

	# Create UC Topology instance
	IITSTopo = IITSTopology()

	# Start mininet and load the topology
	net = Mininet( topo=IITSTopo, controller=RemoteController, autoSetMacs = True )
	net.start()
	setLogLevel( 'info' ) #setLogLevel( 'info' | 'debug' | 'output' )

	# Get the devices
	Devices = dict()
	Devices = net.get('h1', 'h2', 'h3', 'h4', 'h5', 's1', 's2', 's3', 's4', 's5', 's6', 's7', 's8')
	IITSTopo.SetDevices(Devices)
	logger.info('==============================================================\n')

	# Enforce IP configuration
	logger.info('====================== IP Configuration ======================')
	IITSTopo.SetIPConfiguration(Devices, net)
	logger.info('==============================================================\n')

	# Start mininet CLI
	CLI( net )

	# Destroy network after exiting the CLI
	net.stop()
Exemplo n.º 2
0
  def run(self):
    print self.receivelinkevent
    
    setLogLevel("info")
    OVSKernelSwitch.setup()#"Make sure Open vSwitch is installed and working"

    info("****creating network****\n")
    self.net = Mininet(listenPort = self.listenPort)

    controller = RemoteController("mirrorController",   ip = "127.0.0.1")
    self.net.addController(controller)
    #self.gettoptly()
    timesnum=0;
    while core.running:
      try:
        while True:
          rlist, wlist, elist = yield Select([self.receivelinkevent], [], [], 5)
          if len(rlist) == 0 and len(wlist) == 0 and len(elist) == 0:
            #self.gettoptly()
            if not core.running: break
          #if len(rlist)!=0:
            #print self.receivelinkevent
          if self.receivelinkevent==1:
            self.gettoptly()
            timesnum+=1
            if timesnum==5:
              self.net.pingAll()    
      except exceptions.KeyboardInterrupt:
        break
    self.net.stop()
Exemplo n.º 3
0
def main():
    import argparse
    import threading
    from threading import Thread

    parser = argparse.ArgumentParser(description="less script")
    parser.add_argument("-u", "--urls", dest="urls", default="10.128.10.1", type=str, help="a string to show urls to post intents to separated by space, ex. '10.128.10.1:6633 10.128.10.2:6633' ")
    parser.add_argument("-s", "--switches", dest="numsw", default=100, type=int, help="number of switches use in the load generator; together with the ports per switch config, each switch generates (numport + 2) events")
    parser.add_argument("-p", "--ports", dest="numport", default=1, type=int, help="number of ports per switches")
    parser.add_argument("-a", "--addrate", dest="addrate", default=10, type=float, help="rate to add intents groups, groups per second")
    parser.add_argument("-d", "--delrate", dest="delrate", default=100, type=float, help= "rate to delete intents, intents/second")
    parser.add_argument("-l", "--testlength", dest="duration", default=0, type=int, help= "pausing time between add and delete of intents")
    args = parser.parse_args()

    urllist = args.urls.split()
    numsw = args.numsw
    numport = args.numport
    addrate = args.addrate
    delrate = args.delrate
    duration = args.duration
    setLogLevel( 'info' )
    swlist = createSwPorts(numsw,numport)
    telapse,count = loadsw(urllist, swlist, addrate, delrate, duration)
    print ("Total number of switches connected/disconnected: " + str(count) + "; Total events generated: " + str(count * (2 + numport)) + "; Elalpse time: " + str('%.1f' %telapse))
    print ("Effective aggregated loading is: " + str('%.1f' %((( count * (2+ numport))) / telapse ) ) + "Events/s.")
    cleanMN()
Exemplo n.º 4
0
def run():
    "Test a multiple ONOS cluster network"
    setLogLevel( 'info' )
    # East and west control network topologies (using RenamedTopo)
    # We specify switch and host prefixes to avoid name collisions
    # East control switch prefix: 'east_cs', ONOS node prefix: 'east_onos'
    # Each network is a renamed SingleSwitchTopo of size clusterSize
    # It's also possible to specify your own control network topology
    clusterSize = 1
    etopo = RenamedTopo( SingleSwitchTopo, clusterSize,
                         snew='east_cs', hnew='east_onos' )
    wtopo = RenamedTopo( SingleSwitchTopo, clusterSize,
                         snew='west_cs', hnew='west_onos' )
    # east and west ONOS clusters
    # Note that we specify the NAT node names to avoid name collisions
    east = ONOSCluster( 'east', topo=etopo, ipBase='192.168.123.0/24',
                        nat='enat0' )
    west = ONOSCluster( 'west', topo=wtopo, ipBase='192.168.124.0/24',
                        nat='wnat0' )
    # Data network topology
    topo = LinearTopo( 10 )
    # Create network
    net = Mininet( topo=topo, switch=MultiSwitch, controller=[ east, west ] )
    # Assign switches to controllers
    count = len( net.switches )
    for i, switch in enumerate( net.switches ):
        switch.controller = east if i < count/2 else west
    # Start up network
    net.start()
    ONOSCLI( net )  # run our special unified Mininet/ONOS CLI
    net.stop()
Exemplo n.º 5
0
    def start_networking(self):
        setLogLevel("info")
        net = Mininet(topo=self, \
                      controller=lambda name: RemoteController(name))
        net.start()

        # setup each switch
        for sw in net.switches:
            # set ofp version
            self.set_ofp_version(sw, ['OpenFlow10', 'OpenFlow13'])
            # if sw is bridge, set it up for normal SW
            swEntry = self.switchList[sw.name][1]
            isBridge = swEntry["bridge"]
            if isBridge:
                self.set_normalsw(sw)
            self.switchList[sw.name].append(sw)

        # setup each host
        for host in net.hosts:
            self.add_ipv6address(host)
            self.hostList[host.name].append(host)

        # execute pre_command
        if "pre_cmd_file" in self.jsonData:
            cmd_file = self.jsonData["pre_cmd_file"]
            self.exec_usercmd(cmd_file)

        CLI(net)

        # execute post_command
        if "post_cmd_file" in self.jsonData:
            cmd_file = self.jsonData["post_cmd_file"]
            self.exec_usercmd(cmd_file)

        net.stop()
Exemplo n.º 6
0
def main():
    # Defines the log level
    setLogLevel('info')

    # parses command line arguments
    parser = OptionParser()
    parser.add_option('-H', dest='hosts', default=5,
                      help='Number of hosts per switch')
    parser.add_option('-S', dest='switches', default=2,
                      help='Number of switches')
    (options, args) = parser.parse_args()

    # Build network topology (see mininet/topo.py)
    #topo = LinearTopo(int(options.switches), int(options.hosts))
    topo = LinearTopo()

    # Creates the Network using a remote controller
    #net = Mininet(topo)
    net = Mininet(topo,
                  controller=lambda a: RemoteController(a, ip='127.0.0.1'))

    # Starts the network
    net.start()
    # Run the mininet client
    while True:
        try:
            DynCLI(net)
            break
        except Exception as e:
            error('Fail: %s\n Args: %s \n %s \n' % (type(e), e.args, e))
            traceback.print_exc()
            continue
        
    # Stop the network
    net.stop()
Exemplo n.º 7
0
def main():
    # Defines the log level
    setLogLevel('info')

    # parses command line arguments
    parser = OptionParser()
    parser.add_option('-H', dest='hosts', default=5,
                      help='Number of hosts per switch')
    parser.add_option('-S', dest='switches', default=2,
                      help='Number of switches')
    (options, args) = parser.parse_args()

    # Build network topology (see mininet/topo.py)
    topo = LinearTopo(int(options.switches), int(options.hosts))

    # Creates the Network using a remote controller
    net = Mininet(topo,
                  controller=lambda a: RemoteController(a, ip='127.0.0.1'))

    # Starts the network
    net.start()
    # Run the mininet client
    CLI(net)
    # Stop the network
    net.stop()
Exemplo n.º 8
0
def standalone():
	if "info" in argv:
		setLogLevel( 'info' )
	scls=None
	if "of" in argv:
		scls = StaticSwitch 
	elif "lr" in argv:
		scls = DRtr
	else:
		print("Supply either of (for OpenFlow) or lr (for a Linux Router)")
		exit(-1)
	topo = DTopo(scls=scls)
	net = Mininet(topo=topo,autoSetMacs=True)
	net.start()
	sw, h1, h2 = net.get('s1', 'h1', 'n1')
	if "noarp" not in argv:
		makearpentries(sw, [h1, h2])
	#print(sw.cmd("netstat -tulpen"))
	if "dump" in argv:
		if "lr" in argv:
			dump('iptables-save', sw.cmd('iptables-save'))
			dump('ip-route', sw.cmd('ip route'))
			dump('collectedmacs', sw.cmd('collectmacs.sh'))
		elif "of" in argv:
			print("of/dump TODO")
	if "test" in argv:
		sese = [h1,h2]
		net.ping(sese)
		tcpreachtests(net,sese,ports=[80,22])
	if "cli" in argv:
		CLI(net)
	net.stop()
Exemplo n.º 9
0
def pingloop( net ):
    setLogLevel( 'error' )
    try:
        while True:
            net.ping()
    finally:
        setLogLevel( 'info' )
Exemplo n.º 10
0
  def run (self):
    setLogLevel("info")
    OVSKernelSwitch.setup()#"Make sure Open vSwitch is installed and working"

    info("****creating network****\n")
    self.net = Mininet(listenPort = 6666)

    controller = RemoteController("mirrorController",   ip = "127.0.0.1")
    self.net.addController(controller)
    while core.running:
      try:
        time.sleep(3)
        if not core.running: break
        '''
        self.net.pingAll()
        if len(self.addswitches)!=0:
          for i in self.addswitches:
            print self.addswitches[i].dpctl('show')
        '''
        if self.rectopolyreply==1:
          mutex.acquire()
          self.createtoptly()
          self.rectopolyreply=0
          mutex.release()
      except exceptions.KeyboardInterrupt:
        break
      except:
        log.exception("Exception SendMes running ")
        break
    self.net.stop()
Exemplo n.º 11
0
def main():
    _LOGGER.info("Executing the integration topology with pid {0!s} and parent pid {1!s}".format(os.getpid(), os.getppid()))
    setLogLevel('debug')  # set Mininet loglevel
    # create_and_start_topology(DCNetwork(controller=RemoteController,
    #                                     monitor=True,
    #                                     enable_learning=True))
    sc = SigTermCatcher()
    (server_thread, server) = spawn_socket_thread(sc)
    server_thread.start()

    while True:
        if sc.is_alive():
            forked_process = spawn_process(sc)
            sc.ignore_signal()
            forked_process.start()
            sc.setup_signal()
            forked_process.join()
        else:
            break
        time.sleep(1)

    _LOGGER.info("Stopping the server")
    server.shutdown(socket.SHUT_RDWR)
    server_thread.join()
    exit(2)
Exemplo n.º 12
0
def main():
    setLogLevel("info")  # set Mininet loglevel
    # add the SIGTERM handler (eg. received when son-emu docker container stops)
    signal.signal(signal.SIGTERM, exit_gracefully)
    # also handle Ctrl-C
    signal.signal(signal.SIGINT, exit_gracefully)
    # start the topology
    create_topology1()
Exemplo n.º 13
0
 def pingloop( self ):
     "Loop forever pinging the full mesh of hosts"
     setLogLevel( 'error' )
     try:
         while True:
             self.ping()
     finally:
         setLogLevel( 'info' )
Exemplo n.º 14
0
 def run(self):
     setLogLevel('info')
     myNetworkStop()
     myNetwork()
     while True:
         print('Still running...')
         time.sleep(10)
     myNetworkStop()
Exemplo n.º 15
0
def start():

    global net, attacker, running

    if running:
        return '\nServer already running.\n'

    setLogLevel('info')

    topo = MixTopo()
    net = Mininet(topo=topo)

    s1 = net['s1']
    plc2 = net['plc2']
    plc3 = net['plc3']

    s2, rtu2a, scada = net.get('s2', 'rtu2a', 'scada')
    rtu2b, attacker2 = net.get('rtu2b', 'attacker2')
    s3 = net.get('s3')

    # NOTE: root-eth0 interface on the host
    root = Node('root', inNamespace=False)
    intf = net.addLink(root, s3).intf1
    print('DEBUG root intf: {}'.format(intf))
    root.setIP('10.0.0.30', intf=intf)
    # NOTE: all packet from root to the 10.0.0.0 network
    root.cmd('route add -net ' + '10.0.0.0' + ' dev ' + str(intf))


    net.start()
    info('Welcome')

    # NOTE: use for debugging
    #s1.cmd('tcpdump -i s1-eth1 -w /tmp/s1-eth1.pcap &')
    #s1.cmd('tcpdump -i s1-eth2 -w /tmp/s1-eth2.pcap &')

    SLEEP = 0.5

    # NOTE: swat challenge 1 and 2
    plc3.cmd(sys.executable + ' plc3.py &')
    sleep(SLEEP)
    plc2.cmd(sys.executable + ' plc2.py &')
    sleep(SLEEP)

    # NOTE: wadi challenge 1
    scada.cmd(sys.executable + ' scada.py &')
    sleep(SLEEP)
    rtu2a.cmd(sys.executable + ' rtu2a.py &')
    sleep(SLEEP)
    # NOTE: wadi challenge 2
    rtu2b.cmd(sys.executable + ' rtu2b.py &')
    sleep(SLEEP)


    running = True
    return '\nServer started.\n'
Exemplo n.º 16
0
def main():
  desc = ( 'Generate Mininet Testbed' )
  usage = ( '%prog [options]\n'
            '(type %prog -h for details)' )
  op = OptionParser( description=desc, usage=usage )

  ### Options
  op.add_option( '--rate', '-r', action="store", \
                 dest="rate", help = "Set rate. <n>S for (n/second), <n>M for (n/minute). Don't include the brackets when specifying n" )

  op.add_option( '--switchNum', '-s', action="store", \
                 dest="switchnum", help = "Specify the number of switches for this linear topology." )

  op.add_option( '--time', '-t', action="store", \
                 dest="timeout", help = "Specify the timeout in seconds." )
 
  op.add_option( '--type', '-y', action="store", \
                 dest="topo_type", help = "Specify type of the topology (linear, fattree)" )


  wait_time = 0.0
  options, args = op.parse_args()

  if options.rate is not None:
    if options.rate.endswith('S'):
      num_str = options.rate.rstrip('S')
      wait_time = 1.0/float(num_str)
    elif options.rate.endswith('M'):
      num_str = options.rate.rstrip('M')
      wait_time = 60.0/float(num_str)
    else:
      print 'Wrong rate format. Abort.'
      return
  else:
    print '\nNo rate given. Abort.\n'
    return

  # Set parameters      
  timeout_int = math.ceil(float(options.timeout))
  
  top = 1
  middle = 2
  bottom = int(options.switchnum)
  host_fanout = 5

  # Start
  if options.switchnum is not None and options.timeout is not None and options.rate is not None:
    setLogLevel('info')
    MakeTestBed_and_Test(options.topo_type,
                         top,
                         middle,
                         bottom, 
                         host_fanout,
                         timeout_int, wait_time)
  else:
    print '\nNo switch number given. Abort.\n'
Exemplo n.º 17
0
def test( serverCount ):
    "Test this setup"
    setLogLevel( 'info' )
    net = Mininet( topo=SingleSwitchTopo( 3 ),
                   controller=[ ONOSCluster( 'c0', serverCount ) ],
                   switch=ONOSOVSSwitch )
    net.start()
    net.waitConnected()
    CLI( net )
    net.stop()
def run():
    OVSSwitch.setup()
    setLogLevel('debug')

    net = Mininet(topo=KeepForwardingSmartDownlinkTestTopo(),
                  switch=OVSSwitch,
                  controller=RemoteController)
    net.start()
    CLI(net)
    net.stop()
Exemplo n.º 19
0
def test():
    "Test OVSNS switch"
    setLogLevel( 'info' )
    topo = TreeTopo( depth=4, fanout=2 )
    net = Mininet( topo=topo, switch=OVSSwitchNS )
    # Add connectivity to controller which is on LAN or in root NS
    # net.addNAT().configDefault()
    net.start()
    CLI( net )
    net.stop()
Exemplo n.º 20
0
def run():
    setLogLevel('info')
    #topo = S1HNLinearTopo(n=4)
    topo = S2HNTreeTopo(n = 4)
    net = Mininet(topo=topo,
                  autoSetMacs=True,
                  controller = lambda name: RemoteController(name, ip='127.0.0.1'))
    dumpNodeConnections(net.hosts)
    net.start()
    CLI(net)
    net.stop()
Exemplo n.º 21
0
def main():
    setLogLevel('info')
    network = Mininet(topo=MyTopo(), controller=partial(RemoteController, ip='127.0.0.1', port=6633), link=TCLink)
    network.start()
    network.pingAll()

    while True:
        network.pingAll()
        time.sleep(60)

    CLI(network)
Exemplo n.º 22
0
def run():
    OVSSwitch.setup()
    setLogLevel('debug')

    net = Mininet(
        topo=FailoverTestTopo(),
        switch=OVSSwitch,
        controller=RemoteController)
    net.start()
    CLI(net)
    net.stop()
def main():
  desc = ( 'Generate Mininet Testbed' )
  usage = ( '%prog [options]\n'
            '(type %prog -h for details)' )
  op = OptionParser( description=desc, usage=usage )

  ### Options
  op.add_option( '--rate', '-r', action="store", \
                 dest="rate", help = "Set rate. <n>S for (n/second), <n>M for (n/minute). Don't include the brackets when specifying n" )

  op.add_option( '--time', '-t', action="store", \
                 dest="timeout", help = "Specify the timeout in seconds." )
 
  op.add_option( '--kvalue', '-k', action="store", \
                 dest="kvalue", help = "K value for the folded clos topology." )

  op.add_option( '--controller', '-c', action="store", \
                 dest="controller", help = "Controller IP address (with numbers!)" )


  ping_interval = 0.0
  options, args = op.parse_args()

  args = sys.argv[1:]
  if len(args) != 8:
    print '\nWrong number of arguments given: %s. Abort\n' %(str(len(args)))
    op.print_help()
    sys.exit(1)

  if options.rate is not None:
    if options.rate.endswith('S'):
      num_str = options.rate.rstrip('S')
      ping_interval = 1.0/float(num_str)
    elif options.rate.endswith('M'):
      num_str = options.rate.rstrip('M')
      ping_interval = 60.0/float(num_str)
    else:
      print 'Wrong rate format. Abort.'
      return
  else:
    print '\nNo rate given. Abort.\n'
    return

  # Set parameters      
  timeout_int = math.ceil(float(options.timeout))
  controller_ip = options.controller
  
  # Start
  if options.timeout is not None and options.rate is not None:
    setLogLevel('info')
    MakeTestBed_and_Test(int(options.kvalue), timeout_int, ping_interval, controller_ip)

  else:
    print '\nNo switch number given. Abort.\n'
Exemplo n.º 24
0
def experiment():
    # Start POX with the dedicated topology test module
    controller = start_pox(module='mcfpox.test.controller.pox_test_topology')
    
    # Start mininet with given topology
    setLogLevel('output')
    net = pentagon.create_net(controller=RemoteController)
    net.start()
    
    # Wait for long enough to discover the network, then die
    sleep(20)
    controller.kill()
Exemplo n.º 25
0
def run( topo, controllers=None, link=TCLink, autoSetMacs=True ):
    if not controllers and len( sys.argv ) > 1:
        controllers = sys.argv[ 1: ]
    else:
        print 'Need to provide a topology and list of controllers'
        exit( 1 )

    setLogLevel( 'info' )

    net = ONOSMininet( topo=topo, controllers=controllers, link=link, autoSetMacs=autoSetMacs )
    net.start()
    CLI( net )
    net.stop()
def startMininet(switches, hosts, contIP='127.0.0.1'):
    setLogLevel('info')

    net = Mininet(controller=None,
                  autoSetMacs=True,
                  listenPort=6634)

    swobjs = {}
    swports = {}

    for sw in switches:
        swobj = addSwitch(net, sw['name'])
        swobjs[sw['name']] = swobj
        swports[sw['name']] = 0;
    for host in hosts:
        if host['switch'] not in swobjs:
            continue
        sw = swobjs[host['switch']]
        swports[host['switch']] += 1;
        port = swports[host['switch']]
        addHost(net, sw, host['name'], host['ip'], host['mac'])
        host['port'] = port

    try:
        net.start()
        for sw in switches:
            addTunnel(sw['name'], sw['tunnelIp'])

        for host in net.hosts:
            gw = re.sub(r'.\d+$', ".1", host.IP())
            host.cmd('route add default gw {}'.format(gw))

        # ODL is very fragile so let's give it some time
        time.sleep(1)

        # This is a workaround for a bug encountered during
        # the Helium release. Setting the vSwitch from 1.0
        # to 1.3 while it was connected to the controller
        # exposed a bug in the openflowplugin, which resulted
        # in the controller missing some of the ports on the
        # vswitch. This change avoids the bug by switching 
        # the version before connecting the switch to the
        # controller.
        for sw in switches:
            setOFVersion(sw['name'])
            addController(sw['name'], contIP)

        return net
    except Exception, e:
        net.stop()
        raise e
Exemplo n.º 27
0
def main():
  desc = ( 'Generate Mininet Testbed' )
  usage = ( '%prog [options]\n'
            '(type %prog -h for details)' )
  op = OptionParser( description=desc, usage=usage )

  ### Options
  op.add_option( '--rate', '-r', action="store", \
                 dest="rate", help = "Set rate. <n>S for (n/second), <n>M for (n/minute). Don't include the brackets when specifying n" )

  op.add_option( '--switchNum', '-s', action="store", \
                 dest="switchnum", help = "Specify the number of switches for this linear topology." )

  op.add_option( '--mode', '-m', action="store", \
                 dest="mode", help = "rtt or bw" )


  wait_time = 0.0
  options, args = op.parse_args()

  if options.rate is not None:
    if options.rate.endswith('S'):
      num_str = options.rate.rstrip('S')
      wait_time = 1.0/float(num_str)
    elif options.rate.endswith('M'):
      num_str = options.rate.rstrip('M')
      wait_time = 60.0/float(num_str)
    else:
      print 'Wrong rate format. Abort.'
      op.print_usage()
      return
  else:
    print '\nNo rate given. Abort.\n'
    op.print_usage()
    return

  if options.switchnum is not None and options.mode is not None and options.rate is not None:
    setLogLevel('info')
    if options.mode == 'rtt':
      RTTTest(int(options.switchnum), wait_time)
    elif options.mode == 'bw':
      BWTest(int(options.switchnum),  wait_time)
    else: 
      print "wrong mode. exit"
      op.print_usage()
      return

  else:
    print '\nNo switch number given. Abort.\n'
    op.print_usage()
def start_mininet():
	print "[*] Starting Mininet:"
	global exit_mininet
	global net
	setLogLevel('info') # enable Mininet logging
	topo = SingleSwitchTopo()
	net = Mininet(topo = topo,
				host = P4Host,
				switch = P4Switch,
				controller = None)
	net.start()
	host = net.get('h1')
	host.config() # disable IPv6
	exit_mininet = True
	sleep(2)
Exemplo n.º 29
0
def createTopology(switch, hosts):
    setLogLevel('info')
    topo = Topo()
    switch = topo.addSwitch(switch)

    for (hostname, opts) in hosts:
        host = topo.addHost(hostname, **opts)
        topo.addLink(host, switch, None)

    network = Mininet(topo, controller=None)
    network.start()
    print "*** Dumping host connections"
    dumpNodeConnections(network.hosts)
    CLI(network)
    network.stop()
Exemplo n.º 30
0
def run(topo_file, chirouter, pox, pox_location):
    setLogLevel('info')

    with open(topo_file, "r") as f:
        topo = Topology.from_json(f)

    mn_topo = topo.to_mininet_topology()

    if pox is not None:
        # POX is running somewhere else. We connect to it.
        controller = RemoteController("c0", ip=pox[0], port=pox[1])
    else:
        # We launch POX ourselves
        controller = POXController("c0", pox_location, topo_file, chirouter)

    net = Mininet(topo=mn_topo, controller = controller)
    for h in topo.hosts:
        mn_host = net.get(h.name)
        for iface in h.interfaces.values():
            iface_name = h.name + "-" + iface.name
            try:
                mn_iface = mn_host.intf(iface_name)
            except:
                raise Exception("Error fetching interface {} from {}".format(iface_name, h.name))

            mn_iface.setIP(iface.ip_with_prefixlen)

            if iface.gateway is not None:
                mn_host.cmd("route add default gw {} dev {}".format(str(iface.gateway), iface_name))
                
            if "httpd" in h.attrs:
                print "*** Starting SimpleHTTPServer on host %s" % mn_host.name
                mn_host.cmd('nohup python2.7 ./scripts/webserver.py %s &' % (mn_host.name))

    for r in topo.routers:
        mn_router = net.get(r.name)

        for intf_name, intf in r.interfaces.items():
            intf.hwaddr = mn_router.intf(r.name + "-" + intf_name).mac

    net.start()
    CLI( net )
    net.stop()
    
    info("*** Shutting down stale SimpleHTTPServers", 
          quietRun( "pkill -9 -f SimpleHTTPServer" ), "\n" )    
    info('*** Shutting down stale webservers', 
          quietRun( "pkill -9 -f webserver.py" ), "\n" ) 
Exemplo n.º 31
0
    def run(self, sim_args, curtime, entrypoint):
        if any(v not in environ for v in ['CLIENT', 'CLIENT_PARAMS', 'SERVER', 'SERVER', 'CLIENT_LOGS', 'SERVER_LOGS', 'CL_COMMIT', 'SV_COMMIT']):
            # TODO show help
            exit(1)
        client_image = environ['CLIENT']
        client_params = environ['CLIENT_PARAMS']
        server_image = environ['SERVER']
        server_params = environ['SERVER_PARAMS']
        cl_logdir = environ['CLIENT_LOGS']
        sv_logdir = environ['SERVER_LOGS']
        clcommit = environ['CL_COMMIT']
        svcommit = environ['SV_COMMIT']

        setLogLevel('info')

        net = Containernet(controller=Controller)
        info('*** Adding controller\n')
        net.addController('c0')
        info('*** Adding docker containers\n')
        server_vs = [sv_logdir + ':/logs']
        # add kernel debug volume to allow eBPF code to run
        if sim_args.k:
            server_vs.append( '/sys/kernel/debug:/sys/kernel/debug:ro')
        server = net.addDocker('server', ip='10.0.0.251',
                               environment={"ROLE": "server", "SERVER_PARAMS": server_params, "COMMIT": svcommit},
                               dimage=server_image + ":latest",
                               volumes=server_vs)
        client = net.addDocker('client', ip='10.0.0.252', 
                               environment={"ROLE": "client", "CLIENT_PARAMS": client_params, "COMMIT": clcommit},
                               dimage=client_image + ":latest", 
                               volumes=[cl_logdir + ':/logs'])

        info('*** Adding switches\n')
        s1 = net.addSwitch('s1')
        s2 = net.addSwitch('s2')
        info('*** Creating links\n')
        net.addLink(s1, s2, cls=TCLink, delay=sim_args.delay, bw=sim_args.bandwidth, max_queue_size=sim_args.queue)
        net.addLink(s1, client)
        net.addLink(s2, server)
        info('\n*** Updating and building client/server\n')
        server.cmd('./updateAndBuild.sh')
        client.cmd('./updateAndBuild.sh')
        info('*** Starting network\n')
        net.start()
        info('***Config loss on switch links\n')
        net.get('s1').cmd('tc qdisc change dev s1-eth1 parent 5:1 netem delay ' + sim_args.delay + ' loss ' + str(sim_args.rate_to_server) + '% limit ' + str(sim_args.queue))
        net.get('s2').cmd('tc qdisc change dev s2-eth1 parent 5:1 netem delay ' + sim_args.delay + ' loss ' + str(sim_args.rate_to_client) + '% limit ' + str(sim_args.queue))
        capture = PacketCapture()
        if sim_args.k:
            client.cmd(entrypoint + " &")
        else:
            server.cmd(entrypoint + " &" )
        capture.startCapture()
        info('\n' + entrypoint + '\n')
        if sim_args.k:
            info(server.cmd(entrypoint) + "\n")
        else:
            info(client.cmd(entrypoint) + "\n")
        # Wait some time to allow server finish writing to log file
        sleep(3)
        capture.stopCapture()
        info('*** Stopping network')
        net.stop()
Exemplo n.º 32
0
    def run(self, predefined_error=0):
        net = self.net
        setLogLevel("debug")
        net.start()
        net.pingAll()

        error_interval = int(self.config.get('main', 'ErrorInterval'))
        datac = int(self.config.get('main', 'Datacenters'))
        # DEBUGGING: MainHosts is zero
        nm_ho_sf = 0

        #All datacenters will activate their servers
        scenario = self.config.get('main', 'StreamingScenario')
        for n in range(nm_ho_sf + 1, nm_ho_sf + datac * 3 + 1):
            h = net.get('h{}'.format(n))
            h.cmd('./net/server.sh &')
            h.cmd('./net/streaming_server.sh &')
            h.cmd('./net/mail_listen_receive.sh &')
            h.cmd('./net/mail_listen_send.sh &')
            h.cmd('iperf -s &')
        if 'Yes' in scenario:
            for n in range(nm_ho_sf, nm_ho_sf + datac):
                h = net.get('h{}'.format(n * 3 + 1))
                h.cmd('./net/vlc_send.sh &')
                # XTERM any host to connect vlc to the datacenter
                CLI(net)
        elif 'No' not in scenario:
            print '		I could not understand the "StreamingScenario" field '

        #nm_ho is the number of hosts (incuding datacenters) in the network
        nm_ho = nm_ho_sf + datac * 3
        extra_networks = self.config.sections()
        if (len(extra_networks) > 1):
            n_networks = len(extra_networks) - 1
            for i in range(n_networks):
                nm_ho += int(self.config2.get(extra_networks[i + 1], 'Hosts'))

        #All hosts will be listening for normal and small traffic
        for n in range(nm_ho):
            h = net.get('h{}'.format(n + 1))
            h.cmd('./net/listen.sh &')
            h.cmd('./net/small_listen.sh &')

        print "Generating traffic..."
        #DEBUGGING: not smart enough
        self.create_traffic(datac, nm_ho)

        #Simulation ID
        orig_timestamp = datetime.now()
        sim_id = str(orig_timestamp.year) + str(orig_timestamp.month) + str(
            orig_timestamp.day) + str(orig_timestamp.hour) + str(
                orig_timestamp.minute) + '_' + str(predefined_error)
        print "Simulation ID = %s" % sim_id
        #Setting up log
        print "Setting up log..."
        logger = logging.getLogger()
        hdlr = logging.FileHandler('/root/log/' + sim_id + '.log')
        formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
        hdlr.setFormatter(formatter)
        logger.addHandler(hdlr)
        logger.setLevel(logging.INFO)
        logger.info(sim_id + " start " +
                    str(json.dumps(errors.encode_errors())))

        switches_list = net.switches
        for switch in switches_list:
            errors.config_push(switch.dpid)

        print "Giving time for the collector to catch up..."
        time.sleep(25)

        print "Beginning test..."
        minutes = int(self.config.get('main', 'MinutesRunning'))
        now_timestamp = datetime.now()

        while (now_timestamp - orig_timestamp).total_seconds() < minutes * 60:
            time.sleep(error_interval * 2)
            if predefined_error != 0:
                if (predefined_error == 2 or predefined_error == 1):
                    print '1 and 2 errors not supported for the time being'
                    break
                self.create_error(predefined_error, nm_ho, datac, sim_id,
                                  logger, error_interval)
            else:
                # Excluding traffic errors (1 and 2) for the time being
                # Checking error 3 ...
                self.create_error(random.randint(4, 12), nm_ho, datac, sim_id,
                                  logger, error_interval)

            now_timestamp = datetime.now()

        logger.info(sim_id + " stop")
        print "Test ended. Shutting down network..."
        net.stop()

        return
Exemplo n.º 33
0
def myTopology():
    net = Containernet(
        switch=OVSKernelSwitch,
        build=False,
        autoSetMacs=True,
        autoStaticArp=True,
        link=TCLink,
    )

    mgr = VNFManager(net)
    setLogLevel("info")

    info("*** Add Switches\n")
    sconfig1 = {"dpid": "%016x" % 1}
    sconfig2 = {"dpid": "%016x" % 2}
    sconfig3 = {"dpid": "%016x" % 3}
    sconfig4 = {"dpid": "%016x" % 4}
    sconfig5 = {"dpid": "%016x" % 5}
    net.addSwitch("s1", **sconfig1)
    net.addSwitch("s2", **sconfig2)
    net.addSwitch("s3", **sconfig3)
    net.addSwitch("s4", **sconfig4)
    net.addSwitch("s5", **sconfig5)

    info("*** Add Hosts\n")
    host_config = dict(inNamespace=True)
    #net.addHost("h1", **host_config, ip="192.0.0.1")
    h1 = net.addDockerHost(
        "h1",
        dimage="dev_test",
        ip="192.0.0.1",
        docker_args={"hostname": "h1"},
    )
    h2 = net.addDockerHost(
        "h2",
        dimage="dev_test",
        ip="192.0.0.2",
        docker_args={"hostname": "h2"},
    )
    h3 = net.addDockerHost(
        "h3",
        dimage="dev_test",
        ip="192.0.0.3",
        docker_args={"hostname": "h3"},
    )
    h4 = net.addDockerHost(
        "h4",
        dimage="dev_test",
        ip="192.0.0.4",
        docker_args={"hostname": "h4"},
    )
    h5 = net.addDockerHost(
        "h5",
        dimage="dev_test",
        ip="192.0.0.5",
        docker_args={"hostname": "h5"},
    )
    h6 = net.addDockerHost(
        "h6",
        dimage="dev_test",
        ip="192.0.0.6",
        docker_args={"hostname": "h6"},
    )
    h7 = net.addDockerHost(
        "h7",
        dimage="dev_test",
        ip="192.0.0.7",
        docker_args={"hostname": "h7"},
    )
    h8 = net.addDockerHost(
        "h8",
        dimage="dev_test",
        ip="192.0.0.8",
        docker_args={"hostname": "h8"},
    )
    h9 = net.addDockerHost(
        "h9",
        dimage="dev_test",
        ip="192.0.0.9",
        docker_args={"hostname": "h9"},
    )

    info("*** Add Links\n")
    net.addLink("h1", "s1", bw=B1)
    net.addLink("h2", "s1", bw=B1)
    net.addLink("h3", "s1", bw=B1)
    net.addLink("s5", "h4", bw=B2)
    net.addLink("s5", "h5", bw=B2)
    net.addLink("s5", "h6", bw=B2)
    net.addLink("s1", "s2", bw=B1)
    net.addLink("s2", "s3", bw=B1, delay=DELAY)
    net.addLink("s3", "s4", bw=B1, delay=DELAY)
    net.addLink("s2", "s4", bw=B2)
    net.addLink("s1", "s4", bw=B1)
    net.addLink("s1", "s5", bw=B2)
    net.addLink("s4", "h7", bw=B1)
    net.addLink("s4", "h8", bw=B1)
    net.addLink("s4", "h9", bw=B1)

    info("*** Add controller\n")
    controller = RemoteController("c1", ip="127.0.0.1", port=6633)
    net.addController(controller)
    net.build()
    net.start()
    srv1 = mgr.addContainer(
        "srv1",
        "h1",
        "dev_test",
        "bash",
        docker_args={},
    )
    srv2 = mgr.addContainer(
        "srv2",
        "h2",
        "dev_test",
        "bash",
        docker_args={},
    )
    srv3 = mgr.addContainer(
        "srv3",
        "h3",
        "dev_test",
        "bash",
        docker_args={},
    )
    srv4 = mgr.addContainer(
        "srv4",
        "h4",
        "dev_test",
        "bash",
        docker_args={},
    )
    srv5 = mgr.addContainer(
        "srv5",
        "h5",
        "dev_test",
        "bash",
        docker_args={},
    )
    srv6 = mgr.addContainer(
        "srv6",
        "h6",
        "dev_test",
        "bash",
        docker_args={},
    )
    srv7 = mgr.addContainer(
        "srv7",
        "h7",
        "dev_test",
        "bash",
        docker_args={},
    )
    srv8 = mgr.addContainer(
        "srv8",
        "h8",
        "dev_test",
        "bash",
        docker_args={},
    )
    srv9 = mgr.addContainer(
        "srv9",
        "h9",
        "dev_test",
        "bash",
        docker_args={},
    )
    spawnXtermDocker("srv4")
    spawnXtermDocker("srv7")
    CLI(net)
    mgr.removeContainer("srv1")
    mgr.removeContainer("srv2")
    mgr.removeContainer("srv3")
    mgr.removeContainer("srv4")
    mgr.removeContainer("srv5")
    mgr.removeContainer("srv6")
    mgr.removeContainer("srv7")
    mgr.removeContainer("srv8")
    mgr.removeContainer("srv9")
    net.stop()
    mgr.stop()
Exemplo n.º 34
0
def Start(GI=False, MCS=3, Bandwidth=40, UDP=True, TP=54, 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')
    h3 = net.addHost('h3')
    h4 = net.addHost('h4')
    #h5 = net.addHost( 'h5' )
    #h6 = net.addHost( 'h6' )
    h7 = net.addHost('h7')
    h8 = net.addHost('h8')

    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 = "VhtMcs" + str(mcs)

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

    wifi.machelper = ns.wifi.WifiMacHelper()

    #wifi.wifihelper.SetRemoteStationManager( "ns3::ConstantRateWifiManager",
    #                                         "DataMode", ns.core.StringValue ("VhtMcs8"), "ControlMode", ns.core.StringValue ("VhtMcs8") )

    Sssid = "wifi-80211acCA"

    wifi.addSta(h0, ext="ac", ssid=Sssid, port=9977, qosSupported=True)
    wifi.addSta(h3, ext="ac", ssid=Sssid, port=9998, qosSupported=True)
    wifi.addSta(h4, ext="ac", ssid=Sssid, port=9994, qosSupported=True)
    #wifi.addSta( h5,ext="ac", ssid=Sssid, port=9993, qosSupported=True)
    #wifi.addSta( h6,ext="ac", ssid=Sssid, port=9992, qosSupported=True)
    wifi.addSta(h7, ext="ac", ssid=Sssid, port=9977, qosSupported=True)
    wifi.addSta(h8, ext="ac", ssid=Sssid, port=9966, qosSupported=True)

    wifi.addAp(h2, ext="ac", ssid=Sssid, port=9999, qosSupported=True)

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

    if PCAP == True:
        wifi.phyhelper.SetPcapDataLinkType(
            ns.wifi.WifiPhyHelper.DLT_IEEE802_11_RADIO)
        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')
    h2.setIP('192.168.123.3/24')
    h3.setIP('192.168.123.4/24')
    h4.setIP('192.168.123.5/24')
    #h5.setIP('192.168.123.6/24')
    #h6.setIP('192.168.123.7/24')
    h7.setIP('192.168.123.8/24')
    h8.setIP('192.168.123.9/24')

    mininet.ns3.start()

    time.sleep(2)

    info('\n *** Testing network connectivity\n')
    #net.pingFull()

    info('*** Start capturing pcaps\n')
    #h0.cmd("tcpdump -i h0-eth9998 -w h0_test.pcap & ")
    h2.cmd("tcpdump -i h2-eth9999 -w h2_test_multiSTA.pcap & ")

    time.sleep(2)

    # info( '*** Video measurement\n' )
    h0.cmd("iperf3 -s -i 1 -p 9999 --cport 9999 | tee sta_VI_CBR_h0.txt &")
    time.sleep(2)
    val = "iperf3 -c 192.168.123.1 -b 20m -M 1024 -Z -p 9999 -t 30 -i 1 --cport 9999 -S 0x4 &"
    h2.cmd(val)

    time.sleep(3)

    info('*** Voice measurement\n')
    h3.cmd("iperf3 -s -i 1 -p 9998 | tee sta_VO_CBR_h3.txt &")
    h2.cmd("iperf3 -s -i 1 -p 9989 | tee ap_VO_CBR_h4.txt &")
    h4.cmd("iperf3 -s -i 1 -p 9994 | tee sta_VO_CBR_h4.txt &")
    #h2.cmd( "iperf3 -s -i 1 -p 9949 | tee ap_VO_CBR_h5.txt &" )
    # h5.cmd( "iperf3 -s -i 1 -p 9993 | tee sta_VO_CBR_h5.txt &" )
    #h2.cmd( "iperf3 -s -i 1 -p 9939 | tee ap_VO_CBR_h6.txt &" )
    # h6.cmd( "iperf3 -s -i 1 -p 9992 | tee sta_VO_CBR_h6.txt &" )
    h2.cmd("iperf3 -s -i 1 -p 9929 | tee ap_VO_CBR_h3.txt &")

    time.sleep(2)

    val = "iperf3 -c 192.168.123.4 -u -b 64k -Z --length 160 -p 9998 -t 25 -i 1 --cport 9998 -S 0x6 &"
    h2.cmd(val)
    val = "iperf3 -c 192.168.123.3 -u -b 64k -Z --length 160 -p 9929 -t 25 -i 1 --cport 9929 -S 0x6 &"
    h3.cmd(val)
    # val = "iperf3 -c 192.168.123.7 -u -b 64k -Z --length 160 -p 9992 -t 25 -i 1 --cport 9992 -S 0x6 &"
    # h2.cmd(val)
    #val = "iperf3 -c 192.168.123.3 -u -b 6.4m -Z --length 160 -p 9939 -t 25 -i 1 --cport 9939 -S 0x6 &"
    #h6.cmd(val)
    # val = "iperf3 -c 192.168.123.6 -u -b 64k -Z --length 160 -p 9993 -t 25 -i 1 --cport 9993 -S 0x6 &"
    # h2.cmd(val)
    #val = "iperf3 -c 192.168.123.3 -u -b 6.4m -Z --length 160 -p 9949 -t 25 -i 1 --cport 9949 -S 0x6 &"
    #h5.cmd(val)
    val = "iperf3 -c 192.168.123.5 -u -b 64k -Z --length 160 -p 9994 -t 25 -i 1 --cport 9994 -S 0x6 &"
    h2.cmd(val)
    val = "iperf3 -c 192.168.123.3 -u -b 64k -Z --length 160 -p 9989 -t 25 -i 1 --cport 9989 -S 0x6 &"
    h4.cmd(val)

    time.sleep(3)

    info('*** BE&BK measurement\n')
    h7.cmd("iperf3 -s -i 1 -p 9977 | tee sta_BE_CBR_h7.txt &")
    h2.cmd("iperf3 -s -i 1 -p 9979 | tee ap_BE_CBR_h8.txt &")
    h8.cmd("iperf3 -s -i 1 -p 9966 | tee sta_BK_CBR_h8.txt &")
    h2.cmd("iperf3 -s -i 1 -p 9969 | tee ap_BK_CBR_h7.txt &")

    time.sleep(2)

    val = "iperf3 -c 192.168.123.3 -M 750 -l 750 -Z -b 250k -p 9969 -t 20 --cport 9666 -i 1 -S 0x1 &"
    h7.cmd(val)
    val = "iperf3 -c 192.168.123.9 -M 750 -l 750 -Z -b 250k -p 9966 -t 20 --cport 9996 -i 1 -S 0x1 &"
    h2.cmd(val)
    val = "iperf3 -c 192.168.123.3 -M 501 -l 501 -Z -b 161k -p 9979 -t 20 --cport 9777 -i 1 -S 0x0 &"
    h8.cmd(val)
    val = "iperf3 -c 192.168.123.8 -M 501 -l 501 -Z -b 161k -p 9977 -t 20 --cport 9997 -i 1 -S 0x0 &"
    h2.cmd(val)

    time.sleep(10)
    #CLI(net)

    info("***Ending TCPDump and cleaning up***\n")
    h3.cmd("killall tcpdump")
    h4.cmd("killall tcpdump")
    #h5.cmd("killall tcpdump")
    #h6.cmd("killall tcpdump")
    h2.cmd("killall tcpdump")
    h0.cmd("killall tcpdump")
    h7.cmd("killall tcpdump")
    h8.cmd("killall tcpdump")

    h3.cmd("killall iperf3")
    h4.cmd("killall iperf3")
    #h5.cmd("killall iperf3")
    #h6.cmd("killall iperf3")
    h2.cmd("killall iperf3")
    h0.cmd("killall iperf3")
    h7.cmd("killall iperf3")
    h8.cmd("killall iperf3")

    mininet.ns3.stop()
    mininet.ns3.clear()
    net.stop()
Exemplo n.º 35
0
def main():

    topo = MakeSwitchTopo(args.behavioral_exe, args.json)
    net = Mininet(topo=topo, host=P4Host, switch=P4Switch, controller=None)
    net.start()

    h1 = net.get('h1')
    # h1.setARP('10.0.0.1','00:aa:bb:00:00:02')
    h1.setDefaultRoute('dev eth0')
    h2 = net.get('h2')
    # h2.setARP('10.0.0.1','00:aa:cc:00:00:01')
    h2.setDefaultRoute('dev eth0')

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

    sleep(1)

    print "Ready !"

    CLI(net)
    net.stop()


if __name__ == '__main__':
    setLogLevel('debug')  #debug,info
    main()
def emptyNet():
    
    #root = Tk()
    
    
    #"Create an empty network and add nodes to it."

    #####################
    hostCount=0
    a=1 #Loop Variable to assign hosts of hostCount

    ipstring = "" 
    i=1 #Loop Variable to assign ip to hosts

    switchCount=0
    b=1 #Loop Variable for allocating switchCount switches
    j=1 #Loop Variable for assigning switches of switchCount

    hostLink=0 #Number of host to be connected in link
    switchLink=0 #Number of switch to be connected in link
    hostCounter = 0 #For it to stop asking for input when the number of hosts are completed

    #####################

    add_new("This window shows all\nthe progress the user generates \n\n\n\n\n\n\n")
    #roo = Tk()
    #roo.withdraw()

    net = Mininet( controller=Controller )

    info( '*** Adding controller\n' )
    net.addController( 'c0' )

    
    #hostCount=input('Enter the total number of hosts ')
    
    hostCount = tkSimpleDialog.askinteger("Number of Hosts","Enter the number of hosts? ")
    add_new("Number of hosts added are %s"%hostCount)   

    hosts=[Mininet(controller=Controller)] #List for hosts  
    #Loop for allocation host count hosts to list
    
    hosts.append(Mininet(controller=Controller)) #To avoid h0


    while a<=hostCount: 
    hosts.append(Mininet(controller=Controller))
    a=a+1
    #Loop to assign hosts of hostCount
    

    
    
    while i<=hostCount:
    k=str(i)
    #ipstring = raw_input("Enter an ip for host h"+k + " ")
    ipstring = tkSimpleDialog.askstring("IP for host h%s"%k,"Enter an ip for host h%s (Must be of xx.xx.xx.xx format) "%k)
    hosts[i]=net.addHost('h'+k,ip=ipstring)
    i=i+1
    info('Host added h'+k)
    info(' with ip of ' + ipstring)
    add_new("Host added h{0} with ip of {1}".format(k,ipstring))    
    info('\n')

#switchCount=input('Enter the total number of switches: ')
    switchCount = tkSimpleDialog.askinteger("Switches","Enter the total Number of switches")
    switches=[Mininet(controller=Controller)] #List for Switches
    add_new("Number of switches added = %s"%switchCount)

    
    switches.append(Mininet(controller=Controller)) #To avoid s0
    #Loop for allocating switchCount switches
    while b<=switchCount:
    switches.append(Mininet(controller=Controller))
    b=b+1


    
    #loop for assigning switches of switchCount
    while j<=switchCount:
    l=str(j)
    switches[j]=net.addSwitch( 's'+l)
    j=j+1
    info('Switch added s'+l)
    info('\n')
    

        
    #Loop for making links

    
    while hostCounter < hostCount or hostLink == -1:
        #hostLink=input("\nEnter host number that you want to link(-1 to finish or press cancel)\n")
    hostLink = tkSimpleDialog.askinteger("Linking ...","Enter the host number that you want to link (-1 to finish or press cancel)")
    if hostLink ==-1:
       break
        #switchLink=input("Enter switch number that you want to link it with\n")
    switchLink = tkSimpleDialog.askinteger("Linking ...","Enter switch number that you want to link h{0} with ".format(hostLink))
    
    add_new("\nEstablishing connectiong between desired host/switch")   
    #Establishing connectiong between desired host/switch
        net.addLink(hosts[hostLink],switches[switchLink])
    m=str(hostLink)
    n=str(switchLink)       
    info( "Link created between h"+m )
        info( " and s"+n)
    add_new("Link created between h{0} and s{1}".format(m,n))
    
    hostCounter = hostCounter + 1

    add_new("\n You can use the Command prompt from this point onwards. THANKS\n")
    info( '\n*** Starting network\n')
    net.start()

    info( '*** Running CLI\n' )
    CLI( net )

    info( '*** Stopping network' )
    net.stop()
    exit()
    

if __name__ == '__main__':

    
    root.geometry('+900+50')
    root.minsize(420,600)
    root.wm_title("Progress Report")

    setLogLevel( 'info' )
    emptyNet()
    exit()
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.addSta(h1, 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("80211ac_Sta2.pcap", h1.nsNode.GetDevice(0),
                                  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])
    #net.pingFull([h1,h2])
    #net.pingFull([h0,h1])
    info('*** Starting UDP iperf server on AP(h2)\n')
    h2.sendCmd("iperf -s -i 1 -u")
    info(
        '*** Testing bandwidth between h0 and h2 while h1 is not transmitting\n'
    )
    val = "iperf -c 192.168.123.3 -u -b " + str(TP) + "M"
    h0.cmdPrint(val)
    info(
        '*** Testing bandwidth between h0 and h2 while h1 is also transmitting\n'
    )
    val = "iperf -c 192.168.123.3 -u -b " + str(TP) + "M"
    h1.sendCmd(val)
    h0.cmdPrint(val)
Exemplo n.º 38
0
import logging
from mininet.log import setLogLevel
from emuvim.dcemulator.net import DCNetwork
from emuvim.api.rest.rest_api_endpoint import RestApiEndpoint
from emuvim.api.openstack.openstack_api_endpoint import OpenstackApiEndpoint

from emuvim.api.aro.endpoint import Endpoint
from emuvim.api.aro.arorm import ARORM
from emuvim.api.aro.placement import FirstDC, RoundRobinDC, placevnf

logging.basicConfig(level=logging.INFO)
setLogLevel('info')  # set Mininet loglevel

logging.getLogger('werkzeug').setLevel(logging.DEBUG)
logging.getLogger('api.openstack.base').setLevel(logging.DEBUG)
logging.getLogger('api.openstack.compute').setLevel(logging.DEBUG)
logging.getLogger('api.openstack.keystone').setLevel(logging.DEBUG)
logging.getLogger('api.openstack.nova').setLevel(logging.DEBUG)
logging.getLogger('api.openstack.neutron').setLevel(logging.DEBUG)
logging.getLogger('api.openstack.heat').setLevel(logging.DEBUG)
logging.getLogger('api.openstack.heat.parser').setLevel(logging.DEBUG)
logging.getLogger('api.openstack.glance').setLevel(logging.DEBUG)
logging.getLogger('api.openstack.helper').setLevel(logging.DEBUG)


class Topology(DCNetwork):
    def __init__(self):
        super(Topology, self).__init__(monitor=False, enable_learning=True)

    def setup_topo(self):
        self._create_dcs()
Exemplo n.º 39
0
            vc.start()
            #  once the client complete, lets stop the throttling
            tl.terminate()

            sleep(2)
            print("all godash clients have finished streaming")
            # reset the system network
            os.system(
                "tc class change dev s1-eth1 parent 1:0 classid 1:1 htb rate %fkbit ceil %fkbit"
                % (10000, 10000))

            genstats_voip_clients(serverHost, voip_host, int(args.voipclients),
                                  subfolder, run, current_folder)

            net.stop()
            if args.transport_mode == "tcp" and args.serverType == "WSGI":
                Popen("pgrep -f caddy | xargs kill -9", shell=True).wait()
                caddy_s1 = serverHost.popen("rm ./output/caddy_access.log")
            if args.transport_mode == "quic" and args.serverType == "WSGI":
                Popen("pgrep -f example | xargs kill -9", shell=True).wait()
            if args.collaborative == "on":
                # lets stop consul
                os.system("killall -9 consul")


if __name__ == '__main__':
    os.system("mn -c")
    setLogLevel('output')
    goDashBedNet()
    os.system("chmod 777 -R *")
Exemplo n.º 40
0
                      metavar="INTEGER",
                      type="int",
                      default=4)
    parser.add_option("-s",
                      "--spines",
                      dest="spine_count",
                      help="specify the number of spine switches",
                      metavar="INTEGER",
                      type="int",
                      default=2)
    parser.add_option("-c",
                      "--controller",
                      dest="controllers",
                      help="specify the IP address of the controller",
                      action="append",
                      metavar="IP")
    parser.add_option("-v",
                      "--verbose",
                      dest="verbose",
                      help="display additional logging information",
                      action="store_true",
                      default=False)

    (options, args) = parser.parse_args()

    if options.verbose:
        setLogLevel('debug')
    else:
        setLogLevel('info')
    simpleTest(options)
Exemplo n.º 41
0
class OVSUser(OVSAP):
    "OVS User AP convenience class"

    def __init__(self, *args, **kwargs):
        kwargs.update(datapath='user')
        OVSAP.__init__(self, *args, **kwargs)


class testSwitchOVSUser(TestSwitchDpidAssignmentOVS):
    "Test dpid assignnment of OVS User AP."
    accessPointClass = OVSUser


@unittest.skipUnless(quietRun('which ivs-ctl'), 'IVS ap is not installed')
class testSwitchIVS(TestSwitchDpidAssignmentOVS):
    "Test dpid assignment of IVS ap."
    accessPointClass = IVSSwitch


@unittest.skipUnless(quietRun('which ofprotocol'),
                     'Reference user ap is not installed')
class testSwitchUserspace(TestSwitchDpidAssignmentOVS):
    "Test dpid assignment of Userspace ap."
    accessPointClass = UserAP


if __name__ == '__main__':
    setLogLevel('warning')
    unittest.main()
Exemplo n.º 42
0
from mininet.cli import CLI
from mininet.log import setLogLevel, info, error
from mininet.net import Mininet
from mininet.node import RemoteController, OVSSwitch
from mininet.link import TCLink

if __name__ == "__main__":
    default_hs_bw = 10
    default_ss_bw = 10
    default_gs_bw = 10
    default_ng_bw = 10

    setLogLevel("info")
    net = Mininet(switch=OVSSwitch, listenPort=6633, ipBase='191.0.0.1/4')

    mycontroller = RemoteController("RemoteController")
    net.controllers = [mycontroller]
    net.nameToNode["RemoteController"] = mycontroller

    # host
    # tenant 1
    host1 = net.addHost('h1', ip="191.168.2.1", mac='00:00:00:00:01:01')
    host2 = net.addHost('h2', ip="192.168.2.2", mac='00:00:00:00:01:02')

    # tenant 2
    host3 = net.addHost('h3', ip="191.168.2.1", mac='00:00:00:00:01:03')
    host4 = net.addHost('h4', ip="192.168.2.2", mac='00:00:00:00:01:04')

    # switch
    switch1 = net.addSwitch('s1', ip="191.168.3.1", datapath='user')
    switch2 = net.addSwitch('s2', ip="191.168.3.2", datapath='user')
Exemplo n.º 43
0
def Start(OFDM_R=9, UDP=True, TP=9, 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')
    h3 = net.addHost('h3')
    h4 = net.addHost('h4')
    h5 = net.addHost('h5')

    wifi = WIFISegment()

    #CONFIGURATION
    udp = UDP
    bandwidth = 20
    ofdm_r = "OfdmRate" + str(OFDM_R) + "Mbps"
    OfdmRate = ofdm_r  #9,24,48
    if udp == False:
        #TCP
        payloadSize = 1448  #bytes
        ns.core.Config.SetDefault("ns3::TcpSocket::SegmentSize",
                                  ns.core.UintegerValue(payloadSize))
    else:
        payloadSize = 1472

    wifi = WIFISegment()

    wifi.wifihelper.SetStandard(ns.wifi.WIFI_PHY_STANDARD_80211a)

    wifi.wifihelper.SetRemoteStationManager(
        "ns3::ConstantRateWifiManager", "DataMode",
        ns.core.StringValue(OfdmRate), "ControlMode",
        ns.core.StringValue("OfdmRate9Mbps"))

    Sssid = "wifi-80211a"

    wifi.addSta(h0, ssid=Sssid)
    wifi.addSta(h1, ssid=Sssid)
    wifi.addSta(h2, ssid=Sssid)
    wifi.addSta(h3, ssid=Sssid)
    wifi.addSta(h4, ssid=Sssid)
    wifi.addAp(h5, 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("80211a_sta1.pcap", h0.nsNode.GetDevice(0),
                                  True, True)
        wifi.phyhelper.EnablePcap("80211a_sta2.pcap", h1.nsNode.GetDevice(0),
                                  True, True)
        wifi.phyhelper.EnablePcap("80211a_sta3.pcap", h2.nsNode.GetDevice(0),
                                  True, True)
        wifi.phyhelper.EnablePcap("80211a_sta4.pcap", h3.nsNode.GetDevice(0),
                                  True, True)
        wifi.phyhelper.EnablePcap("80211a_sta5.pcap", h4.nsNode.GetDevice(0),
                                  True, True)
        wifi.phyhelper.EnablePcap("80211a_ap.pcap", h5.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')
    h3.setIP('192.168.123.4/24')
    h4.setIP('192.168.123.5/24')
    h5.setIP('192.168.123.6/24')

    mininet.ns3.start()

    #info( '\n *** Testing network connectivity\n' )
    net.pingFull([h0, h5])
    #net.pingFull([h1,h2])
    #net.pingFull([h0,h1])
    info('*** Starting UDP iperf server on AP(h5)\n')
    h5.sendCmd("iperf -s -i 1 -u")
    info(
        '*** Testing bandwidth between h0 and h5 while others stas are not transmitting\n'
    )
    val = "iperf -c 192.168.123.6 -u -b " + str(TP) + "M"
    h0.cmdPrint(val)
    info(
        '*** Testing bandwidth between h0 and h5 while all stats are also transmitting\n'
    )
    val = "iperf -c 192.168.123.6 -u -b " + str(TP) + "M"
    h0.sendCmd(val)
    h1.sendCmd(val)
    h2.sendCmd(val)
    h3.sendCmd(val)
    h4.cmdPrint(val)
Exemplo n.º 44
0
    def simulate(self, controller=None, client=True, minute=1):
        # 删除上一次的测试文件
        U.del_file(FilePath.res_path)

        print('*****************************************')
        print('******     NET is establishing     ******')
        print('*****************************************')
        print
        setLogLevel("info")
        topo = self.datacenter.dc_topo

        if controller is None:
            self.net = Net(switch=OVSSwitch, controller=Controller)
            self.net.addController('c0')
        else:
            if controller["type"] == "remote":
                self.net = Net(switch=OVSSwitch, listenPort=controller["port"])
                mycontroller = RemoteController("RemoteController")
                self.net.controllers = [mycontroller]
                self.net.nameToNode["RemoteController"] = mycontroller
            else:
                self.net = Net(switch=OVSSwitch, controller=Controller)
                self.net.addController('c0')

        net = self.net

        hosts = topo.hosts
        switches = topo.switches
        gateways = topo.gateways

        # add node
        for h in hosts:
            net.addHost(h.name, ip=h.ip, mac=h.mac)
        for s in switches:
            net.addSwitch(s.name,
                          ip=s.ip,
                          mac=s.mac,
                          dpid=Util.dpid_num_2_dpid_hex(s.dpid))
        for g in gateways:
            net.addSwitch(g.name,
                          ip=g.ip,
                          dpid=Util.dpid_num_2_dpid_hex(g.dpid))

        # add link
        for edge in topo.graph.edges:
            self.add_link(edge)

        if client:
            net.start()
            self.set_default_gateway()
            # self.ping_all()
            # self.set_up_udp_listener()
            CLI(net)
            net.stop()
            return
        else:
            st = time.time()
            net.start()
            print('*****************************************')
            print('*** NET has been successfully created ***')
            print('*****************************************')
            print

            et = time.time()
            print('======================================================')
            with open('1.txt', 'w') as f:
                f.write(str(et - st))
                f.close()

            wait_time = 3
            print('*****************************************')
            print(
                '***  please wait for {} ses to start  ***'.format(wait_time))
            print('*****************************************')
            print
            time.sleep(wait_time)

            self.set_default_gateway()
            st = time.time()
            print('*****************************************')
            print('***       Start to do Ping test       ***')
            print('*****************************************')
            print
            # if self.ping_all():
            if True:
                print('*****************************************')
                print('******       Pass Ping test       *******')
                print('*****************************************')
                print
            else:
                print('*****************************************')
                print('******       Fail Ping test       *******')
                print('*****************************************')
                print
            et = time.time()
            print('======================================================')
            with open('2.txt', 'w') as f:
                f.write(str(et - st))
                f.close()

            print('*****************************************')
            print('*****       Start to simulate       *****')
            print('*****************************************')
            print
            self.set_up_udp_listener()
            time.sleep(2)
            self.simulate_flow(minute=minute)
            pkt_loss = self.pkt_loss()
            if pkt_loss == -1:
                print('*****************************************')
                print('******     Result Parser Fail     *******')
                print('*****************************************')
            else:
                print('*****************************************')
                print('******     Total pkt loss is {}   '.format(
                    round(pkt_loss, 4)))
                print('*****************************************')
            CLI(net)
            net.stop()
def Main():
    setLogLevel('info')
    net = Mininet(topo=None, build=False)

    # Create nodes
    h1 = net.addHost('h1',
                     mac='01:00:00:00:01:00',
                     ip='192.168.33.10/24',
                     defaultRoute="via 192.168.33.1")
    h2 = net.addHost('h2',
                     mac='01:00:00:00:02:00',
                     ip='192.168.34.10/24',
                     defaultRoute="via 192.168.34.1")
    h3 = net.addHost('h3',
                     mac='01:00:00:00:03:00',
                     ip='192.168.33.11/24',
                     defaultRoute="via 192.168.33.1")
    # h1 = net.addHost('h1', mac='01:00:00:00:01:00', ip='192.168.33.10/24')
    # h2 = net.addHost('h2', mac='01:00:00:00:02:00', ip='192.168.34.10/24')

    # Create switches
    s1 = net.addSwitch('s1', listenPort=6634, mac='00:00:00:00:00:01')
    s2 = net.addSwitch('s2', listenPort=6634, mac='00:00:00:00:00:02')
    s3 = net.addSwitch('s3', listenPort=6634, mac='00:00:00:00:00:03')

    # non sdn switch to enable multiple hosts behind a port.
    s10 = net.addSwitch('s10', protocols='OpenFlow13', failMode='standalone')

    # create links
    print "*** Creating links"
    net.addLink(
        h1,
        s10,
    )
    net.addLink(
        h3,
        s10,
    )
    net.addLink(s10, s1)
    net.addLink(
        s1,
        s2,
    )
    net.addLink(
        s2,
        s3,
    )
    net.addLink(
        h2,
        s3,
    )

    # Create controller access
    c0 = net.addController('c0',
                           controller=RemoteController,
                           ip='192.168.33.101',
                           port=6633)
    c1 = net.addController('c1',
                           controller=RemoteController,
                           ip='192.168.33.102',
                           port=6633)

    net.build()
    s1.start([c0])
    s2.start([c0])
    s3.start([c1])
    s10.start([])

    s1.cmdPrint('ovs-vsctl show')
    CLI(net)
    #print "Ping h2 from h1"
    #try:
    #     while True:
    #         print h1.cmd('ping -c1 %s' % h2.IP())
    #         time.sleep(1)
    # except KeyboardInterrupt:
    #     print "\nWarning: Caught KeyboardInterrupt, stopping network"
    #     net.stop()
    net.stop()
Exemplo n.º 46
0
def main():
    setLogLevel('info')  # set Mininet loglevel
    create_topology1()
Exemplo n.º 47
0
	f.write(", {}, ".format(rtt2))
		
	bandwidth = net.iperf((h1,h2),fmt='-M 1074 -f M')
	f.write(str(bandwidth))
	bw1=bandwidth[0].split()
	b1=bw1[0]
	bw2=bandwidth[1].split()
	b2=bw2[0]
	cwnd=((float(rtt1)*float(b1)*1000)+(float(rtt2)*float(b2)*1000))/2
	cwnd=float(cwnd/1024)
	f.close()
	net.stop()
	return cwnd

if __name__ == '__main__':
	setLogLevel('error')
	os.system("sysctl -w net.ipv4.tcp_congestion_control=reno")
	bandwidth=[10]
	#bandwidth=[10,9,8]
	#queue = [30,20]
	queue=[30]
	
	loss=numpy.logspace(-1.5,0.69,num=100,base=10.0)
	
	x=[]
	y=[]
	c=[]
	count=1 
	for q in queue:	
		for b in bandwidth:
			for l in loss:
Exemplo n.º 48
0
    info( "*** Creating hosts\n" )
    hosts1 = [ net.addHost( 'h%d' % n ) for n in ( 3, 4 ) ]
    hosts2 = [ net.addHost( 'h%d' % n ) for n in ( 5, 6 ) ]

    info( "*** Creating links\n" )
    for h in hosts1:
        net.addLink( s1, h )
    for h in hosts2:
        net.addLink( s2, h )
    net.addLink( s1, s2 )

    info( "*** Starting network\n" )
    net.build()
    c1.start()
    c2.start()
    s1.start( [ c1 ] )
    s2.start( [ c2 ] )

    info( "*** Testing network\n" )
    net.pingAll()

    info( "*** Running CLI\n" )
    CLI( net )

    info( "*** Stopping network\n" )
    net.stop()

if __name__ == '__main__':
    setLogLevel( 'info' )  # for CLI output
    multiControllerNet()
Exemplo n.º 49
0
        values = [float(s) for s in pout.splitlines()]
        avgnetms = sum(values) / len(values) * 1000.0
        info('*** Average per-ping latency %.3f ms\n' % avgnetms)
        info('*** %s pings completed in %.3f seconds\n' %
             (opts.pings, elapsed))
        avgms = (elapsed / opts.pings * 1000.0)
        info('*** Average ping time overall: %.3f ms\n' % avgms)
        info('*** Stopping cpu stress processes and collecting output\n')
        result = {}
        quietRun('pkill -f ' + cpustress)
        for key, popen in cmd.iteritems():
            popen.terminate()
            info('.')
            result[key] = int(popen.communicate()[0])
        info('\n')
        # Print sorted cpu stress output
        print "*** cpu stress process output:"
        print[(key, result[key]) for key in sorted(result)]
        # Get rid of any stragglers
        print quietRun('pkill -9 -f ' + cpustress)
        info('*** Stopping updping')
        print quietRun('pkill -9 udping')

        net.stop()


if __name__ == '__main__':
    setLogLevel('info')
    opts, args = parseOptions()
    pingpongtest(opts)
Exemplo n.º 50
0
        hosts = int(args.hosts)

    if args.duration:
        duration = int(args.duration)

    if args.queue:
        queueType = str(args.queue)

    return (switches, hosts, duration, queueType)


if __name__ == '__main__':

    (switches, hosts, duration, queueType) = parseArguments()

    setLogLevel('warn')

    net = setUpTopology(switches, hosts)
    warn('\n*** Simulation time: {duration} seconds\n'.format(
        duration=duration))

    setUpQueue(net, queueType)

    s0 = net.get('s0')
    s0.cmd('tcpdump -i {intf} -w jows-0.pcap &'.format(intf='s0-eth1'))

    background(net, hosts=hosts, duration=duration)
    stream(net, hosts=hosts, duration=duration)

    warn("*** Processing...\n")
    time.sleep(duration + 5)
Exemplo n.º 51
0
    speaker1.intf('speaker1-eth1').setIP('1.1.1.1/24')
    speaker2.intf('speaker2-eth1').setIP('1.1.1.3/24')

    stopsshd()

    hosts = [peer64514, peer64515, peer64516, host64514]
    startsshds(hosts)
    '''
    forwarding1 = '%s:2000:%s:2000' % ( '1.1.1.2', onos1IP )
    root.cmd( 'ssh -nNT -o "PasswordAuthentication no" \
    -o "StrictHostKeyChecking no" -l sdn -L %s %s & ' % ( forwarding1, onos1IP ) )

    forwarding2 = '%s:2000:%s:2000' % ( '1.1.1.4', onos2IP )
    root.cmd( 'ssh -nNT -o "PasswordAuthentication no" \
    -o "StrictHostKeyChecking no" -l sdn -L %s %s & ' % ( forwarding2, onos2IP ) )

    forwarding3 = '%s:2000:%s:2000' % ( '1.1.1.6', onos3IP )
    root.cmd( 'ssh -nNT -o "PasswordAuthentication no" \
    -o "StrictHostKeyChecking no" -l sdn -L %s %s & ' % ( forwarding3, onos3IP ) )
    '''
    CLI(net)

    stopsshd()
    stopquagga()
    net.stop()


if __name__ == '__main__':
    setLogLevel('debug')
    sdn1net()
Exemplo n.º 52
0
    """
    Remocao da quebra de linha dupla na serializacao da mensagem,
    O metodo makePickle foi redefinido para enviar somente a string
    do LogRecord
    O método é internamente chamado pela classe SocketHandler para 
    escrita do objeto serializável, durante a execução da método
    handler da super classe
    """
    
    def makePickle(self, record):
        try:
            msg = record.getMessage() # Ou format(record)
            fmt = '%s'
            return pickle.dumps(fmt % msg)
        except:
            self.handleError( record )
            return pickle.dumps('*** Error ')
    

"""
A classe Lg é herdado de Logger, atuando como controlador, permitindo a alteração por ser singleton
"""
setLogLevel('info') #Seta o setLevel do controlador

def connection_addr(addr_client = 'localhost'):
    socket_handler = SocketHandlerMininet(addr_client, handlers.DEFAULT_TCP_LOGGING_PORT)
    socket_handler.setLevel(logging.INFO)
    lg.addHandler(socket_handler)