Exemplo n.º 1
0
def launch (forwarding = "eco"):
  import pox.log.color
  pox.log.color.launch()
  import pox.log
  pox.log.launch(format="[@@@bold@@@level%(name)-22s@@@reset] " +
                        "@@@bold%(message)s@@@normal")
  from pox.core import core
  #import pox.openflow.discovery
  #import eco_flow_table
  #eco_flow_table.launch()
  import eco_discovery
  eco_discovery.launch()

  core.getLogger("openflow.spanning_tree").setLevel("INFO")
  if forwarding.lower() == "l3":
    import pox.forwarding.l3_learning as fw
  elif forwarding.lower() == "l2_multi":
    import pox.forwarding.l2_multi as fw
  elif forwarding.lower() == "l2_learning":
    import pox.forwarding.l2_learning as fw 
  elif forwarding.lower() == "static":
    import static_topology as fw
  else:
    import eco_topology as fw
  core.getLogger().debug("Using forwarding: %s", fw.__name__)
  fw.launch()

  import pox.openflow.spanning_tree
  pox.openflow.spanning_tree.launch()
Exemplo n.º 2
0
def setup ():
  """ Set up GUI """
  global unblocked_list, blocked_list
  top = Toplevel()
  top.title("MAC Blocker")

  # Shut down POX when window is closed
  top.protocol("WM_DELETE_WINDOW", core.quit)

  box1 = Frame(top)
  box2 = Frame(top)
  l1 = Label(box1, text="Allowed")
  l2 = Label(box2, text="Blocked")
  unblocked_list = Listbox(box1)
  blocked_list = Listbox(box2)
  l1.pack()
  l2.pack()
  unblocked_list.pack(expand=True,fill=BOTH)
  blocked_list.pack(expand=True,fill=BOTH)

  buttons = Frame(top)
  block_button = Button(buttons, text="Block >>", command=do_block)
  unblock_button = Button(buttons, text="<< Unblock", command=do_unblock)
  block_button.pack()
  unblock_button.pack()

  opts = {"side":LEFT,"fill":BOTH,"expand":True}
  box1.pack(**opts)
  buttons.pack(**{"side":LEFT})
  box2.pack(**opts)

  core.getLogger().debug("Ready")
Exemplo n.º 3
0
def launch (__INSTANCE__=None, **kw):
  """
  Allows configuring log levels from the commandline.

  For example, to turn off the verbose web logging, try:
  pox.py web.webcore log.level --web.webcore=INFO
  """
  for k,v in kw.iteritems():
    if v is True:
      # This means they did something like log.level --DEBUG
      v = k
      k = "" # Root logger
    try:
      v = int(v)
    except:
      old = v
      v = logging.DEBUG
      def dofail ():
        core.getLogger(k).error("Bad log level: %s. Defaulting to DEBUG.", old)

      if (len(old) == 0) or (len(old.strip(string.ascii_uppercase)) != 0):
        dofail()
      else:
        vv = getattr(logging, old, None)
        if not isinstance(vv, int):
          dofail()
        else:
          v = vv

    core.getLogger(k).setLevel(v)
Exemplo n.º 4
0
def launch():
	#clear some unimportant message
	core.getLogger("packet").setLevel(logging.ERROR)
	core.registerNew(Discovery,explicit_drop=False,install_flow = False)
	core.registerNew(Link_Learning)

	#update flow
	Timer(120,Install_All_Flow,recurring=True,args=["All Path------------------"])
Exemplo n.º 5
0
def launch(**kw):
    """
  Allows configuring log levels from the commandline.

  For example, to turn off the verbose web logging, try:
  pox.py web.webcore log.level --web.webcore=INFO
  """
    for k, v in kw.iteritems():
        core.getLogger(k).setLevel(v)
Exemplo n.º 6
0
def block_handler (event):
	#Handles packet event and kills the ones with a blocked port number

	tcpp = event.parsed.find('tcp')
	if not tcpp: return # Not TCP
	if tcpp.srcport in block_ports or tcpp.dstport in block_ports:
		#Halt the event, stopping l2_learning from seeing it
		#(and installing a table entry for it)
		core.getLogger("blocker").debug("Blocked TCP %s <-> %s",
		tcpp.srcport, tcpp.dstport)
		event.halt = True
Exemplo n.º 7
0
def launch (__INSTANCE__=None, **kw):
  """
  Allows configuring log levels from the commandline.

  For example, to turn off the verbose web logging, try:
  pox.py web.webcore log.level --web.webcore=INFO
  """
  for k,v in kw.iteritems():
    if v is True:
      # This means they did something like log.level --DEBUG
      v = k
      k = "" # Root logger
    core.getLogger(k).setLevel(v)
def launch (debug = False):
  core.registerNew(topo_addressing)
  from proto.arp_helper import launch
  launch(eat_packets=False)
  if not debug:
    core.getLogger("proto.arp_helper").setLevel(99)



  signal.signal(signal.SIGALRM, refresh_all_table)

  # emit SIGALRM after 5 secs

  signal.setitimer(signal.ITIMER_REAL, 60)
Exemplo n.º 9
0
    def check_for_overlapping_entry(self, in_entry):
        # FELIPE TOMM - TCC
        # Esta funcao verifica se ja existe uma flow identica.
        # Sera essa minha funcao base?
        log = core.getLogger()
        log.debug("Debug TCC - Flow Table: Iniciando analise de conflito")
        """
    Tests if the input entry overlaps with another entry in this table.

    Returns true if there is an overlap, false otherwise. Since the table is
    sorted, there is only a need to check a certain portion of it.
    """
        # NOTE: Assumes that entries are sorted by decreasing effective_priority
        # NOTE: Ambiguous whether matching should be based on effective_priority
        #      or the regular priority.  Doing it based on effective_priority
        #      since that's what actually affects packet matching.
        # NOTE: We could improve performance by doing a binary search to find the
        #      right priority entries.

        priority = in_entry.effective_priority

        for e in self._table:
            if e.effective_priority < priority:
                break
            elif e.effective_priority > priority:
                continue
            else:
                if e.is_matched_by(in_entry.match) or in_entry.is_matched_by(e.match):
                    print("Debug TCC - Flow Table: O Flow: ja existe.")
                    return True

        return False
Exemplo n.º 10
0
 def __init__ (self, switch=None, **kw):
   self.switch = switch
   self.connection = None
   from pox.core import core
   self.log = core.getLogger("dp." + dpid_to_str(self.switch.dpid))
   super(OpenFlowWorker, self).__init__(switch=switch,**kw)
   self._info("Disconnected")
Exemplo n.º 11
0
def launch (port=6633, address="0.0.0.0", name=None,
            private_key=None, certificate=None, ca_cert=None,
            __INSTANCE__=None):
  """
  Start a listener for OpenFlow connections

  If you want to enable SSL, pass private_key/certificate/ca_cert in reasonable
  combinations and pointing to reasonable key/cert files.  These have the same
  meanings as with Open vSwitch's old test controller, but they are more
  flexible (e.g., ca-cert can be skipped).
  """
  if name is None:
    basename = "of_01"
    counter = 1
    name = basename
    while core.hasComponent(name):
      counter += 1
      name = "%s-%s" % (basename, counter)

  if core.hasComponent(name):
    log.warn("of_01 '%s' already started", name)
    return None

  global deferredSender
  if not deferredSender:
    deferredSender = DeferredSender()

  if of._logger is None:
    of._logger = core.getLogger('libopenflow_01')

  l = OpenFlow_01_Task(port = int(port), address = address,
                       ssl_key = private_key, ssl_cert = certificate,
                       ssl_ca_cert = ca_cert)
  core.register(name, l)
  return l
Exemplo n.º 12
0
  def __init__ (self,connection,name):
    self.log = core.getLogger("LearningSwitch(%s)" % name)

    # Switch we'll be adding L2 learning switch capabilities to
    self.connection= connection
    self.listenTo(connection)
    self.mactable = {}
