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