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

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

一、实验目的

  1. 能够独立部署RYU控制器;
  2. 能够理解RYU控制器实现软件定义的集线器原理;
  3. 能够理解RYU控制器实现软件定义的交换机原理。

二、实验环境

Ubuntu 20.04 Desktop amd64

三、实验要求

(一)基本要求

  1. 搭建下图所示SDN拓扑,协议使用Open Flow 1.0,并连接Ryu控制器,通过Ryu的图形界面查看网络拓扑。
    • 使用命令在lab6中搭建拓扑图:
      sudo mn --topo=single,3 --mac --controller=remote,ip=127.0.0.1,port=6633 --switch ovsk,protocols=OpenFlow10
      

    • 启动控制器
      ryu-manager ryu/ryu/app/gui_topology/gui_topology.py --observe-links 
      

    • 通过Ryu的图形界面查看网络拓

      

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

    • 在lab6中创建L2Switch.py     
       1 from ryu.base import app_manager
       2 from ryu.controller import ofp_event
       3 from ryu.controller.handler import MAIN_DISPATCHER
       4 from ryu.controller.handler import set_ev_cls
       5 from ryu.ofproto import ofproto_v1_0
       6 
       7 class L2Switch(app_manager.RyuApp):
       8     OFP_VERSIONS = [ofproto_v1_0.OFP_VERSION]
       9 
      10     def __init__(self, *args, **kwargs):
      11         super(L2Switch, self).__init__(*args, **kwargs)
      12 
      13     @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
      14     def packet_in_handler(self, ev):
      15         msg = ev.msg
      16         dp = msg.datapath
      17         ofp = dp.ofproto
      18         ofp_parser = dp.ofproto_parser
      19 
      20         actions = [ofp_parser.OFPActionOutput(ofp.OFPP_FLOOD)]
      21 
      22         data = None
      23         if msg.buffer_id == ofp.OFP_NO_BUFFER:
      24              data = msg.data
      25 
      26         out = ofp_parser.OFPPacketOut(
      27             datapath=dp, buffer_id=msg.buffer_id, in_port=msg.in_port,
      28             actions=actions, data = data)
      29         dp.send_msg(out)
    • 运行ryu:
      ryu-manager L2Switch.py
      

    • 重新搭建拓扑图:
      sudo mn --topo=single,3 --mac --controller=remote,ip=127.0.0.1,port=6633 --switch ovsk,protocols=OpenFlow10
      

    • 对p1和p2进行抓包,在目标主机中验证验证L2Switch 
      使用命令mininet> xterm h2 h3开启主机终端
      在h2主机终端中输入tcpdump -nn -i h2-eth0
      在h3主机终端中输入tcpdump -nn -i h3-eth0

      L2Switch和POX的Hub模块的不同

       相同之处:两个模块使用的是洪泛转发ICMP报文,所以无论h1 ping h2还是h3,都能收到数据包。

       不同之处:L2Switch下发的流表无法在mininet上查看,而Hub可以查看,如图所示

       

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

        

    L2212106691.py

 1 from ryu.base import app_manager
 2 from ryu.ofproto import ofproto_v1_3
 3 from ryu.controller import ofp_event
 4 from ryu.controller.handler import MAIN_DISPATCHER,CONFIG_DISPATCHER
 5 from ryu.controller.handler import set_ev_cls
 6 
 7 
 8 class Hub(app_manager.RyuApp):
 9     OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]
10 
11     def __init__(self,*args,**kwargs):
12         super(Hub,self).__init__(*args,**kwargs)
13 
14     
15     @set_ev_cls(ofp_event.EventOFPSwitchFeatures,CONFIG_DISPATCHER)
16     def switch_features_handler(self,ev):
17         datapath = ev.msg.datapath
18         ofproto = datapath.ofproto
19         ofp_parser = datapath.ofproto_parser
20 
21         match = ofp_parser.OFPMatch()
22         actions = [ofp_parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,ofproto.OFPCML_NO_BUFFER)]
23 
24         self.add_flow(datapath,0,match,actions,"default flow entry")
25 
26     def add_flow(self,datapath,priority,match,actions,remind_content):
27         ofproto = datapath.ofproto
28         ofp_parser = datapath.ofproto_parser
29 
30         inst = [ofp_parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS,
31                                              actions)]
32 
33         mod = ofp_parser.OFPFlowMod(datapath=datapath,priority=priority,
34                                     match=match,instructions=inst);
35         print("install to datapath,"+remind_content)
36         datapath.send_msg(mod);
37 
38 
39     @set_ev_cls(ofp_event.EventOFPPacketIn,MAIN_DISPATCHER)
40     def packet_in_handler(self,ev):
41         msg = ev.msg
42         datapath = msg.datapath
43         ofproto = datapath.ofproto
44         ofp_parser = datapath.ofproto_parser
45 
46         in_port = msg.match['in_port']
47 
48         print("get packet in, install flow entry,and lookback parket to datapath")
49         
50         match = ofp_parser.OFPMatch();
51         actions = [ofp_parser.OFPActionOutput(ofproto.OFPP_FLOOD)]
52 
53         self.add_flow(datapath,1,match,actions,"hub flow entry")
54 
55         out = ofp_parser.OFPPacketOut(datapath=datapath,buffer_id=msg.buffer_id,
56                                             in_port=in_port,actions=actions)    
57 
58         datapath.send_msg(out);

