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
8 package org.opendaylight.openflowplugin.learningswitch;
10 import java.nio.ByteBuffer;
11 import java.util.Arrays;
12 import java.util.HashMap;
13 import java.util.HashSet;
15 import java.util.Objects;
17 import java.util.concurrent.atomic.AtomicLong;
18 import org.eclipse.jdt.annotation.NonNull;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.opendaylight.infrautils.utils.concurrent.LoggingFutures;
21 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
22 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
23 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
24 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowCookie;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketProcessingListener;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketProcessingService;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceived;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.TransmitPacketInput;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.TransmitPacketInputBuilder;
41 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
42 import org.opendaylight.yangtools.yang.common.Uint16;
43 import org.opendaylight.yangtools.yang.common.Uint64;
44 import org.opendaylight.yangtools.yang.common.Uint8;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
49 * Simple Learning Switch implementation which does mac learning for one switch.
51 public class LearningSwitchHandlerSimpleImpl implements LearningSwitchHandler, PacketProcessingListener {
53 private static final Logger LOG = LoggerFactory.getLogger(LearningSwitchHandlerSimpleImpl.class);
54 private static final byte[] ETH_TYPE_IPV4 = new byte[] { 0x08, 0x00 };
55 private static final Uint16 DIRECT_FLOW_PRIORITY = Uint16.valueOf(512);
57 private final DataTreeChangeListenerRegistrationHolder registrationPublisher;
58 private final FlowCommitWrapper dataStoreAccessor;
59 private final PacketProcessingService packetProcessingService;
61 private volatile boolean isLearning = false;
63 private NodeId nodeId;
64 private final AtomicLong flowIdInc = new AtomicLong();
65 private final AtomicLong flowCookieInc = new AtomicLong(0x2a00000000000000L);
67 private InstanceIdentifier<Node> nodePath;
68 private volatile InstanceIdentifier<Table> tablePath;
70 private Map<MacAddress, NodeConnectorRef> mac2portMapping;
71 private final Set<String> coveredMacPaths = new HashSet<>();
73 public LearningSwitchHandlerSimpleImpl(@NonNull FlowCommitWrapper dataStoreAccessor,
74 @NonNull PacketProcessingService packetProcessingService,
75 @Nullable DataTreeChangeListenerRegistrationHolder registrationPublisher) {
76 this.dataStoreAccessor = Objects.requireNonNull(dataStoreAccessor);
77 this.packetProcessingService = Objects.requireNonNull(packetProcessingService);
78 this.registrationPublisher = registrationPublisher;
82 public synchronized void onSwitchAppeared(InstanceIdentifier<Table> appearedTablePath) {
84 LOG.debug("already learning a node, skipping {}", nodeId.getValue());
88 LOG.debug("expected table acquired, learning ..");
90 // disable listening - simple learning handles only one node (switch)
91 if (registrationPublisher != null) {
92 LOG.debug("closing dataTreeChangeListenerRegistration");
93 registrationPublisher.getDataTreeChangeListenerRegistration().close();
98 tablePath = appearedTablePath;
99 nodePath = tablePath.firstIdentifierOf(Node.class);
100 nodeId = nodePath.firstKeyOf(Node.class).getId();
101 mac2portMapping = new HashMap<>();
103 // start forwarding all packages to controller
104 FlowId flowId = new FlowId(String.valueOf(flowIdInc.getAndIncrement()));
105 FlowKey flowKey = new FlowKey(flowId);
106 InstanceIdentifier<Flow> flowPath = InstanceIdentifierUtils.createFlowPath(tablePath, flowKey);
108 Uint16 priority = Uint16.ZERO;
109 // create flow in table with id = 0, priority = 4 (other params are
110 // defaulted in OFDataStoreUtil)
111 FlowBuilder allToCtrlFlow = FlowUtils.createFwdAllToControllerFlow(
112 InstanceIdentifierUtils.getTableId(tablePath), priority, flowId);
114 LOG.debug("writing packetForwardToController flow");
115 dataStoreAccessor.writeFlowToConfig(flowPath, allToCtrlFlow.build());
119 public void onPacketReceived(PacketReceived notification) {
121 // ignoring packets - this should not happen
125 LOG.debug("Received packet via match: {}", notification.getMatch());
127 // detect and compare node - we support one switch
128 if (!nodePath.contains(notification.getIngress().getValue())) {
132 // read src MAC and dst MAC
133 byte[] dstMacRaw = PacketUtils.extractDstMac(notification.getPayload());
134 byte[] srcMacRaw = PacketUtils.extractSrcMac(notification.getPayload());
135 byte[] etherType = PacketUtils.extractEtherType(notification.getPayload());
137 MacAddress dstMac = PacketUtils.rawMacToMac(dstMacRaw);
138 MacAddress srcMac = PacketUtils.rawMacToMac(srcMacRaw);
140 NodeConnectorKey ingressKey = InstanceIdentifierUtils.getNodeConnectorKey(notification.getIngress().getValue());
142 LOG.debug("Received packet from MAC match: {}, ingress: {}", srcMac, ingressKey.getId());
143 LOG.debug("Received packet to MAC match: {}", dstMac);
144 LOG.debug("Ethertype: {}", Integer.toHexString(0x0000ffff & ByteBuffer.wrap(etherType).getShort()));
146 // learn by IPv4 traffic only
147 if (Arrays.equals(ETH_TYPE_IPV4, etherType)) {
148 NodeConnectorRef previousPort = mac2portMapping.put(srcMac, notification.getIngress());
149 if (previousPort != null && !notification.getIngress().equals(previousPort)) {
150 NodeConnectorKey previousPortKey = InstanceIdentifierUtils.getNodeConnectorKey(previousPort.getValue());
151 LOG.debug("mac2port mapping changed by mac {}: {} -> {}", srcMac, previousPortKey, ingressKey.getId());
153 // if dst MAC mapped:
154 NodeConnectorRef destNodeConnector = mac2portMapping.get(dstMac);
155 if (destNodeConnector != null) {
156 synchronized (coveredMacPaths) {
157 if (!destNodeConnector.equals(notification.getIngress())) {
159 addBridgeFlow(srcMac, dstMac, destNodeConnector);
160 addBridgeFlow(dstMac, srcMac, notification.getIngress());
162 LOG.debug("useless rule ignoring - both MACs are behind the same port");
165 LOG.debug("packetIn-directing.. to {}",
166 InstanceIdentifierUtils.getNodeConnectorKey(destNodeConnector.getValue()).getId());
167 sendPacketOut(notification.getPayload(), notification.getIngress(), destNodeConnector);
170 LOG.debug("packetIn-still flooding.. ");
171 flood(notification.getPayload(), notification.getIngress());
175 flood(notification.getPayload(), notification.getIngress());
180 private void addBridgeFlow(MacAddress srcMac, MacAddress dstMac, NodeConnectorRef destNodeConnector) {
181 synchronized (coveredMacPaths) {
182 String macPath = srcMac.toString() + dstMac.toString();
183 if (!coveredMacPaths.contains(macPath)) {
184 LOG.debug("covering mac path: {} by [{}]", macPath,
185 destNodeConnector.getValue().firstKeyOf(NodeConnector.class).getId());
187 coveredMacPaths.add(macPath);
188 FlowId flowId = new FlowId(String.valueOf(flowIdInc.getAndIncrement()));
189 FlowKey flowKey = new FlowKey(flowId);
191 * Path to the flow we want to program.
193 InstanceIdentifier<Flow> flowPath = InstanceIdentifierUtils.createFlowPath(tablePath, flowKey);
195 Uint8 tableId = InstanceIdentifierUtils.getTableId(tablePath);
196 FlowBuilder srcToDstFlow = FlowUtils.createDirectMacToMacFlow(tableId, DIRECT_FLOW_PRIORITY, srcMac,
197 dstMac, destNodeConnector);
198 srcToDstFlow.setCookie(new FlowCookie(Uint64.valueOf(flowCookieInc.getAndIncrement())));
200 dataStoreAccessor.writeFlowToConfig(flowPath, srcToDstFlow.build());
205 private void flood(byte[] payload, NodeConnectorRef ingress) {
206 NodeConnectorKey nodeConnectorKey = new NodeConnectorKey(nodeConnectorId("0xfffffffb"));
207 InstanceIdentifier<?> nodeConnectorPath = InstanceIdentifierUtils.createNodeConnectorPath(
208 nodePath, nodeConnectorKey);
209 NodeConnectorRef egressConnectorRef = new NodeConnectorRef(nodeConnectorPath);
211 sendPacketOut(payload, ingress, egressConnectorRef);
214 private NodeConnectorId nodeConnectorId(String connectorId) {
215 NodeKey nodeKey = nodePath.firstKeyOf(Node.class);
216 StringBuilder stringId = new StringBuilder(nodeKey.getId().getValue()).append(":").append(connectorId);
217 return new NodeConnectorId(stringId.toString());
220 private void sendPacketOut(byte[] payload, NodeConnectorRef ingress, NodeConnectorRef egress) {
221 InstanceIdentifier<Node> egressNodePath = InstanceIdentifierUtils.getNodePath(egress.getValue());
222 TransmitPacketInput input = new TransmitPacketInputBuilder()
224 .setNode(new NodeRef(egressNodePath))
228 LoggingFutures.addErrorLogging(packetProcessingService.transmitPacket(input), LOG, "transmitPacket");