Beispiel #1
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)
Beispiel #2
0
    def tag_install(self, datapath, update_infos):
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser

        current_time = time() * 1000
        # if self.receiving_update_time is not None:
        #     self.logger.info("processing updates at %s" % str(current_time - self.receiving_update_time))

        for update in update_infos:
            # src+1, dst+1 -> IPs
            src_ip = ipAdd(update.init_sw + 1)
            dst_ip = ipAdd(update.end_sw + 1)

            self.logger.debug("process update %s" % update)

            if update.update_next_sw.type == constants.ADD_NEXT:

                out_port = self.topo[datapath.id][update.update_next_sw.next_sw
                                                  + 1]

                match = parser.OFPMatch(eth_type=ether_types.ETH_TYPE_IP,
                                        ipv4_src=src_ip,
                                        ipv4_dst=dst_ip)
                actions = [parser.OFPActionOutput(out_port)]

                self.add_flow(datapath, 2, match, actions)

            elif update.update_next_sw.type == constants.UPDATE_NEXT:
                out_port = self.topo[datapath.id][update.update_next_sw.next_sw
                                                  + 1]

                match = parser.OFPMatch(eth_type=ether_types.ETH_TYPE_IP,
                                        ipv4_src=src_ip,
                                        ipv4_dst=dst_ip)
                actions = [parser.OFPActionOutput(out_port)]

                self.update_flow(datapath, 2, match, actions)

            elif update.update_next_sw.type == constants.REMOVE_NEXT:
                match = parser.OFPMatch(eth_type=ether_types.ETH_TYPE_IP,
                                        ipv4_src=src_ip,
                                        ipv4_dst=dst_ip)

                self.remove_flow(datapath, 2, match)

            elif update.update_next_sw.type == constants.NO_UPDATE_NEXT:
                pass  # Do nothing

            else:
                raise Exception("what type?")

            if len(update.msgs) > 0:
                self.notification_queue.extend(update.msgs)

        self.logger.info("install_updates: here is the notification_queue %s" %
                         str(self.notification_queue))
        self.logger.info(
            "----------------------install_updates over---------------------")
        datapath.send_barrier()
    def process_update_info(self, datapath, sw, update_next, init_sw, end_sw):
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser

        # src+1, dst+1 -> IPs
        src_ip = ipAdd(init_sw + 1)
        dst_ip = ipAdd(end_sw + 1)

        self.logger.debug("process update %s of flow between %s, %s" %
                          (update_next, src_ip, dst_ip))

        if update_next.type == constants.ADD_NEXT or update_next.type == constants.UPDATE_NEXT:

            out_port = self.topo[datapath.id][update_next.next_sw + 1]

            match = parser.OFPMatch(eth_type=ether_types.ETH_TYPE_IP,
                                    ipv4_src=src_ip,
                                    ipv4_dst=dst_ip)
            actions = [parser.OFPActionOutput(out_port)]

            self.add_flow(datapath, 2, match, actions)
            msg = NotificationMessage(sw, global_vars.ctrl,
                                      constants.UPDATED_MSG,
                                      update_next.seg_path_id,
                                      self.current_update,
                                      time() * 1000)
            self.handler.scheduler.enque_msg_to_notification_queue(sw, msg)
            # notification_queue.append(msg)
            #
            # self.no_of_pending_msgs[(datapath.id, self.current_notification_time[datapath.id])] += 1

        elif update_next.type == constants.REMOVE_NEXT:
            match = parser.OFPMatch(eth_type=ether_types.ETH_TYPE_IP,
                                    ipv4_src=src_ip,
                                    ipv4_dst=dst_ip)

            self.remove_flow(datapath, 2, match)
            msg = NotificationMessage(sw, global_vars.ctrl,
                                      constants.REMOVED_MSG,
                                      update_next.seg_path_id,
                                      self.current_update,
                                      time() * 1000)
            # notification_queue.append(msg)
            # self.no_of_pending_msgs[(datapath.id, self.current_notification_time[datapath.id])] += 1
            self.handler.scheduler.enque_msg_to_notification_queue(sw, msg)

        elif update_next.type == constants.NO_UPDATE_NEXT:
            pass  # Do nothing

        else:
            raise Exception("what type?")
Beispiel #4
0
    def switch_features_handler(self, ev):
        datapath = ev.msg.datapath
        if self.datapath is None:
            self.datapath = datapath
        else:
            raise Exception('Only one switch can connect!')
        self.logger.info(datapath)
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser

        # install table-miss flow entry
        #
        # We specify NO BUFFER to max_len of the output action due to
        # OVS bug. At this moment, if we specify a lesser number, e.g.,
        # 128, OVS will send Packet-In with invalid buffer_id and
        # truncated packet data. In that case, we cannot output packets
        # correctly.  The bug has been fixed in OVS v2.1.0.
        match = parser.OFPMatch()
        # actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,
        #                                   ofproto.OFPCML_NO_BUFFER)]
        actions = [
            parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,
                                   ofproto.OFPCML_NO_BUFFER)
        ]
        self.add_flow(datapath, 0, match, actions)

        self.logger.info("datapath id %s", datapath.id)

        match = parser.OFPMatch(eth_type=ether_types.ETH_TYPE_IP,
                                ipv4_dst=ipAdd(datapath.id))
        actions = [parser.OFPActionOutput(1)]
        self.add_flow(datapath, 1, match, actions)
        hub.spawn(self.run_server)

        self.create_topology_info()
