added feature topology manager shell
[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.ITopologyManagerShell;
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         ITopologyManagerShell,
76         IConfigurationContainerAware,
77         IListenTopoUpdates,
78         IObjectReader,
79         CommandProvider {
80     protected static final String TOPOEDGESDB = "topologymanager.edgesDB";
81     protected static final String TOPOHOSTSDB = "topologymanager.hostsDB";
82     protected static final String TOPONODECONNECTORDB = "topologymanager.nodeConnectorDB";
83     protected static final String TOPOUSERLINKSDB = "topologymanager.userLinksDB";
84     private static final String USER_LINKS_FILE_NAME = "userTopology.conf";
85     private static final Logger log = LoggerFactory.getLogger(TopologyManagerImpl.class);
86     private ITopologyService topoService;
87     private IClusterContainerServices clusterContainerService;
88     private IConfigurationContainerService configurationService;
89     private ISwitchManager switchManager;
90     // DB of all the Edges with properties which constitute our topology
91     private ConcurrentMap<Edge, Set<Property>> edgesDB;
92     // DB of all NodeConnector which are part of ISL Edges, meaning they
93     // are connected to another NodeConnector on the other side of an ISL link.
94     // NodeConnector of a Production Edge is not part of this DB.
95     private ConcurrentMap<NodeConnector, Set<Property>> nodeConnectorsDB;
96     // DB of all the NodeConnectors with an Host attached to it
97     private ConcurrentMap<NodeConnector, Set<ImmutablePair<Host, Set<Property>>>> hostsDB;
98     // Topology Manager Aware listeners
99     private Set<ITopologyManagerAware> topologyManagerAware = new CopyOnWriteArraySet<ITopologyManagerAware>();
100     // Topology Manager Aware listeners - for clusterwide updates
101     private Set<ITopologyManagerClusterWideAware> topologyManagerClusterWideAware =
102             new CopyOnWriteArraySet<ITopologyManagerClusterWideAware>();
103     private ConcurrentMap<String, TopologyUserLinkConfig> userLinksDB;
104     private BlockingQueue<TopoEdgeUpdate> notifyQ = new LinkedBlockingQueue<TopoEdgeUpdate>();
105     private volatile Boolean shuttingDown = false;
106     private Thread notifyThread;
107
108
109     void nonClusterObjectCreate() {
110         edgesDB = new ConcurrentHashMap<Edge, Set<Property>>();
111         hostsDB = new ConcurrentHashMap<NodeConnector, Set<ImmutablePair<Host, Set<Property>>>>();
112         nodeConnectorsDB = new ConcurrentHashMap<NodeConnector, Set<Property>>();
113         userLinksDB = new ConcurrentHashMap<String, TopologyUserLinkConfig>();
114     }
115
116     void setTopologyManagerAware(ITopologyManagerAware s) {
117         if (this.topologyManagerAware != null) {
118             log.debug("Adding ITopologyManagerAware: {}", s);
119             this.topologyManagerAware.add(s);
120         }
121     }
122
123     void unsetTopologyManagerAware(ITopologyManagerAware s) {
124         if (this.topologyManagerAware != null) {
125             log.debug("Removing ITopologyManagerAware: {}", s);
126             this.topologyManagerAware.remove(s);
127         }
128     }
129
130     void setTopologyManagerClusterWideAware(ITopologyManagerClusterWideAware s) {
131         if (this.topologyManagerClusterWideAware != null) {
132             log.debug("Adding ITopologyManagerClusterWideAware: {}", s);
133             this.topologyManagerClusterWideAware.add(s);
134         }
135     }
136
137     void unsetTopologyManagerClusterWideAware(ITopologyManagerClusterWideAware s) {
138         if (this.topologyManagerClusterWideAware != null) {
139             log.debug("Removing ITopologyManagerClusterWideAware: {}", s);
140             this.topologyManagerClusterWideAware.remove(s);
141         }
142     }
143
144     void setTopoService(ITopologyService s) {
145         log.debug("Adding ITopologyService: {}", s);
146         this.topoService = s;
147     }
148
149     void unsetTopoService(ITopologyService s) {
150         if (this.topoService == s) {
151             log.debug("Removing ITopologyService: {}", s);
152             this.topoService = null;
153         }
154     }
155
156     void setClusterContainerService(IClusterContainerServices s) {
157         log.debug("Cluster Service set");
158         this.clusterContainerService = s;
159     }
160
161     void unsetClusterContainerService(IClusterContainerServices s) {
162         if (this.clusterContainerService == s) {
163             log.debug("Cluster Service removed!");
164             this.clusterContainerService = null;
165         }
166     }
167
168     public void setConfigurationContainerService(IConfigurationContainerService service) {
169         log.trace("Got configuration service set request {}", service);
170         this.configurationService = service;
171     }
172
173     public void unsetConfigurationContainerService(IConfigurationContainerService service) {
174         log.trace("Got configuration service UNset request");
175         this.configurationService = null;
176     }
177
178     void setSwitchManager(ISwitchManager s) {
179         log.debug("Adding ISwitchManager: {}", s);
180         this.switchManager = s;
181     }
182
183     void unsetSwitchManager(ISwitchManager s) {
184         if (this.switchManager == s) {
185             log.debug("Removing ISwitchManager: {}", s);
186             this.switchManager = null;
187         }
188     }
189
190     /**
191      * Function called by the dependency manager when all the required
192      * dependencies are satisfied
193      *
194      */
195     void init(Component c) {
196         allocateCaches();
197         retrieveCaches();
198         String containerName = null;
199         Dictionary<?, ?> props = c.getServiceProperties();
200         if (props != null) {
201             containerName = (String) props.get("containerName");
202         } else {
203             // In the Global instance case the containerName is empty
204             containerName = "UNKNOWN";
205         }
206
207         registerWithOSGIConsole();
208         loadConfiguration();
209
210         // Restore the shuttingDown status on init of the component
211         shuttingDown = false;
212         notifyThread = new Thread(new TopologyNotify(notifyQ));
213     }
214
215     @SuppressWarnings({ "unchecked" })
216     private void allocateCaches() {
217             this.edgesDB =
218                     (ConcurrentMap<Edge, Set<Property>>) allocateCache(TOPOEDGESDB,EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
219
220             this.hostsDB =
221                     (ConcurrentMap<NodeConnector, Set<ImmutablePair<Host, Set<Property>>>>) allocateCache(TOPOHOSTSDB, EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
222
223             this.nodeConnectorsDB =
224                     (ConcurrentMap<NodeConnector, Set<Property>>) allocateCache(
225                             TOPONODECONNECTORDB, EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
226             this.userLinksDB =
227                     (ConcurrentMap<String, TopologyUserLinkConfig>) allocateCache(
228                             TOPOUSERLINKSDB, EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
229     }
230
231     private ConcurrentMap<?, ?> allocateCache(String cacheName, Set<IClusterServices.cacheMode> cacheModes) {
232         ConcurrentMap<?, ?> cache = null;
233         try {
234             cache = this.clusterContainerService.createCache(cacheName, cacheModes);
235         } catch (CacheExistException e) {
236             log.debug(cacheName + " cache already exists - destroy and recreate if needed");
237         } catch (CacheConfigException e) {
238             log.error(cacheName + " cache configuration invalid - check cache mode");
239         }
240         return cache;
241     }
242
243     @SuppressWarnings({ "unchecked" })
244     private void retrieveCaches() {
245         if (this.clusterContainerService == null) {
246             log.error("Cluster Services is null, can't retrieve caches.");
247             return;
248         }
249
250         this.edgesDB = (ConcurrentMap<Edge, Set<Property>>) this.clusterContainerService.getCache(TOPOEDGESDB);
251         if (edgesDB == null) {
252             log.error("Failed to get cache for " + TOPOEDGESDB);
253         }
254
255         this.hostsDB =
256                 (ConcurrentMap<NodeConnector, Set<ImmutablePair<Host, Set<Property>>>>) this.clusterContainerService.getCache(TOPOHOSTSDB);
257         if (hostsDB == null) {
258             log.error("Failed to get cache for " + TOPOHOSTSDB);
259         }
260
261         this.nodeConnectorsDB =
262                 (ConcurrentMap<NodeConnector, Set<Property>>) this.clusterContainerService.getCache(TOPONODECONNECTORDB);
263         if (nodeConnectorsDB == null) {
264             log.error("Failed to get cache for " + TOPONODECONNECTORDB);
265         }
266
267         this.userLinksDB =
268                 (ConcurrentMap<String, TopologyUserLinkConfig>) this.clusterContainerService.getCache(TOPOUSERLINKSDB);
269         if (userLinksDB == null) {
270             log.error("Failed to get cache for " + TOPOUSERLINKSDB);
271         }
272     }
273
274     /**
275      * Function called after the topology manager has registered the service in
276      * OSGi service registry.
277      *
278      */
279     void started() {
280         // Start the batcher thread for the cluster wide topology updates
281         notifyThread.start();
282         // SollicitRefresh MUST be called here else if called at init
283         // time it may sollicit refresh too soon.
284         log.debug("Sollicit topology refresh");
285         topoService.sollicitRefresh();
286     }
287
288     void stop() {
289         shuttingDown = true;
290         notifyThread.interrupt();
291     }
292
293     /**
294      * Function called by the dependency manager when at least one dependency
295      * become unsatisfied or when the component is shutting down because for
296      * example bundle is being stopped.
297      *
298      */
299     void destroy() {
300         notifyQ.clear();
301         notifyThread = null;
302     }
303
304     private void loadConfiguration() {
305         for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, USER_LINKS_FILE_NAME)) {
306             addUserLink((TopologyUserLinkConfig) conf);
307         }
308     }
309
310     @Override
311     public Status saveConfig() {
312         return saveConfigInternal();
313     }
314
315     public Status saveConfigInternal() {
316         Status saveStatus = configurationService.persistConfiguration(
317                 new ArrayList<ConfigurationObject>(userLinksDB.values()), USER_LINKS_FILE_NAME);
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 synchronized 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
579             if (this.edgesDB.containsKey(e)) {
580                 // Avoid redundant updates (e.g. cluster switch-over) as notifications trigger expensive tasks
581                 log.trace("Skipping redundant edge addition: {}", e);
582                 return null;
583             }
584
585             // Make sure the props are non-null or create a copy
586             if (props == null) {
587                 props = new HashSet<Property>();
588             } else {
589                 props = new HashSet<Property>(props);
590             }
591
592
593             // Ensure that head node connector exists
594             if (!headNodeConnectorExist(e)) {
595                 log.warn("Ignore edge that contains invalid node connector: {}", e);
596                 return null;
597             }
598
599             // Check if nodeConnectors of the edge were correctly categorized
600             // by protocol plugin
601             crossCheckNodeConnectors(e);
602
603             // Now make sure there is the creation timestamp for the
604             // edge, if not there, stamp with the first update
605             boolean found_create = false;
606             for (Property prop : props) {
607                 if (prop instanceof TimeStamp) {
608                     TimeStamp t = (TimeStamp) prop;
609                     if (t.getTimeStampName().equals("creation")) {
610                         found_create = true;
611                         break;
612                     }
613                 }
614             }
615
616             if (!found_create) {
617                 TimeStamp t = new TimeStamp(System.currentTimeMillis(), "creation");
618                 props.add(t);
619             }
620
621             // Now add this in the database eventually overriding
622             // something that may have been already existing
623             this.edgesDB.put(e, props);
624
625             // Now populate the DB of NodeConnectors
626             // NOTE WELL: properties are empty sets, not really needed
627             // for now.
628             // The DB only contains ISL ports
629             if (isISLink(e)) {
630                 this.nodeConnectorsDB.put(e.getHeadNodeConnector(), new HashSet<Property>(1));
631                 this.nodeConnectorsDB.put(e.getTailNodeConnector(), new HashSet<Property>(1));
632             }
633             log.trace("Edge {}  {}", e.toString(), type.name());
634             break;
635         case REMOVED:
636             // Now remove the edge from edgesDB
637             this.edgesDB.remove(e);
638
639             // Now lets update the NodeConnectors DB, the assumption
640             // here is that two NodeConnector are exclusively
641             // connected by 1 and only 1 edge, this is reasonable in
642             // the same plug (virtual of phisical) we can assume two
643             // cables won't be plugged. This could break only in case
644             // of devices in the middle that acts as hubs, but it
645             // should be safe to assume that won't happen.
646             this.nodeConnectorsDB.remove(e.getHeadNodeConnector());
647             this.nodeConnectorsDB.remove(e.getTailNodeConnector());
648             log.trace("Edge {}  {}", e.toString(), type.name());
649             break;
650         case CHANGED:
651             Set<Property> oldProps = this.edgesDB.get(e);
652
653             // When property(s) changes lets make sure we can change it
654             // all except the creation time stamp because that should
655             // be set only when the edge is created
656             TimeStamp timeStamp = null;
657             for (Property prop : oldProps) {
658                 if (prop instanceof TimeStamp) {
659                     TimeStamp tsProp = (TimeStamp) prop;
660                     if (tsProp.getTimeStampName().equals("creation")) {
661                         timeStamp = tsProp;
662                         break;
663                     }
664                 }
665             }
666
667             // Now lets make sure new properties are non-null
668             if (props == null) {
669                 props = new HashSet<Property>();
670             } else {
671                 // Copy the set so noone is going to change the content
672                 props = new HashSet<Property>(props);
673             }
674
675             // Now lets remove the creation property if exist in the
676             // new props
677             for (Iterator<Property> i = props.iterator(); i.hasNext();) {
678                 Property prop = i.next();
679                 if (prop instanceof TimeStamp) {
680                     TimeStamp t = (TimeStamp) prop;
681                     if (t.getTimeStampName().equals("creation")) {
682                         i.remove();
683                         break;
684                     }
685                 }
686             }
687
688             // Now lets add the creation timestamp in it
689             if (timeStamp != null) {
690                 props.add(timeStamp);
691             }
692
693             // Finally update
694             this.edgesDB.put(e, props);
695             log.trace("Edge {}  {}", e.toString(), type.name());
696             break;
697         }
698         return new TopoEdgeUpdate(e, props, type);
699     }
700
701     @Override
702     public void edgeUpdate(List<TopoEdgeUpdate> topoedgeupdateList) {
703         List<TopoEdgeUpdate> teuList = new ArrayList<TopoEdgeUpdate>();
704         for (int i = 0; i < topoedgeupdateList.size(); i++) {
705             Edge e = topoedgeupdateList.get(i).getEdge();
706             Set<Property> p = topoedgeupdateList.get(i).getProperty();
707             UpdateType type = topoedgeupdateList.get(i).getUpdateType();
708             TopoEdgeUpdate teu = edgeUpdate(e, type, p);
709             if (teu != null) {
710                 teuList.add(teu);
711             }
712         }
713
714         if (!teuList.isEmpty()) {
715             // Now update the listeners
716             for (ITopologyManagerAware s : this.topologyManagerAware) {
717                 try {
718                     s.edgeUpdate(teuList);
719                 } catch (Exception exc) {
720                     log.error("Exception on edge update:", exc);
721                 }
722             }
723         }
724     }
725
726     private Edge getReverseLinkTuple(TopologyUserLinkConfig link) {
727         TopologyUserLinkConfig rLink = new TopologyUserLinkConfig(
728                 link.getName(), link.getDstNodeConnector(), link.getSrcNodeConnector());
729         return getLinkTuple(rLink);
730     }
731
732
733     private Edge getLinkTuple(TopologyUserLinkConfig link) {
734         NodeConnector srcNodeConnector = NodeConnector.fromString(link.getSrcNodeConnector());
735         NodeConnector dstNodeConnector = NodeConnector.fromString(link.getDstNodeConnector());
736         try {
737             return new Edge(srcNodeConnector, dstNodeConnector);
738         } catch (Exception e) {
739             return null;
740         }
741     }
742
743     @Override
744     public ConcurrentMap<String, TopologyUserLinkConfig> getUserLinks() {
745         return new ConcurrentHashMap<String, TopologyUserLinkConfig>(userLinksDB);
746     }
747
748     @Override
749     public Status addUserLink(TopologyUserLinkConfig userLink) {
750         if (!userLink.isValid()) {
751             return new Status(StatusCode.BADREQUEST,
752                     "User link configuration invalid.");
753         }
754         userLink.setStatus(TopologyUserLinkConfig.STATUS.LINKDOWN);
755
756         //Check if this link already configured
757         //NOTE: infinispan cache doesn't support Map.containsValue()
758         // (which is linear time in most ConcurrentMap impl anyway)
759         for (TopologyUserLinkConfig existingLink : userLinksDB.values()) {
760             if (existingLink.equals(userLink)) {
761                 return new Status(StatusCode.CONFLICT, "Link configuration exists");
762             }
763         }
764         //attempt put, if mapping for this key already existed return conflict
765         if (userLinksDB.putIfAbsent(userLink.getName(), userLink) != null) {
766             return new Status(StatusCode.CONFLICT, "Link with name : " + userLink.getName()
767                     + " already exists. Please use another name");
768         }
769
770         Edge linkTuple = getLinkTuple(userLink);
771         if (linkTuple != null) {
772             if (!isProductionLink(linkTuple)) {
773                 TopoEdgeUpdate teu = edgeUpdate(linkTuple, UpdateType.ADDED,
774                                                 new HashSet<Property>());
775                 if (teu == null) {
776                     userLinksDB.remove(userLink.getName());
777                     return new Status(StatusCode.NOTFOUND,
778                            "Link configuration contains invalid node connector: "
779                            + userLink);
780                 }
781             }
782
783             linkTuple = getReverseLinkTuple(userLink);
784             if (linkTuple != null) {
785                 userLink.setStatus(TopologyUserLinkConfig.STATUS.SUCCESS);
786                 if (!isProductionLink(linkTuple)) {
787                     edgeUpdate(linkTuple, UpdateType.ADDED, new HashSet<Property>());
788                 }
789             }
790         }
791         return new Status(StatusCode.SUCCESS);
792     }
793
794     @Override
795     public Status deleteUserLink(String linkName) {
796         if (linkName == null) {
797             return new Status(StatusCode.BADREQUEST, "User link name cannot be null.");
798         }
799
800         TopologyUserLinkConfig link = userLinksDB.remove(linkName);
801         Edge linkTuple;
802         if ((link != null) && ((linkTuple = getLinkTuple(link)) != null)) {
803             if (! isProductionLink(linkTuple)) {
804                 edgeUpdate(linkTuple, UpdateType.REMOVED, null);
805             }
806
807             linkTuple = getReverseLinkTuple(link);
808             if (! isProductionLink(linkTuple)) {
809                 edgeUpdate(linkTuple, UpdateType.REMOVED, null);
810             }
811         }
812         return new Status(StatusCode.SUCCESS);
813     }
814
815     private void registerWithOSGIConsole() {
816         BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
817                 .getBundleContext();
818         bundleContext.registerService(CommandProvider.class.getName(), this,
819                 null);
820     }
821
822     @Override
823     public String getHelp() {
824         StringBuffer help = new StringBuffer();
825         help.append("---Topology Manager---\n");
826         help.append("\t addUserLink <name> <node connector string> <node connector string>\n");
827         help.append("\t deleteUserLink <name>\n");
828         help.append("\t printUserLink\n");
829         help.append("\t printNodeEdges\n");
830         return help.toString();
831     }
832
833     public void _printUserLink(CommandInterpreter ci) {
834         for (String name : this.userLinksDB.keySet()) {
835             TopologyUserLinkConfig linkConfig = userLinksDB.get(name);
836             ci.println("Name : " + name);
837             ci.println(linkConfig);
838             ci.println("Edge " + getLinkTuple(linkConfig));
839             ci.println("Reverse Edge " + getReverseLinkTuple(linkConfig));
840         }
841     }
842
843     public void _addUserLink(CommandInterpreter ci) {
844         String name = ci.nextArgument();
845         if ((name == null)) {
846             ci.println("Please enter a valid Name");
847             return;
848         }
849
850         String ncStr1 = ci.nextArgument();
851         if (ncStr1 == null) {
852             ci.println("Please enter two node connector strings");
853             return;
854         }
855         String ncStr2 = ci.nextArgument();
856         if (ncStr2 == null) {
857             ci.println("Please enter second node connector string");
858             return;
859         }
860
861         NodeConnector nc1 = NodeConnector.fromString(ncStr1);
862         if (nc1 == null) {
863             ci.println("Invalid input node connector 1 string: " + ncStr1);
864             return;
865         }
866         NodeConnector nc2 = NodeConnector.fromString(ncStr2);
867         if (nc2 == null) {
868             ci.println("Invalid input node connector 2 string: " + ncStr2);
869             return;
870         }
871
872         TopologyUserLinkConfig config = new TopologyUserLinkConfig(name, ncStr1, ncStr2);
873         ci.println(this.addUserLink(config));
874     }
875
876     public void _deleteUserLink(CommandInterpreter ci) {
877         String name = ci.nextArgument();
878         if ((name == null)) {
879             ci.println("Please enter a valid Name");
880             return;
881         }
882         this.deleteUserLink(name);
883     }
884
885     public void _printNodeEdges(CommandInterpreter ci) {
886         Map<Node, Set<Edge>> nodeEdges = getNodeEdges();
887         if (nodeEdges == null) {
888             return;
889         }
890         Set<Node> nodeSet = nodeEdges.keySet();
891         if (nodeSet == null) {
892             return;
893         }
894         ci.println("        Node                                         Edge");
895         for (Node node : nodeSet) {
896             Set<Edge> edgeSet = nodeEdges.get(node);
897             if (edgeSet == null) {
898                 continue;
899             }
900             for (Edge edge : edgeSet) {
901                 ci.println(node + "             " + edge);
902             }
903         }
904     }
905
906     @Override
907     public Object readObject(ObjectInputStream ois)
908             throws FileNotFoundException, IOException, ClassNotFoundException {
909         return ois.readObject();
910     }
911
912     @Override
913     public Status saveConfiguration() {
914         return saveConfig();
915     }
916
917     @Override
918     public void edgeOverUtilized(Edge edge) {
919         log.warn("Link Utilization above normal: {}", edge);
920     }
921
922     @Override
923     public void edgeUtilBackToNormal(Edge edge) {
924         log.warn("Link Utilization back to normal: {}", edge);
925     }
926
927     private void edgeUpdateClusterWide(Edge e, UpdateType type, Set<Property> props, boolean isLocal) {
928         TopoEdgeUpdate upd = new TopoEdgeUpdate(e, props, type);
929         upd.setLocal(isLocal);
930         notifyQ.add(upd);
931     }
932
933     @Override
934     public void entryCreated(final Object key, final String cacheName, final boolean originLocal) {
935         if (cacheName.equals(TOPOEDGESDB)) {
936             // This is the case of an Edge being added to the topology DB
937             final Edge e = (Edge) key;
938             log.trace("Edge {} CREATED isLocal:{}", e, originLocal);
939             edgeUpdateClusterWide(e, UpdateType.ADDED, null, originLocal);
940         }
941     }
942
943     @Override
944     public void entryUpdated(final Object key, final Object new_value, final String cacheName, final boolean originLocal) {
945         if (cacheName.equals(TOPOEDGESDB)) {
946             final Edge e = (Edge) key;
947             log.trace("Edge {} UPDATED isLocal:{}", e, originLocal);
948             final Set<Property> props = (Set<Property>) new_value;
949             edgeUpdateClusterWide(e, UpdateType.CHANGED, props, originLocal);
950         }
951     }
952
953     @Override
954     public void entryDeleted(final Object key, final String cacheName, final boolean originLocal) {
955         if (cacheName.equals(TOPOEDGESDB)) {
956             final Edge e = (Edge) key;
957             log.trace("Edge {} DELETED isLocal:{}", e, originLocal);
958             edgeUpdateClusterWide(e, UpdateType.REMOVED, null, originLocal);
959         }
960     }
961
962     class TopologyNotify implements Runnable {
963         private final BlockingQueue<TopoEdgeUpdate> notifyQ;
964         private TopoEdgeUpdate entry;
965         private List<TopoEdgeUpdate> teuList = new ArrayList<TopoEdgeUpdate>();
966         private boolean notifyListeners;
967
968         TopologyNotify(BlockingQueue<TopoEdgeUpdate> notifyQ) {
969             this.notifyQ = notifyQ;
970         }
971
972         @Override
973         public void run() {
974             while (true) {
975                 try {
976                     log.trace("New run of TopologyNotify");
977                     notifyListeners = false;
978                     // First we block waiting for an element to get in
979                     entry = notifyQ.take();
980                     // Then we drain the whole queue if elements are
981                     // in it without getting into any blocking condition
982                     for (; entry != null; entry = notifyQ.poll()) {
983                         teuList.add(entry);
984                         notifyListeners = true;
985                     }
986
987                     // Notify listeners only if there were updates drained else
988                     // give up
989                     if (notifyListeners) {
990                         log.trace("Notifier thread, notified a listener");
991                         // Now update the listeners
992                         for (ITopologyManagerClusterWideAware s : topologyManagerClusterWideAware) {
993                             try {
994                                 s.edgeUpdate(teuList);
995                             } catch (Exception exc) {
996                                 log.error("Exception on edge update:", exc);
997                             }
998                         }
999                     }
1000                     teuList.clear();
1001
1002                     // Lets sleep for sometime to allow aggregation of event
1003                     Thread.sleep(100);
1004                 } catch (InterruptedException e1) {
1005                     if (shuttingDown) {
1006                         return;
1007                     }
1008                     log.warn("TopologyNotify interrupted {}", e1.getMessage());
1009                 } catch (Exception e2) {
1010                     log.error("", e2);
1011                 }
1012             }
1013         }
1014     }
1015
1016     public List<String> printUserLink() {
1017         List<String> result = new ArrayList<String>();
1018         for (String name : this.userLinksDB.keySet()) {
1019             TopologyUserLinkConfig linkConfig = userLinksDB.get(name);
1020             result.add("Name : " + name);
1021             result.add(linkConfig.toString());
1022             result.add("Edge " + getLinkTuple(linkConfig));
1023             result.add("Reverse Edge " + getReverseLinkTuple(linkConfig));
1024         }
1025         return result;
1026     }
1027
1028     public List<String> addUserLink(String name, String ncStr1, String ncStr2) {
1029         List<String> result = new ArrayList<String>();
1030         if ((name == null)) {
1031             result.add("Please enter a valid Name");
1032             return result;
1033         }
1034
1035         if (ncStr1 == null) {
1036             result.add("Please enter two node connector strings");
1037             return result;
1038         }
1039         if (ncStr2 == null) {
1040             result.add("Please enter second node connector string");
1041             return result;
1042         }
1043
1044         NodeConnector nc1 = NodeConnector.fromString(ncStr1);
1045         if (nc1 == null) {
1046             result.add("Invalid input node connector 1 string: " + ncStr1);
1047             return result;
1048         }
1049         NodeConnector nc2 = NodeConnector.fromString(ncStr2);
1050         if (nc2 == null) {
1051             result.add("Invalid input node connector 2 string: " + ncStr2);
1052             return result;
1053         }
1054
1055         TopologyUserLinkConfig config = new TopologyUserLinkConfig(name, ncStr1, ncStr2);
1056         result.add(this.addUserLink(config).toString());
1057         return result;
1058     }
1059
1060     public List<String> deleteUserLinkShell(String name) {
1061         List<String> result = new ArrayList<String>();
1062         if ((name == null)) {
1063             result.add("Please enter a valid Name");
1064             return result;
1065         }
1066         this.deleteUserLink(name);
1067         return result;
1068     }
1069
1070     public List<String> printNodeEdges() {
1071         List<String> result = new ArrayList<String>();
1072         Map<Node, Set<Edge>> nodeEdges = getNodeEdges();
1073         if (nodeEdges == null) {
1074             return result;
1075         }
1076         Set<Node> nodeSet = nodeEdges.keySet();
1077         if (nodeSet == null) {
1078             return result;
1079         }
1080         result.add("        Node                                         Edge");
1081         for (Node node : nodeSet) {
1082             Set<Edge> edgeSet = nodeEdges.get(node);
1083             if (edgeSet == null) {
1084                 continue;
1085             }
1086             for (Edge edge : edgeSet) {
1087                 result.add(node + "             " + edge);
1088             }
1089         }
1090         return result;
1091     }
1092
1093 }