實驗6:開源控制器實踐——RYU


一、實驗目的

  • 能夠獨立部署RYU控制器
  • 能夠理解RYU控制器實現軟件定義的集線器原理
  • 能夠理解RYU控制器實現軟件定義的交換機原理

二、實驗環境

  • 下載虛擬機軟件Oracle VisualBox或VMware
  • 在虛擬機中安裝Ubuntu 20.04 Desktop amd64,並完整安裝Mininet

三、實驗要求

3.1 基本要求

3.1.1 完成Ryu控制器的安裝

  • 在Ryu安裝目錄下執行ryu --version結果截圖


3.1.2 搭建下圖所示SDN拓撲,協議使用Open Flow 1.0,並連接Ryu控制器


  • 使用如下命令建立拓撲並連接Ryu控制器
#建立拓撲
sudo mn --topo=single,3 --mac --controller=remote,ip=127.0.0.1,port=6633 --switch ovsk,protocols=OpenFlow10
#連接Ryu控制器
ryu-manager ryu/ryu/app/gui_topology/gui_topology.py --observe-links


3.1.3 通過Ryu的圖形界面查看網絡拓撲

3.1.4 閱讀Ryu文檔的The First Application一節,運行並使用 tcpdump 驗證L2Switch,分析和POX的Hub模塊有何不同

  • 閱讀文檔The First Application,自行編寫L2Switch.py代碼並用命令ryu-manager L2Switch.py運行。
    • L2Switch.py
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)

  • 運行並使用tcpdump來驗證L2Switch(驗證方法同POX)
    • h1 ping h2

    • h1 ping h3

  • 根據上方兩張截圖中的結果,與POX的Hub模塊相比的區別是:
    • HubL2Switch實現的都是洪泛發送ICMP報文,比如當h1 ping h2時,h1發送給h2的ICMP報文,h3也會收到,但L2Switch下發的流表無法查看,而Hub可以查看。

3.2 進階要求

3.2.1 閱讀Ryu關於simple_switch.py和simple_switch_1x.py的實現,以simple_switch_13.py為例,完成其代碼的注釋工作,並回答下列問題:

a) 代碼當中的mac_to_port的作用是什么?
b) simple_switch和simple_switch_13在dpid的輸出上有何不同?
c) 相比simple_switch,simple_switch_13增加的switch_feature_handler實現了什么功能?
d) simple_switch_13是如何實現流規則下發的?
e) switch_features_handler和_packet_in_handler兩個事件在發送流規則的優先級上有何不同?

  • simple_switch_13.py位置在/ryu/ryu/app/中,以下為完整代碼及注釋
# 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): #繼承了ryu.base.app_manager
    OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION] #OFP_VERSIONS指OpenFlow版本,這里調取了在ofproto_v1_3.py里聲明的靜態變量OFP_VERSION,值為4,為OpenFlow1.3版本。

    def __init__(self, *args, **kwargs):
        super(SimpleSwitch13, self).__init__(*args, **kwargs)
        self.mac_to_port = {}  #self.mac_to_port是一個保存(交換機id, mac地址)到轉發端口的字典。


	#這里是利用了一個裝飾器實現了對事件的控制。
  	#控制器事件(Event),Event具體見ryu/controller/ofp_event.py,其事件名稱是由接收到的報文類型來命名的,名字為Event+報文類型,例如本例中,控制器收到的是交換機發送的FEATURE_REPLY	報文,所以事件名稱為EventOFPSwitchFeatures。所以本事件其實就是當控制器接收到FEATURE_REPLY報文觸發。
  	#控制器狀態:ryu控制器和交換機交互有4個階段,詳見ryu/ryu/controller/handler.py
    @set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)
    def switch_features_handler(self, ev):
        datapath = ev.msg.datapath  #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() #match指流表項匹配,這里OFPMatch()指不匹配任何信息
        actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,
                                          ofproto.OFPCML_NO_BUFFER)] #actions是動作,表示匹配成功不緩存數據包並發送給控制器
        self.add_flow(datapath, 0, match, actions) #add_flow是添加流表項的函數,我們可以從add_flow的函數中看到其調用了send_msg(mod),因此本函數的目的即為下發流表。


	 #add_flow()函數作用是增加流表項;
	  #參數有datapath,優先級,匹配項,動作,buffer_id;
          #此流表項匹配成功后應立即執行所規定的動作。如果此函數參數有buffer_id(就是交換機發送來的數據包有buffer_id,即交換機有緩存),那發送的Flow_Mod報文就帶上buffer_id,若沒有buffer_id,buffer_id就是None。最后,發出Flow_Mod報文
    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)
        
	#說明控制器在MAIN_DISPATCHER狀態並且觸發Packet_In事件時調用_packet_in_handler函數
    @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: #傳輸出錯,打印debug信息
            self.logger.debug("packet truncated: only %s of %s bytes",
                              ev.msg.msg_len, ev.msg.total_len)
        #這里是從接收到的Packet_In報文中取出各種信息,如果報文是lldp報文,忽略它。隨后用此dpid(交換機id)初始化mac_to_port,並在日志打印此Packet_In的基本信息。       
        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 #交換機自學習,取來往數據包的交換機id、源mac和入端口綁定來構造表。

        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)]

        # 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
            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)#add_flow函數內部就已發送了Flow_mod報文。,后面不用send_msg()
                return
            else:
                self.add_flow(datapath, 1, match, actions)#若沒有buffer_id,發送的Flow_Mod報文就無需要帶上buffer_id,但是下一步要再發送一個Packet_out報文帶上原數據包信息。
        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_to_port是一個保存(交換機id, mac地址)到轉發端口的字典。
  
