# 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.

import logging
import struct

from ryu.base import app_manager
from ryu.controller import mac_to_port
from ryu.controller import ofp_event
from ryu.controller.handler import MAIN_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ofproto_v1_0
from ryu.lib.mac import haddr_to_bin
from ryu.lib.packet import packet
from ryu.lib.packet import ethernet
from array import *

class SimpleSwitch(app_manager.RyuApp):
    OFP_VERSIONS = [ofproto_v1_0.OFP_VERSION]

    def __init__(self, *args, **kwargs):
        super(SimpleSwitch, self).__init__(*args, **kwargs)
        self.mac_to_port = {}

    def add_flow(self, datapath, in_port, dst, actions):
        ofproto = datapath.ofproto

        match = datapath.ofproto_parser.OFPMatch(
            in_port=in_port, dl_dst=haddr_to_bin(dst))

        mod = datapath.ofproto_parser.OFPFlowMod(
            datapath=datapath, match=match, cookie=0,
            command=ofproto.OFPFC_ADD, idle_timeout=0, hard_timeout=0,
            priority=ofproto.OFP_DEFAULT_PRIORITY,
            flags=ofproto.OFPFF_SEND_FLOW_REM, actions=actions)
        datapath.send_msg(mod)

    def packetParser(self, msg):
        my_array = array('B', msg.data)
        pkt = packet.Packet(my_array)
        for p in pkt:
            print p.protocol_name
            if p.protocol_name == 'ethernet':
                print 'ethernet src = ', p.src
                print 'ethernet dst = ', p.dst
                print 'ethernet type = ', p.ethertype
            if p.protocol_name == 'arp':
                print 'arp src mac = ', p.src_mac
                print 'arp src ip = ', p.src_ip
                print 'arp dst mac = ', p.dst_mac
                print 'arp dst ip = ', p.dst_ip
                
            if p.protocol_name == 'ipv4':
                print 'ipv4 id = ', p.identification
                print 'ipv4 src ip = ', p.src
                print 'ipv4 dst ip = ', p.dst
                print 'ipv4 flags = ', p.flags
            if p.protocol_name == 'icmp':
                print 'icmp type = ', p.type
                print 'icmp code = ', p.code
                print 'icmp data = ', p.data

    @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
    def _packet_in_handler(self, ev):
        msg = ev.msg
        datapath = msg.datapath
        ofproto = datapath.ofproto

        pkt = packet.Packet(msg.data)
        eth = pkt.get_protocol(ethernet.ethernet)

        dst = eth.dst
        src = eth.src

        dpid = datapath.id
        self.mac_to_port.setdefault(dpid, {})

        self.logger.info("packet in %s %s %s %s", dpid, src, dst, msg.in_port)
        
        self.packetParser(msg)
        # learn a mac address to avoid FLOOD next time.
        self.mac_to_port[dpid][src] = msg.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 = [datapath.ofproto_parser.OFPActionOutput(out_port),
                   datapath.ofproto_parser.OFPActionOutput(ofproto.OFPP_CONTROLLER)]

        # install a flow to avoid packet_in next time
        if out_port != ofproto.OFPP_FLOOD:
            self.add_flow(datapath, msg.in_port, dst, actions)

        out = datapath.ofproto_parser.OFPPacketOut(
            datapath=datapath, buffer_id=msg.buffer_id, in_port=msg.in_port,
            actions=actions)
        datapath.send_msg(out)

    @set_ev_cls(ofp_event.EventOFPPortStatus, MAIN_DISPATCHER)
    def _port_status_handler(self, ev):
        msg = ev.msg
        reason = msg.reason
        port_no = msg.desc.port_no

        ofproto = msg.datapath.ofproto
        if reason == ofproto.OFPPR_ADD:
            self.logger.info("port added %s", port_no)
        elif reason == ofproto.OFPPR_DELETE:
            self.logger.info("port deleted %s", port_no)
        elif reason == ofproto.OFPPR_MODIFY:
            self.logger.info("port modified %s", port_no)
        else:
            self.logger.info("Illeagal port state %s %s", port_no, reason)

@@ -1,617 +1,4 @@
-# Copyright (C) 2011 Nippon Telegraph and Telephone Corporation.%0A#%0A# Licensed under the Apache License, Version 2.0 (the %22License%22);%0A# you may not use this file except in compliance with the License.%0A# You may obtain a copy of the License at%0A#%0A#    http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS,%0A# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or%0A# implied.%0A# See the License for the specific language governing permissions and%0A# limitations under the License.%0A%0A
 impo
@@ -406,22 +406,28 @@
 s Simple
-Switch
+PacketParser
 (app_man
@@ -552,14 +552,20 @@
 mple
-Switch
+PacketParser
 , se
@@ -623,16 +623,45 @@
 ort = %7B%7D
+%0A        self.known_dpid = %5B%5D
 %0A%0A    de
@@ -1175,16 +1175,402 @@
 g(mod)%0A%0A
+    def delete_flow_entry(self,datapath):%0A        match = datapath.ofproto_parser.OFPMatch(%0A              dp.ofproto.OFPFW_ALL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)%0A%0A        mod = datapath.ofproto_parser.OFPFlowMod(%0A            datapath=dp, match=match, cookie=0,%0A            command=dp.ofproto.OFPFC_DELETE)%0A%0A        dp.send_msg(mod)%0A        self.known_dpid.extend(%5Bdatapath.id%5D)%0A    %0A%0A
     def 
@@ -2910,16 +2910,16 @@
 th.src%0A%0A
-
         
@@ -2937,16 +2937,123 @@
 path.id%0A
+        %0A        if not dpid in self.known_dpid:%0A            self.delete_flow_entry(datapath)%0A            %0A
         

delete all flows <Tanvi>