def interact(self): """ Begin user interaction """ if self.completion: import readline, rlcompleter ns = globals().copy() ns.update(self.variables) # Note that things added to self.variables later won't be available. # To fix this, make a dict proxy that actually reads from self.variables # *and* globals(). readline.set_completer(rlcompleter.Completer(ns).complete) readline.parse_and_bind("tab: complete") _monkeypatch_console() #print("This program comes with ABSOLUTELY NO WARRANTY. This program " \ # "is free software,") #print("and you are welcome to redistribute it under certain conditions.") #print("Type 'help(pox.license)' for details.") time.sleep(1) import code import sys # Changes by Janos Czentye # Add ESCAPE as the promt in interactive mode to avoid ambiguity sys.ps1 = "ESCAPE> " # Addition END sys.ps2 = " ... " self.running = True code.interact('Ready.', local=self.variables) self.running = False core.quit()
def launch(infile, verbose=False, max_length=110, hide=False, show=False): global _verbose, _max_length, _types, _show_by_default _verbose = verbose if max_length is True or max_length == '0': _max_length = None else: _max_length = int(max_length) force_show = (show is True) or (hide is False and show is False) if isinstance(hide, str): hide = hide.replace(',', ' ').replace('|', ' ') hide = set([p.lower() for p in hide.split()]) else: hide = set() if isinstance(show, str): show = show.replace(',', ' ').replace('|', ' ') show = set([p.lower() for p in show.split()]) else: show = set() if hide and show: raise RuntimeError("Can't both show and hide packet types") if show: _types = show else: _types = hide _show_by_default = not not hide if force_show: _show_by_default = force_show data = open(infile, "r").read() p = pxparse.PCapParser(callback=cb) p.feed(data) core.quit()
def interact (self): """ Begin user interaction """ if self.completion: import readline, rlcompleter ns = globals().copy() ns.update(self.variables) # Note that things added to self.variables later won't be available. # To fix this, make a dict proxy that actually reads from self.variables # *and* globals(). readline.set_completer(rlcompleter.Completer(ns).complete) readline.parse_and_bind("tab: complete") _monkeypatch_console() print("This program comes with ABSOLUTELY NO WARRANTY. This program " \ "is free software,") print("and you are welcome to redistribute it under certain conditions.") print("Type 'help(pox.license)' for details.") time.sleep(1) import code import sys sys.ps1 = "POX> " sys.ps2 = " ... " self.running = True code.interact('Ready.', local=self.variables) self.running = False core.quit()
def on_end(): try: do_score() tester.finish() except Exception: log.exception("Exception during scoring") core.quit()
def _handle_close(self): global client_worker if client_worker is self: client_worker = None log.info("Disconnect") super(ClientWorker, self)._handle_close() if single_message: core.quit()
def _handle_close (self): global client_worker if client_worker is self: client_worker = None log.info("Disconnect") super(ClientWorker, self)._handle_close() if single_message: core.quit()
def interfaces(verbose=False): """ Show interfaces """ if not verbose: print "\n".join( ["%i. %s" % x for x in enumerate(PCap.get_device_names())]) else: import pprint print pprint.pprint(PCap.get_devices()) from pox.core import core core.quit()
def launch(alg='stp'): ''' Registra a instancia da classe l2_hpc que encaminha trafego L2 em ambientes HPC ''' def start(): core.registerNew(L2_hpc, alg) log.info('l2_hpc ready') core.call_when_ready(start, ['openflow_discovery', 'host_tracker', 'Traffic']) if core._waiters: log.warning('Missing component... Shut down POX') core.quit()
def interfaces(verbose=False): """ Show interfaces """ if not verbose: print "\n".join(["%i. %s" % x for x in enumerate(PCap.get_device_names())]) else: import pprint print pprint.pprint(PCap.get_devices()) from pox.core import core core.quit()
def quit_with_code(ret_code, msg=None, logger=None): """ Helper function for quitting with an explicit code. :return: None """ from pox.core import core if isinstance(logger, str): logger = core.getLogger(logger) elif not isinstance(logger, logging.Logger): logger = core.getLogger("core") logger.info(msg if msg else "Exiting from ESCAPE...") core.set_return_value(ret_code) core.quit()
def launch(infile, outfile, in_only=False, out_only=False): """ For stripping PI/PO data """ global _writer, _of_port, _in_only, _out_only _in_only = in_only _out_only = out_only data = open(infile, "r").read() p = pxparse.PCapParser(callback=pi_cb) _writer = pxwriter.PCapRawWriter(open(outfile, "w")) p.feed(data) log.info("%i packet_ins, %i packet_outs", _pis, _pos) core.quit()
def quit_with_ok(msg=None, logger=None): """ Helper function for quitting in case of an error. :param msg: exit message :type msg: str :param logger: logger name or logger object (default: core) :type logger: str or :any:`logging.Logger` :return: None """ from pox.core import core if isinstance(logger, str): logger = core.getLogger(logger) elif not isinstance(logger, logging.Logger): logger = core.getLogger("core") logger.info(msg if msg else "Exiting from ESCAPE...") core.quit()
def launch (infile, outfile, in_only=False, out_only = False): """ For stripping PI/PO data """ global _writer, _of_port, _in_only, _out_only _in_only = in_only _out_only = out_only data = open(infile, "r").read() p = pxparse.PCapParser(callback=pi_cb) _writer = pxwriter.PCapRawWriter(open(outfile, "w")) p.feed(data) log.info("%i packet_ins, %i packet_outs", _pis, _pos) core.quit()
def main (): setup_logging() _monkeypatch_console() try: if doLaunch(): post_startup() core.goUp() else: return except SystemExit: return except: import traceback traceback.print_exc() return if cli: print "This program comes with ABSOLUTELY NO WARRANTY. This program is " \ "free software," print "and you are welcome to redistribute it under certain conditions." print "Type 'help(pox.license)' for details." import pox.license import time time.sleep(1) import code import sys sys.ps1 = "POX> " sys.ps2 = " ... " l = dict(locals()) l['core'] = core code.interact('Ready.', local=l) else: try: import time while True: time.sleep(5) except: pass #core.scheduler._thread.join() # Sleazy try: core.quit() except: pass
def launch(disable_flood=False): global all_ports if disable_flood: all_ports = of.OFPP_ALL connected = connect_to_test_manager() # Even a simple usage of the logger is much nicer than print! # core.openflow.addListenerByName("PacketIn", _handle_PacketIn) if connected: core.openflow.addListenerByName("PacketIn", _handle_PacketIn) log.warn("Forwarding switch running.") log.info( "Make sure that this component is running on the main controller FGS" ) else: log.warn( "Failed to connect to test manager, Forwarding switch won't run") core.quit()
def startup(self): try: _setup_logging() # pre-startup ca.launch() # Default OpenFlow launch # launch components loadPrettyLog() of_01.launch(port=8888) core.registerNew(_Controller, nal=self) # post-startup core.goUp() # forever loop for messaging. while True: time.sleep(5) except: core.quit()
def startup(self): try: _setup_logging() # pre-startup ca.launch() # Default OpenFlow launch # launch components loadPrettyLog() of_01.launch(port = 8888) core.registerNew(_Controller, nal = self) # post-startup core.goUp() # forever loop for messaging. while True: time.sleep(5) except: core.quit()
def _handle_PacketIn(event): global sent_ready packet = event.parsed # Learn the source table[(event.connection, packet.src)] = event.port # dst_port = table.get((event.connection, packet.dst)) # send the packet out all ports (except the one it came in on!) # and hope the destination is out there somewhere. :) msg = of.ofp_packet_out(data=event.ofp) msg.actions.append(of.ofp_action_output(port=all_ports)) event.connection.send(msg) if not sent_ready and packet.type != ethernet.ARP_TYPE: sent_ready = True core.quit() log.debug("Forwarding %s <-> %s" % (packet.src, packet.dst))
def launch (cmd, address = None, port = 7791): core.quit() if not address: address = "127.0.0.1" import socket core.getLogger('core').setLevel(100) log = core.getLogger('ctl') try: s = socket.create_connection((address,port), timeout=2) except: log.error("Couldn't connect") return try: s.settimeout(2) s.send(cmd + "\n") d = s.recv(4096).strip() core.getLogger("ctl").info(d) except socket.timeout: log.warn("No response") except: log.exception("While communicating")
def launch(cmd, address=None, port=7791): core.quit() if not address: address = "127.0.0.1" import socket core.getLogger('core').setLevel(100) log = core.getLogger('ctl') try: s = socket.create_connection((address, port), timeout=2) except: log.error("Couldn't connect") return try: s.settimeout(2) s.send(cmd + "\n") d = s.recv(4096).strip() core.getLogger("ctl").info(d) except socket.timeout: log.warn("No response") except: log.exception("While communicating")
def quit_with_error(msg, logger=None, exception=None): """ Helper function for quitting in case of an error. :param msg: error message :type msg: str :param logger: logger name or logger object (default: core) :type logger: str or :any:`logging.Logger` :param exception: print stacktrace before quit (default: None) :type exception: :any:`exceptions.Exception` :return: None """ from pox.core import core if isinstance(logger, str): logger = core.getLogger(logger) elif not isinstance(logger, logging.Logger): logger = core.getLogger("core") logger.fatal(msg) if exception: logger.exception("Caught exception: %s" % exception) core.quit() os._exit(os.EX_SOFTWARE)
def launch (infile, verbose = False, max_length = 110, hide = False, show = False): global _verbose, _max_length, _types, _show_by_default _verbose = verbose if max_length is True or max_length == '0': _max_length = None else: _max_length = int(max_length) force_show = (show is True) or (hide is False and show is False) if isinstance(hide, basestring): hide = hide.replace(',', ' ').replace('|', ' ') hide = set([p.lower() for p in hide.split()]) else: hide = set() if isinstance(show, basestring): show = show.replace(',', ' ').replace('|', ' ') show = set([p.lower() for p in show.split()]) else: show = set() if hide and show: raise RuntimeError("Can't both show and hide packet types") if show: _types = show else: _types = hide _show_by_default = not not hide if force_show: _show_by_default = force_show data = open(infile, "r").read() p = pxparse.PCapParser(callback=cb) p.feed(data) core.quit()
def terminate_pox(): from pox.core import core as pox_core pox_core.quit()
def run(self): con = None tryconnectnum=0 while core.running: if tryconnectnum==3: raise RuntimeError("Error on RecMessage.py can't connect service") core.quit() clientsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: clientsock.connect((self.address, self.port)) except socket.error as (errno, strerror): #except Exception as error: #raise Exception, str(error) log.error("Error %i while connect socket: %s", errno, strerror) clientsock.close() time.sleep(2) tryconnectnum+=1 continue tryconnetcnum=0 self.connection=Connection(clientsock) #new_con=Connection(clientsock) #time.sleep(1) MininetTask(self.connection) hellomessage=mm.mms_hello() mirrorstatse=MirrorStates(self.connection) core.register("mirrorstatse", mirrorstatse) self.connection.send(hellomessage) #self.connection.addListeners(self) try: while True: con = None rlist, wlist, elist = yield Select([self.connection], [], [self.connection], 5) if len(rlist) == 0 and len(wlist) == 0 and len(elist) == 0: if not core.running: break if len(elist)!=0: raise RuntimeError("Error on RecMessage.py listener socket") if len(rlist)!=0: timestamp = time.time() self.connection.idle_time = timestamp if self.connection.read() is False: self.connection.close() #print 'begin recv' #data = con.recv(2048) #con.close() #else: #hellomessage=mm.mms_hell() #new_con.send(hellomessage) #mutex.acquire() #self.receivelinkevent=0; #print self.receivelinkevent #mutex.release() except exceptions.KeyboardInterrupt: break except: doTraceback = True if sys.exc_info()[0] is socket.error: if sys.exc_info()[1][0] == ECONNRESET: self.connection.info("Connection reset") doTraceback = False if doTraceback: log.exception("Exception reading connection " + str(con)) try: self.connection.close() except: pass
def __call__ (self, code = 0): core.quit() sys.exit(code)
def __call__(self, code=0): core.quit() sys.exit(code)
def interact(self): """ Begin user interaction """ import os history = self.history if history is True: history = ".pox_history" elif history: history = os.path.expanduser(history) if history: history = os.path.abspath(history) import readline, atexit _log = core.getLogger("py") try: readline.read_history_file(history) readline.set_history_length(10000) _log.debug("Read console history") except Exception: pass def save_history(): readline.write_history_file(history) _log.debug("Saved console history") atexit.register(save_history) if self.completion: import readline, rlcompleter ns = globals().copy() ns.update(self.variables) # Note that things added to self.variables later won't be available. # To fix this, make a dict proxy that actually reads from self.variables # *and* globals(). readline.set_completer(rlcompleter.Completer(ns).complete) readline.parse_and_bind("tab: complete") _monkeypatch_console() #print("This program comes with ABSOLUTELY NO WARRANTY. This program " \ # "is free software,") #print("and you are welcome to redistribute it under certain conditions.") #print("Type 'help(pox.license)' for details.") # Ridiculously gross code to wait for a while before showing the console is_up = [False] def notify_up(): is_up[0] = True core.call_later(notify_up) while not is_up[0]: time.sleep(0.2) if core._openflow_wanted: # Hacky time.sleep(0.6) # Long enough? else: time.sleep(0.2) if not core.running: return # A race condition, but probably okay import code import sys sys.ps1 = "POX> " sys.ps2 = " ... " self.running = True console = code.InteractiveConsole(self.variables) # Patch in the synchronized feature real_runcode = console.runcode def runcode(code): if self.variables['sync'] and core.running: with core.scheduler.synchronized(): return real_runcode(code) return real_runcode(code) console.runcode = runcode # Patch in the event hook; why don't we just subclass InteractiveConsole?! real_runsource = console.runsource def runsource(source, *args, **kw): e = SourceEntered(source) self.raiseEvent(e) source = e.source if source is None: return return real_runsource(source, *args, **kw) console.runsource = runsource try: import readline except ImportError: pass console.interact('Ready.', exitmsg='') self.running = False core.quit()
def cb (msg): if msg is None: core.quit() setup_input() # Pop box back up notify(msg)
def _term(signum, _): log.info("Got signal, quitting") core.quit()
def launch (filename): data = open(filename, "r").read() p = pxparse.PCapParser(callback=Multiflow) p.feed(data) core.quit()
def cb(msg): if msg is None: core.quit() setup_input() # Pop box back up notify(msg)