实验6:开源控制器实践——RYU

(一)基本要求

1.搭建下图所示SDN拓扑,协议使用Open Flow 1.0,并连接Ryu控制器,通过Ryu的图形界面查看网络拓扑。

2.阅读Ryu文档的The First Application一节,运行当中的L2Switch,h1 ping h2或h3,在目标主机使用 tcpdump 验证L2Switch,分析L2Switch和POX的Hub模块有何不同。
a) L2Switch代码

点击查看代码
from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller.handler import MAIN_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ofproto_v1_0

class L2Switch(app_manager.RyuApp):
    OFP_VERSIONS = [ofproto_v1_0.OFP_VERSION]

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

    @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
    def packet_in_handler(self, ev):
        msg = ev.msg
        dp = msg.datapath
        ofp = dp.ofproto
        ofp_parser = dp.ofproto_parser

        actions = [ofp_parser.OFPActionOutput(ofp.OFPP_FLOOD)]

        data = None
        if msg.buffer_id == ofp.OFP_NO_BUFFER:
             data = msg.data

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

b)tcpdump验证L2Switch; - h1 ping h2

  • h1 ping h3

c)L2Switch和POX的Hub模块有何不同;
RYU的L2Switch模块和POX的Hub模块都是洪泛转发,但pox的Hub模块是下发流表到交换机,然后交换机直接根据流表进行洪泛转发,ryu的L2Switch模块运行时不下发对应的转发流表,而是将包发送给控制器,由控制器利用packet-out指定为洪泛转发。

3.编程修改L2Switch.py,另存为L2xxxxxxxxx.py,使之和POX的Hub模块的变得一致?(xxxxxxxxx为学号)
a)L2102299245代码

点击查看代码
from ryu.base import app_manager
from ryu.ofproto import ofproto_v1_3
from ryu.controller import ofp_event
from ryu.controller.handler import MAIN_DISPATCHER, CONFIG_DISPATCHER
from ryu.controller.handler import set_ev_cls
 
 
class hub(app_manager.RyuApp):
    OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]
 
    def __init__(self, *args, **kwargs):
        super(hub, self).__init__(*args, **kwargs)
 
    @set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)
    def switch_feathers_handler(self, ev):
        datapath = ev.msg.datapath
        ofproto = datapath.ofproto
        ofp_parser = datapath.ofproto_parser
 
        # install flow table-miss flow entry
        match = ofp_parser.OFPMatch()
        actions = [ofp_parser.OFPActionOutput(ofproto.OFPP_CONTROLLER, ofproto.OFPCML_NO_BUFFER)]
        # 1\OUTPUT PORT, 2\BUFF IN SWITCH?
        self.add_flow(datapath, 0, match, actions)
 
    def add_flow(self, datapath, priority, match, actions):
        # 1\ datapath for the switch, 2\priority for flow entry, 3\match field, 4\action for packet
        ofproto = datapath.ofproto
        ofp_parser = datapath.ofproto_parser
        # install flow
        inst = [ofp_parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS, actions)]
        mod = ofp_parser.OFPFlowMod(datapath=datapath, priority=priority, match=match, instructions=inst)
        datapath.send_msg(mod)
 
    @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
    def packet_in_handler(self, ev):
        msg = ev.msg
        datapath = msg.datapath
        ofproto = datapath.ofproto
        ofp_parser = datapath.ofproto_parser
        in_port = msg.match['in_port']  # get in port of the packet
 
        # add a flow entry for the packet
        match = ofp_parser.OFPMatch()
        actions = [ofp_parser.OFPActionOutput(ofproto.OFPP_FLOOD)]
        self.add_flow(datapath, 1, match, actions)
 
        # to output the current packet. for install rules only output later packets
        out = ofp_parser.OFPPacketOut(datapath=datapath, buffer_id=msg.buffer_id, in_port=in_port, actions=actions)
        # buffer id: locate the buffered packet
        datapath.send_msg(out)

b)结果验证

(二)进阶要求

1.阅读Ryu关于simple_switch.py和simple_switch_1x.py的实现,以simple_switch_13.py为例,完成其代码的注释工作,并回答下列问题:

  • 代码注释
