예제 #1
1
파일: ns3.py 프로젝트: rascov/OpenNet
 def delete( self ):
     "Delete interface"
     if self.nsInstalled:
         warn( "You can not delete once installed ns-3 device, "
               "run mininet.ns3.clear() to delete all ns-3 devices\n" )
     else:
         Intf.delete( self )
예제 #2
0
파일: ns3.py 프로젝트: EliseuTorres/OpenNet
 def rename( self, newname ):
     "Rename interface"
     # If TapBridge is installed in ns-3, but ns-3 has not connected to the Linux tap interface yet...
     if self.nsInstalled and not self.isConnected():
         # ...change device name in TapBridge to the new one.
         self.tapbridge.SetAttribute ( "DeviceName", ns.core.StringValue( newname ) )
     Intf.rename( self, newname )
예제 #3
0
    def _create_links(self, links):
        def is_remote(node):
            return isinstance(node, RemoteSwitch)

        def is_local(node):
            return not is_remote(node)

        self._info('**** Create %d link(s)' % len(links))
        for id, link in links.iteritems():
            self._debug('\tCreate link %s with params: %s' % (id, link))
            node1 = self.net.get(link['node1'])
            node2 = self.net.get(link['node2'])
            name_to_node = {'node1': node1, 'node2': node2}
            link.update(name_to_node)

            remote = filter(is_remote, [node1, node2])
            local = filter(is_local, [node1, node2])
            if not remote:
                self.net.addLink(**link)
            else:
                sw = local[0]
                r = remote[0]
                intfName = r.params['local_intf_name']
                r_mac = None  # unknown, r.params['remote_mac']
                r_port = r.params['remote_port']
                self._debug('\tadd hw interface (%s) to node (%s)' %
                            (intfName, sw.name))

                # This hack avoids calling __init__ which always makeIntfPair()
                link = Link.__new__(Link)
                i1 = Intf(intfName, node=sw, link=link)
                i2 = Intf(intfName, node=r, mac=r_mac, port=r_port, link=link)
                i2.mac = r_mac  # mn runs 'ifconfig', which resets mac to None
                #
                link.intf1, link.intf2 = i1, i2
예제 #4
0
def main():
    topo = MyTopo(args.behavioral_exe, args.json, args.thrift_port)

    net = Mininet(topo=topo, host=P4Host, switch=P4Switch, controller=None)

    cpu_intf1 = Intf("m-veth-1", net.get('s1'), 11)
    cpu_intf2 = Intf("m-veth-2", net.get('s1'), 12)

    net.start()

    sleep(1)

    cmd = [args.cli, args.json, str(args.thrift_port)]
    with open(args.p4_path + "/commands.txt", "r") as f:
        print " ".join(cmd)
        try:
            output = subprocess.check_output(cmd, stdin=f)
            print output
        except subprocess.CalledProcessError as e:
            print e
            print e.output

    sleep(1)

    print "Ready !"

    CLI(net)
    net.stop()
예제 #5
0
파일: ns3.py 프로젝트: aydeger/mininet-lte
 def __init__(self,
              name,
              node,
              port=None,
              nsNode=None,
              nsDevice=None,
              mode=None,
              **params):
     """
     """
     self.name = name
     self.createTap()
     self.delayedMove = True
     if node.inNamespace:
         self.inRightNamespace = False
     else:
         self.inRightNamespace = True
     Intf.__init__(self, name, node, port, **params)
     allTBIntfs.append(self)
     self.nsNode = nsNode
     self.nsDevice = nsDevice
     self.mode = mode
     self.params = params
     self.nsInstalled = False
     self.tapbridge = ns.tap_bridge.TapBridge()
     if self.nsNode and self.nsDevice and (self.mode or self.node):
         self.nsInstall()
     if self.node and self.nsInstalled and self.isInstant(
     ):  # instant mode to be implemented in ns-3
         self.namespaceMove()
예제 #6
0
    def run_exercise(self):
        """ Sets up the mininet instance, programs the switches,
            and starts the mininet CLI. This is the main method to run after
            initializing the object.
        """
        # Initialize mininet with the topology specified by the config
        self.create_network()

	Intf('enp0s3', node=self.net.getNodeByName("s1"), port=255)
	Intf('enp0s3', node=self.net.getNodeByName("s2"), port=255)
	Intf('enp0s3', node=self.net.getNodeByName("s3"), port=255)

        self.net.start()
        sleep(1)

        # some programming that must happen after the net has started
        self.program_hosts()
        self.program_switches()

        # wait for that to finish. Not sure how to do this better
        sleep(1)

        self.do_net_cli()
        # stop right after the CLI is exited
        self.net.stop()
예제 #7
0
def oneswitch():

    CONTROLLER_IP = '127.0.0.1'

    net = Mininet(topo=None, build=False)

    net.addController('c0',
                      controller=RemoteController,
                      ip=CONTROLLER_IP,
                      port=6633)

    s0 = net.addSwitch('s0')

    h0 = net.addHost('h0', ip='192.168.1.5', mac='00:00:00:00:01:05')

    net.addLink(h0, s0)

    # Delete old tunnel if still exists
    s0.cmd('ip link del cntl-s0 || ip link del s0-cntl')

    # Create Veth Pair
    s0.cmd('ip link add cntl-s0 type veth peer name s0-cntl')
    s0.cmd('ip link set cntl-s0 up && ip link set s0-cntl up')

    Intf('s0-cntl', node=s0)
    Intf('eth2', node=s0)

    net.start()
    CLI(net)
    net.stop()
예제 #8
0
def run_fvtopo():
    # Create topology.
    net = Mininet(topo=FVTopo(),
                  controller=RemoteController,
                  autoSetMacs=True,
                  autoStaticArp=False,
                  link=TCLink)

    # Add external interface.
    intfName0 = 'eth0'
    intfName1 = 'eth1'

    switch1 = net.switches[0]
    info('*** Adding hardware interface', intfName0, 'to switch', switch1.name,
         '\n')
    _intf = Intf(intfName0, node=switch1)

    switch4 = net.switches[-1]
    info('*** Adding hardware interface', intfName1, 'to switch', switch4.name,
         '\n')
    _intf = Intf(intfName1, node=switch4)

    # Run it.
    net.start()
    CLI(net)
    net.stop()
