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