(二)进阶要求

  1. 阅读Ryu关于simple_switch.py和simple_switch_1x.py的实现,以simple_switch_13.py为例,完成其代码的注释工作,并回答下列问题:
    a) 代码当中的mac_to_port的作用是什么?
      保存mac地址到交换机端口的映射
    b) simple_switch和simple_switch_13在dpid的输出上有何不同?
      差别在于:simple_switch直接输出dpid,而simple_switch_13则在dpid前端填充0直至满16位
    c) 相比simple_switch,simple_switch_13增加的switch_feature_handler实现了什么功能?
           switch_features_handler函数是新增缺失流表项到流表中,当封包没有匹配到流表时,就触发packet_in
    d) simple_switch_13是如何实现流规则下发的?
      在接收到packetin事件后,首先获取包学习,交换机信息,以太网信息,协议信息等。若以太网类型是LLDP类型,则不予处理。如果不是,则获取源端口的目的端口和交换机id,先学习源地址对应的交换机的入端口,再查看是否已经学习目的mac地址,如果没有则进行洪泛转发。如果学习过该mac地址,则查看是否有buffer_id,如果有的话,则在添加流表信息时加上buffer_id,向交换机发送流表。
    e) switch_features_handler和_packet_in_handler两个事件在发送流规则的优先级上有何不同?

      switch_features_handler下发流表的优先级比_packet_in_handler的优先级高。

  1 # Copyright (C) 2011 Nippon Telegraph and Telephone Corporation.
  2 #
  3 # Licensed under the Apache License, Version 2.0 (the "License");
  4 # you may not use this file except in compliance with the License.
  5 # You may obtain a copy of the License at
  6 #
  7 #    http://www.apache.org/licenses/LICENSE-2.0
  8 #
  9 # Unless required by applicable law or agreed to in writing, software
 10 # distributed under the License is distributed on an "AS IS" BASIS,
 11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 12 # implied.
 13 # See the License for the specific language governing permissions and
 14 # limitations under the License.
 15 
 16 from ryu.base import app_manager
 17 from ryu.controller import ofp_event
 18 from ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER
 19 from ryu.controller.handler import set_ev_cls
 20 from ryu.ofproto import ofproto_v1_3
 21 from ryu.lib.packet import packet
 22 from ryu.lib.packet import ethernet
 23 from ryu.lib.packet import ether_types
 24 # 引入包
 25 
 26 class SimpleSwitch13(app_manager.RyuApp):
 27    
 28     OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]
 29     # 定义openflow版本
 30     def __init__(self, *args, **kwargs):
 31         super(SimpleSwitch13, self).__init__(*args, **kwargs)
 32         # 定义保存mac地址到端口的一个映射
 33         self.mac_to_port = {}
 34 
 35     # 处理SwitchFeatures事件
 36     @set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)
 37     def switch_features_handler(self, ev):
 38         datapath = ev.msg.datapath
 39         ofproto = datapath.ofproto
 40         parser = datapath.ofproto_parser
 41 
 42         # install table-miss flow entry
 43         # We specify NO BUFFER to max_len of the output action due to
 44         # OVS bug. At this moment, if we specify a lesser number, e.g.,
 45         # 128, OVS will send Packet-In with invalid buffer_id and
 46         # truncated packet data. In that case, we cannot output packets
 47         # correctly.  The bug has been fixed in OVS v2.1.0.
 48         match = parser.OFPMatch()
 49         actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,ofproto.OFPCML_NO_BUFFER)]
 50         self.add_flow(datapath, 0, match, actions)
 51 
 52     # 添加流表的函数
 53     def add_flow(self, datapath, priority, match, actions, buffer_id=None):
 54         ofproto = datapath.ofproto 
 55         parser = datapath.ofproto_parser
 56         # 获取交换机信息
 57         
 58         inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS,actions)]
 59         # 对action进行包装
 60 
 61         # 判断是否有buffer_id,并生成mod对象
 62         if buffer_id:
 63             mod = parser.OFPFlowMod(datapath=datapath, buffer_id=buffer_id,
 64                                     priority=priority, match=match,
 65                                     instructions=inst)
 66         else:
 67             mod = parser.OFPFlowMod(datapath=datapath, priority=priority,
 68                                     match=match, instructions=inst)
 69         
 70         datapath.send_msg(mod)# 发送mod
 71 
 72     # 处理PacketIn事件
 73     @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
 74     def _packet_in_handler(self, ev):
 75         # If you hit this you might want to increase
 76         # the "miss_send_length" of your switch
 77         if ev.msg.msg_len < ev.msg.total_len:
 78             self.logger.debug("packet truncated: only %s of %s bytes",
 79                               ev.msg.msg_len, ev.msg.total_len)
 80         
 81         msg = ev.msg
 82         datapath = msg.datapath
 83         ofproto = datapath.ofproto
 84         parser = datapath.ofproto_parser
 85         in_port = msg.match['in_port']
 86         # 获取包信息,交换机信息,协议等等
 87 
 88         pkt = packet.Packet(msg.data)
 89         eth = pkt.get_protocols(ethernet.ethernet)[0]
 90 
 91         if eth.ethertype == ether_types.ETH_TYPE_LLDP:
 92             # ignore lldp packet# 忽略LLDP类型的数据包
 93             return
 94 
 95         # 获取源端口,目的端口
 96         dst = eth.dst
 97         src = eth.src
 98 
 99         dpid = format(datapath.id, "d").zfill(16)