Beispiel #5
0
 def _auto_config_intf(self, node_name, intf_name, **param):
     node = self.nodemap[node_name]
     if 'port' not in param:
         param['port'] = node.newPort()
     if intf_name == 'auto':
         intf_name = Link.intfName(node, param['port'])
     if intf_name in node.nameToIntf:
         error("Node %s already has interface %s." % (node, name))
         return False
     net = self.mn
     if 'ip' not in param:
         ip = net.nextIP
         net.nextIP += 1
         sufix = ipAdd(ip, ipBaseNum=net.ipBaseNum, prefixLen=net.prefixLen)
         prefix = '/%s' % net.prefixLen
         param['ip'] =  sufix + prefix 
         if 'mac' not in param:
             param['mac'] = macColonHex(ip)
     elif 'mac' not in param:
         ip, prefix = netParse(param['ip'])
         param['mac'] = macColonHex(ip)
     if 'cores' not in param and net.autoPinCpus:
         param['cores'] = self.nextCore
         net.nextCore = (net.nextCore + 1) % net.numCores
     return True
Beispiel #6
0
    def addTransitPortalRouter(self, name, cls=None, **params):
        """Add transit portal router.
           name: name of transit portal router to add
           cls: custom router class/constructor (optional)
           returns: added transit portal router ."""

        # Default IP and MAC addresses
        defaults = {
            'ip':
            ipAdd(self.nextIP,
                  ipBaseNum=self.ipBaseNum,
                  prefixLen=self.prefixLen) + '/%s' % self.prefixLen
        }
        if self.autoSetMacs:
            defaults['mac'] = macColonHex(self.nextIP)
        if self.autoPinCpus:
            defaults['cores'] = self.nextCore
            self.nextCore = (self.nextCore + 1) % self.numCores
        self.nextIP += 1
        defaults.update(params)
        if not cls:
            cls = self.transitPortalRouter
        tpr = cls(name, **defaults)
        self.transitPortalRouters.append(tpr)
        self.nameToNode[name] = tpr
        return tpr
Beispiel #7
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)
    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)
    log.close()

    dbg(2, "conode is finished %s" % myNet)
    net.stop()
Beispiel #8
0
    def switch_features_handler(self, ev):
        datapath = ev.msg.datapath
        self.datapaths[datapath.id] = datapath

        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser


        # install table-miss flow entry
        #
        # We specify NO BUFFER to max_len of the output action due to
        # OVS bug. At this moment, if we specify a lesser number, e.g.,
        # 128, OVS will send Packet-In with invalid buffer_id and
        # truncated packet data. In that case, we cannot output packets
        # correctly.  The bug has been fixed in OVS v2.1.0.
        match = parser.OFPMatch()
        actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,
                                          ofproto.OFPCML_NO_BUFFER)]
        self.add_flow(datapath, 0, match, actions)

        self.logger.debug("datapath id %s", datapath.id)

        match = parser.OFPMatch(eth_type=ether_types.ETH_TYPE_IP, ipv4_dst=ipAdd(datapath.id))
        actions = [parser.OFPActionOutput(1)]
        self.add_flow(datapath, 1, match, actions)

        hub.patch(socket=True, thread=True, os=True, select=True)
        if len(self.datapaths) == len(self.topo):
            # All switches have connected
            # Can call to install new path from here
            hub.spawn_after(10, self._cyclic_update)
Beispiel #9
0
 def addHost(self, name, cls=None, **params):
     """Add host.
        name: name of host to add
        cls: custom host class/constructor (optional)
        params: parameters for host
        returns: added host"""
     # Default IP and MAC addresses
     defaults = {
         'ip':
         ipAdd(self.nextIP,
               ipBaseNum=self.ipBaseNum,
               prefixLen=self.prefixLen) + '/%s' % self.prefixLen
     }
     if self.autoSetMacs:
         defaults['mac'] = macColonHex(self.nextIP)
     if self.autoPinCpus:
         defaults['cores'] = self.nextCore
         self.nextCore = (self.nextCore + 1) % self.numCores
     self.nextIP += 1
     defaults.update(params)
     if not cls:
         cls = self.host
     h = cls(name, **defaults)
     self.hosts.append(h)
     self.nameToNode[name] = h
     return h
Beispiel #10
0
    def addHost( self, name, cls=None, **params ):
        """Add host.
           name: name of host to add
           cls: custom host class/constructor (optional)
           params: parameters for host
           returns: added host"""
        defaults = {}

        autoSetIp = params.get( 'autoSetIp', True )
        if autoSetIp:
            # Default IP and MAC addresses
            defaults[ 'ip' ] = ipAdd( self.nextIP, ipBaseNum=self.ipBaseNum,
                                    prefixLen=self.prefixLen) + '/%s' % (self.prefixLen,)
            if self.autoSetMacs:
                defaults[ 'mac' ] = macColonHex( self.nextIP )

            self.nextIP += 1
        if self.autoPinCpus:
            defaults[ 'cores' ] = self.nextCore
            self.nextCore = ( self.nextCore + 1 ) % self.numCores
        defaults.update( params )
        if not cls:
            cls = self.host
        h = cls( name, **defaults )
        self.hosts.append( h )
        self.nameToNode[ name ] = h
        return h
