3 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
5 * This program and the accompanying materials are made available under the
6 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7 * and is available at http://www.eclipse.org/legal/epl-v10.html
10 package org.opendaylight.controller.protocol_plugin.openflow.internal;
12 import java.util.ArrayList;
13 import java.util.HashMap;
14 import java.util.List;
17 import java.util.Timer;
18 import java.util.TimerTask;
19 import java.util.concurrent.BlockingQueue;
20 import java.util.concurrent.ConcurrentHashMap;
21 import java.util.concurrent.ConcurrentMap;
22 import java.util.concurrent.CopyOnWriteArrayList;
23 import java.util.concurrent.LinkedBlockingQueue;
25 import org.apache.commons.lang3.tuple.ImmutablePair;
26 import org.apache.commons.lang3.tuple.Pair;
27 import org.eclipse.osgi.framework.console.CommandInterpreter;
28 import org.eclipse.osgi.framework.console.CommandProvider;
29 import org.opendaylight.controller.protocol_plugin.openflow.IOFStatisticsManager;
30 import org.opendaylight.controller.protocol_plugin.openflow.IRefreshInternalProvider;
31 import org.opendaylight.controller.protocol_plugin.openflow.ITopologyServiceShimListener;
32 import org.osgi.framework.BundleContext;
33 import org.osgi.framework.FrameworkUtil;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
37 import org.opendaylight.controller.sal.core.Bandwidth;
38 import org.opendaylight.controller.sal.core.ContainerFlow;
39 import org.opendaylight.controller.sal.core.Edge;
40 import org.opendaylight.controller.sal.core.IContainerListener;
41 import org.opendaylight.controller.sal.core.Node;
42 import org.opendaylight.controller.sal.core.NodeConnector;
43 import org.opendaylight.controller.sal.core.Property;
44 import org.opendaylight.controller.sal.core.UpdateType;
45 import org.opendaylight.controller.sal.discovery.IDiscoveryService;
46 import org.opendaylight.controller.sal.utils.GlobalConstants;
49 * The class describes a shim layer that relays the topology events from OpenFlow
50 * core to various listeners. The notifications are filtered based on container
53 public class TopologyServiceShim implements IDiscoveryService,
54 IContainerListener, CommandProvider, IRefreshInternalProvider {
55 protected static final Logger logger = LoggerFactory
56 .getLogger(TopologyServiceShim.class);
57 private ConcurrentMap<String, ITopologyServiceShimListener> topologyServiceShimListeners = new ConcurrentHashMap<String, ITopologyServiceShimListener>();
58 private ConcurrentMap<NodeConnector, List<String>> containerMap = new ConcurrentHashMap<NodeConnector, List<String>>();
59 private ConcurrentMap<String, Map<NodeConnector, Pair<Edge, Set<Property>>>> edgeMap = new ConcurrentHashMap<String, Map<NodeConnector, Pair<Edge, Set<Property>>>>();
61 private BlockingQueue<NotifyEntry> notifyQ;
62 private Thread notifyThread;
63 private BlockingQueue<String> bulkNotifyQ;
64 private Thread ofPluginTopoBulkUpdate;
65 private volatile Boolean shuttingDown = false;
66 private IOFStatisticsManager statsMgr;
67 private Timer pollTimer;
68 private TimerTask txRatePoller;
69 private Thread bwUtilNotifyThread;
70 private BlockingQueue<UtilizationUpdate> bwUtilNotifyQ;
71 private List<NodeConnector> connectorsOverUtilized;
72 private float bwThresholdFactor = (float) 0.8; // Threshold = 80% of link bandwidth
76 Pair<Edge, Set<Property>> edgeProps;
79 NotifyEntry(String container, Pair<Edge, Set<Property>> edgeProps,
81 this.container = container;
82 this.edgeProps = edgeProps;
87 class TopologyNotify implements Runnable {
88 private final BlockingQueue<NotifyEntry> notifyQ;
90 TopologyNotify(BlockingQueue<NotifyEntry> notifyQ) {
91 this.notifyQ = notifyQ;
97 NotifyEntry entry = notifyQ.take();
99 ITopologyServiceShimListener topologServiceShimListener = topologyServiceShimListeners
100 .get(entry.container);
101 topologServiceShimListener.edgeUpdate(entry.edgeProps
102 .getLeft(), entry.type, entry.edgeProps.getRight());
105 } catch (InterruptedException e1) {
106 logger.warn("TopologyNotify interrupted", e1.getMessage());
110 } catch (Exception e2) {
111 e2.printStackTrace();
117 class UtilizationUpdate {
118 NodeConnector connector;
121 UtilizationUpdate(NodeConnector connector, UpdateType type) {
122 this.connector = connector;
127 class BwUtilizationNotify implements Runnable {
128 private final BlockingQueue<UtilizationUpdate> notifyQ;
130 BwUtilizationNotify(BlockingQueue<UtilizationUpdate> notifyQ) {
131 this.notifyQ = notifyQ;
137 UtilizationUpdate update = notifyQ.take();
138 NodeConnector connector = update.connector;
139 Set<String> containerList = edgeMap.keySet();//.get(connector);
140 for (String container : containerList) {
141 Map<NodeConnector, Pair<Edge, Set<Property>>> edgePropsMap = edgeMap
143 Edge edge = edgePropsMap.get(connector).getLeft();
144 if (edge.getTailNodeConnector().equals(connector)) {
145 ITopologyServiceShimListener topologServiceShimListener = topologyServiceShimListeners
147 if (update.type == UpdateType.ADDED) {
148 topologServiceShimListener
149 .edgeOverUtilized(edge);
151 topologServiceShimListener
152 .edgeUtilBackToNormal(edge);
156 } catch (InterruptedException e1) {
159 "Edge Bandwidth Utilization Notify Thread interrupted",
164 } catch (Exception e2) {
165 e2.printStackTrace();
172 * Function called by the dependency manager when all the required
173 * dependencies are satisfied
177 logger.trace("Init called");
178 connectorsOverUtilized = new ArrayList<NodeConnector>();
179 notifyQ = new LinkedBlockingQueue<NotifyEntry>();
180 notifyThread = new Thread(new TopologyNotify(notifyQ));
181 bwUtilNotifyQ = new LinkedBlockingQueue<UtilizationUpdate>();
182 bwUtilNotifyThread = new Thread(new BwUtilizationNotify(bwUtilNotifyQ));
183 bulkNotifyQ = new LinkedBlockingQueue<String>();
184 ofPluginTopoBulkUpdate = new Thread(new Runnable() {
189 String containerName = bulkNotifyQ.take();
190 logger.debug("Bulk Notify container:{}", containerName);
191 TopologyBulkUpdate(containerName);
192 } catch (InterruptedException e) {
193 logger.warn("Topology Bulk update thread interrupted");
200 }, "Topology Bulk Update");
202 // Initialize node connector tx bit rate poller timer
203 pollTimer = new Timer();
204 txRatePoller = new TimerTask() {
211 registerWithOSGIConsole();
215 * Continuously polls the transmit bit rate for all the node connectors
216 * from statistics manager and trigger the warning notification upward
217 * when the transmit rate is above a threshold which is a percentage of
220 protected void pollTxBitRates() {
221 Map<NodeConnector, Pair<Edge, Set<Property>>> globalContainerEdges = edgeMap
222 .get(GlobalConstants.DEFAULT.toString());
223 if (globalContainerEdges == null) {
227 for (NodeConnector connector : globalContainerEdges.keySet()) {
228 // Skip if node connector belongs to production switch
229 if (connector.getType().equals(NodeConnector.NodeConnectorIDType.PRODUCTION)) {
233 // Get edge for which this node connector is head
234 Pair<Edge, Set<Property>> props = this.edgeMap.get(
235 GlobalConstants.DEFAULT.toString()).get(connector);
236 // On switch mgr restart the props get reset
240 Set<Property> propSet = props.getRight();
241 if (propSet == null) {
246 for (Property prop : propSet) {
247 if (prop instanceof Bandwidth) {
248 bw = ((Bandwidth) prop).getValue();
253 // Skip if agent did not provide a bandwidth info for the edge
258 // Compare bandwidth usage
259 Long switchId = (Long) connector.getNode().getID();
260 Short port = (Short) connector.getID();
261 float rate = statsMgr.getTransmitRate(switchId, port);
262 if (rate > bwThresholdFactor * bw) {
263 if (!connectorsOverUtilized.contains(connector)) {
264 connectorsOverUtilized.add(connector);
265 this.bwUtilNotifyQ.add(new UtilizationUpdate(connector,
269 if (connectorsOverUtilized.contains(connector)) {
270 connectorsOverUtilized.remove(connector);
271 this.bwUtilNotifyQ.add(new UtilizationUpdate(connector,
272 UpdateType.REMOVED));
280 * Function called by the dependency manager when at least one
281 * dependency become unsatisfied or when the component is shutting
282 * down because for example bundle is being stopped.
286 logger.trace("DESTROY called!");
292 * Function called by dependency manager after "init ()" is called
293 * and after the services provided by the class are registered in
294 * the service registry
298 logger.trace("START called!");
299 notifyThread.start();
300 bwUtilNotifyThread.start();
301 ofPluginTopoBulkUpdate.start();
302 pollTimer.scheduleAtFixedRate(txRatePoller, 10000, 5000);
306 * Function called by the dependency manager before the services
307 * exported by the component are unregistered, this will be
308 * followed by a "destroy ()" calls
312 logger.trace("STOP called!");
314 notifyThread.interrupt();
317 void setTopologyServiceShimListener(Map<?, ?> props,
318 ITopologyServiceShimListener s) {
320 logger.error("Didn't receive the service properties");
323 String containerName = (String) props.get("containerName");
324 if (containerName == null) {
325 logger.error("containerName not supplied");
328 if ((this.topologyServiceShimListeners != null)
329 && !this.topologyServiceShimListeners
330 .containsKey(containerName)) {
331 this.topologyServiceShimListeners.put(containerName, s);
332 logger.trace("Added topologyServiceShimListener for container:"
337 void unsetTopologyServiceShimListener(Map<?, ?> props,
338 ITopologyServiceShimListener s) {
340 logger.error("Didn't receive the service properties");
343 String containerName = (String) props.get("containerName");
344 if (containerName == null) {
345 logger.error("containerName not supplied");
348 if ((this.topologyServiceShimListeners != null)
349 && this.topologyServiceShimListeners
350 .containsKey(containerName)
351 && this.topologyServiceShimListeners
352 .get(containerName).equals(s)
354 this.topologyServiceShimListeners.remove(containerName);
355 logger.trace("Removed topologyServiceShimListener for container: "
360 void setStatisticsManager(IOFStatisticsManager s) {
364 void unsetStatisticsManager(IOFStatisticsManager s) {
365 if (this.statsMgr == s) {
366 this.statsMgr = null;
370 private void removeNodeConnector(String container,
371 NodeConnector nodeConnector) {
372 Map<NodeConnector, Pair<Edge, Set<Property>>> edgePropsMap = edgeMap
374 if (edgePropsMap == null) {
378 // Remove edge in one direction
379 Pair<Edge, Set<Property>> edgeProps = edgePropsMap.get(nodeConnector);
380 if (edgeProps == null) {
383 notifyEdge(container, edgeProps.getLeft(), UpdateType.REMOVED, null);
385 // Remove edge in another direction
386 edgeProps = edgePropsMap
387 .get(edgeProps.getLeft().getHeadNodeConnector());
388 if (edgeProps == null) {
391 notifyEdge(container, edgeProps.getLeft(), UpdateType.REMOVED, null);
394 private void notifyEdge(String container, Edge edge, UpdateType type,
395 Set<Property> props) {
396 Map<NodeConnector, Pair<Edge, Set<Property>>> edgePropsMap = edgeMap
398 NodeConnector src = edge.getTailNodeConnector();
399 Pair<Edge, Set<Property>> edgeProps = new ImmutablePair<Edge, Set<Property>>(
405 if (edgePropsMap == null) {
406 edgePropsMap = new HashMap<NodeConnector, Pair<Edge, Set<Property>>>();
408 if (edgePropsMap.containsKey(src)
409 && edgePropsMap.get(src).equals(edgeProps)) {
410 // Entry already exists. Return here.
414 edgePropsMap.put(src, edgeProps);
415 edgeMap.put(container, edgePropsMap);
418 if (edgePropsMap != null) {
419 edgePropsMap.remove(src);
420 if (edgePropsMap.isEmpty()) {
421 edgeMap.remove(container);
423 edgeMap.put(container, edgePropsMap);
428 logger.debug("Invalid " + type + " Edge " + edge
429 + " in container {}", container);
433 notifyQ.add(new NotifyEntry(container, edgeProps, type));
435 logger.trace(type + " Edge " + edge + " in container {}", container);
439 public void notifyEdge(Edge edge, UpdateType type, Set<Property> props) {
440 if ((edge == null) || (type == null)) {
444 // Notify default container
445 notifyEdge(GlobalConstants.DEFAULT.toString(), edge, type, props);
447 // Notify the corresponding containers
448 List<String> containers = getEdgeContainers(edge);
449 if (containers != null) {
450 for (String container : containers) {
451 notifyEdge(container, edge, type, props);
457 * Return a list of containers the edge associated with
459 private List<String> getEdgeContainers(Edge edge) {
460 NodeConnector src = edge.getTailNodeConnector(), dst = edge
461 .getHeadNodeConnector();
463 if (!src.getType().equals(
464 NodeConnector.NodeConnectorIDType.PRODUCTION)) {
465 /* Find the common containers for both ends */
466 List<String> srcContainers = this.containerMap.get(src), dstContainers = this.containerMap
467 .get(dst), cmnContainers = null;
468 if ((srcContainers != null) && (dstContainers != null)) {
469 cmnContainers = new ArrayList<String>(srcContainers);
470 cmnContainers.retainAll(dstContainers);
472 return cmnContainers;
475 * If the neighbor is part of a monitored production network, get
476 * the containers that the edge port belongs to
478 return this.containerMap.get(dst);
483 public void tagUpdated(String containerName, Node n, short oldTag,
484 short newTag, UpdateType t) {
488 public void containerFlowUpdated(String containerName,
489 ContainerFlow previousFlow, ContainerFlow currentFlow, UpdateType t) {
493 public void nodeConnectorUpdated(String containerName, NodeConnector p,
495 if (this.containerMap == null) {
496 logger.error("containerMap is NULL");
499 List<String> containers = this.containerMap.get(p);
500 if (containers == null) {
501 containers = new CopyOnWriteArrayList<String>();
503 boolean updateMap = false;
506 if (!containers.contains(containerName)) {
507 containers.add(containerName);
512 if (containers.contains(containerName)) {
513 containers.remove(containerName);
515 removeNodeConnector(containerName, p);
522 if (containers.isEmpty()) {
523 // Do cleanup to reduce memory footprint if no
524 // elements to be tracked
525 this.containerMap.remove(p);
527 this.containerMap.put(p, containers);
533 public void containerModeUpdated(UpdateType t) {
537 private void registerWithOSGIConsole() {
538 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
540 bundleContext.registerService(CommandProvider.class.getName(), this,
545 public String getHelp() {
546 StringBuffer help = new StringBuffer();
547 help.append("---Topology Service Shim---\n");
549 .append("\t pem [container] - Print edgeMap entries for a given container\n");
550 return help.toString();
553 public void _pem(CommandInterpreter ci) {
554 String container = ci.nextArgument();
555 if (container == null) {
556 container = GlobalConstants.DEFAULT.toString();
559 ci.println("Container: " + container);
561 .println(" Edge Bandwidth");
563 Map<NodeConnector, Pair<Edge, Set<Property>>> edgePropsMap = edgeMap
565 if (edgePropsMap == null) {
568 for (Pair<Edge, Set<Property>> edgeProps : edgePropsMap.values()) {
569 if (edgeProps == null) {
574 for (Property prop : edgeProps.getRight()) {
575 if (prop.getName().equals(Bandwidth.BandwidthPropName)) {
576 bw = ((Bandwidth) prop).getValue();
580 ci.println(edgeProps.getLeft() + " " + bw);
584 public void _bwfactor(CommandInterpreter ci) {
585 String factorString = ci.nextArgument();
586 if (factorString == null) {
587 ci.println("Bw threshold: " + this.bwThresholdFactor);
588 ci.println("Insert a non null bw threshold");
591 bwThresholdFactor = Float.parseFloat(factorString);
592 ci.println("New Bw threshold: " + this.bwThresholdFactor);
596 * This method will trigger topology updates to be sent
597 * toward SAL. SAL then pushes the updates to ALL the applications
598 * that have registered as listeners for this service. SAL has no
599 * way of knowing which application requested for the refresh.
601 * As an example of this case, is stopping and starting the
602 * Topology Manager. When the topology Manager is stopped,
603 * and restarted, it will no longer have the latest topology.
604 * Hence, a request is sent here.
606 * @param containerName
610 public void requestRefresh(String containerName) {
611 // wake up a bulk update thread and exit
612 // the thread will execute the bulkUpdate()
613 bulkNotifyQ.add(containerName);
617 * Reading the current topology database, the method will replay
618 * all the edge updates for the ITopologyServiceShimListener instance
619 * in the given container, which will in turn publish them toward SAL.
620 * @param containerName
622 private void TopologyBulkUpdate(String containerName) {
623 Map<NodeConnector, Pair<Edge, Set<Property>>> edgePropMap = null;
625 logger.debug("Try bulk update for container:{}", containerName);
626 edgePropMap = edgeMap.get(containerName);
627 if (edgePropMap == null) {
628 logger.debug("No edges known for container:{}", containerName);
631 ITopologyServiceShimListener topologServiceShimListener = topologyServiceShimListeners
633 if (topologServiceShimListener == null) {
634 logger.debug("No topology service shim listener for container:{}",
639 for (Pair<Edge, Set<Property>> edgeProps : edgePropMap.values()) {
640 if (edgeProps != null) {
642 logger.trace("Add edge {}", edgeProps.getLeft());
643 topologServiceShimListener.edgeUpdate(edgeProps.getLeft(),
644 UpdateType.ADDED, edgeProps.getRight());
647 logger.debug("Sent {} updates", i);