def create(self, topology):
        cs0 = topology.addSwitch('cs0', cls=OVSBridge)

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

        out_port = self.topo[datapath.id][msg.dst_id + 1]
        actions = [parser.OFPActionOutput(out_port)]

        src_mac = self.macStr(msg.src_id + 1)
        dst_mac = self.macStr(msg.dst_id + 1)

        src_ip = ipStr(msg.src_id + 1)
        dst_ip = ipStr(msg.dst_id + 1)
        self.logger.debug("sending message from %s to %s" % (src_ip, dst_ip))

        # self.logger.info("sending this message from %s to %s" % (src_ip, dst_ip))
        # self.logger.info(msg)
        # self.logger.info("sending over")
        udp_port = 6620

        e = ethernet.ethernet(dst=dst_mac,
                              src=src_mac,
                              ethertype=ether.ETH_TYPE_IP)
        sending_time = time() * 1000

        msg.sending_time = sending_time
        pmsg = pickle.dumps(msg)

        i = ipv4.ipv4(src=src_ip,
                      dst=dst_ip,
                      proto=IPPROTO_UDP,
                      total_length=ipv4.ipv4._MIN_LEN + udp.udp._MIN_LEN +
                      len(pmsg))
        u = udp.udp(dst_port=udp_port,
                    src_port=udp_port,
                    total_length=udp.udp._MIN_LEN + len(pmsg))
        self.logger.debug("message length: %d" % len(pmsg))

        pkt = packet.Packet()
        pkt.add_protocol(e)
        pkt.add_protocol(i)
        pkt.add_protocol(u)

        pkt.serialize()

        pkt.data += bytearray(pmsg)

        # FIXME: pmsg could be more than maximum payload ~1450 bytes

        out = parser.OFPPacketOut(datapath=datapath,
                                  in_port=ofproto.OFPP_CONTROLLER,
                                  buffer_id=ofproto.OFP_NO_BUFFER,
                                  actions=actions,
                                  data=pkt.data)
        # self.logger.info("in sendmsg the out.data %s "%str(out.data))
        # self.logger.info("in sendmsg the out.data over")
        if self.start_receiving_update_time is not None:
            current_time = time() * 1000
            # self.logger.info("sending msg to %d at %s" %
            #                  (msg.dst_id, str(current_time - self.receiving_update_time)))
        datapath.send_msg(out)
Beispiel #3
0
    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')

        if self.controllers:
            # Add a default controller
            info('*** Adding controller\n')
            classes = self.controller
            if type(classes) is not list:
                classes = [classes]
            for i, cls in enumerate(classes):
                self.addController('c%d' % i, cls)

        info('*** Adding hosts:\n')
        for hostName in topo.hosts():
            #aqui ele adiciona os hosts mesmo. Funcao self.addHost retorna o host adicionado! So precisa entao pegar esse host, passar pra classe MetricsCollector e ja era. Ou se preferir, tem uma lista com todos os hosts self.hosts.
            self.addHost(hostName, **topo.nodeInfo(hostName))
            info(hostName + ' ')
        #info( hostName + '\n' )

        if self.switches:
            info('\n*** Adding switches:\n')
            for switchName in topo.switches():
                self.addSwitch(switchName, **topo.nodeInfo(switchName))
                info(switchName + ' ')

        info('\n*** Adding links:\n')
        #pdb.set_trace()
        for srcName, dstName in topo.links(sort=True):
            src, dst = self.nameToNode[srcName], self.nameToNode[dstName]
            params = topo.linkInfo(srcName, dstName)
            srcPort, dstPort = topo.port(srcName, dstName)
            self.addLink(src, dst, srcPort, dstPort, **params)
            if self.isCCNhost(src):
                src.setIP(ipStr(ipParse(self.ccnNetBase) + 1) + '/30',
                          intf=src.name + '-eth' + str(srcPort))
                dst.setIP(ipStr(ipParse(self.ccnNetBase) + 2) + '/30',
                          intf=dst.name + '-eth' + str(dstPort))
                self.ccnNetBase = nextCCNnet(self.ccnNetBase)

            info('(%s, %s) ' % (src.name, dst.name))

        info('\n')
