080f6d1ff4c1e8b8a008693f4c8fbcd0e8fccebd
[openflowplugin.git] / samples / learning-switch / src / main / java / org / opendaylight / openflowplugin / learningswitch / LearningSwitchHandlerSimpleImpl.java
1 /**
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.openflowplugin.learningswitch;
10
11 import java.math.BigInteger;
12 import java.nio.ByteBuffer;
13 import java.util.Arrays;
14 import java.util.HashMap;
15 import java.util.HashSet;
16 import java.util.Map;
17 import java.util.Set;
18 import java.util.concurrent.atomic.AtomicLong;
19
20 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress;
21 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
22 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
23 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
24 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketProcessingListener;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketProcessingService;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceived;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.TransmitPacketInput;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.TransmitPacketInputBuilder;
39 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 /**
44  * Simple Learning Switch implementation which does mac learning for one switch.
45  * 
46  * 
47  */
48 public class LearningSwitchHandlerSimpleImpl implements LearningSwitchHandler, PacketProcessingListener {
49
50     private static final Logger LOG = LoggerFactory.getLogger(LearningSwitchHandler.class);
51
52     private static final byte[] ETH_TYPE_IPV4 = new byte[] { 0x08, 0x00 };
53
54     private static final int DIRECT_FLOW_PRIORITY = 512;
55
56     private DataChangeListenerRegistrationHolder registrationPublisher;
57     private FlowCommitWrapper dataStoreAccessor;
58     private PacketProcessingService packetProcessingService;
59
60     private boolean iAmLearning = false;
61
62     private NodeId nodeId;
63     private AtomicLong flowIdInc = new AtomicLong();
64     private AtomicLong flowCookieInc = new AtomicLong(0x2a00000000000000L);
65     
66     private InstanceIdentifier<Node> nodePath;
67     private InstanceIdentifier<Table> tablePath;
68
69     private Map<MacAddress, NodeConnectorRef> mac2portMapping;
70     private Set<String> coveredMacPaths;
71
72     @Override
73     public synchronized void onSwitchAppeared(InstanceIdentifier<Table> appearedTablePath) {
74         if (iAmLearning) {
75             LOG.debug("already learning a node, skipping {}", nodeId.getValue());
76             return;
77         }
78
79         LOG.debug("expected table acquired, learning ..");
80
81         // disable listening - simple learning handles only one node (switch)
82         if (registrationPublisher != null) {
83             try {
84                 LOG.debug("closing dataChangeListenerRegistration");
85                 registrationPublisher.getDataChangeListenerRegistration().close();
86             } catch (Exception e) {
87                 LOG.error("closing registration upon flowCapable node update listener failed: " + e.getMessage(), e);
88             }
89         }
90
91         iAmLearning = true;
92         
93         tablePath = appearedTablePath;
94         nodePath = tablePath.firstIdentifierOf(Node.class);
95         nodeId = nodePath.firstKeyOf(Node.class, NodeKey.class).getId();
96         mac2portMapping = new HashMap<>();
97         coveredMacPaths = new HashSet<>();
98
99         // start forwarding all packages to controller
100         FlowId flowId = new FlowId(String.valueOf(flowIdInc.getAndIncrement()));
101         FlowKey flowKey = new FlowKey(flowId);
102         InstanceIdentifier<Flow> flowPath = InstanceIdentifierUtils.createFlowPath(tablePath, flowKey);
103
104         int priority = 0;
105         // create flow in table with id = 0, priority = 4 (other params are
106         // defaulted in OFDataStoreUtil)
107         FlowBuilder allToCtrlFlow = FlowUtils.createFwdAllToControllerFlow(
108                 InstanceIdentifierUtils.getTableId(tablePath), priority, flowId);
109
110         LOG.debug("writing packetForwardToController flow");
111         dataStoreAccessor.writeFlowToConfig(flowPath, allToCtrlFlow.build());
112     }
113
114     @Override
115     public void setRegistrationPublisher(DataChangeListenerRegistrationHolder registrationPublisher) {
116         this.registrationPublisher = registrationPublisher;
117     }
118
119     @Override
120     public void setDataStoreAccessor(FlowCommitWrapper dataStoreAccessor) {
121         this.dataStoreAccessor = dataStoreAccessor;
122     }
123
124     @Override
125     public void setPacketProcessingService(PacketProcessingService packetProcessingService) {
126         this.packetProcessingService = packetProcessingService;
127     }
128
129     @Override
130     public void onPacketReceived(PacketReceived notification) {
131         if (!iAmLearning) {
132             // ignoring packets - this should not happen
133             return;
134         }
135
136         LOG.debug("Received packet via match: {}", notification.getMatch());
137
138         // detect and compare node - we support one switch
139         if (!nodePath.contains(notification.getIngress().getValue())) {
140             return;
141         }
142
143         // read src MAC and dst MAC
144         byte[] dstMacRaw = PacketUtils.extractDstMac(notification.getPayload());
145         byte[] srcMacRaw = PacketUtils.extractSrcMac(notification.getPayload());
146         byte[] etherType = PacketUtils.extractEtherType(notification.getPayload());
147
148         MacAddress dstMac = PacketUtils.rawMacToMac(dstMacRaw);
149         MacAddress srcMac = PacketUtils.rawMacToMac(srcMacRaw);
150
151         NodeConnectorKey ingressKey = InstanceIdentifierUtils.getNodeConnectorKey(notification.getIngress().getValue());
152
153         LOG.debug("Received packet from MAC match: {}, ingress: {}", srcMac, ingressKey.getId());
154         LOG.debug("Received packet to   MAC match: {}", dstMac);
155         LOG.debug("Ethertype: {}", Integer.toHexString(0x0000ffff & ByteBuffer.wrap(etherType).getShort()));
156
157         // learn by IPv4 traffic only
158         if (Arrays.equals(ETH_TYPE_IPV4, etherType)) {
159             NodeConnectorRef previousPort = mac2portMapping.put(srcMac, notification.getIngress());
160             if (previousPort != null && !notification.getIngress().equals(previousPort)) {
161                 NodeConnectorKey previousPortKey = InstanceIdentifierUtils.getNodeConnectorKey(previousPort.getValue());
162                 LOG.debug("mac2port mapping changed by mac {}: {} -> {}", srcMac, previousPortKey, ingressKey.getId());
163             }
164             // if dst MAC mapped:
165             NodeConnectorRef destNodeConnector = mac2portMapping.get(dstMac);
166             if (destNodeConnector != null) {
167                 synchronized (coveredMacPaths) {
168                     if (!destNodeConnector.equals(notification.getIngress())) {
169                         // add flow
170                         addBridgeFlow(srcMac, dstMac, destNodeConnector);
171                         addBridgeFlow(dstMac, srcMac, notification.getIngress());
172                     } else {
173                         LOG.debug("useless rule ignoring - both MACs are behind the same port");
174                     }
175                 }
176                 LOG.debug("packetIn-directing.. to {}",
177                         InstanceIdentifierUtils.getNodeConnectorKey(destNodeConnector.getValue()).getId());
178                 sendPacketOut(notification.getPayload(), notification.getIngress(), destNodeConnector);
179             } else {
180                 // flood
181                 LOG.debug("packetIn-still flooding.. ");
182                 flood(notification.getPayload(), notification.getIngress());
183             }
184         } else {
185             // non IPv4 package
186             flood(notification.getPayload(), notification.getIngress());
187         }
188
189     }
190
191     /**
192      * @param srcMac
193      * @param dstMac
194      * @param destNodeConnector
195      */
196     private void addBridgeFlow(MacAddress srcMac, MacAddress dstMac, NodeConnectorRef destNodeConnector) {
197         synchronized (coveredMacPaths) {
198             String macPath = srcMac.toString() + dstMac.toString();
199             if (!coveredMacPaths.contains(macPath)) {
200                 LOG.debug("covering mac path: {} by [{}]", macPath,
201                         destNodeConnector.getValue().firstKeyOf(NodeConnector.class, NodeConnectorKey.class).getId());
202
203                 coveredMacPaths.add(macPath);
204                 FlowId flowId = new FlowId(String.valueOf(flowIdInc.getAndIncrement()));
205                 FlowKey flowKey = new FlowKey(flowId);
206                 /**
207                  * Path to the flow we want to program.
208                  */
209                 InstanceIdentifier<Flow> flowPath = InstanceIdentifierUtils.createFlowPath(tablePath, flowKey);
210
211                 Short tableId = InstanceIdentifierUtils.getTableId(tablePath);
212                 FlowBuilder srcToDstFlow = FlowUtils.createDirectMacToMacFlow(tableId, DIRECT_FLOW_PRIORITY, srcMac,
213                         dstMac, destNodeConnector);
214                 srcToDstFlow.setCookie(BigInteger.valueOf(flowCookieInc.getAndIncrement()));
215
216                 dataStoreAccessor.writeFlowToConfig(flowPath, srcToDstFlow.build());
217             }
218         }
219     }
220
221     private void flood(byte[] payload, NodeConnectorRef ingress) {
222         NodeConnectorKey nodeConnectorKey = new NodeConnectorKey(nodeConnectorId("0xfffffffb"));
223         InstanceIdentifier<?> nodeConnectorPath = InstanceIdentifierUtils.createNodeConnectorPath(nodePath, nodeConnectorKey);
224         NodeConnectorRef egressConnectorRef = new NodeConnectorRef(nodeConnectorPath);
225
226         sendPacketOut(payload, ingress, egressConnectorRef);
227     }
228
229     private NodeConnectorId nodeConnectorId(String connectorId) {
230         NodeKey nodeKey = nodePath.firstKeyOf(Node.class, NodeKey.class);
231         StringBuilder stringId = new StringBuilder(nodeKey.getId().getValue()).append(":").append(connectorId);
232         return new NodeConnectorId(stringId.toString());
233     }
234
235     private void sendPacketOut(byte[] payload, NodeConnectorRef ingress, NodeConnectorRef egress) {
236         InstanceIdentifier<Node> egressNodePath = InstanceIdentifierUtils.getNodePath(egress.getValue());
237         TransmitPacketInput input = new TransmitPacketInputBuilder() //
238                 .setPayload(payload) //
239                 .setNode(new NodeRef(egressNodePath)) //
240                 .setEgress(egress) //
241                 .setIngress(ingress) //
242                 .build();
243         packetProcessingService.transmitPacket(input);
244     }
245 }