ccis_lab:sdn:ryu:first_application
The First Application of Ryu
0x00 前言
Ryu script 是以 Python 為語言
這篇介紹一個最基本的 Ryu App,這個 Application 讓 OpenFlow switches 像 dumb layer 2 switch 一樣運作
0x01 Start Writing
from ryu.base import app_manager class L2Switch(app_manager.RyuApp): def __init__(self, *args, **kwargs): super(L2Switch, self).__init__(*args, **kwargs)
我們可將上段程式存檔,任意命名放在任意目錄,這邊檔名為 l2.py
存放在家目錄
這個 App 目前還沒什麼用,但他已經算是一個完整的 Ryu App 了
可以透過下面方式執行 App
% ryu-manager ~/l2.py
0x02 Add a function
接著我們增加一個 function 讓 App 可以將收到的 packet 送到所有 ports
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 class L2Switch(app_manager.RyuApp): 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)] out = ofp_parser.OFPPacketOut( datapath=dp, buffer_id=msg.buffer_id, in_port=msg.in_port, actions=actions) dp.send_msg(out)
新增 packet_in_handler
這個 function 到 L2Switch class,這個 function 會在 Ryu 收到 OpenFlow packet_in message 被呼叫,而關鍵在於 set_ev_cls
decorator,decorator 會告訴 Ryu App 何時這個 decorator function 會被呼叫
decorator
- 第一個參數表示 function 監聽的 event,當事件發生,函式就會被呼叫。在這邊是每當 Ryu 收到 packet_in message 就會觸發
- 第二個參數表示 state of the switch。例如我們可能會想在 Ryu 跟 Switch 的協商完成之前忽略 packet_in ,這邊使用
MAIN_DISPATCHER
即可達到此效果,表示這個函式只有在協商完成後才會被呼叫
packet_in_handler function
ev.msg
是一個表示 packet_in data structure 的物件msg.dp
是一個表示 datapath (switch) 的物件dp.ofproto
和dp.ofproto_parser
表示 Ryu 和 Switch 協商的 protocol
- OFPActionOutput class 會使用在處理 packet_out message 用來指定 packet out 到哪一個 switch port
- OFPP_FLOOD constant 用來表示要將 packet out 到 all ports
- OFPPacketOut class 用來建立一個 packet_out message
- send_msg 是 Datapath class 的一個 function,透過這個函式,Ryu 會建立並發送訊息到 Switch
ccis_lab/sdn/ryu/first_application.txt · 上一次變更: 由 127.0.0.1