Beispiel #4
0
    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' )

        if self.controllers:
            # Add a default controller
            info( '*** Adding controller\n' )
            classes = self.controller
            if type( classes ) is not list:
                classes = [ classes ]
            for i, cls in enumerate( classes ):
                self.addController( 'c%d' % i, cls )

        info( '*** Adding hosts:\n' )
        for hostName in topo.hosts():
            #aqui ele adiciona os hosts mesmo. Funcao self.addHost retorna o host adicionado! So precisa entao pegar esse host, passar pra classe MetricsCollector e ja era. Ou se preferir, tem uma lista com todos os hosts self.hosts.
            self.addHost( hostName, **topo.nodeInfo( hostName ) )
            info( hostName + ' ' )
        #info( hostName + '\n' )

        if self.switches:
            info( '\n*** Adding switches:\n' )
            for switchName in topo.switches():
                self.addSwitch( switchName, **topo.nodeInfo( switchName) )
                info( switchName + ' ' )

        info( '\n*** Adding links:\n' )
	#pdb.set_trace()
        for srcName, dstName in topo.links(sort=True):
            src, dst = self.nameToNode[ srcName ], self.nameToNode[ dstName ]
            params = topo.linkInfo( srcName, dstName )
            srcPort, dstPort = topo.port( srcName, dstName )
            self.addLink( src, dst, srcPort, dstPort, **params )
            if self.isCCNhost(src):
                src.setIP(ipStr(ipParse(self.ccnNetBase) + 1) + '/30', intf=src.name + '-eth' + str(srcPort))
                dst.setIP(ipStr(ipParse(self.ccnNetBase) + 2) + '/30', intf=dst.name + '-eth' + str(dstPort))
                self.ccnNetBase=nextCCNnet(self.ccnNetBase)
                
            info( '(%s, %s) ' % ( src.name, dst.name ) )

        info( '\n' )
Beispiel #5
0
 def configureRoutedControlNetwork(self, ip='192.168.123.1', prefixLen=16):
     """Configure a routed control network on controller and switches.
        For use with the user datapath only right now."""
     controller = self.controllers[0]
     info(controller.name + ' <->')
     cip = ip
     snum = ipParse(ip)
     for switch in self.switches:
         info(' ' + switch.name)
         link = self.link(switch, controller, port1=0)
         sintf, cintf = link.intf1, link.intf2
         switch.controlIntf = sintf
         snum += 1
         while snum & 0xff in [0, 255]:
             snum += 1
         sip = ipStr(snum)
         cintf.setIP(cip, prefixLen)
         sintf.setIP(sip, prefixLen)
         controller.setHostRoute(sip, cintf)
         switch.setHostRoute(cip, sintf)
     info('\n')
     info('*** Testing control network\n')
     while not cintf.isUp():
         info('*** Waiting for', cintf, 'to come up\n')
         sleep(1)
     for switch in self.switches:
         while not sintf.isUp():
             info('*** Waiting for', sintf, 'to come up\n')
             sleep(1)
         if self.ping(hosts=[switch, controller]) != 0:
             error('*** Error: control network test failed\n')
             exit(1)
     info('\n')
Beispiel #6
0
    def build( self ):
        "Build network based on our topology."

        net = Mininet( topo=None )

        # Make controller
        net.addController( 'c0' )
        # Make nodes
        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:
                #Generate IP adddress in the 10.0/8 block
                ipAddr = ( 10 << 24 ) + nodeNum
                net.addHost( name, ip=ipStr( ipAddr ) )
            else:
                raise Exception( "Cannot create mystery node: " + name )
        # Make links
        for link in self.links.values():
            ( src, dst ) = link
            srcName, dstName = src[ 'text' ], dst[ 'text' ]
            src, dst = net.nameToNode[ srcName ], net.nameToNode[ dstName ]
            src.linkTo( dst )

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

        return net
