Ejemplo n.º 1
0
    def __init__(self, *args, **kwargs):
        super(TopoSpec, self).__init__(*args, **kwargs)
        app_manager.require_app("ryu.topology.switches")
        CONF.register_opt(StrOpt("spec_path", default="spec/mininet.yml"))

        self.graph = nx.Graph()
        self.spec = Spec.from_yaml(CONF.spec_path)
        self._thread = hub.spawn_after(3, self._compare_spec)
Ejemplo n.º 2
0
class Ijoin(app_manager.RyuApp):
    """
	================ =========================================================
	Attribute        Description
	================ =========================================================
	OFP_VERSIONS     Declaration of supported OFP version
	_EVENTS          The list of events provided by the RyuApp
	================ =========================================================
	"""
    OFP_VERSIONS = [ofproto.OFP_VERSION]
    _EVENTS = []

    app_manager.require_app('timer.timer', api_style=False)
    app_manager.require_app('packet.packet', api_style=False)
    app_manager.require_app('nmm.nmm', api_style=False)
    app_manager.require_app('teem.teem', api_style=False)
    app_manager.require_app('amm.amm', api_style=False)
    app_manager.require_app('mme.mme', api_style=False)
    app_manager.require_app('ndisc.ndisc', api_style=False)
    app_manager.require_app('accesspoint.accesspoint', api_style=False)
    app_manager.require_app('gateway.gateway', api_style=False)

    def __init__(self, *args, **kwargs):
        """
		================ =========================================================
		Attribute        Description
		================ =========================================================
		switches         The dictionary storing the switches
		gateways         The dictionary storing the switches enabled with
						 gateway functionalities
		================ =========================================================
		"""
        super(Ijoin, self).__init__(*args, **kwargs)
        self.logger = log.get_logger(self.name)
Ejemplo n.º 3
0
                           stat.port_no, stat.duration_sec, stat.duration_nsec,
                           stat.rx_packets, stat.rx_bytes, stat.rx_errors,
                           stat.tx_packets, stat.tx_bytes, stat.tx_errors))
                iff.write("\n")

    # The switch notifies controller of change of ports.
    @set_ev_cls(ofp_event.EventOFPPortStatus, MAIN_DISPATCHER)
    def _port_status_handler(self, ev):
        msg = ev.msg
        reason = msg.reason
        port_no = msg.desc.port_no

        ofproto = msg.datapath.ofproto
        if reason == ofproto.OFPPR_ADD:
            self.logger.info("port added %s", port_no)
        elif reason == ofproto.OFPPR_DELETE:
            self.logger.info("port deleted %s", port_no)
        elif reason == ofproto.OFPPR_MODIFY:
            self.logger.info("port modified %s", port_no)
        else:
            self.logger.info("Illeagal port state %s %s", port_no, reason)


# This will turn on Web restAPI
app_manager.require_app('ryu.app.rest_topology')
app_manager.require_app('ryu.app.ws_topology')
app_manager.require_app('ryu.app.ofctl_rest')
# app_manager.require_app('my_traffic_monitor')
app_manager.require_app('ryu.app.gui_topology.gui_topology')
# print "Project Path", PATH
Ejemplo n.º 4
0
#
# 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.

from ryu.base import app_manager
from ryu.services.protocols.ldp import event as ldp_event 


def ldp_config(app, interface, config):
    """create an instance.
    returns EventVRRPConfigReply(instance.name, interface, config)
    on success.
    returns EventVRRPConfigReply(None, interface, config)
    on failure.
    """
    config_request = ldp_event.EventLDPConfigRequest(interface, config)
    config_request.sync = True
    return app.send_request(config_request)

app_manager.require_app('ryu.services.protocols.ldp.manager', api_style=True)
Ejemplo n.º 5
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.

from ryu.base import app_manager
from ryu.topology import event


def get_switch(app, dpid=None):
    rep = app.send_request(event.EventSwitchRequest(dpid))
    return rep.switches


def get_all_switch(app):
    return get_switch(app)


def get_link(app, dpid=None):
    rep = app.send_request(event.EventLinkRequest(dpid))
    return rep.links


def get_all_link(app):
    return get_link(app)


app_manager.require_app('ryu.topology.switches', api_style=True)

Ejemplo n.º 6
0
def vrrp_transmit(app, monitor_name, data):
    """transmit a packet from the switch.  this is internal use only.
    data is str-like, a packet to send.
    """
    transmit_request = vrrp_event.EventVRRPTransmitRequest(data)
    app.send_event(monitor_name, transmit_request)


def vrrp_list(app, instance_name=None):
    """list instances.
    returns EventVRRPListReply([VRRPInstance]).
    """
    list_request = vrrp_event.EventVRRPListRequest(instance_name)
    list_request.dst = vrrp_event.VRRP_MANAGER_NAME
    return app.send_request(list_request)


