Esempio n. 1
0
    def build( self ):
        print "Build network based on our topology."

        net = Mininet( topo=None, build=False, link=TCLink, ipBase=self.minieditIpBase )
 
        net.controllers = self.addControllers()
        
        # Make nodes
        print "Getting Hosts and Switches."
        for widget in self.widgetToItem:
            name = widget[ 'text' ]
            tags = self.canvas.gettags( self.widgetToItem[ widget ] )
            nodeNum = int( name[ 1: ] )
            if 'Switch' in tags:
                net.addSwitch( name )
            elif 'Host' in tags:
                ipBaseNum, prefixLen = netParse( self.minieditIpBase )
                ip = ipAdd(i=nodeNum, prefixLen=prefixLen, ipBaseNum=ipBaseNum)
                net.addHost( name, ip=ip )
            else:
                raise Exception( "Cannot create mystery node: " + name )

        # Make links
        print "Getting Links."
        for link in self.links.values():
            ( src, dst, linkopts ) = link
            srcName, dstName = src[ 'text' ], dst[ 'text' ]
            src, dst = net.nameToNode[ srcName ], net.nameToNode[ dstName ]
            net.addLink(src, dst, **linkopts)

        self.printInfo()
        # Build network (we have to do this separately at the moment )
        net.build()

        return net
Esempio n. 2
0
    def __init__( self, topo=None, switch=OVSKernelSwitch, host=Host,
                  controller=DefaultController, link=Link, intf=Intf,
                  build=True, xterms=False, cleanup=False, ipBase='10.0.0.0/8',
                  inNamespace=False,
                  autoSetMacs=False, autoStaticArp=False, autoPinCpus=False,
                  listenPort=None, waitConnected=False ):
        """Create Mininet object.
           topo: Topo (topology) object or None
           switch: default Switch class
           host: default Host class/constructor
           controller: default Controller class/constructor
           link: default Link class/constructor
           intf: default Intf class/constructor
           ipBase: base IP address for hosts,
           build: build now from topo?
           xterms: if build now, spawn xterms?
           cleanup: if build now, cleanup before creating?
           inNamespace: spawn switches and controller in net namespaces?
           autoSetMacs: set MAC addrs automatically like IP addresses?
           autoStaticArp: set all-pairs static MAC addrs?
           autoPinCpus: pin hosts to (real) cores (requires CPULimitedHost)?
           listenPort: base listening port to open; will be incremented for
               each additional switch in the net if inNamespace=False"""
        self.topo = topo
        self.switch = switch
        self.host = host
        self.controller = controller
        self.link = link
        self.intf = intf
        self.ipBase = ipBase
        self.ipBaseNum, self.prefixLen = netParse( self.ipBase )
        hostIP = ( 0xffffffff >> self.prefixLen ) & self.ipBaseNum
        # Start for address allocation
        self.nextIP = hostIP if hostIP > 0 else 1
        self.inNamespace = inNamespace
        self.xterms = xterms
        self.cleanup = cleanup
        self.autoSetMacs = autoSetMacs
        self.autoStaticArp = autoStaticArp
        self.autoPinCpus = autoPinCpus
        self.numCores = numCores()
        self.nextCore = 0  # next core for pinning hosts to CPUs
        self.listenPort = listenPort
        self.waitConn = waitConnected

        self.hosts = []
        self.switches = []
        self.controllers = []
        self.links = []

        self.nameToNode = {}  # name to Node (Host/Switch) objects

        self.terms = []  # list of spawned xterm processes

        Mininet.init()  # Initialize Mininet if necessary

        self.built = False
        if topo and build:
            self.build()
Esempio n. 3
0
    def __init__( self, topo=None, switch=OVSKernelSwitch, host=Host,
                  controller=DefaultController, link=Link, intf=Intf,
                  build=True, xterms=False, cleanup=False, ipBase='10.0.0.0/8',
                  inNamespace=False,
                  autoSetMacs=False, autoStaticArp=False, autoPinCpus=False,
                  listenPort=None, waitConnected=False ):
        """Create Mininet object.
           topo: Topo (topology) object or None
           switch: default Switch class
           host: default Host class/constructor
           controller: default Controller class/constructor
           link: default Link class/constructor
           intf: default Intf class/constructor
           ipBase: base IP address for hosts,
           build: build now from topo?
           xterms: if build now, spawn xterms?
           cleanup: if build now, cleanup before creating?
           inNamespace: spawn switches and controller in net namespaces?
           autoSetMacs: set MAC addrs automatically like IP addresses?
           autoStaticArp: set all-pairs static MAC addrs?
           autoPinCpus: pin hosts to (real) cores (requires CPULimitedHost)?
           listenPort: base listening port to open; will be incremented for
               each additional switch in the net if inNamespace=False"""
        self.topo = topo
        self.switch = switch
        self.host = host
        self.controller = controller
        self.link = link
        self.intf = intf
        self.ipBase = ipBase
        self.ipBaseNum, self.prefixLen = netParse( self.ipBase )
        hostIP = ( 0xffffffff >> self.prefixLen ) & self.ipBaseNum
        # Start for address allocation
        self.nextIP = hostIP if hostIP > 0 else 1
        self.inNamespace = inNamespace
        self.xterms = xterms
        self.cleanup = cleanup
        self.autoSetMacs = autoSetMacs
        self.autoStaticArp = autoStaticArp
        self.autoPinCpus = autoPinCpus
        self.numCores = numCores()
        self.nextCore = 0  # next core for pinning hosts to CPUs
        self.listenPort = listenPort
        self.waitConn = waitConnected

        self.hosts = []
        self.switches = []
        self.controllers = []
        self.links = []

        self.nameToNode = {}  # name to Node (Host/Switch) objects

        self.terms = []  # list of spawned xterm processes

        Mininet.init()  # Initialize Mininet if necessary

        self.built = False
        if topo and build:
            self.build()