Beispiel #7
0
    def routing_setup(self):
        self.cmd('sysctl net.ipv4.ip_forward=1')

        if routing_direct:
            for (gw, n, i) in otherNets:
                dbg(3, "Adding route for", n, gw)
                self.cmd('route add -net %s gw %s' % (n, gw))
            self.cmd('iptables -t nat -I POSTROUTING -j MASQUERADE')
        else:
            ournet = int(self.IP().split('.')[1])
            for (gw, n, i) in otherNets:
                othernet = int(n.split('.')[1])
                tunhost = ((ournet << 7) + othernet) << 2
                if ournet > othernet:
                    tunhost = (((othernet << 7) + ournet) << 2) + 1

                tunip = ipStr(ipNum(10, 255, 0, 1) + tunhost)
                tundev = "tun%d" % othernet
                dbg(
                    1, "Adding tunnel from %d to %d -> %s" %
                    (ournet, othernet, tunip))

                self.cmd("ip tunnel add %s mode gre remote %s" % (tundev, gw))
                self.cmd("ip link set %s up" % tundev)
                self.cmd("ip addr add %s/30 dev %s" % (tunip, tundev))
                self.cmd("ip route add %s dev %s" % (n, tundev))
    def build( self ):
        "Build network based on our topology."

        net = Mininet(controller=RemoteController, topo=None )

        # Make controller
        net.addController( 'c0' )
        # Make nodes
        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:
                net.addHost( name, ip=ipStr( nodeNum ) )
            else:
                raise Exception( "Cannot create mystery node: " + name )
        # Make links
        for link in self.links.values():
            ( src, dst ) = link
            srcName, dstName = src[ 'text' ], dst[ 'text' ]
            src, dst = net.nameToNode[ srcName ], net.nameToNode[ dstName ]
            src.linkTo( dst )

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

        return net
Beispiel #9
0
 def configureRoutedControlNetwork(self, ip="192.168.123.1", prefixLen=16):
     """Configure a routed control network on controller and switches.
        For use with the user datapath only right now."""
     controller = self.controllers[0]
     info(controller.name + " <->")
     cip = ip
     snum = ipParse(ip)
     for switch in self.switches:
         info(" " + switch.name)
         link = self.link(switch, controller, port1=0)
         sintf, cintf = link.intf1, link.intf2
         switch.controlIntf = sintf
         snum += 1
         while snum & 0xFF in [0, 255]:
             snum += 1
         sip = ipStr(snum)
         cintf.setIP(cip, prefixLen)
         sintf.setIP(sip, prefixLen)
         controller.setHostRoute(sip, cintf)
         switch.setHostRoute(cip, sintf)
     info("\n")
     info("*** Testing control network\n")
     while not cintf.isUp():
         info("*** Waiting for", cintf, "to come up\n")
         sleep(1)
     for switch in self.switches:
         while not sintf.isUp():
             info("*** Waiting for", sintf, "to come up\n")
             sleep(1)
         if self.ping(hosts=[switch, controller]) != 0:
             error("*** Error: control network test failed\n")
             exit(1)
     info("\n")
Beispiel #10
0
 def configureRoutedControlNetwork( self, ip='192.168.123.1',
     prefixLen=16 ):
     """Configure a routed control network on controller and switches.
        For use with the user datapath only right now.
        """
     controller = self.controllers[ 0 ]
     info( controller.name + ' <->' )
     cip = ip
     snum = ipParse( ip )
     for switch in self.switches:
         info( ' ' + switch.name )
         sintf, cintf = createLink( switch, controller )
         snum += 1
         while snum & 0xff in [ 0, 255 ]:
             snum += 1
         sip = ipStr( snum )
         controller.setIP( cintf, cip, prefixLen )
         switch.setIP( sintf, sip, prefixLen )
         controller.setHostRoute( sip, cintf )
         switch.setHostRoute( cip, sintf )
     info( '\n' )
     info( '*** Testing control network\n' )
     while not controller.intfIsUp( cintf ):
         info( '*** Waiting for', cintf, 'to come up\n' )
         sleep( 1 )
     for switch in self.switches:
         while not switch.intfIsUp( sintf ):
             info( '*** Waiting for', sintf, 'to come up\n' )
             sleep( 1 )
         if self.ping( hosts=[ switch, controller ] ) != 0:
             error( '*** Error: control network test failed\n' )
             exit( 1 )
     info( '\n' )
