Merge "Fixed publishDataChangeEvent in 2phase commit"
[controller.git] / opendaylight / topologymanager / implementation / src / main / java / org / opendaylight / controller / topologymanager / internal / TopologyManagerImpl.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.topologymanager.internal;
10
11 import java.io.FileNotFoundException;
12 import java.io.IOException;
13 import java.io.ObjectInputStream;
14 import java.util.ArrayList;
15 import java.util.Dictionary;
16 import java.util.EnumSet;
17 import java.util.HashMap;
18 import java.util.HashSet;
19 import java.util.Iterator;
20 import java.util.LinkedList;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.Set;
24 import java.util.concurrent.BlockingQueue;
25 import java.util.concurrent.ConcurrentHashMap;
26 import java.util.concurrent.ConcurrentMap;
27 import java.util.concurrent.CopyOnWriteArraySet;
28 import java.util.concurrent.LinkedBlockingQueue;
29
30 import org.apache.commons.lang3.tuple.ImmutablePair;
31 import org.apache.felix.dm.Component;
32 import org.eclipse.osgi.framework.console.CommandInterpreter;
33 import org.eclipse.osgi.framework.console.CommandProvider;
34 import org.opendaylight.controller.clustering.services.CacheConfigException;
35 import org.opendaylight.controller.clustering.services.CacheExistException;
36 import org.opendaylight.controller.clustering.services.ICacheUpdateAware;
37 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
38 import org.opendaylight.controller.clustering.services.IClusterServices;
39 import org.opendaylight.controller.configuration.ConfigurationObject;
40 import org.opendaylight.controller.configuration.IConfigurationContainerAware;
41 import org.opendaylight.controller.configuration.IConfigurationContainerService;
42 import org.opendaylight.controller.sal.core.Edge;
43 import org.opendaylight.controller.sal.core.Host;
44 import org.opendaylight.controller.sal.core.Node;
45 import org.opendaylight.controller.sal.core.NodeConnector;
46 import org.opendaylight.controller.sal.core.Property;
47 import org.opendaylight.controller.sal.core.TimeStamp;
48 import org.opendaylight.controller.sal.core.UpdateType;
49 import org.opendaylight.controller.sal.topology.IListenTopoUpdates;
50 import org.opendaylight.controller.sal.topology.ITopologyService;
51 import org.opendaylight.controller.sal.topology.TopoEdgeUpdate;
52 import org.opendaylight.controller.sal.utils.IObjectReader;
53 import org.opendaylight.controller.sal.utils.NodeConnectorCreator;
54 import org.opendaylight.controller.sal.utils.Status;
55 import org.opendaylight.controller.sal.utils.StatusCode;
56 import org.opendaylight.controller.switchmanager.ISwitchManager;
57 import org.opendaylight.controller.topologymanager.ITopologyManager;
58 import org.opendaylight.controller.topologymanager.ITopologyManagerAware;
59 import org.opendaylight.controller.topologymanager.ITopologyManagerClusterWideAware;
60 import org.opendaylight.controller.topologymanager.TopologyUserLinkConfig;
61 import org.osgi.framework.BundleContext;
62 import org.osgi.framework.FrameworkUtil;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
65
66 /**
67  * The class describes TopologyManager which is the central repository of the
68  * network topology. It provides service for applications to interact with
69  * topology database and notifies all the listeners of topology changes.
70  */
71 public class TopologyManagerImpl implements
72         ICacheUpdateAware<Object, Object>,
73         ITopologyManager,
74         IConfigurationContainerAware,
75         IListenTopoUpdates,
76         IObjectReader,
77         CommandProvider {
78     protected static final String TOPOEDGESDB = "topologymanager.edgesDB";
79     protected static final String TOPOHOSTSDB = "topologymanager.hostsDB";
80     protected static final String TOPONODECONNECTORDB = "topologymanager.nodeConnectorDB";
81     protected static final String TOPOUSERLINKSDB = "topologymanager.userLinksDB";
82     private static final String USER_LINKS_FILE_NAME = "userTopology.conf";
83     private static final Logger log = LoggerFactory.getLogger(TopologyManagerImpl.class);
84     private ITopologyService topoService;
85     private IClusterContainerServices clusterContainerService;
86     private IConfigurationContainerService configurationService;
87     private ISwitchManager switchManager;
88     // DB of all the Edges with properties which constitute our topology
89     private ConcurrentMap<Edge, Set<Property>> edgesDB;
90     // DB of all NodeConnector which are part of ISL Edges, meaning they
91     // are connected to another NodeConnector on the other side of an ISL link.
92     // NodeConnector of a Production Edge is not part of this DB.
93     private ConcurrentMap<NodeConnector, Set<Property>> nodeConnectorsDB;
94     // DB of all the NodeConnectors with an Host attached to it
95     private ConcurrentMap<NodeConnector, Set<ImmutablePair<Host, Set<Property>>>> hostsDB;
96     // Topology Manager Aware listeners
97     private Set<ITopologyManagerAware> topologyManagerAware = new CopyOnWriteArraySet<ITopologyManagerAware>();
98     // Topology Manager Aware listeners - for clusterwide updates
99     private Set<ITopologyManagerClusterWideAware> topologyManagerClusterWideAware =
100             new CopyOnWriteArraySet<ITopologyManagerClusterWideAware>();
101     private ConcurrentMap<String, TopologyUserLinkConfig> userLinksDB;
102     private BlockingQueue<TopoEdgeUpdate> notifyQ = new LinkedBlockingQueue<TopoEdgeUpdate>();
103     private volatile Boolean shuttingDown = false;
104     private Thread notifyThread;
105
106
107     void nonClusterObjectCreate() {
108         edgesDB = new ConcurrentHashMap<Edge, Set<Property>>();
109         hostsDB = new ConcurrentHashMap<NodeConnector, Set<ImmutablePair<Host, Set<Property>>>>();
110         nodeConnectorsDB = new ConcurrentHashMap<NodeConnector, Set<Property>>();
111         userLinksDB = new ConcurrentHashMap<String, TopologyUserLinkConfig>();
112     }
113
114     void setTopologyManagerAware(ITopologyManagerAware s) {
115         if (this.topologyManagerAware != null) {
116             log.debug("Adding ITopologyManagerAware: {}", s);
117             this.topologyManagerAware.add(s);
118         }
119     }
120
121     void unsetTopologyManagerAware(ITopologyManagerAware s) {
122         if (this.topologyManagerAware != null) {
123             log.debug("Removing ITopologyManagerAware: {}", s);
124             this.topologyManagerAware.remove(s);
125         }
126     }
127
128     void setTopologyManagerClusterWideAware(ITopologyManagerClusterWideAware s) {
129         if (this.topologyManagerClusterWideAware != null) {
130             log.debug("Adding ITopologyManagerClusterWideAware: {}", s);
131             this.topologyManagerClusterWideAware.add(s);
132         }
133     }
134
135     void unsetTopologyManagerClusterWideAware(ITopologyManagerClusterWideAware s) {
136         if (this.topologyManagerClusterWideAware != null) {
137             log.debug("Removing ITopologyManagerClusterWideAware: {}", s);
138             this.topologyManagerClusterWideAware.remove(s);
139         }
140     }
141
142     void setTopoService(ITopologyService s) {
143         log.debug("Adding ITopologyService: {}", s);
144         this.topoService = s;
145     }
146
147     void unsetTopoService(ITopologyService s) {
148         if (this.topoService == s) {
149             log.debug("Removing ITopologyService: {}", s);
150             this.topoService = null;
151         }
152     }
153
154     void setClusterContainerService(IClusterContainerServices s) {
155         log.debug("Cluster Service set");
156         this.clusterContainerService = s;
157     }
158
159     void unsetClusterContainerService(IClusterContainerServices s) {
160         if (this.clusterContainerService == s) {
161             log.debug("Cluster Service removed!");
162             this.clusterContainerService = null;
163         }
164     }
165
166     public void setConfigurationContainerService(IConfigurationContainerService service) {
167         log.trace("Got configuration service set request {}", service);
168         this.configurationService = service;
169     }
170
171     public void unsetConfigurationContainerService(IConfigurationContainerService service) {
172         log.trace("Got configuration service UNset request");
173         this.configurationService = null;
174     }
175
176     void setSwitchManager(ISwitchManager s) {
177         log.debug("Adding ISwitchManager: {}", s);
178         this.switchManager = s;
179     }
180
181     void unsetSwitchManager(ISwitchManager s) {
182         if (this.switchManager == s) {
183             log.debug("Removing ISwitchManager: {}", s);
184             this.switchManager = null;
185         }
186     }
187
188     /**
189      * Function called by the dependency manager when all the required
190      * dependencies are satisfied
191      *
192      */
193     void init(Component c) {
194         allocateCaches();
195         retrieveCaches();
196         String containerName = null;
197         Dictionary<?, ?> props = c.getServiceProperties();
198         if (props != null) {
199             containerName = (String) props.get("containerName");
200         } else {
201             // In the Global instance case the containerName is empty
202             containerName = "UNKNOWN";
203         }
204
205         registerWithOSGIConsole();
206         loadConfiguration();
207
208         // Restore the shuttingDown status on init of the component
209         shuttingDown = false;
210         notifyThread = new Thread(new TopologyNotify(notifyQ));
211     }
212
213     @SuppressWarnings({ "unchecked" })
214     private void allocateCaches() {
215             this.edgesDB =
216                     (ConcurrentMap<Edge, Set<Property>>) allocateCache(TOPOEDGESDB,EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
217
218             this.hostsDB =
219                     (ConcurrentMap<NodeConnector, Set<ImmutablePair<Host, Set<Property>>>>) allocateCache(TOPOHOSTSDB, EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
220
221             this.nodeConnectorsDB =
222                     (ConcurrentMap<NodeConnector, Set<Property>>) allocateCache(
223                             TOPONODECONNECTORDB, EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
224             this.userLinksDB =
225                     (ConcurrentMap<String, TopologyUserLinkConfig>) allocateCache(
226                             TOPOUSERLINKSDB, EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
227     }
228
229     private ConcurrentMap<?, ?> allocateCache(String cacheName, Set<IClusterServices.cacheMode> cacheModes) {
230         ConcurrentMap<?, ?> cache = null;
231         try {
232             cache = this.clusterContainerService.createCache(cacheName, cacheModes);
233         } catch (CacheExistException e) {
234             log.debug(cacheName + " cache already exists - destroy and recreate if needed");
235         } catch (CacheConfigException e) {
236             log.error(cacheName + " cache configuration invalid - check cache mode");
237         }
238         return cache;
239     }
240
241     @SuppressWarnings({ "unchecked" })
242     private void retrieveCaches() {
243         if (this.clusterContainerService == null) {
244             log.error("Cluster Services is null, can't retrieve caches.");
245             return;
246         }
247
248         this.edgesDB = (ConcurrentMap<Edge, Set<Property>>) this.clusterContainerService.getCache(TOPOEDGESDB);
249         if (edgesDB == null) {
250             log.error("Failed to get cache for " + TOPOEDGESDB);
251         }
252
253         this.hostsDB =
254                 (ConcurrentMap<NodeConnector, Set<ImmutablePair<Host, Set<Property>>>>) this.clusterContainerService.getCache(TOPOHOSTSDB);
255         if (hostsDB == null) {
256             log.error("Failed to get cache for " + TOPOHOSTSDB);
257         }
258
259         this.nodeConnectorsDB =
260                 (ConcurrentMap<NodeConnector, Set<Property>>) this.clusterContainerService.getCache(TOPONODECONNECTORDB);
261         if (nodeConnectorsDB == null) {
262             log.error("Failed to get cache for " + TOPONODECONNECTORDB);
263         }
264
265         this.userLinksDB =
266                 (ConcurrentMap<String, TopologyUserLinkConfig>) this.clusterContainerService.getCache(TOPOUSERLINKSDB);
267         if (userLinksDB == null) {
268             log.error("Failed to get cache for " + TOPOUSERLINKSDB);
269         }
270     }
271
272     /**
273      * Function called after the topology manager has registered the service in
274      * OSGi service registry.
275      *
276      */
277     void started() {
278         // Start the batcher thread for the cluster wide topology updates
279         notifyThread.start();
280         // SollicitRefresh MUST be called here else if called at init
281         // time it may sollicit refresh too soon.
282         log.debug("Sollicit topology refresh");
283         topoService.sollicitRefresh();
284     }
285
286     void stop() {
287         shuttingDown = true;
288         notifyThread.interrupt();
289     }
290
291     /**
292      * Function called by the dependency manager when at least one dependency
293      * become unsatisfied or when the component is shutting down because for
294      * example bundle is being stopped.
295      *
296      */
297     void destroy() {
298         notifyQ.clear();
299         notifyThread = null;
300     }
301
302     private void loadConfiguration() {
303         for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, USER_LINKS_FILE_NAME)) {
304             addUserLink((TopologyUserLinkConfig) conf);
305         }
306     }
307
308     @Override
309     public Status saveConfig() {
310         return saveConfigInternal();
311     }
312
313     public Status saveConfigInternal() {
314         Status saveStatus = configurationService.persistConfiguration(
315                 new ArrayList<ConfigurationObject>(userLinksDB.values()), USER_LINKS_FILE_NAME);
316
317         if (!saveStatus.isSuccess()) {
318             return new Status(StatusCode.INTERNALERROR, "Topology save failed: " + saveStatus.getDescription());
319         }
320         return saveStatus;
321     }
322
323     @Override
324     public Map<Node, Set<Edge>> getNodeEdges() {
325         if (this.edgesDB == null) {
326             return null;
327         }
328
329         Map<Node, Set<Edge>> res = new HashMap<Node, Set<Edge>>();
330         for (Edge edge : this.edgesDB.keySet()) {
331             // Lets analyze the tail
332             Node node = edge.getTailNodeConnector().getNode();
333             Set<Edge> nodeEdges = res.get(node);
334             if (nodeEdges == null) {
335                 nodeEdges = new HashSet<Edge>();
336                 res.put(node, nodeEdges);
337             }
338             nodeEdges.add(edge);
339
340             // Lets analyze the head
341             node = edge.getHeadNodeConnector().getNode();
342             nodeEdges = res.get(node);
343             if (nodeEdges == null) {
344                 nodeEdges = new HashSet<Edge>();
345                 res.put(node, nodeEdges);
346             }
347             nodeEdges.add(edge);
348         }
349
350         return res;
351     }
352
353     @Override
354     public boolean isInternal(NodeConnector p) {
355         if (this.nodeConnectorsDB == null) {
356             return false;
357         }
358
359         // This is an internal NodeConnector if is connected to
360         // another Node i.e it's part of the nodeConnectorsDB
361         return (this.nodeConnectorsDB.get(p) != null);
362     }
363
364     /**
365      * This method returns true if the edge is an ISL link.
366      *
367      * @param e
368      *            The edge
369      * @return true if it is an ISL link
370      */
371     public boolean isISLink(Edge e) {
372         return (!isProductionLink(e));
373     }
374
375     /**
376      * This method returns true if the edge is a production link.
377      *
378      * @param e
379      *            The edge
380      * @return true if it is a production link
381      */
382     public boolean isProductionLink(Edge e) {
383         return (e.getHeadNodeConnector().getType().equals(NodeConnector.NodeConnectorIDType.PRODUCTION)
384                 || e.getTailNodeConnector().getType().equals(NodeConnector.NodeConnectorIDType.PRODUCTION));
385     }
386
387     /**
388      * This method cross checks the determination of nodeConnector type by Discovery Service
389      * against the information in SwitchManager and updates it accordingly.
390      * @param e
391      *          The edge
392      */
393     private void crossCheckNodeConnectors(Edge e) {
394         NodeConnector nc;
395         if (e.getHeadNodeConnector().getType().equals(NodeConnector.NodeConnectorIDType.PRODUCTION)) {
396             nc = updateNCTypeFromSwitchMgr(e.getHeadNodeConnector());
397             if (nc != null) {
398                 e.setHeadNodeConnector(nc);
399             }
400         }
401         if (e.getTailNodeConnector().getType().equals(NodeConnector.NodeConnectorIDType.PRODUCTION)) {
402             nc = updateNCTypeFromSwitchMgr(e.getTailNodeConnector());
403             if (nc != null) {
404                 e.setTailNodeConnector(nc);
405             }
406         }
407     }
408
409     /**
410      * A NodeConnector may have been categorized as of type Production by Discovery Service.
411      * But at the time when this determination was made, only OF nodes were known to Discovery
412      * Service. This method checks if the node of nodeConnector is known to SwitchManager. If
413      * so, then it returns a new NodeConnector with correct type.
414      *
415      * @param nc
416      *       NodeConnector as passed on in the edge
417      * @return
418      *       If Node of the NodeConnector is in SwitchManager, then return a new NodeConnector
419      *       with correct type, null otherwise
420      */
421
422     private NodeConnector updateNCTypeFromSwitchMgr(NodeConnector nc) {
423
424         for (Node node : switchManager.getNodes()) {
425             String nodeName = node.getNodeIDString();
426             log.trace("Switch Manager Node Name: {}, NodeConnector Node Name: {}", nodeName,
427                     nc.getNode().getNodeIDString());
428             if (nodeName.equals(nc.getNode().getNodeIDString())) {
429                 NodeConnector nodeConnector = NodeConnectorCreator
430                         .createNodeConnector(node.getType(), nc.getID(), node);
431                 return nodeConnector;
432             }
433         }
434         return null;
435     }
436
437     /**
438      * The Map returned is a copy of the current topology hence if the topology
439      * changes the copy doesn't
440      *
441      * @return A Map representing the current topology expressed as edges of the
442      *         network
443      */
444     @Override
445     public Map<Edge, Set<Property>> getEdges() {
446         if (this.edgesDB == null) {
447             return null;
448         }
449
450         Map<Edge, Set<Property>> edgeMap = new HashMap<Edge, Set<Property>>();
451         Set<Property> props;
452         for (Map.Entry<Edge, Set<Property>> edgeEntry : edgesDB.entrySet()) {
453             // Sets of props are copied because the composition of
454             // those properties could change with time
455             props = new HashSet<Property>(edgeEntry.getValue());
456             // We can simply reuse the key because the object is
457             // immutable so doesn't really matter that we are
458             // referencing the only owned by a different table, the
459             // meaning is the same because doesn't change with time.
460             edgeMap.put(edgeEntry.getKey(), props);
461         }
462
463         return edgeMap;
464     }
465
466     @Override
467     public Set<NodeConnector> getNodeConnectorWithHost() {
468         if (this.hostsDB == null) {
469             return null;
470         }
471
472         return (new HashSet<NodeConnector>(this.hostsDB.keySet()));
473     }
474
475     @Override
476     public Map<Node, Set<NodeConnector>> getNodesWithNodeConnectorHost() {
477         if (this.hostsDB == null) {
478             return null;
479         }
480         HashMap<Node, Set<NodeConnector>> res = new HashMap<Node, Set<NodeConnector>>();
481         Node node;
482         Set<NodeConnector> portSet;
483         for (NodeConnector nc : this.hostsDB.keySet()) {
484             node = nc.getNode();
485             portSet = res.get(node);
486             if (portSet == null) {
487                 // Create the HashSet if null
488                 portSet = new HashSet<NodeConnector>();
489                 res.put(node, portSet);
490             }
491
492             // Keep updating the HashSet, given this is not a
493             // clustered map we can just update the set without
494             // worrying to update the hashmap.
495             portSet.add(nc);
496         }
497
498         return (res);
499     }
500
501     @Override
502     public Host getHostAttachedToNodeConnector(NodeConnector port) {
503         List<Host> hosts = getHostsAttachedToNodeConnector(port);
504         if(hosts != null && !hosts.isEmpty()){
505             return hosts.get(0);
506         }
507         return null;
508     }
509
510     @Override
511     public List<Host> getHostsAttachedToNodeConnector(NodeConnector p) {
512         Set<ImmutablePair<Host, Set<Property>>> hosts;
513         if (this.hostsDB == null || (hosts = this.hostsDB.get(p)) == null) {
514             return null;
515         }
516         // create a list of hosts
517         List<Host> retHosts = new LinkedList<Host>();
518         for(ImmutablePair<Host, Set<Property>> host : hosts) {
519             retHosts.add(host.getLeft());
520         }
521         return retHosts;
522     }
523
524     @Override
525     public synchronized void updateHostLink(NodeConnector port, Host h, UpdateType t, Set<Property> props) {
526
527         // Clone the property set in case non null else just
528         // create an empty one. Caches allocated via infinispan
529         // don't allow null values
530         if (props == null) {
531             props = new HashSet<Property>();
532         } else {
533             props = new HashSet<Property>(props);
534         }
535         ImmutablePair<Host, Set<Property>> thisHost = new ImmutablePair<Host, Set<Property>>(h, props);
536
537         // get the host list
538         Set<ImmutablePair<Host, Set<Property>>> hostSet = this.hostsDB.get(port);
539         if(hostSet == null) {
540             hostSet = new HashSet<ImmutablePair<Host, Set<Property>>>();
541         }
542         switch (t) {
543         case ADDED:
544         case CHANGED:
545             hostSet.add(thisHost);
546             this.hostsDB.put(port, hostSet);
547             break;
548         case REMOVED:
549             hostSet.remove(thisHost);
550             if(hostSet.isEmpty()) {
551                 //remove only if hasn't been concurrently modified
552                 this.hostsDB.remove(port, hostSet);
553             } else {
554                 this.hostsDB.put(port, hostSet);
555             }
556             break;
557         }
558     }
559
560     private boolean headNodeConnectorExist(Edge e) {
561         /*
562          * Only check the head end point which is supposed to be part of a
563          * network node we control (present in our inventory). If we checked the
564          * tail end point as well, we would not store the edges that connect to
565          * a non sdn enable port on a non sdn capable production switch. We want
566          * to be able to see these switches on the topology.
567          */
568         NodeConnector head = e.getHeadNodeConnector();
569         return (switchManager.doesNodeConnectorExist(head));
570     }
571
572     private TopoEdgeUpdate edgeUpdate(Edge e, UpdateType type, Set<Property> props) {
573         switch (type) {
574         case ADDED:
575
576             // Make sure the props are non-null or create a copy
577             if (props == null) {
578                 props = new HashSet<Property>();
579             } else {
580                 props = new HashSet<Property>(props);
581             }
582
583             Set<Property> currentProps = this.edgesDB.get(e);
584             if (currentProps != null) {
585
586                 if (currentProps.equals(props)) {
587                     // Avoid redundant updates as notifications trigger expensive tasks
588                     log.trace("Skipping redundant edge addition: {}", e);
589                     return null;
590                 }
591
592                 // In case of node switch-over to a different cluster controller,
593                 // let's retain edge props (e.g. creation time)
594                 props.addAll(currentProps);
595             }
596
597             // Ensure that head node connector exists
598             if (!headNodeConnectorExist(e)) {
599                 log.warn("Ignore edge that contains invalid node connector: {}", e);
600                 return null;
601             }
602
603             // Check if nodeConnectors of the edge were correctly categorized
604             // by protocol plugin
605             crossCheckNodeConnectors(e);
606
607             // Now make sure there is the creation timestamp for the
608             // edge, if not there, stamp with the first update
609             boolean found_create = false;
610             for (Property prop : props) {
611                 if (prop instanceof TimeStamp) {
612                     TimeStamp t = (TimeStamp) prop;
613                     if (t.getTimeStampName().equals("creation")) {
614                         found_create = true;
615                         break;
616                     }
617                 }
618             }
619
620             if (!found_create) {
621                 TimeStamp t = new TimeStamp(System.currentTimeMillis(), "creation");
622                 props.add(t);
623             }
624
625             // Now add this in the database eventually overriding
626             // something that may have been already existing
627             this.edgesDB.put(e, props);
628
629             // Now populate the DB of NodeConnectors
630             // NOTE WELL: properties are empty sets, not really needed
631             // for now.
632             // The DB only contains ISL ports
633             if (isISLink(e)) {
634                 this.nodeConnectorsDB.put(e.getHeadNodeConnector(), new HashSet<Property>(1));
635                 this.nodeConnectorsDB.put(e.getTailNodeConnector(), new HashSet<Property>(1));
636             }
637             log.trace("Edge {}  {}", e.toString(), type.name());
638             break;
639         case REMOVED:
640             // Now remove the edge from edgesDB
641             this.edgesDB.remove(e);
642
643             // Now lets update the NodeConnectors DB, the assumption
644             // here is that two NodeConnector are exclusively
645             // connected by 1 and only 1 edge, this is reasonable in
646             // the same plug (virtual of phisical) we can assume two
647             // cables won't be plugged. This could break only in case
648             // of devices in the middle that acts as hubs, but it
649             // should be safe to assume that won't happen.
650             this.nodeConnectorsDB.remove(e.getHeadNodeConnector());
651             this.nodeConnectorsDB.remove(e.getTailNodeConnector());
652             log.trace("Edge {}  {}", e.toString(), type.name());
653             break;
654         case CHANGED:
655             Set<Property> oldProps = this.edgesDB.get(e);
656
657             // When property changes lets make sure we can change it
658             // all except the creation time stamp because that should
659             // be changed only when the edge is destroyed and created
660             // again
661             TimeStamp timeStamp = null;
662             for (Property prop : oldProps) {
663                 if (prop instanceof TimeStamp) {
664                     TimeStamp tsProp = (TimeStamp) prop;
665                     if (tsProp.getTimeStampName().equals("creation")) {
666                         timeStamp = tsProp;
667                         break;
668                     }
669                 }
670             }
671
672             // Now lets make sure new properties are non-null
673             if (props == null) {
674                 props = new HashSet<Property>();
675             } else {
676                 // Copy the set so noone is going to change the content
677                 props = new HashSet<Property>(props);
678             }
679
680             // Now lets remove the creation property if exist in the
681             // new props
682             for (Iterator<Property> i = props.iterator(); i.hasNext();) {
683                 Property prop = i.next();
684                 if (prop instanceof TimeStamp) {
685                     TimeStamp t = (TimeStamp) prop;
686                     if (t.getTimeStampName().equals("creation")) {
687                         i.remove();
688                         break;
689                     }
690                 }
691             }
692
693             // Now lets add the creation timestamp in it
694             if (timeStamp != null) {
695                 props.add(timeStamp);
696             }
697
698             // Finally update
699             this.edgesDB.put(e, props);
700             log.trace("Edge {}  {}", e.toString(), type.name());
701             break;
702         }
703         return new TopoEdgeUpdate(e, props, type);
704     }
705
706     @Override
707     public void edgeUpdate(List<TopoEdgeUpdate> topoedgeupdateList) {
708         List<TopoEdgeUpdate> teuList = new ArrayList<TopoEdgeUpdate>();
709         for (int i = 0; i < topoedgeupdateList.size(); i++) {
710             Edge e = topoedgeupdateList.get(i).getEdge();
711             Set<Property> p = topoedgeupdateList.get(i).getProperty();
712             UpdateType type = topoedgeupdateList.get(i).getUpdateType();
713             TopoEdgeUpdate teu = edgeUpdate(e, type, p);
714             if (teu != null) {
715                 teuList.add(teu);
716             }
717         }
718
719         if (!teuList.isEmpty()) {
720             // Now update the listeners
721             for (ITopologyManagerAware s : this.topologyManagerAware) {
722                 try {
723                     s.edgeUpdate(teuList);
724                 } catch (Exception exc) {
725                     log.error("Exception on edge update:", exc);
726                 }
727             }
728         }
729     }
730
731     private Edge getReverseLinkTuple(TopologyUserLinkConfig link) {
732         TopologyUserLinkConfig rLink = new TopologyUserLinkConfig(
733                 link.getName(), link.getDstNodeConnector(), link.getSrcNodeConnector());
734         return getLinkTuple(rLink);
735     }
736
737
738     private Edge getLinkTuple(TopologyUserLinkConfig link) {
739         NodeConnector srcNodeConnector = NodeConnector.fromString(link.getSrcNodeConnector());
740         NodeConnector dstNodeConnector = NodeConnector.fromString(link.getDstNodeConnector());
741         try {
742             return new Edge(srcNodeConnector, dstNodeConnector);
743         } catch (Exception e) {
744             return null;
745         }
746     }
747
748     @Override
749     public ConcurrentMap<String, TopologyUserLinkConfig> getUserLinks() {
750         return new ConcurrentHashMap<String, TopologyUserLinkConfig>(userLinksDB);
751     }
752
753     @Override
754     public Status addUserLink(TopologyUserLinkConfig userLink) {
755         if (!userLink.isValid()) {
756             return new Status(StatusCode.BADREQUEST,
757                     "User link configuration invalid.");
758         }
759         userLink.setStatus(TopologyUserLinkConfig.STATUS.LINKDOWN);
760
761         //Check if this link already configured
762         //NOTE: infinispan cache doesn't support Map.containsValue()
763         // (which is linear time in most ConcurrentMap impl anyway)
764         for (TopologyUserLinkConfig existingLink : userLinksDB.values()) {
765             if (existingLink.equals(userLink)) {
766                 return new Status(StatusCode.CONFLICT, "Link configuration exists");
767             }
768         }
769         //attempt put, if mapping for this key already existed return conflict
770         if (userLinksDB.putIfAbsent(userLink.getName(), userLink) != null) {
771             return new Status(StatusCode.CONFLICT, "Link with name : " + userLink.getName()
772                     + " already exists. Please use another name");
773         }
774
775         Edge linkTuple = getLinkTuple(userLink);
776         if (linkTuple != null) {
777             if (!isProductionLink(linkTuple)) {
778                 TopoEdgeUpdate teu = edgeUpdate(linkTuple, UpdateType.ADDED,
779                                                 new HashSet<Property>());
780                 if (teu == null) {
781                     userLinksDB.remove(userLink.getName());
782                     return new Status(StatusCode.NOTFOUND,
783                            "Link configuration contains invalid node connector: "
784                            + userLink);
785                 }
786             }
787
788             linkTuple = getReverseLinkTuple(userLink);
789             if (linkTuple != null) {
790                 userLink.setStatus(TopologyUserLinkConfig.STATUS.SUCCESS);
791                 if (!isProductionLink(linkTuple)) {
792                     edgeUpdate(linkTuple, UpdateType.ADDED, new HashSet<Property>());
793                 }
794             }
795         }
796         return new Status(StatusCode.SUCCESS);
797     }
798
799     @Override
800     public Status deleteUserLink(String linkName) {
801         if (linkName == null) {
802             return new Status(StatusCode.BADREQUEST, "User link name cannot be null.");
803         }
804
805         TopologyUserLinkConfig link = userLinksDB.remove(linkName);
806         Edge linkTuple;
807         if ((link != null) && ((linkTuple = getLinkTuple(link)) != null)) {
808             if (! isProductionLink(linkTuple)) {
809                 edgeUpdate(linkTuple, UpdateType.REMOVED, null);
810             }
811
812             linkTuple = getReverseLinkTuple(link);
813             if (! isProductionLink(linkTuple)) {
814                 edgeUpdate(linkTuple, UpdateType.REMOVED, null);
815             }
816         }
817         return new Status(StatusCode.SUCCESS);
818     }
819
820     private void registerWithOSGIConsole() {
821         BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
822                 .getBundleContext();
823         bundleContext.registerService(CommandProvider.class.getName(), this,
824                 null);
825     }
826
827     @Override
828     public String getHelp() {
829         StringBuffer help = new StringBuffer();
830         help.append("---Topology Manager---\n");
831         help.append("\t addUserLink <name> <node connector string> <node connector string>\n");
832         help.append("\t deleteUserLink <name>\n");
833         help.append("\t printUserLink\n");
834         help.append("\t printNodeEdges\n");
835         return help.toString();
836     }
837
838     public void _printUserLink(CommandInterpreter ci) {
839         for (String name : this.userLinksDB.keySet()) {
840             TopologyUserLinkConfig linkConfig = userLinksDB.get(name);
841             ci.println("Name : " + name);
842             ci.println(linkConfig);
843             ci.println("Edge " + getLinkTuple(linkConfig));
844             ci.println("Reverse Edge " + getReverseLinkTuple(linkConfig));
845         }
846     }
847
848     public void _addUserLink(CommandInterpreter ci) {
849         String name = ci.nextArgument();
850         if ((name == null)) {
851             ci.println("Please enter a valid Name");
852             return;
853         }
854
855         String ncStr1 = ci.nextArgument();
856         if (ncStr1 == null) {
857             ci.println("Please enter two node connector strings");
858             return;
859         }
860         String ncStr2 = ci.nextArgument();
861         if (ncStr2 == null) {
862             ci.println("Please enter second node connector string");
863             return;
864         }
865
866         NodeConnector nc1 = NodeConnector.fromString(ncStr1);
867         if (nc1 == null) {
868             ci.println("Invalid input node connector 1 string: " + ncStr1);
869             return;
870         }
871         NodeConnector nc2 = NodeConnector.fromString(ncStr2);
872         if (nc2 == null) {
873             ci.println("Invalid input node connector 2 string: " + ncStr2);
874             return;
875         }
876
877         TopologyUserLinkConfig config = new TopologyUserLinkConfig(name, ncStr1, ncStr2);
878         ci.println(this.addUserLink(config));
879     }
880
881     public void _deleteUserLink(CommandInterpreter ci) {
882         String name = ci.nextArgument();
883         if ((name == null)) {
884             ci.println("Please enter a valid Name");
885             return;
886         }
887         this.deleteUserLink(name);
888     }
889
890     public void _printNodeEdges(CommandInterpreter ci) {
891         Map<Node, Set<Edge>> nodeEdges = getNodeEdges();
892         if (nodeEdges == null) {
893             return;
894         }
895         Set<Node> nodeSet = nodeEdges.keySet();
896         if (nodeSet == null) {
897             return;
898         }
899         ci.println("        Node                                         Edge");
900         for (Node node : nodeSet) {
901             Set<Edge> edgeSet = nodeEdges.get(node);
902             if (edgeSet == null) {
903                 continue;
904             }
905             for (Edge edge : edgeSet) {
906                 ci.println(node + "             " + edge);
907             }
908         }
909     }
910
911     @Override
912     public Object readObject(ObjectInputStream ois)
913             throws FileNotFoundException, IOException, ClassNotFoundException {
914         return ois.readObject();
915     }
916
917     @Override
918     public Status saveConfiguration() {
919         return saveConfig();
920     }
921
922     @Override
923     public void edgeOverUtilized(Edge edge) {
924         log.warn("Link Utilization above normal: {}", edge);
925     }
926
927     @Override
928     public void edgeUtilBackToNormal(Edge edge) {
929         log.warn("Link Utilization back to normal: {}", edge);
930     }
931
932     private void edgeUpdateClusterWide(Edge e, UpdateType type, Set<Property> props, boolean isLocal) {
933         TopoEdgeUpdate upd = new TopoEdgeUpdate(e, props, type);
934         upd.setLocal(isLocal);
935         notifyQ.add(upd);
936     }
937
938     @Override
939     public void entryCreated(final Object key, final String cacheName, final boolean originLocal) {
940         if (cacheName.equals(TOPOEDGESDB)) {
941             // This is the case of an Edge being added to the topology DB
942             final Edge e = (Edge) key;
943             log.trace("Edge {} CREATED isLocal:{}", e, originLocal);
944             edgeUpdateClusterWide(e, UpdateType.ADDED, null, originLocal);
945         }
946     }
947
948     @Override
949     public void entryUpdated(final Object key, final Object new_value, final String cacheName, final boolean originLocal) {
950         if (cacheName.equals(TOPOEDGESDB)) {
951             final Edge e = (Edge) key;
952             log.trace("Edge {} UPDATED isLocal:{}", e, originLocal);
953             final Set<Property> props = (Set<Property>) new_value;
954             edgeUpdateClusterWide(e, UpdateType.CHANGED, props, originLocal);
955         }
956     }
957
958     @Override
959     public void entryDeleted(final Object key, final String cacheName, final boolean originLocal) {
960         if (cacheName.equals(TOPOEDGESDB)) {
961             final Edge e = (Edge) key;
962             log.trace("Edge {} DELETED isLocal:{}", e, originLocal);
963             edgeUpdateClusterWide(e, UpdateType.REMOVED, null, originLocal);
964         }
965     }
966
967     class TopologyNotify implements Runnable {
968         private final BlockingQueue<TopoEdgeUpdate> notifyQ;
969         private TopoEdgeUpdate entry;
970         private List<TopoEdgeUpdate> teuList = new ArrayList<TopoEdgeUpdate>();
971         private boolean notifyListeners;
972
973         TopologyNotify(BlockingQueue<TopoEdgeUpdate> notifyQ) {
974             this.notifyQ = notifyQ;
975         }
976
977         @Override
978         public void run() {
979             while (true) {
980                 try {
981                     log.trace("New run of TopologyNotify");
982                     notifyListeners = false;
983                     // First we block waiting for an element to get in
984                     entry = notifyQ.take();
985                     // Then we drain the whole queue if elements are
986                     // in it without getting into any blocking condition
987                     for (; entry != null; entry = notifyQ.poll()) {
988                         teuList.add(entry);
989                         notifyListeners = true;
990                     }
991
992                     // Notify listeners only if there were updates drained else
993                     // give up
994                     if (notifyListeners) {
995                         log.trace("Notifier thread, notified a listener");
996                         // Now update the listeners
997                         for (ITopologyManagerClusterWideAware s : topologyManagerClusterWideAware) {
998                             try {
999                                 s.edgeUpdate(teuList);
1000                             } catch (Exception exc) {
1001                                 log.error("Exception on edge update:", exc);
1002                             }
1003                         }
1004                     }
1005                     teuList.clear();
1006
1007                     // Lets sleep for sometime to allow aggregation of event
1008                     Thread.sleep(100);
1009                 } catch (InterruptedException e1) {
1010                     if (shuttingDown) {
1011                         return;
1012                     }
1013                     log.warn("TopologyNotify interrupted {}", e1.getMessage());
1014                 } catch (Exception e2) {
1015                     log.error("", e2);
1016                 }
1017             }
1018         }
1019     }
1020 }