Esempio n. 4
0
    def create(self, topology):
        super(ONOSHostSdnipCluster, self).create(topology)

        cs1 = topology.addSwitch('cs1', cls=OVSBridge)

        dataIp, dataPrefixLen = netParse(self.dataSubnet)
        for i in range(1, len(self.instances) + 1):
            c = self.instances[i - 1]
            strDataIp = '%s/%i' % (ipStr(dataIp + i), dataPrefixLen)
            topology.addLink(c, cs1, params1={'ip': strDataIp})

        return cs1
Esempio n. 5
0
 def create(self, topology):
     super(ONOSHostSdnipCluster, self).create(topology)
     
     cs1 = topology.addSwitch('cs1', cls=L2OVSSwitch)
     
     dataIp, dataPrefixLen = netParse(self.dataSubnet)
     for i in range(1, len(self.instances) + 1):
         c = self.instances[i-1]
         strDataIp = '%s/%i' % (ipStr(dataIp + i), dataPrefixLen)
         topology.addLink(c, cs1, params1={ 'ip' : strDataIp })
         
     return cs1
Esempio n. 6
0
def network(ip):
    """Network an IP address belongs to.

    Parameters
    ----------
        ip : str
            IP address.

    Returns
    -------
        network_ip_with_prefix : str
            IP address of the network with prefix.

    """
    ip, prefix = netParse(ip)
    return "{}/{}".format(ipStr(ip & (0xffffffff << (32 - prefix))), prefix)
Esempio n. 7
0
    def printInfo( self ):
        "print nodes and links."
        for widget in self.widgetToItem:
            name = widget[ 'text' ]
            tags = self.canvas.gettags( self.widgetToItem[ widget ] )
            x1, y1 = self.canvas.coords( self.widgetToItem[ widget ] )
            nodeNum = int( name[ 1: ] )
            if 'Switch' in tags:
                print "Switch "+name+" at "+str(x1)+"/"+str(y1)+"."
            elif 'Host' in tags:
                ipBaseNum, prefixLen = netParse( self.minieditIpBase )
                print 'ipBaseNum='+str(ipBaseNum)
                print 'prefixLen='+str(prefixLen)
                ip = ipAdd(i=nodeNum, prefixLen=prefixLen, ipBaseNum=ipBaseNum)
                print "Host "+name+" with IP "+ip+" at "+str(x1)+"/"+str(y1)+"."
            else:
                raise Exception( "Cannot create mystery node: " + name )

        for link in self.links.values():
            ( src, dst, linkopts ) = link
            srcName, dstName = src[ 'text' ], dst[ 'text' ]
            print "Link from "+srcName+" to "+dstName+"."
Esempio n. 8
0
def RunNet():
    """RunNet will start the mininet and add the routes to the other
    mininet-services"""
    rootLog = None
    if myNet[1] > 0:
        i, p = netParse(otherNets[0][1])
        rootLog = ipAdd(1, p, i)
    dbg(2, "Creating network", myNet)
    topo = InternetTopo(myNet=myNet, rootLog=rootLog)
    dbg(3, "Starting on", myNet)

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

    for host in net.hosts[1:]:
        host.startConode()

    # Also set setLogLevel('info') if you want to use this, else
    # there is no correct reporting on commands.
    if startCLI:
        CLI(net)
    log = open(logfile, "r")
    while not os.path.exists(logdone):
        dbg(4, "Waiting for conode to finish at " + platform.node())
        try:
            print(log.read(), end="")
            sys.stdout.flush()
        except IOError:
            time.sleep(1)

        time.sleep(1)

    # Write last line of log
    print(log.read(), end="")
    sys.stdout.flush()
    log.close()

    dbg(2, "conode is finished %s" % myNet)
    net.stop()