Beispiel #11
0
    def _add_host(self, net, net_name, host_name, options, idx=0):
        """ Starts the specified host at runtime (after the base topology has
            been initialized). """

        host_ip = options.get("ip")
        is_multi = options.get("multi", False)
        host_name_i = host_name
        if is_multi:
            host_name_i = host_name + "-" + str(idx + 1)
            host_base, host_prefix = netParse(host_ip)
            host_ip = ipAdd((host_base & 0xFF) + idx,
                            ipBaseNum=host_base,
                            prefixLen=host_prefix)
            host_ip += "/%i" % host_prefix

        if options.get("type") is Docker:
            # code to use ContainerNet (comment Docker code instead)
            mn_args = {
                "network_mode": "none",
                "dimage": options.get("dimage", "ubuntu"),
                "dcmd": options.get("dcmd", None),
                "ip": host_ip,
            }
            net.addDocker(host_name_i, **mn_args)
        else:
            # code to use ContainerNet (comment Docker code instead)
            mn_args = {
                "ip": host_ip,
            }
            net.addHost(host_name_i, **mn_args)

        # link the container to its switch
        net.addLink(host_name_i, options["link"], params1={'ip': host_ip})
        # restart the switch to configure the new link
        debug("%s" % (options["link"]))
Beispiel #12
0
 def build( self, count=1,ipstart=0x0a010000, br='br-int', brdp="0000abcdef000001" ):
     if isinstance(ipstart, str): ipstart=int(ipstart,16)
     customBr = self.addSwitch( str(br), dpid=str(brdp) )
     hosts = [ self.addHost( 'h%d' % i, ip= ipAdd(i,16,ipstart)+'/8') for i in range( 1, count + 1 ) ]
     # Add links
     for h in hosts:                                                                                                       
         self.addLink( h, customBr)
Beispiel #13
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
Beispiel #14
0
 def addHost( self, name, cls=None, **params ):
     """Add host.
        name: name of host to add
        cls: custom host class/constructor (optional)
        params: parameters for host
        returns: added host"""
     # Default IP and MAC addresses
     defaults = { 'ip': ipAdd( self.nextIP,
                               ipBaseNum=self.ipBaseNum,
                               prefixLen=self.prefixLen ) +
                               '/%s' % self.prefixLen }
     print defaults
     IPS=[]
     for lin in defaults.values():
         IPS.append(lin[0:8])
         print IPS
         
     with open('my_dict.json','a')as f:
         json.dump(defaults.values(),f)
         f.write('\n')
     if self.autoSetMacs:
         defaults[ 'mac'] = macColonHex( self.nextIP )
     if self.autoPinCpus:
         defaults[ 'cores' ] = self.nextCore
         self.nextCore = ( self.nextCore + 1 ) % self.numCores
     self.nextIP += 1
     defaults.update( params )
     if not cls:
         cls = self.host
     h = cls( name, **defaults )
     self.hosts.append( h )
     self.nameToNode[ name ] = h
     return h
Beispiel #15
0
    def addMesh(self, node, cls=None, **params):
        """
        Configure wireless mesh
        
        node: name of the node
        cls: custom association class/constructor
        params: parameters for node
        """
        if 'intf' in params:
            for intf_ in node.params['wlan']:
                if params['intf'] == intf_:
                    wlan = node.params['wlan'].index(intf_)
        else:
            if node.type == 'station':
                wlan = node.ifaceToAssociate
            else:
                wlan = node.ifaceToAssociate

        node.func[wlan] = 'mesh'
        node.params['txpower'][wlan] = 20

        options = {
            'ip':
            ipAdd(params['nextIP'],
                  ipBaseNum=params['ipBaseNum'],
                  prefixLen=params['prefixLen']) + '/%s' % params['prefixLen']
        }

        if node.type == 'ap':
            node.params['ssid'].append('')
        else:
            node.params['ssid'] = []
            for n in range(len(node.params['wlan'])):
                node.params['ssid'].append('')

        ip = ("%s" % params.pop('ip', {}))
        if ip == "{}":
            ip = options['ip']

        ssid = ("%s" % params['ssid'])
        if (ssid != "{}"):
            node.params['ssid'][wlan] = ssid
        else:
            node.params['ssid'][wlan] = 'meshNetwork'

        deviceRange(node)

        options['node'] = node
        options.update(params)

        node.setMeshIface(node.params['wlan'][wlan])
        if 'channel' in params:
            node.setChannel(node.params['wlan'][wlan], params['channel'])

        cls = Association
        cls.configureMesh(node, wlan)
        if 'intf' not in params:
            node.ifaceToAssociate += 1
