Redirecting Caught and Uncaught Exceptions to OSGI Console and Log File
[controller.git] / opendaylight / protocol_plugins / openflow / src / main / java / org / opendaylight / controller / protocol_plugin / openflow / internal / InventoryServiceShim.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.Date;
13 import java.util.HashSet;
14 import java.util.List;
15 import java.util.Map;
16 import java.util.Set;
17 import java.util.concurrent.ConcurrentHashMap;
18 import java.util.concurrent.ConcurrentMap;
19 import java.util.concurrent.CopyOnWriteArrayList;
20
21 import org.opendaylight.controller.protocol_plugin.openflow.IInventoryShimExternalListener;
22 import org.opendaylight.controller.protocol_plugin.openflow.IInventoryShimInternalListener;
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.protocol_plugin.openflow.core.ISwitchStateListener;
27 import org.opendaylight.controller.sal.core.Actions;
28 import org.opendaylight.controller.sal.core.Buffers;
29 import org.opendaylight.controller.sal.core.Capabilities;
30 import org.opendaylight.controller.sal.core.ConstructionException;
31 import org.opendaylight.controller.sal.core.ContainerFlow;
32 import org.opendaylight.controller.sal.core.IContainerListener;
33 import org.opendaylight.controller.sal.core.Node;
34 import org.opendaylight.controller.sal.core.Node.NodeIDType;
35 import org.opendaylight.controller.sal.core.NodeConnector;
36 import org.opendaylight.controller.sal.core.Property;
37 import org.opendaylight.controller.sal.core.Tables;
38 import org.opendaylight.controller.sal.core.TimeStamp;
39 import org.opendaylight.controller.sal.core.UpdateType;
40 import org.opendaylight.controller.sal.utils.GlobalConstants;
41 import org.openflow.protocol.OFMessage;
42 import org.openflow.protocol.OFPortStatus;
43 import org.openflow.protocol.OFPortStatus.OFPortReason;
44 import org.openflow.protocol.OFType;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 /**
49  * The class describes a shim layer that bridges inventory events from Openflow
50  * core to various listeners. The notifications are filtered based on container
51  * configurations.
52  *
53  *
54  */
55 public class InventoryServiceShim implements IContainerListener,
56         IMessageListener, ISwitchStateListener {
57     protected static final Logger logger = LoggerFactory
58             .getLogger(InventoryServiceShim.class);
59     private IController controller = null;
60     private ConcurrentMap<String, IInventoryShimInternalListener> inventoryShimInternalListeners = new ConcurrentHashMap<String, IInventoryShimInternalListener>();
61     private List<IInventoryShimExternalListener> inventoryShimExternalListeners = new CopyOnWriteArrayList<IInventoryShimExternalListener>();
62     private ConcurrentMap<NodeConnector, List<String>> containerMap = new ConcurrentHashMap<NodeConnector, List<String>>();
63
64     void setController(IController s) {
65         this.controller = s;
66     }
67
68     void unsetController(IController s) {
69         if (this.controller == s) {
70             this.controller = null;
71         }
72     }
73
74     void setInventoryShimInternalListener(Map<?, ?> props,
75             IInventoryShimInternalListener s) {
76         if (props == null) {
77             logger.error("Didn't receive the service properties");
78             return;
79         }
80         String containerName = (String) props.get("containerName");
81         if (containerName == null) {
82             logger.error("containerName not supplied");
83             return;
84         }
85         if ((this.inventoryShimInternalListeners != null)
86                 && !this.inventoryShimInternalListeners.containsValue(s)) {
87             this.inventoryShimInternalListeners.put(containerName, s);
88             logger.trace("Added inventoryShimInternalListener for container:"
89                     + containerName);
90         }
91     }
92
93     void unsetInventoryShimInternalListener(Map<?, ?> props,
94             IInventoryShimInternalListener s) {
95         if (props == null) {
96             logger.error("Didn't receive the service properties");
97             return;
98         }
99         String containerName = (String) props.get("containerName");
100         if (containerName == null) {
101             logger.error("containerName not supplied");
102             return;
103         }
104         if ((this.inventoryShimInternalListeners != null)
105                 && this.inventoryShimInternalListeners
106                         .get(containerName) != null
107                 && this.inventoryShimInternalListeners
108                         .get(containerName).equals(s)) {
109             this.inventoryShimInternalListeners.remove(containerName);
110             logger
111                     .trace("Removed inventoryShimInternalListener for container: "
112                             + containerName);
113         }
114     }
115
116     void setInventoryShimExternalListener(IInventoryShimExternalListener s) {
117         logger.trace("Set inventoryShimExternalListener");
118         if ((this.inventoryShimExternalListeners != null)
119                 && !this.inventoryShimExternalListeners.contains(s)) {
120             this.inventoryShimExternalListeners.add(s);
121         }
122     }
123
124     void unsetInventoryShimExternalListener(IInventoryShimExternalListener s) {
125         if ((this.inventoryShimExternalListeners != null)
126                 && this.inventoryShimExternalListeners.contains(s)) {
127             this.inventoryShimExternalListeners.remove(s);
128         }
129     }
130
131     /**
132      * Function called by the dependency manager when all the required
133      * dependencies are satisfied
134      *
135      */
136     void init() {
137         this.controller.addMessageListener(OFType.PORT_STATUS, this);
138         this.controller.addSwitchStateListener(this);
139     }
140
141     /**
142      * Function called after registering the
143      * service in OSGi service registry.
144      */
145     void started() {
146         /* Start with existing switches */
147         startService();
148     }
149
150     /**
151      * Function called by the dependency manager when at least one
152      * dependency become unsatisfied or when the component is shutting
153      * down because for example bundle is being stopped.
154      *
155      */
156     void destroy() {
157         this.controller.removeMessageListener(OFType.PACKET_IN, this);
158         this.controller.removeSwitchStateListener(this);
159
160         this.inventoryShimInternalListeners.clear();
161         this.containerMap.clear();
162         this.controller = null;
163     }
164
165     @Override
166     public void receive(ISwitch sw, OFMessage msg) {
167         try {
168             if (msg instanceof OFPortStatus) {
169                 handlePortStatusMessage(sw, (OFPortStatus) msg);
170             }
171         } catch (ConstructionException e) {
172             logger.error("",e);
173         }
174         return;
175     }
176
177     protected void handlePortStatusMessage(ISwitch sw, OFPortStatus m)
178             throws ConstructionException {
179         Node node = new Node(NodeIDType.OPENFLOW, sw.getId());
180         NodeConnector nodeConnector = PortConverter.toNodeConnector(m.getDesc()
181                 .getPortNumber(), node);
182         UpdateType type = null;
183
184         if (m.getReason() == (byte) OFPortReason.OFPPR_ADD.ordinal()) {
185             type = UpdateType.ADDED;
186         } else if (m.getReason() == (byte) OFPortReason.OFPPR_DELETE.ordinal()) {
187             type = UpdateType.REMOVED;
188         } else if (m.getReason() == (byte) OFPortReason.OFPPR_MODIFY.ordinal()) {
189             type = UpdateType.CHANGED;
190         }
191
192         if (type != null) {
193             // get node connector properties
194             Set<Property> props = InventoryServiceHelper.OFPortToProps(m
195                     .getDesc());
196             notifyInventoryShimListener(nodeConnector, type, props);
197         }
198     }
199
200     @Override
201     public void switchAdded(ISwitch sw) {
202         if (sw == null)
203             return;
204
205         // Add all the nodeConnectors of this switch
206         Map<NodeConnector, Set<Property>> ncProps = InventoryServiceHelper
207                 .OFSwitchToProps(sw);
208         for (Map.Entry<NodeConnector, Set<Property>> entry : ncProps.entrySet()) {
209             notifyInventoryShimListener(entry.getKey(), UpdateType.ADDED, entry
210                     .getValue());
211         }
212
213         // Add this node
214         addNode(sw);
215     }
216
217     @Override
218     public void switchDeleted(ISwitch sw) {
219         if (sw == null)
220             return;
221
222         removeNode(sw);
223     }
224
225     @Override
226     public void containerModeUpdated(UpdateType t) {
227         // do nothing
228     }
229
230     @Override
231     public void tagUpdated(String containerName, Node n, short oldTag,
232             short newTag, UpdateType t) {
233     }
234
235     @Override
236     public void containerFlowUpdated(String containerName,
237             ContainerFlow previousFlow, ContainerFlow currentFlow, UpdateType t) {
238     }
239
240     @Override
241     public void nodeConnectorUpdated(String containerName, NodeConnector p,
242             UpdateType t) {
243         if (this.containerMap == null) {
244             logger.error("containerMap is NULL");
245             return;
246         }
247         List<String> containers = this.containerMap.get(p);
248         if (containers == null) {
249             containers = new CopyOnWriteArrayList<String>();
250         }
251         boolean updateMap = false;
252         switch (t) {
253         case ADDED:
254             if (!containers.contains(containerName)) {
255                 containers.add(containerName);
256                 updateMap = true;
257             }
258             break;
259         case REMOVED:
260             if (containers.contains(containerName)) {
261                 containers.remove(containerName);
262                 updateMap = true;
263             }
264             break;
265         case CHANGED:
266             break;
267         }
268         if (updateMap) {
269             if (containers.isEmpty()) {
270                 // Do cleanup to reduce memory footprint if no
271                 // elements to be tracked
272                 this.containerMap.remove(p);
273             } else {
274                 this.containerMap.put(p, containers);
275             }
276         }
277
278         // notify InventoryService
279         notifyInventoryShimInternalListener(containerName, p, t, null);
280     }
281
282     private void notifyInventoryShimExternalListener(Node node,
283             UpdateType type, Set<Property> props) {
284         for (IInventoryShimExternalListener s : this.inventoryShimExternalListeners) {
285             s.updateNode(node, type, props);
286         }
287     }
288
289     private void notifyInventoryShimExternalListener(
290             NodeConnector nodeConnector, UpdateType type, Set<Property> props) {
291         for (IInventoryShimExternalListener s : this.inventoryShimExternalListeners) {
292             s.updateNodeConnector(nodeConnector, type, props);
293         }
294     }
295
296     private void notifyInventoryShimInternalListener(String container,
297             NodeConnector nodeConnector, UpdateType type, Set<Property> props) {
298         IInventoryShimInternalListener inventoryShimInternalListener = inventoryShimInternalListeners
299                 .get(container);
300         if (inventoryShimInternalListener != null) {
301             inventoryShimInternalListener.updateNodeConnector(nodeConnector,
302                     type, props);
303             logger.trace(type + " " + nodeConnector + " on container "
304                     + container);
305         }
306     }
307
308     /*
309      *  Notify all internal and external listeners
310      */
311     private void notifyInventoryShimListener(NodeConnector nodeConnector,
312             UpdateType type, Set<Property> props) {
313         // Always notify default InventoryService. Store properties in default one.
314         notifyInventoryShimInternalListener(GlobalConstants.DEFAULT.toString(),
315                 nodeConnector, type, props);
316
317         // Now notify other containers
318         List<String> containers = containerMap.get(nodeConnector);
319         if (containers != null) {
320             for (String container : containers) {
321                 // no property stored in container components.
322                 notifyInventoryShimInternalListener(container, nodeConnector,
323                         type, null);
324             }
325         }
326
327         // Notify DiscoveryService
328         notifyInventoryShimExternalListener(nodeConnector, type, props);
329     }
330
331     /*
332      *  Notify all internal and external listeners
333      */
334     private void notifyInventoryShimListener(Node node, UpdateType type,
335             Set<Property> props) {
336         switch (type) {
337         case ADDED:
338             // Notify only the default Inventory Service
339             IInventoryShimInternalListener inventoryShimDefaultListener = inventoryShimInternalListeners
340                     .get(GlobalConstants.DEFAULT.toString());
341             if (inventoryShimDefaultListener != null) {
342                 inventoryShimDefaultListener.updateNode(node, type, props);
343             }
344             break;
345         case REMOVED:
346             // Notify all Inventory Service containers
347             for (IInventoryShimInternalListener inventoryShimInternalListener : inventoryShimInternalListeners
348                     .values()) {
349                 inventoryShimInternalListener.updateNode(node, type, null);
350             }
351             break;
352         default:
353             break;
354         }
355
356         // Notify external listener
357         notifyInventoryShimExternalListener(node, type, props);
358     }
359
360     private void addNode(ISwitch sw) {
361         Node node;
362         try {
363             node = new Node(NodeIDType.OPENFLOW, sw.getId());
364         } catch (ConstructionException e) {
365             logger.error("{}", e.getMessage());
366             return;
367         }
368
369         UpdateType type = UpdateType.ADDED;
370
371         Set<Property> props = new HashSet<Property>();
372         Long sid = (Long) node.getID();
373
374         Date connectedSince = controller.getSwitches().get(sid)
375                 .getConnectedDate();
376         Long connectedSinceTime = (connectedSince == null) ? 0 : connectedSince
377                 .getTime();
378         props.add(new TimeStamp(connectedSinceTime, "connectedSince"));
379
380         byte tables = sw.getTables();
381         Tables t = new Tables(tables);
382         if (t != null) {
383                 props.add(t);
384         }
385         int cap = sw.getCapabilities();
386         Capabilities c = new Capabilities(cap);
387         if (c != null) {
388                 props.add(c);
389         }
390         int act = sw.getActions();
391         Actions a = new Actions(act);
392         if (a != null) {
393                 props.add(a);
394         }
395         int buffers = sw.getBuffers();
396         Buffers b = new Buffers(buffers);
397         if (b != null) {
398                 props.add(b);
399         }
400         // Notify all internal and external listeners
401         notifyInventoryShimListener(node, type, props);
402     }
403
404     private void removeNode(ISwitch sw) {
405         Node node;
406         try {
407             node = new Node(NodeIDType.OPENFLOW, sw.getId());
408         } catch (ConstructionException e) {
409             logger.error("{}", e.getMessage());
410             return;
411         }
412
413         UpdateType type = UpdateType.REMOVED;
414
415         // Notify all internal and external listeners
416         notifyInventoryShimListener(node, type, null);
417     }
418
419     private void startService() {
420         // Get a snapshot of all the existing switches
421         Map<Long, ISwitch> switches = this.controller.getSwitches();
422         for (ISwitch sw : switches.values()) {
423             switchAdded(sw);
424         }
425     }
426 }