2 * Copyright (c) 2013 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.controller.protocol_plugin.openflow.internal;
11 import java.util.Collections;
12 import java.util.HashSet;
13 import java.util.List;
16 import java.util.concurrent.ConcurrentHashMap;
17 import java.util.concurrent.ConcurrentMap;
18 import java.util.concurrent.CopyOnWriteArrayList;
20 import org.opendaylight.controller.protocol_plugin.openflow.IDataPacketListen;
21 import org.opendaylight.controller.protocol_plugin.openflow.IDataPacketMux;
22 import org.opendaylight.controller.protocol_plugin.openflow.IInventoryShimExternalListener;
23 import org.opendaylight.controller.protocol_plugin.openflow.core.IController;
24 import org.opendaylight.controller.protocol_plugin.openflow.core.IMessageListener;
25 import org.opendaylight.controller.protocol_plugin.openflow.core.ISwitch;
26 import org.opendaylight.controller.sal.connection.IPluginOutConnectionService;
27 import org.opendaylight.controller.sal.core.ConstructionException;
28 import org.opendaylight.controller.sal.core.ContainerFlow;
29 import org.opendaylight.controller.sal.core.IContainerAware;
30 import org.opendaylight.controller.sal.core.IContainerListener;
31 import org.opendaylight.controller.sal.core.Node;
32 import org.opendaylight.controller.sal.core.NodeConnector;
33 import org.opendaylight.controller.sal.core.Property;
34 import org.opendaylight.controller.sal.core.UpdateType;
35 import org.opendaylight.controller.sal.match.Match;
36 import org.opendaylight.controller.sal.packet.Ethernet;
37 import org.opendaylight.controller.sal.packet.IPluginOutDataPacketService;
38 import org.opendaylight.controller.sal.packet.PacketException;
39 import org.opendaylight.controller.sal.packet.PacketResult;
40 import org.opendaylight.controller.sal.packet.RawPacket;
41 import org.opendaylight.controller.sal.utils.GlobalConstants;
42 import org.opendaylight.controller.sal.utils.HexEncode;
43 import org.opendaylight.controller.sal.utils.NetUtils;
44 import org.openflow.protocol.OFMessage;
45 import org.openflow.protocol.OFPacketIn;
46 import org.openflow.protocol.OFPacketOut;
47 import org.openflow.protocol.OFPort;
48 import org.openflow.protocol.OFType;
49 import org.openflow.protocol.action.OFAction;
50 import org.openflow.protocol.action.OFActionOutput;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
54 public class DataPacketMuxDemux implements IContainerListener,
55 IMessageListener, IDataPacketMux, IInventoryShimExternalListener, IContainerAware {
56 protected static final Logger logger = LoggerFactory
57 .getLogger(DataPacketMuxDemux.class);
58 private IController controller = null;
59 private ConcurrentMap<Long, ISwitch> swID2ISwitch = new ConcurrentHashMap<Long, ISwitch>();
60 // Gives a map between a Container and all the DataPacket listeners on SAL
61 private ConcurrentMap<String, IPluginOutDataPacketService> pluginOutDataPacketServices = new ConcurrentHashMap<String, IPluginOutDataPacketService>();
62 // Gives a map between a NodeConnector and the containers to which it
64 private ConcurrentMap<NodeConnector, List<String>> nc2Container = new ConcurrentHashMap<NodeConnector, List<String>>();
65 // Gives a map between a Container and the FlowSpecs on it
66 private ConcurrentMap<String, List<ContainerFlow>> container2FlowSpecs = new ConcurrentHashMap<String, List<ContainerFlow>>();
67 // Track local data packet listener
68 private List<IDataPacketListen> iDataPacketListen = new CopyOnWriteArrayList<IDataPacketListen>();
69 private IPluginOutConnectionService connectionOutService;
71 void setIDataPacketListen(IDataPacketListen s) {
72 if (this.iDataPacketListen != null) {
73 if (!this.iDataPacketListen.contains(s)) {
74 logger.debug("Added new IDataPacketListen");
75 this.iDataPacketListen.add(s);
80 void unsetIDataPacketListen(IDataPacketListen s) {
81 if (this.iDataPacketListen != null) {
82 if (this.iDataPacketListen.contains(s)) {
83 logger.debug("Removed IDataPacketListen");
84 this.iDataPacketListen.remove(s);
89 void setPluginOutDataPacketService(Map<String, Object> props,
90 IPluginOutDataPacketService s) {
92 logger.error("Didn't receive the service properties");
95 String containerName = (String) props.get("containerName");
96 if (containerName == null) {
97 logger.error("containerName not supplied");
100 if (this.pluginOutDataPacketServices != null) {
101 // It's expected only one SAL per container as long as the
102 // replication is done in the SAL implementation toward
103 // the different APPS
104 this.pluginOutDataPacketServices.put(containerName, s);
105 logger.debug("New outService for container: {}", containerName);
109 void unsetPluginOutDataPacketService(Map<String, Object> props,
110 IPluginOutDataPacketService s) {
112 logger.error("Didn't receive the service properties");
115 String containerName = (String) props.get("containerName");
116 if (containerName == null) {
117 logger.error("containerName not supplied");
120 if (this.pluginOutDataPacketServices != null) {
121 this.pluginOutDataPacketServices.remove(containerName);
122 logger.debug("Removed outService for container: {}", containerName);
126 void setController(IController s) {
127 logger.debug("Controller provider set in DATAPACKET SERVICES");
131 void unsetController(IController s) {
132 if (this.controller == s) {
133 logger.debug("Controller provider UNset in DATAPACKET SERVICES");
134 this.controller = null;
138 void setIPluginOutConnectionService(IPluginOutConnectionService s) {
139 connectionOutService = s;
142 void unsetIPluginOutConnectionService(IPluginOutConnectionService s) {
143 if (connectionOutService == s) {
144 connectionOutService = null;
149 * Function called by the dependency manager when all the required
150 * dependencies are satisfied
154 this.controller.addMessageListener(OFType.PACKET_IN, this);
158 * Function called by the dependency manager when at least one dependency
159 * become unsatisfied or when the component is shutting down because for
160 * example bundle is being stopped.
164 this.controller.removeMessageListener(OFType.PACKET_IN, this);
166 // Clear state that may need to be reused on component restart
167 this.pluginOutDataPacketServices.clear();
168 this.nc2Container.clear();
169 this.container2FlowSpecs.clear();
170 this.controller = null;
171 this.swID2ISwitch.clear();
175 public void receive(ISwitch sw, OFMessage msg) {
176 if (sw == null || msg == null || this.pluginOutDataPacketServices == null) {
177 // Something fishy, we cannot do anything
178 logger.debug("sw: {} and/or msg: {} and/or pluginOutDataPacketServices: {} is null!", new Object[] { sw,
179 msg, this.pluginOutDataPacketServices });
183 Long ofSwitchID = Long.valueOf(sw.getId());
185 Node n = new Node(Node.NodeIDType.OPENFLOW, ofSwitchID);
186 if (!connectionOutService.isLocal(n)) {
187 logger.debug("Connection service refused DataPacketMuxDemux receive {} {}", sw, msg);
190 } catch (Exception e) {
194 if (msg instanceof OFPacketIn) {
195 OFPacketIn ofPacket = (OFPacketIn) msg;
196 Short ofPortID = Short.valueOf(ofPacket.getInPort());
199 Node n = new Node(Node.NodeIDType.OPENFLOW, ofSwitchID);
200 NodeConnector p = PortConverter.toNodeConnector(ofPortID, n);
201 RawPacket dataPacket = new RawPacket(ofPacket.getPacketData());
202 dataPacket.setIncomingNodeConnector(p);
204 // Try to dispatch the packet locally, in here we will
205 // pass the parsed packet simply because once the
206 // packet infra is settled all the packets will passed
207 // around as parsed and read-only
208 for (IDataPacketListen s : this.iDataPacketListen) {
209 if (s.receiveDataPacket(dataPacket).equals(PacketResult.CONSUME)) {
210 logger.trace("Consumed locally data packet");
215 // Now dispatch the packet toward SAL for default container
216 IPluginOutDataPacketService defaultOutService = this.pluginOutDataPacketServices
217 .get(GlobalConstants.DEFAULT.toString());
218 if (defaultOutService != null) {
219 defaultOutService.receiveDataPacket(dataPacket);
220 if (logger.isTraceEnabled()) {
221 logger.trace("Dispatched to apps a frame of size: {} on " + "container: {}: {}",
222 new Object[] { ofPacket.getPacketData().length, GlobalConstants.DEFAULT.toString(),
223 HexEncode.bytesToHexString(dataPacket.getPacketData()) });
226 // Now check the mapping between nodeConnector and
227 // Container and later on optimally filter based on
229 List<String> containersRX = this.nc2Container.get(p);
230 if (containersRX != null) {
231 Ethernet frame = new Ethernet();
232 byte data[] = dataPacket.getPacketData();
233 frame.deserialize(data, 0, data.length * NetUtils.NumBitsInAByte);
234 Match packetMatch = frame.getMatch();
235 for (String container : containersRX) {
236 boolean notify = true;
237 List<ContainerFlow> containerFlows = this.container2FlowSpecs.get(container);
238 if (containerFlows != null) {
240 for (ContainerFlow cFlow : containerFlows) {
241 if (cFlow.allowsMatch(packetMatch)) {
247 IPluginOutDataPacketService s = this.pluginOutDataPacketServices.get(container);
249 s.receiveDataPacket(dataPacket);
250 if (logger.isTraceEnabled()) {
252 "Dispatched to apps a frame of size: {}" + " on container: {}: {}",
253 new Object[] { ofPacket.getPacketData().length, container,
254 HexEncode.bytesToHexString(dataPacket.getPacketData()) });
261 // This is supposed to be the catch all for all the
262 // DataPacket hence we will assume it has been handled
264 } catch (ConstructionException cex) {
265 } catch (PacketException e) {
266 logger.debug("Failed to deserialize raw packet: ", e.getMessage());
268 // If we reach this point something went wrong.
271 // We don't care about non-data packets
277 public void transmitDataPacket(RawPacket outPkt) {
279 if (outPkt == null) {
280 logger.debug("outPkt is null!");
284 NodeConnector outPort = outPkt.getOutgoingNodeConnector();
285 if (outPort == null) {
286 logger.debug("outPort is null! outPkt: {}", outPkt);
290 if (!connectionOutService.isLocal(outPort.getNode())) {
291 logger.debug("data packets will not be sent to {} in a non-master controller", outPort.toString());
296 if (!outPort.getType().equals(
297 NodeConnector.NodeConnectorIDType.OPENFLOW)) {
298 // The output Port is not of type OpenFlow
299 logger.debug("outPort is not OF Type! outPort: {}", outPort);
303 Short port = (Short) outPort.getID();
304 Long swID = (Long) outPort.getNode().getID();
305 ISwitch sw = this.swID2ISwitch.get(swID);
308 // If we cannot get the controller descriptor we cannot even
309 // send out the frame
310 logger.debug("swID: {} - sw is null!", swID);
314 byte[] data = outPkt.getPacketData();
316 OFActionOutput action = new OFActionOutput().setPort(port);
318 OFPacketOut po = new OFPacketOut()
319 .setBufferId(OFPacketOut.BUFFER_ID_NONE)
320 .setActions(Collections.singletonList((OFAction) action))
321 .setActionsLength((short) OFActionOutput.MINIMUM_LENGTH);
322 if(outPkt.getIncomingNodeConnector() != null) {
323 po.setInPort((Short)outPkt.getIncomingNodeConnector().getID());
325 po.setInPort(OFPort.OFPP_NONE);
328 po.setLengthU(OFPacketOut.MINIMUM_LENGTH + po.getActionsLength()
330 po.setPacketData(data);
332 // send PACKET_OUT at high priority
333 sw.asyncFastSend(po);
334 logger.trace("Transmitted a frame of size: {}", data.length);
337 public void addNode(Node node, Set<Property> props) {
339 logger.debug("node is null!");
343 long sid = (Long) node.getID();
344 ISwitch sw = controller.getSwitches().get(sid);
346 logger.debug("sid: {} - sw is null!", sid);
349 this.swID2ISwitch.put(sw.getId(), sw);
352 public void removeNode(Node node) {
354 logger.debug("node is null!");
358 long sid = (Long) node.getID();
359 ISwitch sw = controller.getSwitches().get(sid);
361 logger.debug("sid: {} - sw is null!", sid);
364 this.swID2ISwitch.remove(sw.getId());
368 public void tagUpdated(String containerName, Node n, short oldTag,
369 short newTag, UpdateType t) {
374 public void containerFlowUpdated(String containerName,
375 ContainerFlow previousFlow, ContainerFlow currentFlow, UpdateType t) {
376 if (this.container2FlowSpecs == null) {
377 logger.error("container2FlowSpecs is NULL");
380 List<ContainerFlow> fSpecs = this.container2FlowSpecs
382 if (fSpecs == null) {
383 fSpecs = new CopyOnWriteArrayList<ContainerFlow>();
387 if (!fSpecs.contains(currentFlow)) {
388 fSpecs.add(currentFlow);
390 container2FlowSpecs.put(containerName, fSpecs);
393 fSpecs.remove(currentFlow);
401 public void nodeConnectorUpdated(String containerName, NodeConnector p,
403 if (this.nc2Container == null) {
404 logger.error("nc2Container is NULL");
407 List<String> containers = this.nc2Container.get(p);
408 if (containers == null) {
409 containers = new CopyOnWriteArrayList<String>();
411 boolean updateMap = false;
414 if (!containers.contains(containerName)) {
415 containers.add(containerName);
420 if (containers.contains(containerName)) {
421 containers.remove(containerName);
429 if (containers.isEmpty()) {
430 // Do cleanup to reduce memory footprint if no
431 // elements to be tracked
432 this.nc2Container.remove(p);
434 this.nc2Container.put(p, containers);
440 public void containerModeUpdated(UpdateType t) {
445 public void updateNode(Node node, UpdateType type, Set<Property> props) {
448 addNode(node, props);
459 public void updateNodeConnector(NodeConnector nodeConnector,
460 UpdateType type, Set<Property> props) {
465 public void containerCreate(String containerName) {
470 public void containerDestroy(String containerName) {
471 Set<NodeConnector> removeNodeConnectorSet = new HashSet<NodeConnector>();
472 for (Map.Entry<NodeConnector, List<String>> entry : nc2Container.entrySet()) {
473 List<String> ncContainers = entry.getValue();
474 if (ncContainers.contains(containerName)) {
475 NodeConnector nodeConnector = entry.getKey();
476 removeNodeConnectorSet.add(nodeConnector);
479 for (NodeConnector nodeConnector : removeNodeConnectorSet) {
480 List<String> ncContainers = nc2Container.get(nodeConnector);
481 ncContainers.remove(containerName);
482 if (ncContainers.isEmpty()) {
483 nc2Container.remove(nodeConnector);
486 container2FlowSpecs.remove(containerName);