def vrrp_config_change(app, instance_name,
                       priority=None, advertisement_interval=None,
                       preempt_mode=None, accept_mode=None):
    """change configuration of an instance.
    None means no change.
    """
    config_change = vrrp_event.EventVRRPConfigChangeRequest(
        instance_name, priority, advertisement_interval,
        preempt_mode, accept_mode)
    return app.send_event(vrrp_event.VRRP_MANAGER_NAME, config_change)


app_manager.require_app('ryu.services.protocols.vrrp.manager')
Ejemplo n.º 7
0
Archivo: api.py Proyecto: chenhuan0/ryu
    :param app: Client RyuApp instance
    :param msg: An OpenFlow controller-to-switch message to send
    :param reply_cls: OpenFlow message class for expected replies.
        None means no replies are expected.  The default is None.
    :param reply_multi: True if multipart replies are expected.
        The default is False.

    If no replies, returns None.
    If reply_multi=False, returns OpenFlow switch-to-controller message.
    If reply_multi=True, returns a list of OpenFlow switch-to-controller
    messages.

    Raise an exception on error.

    Example::

        import ryu.app.ofctl.api as api

        msg = parser.OFPPortDescStatsRequest(datapath=datapath)
        result_backup = api.send_msg(self, msg,
                                    reply_cls=parser.OFPPortDescStatsReply,
                                    reply_multi=True)
    """
    return app.send_request(event.SendMsgRequest(msg=msg,
                                                 reply_cls=reply_cls,
                                                 reply_multi=reply_multi))()


app_manager.require_app('ryu.app.ofctl.service', api_style=True)
Ejemplo n.º 8
0
    :param app: Client RyuApp instance
    :param msg: An OpenFlow controller-to-switch message to send
    :param reply_cls: OpenFlow message class for expected replies.
        None means no replies are expected.  The default is None.
    :param reply_multi: True if multipart replies are expected.
        The default is False.

    If no replies, returns None.
    If reply_multi=False, returns OpenFlow switch-to-controller message.
    If reply_multi=True, returns a list of OpenFlow switch-to-controller
    messages.

    Raise an exception on error.

    Example::

        import ryu.app.ofctl.api as api

        msg = parser.OFPPortDescStatsRequest(datapath=datapath)
        result = api.send_msg(self, msg,
                                    reply_cls=parser.OFPPortDescStatsReply,
                                    reply_multi=True)
    """
    return app.send_request(
        event.SendMsgRequest(msg=msg,
                             reply_cls=reply_cls,
                             reply_multi=reply_multi))()


app_manager.require_app('ryu.app.ofctl.service', api_style=True)
Ejemplo n.º 9
0
# 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.

# client for ryu.app.ofctl.service

from ryu.base import app_manager
import event


def get_datapath(app, dpid):
    """
    Get datapath object by dpid.
    Returns None on error.
    """
    assert isinstance(dpid, (int, long))
    return app.send_request(event.GetDatapathRequest(dpid=dpid))()


def send_msg(app, msg, reply_cls=None, reply_multi=False):
    """
    Send an openflow message.
    """
    return app.send_request(event.SendMsgRequest(msg=msg,
                                                 reply_cls=reply_cls,
                                                 reply_multi=reply_multi))()


app_manager.require_app('ryu.app.ofctl.service')
Ejemplo n.º 10
0
    }

    def __init__(self, *args, **kwargs):
        super(GUIServerApp, self).__init__(*args, **kwargs)

        wsgi = kwargs['wsgi']
        wsgi.register(GUIServerController)


class GUIServerController(ControllerBase):
    def __init__(self, req, link, data, **config):
        super(GUIServerController, self).__init__(req, link, data, **config)
        path = "%s/html/" % PATH
        self.static_app = DirectoryApp(path)

    @route('topology', '/{filename:.*}')
    def static_handler(self, req, **kwargs):
        if kwargs['filename']:
            req.path_info = kwargs['filename']
        return self.static_app(req)


'''
Modified here.
'''
app_manager.require_app(PATH + '/simple_switch_stp_13.py')

app_manager.require_app('ryu.app.rest_topology')
app_manager.require_app('ryu.app.ws_topology')
app_manager.require_app('ryu.app.ofctl_rest')
Ejemplo n.º 11
0
from ryu.base import app_manager
from ryu.topology import event


def get_link(app):
    rep = app.send_request(event.EventLinkRequest(None))
    return rep.links