Beispiel #16
0
    def testIpAdd( self ):
        self.assertEqual( ipAdd( 1, 24, 0xc0000200, socket.AF_INET ), "192.0.2.1" )
        self.assertEqual( ipAdd( 2**8 - 1, 24, 0xc0000200, socket.AF_INET ), "192.0.2.255" )
        with self.assertRaises(AssertionError):
            ipAdd( 256, 24, 0xc0000200, socket.AF_INET )

        self.assertEqual( ipAdd( 1, 64, 0x20010db8000000000000000000000000, socket.AF_INET6 ), "2001:db8::1" )
        self.assertEqual( ipAdd( 2**64 - 1, 64, 0x20010db8000000000000000000000000, socket.AF_INET6 ), "2001:db8::ffff:ffff:ffff:ffff" )
        with self.assertRaises(AssertionError):
            ipAdd( 2**64, 64, 0x20010db8000000000000000000000000, socket.AF_INET6 )
Beispiel #17
0
    def add_host(self,
                 name,
                 cls=DAQHost,
                 ip_addr=None,
                 env_vars=None,
                 vol_maps=None,
                 port=None,
                 tmpdir=None):
        """Add a host to the ecosystem"""
        override_ip = bool(ip_addr)
        if self._used_ip_indices and not ip_addr:
            for index in range(1, max(self._used_ip_indices)):
                if index not in self._used_ip_indices:
                    prefix_length = self._mininet_subnet.prefixlen
                    ip_addr = '%s/%s' % (mininet_util.ipAdd(
                        index,
                        prefixLen=prefix_length,
                        ipBaseNum=self.net.ipBaseNum), prefix_length)
                    break
        params = {'ip': ip_addr} if ip_addr else {}
        params['tmpdir'] = os.path.join(tmpdir, 'nodes') if tmpdir else None
        params['env_vars'] = env_vars if env_vars else []
        params['vol_maps'] = vol_maps if vol_maps else []
        try:
            host = self._retry_func(
                partial(self.net.addHost, name, cls, **params))
        except Exception as e:
            # If addHost fails, ip allocation needs to be explicityly cleaned up.
            self._reset_mininet_next_ip()
            raise e
        try:
            switch_link = self._retry_func(
                partial(self.net.addLink,
                        self.pri,
                        host,
                        port1=port,
                        fast=False))
            LOGGER.info('Created host %s with pid %s/%s, intf %s', name,
                        host.pid, host.shell.pid, switch_link.intf1)
            host.switch_intf = switch_link.intf1
            self.switch_links[host] = switch_link
            if self.net.built:
                host.configDefault()
                self._switch_attach(self.pri, host.switch_intf)
        except Exception as e:
            host.terminate()
            raise e

        if not override_ip and host.IP():
            self._used_ip_indices.add(self._get_host_ip_index(host))
        return host
Beispiel #18
0
    def addStation(self, name, cls=None, **params):
        """Add host.
           name: name of host to add
           cls: custom host class/constructor (optional)
           params: parameters for host
           returns: added host"""
        #Default IP and MAC addresses
        defaults = {
            'ip':
            ipAdd(self.nextIP,
                  ipBaseNum=self.ipBaseNum,
                  prefixLen=self.prefixLen) + '/%s' % self.prefixLen
        }
        if self.autoSetMacs:
            defaults['mac'] = macColonHex(self.nextIP)
        if self.autoPinCpus:
            defaults['cores'] = self.nextCore
            self.nextCore = (self.nextCore + 1) % self.numCores
        #self.nextIP += 1
        defaults.update(params)
        if not cls:
            cls = self.host
        h = cls(name, **defaults)
        self.hosts.append(h)
        self.nameToNode[name] = h
        self.wirelessifaceControl.append(self.nextIface)
        self.wirelessdeviceControl.append(name)
        self.stationName.append(name)

        os.system("iw phy phy%s set netns %s" % (self.nextIface, h.pid))
        self.host.cmd(
            h, "ip link set dev wlan%s name %s-wlan0" % (self.nextIface, h))
        self.host.cmd(h, "ifconfig %s-wlan0 up" % h)
        self.host.cmd(
            h, "ifconfig %s-wlan0 10.1.1.%s/%s" %
            (h, self.nextIP, self.prefixLen))

        #callfun="start"
        #intf=self.nextIface
        #src=name
        #wlink(callfun, intf, src)

        #self.host.cmd(h,"iw %s-wlan0 connect %s" % (h, "my_ssid"))
        self.nextIP += 1
        self.nextIface += 1
        #os.system("iw dev wlan2 interface add mesh2 type station")
        #os.system("sleep 2")
        #os.system("sleep 2")
        #os.system("iw dev mesh2 station join bazookaa")
        return h
Beispiel #19
0
 def build(self,
           count=1,
           ipstart=0x0a010000,
           br='br-int',
           brdp="0000abcdef000001"):
     if isinstance(ipstart, str): ipstart = int(ipstart, 16)
     customBr = self.addSwitch(str(br), dpid=str(brdp))
     hosts = [
         self.addHost('h%d' % i, ip=ipAdd(i, 16, ipstart) + '/8')
         for i in range(1, count + 1)
     ]
     # Add links
     for h in hosts:
         self.addLink(h, customBr)
