實(shí)驗(yàn)6:開源控制器實(shí)踐——RYU
一、基本要求
- 建立拓?fù)洌簊udo mn --topo=single,3 --mac --controller=remote,ip=127.0.0.1,port=6633 --switch ovsk,protocols=OpenFlow10
- 連接ryu: ryu-manager gui_topology.py --observe-links
1、通過(guò)Ryu的圖形界面查看網(wǎng)絡(luò)拓?fù)洌?a target="_blank" rel="noopener nofollow">http://192.168.43.209:8080)
2、閱讀Ryu文檔的The First Application一節(jié),運(yùn)行當(dāng)中的L2Switch,h1 ping h2,在目標(biāo)主機(jī)使用 tcpdump 驗(yàn)證L2Switch,分析L2Switch和POX的Hub模塊有何不同。
- 運(yùn)行L2Switch(ryu-manager L2Switch.py)
- 打開終端:xterm h2 h3;在終端輸入:(tcpdump -nn -i h2-eth0)(tcpdump -nn -i h3-eth0)
- L2Switch和POX的Hub模塊不同:Hub和L2Switch模塊都是洪泛轉(zhuǎn)發(fā),但L2Switch模塊下發(fā)的流表無(wú)法查看,而Hub模塊下發(fā)的流表可以查看
3、編程修改L2Switch.py,改為L(zhǎng)2032002225.py,使之和POX的Hub模塊變得一致。
代碼
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)
- 查看流表(dpctl dump-flows)
二、進(jìn)階要求
1.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.
# 引入數(shù)據(jù)包
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] # 定義openflow版本,為1.3
def __init__(self, *args, **kwargs):
super(SimpleSwitch13, self).__init__(*args, **kwargs)
self.mac_to_port = {} #self.mac_to_port是一個(gè)保存(交換機(jī)id, mac地址)到轉(zhuǎn)發(fā)端口的字典,保存mac地址到端口的一個(gè)映射。
#開始處理SwitchFeatures事件
#控制器事件(Event),Event具體見ryu/controller/ofp_event.py,其事件名稱是由接收到的報(bào)文類型來(lái)命名的,名字為Event+報(bào)文類型,例如本例中,控制器收到的是交換機(jī)發(fā)送的FEATURE_REPLY 報(bào)文,所以事件名稱為EventOFPSwitchFeatures。所以本事件其實(shí)就是當(dāng)控制器接收到FEATURE_REPLY報(bào)文觸發(fā)。
@set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)
def switch_features_handler(self, ev):
datapath = ev.msg.datapath #datapath存儲(chǔ)交換機(jī)的信息
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指流表項(xiàng)匹配,這里OFPMatch()指不匹配任何信息
actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,
ofproto.OFPCML_NO_BUFFER)] #actions是動(dòng)作,表示匹配成功不緩存數(shù)據(jù)包并發(fā)送給控制器
self.add_flow(datapath, 0, match, actions) #add_flow是添加流表項(xiàng)的函數(shù),我們可以從add_flow的函數(shù)中看到其調(diào)用了send_msg(mod),因此本函數(shù)的目的即為下發(fā)流表。
# add_flow()增加流表項(xiàng)
# priority:此規(guī)則的優(yōu)先權(quán)
# match:此規(guī)則的 Match 條件
# actions:動(dòng)作
# 參數(shù)有datapath,優(yōu)先級(jí),匹配項(xiàng),動(dòng)作,buffer_id;
# 此流表項(xiàng)匹配成功后應(yīng)立即執(zhí)行所規(guī)定的動(dòng)作。如果此函數(shù)參數(shù)有buffer_id(就是交換機(jī)發(fā)送來(lái)的數(shù)據(jù)包有buffer_id,即交換機(jī)有緩存),那發(fā)送的Flow_Mod報(bào)文就帶上buffer_id,若沒(méi)有buffer_id,buffer_id就是None。最后,發(fā)出Flow_Mod報(bào)文
def add_flow(self, datapath, priority, match, actions, buffer_id=None):
# 獲取交換機(jī)信息
ofproto = datapath.ofproto
parser = datapath.ofproto_parser
# 對(duì)action進(jìn)行包裝
inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS,
actions)]
# 判斷是否存在buffer_id,并生成mod對(duì)象
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)
# 發(fā)送出去
datapath.send_msg(mod)
#處理處理PacketIn事件,說(shuō)明控制器在MAIN_DISPATCHER狀態(tài)并且觸發(fā)Packet_In事件時(shí)調(diào)用_packet_in_handler函數(shù)
@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: #傳輸出錯(cuò),打印debug信息
self.logger.debug("packet truncated: only %s of %s bytes",
ev.msg.msg_len, ev.msg.total_len)
#開始解析數(shù)據(jù)結(jié)構(gòu)
#這里是從接收到的Packet_In報(bào)文中取出各種信息,如果報(bào)文是lldp報(bào)文,忽略它。隨后用此dpid(交換機(jī)id)初始化mac_to_port,并在日志打印此Packet_In的基本信息。
msg = ev.msg # ev.msg 是代表packet_in data structure對(duì)象
datapath = msg.datapath
ofproto = datapath.ofproto
# dp. ofproto 和 dp.ofproto_parser 是代表 Ryu 和交換機(jī)談判的 OpenFlow 協(xié)議的對(duì)象
# dp.ofproto and dp.ofproto_parser are objects that represent the OpenFlow protocol that Ryu and the switch negotiated
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, {})
# 學(xué)習(xí)包的源地址,和交換機(jī)上的入端口綁定
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 #交換機(jī)自學(xué)習(xí),取來(lái)往數(shù)據(jù)包的交換機(jī)id、源mac和入端口綁定來(lái)構(gòu)造表。
# 查看是否已經(jīng)學(xué)習(xí)過(guò)該目的mac地址
if dst in self.mac_to_port[dpid]: #若在表中找到出端口信息,指示出端口(存放mac地址到交換機(jī)端口的映射。)
out_port = self.mac_to_port[dpid][dst]
else:
out_port = ofproto.OFPP_FLOOD # OFPP_FLOOD標(biāo)志表示應(yīng)在所有端口發(fā)送數(shù)據(jù)包,即洪泛
actions = [parser.OFPActionOutput(out_port)]
# 下發(fā)流表避免下次觸發(fā) packet in 事件
# 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,然后只發(fā)送Flow_mod報(bào)文,因?yàn)榻粨Q機(jī)已經(jīng)有緩存數(shù)據(jù)包,就不需要發(fā)送packet_out報(bào)文
self.add_flow(datapath, 1, match, actions, msg.buffer_id)#add_flow函數(shù)內(nèi)部就已發(fā)送了Flow_mod報(bào)文。,后面不用send_msg()
return
else:
self.add_flow(datapath, 1, match, actions)#若沒(méi)有buffer_id,發(fā)送的Flow_Mod報(bào)文就無(wú)需要帶上buffer_id,但是下一步要再發(fā)送一個(gè)Packet_out報(bào)文帶上原數(shù)據(jù)包信息。
data = None
if msg.buffer_id == ofproto.OFP_NO_BUFFER:
data = msg.data
#發(fā)送Packet_out數(shù)據(jù)包 帶上交換機(jī)發(fā)來(lái)的數(shù)據(jù)包的信息
out = parser.OFPPacketOut(datapath=datapath, buffer_id=msg.buffer_id,
in_port=in_port, actions=actions, data=data)
# 發(fā)送流表
datapath.send_msg(out)
a)代碼當(dāng)中的mac_to_port的作用
存放mac地址到交換機(jī)端口的映射。
b)simple_switch和simple_switch_13在dpid的輸出上不同:
simple_switch_13會(huì)把dpid用前置0填充到16位,而simple_switch不會(huì)填充而是直接輸出。
c)相比simple_switch,simple_switch_13增加的switch_feature_handler實(shí)現(xiàn)的功能:
實(shí)現(xiàn)了交換機(jī)以特性應(yīng)答消息來(lái)響應(yīng)特性請(qǐng)求的功能。
d)simple_switch_13實(shí)現(xiàn)流規(guī)則下發(fā)的方法:
在觸發(fā)Packet_In事件后,會(huì)先解析相關(guān)數(shù)據(jù)結(jié)構(gòu),獲取協(xié)議信息、獲取源端口、包學(xué)習(xí),交換機(jī)信息,以太網(wǎng)信息等。
如果以太網(wǎng)類型是LLDP類型,則忽略。
如果以太網(wǎng)類型不是LLDP類型,則獲取目的端口、源端口還有交換機(jī)id。然后進(jìn)行交換機(jī)自學(xué)習(xí),先學(xué)習(xí)源地址對(duì)應(yīng)的交換機(jī)的入端口,再查看是否已經(jīng)學(xué)習(xí)目的mac地址,如果沒(méi)有就洪泛轉(zhuǎn)發(fā)。
如果學(xué)習(xí)過(guò),則查看是否有buffer_id,如果有則在添加流時(shí)加上buffer_id,向交換機(jī)發(fā)送數(shù)據(jù)包和流表。
e)switch_features_handler和_packet_in_handler兩個(gè)事件在發(fā)送流規(guī)則的優(yōu)先級(jí)上的不同:
switch_features_handler優(yōu)先級(jí)比_packet_in_handler要高。
2、編程實(shí)現(xiàn)和ODL實(shí)驗(yàn)的一樣的硬超時(shí)功能。
代碼032002225timeout.py(ryu-manager 032002225timeout.py調(diào)用)
# 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=5
if msg.buffer_id != ofproto.OFP_NO_BUFFER:
self.add_flow(datapath, 2, match,actions_timeout, msg.buffer_id,hard_timeout)
self.add_flow(datapath, 1, match, actions, msg.buffer_id)
return
else:
self.add_flow(datapath, 2, match, actions_timeout, hard_timeout=5)
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)
- h1 ping h3,hard_timeout = 5
三、個(gè)人總結(jié)
基礎(chǔ)部分我感覺(jué)還是挺簡(jiǎn)單的(相比較與實(shí)驗(yàn)四和實(shí)驗(yàn)五來(lái)說(shuō))
但是在實(shí)驗(yàn)過(guò)程中,“編程修改L2Switch.py,改為L(zhǎng)2032002225.py,使之和POX的Hub模塊變得一致”這一步的時(shí)候,總是ping不同。
后來(lái)詢問(wèn)了其他同學(xué)要把構(gòu)建拓?fù)涞膕udo mn --topo=single,3 --mac --controller=remote,ip=127.0.0.1,port=6633 --switch ovsk,protocols=OpenFlow10
中的“,protocols=OpenFlow10”語(yǔ)句刪除。
進(jìn)階部分我感覺(jué)難度挺高的,是在同學(xué)的幫助下才把注釋理解完并了解了各個(gè)文件的不同。
編寫“編程實(shí)現(xiàn)和ODL實(shí)驗(yàn)的一樣的硬超時(shí)功能”后,剛開始無(wú)法實(shí)現(xiàn)硬中斷,后來(lái)修改了各命令的順序解決了這個(gè)問(wèn)題。






浙公網(wǎng)安備 33010602011771號(hào)