예제 #9
0
 def rename( self, newname ):
     "Rename interface"
     # If TapBridge is installed in ns-3, but ns-3 has not connected to the Linux tap interface yet...
     if self.nsInstalled and not self.isConnected():
         # ...change device name in TapBridge to the new one.
         self.tapbridge.SetAttribute ( "DeviceName", ns.core.StringValue( newname ) )
     Intf.rename( self, newname )
예제 #10
0
 def delete(self):
     "Delete interface"
     if self.nsInstalled:
         warn("You can not delete once installed ns-3 device, "
              "run mininet.ns3.clear() to delete all ns-3 devices\n")
     else:
         Intf.delete(self)
예제 #11
0
    def _create_links(self, links):

        def is_remote(node):
            return isinstance(node, RemoteSwitch)

        def is_local(node):
            return not is_remote(node)

        self._info('**** Create %d link(s)' % len(links))
        for id, link in links.iteritems():
            self._debug('\tCreate link %s with params: %s' % (id, link))
            node1 = self.net.get(link['node1'])
            node2 = self.net.get(link['node2'])
            name_to_node = {'node1': node1, 'node2': node2}
            link.update(name_to_node)

            remote = filter(is_remote, [node1, node2])
            local = filter(is_local, [node1, node2])
            if not remote:
                self.net.addLink(**link)
            else:
                sw = local[0]
                r = remote[0]
                intfName = r.params['local_intf_name']
                r_mac = None # unknown, r.params['remote_mac']
                r_port = r.params['remote_port']
                self._debug('\tadd hw interface (%s) to node (%s)' % (intfName, sw.name))

                # This hack avoids calling __init__ which always makeIntfPair()
                link = Link.__new__(Link)
                i1 = Intf(intfName, node=sw, link=link)
                i2 = Intf(intfName, node=r, mac=r_mac, port=r_port, link=link)
                i2.mac = r_mac # mn runs 'ifconfig', which resets mac to None
                #
                link.intf1, link.intf2 = i1, i2
예제 #12
0
def createInboundNet():

    net = Mininet(topo=None,
                  build=False,
                  switch=OVSSwitch,
                  controller=InbandController)

    c0 = net.addController('c0', ip="10.10.100.1",
                           port=6633)  # set remote controller ip & port

    # add 3 hosts to network. controller software will run on h1
    h1 = net.addHost('h1', ip='192.168.0.1/24')

    # add switch, enable in-band control
    s1 = net.addSwitch('s1', inband=True)

    # add links
    net.addLink(h1, s1)

    # add interface
    intf1CtrName = "ens192"
    intf2CtrName = "ens224"
    _intf1Ctr = Intf(intf1CtrName, node=s1)
    _intf2Ctr = Intf(intf2CtrName, node=s1)

    net.start()

    # s1 need to be equipped with an ip address to contact the controller
    s1.cmd('ifconfig s1 inet 10.10.100.2/24')

    # run controller sofware on h1, and redirect STDOUT & STDERR to log file
    # h1.cmd("ovs-testcontroller ptcp:6633 1>/tmp/c0.log 2>/tmp/c0.log &")

    CLI(net)
    net.stop()
예제 #13
0
    def __init__(self, **opts):
        """Create custom topo."""

        # Initialize topology
        # It uses the constructor for the Topo cloass
        super(SimplePktSwitch, self).__init__(**opts)

        # Add hosts and switches
        #h1 = self.addHost('h1')
        #h2 = self.addHost('h2')


        # Adding switches
        s1 = self.addSwitch('s1', dpid="0000000000000001")
        s2 = self.addSwitch('s2', dpid="0000000000000002")
        s3 = self.addSwitch('s3', dpid="0000000000000003")
        s4 = self.addSwitch('s4', dpid="0000000000000004")
	    s5 = self.addSwitch('s5', dpid="0000000000000005")
		# agregar link
		info( '\n*** Creating Physical Interfaces ***\n' )
		info( '	*** Checking', 'eth0', '\n' )
		checkIntf( 'eth1' )
		eth0 = Intf( 'eth0' , node=s1 )
		info( '\n*** Creating Physical Interfaces ***\n' )
		info( '	*** Checking', 'eth1', '\n' )
		checkIntf( 'eth2' )
		eth0 = Intf( 'eth2' , node=s5 )
예제 #14
0
def redeThiago():
    # Criando topologia sem definicao, apenas para testes
    net = Mininet(topo=None, build=False)
    # Adiciona a Controladora com nome c0
    info('=> ADICIONANDO CONTROLLER c0...\n')
    net.addController(name='c0')

    # Cria switch s1, que deve ser bridge da eth1 e conectar o host h1
    info('=> ADICIONANDO SWITCH s1 NA PORTA 3364...\n')
    s1 = net.addSwitch('s1')
    # Adicionando eth1 da controller na switch s1
    Intf('eth1', node=s1)
    s1.listenPort = 6634

    # Cria switch s2, que deve ser bridge da eth2 e conectar o host h2
    info('=> ADICIONANDO SWITCH s2 NA PORTA 3365...\n')
    s2 = net.addSwitch('s2')
    # Adicionando eth2 da controller na switch s1
    Intf('eth2', node=s2)
    s2.listenPort = 6635

    # Cria o host h1 sem parametros de rede
    info('=> ADICIONANDO HOST h1...\n')
    h1 = net.addHost('h1', ip='0.0.0.0')

    # Cria o host h2 sem parametros de rede
    info('=> ADICIONANDO HOST h2...\n')
    h2 = net.addHost('h2', ip='0.0.0.0')

    # Monta a topologia fisica (links)
    info('=> LIGANDO HOSTS AO SWITCH...\n')
    # Liga host h1 ao switch s1
    net.addLink(h1, s1)
    # Liga host h2 ao switch s1 e s2
    net.addLink(h2, s2)  # Deve vir primeiro
    net.addLink(h2, s1)

    # Configuracoes de rede (IPs, MACs e DNS)
    info('=> CONFIGURANDO REDE NOS HOSTS...\n')
    net.start()

    h1.cmdPrint(
        'ifconfig h1-eth0 172.16.0.10 netmask 255.255.255.0 hw ether 00:00:00:00:00:02'
    )
    h1.cmdPrint('route add default gw 172.16.0.1')
    h1.cmdPrint('echo nameserver\ 8.8.8.8 > /etc/resolv.conf')

    h2.cmdPrint(
        'ifconfig h2-eth0 172.16.0.20 netmask 255.255.255.0 hw ether 00:00:00:00:00:03'
    )
    h2.cmdPrint('route add default gw 172.16.0.1')
    h2.cmdPrint('echo nameserver\ 8.8.8.8 > /etc/resolv.conf')

    h2.cmdPrint(
        'ifconfig h2-eth1 172.16.0.21 netmask 255.255.255.0 hw ether 00:00:00:00:00:05'
    )

    CLI(net)
    net.stop()
