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.
19
from ryu.base import app_manager
20
from ryu.controller import ofp_event
21
from ryu.controller.handler import MAIN_DISPATCHER
22
from ryu.controller.handler import set_ev_cls
23
from ryu.ofproto import ofproto_v1_2
24
from ryu.lib.packet import packet
25
from ryu.lib.packet import ethernet
28
class SimpleSwitch12(app_manager.RyuApp):
29
OFP_VERSIONS = [ofproto_v1_2.OFP_VERSION]
31
def __init__(self, *args, **kwargs):
32
super(SimpleSwitch12, self).__init__(*args, **kwargs)
35
def add_flow(self, datapath, port, dst, actions):
36
ofproto = datapath.ofproto
38
match = datapath.ofproto_parser.OFPMatch(in_port=port,
40
inst = [datapath.ofproto_parser.OFPInstructionActions(
41
ofproto.OFPIT_APPLY_ACTIONS, actions)]
43
mod = datapath.ofproto_parser.OFPFlowMod(
44
datapath=datapath, cookie=0, cookie_mask=0, table_id=0,
45
command=ofproto.OFPFC_ADD, idle_timeout=0, hard_timeout=0,
46
priority=0, buffer_id=ofproto.OFP_NO_BUFFER,
47
out_port=ofproto.OFPP_ANY,
48
out_group=ofproto.OFPG_ANY,
49
flags=0, match=match, instructions=inst)
50
datapath.send_msg(mod)
52
@set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
53
def _packet_in_handler(self, ev):
55
datapath = msg.datapath
56
ofproto = datapath.ofproto
57
in_port = msg.match['in_port']
59
pkt = packet.Packet(msg.data)
60
eth = pkt.get_protocols(ethernet.ethernet)[0]
66
self.mac_to_port.setdefault(dpid, {})
68
self.logger.info("packet in %s %s %s %s", dpid, src, dst, in_port)
70
# learn a mac address to avoid FLOOD next time.
71
self.mac_to_port[dpid][src] = in_port
73
if dst in self.mac_to_port[dpid]:
74
out_port = self.mac_to_port[dpid][dst]
76
out_port = ofproto.OFPP_FLOOD
78
actions = [datapath.ofproto_parser.OFPActionOutput(out_port)]
80
# install a flow to avoid packet_in next time
81
if out_port != ofproto.OFPP_FLOOD:
82
self.add_flow(datapath, in_port, dst, actions)
84
out = datapath.ofproto_parser.OFPPacketOut(
85
datapath=datapath, buffer_id=msg.buffer_id, in_port=in_port,
87
datapath.send_msg(out)