100         self.mac_to_port.setdefault(dpid, {})
101 
102         self.logger.info("packet in %s %s %s %s", dpid, src, dst, in_port)
103 
104         # 学习包的源地址,和交换机上的入端口绑定
105         # learn a mac address to avoid FLOOD next time.
106         self.mac_to_port[dpid][src] = in_port
107 
108         # 查看是否已经学习过该目的mac地址
109         if dst in self.mac_to_port[dpid]:
110             out_port = self.mac_to_port[dpid][dst]
111         # 如果没有则进行洪泛
112         else:
113             out_port = ofproto.OFPP_FLOOD
114 
115         actions = [parser.OFPActionOutput(out_port)]
116 
117         # 下发流表处理后续包,不再触发PACKETIN事件
118         # install a flow to avoid packet_in next time
119         if out_port != ofproto.OFPP_FLOOD:
120             match = parser.OFPMatch(in_port=in_port, eth_dst=dst, eth_src=src)
121             # verify if we have a valid buffer_id, if yes avoid to send both
122             # flow_mod & packet_out
123             if msg.buffer_id != ofproto.OFP_NO_BUFFER:
124                 self.add_flow(datapath, 1, match, actions, msg.buffer_id)
125                 return
126             else:
127                 self.add_flow(datapath, 1, match, actions)
128         data = None
129         if msg.buffer_id == ofproto.OFP_NO_BUFFER:
130             data = msg.data
131 
132         out = parser.OFPPacketOut(datapath=datapath, buffer_id=msg.buffer_id,
133                                   in_port=in_port, actions=actions, data=data)
134         # 发送流表
135         datapath.send_msg(out)

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