Beispiel #11
0
    def write_rtablefile(self, router):
        rtablefile = "rtable.%s" % router.name
        info( '*** Writing rtable file %s\n' % rtablefile)
        visited, path = dijkstra(self.graph, router.name)
        try:
            with open(rtablefile, 'w') as f:
                for i in range(0, len(router.ips)):
                    iface = '%s-eth%d' % (router.name, i+1)
                    ip = router.ips[i]
                    mask = router.masks[i]
                    subnet = ipStr(ipParse(ip) & ipParse(mask))
                    f.write('%s 0.0.0.0 %s eth%d\n' % (subnet, mask, i+1))
                for rt in self.vrouters.values():
                    if (rt.name == router.name):
                        continue
                    local = None
                    remote = None
                    reached = path[rt.name]
                    while (reached != router.name):
                        if (reached.split('.')[0] in self.vrouters):
                            remote = local
                            local = reached
                        reached = path[reached]

                    localrt = self.vrouters[local.split('.')[0]]
                    localport = int(local.split('.')[1])
                    remotert = self.vrouters[remote.split('.')[0]]
                    remoteport = int(remote.split('.')[1])
                    info("Reach %s from %s via %s.%d and %s.%d\n" % (
                            rt.name, router.name, localrt.name, 
                            localport, remotert.name, remoteport))
                    gw = remotert.ips[remoteport-1]
                    for i in range(0, len(rt.ips)):
                        iface = '%s-eth%d' % (rt.name, i+1)
                        ip = rt.ips[i]
                        mask = rt.masks[i]
                        subnet = ipStr(ipParse(ip) & ipParse(mask))
                        if (subnet in router.subnets):
                            continue
                        f.write('%s %s %s eth%d\n' % (subnet, gw, mask, 
                                    localport))
                        router.subnets.append(subnet)


                f.close()
        except EnvironmentError:
            sys.exit("Couldn't write IP file" % ipfile)
Beispiel #12
0
    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' )

        if not self.controllers and self.controller:
            # Add a default controller
            info( '*** Adding controller\n' )
            classes = self.controller
            if type( classes ) is not list:
                classes = [ classes ]
            for i, cls in enumerate( classes ):
                self.addController( 'c%d' % i, cls )

        info( '*** Adding hosts:\n' )
        for hostName in topo.hosts():
            self.addHost( hostName, **topo.nodeInfo( hostName ) )
            info( hostName + ' ' )

        info( '\n*** Adding switches:\n' )
        for switchName in topo.switches():
            self.addSwitch( switchName, **topo.nodeInfo( switchName) )
            info( switchName + ' ' )

        info( '\n*** Adding links:\n' )
        for srcName, dstName in topo.links(sort=True):
            src, dst = self.nameToNode[ srcName ], self.nameToNode[ dstName ]
            params = topo.linkInfo( srcName, dstName )
            srcPort, dstPort = topo.port( srcName, dstName )
            self.addLink( src, dst, srcPort, dstPort, **params )

            if self.isCCNhost(src):
                src.setIP(ipStr(ipParse(self.ccnNetBase) + 1) + '/30', intf=src.name + '-eth' + str(srcPort))
                dst.setIP(ipStr(ipParse(self.ccnNetBase) + 2) + '/30', intf=dst.name + '-eth' + str(dstPort))
                self.ccnNetBase=nextCCNnet(self.ccnNetBase)

            info( '(%s, %s) ' % ( src.name, dst.name ) )

        info( '\n' )