点击查看代码
# Copyright (C) 2011 Nippon Telegraph and Telephone Corporation.
#
# 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 #app的基类
from ryu.controller import ofp_event #OpenFlow的事件
from ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ofproto_v1_3 #应用的是OpenFlow1.3协议
from ryu.lib.packet import packet
from ryu.lib.packet import ethernet #引入了基本的网络协议
from ryu.lib.packet import ether_types


class SimpleSwitch13(app_manager.RyuApp):
    OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]  # 定义openflow版本

    def __init__(self, *args, **kwargs):
        super(SimpleSwitch13, self).__init__(*args, **kwargs)
        self.mac_to_port = {} #一个保存(交换机id, mac地址)到转发端口的字典

    @set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER) #@set_ev_cls是一个装饰器,当参数表示的事件触发后会执行下面的函数,其事件名称是由接收到的报文类型来命名的,名字为Event+报文类型
    #起到了事件响应的功能
    #当接收到feature-reply报文后执行下面的函数下发table-miss表项
    
    def switch_features_handler(self, ev):
        datapath = ev.msg.datapath #获取数据通路即交换机
        ofproto = datapath.ofproto #获取数据通路的协议
        parser = datapath.ofproto_parser #对协议进行解析

        # install table-miss flow entry
        #
        # We specify NO BUFFER to max_len of the output action due to
        # OVS bug. At this moment, if we specify a lesser number, e.g.,
        # 128, OVS will send Packet-In with invalid buffer_id and
        # truncated packet data. In that case, we cannot output packets
        # correctly.  The bug has been fixed in OVS v2.1.0.
        match = parser.OFPMatch() #全匹配
        actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,
                                          ofproto.OFPCML_NO_BUFFER)]
        #设置table-miss表项的动作:将数据包发至控制器
        self.add_flow(datapath, 0, match, actions)
	#将0优先级、全匹配、动作为“将数据包发至控制器”的table-miss表项下发给交换机。
        #这样以后交换机不知道咋处理的数据包会自动发至控制器。

    def add_flow(self, datapath, priority, match, actions, buffer_id=None):
	#下发流表项
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser

        inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS,
                                             actions)]
        if buffer_id:
            mod = parser.OFPFlowMod(datapath=datapath, buffer_id=buffer_id,
                                    priority=priority, match=match,
                                    instructions=inst)
        else:
            mod = parser.OFPFlowMod(datapath=datapath, priority=priority,
                                    match=match, instructions=inst)
        datapath.send_msg(mod)
	#如果此函数参数有buffer_id(就是交换机发送来的数据包有buffer_id,即交换机有缓存),那发送的Flow_Mod报文就带上buffer_id,若没有buffer_id,buffer_id就是None
    @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER) 
    #在MAIN_DISPATCHER阶段碰到EventOFPPacketIn事件的时候调用_packet_in_handler函数。
    #即控制器收到数据包的时候执行下面的函数。
    #控制器什么时候会收到数据包呢:就是交换机现有的流表项无法与数据包匹配,利用table-miss表项交给控制器处理。
    
    def _packet_in_handler(self, ev):
        # If you hit this you might want to increase
        # the "miss_send_length" of your switch
        if ev.msg.msg_len < ev.msg.total_len:
            self.logger.debug("packet truncated: only %s of %s bytes",
                              ev.msg.msg_len, ev.msg.total_len) #传输出错,打印debug信息
        
        msg = ev.msg
        datapath = msg.datapath
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser
        in_port = msg.match['in_port']
	#此时能进入这里的都是不知道该被咋处理的数据包。
        #记录下数据包从哪个端口进来
        
        #提取数据包的信息
        pkt = packet.Packet(msg.data)
        eth = pkt.get_protocols(ethernet.ethernet)[0]

        if eth.ethertype == ether_types.ETH_TYPE_LLDP:
            # ignore lldp packet
            return
        dst = eth.dst #获取数据包的目的MAC地址
        src = eth.src #获取数据包的源MAC地址

        dpid = format(datapath.id, "d").zfill(16)
        self.mac_to_port.setdefault(dpid, {})

        self.logger.info("packet in %s %s %s %s", dpid, src, dst, in_port)
	#从接收到的Packet_In报文中取出各种信息,如果报文时lldp报文,忽略它。随后用此dpid(交换机id)初始化mac_to_port,并在日志打印此Packet_In的基本信息。
	
	
	
        # learn a mac address to avoid FLOOD next time.交换机自学习,类似传统二层交换机的MAC地址表自学习,取来往数据包的交换机id、源mac和入端口绑定来构造表。
        #设置该交换机的MAC-端口对。
        #即将数据包的源MAC地址与进入的端口相对应,完成了学习。
        self.mac_to_port[dpid][src] = in_port

        #如果知道目的MAC地址与哪个出的端口相对应,那么就直接转发。
        if dst in self.mac_to_port[dpid]:
            out_port = self.mac_to_port[dpid][dst]
        #否则需要泛洪寻找出的端口。
        else:
            out_port = ofproto.OFPP_FLOOD

	#给流表项赋予动作:遇到该目的MAC地址的时候从这个端口转发。
        actions = [parser.OFPActionOutput(out_port)]

        # install a flow to avoid packet_in next time 创建流表项来避免再次收到Packet_in报文
        if out_port != ofproto.OFPP_FLOOD:
            #创建匹配域:以后再遇到这种情况就知道从哪个端口转发了
            match = parser.OFPMatch(in_port=in_port, eth_dst=dst, eth_src=src)
            # 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:#有buffer_id,带上buffer_id,然后只发送Flow_mod报文,因为交换机已经有缓存数据包,就不需要发送packet_out报文
                self.add_flow(datapath, 1, match, actions, msg.buffer_id)
                return
            #若没有buffer_id,发送的Flow_Mod报文就无需要带上buffer_id,但是下一步要再发送一个Packet_out报文带上原数据包信息。
            else:
                self.add_flow(datapath, 1, match, actions)
        data = None
        if msg.buffer_id == ofproto.OFP_NO_BUFFER:
            data = msg.data

	#发送Packet_out数据包 带上交换机发来的数据包的信息
        out = parser.OFPPacketOut(datapath=datapath, buffer_id=msg.buffer_id,
                                  in_port=in_port, actions=actions, data=data)
        datapath.send_msg(out)
  • 回答问题

    a) 代码当中的mac_to_port的作用是什么?

    • 保存mac地址到交换机端口的映射

    b) simple_switch和simple_switch_13在dpid的输出上有何不同?

    • 在simple_switch_13.py中为dpid = format(datapath.id, "d").zfill(16)
    • 在simple_switch.py中为dpid = datapath.id
    • 在simple_switch_13.py中使用了zfill() 方法返回指定长度为16的字符串,原字符串右对齐,前面填充0;而simple_switch.py直接输出dpid

    c) 相比simple_switch,simple_switch_13增加的switch_feature_handler实现了什么功能?

    • 实现了事件响应的功能,交换机不知道咋处理的数据包会自动发至控制器。

    d) simple_switch_13是如何实现流规则下发的?

    • 碰到EventOFPPacketIn事件的时候调用_packet_in_handler函数,提取数据包的信息,从接收到的Packet_In报文中取出各种信息,如果报文时lldp报文,忽略它。随后用此dpid(交换机id)初始化mac_to_port,并在日志打印此Packet_In的基本信息。将数据包的源MAC地址与进入的端口相对应,完成交换机自学习。如果知道目的MAC地址与哪个出的端口相对应,那么就直接转发,如果没有就洪泛转发查看是否有buffer_id,如果有则在添加流时加上buffer_id,向交换机发送数据包和流表。

    e) switch_features_handler和_packet_in_handler两个事件在发送流规则的优先级上有何不同?

    • switch_features_handler优先级高于_packet_in_handler
    • switch_features_handler在接收到feature-reply后执行
    • _packet_in_handler在接收到PacketIn后执行