Esempio n. 9
0
        def __init__(self, myNet=None, rootLog=None, **opts):
            Topo.__init__(self, **opts)
            server, mn, n = myNet[0]
            switch = self.addSwitch('s0')
            baseIp, prefix = netParse(mn)
            gw = ipAdd(1, prefix, baseIp)
            dbg( 2, "Gw", gw, "baseIp", baseIp, prefix,
                 "Bandwidth:", bandwidth, "- delay:", delay)
            hostgw = self.addNode('h0', cls=BaseRouter,
                                  ip='%s/%d' % (gw, prefix),
                                  inNamespace=False,
                                  rootLog=rootLog)
            self.addLink(switch, hostgw)

            for i in range(1, int(n) + 1):
                ipStr = ipAdd(i + 1, prefix, baseIp)
                host = self.addHost('h%d' % i, cls=Conode,
                                    ip = '%s/%d' % (ipStr, prefix),
                                    defaultRoute='via %s' % gw,
			                	    simul=simulation, gw=gw,
                                    rootLog=rootLog)
                dbg( 3, "Adding link", host, switch )
                self.addLink(host, switch, bw=bandwidth, delay=delay)
Esempio n. 10
0
    def create(self, topology):
        cs0 = topology.addSwitch('cs0', cls=L2OVSSwitch)
        
        ctrlIp, ctrlPrefixLen = netParse(self.controlSubnet)
        
        for i in range(1, self.numInstances + 1):
            strCtrlIp = '%s/%i' % (ipStr(ctrlIp + i), ctrlPrefixLen)

            c = topology.addHost('%s%s' % (self.basename, i), cls=ONOS, inNamespace=True,
                              ip=strCtrlIp,
                              features=['onos-app-config', 'onos-app-proxyarp',
                                        'onos-core'] + self.features,
                              reactive=False)
            
            topology.addLink(c, cs0, params1={ 'ip' : strCtrlIp })
            
            self.instances.append(c)
            
        # Connect switch to root namespace so that data network
        # switches will be able to talk to us
        highestIp = '%s/%i' % (ipStr(ctrlIp + (2 ** (32 - ctrlPrefixLen)) - 2), ctrlPrefixLen)
        root = topology.addHost('root', inNamespace=False, ip=highestIp)
        topology.addLink(root, cs0)