Exemplo n.º 13
0
  def __init__(self, name):
    """
    Note that server may be a direct reference to the NomServer (for simulation), or a Pyro4 proxy
    (for emulation)

    pre: name is unique across the network
    """
    EventMixin.__init__(self)
    # We are a "controller" entity in pox.topology.
    # (Actually injecting ourself into pox.topology is handled
    # by nom_server)
    topology.Controller.__init__(self, name)
    self.name = name
    self.log = core.getLogger(name)
    # Construct an empty topology
    # The "master" copy topology will soon be merged into this guy
    self.topology = topology.Topology("topo:%s" % self.name)
    # Register subclass' event handlers
    self.listenTo(self.topology, "topology")

    self._server_connection = None
    self._queued_commits = []

    # For simulation. can't connect to NomServer until the Messenger is listening to new connections
    # TODO: for emulation, this should be removed / refactored --
    # just assume that the NomServer machine is up
    core.messenger.addListener(messenger.MessengerListening, self._register_with_server)
Exemplo n.º 14
0
    def __init__(self, switch=None, **kw):
        self.switch = switch
        self.connection = None
        from pox.core import core

        self.log = core.getLogger("dp." + dpid_to_str(self.switch.dpid))
        super(OpenFlowWorker, self).__init__(switch=switch, **kw)
        self._info("Connecting to %s:%s", kw.get('addr'), kw.get('port'))
Exemplo n.º 15
0
 def _handle_ConnectionUp (event):
   if dpid_to_str(event.dpid) == "00-00-00-00-00-01":
     core.getLogger().info("Connection %s" % (event.connection,))
     Firewall(event.connection, False)
   elif dpid_to_str(event.dpid) == "00-00-00-00-00-02":
     core.getLogger().info("Connection %s" % (event.connection,))
     Firewall(event.connection, False)
   elif dpid_to_str(event.dpid) == "00-00-00-00-00-05":
     core.getLogger().info("Connection %s" % (event.connection,))
     LearningSwitch(event.connection, False)
   elif dpid_to_str(event.dpid) == "00-00-00-00-00-03":
     core.getLogger().info("Connection %s" % (event.connection,))
     LearningSwitch(event.connection, False)
     #LoadBalancer(event.connection)
   elif dpid_to_str(event.dpid) == "00-00-00-00-00-04":
     core.getLogger().info("Connection %s" % (event.connection,))
     LearningSwitch(event.connection, False)
Exemplo n.º 16
0
 def __init__(self,net_id=0x0):
     self.log = core.getLogger()
     core.openflow.miss_send_len = 1400
     core.openflow.addListeners(self)
     self.log.info("SecondTest initialization")
     self.switches = dict()
     self.connections = set()
     self.net_id = net_id
Exemplo n.º 17
0
	def __init__(self, connection_up_event):
		if not hasattr(self, '_log'):
			self._log = core.getLogger('OpenFlowSwitch %s' % connection_up_event.dpid)

		self._dpid = connection_up_event.dpid
		self._connection = connection_up_event.connection
		self._ports = connection_up_event.ofp.ports  # Save the list of physical ports of the switch.
		self._flow_table = []  # Initialize the inner flow table for the learning switch.
		self._stats_req_timer = None
Exemplo n.º 18
0
def _process_commands (msg):
  """
  Processes logger commands
  """
  def get (key):
    r = msg.get(key)
    if r is not None:
      if not isinstance(r, dict):
        r = {None:r}
    else:
      return {}
    return r

  lowerLevels = get("lowerLevels") # less verbose
  raiseLevels = get("raiseLevels") # more verbose
  setLevels = get("setLevels")

  for k,v in lowerLevels.iteritems():
    logger = core.getLogger(k)
    level = logging._checkLevel(v)
    if not l.isEnabledFor(level+1):
      logger.setLevel(v)

  for k,v in raiseLevels.iteritems():
    logger = core.getLogger(k)
    if not l.isEnabledFor(v):
      logger.setLevel(v)

  for k,v in setLevels.iteritems():
    logger = core.getLogger(k)
    logger.setLevel(v)

  message = msg.get("message", None)
  if message:
    level = msg.get("level", "DEBUG")
    if isinstance(level, basestring):
      import logging
      if not level.isalpha():
        level = logging.DEBUG
      else:
        level = level.upper()
        level = getattr(logging, level, logging.DEBUG)
    sub = msg.get("subsystem", "<external>")
    logging.getLogger(sub).log(level, message)
 def __init__ (self, address, port = 7790, nexus = None,
               connection_class = TCPConnection, max_backoff = 8):
   port = int(port)
   Task.__init__(self)
   Transport.__init__(self, nexus)
   self._addr = (str(address),port)
   self._connections = set()
   self._connection_class = connection_class
   self._max_backoff = max_backoff
   self.log = log or core.getLogger()
Exemplo n.º 20
0
    def __init__(self, name="topology"):
        EventMixin.__init__(self)
        self._entities = {}
        self.name = name
        self.log = core.getLogger(name)

        # If a client registers a handler for these events after they have
        # already occurred, we promise to re-issue them to the newly joined
        # client.
        self._event_promises = {SwitchJoin: self._fulfill_SwitchJoin_promise}
Exemplo n.º 21
0
 def __init__(self):
     self.net = dict()
     self.log = core.getLogger()
     core.openflow.miss_send_len = 1400
     core.openflow.addListeners(self)
     self.log.info("NCS initialization")
     self.timer = dict()
     self.timer[0] = Timer(30, self.gratuitousARP, args=[None],recurring=True)
     self.timer[1] = Timer(5, self.dump,recurring=True)
     self.net[0xaabbcc] = HotOMNet(0xaabbcc)
Exemplo n.º 22
0
def _handle_SwitchDescReceived (event):
  s = _format_entry(event)
  if not _always and s in _switches:
    # We've already logged it.
    return
  _switches.add(s)
  ss = s.split("\n")

  logger = core.getLogger("info." + dpid_to_str(event.connection.dpid))
  for s in ss:
    logger.info(s)
Exemplo n.º 23
0
 def __init__(self,conf):
     self.net = dict()
     self.avs = dict()
     self.confvstag = dict() # vstag table from config file
     self.log = core.getLogger()
     core.openflow.miss_send_len = 1400
     core.openflow.addListeners(self)
     self.log.info("NCS initialization")
     self.parseConf(conf)
     Timer(30, self.gratuitousARP, args=[None],recurring=True)
     Timer(10, self.dump,recurring=True)
Exemplo n.º 24
0
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")
Exemplo n.º 25
0
  def __init__(self, flow_idle_timeout=30, flow_hard_timeout=60,
                default_latency=1, default_bandwidth=100):
    core.listen_to_dependencies(self)

    self.log = core.getLogger()
    # self.path_preference_table = PathPreferenceTable.Instance()
    self.path_preference_table = PathPreferenceTable()
    self.flow_idle_timeout = flow_idle_timeout
    self.flow_hard_timeout = flow_hard_timeout
    self.default_latency = default_latency  # Milliseconds
    self.default_bandwidth = default_bandwidth  # Megabits
    self.path_preferences = dict()
Exemplo n.º 26
0
def launch (port = 6633, address = "0.0.0.0"):
  if core.hasComponent('of_01'):
    return None

  global deferredSender
  deferredSender = DeferredSender()

  if of._logger is None:
    of._logger = core.getLogger('libopenflow_01')

  l = OpenFlow_01_Task(port = int(port), address = address)
  core.register("of_01", l)
  return l
Exemplo n.º 27
0
def launch (port = 8987):
  # Set up logging
  global log
  log = core.getLogger()

  # Set up IO loop
  global _ioloop
  _ioloop = RecocoIOLoop()
  #_ioloop.more_debugging = True
  _ioloop.start()

  # Register our little JSON core as a component
  core.registerNew(JSONServer, port=int(port))
Exemplo n.º 28
0
 def __init__(self, vlan, threshold, *args, **kwargs):
     ## Define logger (defaults to current path)
     self.log = core.getLogger()
     # Disable logger for 'packet' (TLV)
     logger = core.getLogger("packet")
     logger.propagate = False
     ## Registers every method exposed by the class
     core.openflow.addListeners(self)
     self.vlan = int(vlan)
     ## Firewall-related
     self.traffic_frequency = {}
     # Threshold time (in seconds) to determine harmful network conditions (e.g.: 0.2)
     self.threshold = float(threshold)
     # Time (in seconds) to maintain the DROP rules for the network traffic deemed harmful
     self.idle_drop_time = 30
     self.hard_drop_time = 30
     ## Constants section
     # Define value of protocol number assigned to IP and LLDP traffic
     self.ip_proto = 2048 #0x0800
     self.lldp_proto = 35020 #0x88cc
     self.max_priority = 65535
     self.log.info("Toy firewall for FGRE 2015 (seconds threshold=%s, vlan=%s)." % (self.threshold, self.vlan))