app_manager.require_app('ryuo.local.topology', api_style=True)
Ejemplo n.º 12
0
        :param node:
        :param mac_address:
        :return: UnisRT Port Object

        """
        found = 0
        self.logger.info("CHECKING FOR PORT %s IN SWITCH %s" % (port_name, switch_node.name))
        for port in switch_node.ports:
            if port.address.address == mac_address:
                return port

        self.logger.info("PORT %s NOT FOUND IN SWITCH %s" % (port_name, switch_node.name))
        return None

    def create_vport_object(self, port, switch_name):
        # Takes a port from RYU and converts it into a unisRT port object to push into the DB.

        port_object = Port({"name": switch_name + ":" + port.name.decode("utf-8"), "index": str(port.port_no), "address":
            {"address": port.hw_addr, "type": "mac"}})
        port_object.properties.type = "vport"
        port_object.properties.vport_number = port.port_no
        print("CREATING OBJECT FOR NEW PORT: ", port_object.name)
        # ,"port_type":"vport", "vport_number": port.port_no.decode("utf-8")}

        return port_object

app_manager.require_app('ryu.app.simple_switch_13')
app_manager.require_app('ryu.app.rest_conf_switch')
app_manager.require_app('ryu.app.rest_qos')
app_manager.require_app('ryu.app.ofctl_rest')
Ejemplo n.º 13
0
# Serving static files
class GUIServerApp(app_manager.RyuApp):
    _CONTEXTS = {
        'wsgi': WSGIApplication,
    }

    def __init__(self, *args, **kwargs):
        super(GUIServerApp, self).__init__(*args, **kwargs)

        wsgi = kwargs['wsgi']
        wsgi.register(GUIServerController)


class GUIServerController(ControllerBase):
    def __init__(self, req, link, data, **config):
        super(GUIServerController, self).__init__(req, link, data, **config)
        path = "%s/html/" % PATH
        self.static_app = DirectoryApp(path)

    @route('topology', '/{filename:.*}')
    def static_handler(self, req, **kwargs):
        if kwargs['filename']:
            req.path_info = kwargs['filename']
        return self.static_app(req)


app_manager.require_app('ryu.app.rest_topology')
#app_manager.require_app('ws_topology')
#app_manager.require_app('ofctl_rest')
Ejemplo n.º 14
0
                       else:
                            flag=1
                            break
                   if flag==0:
                        ipAll.append(ip)
        mal.MaliciousURLs = ipAll
        body = json.dumps(mal.MaliciousURLs)
        return Response(content_type='application/json', body=body)
    
    def list_decoyHost(self, req, **kwargs):
        mal = self.mal_app
        host = mal.decoyHost           
        body = json.dumps(host)
        return Response(content_type='application/json', body=body)
    
    def add_decoyHost(self, req, **kwargs):
        mal = self.mal_app
        host = eval(req.body)
        ip = host.keys()[0]
        mac = host[ip]
        length = len(host)
        if length == 1:
            mal.decoyHost.clear()
            mal.decoyHost[ip] = mac
            body = json.dumps(mal.decoyHost)
        else:
            body = json.dumps("Should PUT only one MAC address!")
        return Response(content_type='application/json', body=body)    

app_manager.require_app('ryu.app.MaliciousURLsControl.ws_URLs')
Ejemplo n.º 15
0
                self._link_port()
                self._all_simple_path()
            hub.sleep(10)

    # The switch notifies controller of change of ports.
    @set_ev_cls(ofp_event.EventOFPPortStatus, MAIN_DISPATCHER)
    def _port_status_handler(self, ev):
        msg = ev.msg
        reason = msg.reason
        port_no = msg.desc.port_no

        ofproto = msg.datapath.ofproto
        if reason == ofproto.OFPPR_ADD:
            self.logger.info("port added %s", port_no)
        elif reason == ofproto.OFPPR_DELETE:
            self.logger.info("port deleted %s", port_no)
        elif reason == ofproto.OFPPR_MODIFY:
            self.logger.info("port modified %s", port_no)
        else:
            self.logger.info("Illeagal port state %s %s", port_no, reason)


# This will turn on Web restAPI
app_manager.require_app("ryu.app.rest_topology")
app_manager.require_app("ryu.app.ws_topology")
app_manager.require_app("ryu.app.ofctl_rest")
app_manager.require_app("ryu.app.gui_topology.gui_topology")
# app_manager.require_app('ryu.app.my_arp_v2')
# app_manager.require_app('host_tracker')
# app_manager.require_app('ryu.app.my_monitor_v1')
Ejemplo n.º 16
0
        dpid = ev.dp.id
        self.load_balancer.add_dpid(dpid)

    @set_ev_cls(LBEventRoleChange, MAIN_DISPATCHER)
    def _role_change_handler(self, ev):
        dpid = ev.dpid
        role = ev.role
        # Role:
        # 1: master
        # 2: slave

        switch = api.get_switch(self, dpid)

        if switch != None:
            dp = switch.dp
            ofp = dp.ofproto
            ofp_parser = dp.ofproto_parser

            if role == 1:
                role = ofp.OFPCR_ROLE_MASTER

            else:
                role = ofp.OFPCR_ROLE_SLAVE
            # generate new generation id
            gen_id = random.randint(0, 10000)
            msg = ofp_parser.OFPRoleRequest(dp, role, gen_id)
            dp.send_msg(msg)


app_manager.require_app('liblb.LoadBalancer')
Ejemplo n.º 17
0
    def verify_links_down(self, down_links):
        links = [(link.src.dpid, link.dst.dpid) for link in get_all_link(self)]
        res = True
        for down_link in down_links:
            src = int(down_link.intf1.node.dpid, 16)
            dst = int(down_link.intf2.node.dpid, 16)
            self._logger.info((src, dst))
            if (src, dst) in links:
                self._logger.error('%d <-> %d should be down.', src, dst)
                res = False
            if (dst, src) in links:
                self._logger.error('%d <-> %d should be down.', dst, src)
                res = False
        return res

    def clean_links_down(self, links):
        for link in links:
            self.net.configLinkStatus(
                link.intf1.node.name, link.intf2.node.name, 'up')
        time.sleep(len(links))

    @ryuo_test(order=3)
    def links_up_again(self):
        pass

    def verify_links_up_again(self, dummy):
        return self.verify_all_links(dummy)


app_manager.require_app('ryuo.topology.app')
Ejemplo n.º 18
0
    def verify_links_down(self, down_links):
        links = [(link.src.dpid, link.dst.dpid) for link in get_all_link(self)]
        res = True
        for down_link in down_links:
            src = int(down_link.intf1.node.dpid, 16)
            dst = int(down_link.intf2.node.dpid, 16)
            self._logger.info((src, dst))
            if (src, dst) in links:
                self._logger.error('%d <-> %d should be down.', src, dst)
                res = False
            if (dst, src) in links:
                self._logger.error('%d <-> %d should be down.', dst, src)
                res = False
        return res

    def clean_links_down(self, links):
        for link in links:
            self.net.configLinkStatus(link.intf1.node.name,
                                      link.intf2.node.name, 'up')
        time.sleep(len(links))

    @ryuo_test(order=3)
    def links_up_again(self):
        pass

    def verify_links_up_again(self, dummy):
        return self.verify_all_links(dummy)


app_manager.require_app('ryuo.topology.app')
Ejemplo n.º 19
0
from webob.static import DirectoryApp

from ryuo.controller.central import Ryuo


class GUIServerApp(Ryuo):
    _CONTEXTS = {
        'wsgi': WSGIApplication
    }

    def __init__(self, *args, **kwargs):
        super(GUIServerApp, self).__init__(*args, **kwargs)
        wsgi = kwargs['wsgi']
        wsgi.register(GUIServerController)


class GUIServerController(ControllerBase):
    def __init__(self, req, link, data, **config):
        super(GUIServerController, self).__init__(req, link, data, **config)
        path = '%s/html/' % os.path.dirname(__file__)
        self.static_app = DirectoryApp(path)

    @route('topology', '/html/{filename:.*}')
    def static_handler(self, req, **kwargs):
        if kwargs['filename']:
            req.path_info = kwargs['filename']
        return self.static_app(req)


app_manager.require_app('ryuo.topology.rest_topology')
app_manager.require_app('ryuo.topology.ws_topology')
import json
from webob import Response
from ryu.ofproto import ether
from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ofproto_v1_3
from ryu.lib.packet import tcp, icmp, arp, ipv4, ethernet, packet
from ryu.topology import event, switches
from ryu.topology.api import get_switch, get_link, get_host
from ryu.app.wsgi import ControllerBase, WSGIApplication
import time 
import re

app_manager.require_app('ryu.app.ofctl_rest2')

def retornaLinks():	 
	return listaLinks

class No:
	def __init__ (self, Porta, mac = None): #Classe do tipo nó com atributos Porta e Mac
		self.Porta = Porta
		self.mac = mac

listaLinks = []
def testeLink (link):
	for j in listaLinks:

		#print 'link:    dpidOgm: '+ link.dpidOgm + ' dpidDest: '+ link.dpidDest
		#print 'j:       dpidOgm: '+ j.dpidOgm + ' dpidDest: '+ j.dpidDest
Ejemplo n.º 21
0
        link = None
        while True:
            link = random.choice(self.net.links)
            if len(link.intf1.node.ports) > 2 and len(
                    link.intf2.node.ports) > 2:
                break
        self.net.configLinkStatus(link.intf1.node.name,
                                  link.intf2.node.name,
                                  'down')
        return link

    def verify_random_one_link_down(self, down_link):
        return self.net.pingAll(timeout=2) == 0

    def clean_random_one_link_down(self, down_link):
        self.net.configLinkStatus(down_link.intf1.node.name,
                                  down_link.intf2.node.name,
                                  'up')

    @ryuo_test(order=3)
    def link_up_again(self):
        pass

    def verify_link_up_again(self, dummy):
        return self.net.pingAll(timeout=2) == 0


app_manager.require_app('ryuo.kf_routing.app')
app_manager.require_app('ryuo.topology.app')

Ejemplo n.º 22
0
import event
from ryu.base import app_manager


def send_source_query(app):
    reply = app.send_request(event.EventRequestSpectrumRemain('link_resource'))
    return reply.rsc


app_manager.require_app('spec_resource', api_style=True)
Ejemplo n.º 23
0
        dpid = ev.dp.id
        self.load_balancer.add_dpid(dpid)

    @set_ev_cls(LBEventRoleChange, MAIN_DISPATCHER)
    def _role_change_handler(self, ev):
        dpid = ev.dpid
        role = ev.role
        # Role:
        # 1: master
        # 2: slave

        switch = api.get_switch(self, dpid)

        if switch != None:
            dp = switch.dp
            ofp = dp.ofproto
            ofp_parser = dp.ofproto_parser

            if role == 1:
                role = ofp.OFPCR_ROLE_MASTER

            else:
                role = ofp.OFPCR_ROLE_SLAVE
            # generate new generation id
            gen_id = random.randint(0, 10000)
            msg = ofp_parser.OFPRoleRequest(dp, role, gen_id)
            dp.send_msg(msg)


app_manager.require_app("liblb.LoadBalancer")
Ejemplo n.º 24
0
            print "ipv4 packet"
            if not ipv4_pkt.proto == 1:
                return
            print "icmp packet recieved"
            out_port  = self.get_icmp_outport(dpid,ipv4_pkt.dst,ipv4_pkt.src)

            if not out_port:
                print "could not find output port to forward for the IP packet"
                return

            actions = [parser.OFPActionOutput(int(out_port))]
            data = None
            if msg.buffer_id == ofproto.OFP_NO_BUFFER:
                data = msg.data

            out = parser.OFPPacketOut(datapath=datapath, buffer_id=msg.buffer_id,
                                      in_port=in_port, actions=actions, data=data)
            datapath.send_msg(out)

            r = requests.post('http://localhost:8080/stats/flowentry/add',data='{"dpid": '+str(hexdpid)+',"table_id": 0,"idle_timeout": 300,"hard_timeout": 300,"priority": 65535,"flags": 1,"match":{"eth_type":0x800,"nw_dst":"'+str(ipv4_pkt.dst)+'","ip_proto":1},"actions":[{"type":"OUTPUT","port": '+str(out_port)+'}]}')
            print "installing flow mod for ip packet"
            print 'http://localhost:8080/stats/flowentry/add,data={"dpid": '+dpid+',"table_id": 0,"idle_timeout": 300,"hard_timeout": 300,"priority": 65535,"flags": 1,"match":{"eth_type":0x800,"nw_dst":"'+str(ipv4_pkt.dst)+'","ip_proto":1},"actions":[{"type":"OUTPUT","port": '+str(out_port)+'}]}'
            if r.status_code == requests.codes.ok:
                print "successfully installed ip flow in the switch"
            else:
                print "failed installing flow mod"
app_manager.require_app('ryu.app.rest_topology')
app_manager.require_app('ryu.app.ofctl_rest')


Ejemplo n.º 25
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.

from ryu.base import app_manager
from ryu.topology import event


def get_switch(app, dpid=None):
    rep = app.send_request(event.EventSwitchRequest(dpid))
    return rep.switches


def get_all_switch(app):
    return get_switch(app)


def get_link(app, dpid=None):
    rep = app.send_request(event.EventLinkRequest(dpid))
    return rep.links


def get_all_link(app):
    return get_link(app)


app_manager.require_app('ryu.topology.switches')
Ejemplo n.º 26
0
    """
    transmit_request = vrrp_event.EventVRRPTransmitRequest(data)
    app.send_event(monitor_name, transmit_request)