Esempio n. 11
0
class Mininet_IoT(Mininet):

    topo = None
    sixLoWPan = sixLoWPan
    APSensor = OVSSensor
    controller = DefaultController
    intf = Intf
    inNamespace = False
    autoSetMacs = False
    autoStaticArp = False
    autoPinCpus = False
    listenPort = None
    waitConnected = False
    autoSetPositions = False
    ipBase = '10.0.0.0/8'
    ip6Base = '2001:0:0:0:0:0:0:0/64'
    ipBaseNum, prefixLen = netParse(ipBase)
    ip6BaseNum, prefixLen6 = netParse6(ip6Base)
    nextIP = 1  # start for address allocation
    nextIP6 = 1  # start for address allocation
    nextPosition = 1
    inNamespace = inNamespace
    numCores = numCores()
    nextCore = 0  # next core for pinning hosts to CPUs
    nameToNode = {}  # name to Node (Host/Switch) objects
    links = []
    apsensors = []
    sensors = []
    terms = []  # list of spawned xterm processes
    nwpans = 0
    connections = {}
    wlinks = []

    @classmethod
    def init_module(cls, iot_module):
        sensors = cls.sensors + cls.apsensors
        module(sensors, cls.nwpans, iot_module=iot_module)
        return cls.sensors, cls.apsensors

    @classmethod
    def pos_to_array(cls, node):
        pos = node.params['position']
        if isinstance(pos, string_types):
            pos = pos.split(',')
        node.position = [float(pos[0]), float(pos[1]), float(pos[2])]
        node.params.pop('position', None)

    @classmethod
    def addParameters(cls, node, **params):
        """adds parameters to wireless nodes
        node: node
        autoSetMacs: set MAC addrs automatically like IP addresses
        params: parameters
        defaults: Default IP and MAC addresses
        node_mode: if interface is running in managed or master mode"""
        node.params['wpan'] = []

        wpans = cls.count6LoWPANIfaces(**params)

        for wpan in range(wpans):
            node.params['wpan'].append(node.name + '-wpan' + str(wpan))
            node.params.pop("wpans", None)

    @staticmethod
    def appendAssociatedTo(node):
        "Add associatedTo param"
        node.params['associatedTo'].append('')

    @classmethod
    def addAPSensor(self, name, cls=None, **params):
        """Add AccessPoint as a Sensor.
           name: name of accesspoint to add
           cls: custom switch class/constructor (optional)
           returns: added accesspoint
           side effect: increments listenPort var ."""
        defaults = {'listenPort': self.listenPort,
                    'inNamespace': self.inNamespace
                    }
        defaults.update(params)
        if self.autoSetPositions:
            defaults['position'] = (round(self.nextPos_ap, 2), 50, 0)
            self.nextPos_ap += 100

        if not cls:
            cls = self.APSensor
        ap = cls(name, **defaults)
        if not self.inNamespace and self.listenPort:
            self.listenPort += 1
        self.nameToNode[name] = ap

        if 'position' in params:
            self.pos_to_array(ap)

        self.addParameters(ap, **defaults)
        self.apsensors.append(ap)
        return ap

    @classmethod
    def addSensor(self, name, cls=None, **params):
        """Add Sensor node.
           name: name of station to add
           cls: custom 6LoWPAN class/constructor (optional)
           params: parameters for 6LoWPAN
           returns: added station"""
        # Default IP and MAC addresses
        nextIP6 = params['nextIP6']
        defaults = {'ip6': ipAdd6(nextIP6,
                                  ipBaseNum=self.ip6BaseNum,
                                  prefixLen=self.prefixLen6) +
                           '/%s' % self.prefixLen6
                   }
        defaults.update(params)

        if self.autoSetPositions:
            defaults['position'] = ('%s,0,0' % self.nextPosition)
        if self.autoSetMacs:
            defaults['mac'] = macColonHex(nextIP6)
        if self.autoPinCpus:
            defaults['cores'] = self.nextCore
            self.nextCore = (self.nextCore + 1) % self.numCores
        self.nextIP6 += 1
        self.nextPosition += 1

        if not cls:
            cls = self.sixLoWPan
        node = cls(name, **defaults)
        self.nameToNode[name] = node

        if 'position' in params:
            self.pos_to_array(node)

        self.addParameters(node, **defaults)
        self.sensors.append(node)
        return node

    # BL: We now have four ways to look up nodes
    # This may (should?) be cleaned up in the future.
    def getNodeByName(self, *args):
        "Return node(s) with given name(s)"
        if len(args) is 1:
            return self.nameToNode[args[0]]
        return [self.nameToNode[n] for n in args]

    def get(self, *args):
        "Convenience alias for getNodeByName"
        return self.getNodeByName(*args)

    # Even more convenient syntax for node lookup and iteration
    def __getitem__(self, key):
        "net[ name ] operator: Return node with given name"
        return self.nameToNode[key]

    def __delitem__(self, key):
        "del net[ name ] operator - delete node with given name"
        self.delNode(self.nameToNode[key])

    def __contains__(self, item):
        "returns True if net contains named node"
        return item in self.nameToNode

    def keys(self):
        "return a list of all node names or net's keys"
        return list(self)

    def values(self):
        "return a list of all nodes or net's values"
        return [self[name] for name in self]

    def items(self):
        "return (key,value) tuple list for every node in net"
        return zip(self.keys(), self.values())

    @staticmethod
    def _parsePing(pingOutput):
        "Parse ping output and return packets sent, received."
        # Check for downed link
        if 'connect: Network is unreachable' in pingOutput:
            return 1, 0
        r = r'(\d+) packets transmitted, (\d+)( packets)? received'
        m = re.search(r, pingOutput)
        if m is None:
            error('*** Error: could not parse ping output: %s\n' %
                  pingOutput)
            return 1, 0
        sent, received = int(m.group(1)), int(m.group(2))
        return sent, received

    @classmethod
    def ping6(self, hosts=None, timeout=None):
        """Ping6 between all specified hosts.
           hosts: list of hosts
           timeout: time to wait for a response, as string
           returns: ploss packet loss percentage"""
        # should we check if running?
        packets = 0
        lost = 0
        ploss = None
        if not hosts:
            hosts = self.sensors
            output('*** Ping: testing ping reachability\n')
        for node in hosts:
            output('%s -> ' % node.name)
            for dest in hosts:
                if node != dest:
                    opts = ''
                    if timeout:
                        opts = '-W %s' % timeout
                    if dest.intfs:
                        result = node.cmdPrint('ping6 -c1 %s %s'
                                               % (opts, dest.IP()))
                        sent, received = self._parsePing(result)
                    else:
                        sent, received = 0, 0
                    packets += sent
                    if received > sent:
                        error('*** Error: received too many packets')
                        error('%s' % result)
                        node.cmdPrint('route')
                        exit(1)
                    lost += sent - received
                    output(('%s ' % dest.name) if received else 'X ')
            output('\n')
        if packets > 0:
            ploss = 100.0 * lost / packets
            received = packets - lost
            output("*** Results: %i%% dropped (%d/%d received)\n" %
                   (ploss, received, packets))
        else:
            ploss = 0
            output("*** Warning: No packets sent\n")
        return ploss

    @staticmethod
    def _parseFull(pingOutput):
        "Parse ping output and return all data."
        errorTuple = (1, 0, 0, 0, 0, 0)
        # Check for downed link
        r = r'[uU]nreachable'
        m = re.search(r, pingOutput)
        if m is not None:
            return errorTuple
        r = r'(\d+) packets transmitted, (\d+)( packets)? received'
        m = re.search(r, pingOutput)
        if m is None:
            error('*** Error: could not parse ping output: %s\n' %
                  pingOutput)
            return errorTuple
        sent, received = int(m.group(1)), int(m.group(2))
        r = r'rtt min/avg/max/mdev = '
        r += r'(\d+\.\d+)/(\d+\.\d+)/(\d+\.\d+)/(\d+\.\d+) ms'
        m = re.search(r, pingOutput)
        if m is None:
            if received is 0:
                return errorTuple
            error('*** Error: could not parse ping output: %s\n' %
                  pingOutput)
            return errorTuple
        rttmin = float(m.group(1))
        rttavg = float(m.group(2))
        rttmax = float(m.group(3))
        rttdev = float(m.group(4))
        return sent, received, rttmin, rttavg, rttmax, rttdev

    def pingFull(self, hosts=None, timeout=None):
        """Ping between all specified hosts and return all data.
           hosts: list of hosts
           timeout: time to wait for a response, as string
           returns: all ping data; see function body."""
        # should we check if running?
        # Each value is a tuple: (src, dsd, [all ping outputs])
        all_outputs = []
        if not hosts:
            hosts = self.hosts
            output('*** Ping: testing ping reachability\n')
        for node in hosts:
            output('%s -> ' % node.name)
            for dest in hosts:
                if node != dest:
                    opts = ''
                    if timeout:
                        opts = '-W %s' % timeout
                    result = node.cmd('ping -c1 %s %s' % (opts, dest.IP()))
                    outputs = self._parsePingFull(result)
                    sent, received, rttmin, rttavg, rttmax, rttdev = outputs
                    all_outputs.append((node, dest, outputs))
                    output(('%s ' % dest.name) if received else 'X ')
            output('\n')
        output("*** Results: \n")
        for outputs in all_outputs:
            src, dest, ping_outputs = outputs
            sent, received, rttmin, rttavg, rttmax, rttdev = ping_outputs
            output(" %s->%s: %s/%s, " % (src, dest, sent, received))
            output("rtt min/avg/max/mdev %0.3f/%0.3f/%0.3f/%0.3f ms\n" %
                   (rttmin, rttavg, rttmax, rttdev))
        return all_outputs

    def pingAll(self, timeout=None):
        """Ping between all hosts.
           returns: ploss packet loss percentage"""
        return self.ping6(timeout=timeout)

    @staticmethod
    def _parseIperf(iperfOutput):
        """Parse iperf output and return bandwidth.
           iperfOutput: string
           returns: result string"""
        r = r'([\d\.]+ \w+/sec)'
        m = re.findall(r, iperfOutput)
        if m:
            return m[-1]
        else:
            # was: raise Exception(...)
            error('could not parse iperf output: ' + iperfOutput)
            return ''

    def iperf(self, hosts=None, l4Type='TCP', udpBw='10M', fmt=None,
              seconds=5, port=5001):
        """Run iperf between two hosts.
           hosts: list of hosts; if None, uses first and last hosts
           l4Type: string, one of [ TCP, UDP ]
           udpBw: bandwidth target for UDP test
           fmt: iperf format argument if any
           seconds: iperf time to transmit
           port: iperf port
           returns: two-element array of [ server, client ] speeds
           note: send() is buffered, so client rate can be much higher than
           the actual transmission rate; on an unloaded system, server
           rate should be much closer to the actual receive rate"""
        sleep(2)
        nodes = self.sensors
        hosts = hosts or [nodes[0], nodes[-1]]
        assert len(hosts) is 2
        client, server = hosts
        output('*** Iperf: testing', l4Type, 'bandwidth between',
               client, 'and', server, '\n')
        server.cmd('killall -9 iperf')
        iperfArgs = 'iperf -p %d ' % port
        bwArgs = ''
        if l4Type is 'UDP':
            iperfArgs += '-u '
            bwArgs = '-b ' + udpBw + ' '
        elif l4Type != 'TCP':
            raise Exception('Unexpected l4 type: %s' % l4Type)
        if fmt:
            iperfArgs += '-f %s ' % fmt
        server.sendCmd(iperfArgs + '-s')
        if l4Type is 'TCP':
            if not waitListening(client, server.IP(), port):
                raise Exception('Could not connect to iperf on port %d'
                                % port)
        cliout = client.cmd(iperfArgs + '-t %d -c ' % seconds +
                            server.IP() + ' ' + bwArgs)
        debug('Client output: %s\n' % cliout)
        servout = ''
        # We want the last *b/sec from the iperf server output
        # for TCP, there are two of them because of waitListening
        count = 2 if l4Type is 'TCP' else 1
        while len(re.findall('/sec', servout)) < count:
            servout += server.monitor(timeoutms=5000)
        server.sendInt()
        servout += server.waitOutput()
        debug('Server output: %s\n' % servout)
        result = [self._parseIperf(servout), self._parseIperf(cliout)]
        if l4Type is 'UDP':
            result.insert(0, udpBw)
        output('*** Results: %s\n' % result)
        return result

    @classmethod
    def count6LoWPANIfaces(self, **params):
        "Count the number of virtual 6LoWPAN interfaces"
        if 'wpans' in params:
            self.nwpans += int(params['wpans'])
            wpans = int(params['wpans'])
        else:
            wpans = 1
            self.nwpans += 1
        return wpans

    def kill_fakelb(self):
        "Kill fakelb"
        module.fakelb()
        sleep(0.1)

    def configureIface(self, node, wlan):
        intf = module.wlan_list[0]
        module.wlan_list.pop(0)
        node.renameIface(intf, node.params['wpan'][wlan])

    def closeMininetWiFi(self):
        "Close Mininet-WiFi"
        module.stop()
