2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.openflowplugin.learningswitch;
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;
18 import java.util.concurrent.atomic.AtomicLong;
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;
44 * Simple Learning Switch implementation which does mac learning for one switch.
48 public class LearningSwitchHandlerSimpleImpl implements LearningSwitchHandler, PacketProcessingListener {
50 private static final Logger LOG = LoggerFactory.getLogger(LearningSwitchHandler.class);
52 private static final byte[] ETH_TYPE_IPV4 = new byte[] { 0x08, 0x00 };
54 private static final int DIRECT_FLOW_PRIORITY = 512;
56 private DataChangeListenerRegistrationHolder registrationPublisher;
57 private FlowCommitWrapper dataStoreAccessor;
58 private PacketProcessingService packetProcessingService;
60 private boolean iAmLearning = false;
62 private NodeId nodeId;
63 private AtomicLong flowIdInc = new AtomicLong();
64 private AtomicLong flowCookieInc = new AtomicLong(0x2a00000000000000L);
66 private InstanceIdentifier<Node> nodePath;
67 private InstanceIdentifier<Table> tablePath;
69 private Map<MacAddress, NodeConnectorRef> mac2portMapping;
70 private Set<String> coveredMacPaths;
73 public synchronized void onSwitchAppeared(InstanceIdentifier<Table> appearedTablePath) {
75 LOG.debug("already learning a node, skipping {}", nodeId.getValue());
79 LOG.debug("expected table acquired, learning ..");
81 // disable listening - simple learning handles only one node (switch)
82 if (registrationPublisher != null) {
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);
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<>();
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);
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);
110 LOG.debug("writing packetForwardToController flow");
111 dataStoreAccessor.writeFlowToConfig(flowPath, allToCtrlFlow.build());
115 public void setRegistrationPublisher(DataChangeListenerRegistrationHolder registrationPublisher) {
116 this.registrationPublisher = registrationPublisher;
120 public void setDataStoreAccessor(FlowCommitWrapper dataStoreAccessor) {
121 this.dataStoreAccessor = dataStoreAccessor;
125 public void setPacketProcessingService(PacketProcessingService packetProcessingService) {
126 this.packetProcessingService = packetProcessingService;
130 public void onPacketReceived(PacketReceived notification) {
132 // ignoring packets - this should not happen
136 LOG.debug("Received packet via match: {}", notification.getMatch());
138 // detect and compare node - we support one switch
139 if (!nodePath.contains(notification.getIngress().getValue())) {
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());
148 MacAddress dstMac = PacketUtils.rawMacToMac(dstMacRaw);
149 MacAddress srcMac = PacketUtils.rawMacToMac(srcMacRaw);
151 NodeConnectorKey ingressKey = InstanceIdentifierUtils.getNodeConnectorKey(notification.getIngress().getValue());
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()));
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());
164 // if dst MAC mapped:
165 NodeConnectorRef destNodeConnector = mac2portMapping.get(dstMac);
166 if (destNodeConnector != null) {
167 synchronized (coveredMacPaths) {
168 if (!destNodeConnector.equals(notification.getIngress())) {
170 addBridgeFlow(srcMac, dstMac, destNodeConnector);
171 addBridgeFlow(dstMac, srcMac, notification.getIngress());
173 LOG.debug("useless rule ignoring - both MACs are behind the same port");
176 LOG.debug("packetIn-directing.. to {}",
177 InstanceIdentifierUtils.getNodeConnectorKey(destNodeConnector.getValue()).getId());
178 sendPacketOut(notification.getPayload(), notification.getIngress(), destNodeConnector);
181 LOG.debug("packetIn-still flooding.. ");
182 flood(notification.getPayload(), notification.getIngress());
186 flood(notification.getPayload(), notification.getIngress());
194 * @param destNodeConnector
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());
203 coveredMacPaths.add(macPath);
204 FlowId flowId = new FlowId(String.valueOf(flowIdInc.getAndIncrement()));
205 FlowKey flowKey = new FlowKey(flowId);
207 * Path to the flow we want to program.
209 InstanceIdentifier<Flow> flowPath = InstanceIdentifierUtils.createFlowPath(tablePath, flowKey);
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()));
216 dataStoreAccessor.writeFlowToConfig(flowPath, srcToDstFlow.build());
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);
226 sendPacketOut(payload, ingress, egressConnectorRef);
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());
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) //
243 packetProcessingService.transmitPacket(input);