2.编程实现和ODL实验的一样的硬超时功能。
a)硬超时代码

点击查看代码
# Copyright (C) 2011 Nippon Telegraph and Telephone Corporation.
#
# 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.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 packet
from ryu.lib.packet import ethernet
from ryu.lib.packet import ether_types


class SimpleSwitch13(app_manager.RyuApp):
    OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]

    def __init__(self, *args, **kwargs):
        super(SimpleSwitch13, self).__init__(*args, **kwargs)
        self.mac_to_port = {}

    @set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)
    def switch_features_handler(self, ev):
        datapath = ev.msg.datapath
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser

        # install table-miss flow entry
        #
        # We specify NO BUFFER to max_len of the output action due to
        # OVS bug. At this moment, if we specify a lesser number, e.g.,
        # 128, OVS will send Packet-In with invalid buffer_id and
        # truncated packet data. In that case, we cannot output packets
        # correctly.  The bug has been fixed in OVS v2.1.0.
        match = parser.OFPMatch()
        actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,
                                          ofproto.OFPCML_NO_BUFFER)]
        self.add_flow(datapath, 0, match, actions)

    def add_flow(self, datapath, priority, match, actions, buffer_id=None, hard_timeout=0):
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser

        inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS,
                                             actions)]
        if buffer_id:
            mod = parser.OFPFlowMod(datapath=datapath, buffer_id=buffer_id,
                                    priority=priority, match=match,
                                    instructions=inst, hard_timeout=hard_timeout)
        else:
            mod = parser.OFPFlowMod(datapath=datapath, priority=priority,
                                    match=match, instructions=inst, hard_timeout=hard_timeout)
        datapath.send_msg(mod)

    @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
    def _packet_in_handler(self, ev):
        # If you hit this you might want to increase
        # the "miss_send_length" of your switch
        if ev.msg.msg_len < ev.msg.total_len:
            self.logger.debug("packet truncated: only %s of %s bytes",
                              ev.msg.msg_len, ev.msg.total_len)
        msg = ev.msg
        datapath = msg.datapath
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser
        in_port = msg.match['in_port']

        pkt = packet.Packet(msg.data)
        eth = pkt.get_protocols(ethernet.ethernet)[0]

        if eth.ethertype == ether_types.ETH_TYPE_LLDP:
            # ignore lldp packet
            return
        dst = eth.dst
        src = eth.src

        dpid = format(datapath.id, "d").zfill(16)
        self.mac_to_port.setdefault(dpid, {})

        self.logger.info("packet in %s %s %s %s", dpid, src, dst, in_port)

        # learn a mac address to avoid FLOOD next time.
        self.mac_to_port[dpid][src] = in_port

        if dst in self.mac_to_port[dpid]:
            out_port = self.mac_to_port[dpid][dst]
        else:
            out_port = ofproto.OFPP_FLOOD

        actions = [parser.OFPActionOutput(out_port)]\

        actions_timeout=[]

        # 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, eth_src=src)
            # verify if we have a valid buffer_id, if yes avoid to send both
            # flow_mod & packet_out
            hard_timeout=10
            if msg.buffer_id != ofproto.OFP_NO_BUFFER:
                self.add_flow(datapath, 65535, match,actions_timeout, msg.buffer_id,hard_timeout=10)
                self.add_flow(datapath, 1, match, actions, msg.buffer_id)
                return
            else:
                self.add_flow(datapath, 65535, match, actions_timeout, hard_timeout=10)
                self.add_flow(datapath, 1, match, actions)
        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)


b)结果验证

(三)参考资料

https://blog.csdn.net/weixin_44480014/article/details/123258955
https://www.cnblogs.com/kl107/p/13138568.html

(四)个人总结

1.这次的实验基础部分第一部分一如既往按照pdf上的实验指引即可完成,L2Switch的代码老师亦有提供,实验结果验证较为简单,第二部分通过查找资料和查看源码自己动手试验得以运行成功;
2.进阶部分较难,代码注释方面有幸查找到上述参考资料,内容介绍的很详细,得以理解源码中每一步的具体作用,硬超时相比起来简单许多,在理解源码后,添加新的优先级流规则即可实现。

posted @ 2022-10-19 14:22  102299245梁耀和  阅读(59)  评论(0)    收藏  举报