Esempio n. 12
0
    def __init__(self,
                 topo=None,
                 switch=LxcSwitch,
                 host=LxcNode,
                 controller=LxcRemoteController,
                 link=CloudLink,
                 intf=TCIntf,
                 mapper=None,
                 build=True,
                 xterms=False,
                 cleanup=False,
                 ipBase='10.0.0.0/8',
                 adminIpBase='192.168.0.1/8',
                 autoSetMacs=False,
                 autoPinCpus=False,
                 listenPort=None,
                 waitConnected=False,
                 waitConnectionTimeout=5,
                 jump=None,
                 user="******",
                 client_keys=None,
                 master=None,
                 pub_id=None,
                 **kwargs):
        """Create Mininet object.
           topo: Topo (topology) object or None
           switch: default Switch class
           host: default Host class/constructor
           controller: default Controller class/constructor
           link: default Link class/constructor
           intf: default Intf class/constructor
           ipBase: base IP address for hosts,
           mapper: mapper to map virtual topology onto physical topology
           build: build now from topo?
           xterms: if build now, spawn xterms?
           cleanup: if build now, cleanup before creating?
           inNamespace: spawn switches and controller in net namespaces?
           autoSetMacs: set MAC addrs automatically like IP addresses?
           autoStaticArp: set all-pairs static MAC addrs?
           autoPinCpus: pin hosts to (real) cores (requires CPULimitedHost)?
           listenPort: base listening port to open; will be incremented for
               each additional switch in the net if inNamespace=False
           waitConnected: wait for the switches to be connected to their controller
           waitConnectionTimeout: timeout to wait to decide if a switch is connected to its controller
           jump: SSH jump host
           master: master node"""
        self.topo = topo
        self.switch = switch
        self.host = host
        self.controller = controller
        self.link = link
        self.intf = intf
        self.ipBase = ipBase
        self.ipBaseNum, self.prefixLen = netParse(self.ipBase)
        hostIP = (0xffffffff >> self.prefixLen) & self.ipBaseNum
        # Start for address allocation
        self.nextIP = hostIP if hostIP > 0 else 1

        self.adminIpBase = adminIpBase
        self.adminIpBaseNum, self.adminPrefixLen = netParse(self.adminIpBase)
        adminIP = (0xffffffff >> self.adminPrefixLen) & self.adminIpBaseNum
        # Start for address allocation
        self.adminNextIP = adminIP if adminIP > 0 else 1

        #        self.inNamespace = inNamespace
        self.xterms = xterms
        self.cleanup = cleanup
        self.autoSetMacs = autoSetMacs
        #        self.autoStaticArp = autoStaticArp
        self.autoPinCpus = autoPinCpus
        #        self.numCores = numCores()
        #        self.nextCore = 0  # next core for pinning hosts to CPUs
        self.listenPort = listenPort
        self.waitConn = waitConnected
        self.waitConnectionTimeout = waitConnectionTimeout

        self.mapper = mapper
        #
        self.hosts = []
        self.switches = []
        self.controllers = []
        self.links = []

        self.loop = asyncio.get_event_loop()

        def runforever(loop):
            time.sleep(0.001)  ### DSA - WTF ?????????????
            loop.run_forever()

        self.thread = Thread(target=runforever, args=(self.loop, ))
        self.thread.start()

        self.jump = jump
        self.user = user
        self.pub_id = pub_id

        self.client_keys = client_keys
        self.masterhost = master
        _info("Connecting to master node\n")
        self.masterSsh = ASsh(loop=self.loop,
                              host=self.masterhost,
                              username=self.user,
                              bastion=self.jump,
                              client_keys=self.client_keys)
        self.masterSsh.connect()
        self.masterSsh.waitConnected()
        _info("connected to master node\n")

        self.nameToNode = {}  # name to Node (Host/Switch) objects

        self.terms = []  # list of spawned xterm processes

        self.init()  # Initialize Mininet if necessary

        self.built = False
        if topo and build:
            self.build()
