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