def delete( self ): "Delete interface" if self.nsInstalled: warn( "You can not delete once installed ns-3 device, " "run mininet.ns3.clear() to delete all ns-3 devices\n" ) else: Intf.delete( self )
def removeLink( self, node, intf_name ): if self.debug_flag1: args = (node, intf_name) print "EXEC: removeLink(%s, %s):" % args assert isinstance(node, Host) #Node) assert intf_name in node.nameToIntf dummy = self.nameToNode.get("dummy", None) if dummy is None: error('dummy node does not exist\n') return assert isinstance(dummy, Dummy) # Special case: Node already connected to dummy. intf = node.nameToIntf[intf_name] assert intf.link != None assert intf.link.intf1 == intf or intf.link.intf2 == intf assert intf.node != dummy if intf.link.intf1.node == dummy or intf.link.intf2.node == dummy: warn('intf %s of %s already removed\n' % (intf_name, node.name)) return unused = dummy.nameToUnusedPorts if len(unused) == 0: dummy_intf_port = dummy.newPort() dummy_intf_name = 'dummy-eth' + str(dummy_intf_port) unused[dummy_intf_name] = dummy_intf_port else: dummy_intf_name = min(unused, key=unused.get) self.moveLink(node, dummy, intf_name, dummy_intf_name)
def addAp( self, node, channelNumber, ssid=None, enableQos=False, port=None, intfName=None, **attrs): if ssid is None: ssid = self.baseSsid + str(len (self.aps) + 1) if channelNumber <= 0 or channelNumber > self.maxChannelNumber: channelNumber = random.randint (1, self.maxChannelNumber) warn("illegal channel number, choose a random channel number %s.\n", channelNumber) phyHelper = ns.wifi.YansWifiPhyHelper().Default() phyHelper.Set ("ChannelNumber", ns.core.UintegerValue(channelNumber)) if enableQos: macHelper = ns.wifi.QosWifiMacHelper.Default() else: macHelper = ns.wifi.NqosWifiMacHelper.Default() setAttributes (macHelper.SetType, "ns3::ApWifiMac", attrs) tb = self.add (node, phyHelper, macHelper, port, intfName) if type( ssid ) is str: wifissid = ns.wifi.Ssid (ssid) else: wifissid = ssid try: tb.nsDevice.GetMac ().SetAttribute ("Ssid", ns.wifi.SsidValue (wifissid)) except: warn("the type of wifissid isn't ssidvalue.\n") wifissid = ns.wifi.Ssid (self.baseSsid + str(len (self.aps) + 1)) tb.nsDevice.GetMac ().SetAttribute ("Ssid", ns.wifi.SsidValue (wifissid)) self.aps.append(tb) return tb
def dumpTopology(net, agent, collector, topofile): info('*** Dumping topology\n') topoData = {'nodes': {}, 'links': {}} for s in net.switches: topoData['nodes'][s.name] = { 'dpid': s.dpid, 'ports': {}, 'agent': agent } path = '/sys/devices/virtual/net/' for child in os.listdir(path): parts = re.match('(^s[0-9]+)-(.*)', child) if parts == None: continue ifindex = open(path + child + '/ifindex').read().split('\n', 1)[0] topoData['nodes'][parts.group(1)]['ports'][child] = { 'ifindex': ifindex } i = 0 for s1 in net.switches: j = 0 for s2 in net.switches: if j > i: intfs = s1.connectionsTo(s2) for intf in intfs: s1ifIdx = topoData['nodes'][s1.name]['ports'][ intf[0].name]['ifindex'] s2ifIdx = topoData['nodes'][s2.name]['ports'][ intf[1].name]['ifindex'] linkName = '%s-%s' % (s1.name, s2.name) info('topology link %s: %s %s %s %s %s %s\n' % (linkName, s1, intf[0].name, s1ifIdx, s2, intf[1].name, s2ifIdx)) topoData['links'][linkName] = { 'node1': s1.name, 'port1': intf[0].name, 'node2': s2.name, 'port2': intf[1].name } j += 1 i += 1 #now identify the leaf/edge switches for h in net.hosts: for s in net.switches: intfs = h.connectionsTo(s) if intfs: topoData['nodes'][s.name]['tag'] = 'edge' if topofile is None: try: put('http://' + collector + ':8008/topology/json', data=dumps(topoData)) except: warn("topology HTTP PUT failed\n") else: try: f = open(topofile, 'w') f.write(dumps(topoData, indent=4)) f.flush() f.close except: warn("topology write to file failed\n")
def __init__( self, name, n=1, reactive=True, runAsRoot=False, **params): """n: number of ONOS instances to run (1) reactive: run in reactive mode (True) runAsRoot: run ONOS as root (False)""" self.check() self.count = n self.reactive = reactive self.runAsRoot = runAsRoot self.ids = range( 0, self.count ) Controller.__init__( self, name, **params ) self.proxies = [] # We don't need to run as root, and it can interfere # with starting Zookeeper manually self.user = None if not self.runAsRoot: try: self.user = quietRun( 'who am i' ).split()[ 0 ] self.sendCmd( 'su', self.user ) self.waiting = False except: warn( '__init__: failed to drop privileges\n' ) self.cmd( 'mkdir -p', self.logDir ) # Need to run commands from ONOS dir self.cmd( 'cd', self.onosDir ) self.cmd( 'export PATH=$PATH:%s' % self.onosDir )
def build(self, config): """ Given JSON definition of topology, build a Mininet network. :param config: JSON config :return: None """ self.json_config = config nodes = {} # Add Hosts and Switches for node in config['nodes']: if node['id'].startswith('h'): info('Host {} added\n'.format(node['id'])) nodes[node['id']] = self.addHost(str(node['id'])) elif node['id'].startswith('s'): info('Switch {} added\n'.format(node['id'])) nodes[node['id']] = self.addSwitch(str(node['id'])) else: error('Unknown node type encountered!\n') exit(1) # Add links for link in config['links']: src, dst = link['source'], link['target'] latency, bandwidth = link['properties']['latency'], link[ 'properties']['bandwidth'] # check if link config is valid if src not in nodes or dst not in nodes: error('Link src or destination does not exist! \t{}<->{}\n'. format(src, dst)) exit(1) if latency < 0: error('Link has latency smaller than 0! \t{}<->{}\n'.format( src, dst)) exit(1) elif latency == 0 and not self.zero_warning_given: self.zero_warning_given = True warn( 'Attention, working with "{}ms" delay in topologies where there are links with some delay can ' 'yield unexpected results! As a precaution "0ms" is changed to "0.1ms"\n' .format(latency)) hs, hd = nodes.get(src), nodes.get(dst) latency = latency if latency > 1 else 0.1 # Note: Assumption here is that only the bottleneck link notably contributes to the rtt! If that's not the # case, the buffers on the bottleneck links are too small to fully utilize the path. Furthermore do # non-bottleneck links get a small fixed size buffer (~20 pkts) which should be enough to saturate the # bottlenecks as long as the links have a large enough rate compared to the bottleneck. q_size = self.calculate_queue_size(rtt=2 * latency, rate=bandwidth) linkopts = dict(bw=bandwidth, delay='{}ms'.format(latency), jitter='0ms', max_queue_size=q_size) self.addLink(hs, hd, **linkopts) info('Link added {}-{}, options {}\n'.format(hs, hd, linkopts)) self._set_host_pairings()
def waitConnected(self, timeout=None, delay=0.5): """wait for each switch to connect to a controller, up to 5 seconds timeout: time to wait, or None to wait indefinitely delay: seconds to sleep per iteration returns: True if all switches are connected""" info("*** Waiting for switches to connect\n") time = 0 remaining = list(self.switches) while True: for switch in tuple(remaining): if switch.connected(): info("%s " % switch) remaining.remove(switch) if not remaining: info("\n") return True if time > timeout and timeout is not None: break sleep(delay) time += delay warn("Timed out after %d seconds\n" % time) for switch in remaining: if not switch.connected(): warn("Warning: %s is not connected to a controller\n" % switch.name) else: remaining.remove(switch) return not remaining
def __init__(self, name, n=1, reactive=True, runAsRoot=False, **params): """n: number of ONOS instances to run (1) reactive: run in reactive mode (True) runAsRoot: run ONOS as root (False)""" self.check() self.count = n self.reactive = reactive self.runAsRoot = runAsRoot self.ids = range(0, self.count) Controller.__init__(self, name, **params) self.proxies = [] # We don't need to run as root, and it can interfere # with starting Zookeeper manually self.user = None if not self.runAsRoot: try: self.user = quietRun('who am i').split()[0] self.sendCmd('su', self.user) self.waiting = False except: warn('__init__: failed to drop privileges\n') self.cmd('mkdir -p', self.logDir) # Need to run commands from ONOS dir self.cmd('cd', self.onosDir) self.cmd('export PATH=$PATH:%s' % self.onosDir)
def setPosition(node, x, y, z): """ Set the ns-3 (x, y, z) position of a Mininet node. Coordinates are in the 3D Cartesian system. The unit is meters. node: Mininet node x: integer or float x coordinate y: integer or float y coordinate z: integer or float z coordinate""" # Check if this Mininet node has assigned the underlying ns-3 node. if hasattr(node, 'nsNode') and node.nsNode is not None: # If it is assigned, go ahead. pass else: # If not, create new ns-3 node and assign it to this Mininet node. node.nsNode = ns.network.Node() allNodes.append(node) try: mm = node.nsNode.GetObject(ns.mobility.MobilityModel.GetTypeId()) if x is None: x = 0.0 if y is None: y = 0.0 if z is None: z = 0.0 # Set postion coordinates in the ns-3 node pos = mm.SetPosition(ns.core.Vector(x, y, z)) except AttributeError: warn("ns-3 mobility model not found, not setting position\n")
def fixLimits(): "Fix ridiculously small resource limits." debug("*** Setting resource limits\n") try: rlimitTestAndSet(RLIMIT_NPROC, 8192) rlimitTestAndSet(RLIMIT_NOFILE, 16384) #Increase open file limit sysctlTestAndSet('fs.file-max', 10000) #Increase network buffer space sysctlTestAndSet('net.core.wmem_max', 16777216) sysctlTestAndSet('net.core.rmem_max', 16777216) sysctlTestAndSet('net.ipv4.tcp_rmem', '10240 87380 16777216') sysctlTestAndSet('net.ipv4.tcp_wmem', '10240 87380 16777216') sysctlTestAndSet('net.core.netdev_max_backlog', 5000) #Increase arp cache size sysctlTestAndSet('net.ipv4.neigh.default.gc_thresh1', 4096) sysctlTestAndSet('net.ipv4.neigh.default.gc_thresh2', 8192) sysctlTestAndSet('net.ipv4.neigh.default.gc_thresh3', 16384) #Increase routing table size sysctlTestAndSet('net.ipv4.route.max_size', 32768) #Increase number of PTYs for nodes sysctlTestAndSet('kernel.pty.max', 20000) # pylint: disable=broad-except except Exception: warn("*** Error setting resource limits. " "Mininet's performance may be affected.\n")
def _run_pox_switch( self ): if self.pox_pid is not None: warn( "Killing old pox switch to restart new one." ) self._kill_pox_switch() self._build_cmd_args() self.cmd( self.command, printPid=True ) self.pox_pid = self.lastPid print "MY POX PIDDDDDDDDDD: "+str(self.pox_pid) self.started_switch = True return "Run the POX switch" # @GLY print "running !" if self.pox_pid is not None: print "poxid is not none" warn( "Killing old pox switch to restart new one." ) self.lastPid = self.pox_pid self._kill_pox_switch() self.pox_pid = self.lastPid else: self.pox_pid = 1 print "yyyyyyyyyyyyyyyy" self._build_cmd_args() self.cmd( self.command, printPid=True ) self.started_switch = True
def movehosts(): h_list = hosts[:] # move these hosts for host in h_list: if host[0].name == 'h1': continue # don't move h1 # get a new switch to connect to other_nets = [s for s in subnets if host[1] not in s] net = secure_rand.choice(other_nets) new = secure_rand.choice(net) # find an open port on the switch port = 0 sports = new.ports.values() for i in range(0, 48): if i not in sports: port = i break if port != 0: # move the host info('\n* Moving', host[0], 'from', host[1], 'to', new, 'port', port, '\n') hintf, sintf = mobility_switch.moveHost(host[0], host[1], new, newPort=port) host[0].cmd('dhclient ' + host[0].defaultIntf().name) startpings(host[0], ping[host[0]]) hi = hosts.index(host) if hi is not None: hosts[hi] = (host[0], new) else: warn('\nTHIS SHOULD NOT HAPPEN\n') time.sleep(move_interval)
def addAp( self, node, ssid="ns3-80211ac", enableQos=True, channelNumber = 36, port=None, intfName=None, **attrs): if ssid is None: ssid = self.baseSsid + str(len (self.aps) + 1) if channelNumber <= 0 or channelNumber > self.maxChannelNumber: channelNumber = random.randint (1, self.maxChannelNumber) warn("illegal channel number, choose a random channel number %s.\n", channelNumber) phyHelper = ns.wifi.YansWifiPhyHelper().Default() phyHelper.SetChannel (self.channel) phyHelper.Set ("ShortGuardEnabled", ns.core.BooleanValue(1)) if enableQos: macHelper = ns.wifi.VhtWifiMacHelper.Default() else: macHelper = ns.wifi.WifiMacHelper.Default() if type( ssid ) is str: wifissid = ns.wifi.Ssid (ssid) else: wifissid = ssid macHelper.SetType ("ns3::ApWifiMac", "Ssid", ns.wifi.SsidValue(wifissid)) tb = self.add (node, phyHelper, macHelper, port, intfName) try: tb.nsDevice.GetMac ().SetAttribute ("Ssid", ns.wifi.SsidValue (wifissid)) except: warn("the type of wifissid isn't ssidvalue.\n") wifissid = ns.wifi.Ssid (self.baseSsid + str(len (self.aps) + 1)) tb.nsDevice.GetMac ().SetAttribute ("Ssid", ns.wifi.SsidValue (wifissid)) self.aps.append(tb) return tb
def checkListening( self ): "Warn if remote controller is not accessible" listening = self.cmd( "echo A | telnet -e A %s %d" % ( self.ip, self.port ) ) if 'Unable' in listening: warn( "Unable to contact the remote controller" " at %s:%d\n" % ( self.ip, self.port ) )
def start(): """ Start the simulator thread in background. It should be called after configuration of all ns-3 objects (TBintfs, Segments and Links). Attempt of adding an ns-3 object when simulator thread is running may result in segfault. You should stop it first.""" global thread if 'thread' in globals() and thread.isAlive(): warn("NS-3 simulator thread already running.") return # Install all TapBridge ns-3 devices not installed yet. for intf in allTBIntfs: if not intf.nsInstalled: intf.nsInstall() # Set up the simulator thread. thread = threading.Thread(target=runthread) thread.daemon = True # Start the simulator thread (this is where fork happens). # FORK! thread.start() # FORK:PARENT # Code below is executed in the parent thread. # Move all tap interfaces not moved yet to the right namespace. for intf in allTBIntfs: if not intf.inRightNamespace: intf.namespaceMove() return
def start( self, controllers ): "Start up a new POX OpenFlow switch" if self.poxCoreDir is not None: self.cmd( 'cd ' + self.poxCoreDir ) # We should probably call config instead, but this # requires some rethinking... self.cmd( 'ifconfig lo up' ) # Annoyingly, --if-exists option seems not to work for intf in self.intfList(): #nameToIntf #self.intfNames if not intf.IP(): self.attach( intf ) # Add controllers. # NOTE: This case is currently impossible and inaccessible. if not self.controller_ip or not self.controller_port: warn( 'warning: bad input controller ip and port' ) if len(controllers) == 1: c = controllers[0] self.controller_ip = c.IP() self.controller_port = c.port else: raise Exception('Cannot find unique controller to connect to') self._run_pox_switch()
def validatePort( self, intf ): "Validate intf's OF port number" ofport = int( self.cmd( 'ovs-vsctl get Interface', intf, 'ofport' ) ) if ofport != self.ports[ intf ]: warn( 'WARNING: ofport for', intf, 'is actually', ofport, '\n' )
def defaultIntf(self): "Return interface for lowest port" ports = self.intfs.keys() if ports: return self.intfs[min(ports)] else: warn("*** defaultIntf: warning:", self.name, "has no interfaces\n")
def do_arp( self, line ): "Send gratuitous arps from all data network hosts" startTime = time.time() try: count = int( line ) except: count = 1 # Technically this check should be on the host if '-U' not in quietRun( 'arping -h', shell=True ): warn( 'Please install iputils-arping.\n' ) return # This is much faster if we do it in parallel for host in self.mn.net.hosts: intf = host.defaultIntf() # -b: keep using broadcasts; -f: quit after 1 reply # -U: gratuitous ARP update host.sendCmd( 'arping -bf -c', count, '-U -I', intf.name, intf.IP() ) for host in self.mn.net.hosts: # We could check the output here if desired host.waitOutput() info( '.' ) info( '\n' ) elapsed = time.time() - startTime debug( 'Completed in %.2f seconds\n' % elapsed )
def watchDog(sw): try: writeToFile(sw.keepaliveFile, "Remove this file to terminate %s" % sw.name) while True: if ONOSBmv2Switch.mininet_exception == 1 \ or not os.path.isfile(sw.keepaliveFile): sw.killBmv2(log=False) return if sw.stopped: return with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s: port = sw.grpcPortInternal if sw.grpcPortInternal else sw.grpcPort if s.connect_ex(('localhost', port)) == 0: time.sleep(1) else: warn("\n*** WARN: switch %s crashed ☠️, restarting... \n" % sw.name) sw.stop() sw.start() return except Exception as e: warn("*** ERROR: " + e.message) sw.killBmv2(log=True)
def waitConnected(self, timeout=5, delay=.5): """wait for each switch to connect to a controller, up to 5 seconds timeout: time to wait, or None to wait indefinitely delay: seconds to sleep per iteration returns: True if all switches are connected""" info('*** Waiting for switches to connect\n') time = 0 remaining = list(self.switches) while True: for switch in tuple(remaining): if switch.connected(): info('%s ' % switch) remaining.remove(switch) if not remaining: info('\n') return True if timeout is not None and time > timeout: break sleep(delay) time += delay warn('Timed out after %d seconds\n' % time) for switch in remaining: if not switch.connected(): warn('Warning: %s is not connected to a controller\n' % switch.name) else: remaining.remove(switch) return not remaining
def defaultIntf(self): "Return interface for lowest port" ports = self.intfs.keys() if ports: return self.intfs[min(ports)] else: warn('*** defaultIntf: warning:', self.name, 'has no interfaces\n')
def waitConnected(self, timeout=None, delay=.5): """wait for each switch to connect to a controller timeout: time to wait, or None or True to wait indefinitely delay: seconds to sleep per iteration returns: True if all switches are connected""" info('*** Waiting for switches to connect\n') time = 0.0 remaining = list(self.switches) # False: 0s timeout; None: wait forever (preserve 2.2 behavior) if isinstance(timeout, bool): timeout = None if timeout else 0 while True: for switch in tuple(remaining): if switch.connected(): info('%s ' % switch) remaining.remove(switch) if not remaining: info('\n') return True if timeout is not None and time >= timeout: break sleep(delay) time += delay warn('Timed out after %d seconds\n' % time) for switch in remaining: if not switch.connected(): warn('Warning: %s is not connected to a controller\n' % switch.name) else: remaining.remove(switch) return not remaining
def start(): """ Start the simulator thread in background. It should be called after configuration of all ns-3 objects (TBintfs, Segments and Links). Attempt of adding an ns-3 object when simulator thread is running may result in segfault. You should stop it first.""" global thread if 'thread' in globals() and thread.isAlive(): warn( "NS-3 simulator thread already running." ) return # Install all TapBridge ns-3 devices not installed yet. for intf in allTBIntfs: if not intf.nsInstalled: intf.nsInstall() # Set up the simulator thread. thread = threading.Thread( target = runthread ) thread.daemon = True # Start the simulator thread (this is where fork happens). # FORK! thread.start() # FORK:PARENT # Code below is executed in the parent thread. # Move all tap interfaces not moved yet to the right namespace. for intf in allTBIntfs: if not intf.inRightNamespace: intf.namespaceMove() return
def fixLimits(): "Fix ridiculously small resource limits." debug( "*** Setting resource limits\n" ) try: rlimitTestAndSet( RLIMIT_NPROC, 8192 ) rlimitTestAndSet( RLIMIT_NOFILE, 16384 ) #Increase open file limit sysctlTestAndSet( 'fs.file-max', 10000 ) #Increase network buffer space sysctlTestAndSet( 'net.core.wmem_max', 16777216 ) sysctlTestAndSet( 'net.core.rmem_max', 16777216 ) sysctlTestAndSet( 'net.ipv4.tcp_rmem', '10240 87380 16777216' ) sysctlTestAndSet( 'net.ipv4.tcp_wmem', '10240 87380 16777216' ) sysctlTestAndSet( 'net.core.netdev_max_backlog', 5000 ) #Increase arp cache size sysctlTestAndSet( 'net.ipv4.neigh.default.gc_thresh1', 4096 ) sysctlTestAndSet( 'net.ipv4.neigh.default.gc_thresh2', 8192 ) sysctlTestAndSet( 'net.ipv4.neigh.default.gc_thresh3', 16384 ) #Increase routing table size sysctlTestAndSet( 'net.ipv4.route.max_size', 32768 ) #Increase number of PTYs for nodes sysctlTestAndSet( 'kernel.pty.max', 20000 ) except: warn( "*** Error setting resource limits. " "Mininet's performance may be affected.\n" )
def setPosition( node, x, y, z ): """ Set the ns-3 (x, y, z) position of a Mininet node. Coordinates are in the 3D Cartesian system. The unit is meters. node: Mininet node x: integer or float x coordinate y: integer or float y coordinate z: integer or float z coordinate""" # Check if this Mininet node has assigned the underlying ns-3 node. if hasattr( node, 'nsNode' ) and node.nsNode is not None: # If it is assigned, go ahead. pass else: # If not, create new ns-3 node and assign it to this Mininet node. node.nsNode = ns.network.Node() allNodes.append( node ) try: mm = node.nsNode.GetObject( ns.mobility.MobilityModel.GetTypeId() ) if x is None: x = 0.0 if y is None: y = 0.0 if z is None: z = 0.0 # Set postion coordinates in the ns-3 node pos = mm.SetPosition( ns.core.Vector( x, y, z ) ) except AttributeError: warn( "ns-3 mobility model not found, not setting position\n" )
def check_net_config( self ): "Check for any previous CMSnet configurations and adjust if necessary." try: with open(self.config_folder+"/cn.config_cmsnet", "r") as f: config_raw = f.read() config = {} if config_raw: config, l = defaultDecoder.raw_decode(config_raw) for attr in config: if attr.startswith("topo"): # Handle separately. pass elif attr == "net_cls": cls = getattr(mininet.net, config[attr]) setattr(self, attr, cls) elif attr.endswith("cls"): cls = getattr(cmsnet.cms_comp, config[attr]) setattr(self, attr, cls) elif isinstance(config[attr], basestring): setattr(self, attr, str(config[attr])) else: setattr(self, attr, config[attr]) topo_cls_name = config.get("topo_cls") if topo_cls_name: topo_cls = getattr(cmsnet.cms_topo, topo_cls_name) topo_opts = config.get("topo_opts", {}) topo = topo_cls(**topo_opts) self.params.update({'topo': topo}) else: warn("\nNo topology exists for CMSnet\n") f.close() except IOError as e: info("\nNo config exists for CMSnet\n")
def addSta( self, node, channelNumber, ssid=None, enableQos=False, enableScan = True, port=None, intfName=None, **attrs): if ssid is None: ssid = "" if channelNumber <= 0 or channelNumber > self.maxChannelNumber: channelNumber = random.randint (1, self.maxChannelNumber) warn("illegal channel number, choose a random channel number %s.\n", channelNumber) phyHelper = ns.wifi.YansWifiPhyHelper().Default() phyHelper.Set ("ChannelNumber", ns.core.UintegerValue(channelNumber)) if enableQos: macHelper = ns.wifi.QosWifiMacHelper.Default() else: macHelper = ns.wifi.NqosWifiMacHelper.Default() setAttributes (macHelper.SetType, "ns3::StaWifiMac", attrs) tb = self.add (node, phyHelper, macHelper, port, intfName) if type( ssid ) is str: wifissid = ns.wifi.Ssid (ssid) else: wifissid = ssid try: tb.nsDevice.GetMac ().SetAttribute ("Ssid", ns.wifi.SsidValue (wifissid)) except: warn("the type of wifissid isn't ssidvalue.\n") tb.nsDevice.GetMac ().SetAttribute ("Ssid", ns.wifi.SsidValue ("")) if enableScan: tb.nsDevice.GetMac ().SetAttribute ("ScanType", ns.core.EnumValue (ns.wifi.StaWifiMac.ACTIVE)) tb.nsDevice.GetMac ().SetAttribute ("MaxScanningChannelNumber", ns.core.UintegerValue(self.maxChannelNumber)) else: tb.nsDevice.GetMac ().SetAttribute ("ScanType", ns.core.EnumValue (ns.wifi.StaWifiMac.NOTSUPPORT)) self.stas.append(tb) return tb
def doOnosNetcfg(self, controllerIP): """ Notifies ONOS about the new device via Netcfg. """ srcIP = self.getSourceIp(controllerIP) if not srcIP: warn("WARN: unable to get device IP address, won't do onos-netcfg") return cfgData = {"devices": {self.onosDeviceId: self.getDeviceConfig(srcIP)}} with open(self.netcfgfile, 'w') as fp: json.dump(cfgData, fp, indent=4) # Build netcfg URL url = 'http://%s:8181/onos/v1/network/configuration/' % controllerIP # Instantiate password manager for HTTP auth pm = urllib2.HTTPPasswordMgrWithDefaultRealm() pm.add_password(None, url, os.environ['ONOS_WEB_USER'], os.environ['ONOS_WEB_PASS']) urllib2.install_opener( urllib2.build_opener(urllib2.HTTPBasicAuthHandler(pm))) # Push config data to controller req = urllib2.Request(url, json.dumps(cfgData), {'Content-Type': 'application/json'}) try: f = urllib2.urlopen(req) print f.read() f.close() except urllib2.URLError as e: warn("WARN: unable to push config to ONOS (%s)" % e.reason)
def delete(self): "Delete interface" if self.nsInstalled: warn("You can not delete once installed ns-3 device, " "run mininet.ns3.clear() to delete all ns-3 devices\n") else: Intf.delete(self)
def doOnosNetcfg(self): """ Notifies ONOS about the new device via Netcfg. """ controllerIP = "127.0.0.1" srcIP = self.getSourceIp(controllerIP) if not srcIP: warn( "*** WARN: unable to get switch IP address, won't do netcfg\n") return cfgData = self.getDeviceConfig(srcIP) with open(self.netcfgfile, 'w') as fp: json.dump(cfgData, fp, indent=4) if not self.netcfg: # Do not push config to ONOS. return # Build netcfg URL url = 'http://%s:1818/' % controllerIP # Instantiate password manager for HTTP auth # pm = urllib2.HTTPPasswordMgrWithDefaultRealm() # pm.add_password(None, url, ONOS_WEB_USER, ONOS_WEB_PASS) # urllib2.install_opener(urllib2.build_opener( # urllib2.HTTPBasicAuthHandler(pm))) # Push config data to controller req = urllib2.Request(url, json.dumps(cfgData), {'Content-Type': 'application/json'}) try: f = urllib2.urlopen(req) print f.read() f.close() except urllib2.URLError as e: warn("*** WARN: unable to push config to ONOS (%s)\n" % e.reason)
def validatePort(switch, intf): "Validate intf's OF port number" ofport = int(switch.cmd("ovs-vsctl get Interface", intf, "ofport")) if ofport != switch.ports[intf]: warn("WARNING: ofport for", intf, "is actually", ofport, "\n") return 0 else: return 1
def getGatewayIntf( self ): routes = self.cmd( 'ip route show' ) match = re.search('default via \S+ dev (\S+)', routes ) if match: return match.group( 1 ) else: warn( 'There is no default route set. Using eth0 as gateway interface...\n' ) return 'eth0'
def start(self, *args, **kwargs): if not self._is_active: self.startcmd(self, *args, **kwargs) self._is_active = True else: warn( newline('<! Cannot start the already active node', self.name, '!>'))
def validatePort(switch, intf): "Validate intf's OF port number" ofport = int(switch.cmd('ovs-vsctl get Interface', intf, 'ofport')) if ofport != switch.ports[intf]: warn('WARNING: ofport for', intf, 'is actually', ofport, '\n') return 0 else: return 1
def start(self, controllers): if not self.stopped: warn("*** %s is already running!\n" % self.name) return # Remove files from previous executions (if we are restarting) self.cleanupTmpFiles() if self.grpcPort is None: self.grpcPort = pickUnusedPort() writeToFile("/tmp/bmv2-%s-grpc-port" % self.name, self.grpcPort) if self.useStratum: config_dir = "/tmp/bmv2-%s-stratum" % self.name os.mkdir(config_dir) with open(self.chassisConfigFile, 'w') as fp: fp.write(self.chassisConfig()) if self.grpcPortInternal is None: self.grpcPortInternal = pickUnusedPort() cmdString = self.getStratumCmdString(config_dir) else: if self.thriftPort is None: print("grpc port is ", self.grpcPort) print("Thrift port is ", self.thriftPort) print("Unused thrift port xelected", str(self)) self.thriftPort = pickUnusedPort() writeToFile("/tmp/bmv2-%s-thrift-port" % self.name, self.thriftPort) cmdString = self.getBmv2CmdString() print("BMV2 cmd string is :" + cmdString) if self.dryrun: info("\n*** DRY RUN (not executing %s)\n" % self.targetName) debug("\n%s\n" % cmdString) try: if not self.dryrun: # Start the switch self.stopped = False self.logfd = open(self.logfile, "w") self.logfd.write(cmdString + "\n\n" + "-" * 80 + "\n\n") self.logfd.flush() self.bmv2popen = self.popen(cmdString, stdout=self.logfd, stderr=self.logfd) self.waitBmv2Start() # We want to be notified if BMv2/Stratum dies... threading.Thread(target=watchDog, args=[self]).start() #self.doOnosNetcfg(self.controllerIp(controllers)) except Exception: ONOSBmv2Switch.mininet_exception = 1 self.killBmv2() self.printBmv2Log() raise
def setup( cls ): "Check dependencies and warn about firewalling" pathCheck( 'brctl', moduleName='bridge-utils' ) # Disable Linux bridge firewalling so that traffic can flow! for table in 'arp', 'ip', 'ip6': cmd = 'sysctl net.bridge.bridge-nf-call-%stables' % table out = quietRun( cmd ).strip() if out.endswith( '1' ): warn( 'Warning: Linux bridge may not work with', out, '\n' )
def validatePort( switch, intf ): "Validate intf's OF port number" ofport = int( switch.cmd( 'ovs-vsctl get Interface', intf, 'ofport' ) ) if ofport != switch.ports[ intf ]: warn( 'WARNING: ofport for', intf, 'is actually', ofport, '\n' ) return 0 else: return 1
def isListening( self, ip, port ): "Check if a remote controller is listening at a specific ip and port" listening = self.cmd( "echo A | telnet -e A %s %d" % ( ip, port ) ) if 'Connected' not in listening: warn( "Unable to contact the remote controller" " at %s:%d\n" % ( ip, port ) ) return False else: return True
def _run_pox_switch( self ): "Run the POX switch" if self.pox_pid is not None: warn( "Killing old pox switch to restart new one." ) self._kill_pox_switch() self._build_cmd_args() self.cmd( self.command, printPid=True ) self.pox_pid = self.lastPid self.started_switch = True
def setup(cls): "Check dependencies and warn about firewalling" pathCheck("brctl", moduleName="bridge-utils") # Disable Linux bridge firewalling so that traffic can flow! for table in "arp", "ip", "ip6": cmd = "sysctl net.bridge.bridge-nf-call-%stables" % table out = quietRun(cmd).strip() if out.endswith("1"): warn("Warning: Linux bridge may not work with", out, "\n")
def terminateOutput(hosts, queueType): warn('*** Output files:\n') for h in range(hosts): warn('\tresults/h{host_id}-{queueType}.csv\n'.format( host_id=h + 1, queueType=queueType)) os.system( './src/terminator.sh {host_id} {queue_type} > /dev/null 2>&1'. format(host_id=h + 1, queue_type=queueType)) os.remove('results/h{host_id}.out'.format(host_id=h + 1))
def do_set_p4conf(self, line=""): """Updates configuration file location, and reloads it.""" args = line.split() conf = args[0] if not os.path.exists(conf): warn('Configuratuion file %s does not exist' % conf) return self.conf_file = conf self.config = load_conf(conf)
def terminate(self): if self.proxy and self.proxy.process: try: pid = self.proxy.process.pid info('Terminating proxy process with pid {}.\n'.format(pid)) self.proxy.process.terminate() except Exception as e: warn('Could not kill proxy process: \n' '{}\n'.format(e)) super().terminate()
def start(self, *args, **kwargs): if not self._is_active: self.startcmd(self, *args, **kwargs) self._is_active = True # do not call Controller start method else: warn( newline('<! Cannot start the already active controller', self.name, '!>'))
def customized(name, *args, **params): "Customized constructor, useful for Node, Link, and other classes" params = params.copy() params.update(kwargs) if not newargs: return constructor(name, *args, **params) if args: warn("warning: %s replacing %s with %s\n" % (constructor, args, newargs)) return constructor(name, *newargs, **params)
def terminate(self): """ Stop docker container """ if not self._is_container_running(): return try: self.dcli.remove_container(self.dc, force=True, v=True) except docker.errors.APIError as e: warn("Warning: API error during container removal.\n") self.cleanup()
def defaultIntf( self ): "Call ip route to determine default interface" result = quietRun( 'ip route | grep default', shell=True ).strip() match = search( r'dev\s+([^\s]+)', result ) if match: intf = match.group( 1 ) else: warn( "Can't find default network interface - using eth0\n" ) intf = 'eth0' return intf
def stop(self, *args, **kwargs): if self._is_active: self.stopcmd(self, *args, **kwargs) self._is_active = False # bypass Controller stop method Node.stop(self) else: warn( newline('<! Cannot stop the inactive controller', self.name, '!>'))
def setup_controller_connection( self ): "Start the connection to the controller." # Change self.controller_socket from None to the actual socket. try: ip = self.controller_ip port = self.controller_port sock = socket.create_connection((ip, port)) self.controller_socket = sock except Exception,e: warn("\nCannot connect to controller: %s\n" % str(e))
def getGatewayIntf(self, fallback="eth0"): """Return gateway interface name fallback: default device to fall back to""" routes = self.cmd("ip route show") match = re.search(r"default via \S+ dev (\S+)", routes) if match: return match.group(1) else: warn("There is no default route set.", "Using", fallback, "as gateway interface...\n") return fallback
def customized(name, *args, **params): "Customized constructor, useful for Node, Link, and other classes" params = params.copy() params.update(kwargs) if not newargs: return constructor(name, *args, **params) if args: warn('warning: %s replacing %s with %s\n' % (constructor, args, newargs)) return constructor(name, *newargs, **params)
def sanityAlert( self, *args ): "Alert to raise on sanityCheck failure" info( '\n' ) if self.alertAction == 'exception': raise Exception( *args ) if self.alertAction == 'warn': warn( *args + ( '\n', ) ) elif self.alertAction == 'exit': error( '***', *args + ( '\nExiting. Run "sudo mn -c" to clean up.\n', ) ) exit( 1 )
def getGatewayIntf( self, fallback='eth0' ): """Return gateway interface name fallback: default device to fall back to""" routes = self.cmd( 'ip route show' ) match = re.search( r'default via \S+ dev (\S+)', routes ) if match: return match.group( 1 ) else: warn( 'There is no default route set.', 'Using', fallback, 'as gateway interface...\n' ) return fallback
def findDir(directory, userName): "finds and returns the path of any directory in the user's home directory" homeDir = "/home/" + userName Dir = quietRun("find %s -maxdepth 1 -name %s -type d" % (homeDir, directory)).strip("\n") DirList = Dir.split("\n") if not Dir: return None elif len(DirList) > 1: warn("***WARNING: Found multiple instances of %s; using %s\n" % (directory, DirList[0])) return DirList[0] else: return Dir