def vrrp_list(app, instance_name=None):
    """list instances.
    returns EventVRRPListReply([VRRPInstance]).
    """
    list_request = vrrp_event.EventVRRPListRequest(instance_name)
    list_request.dst = vrrp_event.VRRP_MANAGER_NAME
    return app.send_request(list_request)


def vrrp_config_change(app,
                       instance_name,
                       priority=None,
                       advertisement_interval=None,
                       preempt_mode=None,
                       accept_mode=None):
    """change configuration of an instance.
    None means no change.
    """
    config_change = vrrp_event.EventVRRPConfigChangeRequest(
        instance_name, priority, advertisement_interval, preempt_mode,
        accept_mode)
    return app.send_event(vrrp_event.VRRP_MANAGER_NAME, config_change)


app_manager.require_app('ryu.services.protocols.vrrp.manager', api_style=True)
Ejemplo n.º 27
0
class VPNController(app_manager.RyuApp):
    OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]
    app_manager.require_app('ryu.topology.switches')

    def __init__(self, *args, **kwargs):
        super(VPNController, self).__init__(self, *args, **kwargs)
        CONF = cfg.CONF
        #CONF.register_cli_opts([cfg.StrOpt('federation', default='', help='Configuration file for federated networks')])
        #Inserire --main-config + nome-file
        #print '####################################', CONF.federated
        #file =  CONF['config']['file']
        file = CONF.federated
        #print '--------------------------____ Config file:', file
        # Start the System
        self._system = System(10000, file)
        # Load configuration (included VPNs configuration) into the system
        self._system.load_system_configuration()
        # Initialize system
        self._public_to_private_a = {
        }  #Mapping pubblico<-->privato per i miei customer
        self._public_to_private_b = {
        }  #Mapping pubblico<-->privato per customer federati
        self._system.init(self._public_to_private_a, self._public_to_private_b)
        self._public_ip = None

    @set_ev_cls(event.EventSwitchEnter)
    def switch_enter_handler(self, ev):
        # When a switch is added, then add it to the Customer
        datapath = ev.switch.dp
        ip, port = datapath.address
        # print "switch detected: " + ip, port
        self._system.add_node(datapath, ip)

    @set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)
    def switch_features_handler(self, ev):
        msg = ev.msg
        datapath = msg.datapath
        ofp = datapath.ofproto
        parser = datapath.ofproto_parser
        controller = self._system.get_controller_info()
        cs = controller.get_customers()
        #print('-----------cs--------',cs[0])
        if cs[0].get_ns_domain_name() is None:
            #Send Arp packets to Controller --Habib
            match11 = parser.OFPMatch(eth_type=ether.ETH_TYPE_ARP)
            actions11 = [
                parser.OFPActionOutput(ofp.OFPP_CONTROLLER,
                                       ofp.OFPCML_NO_BUFFER)
            ]
            self.add_flow(datapath, 90, match11, actions11)
            #Send DNS packets to controller in order to handle them--> Habib
            match12 = parser.OFPMatch(eth_type=ether.ETH_TYPE_IP, ip_proto=17)
            actions12 = [
                parser.OFPActionOutput(ofp.OFPP_CONTROLLER,
                                       ofp.OFPCML_NO_BUFFER)
            ]
            self.add_flow(datapath, 100, match12, actions12)

        else:
            pool = controller.get_public_subnet()
            ip = IPNetwork(pool)
            ip_list = list(ip)
            oport = cs[0].get_out_port()
            self._public_ip = ip_list[1]
            match3 = parser.OFPMatch(eth_type=ether.ETH_TYPE_IP,
                                     ipv4_src=('10.0.0.3', '255.255.0.0'),
                                     in_port=3)
            actions3 = [parser.OFPActionSetField(ipv4_src=self._public_ip)]
            actions3.append(parser.OFPActionOutput(port=int(oport)))
            inst3 = [
                parser.OFPInstructionActions(ofp.OFPIT_APPLY_ACTIONS, actions3)
            ]
            mod3 = parser.OFPFlowMod(datapath=datapath,
                                     priority=0,
                                     match=match3,
                                     instructions=inst3)
            datapath.send_msg(mod3)

            #Send the recevied DNS packets to the controller
            match4 = parser.OFPMatch(eth_type=ether.ETH_TYPE_IP,
                                     ipv4_dst=(self._public_ip,
                                               '255.255.255.0'))
            actions4 = [
                parser.OFPActionOutput(ofp.OFPP_CONTROLLER,
                                       ofp.OFPCML_NO_BUFFER)
            ]
            inst4 = [
                parser.OFPInstructionActions(ofp.OFPIT_APPLY_ACTIONS, actions4)
            ]
            mod4 = parser.OFPFlowMod(datapath=datapath,
                                     priority=0,
                                     match=match4,
                                     instructions=inst4)
            datapath.send_msg(mod4)

            match = parser.OFPMatch()
            actions = [
                parser.OFPActionOutput(ofp.OFPP_CONTROLLER,
                                       ofp.OFPCML_NO_BUFFER)
            ]
            inst = [
                parser.OFPInstructionActions(ofp.OFPIT_APPLY_ACTIONS, actions)
            ]
            mod = parser.OFPFlowMod(datapath=datapath,
                                    priority=0,
                                    match=match,
                                    instructions=inst)
            #datapath.send_msg(mod)
            #print "installo flow-entry per non droppare"

            #Send Arp packets to Controller --Habib
            match1 = parser.OFPMatch(eth_type=ether.ETH_TYPE_ARP)
            actions1 = [
                parser.OFPActionOutput(ofp.OFPP_CONTROLLER,
                                       ofp.OFPCML_NO_BUFFER)
            ]
            self.add_flow(datapath, 90, match1, actions1)

            # Send DNS packets to controller in order to handle them--> Habib
            match = parser.OFPMatch(eth_type=ether.ETH_TYPE_IP,
                                    ip_proto=17,
                                    in_port=int(cs[0].get_ingress_port()))
            actions = [
                parser.OFPActionOutput(ofp.OFPP_CONTROLLER,
                                       ofp.OFPCML_NO_BUFFER)
            ]
            self.add_flow(datapath, 100, match, actions)

    ''''
    Add flow method for DNS packets when a DNS packet received--> Habib
    '''

    def add_flow(self, datapath, priority, match, actions):
        ofproto = datapath.ofproto
        #print 'hi from add flow'
        parser = datapath.ofproto_parser
        inst = [
            parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS, actions)
        ]
        mod = parser.OFPFlowMod(datapath=datapath,
                                priority=priority,
                                match=match,
                                instructions=inst)
        datapath.send_msg(mod)
        #print'---a rule installed-----'

    @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
    def packet_in_handler(self, ev):
        print "a packet-in is received"
        msg = ev.msg
        datapath = msg.datapath
        dpid = datapath.id
        pkt = packet.Packet(msg.data)
        in_port = msg.match['in_port']
        self._system.handle_packet(pkt, dpid, in_port, msg.data, datapath,
                                   self._public_to_private_a,
                                   self._public_to_private_b)

    @set_ev_cls(ofp_event.EventOFPErrorMsg,
                [HANDSHAKE_DISPATCHER, CONFIG_DISPATCHER, MAIN_DISPATCHER])
    def error_msg_handler(self, ev):
        msg = ev.msg

        self.logger.info(
            'OFPErrorMsg received: type=0x%02x code=0x%02x '
            'message=%s', msg.type, msg.code, utils.hex_array(msg.data))
Ejemplo n.º 28
0
            # Flags must have KBPS or PKTPS
            flags = flags if (flags & 0x03) else (flags | 0x01)

            for band in d["bands"]:
                #mtype = type_convert.get(band[0])
                if band[0] == 'DROP':
                    bands += [parser.OFPMeterBandDrop(rate=band[1],
                                                      burst_size=band[2])]
                elif band[0] == 'DSCP_REMARK':
                    bands += [parser.OFPMeterBandDscpRemark(rate=band[1],
                                                            burst_size=band[2], prec_level=band[3])]

        meter_mod = parser.OFPMeterMod(data_path, cmd, flags, meter_id, bands)
        try:
            data_path.send_msg(meter_mod)
        except KeyError as err:
            return err.__repr__()
        except Exception as err:
            return err.__repr__()

        return "Message sent successfully."

    # def get_flow_stats(self, req, dpid): # unused
    #     flow = {}  # no filters
    #     dp = self.dpset.get(int(str(dpid), 0))
    #     return self.ofctl.get_flow_stats(dp, self.waiters, flow)


# This is is needed for get_topology_data()
app_manager.require_app('ryu.topology.switches', api_style=True)
Ejemplo n.º 29
0
class GUIServerController(ControllerBase):
    def __init__(self, req, link, data, **config):
        super(GUIServerController, self).__init__(req, link, data, **config)
        self.auth = data['auth']
        path = "%s/html/" % PATH
        self.static_app = DirectoryApp(path)

    @route('gui', '/gui/{filename:.*}')
    def static_handler(self, req, **kwargs):
        user = self.auth.get_user(req, **kwargs)
        type = user.user_type

        filename = kwargs['filename']
        if filename == 'topology':
            if type == "god":
                req.path_info = "index_god.html"
            elif type == "manager":
                req.path_info = "index_manager.html"
            else:
                req.path_info = "index.html"
        else:
            req.path_info = filename

        return self.static_app(req)


app_manager.require_app('trustsdn.server.topology')
app_manager.require_app('ryu.app.ws_topology')
app_manager.require_app('trustsdn.server.ofctl_rest')
Ejemplo n.º 30
0
# Serving static files
class GUIServerApp(app_manager.RyuApp):
    _CONTEXTS = {
        'wsgi': WSGIApplication,
    }

    def __init__(self, *args, **kwargs):
        super(GUIServerApp, self).__init__(*args, **kwargs)

        wsgi = kwargs['wsgi']
        wsgi.register(GUIServerController)


class GUIServerController(ControllerBase):
    def __init__(self, req, link, data, **config):
        super(GUIServerController, self).__init__(req, link, data, **config)
        path = "%s/html/" % PATH
        self.static_app = DirectoryApp(path)

    @route('topology', '/{filename:.*}')
    def static_handler(self, req, **kwargs):
        if kwargs['filename']:
            req.path_info = kwargs['filename']
        return self.static_app(req)


app_manager.require_app('ryu.app.MaliciousURLsControl.MaliciousURLsControl_rest')
app_manager.require_app('ryu.app.rest_topology')
app_manager.require_app('ryu.app.ws_topology')
app_manager.require_app('ryu.app.ofctl_rest')
Ejemplo n.º 31
0
        self.logger.info(
            "packet in dpid:%s src:%s dst:%s in:%s out:%s OFF_FLOOD= %s", dpid,
            src, dst, in_port, out_port, ofproto.OFPP_FLOOD)

        # install a flow to avoid packet_in next time
        if out_port != ofproto.OFPP_FLOOD:
            match = parser.OFPMatch(in_port=in_port, eth_dst=dst)
            # verify if we have a valid buffer_id, if yes avoid to send both
            # flow_mod & packet_out
            if msg.buffer_id != ofproto.OFP_NO_BUFFER:
                self.add_flow(datapath, 1, match, actions, table_id,
                              msg.buffer_id)
                return
            else:
                self.add_flow(datapath, 1, match, actions, table_id)
        data = None
        if msg.buffer_id == ofproto.OFP_NO_BUFFER:
            data = msg.data

        out = parser.OFPPacketOut(datapath=datapath,
                                  buffer_id=msg.buffer_id,
                                  in_port=in_port,
                                  actions=actions,
                                  data=data)

        datapath.send_msg(out)


