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;
19 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
20 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
21 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
22 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
23 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
24 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowCookie;
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.
46 public class LearningSwitchHandlerSimpleImpl implements LearningSwitchHandler, PacketProcessingListener {
48 private static final Logger LOG = LoggerFactory.getLogger(LearningSwitchHandlerSimpleImpl.class);
49 private static final byte[] ETH_TYPE_IPV4 = new byte[] { 0x08, 0x00 };
50 private static final int DIRECT_FLOW_PRIORITY = 512;
52 private DataTreeChangeListenerRegistrationHolder registrationPublisher;
53 private FlowCommitWrapper dataStoreAccessor;
54 private PacketProcessingService packetProcessingService;
56 private boolean iAmLearning = false;
58 private NodeId nodeId;
59 private AtomicLong flowIdInc = new AtomicLong();
60 private AtomicLong flowCookieInc = new AtomicLong(0x2a00000000000000L);
62 private InstanceIdentifier<Node> nodePath;
63 private InstanceIdentifier<Table> tablePath;
65 private Map<MacAddress, NodeConnectorRef> mac2portMapping;
66 private Set<String> coveredMacPaths;
69 public synchronized void onSwitchAppeared(InstanceIdentifier<Table> appearedTablePath) {
71 LOG.debug("already learning a node, skipping {}", nodeId.getValue());
75 LOG.debug("expected table acquired, learning ..");
77 // disable listening - simple learning handles only one node (switch)
78 if (registrationPublisher != null) {
80 LOG.debug("closing dataTreeChangeListenerRegistration");
81 registrationPublisher.getDataTreeChangeListenerRegistration().close();
82 } catch (Exception e) {
83 LOG.warn("closing registration upon flowCapable node update listener failed: {}", e.getMessage());
84 LOG.debug("closing registration upon flowCapable node update listener failed.. ", e);
90 tablePath = appearedTablePath;
91 nodePath = tablePath.firstIdentifierOf(Node.class);
92 nodeId = nodePath.firstKeyOf(Node.class, NodeKey.class).getId();
93 mac2portMapping = new HashMap<>();
94 coveredMacPaths = new HashSet<>();
96 // start forwarding all packages to controller
97 FlowId flowId = new FlowId(String.valueOf(flowIdInc.getAndIncrement()));
98 FlowKey flowKey = new FlowKey(flowId);
99 InstanceIdentifier<Flow> flowPath = InstanceIdentifierUtils.createFlowPath(tablePath, flowKey);
102 // create flow in table with id = 0, priority = 4 (other params are
103 // defaulted in OFDataStoreUtil)
104 FlowBuilder allToCtrlFlow = FlowUtils.createFwdAllToControllerFlow(
105 InstanceIdentifierUtils.getTableId(tablePath), priority, flowId);
107 LOG.debug("writing packetForwardToController flow");
108 dataStoreAccessor.writeFlowToConfig(flowPath, allToCtrlFlow.build());
112 public void setRegistrationPublisher(DataTreeChangeListenerRegistrationHolder registrationPublisher) {
113 this.registrationPublisher = registrationPublisher;
117 public void setDataStoreAccessor(FlowCommitWrapper dataStoreAccessor) {
118 this.dataStoreAccessor = dataStoreAccessor;
122 public void setPacketProcessingService(PacketProcessingService packetProcessingService) {
123 this.packetProcessingService = packetProcessingService;
127 public void onPacketReceived(PacketReceived notification) {
129 // ignoring packets - this should not happen
133 LOG.debug("Received packet via match: {}", notification.getMatch());
135 // detect and compare node - we support one switch
136 if (!nodePath.contains(notification.getIngress().getValue())) {
140 // read src MAC and dst MAC
141 byte[] dstMacRaw = PacketUtils.extractDstMac(notification.getPayload());
142 byte[] srcMacRaw = PacketUtils.extractSrcMac(notification.getPayload());
143 byte[] etherType = PacketUtils.extractEtherType(notification.getPayload());
145 MacAddress dstMac = PacketUtils.rawMacToMac(dstMacRaw);
146 MacAddress srcMac = PacketUtils.rawMacToMac(srcMacRaw);
148 NodeConnectorKey ingressKey = InstanceIdentifierUtils.getNodeConnectorKey(notification.getIngress().getValue());
150 LOG.debug("Received packet from MAC match: {}, ingress: {}", srcMac, ingressKey.getId());
151 LOG.debug("Received packet to MAC match: {}", dstMac);
152 LOG.debug("Ethertype: {}", Integer.toHexString(0x0000ffff & ByteBuffer.wrap(etherType).getShort()));
154 // learn by IPv4 traffic only
155 if (Arrays.equals(ETH_TYPE_IPV4, etherType)) {
156 NodeConnectorRef previousPort = mac2portMapping.put(srcMac, notification.getIngress());
157 if (previousPort != null && !notification.getIngress().equals(previousPort)) {
158 NodeConnectorKey previousPortKey = InstanceIdentifierUtils.getNodeConnectorKey(previousPort.getValue());
159 LOG.debug("mac2port mapping changed by mac {}: {} -> {}", srcMac, previousPortKey, ingressKey.getId());
161 // if dst MAC mapped:
162 NodeConnectorRef destNodeConnector = mac2portMapping.get(dstMac);
163 if (destNodeConnector != null) {
164 synchronized (coveredMacPaths) {
165 if (!destNodeConnector.equals(notification.getIngress())) {
167 addBridgeFlow(srcMac, dstMac, destNodeConnector);
168 addBridgeFlow(dstMac, srcMac, notification.getIngress());
170 LOG.debug("useless rule ignoring - both MACs are behind the same port");
173 LOG.debug("packetIn-directing.. to {}",
174 InstanceIdentifierUtils.getNodeConnectorKey(destNodeConnector.getValue()).getId());
175 sendPacketOut(notification.getPayload(), notification.getIngress(), destNodeConnector);
178 LOG.debug("packetIn-still flooding.. ");
179 flood(notification.getPayload(), notification.getIngress());
183 flood(notification.getPayload(), notification.getIngress());
191 * @param destNodeConnector
193 private void addBridgeFlow(MacAddress srcMac, MacAddress dstMac, NodeConnectorRef destNodeConnector) {
194 synchronized (coveredMacPaths) {
195 String macPath = srcMac.toString() + dstMac.toString();
196 if (!coveredMacPaths.contains(macPath)) {
197 LOG.debug("covering mac path: {} by [{}]", macPath,
198 destNodeConnector.getValue().firstKeyOf(NodeConnector.class, NodeConnectorKey.class).getId());
200 coveredMacPaths.add(macPath);
201 FlowId flowId = new FlowId(String.valueOf(flowIdInc.getAndIncrement()));
202 FlowKey flowKey = new FlowKey(flowId);
204 * Path to the flow we want to program.
206 InstanceIdentifier<Flow> flowPath = InstanceIdentifierUtils.createFlowPath(tablePath, flowKey);
208 Short tableId = InstanceIdentifierUtils.getTableId(tablePath);
209 FlowBuilder srcToDstFlow = FlowUtils.createDirectMacToMacFlow(tableId, DIRECT_FLOW_PRIORITY, srcMac,
210 dstMac, destNodeConnector);
211 srcToDstFlow.setCookie(new FlowCookie(BigInteger.valueOf(flowCookieInc.getAndIncrement())));
213 dataStoreAccessor.writeFlowToConfig(flowPath, srcToDstFlow.build());
218 private void flood(byte[] payload, NodeConnectorRef ingress) {
219 NodeConnectorKey nodeConnectorKey = new NodeConnectorKey(nodeConnectorId("0xfffffffb"));
220 InstanceIdentifier<?> nodeConnectorPath = InstanceIdentifierUtils.createNodeConnectorPath(nodePath, nodeConnectorKey);
221 NodeConnectorRef egressConnectorRef = new NodeConnectorRef(nodeConnectorPath);
223 sendPacketOut(payload, ingress, egressConnectorRef);
226 private NodeConnectorId nodeConnectorId(String connectorId) {
227 NodeKey nodeKey = nodePath.firstKeyOf(Node.class, NodeKey.class);
228 StringBuilder stringId = new StringBuilder(nodeKey.getId().getValue()).append(":").append(connectorId);
229 return new NodeConnectorId(stringId.toString());
232 private void sendPacketOut(byte[] payload, NodeConnectorRef ingress, NodeConnectorRef egress) {
233 InstanceIdentifier<Node> egressNodePath = InstanceIdentifierUtils.getNodePath(egress.getValue());
234 TransmitPacketInput input = new TransmitPacketInputBuilder()
236 .setNode(new NodeRef(egressNodePath))
240 packetProcessingService.transmitPacket(input);