b) simple_switch和simple_switch_13在dpid的輸出上有何不同?
回答:simple_switch和simple_switch_13在dpid的輸出上的差別如下:

        #simple_switch.py
        dpid = datapath.id
        self.mac_to_port.setdefault(dpid, {})
        self.logger.info("packet in %s %s %s %s", dpid, src, dst, msg.in_port)
        #simple_switch_13.py
        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)

可以看到simple_switch_13中dpid的輸出格式為:用0在dpid前填充至總長度為16,而simple_switch直接輸出dpid

c) 相比simple_switch,simple_switch_13增加的switch_feature_handler實現了什么功能?
回答:下發流表項。

d) simple_switch_13是如何實現流規則下發的?
回答:有兩種情況:

  • 當控制器處於CONFIG_DISPATCHER狀態(協商版本並發送FEATURE-REQUEST報文)並且接受到FEATURE_REPLY報文時,執行switch_features_handler()函數。該函數的最后一項add_flow是添加流表項的函數,其參數有datapath,優先級,匹配項,動作,buffer_id,當流表項匹配成功后應立即執行所規定的動作,如果此函數參數有buffer_id(就是交換機發送來的數據包有buffer_id,即交換機有緩存),那發送的Flow_Mod報文就帶上buffer_id,若沒有buffer_id,buffer_id就是None。最后,發出Flow_Mod報文,實現流規則的下發。
  • 當控制器處於MAIN_DISPATCHER狀態(已收到FEATURE-REPLY報文並發送SET-CONFIG報文)並且觸發Packet_In事件時調用_packet_in_handler函數,然后從接收到的Packet_In報文中取出各種信息,用此dpid(交換機id)初始化mac_to_port,然后進行交換機自學習,取來往數據包的交換機id、源mac和入端口綁定來構造表。如果交換機發來的數據包沒有buffer_id,則要回復一個Packet_out報文並帶上原數據包的信息,實現流規則的下發。

e) switch_features_handler_packet_in_handler兩個事件在發送流規則的優先級上有何不同?
回答:switch_features_handler下發流表的優先級比_packet_in_handler高,因為switch_features_handler是在交換機處於協商版本並發送FEATURE-REQUEST報文狀態時調用的,而_packet_in_handler是在已收到FEATURE-REPLY報文並發送SET-CONFIG報文時被調用的。

四、個人總結

  • 實驗難度:適中
  • 實驗過程遇到的困難及解決辦法
    • 在使用ryu控制器可視化拓撲時出現了問題,看不到拓撲的情況,暫時還未解決。
    • 在完成進階要求中的代碼注釋時遇到了困難,很多地方看的不是很懂,於是上網查詢了相關的信息完成了注釋。
  • 個人感想:在經歷了實驗五的實踐之后,在完成實驗六的普通要求的過程中顯得更加得心應手,二者連接控制器以及驗證的過程差別不大。這次進階要求的問題有很多,需要自己對於相關代碼的理解要十分全面,在起步時感到不太容易,學會了多上網查詢相關的知識,以及多理解程序自身配有的英文注釋,以后遇到相關類型的代碼時應該會觸類旁通。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM