OpenDaylight Controller functional modules.
[controller.git] / opendaylight / protocol_plugins / openflow / 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             return;
162         }
163         if (msg instanceof OFPacketIn) {
164             OFPacketIn ofPacket = (OFPacketIn) msg;
165             Long ofSwitchID = Long.valueOf(sw.getId());
166             Short ofPortID = Short.valueOf(ofPacket.getInPort());
167
168             try {
169                 Node n = new Node(Node.NodeIDType.OPENFLOW, ofSwitchID);
170                 NodeConnector p = PortConverter.toNodeConnector(ofPortID, n);
171                 RawPacket dataPacket = new RawPacket(ofPacket.getPacketData());
172                 dataPacket.setIncomingNodeConnector(p);
173
174                 // Try to dispatch the packet locally, in here we will
175                 // pass the parsed packet simply because once the
176                 // packet infra is settled all the packets will passed
177                 // around as parsed and read-only
178                 for (int i = 0; i < this.iDataPacketListen.size(); i++) {
179                     IDataPacketListen s = this.iDataPacketListen.get(i);
180                     if (s.receiveDataPacket(dataPacket).equals(
181                             PacketResult.CONSUME)) {
182                         logger.trace("Consumed locally data packet");
183                         return;
184                     }
185                 }
186
187                 // Now dispatch the packet toward SAL at least for
188                 // default container, we need to revisit this in a general
189                 // slicing architecture refresh
190                 IPluginOutDataPacketService defaultOutService = this.pluginOutDataPacketServices
191                         .get(GlobalConstants.DEFAULT.toString());
192                 if (defaultOutService != null) {
193                     defaultOutService.receiveDataPacket(dataPacket);
194                     logger.trace("Dispatched to apps a frame of size: "
195                             + ofPacket.getPacketData().length
196                             + " on container: "
197                             + GlobalConstants.DEFAULT.toString());
198                 }
199                 // Now check the mapping between nodeConnector and
200                 // Container and later on optinally filter based on
201                 // flowSpec
202                 List<String> containersRX = this.nc2Container.get(p);
203                 if (containersRX != null) {
204                     for (int i = 0; i < containersRX.size(); i++) {
205                         String container = containersRX.get(i);
206                         IPluginOutDataPacketService s = this.pluginOutDataPacketServices
207                                 .get(container);
208                         if (s != null) {
209                             // TODO add filtering on a per-flowSpec base
210                             s.receiveDataPacket(dataPacket);
211                             logger.trace("Dispatched to apps a frame of size: "
212                                     + ofPacket.getPacketData().length
213                                     + " on container: " + container);
214
215                         }
216                     }
217                 }
218
219                 // This is supposed to be the catch all for all the
220                 // DataPacket hence we will assume it has been handled
221                 return;
222             } catch (ConstructionException cex) {
223             }
224
225             // If we reach this point something went wrong.
226             return;
227         } else {
228             // We don't care about non-data packets
229             return;
230         }
231     }
232
233     @Override
234     public void transmitDataPacket(RawPacket outPkt) {
235         // Sanity check area
236         if (outPkt == null) {
237             return;
238         }
239
240         NodeConnector outPort = outPkt.getOutgoingNodeConnector();
241         if (outPort == null) {
242             return;
243         }
244
245         if (!outPort.getType().equals(
246                 NodeConnector.NodeConnectorIDType.OPENFLOW)) {
247             // The output Port is not of type OpenFlow
248             return;
249         }
250
251         Short port = (Short) outPort.getID();
252         Long swID = (Long) outPort.getNode().getID();
253         ISwitch sw = this.swID2ISwitch.get(swID);
254
255         if (sw == null) {
256             // If we cannot get the controller descriptor we cannot even
257             // send out the frame
258             return;
259         }
260
261         byte[] data = outPkt.getPacketData();
262         // build action
263         OFActionOutput action = new OFActionOutput().setPort(port);
264         // build packet out
265         OFPacketOut po = new OFPacketOut().setBufferId(
266                 OFPacketOut.BUFFER_ID_NONE).setInPort(OFPort.OFPP_NONE)
267                 .setActions(Collections.singletonList((OFAction) action))
268                 .setActionsLength((short) OFActionOutput.MINIMUM_LENGTH);
269
270         po.setLengthU(OFPacketOut.MINIMUM_LENGTH + po.getActionsLength()
271                 + data.length);
272         po.setPacketData(data);
273
274         sw.asyncSend(po);
275         logger.trace("Transmitted a frame of size:" + data.length);
276     }
277
278     public void addNode(Node node, Set<Property> props) {
279         if (node == null)
280             return;
281
282         long sid = (Long) node.getID();
283         ISwitch sw = controller.getSwitches().get(sid);
284         if (sw != null) {
285             this.swID2ISwitch.put(sw.getId(), sw);
286         }
287     }
288
289     public void removeNode(Node node) {
290         if (node == null)
291             return;
292
293         long sid = (Long) node.getID();
294         ISwitch sw = controller.getSwitches().get(sid);
295         if (sw != null) {
296             this.swID2ISwitch.remove(sw.getId());
297         }
298     }
299
300     @Override
301     public void tagUpdated(String containerName, Node n, short oldTag,
302             short newTag, UpdateType t) {
303         // Do nothing
304     }
305
306     @Override
307     public void containerFlowUpdated(String containerName,
308             ContainerFlow previousFlow, ContainerFlow currentFlow, UpdateType t) {
309         if (this.container2FlowSpecs == null) {
310             logger.error("container2FlowSpecs is NULL");
311             return;
312         }
313         List<ContainerFlow> fSpecs = this.container2FlowSpecs
314                 .get(containerName);
315         if (fSpecs == null) {
316             fSpecs = new CopyOnWriteArrayList<ContainerFlow>();
317         }
318         boolean updateMap = false;
319         switch (t) {
320         case ADDED:
321             if (!fSpecs.contains(previousFlow)) {
322                 fSpecs.add(previousFlow);
323             }
324             break;
325         case REMOVED:
326             if (fSpecs.contains(previousFlow)) {
327                 fSpecs.remove(previousFlow);
328             }
329             break;
330         case CHANGED:
331             break;
332         }
333         if (updateMap) {
334             if (fSpecs.isEmpty()) {
335                 this.container2FlowSpecs.remove(containerName);
336             } else {
337                 this.container2FlowSpecs.put(containerName, fSpecs);
338             }
339         }
340     }
341
342     @Override
343     public void nodeConnectorUpdated(String containerName, NodeConnector p,
344             UpdateType t) {
345         if (this.nc2Container == null) {
346             logger.error("nc2Container is NULL");
347             return;
348         }
349         List<String> containers = this.nc2Container.get(p);
350         if (containers == null) {
351             containers = new CopyOnWriteArrayList<String>();
352         }
353         boolean updateMap = false;
354         switch (t) {
355         case ADDED:
356             if (!containers.contains(containerName)) {
357                 containers.add(containerName);
358                 updateMap = true;
359             }
360             break;
361         case REMOVED:
362             if (containers.contains(containerName)) {
363                 containers.remove(containerName);
364                 updateMap = true;
365             }
366             break;
367         case CHANGED:
368             break;
369         }
370         if (updateMap) {
371             if (containers.isEmpty()) {
372                 // Do cleanup to reduce memory footprint if no
373                 // elements to be tracked
374                 this.nc2Container.remove(p);
375             } else {
376                 this.nc2Container.put(p, containers);
377             }
378         }
379     }
380
381     @Override
382     public void containerModeUpdated(UpdateType t) {
383         // do nothing
384     }
385
386     @Override
387     public void updateNode(Node node, UpdateType type, Set<Property> props) {
388         switch (type) {
389         case ADDED:
390             addNode(node, props);
391             break;
392         case REMOVED:
393             removeNode(node);
394             break;
395         default:
396             break;
397         }
398     }
399
400     @Override
401     public void updateNodeConnector(NodeConnector nodeConnector,
402             UpdateType type, Set<Property> props) {
403         // do nothing
404     }
405 }