예제 #15
0
 def get_or_create_intf(dev_name, obj, port):
     if port not in obj.intfs:
         # does not exist, let's create it
         return Intf(dev_name, node=obj, port=port)
     if str(obj.intfs[port]) != dev_name:
         # intf exists, but port is invalid
         return Intf(dev_name, node=obj, port=port)
     return obj.intfs[port]
예제 #16
0
파일: architecture.py 프로젝트: Fdall/VCDN
    def linkBridgeCluster(self, bridge, cluster):
        clusterId = self.clusters.index(cluster) + 1
        bridgeId = self.bridges.index(bridge) + 1

        clusterIp = '30.0.0.%d' % clusterId

        bridgeIp = '20.0.0.2%d%d' % (bridgeId, clusterId)

        greNameBridge = 'gre%d' % clusterId
        greNameCluster = 'gre%d' % bridgeId

        ### Create gre in cluster
        greRouter = cluster.greRouter

        # Create gre interface
        greRouter.cmd('ip tunnel add name ' + greRouter.name + '-' +
                      greNameCluster + ' mode gre remote ' + bridgeIp +
                      ' local ' + clusterIp + ' ttl 64 dev ' + greRouter.name +
                      '-eth0')
        greRouter.inNamespace = False
        Intf(greRouter.name + '-' + greNameCluster, greRouter)
        greRouter.inNamespace = True

        ### Create gre in bridge
        # New router to support tunnel
        bridgeGre = self.mininet.addHost(bridge.name + greNameBridge,
                                         cls=LinuxRouter,
                                         ip='1.1.1.254/24')

        # Link with bridge
        self.mininet.addLink(bridge,
                             bridgeGre,
                             intfName1=bridge.name + '-' + greNameBridge,
                             intfName2=bridgeGre.name + '-eth0',
                             params1={'ip': '1.1.1.1/24'},
                             params2={'ip': '1.1.1.254/24'})

        # Connect bridge to overlay
        self.mininet.addLink(self.os2,
                             bridgeGre,
                             intfName2=bridgeGre.name + '-eth1',
                             params2={'ip': bridgeIp + '/8'})

        # Create gre interface
        bridgeGre.cmd('ip tunnel add name ' + bridgeGre.name + '-gre1' +
                      ' mode gre remote ' + clusterIp + ' local ' + bridgeIp +
                      ' ttl 64 dev ' + bridgeGre.name + '-eth1')
        bridgeGre.inNamespace = False
        Intf(bridgeGre.name + '-gre1', bridgeGre)
        bridgeGre.inNamespace = True

        ## Routes
        # Default gateway
        bridgeGre.cmd('ip route add default dev ' + bridgeGre.name + '-gre1')

        # To join cluster
        bridgeGre.cmd('ip route add ' + clusterIp + ' via 20.0.0.254')
        '''
예제 #17
0
def main(args):
    if not args.onos_ip:
        controller = ONOSCluster('c0', 3)
        onosIp = controller.nodes()[0].IP()
    else:
        controller = RemoteController('c0', ip=args.onos_ip)
        onosIp = args.onos_ip

    topo = ClosTopo(args)

    net = Mininet(topo=topo, build=False, controller=[controller])

    net.build()
    # Add an interface that the collector is connected to
    collectorIntf1 = Intf('veth_11', node=net.nameToNode["s11"])
    collectorIntf2 = Intf('veth_21', node=net.nameToNode["s12"])
    net.start()

    print "Network started"

    # Always generate background pings.
    sleep(3)
    for (h1, h2) in combinations(net.hosts, 2):
        h1.startPingBg(h2)
        h2.startPingBg(h1)

    print "Background ping started"

    for h in net.hosts:
        h.startIperfServer()

    print "Iperf servers started"

    if args.bg_traffic:
        sleep(4)
        print "Starting iperf clients..."
        for (h1, h2) in combinations(net.hosts, 2):
            h1.startIperfClient(h2, flowBw="10k", numFlows=10, duration=999999)
            h2.startIperfClient(h1, flowBw="10k", numFlows=10, duration=999999)

    generateNetcfg(onosIp, net, args)

    if args.netcfg_sleep > 0:
        print "Waiting %d seconds before pushing config to ONOS..." \
              % args.netcfg_sleep
        sleep(args.netcfg_sleep)

    print "Pushing config to ONOS..."
    call(("%s/onos-netcfg" % RUN_PACK_PATH, onosIp, TEMP_NETCFG_FILE))

    if not args.onos_ip:
        ONOSCLI(net)
    else:
        CLI(net)

    net.stop()
    call(("rm", "-f", TEMP_NETCFG_FILE))
예제 #18
0
def myNetwork():

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

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

    info('*** Add switches\n')
    s1 = net.addSwitch('s1', cls=OVSKernelSwitch, protocols='OpenFlow13')
    s2 = net.addSwitch('s2', cls=OVSKernelSwitch, protocols='OpenFlow13')
    s3 = net.addSwitch('s3', cls=OVSKernelSwitch, protocols='OpenFlow13')
    s4 = net.addSwitch('s4', cls=OVSKernelSwitch, protocols='OpenFlow13')
    s5 = net.addSwitch('s5', cls=OVSKernelSwitch, protocols='OpenFlow13')
    s6 = net.addSwitch('s6', cls=OVSKernelSwitch, protocols='OpenFlow13')
    net.addLink('s1', 's2')
    net.addLink('s1', 's3')
    net.addLink('s1', 's4')
    net.addLink('s1', 's5')
    net.addLink('s2', 's6')
    net.addLink('s3', 's6')
    net.addLink('s4', 's6')
    net.addLink('s5', 's6')
    info('*** Starting network\n')
    net.build()
    info('*** Starting controllers\n')
    for controller in net.controllers:
        controller.start()

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

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

    info('*** Add interfaces to switch ***')

    _intf = Intf('eth0', node=s1)
    _intf = Intf('eth1', node=s1)
    _intf = Intf('eth3', node=s6)
    _intf = Intf('eth4', node=s6)

    call(['ovs-vsctl', 'add-port', 's1', 'eth0'])
    call(['ovs-vsctl', 'add-port', 's1', 'eth1'])
    call(['ovs-vsctl', 'add-port', 's6', 'eth3'])
    call(['ovs-vsctl', 'add-port', 's6', 'eth4'])
    CLI(net)
    net.stop()
예제 #19
0
def myNetwork():

    net = Mininet( topo=None,
                   build=False,
                   switch=OVSSwitch)

    info( '*** Adding controller\n' )
    ryu_ctl=net.addController(name='c0',
                      controller=RemoteController)

    info( '*** Add switches\n')
    s1 = net.addSwitch('s1', dpid='00000002', protocols='OpenFlow13')
    Intf( 'eth0', node=s1 )
    s2 = net.addSwitch('s2',  dpid='0000000A', protocols='OpenFlow13')
    Intf( 'eth1', node=s2 )

    info( '*** Add hosts\n')
    h1 = net.addHost('h1')

    info( '*** Add links\n')
    net.addLink(h1,s1)
    net.addLink(h1,s2)

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

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

    info( '*** Post configure switches and hosts\n')
    s1.cmd("sudo ifconfig eth0 0")
    s1.cmd("sudo ifconfig eth1 0")
    s1.cmd("sudo ifconfig s1 192.168.137.128/24")
    s1.cmd("sudo route add -net 192.168.137.0/24 dev s1")
    s2.cmd("sudo ifconfig s2 192.168.237.138/24")
    s2.cmd("sudo route add -net 192.168.237.0/24 dev s2")
    s2.cmd("sudo route add default gw 192.168.137.2")
    h1.cmd("sudo ifconfig h1-eth0 192.168.137.150/24")
    h1.cmd("sudo ifconfig h1-eth1 192.168.237.150/24")
    h1.cmd("sudo route add default gw 192.168.137.2")
    h1.cmd("sudo sysctl -w net.ipv4.ip_forward=1")
    h1.cmd("sudo iptables -t nat -A POSTROUTING -o h1-eth0 -j MASQUERADE")
    h1.cmd("sudo iptables -A FORWARD -i h1-eth1 -o h1-eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT")
    h1.cmd("sudo iptables -A FORWARD -i h1-eth0 -o h1-eth1 -j ACCEPT")
    CLI(net)
    # the user has exited the mininet prompt.
    # need to stop the net and restore the host IP configurations
    s2.cmd('sudo ip addr add 192.168.237.138/24 dev eth1')
    s1.cmd('sudo ifconfig  eth0 down')
    s1.cmd('sudo ifconfig  eth0 up')
    #s1.cmd('sudo dhclient eth0')
    net.stop()
예제 #20
0
def createInboundNet():

    net = Mininet(topo=None,
                  build=False,
                  switch=OVSSwitch,
                  controller=InbandController)

    c0 = net.addController('c0', ip="192.168.100.1",
                           port=6633)  # set remote controller ip & port

    # add 3 hosts to network. controller software will run on h1
    h1 = net.addHost('h1', ip='192.168.101.1/24')
    h2 = net.addHost('h2', ip='192.168.101.2/24')
    h3 = net.addHost('h3', ip='192.168.101.3/24')

    # add switch, enable in-band control
    s1 = net.addSwitch('s1', inband=True)
    s2 = net.addSwitch('s2', inband=True)
    s3 = net.addSwitch('s3', inband=True)

    # add links
    net.addLink(h1, s1)
    net.addLink(h2, s2)
    net.addLink(h3, s3)

    net.addLink(s1, s2)
    net.addLink(s3, s2)
    net.addLink(s1, s3)

    intf2CtrName = "ens224"
    intf2AjName = "ens256"
    _intf2Ctr = Intf(intf2CtrName, node=s1)
    _intf2Aj = Intf(intf2AjName, node=s2)

    net.start()

    s1.cmd("ovs-vsctl set bridge s1 stp-enable=true")
    s2.cmd("ovs-vsctl set bridge s2 stp-enable=true")
    s3.cmd("ovs-vsctl set bridge s3 stp-enable=true")
    # s1 need to be equipped with an ip address to contact the controller
    s1.cmd('ifconfig s1 inet 192.168.100.11/24')
    s2.cmd('ifconfig s2 inet 192.168.100.12/24')
    s3.cmd('ifconfig s3 inet 192.168.100.13/24')

    # run controller sofware on h1, and redirect STDOUT & STDERR to log file
    #h1.cmd("ovs-testcontroller ptcp:6633 1>/tmp/c0.log 2>/tmp/c0.log &")

    CLI(net)
    net.stop()
예제 #21
0
 def addController( self, *args, **kwargs ):
     "Patch to update IP address to global IP address"
     controller = Mininet.addController( self, *args, **kwargs )
     controllerIP = controller.IP()
     if ( not isinstance( controller, Controller ) or
          not self.isLoopback( controller.IP() ) ):
         return controller
     # Find route to a different server IP address
     serverIPs = [ ip for ip in self.serverIP.values()
                   if ip != controllerIP ]
     if not serverIPs:
         return None  # no remote servers - loopback is fine
     for remoteIP in serverIPs:
         # Route should contain 'dev <intfname>'
         route = controller.cmd( 'ip route get', remoteIP,
                                 r'| egrep -o "dev\s[^[:space:]]+"' )
         if not route:
             raise Exception('addController: no route from', controller,
                             'to', remoteIP )
         intf = route.split()[ 1 ].strip()
         if intf != 'lo':
             break
     if intf == 'lo':
         raise Exception( 'addController: could not find external '
                          'interface/IP for %s' % controller )
     debug( 'adding', intf, 'to', controller )
     Intf( intf, node=controller ).updateIP()
     debug( controller, 'IP address updated to', controller.IP() )
     return controller
예제 #22
0
def setup():
	"Start Network"
	topo = SingleSwitchTopo()
	OVSSwitch13 = partial(OVSSwitch, protocols='OpenFlow13')
	net = Mininet(topo=topo, ipBase='10.11.0.0/24', switch=OVSSwitch13, controller=RemoteController('c0', ip='192.168.56.1'), autoSetMacs=True, xterms=False)

	for h in net.hosts:
		info('Disabling IPV6 for ' + str(h) + '\n')
		h.cmd("sysctl -w net.ipv6.conf.all.disable_ipv6=1")
		h.cmd("sysctl -w net.ipv6.conf.default.disable_ipv6=1")
		h.cmd("sysctl -w net.ipv6.conf.lo.disable_ipv6=1")
		h.cmd("echo ''")

		if str(h) in ['server', 'server2']:
			h.cmd('/usr/sbin/lighttpd -D -f /etc/lighttpd/lighttpd.conf &')
			info(str(h) + " is running a webserver now, You can connect at http://" + h.IP() + "/\n")

#		if str(h) in ['dns']:
#			h.cmd('/usr/sbin/named -f -u bind &')
#			info("dns server started on dns node " + h.IP() + "\n")


	for sw in net.switches:
		if sw.name == 's66766':
			_intf = Intf('enp0s9', node=sw)

	net.start()
	CLI(net)
	net.stop()
예제 #23
0
def setup():
    "Start Network"
    topo = SingleSwitchTopo()
    OVSSwitch13 = partial(OVSSwitch, protocols='OpenFlow13')
    net = Mininet(topo=topo,
                  ipBase='10.11.0.0/24',
                  switch=OVSSwitch13,
                  controller=RemoteController('c0', ip='192.168.56.1'),
                  autoSetMacs=True,
                  xterms=False)

    for h in net.hosts:
        info('Disabling IPV6 for ' + str(h) + '\n')
        h.cmd("sysctl -w net.ipv6.conf.all.disable_ipv6=1")
        h.cmd("sysctl -w net.ipv6.conf.default.disable_ipv6=1")
        h.cmd("sysctl -w net.ipv6.conf.lo.disable_ipv6=1")
        h.cmd("echo ''")

        if str(h) in [
                'server',
        ]:
            h.cmd('python -m SimpleHTTPServer 80 &')
            info(
                "Request Router is running a webserver now, You can connect at http://"
                + h.IP() + "/\n")

    for sw in net.switches:
        if sw.name == 's66766':
            _intf = Intf('enp0s9', node=sw)

    net.start()
    CLI(net)
    net.stop()
예제 #24
0
파일: pinga.py 프로젝트: jzarra34/test
    def build( self, **_opts ):

        defaultIP1 = '10.0.3.10/24'  # IP address for r0-eth1
        defaultIP2 = '10.0.3.20/24' 
        router1 = self.addNode( 'r1', cls=LinuxRouter, ip=defaultIP1 )
	router2 = self.addNode( 'r2', cls=LinuxRouter, ip=defaultIP2 )
	switch1 = self.addSwitch('s1',dpid='1000000000000001')
	switch2 = self.addSwitch('s2',dpid='1000000000000002')
        
        h1 = self.addHost( 'h1', ip='10.0.1.100/24', defaultRoute='via 10.0.1.10',dpid='0000000000000001') #define gateway
        h2 = self.addHost( 'h2', ip='10.0.2.100/24', defaultRoute='via 10.0.2.20',dpid='0000000000000002')
	h3=self.addHost('h3',ip='10.0.4.100/24',defaultRoute='via 10.0.4.10', dpid='0000000000000003')
	h4=self.addHost('h4',ip='10.0.5.100/24',defaultRoute='via 10.0.5.20', dpid='0000000000000004')

	self.addLink(router1,router2,intfName1='r1-eth1',intfName2='r2-eth1')
	self.addLink(h1,router1,intfName2='r1-eth2',params2={ 'ip' : '10.0.1.10/24' })#params2 define the eth2 ip address
	self.addLink(h2,router2,intfName2='r2-eth2',params2={ 'ip' : '10.0.2.20/24' })
	self.addLink(h3,switch1,intfName2='s1-eth0')
	self.addLink(h4,switch2,intfName2='s2-eth0')
	self.addLink(switch1,router1,intfName1='s1-eth1',intfName2='r1-eth3',params2={'ip':'10.0.4.10/24'})
	self.addLink(switch2,router2,intfName1='s2-eth1',intfName2='r2-eth3',params2={'ip':'10.0.5.20/24'})
    # Add physical interface
    	info( 'Defining physical interface\n' )
    	intfName = 'enp0s3'
    	info( 'Adding hardware interface to switch', '\n' )
    	_intf = Intf( intfName, node=switch1 )
예제 #25
0
def testRemoteNet(remote='ubuntu1', link=RemoteGRELink):
    "Test remote Node classes"
    print '*** Remote Node Test'
    net = Mininet(host=RemoteHost, switch=RemoteOVSSwitch, link=link)
    c0 = net.addController('c0')
    # Make sure controller knows its non-loopback address
    Intf('eth0', node=c0).updateIP()
    print "*** Creating local h1"
    h1 = net.addHost('h1')
    print "*** Creating remote h2"
    h2 = net.addHost('h2', server=remote)
    print "*** Creating local s1"
    s1 = net.addSwitch('s1')
    print "*** Creating remote s2"
    s2 = net.addSwitch('s2', server=remote)
    print "*** Adding links"
    net.addLink(h1, s1)
    net.addLink(s1, s2)
    net.addLink(h2, s2)
    net.start()
    print 'Mininet is running on', quietRun('hostname').strip()
    for node in c0, h1, h2, s1, s2:
        print 'Node', node, 'is running on', node.cmd('hostname').strip()
    net.pingAll()
    net.stop()
예제 #26
0
def myNetwork():

    net = Mininet(topo=None, build=False)

    info('*** Adding controller\n')
    net.addController(name='c0',
                      controller=RemoteController,
                      ip='0.0.0.0',
                      port=6633)

    info('*** Add switches\n')
    s1 = net.addSwitch('s1')
    Intf('eth1', node=s1)

    info('*** Add hosts\n')
    h1 = net.addHost('h1', ip='0.0.0.0')
    h2 = net.addHost('h2', ip='0.0.0.0')

    info('*** Add links\n')
    net.addLink(h1, s1)
    net.addLink(h2, s1)

    info('*** Starting network\n')
    net.start()
    h1.cmdPrint('dhclient ' + h1.defaultIntf().name)
    h2.cmdPrint('dhclient ' + h2.defaultIntf().name)
    CLI(net)
    net.stop()
예제 #27
0
def create_dp_cpu_link(id, switch, bridge_name):
    '''
    Add virtual link within the INT collection network for each p4 switch
    '''
    _quietRun('ip link add name veth_dp_%i type veth peer name veth_cpu_%i' %
              (id, id))

    dp_mac = 'f6:61:c0:6a:00:0%i' % id

    _quietRun('ip link set veth_cpu_%i netns ns_int' % id)
    _quietRun('ifconfig veth_dp_%i hw ether %s' % (id, dp_mac))
    _quietRun('ip link set dev veth_dp_%i up' % id)
    quietRunNs('ip link set dev veth_cpu_%i up' % id)
    for off in "rx tx sg tso ufo gso gro lro rxvlan txvlan rxhash".split(' '):
        quietRun('/sbin/ethtool --offload veth_dp_%i %s off' % (id, off))
        quietRunNs('/sbin/ethtool --offload veth_cpu_%i %s off' % (id, off),
                   display=False)

    quietRunNs('sysctl -w net.ipv6.conf.veth_dp_%i.disable_ipv6=1' % id)
    quietRunNs('sysctl -w net.ipv6.conf.veth_cpu_%i.disable_ipv6=1' % id)

    quietRunNs('brctl addif %s veth_cpu_%i' % (bridge_name, id))

    _intf = Intf('veth_dp_%i' % id, node=switch)
    veth_dp_port = switch.intfNames().index('veth_dp_%i' % id)
    print '*** Adding hardware interface', 'veth_dp_%i' % id, 'to switch', switch.name, 'with port index', veth_dp_port, '\n'
    return veth_dp_port
def P2pDemo():

    net = Mininet(topo=None, build=False)

    info('*** Adding controller\n')
    c0 = net.addController('c0',
                           controller=RemoteController,
                           ip='192.168.0.108',
                           port=6633)

    info('*** Add switches\n')
    s1 = net.addSwitch('s1')
    Intf('eth0', node=s1)

    info('*** Add hosts\n')
    h1 = net.addHost('h1', ip='0.0.0.0')

    info('*** Add links\n')
    net.addLink(h1, s1)

    info('*** Starting network\n')
    net.start()
    h1.cmdPrint('dhclient ' + h1.defaultIntf().name)
    #h1.cmd(sudo deluge-gtk 'magnet:?xt=urn:btih:c1aa77dea674d71fbd85559034b6082b8434d36e&dn=lubuntu-16.04.3-desktop-amd64.iso')

    CLI(net)
    net.stop()
예제 #29
0
def perfTest(  ):
    "Create network and run simple performance test"
    net = Mininet( controller=RemoteController, topo=None, link=TCLink )
    c1 = net.addController('c1', ip='192.168.33.101', port=6033)
    c2 = net.addController('c2', ip='192.168.33.101', port=6133)
    c3 = net.addController('c3', ip='192.168.33.101', port=6233)

    s1 = net.addSwitch('s1',dpid='1000000000000001')
    #Intf('enp2s0', node=s1)
    Intf('eth0', node=s1)

    h1 = net.addHost('h1',ip='10.0.1.31')
    h2 = net.addHost('h2',ip='10.0.1.32')
    h3 = net.addHost('h3',ip='10.0.1.33')

    net.addLink(h1, s1, bw=100)
    net.addLink(h2, s1, bw=100)
    net.addLink(h3, s1, bw=100)

    net.start()
    h1.cmd("./Client 2v5 10.0.1.11 10001&")
    h2.cmd("./Client 3v5 10.0.1.11 10002&")
    h3.cmd("./Client 4v5 10.0.1.11 10003")
    #h3.cmd("sleep 10")
    #CLI(net)
    net.stop()
예제 #30
0
 def addController(self, *args, **kwargs):
     "Patch to update IP address to global IP address"
     controller = Mininet.addController(self, *args, **kwargs)
     loopback = '127.0.0.1'
     if (not isinstance(controller, Controller)
             or controller.IP() != loopback):
         return None
     # Find route to a different server IP address
     serverIPs = [
         ip for ip in self.serverIP.values() if ip is not controller.IP()
     ]
     if not serverIPs:
         return None  # no remote servers - loopback is fine
     remoteIP = serverIPs[0]
     # Route should contain 'dev <intfname>'
     route = controller.cmd('ip route get', remoteIP,
                            r'| egrep -o "dev\s[^[:space:]]+"')
     if not route:
         raise Exception('addController: no route from', controller, 'to',
                         remoteIP)
     intf = route.split()[1].strip()
     debug('adding', intf, 'to', controller)
     Intf(intf, node=controller).updateIP()
     debug(controller, 'IP address updated to', controller.IP())
     return controller
def start_mininet(iface_names):
    """Start Mininet with the above topology.

    :param iface_name: Network interface name of the host computer to
    attach to the Mininet virtual network.
    """
    topo = SimpleTopo()
    net = Mininet(topo, build=False)
    net.addController("c0",
                      controller=RemoteController,
                      port=6633,
                      switch=OVSSwitch)
    net.build()
    switch = net.switches[0]
    for iface in iface_names:
        lg.info("***Connecting {0} to virtual switch\n".format(iface))
        # Connect the switch to the eth1 interface of this host machine!
        Intf(iface, node=switch)
    net.start()
    set_qos(switch)
    lg.info("***Dumping host connections\n")
    dumpNodeConnections(net.hosts)
    lg.info("***Dumping switch connections\n")
    dumpNodeConnections(net.switches)
    CLI(net)
    net.stop()
예제 #32
0
def addDummyHost(net, topo):
    print('**Adding dummy host (hardware setup).')
    net.addHost('dummy')
    _intf = Intf(INTERFACE, node=net.getNodeByName('dummy'))
    client_switches = list(map(net.getNodeByName, topo.getClientSwitches()))
    for sw in client_switches:
        net.addLink(sw, net.getNodeByName('dummy'))
예제 #33
0
def testRemoteNet( remote='ubuntu2' ):
    "Test remote Node classes"
    info('*** Remote Node Test\n')
    net = Mininet( host=RemoteHost, switch=RemoteOVSSwitch,
                   link=RemoteLink )
    c0 = net.addController( 'c0' )
    # Make sure controller knows its non-loopback address
    Intf( 'eth0', node=c0 ).updateIP()
    info("*** Creating local h1\n")
    h1 = net.addHost( 'h1' )
    info("*** Creating remote h2\n")
    h2 = net.addHost( 'h2', server=remote )
    info("*** Creating local s1\n")
    s1 = net.addSwitch( 's1' )
    info("*** Creating remote s2\n")
    s2 = net.addSwitch( 's2', server=remote )
    info("*** Adding links\n")
    net.addLink( h1, s1 )
    net.addLink( s1, s2 )
    net.addLink( h2, s2 )
    net.start()
    info('Mininet is running on', quietRun( 'hostname' ).strip())
    for node in c0, h1, h2, s1, s2:
        info('Node', node, 'is running on', node.cmd( 'hostname' ).strip())
    net.pingAll()
    CLI( net )
    net.stop()
예제 #34
0
    def found_vnf_links(self, vnf_id, links):
        def get_intf_by_name(node, intf_name):
            for i in node.intfList():
                if str(i) == intf_name:
                    return i
            return None

        def get_or_create_intf(dev_name, obj, port):
            if port not in obj.intfs:
                # does not exist, let's create it
                return Intf(dev_name, node=obj, port=port)
            if str(obj.intfs[port]) != dev_name:
                # intf exists, but port is invalid
                return Intf(dev_name, node=obj, port=port)
            return obj.intfs[port]

        for i, link in enumerate(links):
            if int(link['sw_port']) == -1:
                # disconnected links (with port==-1) are omitted
                continue
            sw_name = link.get('sw_id', 'sw_id'+str(i))
            sw_dev = link.get('sw_dev', 'sw_dev'+str(i))
            sw_port = int(link['sw_port'])

            nf_name = vnf_id
            nf_dev  = link.get('vnf_dev', 'vnf_dev'+str(i))
            nf_port = int(link['vnf_port'])
            nf_mac = link['vnf_dev_mac']

            sw_obj = self.net.getNodeByName(sw_name)
            try:
                nf_obj = self.net.getNodeByName(nf_name)
            except KeyError:
                # this is a VNF not managed by mininet, yet we have to
                # add to the mininet 'database'.  TODO: Ideally, it
                # would be a RemoteHost, but for now it is a
                # RemoteSwitch.
                nf_obj = self.net.addRemoteSwitch(nf_name, dpid="-1")
            sw_i = get_or_create_intf(sw_dev, sw_obj, sw_port)
            if nf_dev in nf_obj.intfNames():
                nf_i = get_intf_by_name(nf_obj, nf_dev)
            else:
                nf_i = Intf(nf_dev, node=nf_obj, port=nf_port, mac=nf_mac)
                nf_i.mac = nf_mac # mn runs 'ifconfig', which resets mac to None

            self.found_link(sw_obj, nf_obj, sw_i, nf_i)
예제 #35
0
파일: ns3.py 프로젝트: EliseuTorres/OpenNet
 def __init__( self, name, node, port=None,
               nsNode=None, nsDevice=None, mode=None, **params ):
     """name: interface name (e.g. h1-eth0)
        node: owning Mininet node (where this intf most likely lives)
        link: parent link if we're part of a link #TODO
        nsNode: underlying ns-3 node
        nsDevice: ns-3 device which the tap interface is bridged with
        mode: mode of TapBridge ns-3 device (UseLocal or UseBridge)
        other arguments are passed to config()"""
     self.name = name
     # Create a tap interface in the system, ns-3 TapBridge will connect to that interface later.
     self.createTap()
     # Set this Intf to be delayed move. This tells Mininet not to move the interface to the right
     # namespace during Intf.__init__(). Therefore, the interface must be moved manually later.
     # Actually, interfaces are moved right after the simulator thread start, in the start() global
     # function.
     self.delayedMove = True
     # If this node is running in its own namespace...
     if node.inNamespace:
         # ...this interface is not yet in the right namespace (it is in the root namespace just after
         # creation) and should be moved later.
         self.inRightNamespace = False
     else:
         # ...interface should stay in the root namespace, so it is in right namespace now.
         self.inRightNamespace = True
     # Initialize parent Intf object.
     Intf.__init__( self, name, node, port , **params)
     allTBIntfs.append( self )
     self.nsNode = nsNode
     self.nsDevice = nsDevice
     self.mode = mode
     self.params = params
     self.nsInstalled = False
     # Create TapBridge ns-3 device.
     self.tapbridge = ns.tap_bridge.TapBridge()
     # If ns-3 node and bridged ns-3 device are set and TapBridge mode is known...
     if self.nsNode and self.nsDevice and ( self.mode or self.node ):
         # ...call nsInstall().
         self.nsInstall()
예제 #36
0
파일: ns3.py 프로젝트: rascov/OpenNet
 def __init__( self, name, node, port=None,
               nsNode=None, nsDevice=None, mode=None, **params ):
     """
     """
     self.name = name
     self.createTap()
     self.delayedMove = True
     if node.inNamespace:
         self.inRightNamespace = False
     else:
         self.inRightNamespace = True
     Intf.__init__( self, name, node, port , **params)
     allTBIntfs.append( self )
     self.nsNode = nsNode
     self.nsDevice = nsDevice
     self.mode = mode
     self.params = params
     self.nsInstalled = False
     self.tapbridge = ns.tap_bridge.TapBridge()
     if self.nsNode and self.nsDevice and ( self.mode or self.node ):
         self.nsInstall()
     if self.node and self.nsInstalled and self.isInstant(): # instant mode to be implemented in ns-3
         self.namespaceMove()
예제 #37
0
    def config(self, bw=None, delay=None, jitter=None, loss=None,
               disable_gro=True, speedup=0, use_hfsc=False, use_tbf=False,
               latency_ms=None, enable_ecn=False, enable_red=False,
               max_queue_size=None, **params):
        """Configure the port and set its properties."""
        result = Intf.config(self, **params)

        # Disable GRO
        if disable_gro:
            self.cmd('ethtool -K %s gro off' % self)

        # Optimization: return if nothing else to configure
        # Question: what happens if we want to reset things?
        if (bw is None and not delay and not loss
            and max_queue_size is None):
            return

        # Clear existing configuration
        tcoutput = self.tc('%s qdisc show dev %s')
        if "priomap" not in tcoutput and "noqueue" not in tcoutput:
            cmds = ['%s qdisc del dev %s root']
        else:
            cmds = []

        # Bandwidth limits via various methods
        bwcmds, parent = self.bwCmds(bw=bw, speedup=speedup,
                                     use_hfsc=use_hfsc, use_tbf=use_tbf,
                                     latency_ms=latency_ms,
                                     enable_ecn=enable_ecn,
                                     enable_red=enable_red)
        cmds += bwcmds

        # Delay/jitter/loss/max_queue_size using netem
        delaycmds, parent = self.delayCmds(delay=delay, jitter=jitter,
                                           loss=loss,
                                           max_queue_size=max_queue_size,
                                           parent=parent)
        cmds += delaycmds

        # We add the filter for the HTB class
        filtercmds = self.filterCmds(parent="parent 1:0", prio=1, handle=10, flowid="1:10")
        cmds += filtercmds

        filtercmds = self.filterCmds(parent="parent 1:0", prio=2, handle=20, flowid="1:20")
        cmds += filtercmds

        # Ugly but functional: display configuration info
        stuff = ((['%.2fMbit' % bw] if bw is not None else []) +
                 (['%s delay' % delay] if delay is not None else []) +
                 (['%s jitter' % jitter] if jitter is not None else []) +
                 (['%.5f%% loss' % loss] if loss is not None else []) +
                 (['ECN'] if enable_ecn else ['RED']
                 if enable_red else []))
        info('(' + ' '.join(stuff) + ') ')

        # Execute all the commands in our node
        debug("at map stage w/cmds: %s\n" % cmds)
        # for cmd in cmds:
        #     print cmd
        tcoutputs = [self.tc(cmd) for cmd in cmds]
        # if "r_0_e0" in self.name:
        #     for cmd in cmds:
        #         print cmd

        for output in tcoutputs:
            if output != '':
                error("*** Error: %s" % output)
        debug("cmds:", cmds, '\n')
        debug("outputs:", tcoutputs, '\n')

        # add marks to packets through IPTABLES RULES
        # OSPF: marks ospf packets with priority 0x14 (20)
        #self.cmd("iptables -w -t mangle -A POSTROUTING -o %s -p 89 -j MARK --set-mark 20" % self.name)

        # ICMP: marks icmp packets with priority 0xa (10)
        #self.cmd("iptables -w -t mangle -A POSTROUTING -o %s -p 1 -j MARK --set-mark 10" % self.name)

        # Traceroute: marks pakets with TTL < 10 that are not OSPF with priority 0xa (10)
        #self.cmd("iptables -w -t mangle -A POSTROUTING -o %s -m ttl --ttl-lt 10 ! -p 89 -j MARK --set-mark 10" % self.name)

        # TCP flags: Gives priority 20 to TCP SYN and ACK packets
        #self.cmd("iptables -w -t mangle -A POSTROUTING -o %s -m ttl --ttl-gt 10 -p tcp --tcp-flags ACK ACK -m length --length :64 -j MARK --set-mark 20"% self.name)
        #self.cmd("iptables -w -t mangle -A POSTROUTING -o %s -m ttl --ttl-gt 10 -p tcp --tcp-flags SYN SYN -m length --length :64 -j MARK --set-mark 20" % self.name)

        self.cmd(iptables_path + " {0} &".format(self.name))

        result['tcoutputs'] = tcoutputs
        result['parent'] = parent

        return result
예제 #38
0
파일: ns3.py 프로젝트: rascov/OpenNet
 def rename( self, newname ):
     "Rename interface"
     if self.nsInstalled and not self.isConnected():
         self.tapbridge.SetAttribute ( "DeviceName", ns.core.StringValue( newname ) )
     Intf.rename( self, newname )