Merge "Fix ClassCastException in logging bridge stop"
[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
578             // Make sure the props are non-null or create a copy
579             if (props == null) {
580                 props = new HashSet<Property>();
581             } else {
582                 props = new HashSet<Property>(props);
583             }
584
585             Set<Property> currentProps = this.edgesDB.get(e);
586             if (currentProps != null) {
587
588                 if (currentProps.equals(props)) {
589                     // Avoid redundant updates as notifications trigger expensive tasks
590                     log.trace("Skipping redundant edge addition: {}", e);
591                     return null;
592                 }
593
594                 // In case of node switch-over to a different cluster controller,
595                 // let's retain edge props (e.g. creation time)
596                 props.addAll(currentProps);
597             }
598
599             // Ensure that head node connector exists
600             if (!headNodeConnectorExist(e)) {
601                 log.warn("Ignore edge that contains invalid node connector: {}", e);
602                 return null;
603             }
604
605             // Check if nodeConnectors of the edge were correctly categorized
606             // by protocol plugin
607             crossCheckNodeConnectors(e);
608
609             // Now make sure there is the creation timestamp for the
610             // edge, if not there, stamp with the first update
611             boolean found_create = false;
612             for (Property prop : props) {
613                 if (prop instanceof TimeStamp) {
614                     TimeStamp t = (TimeStamp) prop;
615                     if (t.getTimeStampName().equals("creation")) {
616                         found_create = true;
617                         break;
618                     }
619                 }
620             }
621
622             if (!found_create) {
623                 TimeStamp t = new TimeStamp(System.currentTimeMillis(), "creation");
624                 props.add(t);
625             }
626
627             // Now add this in the database eventually overriding
628             // something that may have been already existing
629             this.edgesDB.put(e, props);
630
631             // Now populate the DB of NodeConnectors
632             // NOTE WELL: properties are empty sets, not really needed
633             // for now.
634             // The DB only contains ISL ports
635             if (isISLink(e)) {
636                 this.nodeConnectorsDB.put(e.getHeadNodeConnector(), new HashSet<Property>(1));
637                 this.nodeConnectorsDB.put(e.getTailNodeConnector(), new HashSet<Property>(1));
638             }
639             log.trace("Edge {}  {}", e.toString(), type.name());
640             break;
641         case REMOVED:
642             // Now remove the edge from edgesDB
643             this.edgesDB.remove(e);
644
645             // Now lets update the NodeConnectors DB, the assumption
646             // here is that two NodeConnector are exclusively
647             // connected by 1 and only 1 edge, this is reasonable in
648             // the same plug (virtual of phisical) we can assume two
649             // cables won't be plugged. This could break only in case
650             // of devices in the middle that acts as hubs, but it
651             // should be safe to assume that won't happen.
652             this.nodeConnectorsDB.remove(e.getHeadNodeConnector());
653             this.nodeConnectorsDB.remove(e.getTailNodeConnector());
654             log.trace("Edge {}  {}", e.toString(), type.name());
655             break;
656         case CHANGED:
657             Set<Property> oldProps = this.edgesDB.get(e);
658
659             // When property changes lets make sure we can change it
660             // all except the creation time stamp because that should
661             // be changed only when the edge is destroyed and created
662             // again
663             TimeStamp timeStamp = null;
664             for (Property prop : oldProps) {
665                 if (prop instanceof TimeStamp) {
666                     TimeStamp tsProp = (TimeStamp) prop;
667                     if (tsProp.getTimeStampName().equals("creation")) {
668                         timeStamp = tsProp;
669                         break;
670                     }
671                 }
672             }
673
674             // Now lets make sure new properties are non-null
675             if (props == null) {
676                 props = new HashSet<Property>();
677             } else {
678                 // Copy the set so noone is going to change the content
679                 props = new HashSet<Property>(props);
680             }
681
682             // Now lets remove the creation property if exist in the
683             // new props
684             for (Iterator<Property> i = props.iterator(); i.hasNext();) {
685                 Property prop = i.next();
686                 if (prop instanceof TimeStamp) {
687                     TimeStamp t = (TimeStamp) prop;
688                     if (t.getTimeStampName().equals("creation")) {
689                         i.remove();
690                         break;
691                     }
692                 }
693             }
694
695             // Now lets add the creation timestamp in it
696             if (timeStamp != null) {
697                 props.add(timeStamp);
698             }
699
700             // Finally update
701             this.edgesDB.put(e, props);
702             log.trace("Edge {}  {}", e.toString(), type.name());
703             break;
704         }
705         return new TopoEdgeUpdate(e, props, type);
706     }
707
708     @Override
709     public void edgeUpdate(List<TopoEdgeUpdate> topoedgeupdateList) {
710         List<TopoEdgeUpdate> teuList = new ArrayList<TopoEdgeUpdate>();
711         for (int i = 0; i < topoedgeupdateList.size(); i++) {
712             Edge e = topoedgeupdateList.get(i).getEdge();
713             Set<Property> p = topoedgeupdateList.get(i).getProperty();
714             UpdateType type = topoedgeupdateList.get(i).getUpdateType();
715             TopoEdgeUpdate teu = edgeUpdate(e, type, p);
716             if (teu != null) {
717                 teuList.add(teu);
718             }
719         }
720
721         if (!teuList.isEmpty()) {
722             // Now update the listeners
723             for (ITopologyManagerAware s : this.topologyManagerAware) {
724                 try {
725                     s.edgeUpdate(teuList);
726                 } catch (Exception exc) {
727                     log.error("Exception on edge update:", exc);
728                 }
729             }
730         }
731     }
732
733     private Edge getReverseLinkTuple(TopologyUserLinkConfig link) {
734         TopologyUserLinkConfig rLink = new TopologyUserLinkConfig(
735                 link.getName(), link.getDstNodeConnector(), link.getSrcNodeConnector());
736         return getLinkTuple(rLink);
737     }
738
739
740     private Edge getLinkTuple(TopologyUserLinkConfig link) {
741         NodeConnector srcNodeConnector = NodeConnector.fromString(link.getSrcNodeConnector());
742         NodeConnector dstNodeConnector = NodeConnector.fromString(link.getDstNodeConnector());
743         try {
744             return new Edge(srcNodeConnector, dstNodeConnector);
745         } catch (Exception e) {
746             return null;
747         }
748     }
749
750     @Override
751     public ConcurrentMap<String, TopologyUserLinkConfig> getUserLinks() {
752         return new ConcurrentHashMap<String, TopologyUserLinkConfig>(userLinksDB);
753     }
754
755     @Override
756     public Status addUserLink(TopologyUserLinkConfig userLink) {
757         if (!userLink.isValid()) {
758             return new Status(StatusCode.BADREQUEST,
759                     "User link configuration invalid.");
760         }
761         userLink.setStatus(TopologyUserLinkConfig.STATUS.LINKDOWN);
762
763         //Check if this link already configured
764         //NOTE: infinispan cache doesn't support Map.containsValue()
765         // (which is linear time in most ConcurrentMap impl anyway)
766         for (TopologyUserLinkConfig existingLink : userLinksDB.values()) {
767             if (existingLink.equals(userLink)) {
768                 return new Status(StatusCode.CONFLICT, "Link configuration exists");
769             }
770         }
771         //attempt put, if mapping for this key already existed return conflict
772         if (userLinksDB.putIfAbsent(userLink.getName(), userLink) != null) {
773             return new Status(StatusCode.CONFLICT, "Link with name : " + userLink.getName()
774                     + " already exists. Please use another name");
775         }
776
777         Edge linkTuple = getLinkTuple(userLink);
778         if (linkTuple != null) {
779             if (!isProductionLink(linkTuple)) {
780                 TopoEdgeUpdate teu = edgeUpdate(linkTuple, UpdateType.ADDED,
781                                                 new HashSet<Property>());
782                 if (teu == null) {
783                     userLinksDB.remove(userLink.getName());
784                     return new Status(StatusCode.NOTFOUND,
785                            "Link configuration contains invalid node connector: "
786                            + userLink);
787                 }
788             }
789
790             linkTuple = getReverseLinkTuple(userLink);
791             if (linkTuple != null) {
792                 userLink.setStatus(TopologyUserLinkConfig.STATUS.SUCCESS);
793                 if (!isProductionLink(linkTuple)) {
794                     edgeUpdate(linkTuple, UpdateType.ADDED, new HashSet<Property>());
795                 }
796             }
797         }
798         return new Status(StatusCode.SUCCESS);
799     }
800
801     @Override
802     public Status deleteUserLink(String linkName) {
803         if (linkName == null) {
804             return new Status(StatusCode.BADREQUEST, "User link name cannot be null.");
805         }
806
807         TopologyUserLinkConfig link = userLinksDB.remove(linkName);
808         Edge linkTuple;
809         if ((link != null) && ((linkTuple = getLinkTuple(link)) != null)) {
810             if (! isProductionLink(linkTuple)) {
811                 edgeUpdate(linkTuple, UpdateType.REMOVED, null);
812             }
813
814             linkTuple = getReverseLinkTuple(link);
815             if (! isProductionLink(linkTuple)) {
816                 edgeUpdate(linkTuple, UpdateType.REMOVED, null);
817             }
818         }
819         return new Status(StatusCode.SUCCESS);
820     }
821
822     private void registerWithOSGIConsole() {
823         BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
824                 .getBundleContext();
825         bundleContext.registerService(CommandProvider.class.getName(), this,
826                 null);
827     }
828
829     @Override
830     public String getHelp() {
831         StringBuffer help = new StringBuffer();
832         help.append("---Topology Manager---\n");
833         help.append("\t addUserLink <name> <node connector string> <node connector string>\n");
834         help.append("\t deleteUserLink <name>\n");
835         help.append("\t printUserLink\n");
836         help.append("\t printNodeEdges\n");
837         return help.toString();
838     }
839
840     public void _printUserLink(CommandInterpreter ci) {
841         for (String name : this.userLinksDB.keySet()) {
842             TopologyUserLinkConfig linkConfig = userLinksDB.get(name);
843             ci.println("Name : " + name);
844             ci.println(linkConfig);
845             ci.println("Edge " + getLinkTuple(linkConfig));
846             ci.println("Reverse Edge " + getReverseLinkTuple(linkConfig));
847         }
848     }
849
850     public void _addUserLink(CommandInterpreter ci) {
851         String name = ci.nextArgument();
852         if ((name == null)) {
853             ci.println("Please enter a valid Name");
854             return;
855         }
856
857         String ncStr1 = ci.nextArgument();
858         if (ncStr1 == null) {
859             ci.println("Please enter two node connector strings");
860             return;
861         }
862         String ncStr2 = ci.nextArgument();
863         if (ncStr2 == null) {
864             ci.println("Please enter second node connector string");
865             return;
866         }
867
868         NodeConnector nc1 = NodeConnector.fromString(ncStr1);
869         if (nc1 == null) {
870             ci.println("Invalid input node connector 1 string: " + ncStr1);
871             return;
872         }
873         NodeConnector nc2 = NodeConnector.fromString(ncStr2);
874         if (nc2 == null) {
875             ci.println("Invalid input node connector 2 string: " + ncStr2);
876             return;
877         }
878
879         TopologyUserLinkConfig config = new TopologyUserLinkConfig(name, ncStr1, ncStr2);
880         ci.println(this.addUserLink(config));
881     }
882
883     public void _deleteUserLink(CommandInterpreter ci) {
884         String name = ci.nextArgument();
885         if ((name == null)) {
886             ci.println("Please enter a valid Name");
887             return;
888         }
889         this.deleteUserLink(name);
890     }
891
892     public void _printNodeEdges(CommandInterpreter ci) {
893         Map<Node, Set<Edge>> nodeEdges = getNodeEdges();
894         if (nodeEdges == null) {
895             return;
896         }
897         Set<Node> nodeSet = nodeEdges.keySet();
898         if (nodeSet == null) {
899             return;
900         }
901         ci.println("        Node                                         Edge");
902         for (Node node : nodeSet) {
903             Set<Edge> edgeSet = nodeEdges.get(node);
904             if (edgeSet == null) {
905                 continue;
906             }
907             for (Edge edge : edgeSet) {
908                 ci.println(node + "             " + edge);
909             }
910         }
911     }
912
913     @Override
914     public Object readObject(ObjectInputStream ois)
915             throws FileNotFoundException, IOException, ClassNotFoundException {
916         return ois.readObject();
917     }
918
919     @Override
920     public Status saveConfiguration() {
921         return saveConfig();
922     }
923
924     @Override
925     public void edgeOverUtilized(Edge edge) {
926         log.warn("Link Utilization above normal: {}", edge);
927     }
928
929     @Override
930     public void edgeUtilBackToNormal(Edge edge) {
931         log.warn("Link Utilization back to normal: {}", edge);
932     }
933
934     private void edgeUpdateClusterWide(Edge e, UpdateType type, Set<Property> props, boolean isLocal) {
935         TopoEdgeUpdate upd = new TopoEdgeUpdate(e, props, type);
936         upd.setLocal(isLocal);
937         notifyQ.add(upd);
938     }
939
940     @Override
941     public void entryCreated(final Object key, final String cacheName, final boolean originLocal) {
942         if (cacheName.equals(TOPOEDGESDB)) {
943             // This is the case of an Edge being added to the topology DB
944             final Edge e = (Edge) key;
945             log.trace("Edge {} CREATED isLocal:{}", e, originLocal);
946             edgeUpdateClusterWide(e, UpdateType.ADDED, null, originLocal);
947         }
948     }
949
950     @Override
951     public void entryUpdated(final Object key, final Object new_value, final String cacheName, final boolean originLocal) {
952         if (cacheName.equals(TOPOEDGESDB)) {
953             final Edge e = (Edge) key;
954             log.trace("Edge {} UPDATED isLocal:{}", e, originLocal);
955             final Set<Property> props = (Set<Property>) new_value;
956             edgeUpdateClusterWide(e, UpdateType.CHANGED, props, originLocal);
957         }
958     }
959
960     @Override
961     public void entryDeleted(final Object key, final String cacheName, final boolean originLocal) {
962         if (cacheName.equals(TOPOEDGESDB)) {
963             final Edge e = (Edge) key;
964             log.trace("Edge {} DELETED isLocal:{}", e, originLocal);
965             edgeUpdateClusterWide(e, UpdateType.REMOVED, null, originLocal);
966         }
967     }
968
969     class TopologyNotify implements Runnable {
970         private final BlockingQueue<TopoEdgeUpdate> notifyQ;
971         private TopoEdgeUpdate entry;
972         private List<TopoEdgeUpdate> teuList = new ArrayList<TopoEdgeUpdate>();
973         private boolean notifyListeners;
974
975         TopologyNotify(BlockingQueue<TopoEdgeUpdate> notifyQ) {
976             this.notifyQ = notifyQ;
977         }
978
979         @Override
980         public void run() {
981             while (true) {
982                 try {
983                     log.trace("New run of TopologyNotify");
984                     notifyListeners = false;
985                     // First we block waiting for an element to get in
986                     entry = notifyQ.take();
987                     // Then we drain the whole queue if elements are
988                     // in it without getting into any blocking condition
989                     for (; entry != null; entry = notifyQ.poll()) {
990                         teuList.add(entry);
991                         notifyListeners = true;
992                     }
993
994                     // Notify listeners only if there were updates drained else
995                     // give up
996                     if (notifyListeners) {
997                         log.trace("Notifier thread, notified a listener");
998                         // Now update the listeners
999                         for (ITopologyManagerClusterWideAware s : topologyManagerClusterWideAware) {
1000                             try {
1001                                 s.edgeUpdate(teuList);
1002                             } catch (Exception exc) {
1003                                 log.error("Exception on edge update:", exc);
1004                             }
1005                         }
1006                     }
1007                     teuList.clear();
1008
1009                     // Lets sleep for sometime to allow aggregation of event
1010                     Thread.sleep(100);
1011                 } catch (InterruptedException e1) {
1012                     if (shuttingDown) {
1013                         return;
1014                     }
1015                     log.warn("TopologyNotify interrupted {}", e1.getMessage());
1016                 } catch (Exception e2) {
1017                     log.error("", e2);
1018                 }
1019             }
1020         }
1021     }
1022 }