app_manager.require_app('ryu.app.rest_qos')
app_manager.require_app('ryu.app.rest_conf_switch')
Ejemplo n.º 32
0
                                out_group=ofproto.OFPG_ANY)
        datapath.send_msg(mod)

    def send_packet(self, datapath, out_port, pkt):
        ofproto = ofproto_v1_3
        parser = datapath.ofproto_parser
        pkt.serialize()
        data = pkt.data
        actions = [parser.OFPActionOutput(port=out_port)]
        out = parser.OFPPacketOut(datapath=datapath,
                                  buffer_id=ofproto.OFP_NO_BUFFER,
                                  in_port=ofproto.OFPP_CONTROLLER,
                                  actions=actions,
                                  data=data)
        datapath.send_msg(out)

    def get_host_topology(self):
        return dict(self.hosts_topo)

    def get_switch_topology(self):
        return dict(self.switches_topo)

    def get_datapath(self, dpid):
        return self.datapaths.get(dpid, None)

    # need to modify the structure of func_table to produce usable return value
    def get_featuretable(self):
        return self.func_table

app_manager.require_app('./simple_switch_13.py', api_style=True)
Ejemplo n.º 33
0
class GUIServerApp(app_manager.RyuApp):
    _CONTEXTS = {
        'wsgi': WSGIApplication,
    }

    def __init__(self, *args, **kwargs):
        super(GUIServerApp, self).__init__(*args, **kwargs)

        wsgi = kwargs['wsgi']
        wsgi.register(GUIServerController)


