def __init__(self, name, netcfg=True, **kwargs): OVSSwitch.__init__(self, name, **kwargs) self.netcfg = netcfg in (True, '1', 'true', 'True') self.netcfgfile = '/tmp/ovs-%s-netcfg.json' % self.name self.onosDeviceId = 'of:%s' % self.dpid self.longitude = kwargs['longitude'] if 'longitude' in kwargs else None self.latitude = kwargs['latitude'] if 'latitude' in kwargs else None
def addIntf(self, intf, rename=False, **kwargs): "Add (and reparent) an interface" print 'add interface **', intf OVSSwitch.addIntf(self, intf, **kwargs) intf.node = self if rename: self.renameIntf(intf)
def start(self, *args, **kwargs): OVSSwitch.start(self, *args, **kwargs) OVSSwitchSTP.prio += 1 self.cmd('ovs-vsctl set-fail-mode', self, 'standalone') self.cmd('ovs-vsctl set-controller', self) self.cmd('ovs-vsctl set Bridge', self, 'stp_enable=true', 'other_config:stp-priority=%d' % OVSSwitchSTP.prio)
def start( self, *args, **kwargs ): OVSSwitch.start( self, *args, **kwargs ) OVSBridgeSTP.prio += 1 self.cmd( 'ovs-vsctl set-fail-mode', self, 'standalone' ) self.cmd( 'ovs-vsctl set Bridge', self, 'stp_enable=true', 'other_config:stp-priority=%d' % OVSBridgeSTP.prio )
def __init__(self, name, sw_path = None, json_path = None, thrift_port = None, pcap_dump = False, log_console = False, verbose = False, device_id = None, enable_debugger = False, **kwargs): OVSSwitch.__init__(self, name, **kwargs) assert(sw_path) assert(json_path) # make sure that the provided sw_path is valid pathCheck(sw_path) # make sure that the provided JSON file exists if not os.path.isfile(json_path): error("Invalid JSON file.\n") exit(1) self.sw_path = sw_path self.json_path = json_path self.verbose = verbose logfile = "/tmp/p4s.{}.log".format(self.name) self.output = open(logfile, 'w') self.thrift_port = thrift_port self.pcap_dump = pcap_dump self.enable_debugger = enable_debugger self.log_console = log_console if device_id is not None: self.device_id = device_id P4Switch.device_id = max(P4Switch.device_id, device_id) else: self.device_id = P4Switch.device_id P4Switch.device_id += 1 self.nanomsg = "ipc:///tmp/bm-{}-log.ipc".format(self.device_id)
def start(self, controllers): "Start up a new P4 switch" OVSSwitch.start(self, controllers) info("Starting P4 switch {}.\n".format(self.name)) args = [self.sw_path] for port, intf in self.intfs.items(): if not intf.IP(): args.extend(['-i', str(port) + "@" + intf.name]) if self.pcap_dump: args.append("--pcap") # args.append("--useFiles") if self.thrift_port: args.extend(['--thrift-port', str(self.thrift_port)]) if self.nanomsg: args.extend(['--nanolog', self.nanomsg]) args.extend(['--device-id', str(self.device_id)]) P4Switch.device_id += 1 args.append(self.json_path) if self.enable_debugger: args.append("--debugger") if self.log_console: args.append("--log-console") logfile = "/tmp/p4s.{}.log".format(self.name) info(' '.join(args) + "\n") pid = None with tempfile.NamedTemporaryFile() as f: # self.cmd(' '.join(args) + ' > /dev/null 2>&1 &') self.cmd(' '.join(args) + ' >' + logfile + ' 2>&1 & echo $! >> ' + f.name) pid = int(f.read()) debug("P4 switch {} PID is {}.\n".format(self.name, pid)) if not self.check_switch_started(pid): error("P4 switch {} did not start correctly.\n".format(self.name)) exit(1) info("P4 switch {} has been started.\n".format(self.name))
def emptyNet(): net = Mininet(topo=None, build=False) c0 = Controller('c0', inNamespace=False) h1 = Host('h1') h2 = Host('h2') #intf1 = Intf("h1-eth1") #intf2 = Intf("h2-eth1") s1 = OVSSwitch('br0', inNamespace=False) Link(h1, s1) Link(h2, s1) c0.start() s1.start([c0]) net.start() #s1.cmd('ovs-vsctl set bridge br0 protocols=OpenFlow13') CLI(net) net.stop() h1.stop() h2.stop() s1.stop() c0.stop()
def stop(self): "Terminate P4 switch." OVSSwitch.stop(self) self.output.flush() self.cmd('kill %' + self.sw_path) self.cmd('wait') self.deleteIntfs()
def batchShutdown(cls, switches, **_kwargs): key = attrgetter('server') for server, switchGroup in groupby(sorted(switches, key=key), key): info('(%s)' % server) group = tuple(switchGroup) switch = group[0] OVSSwitch.batchShutdown(group, run=switch.rcmd) return switches
def start(self, controllers): # Call superclass constructor OVSSwitch.start(self, controllers) # Set OpenFlow VersionsHost self.configureOpenFlowVersion() # Set Switch IP address if self.switchIP is not None: self.cmd('ifconfig', self, self.switchIP)
def batchStartup(cls, switches, **_kwargs): "Start up switches in per-server batches" key = attrgetter('server') for server, switchGroup in groupby(sorted(switches, key=key), key): info('(%s)' % server) group = tuple(switchGroup) switch = group[0] OVSSwitch.batchStartup(group, run=switch.cmd) return switches
def batchShutdown( cls, switches, **_kwargs ): "Stop switches in per-server batches" key = attrgetter( 'server' ) for server, switchGroup in groupby( sorted( switches, key=key ), key ): info( '(%s)' % server ) group = tuple( switchGroup ) switch = group[ 0 ] OVSSwitch.batchShutdown( group, run=switch.rcmd ) return switches
def start( self, controllers ): # make sure controllers contains only a ControllerCluster assert len( controllers ) == 1 ccluster = controllers[ 0 ] assert type( ccluster ) == ControllerCluster controller_list = ccluster.clist( self.name ) # TODO: manage order of controllers to control mastership OVSSwitch.start( self, controllers=controller_list )
def batchStartup(cls, switches, **_kwargs): """ :return: started up switches """ key = attrgetter('serverIp') for server, switchBatch in groupby(sorted(switches, key=key), key): info('(%s)' % server) batch = tuple(switchBatch) OVSSwitch.batchStartup(batch, run=batch[0].cmd) return switches
def batchShutdown(cls, switches, **_kwargs): """ :return: stopped switches (in per-server batches) """ key = attrgetter('serverIp') for server, switchBatch in groupby(sorted(switches, key=key), key): info('(%s)' % server) batch = tuple(switchBatch) OVSSwitch.batchShutdown(batch, run=batch[0].rcmd) return switches
def run(): OVSSwitch.setup() setLogLevel('debug') net = Mininet(topo=KeepForwardingSmartDownlinkTestTopo(), switch=OVSSwitch, controller=RemoteController) net.start() CLI(net) net.stop()
def run(): OVSSwitch.setup() setLogLevel('debug') net = Mininet( topo=FailoverTestTopo(), switch=OVSSwitch, controller=RemoteController) net.start() CLI(net) net.stop()
def attach(self, intf): "Connect a data port" #self.cmd( 'ovs-vsctl add-port', self, intf) self.cmd('ovs-vsctl add-port', self, intf, '-- set interface', intf, 'ofport_request=%d' % self.ports[intf]) self.cmd('ifconfig', intf, 'up') OVSSwitch.TCReapply(intf)
def start_seed_topo(net): for cont in net.topo.controllers: cont.checkListening() info('*** Starting %s switches\n' % len(net.switches)) for idx, sw in enumerate(net.switches): type = net.topo.switches_idx[sw.name][1].get("type") if type == "ofSwitch": clist = [ net.topo.controllers_idx[net.topo.node_idx[c]] for c in net.topo.switches_idx[sw.name][1].get("controller").split(" ") ] debug("Starting OFSwitch " + sw.name + " with controller list " + str(clist)) sw.start(clist) elif type == "genericSwitch": debug("Starting genericSwitch " + sw.name) sw.start([]) else: AssertionError( "A switch was not started due to an unsupported type") started = {} success = OVSSwitch.batchStartup(net.switches) started.update({s: s for s in success}) if net.waitConn: net.waitConnected()
def batchStartup( cls, switches ): result = [] for ovsdb, switchGroup in groupby( switches, attrgetter( 'ovsdb') ): switchGroup = list( switchGroup ) info( '(%s)' % ovsdb ) result += OVSSwitch.batchStartup( switchGroup, run=ovsdb.cmd ) return result
def create(self, func, prefix, numberOfDevices, routed): devices = list() for i in range(0, numberOfDevices): if (routed == True): devices.append (func(prefix + str(i + 1), ip='10.0.0.' + str(i + 1))) else: name = prefix + str(i + 1) switch = OVSSwitch(name, failMode='standalone', stp=True) devices.append(func(prefix + str(i + 1))) return devices
def start(self, controllers): """ Starts the switch, then notifies ONOS about the new device via Netcfg. """ OVSSwitch.start(self, controllers) if not self.netcfg: # Do not push config to ONOS. return controllerIP = self.controllerIp(controllers) basicCfg = {"name": self.name, "driver": "ofdpa-ovs"} if self.longitude and self.latitude: basicCfg["longitude"] = self.longitude basicCfg["latitude"] = self.latitude cfgData = {"devices": {self.onosDeviceId: {"basic": basicCfg}}} 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() user = os.environ[ 'ONOS_WEB_USER'] if 'ONOS_WEB_USER' in os.environ else 'onos' password = os.environ[ 'ONOS_WEB_PASS'] if 'ONOS_WEB_PASS' in os.environ else 'rocks' pm.add_password(None, url, user, password) urllib2.install_opener( urllib2.build_opener(urllib2.HTTPBasicAuthHandler(pm))) try: # Push config data to controller req = urllib2.Request(url, json.dumps(cfgData), {'Content-Type': 'application/json'}) 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 __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 kernel mode (kernel|user) inband: use in-band control (False) protocols: use specific OpenFlow version(s) (e.g. OpenFlow13) Unspecified (or old OVS version) uses OVS default reconnectms: max reconnect timeout in ms (0/None for default) stp: enable STP (False, requires failMode=standalone) batch: enable batch startup (False)""" OVSSwitch.__init__(self, name, **params)
def batchShutdown( cls, switches ): result = [] for ovsdb, switchGroup in groupby( switches, attrgetter( 'ovsdb') ): switchGroup = list( switchGroup ) info( '(%s)' % ovsdb ) for switch in switches: if switch.pid == ovsdb.pid: switch.pid = None switch.shell = None result += OVSSwitch.batchShutdown( switchGroup, run=ovsdb.cmd ) for switch in switchGroup: switch.ovsdbFree() return result
class testNumberedports(unittest.TestCase): @unittest.skipIf(OVSSwitch.setup() or OVSSwitch.isOldOVS(), "old version of OVS") def testConsistency(self): """verify consistency between mininet and ovs ports""" p = pexpect.spawn('python -m mininet.examples.numberedports') opts = [ 'Validating that s1-eth\d is actually on port \d ... Validated.', 'Validating that s1-eth\d is actually on port \d ... WARNING', pexpect.EOF ] correct_ports = True count = 0 while True: index = p.expect(opts) if index == 0: count += 1 elif index == 1: correct_ports = False elif index == 2: self.assertNotEqual(0, count) break self.assertTrue(correct_ports) def testNumbering(self): """verify that all of the port numbers are printed correctly and consistent with their interface""" p = pexpect.spawn('python -m mininet.examples.numberedports') opts = ['s1-eth(\d+) : (\d+)', pexpect.EOF] count_intfs = 0 while True: index = p.expect(opts) if index == 0: count_intfs += 1 intfport = p.match.group(1) ofport = p.match.group(2) self.assertEqual(intfport, ofport) elif index == 1: break self.assertNotEqual(0, count_intfs)
def stop( self ): for intf in self.intfList(): if type( intf ) is TCIntf: self.dropOVSqos( intf ) OVSSwitch.stop( self )
#!/usr/bin/python from mininet.node import Host, OVSSwitch, Controller from mininet.link import Link h1 = Host('h1') h2 = Host('h2') h3 = Host('h3') h4 = Host('h4') s1 = OVSSwitch('s1', inNamespace=False) s2 = OVSSwitch('s2', inNamespace=False) c0 = Controller('c0', inNamespace=False) Link(h1, s1) Link(h2, s1) Link(h3, s2) Link(h4, s2) Link(s1, s2) h1.setIP('10.0.0.1/24') h2.setIP('10.0.0.2/24') h3.setIP('10.0.0.3/24') h4.setIP('10.0.0.4/24') c0.start() s1.start([c0]) s2.start([c0]) print h1.IP print h2.IP print h3.IP print h4.IP print 'Pinging ...' print h1.cmd('ping -c3 ', h2.IP()) print h1.cmd('ping -c3 ', h3.IP())
def __init__( self, name, *args, **params ): params['protocols'] = 'OpenFlow13' OVSSwitch.__init__( self, name, *args, **params )
def start(self, controllers): return OVSSwitch.start(self, controllers)
def __init__(self, name, **params): OVSSwitch.__init__(self, name, failMode='standalone', **params) self.switchIP = None
def topology(): total_switches = 1 total_clients = 1 total_servers = 3 switches = [] clients = [] servers = [] servers_running = [] net = Mininet_wifi( controller=lambda name: RemoteController( name, ip='10.0.2.15', port=6633), switch=lambda name, **kwargs: OVSSwitch( name, protocols="OpenFlow13", **kwargs), waitConnected=True ) # net = Mininet_wifi() c0 = net.addController( 'c0', controller=RemoteController, ip='127.0.0.1', port=6633) # s0, s1 #switch IP start at 10.0.2.0 / switch MAC start at 00:00:00:00:00:20 / switch DPID start at 1 for i in range(total_switches): print("Creating switch s" + str(i)) thisip = '10.0.2.' thisip += str(i+1) thisip += '/8' thismac = '00:00:00:00:00:2' thismac += str(i+1) thisdpid = '000000000000000' # START FROM 1 HEXADECIMAL thisdpid += str(i+1) switches.append(net.addSwitch( 's' + str(i), ip=thisip, mac=thismac, dpid=thisdpid)) # h0, h1 h2 #hostsudo ps IP start at 10.0.0.0 / hosts MAC start at 00:00:00:00:00:00 for i in range(1, 1 + total_clients): print("Creating client h" + str(i)) thisip = '10.0.0.' thisip += str(i) thisip += '/8' thismac = '00:00:00:00:00:0' thismac += str(i) clients.append(net.addHost('h' + str(i), ip=thisip, mac=thismac)) # s0 ... s5 #stations IP start at 10.0.1.0 / stations MAC start at 00:00:00:00:01:00 for i in range(1 + total_clients, 1 + total_clients + total_servers): print("Creating server h" + str(i)) thisip = '10.0.1.' thisip += str(i) thisip += '/8' thismac = '00:00:00:00:00:1' thismac += str(i) servers.append(net.addHost('h' + str(i), ip=thisip, mac=thismac)) # info("*** Configuring wifi nodes\n") net.configureWifiNodes() for c in clients: net.addLink(c, switches[0]) for srv in servers: net.addLink(srv, switches[0]) # turn server online for i in range(0, total_servers): initServer(servers[i], i+2) startServer(servers[i], i+2) servers_running.append(True) info("*** Starting network\n") net.build() c0.start() for s in switches: s.start([c0]) # menu: # 1. start server 2 (10.0.1.2) # 2. start server 3 (10.0.1.3) # 3. start server 4 (10.0.1.4) # 4. stop server 2 (10.0.1.2) # 5. stop server 3 (10.0.1.3) # 6. stop server 4 (10.0.1.4) # 7. curl to server 2 (10.0.1.2) # 8. curl to server 3 (10.0.1.3) # 9. curl to server 4 (10.0.1.4) # 10. curl cluster (10.0.1.5) while True: print("+-----------------------------------+") print("| menu: |") if not servers_running[0]: print("| 1. start server 2 (10.0.1.2) |") if not servers_running[1]: print("| 2. start server 3 (10.0.1.3) |") if not servers_running[2]: print("| 3. start server 4 (10.0.1.4) |") if servers_running[0]: print("| 4. stop server 2 (10.0.1.2) |") if servers_running[1]: print("| 5. stop server 3 (10.0.1.3) |") if servers_running[2]: print("| 6. stop server 4 (10.0.1.4) |") print("| 7. curl to server 2 (10.0.1.2) |") print("| 8. curl to server 3 (10.0.1.3) |") print("| 9. curl to server 4 (10.0.1.4) |") print("| 10. curl cluster (10.0.1.1) |") print("+-----------------------------------+") line = raw_input("INPUT ('c' for CLI):") tokens = line.split(" ") x = tokens[0] if x == 'e' or x == "exit": break if x == 'c': CLI(net) if x == "1": print("1) start server 2 (10.0.1.2)\n") startServer(servers[0], 2) servers_running[0] = True if x == "2": print("2) start server 3 (10.0.1.3)\n") startServer(servers[1], 3) servers_running[1] = True if x == "3": print("3) start server 4 (10.0.1.4)\n") startServer(servers[2], 4) servers_running[2] = True if x == "4": print("4) stop server 2 (10.0.1.2)\n") stopServer(servers[0], 2) servers_running[0] = False if x == "5": print("5) stop server 3 (10.0.1.3)\n") stopServer(servers[1], 3) servers_running[1] = False if x == "6": print("6) stop server 4 (10.0.1.4)\n") stopServer(servers[2], 4) servers_running[2] = False if x == "7": print("7) curl to server 2 (10.0.1.2)\n") curlServer(clients[0], servers[0]) if x == "8": print("8) curl to server 3 (10.0.1.3)\n") curlServer(clients[0], servers[1]) if x == "9": print("9) curl to server 4 (10.0.1.4) \n") curlServer(clients[0], servers[2]) if x == "10" or x == "0": print("10) curl cluster (10.0.1.1) \n") curlCluster(clients[0]) net.stop()
def start(self, controllers): my_num = int(self.name[1:]) - 1 return OVSSwitch.start(self, [controllers[my_num % len(controllers)]])
def __init__(self, name, vtep, **params): self.vtep = vtep OVSSwitch.__init__(self, name, **params)
def start( self, controllers ): print "starting ", self.name return OVSSwitch.start( self, [ cmap[ self.name ] ] )
def start(self, controllers): self.init_map(controllers[1:]) return OVSSwitch.start(self, [self.map[self.name]])
#!/usr/bin/python from mininet.topo import Topo from mininet.node import Host, OVSSwitch, Controller from mininet.link import Link h1 = Host('h1') h2 = Host('h2') s1 = OVSSwitch('s1', inNamespace=False) c0 = Controller('c0', inNamespace=False) Link(h1,s1) Link(h2,s1) h1.setIP('10.1/8') h2.setIP('10.2/8') c0.start() s1.start([c0]) print h1.cmd('ping -c1', h2.IP()) s1.stop() c0.stop()
def __init__(self, name, **params): params['protocols'] = 'OpenFlow13,OpenFlow10' OVSSwitch.__init__(self, name, **params)
def detach( self, intf ): if type( intf ) is TCIntf: self.dropOVSqos( intf ) OVSSwitch.detach( self, intf )
def start(self, controllers): return OVSSwitch.start(self, [])
def start( self, controllers ): assert len( controllers ) == 1 c0 = controllers[ 0 ] assert type( c0 ) == ONOSCluster controllers = c0.clist() OVSSwitch.start( self, controllers )
def __init__(self, name, **params): OVSSwitch.__init__(self, name=name, datapath='user', **params)
def __init__(self, name, **params): OVSSwitch.__init__(self, name=name, datapath="kernel", **params)
def __init__( self, *args, **kwargs ): kwargs.update( datapath='user' ) OVSSwitch.__init__( self, *args, **kwargs )
def start(self, controllers): print(self.name) return OVSSwitch.start(self, [_controllers[_translation[self.name]]])
def __init__(self, name, reliability=1.0, **params): OVSSwitch.__init__(self, name, failMode='secure', datapath='kernel', inband=False, protocols=None, **params) self.reliability = reliability self._online = True self.cmd("sysctl -w net.ipv6.conf.all.disable_ipv6=1") self.cmd("sysctl -w net.ipv6.conf.default.disable_ipv6=1")
def start(self, controllers): if self.custom_ctrl is not None: return OVSSwitch.start(self, [self.custom_ctrl]) else: return OVSSwitch.start(self, controllers)
def addIntf( self, intf, rename=False, **kwargs ): "Add (and reparent) an interface" OVSSwitch.addIntf( self, intf, **kwargs ) intf.node = self if rename: self.renameIntf( intf )
def start( self, controllers ): return OVSSwitch.start( self, [ cmap[ self.name ] ] )
def start(self, controllers): print "%s : %s" % (self.name, str(cmap.get(self.name, []))) return OVSSwitch.start(self, cmap.get(self.name, []))
def start(self, controllers): return OVSSwitch.start(self,[{'c0': c0}])
def __init__(self, name, **params): OVSSwitch.__init__(self, name, failMode='standalone', **params)
def start(self, controllers): return OVSSwitch.start(self, [cmap[self.name]])
def start(self, controllers): # This switch should always have no controllers OVSSwitch.start(self, [])