Beispiel #13
0
    def write_rtablefile(self, router):
        rtablefile = "rtable.%s" % router.name
        info('*** Writing rtable file %s\n' % rtablefile)
        visited, path = dijkstra(self.graph, router.name)
        try:
            with open(rtablefile, 'w') as f:
                for i in range(0, len(router.ips)):
                    iface = '%s-eth%d' % (router.name, i + 1)
                    ip = router.ips[i]
                    mask = router.masks[i]
                    subnet = ipStr(ipParse(ip) & ipParse(mask))
                    f.write('%s 0.0.0.0 %s eth%d\n' % (subnet, mask, i + 1))
                for rt in self.vrouters.values():
                    if (rt.name == router.name):
                        continue
                    local = None
                    remote = None
                    reached = path[rt.name]
                    while (reached != router.name):
                        if (reached.split('.')[0] in self.vrouters):
                            remote = local
                            local = reached
                        reached = path[reached]

                    localrt = self.vrouters[local.split('.')[0]]
                    localport = int(local.split('.')[1])
                    remotert = self.vrouters[remote.split('.')[0]]
                    remoteport = int(remote.split('.')[1])
                    info("Reach %s from %s via %s.%d and %s.%d\n" %
                         (rt.name, router.name, localrt.name, localport,
                          remotert.name, remoteport))
                    gw = remotert.ips[remoteport - 1]
                    for i in range(0, len(rt.ips)):
                        iface = '%s-eth%d' % (rt.name, i + 1)
                        ip = rt.ips[i]
                        mask = rt.masks[i]
                        subnet = ipStr(ipParse(ip) & ipParse(mask))
                        if (subnet in router.subnets):
                            continue
                        f.write('%s %s %s eth%d\n' %
                                (subnet, gw, mask, localport))
                        router.subnets.append(subnet)

                f.close()
        except EnvironmentError:
            sys.exit("Couldn't write IP file" % ipfile)
Beispiel #14
0
    def ethernetPairConnectivity(self):
        ndnNetBase = '10.0.0.0'
        interfaces = []
        for host in self.net.hosts:
            for intf in host.intfList():
                link = intf.link
                node1, node2 = link.intf1.node, link.intf2.node

                if isinstance(node1, Switch) or isinstance(node2, Switch):
                    continue

                if link.intf1 not in interfaces and link.intf2 not in interfaces:
                    interfaces.append(link.intf1)
                    interfaces.append(link.intf2)
                    node1.setIP(ipStr(ipParse(ndnNetBase) + 1) + '/30', intf=link.intf1)
                    node2.setIP(ipStr(ipParse(ndnNetBase) + 2) + '/30', intf=link.intf2)
                    ndnNetBase = ipStr(ipParse(ndnNetBase) + 4)
Beispiel #15
0
    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' )

        if not self.controllers:
            # Add a default controller
            info( '*** Adding controller\n' )
            classes = self.controller
            if type( classes ) is not list:
                classes = [ classes ]
            for i, cls in enumerate( classes ):
                self.addController( 'c%d' % i, cls )

        info( '*** Adding hosts:\n' )
        for hostName in topo.hosts():
            self.addHost( hostName, **topo.nodeInfo( hostName ) )
            info( hostName + ' ' )

        info( '\n*** Adding switches:\n' )
        for switchName in topo.switches():
            self.addSwitch( switchName, **topo.nodeInfo( switchName) )
            info( switchName + ' ' )

        info( '\n*** Adding links:\n' )
        for srcName, dstName in topo.links(sort=True):
            src, dst = self.nameToNode[ srcName ], self.nameToNode[ dstName ]
            params = topo.linkInfo( srcName, dstName )
            srcPort, dstPort = topo.port( srcName, dstName )
            self.addLink( src, dst, srcPort, dstPort, **params )
            if self.isCCNhost(src):
                src.setIP(ipStr(ipParse(self.ccnNetBase) + 1) + '/30', intf=src.name + '-eth' + str(srcPort))
                dst.setIP(ipStr(ipParse(self.ccnNetBase) + 2) + '/30', intf=dst.name + '-eth' + str(dstPort))
                self.ccnNetBase=nextCCNnet(self.ccnNetBase)
                
            info( '(%s, %s) ' % ( src.name, dst.name ) )

        info( '\n' )