Exemplo n.º 29
0
def _handle_PacketIn (event):
  packet = event.parsed

  show = _show_by_default
  p = packet
  while p:
    if p.__class__.__name__.lower() in _types:
      if _show_by_default:
        # This packet is hidden
        return
      else:
        # This packet should be shown
        show = True
        break
      return
    if not hasattr(p, 'next'): break
    p = p.next

  if not show: return

  msg = dpidToStr(event.dpid) + ": "
  msg = ""
  if _verbose:
    msg += packet.dump()
  else:
    p = packet
    while p:
      if isinstance(p, basestring):
        msg += "[%s bytes]" % (len(p),)
        break
      msg += "[%s]" % (p.__class__.__name__,)
      p = p.next

  if _max_length:
    if len(msg) > _max_length:
      msg = msg[:_max_length-3]
      msg += "..."
  core.getLogger("dump:" + dpidToStr(event.dpid)).debug(msg)
Exemplo n.º 30
0
def launch(port=6633, address="0.0.0.0"):
    if core.hasComponent("of_01"):
        return None

    global deferredSender
    deferredSender = DeferredSender()  # run the __init__ function and start function

    if of._logger is None:
        of._logger = core.getLogger("libopenflow_01")

    l = OpenFlow_01_Task(port=int(port), address=address)  # an instance of class 'OpenFlow_01_Task'
    core.register("of_01", l)
    # print('of_01 has been launched')   #print information
    return l
Exemplo n.º 31
0
 def launch():
     from pox.core import core
     log = core.getLogger()
     log.critical("This isn't a POX component.")
     log.critical("Please see the documentation.")
     raise RuntimeError("This isn't a POX component.")
Exemplo n.º 32
0
"""
Inception Cloud ARP module
"""

from pox.core import core
from pox.lib.packet.arp import arp
from pox.lib.packet.ethernet import ethernet
from pox.lib.util import dpid_to_str
import pox.openflow.libopenflow_01 as of
from ext import priority

LOGGER = core.getLogger()


class InceptionArp(object):
    """
    Inception Cloud ARP module for handling ARP packets
    """
    def __init__(self, inception):
        self.inception = inception
        # IP address -> MAC address: mapping from IP address to MAC address
        # of end hosts for address resolution
        self.ip_to_mac = {}

    def handle(self, event):
        # process only if it is ARP packet
        eth_packet = event.parsed
        if eth_packet.type != ethernet.ARP_TYPE:
            return

        LOGGER.info("Handle ARP packet")
Exemplo n.º 33
0
from pox.core import core
from pox.lib.revent import *
from pox.lib.recoco import Timer
from pox.openflow.libopenflow_01 import *
from pox.openflow import *
from pox.openflow.discovery import *
from pox.lib.addresses import *
from pox.topology.topology import *
import time
import json
import pymongo

UPDATE_INTERVAL = 5
topology_timer = None

log = core.getLogger("rfproxy")


def rf_id(id):
    return "{:#016x}".format(id)


class StatsDB:
    def __init__(self):
        self.db = {}
        self.connection = pymongo.Connection()
        self.collection = self.connection.db.rfstats

    def update(self, id_, type_, links=None, **data):
        if id_ not in self.db:
            if links is None:
Exemplo n.º 34
0
from pox.openflow.of_json import *
import time

from threading import Thread
from threading import Lock

import socket
import json
import math
import statistics as st
import time
from random import randint
from operator import itemgetter
from pox.lib.recoco import Timer

log = core.getLogger()

# We don't want to flood immediately when a switch connects.
# Can be overriden on commandline.
_flood_delay = 0

LOG = core.getLogger()
CONTROLLER_IP = '10.1.4.1'
switch_states = []
# in bits, obtained experimentally using TCP - Iperf
capacity = 100000000
#bw_for_new_flows = 0.0
remaining_bw = 100000000
num_flows = 0
alfa = 0.9
response_port = 23456
Exemplo n.º 35
0
    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.')

        self.running = False
        core.quit()
Exemplo n.º 36
0
import threading

from .authentication import BasicAuthMixin

from pox.core import core
from pox.lib.revent import Event, EventMixin

import os
import socket
import posixpath
import urllib.request, urllib.parse, urllib.error
import cgi
import errno
from io import StringIO, BytesIO

log = core.getLogger()
try:
    weblog = log.getChild("server")
except:
    # I'm tired of people running Python 2.6 having problems with this.
    #TODO: Remove this someday.
    weblog = core.getLogger("webcore.server")


def _setAttribs(parent, child):
    attrs = [
        'command', 'request_version', 'close_connection', 'raw_requestline',
        'requestline', 'path', 'headers', 'wfile', 'rfile', 'server',
        'client_address', 'connection', 'request'
    ]
    for a in attrs:
Exemplo n.º 37
0
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# POX is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with POX.  If not, see <http://www.gnu.org/licenses/>.
"""
This package contains a nom-based L2 learning switch.
"""
from pox.core import core
log = core.getLogger("nom_l2_switch_controller.init")


def launch(distributed=False):
    # TODO: need a more transparent mechanism for specifying the debug flag...
    """
  Starts a NOM-based L2 learning switch, along with the discovery and topology modules
  """
    if type(distributed) == bool and distributed:
        distributed = 1
    elif type(distributed) == str:
        distributed = int(distributed)

    import pox.openflow.connection_arbiter
    pox.openflow.connection_arbiter.launch()
Exemplo n.º 38
0
    def setup():
        log = core.getLogger(log_name)
        tester = Tester(log)
        topo = core.sim_topo

        if server_isn is None:
            TXWindow.generate_isn = lambda _: random.randint(1000, 100000)
        else:
            TXWindow.generate_isn = lambda _: literal_eval(server_isn)

        def get_client_socket():
            try:
                return next(iter(c1.stack.socket_manager.peered.itervalues()))
            except Exception:
                return None

        c1 = core.sim_topo.get_node("c1")
        s1 = core.sim_topo.get_node("s1")
        r1 = core.sim_topo.get_node("r1")
        r2 = core.sim_topo.get_node("r2")
        tm = core.sim_topo.time
        r1c1_dev = core.sim_topo.get_devs(r1, c1)[0]

        # Create two echo applications.  Nobody should be sending, so
        # they should just three-way handshake and then sit and stare
        # at each other until the simulation ends.
        sapp = s1.new_echo(port=1000, listen=True)
        capp = c1.new_echo(ip=s1.netdev.ip_addr, port=1000, delay=0.1)

        pkts = []

        def on_cap(e):
            parsed = e.parsed
            if not parsed: return
            parsed = parsed.find("tcp")
            if not parsed: return
            # Giant hack, but just tack this stuff on
            parsed._devname = e.dev.name
            parsed._client = e.dev is r1c1_dev
            parsed._server = not parsed._client
            csock = get_client_socket()
            parsed._client_state = csock.state if csock else None
            pkts.append(parsed)
            #print e.dev,parsed.dump()

        r1.stack.add_packet_capture("*", on_cap, ip_only=True)

        def do_score():
            # SYN from client
            client_seq = pkts[0].seq
            tester.expect_true(pkts[0]._client and not pkts[0]._server,
                               "first pkt comes from client")
            tester.expect_true(pkts[0].SYN and not pkts[0].ACK,
                               "first pkt is SYN not ACK")

            # SYN+ACK from server
            server_seq = pkts[1].seq
            tester.expect_true(not pkts[1]._client and pkts[1]._server,
                               "second pkt comes from server")
            tester.expect_true(pkts[1].SYN and pkts[1].ACK,
                               "second pkt is SYN+ACK")
            tester.expect_eq(client_seq | PLUS | 1, pkts[1].ack,
                             "second pkt ack seq num is correct")
            tester.expect_eq(SYN_SENT, pkts[1]._client_state,
                             "state is SYN_SENT when r1 receives SYN+ACK")

            # ACK from client
            tester.expect_true(pkts[2]._client, "third pkt comes from client")
            tester.expect_true(not pkts[2].SYN and pkts[2].ACK,
                               "third pkt is ACK")
            tester.expect_eq(server_seq | PLUS | 1, pkts[2].ack,
                             "third pkt ack seq num is correct")
            tester.expect_eq(ESTABLISHED, pkts[2]._client_state,
                             "state is ESTABLISHED when r1 receives ACK")

            tester.expect_eq(3, len(pkts), "3 packets total")

        def on_end():
            try:
                do_score()
                tester.finish()
            except Exception:
                log.exception("Exception during scoring")
            core.quit()

        tm.set_timer_at(float(run_time), on_end)