Esempio n. 13
0
 def getIP(self, nextIP=1):
     ipBaseNum, prefixLen = netParse(IPBASE)
     return ipAdd(nextIP, ipBaseNum=ipBaseNum, prefixLen=prefixLen)
Esempio n. 14
0
    def __init__(self,
                 topo=None,
                 switch=OVSKernelSwitch,
                 accessPoint=OVSKernelAP,
                 host=Host,
                 station=Station,
                 car=Car,
                 controller=DefaultController,
                 link=Link,
                 intf=Intf,
                 build=True,
                 xterms=False,
                 ipBase='10.0.0.0/8',
                 inNamespace=False,
                 autoSetMacs=False,
                 autoStaticArp=False,
                 autoPinCpus=False,
                 listenPort=None,
                 waitConnected=False,
                 ssid="new-ssid",
                 mode="g",
                 channel="1",
                 enable_wmediumd=False,
                 enable_interference=False,
                 enable_spec_prob_link=False,
                 enable_error_prob=False,
                 fading_coefficient=0,
                 disableAutoAssociation=False,
                 driver='nl80211',
                 autoSetPositions=False,
                 configureWiFiDirect=False,
                 configure4addr=False,
                 defaultGraph=False,
                 noise_threshold=-91,
                 cca_threshold=-90,
                 rec_rssi=False):
        """Create Mininet object.
           topo: Topo (topology) object or None
           switch: default Switch class
           host: default Host class/constructor
           controller: default Controller class/constructor
           link: default Link class/constructor
           intf: default Intf class/constructor
           ipBase: base IP address for hosts,
           build: build now from topo?
           xterms: if build now, spawn xterms?
           cleanup: if build now, cleanup before creating?
           inNamespace: spawn switches and controller in net namespaces?
           autoSetMacs: set MAC addrs automatically like IP addresses?
           autoStaticArp: set all-pairs static MAC addrs?
           autoPinCpus: pin hosts to (real) cores (requires CPULimitedHost)?
           listenPort: base listening port to open; will be incremented for
               each additional switch in the net if inNamespace=False"""
        self.topo = topo
        self.switch = switch
        self.host = host
        self.station = station
        self.accessPoint = accessPoint
        self.car = car
        self.controller = controller
        self.link = link
        self.intf = intf
        self.ipBase = ipBase
        self.ipBaseNum, self.prefixLen = netParse(self.ipBase)
        self.nextIP = 1  # start for address allocation
        self.nextPosition = 1  # start for position allocation
        self.repetitions = 1  # mobility: number of repetitions
        self.inNamespace = inNamespace
        self.xterms = xterms
        self.autoSetMacs = autoSetMacs
        self.autoSetPositions = autoSetPositions
        self.autoStaticArp = autoStaticArp
        self.autoPinCpus = autoPinCpus
        self.numCores = numCores()
        self.nextCore = 0  # next core for pinning hosts to CPUs
        self.listenPort = listenPort
        self.waitConn = waitConnected
        self.routing = ''
        self.ssid = ssid
        self.mode = mode
        self.wmediumd_mode = ''
        self.channel = channel
        self.nameToNode = {}  # name to Node (Host/Switch) objects
        self.aps = []
        self.controllers = []
        self.hosts = []
        self.links = []
        self.cars = []
        self.carsSW = []
        self.carsSTA = []
        self.switches = []
        self.stations = []
        self.sixLP = []
        self.terms = []  # list of spawned xterm processes
        self.driver = driver
        self.disableAutoAssociation = disableAutoAssociation
        self.mobilityKwargs = ''
        self.isMobilityModel = False
        self.isMobility = False
        self.ppm_is_set = False
        self.alreadyPlotted = False
        self.DRAW = False
        self.ifb = False
        self.isVanet = False
        self.noise_threshold = noise_threshold
        self.cca_threshold = cca_threshold
        self.configureWiFiDirect = configureWiFiDirect
        self.configure4addr = configure4addr
        self.enable_wmediumd = enable_wmediumd
        self.enable_error_prob = enable_error_prob
        self.fading_coefficient = fading_coefficient
        self.enable_interference = enable_interference
        self.enable_spec_prob_link = enable_spec_prob_link
        self.mobilityparam = dict()
        self.AC = ''
        self.alternativeModule = ''
        self.rec_rssi = rec_rssi
        self.plot = plot2d
        self.n_radios = 0
        self.min_x = 0
        self.min_y = 0
        self.min_z = 0
        self.max_x = 0
        self.max_y = 0
        self.max_z = 0
        self.nroads = 0
        self.connections = {}
        self.wlinks = []
        Mininet_sixLoWPAN.init()  # Initialize Mininet if necessary

        self.built = False
        if topo and build:
            self.build()