Beispiel #16
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
Beispiel #17
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
Beispiel #18
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)
    def saveTopology( self ):
        "Save command."
        myFormats = [
            ('Mininet Topology','*.mn'),
            ('All Files','*'),
        ]
        
        #fileName = tkFileDialog.asksaveasfilename(filetypes=myFormats ,title="Save the topology as...")
	fileName="ip.txt";        
	if len(fileName ) > 0:
            #print "Now saving under %s" % fileName
            f = open(fileName, 'wb')
            fout = csv.writer(f)

            # Save Switches and Hosts
            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:
                    fout.writerow(["s",str(nodeNum),str(x1),str(y1)])
                    #print "Save Switch "+name+" at "+str(x1)+"/"+str(y1)+"."
                elif 'Host' in tags:
                    ip=ipStr( nodeNum )
                    fout.writerow(["h",str(nodeNum),str(x1),str(y1)])
                    #print "Save Host "+name+" with IP "+ip+" at "+str(x1)+"/"+str(y1)+"."
                else:
                    raise Exception( "Cannot create mystery node: " + name )
            
            # Save Links
            for link in self.links.values():
                ( src, dst ) = link
                srcName, dstName = src[ 'text' ], dst[ 'text' ]
                fout.writerow(["l",srcName,dstName])
                #print "Save Link from "+srcName+" to "+dstName+"."
            
            # Save Controller
            controllerType = self.controllerType
            if controllerType == 'remote':
                controllerIP = self.remoteIP
                controllerPort = self.remotePort
                fout.writerow(["c",controllerType, controllerIP, str(controllerPort)])
            elif controllerType == 'nox':
                fout.writerow(["c",controllerType])
            else:
                fout.writerow(["c",controllerType])

            f.close()
Beispiel #20
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)
Beispiel #21
0
 def __init__(self, name, addrs):
     self.name = name
     self.ips = []
     self.prefixes = []
     self.masks = []
     self.subnets = []
     self.ifaces = 0
     self.switch = None
     for addr in addrs:
         ip = addr.split("/")[0]
         prefix = int(addr.split("/")[1])
         mask = prefixToMask(prefix)
         subnet = ipStr(ipParse(ip) & ipParse(mask))
         self.ips.append(ip)
         self.prefixes.append(prefix)
         self.masks.append(mask)
         self.subnets.append(subnet)
Beispiel #22
0
 def __init__(self, name, addrs):
     self.name = name
     self.ips = []
     self.prefixes = []
     self.masks = []
     self.subnets = []
     self.ifaces = 0
     self.switch = None
     for addr in addrs:
         ip = addr.split("/")[0]
         prefix = int(addr.split("/")[1])
         mask = prefixToMask(prefix)
         subnet = ipStr(ipParse(ip) & ipParse(mask))
         self.ips.append(ip)
         self.prefixes.append(prefix)
         self.masks.append(mask)
         self.subnets.append(subnet)
    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:
                ip=ipStr( nodeNum )
                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 ) = link
            srcName, dstName = src[ 'text' ], dst[ 'text' ]
            print "Link from "+srcName+" to "+dstName+"."