Beispiel #20
0
def interopNet(topo):
    net = Mininet(host=P4Host)

    # Controllers have IPs from 10.10.0.0/16
    nextIP = 1
    ipBaseNum = 0x0a0a0000
    prefixLen = 16

    for sw_name in sorted(topo.get('switches', {}).keys()):
        sw_info = topo['switches'][sw_name]
        sw_cls = Node
        if 'class' in sw_info.keys():
            names = sw_info['class'].split('.')
            cls_module_name = '.'.join(names[:-1])
            cls_name = names[-1]
            cls_module = __import__(cls_module_name, fromlist=[cls_name])
            sw_cls = getattr(cls_module, cls_name)

        if 'prog' in sw_info.keys():
            # Resolve p4 program name conflicts
            prog_src = sw_info['prog']
            if not prog_src.startswith('/'):
                prog_src = os.path.join('/p4app', prog_src)
            prog_dst = os.path.join(os.path.dirname(prog_src),
                                    '_'.join(prog_src.split('/')))
            shutil.copy2(prog_src, prog_dst)
            sw_info['prog'] = prog_dst

        sw = net.addSwitch(sw_name, cls=sw_cls, **sw_info)
        if sw_info.get('enable_ctrl'):
            sw_ctrl = net.addHost(
                '%s-c' % sw_name,
                ip=ipAdd(nextIP, ipBaseNum=ipBaseNum, prefixLen=prefixLen) +
                '/%s' % prefixLen)
            nextIP += 1
            net.addLink(sw_ctrl, sw)

    for h_name in sorted(topo.get('hosts', {}).keys()):
        h_info = topo['hosts'][h_name]
        net.addHost(h_name, **h_info)

    for link in topo.get('links', []):
        node1 = link[0]
        node2 = link[1]
        link_args = link[2] if len(link) > 2 else {}
        net.addLink(node1, node2, **link_args)
    return net
Beispiel #21
0
 def addStation( self, name, cls=None, **params ):
     """Add host.
        name: name of host to add
        cls: custom host class/constructor (optional)
        params: parameters for host
        returns: added host"""
     #Default IP and MAC addresses
     defaults = { 'ip': ipAdd( self.nextIP,
                               ipBaseNum=self.ipBaseNum,
                               prefixLen=self.prefixLen ) +
                               '/%s' % self.prefixLen }
     if self.autoSetMacs:
         defaults[ 'mac' ] = macColonHex( self.nextIP )
     if self.autoPinCpus:
         defaults[ 'cores' ] = self.nextCore
         self.nextCore = ( self.nextCore + 1 ) % self.numCores
     #self.nextIP += 1
     defaults.update( params )
     if not cls:
         cls = self.host
     h = cls( name, **defaults )      
     self.hosts.append( h )
     self.nameToNode[ name ] = h
     self.wirelessifaceControl.append(self.nextIface)
     self.wirelessdeviceControl.append(name)
     self.stationName.append(name)
     
     os.system("iw phy phy%s set netns %s" % (self.nextIface, h.pid))
     self.host.cmd(h,"ip link set dev wlan%s name %s-wlan0" % (self.nextIface, h))
     self.host.cmd(h,"ifconfig %s-wlan0 up" % h)
     self.host.cmd(h,"ifconfig %s-wlan0 10.1.1.%s/%s" % (h, self.nextIP, self.prefixLen)) 
     
     #callfun="start"
     #intf=self.nextIface
     #src=name        
     #wlink(callfun, intf, src)
            
     #self.host.cmd(h,"iw %s-wlan0 connect %s" % (h, "my_ssid"))
     self.nextIP += 1        
     self.nextIface+=1
     #os.system("iw dev wlan2 interface add mesh2 type station")
     #os.system("sleep 2")
     #os.system("sleep 2")
     #os.system("iw dev mesh2 station join bazookaa")
     return h
