def monkey_patch_pox(): '''Override two key bits of POX functionality: the Timer class and the openflow connection class. Other overrides are mainly to ensure that nothing unexpected happens, but are strictly not necessary at present (using betta branch of POX)''' get_logger().info("Monkeypatching POX for integration with fs") fakerlib = PoxLibPlug() import pox.lib.recoco as recoco setattr(recoco, "Timer", FakePoxTimer) import pox.lib setattr(pox.lib, "ioworker", fakerlib) setattr(pox.lib, "pxpcap", fakerlib) setattr(pox.lib, "socketcapture", fakerlib) import pox setattr(pox, "messenger", fakerlib) setattr(pox, "misc", fakerlib) setattr(ofcore, "Connection", FakeOpenflowConnection) setattr(ofcore, "OpenFlow_01_Task", fakerlib) import pox.core setattr(pox.core, "getLogger", get_pox_logger)
def parse_delay(delay): '''Parse config file delay, return delay as a float in seconds''' if isinstance(delay, (int,float)): return float(delay) elif isinstance(delay, (str, unicode)): if re.match('^(\d*\.?\d+)$', delay): return float(delay) # [sS]+anything assumed to be seconds mobj = re.match('^(\d*\.?\d+)s', delay, re.IGNORECASE) if mobj: return float(mobj.groups()[0]) # [ms]+anything assumed to be milliseconds mobj = re.match('^(\d*\.?\d+)ms', delay, re.IGNORECASE) if mobj: return float(mobj.groups()[0]) / 1000.0 # [us]+anything assumed to be microseconds mobj = re.match('^(\d*\.?\d+)us', delay, re.IGNORECASE) if mobj: return float(mobj.groups()[0]) / 1000000.0 get_logger().error("Can't parse link delay: {}".format(delay)) sys.exit(-1)
def parse_delay(delay): '''Parse config file delay, return delay as a float in seconds''' if isinstance(delay, (int, float)): return float(delay) elif isinstance(delay, (str, unicode)): if re.match('^(\d*\.?\d+)$', delay): return float(delay) # [sS]+anything assumed to be seconds mobj = re.match('^(\d*\.?\d+)s', delay, re.IGNORECASE) if mobj: return float(mobj.groups()[0]) # [ms]+anything assumed to be milliseconds mobj = re.match('^(\d*\.?\d+)ms', delay, re.IGNORECASE) if mobj: return float(mobj.groups()[0]) / 1000.0 # [us]+anything assumed to be microseconds mobj = re.match('^(\d*\.?\d+)us', delay, re.IGNORECASE) if mobj: return float(mobj.groups()[0]) / 1000000.0 get_logger().error("Can't parse link delay: {}".format(delay)) sys.exit(-1)
def __init__(self, timeToWake, callback, absoluteTime=False, recurring=False, args=(), kw={}, scheduler=None, started=True, selfStoppable=True): if absoluteTime and recurring: raise RuntimeError( "Can't have a recurring timer for an absolute time!") if absoluteTime: raise RuntimeError("Can't have an absolute time in FakePoxTimer") self._self_stoppable = selfStoppable self._timeToWake = timeToWake self.id = "poxtimer{}".format(FakePoxTimer.timerid) FakePoxTimer.timerid += 1 self._recurring = recurring self._callback = callback self._args = args self._kw = kw get_logger().debug("Setting fake pox timer callback {} {}".format( self._timeToWake, self._callback)) fscore().after(self._timeToWake, self.id, self.docallback, None)
def load_pox_component(name): '''Load a pox component by trying to import the named module and invoking launch(). Raise a runtime error if something goes wrong.''' log = get_logger() try: m = import_module(name) if 'launch' not in dir(m): log.error("Can't load POX module {}".format(name)) raise RuntimeError('No launch function in module {}'.format(name)) else: log.debug("Loading POX component {}".format(name)) # FIXME: component launch needs some rework. # import pox.boot # pox.boot._do_launch([name]) if m.launch.func_code.co_argcount == 0: m.launch() elif m.launch.func_code.co_argcount >= 1: m.launch(m.__dict__) log.debug("Loaded POX component {}".format(name)) except ImportError,e: log.error("Error trying to import {} POX component".format(name)) raise RuntimeError(str(e))
def __init__(self, gfunc, stime=0, emerge_profile=None, sustain_profile=None, withdraw_profile=None): self.generators = {} self.generator_generator = gfunc self.starttime = stime self.logger = get_logger("fslib.traffic") if isinstance(self.starttime, (int, float)): self.starttime = randomchoice(self.starttime) # profiles should be generators that return a list of tuples: (time, numsources) self.emerge = self.sustain = self.withdraw = None # print 'emerge',emerge_profile # print 'sustain',sustain_profile # print 'withdraw',withdraw_profile # examples: # profile=((10,10,10,10,10,10),(1,2,3,4,5,6))" # profile=((10,),(1,))" # emerge=((1,),range(1,100,10)) sustain=((0,30),(100,100)) withdraw=((1,),range(100,1,10))" if emerge_profile: emerge = eval(emerge_profile) # print 'emerge',emerge self.emerge = zipit(emerge) if sustain_profile: sustain = eval(sustain_profile) # print 'sustain',sustain self.sustain = zipit(sustain) if withdraw_profile: withdraw = eval(withdraw_profile) print 'withdraw',withdraw self.withdraw = zipit(withdraw)
def load_pox_component(name): '''Load a pox component by trying to import the named module and invoking launch(). Raise a runtime error if something goes wrong.''' log = get_logger() try: m = import_module(name) if 'launch' not in dir(m): log.error("Can't load POX module {}".format(name)) raise RuntimeError('No launch function in module {}'.format(name)) else: log.debug("Loading POX component {}".format(name)) # FIXME: component launch needs some rework. # import pox.boot # pox.boot._do_launch([name]) if m.launch.func_code.co_argcount == 0: m.launch() elif m.launch.func_code.co_argcount >= 1: m.launch(m.__dict__) log.debug("Loaded POX component {}".format(name)) except ImportError, e: log.error("Error trying to import {} POX component".format(name)) raise RuntimeError(str(e))
def __init__(self, interval, endtime=1.0, debug=0, progtick=0.05): if FsCore.inited: fscommon.get_logger().warn("Trying to initialize a new simulation object.") sys.exit(-1) FsCore.inited = True self.__debug = debug self.__interval = interval self.__now = 0.0 self.__logger = fscommon.get_logger('fs.core') self.__heap = [] self.endtime = endtime self.starttime = self.__now self.intr = False self.progtick = progtick self.__topology = NullTopology() self.monkeypatch() fscommon.set_fscore(self)
def __init__(self, interval, endtime=1.0, debug=0, progtick=0.05): if FsCore.inited: fscommon.get_logger().warn( "Trying to initialize a new simulation object.") sys.exit(-1) FsCore.inited = True self.__debug = debug self.__interval = interval self.__now = 0.0 self.__logger = fscommon.get_logger('fs.core') self.__heap = [] self.endtime = endtime self.starttime = self.__now self.intr = False self.progtick = progtick self.__topology = NullTopology() self.monkeypatch() fscommon.set_fscore(self)
def simrecv(self, msg): # print "Received message in FakeOpenflowConnection:", str(msg) # print "seq 3" if msg.version != oflib.OFP_VERSION: get_logger().debug("Bad OpenFlow version (0x%02x) on connection %s" % (ord(self.buf[offset]), self)) return False # Throw connection away # don't need to pack/unpack because we control message send/recv # new_offset,msg = unpackers[ofp_type](self.buf, offset) ofp_type = msg.header_type try: from pox.openflow.of_01 import handlers h = handlers[ofp_type] h(self, msg) except: get_logger().debug("%s: Exception while handling OpenFlow message:\n" + "%s %s", self,self, ("\n" + str(self) + " ").join(str(msg).split('\n'))) return True
def __init__ (self, timeToWake, callback, absoluteTime = False, recurring = False, args = (), kw = {}, scheduler = None, started = True, selfStoppable = True): if absoluteTime and recurring: raise RuntimeError("Can't have a recurring timer for an absolute time!") if absoluteTime: raise RuntimeError("Can't have an absolute time in FakePoxTimer") self._self_stoppable = selfStoppable self._timeToWake = timeToWake self.id = "poxtimer{}".format(FakePoxTimer.timerid) FakePoxTimer.timerid += 1 self._recurring = recurring self._callback = callback self._args = args self._kw = kw get_logger().debug("Setting fake pox timer callback {} {}".format(self._timeToWake, self._callback)) fscore().after(self._timeToWake, self.id, self.docallback, None)
def __init__(self, graph, nodes, links, traffic_modulators): self.logger = get_logger('fslib.config') self.__graph = graph self.nodes = nodes self.links = links self.traffic_modulators = traffic_modulators self.routing = {} self.ipdestlpm = None self.owdhash = {} self.__configure_routing() for a,b,d in self.graph.edges(data=True): if 'reliability' in d: self.__configure_edge_reliability(a,b,d['reliability'],d)
def parse_capacity(capacity): '''Parse config file capacity, return capacity as a float in bits/sec''' if isinstance(capacity, (int, float)): return float(capacity) elif isinstance(capacity, (str, unicode)): if re.match('^(\d+\.?\d*)$', capacity): return float(capacity) # [kK]+anything assumed to be kbit/sec mobj = re.match('^(\d+\.?\d*)[kK]', capacity) if mobj: return float(mobj.groups()[0]) * 1000.0 # [mM]+anything assumed to be mbit/sec mobj = re.match('^(\d+\.?\d*)[mM]', capacity) if mobj: return float(mobj.groups()[0]) * 1000000.0 # [gG]+anything assumed to be gbit/sec mobj = re.match('^(\d+\.?\d*)[gG]', capacity) if mobj: return float(mobj.groups()[0]) * 1000000000.0 get_logger().error("Can't parse link capacity: {}".format(capacity)) sys.exit(-1)
def parse_capacity(capacity): '''Parse config file capacity, return capacity as a float in bits/sec''' if isinstance(capacity, (int,float)): return float(capacity) elif isinstance(capacity, (str, unicode)): if re.match('^(\d+)$', capacity): return float(capacity) # [kK]+anything assumed to be kbit/sec mobj = re.match('^(\d+)[kK]', capacity) if mobj: return float(mobj.groups()[0]) * 1000.0 # [mM]+anything assumed to be mbit/sec mobj = re.match('^(\d+)[mM]', capacity) if mobj: return float(mobj.groups()[0]) * 1000000.0 # [gG]+anything assumed to be gbit/sec mobj = re.match('^(\d+)[gG]', capacity) if mobj: return float(mobj.groups()[0]) * 1000000000.0 get_logger().error("Can't parse link capacity: {}".format(capacity)) sys.exit(-1)
def __init__(self, capacity, delay, ingress_node, egress_node): self.capacity = Link.parse_capacity(capacity)/8.0 # bytes/sec self.delay = Link.parse_delay(delay) self.ingress_ip = 0 self.egress_ip = 0 self.egress_node = egress_node self.egress_name = Link.make_portname(self.egress_node.name, self.egress_ip) self.ingress_node = ingress_node self.ingress_name = Link.make_portname(self.ingress_node.name, self.ingress_ip) self.backlog = 0 self.bdp = self.capacity * self.delay # bytes self.queuealarm = 1.0 self.lastalarm = -1 self.alarminterval = 30 self.doqdelay = True self.logger = get_logger("link {}->{}".format(self.ingress_node.name, self.egress_node.name))
def packet_to_flowlet(pkt): try: return getattr(pkt, "origflet") except AttributeError, e: log = get_logger() flet = None ip = pkt.find("ipv4") if ip is None: flet = PoxFlowlet(FlowIdent()) log.debug( "Received non-IP packet {} from POX: there's no direct translation to fs".format(str(pkt.payload)) ) else: dport = sport = tcpflags = 0 if ip.protocol == IPPROTO_TCP: tcp = ip.payload sport = tcp.srcport dport = tcp.dstport tcpflags = tcp.flags log.debug("Translating POX TCP packet to fs {}".format(tcp)) elif ip.protocol == IPPROTO_UDP: udp = ip.payload sport = udp.srcport dport = udp.dstport log.debug("Translating POX UDP packet to fs {}".format(udp)) elif ip.protocol == IPPROTO_ICMP: icmp = ip.payload dport = (icmp.type << 8) | icmp.code log.debug("Translating POX ICMP packet to fs {}".format(icmp)) else: log.warn("Received unhandled IPv4 packet {} from POX: can't translate to fs".format(str(ip.payload))) flet = PoxFlowlet(FlowIdent(srcip=ip.srcip, dstip=ip.dstip, ipproto=ip.protocol, sport=sport, dport=dport)) flet.tcpflags = tcpflags flet.iptos = ip.tos flet.srcmac = pkt.src flet.dstmac = pkt.dst flet.pkts = 1 flet.bytes = len(pkt) flet.origpkt = pkt return flet
def packet_to_flowlet(pkt): '''Translate a POX packet to an fs flowlet''' try: return getattr(pkt, "origflet") except AttributeError,e: log = get_logger() flet = None ip = pkt.find('ipv4') if ip is None: flet = PoxFlowlet(FlowIdent()) log.debug("Received non-IP packet {} from POX: there's no direct translation to fs".format(str(pkt.payload))) else: dport = sport = tcpflags = 0 if ip.protocol == IPPROTO_TCP: tcp = ip.payload sport = tcp.srcport dport = tcp.dstport tcpflags = tcp.flags log.debug("Translating POX TCP packet to fs {}".format(tcp)) elif ip.protocol == IPPROTO_UDP: udp = ip.payload sport = udp.srcport dport = udp.dstport log.debug("Translating POX UDP packet to fs {}".format(udp)) elif ip.protocol == IPPROTO_ICMP: icmp = ip.payload dport = (icmp.type << 8) | icmp.code log.debug("Translating POX ICMP packet to fs {}".format(icmp)) else: log.warn("Received unhandled IPv4 packet {} from POX: can't translate to fs".format(str(ip.payload))) flet = PoxFlowlet(FlowIdent(srcip=ip.srcip, dstip=ip.dstip, ipproto=ip.protocol, sport=sport, dport=dport)) flet.tcpflags = tcpflags flet.iptos = ip.tos flet.srcmac = pkt.src flet.dstmac = pkt.dst flet.pkts = 1 flet.bytes = len(pkt) flet.origpkt = pkt return flet
def __init__(self, srcnode): self.srcnode = srcnode self.done = False self.logger = get_logger("tgen.{}".format(self.srcnode))
def __init__(self, srcnode, ipsrc='0.0.0.0', ipdst='0.0.0.0', sport=0, dport=0, flowsize=1500, pktsize=1500, flowstart=0, ipproto=socket.IPPROTO_TCP, lossrate=0.001, mss=1460, iptos=0x0, xopen=True, tcpmodel='csa00'): TrafficGenerator.__init__(self, srcnode) self.logger = get_logger('fs.harpoon') self.srcnet = ipaddr.IPNetwork(ipsrc) self.dstnet = ipaddr.IPNetwork(ipdst) if haveIPAddrGen: self.ipsrcgen = ipaddrgen.initialize_trie(int(self.srcnet), self.srcnet.prefixlen, 0.61) self.ipdstgen = ipaddrgen.initialize_trie(int(self.dstnet), self.dstnet.prefixlen, 0.61) if isinstance(ipproto, (str,unicode)): self.ipproto = eval(ipproto) else: self.ipproto = randomchoice(ipproto) if isinstance(sport, (str,unicode)): self.srcports = eval(sport) else: self.srcports = randomchoice(sport) if isinstance(dport, (str,unicode)): self.dstports = eval(dport) else: self.dstports = randomchoice(dport) if isinstance(flowsize, (str,unicode)): self.flowsizerv = eval(flowsize) else: self.flowsizerv = randomchoice(flowsize) if isinstance(pktsize, (str,unicode)): self.pktsizerv = eval(pktsize) else: self.pktsizerv = randomchoice(pktsize) if isinstance(flowstart, (str,unicode)): self.flowstartrv = eval(flowstart) else: self.flowstartrv = randomchoice(flowstart) if isinstance(lossrate, (str,unicode)): self.lossraterv = eval(lossrate) else: self.lossraterv = randomchoice(lossrate) if isinstance(mss, (str,unicode)): self.mssrv = eval(mss) else: self.mssrv = randomchoice(mss) if isinstance(iptos, (str,unicode)): self.iptosrv = eval(iptos) else: self.iptosrv = randomchoice(iptos) self.xopen = xopen self.activeflows = {} try: self.tcpmodel = import_module("tcpmodels.{}".format(tcpmodel)) except ImportError,e: raise InvalidFlowConfiguration('Unrecognized tcp model for harpoon: {} (Error on import: {})'.format(tcpmodel, str(e)))
if 'launch' not in dir(m): log.error("Can't load POX module {}".format(name)) raise RuntimeError('No launch function in module {}'.format(name)) else: log.debug("Loading POX component {}".format(name)) # FIXME: component launch needs some rework. # import pox.boot # pox.boot._do_launch([name]) if m.launch.func_code.co_argcount == 0: m.launch() elif m.launch.func_code.co_argcount >= 1: m.launch(m.__dict__) log.debug("Loaded POX component {}".format(name)) except ImportError, e: log.error("Error trying to import {} POX component".format(name)) raise RuntimeError(str(e)) monkey_patch_pox() load_pox_component("pox.openflow") get_logger().debug("Kicking POX Up") pox.core.core.goUp() get_logger().debug("POX components: {}".format(pox.core.core.components)) from pox_bridge import *
def __init__(self, srcnode, ipsrc='0.0.0.0', ipdst='0.0.0.0', sport=0, dport=0, flowstarttime=0, flowsize=1500, pktsize=1500, flowstart=0, ipproto=socket.IPPROTO_TCP, lossrate=0.0045, mss=1460, iptos=0x0, xopen=True, tcpmodel='csa00',matrix='../conf/input.matrix'): TrafficGenerator.__init__(self, srcnode) self.logger = get_logger('fs.matrix') trafficmatrix = open(matrix, 'r') flowList = [] flowStartList = [] srcipList = [] dstipList = [] flowSizeList = [] for line in trafficmatrix: if line.strip()!= "": flowList.append(line.strip().split(" ")) for item in flowList: try: if nodename_to_ipaddr(srcnode)==item[1]: flowStartList.append(item[0]) srcipList.append(item[1]) dstipList.append(item[2]) #srcipList.append(nodename_to_ipaddr(item[1])) #dstipList.append(nodename_to_ipaddr(item[2])) flowSizeList.append(item[3]) except: print "Invalid Flow" print item pass self.srcipList=srcipList self.srcnet = eval('sequentialchoice(srcipList)') self.dstnet = eval('sequentialchoice(dstipList)') self.flowstarttimerv = eval('sequentialchoice(flowStartList)') self.flowsizerv = eval('sequentialchoice(flowSizeList)') if haveIPAddrGen: self.ipsrcgen = ipaddrgen.initialize_trie(int(self.srcnet), self.srcnet.prefixlen, 0.61) self.ipdstgen = ipaddrgen.initialize_trie(int(self.dstnet), self.dstnet.prefixlen, 0.61) if isinstance(ipproto, (str,unicode)): #print eval(ipproto) self.ipproto = eval(ipproto) else: self.ipproto = randomchoice(ipproto) if isinstance(sport, (str,unicode)): self.srcports = eval(sport) else: self.srcports = randomchoice(sport) if isinstance(dport, (str,unicode)): self.dstports = eval(dport) else: self.dstports = randomchoice(dport) if isinstance(pktsize, (str,unicode)): self.pktsizerv = eval(pktsize) else: self.pktsizerv = randomchoice(pktsize) if isinstance(flowstart, (str,unicode)): self.flowstartrv = eval(flowstart) else: self.flowstartrv = randomchoice(flowstart) if isinstance(lossrate, (str,unicode)): self.lossraterv = eval(lossrate) else: self.lossraterv = randomchoice(lossrate) if isinstance(mss, (str,unicode)): self.mssrv = eval(mss) else: self.mssrv = randomchoice(mss) if isinstance(iptos, (str,unicode)): self.iptosrv = eval(iptos) else: self.iptosrv = randomchoice(iptos) self.xopen = xopen self.activeflows = {} try: self.tcpmodel = import_module("tcpmodels.{}".format(tcpmodel)) except ImportError,e: raise InvalidFlowConfiguration('Unrecognized tcp model for matrix: {} (Error on import: {})'.format(tcpmodel, str(e)))
def cancel(self): get_logger().debug("Attempting to cancel fake POX timer {}".format( self.id)) fscore().cancel(self.id)
def get_pox_logger(*args, **kwargs): return get_logger()
def cancel(self): get_logger().debug("Attempting to cancel fake POX timer {}".format(self.id)) fscore().cancel(self.id)
def docallback(self, *args): get_logger().debug("In fake pox timer callback {} {}".format(self._timeToWake, self._callback)) rv = self._callback(*self._args, **self._kw) if rv and self._recurring: fscore().after(self._timeToWake, self.id, self.docallback, None)
def docallback(self, *args): get_logger().debug("In fake pox timer callback {} {}".format( self._timeToWake, self._callback)) rv = self._callback(*self._args, **self._kw) if rv and self._recurring: fscore().after(self._timeToWake, self.id, self.docallback, None)
def send(self, ofmessage): get_logger().debug( "Doing callback in OF connection from controller->switch {}". format(ofmessage)) self.sendfn(self.switchname, ofmessage)
def __init__(self, srcnode): self.srcnode = srcnode self.done = False self.logger = get_logger("tgen {}".format(self.srcnode))
def __init__(self, node): ControllerModule.__init__(self) self.logger = get_logger() self.graph = None self.node = node
def __init__(self): self.logger = get_logger('fslib.config') # FIXME: let this be configurable FsConfigurator.link_subnetter = fsutil.subnet_generator("172.16.0.0/12", 2)
def send(self, ofmessage): get_logger().debug("Doing callback in OF connection from controller->switch {}".format(ofmessage)) # print "unknown", self.switchname self.sendfn(self.switchname, ofmessage)
if 'launch' not in dir(m): log.error("Can't load POX module {}".format(name)) raise RuntimeError('No launch function in module {}'.format(name)) else: log.debug("Loading POX component {}".format(name)) # FIXME: component launch needs some rework. # import pox.boot # pox.boot._do_launch([name]) if m.launch.func_code.co_argcount == 0: m.launch() elif m.launch.func_code.co_argcount >= 1: m.launch(m.__dict__) log.debug("Loaded POX component {}".format(name)) except ImportError,e: log.error("Error trying to import {} POX component".format(name)) raise RuntimeError(str(e)) monkey_patch_pox() load_pox_component("pox.openflow") get_logger().debug("Kicking POX Up") pox.core.core.goUp() get_logger().debug("POX components: {}".format(pox.core.core.components)) from pox_bridge import *