Beispiel #24
0
def execute(options):
    "Create a network based on template_file"

    template_file = options.templateFile
    install_dir='/usr/local/etc/mini-ndn/'

    if template_file == '':
        template_file = install_dir + 'default-topology.conf'

    if options.testbed:
        template_file = install_dir + 'minindn.testbed.conf'

    if os.path.exists(template_file) == False:
        info('No template file given and default template file cannot be found. Exiting...\n')
        quit()

    # Update nfd.conf file used by Mini-NDN to match the currently installed version of NFD
    nfdConfFile = "%s/nfd.conf" % install_dir
    os.system("sudo cp /usr/local/etc/ndn/nfd.conf.sample %s" % nfdConfFile)
    os.system("sudo sed -i \'s|default_level [A-Z]*$|default_level $LOG_LEVEL|g\' %s" % nfdConfFile)

    topo = NdnTopo(template_file, options.workDir)

    t = datetime.datetime.now()

    if topo.isTCLink == True and topo.isLimited == True:
        net = Mininet(topo,host=CpuLimitedNdnHost,link=TCLink)
    elif topo.isTCLink == True and topo.isLimited == False:
        net = Mininet(topo,host=NdnHost,link=TCLink)
    elif topo.isTCLink == False and topo.isLimited == True:
        net = Mininet(topo,host=CpuLimitedNdnHost)
    else:
        net = Mininet(topo,host=NdnHost,controller=RemoteController)

    # [PZ] probable alternative is to have net=Mininet(...,build=False) and add something like
    # net.addController(name='c0', controller=RemoteController, ip='127.0.0.1')
    # ..and then have net.build()

    t2 = datetime.datetime.now()

    delta = t2 - t

    info('Setup time: ' + str(delta.seconds) + '\n')    

    net.start()

    # Giving proper IPs to intf so neighbor nodes can communicate
    # This is one way of giving connectivity, another way could be
    # to insert a switch between each pair of neighbors
    ndnNetBase = "1.0.0.0"
    sdnNetBase = "2.0.0.0"
    sdnHostCount = 0
    interfaces = []
    for host in net.hosts:
        for intf in host.intfList():
            link = intf.link
            node1, node2 = link.intf1.node, link.intf2.node

            # if node1 in net.switches or node2 in net.switches:
                # print "%s or %s is a switch" % (node1.name, node2.name)
                # continue

            if node1 in net.hosts and node2 in net.switches:
                sdnHostCount += 1
                if sdnHostCount > 254:
                    print "too many sdn hosts"
                    exit()
                node1.setIP(ipStr(ipParse(sdnNetBase) + sdnHostCount) + '/24', intf=link.intf1)
                continue

            if node2 in net.hosts and node1 in net.switches:
                sdnHostCount += 1
                if sdnHostCount > 254:
                    print "too many sdn hosts"
                    exit()
                node2.setIP(ipStr(ipParse(sdnNetBase) + sdnHostCount) + '/24', intf=link.intf2)
                continue


            if link.intf1 not in interfaces and link.intf2 not in interfaces:
                interfaces.append(link.intf1)
                interfaces.append(link.intf2)
                node1.setIP(ipStr(ipParse(ndnNetBase) + 1) + '/30', intf=link.intf1)
                node2.setIP(ipStr(ipParse(ndnNetBase) + 2) + '/30', intf=link.intf2)
                ndnNetBase = ipStr(ipParse(ndnNetBase) + 4)

    nodes = ""    # Used later to check prefix name in checkFIB

    # NLSR initialization
    for host in net.hosts:
        nodes += str(host.name) + ","

        conf = next(x for x in hosts_conf if x.name == host.name)
        host.nlsrParameters = conf.nlsrParameters

        if options.nFaces is not None:
            host.nlsrParameters["max-faces-per-prefix"] = options.nFaces

        if options.hr is True:
            host.nlsrParameters["hyperbolic-state"] = "on"

        # Generate NLSR configuration file
        configGenerator = NlsrConfigGenerator(host)
        configGenerator.createConfigFile()

        # Start NLSR
        host.nlsr = Nlsr(host)
        host.nlsr.start()

    nodes = nodes[0:-1]

    for host in net.hosts:
        if 'app' in host.params:
            if host.params['app'] != '':
                app = host.params['app']
                print "Starting " + app + " on node " + host.name
                print(host.cmd(app))

    # Load experiment
    experimentName = options.experimentName

    if experimentName is not None:
        print "Loading experiment: %s" % experimentName

        experimentArgs = {
            "net": net,
            "nodes": nodes,
            "ctime": options.ctime,
            "nPings": options.nPings,
            "strategy": Nfd.STRATEGY_BEST_ROUTE_V3
        }

        experiment = ExperimentManager.create(experimentName, experimentArgs)

        if experiment is not None:
            experiment.start()
        else:
            print "ERROR: Experiment '%s' does not exist" % experimentName
            return

    if options.isCliEnabled is True:
        CLI(net)

    net.stop()
Beispiel #25
0
def prefixToMask(prefix):
    shift = 32 - prefix
    return ipStr((0xffffffff >> shift) << shift)
Beispiel #26
0
 def testIpStr( self ):
     self.assertEqual( ipStr( 0xc0000201, socket.AF_INET ), "192.0.2.1" )
     self.assertEqual( ipStr( 0x7f000001, socket.AF_INET ), "127.0.0.1" )
     self.assertEqual( ipStr( 0x01, socket.AF_INET ), "0.0.0.1")
     self.assertEqual( ipStr( 0x20010db8000000000000000000000001, socket.AF_INET6 ), "2001:db8::1" )
     self.assertEqual( ipStr( 0x01, socket.AF_INET6 ), "::1")
Beispiel #27
0
def prefixToMask(prefix):
    shift = 32 - prefix
    return ipStr((0xffffffff >> shift) << shift)
Beispiel #28
0
def nextCCNnet(curCCNnet):
    netNum = ipParse(curCCNnet)
    return ipStr(netNum+4)