280e925b419ea384aef7794b80ef055619601e55
[controller.git] / opendaylight / protocol_plugins / openflow_netty / src / main / java / org / opendaylight / controller / protocol_plugin / openflow / internal / DataPacketMuxDemux.java
1
2 /*
3  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
4  *
5  * This program and the accompanying materials are made available under the
6  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7  * and is available at http://www.eclipse.org/legal/epl-v10.html
8  */
9
10 package org.opendaylight.controller.protocol_plugin.openflow.internal;
11
12 import java.util.Collections;
13 import java.util.List;
14 import java.util.Map;
15 import java.util.Set;
16 import java.util.concurrent.ConcurrentHashMap;
17 import java.util.concurrent.ConcurrentMap;
18 import java.util.concurrent.CopyOnWriteArrayList;
19
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.openflow.protocol.OFMessage;
27 import org.openflow.protocol.OFPacketIn;
28 import org.openflow.protocol.OFPacketOut;
29 import org.openflow.protocol.OFPort;
30 import org.openflow.protocol.OFType;
31 import org.openflow.protocol.action.OFAction;
32 import org.openflow.protocol.action.OFActionOutput;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 import org.opendaylight.controller.sal.core.ConstructionException;
37 import org.opendaylight.controller.sal.core.ContainerFlow;
38 import org.opendaylight.controller.sal.core.IContainerListener;
39 import org.opendaylight.controller.sal.core.Node;
40 import org.opendaylight.controller.sal.core.NodeConnector;
41 import org.opendaylight.controller.sal.core.Property;
42 import org.opendaylight.controller.sal.core.UpdateType;
43 import org.opendaylight.controller.sal.packet.IPluginOutDataPacketService;
44 import org.opendaylight.controller.sal.packet.PacketResult;
45 import org.opendaylight.controller.sal.packet.RawPacket;
46 import org.opendaylight.controller.sal.utils.GlobalConstants;
47
48 public class DataPacketMuxDemux implements IContainerListener,
49         IMessageListener, IDataPacketMux, IInventoryShimExternalListener {
50     protected static final Logger logger = LoggerFactory
51             .getLogger(DataPacketMuxDemux.class);
52     private IController controller = null;
53     private ConcurrentMap<Long, ISwitch> swID2ISwitch = new ConcurrentHashMap<Long, ISwitch>();
54     // Gives a map between a Container and all the DataPacket listeners on SAL
55     private ConcurrentMap<String, IPluginOutDataPacketService> pluginOutDataPacketServices = new ConcurrentHashMap<String, IPluginOutDataPacketService>();
56     // Gives a map between a NodeConnector and the containers to which it belongs
57     private ConcurrentMap<NodeConnector, List<String>> nc2Container = new ConcurrentHashMap<NodeConnector, List<String>>();
58     // Gives a map between a Container and the FlowSpecs on it
59     private ConcurrentMap<String, List<ContainerFlow>> container2FlowSpecs = new ConcurrentHashMap<String, List<ContainerFlow>>();
60     // Track local data packet listener
61     private List<IDataPacketListen> iDataPacketListen = new CopyOnWriteArrayList<IDataPacketListen>();
62
63     void setIDataPacketListen(IDataPacketListen s) {
64         if (this.iDataPacketListen != null) {
65             if (!this.iDataPacketListen.contains(s)) {
66                 logger.debug("Added new IDataPacketListen");
67                 this.iDataPacketListen.add(s);
68             }
69         }
70     }
71
72     void unsetIDataPacketListen(IDataPacketListen s) {
73         if (this.iDataPacketListen != null) {
74             if (this.iDataPacketListen.contains(s)) {
75                 logger.debug("Removed IDataPacketListen");
76                 this.iDataPacketListen.remove(s);
77             }
78         }
79     }
80
81     void setPluginOutDataPacketService(Map<String, Object> props,
82             IPluginOutDataPacketService s) {
83         if (props == null) {
84             logger.error("Didn't receive the service properties");
85             return;
86         }
87         String containerName = (String) props.get("containerName");
88         if (containerName == null) {
89             logger.error("containerName not supplied");
90             return;
91         }
92         if (this.pluginOutDataPacketServices != null) {
93             // It's expected only one SAL per container as long as the
94             // replication is done in the SAL implementation toward
95             // the different APPS
96             this.pluginOutDataPacketServices.put(containerName, s);
97             logger.debug("New outService for container: {}", containerName);
98         }
99     }
100
101     void unsetPluginOutDataPacketService(Map<String, Object> props,
102             IPluginOutDataPacketService s) {
103         if (props == null) {
104             logger.error("Didn't receive the service properties");
105             return;
106         }
107         String containerName = (String) props.get("containerName");
108         if (containerName == null) {
109             logger.error("containerName not supplied");
110             return;
111         }
112         if (this.pluginOutDataPacketServices != null) {
113             this.pluginOutDataPacketServices.remove(containerName);
114             logger.debug("Removed outService for container: {}", containerName);
115         }
116     }
117
118     void setController(IController s) {
119         logger.debug("Controller provider set in DATAPACKET SERVICES");
120         this.controller = s;
121     }
122
123     void unsetController(IController s) {
124         if (this.controller == s) {
125             logger.debug("Controller provider UNset in DATAPACKET SERVICES");
126             this.controller = null;
127         }
128     }
129
130     /**
131      * Function called by the dependency manager when all the required
132      * dependencies are satisfied
133      *
134      */
135     void init() {
136         this.controller.addMessageListener(OFType.PACKET_IN, this);
137     }
138
139     /**
140      * Function called by the dependency manager when at least one
141      * dependency become unsatisfied or when the component is shutting
142      * down because for example bundle is being stopped.
143      *
144      */
145     void destroy() {
146         this.controller.removeMessageListener(OFType.PACKET_IN, this);
147
148         // Clear state that may need to be reused on component restart
149         this.pluginOutDataPacketServices.clear();
150         this.nc2Container.clear();
151         this.container2FlowSpecs.clear();
152         this.controller = null;
153         this.swID2ISwitch.clear();
154     }
155
156     @Override
157     public void receive(ISwitch sw, OFMessage msg) {
158         if (sw == null || msg == null
159                 || this.pluginOutDataPacketServices == null) {
160             // Something fishy, we cannot do anything
161             logger.debug("sw: {} and/or msg: {} and/or pluginOutDataPacketServices: {} is null!",
162                         new Object[]{sw, msg, this.pluginOutDataPacketServices});
163             return;
164         }
165         if (msg instanceof OFPacketIn) {
166             OFPacketIn ofPacket = (OFPacketIn) msg;
167             Long ofSwitchID = Long.valueOf(sw.getId());
168             Short ofPortID = Short.valueOf(ofPacket.getInPort());
169
170             try {
171                 Node n = new Node(Node.NodeIDType.OPENFLOW, ofSwitchID);
172                 NodeConnector p = PortConverter.toNodeConnector(ofPortID, n);
173                 RawPacket dataPacket = new RawPacket(ofPacket.getPacketData());
174                 dataPacket.setIncomingNodeConnector(p);
175
176                 // Try to dispatch the packet locally, in here we will
177                 // pass the parsed packet simply because once the
178                 // packet infra is settled all the packets will passed
179                 // around as parsed and read-only
180                 for (int i = 0; i < this.iDataPacketListen.size(); i++) {
181                     IDataPacketListen s = this.iDataPacketListen.get(i);
182                     if (s.receiveDataPacket(dataPacket).equals(
183                             PacketResult.CONSUME)) {
184                         logger.trace("Consumed locally data packet");
185                         return;
186                     }
187                 }
188
189                 // Now dispatch the packet toward SAL at least for
190                 // default container, we need to revisit this in a general
191                 // slicing architecture refresh
192                 IPluginOutDataPacketService defaultOutService = this.pluginOutDataPacketServices
193                         .get(GlobalConstants.DEFAULT.toString());
194                 if (defaultOutService != null) {
195                     defaultOutService.receiveDataPacket(dataPacket);
196                     logger.trace("Dispatched to apps a frame of size: {} on container: {}",
197                             ofPacket.getPacketData().length, GlobalConstants.DEFAULT.toString());
198                 }
199                 // Now check the mapping between nodeConnector and
200                 // Container and later on optinally filter based on
201                 // flowSpec
202                 /*
203                 List<String> containersRX = this.nc2Container.get(p);
204                 if (containersRX != null) {
205                     for (int i = 0; i < containersRX.size(); i++) {
206                         String container = containersRX.get(i);
207                         IPluginOutDataPacketService s = this.pluginOutDataPacketServices
208                                 .get(container);
209                         if (s != null) {
210                             // TODO add filtering on a per-flowSpec base
211                             s.receiveDataPacket(dataPacket);
212                             logger.trace("Dispatched to apps a frame of size: {} on container: {}",
213                                     ofPacket.getPacketData().length, GlobalConstants.DEFAULT.toString());
214
215                         }
216                     }
217                 }
218                 */
219
220                 // This is supposed to be the catch all for all the
221                 // DataPacket hence we will assume it has been handled
222                 return;
223             } catch (ConstructionException cex) {
224             }
225
226             // If we reach this point something went wrong.
227             return;
228         } else {
229             // We don't care about non-data packets
230             return;
231         }
232     }
233
234     @Override
235     public void transmitDataPacket(RawPacket outPkt) {
236         // Sanity check area
237         if (outPkt == null) {
238             logger.debug("outPkt is null!");
239             return;
240         }
241
242         NodeConnector outPort = outPkt.getOutgoingNodeConnector();
243         if (outPort == null) {
244             logger.debug("outPort is null! outPkt: {}", outPkt);
245             return;
246         }
247
248         if (!outPort.getType().equals(
249                 NodeConnector.NodeConnectorIDType.OPENFLOW)) {
250             // The output Port is not of type OpenFlow
251             logger.debug("outPort is not OF Type! outPort: {}", outPort);
252             return;
253         }
254
255         Short port = (Short) outPort.getID();
256         Long swID = (Long) outPort.getNode().getID();
257         ISwitch sw = this.swID2ISwitch.get(swID);
258
259         if (sw == null) {
260             // If we cannot get the controller descriptor we cannot even
261             // send out the frame
262             logger.debug("swID: {} - sw is null!", swID);
263             return;
264         }
265
266         byte[] data = outPkt.getPacketData();
267         // build action
268         OFActionOutput action = new OFActionOutput().setPort(port);
269         // build packet out
270         OFPacketOut po = new OFPacketOut().setBufferId(
271                 OFPacketOut.BUFFER_ID_NONE).setInPort(OFPort.OFPP_NONE)
272                 .setActions(Collections.singletonList((OFAction) action))
273                 .setActionsLength((short) OFActionOutput.MINIMUM_LENGTH);
274
275         po.setLengthU(OFPacketOut.MINIMUM_LENGTH + po.getActionsLength()
276                 + data.length);
277         po.setPacketData(data);
278
279         sw.asyncSend(po);
280         logger.trace("Transmitted a frame of size: {}", data.length);
281     }
282
283     public void addNode(Node node, Set<Property> props) {
284         if (node == null) {
285             logger.debug("node is null!");
286             return;
287         }
288
289         long sid = (Long) node.getID();
290         ISwitch sw = controller.getSwitches().get(sid);
291         if (sw == null) {
292             logger.debug("sid: {} - sw is null!", sid);
293             return;
294         }
295         this.swID2ISwitch.put(sw.getId(), sw);
296     }
297
298     public void removeNode(Node node) {
299         if (node == null) {
300             logger.debug("node is null!");
301             return;
302         }
303
304         long sid = (Long) node.getID();
305         ISwitch sw = controller.getSwitches().get(sid);
306         if (sw == null) {
307             logger.debug("sid: {} - sw is null!", sid);
308             return;
309         }
310         this.swID2ISwitch.remove(sw.getId());
311     }
312
313     @Override
314     public void tagUpdated(String containerName, Node n, short oldTag,
315             short newTag, UpdateType t) {
316         // Do nothing
317     }
318
319     @Override
320     public void containerFlowUpdated(String containerName,
321             ContainerFlow previousFlow, ContainerFlow currentFlow, UpdateType t) {
322         if (this.container2FlowSpecs == null) {
323             logger.error("container2FlowSpecs is NULL");
324             return;
325         }
326         List<ContainerFlow> fSpecs = this.container2FlowSpecs
327                 .get(containerName);
328         if (fSpecs == null) {
329             fSpecs = new CopyOnWriteArrayList<ContainerFlow>();
330         }
331         switch (t) {
332         case ADDED:
333             if (!fSpecs.contains(previousFlow)) {
334                 fSpecs.add(previousFlow);
335             }
336             break;
337         case REMOVED:
338             if (fSpecs.contains(previousFlow)) {
339                 fSpecs.remove(previousFlow);
340             }
341             break;
342         case CHANGED:
343             break;
344         }
345     }
346
347     @Override
348     public void nodeConnectorUpdated(String containerName, NodeConnector p,
349             UpdateType t) {
350         if (this.nc2Container == null) {
351             logger.error("nc2Container is NULL");
352             return;
353         }
354         List<String> containers = this.nc2Container.get(p);
355         if (containers == null) {
356             containers = new CopyOnWriteArrayList<String>();
357         }
358         boolean updateMap = false;
359         switch (t) {
360         case ADDED:
361             if (!containers.contains(containerName)) {
362                 containers.add(containerName);
363                 updateMap = true;
364             }
365             break;
366         case REMOVED:
367             if (containers.contains(containerName)) {
368                 containers.remove(containerName);
369                 updateMap = true;
370             }
371             break;
372         case CHANGED:
373             break;
374         }
375         if (updateMap) {
376             if (containers.isEmpty()) {
377                 // Do cleanup to reduce memory footprint if no
378                 // elements to be tracked
379                 this.nc2Container.remove(p);
380             } else {
381                 this.nc2Container.put(p, containers);
382             }
383         }
384     }
385
386     @Override
387     public void containerModeUpdated(UpdateType t) {
388         // do nothing
389     }
390
391     @Override
392     public void updateNode(Node node, UpdateType type, Set<Property> props) {
393         switch (type) {
394         case ADDED:
395             addNode(node, props);
396             break;
397         case REMOVED:
398             removeNode(node);
399             break;
400         default:
401             break;
402         }
403     }
404
405     @Override
406     public void updateNodeConnector(NodeConnector nodeConnector,
407             UpdateType type, Set<Property> props) {
408         // do nothing
409     }
410 }