Beispiel #22
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+"."
Beispiel #23
0
    def add6LoWPAN(self, name, cls=None, **params):
        """Add 6LoWPAN 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
        defaults = {
            'ip':
            ipAdd(self.nextIP,
                  ipBaseNum=self.ipBaseNum,
                  prefixLen=self.prefixLen) + '/%s' % self.prefixLen,
            'channel':
            self.channel,
            'mode':
            self.mode
        }
        defaults.update(params)

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

        if not cls:
            cls = self.station
        node = cls(name, **defaults)

        self.addParameters(node, self.autoSetMacs, defaults)

        self.sixLP.append(node)
        self.nameToNode[name] = node

        return node
Beispiel #24
0
 def addHost(self, name, cls=None, **params):
     """Add host.
        name: name of host to add
        cls: custom host class/constructor (optional)
        params: parameters for host
        returns: added host"""
     # Default IP and MAC addresses
     defaults = {
         "ip": ipAdd(self.nextIP, ipBaseNum=self.ipBaseNum, prefixLen=self.prefixLen) + "/%s" % self.prefixLen
     }
     if self.autoSetMacs:
         defaults["mac"] = macColonHex(self.nextIP)
     if self.autoPinCpus:
         defaults["cores"] = self.nextCore
         self.nextCore = (self.nextCore + 1) % self.numCores
     self.nextIP += 1
     defaults.update(params)
     if not cls:
         cls = self.host
     h = cls(name, **defaults)
     self.hosts.append(h)
     self.nameToNode[name] = h
     return h
    def addHost(self, name, cls=None, **params):
        """Add host.
           name: name of host to add
           cls: custom host class/constructor (optional)
           params: parameters for host
           returns: added host"""
        # Default IP and MAC addresses
        defaults = {
            'ip':
            ipAdd(self.nextIP,
                  ipBaseNum=self.ipBaseNum,
                  prefixLen=self.prefixLen) + '/%s' % self.prefixLen
        }
        if "image" in self.topo.nodeInfo(name):
            defaults.update({"image": self.topo.nodeInfo(name)["image"]})

        # XXX DSA - doesn't make sense to generate MAC automatically here, we
        # keep for compatibility prurpose but never use it...
        if self.autoSetMacs:
            defaults['mac'] = macColonHex(self.nextIP)
        if self.autoPinCpus:
            raise Exception("to be implemented")
#            defaults[ 'cores' ] = self.nextCore
#            self.nextCore = ( self.nextCore + 1 ) % self.numCores
        self.nextIP += 1
        defaults.update(params)

        if not cls:
            cls = self.host

        if self.mapper:
            defaults.update({"target": self.mapper.place(name)})

        h = cls(name=name, **defaults)
        self.hosts.append(h)
        self.nameToNode[name] = h
        return h
Beispiel #26
0
    def addTransitPortalRouter( self, name, cls=None, **params ):
        """Add transit portal router.
           name: name of transit portal router to add
           cls: custom router class/constructor (optional)
           returns: added transit portal router ."""

        # Default IP and MAC addresses
        defaults = { 'ip': ipAdd( self.nextIP,
                                  ipBaseNum=self.ipBaseNum,
                                  prefixLen=self.prefixLen ) +
                                  '/%s' % self.prefixLen }
        if self.autoSetMacs:
            defaults[ 'mac'] = macColonHex( self.nextIP )
        if self.autoPinCpus:
            defaults[ 'cores' ] = self.nextCore
            self.nextCore = ( self.nextCore + 1 ) % self.numCores
        self.nextIP += 1
        defaults.update( params )
        if not cls:
            cls = self.transitPortalRouter
        tpr = cls( name, **defaults )
        self.transitPortalRouters.append( tpr )
        self.nameToNode[ name ] = tpr
        return tpr
Beispiel #27
0
    def switch_features_handler(self, ev):
        datapath = ev.msg.datapath
        # reconnect = False
        if self.datapath is None:
            self.datapath = datapath
        else:
            # t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            self.logger.info("time is " + str(time()))
            self.logger.info("dp try to connect me is " + str(datapath))
            self.logger.info("dp i've connected is " + str(self.datapath))
            raise Exception('Only one switch can connect!')

        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser

        # install table-miss flow entry
        #
        # We specify NO BUFFER to max_len of the output action due to
        # OVS bug. At this moment, if we specify a lesser number, e.g.,
        # 128, OVS will send Packet-In with invalid buffer_id and
        # truncated packet data. In that case, we cannot output packets
        # correctly.  The bug has been fixed in OVS v2.1.0.

        #xunjie  modifiedx
        # kwargs = dict(ip_proto=inet.IPPROTO_UDP, udp_dst=6620)
        # kwargs = dict(udp_dst=6620)
        # match1 = parser.OFPMatch(**kwargs)
        kwargs = dict(eth_type=ether_types.ETH_TYPE_IP,
                      ip_proto=IPPROTO_UDP,
                      udp_dst=6620)
        match1 = parser.OFPMatch(**kwargs)

        # match = parser.OFPMatch(nw_proto='UDP',)
        # actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,
        #                                   ofproto.OFPCML_NO_BUFFER)]
        actions = [
            parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,
                                   ofproto.OFPCML_NO_BUFFER)
        ]

        self.add_flow(datapath, 0, match1, actions)

        # match = parser.OFPMatch()
        # # actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,
        # #                                   ofproto.OFPCML_NO_BUFFER)]
        # actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,
        #                                    ofproto.OFPCML_NO_BUFFER)]

        # self.add_flow(datapath, 0, match, actions)

        # self.logger.info("datapath id %s", datapath.id)

        match = parser.OFPMatch(eth_type=ether_types.ETH_TYPE_IP,
                                ipv4_dst=ipAdd(datapath.id))
        actions = [parser.OFPActionOutput(1)]

        self.add_flow(datapath, 1, match, actions)
        #modify the miss_len
        # req = parser.OFPSetConfig(datapath,ofproto.OFPC_FRAG_NORMAL,512)
        # datapath.send_msg(req)

        #after the only switch connected, start the server --global
        hub.spawn(self.run_server)
        # hub.spawn(self.run_server)
        self.create_topology_info()
Beispiel #28
0
 def getNextIp( self ):
     ip = ipAdd( self.nextIP,
                 ipBaseNum=self.ipBaseNum,
                 prefixLen=self.prefixLen ) + '/%s' % self.prefixLen
     self.nextIP += 1
     return ip
Beispiel #29
0
    def addHoc(self, node, cls=None, **params):
        """
        Configure AdHoc
        
        node: name of the node
        cls: custom association class/constructor
        params: parameters for station
           
        """
        if 'intf' in params:
            for intf_ in node.params['wlan']:
                if params['intf'] == intf_:
                    wlan = node.params['wlan'].index(intf_)
        else:
            wlan = node.ifaceToAssociate

        node.func[wlan] = 'adhoc'

        options = {
            'ip':
            ipAdd(params['nextIP'],
                  ipBaseNum=params['ipBaseNum'],
                  prefixLen=params['prefixLen']) + '/%s' % params['prefixLen']
        }
        options.update(params)

        node.params['cell'] = []
        node.params['ssid'] = []
        for w in range(0, len(node.params['wlan'])):
            node.params['cell'].append('')
            node.params['ssid'].append('')

        ip = ("%s" % params.pop('ip', {}))
        if ip == "{}":
            ip = options['ip']

        ssid = ("%s" % params.pop('ssid', {}))
        if (ssid != "{}"):
            node.params['ssid'][wlan] = ssid
            node.params['associatedTo'][wlan] = ssid
        else:
            node.params['ssid'][wlan] = 'adhocNetwork'
            node.params['associatedTo'][wlan] = 'adhocNetwork'

        cell = ("%s" % params.pop('cell', {}))
        if (cell != "{}"):
            node.params['cell'][wlan] = cell
        else:
            if 'position' not in node.params:
                node.params['cell'][wlan] = 'FE:4C:6A:B5:A9:7E'

        deviceRange(node)

        value = deviceDataRate(sta=node, wlan=wlan)
        self.bw = value.rate

        options['sta'] = node
        options.update(params)
        # Set default MAC - this should probably be in Link
        options.setdefault('addr1', self.randMac())

        cls = Association
        cls.configureAdhoc(node, self.useWmediumd)
        if 'intf' not in params:
            node.ifaceToAssociate += 1
    def buildFromTopo(self, topo=None):
        """Build mininet from a topology object
           At the end of this function, everything should be connected
           and up."""

        # Possibly we should clean up here and/or validate
        # the topo
        if self.cleanup:
            pass

        info('*** Creating network\n')

        bastion = self.jump
        waitStart = False
        _ip = "{}/{}".format(
            ipAdd(self.adminNextIP,
                  ipBaseNum=self.adminIpBaseNum,
                  prefixLen=self.adminPrefixLen), self.adminPrefixLen)
        self.adminNextIP += 1
        self.host.createMasterAdminNetwork(self.masterSsh,
                                           brname="admin-br",
                                           ip=_ip)
        _info(" admin network created on {}\n".format(self.masterhost))

        assert (isinstance(self.controllers, list))

        if not self.controllers and self.controller:
            # Add a default controller
            info('*** Adding controller\n')
            classes = self.controller
            if not isinstance(classes, list):
                classes = [classes]
            for i, cls in enumerate(classes):
                # Allow Controller objects because nobody understands partial()
                if isinstance(cls, Controller):
                    self.addController(cls)
                else:
                    self.addController('c%d' % i, cls)

#        from assh import ASsh
# prepare SSH connection to the master

        info('*** Adding hosts:\n')

        # == Hosts ===========================================================
        for hostName in topo.hosts():
            _ip = "{}/{}".format(
                ipAdd(self.adminNextIP,
                      ipBaseNum=self.adminIpBaseNum,
                      prefixLen=self.adminPrefixLen), self.adminPrefixLen)
            self.adminNextIP += 1
            #            __ip= newAdminIp(admin_ip)
            self.addHost(name=hostName,
                         admin_ip=_ip,
                         loop=self.loop,
                         master=self.masterSsh,
                         username=self.user,
                         bastion=bastion,
                         client_keys=self.client_keys,
                         waitStart=waitStart,
                         **topo.nodeInfo(hostName))
            info(hostName + ' ')

        info('\n*** Adding switches:\n')
        for switchName in topo.switches():
            _ip = "{}/{}".format(
                ipAdd(self.adminNextIP,
                      ipBaseNum=self.adminIpBaseNum,
                      prefixLen=self.adminPrefixLen), self.adminPrefixLen)
            self.adminNextIP += 1
            self.addSwitch(name=switchName,
                           admin_ip=_ip,
                           loop=self.loop,
                           master=self.masterSsh,
                           username=self.user,
                           bastion=bastion,
                           client_keys=self.client_keys,
                           waitStart=waitStart,
                           **topo.nodeInfo(switchName))
            info(switchName + ' ')

        if not waitStart:
            nodes = self.hosts + self.switches

            _info("[starting\n")
            for node in nodes:
                _info("connectTarget {} ".format(node.name))
                node.connectTarget()

            for node in nodes:
                node.waitConnectedTarget()
                _info("connectedTarget {} ".format(node.name))

            count = 0
            reset = 50
            for node in nodes:
                _info("createContainer {} ".format(node.name))
                node.createContainer()
                count += 1
                if count > reset:
                    output("{} nodes created...\n".format(reset))
                    sleep(10)
                    count = 0

            for node in nodes:
                node.waitCreated()
                _info("createdContainer {} ".format(node.name))

            for node in nodes:
                _info("create admin interface {} ".format(node.name))
                node.addContainerInterface(intfName="admin",
                                           brname="admin-br",
                                           wait=False)

            for node in nodes:
                node.targetSshWaitOutput()
                _info("admin interface created on {} ".format(node.name))
            _info("\n")

            cmds = []
            for node in nodes:
                cmds = cmds + node.connectToAdminNetwork(
                    master=node.masternode.host,
                    target=node.target,
                    link_id=CloudLink.newLinkId(),
                    admin_br="admin-br",
                    wait=False)
            if len(cmds) > 0:
                cmd = ';'.join(cmds)
                self.masterSsh.cmd(cmd)

            for node in nodes:
                node.configureContainer(wait=False)
            for node in nodes:
                node.targetSshWaitOutput()

            for node in nodes:
                _info("connecting {} ".format(node.name))
                node.connect()

            for node in nodes:
                node.waitConnected()
                _info("connected {} ".format(node.name))

            for node in nodes:
                _info("startshell {} ".format(node.name))
                node.asyncStartShell()
            for node in nodes:
                node.waitStarted()
                _info("startedshell {}".format(node.name))

            for node in nodes:
                _info("finalize {}".format(node.name))
                node.finalizeStartShell()
            _info("\n")

        info('\n*** Adding links:\n')
        for srcName, dstName, params in topo.links(sort=True, withInfo=True):
            self.addLink(**params)
            info('(%s, %s) ' % (srcName, dstName))
        info('\n')
Beispiel #31
0
 def getIP(self, nextIP=1):
     ipBaseNum, prefixLen = netParse(IPBASE)
     return ipAdd(nextIP, ipBaseNum=ipBaseNum, prefixLen=prefixLen)
Beispiel #32
0
from errno import EEXIST
from signal import SIGALRM, alarm, signal
from itertools import tee
from argparse import Action, ArgumentParser
from shutil import copy2, rmtree
from logging import basicConfig, INFO, getLogger
from time import sleep

GRID_MODULE_LISTEN_PORT = '12347'

LOCAL_IP = '192.168.0.0'
LOCAL_PREFIX = 16

# Local addresses of the LAN 192.168.0.0/16 with the prefix
# (except network and broadcast addresses)
LOCAL_ADDRS = ('{}/{}'.format(ipAdd(i + 1, LOCAL_PREFIX, ipParse(LOCAL_IP)),
                              LOCAL_PREFIX)
               for i in range((1 << (32 - LOCAL_PREFIX)) - 2))

GLOBAL_IP = '10.0.0.0'
GLOBAL_PREFIX = 8
SUBNET_PREFIX = 24

# Host addresses within each subnet with the subnet prefix.
# There is only one host address (10.x.y.1/24) in each subnet
# where each subnet is of the form 10.x.y.0/24
# and is part of the CIDR block 10.0.0.0/8.
HOST_ADDRS = ('{}/{}'.format(
    ipAdd(1 + i * (1 << (32 - SUBNET_PREFIX)), GLOBAL_PREFIX,
          ipParse(GLOBAL_IP)), SUBNET_PREFIX)
              for i in range(1 << (SUBNET_PREFIX - GLOBAL_PREFIX)))
Beispiel #33
0
 def getNextIp( self ):
     ip = ipAdd( self.nextIP,
                 ipBaseNum=self.ipBaseNum,
                 prefixLen=self.prefixLen ) + '/%s' % self.prefixLen
     self.nextIP += 1
     return ip
Beispiel #34
0
    def addMesh(self, node, cls=None, **params):
        """
        Configure wireless mesh
        
        node: name of the node
        cls: custom association class/constructor
        params: parameters for node
        """
        if 'intf' in params:
            for intf_ in node.params['wlan']:
                if params['intf'] == intf_:
                    wlan = node.params['wlan'].index(intf_)
        else:
            if node.type == 'station':
                wlan = node.ifaceToAssociate
            else:
                wlan = 0

        node.func[wlan] = 'mesh'

        options = {
            'ip':
            ipAdd(params['nextIP'],
                  ipBaseNum=params['ipBaseNum'],
                  prefixLen=params['prefixLen']) + '/%s' % params['prefixLen']
        }
        options.update(params)

        node.params['ssid'] = []
        if hasattr(node, 'meshMac'):
            for n in range(len(node.params['wlan'])):
                node.meshMac.append('')
                node.params['ssid'].append('')
        else:
            node.meshMac = []
            for n in range(len(node.params['wlan'])):
                node.meshMac.append('')
                node.params['ssid'].append('')

        ip = ("%s" % params.pop('ip', {}))
        if ip == "{}":
            ip = options['ip']

        ssid = ("%s" % params['ssid'])
        if (ssid != "{}"):
            node.params['ssid'][wlan] = ssid
        else:
            node.params['ssid'][wlan] = 'meshNetwork'

        deviceRange(node)

        value = deviceDataRate(sta=node, wlan=wlan)
        self.bw = value.rate

        options['node'] = node
        options.update(params)

        # Set default MAC - this should probably be in Link
        options.setdefault('addr1', self.randMac())

        cls = Association
        cls.configureMesh(node, wlan)
        if 'intf' not in params:
            node.ifaceToAssociate += 1