Merge "sal-remoterpc-connector: sync ch.qos.logback:logback-classic version"
[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.IConfigurationContainerAware;
40 import org.opendaylight.controller.sal.core.Edge;
41 import org.opendaylight.controller.sal.core.Host;
42 import org.opendaylight.controller.sal.core.Node;
43 import org.opendaylight.controller.sal.core.NodeConnector;
44 import org.opendaylight.controller.sal.core.Property;
45 import org.opendaylight.controller.sal.core.TimeStamp;
46 import org.opendaylight.controller.sal.core.UpdateType;
47 import org.opendaylight.controller.sal.topology.IListenTopoUpdates;
48 import org.opendaylight.controller.sal.topology.ITopologyService;
49 import org.opendaylight.controller.sal.topology.TopoEdgeUpdate;
50 import org.opendaylight.controller.sal.utils.GlobalConstants;
51 import org.opendaylight.controller.sal.utils.IObjectReader;
52 import org.opendaylight.controller.sal.utils.NodeConnectorCreator;
53 import org.opendaylight.controller.sal.utils.ObjectReader;
54 import org.opendaylight.controller.sal.utils.ObjectWriter;
55 import org.opendaylight.controller.sal.utils.Status;
56 import org.opendaylight.controller.sal.utils.StatusCode;
57 import org.opendaylight.controller.switchmanager.ISwitchManager;
58 import org.opendaylight.controller.topologymanager.ITopologyManager;
59 import org.opendaylight.controller.topologymanager.ITopologyManagerAware;
60 import org.opendaylight.controller.topologymanager.ITopologyManagerClusterWideAware;
61 import org.opendaylight.controller.topologymanager.TopologyUserLinkConfig;
62 import org.osgi.framework.BundleContext;
63 import org.osgi.framework.FrameworkUtil;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
66
67 /**
68  * The class describes TopologyManager which is the central repository of the
69  * network topology. It provides service for applications to interact with
70  * topology database and notifies all the listeners of topology changes.
71  */
72 public class TopologyManagerImpl implements
73         ICacheUpdateAware<Object, Object>,
74         ITopologyManager,
75         IConfigurationContainerAware,
76         IListenTopoUpdates,
77         IObjectReader,
78         CommandProvider {
79     protected static final String TOPOEDGESDB = "topologymanager.edgesDB";
80     protected static final String TOPOHOSTSDB = "topologymanager.hostsDB";
81     protected static final String TOPONODECONNECTORDB = "topologymanager.nodeConnectorDB";
82     protected static final String TOPOUSERLINKSDB = "topologymanager.userLinksDB";
83     private static final Logger log = LoggerFactory.getLogger(TopologyManagerImpl.class);
84     private ITopologyService topoService;
85     private IClusterContainerServices clusterContainerService;
86     private ISwitchManager switchManager;
87     // DB of all the Edges with properties which constitute our topology
88     private ConcurrentMap<Edge, Set<Property>> edgesDB;
89     // DB of all NodeConnector which are part of ISL Edges, meaning they
90     // are connected to another NodeConnector on the other side of an ISL link.
91     // NodeConnector of a Production Edge is not part of this DB.
92     private ConcurrentMap<NodeConnector, Set<Property>> nodeConnectorsDB;
93     // DB of all the NodeConnectors with an Host attached to it
94     private ConcurrentMap<NodeConnector, Set<ImmutablePair<Host, Set<Property>>>> hostsDB;
95     // Topology Manager Aware listeners
96     private Set<ITopologyManagerAware> topologyManagerAware = new CopyOnWriteArraySet<ITopologyManagerAware>();
97     // Topology Manager Aware listeners - for clusterwide updates
98     private Set<ITopologyManagerClusterWideAware> topologyManagerClusterWideAware =
99             new CopyOnWriteArraySet<ITopologyManagerClusterWideAware>();
100     private static String ROOT = GlobalConstants.STARTUPHOME.toString();
101     private String userLinksFileName;
102     private ConcurrentMap<String, TopologyUserLinkConfig> userLinksDB;
103     private BlockingQueue<TopoEdgeUpdate> notifyQ = new LinkedBlockingQueue<TopoEdgeUpdate>();
104     private volatile Boolean shuttingDown = false;
105     private Thread notifyThread;
106
107
108     void nonClusterObjectCreate() {
109         edgesDB = new ConcurrentHashMap<Edge, Set<Property>>();
110         hostsDB = new ConcurrentHashMap<NodeConnector, Set<ImmutablePair<Host, Set<Property>>>>();
111         nodeConnectorsDB = new ConcurrentHashMap<NodeConnector, Set<Property>>();
112         userLinksDB = new ConcurrentHashMap<String, TopologyUserLinkConfig>();
113     }
114
115     void setTopologyManagerAware(ITopologyManagerAware s) {
116         if (this.topologyManagerAware != null) {
117             log.debug("Adding ITopologyManagerAware: {}", s);
118             this.topologyManagerAware.add(s);
119         }
120     }
121
122     void unsetTopologyManagerAware(ITopologyManagerAware s) {
123         if (this.topologyManagerAware != null) {
124             log.debug("Removing ITopologyManagerAware: {}", s);
125             this.topologyManagerAware.remove(s);
126         }
127     }
128
129     void setTopologyManagerClusterWideAware(ITopologyManagerClusterWideAware s) {
130         if (this.topologyManagerClusterWideAware != null) {
131             log.debug("Adding ITopologyManagerClusterWideAware: {}", s);
132             this.topologyManagerClusterWideAware.add(s);
133         }
134     }
135
136     void unsetTopologyManagerClusterWideAware(ITopologyManagerClusterWideAware s) {
137         if (this.topologyManagerClusterWideAware != null) {
138             log.debug("Removing ITopologyManagerClusterWideAware: {}", s);
139             this.topologyManagerClusterWideAware.remove(s);
140         }
141     }
142
143     void setTopoService(ITopologyService s) {
144         log.debug("Adding ITopologyService: {}", s);
145         this.topoService = s;
146     }
147
148     void unsetTopoService(ITopologyService s) {
149         if (this.topoService == s) {
150             log.debug("Removing ITopologyService: {}", s);
151             this.topoService = null;
152         }
153     }
154
155     void setClusterContainerService(IClusterContainerServices s) {
156         log.debug("Cluster Service set");
157         this.clusterContainerService = s;
158     }
159
160     void unsetClusterContainerService(IClusterContainerServices s) {
161         if (this.clusterContainerService == s) {
162             log.debug("Cluster Service removed!");
163             this.clusterContainerService = null;
164         }
165     }
166
167     void setSwitchManager(ISwitchManager s) {
168         log.debug("Adding ISwitchManager: {}", s);
169         this.switchManager = s;
170     }
171
172     void unsetSwitchManager(ISwitchManager s) {
173         if (this.switchManager == s) {
174             log.debug("Removing ISwitchManager: {}", s);
175             this.switchManager = null;
176         }
177     }
178
179     /**
180      * Function called by the dependency manager when all the required
181      * dependencies are satisfied
182      *
183      */
184     void init(Component c) {
185         allocateCaches();
186         retrieveCaches();
187         String containerName = null;
188         Dictionary<?, ?> props = c.getServiceProperties();
189         if (props != null) {
190             containerName = (String) props.get("containerName");
191         } else {
192             // In the Global instance case the containerName is empty
193             containerName = "UNKNOWN";
194         }
195
196         userLinksFileName = ROOT + "userTopology_" + containerName + ".conf";
197         registerWithOSGIConsole();
198         if ((clusterContainerService != null) && (clusterContainerService.amICoordinator())) {
199             loadConfiguration();
200         }
201         // Restore the shuttingDown status on init of the component
202         shuttingDown = false;
203         notifyThread = new Thread(new TopologyNotify(notifyQ));
204     }
205
206     @SuppressWarnings({ "unchecked" })
207     private void allocateCaches() {
208             this.edgesDB =
209                     (ConcurrentMap<Edge, Set<Property>>) allocateCache(TOPOEDGESDB,EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
210
211             this.hostsDB =
212                     (ConcurrentMap<NodeConnector, Set<ImmutablePair<Host, Set<Property>>>>) allocateCache(TOPOHOSTSDB, EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
213
214             this.nodeConnectorsDB =
215                     (ConcurrentMap<NodeConnector, Set<Property>>) allocateCache(
216                             TOPONODECONNECTORDB, EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
217             this.userLinksDB =
218                     (ConcurrentMap<String, TopologyUserLinkConfig>) allocateCache(
219                             TOPOUSERLINKSDB, EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
220     }
221
222     private ConcurrentMap<?, ?> allocateCache(String cacheName, Set<IClusterServices.cacheMode> cacheModes) {
223         ConcurrentMap<?, ?> cache = null;
224         try {
225             cache = this.clusterContainerService.createCache(cacheName, cacheModes);
226         } catch (CacheExistException e) {
227             log.debug(cacheName + " cache already exists - destroy and recreate if needed");
228         } catch (CacheConfigException e) {
229             log.error(cacheName + " cache configuration invalid - check cache mode");
230         }
231         return cache;
232     }
233
234     @SuppressWarnings({ "unchecked" })
235     private void retrieveCaches() {
236         if (this.clusterContainerService == null) {
237             log.error("Cluster Services is null, can't retrieve caches.");
238             return;
239         }
240
241         this.edgesDB = (ConcurrentMap<Edge, Set<Property>>) this.clusterContainerService.getCache(TOPOEDGESDB);
242         if (edgesDB == null) {
243             log.error("Failed to get cache for " + TOPOEDGESDB);
244         }
245
246         this.hostsDB =
247                 (ConcurrentMap<NodeConnector, Set<ImmutablePair<Host, Set<Property>>>>) this.clusterContainerService.getCache(TOPOHOSTSDB);
248         if (hostsDB == null) {
249             log.error("Failed to get cache for " + TOPOHOSTSDB);
250         }
251
252         this.nodeConnectorsDB =
253                 (ConcurrentMap<NodeConnector, Set<Property>>) this.clusterContainerService.getCache(TOPONODECONNECTORDB);
254         if (nodeConnectorsDB == null) {
255             log.error("Failed to get cache for " + TOPONODECONNECTORDB);
256         }
257
258         this.userLinksDB =
259                 (ConcurrentMap<String, TopologyUserLinkConfig>) this.clusterContainerService.getCache(TOPOUSERLINKSDB);
260         if (userLinksDB == null) {
261             log.error("Failed to get cache for " + TOPOUSERLINKSDB);
262         }
263     }
264
265     /**
266      * Function called after the topology manager has registered the service in
267      * OSGi service registry.
268      *
269      */
270     void started() {
271         // Start the batcher thread for the cluster wide topology updates
272         notifyThread.start();
273         // SollicitRefresh MUST be called here else if called at init
274         // time it may sollicit refresh too soon.
275         log.debug("Sollicit topology refresh");
276         topoService.sollicitRefresh();
277     }
278
279     void stop() {
280         shuttingDown = true;
281         notifyThread.interrupt();
282     }
283
284     /**
285      * Function called by the dependency manager when at least one dependency
286      * become unsatisfied or when the component is shutting down because for
287      * example bundle is being stopped.
288      *
289      */
290     void destroy() {
291         notifyQ.clear();
292         notifyThread = null;
293     }
294
295     @SuppressWarnings("unchecked")
296     private void loadConfiguration() {
297         ObjectReader objReader = new ObjectReader();
298         ConcurrentMap<String, TopologyUserLinkConfig> confList =
299                 (ConcurrentMap<String, TopologyUserLinkConfig>) objReader.read(this, userLinksFileName);
300
301         if (confList != null) {
302             for (TopologyUserLinkConfig conf : confList.values()) {
303                 addUserLink(conf);
304             }
305         }
306     }
307
308     @Override
309     public Status saveConfig() {
310         return saveConfigInternal();
311     }
312
313     public Status saveConfigInternal() {
314         ObjectWriter objWriter = new ObjectWriter();
315
316         Status saveStatus = objWriter.write(
317                 new ConcurrentHashMap<String, TopologyUserLinkConfig>(userLinksDB), userLinksFileName);
318
319         if (! saveStatus.isSuccess()) {
320             return new Status(StatusCode.INTERNALERROR, "Topology save failed: " + saveStatus.getDescription());
321         }
322         return saveStatus;
323     }
324
325     @Override
326     public Map<Node, Set<Edge>> getNodeEdges() {
327         if (this.edgesDB == null) {
328             return null;
329         }
330
331         Map<Node, Set<Edge>> res = new HashMap<Node, Set<Edge>>();
332         for (Edge edge : this.edgesDB.keySet()) {
333             // Lets analyze the tail
334             Node node = edge.getTailNodeConnector().getNode();
335             Set<Edge> nodeEdges = res.get(node);
336             if (nodeEdges == null) {
337                 nodeEdges = new HashSet<Edge>();
338                 res.put(node, nodeEdges);
339             }
340             nodeEdges.add(edge);
341
342             // Lets analyze the head
343             node = edge.getHeadNodeConnector().getNode();
344             nodeEdges = res.get(node);
345             if (nodeEdges == null) {
346                 nodeEdges = new HashSet<Edge>();
347                 res.put(node, nodeEdges);
348             }
349             nodeEdges.add(edge);
350         }
351
352         return res;
353     }
354
355     @Override
356     public boolean isInternal(NodeConnector p) {
357         if (this.nodeConnectorsDB == null) {
358             return false;
359         }
360
361         // This is an internal NodeConnector if is connected to
362         // another Node i.e it's part of the nodeConnectorsDB
363         return (this.nodeConnectorsDB.get(p) != null);
364     }
365
366     /**
367      * This method returns true if the edge is an ISL link.
368      *
369      * @param e
370      *            The edge
371      * @return true if it is an ISL link
372      */
373     public boolean isISLink(Edge e) {
374         return (!isProductionLink(e));
375     }
376
377     /**
378      * This method returns true if the edge is a production link.
379      *
380      * @param e
381      *            The edge
382      * @return true if it is a production link
383      */
384     public boolean isProductionLink(Edge e) {
385         return (e.getHeadNodeConnector().getType().equals(NodeConnector.NodeConnectorIDType.PRODUCTION)
386                 || e.getTailNodeConnector().getType().equals(NodeConnector.NodeConnectorIDType.PRODUCTION));
387     }
388
389     /**
390      * This method cross checks the determination of nodeConnector type by Discovery Service
391      * against the information in SwitchManager and updates it accordingly.
392      * @param e
393      *          The edge
394      */
395     private void crossCheckNodeConnectors(Edge e) {
396         NodeConnector nc;
397         if (e.getHeadNodeConnector().getType().equals(NodeConnector.NodeConnectorIDType.PRODUCTION)) {
398             nc = updateNCTypeFromSwitchMgr(e.getHeadNodeConnector());
399             if (nc != null) {
400                 e.setHeadNodeConnector(nc);
401             }
402         }
403         if (e.getTailNodeConnector().getType().equals(NodeConnector.NodeConnectorIDType.PRODUCTION)) {
404             nc = updateNCTypeFromSwitchMgr(e.getTailNodeConnector());
405             if (nc != null) {
406                 e.setTailNodeConnector(nc);
407             }
408         }
409     }
410
411     /**
412      * A NodeConnector may have been categorized as of type Production by Discovery Service.
413      * But at the time when this determination was made, only OF nodes were known to Discovery
414      * Service. This method checks if the node of nodeConnector is known to SwitchManager. If
415      * so, then it returns a new NodeConnector with correct type.
416      *
417      * @param nc
418      *       NodeConnector as passed on in the edge
419      * @return
420      *       If Node of the NodeConnector is in SwitchManager, then return a new NodeConnector
421      *       with correct type, null otherwise
422      */
423
424     private NodeConnector updateNCTypeFromSwitchMgr(NodeConnector nc) {
425
426         for (Node node : switchManager.getNodes()) {
427             String nodeName = node.getNodeIDString();
428             log.trace("Switch Manager Node Name: {}, NodeConnector Node Name: {}", nodeName,
429                     nc.getNode().getNodeIDString());
430             if (nodeName.equals(nc.getNode().getNodeIDString())) {
431                 NodeConnector nodeConnector = NodeConnectorCreator
432                         .createNodeConnector(node.getType(), nc.getID(), node);
433                 return nodeConnector;
434             }
435         }
436         return null;
437     }
438
439     /**
440      * The Map returned is a copy of the current topology hence if the topology
441      * changes the copy doesn't
442      *
443      * @return A Map representing the current topology expressed as edges of the
444      *         network
445      */
446     @Override
447     public Map<Edge, Set<Property>> getEdges() {
448         if (this.edgesDB == null) {
449             return null;
450         }
451
452         Map<Edge, Set<Property>> edgeMap = new HashMap<Edge, Set<Property>>();
453         Set<Property> props;
454         for (Map.Entry<Edge, Set<Property>> edgeEntry : edgesDB.entrySet()) {
455             // Sets of props are copied because the composition of
456             // those properties could change with time
457             props = new HashSet<Property>(edgeEntry.getValue());
458             // We can simply reuse the key because the object is
459             // immutable so doesn't really matter that we are
460             // referencing the only owned by a different table, the
461             // meaning is the same because doesn't change with time.
462             edgeMap.put(edgeEntry.getKey(), props);
463         }
464
465         return edgeMap;
466     }
467
468     @Override
469     public Set<NodeConnector> getNodeConnectorWithHost() {
470         if (this.hostsDB == null) {
471             return null;
472         }
473
474         return (new HashSet<NodeConnector>(this.hostsDB.keySet()));
475     }
476
477     @Override
478     public Map<Node, Set<NodeConnector>> getNodesWithNodeConnectorHost() {
479         if (this.hostsDB == null) {
480             return null;
481         }
482         HashMap<Node, Set<NodeConnector>> res = new HashMap<Node, Set<NodeConnector>>();
483         Node node;
484         Set<NodeConnector> portSet;
485         for (NodeConnector nc : this.hostsDB.keySet()) {
486             node = nc.getNode();
487             portSet = res.get(node);
488             if (portSet == null) {
489                 // Create the HashSet if null
490                 portSet = new HashSet<NodeConnector>();
491                 res.put(node, portSet);
492             }
493
494             // Keep updating the HashSet, given this is not a
495             // clustered map we can just update the set without
496             // worrying to update the hashmap.
497             portSet.add(nc);
498         }
499
500         return (res);
501     }
502
503     @Override
504     public Host getHostAttachedToNodeConnector(NodeConnector port) {
505         List<Host> hosts = getHostsAttachedToNodeConnector(port);
506         if(hosts != null && !hosts.isEmpty()){
507             return hosts.get(0);
508         }
509         return null;
510     }
511
512     @Override
513     public List<Host> getHostsAttachedToNodeConnector(NodeConnector p) {
514         Set<ImmutablePair<Host, Set<Property>>> hosts;
515         if (this.hostsDB == null || (hosts = this.hostsDB.get(p)) == null) {
516             return null;
517         }
518         // create a list of hosts
519         List<Host> retHosts = new LinkedList<Host>();
520         for(ImmutablePair<Host, Set<Property>> host : hosts) {
521             retHosts.add(host.getLeft());
522         }
523         return retHosts;
524     }
525
526     @Override
527     public void updateHostLink(NodeConnector port, Host h, UpdateType t, Set<Property> props) {
528
529         // Clone the property set in case non null else just
530         // create an empty one. Caches allocated via infinispan
531         // don't allow null values
532         if (props == null) {
533             props = new HashSet<Property>();
534         } else {
535             props = new HashSet<Property>(props);
536         }
537         ImmutablePair<Host, Set<Property>> thisHost = new ImmutablePair<Host, Set<Property>>(h, props);
538
539         // get the host list
540         Set<ImmutablePair<Host, Set<Property>>> hostSet = this.hostsDB.get(port);
541         if(hostSet == null) {
542             hostSet = new HashSet<ImmutablePair<Host, Set<Property>>>();
543         }
544         switch (t) {
545         case ADDED:
546         case CHANGED:
547             hostSet.add(thisHost);
548             this.hostsDB.put(port, hostSet);
549             break;
550         case REMOVED:
551             hostSet.remove(thisHost);
552             if(hostSet.isEmpty()) {
553                 //remove only if hasn't been concurrently modified
554                 this.hostsDB.remove(port, hostSet);
555             } else {
556                 this.hostsDB.put(port, hostSet);
557             }
558             break;
559         }
560     }
561
562     private boolean headNodeConnectorExist(Edge e) {
563         /*
564          * Only check the head end point which is supposed to be part of a
565          * network node we control (present in our inventory). If we checked the
566          * tail end point as well, we would not store the edges that connect to
567          * a non sdn enable port on a non sdn capable production switch. We want
568          * to be able to see these switches on the topology.
569          */
570         NodeConnector head = e.getHeadNodeConnector();
571         return (switchManager.doesNodeConnectorExist(head));
572     }
573
574     private TopoEdgeUpdate edgeUpdate(Edge e, UpdateType type, Set<Property> props) {
575         switch (type) {
576         case ADDED:
577             // Avoid redundant update as notifications trigger expensive tasks
578             if (edgesDB.containsKey(e)) {
579                 log.trace("Skipping redundant edge addition: {}", e);
580                 return null;
581             }
582
583             // Ensure that head node connector exists
584             if (!headNodeConnectorExist(e)) {
585                 log.warn("Ignore edge that contains invalid node connector: {}", e);
586                 return null;
587             }
588
589             // Check if nodeConnectors of the edge were correctly categorized
590             // by OF plugin
591             crossCheckNodeConnectors(e);
592
593             // Make sure the props are non-null
594             if (props == null) {
595                 props = new HashSet<Property>();
596             } else {
597                 props = new HashSet<Property>(props);
598             }
599
600             //in case of node switch-over to a different cluster controller,
601             //let's retain edge props
602             Set<Property> currentProps = this.edgesDB.get(e);
603             if (currentProps != null){
604                 props.addAll(currentProps);
605             }
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 }