1 # Copyright (C) 2011 Nippon Telegraph and Telephone Corporation.
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
16 from ryu.base import app_manager
17 from ryu.controller import ofp_event
18 from ryu.controller.handler import MAIN_DISPATCHER
19 from ryu.controller.handler import set_ev_cls
20 from ryu.ofproto import ofproto_v1_2
21 from ryu.lib.packet import packet
22 from ryu.lib.packet import ethernet
23 from ryu.lib.packet import ether_types
26 class SimpleSwitch12(app_manager.RyuApp):
27 OFP_VERSIONS = [ofproto_v1_2.OFP_VERSION]
29 def __init__(self, *args, **kwargs):
30 super(SimpleSwitch12, self).__init__(*args, **kwargs)
33 def add_flow(self, datapath, port, dst, src, actions):
34 ofproto = datapath.ofproto
36 match = datapath.ofproto_parser.OFPMatch(in_port=port,
39 inst = [datapath.ofproto_parser.OFPInstructionActions(
40 ofproto.OFPIT_APPLY_ACTIONS, actions)]
42 mod = datapath.ofproto_parser.OFPFlowMod(
43 datapath=datapath, cookie=0, cookie_mask=0, table_id=0,
44 command=ofproto.OFPFC_ADD, idle_timeout=0, hard_timeout=0,
45 priority=0, buffer_id=ofproto.OFP_NO_BUFFER,
46 out_port=ofproto.OFPP_ANY,
47 out_group=ofproto.OFPG_ANY,
48 flags=0, match=match, instructions=inst)
49 datapath.send_msg(mod)
51 @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
52 def _packet_in_handler(self, ev):
54 datapath = msg.datapath
55 ofproto = datapath.ofproto
56 in_port = msg.match['in_port']
58 pkt = packet.Packet(msg.data)
59 eth = pkt.get_protocols(ethernet.ethernet)[0]
61 if eth.ethertype == ether_types.ETH_TYPE_LLDP:
68 self.mac_to_port.setdefault(dpid, {})
70 self.logger.info("packet in %s %s %s %s", dpid, src, dst, in_port)
72 # learn a mac address to avoid FLOOD next time.
73 self.mac_to_port[dpid][src] = in_port
75 if dst in self.mac_to_port[dpid]:
76 out_port = self.mac_to_port[dpid][dst]
78 out_port = ofproto.OFPP_FLOOD
80 actions = [datapath.ofproto_parser.OFPActionOutput(out_port)]
82 # install a flow to avoid packet_in next time
83 if out_port != ofproto.OFPP_FLOOD:
84 self.add_flow(datapath, in_port, dst, src, actions)
87 if msg.buffer_id == ofproto.OFP_NO_BUFFER:
90 out = datapath.ofproto_parser.OFPPacketOut(
91 datapath=datapath, buffer_id=msg.buffer_id, in_port=in_port,
92 actions=actions, data=data)
93 datapath.send_msg(out)