Esempio n. 15
0
    def __init__( self, topo=None, switch=OVSKernelSwitch,
                  legacySwitch=LegacySwitch, hostInterface=HostInterface,
                  legacyRouter=QuaggaRouter,
                  transitPortalRouter=TransitPortalRouter,
                  host=Host, controller=Controller, link=Link, intf=Intf,
                  build=True, xterms=False, cleanup=False, ipBase='10.0.0.0/8',
                  inNamespace=False,
                  autoSetMacs=False, autoStaticArp=False, autoPinCpus=False,
                  listenPort=None, bridgeNum=0, defaultHostInterfaceBind='eth0'):
        """Create Mininet object.
           topo: Topo (topology) object or None
           switch: default Switch class
           host: default Host class/constructor
           controller: default Controller class/constructor
           link: default Link class/constructor
           intf: default Intf class/constructor
           ipBase: base IP address for hosts,
           build: build now from topo?
           xterms: if build now, spawn xterms?
           cleanup: if build now, cleanup before creating?
           inNamespace: spawn switches and controller in net namespaces?
           autoSetMacs: set MAC addrs automatically like IP addresses?
           autoStaticArp: set all-pairs static MAC addrs?
           autoPinCpus: pin hosts to (real) cores (requires CPULimitedHost)?
           listenPort: base listening port to open; will be incremented for
               each additional switch in the net if inNamespace=False"""
        self.topo = topo
        self.switch = switch
        self.legacySwitch = legacySwitch
        self.hostInterface = hostInterface
        self.legacyRouter = legacyRouter
        self.transitPortalRouter = transitPortalRouter
        self.host = host
        self.controller = controller
        self.link = link
        self.intf = intf
        self.ipBase = ipBase
        self.ipBaseNum, self.prefixLen = netParse( self.ipBase )
        self.nextIP = 1  # start for address allocation
        self.inNamespace = inNamespace
        self.xterms = xterms
        self.cleanup = cleanup
        self.autoSetMacs = autoSetMacs
        self.autoStaticArp = autoStaticArp
        self.autoPinCpus = autoPinCpus
        self.numCores = numCores()
        self.nextCore = 0  # next core for pinning hosts to CPUs
        self.listenPort = listenPort
        self.bridgeNum = bridgeNum
        self.defaultHostInterfaceBind = defaultHostInterfaceBind

        self.hosts = []
        self.switches = []
        self.legacySwitches = []
        self.hostInterfaces = []
        self.legacyRouters = []
        self.transitPortalRouters = []
        self.controllers = []

        self.nameToNode = {}  # name to Node (Host/Switch/hostInterface/legacy(Router,Switch)) objects
        self.physicalAdaptersBridged = [] # physical adapters connected to a (any) bridge
        self.bridgeInterfaces = [] # instantiated bridges

        self.terms = []  # list of spawned xterm processes

        Mininet.init()  # Initialize Mininet if necessary

        self.built = False
        if topo and build:
            self.build()