Timeout.py

  1 # Copyright (C) 2011 Nippon Telegraph and Telephone Corporation.
  2 #
  3 # Licensed under the Apache License, Version 2.0 (the "License");
  4 # you may not use this file except in compliance with the License.
  5 # You may obtain a copy of the License at
  6 #
  7 #    http://www.apache.org/licenses/LICENSE-2.0
  8 #
  9 # Unless required by applicable law or agreed to in writing, software
 10 # distributed under the License is distributed on an "AS IS" BASIS,
 11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 12 # implied.
 13 # See the License for the specific language governing permissions and
 14 # limitations under the License.
 15 
 16 from ryu.base import app_manager
 17 from ryu.controller import ofp_event
 18 from ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER
 19 from ryu.controller.handler import set_ev_cls
 20 from ryu.ofproto import ofproto_v1_3
 21 from ryu.lib.packet import packet
 22 from ryu.lib.packet import ethernet
 23 from ryu.lib.packet import ether_types
 24 
 25 
 26 class SimpleSwitch13(app_manager.RyuApp):
 27     OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]
 28 
 29     def __init__(self, *args, **kwargs):
 30         super(SimpleSwitch13, self).__init__(*args, **kwargs)
 31         self.mac_to_port = {}
 32 
 33     @set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)
 34     def switch_features_handler(self, ev):
 35         datapath = ev.msg.datapath
 36         ofproto = datapath.ofproto
 37         parser = datapath.ofproto_parser
 38 
 39         # install table-miss flow entry
 40         #
 41         # We specify NO BUFFER to max_len of the output action due to
 42         # OVS bug. At this moment, if we specify a lesser number, e.g.,
 43         # 128, OVS will send Packet-In with invalid buffer_id and
 44         # truncated packet data. In that case, we cannot output packets
 45         # correctly.  The bug has been fixed in OVS v2.1.0.
 46         match = parser.OFPMatch()
 47         actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,
 48                                           ofproto.OFPCML_NO_BUFFER)]
 49         self.add_flow(datapath, 0, match, actions)
 50 
 51     def add_flow(self, datapath, priority, match, actions, buffer_id=None, hard_timeout=0):
 52         ofproto = datapath.ofproto
 53         parser = datapath.ofproto_parser
 54 
 55         inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS,
 56                                              actions)]
 57         if buffer_id:
 58             mod = parser.OFPFlowMod(datapath=datapath, buffer_id=buffer_id,
 59                                     priority=priority, match=match,
 60                                     instructions=inst, hard_timeout=hard_timeout)
 61         else:
 62             mod = parser.OFPFlowMod(datapath=datapath, priority=priority,
 63                                     match=match, instructions=inst, hard_timeout=hard_timeout)
 64         datapath.send_msg(mod)
 65 
 66     @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
 67     def _packet_in_handler(self, ev):
 68         # If you hit this you might want to increase
 69         # the "miss_send_length" of your switch
 70         if ev.msg.msg_len < ev.msg.total_len:
 71             self.logger.debug("packet truncated: only %s of %s bytes",
 72                               ev.msg.msg_len, ev.msg.total_len)
 73         msg = ev.msg
 74         datapath = msg.datapath
 75         ofproto = datapath.ofproto
 76         parser = datapath.ofproto_parser
 77         in_port = msg.match['in_port']
 78 
 79         pkt = packet.Packet(msg.data)
 80         eth = pkt.get_protocols(ethernet.ethernet)[0]
 81 
 82         if eth.ethertype == ether_types.ETH_TYPE_LLDP:
 83             # ignore lldp packet
 84             return
 85         dst = eth.dst
 86         src = eth.src
 87 
 88         dpid = format(datapath.id, "d").zfill(16)
 89         self.mac_to_port.setdefault(dpid, {})
 90 
 91         self.logger.info("packet in %s %s %s %s", dpid, src, dst, in_port)
 92 
 93         # learn a mac address to avoid FLOOD next time.
 94         self.mac_to_port[dpid][src] = in_port
 95 
 96         if dst in self.mac_to_port[dpid]:
 97             out_port = self.mac_to_port[dpid][dst]
 98         else:
 99             out_port = ofproto.OFPP_FLOOD
100 
101         actions = [parser.OFPActionOutput(out_port)]\
102 
103         actions_timeout=[]
104 
105         # install a flow to avoid packet_in next time
106         if out_port != ofproto.OFPP_FLOOD:
107             match = parser.OFPMatch(in_port=in_port, eth_dst=dst, eth_src=src)
108             # verify if we have a valid buffer_id, if yes avoid to send both
109             # flow_mod & packet_out
110             hard_timeout=10
111             if msg.buffer_id != ofproto.OFP_NO_BUFFER:
112                 self.add_flow(datapath, 2, match,actions_timeout, msg.buffer_id,hard_timeout=10)
113                 self.add_flow(datapath, 1, match, actions, msg.buffer_id)
114                 return
115             else:
116                 self.add_flow(datapath, 2, match, actions_timeout, hard_timeout=10)
117                 self.add_flow(datapath, 1, match, actions)
118         data = None
119         if msg.buffer_id == ofproto.OFP_NO_BUFFER:
120             data = msg.data
121 
122         out = parser.OFPPacketOut(datapath=datapath, buffer_id=msg.buffer_id,
123                                   in_port=in_port, actions=actions, data=data)
124         datapath.send_msg(out)
重新构建:
sudo mn --topo=single,3 --mac --controller=remote,ip=127.0.0.1,port=6633 --switch ovsk,protocols=OpenFlow13

(三)实验小结

   通过本次实验,让我熟悉了RYU控制器实现软件定义的集线器和交换机原理。在L2Switch模块查看流表时报错,通过找资料发现,应该先打开L2Switch模块在启动ryu控制器,构建拓扑图,改正后也成功的ping通,也实现了无法查看流表的效果。还有就是新建一个L2212106691.py,使之和POX的Hub模块的变得一致,创建后无法开启,经过多次排查问题,发现将新建的拓扑图的命令中去掉protocols=OpenFlow10就可以启动,完整的命令为sudo mn --topo=single,3 --mac --controller=remote,ip=127.0.0.1,port=6633 --switch ovsk,protocols=OpenFlow10。在完成进阶的代码注释时,感觉有几分吃力,源码中使用很多RYU中定义的数据结构并不是很能理解,只能通过查阅资料的来完成注释,还有就是做进阶的硬超时要使用OpenFlow=13,使用OpenFlow=10是会报错。

posted @ 2022-10-22 15:27  三维世界是个球  阅读(160)  评论(0编辑  收藏  举报