Exemplo n.º 39
0
  def setup ():
    log = core.getLogger(log_name)
    tester = Tester(log)
    topo = core.sim_topo

    if server_isn is None:
      TXWindow.generate_isn = lambda _: random.randint(1000,100000)
    else:
      TXWindow.generate_isn = lambda _: literal_eval(server_isn)

    def get_client_socket ():
      try:
        return next(iter(c1.stack.socket_manager.peered.itervalues()))
      except Exception:
        return None

    c1 = core.sim_topo.get_node("c1")
    s1 = core.sim_topo.get_node("s1")
    r1 = core.sim_topo.get_node("r1")
    r2 = core.sim_topo.get_node("r2")
    tm = core.sim_topo.time
    r1c1_dev = core.sim_topo.get_devs(r1,c1)[0]

    # sapp calls close() after receiving data
    # capp calls sends data and immediately calls close()
    sapp = s1._new_resocket_app(ClosingRXApp, port=1000, listen=True)
    capp = c1.new_fast_sender(data=1000, ip=s1.netdev.ip_addr, port=1000, delay=0.5)

    pkts = []
    def on_cap (e):
      parsed = e.parsed
      if not parsed: return
      parsed = parsed.find("tcp")
      if not parsed: return
      # Giant hack, but just tack this stuff on
      parsed._devname = e.dev.name
      parsed._client = e.dev is r1c1_dev
      parsed._server = not parsed._client
      csock = get_client_socket()
      parsed._client_state = csock.state if csock else None
      pkts.append(parsed)
      #print e.dev,parsed.dump()

    r1.stack.add_packet_capture("*", on_cap, ip_only=True)

    def do_score ():
      tester.expect_eq("*" * 1000, sapp.all_rx[0][1], "payload correctly sent")

      payload_pkts = sum(1 for p in pkts if p.payload)
      tester.expect_eq(1, payload_pkts, "1 retransmission")

    class drop_payload(object):
      def __init__(self):
        self.dropped = False

      def __call__ (self, dev, packet):
        tcp = packet.find("tcp")
        if not tcp:
          return False

        if tcp.payload and not self.dropped:
          self.dropped = True
          log.info("dropped packet seq={0}, ack={1}".format(tcp.seq, tcp.ack))
          return True

        return False

    topo.get_wire(c1,r1).drop_conditions.append(drop_payload())

    def on_end ():
      try:
        do_score()
        tester.finish()
      except Exception:
        log.exception("Exception during scoring")
      core.quit()

    tm.set_timer_at(float(run_time), on_end)
Exemplo n.º 40
0
# strings from lark setup callout script and parses these
# received strings to job and machine classads. It looks for
# interesting classad attributes value and uses it for network
# scheduling.
#

import sys
import time
import socket
import threading
import SocketServer
import classad
import htcondor
from pox.core import core

log = core.getLogger()
try:
    serverlog = log.getChild("server")
except:
    serverlog = core.getLogger("htcondor_module.server")

threadLock = threading.Lock()

# use a dictionary to store all the network classads, internal IPv4 address
# is used as the key
classadDict = {}


class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        # there are two possible kinds of request to handle
Exemplo n.º 41
0
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
# IN THE WORK.
#----------------------------------------------------------------------

from pox.core import core
import pox.openflow.libopenflow_01 as of
from pox.openflow import *
from utils import *
from BBN_SimpleL2Learning import SimpleL2LearningSwitch

log = core.getLogger() # Use central logging service

class DuplicateTrafficSwitch(SimpleL2LearningSwitch):

    def __init__(self, connection, duplicate_port):
        SimpleL2LearningSwitch.__init__(self, connection, False)
        self._connection = connection;
        self._duplicate_port=duplicate_port
        self._of_duplicate_port=getOpenFlowPort(connection, duplicate_port)

    def _handle_PacketIn(self, event):
        log.debug("Got a packet : " + str(event.parsed))
        self.packet = event.parsed
        self.event = event
        self.macLearningHandle()
        out_port = self.get_out_port()
Exemplo n.º 42
0
    def setup():
        log = core.getLogger(log_name)
        tester = Tester(log)
        topo = core.sim_topo

        if server_isn is None:
            TXWindow.generate_isn = lambda _: random.randint(1000, 100000)
        else:
            TXWindow.generate_isn = lambda _: literal_eval(server_isn)

        def get_client_socket():
            try:
                return next(iter(c1.stack.socket_manager.peered.itervalues()))
            except Exception:
                return None

        c1 = core.sim_topo.get_node("c1")
        s1 = core.sim_topo.get_node("s1")
        r1 = core.sim_topo.get_node("r1")
        r2 = core.sim_topo.get_node("r2")
        tm = core.sim_topo.time
        r1c1_dev = core.sim_topo.get_devs(r1, c1)[0]

        # sapp calls close() after receiving data
        # capp calls sends data and immediately calls close()
        sapp = s1._new_resocket_app(ClosingRXApp, port=1000, listen=True)
        capp = c1._new_resocket_app(TXRatedApp,
                                    ip=s1.netdev.ip_addr,
                                    port=1000,
                                    delay=0.5)
        capp.tx_data = '#' * 1300 * 100

        pkts = []
        client_socket = None

        def on_cap(e):
            if not pkts:
                global client_socket
                client_socket = get_client_socket()

            parsed = e.parsed
            if not parsed: return
            parsed = parsed.find("tcp")
            if not parsed: return
            # Giant hack, but just tack this stuff on
            parsed._devname = e.dev.name
            parsed._client = e.dev is r1c1_dev
            parsed._server = not parsed._client
            csock = get_client_socket()
            parsed._client_state = csock.state if csock else None
            pkts.append(parsed)
            #print e.dev,parsed.dump()

        r1.stack.add_packet_capture("*", on_cap, ip_only=True)

        def do_score():
            tester.expect_eq("#" * 1300 * 100, sapp.all_rx[0][1],
                             "payload correctly sent")

            global client_socket
            actual_srtt = client_socket.srtt
            tester.expect_true(client_socket.rto < 32, "rto < 32")
            tester.expect_true(client_socket.srtt < 16, "srtt < 16")
            tester.expect_true(client_socket.rttvar > 1.5, "rttvar > 1.5")

        random.seed(168)

        class drop_pct(object):
            def __init__(self):
                self.pct = 0.04
                self.dropped_pkts = {}

            def __call__(self, dev, packet):
                tcp = packet.find("tcp")
                # only packets with payload
                if not tcp or not tcp.payload:
                    return False

                if tcp.seq in self.dropped_pkts:
                    return False

                r = random.uniform(0, 1)
                if r <= self.pct:
                    self.dropped_pkts[tcp.seq] = True
                    log.error("dropped pkt")
                    return True

                return False

        topo.get_wire(r1, r2).drop_conditions.append(drop_pct())

        def on_end():
            try:
                do_score()
                tester.finish()
            except Exception:
                log.exception("Exception during scoring")
            core.quit()

        tm.set_timer_at(float(run_time), on_end)
Exemplo n.º 43
0
def launch(debug=False):
    core.registerNew(topo_addressing)
    from proto.arp_helper import launch
    launch(eat_packets=False)
    if not debug:
        core.getLogger("proto.arp_helper").setLevel(99)
