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;
17 import java.util.Objects;
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;
48 * Simple Learning Switch implementation which does mac learning for one switch.
50 public class LearningSwitchHandlerSimpleImpl implements LearningSwitchHandler, PacketProcessingListener {
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;
56 private final DataTreeChangeListenerRegistrationHolder registrationPublisher;
57 private final FlowCommitWrapper dataStoreAccessor;
58 private final PacketProcessingService packetProcessingService;
60 private volatile boolean isLearning = false;
62 private NodeId nodeId;
63 private final AtomicLong flowIdInc = new AtomicLong();
64 private final AtomicLong flowCookieInc = new AtomicLong(0x2a00000000000000L);
66 private InstanceIdentifier<Node> nodePath;
67 private volatile InstanceIdentifier<Table> tablePath;
69 private Map<MacAddress, NodeConnectorRef> mac2portMapping;
70 private final Set<String> coveredMacPaths = new HashSet<>();
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;
81 public synchronized void onSwitchAppeared(InstanceIdentifier<Table> appearedTablePath) {
83 LOG.debug("already learning a node, skipping {}", nodeId.getValue());
87 LOG.debug("expected table acquired, learning ..");
89 // disable listening - simple learning handles only one node (switch)
90 if (registrationPublisher != null) {
91 LOG.debug("closing dataTreeChangeListenerRegistration");
92 registrationPublisher.getDataTreeChangeListenerRegistration().close();
97 tablePath = appearedTablePath;
98 nodePath = tablePath.firstIdentifierOf(Node.class);
99 nodeId = nodePath.firstKeyOf(Node.class).getId();
100 mac2portMapping = new HashMap<>();
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);
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);
113 LOG.debug("writing packetForwardToController flow");
114 dataStoreAccessor.writeFlowToConfig(flowPath, allToCtrlFlow.build());
118 public void onPacketReceived(PacketReceived notification) {
120 // ignoring packets - this should not happen
124 LOG.debug("Received packet via match: {}", notification.getMatch());
126 // detect and compare node - we support one switch
127 if (!nodePath.contains(notification.getIngress().getValue())) {
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());
136 MacAddress dstMac = PacketUtils.rawMacToMac(dstMacRaw);
137 MacAddress srcMac = PacketUtils.rawMacToMac(srcMacRaw);
139 NodeConnectorKey ingressKey = InstanceIdentifierUtils.getNodeConnectorKey(notification.getIngress().getValue());
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()));
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());
152 // if dst MAC mapped:
153 NodeConnectorRef destNodeConnector = mac2portMapping.get(dstMac);
154 if (destNodeConnector != null) {
155 synchronized (coveredMacPaths) {
156 if (!destNodeConnector.equals(notification.getIngress())) {
158 addBridgeFlow(srcMac, dstMac, destNodeConnector);
159 addBridgeFlow(dstMac, srcMac, notification.getIngress());
161 LOG.debug("useless rule ignoring - both MACs are behind the same port");
164 LOG.debug("packetIn-directing.. to {}",
165 InstanceIdentifierUtils.getNodeConnectorKey(destNodeConnector.getValue()).getId());
166 sendPacketOut(notification.getPayload(), notification.getIngress(), destNodeConnector);
169 LOG.debug("packetIn-still flooding.. ");
170 flood(notification.getPayload(), notification.getIngress());
174 flood(notification.getPayload(), notification.getIngress());
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());
186 coveredMacPaths.add(macPath);
187 FlowId flowId = new FlowId(String.valueOf(flowIdInc.getAndIncrement()));
188 FlowKey flowKey = new FlowKey(flowId);
190 * Path to the flow we want to program.
192 InstanceIdentifier<Flow> flowPath = InstanceIdentifierUtils.createFlowPath(tablePath, flowKey);
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())));
199 dataStoreAccessor.writeFlowToConfig(flowPath, srcToDstFlow.build());
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);
210 sendPacketOut(payload, ingress, egressConnectorRef);
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());
219 private void sendPacketOut(byte[] payload, NodeConnectorRef ingress, NodeConnectorRef egress) {
220 InstanceIdentifier<Node> egressNodePath = InstanceIdentifierUtils.getNodePath(egress.getValue());
221 TransmitPacketInput input = new TransmitPacketInputBuilder()
223 .setNode(new NodeRef(egressNodePath))
227 JdkFutures.addErrorLogging(packetProcessingService.transmitPacket(input), LOG, "transmitPacket");