Esempio n. 16
0
    def __init__(self,
                 topo=None,
                 switch=OVSKernelSwitch,
                 legacySwitch=LegacySwitch,
                 hostInterface=HostInterface,
                 legacyRouter=QuaggaRouter,
                 transitPortalRouter=TransitPortalRouter,
                 host=Host,
                 controller=Controller,
                 link=Link,
                 intf=Intf,
                 build=True,
                 xterms=False,
                 cleanup=False,
                 ipBase='10.0.0.0/8',
                 inNamespace=False,
                 autoSetMacs=False,
                 autoStaticArp=False,
                 autoPinCpus=False,
                 listenPort=None,
                 bridgeNum=0,
                 defaultHostInterfaceBind='eth0'):
        """Create Mininet object.
           topo: Topo (topology) object or None
           switch: default Switch class
           host: default Host class/constructor
           controller: default Controller class/constructor
           link: default Link class/constructor
           intf: default Intf class/constructor
           ipBase: base IP address for hosts,
           build: build now from topo?
           xterms: if build now, spawn xterms?
           cleanup: if build now, cleanup before creating?
           inNamespace: spawn switches and controller in net namespaces?
           autoSetMacs: set MAC addrs automatically like IP addresses?
           autoStaticArp: set all-pairs static MAC addrs?
           autoPinCpus: pin hosts to (real) cores (requires CPULimitedHost)?
           listenPort: base listening port to open; will be incremented for
               each additional switch in the net if inNamespace=False"""
        self.topo = topo
        self.switch = switch
        self.legacySwitch = legacySwitch
        self.hostInterface = hostInterface
        self.legacyRouter = legacyRouter
        self.transitPortalRouter = transitPortalRouter
        self.host = host
        self.controller = controller
        self.link = link
        self.intf = intf
        self.ipBase = ipBase
        self.ipBaseNum, self.prefixLen = netParse(self.ipBase)
        self.nextIP = 1  # start for address allocation
        self.inNamespace = inNamespace
        self.xterms = xterms
        self.cleanup = cleanup
        self.autoSetMacs = autoSetMacs
        self.autoStaticArp = autoStaticArp
        self.autoPinCpus = autoPinCpus
        self.numCores = numCores()
        self.nextCore = 0  # next core for pinning hosts to CPUs
        self.listenPort = listenPort
        self.bridgeNum = bridgeNum
        self.defaultHostInterfaceBind = defaultHostInterfaceBind

        self.hosts = []
        self.switches = []
        self.legacySwitches = []
        self.hostInterfaces = []
        self.legacyRouters = []
        self.transitPortalRouters = []
        self.controllers = []

        self.nameToNode = {
        }  # name to Node (Host/Switch/hostInterface/legacy(Router,Switch)) objects
        self.physicalAdaptersBridged = [
        ]  # physical adapters connected to a (any) bridge
        self.bridgeInterfaces = []  # instantiated bridges

        self.terms = []  # list of spawned xterm processes

        Mininet.init()  # Initialize Mininet if necessary

        self.built = False
        if topo and build:
            self.build()