Exemplo n.º 44
0
"""

from pox.core import core
import pox.openflow.libopenflow_01 as of
import pox.lib.packet as pkt

from pox.lib.addresses import IPAddr, EthAddr, parse_cidr
from pox.lib.addresses import IP_BROADCAST, IP_ANY
from pox.lib.revent import *
from pox.lib.util import dpid_to_str
from pox.proto.dhcpd import DHCPLease, DHCPD
from collections import defaultdict
from pox.openflow.discovery import Discovery
import time

log = core.getLogger("f.t_p")

# Adjacency map.  [sw1][sw2] -> port from sw1 to sw2
adjacency = defaultdict(lambda: defaultdict(lambda: None))

# Switches we know of.  [dpid] -> Switch and [id] -> Switch
switches_by_dpid = {}
switches_by_id = {}

# [sw1][sw2] -> (distance, intermediate)
path_map = defaultdict(lambda: defaultdict(lambda: (None, None)))


def dpid_to_mac(dpid):
    return EthAddr("%012x" % (dpid & 0xffFFffFFffFF, ))
Exemplo n.º 45
0
# Copyright 2017 Janos Czentye
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Subpackage for classes related mostly to Service (Graph) Adaptation sublayer
"""
from pox.core import core

LAYER_NAME = "service"
log = core.getLogger(LAYER_NAME)
Exemplo n.º 46
0
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 *******************************************************************************/
'''

import pox.openflow.libopenflow_01 as of
from pox.core import core
from pox.lib.recoco import Timer

log = core.getLogger("Global_Stats")

rx_packets = 0
tx_packets = 0
rx_dropped = 0
tx_dropped = 0
rx_errors = 0
tx_errors = 0
num_sw = 0 #total num of switches
num_done = 0 #num of switches for whom stats have been collected
wait_timeout = 0
handler = {} #{dpid:portstats listner handler}



def _init():
Exemplo n.º 47
0
# Import some POX stuff
from pox.core import core                     # Main POX object
import pox.openflow.libopenflow_01 as of      # OpenFlow 1.0 library
import pox.lib.packet as pkt                  # Packet parsing/construction
from pox.lib.addresses import EthAddr, IPAddr # Address types
import pox.lib.util as poxutil                # Various util functions
import pox.lib.revent as revent               # Event library
import pox.lib.recoco as recoco               # Multitasking library
from pox.lib.util import dpid_to_str
from pox.openflow.of_json import *

import multiprocessing
import json

# Create a logger for this component
log = core.getLogger("Monitor")

# Create a global var to portStatus method


def _send_to_pipe(data):
    with open('/dev/shm/poxpipe','w') as pipe:
        pipe.write(data)

def _to_pipe(data):
    p = multiprocessing.Process(target=_send_to_pipe, args=(data,))
    p.start()

def _go_up (event):
    # Event handler called when POX goes into up state
    # (we actually listen to the event in launch() below)
Exemplo n.º 48
0
    def setup():
        log = core.getLogger(log_name)
        tester = Tester(log)
        topo = core.sim_topo

        if server_isn is None:
            TXWindow.generate_isn = lambda _: random.randint(1000, 100000)
        else:
            TXWindow.generate_isn = lambda _: literal_eval(server_isn)

        def get_client_socket():
            try:
                return next(iter(c1.stack.socket_manager.peered.itervalues()))
            except Exception:
                return None

        c1 = core.sim_topo.get_node("c1")
        s1 = core.sim_topo.get_node("s1")
        r1 = core.sim_topo.get_node("r1")
        r2 = core.sim_topo.get_node("r2")
        tm = core.sim_topo.time
        r1c1_dev = core.sim_topo.get_devs(r1, c1)[0]

        # sapp calls close() immediately after connect()
        # capp calls close() after 1 sec
        sapp = s1.new_basic_state_trans(port=1000, listen=True)
        capp = c1._new_resocket_app(DelayedCloseApp,
                                    ip=s1.netdev.ip_addr,
                                    port=1000,
                                    delay=0.1)

        pkts = []
        client_socket = None

        def on_cap(e):
            if not pkts:
                global client_socket
                client_socket = get_client_socket()

            parsed = e.parsed
            if not parsed: return
            parsed = parsed.find("tcp")
            if not parsed: return
            # Giant hack, but just tack this stuff on
            parsed._devname = e.dev.name
            parsed._client = e.dev is r1c1_dev
            parsed._server = not parsed._client
            csock = get_client_socket()
            parsed._client_state = csock.state if csock else None
            pkts.append(parsed)
            #print e.dev,parsed.dump()

        r1.stack.add_packet_capture("*", on_cap, ip_only=True)

        def from_server(p):
            return p._server and not p._client

        def from_client(p):
            return not p._server and p._client

        def do_score():
            # SYN from client
            tester.expect_true(from_client(pkts[0]), "1st SYN from client")

            # SYN+ACK from server
            tester.expect_true(from_server(pkts[1]),
                               "2nd pkt comes from server")
            tester.expect_eq(pkts[1]._client_state, SYN_SENT,
                             "state is SYN_SENT when r2 receives SYN+ACK")

            # ACK from client
            tester.expect_true(from_client(pkts[2]),
                               "3rd pkt comes from client")
            tester.expect_eq(pkts[2]._client_state, ESTABLISHED,
                             "state is ESTABLISHED when r2 receives ACK")

            # FIN+ACK from server
            tester.expect_true(from_server(pkts[3]),
                               "4th pkt comes from server")
            tester.expect_eq(pkts[3]._client_state, ESTABLISHED,
                             "state is ESTABLISHED when r2 receives FINACK")
            tester.expect_true(pkts[3].ACK and pkts[3].FIN,
                               "4th pkt is FIN+ACK")

            # ACK from client
            tester.expect_true(from_client(pkts[4]),
                               "5th pkt comes from client")
            tester.expect_true(pkts[4].ACK, "5th pkt is ACK")

            # FIN+ACK from client
            tester.expect_true(from_client(pkts[5]),
                               "6th pkt comes from client")
            tester.expect_true(pkts[5].ACK and pkts[5].FIN,
                               "6th pkt is FIN+ACK")

            # ACK from server
            tester.expect_true(from_server(pkts[6]),
                               "7th pkt comes from server")
            tester.expect_eq(LAST_ACK, pkts[6]._client_state,
                             "state is LAST_ACK when r2 receives ACK")
            tester.expect_true(pkts[6].ACK, "7th pkt is ACK")

            global client_socket
            tester.expect_eq(CLOSED, client_socket.state,
                             "At end, client state is CLOSED")

        def on_end():
            try:
                do_score()
                tester.finish()
            except Exception:
                log.exception("Exception during scoring")
            core.quit()

        tm.set_timer_at(float(run_time), on_end)
Exemplo n.º 49
0
def launch (entire=False):
  """
  If --entire then the whole message is color-coded, otherwise just the
  log level.

  Also turns on interpretation of some special sequences in the log
  format string.  For example, try:
   log --format="%(levelname)s: @@@bold%(message)s@@@normal" log.color
  """

  global enabled
  if enabled: return

  from pox.core import core
  log = core.getLogger()

  windows_hack = False

  # Try to work on Windows
  if sys.platform == "win32":
    try:
      from colorama import init
      windows_hack = True
      init()
    except:
      log.info("You need colorama if you want color logging on Windows")
      global _strip_only
      _strip_only = True

  from pox.core import _default_log_handler as dlf
  if not dlf:
    log.warning("Color logging disabled -- no default logger found")
    return
  #if not hasattr(dlf, 'formatter'):
  #  log.warning("Color logging disabled -- no formatter found")
  #  return
  #if not hasattr(dlf.formatter, '_fmt'):
  #  log.warning("Color logging disabled -- formatter unrecognized")
  #  return

  # Monkeypatch in a new format function...
  old_format = dlf.format
  if entire:
    def new_format (record):
      msg = _proc(old_format(record), record.levelname)
      color = LEVEL_COLORS.get(record.levelname)
      if color is None:
        return msg
      return _color(color, msg)
  else:
    def new_format (record):
      color = LEVEL_COLORS.get(record.levelname)
      oldlevelname = record.levelname
      if color is not None:
        record.levelname = _color(color, record.levelname)
      return _proc(old_format(record), oldlevelname)
  dlf.format = new_format

  if windows_hack:
    if hasattr(dlf, "stream"):
      if dlf.stream is sys.__stderr__:
        dlf.stream = sys.stderr
        enabled = True
  else:
    enabled = True
Exemplo n.º 50
0
from pox.core import core
from pox.lib.addresses import *
from pox.lib.packet import *
from pox.lib.recoco.recoco import *
import fileinput
import re
# Get a logger
log = core.getLogger("fw")


class Firewall(object):
    """
  Firewall class.
  Extend this to implement some firewall functionality.
  Don't change the name or anything -- the eecore component
  expects it to be firewall.Firewall.
  """
    def __init__(self):
        """
    Constructor.
    Put your initialization code here.
    """
        self.debug = True
        self.debug2 = True
        self.banned_ports = set()
        for line in fileinput.input('/root/pox/ext/banned-ports.txt'):
            portNumber = int(line.rstrip())
            log.debug(portNumber)
            self.banned_ports.add(portNumber)
        self.banned_domains = set()
        for line in fileinput.input('/root/pox/ext/banned-domains.txt'):
Exemplo n.º 51
0
    def setup():
        log = core.getLogger(log_name)
        tester = Tester(log)
        topo = core.sim_topo

        if server_isn is None:
            TXWindow.generate_isn = lambda _: random.randint(1000, 100000)
        else:
            TXWindow.generate_isn = lambda _: literal_eval(server_isn)

        def get_client_socket():
            try:
                return next(iter(c1.stack.socket_manager.peered.itervalues()))
            except Exception:
                return None

        c1 = core.sim_topo.get_node("c1")
        s1 = core.sim_topo.get_node("s1")
        r1 = core.sim_topo.get_node("r1")
        r2 = core.sim_topo.get_node("r2")
        tm = core.sim_topo.time
        r1c1_dev = core.sim_topo.get_devs(r1, c1)[0]

        # sapp calls close() after receiving data
        # capp calls sends data and immediately calls close()
        sapp = s1._new_resocket_app(ClosingRXApp, port=1000, listen=True)
        capp = c1.new_fast_sender(data=100,
                                  ip=s1.netdev.ip_addr,
                                  port=1000,
                                  delay=0.5)

        pkts = []

        def on_cap(e):
            parsed = e.parsed
            if not parsed: return
            parsed = parsed.find("tcp")
            if not parsed: return
            # Giant hack, but just tack this stuff on
            parsed._devname = e.dev.name
            parsed._client = e.dev is r1c1_dev
            parsed._server = not parsed._client
            csock = get_client_socket()
            parsed._client_state = csock.state if csock else None
            pkts.append(parsed)
            #print e.dev,parsed.dump()

        r1.stack.add_packet_capture("*", on_cap, ip_only=True)

        def do_score():
            tester.expect_eq("*" * 100, sapp.all_rx[0][1],
                             "payload correctly sent")

            # search first FIN
            fin_idx = -1
            for i, p in enumerate(pkts):
                if p.FIN:
                    fin_idx = i

            # make sure there's no payloads after FIN
            payload_after_fin = False
            for p in pkts[fin_idx:]:
                if p.payload:
                    payload_after_fin = True
                    break

            tester.expect_true(not payload_after_fin, "no payload after fin")

        def on_end():
            try:
                do_score()
                tester.finish()
            except Exception:
                log.exception("Exception during scoring")
            core.quit()

        tm.set_timer_at(float(run_time), on_end)
Exemplo n.º 52
0
    def setup():
        log = core.getLogger(log_name)
        tester = Tester(log)
        topo = core.sim_topo

        if server_isn is None:
            TXWindow.generate_isn = lambda _: random.randint(1000, 100000)
        else:
            TXWindow.generate_isn = lambda _: literal_eval(server_isn)

        def get_client_socket():
            try:
                return next(iter(c1.stack.socket_manager.peered.itervalues()))
            except Exception:
                return None

        c1 = core.sim_topo.get_node("c1")
        s1 = core.sim_topo.get_node("s1")
        r1 = core.sim_topo.get_node("r1")
        r2 = core.sim_topo.get_node("r2")
        tm = core.sim_topo.time
        r1c1_dev = core.sim_topo.get_devs(r1, c1)[0]

        # sapp calls close() after receiving data
        # capp calls sends data and immediately calls close()
        sapp = s1._new_resocket_app(ClosingRXApp, port=1000, listen=True)
        capp = c1._new_resocket_app(TXRatedApp,
                                    ip=s1.netdev.ip_addr,
                                    port=1000,
                                    delay=0.5)
        capp.tx_data = '#' * 1300 * 100

        pkts = []
        client_socket = None

        def on_cap(e):
            if not pkts:
                global client_socket
                client_socket = get_client_socket()

            parsed = e.parsed
            if not parsed: return
            parsed = parsed.find("tcp")
            if not parsed: return
            # Giant hack, but just tack this stuff on
            parsed._devname = e.dev.name
            parsed._client = e.dev is r1c1_dev
            parsed._server = not parsed._client
            csock = get_client_socket()
            parsed._client_state = csock.state if csock else None
            pkts.append(parsed)
            #print e.dev,parsed.dump()

        r1.stack.add_packet_capture("*", on_cap, ip_only=True)

        def do_score():
            tester.expect_eq("#" * 1300 * 100, sapp.all_rx[0][1],
                             "payload correctly sent")
            lat = 200 / 1000.0
            low_srtt = lat * 2 * 0.9
            high_srtt = lat * 2 * 1.1

            global client_socket
            actual_srtt = client_socket.srtt
            tester.expect_true(low_srtt <= actual_srtt <= high_srtt,
                               "srtt is within +-10% of 2*RTT")

        def on_end():
            try:
                do_score()
                tester.finish()
            except Exception:
                log.exception("Exception during scoring")
            core.quit()

        tm.set_timer_at(float(run_time), on_end)
Exemplo n.º 53
0
 def set_miss_length(event=None):
     if not core.hasComponent('openflow'):
         return
     core.openflow.miss_send_len = 0x7fff
     core.getLogger().info("Requesting full packet payloads")
     return EventRemove
Exemplo n.º 54
0
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
A very sloppy IP load balancer.

Run it with --ip=<Service IP> --servers=IP1,IP2,...

Please submit improvements. :)
"""

from pox.core import core
import pox

log = core.getLogger("iplb")

from pox.lib.packet.ethernet import ethernet, ETHER_BROADCAST
from pox.lib.packet.ipv4 import ipv4
from pox.lib.packet.arp import arp
from pox.lib.addresses import IPAddr, EthAddr
from pox.lib.util import str_to_bool, dpid_to_str

import pox.openflow.libopenflow_01 as of

import time
import random

FLOW_IDLE_TIMEOUT = 10
FLOW_MEMORY_TIMEOUT = 60
Exemplo n.º 55
0
from zlib import crc32

from pox.core import core
from pox.lib.util import dpidToStr
import pox.openflow.libopenflow_01 as of
from pox.lib.revent import EventMixin
from pox.lib.addresses import EthAddr
from pox.lib.packet.ipv4 import ipv4
from pox.lib.packet.udp import udp
from pox.lib.packet.tcp import tcp
from pox.lib.util import str_to_bool, dpid_to_str
from ripllib.mn import topos

from util import buildTopo, getRouting

log = core.getLogger("hederaController")
# log.setLevel(logging.WARNING)

# Number of bytes to send for packet_ins
MISS_SEND_LEN = 2000

IDLE_TIMEOUT = 10
CAPACITY = 1


# Borrowed from pox/forwarding/l2_multi
class Switch(object):
    def __init__(self):
        self.connection = None
        self.ports = None
        self.dpid = None
Exemplo n.º 56
0
class AbstractRequestHandler(BaseHTTPRequestHandler, object):
    """
  Minimalistic RESTful API for Layer APIs.

  Handle /escape/* URLs.

  Method calling permissions represented in escape_intf dictionary.

  .. warning::
    This class is out of the context of the recoco's co-operative thread
    context! While you don't need to worry much about synchronization between
    recoco tasks, you do need to think about synchronization between recoco task
    and normal threads. Synchronisation is needed to take care manually - use
    relevant helper function of core object: :func:`callLater()`/
    :func:`raiseLater()` or use :func:`schedule_as_coop_task()
    <escape.util.misc.schedule_as_coop_task>` decorator defined in
    :mod:`escape.util.misc` on the called function!
  """
    # For HTTP Response messages
    server_version = "ESCAPE/" + get_escape_version()
    """server version for HTTP Response messages"""
    static_prefix = "escape"
    # Bound HTTP verbs to UNIFY's API functions
    request_perm = {
        'GET': ('ping', 'version', 'operations'),
        'POST': ('ping', )
    }
    """Bound HTTP verbs to UNIFY's API functions"""
    # Name of the layer API to which the server bounded
    bounded_layer = None
    """Name of the layer API to which the server bounded"""
    # Name mapper to avoid Python naming constraint (dict: rpc-name: mapped name)
    rpc_mapper = None
    """Name mapper to avoid Python naming constraint"""
    # Logger name
    LOGGER_NAME = "REST-API"
    """Logger name"""
    # Logger. Should be overrided in child classes
    log = core.getLogger("[%s]" % LOGGER_NAME)
    # Use Virtualizer format
    virtualizer_format_enabled = False
    """Use Virtualizer format"""
    # Default communication approach
    format = "FULL"
    """Default communication approach"""
    MESSAGE_ID_NAME = "message-id"

    def setup(self):
        BaseHTTPRequestHandler.setup(self)

    def do_GET(self):
        """
    Get information about an entity. R for CRUD convention.
    """
        self._process_url()

    def do_POST(self):
        """
    Create an entity. C for CRUD convention.

    :return: None
    """
        self._process_url()

    def do_PUT(self):
        """
    Update an entity. U for CRUD convention.

    :return: None
    """
        self._process_url()

    def do_DELETE(self):
        """
    Delete an entity. D for CRUD convention.

    :return: None
    """
        self._process_url()

    # Unsupported HTTP verbs

    def do_OPTIONS(self):
        """
    Handling unsupported HTTP verbs.

    :return: None
    """
        self.send_error(httplib.NOT_IMPLEMENTED)
        self.wfile.close()

    def do_HEAD(self):
        """
    Handling unsupported HTTP verbs.

    :return: None
    """
        # self.send_error(501)
        self.wfile.close()

    def do_TRACE(self):
        """
    Handling unsupported HTTP verbs.

    :return: None
    """
        self.send_error(httplib.NOT_IMPLEMENTED)
        self.wfile.close()

    def do_CONNECT(self):
        """
    Handling unsupported HTTP verbs.

    :return: None
    """
        self.send_error(httplib.NOT_IMPLEMENTED)
        self.wfile.close()

    def get_request_params(self):
        """
    Parse request params from URL.

    :return: parsed params
    :rtype: dict
    """
        params = {}
        query = urlparse.urlparse(self.path).query
        if query:
            query = query.split('&')
            for param in query:
                if '=' in param:
                    name, value = param.split('=', 1)
                    params[name] = value
                else:
                    params[param] = True
        # Check message-id in headers as backup
        if self.MESSAGE_ID_NAME not in params:
            if self.MESSAGE_ID_NAME in self.headers:
                params[self.MESSAGE_ID_NAME] = self.headers[
                    self.MESSAGE_ID_NAME]
                self.log.debug("Detected message id: %s" %
                               params[self.MESSAGE_ID_NAME])
            else:
                params[self.MESSAGE_ID_NAME] = str(uuid.uuid1())
                self.log.debug("No message-id! Generated id: %s" %
                               params[self.MESSAGE_ID_NAME])
        else:
            self.log.debug("Detected message id: %s" %
                           params[self.MESSAGE_ID_NAME])
        self.log.debug("Detected request parameters: %s" % params)
        return params

    def _process_url(self):
        """
    Split HTTP path and call the carved function if it is defined in this class
    and in request_perm.

    :return: None
    """
        self.log.debug(">>> Got HTTP %s request: %s:%s --> %s" %
                       (self.command, self.client_address[0],
                        self.client_address[1], self.path))
        http_method = self.command
        real_path = urlparse.urlparse(self.path).path
        try:
            prefix = '/%s/' % self.static_prefix
            if real_path.startswith(prefix):
                self.func_name = real_path[len(prefix):].split('/')[0]
                if self.rpc_mapper:
                    try:
                        self.func_name = self.rpc_mapper[self.func_name]
                    except KeyError:
                        # No need for RPC name mapping, continue
                        pass
                if http_method in self.request_perm:
                    if self.func_name in self.request_perm[http_method]:
                        if hasattr(self, self.func_name):
                            # Response is assembled, and sent back by handler functions
                            params = self.get_request_params()
                            getattr(self, self.func_name)(params=params)
                        else:
                            self.send_error(
                                httplib.INTERNAL_SERVER_ERROR,
                                "Missing handler for actual request!")
                    else:
                        self.send_error(httplib.NOT_ACCEPTABLE)
                else:
                    self.send_error(httplib.NOT_IMPLEMENTED)
            else:
                self.send_error(httplib.NOT_FOUND,
                                "URL path is not valid or misconfigured!")
        except RESTError as e:
            # Handle all the errors
            if e.code:
                self.send_error(e.code, e.msg)
            else:
                self.send_error(httplib.INTERNAL_SERVER_ERROR, e.msg)
        except:
            # Got unexpected exception
            self.send_error(httplib.INTERNAL_SERVER_ERROR)
            self.log.error("\n%s" % traceback.format_exc())
        finally:
            self.func_name = None
            self.wfile.flush()
            self.wfile.close()
        self.log.debug(">>> HTTP request: %s ended!" %
                       str(self.raw_requestline).rstrip())

    def _get_body(self):
        """
    Parse HTTP request body as a plain text.

    .. note::

      Call only once by HTTP request.

    .. note::

      Parsed JSON object is Unicode.

    GET, DELETE messages don't have body - return empty dict by default.

    :return: request body in str format
    :rtype: str
    """
        charset = 'utf-8'
        # json.loads returns an empty dict if it's called with an empty string
        # but this check we can avoid to respond with unnecessary missing
        # content-* error
        if self.command.upper() in ('GET', 'DELETE'):
            return {}
        try:
            splitted_type = self.headers['Content-Type'].split('charset=')
            if len(splitted_type) > 1:
                charset = splitted_type[1]
            content_len = int(self.headers['Content-Length'])
            raw_data = self.rfile.read(size=content_len).encode(charset)
            # Avoid missing param exception by hand over an empty json data
            return raw_data if content_len else "{}"
        except KeyError as e:
            # Content-Length header is not defined
            # or charset is not defined in Content-Type header.
            if e.args[0] == 'Content-Type':
                self.log.warning("Missing header from request: %s" % e.args[0])
            if e.args[0] == 'Content-Length':
                # 411: ('Length Required', 'Client must specify Content-Length.'),
                raise RESTError(code=httplib.LENGTH_REQUIRED)
            else:
                raise RESTError(code=httplib.PRECONDITION_FAILED,
                                msg="Missing header from request: %s" %
                                e.args[0])
        except ValueError as e:
            # Failed to parse request body to JSON
            self.log_error("Request parsing failed: %s", e)
            raise RESTError(code=httplib.UNSUPPORTED_MEDIA_TYPE,
                            msg="Request parsing failed: %s" % e)

    def send_REST_headers(self):
        """
    Set the allowed REST verbs as an HTTP header (Allow).

    :return: None
    """
        try:
            if self.func_name:
                self.send_header(
                    'Allow', ','.join([
                        str(verbs)
                        for verbs, f in self.request_perm.iteritems()
                        if self.func_name in f
                    ]))
        except KeyError:
            pass

    def send_acknowledge(self, code=None, message_id=None):
        """
    Send back acknowledge message.

    :param code: use explicit response code
    :type code: int
    :param message_id: response body
    :param message_id: dict
    :return: None
    """
        if code:
            self.send_response(int(code))
        else:
            self.send_response(httplib.ACCEPTED)
        if message_id:
            self.send_header('message-id', message_id)
        self.send_REST_headers()
        self.end_headers()

    def send_raw_response(self,
                          raw_data,
                          code=None,
                          content="text/plain",
                          encoding='utf-8'):
        """
    Send requested data.

    :param code: use explicit response code
    :type code: int
    :param content: use explicit content type
    :type content: str
    :param raw_data: data in JSON format
    :type raw_data: dict
    :param encoding: Set data encoding (optional)
    :type encoding: str
    :return: None
    """
        if code:
            self.send_response(int(code))
        else:
            self.send_response(httplib.OK)
        self.send_header('Content-Type',
                         '%s; charset=%s' % (content, encoding))
        self.send_header('Content-Length', len(raw_data))
        self.send_REST_headers()
        self.end_headers()
        self.wfile.write(raw_data)

    def send_json_response(self, data, code=None, encoding='utf-8'):
        """
    Send requested data in JSON format.

    :param data: data in JSON format
    :type data: dict
    :param code: use explicit response code
    :type code: int
    :param encoding: Set data encoding (optional)
    :type encoding: str
    :return: None
    """
        response_body = json.dumps(data, encoding=encoding)
        return self.send_raw_response(raw_data=response_body,
                                      code=code,
                                      content="application/json",
                                      encoding=encoding)

    error_content_type = "text/json"
    """Content-Type for error responses"""

    def send_error(self, code, message=None):
        """
    Override original function to send back allowed HTTP verbs and set format
    to JSON.

    :param code: error code
    :type code: int
    :param message: error message
    :type message: str
    :return: None
    """
        try:
            short, long = self.responses[code]
        except KeyError:
            short, long = '???', '???'
        if message is None:
            message = short
        explain = long
        self.log_error("code %d, message %s", code, message)
        # using _quote_html to prevent Cross Site Scripting attacks (see bug
        # #1100201)
        content = {
            "title": "Error response",
            'Error code': code,
            'Message': message,
            'Explanation': explain
        }
        self.send_response(code, message)
        self.send_header("Content-Type", self.error_content_type)
        self.send_header('Connection', 'close')
        # self.send_REST_headers()
        self.end_headers()
        if self.command != 'HEAD' and code >= 200 and code not in (204, 304):
            self.wfile.write(json.dumps(content))

    def log_error(self, mformat, *args):
        """
    Overwritten to use POX logging mechanism.

    :param mformat: message format
    :type mformat: str
    :return: None
    """
        self.log.error(
            "%s - - [%s] %s" % (self.client_address[0],
                                self.log_date_time_string(), mformat % args))

    def log_message(self, mformat, *args):
        """
    Disable logging of incoming messages.

    :param mformat: message format
    :type mformat: str
    :return: None
    """
        pass

    def log_full_message(self, mformat, *args):
        """
    Overwritten to use POX logging mechanism.

    :param mformat: message format
    :type mformat: str
    :return: None
    """
        self.log.debug(
            "%s - - [%s] %s" % (self.client_address[0],
                                self.log_date_time_string(), mformat % args))

    def _proceed_API_call(self, function, *args, **kwargs):
        """
    Fail-safe method to call API function.

    The cooperative micro-task context is handled by actual APIs.

    Should call this with params, not directly the function of actual API.

    :param function: function name
    :type function: str
    :param args: Optional params
    :type args: tuple
    :param kwargs: Optional named params
    :type kwargs: dict
    :return: None
    """
        if core.core.hasComponent(self.bounded_layer):
            layer = core.components[self.bounded_layer]
            if hasattr(layer, function):
                return getattr(layer, function)(*args, **kwargs)
            else:
                self.log.warning(
                    'Mistyped or not implemented API function call: %s ' %
                    function)
                raise RESTError(
                    msg='Mistyped or not implemented API function call: %s ' %
                    function)
        else:
            self.log.error(
                'Error: No component has registered with the name: %s, '
                'ABORT function call!' % self.bounded_layer)

    ##############################################################################
    # Basic REST-API functions
    ##############################################################################

    # noinspection PyUnusedLocal
    def ping(self, params):
        """
    For testing REST API aliveness and reachability.

    :param params: additional params (skipped)
    :return: None
    """
        if self.server.ping_response_code == self.server.POST_UP_PING_CODE:
            response_body = "OK"
        else:
            response_body = "INITIALIZING"
        self.send_response(code=self.server.ping_response_code)
        self.send_header('Content-Type', 'text/plain')
        self.send_header('Content-Length', len(response_body))
        self.send_REST_headers()
        self.end_headers()
        self.wfile.write(response_body)
        self.log.debug("Sent response: %s, %s" %
                       (self.server.ping_response_code, response_body))

    # noinspection PyUnusedLocal
    def version(self, params):
        """
    Return with version

    :param params: additional params (skipped)
    :return: None
    """
        self.log.debug("Call REST-API function: version")
        body = {"name": __project__, "version": get_escape_version()}
        self.send_json_response(body)
        self.log.debug("Sent response: %s" % body)

    # noinspection PyUnusedLocal
    def operations(self, params):
        """
    Return with allowed operations

    :param params: additional params (skipped)
    :return: None
    """
        self.log.debug("Call REST-API function: operations")
        self.send_json_response(self.request_perm)
Exemplo n.º 57
0
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with POX.  If not, see <http://www.gnu.org/licenses/>.
"""
This is a prototype control application written on top of the (substrate) NOM.

It converts NOM switch entities into LearningSwitches.
"""

from pox.core import core
from pox.controllers.controller import Controller
from learning_switch import LearningSwitch

name = "l2_controller"
log = core.getLogger(name)


# In addition to declaring the user-defined NOM entity, the application must tell the platform
# how and when to instantiate these NOM entities. We do this with the following controller:
class nom_l2_switch_controller(Controller):
    """ Controller that treats the network as a set of learning switches """

    _core_name = name

    def __init__(self):
        """ Initializes the l2 switch controller component """
        Controller.__init__(self)
        log.debug("nom_l2_switch_controller booting...")

    def _handle_topology_SwitchJoin(self, switchjoin_event):
An L2 learning switch.

It is derived from one written live for an SDN crash course.
It is somwhat similar to NOX's pyswitch in that it installs
exact-match rules for each flow.
"""
from __future__ import division
from random import randrange
from pox.core import core
import pox.openflow.libopenflow_01 as of
from pox.lib.util import dpid_to_str
from pox.lib.util import str_to_bool
import sys, os, commands, time
from pox.lib.util import dpidToStr

log = core.getLogger()
#-------------------------------define flow rate----------
flow_rate = 50
interval = 1 / flow_rate
print 'current flow modification rate is:', flow_rate
global burst
burst = {}
# We don't want to flood immediately when a switch connects.
# Can be overriden on commandline.
_flood_delay = 0


class LearningSwitch(object):
    """
  The learning switch "brain" associated with a single OpenFlow switch.
Exemplo n.º 59
0
from pox.core import core
import pox.openflow.libopenflow_01 as of
from pox.lib.revent import *
from pox.lib.util import dpidToStr
from pox.lib.revent import EventMixin

from pox.openflow.of_json import *

from threading import Thread

import socket
import json
import math
import time

LOG = core.getLogger()
CONTROLLER_IP = '10.1.4.1'


class ServerSocket(Thread):
    """ Class that listens for switch messages """
    def __init__(self, connections):
        Thread.__init__(self)
        self.sock = None
        self.connections = connections  #dpdi of the switch

    def run(self):
        self.sock = socket.socket()
        host = CONTROLLER_IP
        port = 12345  # Reserve a port for own communication btwn switches and controller
        #log.info("Binding to listen for switch messages")
Exemplo n.º 60
0
# ext/aula2ex2.py

# Importar as bibliotecas
from pox.core import core
import pox.openflow.libopenflow_01 as of
from pox.lib.revent import *
from pox.lib.addresses import EthAddr, IPAddr
from pox.lib.util import dpidToStr

log = core.getLogger()  # logging


class aula2ex2(EventMixin):
    def __init__(self):
        self.listenTo(core.openflow)

    def _handle_ConnectionUp(self, event):
        log.debug("Connection UP from %s", event.dpid)

    def _handle_PacketIn(self, event):
        packet = event.parsed
        # Drop de todos os pacotes
        msg = of.ofp_flow_mod()
        msg.match.in_port = event.port
        msg.match.dl_src = packet.src
        msg.match.dl_dst = packet.dst
        event.connection.send(msg)
        log.debug("Drop packet sw=%s in_port=%s src=%s dst=%s" \
              % (event.dpid, event.port, packet.src, packet.dst))