class GUIServerController(ControllerBase):
    def __init__(self, req, link, data, **config):
        super(GUIServerController, self).__init__(req, link, data, **config)
        path = "%s/html/" % PATH
        self.static_app = DirectoryApp(path)

    @route('topology', '/{filename:.*}')
    def static_handler(self, req, **kwargs):
        if kwargs['filename']:
            req.path_info = kwargs['filename']
        return self.static_app(req)


app_manager.require_app(PATH + '/shortest_forwarding.py')
app_manager.require_app(PATH + '/rest_firewall.py')
app_manager.require_app('ryu.app.rest_topology')
app_manager.require_app('ryu.app.ws_topology')
app_manager.require_app('ryu.app.ofctl_rest')
Ejemplo n.º 34
0
        return 0, 9

    def send_group_mod(self, datapath, port, queue_id):
        #function to match the destination port and an specific queue
        ofp = datapath.ofproto
        ofp_parser = datapath.ofproto_parser
        port_1 = ofp_parser.OFPActionOutput(port)  #destination port
        queue_1 = ofp_parser.OFPActionSetQueue(queue_id)  #associated queue
        actions_1 = [queue_1, port_1]  #matching port and queue
        weight_1 = 100  #in case of load balancing, porcentage of the traffic by this link
        watch_port = ofproto_v1_3.OFPP_ANY
        watch_group = ofproto_v1_3.OFPQ_ALL

        buckets = [
            ofp_parser.OFPBucket(weight_1, watch_port, watch_group, actions_1)
        ]  #buckets

        group_id = port * 10 + queue_id  # the first number of the identifier identifies the port, the second one the queue
        req = ofp_parser.OFPGroupMod(
            datapath, ofp.OFPFC_ADD, ofp.OFPGT_SELECT, group_id,
            buckets)  #definition of the groupMod with the action buckets.

        datapath.send_msg(req)

        return [datapath.ofproto_parser.OFPActionGroup(group_id)]


app_manager.require_app('ryu.app.ws_topology')
app_manager.require_app('ryu.app.ofctl_rest')
app_manager.require_app('ryu.app.gui_topology.gui_topology')
            s['dpid'] = dpid_to_str(dp)
            s['total_packet_in'] = self.dp_packet_in[dp]
            switches.append(s)
        return switches
            
    def controller_stats(self):
        current_time = calendar.timegm(time.gmtime())
        rv = {}
        
        # times
        rv['up_time'] = current_time - self.start_time
        rv['duration'] = current_time - self.prev_time
        self.prev_time = current_time
        
        # stats
        rv['packet_in_total'] = self.total_packet_in
        rv['packet_in_delta'] = self.total_packet_in - self.prev_packet_in
        rv['switches'] = self.get_ctrl_switches()
        # rv['service_rate'] = '0'
        
        self.prev_packet_in = self.total_packet_in
        
        # print('controller %d' % (self.total_packet_in))
        # sys.stdout.write('controller %d      \n' % (self.total_packet_in))
        # sys.stdout.flush();
        
        return rv
        
app_manager.require_app('ryu.app.simple_switch_13_lldp')
app_manager.require_app('ryu.app.rest_topology')
app_manager.require_app('ryu.app.ws_topology')