code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def connected( self ): "Is the switch connected to a controller?" status = self.dpctl( 'status' ) return ( 'remote.is-connected=true' in status and 'local.is-connected=true' in status )
Is the switch connected to a controller?
connected
python
mininet/mininet
mininet/node.py
https://github.com/mininet/mininet/blob/master/mininet/node.py
BSD-3-Clause
def TCReapply( intf ): """Unfortunately user switch and Mininet are fighting over tc queuing disciplines. To resolve the conflict, we re-create the user switch's configuration, but as a leaf of the TCIntf-created configuration.""" if isinstance( intf, TCIntf ): ...
Unfortunately user switch and Mininet are fighting over tc queuing disciplines. To resolve the conflict, we re-create the user switch's configuration, but as a leaf of the TCIntf-created configuration.
TCReapply
python
mininet/mininet
mininet/node.py
https://github.com/mininet/mininet/blob/master/mininet/node.py
BSD-3-Clause
def start( self, controllers ): """Start OpenFlow reference user datapath. Log to /tmp/sN-{ofd,ofp}.log. controllers: list of controller objects""" # Add controllers clist = ','.join( [ 'tcp:%s:%d' % ( c.IP(), c.port ) for c in controllers ] ) ...
Start OpenFlow reference user datapath. Log to /tmp/sN-{ofd,ofp}.log. controllers: list of controller objects
start
python
mininet/mininet
mininet/node.py
https://github.com/mininet/mininet/blob/master/mininet/node.py
BSD-3-Clause
def stop( self, deleteIntfs=True ): """Stop OpenFlow reference user datapath. deleteIntfs: delete interfaces? (True)""" self.cmd( 'kill %ofdatapath' ) self.cmd( 'kill %ofprotocol' ) super( UserSwitch, self ).stop( deleteIntfs )
Stop OpenFlow reference user datapath. deleteIntfs: delete interfaces? (True)
stop
python
mininet/mininet
mininet/node.py
https://github.com/mininet/mininet/blob/master/mininet/node.py
BSD-3-Clause
def __init__( self, name, failMode='secure', datapath='kernel', inband=False, protocols=None, reconnectms=1000, stp=False, batch=False, **params ): """name: name for switch failMode: controller loss behavior (secure|standalone) datapath: userspace or ker...
name: name for switch failMode: controller loss behavior (secure|standalone) datapath: userspace or kernel mode (kernel|user) inband: use in-band control (False) protocols: use specific OpenFlow version(s) (e.g. OpenFlow13) Unspecified (or old OVS versio...
__init__
python
mininet/mininet
mininet/node.py
https://github.com/mininet/mininet/blob/master/mininet/node.py
BSD-3-Clause
def setup( cls ): "Make sure Open vSwitch is installed and working" pathCheck( 'ovs-vsctl', moduleName='Open vSwitch (openvswitch.org)') # This should no longer be needed, and it breaks # with OVS 1.7 which has renamed the kernel module: # moduleDeps( subtract...
Make sure Open vSwitch is installed and working
setup
python
mininet/mininet
mininet/node.py
https://github.com/mininet/mininet/blob/master/mininet/node.py
BSD-3-Clause
def vsctl( self, *args, **kwargs ): "Run ovs-vsctl command (or queue for later execution)" if self.batch: cmd = ' '.join( str( arg ).strip() for arg in args ) self.commands.append( cmd ) return None else: return self.cmd( 'ovs-vsctl', *args, **kwar...
Run ovs-vsctl command (or queue for later execution)
vsctl
python
mininet/mininet
mininet/node.py
https://github.com/mininet/mininet/blob/master/mininet/node.py
BSD-3-Clause
def TCReapply( intf ): """Unfortunately OVS and Mininet are fighting over tc queuing disciplines. As a quick hack/ workaround, we clear OVS's and reapply our own.""" if isinstance( intf, TCIntf ): intf.config( **intf.params )
Unfortunately OVS and Mininet are fighting over tc queuing disciplines. As a quick hack/ workaround, we clear OVS's and reapply our own.
TCReapply
python
mininet/mininet
mininet/node.py
https://github.com/mininet/mininet/blob/master/mininet/node.py
BSD-3-Clause
def controllerUUIDs( self, update=False ): """Return ovsdb UUIDs for our controllers update: update cached value""" if not self._uuids or update: controllers = self.cmd( 'ovs-vsctl -- get Bridge', self, 'Controller' ).strip() if cont...
Return ovsdb UUIDs for our controllers update: update cached value
controllerUUIDs
python
mininet/mininet
mininet/node.py
https://github.com/mininet/mininet/blob/master/mininet/node.py
BSD-3-Clause
def connected( self ): "Are we connected to at least one of our controllers?" for uuid in self.controllerUUIDs(): if 'true' in self.vsctl( '-- get Controller', uuid, 'is_connected' ): return True return self.failMode == 'standalone...
Are we connected to at least one of our controllers?
connected
python
mininet/mininet
mininet/node.py
https://github.com/mininet/mininet/blob/master/mininet/node.py
BSD-3-Clause
def intfOpts( self, intf ): "Return OVS interface options for intf" opts = '' if not self.isOldOVS(): # ofport_request is not supported on old OVS opts += ' ofport_request=%s' % self.ports[ intf ] # Patch ports don't work well with old OVS if isins...
Return OVS interface options for intf
intfOpts
python
mininet/mininet
mininet/node.py
https://github.com/mininet/mininet/blob/master/mininet/node.py
BSD-3-Clause
def start( self, controllers ): "Start up a new OVS OpenFlow switch using ovs-vsctl" if self.inNamespace: raise Exception( 'OVS kernel switch does not work in a namespace' ) int( self.dpid, 16 ) # DPID must be a hex string # Command to add interfaces ...
Start up a new OVS OpenFlow switch using ovs-vsctl
start
python
mininet/mininet
mininet/node.py
https://github.com/mininet/mininet/blob/master/mininet/node.py
BSD-3-Clause
def batchStartup( cls, switches, run=errRun ): """Batch startup for OVS switches: switches to start up run: function to run commands (errRun)""" info( '...' ) cmds = 'ovs-vsctl' for switch in switches: if switch.isOldOVS(): # Ideally we'd...
Batch startup for OVS switches: switches to start up run: function to run commands (errRun)
batchStartup
python
mininet/mininet
mininet/node.py
https://github.com/mininet/mininet/blob/master/mininet/node.py
BSD-3-Clause
def stop( self, deleteIntfs=True ): """Terminate OVS switch. deleteIntfs: delete interfaces? (True)""" self.cmd( 'ovs-vsctl del-br', self ) if self.datapath == 'user': self.cmd( 'ip link del', self ) super( OVSSwitch, self ).stop( deleteIntfs )
Terminate OVS switch. deleteIntfs: delete interfaces? (True)
stop
python
mininet/mininet
mininet/node.py
https://github.com/mininet/mininet/blob/master/mininet/node.py
BSD-3-Clause
def batchShutdown( cls, switches, run=errRun ): "Shut down a list of OVS switches" delcmd = 'del-br %s' if switches and not switches[ 0 ].isOldOVS(): delcmd = '--if-exists ' + delcmd # First, delete them all from ovsdb run( 'ovs-vsctl ' + ' -- '.join( del...
Shut down a list of OVS switches
batchShutdown
python
mininet/mininet
mininet/node.py
https://github.com/mininet/mininet/blob/master/mininet/node.py
BSD-3-Clause
def __init__( self, *args, **kwargs ): """stp: enable Spanning Tree Protocol (False) see OVSSwitch for other options""" kwargs.update( failMode='standalone' ) OVSSwitch.__init__( self, *args, **kwargs )
stp: enable Spanning Tree Protocol (False) see OVSSwitch for other options
__init__
python
mininet/mininet
mininet/node.py
https://github.com/mininet/mininet/blob/master/mininet/node.py
BSD-3-Clause
def batchShutdown( cls, switches ): "Kill each IVS switch, to be waited on later in stop()" for switch in switches: switch.cmd( 'kill %ivs' ) return switches
Kill each IVS switch, to be waited on later in stop()
batchShutdown
python
mininet/mininet
mininet/node.py
https://github.com/mininet/mininet/blob/master/mininet/node.py
BSD-3-Clause
def stop( self, deleteIntfs=True ): """Terminate IVS switch. deleteIntfs: delete interfaces? (True)""" self.cmd( 'kill %ivs' ) self.cmd( 'wait' ) super( IVSSwitch, self ).stop( deleteIntfs )
Terminate IVS switch. deleteIntfs: delete interfaces? (True)
stop
python
mininet/mininet
mininet/node.py
https://github.com/mininet/mininet/blob/master/mininet/node.py
BSD-3-Clause
def checkListening( self ): "Make sure no controllers are running on our port" # Verify that Telnet is installed first: out, _err, returnCode = errRun( "which telnet" ) if 'telnet' not in out or returnCode != 0: raise Exception( "Error running telnet to check for listening " ...
Make sure no controllers are running on our port
checkListening
python
mininet/mininet
mininet/node.py
https://github.com/mininet/mininet/blob/master/mininet/node.py
BSD-3-Clause
def start( self ): """Start <controller> <args> on controller. Log to /tmp/cN.log""" pathCheck( self.command ) cout = '/tmp/' + self.name + '.log' if self.cdir is not None: self.cmd( 'cd ' + self.cdir ) self.cmd( self.command + ' ' + self.cargs % self.port ...
Start <controller> <args> on controller. Log to /tmp/cN.log
start
python
mininet/mininet
mininet/node.py
https://github.com/mininet/mininet/blob/master/mininet/node.py
BSD-3-Clause
def IP( self, intf=None ): "Return IP address of the Controller" if self.intfs: ip = Node.IP( self, intf ) else: ip = self.ip return ip
Return IP address of the Controller
IP
python
mininet/mininet
mininet/node.py
https://github.com/mininet/mininet/blob/master/mininet/node.py
BSD-3-Clause
def __init__( self, name, *noxArgs, **kwargs ): """Init. name: name to give controller noxArgs: arguments (strings) to pass to NOX""" if not noxArgs: warn( 'warning: no NOX modules specified; ' 'running packetdump only\n' ) noxArgs = [ 'pac...
Init. name: name to give controller noxArgs: arguments (strings) to pass to NOX
__init__
python
mininet/mininet
mininet/node.py
https://github.com/mininet/mininet/blob/master/mininet/node.py
BSD-3-Clause
def __init__( self, name, ryuArgs='ryu.app.simple_switch', command='ryu run', **kwargs ): """Init. name: name to give controller. ryuArgs: modules to pass to Ryu (ryu.app.simple_switch) command: command to run Ryu ('ryu run')""" if isinstance( ryuArgs, ...
Init. name: name to give controller. ryuArgs: modules to pass to Ryu (ryu.app.simple_switch) command: command to run Ryu ('ryu run')
__init__
python
mininet/mininet
mininet/node.py
https://github.com/mininet/mininet/blob/master/mininet/node.py
BSD-3-Clause
def __init__( self, name, ip='127.0.0.1', port=None, **kwargs): """Init. name: name to give controller ip: the IP address where the remote controller is listening port: the port where the remote controller is listening""" Controller.__init__(...
Init. name: name to give controller ip: the IP address where the remote controller is listening port: the port where the remote controller is listening
__init__
python
mininet/mininet
mininet/node.py
https://github.com/mininet/mininet/blob/master/mininet/node.py
BSD-3-Clause
def checkListening( self ): "Warn if remote controller is not accessible" if self.port is not None: self.isListening( self.ip, self.port ) else: for port in 6653, 6633: if self.isListening( self.ip, port ): self.port = port ...
Warn if remote controller is not accessible
checkListening
python
mininet/mininet
mininet/node.py
https://github.com/mininet/mininet/blob/master/mininet/node.py
BSD-3-Clause
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...
Check if a remote controller is listening at a specific ip and port
isListening
python
mininet/mininet
mininet/node.py
https://github.com/mininet/mininet/blob/master/mininet/node.py
BSD-3-Clause
def findController( controllers=DefaultControllers ): "Return first available controller from list, if any" for controller in controllers: if controller.isAvailable(): return controller return None
Return first available controller from list, if any
findController
python
mininet/mininet
mininet/node.py
https://github.com/mininet/mininet/blob/master/mininet/node.py
BSD-3-Clause
def DefaultController( name, controllers=DefaultControllers, **kwargs ): "Find a controller that is available and instantiate it" controller = findController( controllers ) if not controller: raise Exception( 'Could not find a default OpenFlow controller' ) return controller( name, **kwargs )
Find a controller that is available and instantiate it
DefaultController
python
mininet/mininet
mininet/node.py
https://github.com/mininet/mininet/blob/master/mininet/node.py
BSD-3-Clause
def __init__( self, name, stp=False, prio=None, **kwargs ): """stp: use spanning tree protocol? (default False) prio: optional explicit bridge priority for STP""" self.stp = stp if prio: self.prio = prio else: self.prio = LinuxBridge.nextPrio ...
stp: use spanning tree protocol? (default False) prio: optional explicit bridge priority for STP
__init__
python
mininet/mininet
mininet/nodelib.py
https://github.com/mininet/mininet/blob/master/mininet/nodelib.py
BSD-3-Clause
def stop( self, deleteIntfs=True ): """Stop Linux bridge deleteIntfs: delete interfaces? (True)""" self.cmd( 'ifconfig', self, 'down' ) self.cmd( 'brctl delbr', self ) super( LinuxBridge, self ).stop( deleteIntfs )
Stop Linux bridge deleteIntfs: delete interfaces? (True)
stop
python
mininet/mininet
mininet/nodelib.py
https://github.com/mininet/mininet/blob/master/mininet/nodelib.py
BSD-3-Clause
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 ...
Check dependencies and warn about firewalling
setup
python
mininet/mininet
mininet/nodelib.py
https://github.com/mininet/mininet/blob/master/mininet/nodelib.py
BSD-3-Clause
def __init__( self, name, subnet='10.0/8', localIntf=None, flush=False, **params): """Start NAT/forwarding between Mininet and external network subnet: Mininet subnet (default 10.0/8) flush: flush iptables before installing NAT rules""" super( NAT, self ).__init__...
Start NAT/forwarding between Mininet and external network subnet: Mininet subnet (default 10.0/8) flush: flush iptables before installing NAT rules
__init__
python
mininet/mininet
mininet/nodelib.py
https://github.com/mininet/mininet/blob/master/mininet/nodelib.py
BSD-3-Clause
def setManualConfig( self, intf ): """Prevent network-manager/networkd from messing with our interface by specifying manual configuration in /etc/network/interfaces""" cfile = '/etc/network/interfaces' line = '\niface %s inet manual\n' % intf try: with open( cfile ...
Prevent network-manager/networkd from messing with our interface by specifying manual configuration in /etc/network/interfaces
setManualConfig
python
mininet/mininet
mininet/nodelib.py
https://github.com/mininet/mininet/blob/master/mininet/nodelib.py
BSD-3-Clause
def terminate( self ): "Stop NAT/forwarding between Mininet and external network" # Remote NAT rules self.cmd( 'iptables -D FORWARD', '-i', self.localIntf, '-d', self.subnet, '-j DROP' ) self.cmd( 'iptables -D FORWARD', '-i', self.localIntf, '-s', sel...
Stop NAT/forwarding between Mininet and external network
terminate
python
mininet/mininet
mininet/nodelib.py
https://github.com/mininet/mininet/blob/master/mininet/nodelib.py
BSD-3-Clause
def tunnelX11( node, display=None): """Create an X11 tunnel from node:6000 to the root host display: display on root host (optional) returns: node $DISPLAY, Popen object for tunnel""" if display is None and 'DISPLAY' in environ: display = environ[ 'DISPLAY' ] if display is None: ...
Create an X11 tunnel from node:6000 to the root host display: display on root host (optional) returns: node $DISPLAY, Popen object for tunnel
tunnelX11
python
mininet/mininet
mininet/term.py
https://github.com/mininet/mininet/blob/master/mininet/term.py
BSD-3-Clause
def makeTerm( node, title='Node', term='xterm', display=None, cmd='bash'): """Create an X11 tunnel to the node and start up a terminal. node: Node object title: base title term: 'xterm' or 'gterm' returns: two Popen objects, tunnel and terminal""" title = '"%s: %s"' % ( title, node.n...
Create an X11 tunnel to the node and start up a terminal. node: Node object title: base title term: 'xterm' or 'gterm' returns: two Popen objects, tunnel and terminal
makeTerm
python
mininet/mininet
mininet/term.py
https://github.com/mininet/mininet/blob/master/mininet/term.py
BSD-3-Clause
def makeTerms( nodes, title='Node', term='xterm' ): """Create terminals. nodes: list of Node objects title: base title for each returns: list of created tunnel/terminal processes""" terms = [] for node in nodes: terms += makeTerm( node, title, term ) return terms
Create terminals. nodes: list of Node objects title: base title for each returns: list of created tunnel/terminal processes
makeTerms
python
mininet/mininet
mininet/term.py
https://github.com/mininet/mininet/blob/master/mininet/term.py
BSD-3-Clause
def add_node( self, node, attr_dict=None, **attrs): """Add node to graph attr_dict: attribute dict (optional) attrs: more attributes (optional) warning: updates attr_dict with attrs""" attr_dict = {} if attr_dict is None else attr_dict attr_dict.update( attrs ) ...
Add node to graph attr_dict: attribute dict (optional) attrs: more attributes (optional) warning: updates attr_dict with attrs
add_node
python
mininet/mininet
mininet/topo.py
https://github.com/mininet/mininet/blob/master/mininet/topo.py
BSD-3-Clause
def add_edge( self, src, dst, key=None, attr_dict=None, **attrs ): """Add edge to graph key: optional key attr_dict: optional attribute dict attrs: more attributes warning: updates attr_dict with attrs""" attr_dict = {} if attr_dict is None else attr_dict ...
Add edge to graph key: optional key attr_dict: optional attribute dict attrs: more attributes warning: updates attr_dict with attrs
add_edge
python
mininet/mininet
mininet/topo.py
https://github.com/mininet/mininet/blob/master/mininet/topo.py
BSD-3-Clause
def edges_iter( self, data=False, keys=False ): "Iterator: return graph edges, optionally with data and keys" for src, entry in self.edge.items(): for dst, entrykeys in entry.items(): if src > dst: # Skip duplicate edges continue ...
Iterator: return graph edges, optionally with data and keys
edges_iter
python
mininet/mininet
mininet/topo.py
https://github.com/mininet/mininet/blob/master/mininet/topo.py
BSD-3-Clause
def __getitem__( self, node ): "Return link dict for given src node" return self.edge[ node ]
Return link dict for given src node
__getitem__
python
mininet/mininet
mininet/topo.py
https://github.com/mininet/mininet/blob/master/mininet/topo.py
BSD-3-Clause
def convertTo( self, cls, data=False, keys=False ): """Convert to a new object of networkx.MultiGraph-like class cls data: include node and edge data keys: include edge keys as well as edge data""" g = cls() g.add_nodes_from( self.nodes( data=data ) ) g.add_edges_fr...
Convert to a new object of networkx.MultiGraph-like class cls data: include node and edge data keys: include edge keys as well as edge data
convertTo
python
mininet/mininet
mininet/topo.py
https://github.com/mininet/mininet/blob/master/mininet/topo.py
BSD-3-Clause
def __init__( self, *args, **params ): """Topo object. Optional named parameters: hinfo: default host options sopts: default switch options lopts: default link options calls build()""" self.g = MultiGraph() self.hopts = params.pop( 'hopts', ...
Topo object. Optional named parameters: hinfo: default host options sopts: default switch options lopts: default link options calls build()
__init__
python
mininet/mininet
mininet/topo.py
https://github.com/mininet/mininet/blob/master/mininet/topo.py
BSD-3-Clause
def addHost( self, name, **opts ): """Convenience method: Add host to graph. name: host name opts: host options returns: host name""" if not opts and self.hopts: opts = self.hopts return self.addNode( name, **opts )
Convenience method: Add host to graph. name: host name opts: host options returns: host name
addHost
python
mininet/mininet
mininet/topo.py
https://github.com/mininet/mininet/blob/master/mininet/topo.py
BSD-3-Clause
def addSwitch( self, name, **opts ): """Convenience method: Add switch to graph. name: switch name opts: switch options returns: switch name""" if not opts and self.sopts: opts = self.sopts result = self.addNode( name, isSwitch=True, **opts ) ...
Convenience method: Add switch to graph. name: switch name opts: switch options returns: switch name
addSwitch
python
mininet/mininet
mininet/topo.py
https://github.com/mininet/mininet/blob/master/mininet/topo.py
BSD-3-Clause
def addLink( self, node1, node2, port1=None, port2=None, key=None, **opts ): """node1, node2: nodes to link together port1, port2: ports (optional) opts: link options (optional) returns: link info key""" if not opts and self.lopts: opts = sel...
node1, node2: nodes to link together port1, port2: ports (optional) opts: link options (optional) returns: link info key
addLink
python
mininet/mininet
mininet/topo.py
https://github.com/mininet/mininet/blob/master/mininet/topo.py
BSD-3-Clause
def isSwitch( self, n ): "Returns true if node is a switch." return self.g.node[ n ].get( 'isSwitch', False )
Returns true if node is a switch.
isSwitch
python
mininet/mininet
mininet/topo.py
https://github.com/mininet/mininet/blob/master/mininet/topo.py
BSD-3-Clause
def iterLinks( self, withKeys=False, withInfo=False ): """Return links (iterator) withKeys: return link keys withInfo: return link info returns: list of ( src, dst [,key, info ] )""" for _src, _dst, key, info in self.g.edges_iter( data=True, keys=True ): node...
Return links (iterator) withKeys: return link keys withInfo: return link info returns: list of ( src, dst [,key, info ] )
iterLinks
python
mininet/mininet
mininet/topo.py
https://github.com/mininet/mininet/blob/master/mininet/topo.py
BSD-3-Clause
def links( self, sort=False, withKeys=False, withInfo=False ): """Return links sort: sort links alphabetically, preserving (src, dst) order withKeys: return link keys withInfo: return link info returns: list of ( src, dst [,key, info ] )""" links = list( self....
Return links sort: sort links alphabetically, preserving (src, dst) order withKeys: return link keys withInfo: return link info returns: list of ( src, dst [,key, info ] )
links
python
mininet/mininet
mininet/topo.py
https://github.com/mininet/mininet/blob/master/mininet/topo.py
BSD-3-Clause
def addPort( self, src, dst, sport=None, dport=None ): """Generate port mapping for new edge. src: source switch name dst: destination switch name""" # Initialize if necessary ports = self.ports ports.setdefault( src, {} ) ports.setdefault( dst, {} ) ...
Generate port mapping for new edge. src: source switch name dst: destination switch name
addPort
python
mininet/mininet
mininet/topo.py
https://github.com/mininet/mininet/blob/master/mininet/topo.py
BSD-3-Clause
def port( self, src, dst ): """Get port numbers. src: source switch name dst: destination switch name sport: optional source port (otherwise use lowest src port) returns: tuple (sport, dport), where sport = port on source switch leading to the dest...
Get port numbers. src: source switch name dst: destination switch name sport: optional source port (otherwise use lowest src port) returns: tuple (sport, dport), where sport = port on source switch leading to the destination switch dport = ...
port
python
mininet/mininet
mininet/topo.py
https://github.com/mininet/mininet/blob/master/mininet/topo.py
BSD-3-Clause
def _linkEntry( self, src, dst, key=None ): "Helper function: return link entry and key" entry = self.g[ src ][ dst ] if key is None: key = min( entry ) return entry, key
Helper function: return link entry and key
_linkEntry
python
mininet/mininet
mininet/topo.py
https://github.com/mininet/mininet/blob/master/mininet/topo.py
BSD-3-Clause
def sorted( items ): "Items sorted in natural (i.e. alphabetical) order" return sorted( items, key=natural )
Items sorted in natural (i.e. alphabetical) order
sorted
python
mininet/mininet
mininet/topo.py
https://github.com/mininet/mininet/blob/master/mininet/topo.py
BSD-3-Clause
def build( self, k=2, n=1, **_opts): """k: number of switches n: number of hosts per switch""" self.k = k self.n = n if n == 1: def genHostName( i, _j ): return 'h%s' % i else: def genHostName( i, j ): return 'h%...
k: number of switches n: number of hosts per switch
build
python
mininet/mininet
mininet/topo.py
https://github.com/mininet/mininet/blob/master/mininet/topo.py
BSD-3-Clause
def addTree( self, depth, fanout ): """Add a subtree starting with node n. returns: last node added""" isSwitch = depth > 0 if isSwitch: node = self.addSwitch( 's%s' % self.switchNum ) self.switchNum += 1 for _ in range( fanout ): ch...
Add a subtree starting with node n. returns: last node added
addTree
python
mininet/mininet
mininet/topolib.py
https://github.com/mininet/mininet/blob/master/mininet/topolib.py
BSD-3-Clause
def build( self, x, y, n=1 ): """x: dimension of torus in x-direction y: dimension of torus in y-direction n: number of hosts per switch""" if x < 3 or y < 3: raise Exception( 'Please use 3x3 or greater for compatibility ' 'with 2.1' ) ...
x: dimension of torus in x-direction y: dimension of torus in y-direction n: number of hosts per switch
build
python
mininet/mininet
mininet/topolib.py
https://github.com/mininet/mininet/blob/master/mininet/topolib.py
BSD-3-Clause
def spawn( *args, **kwargs): "pexpect.spawn that is compatible with str" if Python3 and 'encoding' not in kwargs: kwargs.update( encoding='utf-8' ) return oldpexpect.spawn( *args, **kwargs )
pexpect.spawn that is compatible with str
spawn
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def oldQuietRun( *cmd ): """Run a command, routing stderr to stdout, and return the output. cmd: list of command params""" if len( cmd ) == 1: cmd = cmd[ 0 ] if isinstance( cmd, BaseString ): cmd = cmd.split( ' ' ) out = '' popen = Popen( # pylint: disable=consider-us...
Run a command, routing stderr to stdout, and return the output. cmd: list of command params
oldQuietRun
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def errRun( *cmd, **kwargs ): """Run a command and return stdout, stderr and return code cmd: string or list of command and args stderr: STDOUT to merge stderr with stdout shell: run command using shell echo: monitor output to console""" # By default we separate stderr, don't run in ...
Run a command and return stdout, stderr and return code cmd: string or list of command and args stderr: STDOUT to merge stderr with stdout shell: run command using shell echo: monitor output to console
errRun
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def errFail( *cmd, **kwargs ): "Run a command using errRun and raise exception on nonzero exit" out, err, ret = errRun( *cmd, **kwargs ) if ret: raise Exception( "errFail: %s failed with return code %s: %s" % ( cmd, ret, err ) ) return CmdResult( out, err, ret )
Run a command using errRun and raise exception on nonzero exit
errFail
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def quietRun( cmd, **kwargs ): "Run a command and return merged stdout and stderr" return errRun( cmd, stderr=STDOUT, **kwargs ).out
Run a command and return merged stdout and stderr
quietRun
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def isShellBuiltin( cmd ): "Return True if cmd is a bash builtin." if isShellBuiltin.builtIns is None: isShellBuiltin.builtIns = set(quietRun( 'bash -c enable' ).split()) space = cmd.find( ' ' ) if space > 0: cmd = cmd[ :space] return cmd in isShellBuiltin.builtIns
Return True if cmd is a bash builtin.
isShellBuiltin
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def makeIntfPair( intf1, intf2, addr1=None, addr2=None, node1=None, node2=None, deleteIntfs=True, runCmd=None ): """Make a veth pair connnecting new interfaces intf1 and intf2 intf1: name for interface 1 intf2: name for interface 2 addr1: MAC address for interface 1 (optional)...
Make a veth pair connnecting new interfaces intf1 and intf2 intf1: name for interface 1 intf2: name for interface 2 addr1: MAC address for interface 1 (optional) addr2: MAC address for interface 2 (optional) node1: home node for interface 1 (optional) node2: home node for inter...
makeIntfPair
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def retry( retries, delaySecs, fn, *args, **keywords ): """Try something several times before giving up. n: number of times to retry delaySecs: wait this long between tries fn: function to call args: args to apply to function call""" tries = 0 while not fn( *args, **keywords ) an...
Try something several times before giving up. n: number of times to retry delaySecs: wait this long between tries fn: function to call args: args to apply to function call
retry
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def moveIntfNoRetry( intf, dstNode, printError=False ): """Move interface to node, without retrying. intf: string, interface dstNode: destination Node printError: if true, print error""" intf = str( intf ) cmd = 'ip link set %s netns %s' % ( intf, dstNode.pid ) cmdOutput = quietRu...
Move interface to node, without retrying. intf: string, interface dstNode: destination Node printError: if true, print error
moveIntfNoRetry
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def moveIntf( intf, dstNode, printError=True, retries=3, delaySecs=0.001 ): """Move interface to node, retrying on failure. intf: string, interface dstNode: destination Node printError: if true, print error""" retry( retries, delaySecs, moveIntfNoRetry, intf, dstNode, ...
Move interface to node, retrying on failure. intf: string, interface dstNode: destination Node printError: if true, print error
moveIntf
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def dumpConnections( node ): "Helper function: dump connections to node" for intf in node.intfList(): output( ' %s:' % intf ) if intf.link: intfs = [ intf.link.intf1, intf.link.intf2 ] intfs.remove( intf ) output( intfs[ 0 ] ) ...
Helper function: dump connections to node
dumpConnections
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def dumpPorts( switches ): "dump interface to openflow port mappings for each switch" for switch in switches: output( '%s ' % switch.name ) for intf in switch.intfList(): port = switch.ports[ intf ] output( '%s:%d ' % ( intf, port ) ) output( '\n' )
dump interface to openflow port mappings for each switch
dumpPorts
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def _colonHex( val, bytecount ): """Generate colon-hex string. val: input as unsigned int bytecount: number of bytes to convert returns: chStr colon-hex string""" pieces = [] for i in range( bytecount - 1, -1, -1 ): piece = ( ( 0xff << ( i * 8 ) ) & val ) >> ( i * 8 ) pi...
Generate colon-hex string. val: input as unsigned int bytecount: number of bytes to convert returns: chStr colon-hex string
_colonHex
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def ipStr( ip ): """Generate IP address string from an unsigned int. ip: unsigned int of form w << 24 | x << 16 | y << 8 | z returns: ip address string w.x.y.z""" w = ( ip >> 24 ) & 0xff x = ( ip >> 16 ) & 0xff y = ( ip >> 8 ) & 0xff z = ip & 0xff return "%i.%i.%i.%i" % ( w, x, y, ...
Generate IP address string from an unsigned int. ip: unsigned int of form w << 24 | x << 16 | y << 8 | z returns: ip address string w.x.y.z
ipStr
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def ipAdd( i, prefixLen=8, ipBaseNum=0x0a000000 ): """Return IP address string from ints i: int to be added to ipbase prefixLen: optional IP prefix length ipBaseNum: option base IP address as int returns IP address as string""" imax = 0xffffffff >> prefixLen assert i <= imax, 'No...
Return IP address string from ints i: int to be added to ipbase prefixLen: optional IP prefix length ipBaseNum: option base IP address as int returns IP address as string
ipAdd
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def ipParse( ip ): "Parse an IP address and return an unsigned int." args = [ int( arg ) for arg in ip.split( '.' ) ] while len(args) < 4: args.insert( len(args) - 1, 0 ) return ipNum( *args )
Parse an IP address and return an unsigned int.
ipParse
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def netParse( ipstr ): """Parse an IP network specification, returning address and prefix len as unsigned ints""" prefixLen = 0 if '/' in ipstr: ip, pf = ipstr.split( '/' ) prefixLen = int( pf ) # if no prefix is specified, set the prefix to 24 else: ip = ipstr ...
Parse an IP network specification, returning address and prefix len as unsigned ints
netParse
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def checkInt( s ): "Check if input string is an int" try: int( s ) return True except ValueError: return False
Check if input string is an int
checkInt
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def checkFloat( s ): "Check if input string is a float" try: float( s ) return True except ValueError: return False
Check if input string is a float
checkFloat
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def makeNumeric( s ): "Convert string to int or float if numeric." if checkInt( s ): return int( s ) elif checkFloat( s ): return float( s ) else: return s
Convert string to int or float if numeric.
makeNumeric
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def pmonitor(popens, timeoutms=500, readline=True, readmax=1024 ): """Monitor dict of hosts to popen objects a line at a time timeoutms: timeout for poll() readline: return single line of output yields: host, line/output (if any) terminates: when all EOFs received""" ...
Monitor dict of hosts to popen objects a line at a time timeoutms: timeout for poll() readline: return single line of output yields: host, line/output (if any) terminates: when all EOFs received
pmonitor
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def mountCgroups( cgcontrol='cpu cpuacct cpuset' ): """Mount cgroupfs if needed and return cgroup version cgcontrol: cgroup controllers to check ('cpu cpuacct cpuset') Returns: 'cgroup' | 'cgroup2' """ # Try to read the cgroup controllers in cgcontrol cglist = cgcontrol.split() paths = ' '...
Mount cgroupfs if needed and return cgroup version cgcontrol: cgroup controllers to check ('cpu cpuacct cpuset') Returns: 'cgroup' | 'cgroup2'
mountCgroups
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def natural( text ): "To sort sanely/alphabetically: sorted( l, key=natural )" def num( s ): "Convert text segment to int if necessary" return int( s ) if s.isdigit() else s return [ num( s ) for s in re.split( r'(\d+)', str( text ) ) ]
To sort sanely/alphabetically: sorted( l, key=natural )
natural
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def num( s ): "Convert text segment to int if necessary" return int( s ) if s.isdigit() else s
Convert text segment to int if necessary
num
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def naturalSeq( t ): "Natural sort key function for sequences" return [ natural( x ) for x in t ]
Natural sort key function for sequences
naturalSeq
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def numCores(): "Returns number of CPU cores based on /proc/cpuinfo" if hasattr( numCores, 'ncores' ): return numCores.ncores try: numCores.ncores = int( quietRun('grep -c processor /proc/cpuinfo') ) except ValueError: return 0 return numCores.ncores
Returns number of CPU cores based on /proc/cpuinfo
numCores
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def custom( cls, **params ): "Returns customized constructor for class cls." # Note: we may wish to see if we can use functools.partial() here # and in customConstructor def customized( *args, **kwargs): "Customized constructor" kwargs = kwargs.copy() kwargs.update( params ) ...
Returns customized constructor for class cls.
custom
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def splitArgs( argstr ): """Split argument string into usable python arguments argstr: argument string with format fn,arg2,kw1=arg3... returns: fn, args, kwargs""" split = argstr.split( ',' ) fn = split[ 0 ] params = split[ 1: ] # Convert int and float args; removes the need for functi...
Split argument string into usable python arguments argstr: argument string with format fn,arg2,kw1=arg3... returns: fn, args, kwargs
splitArgs
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def customClass( classes, argStr ): """Return customized class based on argStr The args and key/val pairs in argStr will be automatically applied when the generated class is later used. """ cname, args, kwargs = splitArgs( argStr ) cls = classes.get( cname, None ) if not cls: raise E...
Return customized class based on argStr The args and key/val pairs in argStr will be automatically applied when the generated class is later used.
customClass
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def specialClass( cls, prepend=None, append=None, defaults=None, override=None ): """Like functools.partial, but it returns a class prepend: arguments to prepend to argument list append: arguments to append to argument list defaults: default values for keyword arguments ...
Like functools.partial, but it returns a class prepend: arguments to prepend to argument list append: arguments to append to argument list defaults: default values for keyword arguments override: keyword arguments to override
specialClass
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def buildTopo( topos, topoStr ): """Create topology from string with format (object, arg1, arg2,...). input topos is a dict of topo names to constructors, possibly w/args. """ topo, args, kwargs = splitArgs( topoStr ) if topo not in topos: raise Exception( 'Invalid topo name %s' % topo ) ...
Create topology from string with format (object, arg1, arg2,...). input topos is a dict of topo names to constructors, possibly w/args.
buildTopo
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def ensureRoot(): """Ensure that we are running as root. Probably we should only sudo when needed as per Big Switch's patch. """ if os.getuid() != 0: error( '*** Mininet must run as root.\n' ) exit( 1 )
Ensure that we are running as root. Probably we should only sudo when needed as per Big Switch's patch.
ensureRoot
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def waitListening( client=None, server='127.0.0.1', port=80, timeout=None ): """Wait until server is listening on port. returns True if server is listening""" runCmd = ( client.cmd if client else partial( quietRun, shell=True ) ) if not runCmd( 'which telnet' ): raise Exception...
Wait until server is listening on port. returns True if server is listening
waitListening
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def unitScale( num, prefix='' ): "Return unit scale prefix and factor" scale = 'kMGTP' if prefix: pos = scale.lower().index( prefix.lower() ) return prefix, float( 10**(3*(pos+1)) ) num, prefix, factor = float( num ), '', 1 for i, c in enumerate(scale, start=1): f = 10**(3*i)...
Return unit scale prefix and factor
unitScale
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def fmtBps( bps, prefix='', fmt='%.1f %sbits/sec' ): """Return bps as iperf-style formatted rate string prefix: lock to specific prefix (k, M, G, ...) fmt: default format string for bps, prefix""" bps = float( bps ) prefix, factor = unitScale( bps, prefix ) bps /= factor return fmt % (...
Return bps as iperf-style formatted rate string prefix: lock to specific prefix (k, M, G, ...) fmt: default format string for bps, prefix
fmtBps
python
mininet/mininet
mininet/util.py
https://github.com/mininet/mininet/blob/master/mininet/util.py
BSD-3-Clause
def runTests( mn, options ): """Run tests mn: Mininet object option: list of test optinos """ # Split option into test name and parameters for option in options: # Multiple tests may be separated by '+' for now for test in option.split( '+' ): test, args, kwargs = s...
Run tests mn: Mininet object option: list of test optinos
runTests
python
mininet/mininet
mininet/__main__.py
https://github.com/mininet/mininet/blob/master/mininet/__main__.py
BSD-3-Clause
def addDictOption( opts, choicesDict, default, name, **kwargs ): """Convenience function to add choices dicts to OptionParser. opts: OptionParser instance choicesDict: dictionary of valid choices, must include default default: default choice key name: long option name kwargs: addi...
Convenience function to add choices dicts to OptionParser. opts: OptionParser instance choicesDict: dictionary of valid choices, must include default default: default choice key name: long option name kwargs: additional arguments to add_option
addDictOption
python
mininet/mininet
mininet/__main__.py
https://github.com/mininet/mininet/blob/master/mininet/__main__.py
BSD-3-Clause
def custom( self, _option, _opt_str, value, _parser ): """Parse custom file and add params. option: option e.g. --custom opt_str: option string e.g. --custom value: the value the follows the option parser: option parser instance""" files = [] if os.pat...
Parse custom file and add params. option: option e.g. --custom opt_str: option string e.g. --custom value: the value the follows the option parser: option parser instance
custom
python
mininet/mininet
mininet/__main__.py
https://github.com/mininet/mininet/blob/master/mininet/__main__.py
BSD-3-Clause
def runOptionsTopoTest( self, n, msg, hopts=None, lopts=None ): "Generic topology-with-options test runner." mn = Mininet( topo=SingleSwitchOptionsTopo( n=n, hopts=hopts, lopts=lopts ), host=CPULimitedHost, link=TCLink, ...
Generic topology-with-options test runner.
runOptionsTopoTest
python
mininet/mininet
mininet/test/test_hifi.py
https://github.com/mininet/mininet/blob/master/mininet/test/test_hifi.py
BSD-3-Clause
def assertWithinTolerance( self, measured, expected, tolerance_frac, msg ): """Check that a given value is within a tolerance of expected tolerance_frac: less-than-1.0 value; 0.8 would yield 20% tolerance. """ upperBound = ( float( expected ) + ( 1 - tolerance_frac ) * ...
Check that a given value is within a tolerance of expected tolerance_frac: less-than-1.0 value; 0.8 would yield 20% tolerance.
assertWithinTolerance
python
mininet/mininet
mininet/test/test_hifi.py
https://github.com/mininet/mininet/blob/master/mininet/test/test_hifi.py
BSD-3-Clause
def testLinkBandwidth( self ): "Verify that link bandwidths are accurate within a bound." if self.switchClass is UserSwitch: self.skipTest( 'UserSwitch has very poor performance -' ' skipping for now' ) BW = 5 # Mbps BW_TOLERANCE = 0.8 # BW fracti...
Verify that link bandwidths are accurate within a bound.
testLinkBandwidth
python
mininet/mininet
mininet/test/test_hifi.py
https://github.com/mininet/mininet/blob/master/mininet/test/test_hifi.py
BSD-3-Clause
def testLinkDelay( self ): "Verify that link delays are accurate within a bound." DELAY_MS = 15 DELAY_TOLERANCE = 0.8 # Delay fraction below which test should fail REPS = 3 lopts = { 'delay': '%sms' % DELAY_MS, 'use_htb': True } mn = Mininet( SingleSwitchOptionsTopo( n=N...
Verify that link delays are accurate within a bound.
testLinkDelay
python
mininet/mininet
mininet/test/test_hifi.py
https://github.com/mininet/mininet/blob/master/mininet/test/test_hifi.py
BSD-3-Clause
def testLinkLoss( self ): "Verify that we see packet drops with a high configured loss rate." LOSS_PERCENT = 99 REPS = 1 lopts = { 'loss': LOSS_PERCENT, 'use_htb': True } mn = Mininet( topo=SingleSwitchOptionsTopo( n=N, lopts=lopts ), host=CPULimitedHost, li...
Verify that we see packet drops with a high configured loss rate.
testLinkLoss
python
mininet/mininet
mininet/test/test_hifi.py
https://github.com/mininet/mininet/blob/master/mininet/test/test_hifi.py
BSD-3-Clause
def testSingle5( self ): "Ping test on 5-host single-switch topology" mn = Mininet( SingleSwitchTopo( k=5 ), self.switchClass, Host, Controller, waitConnected=True ) dropped = mn.run( mn.ping ) self.assertEqual( dropped, 0 )
Ping test on 5-host single-switch topology
testSingle5
python
mininet/mininet
mininet/test/test_nets.py
https://github.com/mininet/mininet/blob/master/mininet/test/test_nets.py
BSD-3-Clause