repo
stringlengths
2
152
file
stringlengths
15
239
code
stringlengths
0
58.4M
file_length
int64
0
58.4M
avg_line_length
float64
0
1.81M
max_line_length
int64
0
12.7M
extension_type
stringclasses
364 values
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/miniedit.py
#!/usr/bin/python """ MiniEdit: a simple network editor for Mininet This is a simple demonstration of how one might build a GUI application using Mininet as the network model. Bob Lantz, April 2010 Gregory Gee, July 2013 Controller icon from http://semlabs.co.uk/ OpenFlow icon from https://www.opennetworking.org/ """ # Miniedit needs some work in order to pass pylint... # pylint: disable=line-too-long,too-many-branches # pylint: disable=too-many-statements,attribute-defined-outside-init # pylint: disable=missing-docstring MINIEDIT_VERSION = '2.2.0.1' from optparse import OptionParser # from Tkinter import * from Tkinter import ( Frame, Label, LabelFrame, Entry, OptionMenu, Checkbutton, Menu, Toplevel, Button, BitmapImage, PhotoImage, Canvas, Scrollbar, Wm, TclError, StringVar, IntVar, E, W, EW, NW, Y, VERTICAL, SOLID, CENTER, RIGHT, LEFT, BOTH, TRUE, FALSE ) from ttk import Notebook from tkMessageBox import showerror from subprocess import call import tkFont import tkFileDialog import tkSimpleDialog import re import json from distutils.version import StrictVersion import os import sys from functools import partial if 'PYTHONPATH' in os.environ: sys.path = os.environ[ 'PYTHONPATH' ].split( ':' ) + sys.path # someday: from ttk import * from mininet.log import info, setLogLevel from mininet.net import Mininet, VERSION from mininet.util import netParse, ipAdd, quietRun from mininet.util import buildTopo from mininet.util import custom, customClass from mininet.term import makeTerm, cleanUpScreens from mininet.node import Controller, RemoteController, NOX, OVSController from mininet.node import CPULimitedHost, Host, Node from mininet.node import OVSSwitch, UserSwitch from mininet.link import TCLink, Intf, Link from mininet.cli import CLI from mininet.moduledeps import moduleDeps from mininet.topo import SingleSwitchTopo, LinearTopo, SingleSwitchReversedTopo from mininet.topolib import TreeTopo print 'MiniEdit running against Mininet '+VERSION MININET_VERSION = re.sub(r'[^\d\.]', '', VERSION) if StrictVersion(MININET_VERSION) > StrictVersion('2.0'): from mininet.node import IVSSwitch TOPODEF = 'none' TOPOS = { 'minimal': lambda: SingleSwitchTopo( k=2 ), 'linear': LinearTopo, 'reversed': SingleSwitchReversedTopo, 'single': SingleSwitchTopo, 'none': None, 'tree': TreeTopo } CONTROLLERDEF = 'ref' CONTROLLERS = { 'ref': Controller, 'ovsc': OVSController, 'nox': NOX, 'remote': RemoteController, 'none': lambda name: None } LINKDEF = 'default' LINKS = { 'default': Link, 'tc': TCLink } HOSTDEF = 'proc' HOSTS = { 'proc': Host, 'rt': custom( CPULimitedHost, sched='rt' ), 'cfs': custom( CPULimitedHost, sched='cfs' ) } class InbandController( RemoteController ): "RemoteController that ignores checkListening" def checkListening( self ): "Overridden to do nothing." return class CustomUserSwitch(UserSwitch): "Customized UserSwitch" def __init__( self, name, dpopts='--no-slicing', **kwargs ): UserSwitch.__init__( self, name, **kwargs ) self.switchIP = None def getSwitchIP(self): "Return management IP address" return self.switchIP def setSwitchIP(self, ip): "Set management IP address" self.switchIP = ip def start( self, controllers ): "Start and set management IP address" # Call superclass constructor UserSwitch.start( self, controllers ) # Set Switch IP address if self.switchIP is not None: if not self.inNamespace: self.cmd( 'ifconfig', self, self.switchIP ) else: self.cmd( 'ifconfig lo', self.switchIP ) class LegacyRouter( Node ): "Simple IP router" def __init__( self, name, inNamespace=True, **params ): Node.__init__( self, name, inNamespace, **params ) def config( self, **_params ): if self.intfs: self.setParam( _params, 'setIP', ip='0.0.0.0' ) r = Node.config( self, **_params ) self.cmd('sysctl -w net.ipv4.ip_forward=1') return r class LegacySwitch(OVSSwitch): "OVS switch in standalone/bridge mode" def __init__( self, name, **params ): OVSSwitch.__init__( self, name, failMode='standalone', **params ) self.switchIP = None class customOvs(OVSSwitch): "Customized OVS switch" def __init__( self, name, failMode='secure', datapath='kernel', **params ): OVSSwitch.__init__( self, name, failMode=failMode, datapath=datapath,**params ) self.switchIP = None def getSwitchIP(self): "Return management IP address" return self.switchIP def setSwitchIP(self, ip): "Set management IP address" self.switchIP = ip def start( self, controllers ): "Start and set management IP address" # Call superclass constructor OVSSwitch.start( self, controllers ) # Set Switch IP address if self.switchIP is not None: self.cmd( 'ifconfig', self, self.switchIP ) class PrefsDialog(tkSimpleDialog.Dialog): "Preferences dialog" def __init__(self, parent, title, prefDefaults): self.prefValues = prefDefaults tkSimpleDialog.Dialog.__init__(self, parent, title) def body(self, master): "Create dialog body" self.rootFrame = master self.leftfieldFrame = Frame(self.rootFrame, padx=5, pady=5) self.leftfieldFrame.grid(row=0, column=0, sticky='nswe', columnspan=2) self.rightfieldFrame = Frame(self.rootFrame, padx=5, pady=5) self.rightfieldFrame.grid(row=0, column=2, sticky='nswe', columnspan=2) # Field for Base IP Label(self.leftfieldFrame, text="IP Base:").grid(row=0, sticky=E) self.ipEntry = Entry(self.leftfieldFrame) self.ipEntry.grid(row=0, column=1) ipBase = self.prefValues['ipBase'] self.ipEntry.insert(0, ipBase) # Selection of terminal type Label(self.leftfieldFrame, text="Default Terminal:").grid(row=1, sticky=E) self.terminalVar = StringVar(self.leftfieldFrame) self.terminalOption = OptionMenu(self.leftfieldFrame, self.terminalVar, "xterm", "gterm") self.terminalOption.grid(row=1, column=1, sticky=W) terminalType = self.prefValues['terminalType'] self.terminalVar.set(terminalType) # Field for CLI Label(self.leftfieldFrame, text="Start CLI:").grid(row=2, sticky=E) self.cliStart = IntVar() self.cliButton = Checkbutton(self.leftfieldFrame, variable=self.cliStart) self.cliButton.grid(row=2, column=1, sticky=W) if self.prefValues['startCLI'] == '0': self.cliButton.deselect() else: self.cliButton.select() # Selection of switch type Label(self.leftfieldFrame, text="Default Switch:").grid(row=3, sticky=E) self.switchType = StringVar(self.leftfieldFrame) self.switchTypeMenu = OptionMenu(self.leftfieldFrame, self.switchType, "Open vSwitch Kernel Mode", "Indigo Virtual Switch", "Userspace Switch", "Userspace Switch inNamespace") self.switchTypeMenu.grid(row=3, column=1, sticky=W) switchTypePref = self.prefValues['switchType'] if switchTypePref == 'ivs': self.switchType.set("Indigo Virtual Switch") elif switchTypePref == 'userns': self.switchType.set("Userspace Switch inNamespace") elif switchTypePref == 'user': self.switchType.set("Userspace Switch") else: self.switchType.set("Open vSwitch Kernel Mode") # Fields for OVS OpenFlow version ovsFrame= LabelFrame(self.leftfieldFrame, text='Open vSwitch', padx=5, pady=5) ovsFrame.grid(row=4, column=0, columnspan=2, sticky=EW) Label(ovsFrame, text="OpenFlow 1.0:").grid(row=0, sticky=E) Label(ovsFrame, text="OpenFlow 1.1:").grid(row=1, sticky=E) Label(ovsFrame, text="OpenFlow 1.2:").grid(row=2, sticky=E) Label(ovsFrame, text="OpenFlow 1.3:").grid(row=3, sticky=E) self.ovsOf10 = IntVar() self.covsOf10 = Checkbutton(ovsFrame, variable=self.ovsOf10) self.covsOf10.grid(row=0, column=1, sticky=W) if self.prefValues['openFlowVersions']['ovsOf10'] == '0': self.covsOf10.deselect() else: self.covsOf10.select() self.ovsOf11 = IntVar() self.covsOf11 = Checkbutton(ovsFrame, variable=self.ovsOf11) self.covsOf11.grid(row=1, column=1, sticky=W) if self.prefValues['openFlowVersions']['ovsOf11'] == '0': self.covsOf11.deselect() else: self.covsOf11.select() self.ovsOf12 = IntVar() self.covsOf12 = Checkbutton(ovsFrame, variable=self.ovsOf12) self.covsOf12.grid(row=2, column=1, sticky=W) if self.prefValues['openFlowVersions']['ovsOf12'] == '0': self.covsOf12.deselect() else: self.covsOf12.select() self.ovsOf13 = IntVar() self.covsOf13 = Checkbutton(ovsFrame, variable=self.ovsOf13) self.covsOf13.grid(row=3, column=1, sticky=W) if self.prefValues['openFlowVersions']['ovsOf13'] == '0': self.covsOf13.deselect() else: self.covsOf13.select() # Field for DPCTL listen port Label(self.leftfieldFrame, text="dpctl port:").grid(row=5, sticky=E) self.dpctlEntry = Entry(self.leftfieldFrame) self.dpctlEntry.grid(row=5, column=1) if 'dpctl' in self.prefValues: self.dpctlEntry.insert(0, self.prefValues['dpctl']) # sFlow sflowValues = self.prefValues['sflow'] self.sflowFrame= LabelFrame(self.rightfieldFrame, text='sFlow Profile for Open vSwitch', padx=5, pady=5) self.sflowFrame.grid(row=0, column=0, columnspan=2, sticky=EW) Label(self.sflowFrame, text="Target:").grid(row=0, sticky=E) self.sflowTarget = Entry(self.sflowFrame) self.sflowTarget.grid(row=0, column=1) self.sflowTarget.insert(0, sflowValues['sflowTarget']) Label(self.sflowFrame, text="Sampling:").grid(row=1, sticky=E) self.sflowSampling = Entry(self.sflowFrame) self.sflowSampling.grid(row=1, column=1) self.sflowSampling.insert(0, sflowValues['sflowSampling']) Label(self.sflowFrame, text="Header:").grid(row=2, sticky=E) self.sflowHeader = Entry(self.sflowFrame) self.sflowHeader.grid(row=2, column=1) self.sflowHeader.insert(0, sflowValues['sflowHeader']) Label(self.sflowFrame, text="Polling:").grid(row=3, sticky=E) self.sflowPolling = Entry(self.sflowFrame) self.sflowPolling.grid(row=3, column=1) self.sflowPolling.insert(0, sflowValues['sflowPolling']) # NetFlow nflowValues = self.prefValues['netflow'] self.nFrame= LabelFrame(self.rightfieldFrame, text='NetFlow Profile for Open vSwitch', padx=5, pady=5) self.nFrame.grid(row=1, column=0, columnspan=2, sticky=EW) Label(self.nFrame, text="Target:").grid(row=0, sticky=E) self.nflowTarget = Entry(self.nFrame) self.nflowTarget.grid(row=0, column=1) self.nflowTarget.insert(0, nflowValues['nflowTarget']) Label(self.nFrame, text="Active Timeout:").grid(row=1, sticky=E) self.nflowTimeout = Entry(self.nFrame) self.nflowTimeout.grid(row=1, column=1) self.nflowTimeout.insert(0, nflowValues['nflowTimeout']) Label(self.nFrame, text="Add ID to Interface:").grid(row=2, sticky=E) self.nflowAddId = IntVar() self.nflowAddIdButton = Checkbutton(self.nFrame, variable=self.nflowAddId) self.nflowAddIdButton.grid(row=2, column=1, sticky=W) if nflowValues['nflowAddId'] == '0': self.nflowAddIdButton.deselect() else: self.nflowAddIdButton.select() # initial focus return self.ipEntry def apply(self): ipBase = self.ipEntry.get() terminalType = self.terminalVar.get() startCLI = str(self.cliStart.get()) sw = self.switchType.get() dpctl = self.dpctlEntry.get() ovsOf10 = str(self.ovsOf10.get()) ovsOf11 = str(self.ovsOf11.get()) ovsOf12 = str(self.ovsOf12.get()) ovsOf13 = str(self.ovsOf13.get()) sflowValues = {'sflowTarget':self.sflowTarget.get(), 'sflowSampling':self.sflowSampling.get(), 'sflowHeader':self.sflowHeader.get(), 'sflowPolling':self.sflowPolling.get()} nflowvalues = {'nflowTarget':self.nflowTarget.get(), 'nflowTimeout':self.nflowTimeout.get(), 'nflowAddId':str(self.nflowAddId.get())} self.result = {'ipBase':ipBase, 'terminalType':terminalType, 'dpctl':dpctl, 'sflow':sflowValues, 'netflow':nflowvalues, 'startCLI':startCLI} if sw == 'Indigo Virtual Switch': self.result['switchType'] = 'ivs' if StrictVersion(MININET_VERSION) < StrictVersion('2.1'): self.ovsOk = False showerror(title="Error", message='MiniNet version 2.1+ required. You have '+VERSION+'.') elif sw == 'Userspace Switch': self.result['switchType'] = 'user' elif sw == 'Userspace Switch inNamespace': self.result['switchType'] = 'userns' else: self.result['switchType'] = 'ovs' self.ovsOk = True if ovsOf11 == "1": ovsVer = self.getOvsVersion() if StrictVersion(ovsVer) < StrictVersion('2.0'): self.ovsOk = False showerror(title="Error", message='Open vSwitch version 2.0+ required. You have '+ovsVer+'.') if ovsOf12 == "1" or ovsOf13 == "1": ovsVer = self.getOvsVersion() if StrictVersion(ovsVer) < StrictVersion('1.10'): self.ovsOk = False showerror(title="Error", message='Open vSwitch version 1.10+ required. You have '+ovsVer+'.') if self.ovsOk: self.result['openFlowVersions']={'ovsOf10':ovsOf10, 'ovsOf11':ovsOf11, 'ovsOf12':ovsOf12, 'ovsOf13':ovsOf13} else: self.result = None @staticmethod def getOvsVersion(): "Return OVS version" outp = quietRun("ovs-vsctl show") r = r'ovs_version: "(.*)"' m = re.search(r, outp) if m is None: print 'Version check failed' return None else: print 'Open vSwitch version is '+m.group(1) return m.group(1) class CustomDialog(object): # TODO: Fix button placement and Title and window focus lock def __init__(self, master, _title): self.top=Toplevel(master) self.bodyFrame = Frame(self.top) self.bodyFrame.grid(row=0, column=0, sticky='nswe') self.body(self.bodyFrame) #return self.b # initial focus buttonFrame = Frame(self.top, relief='ridge', bd=3, bg='lightgrey') buttonFrame.grid(row=1 , column=0, sticky='nswe') okButton = Button(buttonFrame, width=8, text='OK', relief='groove', bd=4, command=self.okAction) okButton.grid(row=0, column=0, sticky=E) canlceButton = Button(buttonFrame, width=8, text='Cancel', relief='groove', bd=4, command=self.cancelAction) canlceButton.grid(row=0, column=1, sticky=W) def body(self, master): self.rootFrame = master def apply(self): self.top.destroy() def cancelAction(self): self.top.destroy() def okAction(self): self.apply() self.top.destroy() class HostDialog(CustomDialog): def __init__(self, master, title, prefDefaults): self.prefValues = prefDefaults self.result = None CustomDialog.__init__(self, master, title) def body(self, master): self.rootFrame = master n = Notebook(self.rootFrame) self.propFrame = Frame(n) self.vlanFrame = Frame(n) self.interfaceFrame = Frame(n) self.mountFrame = Frame(n) n.add(self.propFrame, text='Properties') n.add(self.vlanFrame, text='VLAN Interfaces') n.add(self.interfaceFrame, text='External Interfaces') n.add(self.mountFrame, text='Private Directories') n.pack() ### TAB 1 # Field for Hostname Label(self.propFrame, text="Hostname:").grid(row=0, sticky=E) self.hostnameEntry = Entry(self.propFrame) self.hostnameEntry.grid(row=0, column=1) if 'hostname' in self.prefValues: self.hostnameEntry.insert(0, self.prefValues['hostname']) # Field for Switch IP Label(self.propFrame, text="IP Address:").grid(row=1, sticky=E) self.ipEntry = Entry(self.propFrame) self.ipEntry.grid(row=1, column=1) if 'ip' in self.prefValues: self.ipEntry.insert(0, self.prefValues['ip']) # Field for default route Label(self.propFrame, text="Default Route:").grid(row=2, sticky=E) self.routeEntry = Entry(self.propFrame) self.routeEntry.grid(row=2, column=1) if 'defaultRoute' in self.prefValues: self.routeEntry.insert(0, self.prefValues['defaultRoute']) # Field for CPU Label(self.propFrame, text="Amount CPU:").grid(row=3, sticky=E) self.cpuEntry = Entry(self.propFrame) self.cpuEntry.grid(row=3, column=1) if 'cpu' in self.prefValues: self.cpuEntry.insert(0, str(self.prefValues['cpu'])) # Selection of Scheduler if 'sched' in self.prefValues: sched = self.prefValues['sched'] else: sched = 'host' self.schedVar = StringVar(self.propFrame) self.schedOption = OptionMenu(self.propFrame, self.schedVar, "host", "cfs", "rt") self.schedOption.grid(row=3, column=2, sticky=W) self.schedVar.set(sched) # Selection of Cores Label(self.propFrame, text="Cores:").grid(row=4, sticky=E) self.coreEntry = Entry(self.propFrame) self.coreEntry.grid(row=4, column=1) if 'cores' in self.prefValues: self.coreEntry.insert(1, self.prefValues['cores']) # Start command Label(self.propFrame, text="Start Command:").grid(row=5, sticky=E) self.startEntry = Entry(self.propFrame) self.startEntry.grid(row=5, column=1, sticky='nswe', columnspan=3) if 'startCommand' in self.prefValues: self.startEntry.insert(0, str(self.prefValues['startCommand'])) # Stop command Label(self.propFrame, text="Stop Command:").grid(row=6, sticky=E) self.stopEntry = Entry(self.propFrame) self.stopEntry.grid(row=6, column=1, sticky='nswe', columnspan=3) if 'stopCommand' in self.prefValues: self.stopEntry.insert(0, str(self.prefValues['stopCommand'])) ### TAB 2 # External Interfaces self.externalInterfaces = 0 Label(self.interfaceFrame, text="External Interface:").grid(row=0, column=0, sticky=E) self.b = Button( self.interfaceFrame, text='Add', command=self.addInterface) self.b.grid(row=0, column=1) self.interfaceFrame = VerticalScrolledTable(self.interfaceFrame, rows=0, columns=1, title='External Interfaces') self.interfaceFrame.grid(row=1, column=0, sticky='nswe', columnspan=2) self.tableFrame = self.interfaceFrame.interior self.tableFrame.addRow(value=['Interface Name'], readonly=True) # Add defined interfaces externalInterfaces = [] if 'externalInterfaces' in self.prefValues: externalInterfaces = self.prefValues['externalInterfaces'] for externalInterface in externalInterfaces: self.tableFrame.addRow(value=[externalInterface]) ### TAB 3 # VLAN Interfaces self.vlanInterfaces = 0 Label(self.vlanFrame, text="VLAN Interface:").grid(row=0, column=0, sticky=E) self.vlanButton = Button( self.vlanFrame, text='Add', command=self.addVlanInterface) self.vlanButton.grid(row=0, column=1) self.vlanFrame = VerticalScrolledTable(self.vlanFrame, rows=0, columns=2, title='VLAN Interfaces') self.vlanFrame.grid(row=1, column=0, sticky='nswe', columnspan=2) self.vlanTableFrame = self.vlanFrame.interior self.vlanTableFrame.addRow(value=['IP Address','VLAN ID'], readonly=True) vlanInterfaces = [] if 'vlanInterfaces' in self.prefValues: vlanInterfaces = self.prefValues['vlanInterfaces'] for vlanInterface in vlanInterfaces: self.vlanTableFrame.addRow(value=vlanInterface) ### TAB 4 # Private Directories self.privateDirectories = 0 Label(self.mountFrame, text="Private Directory:").grid(row=0, column=0, sticky=E) self.mountButton = Button( self.mountFrame, text='Add', command=self.addDirectory) self.mountButton.grid(row=0, column=1) self.mountFrame = VerticalScrolledTable(self.mountFrame, rows=0, columns=2, title='Directories') self.mountFrame.grid(row=1, column=0, sticky='nswe', columnspan=2) self.mountTableFrame = self.mountFrame.interior self.mountTableFrame.addRow(value=['Mount','Persistent Directory'], readonly=True) directoryList = [] if 'privateDirectory' in self.prefValues: directoryList = self.prefValues['privateDirectory'] for privateDir in directoryList: if isinstance( privateDir, tuple ): self.mountTableFrame.addRow(value=privateDir) else: self.mountTableFrame.addRow(value=[privateDir,'']) def addDirectory( self ): self.mountTableFrame.addRow() def addVlanInterface( self ): self.vlanTableFrame.addRow() def addInterface( self ): self.tableFrame.addRow() def apply(self): externalInterfaces = [] for row in range(self.tableFrame.rows): if (len(self.tableFrame.get(row, 0)) > 0 and row > 0): externalInterfaces.append(self.tableFrame.get(row, 0)) vlanInterfaces = [] for row in range(self.vlanTableFrame.rows): if (len(self.vlanTableFrame.get(row, 0)) > 0 and len(self.vlanTableFrame.get(row, 1)) > 0 and row > 0): vlanInterfaces.append([self.vlanTableFrame.get(row, 0), self.vlanTableFrame.get(row, 1)]) privateDirectories = [] for row in range(self.mountTableFrame.rows): if len(self.mountTableFrame.get(row, 0)) > 0 and row > 0: if len(self.mountTableFrame.get(row, 1)) > 0: privateDirectories.append((self.mountTableFrame.get(row, 0), self.mountTableFrame.get(row, 1))) else: privateDirectories.append(self.mountTableFrame.get(row, 0)) results = {'cpu': self.cpuEntry.get(), 'cores':self.coreEntry.get(), 'sched':self.schedVar.get(), 'hostname':self.hostnameEntry.get(), 'ip':self.ipEntry.get(), 'defaultRoute':self.routeEntry.get(), 'startCommand':self.startEntry.get(), 'stopCommand':self.stopEntry.get(), 'privateDirectory':privateDirectories, 'externalInterfaces':externalInterfaces, 'vlanInterfaces':vlanInterfaces} self.result = results class SwitchDialog(CustomDialog): def __init__(self, master, title, prefDefaults): self.prefValues = prefDefaults self.result = None CustomDialog.__init__(self, master, title) def body(self, master): self.rootFrame = master self.leftfieldFrame = Frame(self.rootFrame) self.rightfieldFrame = Frame(self.rootFrame) self.leftfieldFrame.grid(row=0, column=0, sticky='nswe') self.rightfieldFrame.grid(row=0, column=1, sticky='nswe') rowCount = 0 externalInterfaces = [] if 'externalInterfaces' in self.prefValues: externalInterfaces = self.prefValues['externalInterfaces'] # Field for Hostname Label(self.leftfieldFrame, text="Hostname:").grid(row=rowCount, sticky=E) self.hostnameEntry = Entry(self.leftfieldFrame) self.hostnameEntry.grid(row=rowCount, column=1) self.hostnameEntry.insert(0, self.prefValues['hostname']) rowCount+=1 # Field for DPID Label(self.leftfieldFrame, text="DPID:").grid(row=rowCount, sticky=E) self.dpidEntry = Entry(self.leftfieldFrame) self.dpidEntry.grid(row=rowCount, column=1) if 'dpid' in self.prefValues: self.dpidEntry.insert(0, self.prefValues['dpid']) rowCount+=1 # Field for Netflow Label(self.leftfieldFrame, text="Enable NetFlow:").grid(row=rowCount, sticky=E) self.nflow = IntVar() self.nflowButton = Checkbutton(self.leftfieldFrame, variable=self.nflow) self.nflowButton.grid(row=rowCount, column=1, sticky=W) if 'netflow' in self.prefValues: if self.prefValues['netflow'] == '0': self.nflowButton.deselect() else: self.nflowButton.select() else: self.nflowButton.deselect() rowCount+=1 # Field for sflow Label(self.leftfieldFrame, text="Enable sFlow:").grid(row=rowCount, sticky=E) self.sflow = IntVar() self.sflowButton = Checkbutton(self.leftfieldFrame, variable=self.sflow) self.sflowButton.grid(row=rowCount, column=1, sticky=W) if 'sflow' in self.prefValues: if self.prefValues['sflow'] == '0': self.sflowButton.deselect() else: self.sflowButton.select() else: self.sflowButton.deselect() rowCount+=1 # Selection of switch type Label(self.leftfieldFrame, text="Switch Type:").grid(row=rowCount, sticky=E) self.switchType = StringVar(self.leftfieldFrame) self.switchTypeMenu = OptionMenu(self.leftfieldFrame, self.switchType, "Default", "Open vSwitch Kernel Mode", "Indigo Virtual Switch", "Userspace Switch", "Userspace Switch inNamespace") self.switchTypeMenu.grid(row=rowCount, column=1, sticky=W) if 'switchType' in self.prefValues: switchTypePref = self.prefValues['switchType'] if switchTypePref == 'ivs': self.switchType.set("Indigo Virtual Switch") elif switchTypePref == 'userns': self.switchType.set("Userspace Switch inNamespace") elif switchTypePref == 'user': self.switchType.set("Userspace Switch") elif switchTypePref == 'ovs': self.switchType.set("Open vSwitch Kernel Mode") else: self.switchType.set("Default") else: self.switchType.set("Default") rowCount+=1 # Field for Switch IP Label(self.leftfieldFrame, text="IP Address:").grid(row=rowCount, sticky=E) self.ipEntry = Entry(self.leftfieldFrame) self.ipEntry.grid(row=rowCount, column=1) if 'switchIP' in self.prefValues: self.ipEntry.insert(0, self.prefValues['switchIP']) rowCount+=1 # Field for DPCTL port Label(self.leftfieldFrame, text="DPCTL port:").grid(row=rowCount, sticky=E) self.dpctlEntry = Entry(self.leftfieldFrame) self.dpctlEntry.grid(row=rowCount, column=1) if 'dpctl' in self.prefValues: self.dpctlEntry.insert(0, self.prefValues['dpctl']) rowCount+=1 # External Interfaces Label(self.rightfieldFrame, text="External Interface:").grid(row=0, sticky=E) self.b = Button( self.rightfieldFrame, text='Add', command=self.addInterface) self.b.grid(row=0, column=1) self.interfaceFrame = VerticalScrolledTable(self.rightfieldFrame, rows=0, columns=1, title='External Interfaces') self.interfaceFrame.grid(row=1, column=0, sticky='nswe', columnspan=2) self.tableFrame = self.interfaceFrame.interior # Add defined interfaces for externalInterface in externalInterfaces: self.tableFrame.addRow(value=[externalInterface]) self.commandFrame = Frame(self.rootFrame) self.commandFrame.grid(row=1, column=0, sticky='nswe', columnspan=2) self.commandFrame.columnconfigure(1, weight=1) # Start command Label(self.commandFrame, text="Start Command:").grid(row=0, column=0, sticky=W) self.startEntry = Entry(self.commandFrame) self.startEntry.grid(row=0, column=1, sticky='nsew') if 'startCommand' in self.prefValues: self.startEntry.insert(0, str(self.prefValues['startCommand'])) # Stop command Label(self.commandFrame, text="Stop Command:").grid(row=1, column=0, sticky=W) self.stopEntry = Entry(self.commandFrame) self.stopEntry.grid(row=1, column=1, sticky='nsew') if 'stopCommand' in self.prefValues: self.stopEntry.insert(0, str(self.prefValues['stopCommand'])) def addInterface( self ): self.tableFrame.addRow() def defaultDpid( self, name): "Derive dpid from switch name, s1 -> 1" assert self # satisfy pylint and allow contextual override try: dpid = int( re.findall( r'\d+', name )[ 0 ] ) dpid = hex( dpid )[ 2: ] return dpid except IndexError: return None #raise Exception( 'Unable to derive default datapath ID - ' # 'please either specify a dpid or use a ' # 'canonical switch name such as s23.' ) def apply(self): externalInterfaces = [] for row in range(self.tableFrame.rows): #print 'Interface is ' + self.tableFrame.get(row, 0) if len(self.tableFrame.get(row, 0)) > 0: externalInterfaces.append(self.tableFrame.get(row, 0)) dpid = self.dpidEntry.get() if (self.defaultDpid(self.hostnameEntry.get()) is None and len(dpid) == 0): showerror(title="Error", message= 'Unable to derive default datapath ID - ' 'please either specify a DPID or use a ' 'canonical switch name such as s23.' ) results = {'externalInterfaces':externalInterfaces, 'hostname':self.hostnameEntry.get(), 'dpid':dpid, 'startCommand':self.startEntry.get(), 'stopCommand':self.stopEntry.get(), 'sflow':str(self.sflow.get()), 'netflow':str(self.nflow.get()), 'dpctl':self.dpctlEntry.get(), 'switchIP':self.ipEntry.get()} sw = self.switchType.get() if sw == 'Indigo Virtual Switch': results['switchType'] = 'ivs' if StrictVersion(MININET_VERSION) < StrictVersion('2.1'): self.ovsOk = False showerror(title="Error", message='MiniNet version 2.1+ required. You have '+VERSION+'.') elif sw == 'Userspace Switch inNamespace': results['switchType'] = 'userns' elif sw == 'Userspace Switch': results['switchType'] = 'user' elif sw == 'Open vSwitch Kernel Mode': results['switchType'] = 'ovs' else: results['switchType'] = 'default' self.result = results class VerticalScrolledTable(LabelFrame): """A pure Tkinter scrollable frame that actually works! * Use the 'interior' attribute to place widgets inside the scrollable frame * Construct and pack/place/grid normally * This frame only allows vertical scrolling """ def __init__(self, parent, rows=2, columns=2, title=None, *args, **kw): LabelFrame.__init__(self, parent, text=title, padx=5, pady=5, *args, **kw) # create a canvas object and a vertical scrollbar for scrolling it vscrollbar = Scrollbar(self, orient=VERTICAL) vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE) canvas = Canvas(self, bd=0, highlightthickness=0, yscrollcommand=vscrollbar.set) canvas.pack(side=LEFT, fill=BOTH, expand=TRUE) vscrollbar.config(command=canvas.yview) # reset the view canvas.xview_moveto(0) canvas.yview_moveto(0) # create a frame inside the canvas which will be scrolled with it self.interior = interior = TableFrame(canvas, rows=rows, columns=columns) interior_id = canvas.create_window(0, 0, window=interior, anchor=NW) # track changes to the canvas and frame width and sync them, # also updating the scrollbar def _configure_interior(_event): # update the scrollbars to match the size of the inner frame size = (interior.winfo_reqwidth(), interior.winfo_reqheight()) canvas.config(scrollregion="0 0 %s %s" % size) if interior.winfo_reqwidth() != canvas.winfo_width(): # update the canvas's width to fit the inner frame canvas.config(width=interior.winfo_reqwidth()) interior.bind('<Configure>', _configure_interior) def _configure_canvas(_event): if interior.winfo_reqwidth() != canvas.winfo_width(): # update the inner frame's width to fill the canvas canvas.itemconfigure(interior_id, width=canvas.winfo_width()) canvas.bind('<Configure>', _configure_canvas) return class TableFrame(Frame): def __init__(self, parent, rows=2, columns=2): Frame.__init__(self, parent, background="black") self._widgets = [] self.rows = rows self.columns = columns for row in range(rows): current_row = [] for column in range(columns): label = Entry(self, borderwidth=0) label.grid(row=row, column=column, sticky="wens", padx=1, pady=1) current_row.append(label) self._widgets.append(current_row) def set(self, row, column, value): widget = self._widgets[row][column] widget.insert(0, value) def get(self, row, column): widget = self._widgets[row][column] return widget.get() def addRow( self, value=None, readonly=False ): #print "Adding row " + str(self.rows +1) current_row = [] for column in range(self.columns): label = Entry(self, borderwidth=0) label.grid(row=self.rows, column=column, sticky="wens", padx=1, pady=1) if value is not None: label.insert(0, value[column]) if readonly == True: label.configure(state='readonly') current_row.append(label) self._widgets.append(current_row) self.update_idletasks() self.rows += 1 class LinkDialog(tkSimpleDialog.Dialog): def __init__(self, parent, title, linkDefaults): self.linkValues = linkDefaults tkSimpleDialog.Dialog.__init__(self, parent, title) def body(self, master): self.var = StringVar(master) Label(master, text="Bandwidth:").grid(row=0, sticky=E) self.e1 = Entry(master) self.e1.grid(row=0, column=1) Label(master, text="Mbit").grid(row=0, column=2, sticky=W) if 'bw' in self.linkValues: self.e1.insert(0,str(self.linkValues['bw'])) Label(master, text="Delay:").grid(row=1, sticky=E) self.e2 = Entry(master) self.e2.grid(row=1, column=1) if 'delay' in self.linkValues: self.e2.insert(0, self.linkValues['delay']) Label(master, text="Loss:").grid(row=2, sticky=E) self.e3 = Entry(master) self.e3.grid(row=2, column=1) Label(master, text="%").grid(row=2, column=2, sticky=W) if 'loss' in self.linkValues: self.e3.insert(0, str(self.linkValues['loss'])) Label(master, text="Max Queue size:").grid(row=3, sticky=E) self.e4 = Entry(master) self.e4.grid(row=3, column=1) if 'max_queue_size' in self.linkValues: self.e4.insert(0, str(self.linkValues['max_queue_size'])) Label(master, text="Jitter:").grid(row=4, sticky=E) self.e5 = Entry(master) self.e5.grid(row=4, column=1) if 'jitter' in self.linkValues: self.e5.insert(0, self.linkValues['jitter']) Label(master, text="Speedup:").grid(row=5, sticky=E) self.e6 = Entry(master) self.e6.grid(row=5, column=1) if 'speedup' in self.linkValues: self.e6.insert(0, str(self.linkValues['speedup'])) return self.e1 # initial focus def apply(self): self.result = {} if len(self.e1.get()) > 0: self.result['bw'] = int(self.e1.get()) if len(self.e2.get()) > 0: self.result['delay'] = self.e2.get() if len(self.e3.get()) > 0: self.result['loss'] = int(self.e3.get()) if len(self.e4.get()) > 0: self.result['max_queue_size'] = int(self.e4.get()) if len(self.e5.get()) > 0: self.result['jitter'] = self.e5.get() if len(self.e6.get()) > 0: self.result['speedup'] = int(self.e6.get()) class ControllerDialog(tkSimpleDialog.Dialog): def __init__(self, parent, title, ctrlrDefaults=None): if ctrlrDefaults: self.ctrlrValues = ctrlrDefaults tkSimpleDialog.Dialog.__init__(self, parent, title) def body(self, master): self.var = StringVar(master) self.protcolvar = StringVar(master) rowCount=0 # Field for Hostname Label(master, text="Name:").grid(row=rowCount, sticky=E) self.hostnameEntry = Entry(master) self.hostnameEntry.grid(row=rowCount, column=1) self.hostnameEntry.insert(0, self.ctrlrValues['hostname']) rowCount+=1 # Field for Remove Controller Port Label(master, text="Controller Port:").grid(row=rowCount, sticky=E) self.e2 = Entry(master) self.e2.grid(row=rowCount, column=1) self.e2.insert(0, self.ctrlrValues['remotePort']) rowCount+=1 # Field for Controller Type Label(master, text="Controller Type:").grid(row=rowCount, sticky=E) controllerType = self.ctrlrValues['controllerType'] self.o1 = OptionMenu(master, self.var, "Remote Controller", "In-Band Controller", "OpenFlow Reference", "OVS Controller") self.o1.grid(row=rowCount, column=1, sticky=W) if controllerType == 'ref': self.var.set("OpenFlow Reference") elif controllerType == 'inband': self.var.set("In-Band Controller") elif controllerType == 'remote': self.var.set("Remote Controller") else: self.var.set("OVS Controller") rowCount+=1 # Field for Controller Protcol Label(master, text="Protocol:").grid(row=rowCount, sticky=E) if 'controllerProtocol' in self.ctrlrValues: controllerProtocol = self.ctrlrValues['controllerProtocol'] else: controllerProtocol = 'tcp' self.protcol = OptionMenu(master, self.protcolvar, "TCP", "SSL") self.protcol.grid(row=rowCount, column=1, sticky=W) if controllerProtocol == 'ssl': self.protcolvar.set("SSL") else: self.protcolvar.set("TCP") rowCount+=1 # Field for Remove Controller IP remoteFrame= LabelFrame(master, text='Remote/In-Band Controller', padx=5, pady=5) remoteFrame.grid(row=rowCount, column=0, columnspan=2, sticky=W) Label(remoteFrame, text="IP Address:").grid(row=0, sticky=E) self.e1 = Entry(remoteFrame) self.e1.grid(row=0, column=1) self.e1.insert(0, self.ctrlrValues['remoteIP']) rowCount+=1 return self.hostnameEntry # initial focus def apply(self): self.result = { 'hostname': self.hostnameEntry.get(), 'remoteIP': self.e1.get(), 'remotePort': int(self.e2.get())} controllerType = self.var.get() if controllerType == 'Remote Controller': self.result['controllerType'] = 'remote' elif controllerType == 'In-Band Controller': self.result['controllerType'] = 'inband' elif controllerType == 'OpenFlow Reference': self.result['controllerType'] = 'ref' else: self.result['controllerType'] = 'ovsc' controllerProtocol = self.protcolvar.get() if controllerProtocol == 'SSL': self.result['controllerProtocol'] = 'ssl' else: self.result['controllerProtocol'] = 'tcp' class ToolTip(object): def __init__(self, widget): self.widget = widget self.tipwindow = None self.id = None self.x = self.y = 0 def showtip(self, text): "Display text in tooltip window" self.text = text if self.tipwindow or not self.text: return x, y, _cx, cy = self.widget.bbox("insert") x = x + self.widget.winfo_rootx() + 27 y = y + cy + self.widget.winfo_rooty() +27 self.tipwindow = tw = Toplevel(self.widget) tw.wm_overrideredirect(1) tw.wm_geometry("+%d+%d" % (x, y)) try: # For Mac OS # pylint: disable=protected-access tw.tk.call("::tk::unsupported::MacWindowStyle", "style", tw._w, "help", "noActivates") # pylint: enable=protected-access except TclError: pass label = Label(tw, text=self.text, justify=LEFT, background="#ffffe0", relief=SOLID, borderwidth=1, font=("tahoma", "8", "normal")) label.pack(ipadx=1) def hidetip(self): tw = self.tipwindow self.tipwindow = None if tw: tw.destroy() class MiniEdit( Frame ): "A simple network editor for Mininet." def __init__( self, parent=None, cheight=600, cwidth=1000 ): self.defaultIpBase='10.0.0.0/8' self.nflowDefaults = {'nflowTarget':'', 'nflowTimeout':'600', 'nflowAddId':'0'} self.sflowDefaults = {'sflowTarget':'', 'sflowSampling':'400', 'sflowHeader':'128', 'sflowPolling':'30'} self.appPrefs={ "ipBase": self.defaultIpBase, "startCLI": "0", "terminalType": 'xterm', "switchType": 'ovs', "dpctl": '', 'sflow':self.sflowDefaults, 'netflow':self.nflowDefaults, 'openFlowVersions':{'ovsOf10':'1', 'ovsOf11':'0', 'ovsOf12':'0', 'ovsOf13':'0'} } Frame.__init__( self, parent ) self.action = None self.appName = 'MiniEdit' self.fixedFont = tkFont.Font ( family="DejaVu Sans Mono", size="14" ) # Style self.font = ( 'Geneva', 9 ) self.smallFont = ( 'Geneva', 7 ) self.bg = 'white' # Title self.top = self.winfo_toplevel() self.top.title( self.appName ) # Menu bar self.createMenubar() # Editing canvas self.cheight, self.cwidth = cheight, cwidth self.cframe, self.canvas = self.createCanvas() # Toolbar self.controllers = {} # Toolbar self.images = miniEditImages() self.buttons = {} self.active = None self.tools = ( 'Select', 'Host', 'Switch', 'LegacySwitch', 'LegacyRouter', 'NetLink', 'Controller' ) self.customColors = { 'Switch': 'darkGreen', 'Host': 'blue' } self.toolbar = self.createToolbar() # Layout self.toolbar.grid( column=0, row=0, sticky='nsew') self.cframe.grid( column=1, row=0 ) self.columnconfigure( 1, weight=1 ) self.rowconfigure( 0, weight=1 ) self.pack( expand=True, fill='both' ) # About box self.aboutBox = None # Initialize node data self.nodeBindings = self.createNodeBindings() self.nodePrefixes = { 'LegacyRouter': 'r', 'LegacySwitch': 's', 'Switch': 's', 'Host': 'h' , 'Controller': 'c'} self.widgetToItem = {} self.itemToWidget = {} # Initialize link tool self.link = self.linkWidget = None # Selection support self.selection = None # Keyboard bindings self.bind( '<Control-q>', lambda event: self.quit() ) self.bind( '<KeyPress-Delete>', self.deleteSelection ) self.bind( '<KeyPress-BackSpace>', self.deleteSelection ) self.focus() self.hostPopup = Menu(self.top, tearoff=0) self.hostPopup.add_command(label='Host Options', font=self.font) self.hostPopup.add_separator() self.hostPopup.add_command(label='Properties', font=self.font, command=self.hostDetails ) self.hostRunPopup = Menu(self.top, tearoff=0) self.hostRunPopup.add_command(label='Host Options', font=self.font) self.hostRunPopup.add_separator() self.hostRunPopup.add_command(label='Terminal', font=self.font, command=self.xterm ) self.legacyRouterRunPopup = Menu(self.top, tearoff=0) self.legacyRouterRunPopup.add_command(label='Router Options', font=self.font) self.legacyRouterRunPopup.add_separator() self.legacyRouterRunPopup.add_command(label='Terminal', font=self.font, command=self.xterm ) self.switchPopup = Menu(self.top, tearoff=0) self.switchPopup.add_command(label='Switch Options', font=self.font) self.switchPopup.add_separator() self.switchPopup.add_command(label='Properties', font=self.font, command=self.switchDetails ) self.switchRunPopup = Menu(self.top, tearoff=0) self.switchRunPopup.add_command(label='Switch Options', font=self.font) self.switchRunPopup.add_separator() self.switchRunPopup.add_command(label='List bridge details', font=self.font, command=self.listBridge ) self.linkPopup = Menu(self.top, tearoff=0) self.linkPopup.add_command(label='Link Options', font=self.font) self.linkPopup.add_separator() self.linkPopup.add_command(label='Properties', font=self.font, command=self.linkDetails ) self.linkRunPopup = Menu(self.top, tearoff=0) self.linkRunPopup.add_command(label='Link Options', font=self.font) self.linkRunPopup.add_separator() self.linkRunPopup.add_command(label='Link Up', font=self.font, command=self.linkUp ) self.linkRunPopup.add_command(label='Link Down', font=self.font, command=self.linkDown ) self.controllerPopup = Menu(self.top, tearoff=0) self.controllerPopup.add_command(label='Controller Options', font=self.font) self.controllerPopup.add_separator() self.controllerPopup.add_command(label='Properties', font=self.font, command=self.controllerDetails ) # Event handling initalization self.linkx = self.linky = self.linkItem = None self.lastSelection = None # Model initialization self.links = {} self.hostOpts = {} self.switchOpts = {} self.hostCount = 0 self.switchCount = 0 self.controllerCount = 0 self.net = None # Close window gracefully Wm.wm_protocol( self.top, name='WM_DELETE_WINDOW', func=self.quit ) def quit( self ): "Stop our network, if any, then quit." self.stop() Frame.quit( self ) def createMenubar( self ): "Create our menu bar." font = self.font mbar = Menu( self.top, font=font ) self.top.configure( menu=mbar ) fileMenu = Menu( mbar, tearoff=False ) mbar.add_cascade( label="File", font=font, menu=fileMenu ) fileMenu.add_command( label="New", font=font, command=self.newTopology ) fileMenu.add_command( label="Open", font=font, command=self.loadTopology ) fileMenu.add_command( label="Save", font=font, command=self.saveTopology ) fileMenu.add_command( label="Export Level 2 Script", font=font, command=self.exportScript ) fileMenu.add_separator() fileMenu.add_command( label='Quit', command=self.quit, font=font ) editMenu = Menu( mbar, tearoff=False ) mbar.add_cascade( label="Edit", font=font, menu=editMenu ) editMenu.add_command( label="Cut", font=font, command=lambda: self.deleteSelection( None ) ) editMenu.add_command( label="Preferences", font=font, command=self.prefDetails) runMenu = Menu( mbar, tearoff=False ) mbar.add_cascade( label="Run", font=font, menu=runMenu ) runMenu.add_command( label="Run", font=font, command=self.doRun ) runMenu.add_command( label="Stop", font=font, command=self.doStop ) fileMenu.add_separator() runMenu.add_command( label='Show OVS Summary', font=font, command=self.ovsShow ) runMenu.add_command( label='Root Terminal', font=font, command=self.rootTerminal ) # Application menu appMenu = Menu( mbar, tearoff=False ) mbar.add_cascade( label="Help", font=font, menu=appMenu ) appMenu.add_command( label='About MiniEdit', command=self.about, font=font) # Canvas def createCanvas( self ): "Create and return our scrolling canvas frame." f = Frame( self ) canvas = Canvas( f, width=self.cwidth, height=self.cheight, bg=self.bg ) # Scroll bars xbar = Scrollbar( f, orient='horizontal', command=canvas.xview ) ybar = Scrollbar( f, orient='vertical', command=canvas.yview ) canvas.configure( xscrollcommand=xbar.set, yscrollcommand=ybar.set ) # Resize box resize = Label( f, bg='white' ) # Layout canvas.grid( row=0, column=1, sticky='nsew') ybar.grid( row=0, column=2, sticky='ns') xbar.grid( row=1, column=1, sticky='ew' ) resize.grid( row=1, column=2, sticky='nsew' ) # Resize behavior f.rowconfigure( 0, weight=1 ) f.columnconfigure( 1, weight=1 ) f.grid( row=0, column=0, sticky='nsew' ) f.bind( '<Configure>', lambda event: self.updateScrollRegion() ) # Mouse bindings canvas.bind( '<ButtonPress-1>', self.clickCanvas ) canvas.bind( '<B1-Motion>', self.dragCanvas ) canvas.bind( '<ButtonRelease-1>', self.releaseCanvas ) return f, canvas def updateScrollRegion( self ): "Update canvas scroll region to hold everything." bbox = self.canvas.bbox( 'all' ) if bbox is not None: self.canvas.configure( scrollregion=( 0, 0, bbox[ 2 ], bbox[ 3 ] ) ) def canvasx( self, x_root ): "Convert root x coordinate to canvas coordinate." c = self.canvas return c.canvasx( x_root ) - c.winfo_rootx() def canvasy( self, y_root ): "Convert root y coordinate to canvas coordinate." c = self.canvas return c.canvasy( y_root ) - c.winfo_rooty() # Toolbar def activate( self, toolName ): "Activate a tool and press its button." # Adjust button appearance if self.active: self.buttons[ self.active ].configure( relief='raised' ) self.buttons[ toolName ].configure( relief='sunken' ) # Activate dynamic bindings self.active = toolName @staticmethod def createToolTip(widget, text): toolTip = ToolTip(widget) def enter(_event): toolTip.showtip(text) def leave(_event): toolTip.hidetip() widget.bind('<Enter>', enter) widget.bind('<Leave>', leave) def createToolbar( self ): "Create and return our toolbar frame." toolbar = Frame( self ) # Tools for tool in self.tools: cmd = ( lambda t=tool: self.activate( t ) ) b = Button( toolbar, text=tool, font=self.smallFont, command=cmd) if tool in self.images: b.config( height=35, image=self.images[ tool ] ) self.createToolTip(b, str(tool)) # b.config( compound='top' ) b.pack( fill='x' ) self.buttons[ tool ] = b self.activate( self.tools[ 0 ] ) # Spacer Label( toolbar, text='' ).pack() # Commands for cmd, color in [ ( 'Stop', 'darkRed' ), ( 'Run', 'darkGreen' ) ]: doCmd = getattr( self, 'do' + cmd ) b = Button( toolbar, text=cmd, font=self.smallFont, fg=color, command=doCmd ) b.pack( fill='x', side='bottom' ) return toolbar def doRun( self ): "Run command." self.activate( 'Select' ) for tool in self.tools: self.buttons[ tool ].config( state='disabled' ) self.start() def doStop( self ): "Stop command." self.stop() for tool in self.tools: self.buttons[ tool ].config( state='normal' ) def addNode( self, node, nodeNum, x, y, name=None): "Add a new node to our canvas." if 'Switch' == node: self.switchCount += 1 if 'Host' == node: self.hostCount += 1 if 'Controller' == node: self.controllerCount += 1 if name is None: name = self.nodePrefixes[ node ] + nodeNum self.addNamedNode(node, name, x, y) def addNamedNode( self, node, name, x, y): "Add a new node to our canvas." icon = self.nodeIcon( node, name ) item = self.canvas.create_window( x, y, anchor='c', window=icon, tags=node ) self.widgetToItem[ icon ] = item self.itemToWidget[ item ] = icon icon.links = {} def convertJsonUnicode(self, text): "Some part of Mininet don't like Unicode" if isinstance(text, dict): return {self.convertJsonUnicode(key): self.convertJsonUnicode(value) for key, value in text.iteritems()} elif isinstance(text, list): return [self.convertJsonUnicode(element) for element in text] elif isinstance(text, unicode): return text.encode('utf-8') else: return text def loadTopology( self ): "Load command." c = self.canvas myFormats = [ ('Mininet Topology','*.mn'), ('All Files','*'), ] f = tkFileDialog.askopenfile(filetypes=myFormats, mode='rb') if f == None: return self.newTopology() loadedTopology = self.convertJsonUnicode(json.load(f)) # Load application preferences if 'application' in loadedTopology: self.appPrefs = dict(self.appPrefs.items() + loadedTopology['application'].items()) if "ovsOf10" not in self.appPrefs["openFlowVersions"]: self.appPrefs["openFlowVersions"]["ovsOf10"] = '0' if "ovsOf11" not in self.appPrefs["openFlowVersions"]: self.appPrefs["openFlowVersions"]["ovsOf11"] = '0' if "ovsOf12" not in self.appPrefs["openFlowVersions"]: self.appPrefs["openFlowVersions"]["ovsOf12"] = '0' if "ovsOf13" not in self.appPrefs["openFlowVersions"]: self.appPrefs["openFlowVersions"]["ovsOf13"] = '0' if "sflow" not in self.appPrefs: self.appPrefs["sflow"] = self.sflowDefaults if "netflow" not in self.appPrefs: self.appPrefs["netflow"] = self.nflowDefaults # Load controllers if 'controllers' in loadedTopology: if loadedTopology['version'] == '1': # This is old location of controller info hostname = 'c0' self.controllers = {} self.controllers[hostname] = loadedTopology['controllers']['c0'] self.controllers[hostname]['hostname'] = hostname self.addNode('Controller', 0, float(30), float(30), name=hostname) icon = self.findWidgetByName(hostname) icon.bind('<Button-3>', self.do_controllerPopup ) else: controllers = loadedTopology['controllers'] for controller in controllers: hostname = controller['opts']['hostname'] x = controller['x'] y = controller['y'] self.addNode('Controller', 0, float(x), float(y), name=hostname) self.controllers[hostname] = controller['opts'] icon = self.findWidgetByName(hostname) icon.bind('<Button-3>', self.do_controllerPopup ) # Load hosts hosts = loadedTopology['hosts'] for host in hosts: nodeNum = host['number'] hostname = 'h'+nodeNum if 'hostname' in host['opts']: hostname = host['opts']['hostname'] else: host['opts']['hostname'] = hostname if 'nodeNum' not in host['opts']: host['opts']['nodeNum'] = int(nodeNum) x = host['x'] y = host['y'] self.addNode('Host', nodeNum, float(x), float(y), name=hostname) # Fix JSON converting tuple to list when saving if 'privateDirectory' in host['opts']: newDirList = [] for privateDir in host['opts']['privateDirectory']: if isinstance( privateDir, list ): newDirList.append((privateDir[0],privateDir[1])) else: newDirList.append(privateDir) host['opts']['privateDirectory'] = newDirList self.hostOpts[hostname] = host['opts'] icon = self.findWidgetByName(hostname) icon.bind('<Button-3>', self.do_hostPopup ) # Load switches switches = loadedTopology['switches'] for switch in switches: nodeNum = switch['number'] hostname = 's'+nodeNum if 'controllers' not in switch['opts']: switch['opts']['controllers'] = [] if 'switchType' not in switch['opts']: switch['opts']['switchType'] = 'default' if 'hostname' in switch['opts']: hostname = switch['opts']['hostname'] else: switch['opts']['hostname'] = hostname if 'nodeNum' not in switch['opts']: switch['opts']['nodeNum'] = int(nodeNum) x = switch['x'] y = switch['y'] if switch['opts']['switchType'] == "legacyRouter": self.addNode('LegacyRouter', nodeNum, float(x), float(y), name=hostname) icon = self.findWidgetByName(hostname) icon.bind('<Button-3>', self.do_legacyRouterPopup ) elif switch['opts']['switchType'] == "legacySwitch": self.addNode('LegacySwitch', nodeNum, float(x), float(y), name=hostname) icon = self.findWidgetByName(hostname) icon.bind('<Button-3>', self.do_legacySwitchPopup ) else: self.addNode('Switch', nodeNum, float(x), float(y), name=hostname) icon = self.findWidgetByName(hostname) icon.bind('<Button-3>', self.do_switchPopup ) self.switchOpts[hostname] = switch['opts'] # create links to controllers if int(loadedTopology['version']) > 1: controllers = self.switchOpts[hostname]['controllers'] for controller in controllers: dest = self.findWidgetByName(controller) dx, dy = self.canvas.coords( self.widgetToItem[ dest ] ) self.link = self.canvas.create_line(float(x), float(y), dx, dy, width=4, fill='red', dash=(6, 4, 2, 4), tag='link' ) c.itemconfig(self.link, tags=c.gettags(self.link)+('control',)) self.addLink( icon, dest, linktype='control' ) self.createControlLinkBindings() self.link = self.linkWidget = None else: dest = self.findWidgetByName('c0') dx, dy = self.canvas.coords( self.widgetToItem[ dest ] ) self.link = self.canvas.create_line(float(x), float(y), dx, dy, width=4, fill='red', dash=(6, 4, 2, 4), tag='link' ) c.itemconfig(self.link, tags=c.gettags(self.link)+('control',)) self.addLink( icon, dest, linktype='control' ) self.createControlLinkBindings() self.link = self.linkWidget = None # Load links links = loadedTopology['links'] for link in links: srcNode = link['src'] src = self.findWidgetByName(srcNode) sx, sy = self.canvas.coords( self.widgetToItem[ src ] ) destNode = link['dest'] dest = self.findWidgetByName(destNode) dx, dy = self.canvas.coords( self.widgetToItem[ dest] ) self.link = self.canvas.create_line( sx, sy, dx, dy, width=4, fill='blue', tag='link' ) c.itemconfig(self.link, tags=c.gettags(self.link)+('data',)) self.addLink( src, dest, linkopts=link['opts'] ) self.createDataLinkBindings() self.link = self.linkWidget = None f.close() def findWidgetByName( self, name ): for widget in self.widgetToItem: if name == widget[ 'text' ]: return widget def newTopology( self ): "New command." for widget in self.widgetToItem.keys(): self.deleteItem( self.widgetToItem[ widget ] ) self.hostCount = 0 self.switchCount = 0 self.controllerCount = 0 self.links = {} self.hostOpts = {} self.switchOpts = {} self.controllers = {} self.appPrefs["ipBase"]= self.defaultIpBase def saveTopology( self ): "Save command." myFormats = [ ('Mininet Topology','*.mn'), ('All Files','*'), ] savingDictionary = {} fileName = tkFileDialog.asksaveasfilename(filetypes=myFormats ,title="Save the topology as...") if len(fileName ) > 0: # Save Application preferences savingDictionary['version'] = '2' # Save Switches and Hosts hostsToSave = [] switchesToSave = [] controllersToSave = [] for widget in self.widgetToItem: name = widget[ 'text' ] tags = self.canvas.gettags( self.widgetToItem[ widget ] ) x1, y1 = self.canvas.coords( self.widgetToItem[ widget ] ) if 'Switch' in tags or 'LegacySwitch' in tags or 'LegacyRouter' in tags: nodeNum = self.switchOpts[name]['nodeNum'] nodeToSave = {'number':str(nodeNum), 'x':str(x1), 'y':str(y1), 'opts':self.switchOpts[name] } switchesToSave.append(nodeToSave) elif 'Host' in tags: nodeNum = self.hostOpts[name]['nodeNum'] nodeToSave = {'number':str(nodeNum), 'x':str(x1), 'y':str(y1), 'opts':self.hostOpts[name] } hostsToSave.append(nodeToSave) elif 'Controller' in tags: nodeToSave = {'x':str(x1), 'y':str(y1), 'opts':self.controllers[name] } controllersToSave.append(nodeToSave) else: raise Exception( "Cannot create mystery node: " + name ) savingDictionary['hosts'] = hostsToSave savingDictionary['switches'] = switchesToSave savingDictionary['controllers'] = controllersToSave # Save Links linksToSave = [] for link in self.links.values(): src = link['src'] dst = link['dest'] linkopts = link['linkOpts'] srcName, dstName = src[ 'text' ], dst[ 'text' ] linkToSave = {'src':srcName, 'dest':dstName, 'opts':linkopts} if link['type'] == 'data': linksToSave.append(linkToSave) savingDictionary['links'] = linksToSave # Save Application preferences savingDictionary['application'] = self.appPrefs try: f = open(fileName, 'wb') f.write(json.dumps(savingDictionary, sort_keys=True, indent=4, separators=(',', ': '))) # pylint: disable=broad-except except Exception as er: print er # pylint: enable=broad-except finally: f.close() def exportScript( self ): "Export command." myFormats = [ ('Mininet Custom Topology','*.py'), ('All Files','*'), ] fileName = tkFileDialog.asksaveasfilename(filetypes=myFormats ,title="Export the topology as...") if len(fileName ) > 0: #print "Now saving under %s" % fileName f = open(fileName, 'wb') f.write("#!/usr/bin/python\n") f.write("\n") f.write("from mininet.net import Mininet\n") f.write("from mininet.node import Controller, RemoteController, OVSController\n") f.write("from mininet.node import CPULimitedHost, Host, Node\n") f.write("from mininet.node import OVSKernelSwitch, UserSwitch\n") if StrictVersion(MININET_VERSION) > StrictVersion('2.0'): f.write("from mininet.node import IVSSwitch\n") f.write("from mininet.cli import CLI\n") f.write("from mininet.log import setLogLevel, info\n") f.write("from mininet.link import TCLink, Intf\n") f.write("from subprocess import call\n") inBandCtrl = False for widget in self.widgetToItem: name = widget[ 'text' ] tags = self.canvas.gettags( self.widgetToItem[ widget ] ) if 'Controller' in tags: opts = self.controllers[name] controllerType = opts['controllerType'] if controllerType == 'inband': inBandCtrl = True if inBandCtrl == True: f.write("\n") f.write("class InbandController( RemoteController ):\n") f.write("\n") f.write(" def checkListening( self ):\n") f.write(" \"Overridden to do nothing.\"\n") f.write(" return\n") f.write("\n") f.write("def myNetwork():\n") f.write("\n") f.write(" net = Mininet( topo=None,\n") if len(self.appPrefs['dpctl']) > 0: f.write(" listenPort="+self.appPrefs['dpctl']+",\n") f.write(" build=False,\n") f.write(" ipBase='"+self.appPrefs['ipBase']+"')\n") f.write("\n") f.write(" info( '*** Adding controller\\n' )\n") for widget in self.widgetToItem: name = widget[ 'text' ] tags = self.canvas.gettags( self.widgetToItem[ widget ] ) if 'Controller' in tags: opts = self.controllers[name] controllerType = opts['controllerType'] if 'controllerProtocol' in opts: controllerProtocol = opts['controllerProtocol'] else: controllerProtocol = 'tcp' controllerIP = opts['remoteIP'] controllerPort = opts['remotePort'] f.write(" "+name+"=net.addController(name='"+name+"',\n") if controllerType == 'remote': f.write(" controller=RemoteController,\n") f.write(" ip='"+controllerIP+"',\n") elif controllerType == 'inband': f.write(" controller=InbandController,\n") f.write(" ip='"+controllerIP+"',\n") elif controllerType == 'ovsc': f.write(" controller=OVSController,\n") else: f.write(" controller=Controller,\n") f.write(" protocol='"+controllerProtocol+"',\n") f.write(" port="+str(controllerPort)+")\n") f.write("\n") # Save Switches and Hosts f.write(" info( '*** Add switches\\n')\n") for widget in self.widgetToItem: name = widget[ 'text' ] tags = self.canvas.gettags( self.widgetToItem[ widget ] ) if 'LegacyRouter' in tags: f.write(" "+name+" = net.addHost('"+name+"', cls=Node, ip='0.0.0.0')\n") f.write(" "+name+".cmd('sysctl -w net.ipv4.ip_forward=1')\n") if 'LegacySwitch' in tags: f.write(" "+name+" = net.addSwitch('"+name+"', cls=OVSKernelSwitch, failMode='standalone')\n") if 'Switch' in tags: opts = self.switchOpts[name] nodeNum = opts['nodeNum'] f.write(" "+name+" = net.addSwitch('"+name+"'") if opts['switchType'] == 'default': if self.appPrefs['switchType'] == 'ivs': f.write(", cls=IVSSwitch") elif self.appPrefs['switchType'] == 'user': f.write(", cls=UserSwitch") elif self.appPrefs['switchType'] == 'userns': f.write(", cls=UserSwitch, inNamespace=True") else: f.write(", cls=OVSKernelSwitch") elif opts['switchType'] == 'ivs': f.write(", cls=IVSSwitch") elif opts['switchType'] == 'user': f.write(", cls=UserSwitch") elif opts['switchType'] == 'userns': f.write(", cls=UserSwitch, inNamespace=True") else: f.write(", cls=OVSKernelSwitch") if 'dpctl' in opts: f.write(", listenPort="+opts['dpctl']) if 'dpid' in opts: f.write(", dpid='"+opts['dpid']+"'") f.write(")\n") if 'externalInterfaces' in opts: for extInterface in opts['externalInterfaces']: f.write(" Intf( '"+extInterface+"', node="+name+" )\n") f.write("\n") f.write(" info( '*** Add hosts\\n')\n") for widget in self.widgetToItem: name = widget[ 'text' ] tags = self.canvas.gettags( self.widgetToItem[ widget ] ) if 'Host' in tags: opts = self.hostOpts[name] ip = None defaultRoute = None if 'defaultRoute' in opts and len(opts['defaultRoute']) > 0: defaultRoute = "'via "+opts['defaultRoute']+"'" else: defaultRoute = 'None' if 'ip' in opts and len(opts['ip']) > 0: ip = opts['ip'] else: nodeNum = self.hostOpts[name]['nodeNum'] ipBaseNum, prefixLen = netParse( self.appPrefs['ipBase'] ) ip = ipAdd(i=nodeNum, prefixLen=prefixLen, ipBaseNum=ipBaseNum) if 'cores' in opts or 'cpu' in opts: f.write(" "+name+" = net.addHost('"+name+"', cls=CPULimitedHost, ip='"+ip+"', defaultRoute="+defaultRoute+")\n") if 'cores' in opts: f.write(" "+name+".setCPUs(cores='"+opts['cores']+"')\n") if 'cpu' in opts: f.write(" "+name+".setCPUFrac(f="+str(opts['cpu'])+", sched='"+opts['sched']+"')\n") else: f.write(" "+name+" = net.addHost('"+name+"', cls=Host, ip='"+ip+"', defaultRoute="+defaultRoute+")\n") if 'externalInterfaces' in opts: for extInterface in opts['externalInterfaces']: f.write(" Intf( '"+extInterface+"', node="+name+" )\n") f.write("\n") # Save Links f.write(" info( '*** Add links\\n')\n") for key,linkDetail in self.links.iteritems(): tags = self.canvas.gettags(key) if 'data' in tags: optsExist = False src = linkDetail['src'] dst = linkDetail['dest'] linkopts = linkDetail['linkOpts'] srcName, dstName = src[ 'text' ], dst[ 'text' ] bw = '' # delay = '' # loss = '' # max_queue_size = '' linkOpts = "{" if 'bw' in linkopts: bw = linkopts['bw'] linkOpts = linkOpts + "'bw':"+str(bw) optsExist = True if 'delay' in linkopts: # delay = linkopts['delay'] if optsExist: linkOpts = linkOpts + "," linkOpts = linkOpts + "'delay':'"+linkopts['delay']+"'" optsExist = True if 'loss' in linkopts: if optsExist: linkOpts = linkOpts + "," linkOpts = linkOpts + "'loss':"+str(linkopts['loss']) optsExist = True if 'max_queue_size' in linkopts: if optsExist: linkOpts = linkOpts + "," linkOpts = linkOpts + "'max_queue_size':"+str(linkopts['max_queue_size']) optsExist = True if 'jitter' in linkopts: if optsExist: linkOpts = linkOpts + "," linkOpts = linkOpts + "'jitter':'"+linkopts['jitter']+"'" optsExist = True if 'speedup' in linkopts: if optsExist: linkOpts = linkOpts + "," linkOpts = linkOpts + "'speedup':"+str(linkopts['speedup']) optsExist = True linkOpts = linkOpts + "}" if optsExist: f.write(" "+srcName+dstName+" = "+linkOpts+"\n") f.write(" net.addLink("+srcName+", "+dstName) if optsExist: f.write(", cls=TCLink , **"+srcName+dstName) f.write(")\n") f.write("\n") f.write(" info( '*** Starting network\\n')\n") f.write(" net.build()\n") f.write(" info( '*** Starting controllers\\n')\n") f.write(" for controller in net.controllers:\n") f.write(" controller.start()\n") f.write("\n") f.write(" info( '*** Starting switches\\n')\n") for widget in self.widgetToItem: name = widget[ 'text' ] tags = self.canvas.gettags( self.widgetToItem[ widget ] ) if 'Switch' in tags or 'LegacySwitch' in tags: opts = self.switchOpts[name] ctrlList = ",".join(opts['controllers']) f.write(" net.get('"+name+"').start(["+ctrlList+"])\n") f.write("\n") f.write(" info( '*** Post configure switches and hosts\\n')\n") for widget in self.widgetToItem: name = widget[ 'text' ] tags = self.canvas.gettags( self.widgetToItem[ widget ] ) if 'Switch' in tags: opts = self.switchOpts[name] if opts['switchType'] == 'default': if self.appPrefs['switchType'] == 'user': if 'switchIP' in opts: if len(opts['switchIP']) > 0: f.write(" "+name+".cmd('ifconfig "+name+" "+opts['switchIP']+"')\n") elif self.appPrefs['switchType'] == 'userns': if 'switchIP' in opts: if len(opts['switchIP']) > 0: f.write(" "+name+".cmd('ifconfig lo "+opts['switchIP']+"')\n") elif self.appPrefs['switchType'] == 'ovs': if 'switchIP' in opts: if len(opts['switchIP']) > 0: f.write(" "+name+".cmd('ifconfig "+name+" "+opts['switchIP']+"')\n") elif opts['switchType'] == 'user': if 'switchIP' in opts: if len(opts['switchIP']) > 0: f.write(" "+name+".cmd('ifconfig "+name+" "+opts['switchIP']+"')\n") elif opts['switchType'] == 'userns': if 'switchIP' in opts: if len(opts['switchIP']) > 0: f.write(" "+name+".cmd('ifconfig lo "+opts['switchIP']+"')\n") elif opts['switchType'] == 'ovs': if 'switchIP' in opts: if len(opts['switchIP']) > 0: f.write(" "+name+".cmd('ifconfig "+name+" "+opts['switchIP']+"')\n") for widget in self.widgetToItem: name = widget[ 'text' ] tags = self.canvas.gettags( self.widgetToItem[ widget ] ) if 'Host' in tags: opts = self.hostOpts[name] # Attach vlan interfaces if 'vlanInterfaces' in opts: for vlanInterface in opts['vlanInterfaces']: f.write(" "+name+".cmd('vconfig add "+name+"-eth0 "+vlanInterface[1]+"')\n") f.write(" "+name+".cmd('ifconfig "+name+"-eth0."+vlanInterface[1]+" "+vlanInterface[0]+"')\n") # Run User Defined Start Command if 'startCommand' in opts: f.write(" "+name+".cmdPrint('"+opts['startCommand']+"')\n") if 'Switch' in tags: opts = self.switchOpts[name] # Run User Defined Start Command if 'startCommand' in opts: f.write(" "+name+".cmdPrint('"+opts['startCommand']+"')\n") # Configure NetFlow nflowValues = self.appPrefs['netflow'] if len(nflowValues['nflowTarget']) > 0: nflowEnabled = False nflowSwitches = '' for widget in self.widgetToItem: name = widget[ 'text' ] tags = self.canvas.gettags( self.widgetToItem[ widget ] ) if 'Switch' in tags: opts = self.switchOpts[name] if 'netflow' in opts: if opts['netflow'] == '1': nflowSwitches = nflowSwitches+' -- set Bridge '+name+' netflow=@MiniEditNF' nflowEnabled=True if nflowEnabled: nflowCmd = 'ovs-vsctl -- --id=@MiniEditNF create NetFlow '+ 'target=\\\"'+nflowValues['nflowTarget']+'\\\" '+ 'active-timeout='+nflowValues['nflowTimeout'] if nflowValues['nflowAddId'] == '1': nflowCmd = nflowCmd + ' add_id_to_interface=true' else: nflowCmd = nflowCmd + ' add_id_to_interface=false' f.write(" \n") f.write(" call('"+nflowCmd+nflowSwitches+"', shell=True)\n") # Configure sFlow sflowValues = self.appPrefs['sflow'] if len(sflowValues['sflowTarget']) > 0: sflowEnabled = False sflowSwitches = '' for widget in self.widgetToItem: name = widget[ 'text' ] tags = self.canvas.gettags( self.widgetToItem[ widget ] ) if 'Switch' in tags: opts = self.switchOpts[name] if 'sflow' in opts: if opts['sflow'] == '1': sflowSwitches = sflowSwitches+' -- set Bridge '+name+' sflow=@MiniEditSF' sflowEnabled=True if sflowEnabled: sflowCmd = 'ovs-vsctl -- --id=@MiniEditSF create sFlow '+ 'target=\\\"'+sflowValues['sflowTarget']+'\\\" '+ 'header='+sflowValues['sflowHeader']+' '+ 'sampling='+sflowValues['sflowSampling']+' '+ 'polling='+sflowValues['sflowPolling'] f.write(" \n") f.write(" call('"+sflowCmd+sflowSwitches+"', shell=True)\n") f.write("\n") f.write(" CLI(net)\n") for widget in self.widgetToItem: name = widget[ 'text' ] tags = self.canvas.gettags( self.widgetToItem[ widget ] ) if 'Host' in tags: opts = self.hostOpts[name] # Run User Defined Stop Command if 'stopCommand' in opts: f.write(" "+name+".cmdPrint('"+opts['stopCommand']+"')\n") if 'Switch' in tags: opts = self.switchOpts[name] # Run User Defined Stop Command if 'stopCommand' in opts: f.write(" "+name+".cmdPrint('"+opts['stopCommand']+"')\n") f.write(" net.stop()\n") f.write("\n") f.write("if __name__ == '__main__':\n") f.write(" setLogLevel( 'info' )\n") f.write(" myNetwork()\n") f.write("\n") f.close() # Generic canvas handler # # We could have used bindtags, as in nodeIcon, but # the dynamic approach used here # may actually require less code. In any case, it's an # interesting introspection-based alternative to bindtags. def canvasHandle( self, eventName, event ): "Generic canvas event handler" if self.active is None: return toolName = self.active handler = getattr( self, eventName + toolName, None ) if handler is not None: handler( event ) def clickCanvas( self, event ): "Canvas click handler." self.canvasHandle( 'click', event ) def dragCanvas( self, event ): "Canvas drag handler." self.canvasHandle( 'drag', event ) def releaseCanvas( self, event ): "Canvas mouse up handler." self.canvasHandle( 'release', event ) # Currently the only items we can select directly are # links. Nodes are handled by bindings in the node icon. def findItem( self, x, y ): "Find items at a location in our canvas." items = self.canvas.find_overlapping( x, y, x, y ) if len( items ) == 0: return None else: return items[ 0 ] # Canvas bindings for Select, Host, Switch and Link tools def clickSelect( self, event ): "Select an item." self.selectItem( self.findItem( event.x, event.y ) ) def deleteItem( self, item ): "Delete an item." # Don't delete while network is running if self.buttons[ 'Select' ][ 'state' ] == 'disabled': return # Delete from model if item in self.links: self.deleteLink( item ) if item in self.itemToWidget: self.deleteNode( item ) # Delete from view self.canvas.delete( item ) def deleteSelection( self, _event ): "Delete the selected item." if self.selection is not None: self.deleteItem( self.selection ) self.selectItem( None ) def nodeIcon( self, node, name ): "Create a new node icon." icon = Button( self.canvas, image=self.images[ node ], text=name, compound='top' ) # Unfortunately bindtags wants a tuple bindtags = [ str( self.nodeBindings ) ] bindtags += list( icon.bindtags() ) icon.bindtags( tuple( bindtags ) ) return icon def newNode( self, node, event ): "Add a new node to our canvas." c = self.canvas x, y = c.canvasx( event.x ), c.canvasy( event.y ) name = self.nodePrefixes[ node ] if 'Switch' == node: self.switchCount += 1 name = self.nodePrefixes[ node ] + str( self.switchCount ) self.switchOpts[name] = {} self.switchOpts[name]['nodeNum']=self.switchCount self.switchOpts[name]['hostname']=name self.switchOpts[name]['switchType']='default' self.switchOpts[name]['controllers']=[] if 'LegacyRouter' == node: self.switchCount += 1 name = self.nodePrefixes[ node ] + str( self.switchCount ) self.switchOpts[name] = {} self.switchOpts[name]['nodeNum']=self.switchCount self.switchOpts[name]['hostname']=name self.switchOpts[name]['switchType']='legacyRouter' if 'LegacySwitch' == node: self.switchCount += 1 name = self.nodePrefixes[ node ] + str( self.switchCount ) self.switchOpts[name] = {} self.switchOpts[name]['nodeNum']=self.switchCount self.switchOpts[name]['hostname']=name self.switchOpts[name]['switchType']='legacySwitch' self.switchOpts[name]['controllers']=[] if 'Host' == node: self.hostCount += 1 name = self.nodePrefixes[ node ] + str( self.hostCount ) self.hostOpts[name] = {'sched':'host'} self.hostOpts[name]['nodeNum']=self.hostCount self.hostOpts[name]['hostname']=name if 'Controller' == node: name = self.nodePrefixes[ node ] + str( self.controllerCount ) ctrlr = { 'controllerType': 'ref', 'hostname': name, 'controllerProtocol': 'tcp', 'remoteIP': '127.0.0.1', 'remotePort': 6633} self.controllers[name] = ctrlr # We want to start controller count at 0 self.controllerCount += 1 icon = self.nodeIcon( node, name ) item = self.canvas.create_window( x, y, anchor='c', window=icon, tags=node ) self.widgetToItem[ icon ] = item self.itemToWidget[ item ] = icon self.selectItem( item ) icon.links = {} if 'Switch' == node: icon.bind('<Button-3>', self.do_switchPopup ) if 'LegacyRouter' == node: icon.bind('<Button-3>', self.do_legacyRouterPopup ) if 'LegacySwitch' == node: icon.bind('<Button-3>', self.do_legacySwitchPopup ) if 'Host' == node: icon.bind('<Button-3>', self.do_hostPopup ) if 'Controller' == node: icon.bind('<Button-3>', self.do_controllerPopup ) def clickController( self, event ): "Add a new Controller to our canvas." self.newNode( 'Controller', event ) def clickHost( self, event ): "Add a new host to our canvas." self.newNode( 'Host', event ) def clickLegacyRouter( self, event ): "Add a new switch to our canvas." self.newNode( 'LegacyRouter', event ) def clickLegacySwitch( self, event ): "Add a new switch to our canvas." self.newNode( 'LegacySwitch', event ) def clickSwitch( self, event ): "Add a new switch to our canvas." self.newNode( 'Switch', event ) def dragNetLink( self, event ): "Drag a link's endpoint to another node." if self.link is None: return # Since drag starts in widget, we use root coords x = self.canvasx( event.x_root ) y = self.canvasy( event.y_root ) c = self.canvas c.coords( self.link, self.linkx, self.linky, x, y ) def releaseNetLink( self, _event ): "Give up on the current link." if self.link is not None: self.canvas.delete( self.link ) self.linkWidget = self.linkItem = self.link = None # Generic node handlers def createNodeBindings( self ): "Create a set of bindings for nodes." bindings = { '<ButtonPress-1>': self.clickNode, '<B1-Motion>': self.dragNode, '<ButtonRelease-1>': self.releaseNode, '<Enter>': self.enterNode, '<Leave>': self.leaveNode } l = Label() # lightweight-ish owner for bindings for event, binding in bindings.items(): l.bind( event, binding ) return l def selectItem( self, item ): "Select an item and remember old selection." self.lastSelection = self.selection self.selection = item def enterNode( self, event ): "Select node on entry." self.selectNode( event ) def leaveNode( self, _event ): "Restore old selection on exit." self.selectItem( self.lastSelection ) def clickNode( self, event ): "Node click handler." if self.active is 'NetLink': self.startLink( event ) else: self.selectNode( event ) return 'break' def dragNode( self, event ): "Node drag handler." if self.active is 'NetLink': self.dragNetLink( event ) else: self.dragNodeAround( event ) def releaseNode( self, event ): "Node release handler." if self.active is 'NetLink': self.finishLink( event ) # Specific node handlers def selectNode( self, event ): "Select the node that was clicked on." item = self.widgetToItem.get( event.widget, None ) self.selectItem( item ) def dragNodeAround( self, event ): "Drag a node around on the canvas." c = self.canvas # Convert global to local coordinates; # Necessary since x, y are widget-relative x = self.canvasx( event.x_root ) y = self.canvasy( event.y_root ) w = event.widget # Adjust node position item = self.widgetToItem[ w ] c.coords( item, x, y ) # Adjust link positions for dest in w.links: link = w.links[ dest ] item = self.widgetToItem[ dest ] x1, y1 = c.coords( item ) c.coords( link, x, y, x1, y1 ) self.updateScrollRegion() def createControlLinkBindings( self ): "Create a set of bindings for nodes." # Link bindings # Selection still needs a bit of work overall # Callbacks ignore event def select( _event, link=self.link ): "Select item on mouse entry." self.selectItem( link ) def highlight( _event, link=self.link ): "Highlight item on mouse entry." self.selectItem( link ) self.canvas.itemconfig( link, fill='green' ) def unhighlight( _event, link=self.link ): "Unhighlight item on mouse exit." self.canvas.itemconfig( link, fill='red' ) #self.selectItem( None ) self.canvas.tag_bind( self.link, '<Enter>', highlight ) self.canvas.tag_bind( self.link, '<Leave>', unhighlight ) self.canvas.tag_bind( self.link, '<ButtonPress-1>', select ) def createDataLinkBindings( self ): "Create a set of bindings for nodes." # Link bindings # Selection still needs a bit of work overall # Callbacks ignore event def select( _event, link=self.link ): "Select item on mouse entry." self.selectItem( link ) def highlight( _event, link=self.link ): "Highlight item on mouse entry." self.selectItem( link ) self.canvas.itemconfig( link, fill='green' ) def unhighlight( _event, link=self.link ): "Unhighlight item on mouse exit." self.canvas.itemconfig( link, fill='blue' ) #self.selectItem( None ) self.canvas.tag_bind( self.link, '<Enter>', highlight ) self.canvas.tag_bind( self.link, '<Leave>', unhighlight ) self.canvas.tag_bind( self.link, '<ButtonPress-1>', select ) self.canvas.tag_bind( self.link, '<Button-3>', self.do_linkPopup ) def startLink( self, event ): "Start a new link." if event.widget not in self.widgetToItem: # Didn't click on a node return w = event.widget item = self.widgetToItem[ w ] x, y = self.canvas.coords( item ) self.link = self.canvas.create_line( x, y, x, y, width=4, fill='blue', tag='link' ) self.linkx, self.linky = x, y self.linkWidget = w self.linkItem = item def finishLink( self, event ): "Finish creating a link" if self.link is None: return source = self.linkWidget c = self.canvas # Since we dragged from the widget, use root coords x, y = self.canvasx( event.x_root ), self.canvasy( event.y_root ) target = self.findItem( x, y ) dest = self.itemToWidget.get( target, None ) if ( source is None or dest is None or source == dest or dest in source.links or source in dest.links ): self.releaseNetLink( event ) return # For now, don't allow hosts to be directly linked stags = self.canvas.gettags( self.widgetToItem[ source ] ) dtags = self.canvas.gettags( target ) if (('Host' in stags and 'Host' in dtags) or ('Controller' in dtags and 'LegacyRouter' in stags) or ('Controller' in stags and 'LegacyRouter' in dtags) or ('Controller' in dtags and 'LegacySwitch' in stags) or ('Controller' in stags and 'LegacySwitch' in dtags) or ('Controller' in dtags and 'Host' in stags) or ('Controller' in stags and 'Host' in dtags) or ('Controller' in stags and 'Controller' in dtags)): self.releaseNetLink( event ) return # Set link type linkType='data' if 'Controller' in stags or 'Controller' in dtags: linkType='control' c.itemconfig(self.link, dash=(6, 4, 2, 4), fill='red') self.createControlLinkBindings() else: linkType='data' self.createDataLinkBindings() c.itemconfig(self.link, tags=c.gettags(self.link)+(linkType,)) x, y = c.coords( target ) c.coords( self.link, self.linkx, self.linky, x, y ) self.addLink( source, dest, linktype=linkType ) if linkType == 'control': controllerName = '' switchName = '' if 'Controller' in stags: controllerName = source[ 'text' ] switchName = dest[ 'text' ] else: controllerName = dest[ 'text' ] switchName = source[ 'text' ] self.switchOpts[switchName]['controllers'].append(controllerName) # We're done self.link = self.linkWidget = None # Menu handlers def about( self ): "Display about box." about = self.aboutBox if about is None: bg = 'white' about = Toplevel( bg='white' ) about.title( 'About' ) desc = self.appName + ': a simple network editor for MiniNet' version = 'MiniEdit '+MINIEDIT_VERSION author = 'Originally by: Bob Lantz <rlantz@cs>, April 2010' enhancements = 'Enhancements by: Gregory Gee, Since July 2013' www = 'http://gregorygee.wordpress.com/category/miniedit/' line1 = Label( about, text=desc, font='Helvetica 10 bold', bg=bg ) line2 = Label( about, text=version, font='Helvetica 9', bg=bg ) line3 = Label( about, text=author, font='Helvetica 9', bg=bg ) line4 = Label( about, text=enhancements, font='Helvetica 9', bg=bg ) line5 = Entry( about, font='Helvetica 9', bg=bg, width=len(www), justify=CENTER ) line5.insert(0, www) line5.configure(state='readonly') line1.pack( padx=20, pady=10 ) line2.pack(pady=10 ) line3.pack(pady=10 ) line4.pack(pady=10 ) line5.pack(pady=10 ) hide = ( lambda about=about: about.withdraw() ) self.aboutBox = about # Hide on close rather than destroying window Wm.wm_protocol( about, name='WM_DELETE_WINDOW', func=hide ) # Show (existing) window about.deiconify() def createToolImages( self ): "Create toolbar (and icon) images." @staticmethod def checkIntf( intf ): "Make sure intf exists and is not configured." if ( ' %s:' % intf ) not in quietRun( 'ip link show' ): showerror(title="Error", message='External interface ' +intf + ' does not exist! Skipping.') return False ips = re.findall( r'\d+\.\d+\.\d+\.\d+', quietRun( 'ifconfig ' + intf ) ) if ips: showerror(title="Error", message= intf + ' has an IP address and is probably in use! Skipping.' ) return False return True def hostDetails( self, _ignore=None ): if ( self.selection is None or self.net is not None or self.selection not in self.itemToWidget ): return widget = self.itemToWidget[ self.selection ] name = widget[ 'text' ] tags = self.canvas.gettags( self.selection ) if 'Host' not in tags: return prefDefaults = self.hostOpts[name] hostBox = HostDialog(self, title='Host Details', prefDefaults=prefDefaults) self.master.wait_window(hostBox.top) if hostBox.result: newHostOpts = {'nodeNum':self.hostOpts[name]['nodeNum']} newHostOpts['sched'] = hostBox.result['sched'] if len(hostBox.result['startCommand']) > 0: newHostOpts['startCommand'] = hostBox.result['startCommand'] if len(hostBox.result['stopCommand']) > 0: newHostOpts['stopCommand'] = hostBox.result['stopCommand'] if len(hostBox.result['cpu']) > 0: newHostOpts['cpu'] = float(hostBox.result['cpu']) if len(hostBox.result['cores']) > 0: newHostOpts['cores'] = hostBox.result['cores'] if len(hostBox.result['hostname']) > 0: newHostOpts['hostname'] = hostBox.result['hostname'] name = hostBox.result['hostname'] widget[ 'text' ] = name if len(hostBox.result['defaultRoute']) > 0: newHostOpts['defaultRoute'] = hostBox.result['defaultRoute'] if len(hostBox.result['ip']) > 0: newHostOpts['ip'] = hostBox.result['ip'] if len(hostBox.result['externalInterfaces']) > 0: newHostOpts['externalInterfaces'] = hostBox.result['externalInterfaces'] if len(hostBox.result['vlanInterfaces']) > 0: newHostOpts['vlanInterfaces'] = hostBox.result['vlanInterfaces'] if len(hostBox.result['privateDirectory']) > 0: newHostOpts['privateDirectory'] = hostBox.result['privateDirectory'] self.hostOpts[name] = newHostOpts print 'New host details for ' + name + ' = ' + str(newHostOpts) def switchDetails( self, _ignore=None ): if ( self.selection is None or self.net is not None or self.selection not in self.itemToWidget ): return widget = self.itemToWidget[ self.selection ] name = widget[ 'text' ] tags = self.canvas.gettags( self.selection ) if 'Switch' not in tags: return prefDefaults = self.switchOpts[name] switchBox = SwitchDialog(self, title='Switch Details', prefDefaults=prefDefaults) self.master.wait_window(switchBox.top) if switchBox.result: newSwitchOpts = {'nodeNum':self.switchOpts[name]['nodeNum']} newSwitchOpts['switchType'] = switchBox.result['switchType'] newSwitchOpts['controllers'] = self.switchOpts[name]['controllers'] if len(switchBox.result['startCommand']) > 0: newSwitchOpts['startCommand'] = switchBox.result['startCommand'] if len(switchBox.result['stopCommand']) > 0: newSwitchOpts['stopCommand'] = switchBox.result['stopCommand'] if len(switchBox.result['dpctl']) > 0: newSwitchOpts['dpctl'] = switchBox.result['dpctl'] if len(switchBox.result['dpid']) > 0: newSwitchOpts['dpid'] = switchBox.result['dpid'] if len(switchBox.result['hostname']) > 0: newSwitchOpts['hostname'] = switchBox.result['hostname'] name = switchBox.result['hostname'] widget[ 'text' ] = name if len(switchBox.result['externalInterfaces']) > 0: newSwitchOpts['externalInterfaces'] = switchBox.result['externalInterfaces'] newSwitchOpts['switchIP'] = switchBox.result['switchIP'] newSwitchOpts['sflow'] = switchBox.result['sflow'] newSwitchOpts['netflow'] = switchBox.result['netflow'] self.switchOpts[name] = newSwitchOpts print 'New switch details for ' + name + ' = ' + str(newSwitchOpts) def linkUp( self ): if ( self.selection is None or self.net is None): return link = self.selection linkDetail = self.links[link] src = linkDetail['src'] dst = linkDetail['dest'] srcName, dstName = src[ 'text' ], dst[ 'text' ] self.net.configLinkStatus(srcName, dstName, 'up') self.canvas.itemconfig(link, dash=()) def linkDown( self ): if ( self.selection is None or self.net is None): return link = self.selection linkDetail = self.links[link] src = linkDetail['src'] dst = linkDetail['dest'] srcName, dstName = src[ 'text' ], dst[ 'text' ] self.net.configLinkStatus(srcName, dstName, 'down') self.canvas.itemconfig(link, dash=(4, 4)) def linkDetails( self, _ignore=None ): if ( self.selection is None or self.net is not None): return link = self.selection linkDetail = self.links[link] # src = linkDetail['src'] # dest = linkDetail['dest'] linkopts = linkDetail['linkOpts'] linkBox = LinkDialog(self, title='Link Details', linkDefaults=linkopts) if linkBox.result is not None: linkDetail['linkOpts'] = linkBox.result print 'New link details = ' + str(linkBox.result) def prefDetails( self ): prefDefaults = self.appPrefs prefBox = PrefsDialog(self, title='Preferences', prefDefaults=prefDefaults) print 'New Prefs = ' + str(prefBox.result) if prefBox.result: self.appPrefs = prefBox.result def controllerDetails( self ): if ( self.selection is None or self.net is not None or self.selection not in self.itemToWidget ): return widget = self.itemToWidget[ self.selection ] name = widget[ 'text' ] tags = self.canvas.gettags( self.selection ) oldName = name if 'Controller' not in tags: return ctrlrBox = ControllerDialog(self, title='Controller Details', ctrlrDefaults=self.controllers[name]) if ctrlrBox.result: #print 'Controller is ' + ctrlrBox.result[0] if len(ctrlrBox.result['hostname']) > 0: name = ctrlrBox.result['hostname'] widget[ 'text' ] = name else: ctrlrBox.result['hostname'] = name self.controllers[name] = ctrlrBox.result print 'New controller details for ' + name + ' = ' + str(self.controllers[name]) # Find references to controller and change name if oldName != name: for widget in self.widgetToItem: switchName = widget[ 'text' ] tags = self.canvas.gettags( self.widgetToItem[ widget ] ) if 'Switch' in tags: switch = self.switchOpts[switchName] if oldName in switch['controllers']: switch['controllers'].remove(oldName) switch['controllers'].append(name) def listBridge( self, _ignore=None ): if ( self.selection is None or self.net is None or self.selection not in self.itemToWidget ): return name = self.itemToWidget[ self.selection ][ 'text' ] tags = self.canvas.gettags( self.selection ) if name not in self.net.nameToNode: return if 'Switch' in tags or 'LegacySwitch' in tags: call(["xterm -T 'Bridge Details' -sb -sl 2000 -e 'ovs-vsctl list bridge " + name + "; read -p \"Press Enter to close\"' &"], shell=True) @staticmethod def ovsShow( _ignore=None ): call(["xterm -T 'OVS Summary' -sb -sl 2000 -e 'ovs-vsctl show; read -p \"Press Enter to close\"' &"], shell=True) @staticmethod def rootTerminal( _ignore=None ): call(["xterm -T 'Root Terminal' -sb -sl 2000 &"], shell=True) # Model interface # # Ultimately we will either want to use a topo or # mininet object here, probably. def addLink( self, source, dest, linktype='data', linkopts=None ): "Add link to model." if linkopts is None: linkopts = {} source.links[ dest ] = self.link dest.links[ source ] = self.link self.links[ self.link ] = {'type' :linktype, 'src':source, 'dest':dest, 'linkOpts':linkopts} def deleteLink( self, link ): "Delete link from model." pair = self.links.get( link, None ) if pair is not None: source=pair['src'] dest=pair['dest'] del source.links[ dest ] del dest.links[ source ] stags = self.canvas.gettags( self.widgetToItem[ source ] ) # dtags = self.canvas.gettags( self.widgetToItem[ dest ] ) ltags = self.canvas.gettags( link ) if 'control' in ltags: controllerName = '' switchName = '' if 'Controller' in stags: controllerName = source[ 'text' ] switchName = dest[ 'text' ] else: controllerName = dest[ 'text' ] switchName = source[ 'text' ] if controllerName in self.switchOpts[switchName]['controllers']: self.switchOpts[switchName]['controllers'].remove(controllerName) if link is not None: del self.links[ link ] def deleteNode( self, item ): "Delete node (and its links) from model." widget = self.itemToWidget[ item ] tags = self.canvas.gettags(item) if 'Controller' in tags: # remove from switch controller lists for serachwidget in self.widgetToItem: name = serachwidget[ 'text' ] tags = self.canvas.gettags( self.widgetToItem[ serachwidget ] ) if 'Switch' in tags: if widget['text'] in self.switchOpts[name]['controllers']: self.switchOpts[name]['controllers'].remove(widget['text']) for link in widget.links.values(): # Delete from view and model self.deleteItem( link ) del self.itemToWidget[ item ] del self.widgetToItem[ widget ] def buildNodes( self, net): # Make nodes print "Getting Hosts and Switches." for widget in self.widgetToItem: name = widget[ 'text' ] tags = self.canvas.gettags( self.widgetToItem[ widget ] ) #print name+' has '+str(tags) if 'Switch' in tags: opts = self.switchOpts[name] #print str(opts) # Create the correct switch class switchClass = customOvs switchParms={} if 'dpctl' in opts: switchParms['listenPort']=int(opts['dpctl']) if 'dpid' in opts: switchParms['dpid']=opts['dpid'] if opts['switchType'] == 'default': if self.appPrefs['switchType'] == 'ivs': switchClass = IVSSwitch elif self.appPrefs['switchType'] == 'user': switchClass = CustomUserSwitch elif self.appPrefs['switchType'] == 'userns': switchParms['inNamespace'] = True switchClass = CustomUserSwitch else: switchClass = customOvs elif opts['switchType'] == 'user': switchClass = CustomUserSwitch elif opts['switchType'] == 'userns': switchClass = CustomUserSwitch switchParms['inNamespace'] = True elif opts['switchType'] == 'ivs': switchClass = IVSSwitch else: switchClass = customOvs if switchClass == customOvs: # Set OpenFlow versions self.openFlowVersions = [] if self.appPrefs['openFlowVersions']['ovsOf10'] == '1': self.openFlowVersions.append('OpenFlow10') if self.appPrefs['openFlowVersions']['ovsOf11'] == '1': self.openFlowVersions.append('OpenFlow11') if self.appPrefs['openFlowVersions']['ovsOf12'] == '1': self.openFlowVersions.append('OpenFlow12') if self.appPrefs['openFlowVersions']['ovsOf13'] == '1': self.openFlowVersions.append('OpenFlow13') protoList = ",".join(self.openFlowVersions) switchParms['protocols'] = protoList newSwitch = net.addSwitch( name , cls=switchClass, **switchParms) # Some post startup config if switchClass == CustomUserSwitch: if 'switchIP' in opts: if len(opts['switchIP']) > 0: newSwitch.setSwitchIP(opts['switchIP']) if switchClass == customOvs: if 'switchIP' in opts: if len(opts['switchIP']) > 0: newSwitch.setSwitchIP(opts['switchIP']) # Attach external interfaces if 'externalInterfaces' in opts: for extInterface in opts['externalInterfaces']: if self.checkIntf(extInterface): Intf( extInterface, node=newSwitch ) elif 'LegacySwitch' in tags: newSwitch = net.addSwitch( name , cls=LegacySwitch) elif 'LegacyRouter' in tags: newSwitch = net.addHost( name , cls=LegacyRouter) elif 'Host' in tags: opts = self.hostOpts[name] #print str(opts) ip = None defaultRoute = None if 'defaultRoute' in opts and len(opts['defaultRoute']) > 0: defaultRoute = 'via '+opts['defaultRoute'] if 'ip' in opts and len(opts['ip']) > 0: ip = opts['ip'] else: nodeNum = self.hostOpts[name]['nodeNum'] ipBaseNum, prefixLen = netParse( self.appPrefs['ipBase'] ) ip = ipAdd(i=nodeNum, prefixLen=prefixLen, ipBaseNum=ipBaseNum) # Create the correct host class if 'cores' in opts or 'cpu' in opts: if 'privateDirectory' in opts: hostCls = partial( CPULimitedHost, privateDirs=opts['privateDirectory'] ) else: hostCls=CPULimitedHost else: if 'privateDirectory' in opts: hostCls = partial( Host, privateDirs=opts['privateDirectory'] ) else: hostCls=Host print hostCls newHost = net.addHost( name, cls=hostCls, ip=ip, defaultRoute=defaultRoute ) # Set the CPULimitedHost specific options if 'cores' in opts: newHost.setCPUs(cores = opts['cores']) if 'cpu' in opts: newHost.setCPUFrac(f=opts['cpu'], sched=opts['sched']) # Attach external interfaces if 'externalInterfaces' in opts: for extInterface in opts['externalInterfaces']: if self.checkIntf(extInterface): Intf( extInterface, node=newHost ) if 'vlanInterfaces' in opts: if len(opts['vlanInterfaces']) > 0: print 'Checking that OS is VLAN prepared' self.pathCheck('vconfig', moduleName='vlan package') moduleDeps( add='8021q' ) elif 'Controller' in tags: opts = self.controllers[name] # Get controller info from panel controllerType = opts['controllerType'] if 'controllerProtocol' in opts: controllerProtocol = opts['controllerProtocol'] else: controllerProtocol = 'tcp' opts['controllerProtocol'] = 'tcp' controllerIP = opts['remoteIP'] controllerPort = opts['remotePort'] # Make controller print 'Getting controller selection:'+controllerType if controllerType == 'remote': net.addController(name=name, controller=RemoteController, ip=controllerIP, protocol=controllerProtocol, port=controllerPort) elif controllerType == 'inband': net.addController(name=name, controller=InbandController, ip=controllerIP, protocol=controllerProtocol, port=controllerPort) elif controllerType == 'ovsc': net.addController(name=name, controller=OVSController, protocol=controllerProtocol, port=controllerPort) else: net.addController(name=name, controller=Controller, protocol=controllerProtocol, port=controllerPort) else: raise Exception( "Cannot create mystery node: " + name ) @staticmethod def pathCheck( *args, **kwargs ): "Make sure each program in *args can be found in $PATH." moduleName = kwargs.get( 'moduleName', 'it' ) for arg in args: if not quietRun( 'which ' + arg ): showerror(title="Error", message= 'Cannot find required executable %s.\n' % arg + 'Please make sure that %s is installed ' % moduleName + 'and available in your $PATH.' ) def buildLinks( self, net): # Make links print "Getting Links." for key,link in self.links.iteritems(): tags = self.canvas.gettags(key) if 'data' in tags: src=link['src'] dst=link['dest'] linkopts=link['linkOpts'] srcName, dstName = src[ 'text' ], dst[ 'text' ] srcNode, dstNode = net.nameToNode[ srcName ], net.nameToNode[ dstName ] if linkopts: net.addLink(srcNode, dstNode, cls=TCLink, **linkopts) else: #print str(srcNode) #print str(dstNode) net.addLink(srcNode, dstNode) self.canvas.itemconfig(key, dash=()) def build( self ): print "Build network based on our topology." dpctl = None if len(self.appPrefs['dpctl']) > 0: dpctl = int(self.appPrefs['dpctl']) net = Mininet( topo=None, listenPort=dpctl, build=False, ipBase=self.appPrefs['ipBase'] ) self.buildNodes(net) self.buildLinks(net) # Build network (we have to do this separately at the moment ) net.build() return net def postStartSetup( self ): # Setup host details for widget in self.widgetToItem: name = widget[ 'text' ] tags = self.canvas.gettags( self.widgetToItem[ widget ] ) if 'Host' in tags: newHost = self.net.get(name) opts = self.hostOpts[name] # Attach vlan interfaces if 'vlanInterfaces' in opts: for vlanInterface in opts['vlanInterfaces']: print 'adding vlan interface '+vlanInterface[1] newHost.cmdPrint('ifconfig '+name+'-eth0.'+vlanInterface[1]+' '+vlanInterface[0]) # Run User Defined Start Command if 'startCommand' in opts: newHost.cmdPrint(opts['startCommand']) if 'Switch' in tags: newNode = self.net.get(name) opts = self.switchOpts[name] # Run User Defined Start Command if 'startCommand' in opts: newNode.cmdPrint(opts['startCommand']) # Configure NetFlow nflowValues = self.appPrefs['netflow'] if len(nflowValues['nflowTarget']) > 0: nflowEnabled = False nflowSwitches = '' for widget in self.widgetToItem: name = widget[ 'text' ] tags = self.canvas.gettags( self.widgetToItem[ widget ] ) if 'Switch' in tags: opts = self.switchOpts[name] if 'netflow' in opts: if opts['netflow'] == '1': print name+' has Netflow enabled' nflowSwitches = nflowSwitches+' -- set Bridge '+name+' netflow=@MiniEditNF' nflowEnabled=True if nflowEnabled: nflowCmd = 'ovs-vsctl -- --id=@MiniEditNF create NetFlow '+ 'target=\\\"'+nflowValues['nflowTarget']+'\\\" '+ 'active-timeout='+nflowValues['nflowTimeout'] if nflowValues['nflowAddId'] == '1': nflowCmd = nflowCmd + ' add_id_to_interface=true' else: nflowCmd = nflowCmd + ' add_id_to_interface=false' print 'cmd = '+nflowCmd+nflowSwitches call(nflowCmd+nflowSwitches, shell=True) else: print 'No switches with Netflow' else: print 'No NetFlow targets specified.' # Configure sFlow sflowValues = self.appPrefs['sflow'] if len(sflowValues['sflowTarget']) > 0: sflowEnabled = False sflowSwitches = '' for widget in self.widgetToItem: name = widget[ 'text' ] tags = self.canvas.gettags( self.widgetToItem[ widget ] ) if 'Switch' in tags: opts = self.switchOpts[name] if 'sflow' in opts: if opts['sflow'] == '1': print name+' has sflow enabled' sflowSwitches = sflowSwitches+' -- set Bridge '+name+' sflow=@MiniEditSF' sflowEnabled=True if sflowEnabled: sflowCmd = 'ovs-vsctl -- --id=@MiniEditSF create sFlow '+ 'target=\\\"'+sflowValues['sflowTarget']+'\\\" '+ 'header='+sflowValues['sflowHeader']+' '+ 'sampling='+sflowValues['sflowSampling']+' '+ 'polling='+sflowValues['sflowPolling'] print 'cmd = '+sflowCmd+sflowSwitches call(sflowCmd+sflowSwitches, shell=True) else: print 'No switches with sflow' else: print 'No sFlow targets specified.' ## NOTE: MAKE SURE THIS IS LAST THING CALLED # Start the CLI if enabled if self.appPrefs['startCLI'] == '1': info( "\n\n NOTE: PLEASE REMEMBER TO EXIT THE CLI BEFORE YOU PRESS THE STOP BUTTON. Not exiting will prevent MiniEdit from quitting and will prevent you from starting the network again during this sessoin.\n\n") CLI(self.net) def start( self ): "Start network." if self.net is None: self.net = self.build() # Since I am going to inject per switch controllers. # I can't call net.start(). I have to replicate what it # does and add the controller options. #self.net.start() info( '**** Starting %s controllers\n' % len( self.net.controllers ) ) for controller in self.net.controllers: info( str(controller) + ' ') controller.start() info('\n') info( '**** Starting %s switches\n' % len( self.net.switches ) ) #for switch in self.net.switches: # info( switch.name + ' ') # switch.start( self.net.controllers ) for widget in self.widgetToItem: name = widget[ 'text' ] tags = self.canvas.gettags( self.widgetToItem[ widget ] ) if 'Switch' in tags: opts = self.switchOpts[name] switchControllers = [] for ctrl in opts['controllers']: switchControllers.append(self.net.get(ctrl)) info( name + ' ') # Figure out what controllers will manage this switch self.net.get(name).start( switchControllers ) if 'LegacySwitch' in tags: self.net.get(name).start( [] ) info( name + ' ') info('\n') self.postStartSetup() def stop( self ): "Stop network." if self.net is not None: # Stop host details for widget in self.widgetToItem: name = widget[ 'text' ] tags = self.canvas.gettags( self.widgetToItem[ widget ] ) if 'Host' in tags: newHost = self.net.get(name) opts = self.hostOpts[name] # Run User Defined Stop Command if 'stopCommand' in opts: newHost.cmdPrint(opts['stopCommand']) if 'Switch' in tags: newNode = self.net.get(name) opts = self.switchOpts[name] # Run User Defined Stop Command if 'stopCommand' in opts: newNode.cmdPrint(opts['stopCommand']) self.net.stop() cleanUpScreens() self.net = None def do_linkPopup(self, event): # display the popup menu if self.net is None: try: self.linkPopup.tk_popup(event.x_root, event.y_root, 0) finally: # make sure to release the grab (Tk 8.0a1 only) self.linkPopup.grab_release() else: try: self.linkRunPopup.tk_popup(event.x_root, event.y_root, 0) finally: # make sure to release the grab (Tk 8.0a1 only) self.linkRunPopup.grab_release() def do_controllerPopup(self, event): # display the popup menu if self.net is None: try: self.controllerPopup.tk_popup(event.x_root, event.y_root, 0) finally: # make sure to release the grab (Tk 8.0a1 only) self.controllerPopup.grab_release() def do_legacyRouterPopup(self, event): # display the popup menu if self.net is not None: try: self.legacyRouterRunPopup.tk_popup(event.x_root, event.y_root, 0) finally: # make sure to release the grab (Tk 8.0a1 only) self.legacyRouterRunPopup.grab_release() def do_hostPopup(self, event): # display the popup menu if self.net is None: try: self.hostPopup.tk_popup(event.x_root, event.y_root, 0) finally: # make sure to release the grab (Tk 8.0a1 only) self.hostPopup.grab_release() else: try: self.hostRunPopup.tk_popup(event.x_root, event.y_root, 0) finally: # make sure to release the grab (Tk 8.0a1 only) self.hostRunPopup.grab_release() def do_legacySwitchPopup(self, event): # display the popup menu if self.net is not None: try: self.switchRunPopup.tk_popup(event.x_root, event.y_root, 0) finally: # make sure to release the grab (Tk 8.0a1 only) self.switchRunPopup.grab_release() def do_switchPopup(self, event): # display the popup menu if self.net is None: try: self.switchPopup.tk_popup(event.x_root, event.y_root, 0) finally: # make sure to release the grab (Tk 8.0a1 only) self.switchPopup.grab_release() else: try: self.switchRunPopup.tk_popup(event.x_root, event.y_root, 0) finally: # make sure to release the grab (Tk 8.0a1 only) self.switchRunPopup.grab_release() def xterm( self, _ignore=None ): "Make an xterm when a button is pressed." if ( self.selection is None or self.net is None or self.selection not in self.itemToWidget ): return name = self.itemToWidget[ self.selection ][ 'text' ] if name not in self.net.nameToNode: return term = makeTerm( self.net.nameToNode[ name ], 'Host', term=self.appPrefs['terminalType'] ) if StrictVersion(MININET_VERSION) > StrictVersion('2.0'): self.net.terms += term else: self.net.terms.append(term) def iperf( self, _ignore=None ): "Make an xterm when a button is pressed." if ( self.selection is None or self.net is None or self.selection not in self.itemToWidget ): return name = self.itemToWidget[ self.selection ][ 'text' ] if name not in self.net.nameToNode: return self.net.nameToNode[ name ].cmd( 'iperf -s -p 5001 &' ) ### BELOW HERE IS THE TOPOLOGY IMPORT CODE ### def parseArgs( self ): """Parse command-line args and return options object. returns: opts parse options dict""" if '--custom' in sys.argv: index = sys.argv.index( '--custom' ) if len( sys.argv ) > index + 1: filename = sys.argv[ index + 1 ] self.parseCustomFile( filename ) else: raise Exception( 'Custom file name not found' ) desc = ( "The %prog utility creates Mininet network from the\n" "command line. It can create parametrized topologies,\n" "invoke the Mininet CLI, and run tests." ) usage = ( '%prog [options]\n' '(type %prog -h for details)' ) opts = OptionParser( description=desc, usage=usage ) addDictOption( opts, TOPOS, TOPODEF, 'topo' ) addDictOption( opts, LINKS, LINKDEF, 'link' ) opts.add_option( '--custom', type='string', default=None, help='read custom topo and node params from .py' + 'file' ) self.options, self.args = opts.parse_args() # We don't accept extra arguments after the options if self.args: opts.print_help() exit() def setCustom( self, name, value ): "Set custom parameters for MininetRunner." if name in ( 'topos', 'switches', 'hosts', 'controllers' ): # Update dictionaries param = name.upper() globals()[ param ].update( value ) elif name == 'validate': # Add custom validate function self.validate = value else: # Add or modify global variable or class globals()[ name ] = value def parseCustomFile( self, fileName ): "Parse custom file and add params before parsing cmd-line options." customs = {} if os.path.isfile( fileName ): execfile( fileName, customs, customs ) for name, val in customs.iteritems(): self.setCustom( name, val ) else: raise Exception( 'could not find custom file: %s' % fileName ) def importTopo( self ): print 'topo='+self.options.topo if self.options.topo == 'none': return self.newTopology() topo = buildTopo( TOPOS, self.options.topo ) link = customClass( LINKS, self.options.link ) importNet = Mininet(topo=topo, build=False, link=link) importNet.build() c = self.canvas rowIncrement = 100 currentY = 100 # Add Controllers print 'controllers:'+str(len(importNet.controllers)) for controller in importNet.controllers: name = controller.name x = self.controllerCount*100+100 self.addNode('Controller', self.controllerCount, float(x), float(currentY), name=name) icon = self.findWidgetByName(name) icon.bind('<Button-3>', self.do_controllerPopup ) ctrlr = { 'controllerType': 'ref', 'hostname': name, 'controllerProtocol': controller.protocol, 'remoteIP': controller.ip, 'remotePort': controller.port} self.controllers[name] = ctrlr currentY = currentY + rowIncrement # Add switches print 'switches:'+str(len(importNet.switches)) columnCount = 0 for switch in importNet.switches: name = switch.name self.switchOpts[name] = {} self.switchOpts[name]['nodeNum']=self.switchCount self.switchOpts[name]['hostname']=name self.switchOpts[name]['switchType']='default' self.switchOpts[name]['controllers']=[] x = columnCount*100+100 self.addNode('Switch', self.switchCount, float(x), float(currentY), name=name) icon = self.findWidgetByName(name) icon.bind('<Button-3>', self.do_switchPopup ) # Now link to controllers for controller in importNet.controllers: self.switchOpts[name]['controllers'].append(controller.name) dest = self.findWidgetByName(controller.name) dx, dy = c.coords( self.widgetToItem[ dest ] ) self.link = c.create_line(float(x), float(currentY), dx, dy, width=4, fill='red', dash=(6, 4, 2, 4), tag='link' ) c.itemconfig(self.link, tags=c.gettags(self.link)+('control',)) self.addLink( icon, dest, linktype='control' ) self.createControlLinkBindings() self.link = self.linkWidget = None if columnCount == 9: columnCount = 0 currentY = currentY + rowIncrement else: columnCount =columnCount+1 currentY = currentY + rowIncrement # Add hosts print 'hosts:'+str(len(importNet.hosts)) columnCount = 0 for host in importNet.hosts: name = host.name self.hostOpts[name] = {'sched':'host'} self.hostOpts[name]['nodeNum']=self.hostCount self.hostOpts[name]['hostname']=name self.hostOpts[name]['ip']=host.IP() x = columnCount*100+100 self.addNode('Host', self.hostCount, float(x), float(currentY), name=name) icon = self.findWidgetByName(name) icon.bind('<Button-3>', self.do_hostPopup ) if columnCount == 9: columnCount = 0 currentY = currentY + rowIncrement else: columnCount =columnCount+1 print 'links:'+str(len(topo.links())) #[('h1', 's3'), ('h2', 's4'), ('s3', 's4')] for link in topo.links(): print str(link) srcNode = link[0] src = self.findWidgetByName(srcNode) sx, sy = self.canvas.coords( self.widgetToItem[ src ] ) destNode = link[1] dest = self.findWidgetByName(destNode) dx, dy = self.canvas.coords( self.widgetToItem[ dest] ) params = topo.linkInfo( srcNode, destNode ) print 'Link Parameters='+str(params) self.link = self.canvas.create_line( sx, sy, dx, dy, width=4, fill='blue', tag='link' ) c.itemconfig(self.link, tags=c.gettags(self.link)+('data',)) self.addLink( src, dest, linkopts=params ) self.createDataLinkBindings() self.link = self.linkWidget = None importNet.stop() def miniEditImages(): "Create and return images for MiniEdit." # Image data. Git will be unhappy. However, the alternative # is to keep track of separate binary files, which is also # unappealing. return { 'Select': BitmapImage( file='/usr/include/X11/bitmaps/left_ptr' ), 'Switch': PhotoImage( data=r""" R0lGODlhLgAgAPcAAB2ZxGq61imex4zH3RWWwmK41tzd3vn9/jCiyfX7/Q6SwFay0gBlmtnZ2snJ yr+2tAuMu6rY6D6kyfHx8XO/2Uqszjmly6DU5uXz+JLN4uz3+kSrzlKx0ZeZm2K21BuYw67a6QB9 r+Xl5rW2uHW61On1+UGpzbrf6xiXwny9166vsMLCwgBdlAmHt8TFxgBwpNTs9C2hyO7t7ZnR5L/B w0yv0NXV1gBimKGjpABtoQBuoqKkpiaUvqWmqHbB2/j4+Pf39729vgB/sN7w9obH3hSMugCAsonJ 4M/q8wBglgB6rCCaxLO0tX7C2wBqniGMuABzpuPl5f3+/v39/fr6+r7i7vP6/ABonV621LLc6zWk yrq6uq6wskGlyUaszp6gohmYw8HDxKaoqn3E3LGztWGuzcnLzKmrrOnp6gB1qCaex1q001ewz+Dg 4QB3qrCxstHS09LR0dHR0s7Oz8zNzsfIyQaJuQB0pozL4YzI3re4uAGFtYDG3hOUwb+/wQB5rOvr 6wB2qdju9TWfxgBpniOcxeLj48vn8dvc3VKuzwB2qp6fos/Q0aXV6D+jxwB7rsXHyLu8vb27vCSc xSGZwxyZxH3A2RuUv0+uzz+ozCedxgCDtABnnABroKutr/7+/n2/2LTd6wBvo9bX2OLo6lGv0C6d xS6avjmmzLTR2uzr6m651RuXw4jF3CqfxySaxSadyAuRv9bd4cPExRiMuDKjyUWevNPS0sXl8BeY xKytr8G/wABypXvC23vD3O73+3vE3cvU2PH5+7S1t7q7vCGVwO/v8JfM3zymyyyZwrWys+Hy90Ki xK6qqg+TwBKXxMvMzaWtsK7U4jemzLXEygBxpW++2aCho97Z18bP0/T09fX29vb19ViuzdDR0crf 51qz01y00ujo6Onq6hCDs2Gpw3i71CqWv3S71nO92M/h52m207bJ0AN6rPPz9Nrh5Nvo7K/b6oTI 37Td7ABqneHi4yScxo/M4RiWwRqVwcro8n3B2lGoylStzszMzAAAACH5BAEAAP8ALAAAAAAuACAA Bwj/AP8JHEjw3wEkEY74WOjrQhUNBSNKnCjRSoYKCOwJcKWpEAACBFBRGEKxZMkDjRAg2OBlQyYL WhDEcOWxDwofv0zqHIhhDYIFC2p4MYFMS62ZaiYVWlJJAYIqO00KMlEjABYOQokaRbp0CYBKffpE iDpxSKYC1gqswToUmYVaCFyp6QrgwwcCscaSJZhgQYBeAdRyqFBhgwWkGyct8WoXRZ8Ph/YOxMOB CIUAHsBxwGQBAII1YwpMI5Brcd0PKFA4Q2ZFMgYteZqkwxyu1KQNJzQc+CdFCrxypyqdRoEPX6x7 ki/n2TfbAxtNRHYTVCWpWTRbuRoX7yMgZ9QSFQa0/7LU/BXygjIWXVOBTR2sxp7BxGpENgKbY+PR reqyIOKnOh0M445AjTjDCgrPSBNFKt9w8wMVU5g0Bg8kDAAKOutQAkNEQNBwDRAEeVEcAV6w84Ay KowQSRhmzNGAASIAYow2IP6DySPk8ANKCv1wINE2cpjxCUEgOIOPAKicQMMbKnhyhhg97HDNF4vs IEYkNkzwjwSP/PHIE2VIgIdEnxjAiBwNGIKGDKS8I0sw2VAzApNOQimGLlyMAIkDw2yhZTF/KKGE lxCEMtEPBtDhACQurLDCLkFIsoUeZLyRpx8OmEGHN3AEcU0HkFAhUDFulDroJvOU5M44iDjgDTQO 1P/hzRw2IFJPGw3AAY0LI/SAwxc7jEKQI2mkEUipRoxp0g821AMIGlG0McockMzihx5c1LkDDmSg UVAiafACRbGPVKDTFG3MYUYdLoThRxDE6DEMGUww8eQONGwTER9piFINFOPasaFJVIjTwC1xzOGP A3HUKoIMDTwJR4QRgdBOJzq8UM0Lj5QihU5ZdGMOCSSYUwYzAwwkDhNtUKTBOZ10koMOoohihDwm HZKPEDwb4fMe9An0g5Yl+SDKFTHnkMMLLQAjXUTxUCLEIyH0bIQAwuxVQhEMcEIIIUmHUEsWGCQg xQEaIFGAHV0+QnUIIWwyg2T/3MPLDQwwcAUhTjiswYsQl1SAxQKmbBJCIMe6ISjVmXwsWQKJEJJE 3l1/TY8O4wZyh8ZQ3IF4qX9cggTdAmEwCAMs3IB311fsDfbMGv97BxSBQBAP6QMN0QUhLCSRhOp5 e923zDpk/EIaRdyO+0C/eHBHEiz0vjrrfMfciSKD4LJ8RBEk88IN0ff+O/CEVEPLGK1tH1ECM7Dx RDWdcMLJFTpUQ44jfCyjvlShZNDE/0QAgT6ypr6AAAA7 """), 'LegacySwitch': PhotoImage( data=r""" R0lGODlhMgAYAPcAAAEBAXmDjbe4uAE5cjF7xwFWq2Sa0S9biSlrrdTW1k2Ly02a5xUvSQFHjmep 6bfI2Q5SlQIYLwFfvj6M3Jaan8fHyDuFzwFp0Vah60uU3AEiRhFgrgFRogFr10N9uTFrpytHYQFM mGWt9wIwX+bm5kaT4gtFgR1cnJPF9yt80CF0yAIMGHmp2c/P0AEoUb/P4Fei7qK4zgpLjgFkyQlf t1mf5jKD1WWJrQ86ZwFAgBhYmVOa4MPV52uv8y+A0iR3ywFbtUyX5ECI0Q1UmwIcOUGQ3RBXoQI0 aRJbpr3BxVeJvQUJDafH5wIlS2aq7xBmv52lr7fH12el5Wml3097ph1ru7vM3HCz91Ke6lid40KQ 4GSQvgQGClFnfwVJjszMzVCX3hljrdPT1AFLlBRnutPf6yd5zjeI2QE9eRBdrBNVl+3v70mV4ydf lwMVKwErVlul8AFChTGB1QE3bsTFxQImTVmAp0FjiUSM1k+b6QQvWQ1SlxMgLgFixEqU3xJhsgFT pn2Xs5OluZ+1yz1Xb6HN+Td9wy1zuYClykV5r0x2oeDh4qmvt8LDwxhuxRlLfyRioo2124mft9bi 71mDr7fT79nl8Z2hpQs9b7vN4QMQIOPj5XOPrU2Jx32z6xtvwzeBywFFikFnjwcPFa29yxJjuFmP xQFv3qGxwRc/Z8vb6wsRGBNqwqmpqTdvqQIbNQFPngMzZAEfP0mQ13mHlQFYsAFnznOXu2mPtQxj vQ1Vn4Ot1+/x8my0/CJgnxNNh8DT5CdJaWyx+AELFWmt8QxPkxBZpwMFB015pgFduGCNuyx7zdnZ 2WKm6h1xyOPp8aW70QtPkUmM0LrCyr/FyztljwFPm0OJzwFny7/L1xFjswE/e12i50iR2VR8o2Gf 3xszS2eTvz2BxSlloQdJiwMHDzF3u7bJ3T2I1WCp8+Xt80FokQFJklef6mORw2ap7SJ1y77Q47nN 3wFfu1Kb5cXJyxdhrdDR0wlNkTSF11Oa4yp4yQEuW0WQ3QIDBQI7dSH5BAEAAAAALAAAAAAyABgA Bwj/AAEIHDjKF6SDvhImPMHwhA6HOiLqUENRDYSLEIplxBcNHz4Z5GTI8BLKS5OBA1Ply2fDhxwf PlLITGFmmRkzP+DlVKHCmU9nnz45csSqKKsn9gileZKrVC4aRFACOGZu5UobNuRohRkzhc2b+36o qCaqrFmzZEV1ERBg3BOmMl5JZTBhwhm7ZyycYZnvJdeuNl21qkCHTiPDhxspTtKoQgUKCJ6wehMV 5QctWupeo6TkjOd8e1lmdQkTGbTTMaDFiDGINeskX6YhEicUiQa5A/kUKaFFwQ0oXzjZ8Tbcm3Hj irwpMtTSgg9QMJf5WEZ9375AiED19ImpSQSUB4Kw/8HFSMyiRWJaqG/xhf2X91+oCbmq1e/MFD/2 EcApVkWVJhp8J9AqsywQxDfAbLJJPAy+kMkL8shjxTkUnhOJZ5+JVp8cKfhwxwdf4fQLgG4MFAwW KOZRAxM81EAPPQvoE0QQfrDhx4399OMBMjz2yCMVivCoCAWXKLKMTPvoUYcsKwi0RCcwYCAlFjU0 A6OBM4pXAhsl8FYELYWFWZhiZCbRQgIC2AGTLy408coxAoEDx5wwtGPALTVg0E4NKC7gp4FsBKoA Ki8U+oIVmVih6DnZPMBMAlGwIARWOLiggSYC+ZNIOulwY4AkSZCyxaikbqHMqaeaIp4+rAaxQxBg 2P+IozuRzvLZIS4syYVAfMAhwhSC1EPCGoskIIYY9yS7Hny75OFnEIAGyiVvWkjjRxF11fXIG3WU KNA6wghDTCW88PKMJZOkm24Z7LarSjPtoIjFn1lKyyVmmBVhwRtvaDDMgFL0Eu4VhaiDwhXCXNFD D8QQw7ATEDsBw8RSxotFHs7CKJ60XWrRBj91EOGPQCA48c7J7zTjSTPctOzynjVkkYU+O9S8Axg4 Z6BzBt30003Ps+AhNB5C4PCGC5gKJMMTZJBRytOl/CH1HxvQkMbVVxujtdZGGKGL17rsEfYQe+xR zNnFcGQCv7LsKlAtp8R9Sgd0032BLXjPoPcMffTd3YcEgAMOxOBA1GJ4AYgXAMjiHDTgggveCgRI 3RfcnffefgcOeDKEG3444osDwgEspMNiTQhx5FoOShxcrrfff0uQjOycD+554qFzMHrpp4cwBju/ 5+CmVNbArnntndeCO+O689777+w0IH0o1P/TRJMohRA4EJwn47nyiocOSOmkn/57COxE3wD11Mfh fg45zCGyVF4Ufvvyze8ewv5jQK9++6FwXxzglwM0GPAfR8AeSo4gwAHCbxsQNCAa/kHBAVhwAHPI 4BE2eIRYeHAEIBwBP0Y4Qn41YWRSCQgAOw== """), 'LegacyRouter': PhotoImage( data=r""" R0lGODlhMgAYAPcAAAEBAXZ8gQNAgL29vQNctjl/xVSa4j1dfCF+3QFq1DmL3wJMmAMzZZW11dnZ 2SFrtyNdmTSO6gIZMUKa8gJVqEOHzR9Pf5W74wFjxgFx4jltn+np6Eyi+DuT6qKiohdtwwUPGWiq 6ymF4LHH3Rh11CV81kKT5AMoUA9dq1ap/mV0gxdXlytRdR1ptRNPjTt9vwNgvwJZsX+69gsXJQFH jTtjizF0tvHx8VOm9z2V736Dhz2N3QM2acPZ70qe8gFo0HS19wVRnTiR6hMpP0eP1i6J5iNlqAtg tktjfQFu3TNxryx4xAMTIzOE1XqAh1uf5SWC4AcfNy1XgQJny93n8a2trRh312Gt+VGm/AQIDTmB yAF37QJasydzvxM/ayF3zhdLf8zLywFdu4i56gFlyi2J4yV/1w8wUo2/8j+X8D2Q5Eee9jeR7Uia 7DpeggFt2QNPm97e3jRong9bpziH2DuT7aipqQoVICmG45vI9R5720eT4Q1hs1er/yVVhwJJktPh 70tfdbHP7Xev5xs5V7W1sz9jhz11rUVZcQ9WoCVVhQk7cRdtwWuw9QYOFyFHbSBnr0dznxtWkS18 zKfP9wwcLAMHCwFFiS5UeqGtuRNNiwMfPS1hlQMtWRE5XzGM5yhxusLCwCljnwMdOFWh7cve8pG/ 7Tlxp+Tr8g9bpXF3f0lheStrrYu13QEXLS1ppTV3uUuR1RMjNTF3vU2X4TZupwRSolNne4nB+T+L 2YGz4zJ/zYe99YGHjRdDcT95sx09XQldsgMLEwMrVc/X3yN3yQ1JhTRbggsdMQNfu9HPz6WlpW2t 7RctQ0GFyeHh4dvl8SBZklCb5kOO2kWR3Vmt/zdjkQIQHi90uvPz8wIVKBp42SV5zbfT7wtXpStV fwFWrBVvyTt3swFz5kGBv2+1/QlbrVFjdQM7d1+j54i67UmX51qn9i1vsy+D2TuR5zddhQsjOR1t u0GV6ghbsDVZf4+76RRisent8Xd9hQFBgwFNmwJLlcPDwwFr1z2T5yH5BAEAAAAALAAAAAAyABgA Bwj/AAEIHEiQYJY7Qwg9UsTplRIbENuxEiXJgpcz8e5YKsixY8Essh7JcbbOBwcOa1JOmJAmTY4c HeoIabJrCShI0XyB8YRso0eOjoAdWpciBZajJ1GuWcnSZY46Ed5N8hPATqEBoRB9gVJsxRlhPwHI 0kDkVywcRpGe9LF0adOnMpt8CxDnxg1o9lphKoEACoIvmlxxvHOKVg0n/Tzku2WoVoU2J1P6WNkS rtwADuxCG/MOjwgRUEIjGG3FhaOBzaThiDSCil27G8Isc3LLjZwXsA6YYJmDjhTMmseoKQIFDx7R oxHo2abnwygAlUj1mV6tWjlelEpRwfd6gzI7VeJQ/2vZoVaDUqigqftXpH0R46H9Kl++zUo4JnKq 9dGvv09RHFhcIUMe0NiFDyql0OJUHWywMc87TXRhhCRGiHAccvNZUR8JxpDTH38p9HEUFhxgMSAv jbBjQge8PSXEC6uo0IsHA6gAAShmgCbffNtsQwIJifhRHX/TpUUiSijlUk8AqgQixSwdNBjCa7CF oVggmEgCyRf01WcFCYvYUgB104k4YlK5HONEXXfpokYdMrXRAzMhmNINNNzB9p0T57AgyZckpKKP GFNgw06ZWKR10jTw6MAmFWj4AJcQQkQQwSefvFeGCemMIQggeaJywSQ/wgHOAmJskQEfWqBlFBEH 1P/QaGY3QOpDZXA2+A6m7hl3IRQKGDCIAj6iwE8yGKC6xbJv8IHNHgACQQybN2QiTi5NwdlBpZdi isd7vyanByOJ7CMGGRhgwE+qyy47DhnBPLDLEzLIAEQjBtChRmVPNWgpr+Be+Nc9icARww9TkIEu DAsQ0O7DzGIQzD2QdDEJHTsIAROc3F7qWQncyHPPHN5QQAAG/vjzw8oKp8sPPxDH3O44/kwBQzLB xBCMOTzzHEMMBMBARgJvZJBBEm/4k0ACKydMBgwYoKNNEjJXbTXE42Q9jtFIp8z0Dy1jQMA1AGzi z9VoW7310V0znYDTGMQgwUDXLDBO2nhvoTXbbyRk/XXL+pxWkAT8UJ331WsbnbTSK8MggDZhCTOM LQkcjvXeSPedAAw0nABWWARZIgEDfyTzxt15Z53BG1PEcEknrvgEelhZMDHKCTwI8EcQFHBBAAFc gGPLHwLwcMIo12Qxu0ABAQA7 """), 'Controller': PhotoImage( data=r""" R0lGODlhMAAwAPcAAAEBAWfNAYWFhcfHx+3t6/f390lJUaWlpfPz8/Hx72lpaZGRke/v77m5uc0B AeHh4e/v7WNjY3t7e5eXlyMjI4mJidPT0+3t7f///09PT7Ozs/X19fHx8ZWTk8HBwX9/fwAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAAwADAA Bwj/AAEIHEiwoMGDCBMqXMiwocOHECNKnEixosWLGAEIeMCxo8ePHwVkBGABg8mTKFOmtDByAIYN MGPCRCCzQIENNzEMGOkBAwIKQIMKpYCgKAIHCDB4GNkAA4OnUJ9++CDhQ1QGFzA0GKkBA4GvYMOK BYtBA1cNaNOqXcuWq8q3b81m7Cqzbk2bMMu6/Tl0qFEEAZLKxdj1KlSqVA3rnet1rOOwiwmznUzZ LdzLJgdfpIv3pmebN2Pm1GyRbocNp1PLNMDaAM3Im1/alQk4gO28pCt2RdCBt+/eRg8IP1AUdmmf f5MrL56bYlcOvaP7Xo6Ag3HdGDho3869u/YE1507t+3AgLz58ujPMwg/sTBUCAzgy49PH0LW5u0x XFiwvz////5dcJ9bjxVIAHsSdUXAAgs2yOCDDn6FYEQaFGDgYxNCpEFfHHKIX4IDhCjiiCSS+CGF FlCmogYpcnVABTDGKGOMAlRQYwUHnKjhAjX2aOOPN8LImgAL6PiQBhLMqCSNAThQgQRGOqRBBD1W aaOVAggnQARRNqRBBxmEKeaYZIrZQZcMKbDiigqM5OabcMYp55x01ilnQAA7 """), 'Host': PhotoImage( data=r""" R0lGODlhIAAYAPcAMf//////zP//mf//Zv//M///AP/M///MzP/M mf/MZv/MM//MAP+Z//+ZzP+Zmf+ZZv+ZM/+ZAP9m//9mzP9mmf9m Zv9mM/9mAP8z//8zzP8zmf8zZv8zM/8zAP8A//8AzP8Amf8AZv8A M/8AAMz//8z/zMz/mcz/Zsz/M8z/AMzM/8zMzMzMmczMZszMM8zM AMyZ/8yZzMyZmcyZZsyZM8yZAMxm/8xmzMxmmcxmZsxmM8xmAMwz /8wzzMwzmcwzZswzM8wzAMwA/8wAzMwAmcwAZswAM8wAAJn//5n/ zJn/mZn/Zpn/M5n/AJnM/5nMzJnMmZnMZpnMM5nMAJmZ/5mZzJmZ mZmZZpmZM5mZAJlm/5lmzJlmmZlmZplmM5lmAJkz/5kzzJkzmZkz ZpkzM5kzAJkA/5kAzJkAmZkAZpkAM5kAAGb//2b/zGb/mWb/Zmb/ M2b/AGbM/2bMzGbMmWbMZmbMM2bMAGaZ/2aZzGaZmWaZZmaZM2aZ AGZm/2ZmzGZmmWZmZmZmM2ZmAGYz/2YzzGYzmWYzZmYzM2YzAGYA /2YAzGYAmWYAZmYAM2YAADP//zP/zDP/mTP/ZjP/MzP/ADPM/zPM zDPMmTPMZjPMMzPMADOZ/zOZzDOZmTOZZjOZMzOZADNm/zNmzDNm mTNmZjNmMzNmADMz/zMzzDMzmTMzZjMzMzMzADMA/zMAzDMAmTMA ZjMAMzMAAAD//wD/zAD/mQD/ZgD/MwD/AADM/wDMzADMmQDMZgDM MwDMAACZ/wCZzACZmQCZZgCZMwCZAABm/wBmzABmmQBmZgBmMwBm AAAz/wAzzAAzmQAzZgAzMwAzAAAA/wAAzAAAmQAAZgAAM+4AAN0A ALsAAKoAAIgAAHcAAFUAAEQAACIAABEAAADuAADdAAC7AACqAACI AAB3AABVAABEAAAiAAARAAAA7gAA3QAAuwAAqgAAiAAAdwAAVQAA RAAAIgAAEe7u7t3d3bu7u6qqqoiIiHd3d1VVVURERCIiIhEREQAA ACH5BAEAAAAALAAAAAAgABgAAAiNAAH8G0iwoMGDCAcKTMiw4UBw BPXVm0ixosWLFvVBHFjPoUeC9Tb+6/jRY0iQ/8iVbHiS40CVKxG2 HEkQZsyCM0mmvGkw50uePUV2tEnOZkyfQA8iTYpTKNOgKJ+C3AhO p9SWVaVOfWj1KdauTL9q5UgVbFKsEjGqXVtP40NwcBnCjXtw7tx/ C8cSBBAQADs= """ ), 'OldSwitch': PhotoImage( data=r""" R0lGODlhIAAYAPcAMf//////zP//mf//Zv//M///AP/M///MzP/M mf/MZv/MM//MAP+Z//+ZzP+Zmf+ZZv+ZM/+ZAP9m//9mzP9mmf9m Zv9mM/9mAP8z//8zzP8zmf8zZv8zM/8zAP8A//8AzP8Amf8AZv8A M/8AAMz//8z/zMz/mcz/Zsz/M8z/AMzM/8zMzMzMmczMZszMM8zM AMyZ/8yZzMyZmcyZZsyZM8yZAMxm/8xmzMxmmcxmZsxmM8xmAMwz /8wzzMwzmcwzZswzM8wzAMwA/8wAzMwAmcwAZswAM8wAAJn//5n/ zJn/mZn/Zpn/M5n/AJnM/5nMzJnMmZnMZpnMM5nMAJmZ/5mZzJmZ mZmZZpmZM5mZAJlm/5lmzJlmmZlmZplmM5lmAJkz/5kzzJkzmZkz ZpkzM5kzAJkA/5kAzJkAmZkAZpkAM5kAAGb//2b/zGb/mWb/Zmb/ M2b/AGbM/2bMzGbMmWbMZmbMM2bMAGaZ/2aZzGaZmWaZZmaZM2aZ AGZm/2ZmzGZmmWZmZmZmM2ZmAGYz/2YzzGYzmWYzZmYzM2YzAGYA /2YAzGYAmWYAZmYAM2YAADP//zP/zDP/mTP/ZjP/MzP/ADPM/zPM zDPMmTPMZjPMMzPMADOZ/zOZzDOZmTOZZjOZMzOZADNm/zNmzDNm mTNmZjNmMzNmADMz/zMzzDMzmTMzZjMzMzMzADMA/zMAzDMAmTMA ZjMAMzMAAAD//wD/zAD/mQD/ZgD/MwD/AADM/wDMzADMmQDMZgDM MwDMAACZ/wCZzACZmQCZZgCZMwCZAABm/wBmzABmmQBmZgBmMwBm AAAz/wAzzAAzmQAzZgAzMwAzAAAA/wAAzAAAmQAAZgAAM+4AAN0A ALsAAKoAAIgAAHcAAFUAAEQAACIAABEAAADuAADdAAC7AACqAACI AAB3AABVAABEAAAiAAARAAAA7gAA3QAAuwAAqgAAiAAAdwAAVQAA RAAAIgAAEe7u7t3d3bu7u6qqqoiIiHd3d1VVVURERCIiIhEREQAA ACH5BAEAAAAALAAAAAAgABgAAAhwAAEIHEiwoMGDCBMqXMiwocOH ECNKnEixosWB3zJq3Mixo0eNAL7xG0mypMmTKPl9Cznyn8uWL/m5 /AeTpsyYI1eKlBnO5r+eLYHy9Ck0J8ubPmPOrMmUpM6UUKMa/Ui1 6saLWLNq3cq1q9evYB0GBAA7 """ ), 'NetLink': PhotoImage( data=r""" R0lGODlhFgAWAPcAMf//////zP//mf//Zv//M///AP/M///MzP/M mf/MZv/MM//MAP+Z//+ZzP+Zmf+ZZv+ZM/+ZAP9m//9mzP9mmf9m Zv9mM/9mAP8z//8zzP8zmf8zZv8zM/8zAP8A//8AzP8Amf8AZv8A M/8AAMz//8z/zMz/mcz/Zsz/M8z/AMzM/8zMzMzMmczMZszMM8zM AMyZ/8yZzMyZmcyZZsyZM8yZAMxm/8xmzMxmmcxmZsxmM8xmAMwz /8wzzMwzmcwzZswzM8wzAMwA/8wAzMwAmcwAZswAM8wAAJn//5n/ zJn/mZn/Zpn/M5n/AJnM/5nMzJnMmZnMZpnMM5nMAJmZ/5mZzJmZ mZmZZpmZM5mZAJlm/5lmzJlmmZlmZplmM5lmAJkz/5kzzJkzmZkz ZpkzM5kzAJkA/5kAzJkAmZkAZpkAM5kAAGb//2b/zGb/mWb/Zmb/ M2b/AGbM/2bMzGbMmWbMZmbMM2bMAGaZ/2aZzGaZmWaZZmaZM2aZ AGZm/2ZmzGZmmWZmZmZmM2ZmAGYz/2YzzGYzmWYzZmYzM2YzAGYA /2YAzGYAmWYAZmYAM2YAADP//zP/zDP/mTP/ZjP/MzP/ADPM/zPM zDPMmTPMZjPMMzPMADOZ/zOZzDOZmTOZZjOZMzOZADNm/zNmzDNm mTNmZjNmMzNmADMz/zMzzDMzmTMzZjMzMzMzADMA/zMAzDMAmTMA ZjMAMzMAAAD//wD/zAD/mQD/ZgD/MwD/AADM/wDMzADMmQDMZgDM MwDMAACZ/wCZzACZmQCZZgCZMwCZAABm/wBmzABmmQBmZgBmMwBm AAAz/wAzzAAzmQAzZgAzMwAzAAAA/wAAzAAAmQAAZgAAM+4AAN0A ALsAAKoAAIgAAHcAAFUAAEQAACIAABEAAADuAADdAAC7AACqAACI AAB3AABVAABEAAAiAAARAAAA7gAA3QAAuwAAqgAAiAAAdwAAVQAA RAAAIgAAEe7u7t3d3bu7u6qqqoiIiHd3d1VVVURERCIiIhEREQAA ACH5BAEAAAAALAAAAAAWABYAAAhIAAEIHEiwoEGBrhIeXEgwoUKG Cx0+hGhQoiuKBy1irChxY0GNHgeCDAlgZEiTHlFuVImRJUWXEGEy lBmxI8mSNknm1Dnx5sCAADs= """ ) } def addDictOption( opts, choicesDict, default, name, helpStr=None ): """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 help: string""" if default not in choicesDict: raise Exception( 'Invalid default %s for choices dict: %s' % ( default, name ) ) if not helpStr: helpStr = ( '|'.join( sorted( choicesDict.keys() ) ) + '[,param=value...]' ) opts.add_option( '--' + name, type='string', default = default, help = helpStr ) if __name__ == '__main__': setLogLevel( 'info' ) app = MiniEdit() ### import topology if specified ### app.parseArgs() app.importTopo() app.mainloop()
154,479
42.090656
254
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/tree1024.py
#!/usr/bin/python """ Create a 1024-host network, and run the CLI on it. If this fails because of kernel limits, you may have to adjust them, e.g. by adding entries to /etc/sysctl.conf and running sysctl -p. Check util/sysctl_addon. """ from mininet.cli import CLI from mininet.log import setLogLevel from mininet.node import OVSSwitch from mininet.topolib import TreeNet if __name__ == '__main__': setLogLevel( 'info' ) network = TreeNet( depth=2, fanout=32, switch=OVSSwitch ) network.run( CLI, network )
522
26.526316
61
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/natnet.py
#!/usr/bin/python """ natnet.py: Example network with NATs h0 | s0 | ---------------- | | nat1 nat2 | | s1 s2 | | h1 h2 """ from mininet.topo import Topo from mininet.net import Mininet from mininet.nodelib import NAT from mininet.log import setLogLevel from mininet.cli import CLI from mininet.util import irange class InternetTopo(Topo): "Single switch connected to n hosts." def __init__(self, n=2, **opts): Topo.__init__(self, **opts) # set up inet switch inetSwitch = self.addSwitch('s0') # add inet host inetHost = self.addHost('h0') self.addLink(inetSwitch, inetHost) # add local nets for i in irange(1, n): inetIntf = 'nat%d-eth0' % i localIntf = 'nat%d-eth1' % i localIP = '192.168.%d.1' % i localSubnet = '192.168.%d.0/24' % i natParams = { 'ip' : '%s/24' % localIP } # add NAT to topology nat = self.addNode('nat%d' % i, cls=NAT, subnet=localSubnet, inetIntf=inetIntf, localIntf=localIntf) switch = self.addSwitch('s%d' % i) # connect NAT to inet and local switches self.addLink(nat, inetSwitch, intfName1=inetIntf) self.addLink(nat, switch, intfName1=localIntf, params1=natParams) # add host and connect to local switch host = self.addHost('h%d' % i, ip='192.168.%d.100/24' % i, defaultRoute='via %s' % localIP) self.addLink(host, switch) def run(): "Create network and run the CLI" topo = InternetTopo() net = Mininet(topo=topo) net.start() CLI(net) net.stop() if __name__ == '__main__': setLogLevel('info') run()
1,948
26.842857
77
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/linearbandwidth.py
#!/usr/bin/python """ Test bandwidth (using iperf) on linear networks of varying size, using both kernel and user datapaths. We construct a network of N hosts and N-1 switches, connected as follows: h1 <-> s1 <-> s2 .. sN-1 | | | h2 h3 hN WARNING: by default, the reference controller only supports 16 switches, so this test WILL NOT WORK unless you have recompiled your controller to support 100 switches (or more.) In addition to testing the bandwidth across varying numbers of switches, this example demonstrates: - creating a custom topology, LinearTestTopo - using the ping() and iperf() tests from Mininet() - testing both the kernel and user switches """ from mininet.net import Mininet from mininet.node import UserSwitch, OVSKernelSwitch, Controller from mininet.topo import Topo from mininet.log import lg from mininet.util import irange, quietRun from mininet.link import TCLink from functools import partial import sys flush = sys.stdout.flush class LinearTestTopo( Topo ): "Topology for a string of N hosts and N-1 switches." def __init__( self, N, **params ): # Initialize topology Topo.__init__( self, **params ) # Create switches and hosts hosts = [ self.addHost( 'h%s' % h ) for h in irange( 1, N ) ] switches = [ self.addSwitch( 's%s' % s ) for s in irange( 1, N - 1 ) ] # Wire up switches last = None for switch in switches: if last: self.addLink( last, switch ) last = switch # Wire up hosts self.addLink( hosts[ 0 ], switches[ 0 ] ) for host, switch in zip( hosts[ 1: ], switches ): self.addLink( host, switch ) def linearBandwidthTest( lengths ): "Check bandwidth at various lengths along a switch chain." results = {} switchCount = max( lengths ) hostCount = switchCount + 1 switches = { 'reference user': UserSwitch, 'Open vSwitch kernel': OVSKernelSwitch } # UserSwitch is horribly slow with recent kernels. # We can reinstate it once its performance is fixed del switches[ 'reference user' ] topo = LinearTestTopo( hostCount ) # Select TCP Reno output = quietRun( 'sysctl -w net.ipv4.tcp_congestion_control=reno' ) assert 'reno' in output for datapath in switches.keys(): print "*** testing", datapath, "datapath" Switch = switches[ datapath ] results[ datapath ] = [] link = partial( TCLink, delay='1ms' ) net = Mininet( topo=topo, switch=Switch, controller=Controller, waitConnected=True, link=link ) net.start() print "*** testing basic connectivity" for n in lengths: net.ping( [ net.hosts[ 0 ], net.hosts[ n ] ] ) print "*** testing bandwidth" for n in lengths: src, dst = net.hosts[ 0 ], net.hosts[ n ] # Try to prime the pump to reduce PACKET_INs during test # since the reference controller is reactive src.cmd( 'telnet', dst.IP(), '5001' ) print "testing", src.name, "<->", dst.name, bandwidth = net.iperf( [ src, dst ], seconds=10 ) print bandwidth flush() results[ datapath ] += [ ( n, bandwidth ) ] net.stop() for datapath in switches.keys(): print print "*** Linear network results for", datapath, "datapath:" print result = results[ datapath ] print "SwitchCount\tiperf Results" for switchCount, bandwidth in result: print switchCount, '\t\t', print bandwidth[ 0 ], 'server, ', bandwidth[ 1 ], 'client' print print if __name__ == '__main__': lg.setLogLevel( 'info' ) sizes = [ 1, 10, 20, 40, 60, 80 ] print "*** Running linearBandwidthTest", sizes linearBandwidthTest( sizes )
3,988
30.409449
73
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/intfoptions.py
#!/usr/bin/python ''' example of using various TCIntf options. reconfigures a single interface using intf.config() to use different traffic control commands to test bandwidth, loss, and delay ''' from mininet.net import Mininet from mininet.log import setLogLevel, info from mininet.link import TCLink def intfOptions(): "run various traffic control commands on a single interface" net = Mininet( autoStaticArp=True ) net.addController( 'c0' ) h1 = net.addHost( 'h1' ) h2 = net.addHost( 'h2' ) s1 = net.addSwitch( 's1' ) link1 = net.addLink( h1, s1, cls=TCLink ) net.addLink( h2, s1 ) net.start() # flush out latency from reactive forwarding delay net.pingAll() info( '\n*** Configuring one intf with bandwidth of 5 Mb\n' ) link1.intf1.config( bw=5 ) info( '\n*** Running iperf to test\n' ) net.iperf() info( '\n*** Configuring one intf with loss of 50%\n' ) link1.intf1.config( loss=50 ) info( '\n' ) net.iperf( ( h1, h2 ), l4Type='UDP' ) info( '\n*** Configuring one intf with delay of 15ms\n' ) link1.intf1.config( delay='15ms' ) info( '\n*** Run a ping to confirm delay\n' ) net.pingPairFull() info( '\n*** Done testing\n' ) net.stop() if __name__ == '__main__': setLogLevel( 'info' ) intfOptions()
1,320
25.959184
65
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/sshd.py
#!/usr/bin/python """ Create a network and start sshd(8) on each host. While something like rshd(8) would be lighter and faster, (and perfectly adequate on an in-machine network) the advantage of running sshd is that scripts can work unchanged on mininet and hardware. In addition to providing ssh access to hosts, this example demonstrates: - creating a convenience function to construct networks - connecting the host network to the root namespace - running server processes (sshd in this case) on hosts """ import sys from mininet.net import Mininet from mininet.cli import CLI from mininet.log import lg from mininet.node import Node from mininet.topolib import TreeTopo from mininet.util import waitListening def TreeNet( depth=1, fanout=2, **kwargs ): "Convenience function for creating tree networks." topo = TreeTopo( depth, fanout ) return Mininet( topo, **kwargs ) def connectToRootNS( network, switch, ip, routes ): """Connect hosts to root namespace via switch. Starts network. network: Mininet() network object switch: switch to connect to root namespace ip: IP address for root namespace node routes: host networks to route to""" # Create a node in root namespace and link to switch 0 root = Node( 'root', inNamespace=False ) intf = network.addLink( root, switch ).intf1 root.setIP( ip, intf=intf ) # Start network that now includes link to root namespace network.start() # Add routes from root ns to hosts for route in routes: root.cmd( 'route add -net ' + route + ' dev ' + str( intf ) ) def sshd( network, cmd='/usr/sbin/sshd', opts='-D', ip='10.123.123.1/32', routes=None, switch=None ): """Start a network, connect it to root ns, and run sshd on all hosts. ip: root-eth0 IP address in root namespace (10.123.123.1/32) routes: Mininet host networks to route to (10.0/24) switch: Mininet switch to connect to root namespace (s1)""" if not switch: switch = network[ 's1' ] # switch to use if not routes: routes = [ '10.0.0.0/24' ] connectToRootNS( network, switch, ip, routes ) for host in network.hosts: host.cmd( cmd + ' ' + opts + '&' ) print "*** Waiting for ssh daemons to start" for server in network.hosts: waitListening( server=server, port=22, timeout=5 ) print print "*** Hosts are running sshd at the following addresses:" print for host in network.hosts: print host.name, host.IP() print print "*** Type 'exit' or control-D to shut down network" CLI( network ) for host in network.hosts: host.cmd( 'kill %' + cmd ) network.stop() if __name__ == '__main__': lg.setLogLevel( 'info') net = TreeNet( depth=1, fanout=4 ) # get sshd args from the command line or use default args # useDNS=no -u0 to avoid reverse DNS lookup timeout argvopts = ' '.join( sys.argv[ 1: ] ) if len( sys.argv ) > 1 else ( '-D -o UseDNS=no -u0' ) sshd( net, opts=argvopts )
3,040
34.360465
73
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/controlnet.py
#!/usr/bin/python """ controlnet.py: Mininet with a custom control network We create two Mininet() networks, a control network and a data network, running four DataControllers on the control network to control the data network. Since we're using UserSwitch on the data network, it should correctly fail over to a backup controller. We also use a Mininet Facade to talk to both the control and data networks from a single CLI. """ from functools import partial from mininet.net import Mininet from mininet.node import Controller, UserSwitch from mininet.cli import CLI from mininet.topo import Topo from mininet.topolib import TreeTopo from mininet.log import setLogLevel, info # Some minor hacks class DataController( Controller ): """Data Network Controller. patched to avoid checkListening error and to delete intfs""" def checkListening( self ): "Ignore spurious error" pass def stop( self, *args, **kwargs ): "Make sure intfs are deleted" kwargs.update( deleteIntfs=True ) super( DataController, self ).stop( *args, **kwargs ) class MininetFacade( object ): """Mininet object facade that allows a single CLI to talk to one or more networks""" def __init__( self, net, *args, **kwargs ): """Create MininetFacade object. net: Primary Mininet object args: unnamed networks passed as arguments kwargs: named networks passed as arguments""" self.net = net self.nets = [ net ] + list( args ) + kwargs.values() self.nameToNet = kwargs self.nameToNet['net'] = net def __getattr__( self, name ): "returns attribute from Primary Mininet object" return getattr( self.net, name ) def __getitem__( self, key ): "returns primary/named networks or node from any net" #search kwargs for net named key if key in self.nameToNet: return self.nameToNet[ key ] #search each net for node named key for net in self.nets: if key in net: return net[ key ] def __iter__( self ): "Iterate through all nodes in all Mininet objects" for net in self.nets: for node in net: yield node def __len__( self ): "returns aggregate number of nodes in all nets" count = 0 for net in self.nets: count += len(net) return count def __contains__( self, key ): "returns True if node is a member of any net" return key in self.keys() def keys( self ): "returns a list of all node names in all networks" return list( self ) def values( self ): "returns a list of all nodes in all networks" return [ self[ key ] for key in self ] def items( self ): "returns (key,value) tuple list for every node in all networks" return zip( self.keys(), self.values() ) # A real control network! class ControlNetwork( Topo ): "Control Network Topology" def __init__( self, n, dataController=DataController, **kwargs ): """n: number of data network controller nodes dataController: class for data network controllers""" Topo.__init__( self, **kwargs ) # Connect everything to a single switch cs0 = self.addSwitch( 'cs0' ) # Add hosts which will serve as data network controllers for i in range( 0, n ): c = self.addHost( 'c%s' % i, cls=dataController, inNamespace=True ) self.addLink( c, cs0 ) # Connect switch to root namespace so that data network # switches will be able to talk to us root = self.addHost( 'root', inNamespace=False ) self.addLink( root, cs0 ) # Make it Happen!! def run(): "Create control and data networks, and invoke the CLI" info( '* Creating Control Network\n' ) ctopo = ControlNetwork( n=4, dataController=DataController ) cnet = Mininet( topo=ctopo, ipBase='192.168.123.0/24', controller=None ) info( '* Adding Control Network Controller\n') cnet.addController( 'cc0', controller=Controller ) info( '* Starting Control Network\n') cnet.start() info( '* Creating Data Network\n' ) topo = TreeTopo( depth=2, fanout=2 ) # UserSwitch so we can easily test failover sw = partial( UserSwitch, opts='--inactivity-probe=1 --max-backoff=1' ) net = Mininet( topo=topo, switch=sw, controller=None ) info( '* Adding Controllers to Data Network\n' ) for host in cnet.hosts: if isinstance(host, Controller): net.addController( host ) info( '* Starting Data Network\n') net.start() mn = MininetFacade( net, cnet=cnet ) CLI( mn ) info( '* Stopping Data Network\n' ) net.stop() info( '* Stopping Control Network\n' ) cnet.stop() if __name__ == '__main__': setLogLevel( 'info' ) run()
4,967
30.245283
76
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/cluster.py
#!/usr/bin/python """ cluster.py: prototyping/experimentation for distributed Mininet, aka Mininet: Cluster Edition Author: Bob Lantz Core classes: RemoteNode: a Node() running on a remote server RemoteOVSSwitch(): an OVSSwitch() running on a remote server RemoteLink: a Link() on a remote server Tunnel: a Link() between a local Node() and a RemoteNode() These are largely interoperable with local objects. - One Mininet to rule them all It is important that the same topologies, APIs, and CLI can be used with minimal or no modification in both local and distributed environments. - Multiple placement models Placement should be as easy as possible. We should provide basic placement support and also allow for explicit placement. Questions: What is the basic communication mechanism? To start with? Probably a single multiplexed ssh connection between each pair of mininet servers that needs to communicate. How are tunnels created? We have several options including ssh, GRE, OF capsulator, socat, VDE, l2tp, etc.. It's not clear what the best one is. For now, we use ssh tunnels since they are encrypted and semi-automatically shared. We will probably want to support GRE as well because it's very easy to set up with OVS. How are tunnels destroyed? They are destroyed when the links are deleted in Mininet.stop() How does RemoteNode.popen() work? It opens a shared ssh connection to the remote server and attaches to the namespace using mnexec -a -g. Is there any value to using Paramiko vs. raw ssh? Maybe, but it doesn't seem to support L2 tunneling. Should we preflight the entire network, including all server-to-server connections? Yes! We don't yet do this with remote server-to-server connections yet. Should we multiplex the link ssh connections? Yes, this is done automatically with ControlMaster=auto. Note on ssh and DNS: Please add UseDNS: no to your /etc/ssh/sshd_config!!! Things to do: - asynchronous/pipelined/parallel startup - ssh debugging/profiling - make connections into real objects - support for other tunneling schemes - tests and benchmarks - hifi support (e.g. delay compensation) """ from mininet.node import Node, Host, OVSSwitch, Controller from mininet.link import Link, Intf from mininet.net import Mininet from mininet.topo import LinearTopo from mininet.topolib import TreeTopo from mininet.util import quietRun, errRun from mininet.examples.clustercli import CLI from mininet.log import setLogLevel, debug, info, error from mininet.clean import addCleanupCallback from signal import signal, SIGINT, SIG_IGN from subprocess import Popen, PIPE, STDOUT import os from random import randrange import sys import re from itertools import groupby from operator import attrgetter from distutils.version import StrictVersion def findUser(): "Try to return logged-in (usually non-root) user" return ( # If we're running sudo os.environ.get( 'SUDO_USER', False ) or # Logged-in user (if we have a tty) ( quietRun( 'who am i' ).split() or [ False ] )[ 0 ] or # Give up and return effective user quietRun( 'whoami' ).strip() ) class ClusterCleanup( object ): "Cleanup callback" inited = False serveruser = {} @classmethod def add( cls, server, user='' ): "Add an entry to server: user dict" if not cls.inited: addCleanupCallback( cls.cleanup ) if not user: user = findUser() cls.serveruser[ server ] = user @classmethod def cleanup( cls ): "Clean up" info( '*** Cleaning up cluster\n' ) for server, user in cls.serveruser.iteritems(): if server == 'localhost': # Handled by mininet.clean.cleanup() continue else: cmd = [ 'su', user, '-c', 'ssh %s@%s sudo mn -c' % ( user, server ) ] info( cmd, '\n' ) info( quietRun( cmd ) ) # BL note: so little code is required for remote nodes, # we will probably just want to update the main Node() # class to enable it for remote access! However, there # are a large number of potential failure conditions with # remote nodes which we may want to detect and handle. # Another interesting point is that we could put everything # in a mix-in class and easily add cluster mode to 2.0. class RemoteMixin( object ): "A mix-in class to turn local nodes into remote nodes" # ssh base command # -q: don't print stupid diagnostic messages # BatchMode yes: don't ask for password # ForwardAgent yes: forward authentication credentials sshbase = [ 'ssh', '-q', '-o', 'BatchMode=yes', '-o', 'ForwardAgent=yes', '-tt' ] def __init__( self, name, server='localhost', user=None, serverIP=None, controlPath=False, splitInit=False, **kwargs): """Instantiate a remote node name: name of remote node server: remote server (optional) user: user on remote server (optional) controlPath: specify shared ssh control path (optional) splitInit: split initialization? **kwargs: see Node()""" # We connect to servers by IP address self.server = server if server else 'localhost' self.serverIP = ( serverIP if serverIP else self.findServerIP( self.server ) ) self.user = user if user else findUser() ClusterCleanup.add( server=server, user=user ) if controlPath is True: # Set a default control path for shared SSH connections controlPath = '/tmp/mn-%r@%h:%p' self.controlPath = controlPath self.splitInit = splitInit if self.user and self.server != 'localhost': self.dest = '%s@%s' % ( self.user, self.serverIP ) self.sshcmd = [ 'sudo', '-E', '-u', self.user ] + self.sshbase if self.controlPath: self.sshcmd += [ '-o', 'ControlPath=' + self.controlPath, '-o', 'ControlMaster=auto', '-o', 'ControlPersist=' + '1' ] self.sshcmd += [ self.dest ] self.isRemote = True else: self.dest = None self.sshcmd = [] self.isRemote = False # Satisfy pylint self.shell, self.pid = None, None super( RemoteMixin, self ).__init__( name, **kwargs ) # Determine IP address of local host _ipMatchRegex = re.compile( r'\d+\.\d+\.\d+\.\d+' ) @classmethod def findServerIP( cls, server ): "Return our server's IP address" # First, check for an IP address ipmatch = cls._ipMatchRegex.findall( server ) if ipmatch: return ipmatch[ 0 ] # Otherwise, look up remote server output = quietRun( 'getent ahostsv4 %s' % server ) ips = cls._ipMatchRegex.findall( output ) ip = ips[ 0 ] if ips else None return ip # Command support via shell process in namespace def startShell( self, *args, **kwargs ): "Start a shell process for running commands" if self.isRemote: kwargs.update( mnopts='-c' ) super( RemoteMixin, self ).startShell( *args, **kwargs ) # Optional split initialization self.sendCmd( 'echo $$' ) if not self.splitInit: self.finishInit() def finishInit( self ): "Wait for split initialization to complete" self.pid = int( self.waitOutput() ) def rpopen( self, *cmd, **opts ): "Return a Popen object on underlying server in root namespace" params = { 'stdin': PIPE, 'stdout': PIPE, 'stderr': STDOUT, 'sudo': True } params.update( opts ) return self._popen( *cmd, **params ) def rcmd( self, *cmd, **opts): """rcmd: run a command on underlying server in root namespace args: string or list of strings returns: stdout and stderr""" popen = self.rpopen( *cmd, **opts ) # print 'RCMD: POPEN:', popen # These loops are tricky to get right. # Once the process exits, we can read # EOF twice if necessary. result = '' while True: poll = popen.poll() result += popen.stdout.read() if poll is not None: break return result @staticmethod def _ignoreSignal(): "Detach from process group to ignore all signals" os.setpgrp() def _popen( self, cmd, sudo=True, tt=True, **params): """Spawn a process on a remote node cmd: remote command to run (list) **params: parameters to Popen() returns: Popen() object""" if type( cmd ) is str: cmd = cmd.split() if self.isRemote: if sudo: cmd = [ 'sudo', '-E' ] + cmd if tt: cmd = self.sshcmd + cmd else: # Hack: remove -tt sshcmd = list( self.sshcmd ) sshcmd.remove( '-tt' ) cmd = sshcmd + cmd else: if self.user and not sudo: # Drop privileges cmd = [ 'sudo', '-E', '-u', self.user ] + cmd params.update( preexec_fn=self._ignoreSignal ) debug( '_popen', cmd, '\n' ) popen = super( RemoteMixin, self )._popen( cmd, **params ) return popen def popen( self, *args, **kwargs ): "Override: disable -tt" return super( RemoteMixin, self).popen( *args, tt=False, **kwargs ) def addIntf( self, *args, **kwargs ): "Override: use RemoteLink.moveIntf" kwargs.update( moveIntfFn=RemoteLink.moveIntf ) return super( RemoteMixin, self).addIntf( *args, **kwargs ) class RemoteNode( RemoteMixin, Node ): "A node on a remote server" pass class RemoteHost( RemoteNode ): "A RemoteHost is simply a RemoteNode" pass class RemoteOVSSwitch( RemoteMixin, OVSSwitch ): "Remote instance of Open vSwitch" OVSVersions = {} def __init__( self, *args, **kwargs ): # No batch startup yet kwargs.update( batch=True ) super( RemoteOVSSwitch, self ).__init__( *args, **kwargs ) def isOldOVS( self ): "Is remote switch using an old OVS version?" cls = type( self ) if self.server not in cls.OVSVersions: # pylint: disable=not-callable vers = self.cmd( 'ovs-vsctl --version' ) # pylint: enable=not-callable cls.OVSVersions[ self.server ] = re.findall( r'\d+\.\d+', vers )[ 0 ] return ( StrictVersion( cls.OVSVersions[ self.server ] ) < StrictVersion( '1.10' ) ) @classmethod 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 @classmethod 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 class RemoteLink( Link ): "A RemoteLink is a link between nodes which may be on different servers" def __init__( self, node1, node2, **kwargs ): """Initialize a RemoteLink see Link() for parameters""" # Create links on remote node self.node1 = node1 self.node2 = node2 self.tunnel = None kwargs.setdefault( 'params1', {} ) kwargs.setdefault( 'params2', {} ) self.cmd = None # satisfy pylint Link.__init__( self, node1, node2, **kwargs ) def stop( self ): "Stop this link" if self.tunnel: self.tunnel.terminate() self.intf1.delete() self.intf2.delete() else: Link.stop( self ) self.tunnel = None def makeIntfPair( self, intfname1, intfname2, addr1=None, addr2=None, node1=None, node2=None, deleteIntfs=True ): """Create pair of interfaces intfname1: name of interface 1 intfname2: name of interface 2 (override this method [and possibly delete()] to change link type)""" node1 = self.node1 if node1 is None else node1 node2 = self.node2 if node2 is None else node2 server1 = getattr( node1, 'server', 'localhost' ) server2 = getattr( node2, 'server', 'localhost' ) if server1 == server2: # Link within same server return Link.makeIntfPair( intfname1, intfname2, addr1, addr2, node1, node2, deleteIntfs=deleteIntfs ) # Otherwise, make a tunnel self.tunnel = self.makeTunnel( node1, node2, intfname1, intfname2, addr1, addr2 ) return self.tunnel @staticmethod def moveIntf( intf, node, printError=True ): """Move remote interface from root ns to node intf: string, interface dstNode: destination Node srcNode: source Node or None (default) for root ns printError: if true, print error""" intf = str( intf ) cmd = 'ip link set %s netns %s' % ( intf, node.pid ) node.rcmd( cmd ) links = node.cmd( 'ip link show' ) if not ' %s:' % intf in links: if printError: error( '*** Error: RemoteLink.moveIntf: ' + intf + ' not successfully moved to ' + node.name + '\n' ) return False return True def makeTunnel( self, node1, node2, intfname1, intfname2, addr1=None, addr2=None ): "Make a tunnel across switches on different servers" # We should never try to create a tunnel to ourselves! assert node1.server != 'localhost' or node2.server != 'localhost' # And we can't ssh into this server remotely as 'localhost', # so try again swappping node1 and node2 if node2.server == 'localhost': return self.makeTunnel( node2, node1, intfname2, intfname1, addr2, addr1 ) # 1. Create tap interfaces for node in node1, node2: # For now we are hard-wiring tap9, which we will rename cmd = 'ip tuntap add dev tap9 mode tap user ' + node.user result = node.rcmd( cmd ) if result: raise Exception( 'error creating tap9 on %s: %s' % ( node, result ) ) # 2. Create ssh tunnel between tap interfaces # -n: close stdin dest = '%s@%s' % ( node2.user, node2.serverIP ) cmd = [ 'ssh', '-n', '-o', 'Tunnel=Ethernet', '-w', '9:9', dest, 'echo @' ] self.cmd = cmd tunnel = node1.rpopen( cmd, sudo=False ) # When we receive the character '@', it means that our # tunnel should be set up debug( 'Waiting for tunnel to come up...\n' ) ch = tunnel.stdout.read( 1 ) if ch != '@': raise Exception( 'makeTunnel:\n', 'Tunnel setup failed for', '%s:%s' % ( node1, node1.dest ), 'to', '%s:%s\n' % ( node2, node2.dest ), 'command was:', cmd, '\n' ) # 3. Move interfaces if necessary for node in node1, node2: if not self.moveIntf( 'tap9', node ): raise Exception( 'interface move failed on node %s' % node ) # 4. Rename tap interfaces to desired names for node, intf, addr in ( ( node1, intfname1, addr1 ), ( node2, intfname2, addr2 ) ): if not addr: result = node.cmd( 'ip link set tap9 name', intf ) else: result = node.cmd( 'ip link set tap9 name', intf, 'address', addr ) if result: raise Exception( 'error renaming %s: %s' % ( intf, result ) ) return tunnel def status( self ): "Detailed representation of link" if self.tunnel: if self.tunnel.poll() is not None: status = "Tunnel EXITED %s" % self.tunnel.returncode else: status = "Tunnel Running (%s: %s)" % ( self.tunnel.pid, self.cmd ) else: status = "OK" result = "%s %s" % ( Link.status( self ), status ) return result # Some simple placement algorithms for MininetCluster class Placer( object ): "Node placement algorithm for MininetCluster" def __init__( self, servers=None, nodes=None, hosts=None, switches=None, controllers=None, links=None ): """Initialize placement object servers: list of servers nodes: list of all nodes hosts: list of hosts switches: list of switches controllers: list of controllers links: list of links (all arguments are optional) returns: server""" self.servers = servers or [] self.nodes = nodes or [] self.hosts = hosts or [] self.switches = switches or [] self.controllers = controllers or [] self.links = links or [] def place( self, node ): "Return server for a given node" assert self, node # satisfy pylint # Default placement: run locally return 'localhost' class RandomPlacer( Placer ): "Random placement" def place( self, nodename ): """Random placement function nodename: node name""" assert nodename # please pylint # This may be slow with lots of servers return self.servers[ randrange( 0, len( self.servers ) ) ] class RoundRobinPlacer( Placer ): """Round-robin placement Note this will usually result in cross-server links between hosts and switches""" def __init__( self, *args, **kwargs ): Placer.__init__( self, *args, **kwargs ) self.next = 0 def place( self, nodename ): """Round-robin placement function nodename: node name""" assert nodename # please pylint # This may be slow with lots of servers server = self.servers[ self.next ] self.next = ( self.next + 1 ) % len( self.servers ) return server class SwitchBinPlacer( Placer ): """Place switches (and controllers) into evenly-sized bins, and attempt to co-locate hosts and switches""" def __init__( self, *args, **kwargs ): Placer.__init__( self, *args, **kwargs ) # Easy lookup for servers and node sets self.servdict = dict( enumerate( self.servers ) ) self.hset = frozenset( self.hosts ) self.sset = frozenset( self.switches ) self.cset = frozenset( self.controllers ) # Server and switch placement indices self.placement = self.calculatePlacement() @staticmethod def bin( nodes, servers ): "Distribute nodes evenly over servers" # Calculate base bin size nlen = len( nodes ) slen = len( servers ) # Basic bin size quotient = int( nlen / slen ) binsizes = { server: quotient for server in servers } # Distribute remainder remainder = nlen % slen for server in servers[ 0 : remainder ]: binsizes[ server ] += 1 # Create binsize[ server ] tickets for each server tickets = sum( [ binsizes[ server ] * [ server ] for server in servers ], [] ) # And assign one ticket to each node return { node: ticket for node, ticket in zip( nodes, tickets ) } def calculatePlacement( self ): "Pre-calculate node placement" placement = {} # Create host-switch connectivity map, # associating host with last switch that it's # connected to switchFor = {} for src, dst in self.links: if src in self.hset and dst in self.sset: switchFor[ src ] = dst if dst in self.hset and src in self.sset: switchFor[ dst ] = src # Place switches placement = self.bin( self.switches, self.servers ) # Place controllers and merge into placement dict placement.update( self.bin( self.controllers, self.servers ) ) # Co-locate hosts with their switches for h in self.hosts: if h in placement: # Host is already placed - leave it there continue if h in switchFor: placement[ h ] = placement[ switchFor[ h ] ] else: raise Exception( "SwitchBinPlacer: cannot place isolated host " + h ) return placement def place( self, node ): """Simple placement algorithm: place switches into evenly sized bins, and place hosts near their switches""" return self.placement[ node ] class HostSwitchBinPlacer( Placer ): """Place switches *and hosts* into evenly-sized bins Note that this will usually result in cross-server links between hosts and switches""" def __init__( self, *args, **kwargs ): Placer.__init__( self, *args, **kwargs ) # Calculate bin sizes scount = len( self.servers ) self.hbin = max( int( len( self.hosts ) / scount ), 1 ) self.sbin = max( int( len( self.switches ) / scount ), 1 ) self.cbin = max( int( len( self.controllers ) / scount ), 1 ) info( 'scount:', scount ) info( 'bins:', self.hbin, self.sbin, self.cbin, '\n' ) self.servdict = dict( enumerate( self.servers ) ) self.hset = frozenset( self.hosts ) self.sset = frozenset( self.switches ) self.cset = frozenset( self.controllers ) self.hind, self.sind, self.cind = 0, 0, 0 def place( self, nodename ): """Simple placement algorithm: place nodes into evenly sized bins""" # Place nodes into bins if nodename in self.hset: server = self.servdict[ self.hind / self.hbin ] self.hind += 1 elif nodename in self.sset: server = self.servdict[ self.sind / self.sbin ] self.sind += 1 elif nodename in self.cset: server = self.servdict[ self.cind / self.cbin ] self.cind += 1 else: info( 'warning: unknown node', nodename ) server = self.servdict[ 0 ] return server # The MininetCluster class is not strictly necessary. # However, it has several purposes: # 1. To set up ssh connection sharing/multiplexing # 2. To pre-flight the system so that everything is more likely to work # 3. To allow connection/connectivity monitoring # 4. To support pluggable placement algorithms class MininetCluster( Mininet ): "Cluster-enhanced version of Mininet class" # Default ssh command # BatchMode yes: don't ask for password # ForwardAgent yes: forward authentication credentials sshcmd = [ 'ssh', '-o', 'BatchMode=yes', '-o', 'ForwardAgent=yes' ] def __init__( self, *args, **kwargs ): """servers: a list of servers to use (note: include localhost or None to use local system as well) user: user name for server ssh placement: Placer() subclass""" params = { 'host': RemoteHost, 'switch': RemoteOVSSwitch, 'link': RemoteLink, 'precheck': True } params.update( kwargs ) servers = params.pop( 'servers', [ 'localhost' ] ) servers = [ s if s else 'localhost' for s in servers ] self.servers = servers self.serverIP = params.pop( 'serverIP', {} ) if not self.serverIP: self.serverIP = { server: RemoteMixin.findServerIP( server ) for server in self.servers } self.user = params.pop( 'user', findUser() ) if params.pop( 'precheck' ): self.precheck() self.connections = {} self.placement = params.pop( 'placement', SwitchBinPlacer ) # Make sure control directory exists self.cdir = os.environ[ 'HOME' ] + '/.ssh/mn' errRun( [ 'mkdir', '-p', self.cdir ] ) Mininet.__init__( self, *args, **params ) def popen( self, cmd ): "Popen() for server connections" assert self # please pylint old = signal( SIGINT, SIG_IGN ) conn = Popen( cmd, stdin=PIPE, stdout=PIPE, close_fds=True ) signal( SIGINT, old ) return conn def baddLink( self, *args, **kwargs ): "break addlink for testing" pass def precheck( self ): """Pre-check to make sure connection works and that we can call sudo without a password""" result = 0 info( '*** Checking servers\n' ) for server in self.servers: ip = self.serverIP[ server ] if not server or server == 'localhost': continue info( server, '' ) dest = '%s@%s' % ( self.user, ip ) cmd = [ 'sudo', '-E', '-u', self.user ] cmd += self.sshcmd + [ '-n', dest, 'sudo true' ] debug( ' '.join( cmd ), '\n' ) _out, _err, code = errRun( cmd ) if code != 0: error( '\nstartConnection: server connection check failed ' 'to %s using command:\n%s\n' % ( server, ' '.join( cmd ) ) ) result |= code if result: error( '*** Server precheck failed.\n' '*** Make sure that the above ssh command works' ' correctly.\n' '*** You may also need to run mn -c on all nodes, and/or\n' '*** use sudo -E.\n' ) sys.exit( 1 ) info( '\n' ) def modifiedaddHost( self, *args, **kwargs ): "Slightly modify addHost" assert self # please pylint kwargs[ 'splitInit' ] = True return Mininet.addHost( *args, **kwargs ) def placeNodes( self ): """Place nodes on servers (if they don't have a server), and start shell processes""" if not self.servers or not self.topo: # No shirt, no shoes, no service return nodes = self.topo.nodes() placer = self.placement( servers=self.servers, nodes=self.topo.nodes(), hosts=self.topo.hosts(), switches=self.topo.switches(), links=self.topo.links() ) for node in nodes: config = self.topo.nodeInfo( node ) # keep local server name consistent accross nodes if 'server' in config.keys() and config[ 'server' ] is None: config[ 'server' ] = 'localhost' server = config.setdefault( 'server', placer.place( node ) ) if server: config.setdefault( 'serverIP', self.serverIP[ server ] ) info( '%s:%s ' % ( node, server ) ) key = ( None, server ) _dest, cfile, _conn = self.connections.get( key, ( None, None, None ) ) if cfile: config.setdefault( 'controlPath', cfile ) def addController( self, *args, **kwargs ): "Patch to update IP address to global IP address" controller = Mininet.addController( self, *args, **kwargs ) # Update IP address for controller that may not be local if ( isinstance( controller, Controller) and controller.IP() == '127.0.0.1' and ' eth0:' in controller.cmd( 'ip link show' ) ): Intf( 'eth0', node=controller ).updateIP() return controller def buildFromTopo( self, *args, **kwargs ): "Start network" info( '*** Placing nodes\n' ) self.placeNodes() info( '\n' ) Mininet.buildFromTopo( self, *args, **kwargs ) def testNsTunnels(): "Test tunnels between nodes in namespaces" net = Mininet( host=RemoteHost, link=RemoteLink ) h1 = net.addHost( 'h1' ) h2 = net.addHost( 'h2', server='ubuntu2' ) net.addLink( h1, h2 ) net.start() net.pingAll() net.stop() # Manual topology creation with net.add*() # # This shows how node options may be used to manage # cluster placement using the net.add*() API def testRemoteNet( remote='ubuntu2' ): "Test remote Node classes" print '*** Remote Node Test' net = Mininet( host=RemoteHost, switch=RemoteOVSSwitch, link=RemoteLink ) c0 = net.addController( 'c0' ) # Make sure controller knows its non-loopback address Intf( 'eth0', node=c0 ).updateIP() print "*** Creating local h1" h1 = net.addHost( 'h1' ) print "*** Creating remote h2" h2 = net.addHost( 'h2', server=remote ) print "*** Creating local s1" s1 = net.addSwitch( 's1' ) print "*** Creating remote s2" s2 = net.addSwitch( 's2', server=remote ) print "*** Adding links" net.addLink( h1, s1 ) net.addLink( s1, s2 ) net.addLink( h2, s2 ) net.start() print 'Mininet is running on', quietRun( 'hostname' ).strip() for node in c0, h1, h2, s1, s2: print 'Node', node, 'is running on', node.cmd( 'hostname' ).strip() net.pingAll() CLI( net ) net.stop() # High-level/Topo API example # # This shows how existing Mininet topologies may be used in cluster # mode by creating node placement functions and a controller which # can be accessed remotely. This implements a very compatible version # of cluster edition with a minimum of code! remoteHosts = [ 'h2' ] remoteSwitches = [ 's2' ] remoteServer = 'ubuntu2' def HostPlacer( name, *args, **params ): "Custom Host() constructor which places hosts on servers" if name in remoteHosts: return RemoteHost( name, *args, server=remoteServer, **params ) else: return Host( name, *args, **params ) def SwitchPlacer( name, *args, **params ): "Custom Switch() constructor which places switches on servers" if name in remoteSwitches: return RemoteOVSSwitch( name, *args, server=remoteServer, **params ) else: return RemoteOVSSwitch( name, *args, **params ) def ClusterController( *args, **kwargs): "Custom Controller() constructor which updates its eth0 IP address" controller = Controller( *args, **kwargs ) # Find out its IP address so that cluster switches can connect Intf( 'eth0', node=controller ).updateIP() return controller def testRemoteTopo(): "Test remote Node classes using Mininet()/Topo() API" topo = LinearTopo( 2 ) net = Mininet( topo=topo, host=HostPlacer, switch=SwitchPlacer, link=RemoteLink, controller=ClusterController ) net.start() net.pingAll() net.stop() # Need to test backwards placement, where each host is on # a server other than its switch!! But seriously we could just # do random switch placement rather than completely random # host placement. def testRemoteSwitches(): "Test with local hosts and remote switches" servers = [ 'localhost', 'ubuntu2'] topo = TreeTopo( depth=4, fanout=2 ) net = MininetCluster( topo=topo, servers=servers, placement=RoundRobinPlacer ) net.start() net.pingAll() net.stop() # # For testing and demo purposes it would be nice to draw the # network graph and color it based on server. # The MininetCluster() class integrates pluggable placement # functions, for maximum ease of use. MininetCluster() also # pre-flights and multiplexes server connections. def testMininetCluster(): "Test MininetCluster()" servers = [ 'localhost', 'ubuntu2' ] topo = TreeTopo( depth=3, fanout=3 ) net = MininetCluster( topo=topo, servers=servers, placement=SwitchBinPlacer ) net.start() net.pingAll() net.stop() def signalTest(): "Make sure hosts are robust to signals" h = RemoteHost( 'h0', server='ubuntu1' ) h.shell.send_signal( SIGINT ) h.shell.poll() if h.shell.returncode is None: print 'OK: ', h, 'has not exited' else: print 'FAILURE:', h, 'exited with code', h.shell.returncode h.stop() if __name__ == '__main__': setLogLevel( 'info' ) # testRemoteTopo() # testRemoteNet() # testMininetCluster() # testRemoteSwitches() signalTest()
33,412
35.51694
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/popenpoll.py
#!/usr/bin/python "Monitor multiple hosts using popen()/pmonitor()" from mininet.net import Mininet from mininet.topo import SingleSwitchTopo from mininet.util import pmonitor from time import time from signal import SIGINT def pmonitorTest( N=3, seconds=10 ): "Run pings and monitor multiple hosts using pmonitor" topo = SingleSwitchTopo( N ) net = Mininet( topo ) net.start() hosts = net.hosts print "Starting test..." server = hosts[ 0 ] popens = {} for h in hosts: popens[ h ] = h.popen('ping', server.IP() ) print "Monitoring output for", seconds, "seconds" endTime = time() + seconds for h, line in pmonitor( popens, timeoutms=500 ): if h: print '<%s>: %s' % ( h.name, line ), if time() >= endTime: for p in popens.values(): p.send_signal( SIGINT ) net.stop() if __name__ == '__main__': pmonitorTest()
932
26.441176
57
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/consoles.py
#!/usr/bin/python """ consoles.py: bring up a bunch of miniature consoles on a virtual network This demo shows how to monitor a set of nodes by using Node's monitor() and Tkinter's createfilehandler(). We monitor nodes in a couple of ways: - First, each individual node is monitored, and its output is added to its console window - Second, each time a console window gets iperf output, it is parsed and accumulated. Once we have output for all consoles, a bar is added to the bandwidth graph. The consoles also support limited interaction: - Pressing "return" in a console will send a command to it - Pressing the console's title button will open up an xterm Bob Lantz, April 2010 """ import re from Tkinter import Frame, Button, Label, Text, Scrollbar, Canvas, Wm, READABLE from mininet.log import setLogLevel from mininet.topolib import TreeNet from mininet.term import makeTerms, cleanUpScreens from mininet.util import quietRun class Console( Frame ): "A simple console on a host." def __init__( self, parent, net, node, height=10, width=32, title='Node' ): Frame.__init__( self, parent ) self.net = net self.node = node self.prompt = node.name + '# ' self.height, self.width, self.title = height, width, title # Initialize widget styles self.buttonStyle = { 'font': 'Monaco 7' } self.textStyle = { 'font': 'Monaco 7', 'bg': 'black', 'fg': 'green', 'width': self.width, 'height': self.height, 'relief': 'sunken', 'insertbackground': 'green', 'highlightcolor': 'green', 'selectforeground': 'black', 'selectbackground': 'green' } # Set up widgets self.text = self.makeWidgets( ) self.bindEvents() self.sendCmd( 'export TERM=dumb' ) self.outputHook = None def makeWidgets( self ): "Make a label, a text area, and a scroll bar." def newTerm( net=self.net, node=self.node, title=self.title ): "Pop up a new terminal window for a node." net.terms += makeTerms( [ node ], title ) label = Button( self, text=self.node.name, command=newTerm, **self.buttonStyle ) label.pack( side='top', fill='x' ) text = Text( self, wrap='word', **self.textStyle ) ybar = Scrollbar( self, orient='vertical', width=7, command=text.yview ) text.configure( yscrollcommand=ybar.set ) text.pack( side='left', expand=True, fill='both' ) ybar.pack( side='right', fill='y' ) return text def bindEvents( self ): "Bind keyboard and file events." # The text widget handles regular key presses, but we # use special handlers for the following: self.text.bind( '<Return>', self.handleReturn ) self.text.bind( '<Control-c>', self.handleInt ) self.text.bind( '<KeyPress>', self.handleKey ) # This is not well-documented, but it is the correct # way to trigger a file event handler from Tk's # event loop! self.tk.createfilehandler( self.node.stdout, READABLE, self.handleReadable ) # We're not a terminal (yet?), so we ignore the following # control characters other than [\b\n\r] ignoreChars = re.compile( r'[\x00-\x07\x09\x0b\x0c\x0e-\x1f]+' ) def append( self, text ): "Append something to our text frame." text = self.ignoreChars.sub( '', text ) self.text.insert( 'end', text ) self.text.mark_set( 'insert', 'end' ) self.text.see( 'insert' ) outputHook = lambda x, y: True # make pylint happier if self.outputHook: outputHook = self.outputHook outputHook( self, text ) def handleKey( self, event ): "If it's an interactive command, send it to the node." char = event.char if self.node.waiting: self.node.write( char ) def handleReturn( self, event ): "Handle a carriage return." cmd = self.text.get( 'insert linestart', 'insert lineend' ) # Send it immediately, if "interactive" command if self.node.waiting: self.node.write( event.char ) return # Otherwise send the whole line to the shell pos = cmd.find( self.prompt ) if pos >= 0: cmd = cmd[ pos + len( self.prompt ): ] self.sendCmd( cmd ) # Callback ignores event def handleInt( self, _event=None ): "Handle control-c." self.node.sendInt() def sendCmd( self, cmd ): "Send a command to our node." if not self.node.waiting: self.node.sendCmd( cmd ) def handleReadable( self, _fds, timeoutms=None ): "Handle file readable event." data = self.node.monitor( timeoutms ) self.append( data ) if not self.node.waiting: # Print prompt self.append( self.prompt ) def waiting( self ): "Are we waiting for output?" return self.node.waiting def waitOutput( self ): "Wait for any remaining output." while self.node.waiting: # A bit of a trade-off here... self.handleReadable( self, timeoutms=1000) self.update() def clear( self ): "Clear all of our text." self.text.delete( '1.0', 'end' ) class Graph( Frame ): "Graph that we can add bars to over time." def __init__( self, parent=None, bg = 'white', gheight=200, gwidth=500, barwidth=10, ymax=3.5,): Frame.__init__( self, parent ) self.bg = bg self.gheight = gheight self.gwidth = gwidth self.barwidth = barwidth self.ymax = float( ymax ) self.xpos = 0 # Create everything self.title, self.scale, self.graph = self.createWidgets() self.updateScrollRegions() self.yview( 'moveto', '1.0' ) def createScale( self ): "Create a and return a new canvas with scale markers." height = float( self.gheight ) width = 25 ymax = self.ymax scale = Canvas( self, width=width, height=height, background=self.bg ) opts = { 'fill': 'red' } # Draw scale line scale.create_line( width - 1, height, width - 1, 0, **opts ) # Draw ticks and numbers for y in range( 0, int( ymax + 1 ) ): ypos = height * (1 - float( y ) / ymax ) scale.create_line( width, ypos, width - 10, ypos, **opts ) scale.create_text( 10, ypos, text=str( y ), **opts ) return scale def updateScrollRegions( self ): "Update graph and scale scroll regions." ofs = 20 height = self.gheight + ofs self.graph.configure( scrollregion=( 0, -ofs, self.xpos * self.barwidth, height ) ) self.scale.configure( scrollregion=( 0, -ofs, 0, height ) ) def yview( self, *args ): "Scroll both scale and graph." self.graph.yview( *args ) self.scale.yview( *args ) def createWidgets( self ): "Create initial widget set." # Objects title = Label( self, text='Bandwidth (Gb/s)', bg=self.bg ) width = self.gwidth height = self.gheight scale = self.createScale() graph = Canvas( self, width=width, height=height, background=self.bg) xbar = Scrollbar( self, orient='horizontal', command=graph.xview ) ybar = Scrollbar( self, orient='vertical', command=self.yview ) graph.configure( xscrollcommand=xbar.set, yscrollcommand=ybar.set, scrollregion=(0, 0, width, height ) ) scale.configure( yscrollcommand=ybar.set ) # Layout title.grid( row=0, columnspan=3, sticky='new') scale.grid( row=1, column=0, sticky='nsew' ) graph.grid( row=1, column=1, sticky='nsew' ) ybar.grid( row=1, column=2, sticky='ns' ) xbar.grid( row=2, column=0, columnspan=2, sticky='ew' ) self.rowconfigure( 1, weight=1 ) self.columnconfigure( 1, weight=1 ) return title, scale, graph def addBar( self, yval ): "Add a new bar to our graph." percent = yval / self.ymax c = self.graph x0 = self.xpos * self.barwidth x1 = x0 + self.barwidth y0 = self.gheight y1 = ( 1 - percent ) * self.gheight c.create_rectangle( x0, y0, x1, y1, fill='green' ) self.xpos += 1 self.updateScrollRegions() self.graph.xview( 'moveto', '1.0' ) def clear( self ): "Clear graph contents." self.graph.delete( 'all' ) self.xpos = 0 def test( self ): "Add a bar for testing purposes." ms = 1000 if self.xpos < 10: self.addBar( self.xpos / 10 * self.ymax ) self.after( ms, self.test ) def setTitle( self, text ): "Set graph title" self.title.configure( text=text, font='Helvetica 9 bold' ) class ConsoleApp( Frame ): "Simple Tk consoles for Mininet." menuStyle = { 'font': 'Geneva 7 bold' } def __init__( self, net, parent=None, width=4 ): Frame.__init__( self, parent ) self.top = self.winfo_toplevel() self.top.title( 'Mininet' ) self.net = net self.menubar = self.createMenuBar() cframe = self.cframe = Frame( self ) self.consoles = {} # consoles themselves titles = { 'hosts': 'Host', 'switches': 'Switch', 'controllers': 'Controller' } for name in titles: nodes = getattr( net, name ) frame, consoles = self.createConsoles( cframe, nodes, width, titles[ name ] ) self.consoles[ name ] = Object( frame=frame, consoles=consoles ) self.selected = None self.select( 'hosts' ) self.cframe.pack( expand=True, fill='both' ) cleanUpScreens() # Close window gracefully Wm.wm_protocol( self.top, name='WM_DELETE_WINDOW', func=self.quit ) # Initialize graph graph = Graph( cframe ) self.consoles[ 'graph' ] = Object( frame=graph, consoles=[ graph ] ) self.graph = graph self.graphVisible = False self.updates = 0 self.hostCount = len( self.consoles[ 'hosts' ].consoles ) self.bw = 0 self.pack( expand=True, fill='both' ) def updateGraph( self, _console, output ): "Update our graph." m = re.search( r'(\d+.?\d*) ([KMG]?bits)/sec', output ) if not m: return val, units = float( m.group( 1 ) ), m.group( 2 ) #convert to Gbps if units[0] == 'M': val *= 10 ** -3 elif units[0] == 'K': val *= 10 ** -6 elif units[0] == 'b': val *= 10 ** -9 self.updates += 1 self.bw += val if self.updates >= self.hostCount: self.graph.addBar( self.bw ) self.bw = 0 self.updates = 0 def setOutputHook( self, fn=None, consoles=None ): "Register fn as output hook [on specific consoles.]" if consoles is None: consoles = self.consoles[ 'hosts' ].consoles for console in consoles: console.outputHook = fn def createConsoles( self, parent, nodes, width, title ): "Create a grid of consoles in a frame." f = Frame( parent ) # Create consoles consoles = [] index = 0 for node in nodes: console = Console( f, self.net, node, title=title ) consoles.append( console ) row = index / width column = index % width console.grid( row=row, column=column, sticky='nsew' ) index += 1 f.rowconfigure( row, weight=1 ) f.columnconfigure( column, weight=1 ) return f, consoles def select( self, groupName ): "Select a group of consoles to display." if self.selected is not None: self.selected.frame.pack_forget() self.selected = self.consoles[ groupName ] self.selected.frame.pack( expand=True, fill='both' ) def createMenuBar( self ): "Create and return a menu (really button) bar." f = Frame( self ) buttons = [ ( 'Hosts', lambda: self.select( 'hosts' ) ), ( 'Switches', lambda: self.select( 'switches' ) ), ( 'Controllers', lambda: self.select( 'controllers' ) ), ( 'Graph', lambda: self.select( 'graph' ) ), ( 'Ping', self.ping ), ( 'Iperf', self.iperf ), ( 'Interrupt', self.stop ), ( 'Clear', self.clear ), ( 'Quit', self.quit ) ] for name, cmd in buttons: b = Button( f, text=name, command=cmd, **self.menuStyle ) b.pack( side='left' ) f.pack( padx=4, pady=4, fill='x' ) return f def clear( self ): "Clear selection." for console in self.selected.consoles: console.clear() def waiting( self, consoles=None ): "Are any of our hosts waiting for output?" if consoles is None: consoles = self.consoles[ 'hosts' ].consoles for console in consoles: if console.waiting(): return True return False def ping( self ): "Tell each host to ping the next one." consoles = self.consoles[ 'hosts' ].consoles if self.waiting( consoles ): return count = len( consoles ) i = 0 for console in consoles: i = ( i + 1 ) % count ip = consoles[ i ].node.IP() console.sendCmd( 'ping ' + ip ) def iperf( self ): "Tell each host to iperf to the next one." consoles = self.consoles[ 'hosts' ].consoles if self.waiting( consoles ): return count = len( consoles ) self.setOutputHook( self.updateGraph ) for console in consoles: # Sometimes iperf -sD doesn't return, # so we run it in the background instead console.node.cmd( 'iperf -s &' ) i = 0 for console in consoles: i = ( i + 1 ) % count ip = consoles[ i ].node.IP() console.sendCmd( 'iperf -t 99999 -i 1 -c ' + ip ) def stop( self, wait=True ): "Interrupt all hosts." consoles = self.consoles[ 'hosts' ].consoles for console in consoles: console.handleInt() if wait: for console in consoles: console.waitOutput() self.setOutputHook( None ) # Shut down any iperfs that might still be running quietRun( 'killall -9 iperf' ) def quit( self ): "Stop everything and quit." self.stop( wait=False) Frame.quit( self ) # Make it easier to construct and assign objects def assign( obj, **kwargs ): "Set a bunch of fields in an object." obj.__dict__.update( kwargs ) class Object( object ): "Generic object you can stuff junk into." def __init__( self, **kwargs ): assign( self, **kwargs ) if __name__ == '__main__': setLogLevel( 'info' ) network = TreeNet( depth=2, fanout=4 ) network.start() app = ConsoleApp( network, width=4 ) app.mainloop() network.stop()
15,612
32.432548
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/nat.py
#!/usr/bin/python """ Example to create a Mininet topology and connect it to the internet via NAT """ from mininet.cli import CLI from mininet.log import lg from mininet.topolib import TreeNet if __name__ == '__main__': lg.setLogLevel( 'info') net = TreeNet( depth=1, fanout=4 ) # Add NAT connectivity net.addNAT().configDefault() net.start() print "*** Hosts are running and should have internet connectivity" print "*** Type 'exit' or control-D to shut down network" CLI( net ) # Shut down NAT net.stop()
550
24.045455
75
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/mobility.py
#!/usr/bin/python """ Simple example of Mobility with Mininet (aka enough rope to hang yourself.) We move a host from s1 to s2, s2 to s3, and then back to s1. Gotchas: The reference controller doesn't support mobility, so we need to manually flush the switch flow tables! Good luck! to-do: - think about wifi/hub behavior - think about clearing last hop - why doesn't that work? """ from mininet.net import Mininet from mininet.node import OVSSwitch from mininet.topo import LinearTopo from mininet.log import output, warn from random import randint class MobilitySwitch( OVSSwitch ): "Switch that can reattach and rename interfaces" def delIntf( self, intf ): "Remove (and detach) an interface" port = self.ports[ intf ] del self.ports[ intf ] del self.intfs[ port ] del self.nameToIntf[ intf.name ] 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 attach( self, intf ): "Attach an interface and set its port" port = self.ports[ intf ] if port: if self.isOldOVS(): self.cmd( 'ovs-vsctl add-port', self, intf ) else: self.cmd( 'ovs-vsctl add-port', self, intf, '-- set Interface', intf, 'ofport_request=%s' % port ) self.validatePort( intf ) 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 renameIntf( self, intf, newname='' ): "Rename an interface (to its canonical name)" intf.ifconfig( 'down' ) if not newname: newname = '%s-eth%d' % ( self.name, self.ports[ intf ] ) intf.cmd( 'ip link set', intf, 'name', newname ) del self.nameToIntf[ intf.name ] intf.name = newname self.nameToIntf[ intf.name ] = intf intf.ifconfig( 'up' ) def moveIntf( self, intf, switch, port=None, rename=True ): "Move one of our interfaces to another switch" self.detach( intf ) self.delIntf( intf ) switch.addIntf( intf, port=port, rename=rename ) switch.attach( intf ) def printConnections( switches ): "Compactly print connected nodes to each switch" for sw in switches: output( '%s: ' % sw ) for intf in sw.intfList(): link = intf.link if link: intf1, intf2 = link.intf1, link.intf2 remote = intf1 if intf1.node != sw else intf2 output( '%s(%s) ' % ( remote.node, sw.ports[ intf ] ) ) output( '\n' ) def moveHost( host, oldSwitch, newSwitch, newPort=None ): "Move a host from old switch to new switch" hintf, sintf = host.connectionsTo( oldSwitch )[ 0 ] oldSwitch.moveIntf( sintf, newSwitch, port=newPort ) return hintf, sintf def mobilityTest(): "A simple test of mobility" print '* Simple mobility test' net = Mininet( topo=LinearTopo( 3 ), switch=MobilitySwitch ) print '* Starting network:' net.start() printConnections( net.switches ) print '* Testing network' net.pingAll() print '* Identifying switch interface for h1' h1, old = net.get( 'h1', 's1' ) for s in 2, 3, 1: new = net[ 's%d' % s ] port = randint( 10, 20 ) print '* Moving', h1, 'from', old, 'to', new, 'port', port hintf, sintf = moveHost( h1, old, new, newPort=port ) print '*', hintf, 'is now connected to', sintf print '* Clearing out old flows' for sw in net.switches: sw.dpctl( 'del-flows' ) print '* New network:' printConnections( net.switches ) print '* Testing connectivity:' net.pingAll() old = new net.stop() if __name__ == '__main__': mobilityTest()
4,198
30.103704
71
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/multilink.py
#!/usr/bin/python """ This is a simple example that demonstrates multiple links between nodes. """ from mininet.cli import CLI from mininet.log import setLogLevel from mininet.net import Mininet from mininet.topo import Topo def runMultiLink(): "Create and run multiple link network" topo = simpleMultiLinkTopo( n=2 ) net = Mininet( topo=topo ) net.start() CLI( net ) net.stop() class simpleMultiLinkTopo( Topo ): "Simple topology with multiple links" def __init__( self, n, **kwargs ): Topo.__init__( self, **kwargs ) h1, h2 = self.addHost( 'h1' ), self.addHost( 'h2' ) s1 = self.addSwitch( 's1' ) for _ in range( n ): self.addLink( s1, h1 ) self.addLink( s1, h2 ) if __name__ == '__main__': setLogLevel( 'info' ) runMultiLink()
834
21.567568
59
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/scratchnetuser.py
#!/usr/bin/python """ Build a simple network from scratch, using mininet primitives. This is more complicated than using the higher-level classes, but it exposes the configuration details and allows customization. For most tasks, the higher-level API will be preferable. This version uses the user datapath and an explicit control network. """ from mininet.net import Mininet from mininet.node import Node from mininet.link import Link from mininet.log import setLogLevel, info def linkIntfs( node1, node2 ): "Create link from node1 to node2 and return intfs" link = Link( node1, node2 ) return link.intf1, link.intf2 def scratchNetUser( cname='controller', cargs='ptcp:' ): "Create network from scratch using user switch." # It's not strictly necessary for the controller and switches # to be in separate namespaces. For performance, they probably # should be in the root namespace. However, it's interesting to # see how they could work even if they are in separate namespaces. info( '*** Creating Network\n' ) controller = Node( 'c0' ) switch = Node( 's0') h0 = Node( 'h0' ) h1 = Node( 'h1' ) cintf, sintf = linkIntfs( controller, switch ) h0intf, sintf1 = linkIntfs( h0, switch ) h1intf, sintf2 = linkIntfs( h1, switch ) info( '*** Configuring control network\n' ) controller.setIP( '10.0.123.1/24', intf=cintf ) switch.setIP( '10.0.123.2/24', intf=sintf) info( '*** Configuring hosts\n' ) h0.setIP( '192.168.123.1/24', intf=h0intf ) h1.setIP( '192.168.123.2/24', intf=h1intf ) info( '*** Network state:\n' ) for node in controller, switch, h0, h1: info( str( node ) + '\n' ) info( '*** Starting controller and user datapath\n' ) controller.cmd( cname + ' ' + cargs + '&' ) switch.cmd( 'ifconfig lo 127.0.0.1' ) intfs = [ str( i ) for i in sintf1, sintf2 ] switch.cmd( 'ofdatapath -i ' + ','.join( intfs ) + ' ptcp: &' ) switch.cmd( 'ofprotocol tcp:' + controller.IP() + ' tcp:localhost &' ) info( '*** Running test\n' ) h0.cmdPrint( 'ping -c1 ' + h1.IP() ) info( '*** Stopping network\n' ) controller.cmd( 'kill %' + cname ) switch.cmd( 'kill %ofdatapath' ) switch.cmd( 'kill %ofprotocol' ) switch.deleteIntfs() info( '\n' ) if __name__ == '__main__': setLogLevel( 'info' ) info( '*** Scratch network demo (user datapath)\n' ) Mininet.init() scratchNetUser()
2,455
32.189189
74
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/simpleperf.py
#!/usr/bin/python """ Simple example of setting network and CPU parameters NOTE: link params limit BW, add latency, and loss. There is a high chance that pings WILL fail and that iperf will hang indefinitely if the TCP handshake fails to complete. """ from mininet.topo import Topo from mininet.net import Mininet from mininet.node import CPULimitedHost from mininet.link import TCLink from mininet.util import dumpNodeConnections from mininet.log import setLogLevel from sys import argv class SingleSwitchTopo(Topo): "Single switch connected to n hosts." def __init__(self, n=2, lossy=True, **opts): Topo.__init__(self, **opts) switch = self.addSwitch('s1') for h in range(n): # Each host gets 50%/n of system CPU host = self.addHost('h%s' % (h + 1), cpu=.5 / n) if lossy: # 10 Mbps, 5ms delay, 10% packet loss self.addLink(host, switch, bw=10, delay='5ms', loss=10, use_htb=True) else: # 10 Mbps, 5ms delay, no packet loss self.addLink(host, switch, bw=10, delay='5ms', loss=0, use_htb=True) def perfTest( lossy=True ): "Create network and run simple performance test" topo = SingleSwitchTopo( n=4, lossy=lossy ) net = Mininet( topo=topo, host=CPULimitedHost, link=TCLink, autoStaticArp=True ) net.start() print "Dumping host connections" dumpNodeConnections(net.hosts) print "Testing bandwidth between h1 and h4" h1, h4 = net.getNodeByName('h1', 'h4') net.iperf( ( h1, h4 ), l4Type='UDP' ) net.stop() if __name__ == '__main__': setLogLevel( 'info' ) # Prevent test_simpleperf from failing due to packet loss perfTest( lossy=( 'testmode' not in argv ) )
1,888
31.568966
71
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/vlanhost.py
#!/usr/bin/env python """ vlanhost.py: Host subclass that uses a VLAN tag for the default interface. Dependencies: This class depends on the "vlan" package $ sudo apt-get install vlan Usage (example uses VLAN ID=1000): From the command line: sudo mn --custom vlanhost.py --host vlan,vlan=1000 From a script (see exampleUsage function below): from functools import partial from vlanhost import VLANHost .... host = partial( VLANHost, vlan=1000 ) net = Mininet( host=host, ... ) Directly running this script: sudo python vlanhost.py 1000 """ from mininet.node import Host from mininet.topo import Topo from mininet.util import quietRun from mininet.log import error class VLANHost( Host ): "Host connected to VLAN interface" def config( self, vlan=100, **params ): """Configure VLANHost according to (optional) parameters: vlan: VLAN ID for default interface""" r = super( VLANHost, self ).config( **params ) intf = self.defaultIntf() # remove IP from default, "physical" interface self.cmd( 'ifconfig %s inet 0' % intf ) # create VLAN interface self.cmd( 'vconfig add %s %d' % ( intf, vlan ) ) # assign the host's IP to the VLAN interface self.cmd( 'ifconfig %s.%d inet %s' % ( intf, vlan, params['ip'] ) ) # update the intf name and host's intf map newName = '%s.%d' % ( intf, vlan ) # update the (Mininet) interface to refer to VLAN interface name intf.name = newName # add VLAN interface to host's name to intf map self.nameToIntf[ newName ] = intf return r hosts = { 'vlan': VLANHost } def exampleAllHosts( vlan ): """Simple example of how VLANHost can be used in a script""" # This is where the magic happens... host = partial( VLANHost, vlan=vlan ) # vlan (type: int): VLAN ID to be used by all hosts # Start a basic network using our VLANHost topo = SingleSwitchTopo( k=2 ) net = Mininet( host=host, topo=topo ) net.start() CLI( net ) net.stop() # pylint: disable=arguments-differ class VLANStarTopo( Topo ): """Example topology that uses host in multiple VLANs The topology has a single switch. There are k VLANs with n hosts in each, all connected to the single switch. There are also n hosts that are not in any VLAN, also connected to the switch.""" def build( self, k=2, n=2, vlanBase=100 ): s1 = self.addSwitch( 's1' ) for i in range( k ): vlan = vlanBase + i for j in range(n): name = 'h%d-%d' % ( j+1, vlan ) h = self.addHost( name, cls=VLANHost, vlan=vlan ) self.addLink( h, s1 ) for j in range( n ): h = self.addHost( 'h%d' % (j+1) ) self.addLink( h, s1 ) def exampleCustomTags(): """Simple example that exercises VLANStarTopo""" net = Mininet( topo=VLANStarTopo() ) net.start() CLI( net ) net.stop() if __name__ == '__main__': import sys from functools import partial from mininet.net import Mininet from mininet.cli import CLI from mininet.topo import SingleSwitchTopo from mininet.log import setLogLevel setLogLevel( 'info' ) if not quietRun( 'which vconfig' ): error( "Cannot find command 'vconfig'\nThe package", "'vlan' is required in Ubuntu or Debian,", "or 'vconfig' in Fedora\n" ) exit() if len( sys.argv ) >= 2: exampleAllHosts( vlan=int( sys.argv[ 1 ] ) ) else: exampleCustomTags()
3,679
28.44
75
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/treeping64.py
#!/usr/bin/python "Create a 64-node tree network, and test connectivity using ping." from mininet.log import setLogLevel from mininet.node import UserSwitch, OVSKernelSwitch # , KernelSwitch from mininet.topolib import TreeNet def treePing64(): "Run ping test on 64-node tree networks." results = {} switches = { # 'reference kernel': KernelSwitch, 'reference user': UserSwitch, 'Open vSwitch kernel': OVSKernelSwitch } for name in switches: print "*** Testing", name, "datapath" switch = switches[ name ] network = TreeNet( depth=2, fanout=8, switch=switch ) result = network.run( network.pingAll ) results[ name ] = result print print "*** Tree network ping results:" for name in switches: print "%s: %d%% packet loss" % ( name, results[ name ] ) print if __name__ == '__main__': setLogLevel( 'info' ) treePing64()
950
27.818182
70
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/numberedports.py
#!/usr/bin/python """ Create a network with 5 hosts, numbered 1-4 and 9. Validate that the port numbers match to the interface name, and that the ovs ports match the mininet ports. """ from mininet.net import Mininet from mininet.node import Controller from mininet.log import setLogLevel, info, warn 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 testPortNumbering(): """Test port numbering: Create a network with 5 hosts (using Mininet's mid-level API) and check that implicit and explicit port numbering works as expected.""" net = Mininet( controller=Controller ) info( '*** Adding controller\n' ) net.addController( 'c0' ) info( '*** Adding hosts\n' ) h1 = net.addHost( 'h1', ip='10.0.0.1' ) h2 = net.addHost( 'h2', ip='10.0.0.2' ) h3 = net.addHost( 'h3', ip='10.0.0.3' ) h4 = net.addHost( 'h4', ip='10.0.0.4' ) h5 = net.addHost( 'h5', ip='10.0.0.5' ) info( '*** Adding switch\n' ) s1 = net.addSwitch( 's1' ) info( '*** Creating links\n' ) # host 1-4 connect to ports 1-4 on the switch net.addLink( h1, s1 ) net.addLink( h2, s1 ) net.addLink( h3, s1 ) net.addLink( h4, s1 ) # specify a different port to connect host 5 to on the switch. net.addLink( h5, s1, port1=1, port2= 9) info( '*** Starting network\n' ) net.start() # print the interfaces and their port numbers info( '\n*** printing and validating the ports ' 'running on each interface\n' ) for intfs in s1.intfList(): if not intfs.name == "lo": info( intfs, ': ', s1.ports[intfs], '\n' ) info( 'Validating that', intfs, 'is actually on port', s1.ports[intfs], '... ' ) if validatePort( s1, intfs ): info( 'Validated.\n' ) print '\n' # test the network with pingall net.pingAll() print '\n' info( '*** Stopping network' ) net.stop() if __name__ == '__main__': setLogLevel( 'info' ) testPortNumbering()
2,330
28.1375
72
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/controllers2.py
#!/usr/bin/python """ This example creates a multi-controller network from semi-scratch by using the net.add*() API and manually starting the switches and controllers. This is the "mid-level" API, which is an alternative to the "high-level" Topo() API which supports parametrized topology classes. Note that one could also create a custom switch class and pass it into the Mininet() constructor. """ from mininet.net import Mininet from mininet.node import Controller, OVSSwitch from mininet.cli import CLI from mininet.log import setLogLevel def multiControllerNet(): "Create a network from semi-scratch with multiple controllers." net = Mininet( controller=Controller, switch=OVSSwitch ) print "*** Creating (reference) controllers" c1 = net.addController( 'c1', port=6633 ) c2 = net.addController( 'c2', port=6634 ) print "*** Creating switches" s1 = net.addSwitch( 's1' ) s2 = net.addSwitch( 's2' ) print "*** Creating hosts" hosts1 = [ net.addHost( 'h%d' % n ) for n in 3, 4 ] hosts2 = [ net.addHost( 'h%d' % n ) for n in 5, 6 ] print "*** Creating links" for h in hosts1: net.addLink( s1, h ) for h in hosts2: net.addLink( s2, h ) net.addLink( s1, s2 ) print "*** Starting network" net.build() c1.start() c2.start() s1.start( [ c1 ] ) s2.start( [ c2 ] ) print "*** Testing network" net.pingAll() print "*** Running CLI" CLI( net ) print "*** Stopping network" net.stop() if __name__ == '__main__': setLogLevel( 'info' ) # for CLI output multiControllerNet()
1,612
25.016129
76
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/bind.py
#!/usr/bin/python """ bind.py: Bind mount example This creates hosts with private directories that the user specifies. These hosts may have persistent directories that will be available across multiple mininet session, or temporary directories that will only last for one mininet session. To specify a persistent directory, add a tuple to a list of private directories: [ ( 'directory to be mounted on', 'directory to be mounted' ) ] String expansion may be used to create a directory template for each host. To do this, add a %(name)s in place of the host name when creating your list of directories: [ ( '/var/run', '/tmp/%(name)s/var/run' ) ] If no persistent directory is specified, the directories will default to temporary private directories. To do this, simply create a list of directories to be made private. A tmpfs will then be mounted on them. You may use both temporary and persistent directories at the same time. In the following privateDirs string, each host will have a persistent directory in the root filesystem at "/tmp/(hostname)/var/run" mounted on "/var/run". Each host will also have a temporary private directory mounted on "/var/log". [ ( '/var/run', '/tmp/%(name)s/var/run' ), '/var/log' ] This example has both persistent directories mounted on '/var/log' and '/var/run'. It also has a temporary private directory mounted on '/var/mn' """ from mininet.net import Mininet from mininet.node import Host from mininet.cli import CLI from mininet.topo import SingleSwitchTopo from mininet.log import setLogLevel, info from functools import partial # Sample usage def testHostWithPrivateDirs(): "Test bind mounts" topo = SingleSwitchTopo( 10 ) privateDirs = [ ( '/var/log', '/tmp/%(name)s/var/log' ), ( '/var/run', '/tmp/%(name)s/var/run' ), '/var/mn' ] host = partial( Host, privateDirs=privateDirs ) net = Mininet( topo=topo, host=host ) net.start() directories = [ directory[ 0 ] if isinstance( directory, tuple ) else directory for directory in privateDirs ] info( 'Private Directories:', directories, '\n' ) CLI( net ) net.stop() if __name__ == '__main__': setLogLevel( 'info' ) testHostWithPrivateDirs() info( 'Done.\n')
2,310
32.985294
69
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/clustercli.py
#!/usr/bin/python "CLI for Mininet Cluster Edition prototype demo" from mininet.cli import CLI from mininet.log import output, error # pylint: disable=global-statement nx, graphviz_layout, plt = None, None, None # Will be imported on demand class ClusterCLI( CLI ): "CLI with additional commands for Cluster Edition demo" @staticmethod def colorsFor( seq ): "Return a list of background colors for a sequence" colors = [ 'red', 'lightgreen', 'cyan', 'yellow', 'orange', 'magenta', 'pink', 'grey', 'brown', 'white' ] slen, clen = len( seq ), len( colors ) reps = max( 1, slen / clen ) colors = colors * reps colors = colors[ 0 : slen ] return colors def do_plot( self, _line ): "Plot topology colored by node placement" # Import networkx if needed global nx, plt if not nx: try: # pylint: disable=import-error import networkx nx = networkx # satisfy pylint from matplotlib import pyplot plt = pyplot # satisfiy pylint import pygraphviz assert pygraphviz # silence pyflakes # pylint: enable=import-error except ImportError: error( 'plot requires networkx, matplotlib and pygraphviz - ' 'please install them and try again\n' ) return # Make a networkx Graph g = nx.Graph() mn = self.mn servers, hosts, switches = mn.servers, mn.hosts, mn.switches nodes = hosts + switches g.add_nodes_from( nodes ) links = [ ( link.intf1.node, link.intf2.node ) for link in self.mn.links ] g.add_edges_from( links ) # Pick some shapes and colors # shapes = hlen * [ 's' ] + slen * [ 'o' ] color = dict( zip( servers, self.colorsFor( servers ) ) ) # Plot it! pos = nx.graphviz_layout( g ) opts = { 'ax': None, 'font_weight': 'bold', 'width': 2, 'edge_color': 'darkblue' } hcolors = [ color[ getattr( h, 'server', 'localhost' ) ] for h in hosts ] scolors = [ color[ getattr( s, 'server', 'localhost' ) ] for s in switches ] nx.draw_networkx( g, pos=pos, nodelist=hosts, node_size=800, label='host', node_color=hcolors, node_shape='s', **opts ) nx.draw_networkx( g, pos=pos, nodelist=switches, node_size=1000, node_color=scolors, node_shape='o', **opts ) # Get rid of axes, add title, and show fig = plt.gcf() ax = plt.gca() ax.get_xaxis().set_visible( False ) ax.get_yaxis().set_visible( False ) fig.canvas.set_window_title( 'Mininet') plt.title( 'Node Placement', fontweight='bold' ) plt.show() def do_status( self, _line ): "Report on node shell status" nodes = self.mn.hosts + self.mn.switches for node in nodes: node.shell.poll() exited = [ node for node in nodes if node.shell.returncode is not None ] if exited: for node in exited: output( '%s has exited with code %d\n' % ( node, node.shell.returncode ) ) else: output( 'All nodes are still running.\n' ) def do_placement( self, _line ): "Describe node placement" mn = self.mn nodes = mn.hosts + mn.switches + mn.controllers for server in mn.servers: names = [ n.name for n in nodes if hasattr( n, 'server' ) and n.server == server ] output( '%s: %s\n' % ( server, ' '.join( names ) ) )
3,875
37.376238
77
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/README.md
Mininet Examples ======================================================== These examples are intended to help you get started using Mininet's Python API. ======================================================== #### baresshd.py: This example uses Mininet's medium-level API to create an sshd process running in a namespace. Doesn't use OpenFlow. #### bind.py: This example shows how you can create private directories for each node in a Mininet topology. #### cluster.py: This example contains all of the code for experimental cluster edition. Remote classes and MininetCluster can be imported from here to create a topology with nodes on remote machines. #### clusterSanity.py: This example runs cluster edition locally as a sanity check to test basic functionality. #### clustercli.py: This example contains a CLI for experimental cluster edition. #### clusterdemo.py: This example is a basic demo of cluster edition on 3 servers with a tree topology of depth 3 and fanout 3. #### consoles.py: This example creates a grid of console windows, one for each node, and allows interaction with and monitoring of each console, including graphical monitoring. #### controllers.py: This example creates a network with multiple controllers, by using a custom `Switch()` subclass. #### controllers2.py: This example creates a network with multiple controllers by creating an empty network, adding nodes to it, and manually starting the switches. #### controlnet.py: This examples shows how you can model the control network as well as the data network, by actually creating two Mininet objects. #### cpu.py: This example tests iperf bandwidth for varying CPU limits. #### emptynet.py: This example demonstrates creating an empty network (i.e. with no topology object) and adding nodes to it. #### hwintf.py: This example shows how to add an interface (for example a real hardware interface) to a network after the network is created. #### intfoptions.py: This example reconfigures a TCIntf during runtime with different traffic control commands to test bandwidth, loss, and delay. #### limit.py: This example shows how to use link and CPU limits. #### linearbandwidth.py: This example shows how to create a custom topology programatically by subclassing Topo, and how to run a series of tests on it. #### linuxrouter.py: This example shows how to create and configure a router in Mininet that uses Linux IP forwarding. #### miniedit.py: This example demonstrates creating a network via a graphical editor. #### mobility.py: This example demonstrates detaching an interface from one switch and attaching it another as a basic way to move a host around a network. #### multiLink.py: This example demonstrates the creation of multiple links between nodes using a custom Topology class. #### multiping.py: This example demonstrates one method for monitoring output from multiple hosts, using `node.monitor()`. #### multipoll.py: This example demonstrates monitoring output files from multiple hosts. #### multitest.py: This example creates a network and runs multiple tests on it. #### nat.py: This example shows how to connect a Mininet network to the Internet using NAT. It also answers the eternal question "why can't I ping `google.com`?" #### natnet.py: This example demonstrates how to create a network using a NAT node to connect hosts to the internet. #### numberedports.py: This example verifies the mininet ofport numbers match up to the ovs port numbers. It also verifies that the port numbers match up to the interface numbers #### popen.py: This example monitors a number of hosts using `host.popen()` and `pmonitor()`. #### popenpoll.py: This example demonstrates monitoring output from multiple hosts using the `node.popen()` interface (which returns `Popen` objects) and `pmonitor()`. #### scratchnet.py, scratchnetuser.py: These two examples demonstrate how to create a network by using the lowest- level Mininet functions. Generally the higher-level API is easier to use, but scratchnet shows what is going on behind the scenes. #### simpleperf.py: A simple example of configuring network and CPU bandwidth limits. #### sshd.py: This example shows how to run an `sshd` process in each host, allowing you to log in via `ssh`. This requires connecting the Mininet data network to an interface in the root namespace (generaly the control network already lives in the root namespace, so it does not need to be explicitly connected.) #### tree1024.py: This example attempts to create a 1024-host network, and then runs the CLI on it. It may run into scalability limits, depending on available memory and `sysctl` configuration (see `INSTALL`.) #### treeping64.py: This example creates a 64-host tree network, and attempts to check full connectivity using `ping`, for different switch/datapath types. #### vlanhost.py: An example of how to subclass Host to use a VLAN on its primary interface.
4,965
26.588889
82
md
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/baresshd.py
#!/usr/bin/python "This example doesn't use OpenFlow, but attempts to run sshd in a namespace." import sys from mininet.node import Host from mininet.util import ensureRoot, waitListening ensureRoot() timeout = 5 print "*** Creating nodes" h1 = Host( 'h1' ) root = Host( 'root', inNamespace=False ) print "*** Creating links" h1.linkTo( root ) print h1 print "*** Configuring nodes" h1.setIP( '10.0.0.1', 8 ) root.setIP( '10.0.0.2', 8 ) print "*** Creating banner file" f = open( '/tmp/%s.banner' % h1.name, 'w' ) f.write( 'Welcome to %s at %s\n' % ( h1.name, h1.IP() ) ) f.close() print "*** Running sshd" cmd = '/usr/sbin/sshd -o UseDNS=no -u0 -o "Banner /tmp/%s.banner"' % h1.name # add arguments from the command line if len( sys.argv ) > 1: cmd += ' ' + ' '.join( sys.argv[ 1: ] ) h1.cmd( cmd ) listening = waitListening( server=h1, port=22, timeout=timeout ) if listening: print "*** You may now ssh into", h1.name, "at", h1.IP() else: print ( "*** Warning: after %s seconds, %s is not listening on port 22" % ( timeout, h1.name ) )
1,074
23.431818
77
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/scratchnet.py
#!/usr/bin/python """ Build a simple network from scratch, using mininet primitives. This is more complicated than using the higher-level classes, but it exposes the configuration details and allows customization. For most tasks, the higher-level API will be preferable. """ from mininet.net import Mininet from mininet.node import Node from mininet.link import Link from mininet.log import setLogLevel, info from mininet.util import quietRun from time import sleep def scratchNet( cname='controller', cargs='-v ptcp:' ): "Create network from scratch using Open vSwitch." info( "*** Creating nodes\n" ) controller = Node( 'c0', inNamespace=False ) switch = Node( 's0', inNamespace=False ) h0 = Node( 'h0' ) h1 = Node( 'h1' ) info( "*** Creating links\n" ) Link( h0, switch ) Link( h1, switch ) info( "*** Configuring hosts\n" ) h0.setIP( '192.168.123.1/24' ) h1.setIP( '192.168.123.2/24' ) info( str( h0 ) + '\n' ) info( str( h1 ) + '\n' ) info( "*** Starting network using Open vSwitch\n" ) controller.cmd( cname + ' ' + cargs + '&' ) switch.cmd( 'ovs-vsctl del-br dp0' ) switch.cmd( 'ovs-vsctl add-br dp0' ) for intf in switch.intfs.values(): print switch.cmd( 'ovs-vsctl add-port dp0 %s' % intf ) # Note: controller and switch are in root namespace, and we # can connect via loopback interface switch.cmd( 'ovs-vsctl set-controller dp0 tcp:127.0.0.1:6633' ) info( '*** Waiting for switch to connect to controller' ) while 'is_connected' not in quietRun( 'ovs-vsctl show' ): sleep( 1 ) info( '.' ) info( '\n' ) info( "*** Running test\n" ) h0.cmdPrint( 'ping -c1 ' + h1.IP() ) info( "*** Stopping network\n" ) controller.cmd( 'kill %' + cname ) switch.cmd( 'ovs-vsctl del-br dp0' ) switch.deleteIntfs() info( '\n' ) if __name__ == '__main__': setLogLevel( 'info' ) info( '*** Scratch network demo (kernel datapath)\n' ) Mininet.init() scratchNet()
2,032
28.463768
67
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/linuxrouter.py
#!/usr/bin/python """ linuxrouter.py: Example network with Linux IP router This example converts a Node into a router using IP forwarding already built into Linux. The example topology creates a router and three IP subnets: - 192.168.1.0/24 (r0-eth1, IP: 192.168.1.1) - 172.16.0.0/12 (r0-eth2, IP: 172.16.0.1) - 10.0.0.0/8 (r0-eth3, IP: 10.0.0.1) Each subnet consists of a single host connected to a single switch: r0-eth1 - s1-eth1 - h1-eth0 (IP: 192.168.1.100) r0-eth2 - s2-eth1 - h2-eth0 (IP: 172.16.0.100) r0-eth3 - s3-eth1 - h3-eth0 (IP: 10.0.0.100) The example relies on default routing entries that are automatically created for each router interface, as well as 'defaultRoute' parameters for the host interfaces. Additional routes may be added to the router or hosts by executing 'ip route' or 'route' commands on the router or hosts. """ from mininet.topo import Topo from mininet.net import Mininet from mininet.node import Node from mininet.log import setLogLevel, info from mininet.cli import CLI class LinuxRouter( Node ): "A Node with IP forwarding enabled." def config( self, **params ): super( LinuxRouter, self).config( **params ) # Enable forwarding on the router self.cmd( 'sysctl net.ipv4.ip_forward=1' ) def terminate( self ): self.cmd( 'sysctl net.ipv4.ip_forward=0' ) super( LinuxRouter, self ).terminate() class NetworkTopo( Topo ): "A LinuxRouter connecting three IP subnets" def build( self, **_opts ): defaultIP = '192.168.1.1/24' # IP address for r0-eth1 router = self.addNode( 'r0', cls=LinuxRouter, ip=defaultIP ) s1, s2, s3 = [ self.addSwitch( s ) for s in 's1', 's2', 's3' ] self.addLink( s1, router, intfName2='r0-eth1', params2={ 'ip' : defaultIP } ) # for clarity self.addLink( s2, router, intfName2='r0-eth2', params2={ 'ip' : '172.16.0.1/12' } ) self.addLink( s3, router, intfName2='r0-eth3', params2={ 'ip' : '10.0.0.1/8' } ) h1 = self.addHost( 'h1', ip='192.168.1.100/24', defaultRoute='via 192.168.1.1' ) h2 = self.addHost( 'h2', ip='172.16.0.100/12', defaultRoute='via 172.16.0.1' ) h3 = self.addHost( 'h3', ip='10.0.0.100/8', defaultRoute='via 10.0.0.1' ) for h, s in [ (h1, s1), (h2, s2), (h3, s3) ]: self.addLink( h, s ) def run(): "Test linux router" topo = NetworkTopo() net = Mininet( topo=topo ) # controller is used by s1-s3 net.start() info( '*** Routing Table on Router:\n' ) print net[ 'r0' ].cmd( 'route' ) CLI( net ) net.stop() if __name__ == '__main__': setLogLevel( 'info' ) run()
2,826
30.411111
70
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/controllers.py
#!/usr/bin/python """ Create a network where different switches are connected to different controllers, by creating a custom Switch() subclass. """ from mininet.net import Mininet from mininet.node import OVSSwitch, Controller, RemoteController from mininet.topolib import TreeTopo from mininet.log import setLogLevel from mininet.cli import CLI setLogLevel( 'info' ) # Two local and one "external" controller (which is actually c0) # Ignore the warning message that the remote isn't (yet) running c0 = Controller( 'c0', port=6633 ) c1 = Controller( 'c1', port=6634 ) c2 = RemoteController( 'c2', ip='127.0.0.1', port=6633 ) cmap = { 's1': c0, 's2': c1, 's3': c2 } class MultiSwitch( OVSSwitch ): "Custom Switch() subclass that connects to different controllers" def start( self, controllers ): return OVSSwitch.start( self, [ cmap[ self.name ] ] ) topo = TreeTopo( depth=2, fanout=2 ) net = Mininet( topo=topo, switch=MultiSwitch, build=False ) for c in [ c0, c1 ]: net.addController(c) net.build() net.start() CLI( net ) net.stop()
1,061
27.702703
69
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/__init__.py
""" Mininet Examples See README for details """
48
8.8
22
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/limit.py
#!/usr/bin/python """ limit.py: example of using link and CPU limits """ from mininet.net import Mininet from mininet.link import TCIntf from mininet.node import CPULimitedHost from mininet.topolib import TreeTopo from mininet.util import custom, quietRun from mininet.log import setLogLevel, info def testLinkLimit( net, bw ): "Run bandwidth limit test" info( '*** Testing network %.2f Mbps bandwidth limit\n' % bw ) net.iperf() def limit( bw=10, cpu=.1 ): """Example/test of link and CPU bandwidth limits bw: interface bandwidth limit in Mbps cpu: cpu limit as fraction of overall CPU time""" intf = custom( TCIntf, bw=bw ) myTopo = TreeTopo( depth=1, fanout=2 ) for sched in 'rt', 'cfs': info( '*** Testing with', sched, 'bandwidth limiting\n' ) if sched == 'rt': release = quietRun( 'uname -r' ).strip('\r\n') output = quietRun( 'grep CONFIG_RT_GROUP_SCHED /boot/config-%s' % release ) if output == '# CONFIG_RT_GROUP_SCHED is not set\n': info( '*** RT Scheduler is not enabled in your kernel. ' 'Skipping this test\n' ) continue host = custom( CPULimitedHost, sched=sched, cpu=cpu ) net = Mininet( topo=myTopo, intf=intf, host=host ) net.start() testLinkLimit( net, bw=bw ) net.runCpuLimitTest( cpu=cpu ) net.stop() def verySimpleLimit( bw=150 ): "Absurdly simple limiting test" intf = custom( TCIntf, bw=bw ) net = Mininet( intf=intf ) h1, h2 = net.addHost( 'h1' ), net.addHost( 'h2' ) net.addLink( h1, h2 ) net.start() net.pingAll() net.iperf() h1.cmdPrint( 'tc -s qdisc ls dev', h1.defaultIntf() ) h2.cmdPrint( 'tc -d class show dev', h2.defaultIntf() ) h1.cmdPrint( 'tc -s qdisc ls dev', h1.defaultIntf() ) h2.cmdPrint( 'tc -d class show dev', h2.defaultIntf() ) net.stop() if __name__ == '__main__': setLogLevel( 'info' ) limit()
2,034
32.360656
75
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/popen.py
#!/usr/bin/python """ This example monitors a number of hosts using host.popen() and pmonitor() """ from mininet.net import Mininet from mininet.node import CPULimitedHost from mininet.topo import SingleSwitchTopo from mininet.log import setLogLevel from mininet.util import custom, pmonitor def monitorhosts( hosts=5, sched='cfs' ): "Start a bunch of pings and monitor them using popen" mytopo = SingleSwitchTopo( hosts ) cpu = .5 / hosts myhost = custom( CPULimitedHost, cpu=cpu, sched=sched ) net = Mininet( topo=mytopo, host=myhost ) net.start() # Start a bunch of pings popens = {} last = net.hosts[ -1 ] for host in net.hosts: popens[ host ] = host.popen( "ping -c5 %s" % last.IP() ) last = host # Monitor them and print output for host, line in pmonitor( popens ): if host: print "<%s>: %s" % ( host.name, line.strip() ) # Done net.stop() if __name__ == '__main__': setLogLevel( 'info' ) monitorhosts( hosts=5 )
1,023
26.675676
64
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/emptynet.py
#!/usr/bin/python """ This example shows how to create an empty Mininet object (without a topology object) and add nodes to it manually. """ from mininet.net import Mininet from mininet.node import Controller from mininet.cli import CLI from mininet.log import setLogLevel, info def emptyNet(): "Create an empty network and add nodes to it." net = Mininet( controller=Controller ) info( '*** Adding controller\n' ) net.addController( 'c0' ) info( '*** Adding hosts\n' ) h1 = net.addHost( 'h1', ip='10.0.0.1' ) h2 = net.addHost( 'h2', ip='10.0.0.2' ) info( '*** Adding switch\n' ) s3 = net.addSwitch( 's3' ) info( '*** Creating links\n' ) net.addLink( h1, s3 ) net.addLink( h2, s3 ) info( '*** Starting network\n') net.start() info( '*** Running CLI\n' ) CLI( net ) info( '*** Stopping network' ) net.stop() if __name__ == '__main__': setLogLevel( 'info' ) emptyNet()
960
20.355556
57
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/cpu.py
#!/usr/bin/python """ cpu.py: test iperf bandwidth for varying cpu limits """ from mininet.net import Mininet from mininet.node import CPULimitedHost from mininet.topolib import TreeTopo from mininet.util import custom, waitListening from mininet.log import setLogLevel, info def bwtest( cpuLimits, period_us=100000, seconds=5 ): """Example/test of link and CPU bandwidth limits cpu: cpu limit as fraction of overall CPU time""" topo = TreeTopo( depth=1, fanout=2 ) results = {} for sched in 'rt', 'cfs': print '*** Testing with', sched, 'bandwidth limiting' for cpu in cpuLimits: host = custom( CPULimitedHost, sched=sched, period_us=period_us, cpu=cpu ) try: net = Mininet( topo=topo, host=host ) # pylint: disable=bare-except except: info( '*** Skipping host %s\n' % sched ) break net.start() net.pingAll() hosts = [ net.getNodeByName( h ) for h in topo.hosts() ] client, server = hosts[ 0 ], hosts[ -1 ] server.cmd( 'iperf -s -p 5001 &' ) waitListening( client, server, 5001 ) result = client.cmd( 'iperf -yc -t %s -c %s' % ( seconds, server.IP() ) ).split( ',' ) bps = float( result[ -1 ] ) server.cmdPrint( 'kill %iperf' ) net.stop() updated = results.get( sched, [] ) updated += [ ( cpu, bps ) ] results[ sched ] = updated return results def dump( results ): "Dump results" fmt = '%s\t%s\t%s' print print fmt % ( 'sched', 'cpu', 'client MB/s' ) print for sched in sorted( results.keys() ): entries = results[ sched ] for cpu, bps in entries: pct = '%.2f%%' % ( cpu * 100 ) mbps = bps / 1e6 print fmt % ( sched, pct, mbps ) if __name__ == '__main__': setLogLevel( 'info' ) limits = [ .45, .4, .3, .2, .1 ] out = bwtest( limits ) dump( out )
2,119
27.648649
68
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/hwintf.py
#!/usr/bin/python """ This example shows how to add an interface (for example a real hardware interface) to a network after the network is created. """ import re import sys from mininet.cli import CLI from mininet.log import setLogLevel, info, error from mininet.net import Mininet from mininet.link import Intf from mininet.topolib import TreeTopo from mininet.util import quietRun def checkIntf( intf ): "Make sure intf exists and is not configured." config = quietRun( 'ifconfig %s 2>/dev/null' % intf, shell=True ) if not config: error( 'Error:', intf, 'does not exist!\n' ) exit( 1 ) ips = re.findall( r'\d+\.\d+\.\d+\.\d+', config ) if ips: error( 'Error:', intf, 'has an IP address,' 'and is probably in use!\n' ) exit( 1 ) if __name__ == '__main__': setLogLevel( 'info' ) # try to get hw intf from the command line; by default, use eth1 intfName = sys.argv[ 1 ] if len( sys.argv ) > 1 else 'eth1' info( '*** Connecting to hw intf: %s' % intfName ) info( '*** Checking', intfName, '\n' ) checkIntf( intfName ) info( '*** Creating network\n' ) net = Mininet( topo=TreeTopo( depth=1, fanout=2 ) ) switch = net.switches[ 0 ] info( '*** Adding hardware interface', intfName, 'to switch', switch.name, '\n' ) _intf = Intf( intfName, node=switch ) info( '*** Note: you may need to reconfigure the interfaces for ' 'the Mininet hosts:\n', net.hosts, '\n' ) net.start() CLI( net ) net.stop()
1,549
27.703704
69
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/dockerhosts.py
#!/usr/bin/python """ This example shows how to create a simple network and how to create docker containers (based on existing images) to it. """ from mininet.net import Containernet from mininet.node import Controller, Docker, OVSSwitch from mininet.cli import CLI from mininet.log import setLogLevel, info from mininet.link import TCLink, Link def topology(): "Create a network with some docker containers acting as hosts." net = Containernet(controller=Controller) info('*** Adding controller\n') net.addController('c0') info('*** Adding hosts\n') h1 = net.addHost('h1') h2 = net.addHost('h2') info('*** Adding docker containers\n') d1 = net.addDocker('d1', ip='10.0.0.251', dimage="ubuntu:trusty") d2 = net.addDocker('d2', ip='10.0.0.252', dimage="ubuntu:trusty", cpu_period=50000, cpu_quota=25000) d3 = net.addHost( 'd3', ip='11.0.0.253', cls=Docker, dimage="ubuntu:trusty", cpu_shares=20) d5 = net.addDocker('d5', dimage="ubuntu:trusty", volumes=["/:/mnt/vol1:rw"]) info('*** Adding switch\n') s1 = net.addSwitch('s1') s2 = net.addSwitch('s2', cls=OVSSwitch) s3 = net.addSwitch('s3') info('*** Creating links\n') net.addLink(h1, s1) net.addLink(s1, d1) net.addLink(h2, s2) net.addLink(d2, s2) net.addLink(s1, s2) #net.addLink(s1, s2, cls=TCLink, delay="100ms", bw=1, loss=10) # try to add a second interface to a docker container net.addLink(d2, s3, params1={"ip": "11.0.0.254/8"}) net.addLink(d3, s3) info('*** Starting network\n') net.start() net.ping([d1, d2]) # our extended ping functionality net.ping([d1], manualdestip="10.0.0.252") net.ping([d2, d3], manualdestip="11.0.0.254") info('*** Dynamically add a container at runtime\n') d4 = net.addDocker('d4', dimage="ubuntu:trusty") # we have to specify a manual ip when we add a link at runtime net.addLink(d4, s1, params1={"ip": "10.0.0.254/8"}) # other options to do this #d4.defaultIntf().ifconfig("10.0.0.254 up") #d4.setIP("10.0.0.254") net.ping([d1], manualdestip="10.0.0.254") info('*** Running CLI\n') CLI(net) info('*** Stopping network') net.stop() if __name__ == '__main__': setLogLevel('info') topology()
2,290
27.6375
104
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/multitest.py
#!/usr/bin/python """ This example shows how to create a network and run multiple tests. For a more complicated test example, see udpbwtest.py. """ from mininet.cli import CLI from mininet.log import lg, info from mininet.net import Mininet from mininet.node import OVSKernelSwitch from mininet.topolib import TreeTopo def ifconfigTest( net ): "Run ifconfig on all hosts in net." hosts = net.hosts for host in hosts: info( host.cmd( 'ifconfig' ) ) if __name__ == '__main__': lg.setLogLevel( 'info' ) info( "*** Initializing Mininet and kernel modules\n" ) OVSKernelSwitch.setup() info( "*** Creating network\n" ) network = Mininet( TreeTopo( depth=2, fanout=2 ), switch=OVSKernelSwitch ) info( "*** Starting network\n" ) network.start() info( "*** Running ping test\n" ) network.pingAll() info( "*** Running ifconfig test\n" ) ifconfigTest( network ) info( "*** Starting CLI (type 'exit' to exit)\n" ) CLI( network ) info( "*** Stopping network\n" ) network.stop()
1,049
28.166667
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/clusterdemo.py
#!/usr/bin/python "clusterdemo.py: demo of Mininet Cluster Edition prototype" from mininet.examples.cluster import MininetCluster, SwitchBinPlacer from mininet.topolib import TreeTopo from mininet.log import setLogLevel from mininet.examples.clustercli import ClusterCLI as CLI def demo(): "Simple Demo of Cluster Mode" servers = [ 'localhost', 'ubuntu2', 'ubuntu3' ] topo = TreeTopo( depth=3, fanout=3 ) net = MininetCluster( topo=topo, servers=servers, placement=SwitchBinPlacer ) net.start() CLI( net ) net.stop() if __name__ == '__main__': setLogLevel( 'info' ) demo()
639
26.826087
68
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/multipoll.py
#!/usr/bin/python """ Simple example of sending output to multiple files and monitoring them """ from mininet.topo import SingleSwitchTopo from mininet.net import Mininet from mininet.log import setLogLevel from time import time from select import poll, POLLIN from subprocess import Popen, PIPE def monitorFiles( outfiles, seconds, timeoutms ): "Monitor set of files and return [(host, line)...]" devnull = open( '/dev/null', 'w' ) tails, fdToFile, fdToHost = {}, {}, {} for h, outfile in outfiles.iteritems(): tail = Popen( [ 'tail', '-f', outfile ], stdout=PIPE, stderr=devnull ) fd = tail.stdout.fileno() tails[ h ] = tail fdToFile[ fd ] = tail.stdout fdToHost[ fd ] = h # Prepare to poll output files readable = poll() for t in tails.values(): readable.register( t.stdout.fileno(), POLLIN ) # Run until a set number of seconds have elapsed endTime = time() + seconds while time() < endTime: fdlist = readable.poll(timeoutms) if fdlist: for fd, _flags in fdlist: f = fdToFile[ fd ] host = fdToHost[ fd ] # Wait for a line of output line = f.readline().strip() yield host, line else: # If we timed out, return nothing yield None, '' for t in tails.values(): t.terminate() devnull.close() # Not really necessary def monitorTest( N=3, seconds=3 ): "Run pings and monitor multiple hosts" topo = SingleSwitchTopo( N ) net = Mininet( topo ) net.start() hosts = net.hosts print "Starting test..." server = hosts[ 0 ] outfiles, errfiles = {}, {} for h in hosts: # Create and/or erase output files outfiles[ h ] = '/tmp/%s.out' % h.name errfiles[ h ] = '/tmp/%s.err' % h.name h.cmd( 'echo >', outfiles[ h ] ) h.cmd( 'echo >', errfiles[ h ] ) # Start pings h.cmdPrint('ping', server.IP(), '>', outfiles[ h ], '2>', errfiles[ h ], '&' ) print "Monitoring output for", seconds, "seconds" for h, line in monitorFiles( outfiles, seconds, timeoutms=500 ): if h: print '%s: %s' % ( h.name, line ) for h in hosts: h.cmd('kill %ping') net.stop() if __name__ == '__main__': setLogLevel('info') monitorTest()
2,469
29.121951
68
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/multiping.py
#!/usr/bin/python """ multiping.py: monitor multiple sets of hosts using ping This demonstrates how one may send a simple shell script to multiple hosts and monitor their output interactively for a period= of time. """ from mininet.net import Mininet from mininet.node import Node from mininet.topo import SingleSwitchTopo from mininet.log import setLogLevel from select import poll, POLLIN from time import time def chunks( l, n ): "Divide list l into chunks of size n - thanks Stackoverflow" return [ l[ i: i + n ] for i in range( 0, len( l ), n ) ] def startpings( host, targetips ): "Tell host to repeatedly ping targets" targetips = ' '.join( targetips ) # Simple ping loop cmd = ( 'while true; do ' ' for ip in %s; do ' % targetips + ' echo -n %s "->" $ip ' % host.IP() + ' `ping -c1 -w 1 $ip | grep packets` ;' ' sleep 1;' ' done; ' 'done &' ) print ( '*** Host %s (%s) will be pinging ips: %s' % ( host.name, host.IP(), targetips ) ) host.cmd( cmd ) def multiping( netsize, chunksize, seconds): "Ping subsets of size chunksize in net of size netsize" # Create network and identify subnets topo = SingleSwitchTopo( netsize ) net = Mininet( topo=topo ) net.start() hosts = net.hosts subnets = chunks( hosts, chunksize ) # Create polling object fds = [ host.stdout.fileno() for host in hosts ] poller = poll() for fd in fds: poller.register( fd, POLLIN ) # Start pings for subnet in subnets: ips = [ host.IP() for host in subnet ] #adding bogus to generate packet loss ips.append( '10.0.0.200' ) for host in subnet: startpings( host, ips ) # Monitor output endTime = time() + seconds while time() < endTime: readable = poller.poll(1000) for fd, _mask in readable: node = Node.outToNode[ fd ] print '%s:' % node.name, node.monitor().strip() # Stop pings for host in hosts: host.cmd( 'kill %while' ) net.stop() if __name__ == '__main__': setLogLevel( 'info' ) multiping( netsize=20, chunksize=4, seconds=10 )
2,235
25.619048
67
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/clusterSanity.py
#!/usr/bin/env python ''' A sanity check for cluster edition ''' from mininet.examples.cluster import MininetCluster from mininet.log import setLogLevel from mininet.examples.clustercli import ClusterCLI as CLI from mininet.topo import SingleSwitchTopo def clusterSanity(): "Sanity check for cluster mode" topo = SingleSwitchTopo() net = MininetCluster( topo=topo ) net.start() CLI( net ) net.stop() if __name__ == '__main__': setLogLevel( 'info' ) clusterSanity()
501
20.826087
57
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/test/test_popen.py
#!/usr/bin/env python """ Test for popen.py and popenpoll.py """ import unittest import pexpect class testPopen( unittest.TestCase ): def pingTest( self, name ): "Verify that there are no dropped packets for each host" p = pexpect.spawn( 'python -m %s' % name ) opts = [ "<(h\d+)>: PING ", "<(h\d+)>: (\d+) packets transmitted, (\d+) received", pexpect.EOF ] pings = {} while True: index = p.expect( opts ) if index == 0: name = p.match.group(1) pings[ name ] = 0 elif index == 1: name = p.match.group(1) transmitted = p.match.group(2) received = p.match.group(3) # verify no dropped packets self.assertEqual( received, transmitted ) pings[ name ] += 1 else: break self.assertTrue( len(pings) > 0 ) # verify that each host has gotten results for count in pings.values(): self.assertEqual( count, 1 ) def testPopen( self ): self.pingTest( 'mininet.examples.popen' ) def testPopenPoll( self ): self.pingTest( 'mininet.examples.popenpoll' ) if __name__ == '__main__': unittest.main()
1,322
27.76087
71
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/test/test_sshd.py
#!/usr/bin/env python """ Test for sshd.py """ import unittest import pexpect from mininet.clean import sh class testSSHD( unittest.TestCase ): opts = [ '\(yes/no\)\?', 'refused', 'Welcome|\$|#', pexpect.EOF, pexpect.TIMEOUT ] def connected( self, ip ): "Log into ssh server, check banner, then exit" # Note: this test will fail if "Welcome" is not in the sshd banner # and '#'' or '$'' are not in the prompt p = pexpect.spawn( 'ssh -i /tmp/ssh/test_rsa %s' % ip, timeout=10 ) while True: index = p.expect( self.opts ) if index == 0: print p.match.group(0) p.sendline( 'yes' ) elif index == 1: return False elif index == 2: p.sendline( 'exit' ) p.wait() return True else: return False def setUp( self ): # create public key pair for testing sh( 'rm -rf /tmp/ssh' ) sh( 'mkdir /tmp/ssh' ) sh( "ssh-keygen -t rsa -P '' -f /tmp/ssh/test_rsa" ) sh( 'cat /tmp/ssh/test_rsa.pub >> /tmp/ssh/authorized_keys' ) cmd = ( 'python -m mininet.examples.sshd -D ' '-o AuthorizedKeysFile=/tmp/ssh/authorized_keys ' '-o StrictModes=no -o UseDNS=no -u0' ) # run example with custom sshd args self.net = pexpect.spawn( cmd ) self.net.expect( 'mininet>' ) def testSSH( self ): "Verify that we can ssh into all hosts (h1 to h4)" for h in range( 1, 5 ): self.assertTrue( self.connected( '10.0.0.%d' % h ) ) def tearDown( self ): self.net.sendline( 'exit' ) self.net.wait() # remove public key pair sh( 'rm -rf /tmp/ssh' ) if __name__ == '__main__': unittest.main()
1,853
29.393443
86
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/test/test_multipoll.py
#!/usr/bin/env python """ Test for multipoll.py """ import unittest import pexpect class testMultiPoll( unittest.TestCase ): def testMultiPoll( self ): "Verify that we receive one ping per second per host" p = pexpect.spawn( 'python -m mininet.examples.multipoll' ) opts = [ "\*\*\* (h\d) :" , "(h\d+): \d+ bytes from", "Monitoring output for (\d+) seconds", pexpect.EOF ] pings = {} while True: index = p.expect( opts ) if index == 0: name = p.match.group( 1 ) pings[ name ] = 0 elif index == 1: name = p.match.group( 1 ) pings[ name ] += 1 elif index == 2: seconds = int( p.match.group( 1 ) ) else: break self.assertTrue( len( pings ) > 0 ) # make sure we have received at least one ping per second for count in pings.values(): self.assertTrue( count >= seconds ) if __name__ == '__main__': unittest.main()
1,105
27.358974
67
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/test/test_multiping.py
#!/usr/bin/env python """ Test for multiping.py """ import unittest import pexpect from collections import defaultdict class testMultiPing( unittest.TestCase ): def testMultiPing( self ): """Verify that each target is pinged at least once, and that pings to 'real' targets are successful and unknown targets fail""" p = pexpect.spawn( 'python -m mininet.examples.multiping' ) opts = [ "Host (h\d+) \(([\d.]+)\) will be pinging ips: ([\d\. ]+)", "(h\d+): ([\d.]+) -> ([\d.]+) \d packets transmitted, (\d) received", pexpect.EOF ] pings = defaultdict( list ) while True: index = p.expect( opts ) if index == 0: name = p.match.group(1) ip = p.match.group(2) targets = p.match.group(3).split() pings[ name ] += targets elif index == 1: name = p.match.group(1) ip = p.match.group(2) target = p.match.group(3) received = int( p.match.group(4) ) if target == '10.0.0.200': self.assertEqual( received, 0 ) else: self.assertEqual( received, 1 ) try: pings[ name ].remove( target ) except: pass else: break self.assertTrue( len( pings ) > 0 ) for t in pings.values(): self.assertEqual( len( t ), 0 ) if __name__ == '__main__': unittest.main()
1,595
31.571429
86
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/test/test_hwintf.py
#!/usr/bin/env python """ Test for hwintf.py """ import unittest import re import pexpect from mininet.log import setLogLevel from mininet.node import Node from mininet.link import Link class testHwintf( unittest.TestCase ): prompt = 'mininet>' def setUp( self ): self.h3 = Node( 't0', ip='10.0.0.3/8' ) self.n0 = Node( 't1', inNamespace=False ) Link( self.h3, self.n0 ) self.h3.configDefault() def testLocalPing( self ): "Verify connectivity between virtual hosts using pingall" p = pexpect.spawn( 'python -m mininet.examples.hwintf %s' % self.n0.intf() ) p.expect( self.prompt ) p.sendline( 'pingall' ) p.expect ( '(\d+)% dropped' ) percent = int( p.match.group( 1 ) ) if p.match else -1 self.assertEqual( percent, 0 ) p.expect( self.prompt ) p.sendline( 'exit' ) p.wait() def testExternalPing( self ): "Verify connnectivity between virtual host and virtual-physical 'external' host " p = pexpect.spawn( 'python -m mininet.examples.hwintf %s' % self.n0.intf() ) p.expect( self.prompt ) # test ping external to internal expectStr = '(\d+) packets transmitted, (\d+) received' m = re.search( expectStr, self.h3.cmd( 'ping -v -c 1 10.0.0.1' ) ) tx = m.group( 1 ) rx = m.group( 2 ) self.assertEqual( tx, rx ) # test ping internal to external p.sendline( 'h1 ping -c 1 10.0.0.3') p.expect( expectStr ) tx = p.match.group( 1 ) rx = p.match.group( 2 ) self.assertEqual( tx, rx ) p.expect( self.prompt ) p.sendline( 'exit' ) p.wait() def tearDown( self ): self.h3.terminate() self.n0.terminate() if __name__ == '__main__': setLogLevel( 'warning' ) unittest.main()
1,870
27.348485
89
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/test/test_baresshd.py
#!/usr/bin/env python """ Tests for baresshd.py """ import unittest import pexpect from mininet.clean import cleanup, sh class testBareSSHD( unittest.TestCase ): opts = [ 'Welcome to h1', pexpect.EOF, pexpect.TIMEOUT ] def connected( self ): "Log into ssh server, check banner, then exit" p = pexpect.spawn( 'ssh 10.0.0.1 -o StrictHostKeyChecking=no -i /tmp/ssh/test_rsa exit' ) while True: index = p.expect( self.opts ) if index == 0: return True else: return False def setUp( self ): # verify that sshd is not running self.assertFalse( self.connected() ) # create public key pair for testing sh( 'rm -rf /tmp/ssh' ) sh( 'mkdir /tmp/ssh' ) sh( "ssh-keygen -t rsa -P '' -f /tmp/ssh/test_rsa" ) sh( 'cat /tmp/ssh/test_rsa.pub >> /tmp/ssh/authorized_keys' ) # run example with custom sshd args cmd = ( 'python -m mininet.examples.baresshd ' '-o AuthorizedKeysFile=/tmp/ssh/authorized_keys ' '-o StrictModes=no' ) p = pexpect.spawn( cmd ) runOpts = [ 'You may now ssh into h1 at 10.0.0.1', 'after 5 seconds, h1 is not listening on port 22', pexpect.EOF, pexpect.TIMEOUT ] while True: index = p.expect( runOpts ) if index == 0: break else: self.tearDown() self.fail( 'sshd failed to start in host h1' ) def testSSH( self ): "Simple test to verify that we can ssh into h1" result = False # try to connect up to 3 times; sshd can take a while to start result = self.connected() self.assertTrue( result ) def tearDown( self ): # kill the ssh process sh( "ps aux | grep 'ssh.*Banner' | awk '{ print $2 }' | xargs kill" ) cleanup() # remove public key pair sh( 'rm -rf /tmp/ssh' ) if __name__ == '__main__': unittest.main()
2,072
30.892308
97
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/test/test_multilink.py
#!/usr/bin/env python ''' Test for multiple links between nodes validates mininet interfaces against systems interfaces ''' import unittest import pexpect class testMultiLink( unittest.TestCase ): prompt = 'mininet>' def testMultiLink(self): p = pexpect.spawn( 'python -m mininet.examples.multilink' ) p.expect( self.prompt ) p.sendline( 'intfs' ) p.expect( 's(\d): lo' ) intfsOutput = p.before # parse interfaces from mininet intfs, and store them in a list hostToIntfs = intfsOutput.split( '\r\n' )[ 1:3 ] intfList = [] for hostToIntf in hostToIntfs: intfList += [ intf for intf in hostToIntf.split()[1].split(',') ] # get interfaces from system by running ifconfig on every host sysIntfList = [] opts = [ 'h(\d)-eth(\d)', self.prompt ] p.expect( self.prompt ) p.sendline( 'h1 ifconfig' ) while True: p.expect( opts ) if p.after == self.prompt: break sysIntfList.append( p.after ) p.sendline( 'h2 ifconfig' ) while True: p.expect( opts ) if p.after == self.prompt: break sysIntfList.append( p.after ) failMsg = ( 'The systems interfaces and mininet interfaces\n' 'are not the same' ) self.assertEqual( sysIntfList, intfList, msg=failMsg ) p.sendline( 'exit' ) p.wait() if __name__ == '__main__': unittest.main()
1,571
27.071429
71
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/test/test_linearbandwidth.py
#!/usr/bin/env python """ Test for linearbandwidth.py """ import unittest import pexpect import sys class testLinearBandwidth( unittest.TestCase ): @unittest.skipIf( '-quick' in sys.argv, 'long test' ) def testLinearBandwidth( self ): "Verify that bandwidth is monotonically decreasing as # of hops increases" p = pexpect.spawn( 'python -m mininet.examples.linearbandwidth' ) count = 0 opts = [ '\*\*\* Linear network results', '(\d+)\s+([\d\.]+) (.bits)', pexpect.EOF ] while True: index = p.expect( opts, timeout=600 ) if index == 0: count += 1 elif index == 1: n = int( p.match.group( 1 ) ) bw = float( p.match.group( 2 ) ) unit = p.match.group( 3 ) if unit[ 0 ] == 'K': bw *= 10 ** 3 elif unit[ 0 ] == 'M': bw *= 10 ** 6 elif unit[ 0 ] == 'G': bw *= 10 ** 9 # check that we have a previous result to compare to if n != 1: info = ( 'bw: %d bits/s across %d switches, ' 'previous: %d bits/s across %d switches' % ( bw, n, previous_bw, previous_n ) ) self.assertTrue( bw < previous_bw, info ) previous_bw, previous_n = bw, n else: break # verify that we received results from at least one switch self.assertTrue( count > 0 ) if __name__ == '__main__': unittest.main()
1,659
32.2
82
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/test/test_controlnet.py
#!/usr/bin/env python """ Test for controlnet.py """ import unittest import pexpect class testControlNet( unittest.TestCase ): prompt = 'mininet>' def testPingall( self ): "Simple pingall test that verifies 0% packet drop in data network" p = pexpect.spawn( 'python -m mininet.examples.controlnet' ) p.expect( self.prompt ) p.sendline( 'pingall' ) p.expect ( '(\d+)% dropped' ) percent = int( p.match.group( 1 ) ) if p.match else -1 self.assertEqual( percent, 0 ) p.expect( self.prompt ) p.sendline( 'exit' ) p.wait() def testFailover( self ): "Kill controllers and verify that switch, s1, fails over properly" count = 1 p = pexpect.spawn( 'python -m mininet.examples.controlnet' ) p.expect( self.prompt ) lp = pexpect.spawn( 'tail -f /tmp/s1-ofp.log' ) lp.expect( 'tcp:\d+\.\d+\.\d+\.(\d+):\d+: connected' ) ip = int( lp.match.group( 1 ) ) self.assertEqual( count, ip ) count += 1 for c in [ 'c0', 'c1' ]: p.sendline( '%s ifconfig %s-eth0 down' % ( c, c) ) p.expect( self.prompt ) lp.expect( 'tcp:\d+\.\d+\.\d+\.(\d+):\d+: connected' ) ip = int( lp.match.group( 1 ) ) self.assertEqual( count, ip ) count += 1 p.sendline( 'exit' ) p.wait() if __name__ == '__main__': unittest.main()
1,454
29.3125
74
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/test/test_nat.py
#!/usr/bin/env python """ Test for nat.py """ import unittest import pexpect from mininet.util import quietRun destIP = '8.8.8.8' # Google DNS class testNAT( unittest.TestCase ): prompt = 'mininet>' @unittest.skipIf( '0 received' in quietRun( 'ping -c 1 %s' % destIP ), 'Destination IP is not reachable' ) def testNAT( self ): "Attempt to ping an IP on the Internet and verify 0% packet loss" p = pexpect.spawn( 'python -m mininet.examples.nat' ) p.expect( self.prompt ) p.sendline( 'h1 ping -c 1 %s' % destIP ) p.expect ( '(\d+)% packet loss' ) percent = int( p.match.group( 1 ) ) if p.match else -1 p.expect( self.prompt ) p.sendline( 'exit' ) p.wait() self.assertEqual( percent, 0 ) if __name__ == '__main__': unittest.main()
854
24.909091
74
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/test/test_tree1024.py
#!/usr/bin/env python """ Test for tree1024.py """ import unittest import pexpect import sys class testTree1024( unittest.TestCase ): prompt = 'mininet>' @unittest.skipIf( '-quick' in sys.argv, 'long test' ) def testTree1024( self ): "Run the example and do a simple ping test from h1 to h1024" p = pexpect.spawn( 'python -m mininet.examples.tree1024' ) p.expect( self.prompt, timeout=6000 ) # it takes awhile to set up p.sendline( 'h1 ping -c 20 h1024' ) p.expect ( '(\d+)% packet loss' ) packetLossPercent = int( p.match.group( 1 ) ) if p.match else -1 p.expect( self.prompt ) p.sendline( 'exit' ) p.wait() # Tolerate slow startup on some systems - we should revisit this # and determine the root cause. self.assertLess( packetLossPercent, 60 ) if __name__ == '__main__': unittest.main()
908
27.40625
73
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/test/test_vlanhost.py
#!/usr/bin/env python """ Test for vlanhost.py """ import unittest import pexpect import sys from mininet.util import quietRun class testVLANHost( unittest.TestCase ): prompt = 'mininet>' @unittest.skipIf( '-quick' in sys.argv, 'long test' ) def testVLANTopo( self ): "Test connectivity (or lack thereof) between hosts in VLANTopo" p = pexpect.spawn( 'python -m mininet.examples.vlanhost' ) p.expect( self.prompt ) p.sendline( 'pingall 1' ) #ping timeout=1 p.expect( '(\d+)% dropped', timeout=30 ) # there should be 24 failed pings percent = int( p.match.group( 1 ) ) if p.match else -1 p.expect( self.prompt ) p.sendline( 'exit' ) p.wait() self.assertEqual( percent, 80 ) def testSpecificVLAN( self ): "Test connectivity between hosts on a specific VLAN" vlan = 1001 p = pexpect.spawn( 'python -m mininet.examples.vlanhost %d' % vlan ) p.expect( self.prompt ) p.sendline( 'h1 ping -c 1 h2' ) p.expect ( '(\d+)% packet loss' ) percent = int( p.match.group( 1 ) ) if p.match else -1 p.expect( self.prompt ) p.sendline( 'h1 ifconfig' ) i = p.expect( ['h1-eth0.%d' % vlan, pexpect.TIMEOUT ], timeout=2 ) p.expect( self.prompt ) p.sendline( 'exit' ) p.wait() self.assertEqual( percent, 0 ) # no packet loss on ping self.assertEqual( i, 0 ) # check vlan intf is present if __name__ == '__main__': unittest.main()
1,539
29.196078
83
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/test/test_emptynet.py
#!/usr/bin/env python """ Test for emptynet.py """ import unittest import pexpect class testEmptyNet( unittest.TestCase ): prompt = 'mininet>' def testEmptyNet( self ): "Run simple CLI tests: pingall (verify 0% drop) and iperf (sanity)" p = pexpect.spawn( 'python -m mininet.examples.emptynet' ) p.expect( self.prompt ) # pingall test p.sendline( 'pingall' ) p.expect ( '(\d+)% dropped' ) percent = int( p.match.group( 1 ) ) if p.match else -1 self.assertEqual( percent, 0 ) p.expect( self.prompt ) # iperf test p.sendline( 'iperf' ) p.expect( "Results: \['[\d.]+ .bits/sec', '[\d.]+ .bits/sec'\]" ) p.expect( self.prompt ) p.sendline( 'exit' ) p.wait() if __name__ == '__main__': unittest.main()
835
24.333333
75
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/test/test_linuxrouter.py
#!/usr/bin/env python """ Test for linuxrouter.py """ import unittest import pexpect from mininet.util import quietRun class testLinuxRouter( unittest.TestCase ): prompt = 'mininet>' def testPingall( self ): "Test connectivity between hosts" p = pexpect.spawn( 'python -m mininet.examples.linuxrouter' ) p.expect( self.prompt ) p.sendline( 'pingall' ) p.expect ( '(\d+)% dropped' ) percent = int( p.match.group( 1 ) ) if p.match else -1 p.expect( self.prompt ) p.sendline( 'exit' ) p.wait() self.assertEqual( percent, 0 ) def testRouterPing( self ): "Test connectivity from h1 to router" p = pexpect.spawn( 'python -m mininet.examples.linuxrouter' ) p.expect( self.prompt ) p.sendline( 'h1 ping -c 1 r0' ) p.expect ( '(\d+)% packet loss' ) percent = int( p.match.group( 1 ) ) if p.match else -1 p.expect( self.prompt ) p.sendline( 'exit' ) p.wait() self.assertEqual( percent, 0 ) def testTTL( self ): "Verify that the TTL is decremented" p = pexpect.spawn( 'python -m mininet.examples.linuxrouter' ) p.expect( self.prompt ) p.sendline( 'h1 ping -c 1 h2' ) p.expect ( 'ttl=(\d+)' ) ttl = int( p.match.group( 1 ) ) if p.match else -1 p.expect( self.prompt ) p.sendline( 'exit' ) p.wait() self.assertEqual( ttl, 63 ) # 64 - 1 if __name__ == '__main__': unittest.main()
1,534
27.962264
69
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/test/runner.py
#!/usr/bin/env python """ Run all mininet.examples tests -v : verbose output -quick : skip tests that take more than ~30 seconds """ import unittest import os import sys from mininet.util import ensureRoot from mininet.clean import cleanup class MininetTestResult( unittest.TextTestResult ): def addFailure( self, test, err ): super( MininetTestResult, self ).addFailure( test, err ) cleanup() def addError( self,test, err ): super( MininetTestResult, self ).addError( test, err ) cleanup() class MininetTestRunner( unittest.TextTestRunner ): def _makeResult( self ): return MininetTestResult( self.stream, self.descriptions, self.verbosity ) def runTests( testDir, verbosity=1 ): "discover and run all tests in testDir" # ensure root and cleanup before starting tests ensureRoot() cleanup() # discover all tests in testDir testSuite = unittest.defaultTestLoader.discover( testDir ) # run tests MininetTestRunner( verbosity=verbosity ).run( testSuite ) if __name__ == '__main__': # get the directory containing example tests testDir = os.path.dirname( os.path.realpath( __file__ ) ) verbosity = 2 if '-v' in sys.argv else 1 runTests( testDir, verbosity )
1,263
29.095238
82
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/test/test_multitest.py
#!/usr/bin/env python """ Test for multitest.py """ import unittest import pexpect class testMultiTest( unittest.TestCase ): prompt = 'mininet>' def testMultiTest( self ): "Verify pingall (0% dropped) and hX-eth0 interface for each host (ifconfig)" p = pexpect.spawn( 'python -m mininet.examples.multitest' ) p.expect( '(\d+)% dropped' ) dropped = int( p.match.group( 1 ) ) self.assertEqual( dropped, 0 ) ifCount = 0 while True: index = p.expect( [ 'h\d-eth0', self.prompt ] ) if index == 0: ifCount += 1 elif index == 1: p.sendline( 'exit' ) break p.wait() self.assertEqual( ifCount, 4 ) if __name__ == '__main__': unittest.main()
806
23.454545
84
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/test/test_controllers.py
#!/usr/bin/env python """ Tests for controllers.py and controllers2.py """ import unittest import pexpect class testControllers( unittest.TestCase ): prompt = 'mininet>' def connectedTest( self, name, cmap ): "Verify that switches are connected to the controller specified by cmap" p = pexpect.spawn( 'python -m %s' % name ) p.expect( self.prompt ) # but first a simple ping test p.sendline( 'pingall' ) p.expect ( '(\d+)% dropped' ) percent = int( p.match.group( 1 ) ) if p.match else -1 self.assertEqual( percent, 0 ) p.expect( self.prompt ) # verify connected controller for switch in cmap: p.sendline( 'sh ovs-vsctl get-controller %s' % switch ) p.expect( 'tcp:([\d.:]+)') actual = p.match.group(1) expected = cmap[ switch ] self.assertEqual( actual, expected ) p.expect( self.prompt ) p.sendline( 'exit' ) p.wait() def testControllers( self ): c0 = '127.0.0.1:6633' c1 = '127.0.0.1:6634' cmap = { 's1': c0, 's2': c1, 's3': c0 } self.connectedTest( 'mininet.examples.controllers', cmap ) def testControllers2( self ): c0 = '127.0.0.1:6633' c1 = '127.0.0.1:6634' cmap = { 's1': c0, 's2': c1 } self.connectedTest( 'mininet.examples.controllers2', cmap ) if __name__ == '__main__': unittest.main()
1,463
28.877551
80
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/test/test_cpu.py
#!/usr/bin/env python """ Test for cpu.py results format: sched cpu client MB/s cfs 45.00% 13254.669841 cfs 40.00% 11822.441399 cfs 30.00% 5112.963009 cfs 20.00% 3449.090009 cfs 10.00% 2271.741564 """ import unittest import pexpect import sys class testCPU( unittest.TestCase ): prompt = 'mininet>' @unittest.skipIf( '-quick' in sys.argv, 'long test' ) def testCPU( self ): "Verify that CPU utilization is monotonically decreasing for each scheduler" p = pexpect.spawn( 'python -m mininet.examples.cpu' ) # matches each line from results( shown above ) opts = [ '([a-z]+)\t([\d\.]+)%\t([\d\.]+)', pexpect.EOF ] scheds = [] while True: index = p.expect( opts, timeout=600 ) if index == 0: sched = p.match.group( 1 ) cpu = float( p.match.group( 2 ) ) bw = float( p.match.group( 3 ) ) if sched not in scheds: scheds.append( sched ) else: self.assertTrue( bw < previous_bw, "%f should be less than %f\n" % ( bw, previous_bw ) ) previous_bw = bw else: break self.assertTrue( len( scheds ) > 0 ) if __name__ == '__main__': unittest.main()
1,426
25.425926
84
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/test/test_treeping64.py
#!/usr/bin/env python """ Test for treeping64.py """ import unittest import pexpect import sys class testTreePing64( unittest.TestCase ): prompt = 'mininet>' @unittest.skipIf( '-quick' in sys.argv, 'long test' ) def testTreePing64( self ): "Run the example and verify ping results" p = pexpect.spawn( 'python -m mininet.examples.treeping64' ) p.expect( 'Tree network ping results:', timeout=6000 ) count = 0 while True: index = p.expect( [ '(\d+)% packet loss', pexpect.EOF ] ) if index == 0: percent = int( p.match.group( 1 ) ) if p.match else -1 self.assertEqual( percent, 0 ) count += 1 else: break self.assertTrue( count > 0 ) if __name__ == '__main__': unittest.main()
844
24.606061
70
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/test/test_bind.py
#!/usr/bin/env python """ Tests for bind.py """ import unittest import pexpect class testBind( unittest.TestCase ): prompt = 'mininet>' def setUp( self ): self.net = pexpect.spawn( 'python -m mininet.examples.bind' ) self.net.expect( "Private Directories: \[([\w\s,'/]+)\]" ) self.directories = [] # parse directories from mn output for d in self.net.match.group(1).split(', '): self.directories.append( d.strip("'") ) self.net.expect( self.prompt ) self.assertTrue( len( self.directories ) > 0 ) def testCreateFile( self ): "Create a file, a.txt, in the first private directory and verify" fileName = 'a.txt' directory = self.directories[ 0 ] path = directory + '/' + fileName self.net.sendline( 'h1 touch %s; ls %s' % ( path, directory ) ) index = self.net.expect( [ fileName, self.prompt ] ) self.assertTrue( index == 0 ) self.net.expect( self.prompt ) self.net.sendline( 'h1 rm %s' % path ) self.net.expect( self.prompt ) def testIsolation( self ): "Create a file in two hosts and verify that contents are different" fileName = 'b.txt' directory = self.directories[ 0 ] path = directory + '/' + fileName contents = { 'h1' : '1', 'h2' : '2' } # Verify file doesn't exist, then write private copy of file for host in contents: value = contents[ host ] self.net.sendline( '%s cat %s' % ( host, path ) ) self.net.expect( 'No such file' ) self.net.expect( self.prompt ) self.net.sendline( '%s echo %s > %s' % ( host, value, path ) ) self.net.expect( self.prompt ) # Verify file contents for host in contents: value = contents[ host ] self.net.sendline( '%s cat %s' % ( host, path ) ) self.net.expect( value ) self.net.expect( self.prompt ) self.net.sendline( '%s rm %s' % ( host, path ) ) self.net.expect( self.prompt ) # TODO: need more tests def tearDown( self ): self.net.sendline( 'exit' ) self.net.wait() if __name__ == '__main__': unittest.main()
2,270
32.895522
75
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/test/test_limit.py
#!/usr/bin/env python """ Test for limit.py """ import unittest import pexpect import sys class testLimit( unittest.TestCase ): @unittest.skipIf( '-quick' in sys.argv, 'long test' ) def testLimit( self ): "Verify that CPU limits are within a 2% tolerance of limit for each scheduler" p = pexpect.spawn( 'python -m mininet.examples.limit' ) opts = [ '\*\*\* Testing network ([\d\.]+) Mbps', '\*\*\* Results: \[([\d\., ]+)\]', pexpect.EOF ] count = 0 bw = 0 tolerance = 2 while True: index = p.expect( opts ) if index == 0: bw = float( p.match.group( 1 ) ) count += 1 elif index == 1: results = p.match.group( 1 ) for x in results.split( ',' ): result = float( x ) self.assertTrue( result < bw + tolerance ) self.assertTrue( result > bw - tolerance ) else: break self.assertTrue( count > 0 ) if __name__ == '__main__': unittest.main()
1,137
26.756098
86
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/test/test_simpleperf.py
#!/usr/bin/env python """ Test for simpleperf.py """ import unittest import pexpect import sys from mininet.log import setLogLevel from mininet.examples.simpleperf import SingleSwitchTopo class testSimplePerf( unittest.TestCase ): @unittest.skipIf( '-quick' in sys.argv, 'long test' ) def testE2E( self ): "Run the example and verify iperf results" # 10 Mb/s, plus or minus 20% tolerance BW = 10 TOLERANCE = .2 p = pexpect.spawn( 'python -m mininet.examples.simpleperf testmode' ) # check iperf results p.expect( "Results: \['10M', '([\d\.]+) .bits/sec", timeout=480 ) measuredBw = float( p.match.group( 1 ) ) lowerBound = BW * ( 1 - TOLERANCE ) upperBound = BW + ( 1 + TOLERANCE ) self.assertGreaterEqual( measuredBw, lowerBound ) self.assertLessEqual( measuredBw, upperBound ) p.wait() if __name__ == '__main__': setLogLevel( 'warning' ) unittest.main()
976
26.914286
77
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/test/test_numberedports.py
#!/usr/bin/env python """ Test for numberedports.py """ import unittest import pexpect from collections import defaultdict from mininet.node import OVSSwitch 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 ) if __name__ == '__main__': unittest.main()
1,744
31.924528
107
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/test/test_scratchnet.py
#!/usr/bin/env python """ Test for scratchnet.py """ import unittest import pexpect class testScratchNet( unittest.TestCase ): opts = [ "1 packets transmitted, 1 received, 0% packet loss", pexpect.EOF ] def pingTest( self, name ): "Verify that no ping packets were dropped" p = pexpect.spawn( 'python -m %s' % name ) index = p.expect( self.opts ) self.assertEqual( index, 0 ) def testPingKernel( self ): self.pingTest( 'mininet.examples.scratchnet' ) def testPingUser( self ): self.pingTest( 'mininet.examples.scratchnetuser' ) if __name__ == '__main__': unittest.main()
647
22.142857
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/test/test_intfoptions.py
#!/usr/bin/env python """ Test for intfOptions.py """ import unittest import pexpect import sys class testIntfOptions( unittest.TestCase ): def testIntfOptions( self ): "verify that intf.config is correctly limiting traffic" p = pexpect.spawn( 'python -m mininet.examples.intfoptions ' ) tolerance = .2 # plus or minus 20% opts = [ "Results: \['([\d\.]+) .bits/sec", "Results: \['10M', '([\d\.]+) .bits/sec", "h(\d+)->h(\d+): (\d)/(\d)," "rtt min/avg/max/mdev ([\d\.]+)/([\d\.]+)/([\d\.]+)/([\d\.]+) ms", pexpect.EOF ] while True: index = p.expect( opts, timeout=600 ) if index == 0: BW = 5 bw = float( p.match.group( 1 ) ) self.assertGreaterEqual( bw, BW * ( 1 - tolerance ) ) self.assertLessEqual( bw, BW * ( 1 + tolerance ) ) elif index == 1: BW = 10 measuredBw = float( p.match.group( 1 ) ) loss = ( measuredBw / BW ) * 100 self.assertGreaterEqual( loss, 50 * ( 1 - tolerance ) ) self.assertLessEqual( loss, 50 * ( 1 + tolerance ) ) elif index == 2: delay = float( p.match.group( 6 ) ) self.assertGreaterEqual( delay, 15 * ( 1 - tolerance ) ) self.assertLessEqual( delay, 15 * ( 1 + tolerance ) ) else: break if __name__ == '__main__': unittest.main()
1,549
33.444444
83
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/test/test_clusterSanity.py
#!/usr/bin/env python ''' A simple sanity check test for cluster edition ''' import unittest import pexpect class clusterSanityCheck( unittest.TestCase ): prompt = 'mininet>' def testClusterPingAll( self ): p = pexpect.spawn( 'python -m mininet.examples.clusterSanity' ) p.expect( self.prompt ) p.sendline( 'pingall' ) p.expect ( '(\d+)% dropped' ) percent = int( p.match.group( 1 ) ) if p.match else -1 self.assertEqual( percent, 0 ) p.expect( self.prompt ) p.sendline( 'exit' ) p.wait() if __name__ == '__main__': unittest.main()
624
21.321429
71
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/test/test_mobility.py
#!/usr/bin/env python """ Test for mobility.py """ import unittest from subprocess import check_output class testMobility( unittest.TestCase ): def testMobility( self ): "Run the example and verify its 4 ping results" cmd = 'python -m mininet.examples.mobility 2>&1' grep = ' | grep -c " 0% dropped" ' result = check_output( cmd + grep, shell=True ) assert int( result ) == 4 if __name__ == '__main__': unittest.main()
472
21.52381
56
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/examples/test/test_natnet.py
#!/usr/bin/env python """ Test for natnet.py """ import unittest import pexpect from mininet.util import quietRun class testNATNet( unittest.TestCase ): prompt = 'mininet>' def setUp( self ): self.net = pexpect.spawn( 'python -m mininet.examples.natnet' ) self.net.expect( self.prompt ) def testPublicPing( self ): "Attempt to ping the public server (h0) from h1 and h2" self.net.sendline( 'h1 ping -c 1 h0' ) self.net.expect ( '(\d+)% packet loss' ) percent = int( self.net.match.group( 1 ) ) if self.net.match else -1 self.assertEqual( percent, 0 ) self.net.expect( self.prompt ) self.net.sendline( 'h2 ping -c 1 h0' ) self.net.expect ( '(\d+)% packet loss' ) percent = int( self.net.match.group( 1 ) ) if self.net.match else -1 self.assertEqual( percent, 0 ) self.net.expect( self.prompt ) def testPrivatePing( self ): "Attempt to ping h1 and h2 from public server" self.net.sendline( 'h0 ping -c 1 -t 1 h1' ) result = self.net.expect ( [ 'unreachable', 'loss' ] ) self.assertEqual( result, 0 ) self.net.expect( self.prompt ) self.net.sendline( 'h0 ping -c 1 -t 1 h2' ) result = self.net.expect ( [ 'unreachable', 'loss' ] ) self.assertEqual( result, 0 ) self.net.expect( self.prompt ) def testPrivateToPrivatePing( self ): "Attempt to ping from NAT'ed host h1 to NAT'ed host h2" self.net.sendline( 'h1 ping -c 1 -t 1 h2' ) result = self.net.expect ( [ '[Uu]nreachable', 'loss' ] ) self.assertEqual( result, 0 ) self.net.expect( self.prompt ) def tearDown( self ): self.net.sendline( 'exit' ) self.net.wait() if __name__ == '__main__': unittest.main()
1,827
30.517241
76
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/test/test_nets.py
#!/usr/bin/env python """Package: mininet Test creation and all-pairs ping for each included mininet topo type.""" import unittest import sys from functools import partial from mininet.net import Mininet from mininet.node import Host, Controller from mininet.node import UserSwitch, OVSSwitch, IVSSwitch from mininet.topo import SingleSwitchTopo, LinearTopo from mininet.log import setLogLevel from mininet.util import quietRun from mininet.clean import cleanup # Tell pylint not to complain about calls to other class # pylint: disable=E1101 class testSingleSwitchCommon( object ): "Test ping with single switch topology (common code)." switchClass = None # overridden in subclasses @staticmethod def tearDown(): "Clean up if necessary" if sys.exc_info != ( None, None, None ): cleanup() def testMinimal( self ): "Ping test on minimal topology" mn = Mininet( SingleSwitchTopo(), self.switchClass, Host, Controller, waitConnected=True ) dropped = mn.run( mn.ping ) self.assertEqual( dropped, 0 ) 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 ) # pylint: enable=E1101 class testSingleSwitchOVSKernel( testSingleSwitchCommon, unittest.TestCase ): "Test ping with single switch topology (OVS kernel switch)." switchClass = OVSSwitch class testSingleSwitchOVSUser( testSingleSwitchCommon, unittest.TestCase ): "Test ping with single switch topology (OVS user switch)." switchClass = partial( OVSSwitch, datapath='user' ) @unittest.skipUnless( quietRun( 'which ivs-ctl' ), 'IVS is not installed' ) class testSingleSwitchIVS( testSingleSwitchCommon, unittest.TestCase ): "Test ping with single switch topology (IVS switch)." switchClass = IVSSwitch @unittest.skipUnless( quietRun( 'which ofprotocol' ), 'Reference user switch is not installed' ) class testSingleSwitchUserspace( testSingleSwitchCommon, unittest.TestCase ): "Test ping with single switch topology (Userspace switch)." switchClass = UserSwitch # Tell pylint not to complain about calls to other class # pylint: disable=E1101 class testLinearCommon( object ): "Test all-pairs ping with LinearNet (common code)." switchClass = None # overridden in subclasses def testLinear5( self ): "Ping test on a 5-switch topology" mn = Mininet( LinearTopo( k=5 ), self.switchClass, Host, Controller, waitConnected=True ) dropped = mn.run( mn.ping ) self.assertEqual( dropped, 0 ) # pylint: enable=E1101 class testLinearOVSKernel( testLinearCommon, unittest.TestCase ): "Test all-pairs ping with LinearNet (OVS kernel switch)." switchClass = OVSSwitch class testLinearOVSUser( testLinearCommon, unittest.TestCase ): "Test all-pairs ping with LinearNet (OVS user switch)." switchClass = partial( OVSSwitch, datapath='user' ) @unittest.skipUnless( quietRun( 'which ivs-ctl' ), 'IVS is not installed' ) class testLinearIVS( testLinearCommon, unittest.TestCase ): "Test all-pairs ping with LinearNet (IVS switch)." switchClass = IVSSwitch @unittest.skipUnless( quietRun( 'which ofprotocol' ), 'Reference user switch is not installed' ) class testLinearUserspace( testLinearCommon, unittest.TestCase ): "Test all-pairs ping with LinearNet (Userspace switch)." switchClass = UserSwitch if __name__ == '__main__': setLogLevel( 'warning' ) unittest.main()
3,743
33.348624
77
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/test/test_hifi.py
#!/usr/bin/env python """Package: mininet Test creation and pings for topologies with link and/or CPU options.""" import unittest import sys from functools import partial from mininet.net import Mininet from mininet.node import OVSSwitch, UserSwitch, IVSSwitch from mininet.node import CPULimitedHost from mininet.link import TCLink from mininet.topo import Topo from mininet.log import setLogLevel from mininet.util import quietRun from mininet.clean import cleanup # Number of hosts for each test N = 2 class SingleSwitchOptionsTopo(Topo): "Single switch connected to n hosts." def __init__(self, n=2, hopts=None, lopts=None): if not hopts: hopts = {} if not lopts: lopts = {} Topo.__init__(self, hopts=hopts, lopts=lopts) switch = self.addSwitch('s1') for h in range(n): host = self.addHost('h%s' % (h + 1)) self.addLink(host, switch) # Tell pylint not to complain about calls to other class # pylint: disable=E1101 class testOptionsTopoCommon( object ): """Verify ability to create networks with host and link options (common code).""" switchClass = None # overridden in subclasses @staticmethod def tearDown(): "Clean up if necessary" if sys.exc_info != ( None, None, None ): cleanup() 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, switch=self.switchClass, waitConnected=True ) dropped = mn.run( mn.ping ) hoptsStr = ', '.join( '%s: %s' % ( opt, value ) for opt, value in hopts.items() ) loptsStr = ', '.join( '%s: %s' % ( opt, value ) for opt, value in lopts.items() ) msg += ( '%s%% of pings were dropped during mininet.ping().\n' 'Topo = SingleSwitchTopo, %s hosts\n' 'hopts = %s\n' 'lopts = %s\n' 'host = CPULimitedHost\n' 'link = TCLink\n' 'Switch = %s\n' % ( dropped, n, hoptsStr, loptsStr, self.switchClass ) ) self.assertEqual( dropped, 0, msg=msg ) 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 ) * float( expected ) ) lowerBound = float( expected ) * tolerance_frac info = ( 'measured value is out of bounds\n' 'expected value: %s\n' 'measured value: %s\n' 'failure tolerance: %s\n' 'upper bound: %s\n' 'lower bound: %s\n' % ( expected, measured, tolerance_frac, upperBound, lowerBound ) ) msg += info self.assertGreaterEqual( float( measured ), lowerBound, msg=msg ) self.assertLessEqual( float( measured ), upperBound, msg=msg ) def testCPULimits( self ): "Verify topology creation with CPU limits set for both schedulers." CPU_FRACTION = 0.1 CPU_TOLERANCE = 0.8 # CPU fraction below which test should fail hopts = { 'cpu': CPU_FRACTION } #self.runOptionsTopoTest( N, hopts=hopts ) mn = Mininet( SingleSwitchOptionsTopo( n=N, hopts=hopts ), host=CPULimitedHost, switch=self.switchClass, waitConnected=True ) mn.start() results = mn.runCpuLimitTest( cpu=CPU_FRACTION ) mn.stop() hostUsage = '\n'.join( 'h%s: %s' % ( n + 1, results[ (n - 1) * 5 : (n * 5) - 1 ] ) for n in range( N ) ) hoptsStr = ', '.join( '%s: %s' % ( opt, value ) for opt, value in hopts.items() ) msg = ( '\nTesting cpu limited to %d%% of cpu per host\n' 'cpu usage percent per host:\n%s\n' 'Topo = SingleSwitchTopo, %s hosts\n' 'hopts = %s\n' 'host = CPULimitedHost\n' 'Switch = %s\n' % ( CPU_FRACTION * 100, hostUsage, N, hoptsStr, self.switchClass ) ) for pct in results: #divide cpu by 100 to convert from percentage to fraction self.assertWithinTolerance( pct/100, CPU_FRACTION, CPU_TOLERANCE, msg ) 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 fraction below which test should fail # Verify ability to create limited-link topo first; lopts = { 'bw': BW, 'use_htb': True } # Also verify correctness of limit limitng within a bound. mn = Mininet( SingleSwitchOptionsTopo( n=N, lopts=lopts ), link=TCLink, switch=self.switchClass, waitConnected=True ) bw_strs = mn.run( mn.iperf, fmt='m' ) loptsStr = ', '.join( '%s: %s' % ( opt, value ) for opt, value in lopts.items() ) msg = ( '\nTesting link bandwidth limited to %d Mbps per link\n' 'iperf results[ client, server ]: %s\n' 'Topo = SingleSwitchTopo, %s hosts\n' 'Link = TCLink\n' 'lopts = %s\n' 'host = default\n' 'switch = %s\n' % ( BW, bw_strs, N, loptsStr, self.switchClass ) ) # On the client side, iperf doesn't wait for ACKs - it simply # reports how long it took to fill up the TCP send buffer. # As long as the kernel doesn't wait a long time before # delivering bytes to the iperf server, its reported data rate # should be close to the actual receive rate. serverRate, _clientRate = bw_strs bw = float( serverRate.split(' ')[0] ) self.assertWithinTolerance( bw, BW, BW_TOLERANCE, msg ) 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, lopts=lopts ), link=TCLink, switch=self.switchClass, autoStaticArp=True, waitConnected=True ) mn.start() for _ in range( REPS ): ping_delays = mn.pingFull() mn.stop() test_outputs = ping_delays[0] # Ignore unused variables below # pylint: disable=W0612 node, dest, ping_outputs = test_outputs sent, received, rttmin, rttavg, rttmax, rttdev = ping_outputs pingFailMsg = 'sent %s pings, only received %s' % ( sent, received ) self.assertEqual( sent, received, msg=pingFailMsg ) # pylint: enable=W0612 loptsStr = ', '.join( '%s: %s' % ( opt, value ) for opt, value in lopts.items() ) msg = ( '\nTesting Link Delay of %s ms\n' 'ping results across 4 links:\n' '(Sent, Received, rttmin, rttavg, rttmax, rttdev)\n' '%s\n' 'Topo = SingleSwitchTopo, %s hosts\n' 'Link = TCLink\n' 'lopts = %s\n' 'host = default' 'switch = %s\n' % ( DELAY_MS, ping_outputs, N, loptsStr, self.switchClass ) ) for rttval in [rttmin, rttavg, rttmax]: # Multiply delay by 4 to cover there & back on two links self.assertWithinTolerance( rttval, DELAY_MS * 4.0, DELAY_TOLERANCE, msg ) 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, link=TCLink, switch=self.switchClass, waitConnected=True ) # Drops are probabilistic, but the chance of no dropped packets is # 1 in 100 million with 4 hops for a link w/99% loss. dropped_total = 0 mn.start() for _ in range(REPS): dropped_total += mn.ping(timeout='1') mn.stop() loptsStr = ', '.join( '%s: %s' % ( opt, value ) for opt, value in lopts.items() ) msg = ( '\nTesting packet loss with %d%% loss rate\n' 'number of dropped pings during mininet.ping(): %s\n' 'expected number of dropped packets: 1\n' 'Topo = SingleSwitchTopo, %s hosts\n' 'Link = TCLink\n' 'lopts = %s\n' 'host = default\n' 'switch = %s\n' % ( LOSS_PERCENT, dropped_total, N, loptsStr, self.switchClass ) ) self.assertGreater( dropped_total, 0, msg ) def testMostOptions( self ): "Verify topology creation with most link options and CPU limits." lopts = { 'bw': 10, 'delay': '5ms', 'use_htb': True } hopts = { 'cpu': 0.5 / N } msg = '\nTesting many cpu and link options\n' self.runOptionsTopoTest( N, msg, hopts=hopts, lopts=lopts ) # pylint: enable=E1101 class testOptionsTopoOVSKernel( testOptionsTopoCommon, unittest.TestCase ): """Verify ability to create networks with host and link options (OVS kernel switch).""" longMessage = True switchClass = OVSSwitch @unittest.skip( 'Skipping OVS user switch test for now' ) class testOptionsTopoOVSUser( testOptionsTopoCommon, unittest.TestCase ): """Verify ability to create networks with host and link options (OVS user switch).""" longMessage = True switchClass = partial( OVSSwitch, datapath='user' ) @unittest.skipUnless( quietRun( 'which ivs-ctl' ), 'IVS is not installed' ) class testOptionsTopoIVS( testOptionsTopoCommon, unittest.TestCase ): "Verify ability to create networks with host and link options (IVS)." longMessage = True switchClass = IVSSwitch @unittest.skipUnless( quietRun( 'which ofprotocol' ), 'Reference user switch is not installed' ) class testOptionsTopoUserspace( testOptionsTopoCommon, unittest.TestCase ): """Verify ability to create networks with host and link options (UserSwitch).""" longMessage = True switchClass = UserSwitch if __name__ == '__main__': setLogLevel( 'warning' ) unittest.main()
11,315
41.066914
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/test/test_walkthrough.py
#!/usr/bin/env python """ Tests for the Mininet Walkthrough TODO: missing xterm test """ import unittest import pexpect import os import re from mininet.util import quietRun from distutils.version import StrictVersion def tsharkVersion(): "Return tshark version" versionStr = quietRun( 'tshark -v' ) versionMatch = re.findall( r'TShark \d+.\d+.\d+', versionStr )[0] return versionMatch.split()[ 1 ] # pylint doesn't understand pexpect.match, unfortunately! # pylint:disable=maybe-no-member class testWalkthrough( unittest.TestCase ): "Test Mininet walkthrough" prompt = 'mininet>' # PART 1 def testHelp( self ): "Check the usage message" p = pexpect.spawn( 'mn -h' ) index = p.expect( [ 'Usage: mn', pexpect.EOF ] ) self.assertEqual( index, 0 ) def testWireshark( self ): "Use tshark to test the of dissector" # Satisfy pylint assert self if StrictVersion( tsharkVersion() ) < StrictVersion( '1.12.0' ): tshark = pexpect.spawn( 'tshark -i lo -R of' ) else: tshark = pexpect.spawn( 'tshark -i lo -Y openflow_v1' ) tshark.expect( [ 'Capturing on lo', "Capturing on 'Loopback'" ] ) mn = pexpect.spawn( 'mn --test pingall' ) mn.expect( '0% dropped' ) tshark.expect( [ '74 Hello', '74 of_hello', '74 Type: OFPT_HELLO' ] ) tshark.sendintr() def testBasic( self ): "Test basic CLI commands (help, nodes, net, dump)" p = pexpect.spawn( 'mn' ) p.expect( self.prompt ) # help command p.sendline( 'help' ) index = p.expect( [ 'commands', self.prompt ] ) self.assertEqual( index, 0, 'No output for "help" command') # nodes command p.sendline( 'nodes' ) p.expect( r'([chs]\d ?){4}' ) nodes = p.match.group( 0 ).split() self.assertEqual( len( nodes ), 4, 'No nodes in "nodes" command') p.expect( self.prompt ) # net command p.sendline( 'net' ) expected = [ x for x in nodes ] while len( expected ) > 0: index = p.expect( expected ) node = p.match.group( 0 ) expected.remove( node ) p.expect( '\n' ) self.assertEqual( len( expected ), 0, '"nodes" and "net" differ') p.expect( self.prompt ) # dump command p.sendline( 'dump' ) expected = [ r'<\w+ (%s)' % n for n in nodes ] actual = [] for _ in nodes: index = p.expect( expected ) node = p.match.group( 1 ) actual.append( node ) p.expect( '\n' ) self.assertEqual( actual.sort(), nodes.sort(), '"nodes" and "dump" differ' ) p.expect( self.prompt ) p.sendline( 'exit' ) p.wait() def testHostCommands( self ): "Test ifconfig and ps on h1 and s1" p = pexpect.spawn( 'mn' ) p.expect( self.prompt ) interfaces = [ 'h1-eth0', 's1-eth1', '[^-]eth0', 'lo', self.prompt ] # h1 ifconfig p.sendline( 'h1 ifconfig -a' ) ifcount = 0 while True: index = p.expect( interfaces ) if index == 0 or index == 3: ifcount += 1 elif index == 1: self.fail( 's1 interface displayed in "h1 ifconfig"' ) elif index == 2: self.fail( 'eth0 displayed in "h1 ifconfig"' ) else: break self.assertEqual( ifcount, 2, 'Missing interfaces on h1') # s1 ifconfig p.sendline( 's1 ifconfig -a' ) ifcount = 0 while True: index = p.expect( interfaces ) if index == 0: self.fail( 'h1 interface displayed in "s1 ifconfig"' ) elif index == 1 or index == 2 or index == 3: ifcount += 1 else: break self.assertEqual( ifcount, 3, 'Missing interfaces on s1') # h1 ps p.sendline( "h1 ps -a | egrep -v 'ps|grep'" ) p.expect( self.prompt ) h1Output = p.before # s1 ps p.sendline( "s1 ps -a | egrep -v 'ps|grep'" ) p.expect( self.prompt ) s1Output = p.before # strip command from ps output h1Output = h1Output.split( '\n', 1 )[ 1 ] s1Output = s1Output.split( '\n', 1 )[ 1 ] self.assertEqual( h1Output, s1Output, 'h1 and s1 "ps" output differs') p.sendline( 'exit' ) p.wait() def testConnectivity( self ): "Test ping and pingall" p = pexpect.spawn( 'mn' ) p.expect( self.prompt ) p.sendline( 'h1 ping -c 1 h2' ) p.expect( '1 packets transmitted, 1 received' ) p.expect( self.prompt ) p.sendline( 'pingall' ) p.expect( '0% dropped' ) p.expect( self.prompt ) p.sendline( 'exit' ) p.wait() def testSimpleHTTP( self ): "Start an HTTP server on h1 and wget from h2" p = pexpect.spawn( 'mn' ) p.expect( self.prompt ) p.sendline( 'h1 python -m SimpleHTTPServer 80 &' ) p.expect( self.prompt ) p.sendline( ' h2 wget -O - h1' ) p.expect( '200 OK' ) p.expect( self.prompt ) p.sendline( 'h1 kill %python' ) p.expect( self.prompt ) p.sendline( 'exit' ) p.wait() # PART 2 def testRegressionRun( self ): "Test pingpair (0% drop) and iperf (bw > 0) regression tests" # test pingpair p = pexpect.spawn( 'mn --test pingpair' ) p.expect( '0% dropped' ) p.expect( pexpect.EOF ) # test iperf p = pexpect.spawn( 'mn --test iperf' ) p.expect( r"Results: \['([\d\.]+) .bits/sec'," ) bw = float( p.match.group( 1 ) ) self.assertTrue( bw > 0 ) p.expect( pexpect.EOF ) def testTopoChange( self ): "Test pingall on single,3 and linear,4 topos" # testing single,3 p = pexpect.spawn( 'mn --test pingall --topo single,3' ) p.expect( r'(\d+)/(\d+) received') received = int( p.match.group( 1 ) ) sent = int( p.match.group( 2 ) ) self.assertEqual( sent, 6, 'Wrong number of pings sent in single,3' ) self.assertEqual( sent, received, 'Dropped packets in single,3') p.expect( pexpect.EOF ) # testing linear,4 p = pexpect.spawn( 'mn --test pingall --topo linear,4' ) p.expect( r'(\d+)/(\d+) received') received = int( p.match.group( 1 ) ) sent = int( p.match.group( 2 ) ) self.assertEqual( sent, 12, 'Wrong number of pings sent in linear,4' ) self.assertEqual( sent, received, 'Dropped packets in linear,4') p.expect( pexpect.EOF ) def testLinkChange( self ): "Test TCLink bw and delay" p = pexpect.spawn( 'mn --link tc,bw=10,delay=10ms' ) # test bw p.expect( self.prompt ) p.sendline( 'iperf' ) p.expect( r"Results: \['([\d\.]+) Mbits/sec'," ) bw = float( p.match.group( 1 ) ) self.assertTrue( bw < 10.1, 'Bandwidth > 10 Mb/s') self.assertTrue( bw > 9.0, 'Bandwidth < 9 Mb/s') p.expect( self.prompt ) # test delay p.sendline( 'h1 ping -c 4 h2' ) p.expect( r'rtt min/avg/max/mdev = ' r'([\d\.]+)/([\d\.]+)/([\d\.]+)/([\d\.]+) ms' ) delay = float( p.match.group( 2 ) ) self.assertTrue( delay > 40, 'Delay < 40ms' ) self.assertTrue( delay < 45, 'Delay > 40ms' ) p.expect( self.prompt ) p.sendline( 'exit' ) p.wait() def testVerbosity( self ): "Test debug and output verbosity" # test output p = pexpect.spawn( 'mn -v output' ) p.expect( self.prompt ) self.assertEqual( len( p.before ), 0, 'Too much output for "output"' ) p.sendline( 'exit' ) p.wait() # test debug p = pexpect.spawn( 'mn -v debug --test none' ) p.expect( pexpect.EOF ) lines = p.before.split( '\n' ) self.assertTrue( len( lines ) > 70, "Debug output is too short" ) def testCustomTopo( self ): "Start Mininet using a custom topo, then run pingall" # Satisfy pylint assert self custom = os.path.dirname( os.path.realpath( __file__ ) ) custom = os.path.join( custom, '../../custom/topo-2sw-2host.py' ) custom = os.path.normpath( custom ) p = pexpect.spawn( 'mn --custom %s --topo mytopo --test pingall' % custom ) p.expect( '0% dropped' ) p.expect( pexpect.EOF ) def testStaticMAC( self ): "Verify that MACs are set to easy to read numbers" p = pexpect.spawn( 'mn --mac' ) p.expect( self.prompt ) for i in range( 1, 3 ): p.sendline( 'h%d ifconfig' % i ) p.expect( 'HWaddr 00:00:00:00:00:0%d' % i ) p.expect( self.prompt ) def testSwitches( self ): "Run iperf test using user and ovsk switches" switches = [ 'user', 'ovsk' ] for sw in switches: p = pexpect.spawn( 'mn --switch %s --test iperf' % sw ) p.expect( r"Results: \['([\d\.]+) .bits/sec'," ) bw = float( p.match.group( 1 ) ) self.assertTrue( bw > 0 ) p.expect( pexpect.EOF ) def testBenchmark( self ): "Run benchmark and verify that it takes less than 2 seconds" p = pexpect.spawn( 'mn --test none' ) p.expect( r'completed in ([\d\.]+) seconds' ) time = float( p.match.group( 1 ) ) self.assertTrue( time < 2, 'Benchmark takes more than 2 seconds' ) def testOwnNamespace( self ): "Test running user switch in its own namespace" p = pexpect.spawn( 'mn --innamespace --switch user' ) p.expect( self.prompt ) interfaces = [ 'h1-eth0', 's1-eth1', '[^-]eth0', 'lo', self.prompt ] p.sendline( 's1 ifconfig -a' ) ifcount = 0 while True: index = p.expect( interfaces ) if index == 1 or index == 3: ifcount += 1 elif index == 0: self.fail( 'h1 interface displayed in "s1 ifconfig"' ) elif index == 2: self.fail( 'eth0 displayed in "s1 ifconfig"' ) else: break self.assertEqual( ifcount, 2, 'Missing interfaces on s1' ) # verify that all hosts a reachable p.sendline( 'pingall' ) p.expect( r'(\d+)% dropped' ) dropped = int( p.match.group( 1 ) ) self.assertEqual( dropped, 0, 'pingall failed') p.expect( self.prompt ) p.sendline( 'exit' ) p.wait() # PART 3 def testPythonInterpreter( self ): "Test py and px by checking IP for h1 and adding h3" p = pexpect.spawn( 'mn' ) p.expect( self.prompt ) # test host IP p.sendline( 'py h1.IP()' ) p.expect( '10.0.0.1' ) p.expect( self.prompt ) # test adding host p.sendline( "px net.addHost('h3')" ) p.expect( self.prompt ) p.sendline( "px net.addLink(s1, h3)" ) p.expect( self.prompt ) p.sendline( 'net' ) p.expect( 'h3' ) p.expect( self.prompt ) p.sendline( 'py h3.MAC()' ) p.expect( '([a-f0-9]{2}:?){6}' ) p.expect( self.prompt ) p.sendline( 'exit' ) p.wait() def testLink( self ): "Test link CLI command using ping" p = pexpect.spawn( 'mn' ) p.expect( self.prompt ) p.sendline( 'link s1 h1 down' ) p.expect( self.prompt ) p.sendline( 'h1 ping -c 1 h2' ) p.expect( 'unreachable' ) p.expect( self.prompt ) p.sendline( 'link s1 h1 up' ) p.expect( self.prompt ) p.sendline( 'h1 ping -c 1 h2' ) p.expect( '0% packet loss' ) p.expect( self.prompt ) p.sendline( 'exit' ) p.wait() @unittest.skipUnless( os.path.exists( '/tmp/pox' ) or '1 received' in quietRun( 'ping -c 1 github.com' ), 'Github is not reachable; cannot download Pox' ) def testRemoteController( self ): "Test Mininet using Pox controller" # Satisfy pylint assert self if not os.path.exists( '/tmp/pox' ): p = pexpect.spawn( 'git clone https://github.com/noxrepo/pox.git /tmp/pox' ) p.expect( pexpect.EOF ) pox = pexpect.spawn( '/tmp/pox/pox.py forwarding.l2_learning' ) net = pexpect.spawn( 'mn --controller=remote,ip=127.0.0.1,port=6633 --test pingall' ) net.expect( '0% dropped' ) net.expect( pexpect.EOF ) pox.sendintr() pox.wait() if __name__ == '__main__': unittest.main()
12,869
34.849582
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/test/test_switchdpidassignment.py
#!/usr/bin/env python """Package: mininet Regression tests for switch dpid assignment.""" import unittest import sys from mininet.net import Mininet from mininet.node import Host, Controller from mininet.node import ( UserSwitch, OVSSwitch, IVSSwitch ) from mininet.topo import Topo from mininet.log import setLogLevel from mininet.util import quietRun from mininet.clean import cleanup class TestSwitchDpidAssignmentOVS( unittest.TestCase ): "Verify Switch dpid assignment." switchClass = OVSSwitch # overridden in subclasses def tearDown( self ): "Clean up if necessary" # satisfy pylint assert self if sys.exc_info != ( None, None, None ): cleanup() def testDefaultDpid( self ): """Verify that the default dpid is assigned using a valid provided canonical switchname if no dpid is passed in switch creation.""" switch = Mininet( Topo(), self.switchClass, Host, Controller ).addSwitch( 's1' ) self.assertEqual( switch.defaultDpid(), switch.dpid ) def dpidFrom( self, num ): "Compute default dpid from number" fmt = ( '%0' + str( self.switchClass.dpidLen ) + 'x' ) return fmt % num def testActualDpidAssignment( self ): """Verify that Switch dpid is the actual dpid assigned if dpid is passed in switch creation.""" dpid = self.dpidFrom( 0xABCD ) switch = Mininet( Topo(), self.switchClass, Host, Controller ).addSwitch( 's1', dpid=dpid ) self.assertEqual( switch.dpid, dpid ) def testDefaultDpidAssignmentFailure( self ): """Verify that Default dpid assignment raises an Exception if the name of the switch does not contin a digit. Also verify the exception message.""" with self.assertRaises( Exception ) as raises_cm: Mininet( Topo(), self.switchClass, Host, Controller ).addSwitch( 'A' ) self.assertEqual(raises_cm.exception.message, 'Unable to derive ' 'default datapath ID - please either specify a dpid ' 'or use a canonical switch name such as s23.') def testDefaultDpidLen( self ): """Verify that Default dpid length is 16 characters consisting of 16 - len(hex of first string of contiguous digits passed in switch name) 0's followed by hex of first string of contiguous digits passed in switch name.""" switch = Mininet( Topo(), self.switchClass, Host, Controller ).addSwitch( 's123' ) self.assertEqual( switch.dpid, self.dpidFrom( 123 ) ) class OVSUser( OVSSwitch): "OVS User Switch convenience class" def __init__( self, *args, **kwargs ): kwargs.update( datapath='user' ) OVSSwitch.__init__( self, *args, **kwargs ) class testSwitchOVSUser( TestSwitchDpidAssignmentOVS ): "Test dpid assignnment of OVS User Switch." switchClass = OVSUser @unittest.skipUnless( quietRun( 'which ivs-ctl' ), 'IVS switch is not installed' ) class testSwitchIVS( TestSwitchDpidAssignmentOVS ): "Test dpid assignment of IVS switch." switchClass = IVSSwitch @unittest.skipUnless( quietRun( 'which ofprotocol' ), 'Reference user switch is not installed' ) class testSwitchUserspace( TestSwitchDpidAssignmentOVS ): "Test dpid assignment of Userspace switch." switchClass = UserSwitch if __name__ == '__main__': setLogLevel( 'warning' ) unittest.main()
3,638
36.132653
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/mininet/test/test_containernet.py
import unittest import os import time import subprocess import docker from mininet.net import Containernet from mininet.node import Host, Controller, OVSSwitch, Docker from mininet.link import TCLink from mininet.topo import SingleSwitchTopo, LinearTopo from mininet.log import setLogLevel from mininet.util import quietRun from mininet.clean import cleanup class simpleTestTopology( unittest.TestCase ): """ Helper class to do basic test setups. s1 -- s2 -- s3 -- ... -- sN """ def __init__(self, *args, **kwargs): self.net = None self.s = [] # list of switches self.h = [] # list of hosts self.d = [] # list of docker containers self.docker_cli = None super(simpleTestTopology, self).__init__(*args, **kwargs) def createNet( self, nswitches=1, nhosts=0, ndockers=0, autolinkswitches=False): """ Creates a Mininet instance and automatically adds some nodes to it. """ self.net = Containernet( controller=Controller ) self.net.addController( 'c0' ) # add some switches for i in range(0, nswitches): self.s.append(self.net.addSwitch('s%d' % i)) # if specified, chain all switches if autolinkswitches: for i in range(0, len(self.s) - 1): self.net.addLink(self.s[i], self.s[i + 1]) # add some hosts for i in range(0, nhosts): self.h.append(self.net.addHost('h%d' % i)) # add some dockers for i in range(0, ndockers): self.d.append(self.net.addDocker('d%d' % i, dimage="ubuntu:trusty")) def startNet(self): self.net.start() def stopNet(self): self.net.stop() def getDockerCli(self): """ Helper to interact with local docker instance. """ if self.docker_cli is None: self.docker_cli = docker.APIClient( base_url='unix://var/run/docker.sock') return self.docker_cli @staticmethod def setUp(): pass @staticmethod def tearDown(): cleanup() # make sure that all pending docker containers are killed with open(os.devnull, 'w') as devnull: subprocess.call( "docker rm -f $(docker ps --filter 'label=com.containernet' -a -q)", stdout=devnull, stderr=devnull, shell=True) def getContainernetContainers(self): """ List the containers managed by containernet """ return self.getDockerCli().containers(filters={"label": "com.containernet"}) #@unittest.skip("disabled connectivity tests for development") class testContainernetConnectivity( simpleTestTopology ): """ Tests to check connectivity of Docker containers within the emulated network. """ def testHostDocker( self ): """ d1 -- h1 """ # create network self.createNet(nswitches=0, nhosts=1, ndockers=1) # setup links self.net.addLink(self.h[0], self.d[0]) # start Mininet network self.startNet() # check number of running docker containers self.assertTrue(len(self.getContainernetContainers()) == 1) self.assertTrue(len(self.net.hosts) == 2) # check connectivity by using ping self.assertTrue(self.net.pingAll() <= 0.0) # stop Mininet network self.stopNet() def testDockerDocker( self ): """ d1 -- d2 """ # create network self.createNet(nswitches=0, nhosts=0, ndockers=2) # setup links self.net.addLink(self.d[0], self.d[1]) # start Mininet network self.startNet() # check number of running docker containers self.assertTrue(len(self.getContainernetContainers()) == 2) self.assertTrue(len(self.net.hosts) == 2) # check connectivity by using ping self.assertTrue(self.net.pingAll() <= 0.0) # stop Mininet network self.stopNet() def testHostSwtichDocker( self ): """ d1 -- s1 -- h1 """ # create network self.createNet(nswitches=1, nhosts=1, ndockers=1) # setup links self.net.addLink(self.h[0], self.s[0]) self.net.addLink(self.d[0], self.s[0]) # start Mininet network self.startNet() # check number of running docker containers self.assertTrue(len(self.getContainernetContainers()) == 1) self.assertTrue(len(self.net.hosts) == 2) # check connectivity by using ping self.assertTrue(self.net.pingAll() <= 0.0) # stop Mininet network self.stopNet() def testDockerSwtichDocker( self ): """ d1 -- s1 -- d2 """ # create network self.createNet(nswitches=1, nhosts=0, ndockers=2) # setup links self.net.addLink(self.d[0], self.s[0]) self.net.addLink(self.d[1], self.s[0]) # start Mininet network self.startNet() # check number of running docker containers self.assertTrue(len(self.getContainernetContainers()) == 2) self.assertTrue(len(self.net.hosts) == 2) # check connectivity by using ping self.assertTrue(self.net.pingAll() <= 0.0) # stop Mininet network self.stopNet() def testDockerMultipleInterfaces( self ): """ d1 -- s1 -- d2 -- s2 -- d3 d2 has two interfaces, each with its own subnet """ # create network self.createNet(nswitches=2, nhosts=0, ndockers=2) # add additional Docker with special IP self.d.append(self.net.addDocker( 'd%d' % len(self.d), ip="11.0.0.2", dimage="ubuntu:trusty")) # setup links self.net.addLink(self.s[0], self.s[1]) self.net.addLink(self.d[0], self.s[0]) self.net.addLink(self.d[1], self.s[0]) self.net.addLink(self.d[2], self.s[1]) # special link that add second interface to d2 self.net.addLink( self.d[1], self.s[1], params1={"ip": "11.0.0.1/8"}) # start Mininet network self.startNet() # check number of running docker containers self.assertTrue(len(self.getContainernetContainers()) == 3) self.assertTrue(len(self.net.hosts) == 3) # check connectivity by using ping self.assertTrue(self.net.ping([self.d[0], self.d[1]]) <= 0.0) self.assertTrue(self.net.ping([self.d[2]], manualdestip="11.0.0.1") <= 0.0) self.assertTrue(self.net.ping([self.d[1]], manualdestip="11.0.0.2") <= 0.0) # stop Mininet network self.stopNet() #@unittest.skip("disabled command execution tests for development") class testContainernetContainerCommandExecution( simpleTestTopology ): """ Test to check the command execution inside Docker containers by using the Mininet API. """ def testCommandSimple( self ): """ d1 ls d1 ifconfig -a d1 ping 127.0.0.1 -c 3 """ # create network self.createNet(nswitches=1, nhosts=0, ndockers=1) # setup links (we always need one connection to suppress warnings) self.net.addLink(self.d[0], self.s[0]) # start Mininet network self.startNet() # check number of running docker containers self.assertTrue(len(self.getContainernetContainers()) == 1) self.assertTrue("etc" in self.d[0].cmd("ls")) self.assertTrue("d0-eth0" in self.d[0].cmd("ifconfig -a")) self.assertTrue("0%" in self.d[0].cmd("ping 127.0.0.1 -c 3")) # stop Mininet network self.stopNet() #@unittest.skip("disabled dynamic topology tests for development") class testContainernetDynamicTopologies( simpleTestTopology ): """ Tests to check dynamic topology support which allows to add and remove containers to/from a running Mininet network instance. """ def testSimpleAdd( self ): """ start: d0 -- s0 add d1 """ # create network self.createNet(nswitches=1, nhosts=0, ndockers=1) # setup links self.net.addLink(self.s[0], self.d[0]) # start Mininet network self.startNet() # check number of running docker containers self.assertTrue(len(self.getContainernetContainers()) == 1) self.assertTrue(len(self.net.hosts) == 1) # add d2 and connect it on-the-fly d2 = self.net.addDocker('d2', dimage="ubuntu:trusty") self.net.addLink(d2, self.s[0], params1={"ip": "10.0.0.254/8"}) # check number of running docker containers self.assertTrue(len(self.getContainernetContainers()) == 2) self.assertTrue(len(self.net.hosts) == 2) # check connectivity by using ping self.assertTrue(self.net.ping([self.d[0]], manualdestip="10.0.0.254") <= 0.0) # stop Mininet network self.stopNet() def testSimpleRemove( self ): """ start: d0 -- s0 -- d1 remove d1 """ # create network self.createNet(nswitches=1, nhosts=0, ndockers=2) # setup links self.net.addLink(self.s[0], self.d[0]) self.net.addLink(self.s[0], self.d[1]) # start Mininet network self.startNet() # check number of running docker containers self.assertTrue(len(self.getContainernetContainers()) == 2) self.assertTrue(len(self.net.hosts) == 2) self.assertTrue(len(self.net.links) == 2) # check connectivity by using ping self.assertTrue(self.net.ping([self.d[0]], manualdestip="10.0.0.2") <= 0.0) # remove d2 on-the-fly self.net.removeLink(node1=self.d[1], node2=self.s[0]) self.net.removeDocker(self.d[1]) # check number of running docker containers self.assertTrue(len(self.getContainernetContainers()) == 1) self.assertTrue(len(self.net.hosts) == 1) self.assertTrue(len(self.net.links) == 1) # check connectivity by using ping (now it should be broken) self.assertTrue(self.net.ping( [self.d[0]], manualdestip="10.0.0.2", timeout=1) >= 100.0) # stop Mininet network self.stopNet() def testFullyDynamic( self ): """ start: s1 -- h1 (for ping tests) add d0, d1, d2, d3 remove d0, d1 add d4 remove d2, d3, d4 """ # create network self.createNet(nswitches=1, nhosts=1, ndockers=0) # setup links self.net.addLink(self.s[0], self.h[0]) # start Mininet network self.startNet() # check number of running docker containers self.assertTrue(len(self.getContainernetContainers()) == 0) self.assertTrue(len(self.net.hosts) == 1) self.assertTrue(len(self.net.links) == 1) ### add some containers: d0, d1, d2, d3 d0 = self.net.addDocker('d0', dimage="ubuntu:trusty") self.net.addLink(d0, self.s[0], params1={"ip": "10.0.0.200/8"}) d1 = self.net.addDocker('d1', dimage="ubuntu:trusty") self.net.addLink(d1, self.s[0], params1={"ip": "10.0.0.201/8"}) d2 = self.net.addDocker('d2', dimage="ubuntu:trusty") self.net.addLink(d2, self.s[0], params1={"ip": "10.0.0.202/8"}) d3 = self.net.addDocker('d3', dimage="ubuntu:trusty") self.net.addLink(d3, self.s[0], params1={"ip": "10.0.0.203/8"}) # check number of running docker containers self.assertTrue(len(self.getContainernetContainers()) == 4) self.assertTrue(len(self.net.hosts) == 5) self.assertTrue(len(self.net.links) == 5) # check connectivity by using ping self.assertTrue(self.net.ping([self.h[0]], manualdestip="10.0.0.200") <= 0.0) self.assertTrue(self.net.ping([self.h[0]], manualdestip="10.0.0.201") <= 0.0) self.assertTrue(self.net.ping([self.h[0]], manualdestip="10.0.0.202") <= 0.0) self.assertTrue(self.net.ping([self.h[0]], manualdestip="10.0.0.203") <= 0.0) ### remove d0, d1 self.net.removeLink(node1=d0, node2=self.s[0]) self.net.removeDocker(d0) self.net.removeLink(node1=d1, node2=self.s[0]) self.net.removeDocker(d1) # check number of running docker containers self.assertTrue(len(self.getContainernetContainers()) == 2) self.assertTrue(len(self.net.hosts) == 3) self.assertTrue(len(self.net.links) == 3) # check connectivity by using ping self.assertTrue(self.net.ping( [self.h[0]], manualdestip="10.0.0.200", timeout=1) >= 100.0) self.assertTrue(self.net.ping( [self.h[0]], manualdestip="10.0.0.201", timeout=1) >= 100.0) ### add container: d4 d4 = self.net.addDocker('d4', dimage="ubuntu:trusty") self.net.addLink(d4, self.s[0], params1={"ip": "10.0.0.204/8"}) # check number of running docker containers self.assertTrue(len(self.getContainernetContainers()) == 3) self.assertTrue(len(self.net.hosts) == 4) self.assertTrue(len(self.net.links) == 4) # check connectivity by using ping self.assertTrue(self.net.ping([self.h[0]], manualdestip="10.0.0.204") <= 0.0) ### remove all containers self.net.removeLink(node1=d2, node2=self.s[0]) self.net.removeDocker(d2) self.net.removeLink(node1=d3, node2=self.s[0]) self.net.removeDocker(d3) self.net.removeLink(node1=d4, node2=self.s[0]) self.net.removeDocker(d4) # check number of running docker containers self.assertTrue(len(self.getContainernetContainers()) == 0) self.assertTrue(len(self.net.hosts) == 1) self.assertTrue(len(self.net.links) == 1) # check connectivity by using ping self.assertTrue(self.net.ping( [self.h[0]], manualdestip="10.0.0.202", timeout=1) >= 100.0) self.assertTrue(self.net.ping( [self.h[0]], manualdestip="10.0.0.203", timeout=1) >= 100.0) self.assertTrue(self.net.ping( [self.h[0]], manualdestip="10.0.0.204", timeout=1) >= 100.0) # stop Mininet network self.stopNet() #@unittest.skip("disabled TCLink tests for development") class testContainernetTCLinks( simpleTestTopology ): """ Tests to check TCLinks together with Docker containers. """ def testCustomDelay( self ): """ d0,d1 -- s0 --delay-- d2 """ # create network self.createNet(nswitches=1, nhosts=0, ndockers=3) # setup links self.net.addLink(self.s[0], self.d[0]) self.net.addLink(self.s[0], self.d[1]) self.net.addLink(self.s[0], self.d[2], cls=TCLink, delay="100ms") # start Mininet network self.startNet() # check number of running docker containers self.assertTrue(len(self.getContainernetContainers()) == 3) self.assertTrue(len(self.net.hosts) == 3) # check connectivity by using ping: default link _, _, res = self.net.pingFull([self.d[0]], manualdestip="10.0.0.2")[0] self.assertTrue(res[3] <= 20) # check connectivity by using ping: delayed TCLink _, _, res = self.net.pingFull([self.d[0]], manualdestip="10.0.0.3")[0] self.assertTrue(res[3] > 200 and res[3] < 500) # stop Mininet network self.stopNet() def testCustomLoss( self ): """ d0,d1 -- s0 --loss-- d2 """ # create network self.createNet(nswitches=1, nhosts=0, ndockers=3) # setup links self.net.addLink(self.s[0], self.d[0]) self.net.addLink(self.s[0], self.d[1]) self.net.addLink( self.s[0], self.d[2], cls=TCLink, loss=100) # 100% loss # start Mininet network self.startNet() # check number of running docker containers self.assertTrue(len(self.getContainernetContainers()) == 3) self.assertTrue(len(self.net.hosts) == 3) # check connectivity by using ping: default link self.assertTrue(self.net.ping( [self.d[0]], manualdestip="10.0.0.2", timeout=1) <= 0.0) # check connectivity by using ping: lossy TCLink (100%) self.assertTrue(self.net.ping( [self.d[0]], manualdestip="10.0.0.3", timeout=1) >= 100.0) # stop Mininet network self.stopNet() #@unittest.skip("disabled container resource limit tests for development") class testContainernetContainerResourceLimitAPI( simpleTestTopology ): """ Test to check the resource limitation API of the Docker integration. TODO: Also check if values are set correctly in to running containers, e.g., with: docker inspect mn.d1 CLI calls? """ def testCPUShare( self ): """ d1, d2 with CPU share limits """ # create network self.createNet(nswitches=1, nhosts=0, ndockers=0) # add dockers d0 = self.net.addDocker('d0', ip='10.0.0.1', dimage="ubuntu:trusty", cpu_shares=10) d1 = self.net.addDocker('d1', ip='10.0.0.2', dimage="ubuntu:trusty", cpu_shares=90) # setup links (we always need one connection to suppress warnings) self.net.addLink(d0, self.s[0]) self.net.addLink(d1, self.s[0]) # start Mininet network self.startNet() # check number of running docker containers self.assertTrue(len(self.net.hosts) == 2) # check connectivity by using ping: default link self.assertTrue(self.net.ping([d0, d1]) <= 0.0) # stop Mininet network self.stopNet() def testCPULimitCFSBased( self ): """ d1, d2 with CPU share limits """ # create network self.createNet(nswitches=1, nhosts=0, ndockers=0) # add dockers d0 = self.net.addDocker( 'd0', ip='10.0.0.1', dimage="ubuntu:trusty", cpu_period=50000, cpu_quota=10000) d1 = self.net.addDocker( 'd1', ip='10.0.0.2', dimage="ubuntu:trusty", cpu_period=50000, cpu_quota=10000) # setup links (we always need one connection to suppress warnings) self.net.addLink(d0, self.s[0]) self.net.addLink(d1, self.s[0]) # start Mininet network self.startNet() # check number of running docker containers self.assertTrue(len(self.net.hosts) == 2) # check connectivity by using ping: default link self.assertTrue(self.net.ping([d0, d1]) <= 0.0) # stop Mininet network self.stopNet() def testMemLimits( self ): """ d1, d2 with CPU share limits """ # create network self.createNet(nswitches=1, nhosts=0, ndockers=0) # add dockers d0 = self.net.addDocker( 'd0', ip='10.0.0.1', dimage="ubuntu:trusty", mem_limit=132182016) d1 = self.net.addDocker( 'd1', ip='10.0.0.2', dimage="ubuntu:trusty", mem_limit=132182016) # setup links (we always need one connection to suppress warnings) self.net.addLink(d0, self.s[0]) self.net.addLink(d1, self.s[0]) # start Mininet network self.startNet() # check number of running docker containers self.assertTrue(len(self.net.hosts) == 2) # check connectivity by using ping: default link self.assertTrue(self.net.ping([d0, d1]) <= 0.0) # stop Mininet network self.stopNet() def testRuntimeCPULimitUpdate(self): """ Test CPU limit update at runtime """ # create network self.createNet(nswitches=1, nhosts=0, ndockers=0) # add dockers d0 = self.net.addDocker( 'd0', ip='10.0.0.1', dimage="ubuntu:trusty", cpu_share=0.3) d1 = self.net.addDocker( 'd1', ip='10.0.0.2', dimage="ubuntu:trusty", cpu_period=50000, cpu_quota=10000) # setup links (we always need one connection to suppress warnings) self.net.addLink(d0, self.s[0]) self.net.addLink(d1, self.s[0]) # start Mininet network self.startNet() # check number of running docker containers self.assertTrue(len(self.net.hosts) == 2) # check connectivity by using ping: default link self.assertTrue(self.net.ping([d0, d1]) <= 0.0) # update limits d0.updateCpuLimit(cpu_shares=512) self.assertEqual(d0.resources['cpu_shares'], 512) d1.updateCpuLimit(cpu_period=50001, cpu_quota=20000) self.assertEqual(d1.resources['cpu_period'], 50001) self.assertEqual(d1.resources['cpu_quota'], 20000) # stop Mininet network self.stopNet() def testRuntimeMemoryLimitUpdate(self): """ Test mem limit update at runtime """ # create network self.createNet(nswitches=1, nhosts=0, ndockers=0) # add dockers d0 = self.net.addDocker( 'd0', ip='10.0.0.1', dimage="ubuntu:trusty", mem_limit=132182016) d1 = self.net.addDocker( 'd1', ip='10.0.0.2', dimage="ubuntu:trusty", ) # setup links (we always need one connection to suppress warnings) self.net.addLink(d0, self.s[0]) self.net.addLink(d1, self.s[0]) # start Mininet network self.startNet() # check number of running docker containers self.assertTrue(len(self.net.hosts) == 2) # check connectivity by using ping: default link self.assertTrue(self.net.ping([d0, d1]) <= 0.0) # update limits d0.updateMemoryLimit(mem_limit=66093056) self.assertEqual(d0.resources['mem_limit'], 66093056) d1.updateMemoryLimit(memswap_limit=-1) self.assertEqual(d1.resources['memswap_limit'], None) # stop Mininet network self.stopNet() #@unittest.skip("disabled container resource limit tests for development") class testContainernetVolumeAPI( simpleTestTopology ): """ Test the volume API. """ def testContainerVolumes( self ): """ d1, d2 with volumes """ # create network self.createNet(nswitches=1, nhosts=0, ndockers=0) # add dockers d0 = self.net.addDocker('d0', ip='10.0.0.1', dimage="ubuntu:trusty", volumes=["/:/mnt/vol1:rw"]) d1 = self.net.addDocker('d1', ip='10.0.0.2', dimage="ubuntu:trusty", volumes=["/:/mnt/vol1:rw", "/:/mnt/vol2:rw"]) # start Mininet network self.startNet() # check if we can see the root file system self.assertTrue("etc" in d0.cmd("ls /mnt/vol1")) self.assertTrue("etc" in d1.cmd("ls /mnt/vol1")) self.assertTrue("etc" in d1.cmd("ls /mnt/vol2")) # stop Mininet network self.stopNet() if __name__ == '__main__': unittest.main()
23,033
37.39
122
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ansible/install.yml
- hosts: localhost tasks: - name: updates apt shell: apt-get -qq update - name: install basic packages apt: name={{item}} state=installed with_items: - aptitude - apt-transport-https - ca-certificates - curl - python-setuptools - python-dev - build-essential - python-pip - iptables - software-properties-common - name: install Docker CE repos (1/3) shell: curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - - name: install Docker CE repos (2/3) #shell: add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" shell: add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) pool stable amd64" - name: install Docker CE repos (3/3) shell: apt-get -qq update - name: install Docker CE apt: name=docker-ce=17.06.2~ce-0~ubuntu force=yes - name: install pytest pip: name=pytest state=latest - name: install docker-py pip: name=docker version=2.0.2 - name: install python-iptables pip: name=python-iptables version=0.12 - name: install networkx pip: name=networkx version=2.2 - name: install python-fnss pip: name=fnss version=0.8.2 - name: install pandas pip: name=pandas state=latest - name: install lxml pip: name=lxml state=latest - name: install tabulate pip: name=tabulate state=latest - name: install ifparser pip: name=ifparser state=latest - name: built and install Containernet (using Mininet installer) shell: containernet/util/install.sh args: chdir: ../../ - name: install Containernet Python egg etc. shell: make develop args: chdir: ../ - name: download 'ubuntu' docker image for Containernet example shell: docker pull ubuntu:trusty
1,927
25.777778
127
yml
cba-pipeline-public
cba-pipeline-public-master/containernet/custom/topo-2sw-2host.py
"""Custom topology example Two directly connected switches plus a host for each switch: host --- switch --- switch --- host Adding the 'topos' dict with a key/value pair to generate our newly defined topology enables one to pass in '--topo=mytopo' from the command line. """ from mininet.topo import Topo class MyTopo( Topo ): "Simple topology example." def __init__( self ): "Create custom topo." # Initialize topology Topo.__init__( self ) # Add hosts and switches leftHost = self.addHost( 'h1' ) rightHost = self.addHost( 'h2' ) leftSwitch = self.addSwitch( 's3' ) rightSwitch = self.addSwitch( 's4' ) # Add links self.addLink( leftHost, leftSwitch ) self.addLink( leftSwitch, rightSwitch ) self.addLink( rightSwitch, rightHost ) topos = { 'mytopo': ( lambda: MyTopo() ) }
894
24.571429
75
py
cba-pipeline-public
cba-pipeline-public-master/visualization/figure_configuration_ieee_standard.py
import matplotlib def figure_configuration_ieee_standard(): # IEEE Standard Figure Configuration - Version 1.0 # run this code before the plot command # # According to the standard of IEEE Transactions and Journals: # Times New Roman is the suggested font in labels. # For a singlepart figure, labels should be in 8 to 10 points, # whereas for a multipart figure, labels should be in 8 points. # Width: column width: 8.8 cm; page width: 18.1 cm. # width & height of the figure k_scaling = 1 # scaling factor of the figure # (You need to plot a figure which has a width of (8.8 * k_scaling) # in MATLAB, so that when you paste it into your paper, the width will be # scalled down to 8.8 cm which can guarantee a preferred clearness. k_width_height = 1.5#1.3 # width:height ratio of the figure fig_width = 8.8/2.54 * k_scaling fig_height = fig_width / k_width_height # ## figure margins # top = 0.5 # normalized top margin # bottom = 3 # normalized bottom margin # left = 4 # normalized left margin # right = 1.5 # normalized right margin params = {'axes.labelsize': 8, # fontsize for x and y labels (was 10) 'axes.titlesize': 8, 'font.size': 8, # was 10 'legend.fontsize': 8, # was 10 'xtick.labelsize': 8, 'ytick.labelsize': 8, 'figure.figsize': [fig_width, fig_height], 'font.family': 'serif', 'font.serif': ['Times New Roman'], 'lines.linewidth': 2.5, 'axes.linewidth': 1, 'axes.grid': True, 'savefig.format': 'pdf', 'axes.xmargin': 0, 'axes.ymargin': 0, 'savefig.pad_inches': 0, 'legend.markerscale': 1, 'savefig.bbox': 'tight', 'lines.markersize': 2, 'legend.numpoints': 4, 'legend.handlelength': 3.5, } matplotlib.rcParams.update(params)
2,053
32.672131
77
py
cba-pipeline-public
cba-pipeline-public-master/visualization/make_fairness_graph.py
import numpy as np import matplotlib.pyplot as plt import pickle import pandas as pd from figure_configuration_ieee_standard import figure_configuration_ieee_standard from scipy.interpolate import interp1d def main(): #sbu_client1 = np.load('sbu-100-doubles-tc-mem_client1.npy') #sbu_client2 = np.load('sbu-100-doubles-tc-mem_client2.npy') #sbuose_client1 = np.load('sbuose-100-doubles-tc-mem_client1.npy') #sbuose_client2 = np.load('sbuose-100-doubles-tc-mem_client2.npy') #data_pandas = load_results('data_pandas_df.pkl') #data_pandas2= load_results('data_pandas_df_2.pkl') #data_pandas3 = load_results('data_pandas_df_3.pkl') ##trace = np.loadtxt(open("trevor_trace.csv", "rb"), delimiter=",", skiprows=1) # ## Quality plots singles #pd = data_pandas[0].values # #sbuose_quality = pd[197:99:-1, 3] #sbuose_rebuf = pd[197:99:-1, 8] #sbuose_extime = pd[197:99:-1, 11] #sbuose_qoe = pd[197:99:-1, 9] #t_sbuose = pd[197:99:-1, 15] # #sbu_quality = pd[496:398:-1, 3] #sbu_rebuf = pd[496:398:-1, 8] #sbu_extime = pd[496:398:-1, 11] #sbu_qoe = pd[496:398:-1, 9] #t_sbu = pd[496:398:-1, 15] # # %% Fairness #N_points=1000 #t_fairness = np.linspace(5, 175, num=N_points) #sbuose_qoe_client2 = pd[197:99:-1, 9] #t_sbuose_client2 = pd[197:99:-1, 15] #f_sbuose_qoe_client2 = interp1d(t_sbuose_client2, sbuose_qoe_client2) #sbuose_qoe_client2_resam = f_sbuose_qoe_client2(t_fairness) # #sbuose_qoe_client1 = pd[297:199:-1, 9] #t_sbuose_client1 = pd[297:199:-1, 15] #f_sbuose_qoe_client1 = interp1d(t_sbuose_client1, sbuose_qoe_client1) #sbuose_qoe_client1_resam = f_sbuose_qoe_client1(t_fairness) # #sbu_qoe_client2 = pd[496:398:-1, 9] #t_sbu_client2 = pd[496:398:-1, 15] #f_sbu_qoe_client2 = interp1d(t_sbu_client2, sbu_qoe_client2) #sbu_qoe_client2_resam = f_sbu_qoe_client2(t_fairness) # #sbu_qoe_client1 = pd[595:497:-1, 9] #t_sbu_client1 = pd[595:497:-1, 15] #f_sbu_qoe_client1 = interp1d(t_sbu_client1, sbu_qoe_client1) #sbu_qoe_client1_resam = f_sbu_qoe_client1(t_fairness) # %% Fairness N_points=1000 t_fairness = np.linspace(5, 175, num=N_points) suffix = '_60-20-20_mem' # Remove negative values by adding to everything #sbu=np.load('sbu_client1{}.npy'.format(suffix)) #sbu2 = np.load('sbu_client2{}.npy'.format(suffix)) #sbuose=np.load('sbuose_client1{}.npy'.format(suffix)) #sbuose2 = np.load('sbuose_client2{}.npy'.format(suffix)) #panda=np.load('p_client1{}.npy'.format(suffix)) #panda2 = np.load('p_client2{}.npy'.format(suffix)) #bola=np.load('bola_client1{}.npy'.format(suffix)) #bola2 = np.load('bola_client2{}.npy'.format(suffix)) #linucb=np.load('linucb_client1{}.npy'.format(suffix)) #linucb2 = np.load('linucb_client2{}.npy'.format(suffix)) #min_val = np.min([np.min(sbu[:,1]),np.min(sbu2[:,1]), # np.min(sbuose[:,1]),np.min(sbuose2[:,1]), # np.min(panda[:,1]),np.min(panda2[:,1]), # np.min(bola[:,1]),np.min(bola2[:,1]), # np.min(linucb[:,1]),np.min(linucb2[:,1])]) #print(min_val) #if min_val < 0: # sbu[:,1] = sbu[:,1] + min_val # sbu2[:,1] = sbu2[:,1] + min_val # sbuose[:,1] = sbuose[:,1] + min_val # sbuose2[:,1] = sbuose2[:,1] + min_val # panda[:,1] = panda[:,1] + min_val # panda2[:,1] = panda2[:,1] + min_val # bola[:,1] = bola[:,1] + min_val # bola2[:,1] = bola2[:,1] + min_val # linucb[:,1] = linucb[:,1] + min_val # linucb2[:,1] = linucb2[:,1] + min_val # SBU sbu=np.load('sbu_client1{}.npy'.format(suffix)) sbu2 = np.load('sbu_client2{}.npy'.format(suffix)) qoenorm=np.min([np.min(sbu[:,1]),np.min(sbu2[:,1])]) sbu_client1 = sbu[:,1]-qoenorm t_sbu_client1 = sbu[:,0] f_sbu_qoe_client1 = interp1d(t_sbu_client1, sbu_client1) sbu_qoe_client1_resam = f_sbu_qoe_client1(t_fairness) sbu_client2 = sbu2[:,1]-qoenorm t_sbu_client2 = sbu2[:,0] f_sbu_qoe_client2 = interp1d(t_sbu_client2, sbu_client2) sbu_qoe_client2_resam = f_sbu_qoe_client2(t_fairness) # SBU-OSE sbuose=np.load('sbuose_client1{}.npy'.format(suffix)) sbuose2 = np.load('sbuose_client2{}.npy'.format(suffix)) qoenorm=np.min([np.min(sbuose[:,1]),np.min(sbuose2[:,1])]) sbuose_client1 = sbuose[:,1]-qoenorm t_sbuose_client1 = sbuose[:,0] f_sbuose_qoe_client1 = interp1d(t_sbuose_client1, sbuose_client1) sbuose_qoe_client1_resam = f_sbuose_qoe_client1(t_fairness) sbuose_client2 = sbuose2[:,1]-qoenorm t_sbuose_client2 = sbuose2[:,0] f_sbuose_qoe_client2 = interp1d(t_sbuose_client2, sbuose_client2) sbuose_qoe_client2_resam = f_sbuose_qoe_client2(t_fairness) # PANDA panda=np.load('p_client1{}.npy'.format(suffix)) panda2 = np.load('p_client2{}.npy'.format(suffix)) qoenorm=np.min([np.min(panda[:,1]),np.min(panda2[:,1])]) panda_client1 = panda[:,1]-qoenorm t_panda_client1 = panda[:,0] f_panda_qoe_client1 = interp1d(t_panda_client1, panda_client1) panda_qoe_client1_resam = f_panda_qoe_client1(t_fairness) panda_client2 = panda2[:,1]-qoenorm t_panda_client2 = panda2[:,0] f_panda_qoe_client2 = interp1d(t_panda_client2, panda_client2) panda_qoe_client2_resam = f_panda_qoe_client2(t_fairness) # BOLA bola=np.load('bola_client1{}.npy'.format(suffix)) bola2 = np.load('bola_client2{}.npy'.format(suffix)) qoenorm=np.min([np.min(bola[:,1]),np.min(bola2[:,1])]) bola_client1 = bola[:,1]-qoenorm t_bola_client1 = bola[:,0] f_bola_qoe_client1 = interp1d(t_bola_client1, bola_client1) bola_qoe_client1_resam = f_bola_qoe_client1(t_fairness) bola_client2 = bola2[:,1]-qoenorm t_bola_client2 = bola2[:,0] f_bola_qoe_client2 = interp1d(t_bola_client2, bola_client2) bola_qoe_client2_resam = f_bola_qoe_client2(t_fairness) # LinUCB linucb=np.load('linucb_client1{}.npy'.format(suffix)) linucb2 = np.load('linucb_client2{}.npy'.format(suffix)) qoenorm=np.min([np.min(linucb[:,1]),np.min(linucb2[:,1])]) linucb_client1 = linucb[:,1]-qoenorm t_linucb_client1 = linucb[:,0] f_linucb_qoe_client1 = interp1d(t_linucb_client1, linucb_client1) linucb_qoe_client1_resam = f_linucb_qoe_client1(t_fairness) linucb_client2 = linucb2[:,1]-qoenorm t_linucb_client2 = linucb2[:,0] f_linucb_qoe_client2 = interp1d(t_linucb_client2, linucb_client2) linucb_qoe_client2_resam = f_linucb_qoe_client2(t_fairness) # bola = np.load('linucb-100-doubles-tc-membola-100-doubles-tc-na_client1.npy') # bola_client1 = bola[:, 1] # t_bola_client1 = bola[:, 0] # f_bola_qoe_client1 = interp1d(t_bola_client1, bola_client1) # bola_qoe_client1_resam = f_bola_qoe_client1(t_fairness) sbuose_qoe_fairness = fairness(sbuose_qoe_client1_resam, sbuose_qoe_client2_resam) sbu_qoe_fairness = fairness(sbu_qoe_client1_resam, sbu_qoe_client2_resam) panda_qoe_fairness = fairness(panda_qoe_client1_resam, panda_qoe_client2_resam) bola_qoe_fairness = fairness(bola_qoe_client1_resam, bola_qoe_client2_resam) linucb_qoe_fairness = fairness(linucb_qoe_client1_resam, linucb_qoe_client2_resam) # %%Plot! figure_configuration_ieee_standard() # %% k_scaling = 2 fig_width = 8.8/2.54 * k_scaling fig_height = 4.4/2.54 * k_scaling params = {'figure.figsize': [fig_width, fig_height], 'axes.labelsize': 8*k_scaling, # fontsize for x and y labels (was 10) 'axes.titlesize': 8*k_scaling, 'font.size': 8*k_scaling, # was 10 'legend.fontsize': 8*k_scaling, # was 10 'xtick.labelsize': 8*k_scaling, 'ytick.labelsize': 8*k_scaling, 'xtick.major.width': 1*k_scaling, 'xtick.major.size': 3.5*k_scaling, 'ytick.major.width': 1*k_scaling, 'ytick.major.size': 3.5*k_scaling, 'lines.linewidth': 2.5*k_scaling, 'axes.linewidth': 1*k_scaling, 'axes.grid': True, 'savefig.format': 'pdf', 'axes.xmargin': 0, 'axes.ymargin': 0, 'savefig.pad_inches': 0, 'legend.markerscale': 1*k_scaling, 'savefig.bbox': 'tight', 'lines.markersize': 3*k_scaling, #'legend.numpoints': 4*k_scaling, #'legend.handlelength': 3.5*k_scaling, } import matplotlib matplotlib.rcParams.update(params) plt.figure() plt.plot(t_fairness, np.cumsum(np.ones(N_points))-np.cumsum(sbuose_qoe_fairness), '-.', label='CBA-OS-SVI',color='tab:green') plt.plot(t_fairness, np.cumsum(np.ones(N_points))-np.cumsum(sbu_qoe_fairness), ':', label="CBA-VB",color='tab:green') plt.plot(t_fairness, np.cumsum(np.ones(N_points)) - np.cumsum(linucb_qoe_fairness), '^', label="LinUCB", color='tab:orange', markevery=20) plt.plot(t_fairness, np.cumsum(np.ones(N_points))-np.cumsum(panda_qoe_fairness), '-', label="PANDA") plt.plot(t_fairness, np.cumsum(np.ones(N_points)) - np.cumsum(bola_qoe_fairness), '--', label="BOLA",color='tab:red') plt.xlabel("time [s]") #plt.xlim(0, 180) plt.ylabel("Regret of QoE Fairness") lgnd = plt.legend(loc='lower right') for lh in lgnd.legendHandles: lh._legmarker.set_markersize(7) fig = plt.gcf() fig.savefig('fairness{}'.format(suffix)) plt.show() test=1 # # plt.plot(mean_rew_f_oracle - mean_rew_f_sbo, '-.', label="OS-SVI") # plt.plot(mean_rew_f_oracle - mean_rew_f_sbsvi, '^', label="SVI", markevery=40) # plt.plot(mean_rew_f_oracle - mean_rew_f_sbvb, ':', label="VB") # # %% # plt.figure() # plt.step(t_sbuose, sbuose_quality, '-', label='CBA-OS-SVI') # plt.plot(t_sbu, sbu_quality, '--', label="CBA-VB") # plt.xlabel("time [s]") # plt.ylabel("Quality Level") # plt.legend() # fig = plt.gcf() # # fig.savefig('qoe_single') # plt.show() # # # %% # plt.figure() # plt.plot(t_sbuose, sbuose_qoe, '-', label='CBA-OS-SVI') # plt.plot(t_sbu, sbu_qoe, '--', label="CBA-VB") # # plt.xlabel("time [s]") # plt.ylabel("QoE") # plt.legend() # fig = plt.gcf() # # fig.savefig('qoe_single') # plt.show() # # # %% # plt.figure() # plt.plot(t_sbuose, sbuose_rebuf, '-', label='CBA-OS-SVI') # plt.plot(t_sbu, sbu_rebuf, '--', label="CBA-VB") # plt.xlabel("time [s]") # plt.ylabel("Rebuffering [ms]") # plt.legend() # fig = plt.gcf() # # fig.savefig('qoe_single') # plt.show() # # # %% # plt.figure() # plt.plot(t_sbuose, sbuose_extime, '-', label='CBA-OS-SVI') # plt.plot(t_sbu, sbu_extime, '--', label="CBA-VB") # # plt.xlabel("time [s]") # plt.ylabel("Runtime Learning [ms]") # plt.legend() # fig = plt.gcf() # # fig.savefig('qoe_single') # plt.show() # # # %% # plt.figure() # plt.step(np.cumsum(trace[0:30, 0]), trace[0:30, 1], '-') # plt.xlabel("time [s]") # plt.ylabel("Bandwidth [Mbit/s]") # fig = plt.gcf() # # fig.savefig('qoe_single') # plt.show() def load_results(path): results = [] with open(path, 'rb') as input: while 1: try: results.append(pickle.load(input)) except EOFError: break input.close() return results def fairness(qoe1, qoe2): relative_qoe = qoe1 / (qoe1+qoe2) mu_fairness = binary_entropy(relative_qoe) return mu_fairness def binary_entropy(p): p = np.array(p, dtype=np.float32) h = -(1 - p) * np.log2(1 - p) - p * np.log2(p) return h if __name__ == '__main__': main()
11,808
35.560372
129
py