Ryu作为SDN的Controller,即数据控制平面,我们可以在其下编写多样的应用程序,比如像一个自学习交换机的实现,我们可以基于ryu编写代码,能够表现出与传统网络设施相同的功能 我们编写的代码需要放置在app文件夹下,首先切换目录: cd ryu/ryu/app ryu很好的一点,是基于python编写应用代码,例如如下的自学习交换机的代码实现:
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 from ryu.lib.packet import packet from ryu.lib.packet import ethernet
class Learning_switch(app_manager.RyuApp): # Example Switch OFP_VERSIOnS=[ofproto_v1_3.OFP_VERSION]
self.logger.info("packet in %s %s %s %s",dpid,src,dst,in_port) # learn the relationship between source mac address and ports to avoid Flood next time self.mac_to_port[dpid][src]=in_port # if the dst mac address exists, decide which port to send the packet # otherwise Flood (Don't know which port lead to the dest port) if dst in self.mac_to_port[dpid]: out_port=self.mac_to_port[dpid][dst] else: out_port=ofproto.OFPP_FLOOD # build actions actiOns=[ofp_parser.OFPActionOutput(out_port)] # install a new flow rule if out_port != ofproto.OFPP_FLOOD: match=ofp_parser.OFPMatch(in_port=in_port,eth_dst=dst) self.add_flow(datapath, 1, match, actions) # send a packet-out out=ofp_parser.OFPPacketOut(datapath=datapath, buffer_id=msg.buffer_id, in_port=in_port, actiOns=actions) datapath.send_msg(out)