2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.openflowplugin.applications.statistics.manager.impl;
11 import com.google.common.base.Preconditions;
12 import com.google.common.util.concurrent.ThreadFactoryBuilder;
13 import java.util.ArrayList;
14 import java.util.Collections;
15 import java.util.List;
17 import java.util.UUID;
18 import java.util.concurrent.BlockingQueue;
19 import java.util.concurrent.ConcurrentHashMap;
20 import java.util.concurrent.ExecutorService;
21 import java.util.concurrent.Executors;
22 import java.util.concurrent.LinkedBlockingDeque;
23 import java.util.concurrent.ThreadFactory;
24 import java.util.concurrent.atomic.AtomicInteger;
25 import org.opendaylight.controller.md.sal.binding.api.BindingTransactionChain;
26 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
27 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
28 import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
29 import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
30 import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
31 import org.opendaylight.controller.sal.binding.api.RpcConsumerRegistry;
32 import org.opendaylight.openflowplugin.applications.statistics.manager.StatListeningCommiter;
33 import org.opendaylight.openflowplugin.applications.statistics.manager.StatNodeRegistration;
34 import org.opendaylight.openflowplugin.applications.statistics.manager.StatNotifyCommiter;
35 import org.opendaylight.openflowplugin.applications.statistics.manager.StatPermCollector;
36 import org.opendaylight.openflowplugin.applications.statistics.manager.StatPermCollector.StatCapabTypes;
37 import org.opendaylight.openflowplugin.applications.statistics.manager.StatRpcMsgManager;
38 import org.opendaylight.openflowplugin.applications.statistics.manager.StatisticsManager;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.Meter;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.OpendaylightFlowStatisticsListener;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.OpendaylightFlowTableStatisticsListener;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.queues.Queue;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.OpendaylightGroupStatisticsListener;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.OpendaylightMeterStatisticsListener;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.OpendaylightPortStatisticsListener;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.OpendaylightQueueStatisticsListener;
51 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
57 * org.opendaylight.openflowplugin.applications.statistics.manager.impl
59 * StatisticsManagerImpl
60 * It represent a central point for whole module. Implementation
61 * {@link StatisticsManager} registers all Operation/DS {@link StatNotifyCommiter} and
62 * Config/DS {@link StatListeningCommiter}, as well as {@link StatPermCollector}
63 * for statistic collecting and {@link StatRpcMsgManager} as Device RPCs provider.
64 * In next, StatisticsManager provides all DS contact Transaction services.
66 * @author avishnoi@in.ibm.com <a href="mailto:vdemcak@cisco.com">Vaclav Demcak</a>
69 public class StatisticsManagerImpl implements StatisticsManager, Runnable {
71 private static final Logger LOG = LoggerFactory.getLogger(StatisticsManagerImpl.class);
73 private static final int QUEUE_DEPTH = 5000;
74 private static final int MAX_BATCH = 100;
76 private final BlockingQueue<StatDataStoreOperation> dataStoreOperQueue = new LinkedBlockingDeque<>(QUEUE_DEPTH);
77 private final Map<InstanceIdentifier<Node>, Pair<StatPermCollector, UUID>> nodeCollectorMap = new ConcurrentHashMap<>();
78 private AtomicInteger numNodesBeingCollected = new AtomicInteger(0);
81 private final DataBroker dataBroker;
82 private final ExecutorService statRpcMsgManagerExecutor;
83 private final ExecutorService statDataStoreOperationServ;
84 private StatRpcMsgManager rpcMsgManager;
85 private List<StatPermCollector> statCollectors;
86 private final Object statCollectorLock = new Object();
87 private BindingTransactionChain txChain;
88 private volatile boolean finishing = false;
90 private StatNodeRegistration nodeRegistrator;
91 private StatListeningCommiter<Flow, OpendaylightFlowStatisticsListener> flowListeningCommiter;
92 private StatListeningCommiter<Meter, OpendaylightMeterStatisticsListener> meterListeningCommiter;
93 private StatListeningCommiter<Group, OpendaylightGroupStatisticsListener> groupListeningCommiter;
94 private StatListeningCommiter<Queue, OpendaylightQueueStatisticsListener> queueNotifyCommiter;
95 private StatNotifyCommiter<OpendaylightFlowTableStatisticsListener> tableNotifCommiter;
96 private StatNotifyCommiter<OpendaylightPortStatisticsListener> portNotifyCommiter;
98 private final StatisticsManagerConfig statManagerConfig;
100 public StatisticsManagerImpl (final DataBroker dataBroker, final StatisticsManagerConfig statManagerconfig) {
101 statManagerConfig = Preconditions.checkNotNull(statManagerconfig);
102 this.dataBroker = Preconditions.checkNotNull(dataBroker, "DataBroker can not be null!");
103 ThreadFactory threadFact;
104 threadFact = new ThreadFactoryBuilder().setNameFormat("odl-stat-rpc-oper-thread-%d").build();
105 statRpcMsgManagerExecutor = Executors.newSingleThreadExecutor(threadFact);
106 threadFact = new ThreadFactoryBuilder().setNameFormat("odl-stat-ds-oper-thread-%d").build();
107 statDataStoreOperationServ = Executors.newSingleThreadExecutor(threadFact);
108 txChain = dataBroker.createTransactionChain(this);
112 public void start(final NotificationProviderService notifService,
113 final RpcConsumerRegistry rpcRegistry) {
114 Preconditions.checkArgument(rpcRegistry != null, "RpcConsumerRegistry can not be null !");
115 rpcMsgManager = new StatRpcMsgManagerImpl(this, rpcRegistry, statManagerConfig.getMaxNodesForCollector());
116 statCollectors = Collections.emptyList();
117 nodeRegistrator = new StatNodeRegistrationImpl(this, dataBroker, notifService);
118 flowListeningCommiter = new StatListenCommitFlow(this, dataBroker, notifService);
119 meterListeningCommiter = new StatListenCommitMeter(this, dataBroker, notifService);
120 groupListeningCommiter = new StatListenCommitGroup(this, dataBroker, notifService);
121 tableNotifCommiter = new StatNotifyCommitTable(this, notifService);
122 portNotifyCommiter = new StatNotifyCommitPort(this, notifService);
123 queueNotifyCommiter = new StatListenCommitQueue(this, dataBroker, notifService);
125 statRpcMsgManagerExecutor.execute(rpcMsgManager);
126 statDataStoreOperationServ.execute(this);
127 LOG.info("Statistics Manager started successfully!");
130 private <T extends AutoCloseable> T close(final T closeable) throws Exception {
131 if (closeable != null) {
138 public void close() throws Exception {
139 LOG.info("StatisticsManager close called");
141 nodeRegistrator = close(nodeRegistrator);
142 flowListeningCommiter = close(flowListeningCommiter);
143 meterListeningCommiter = close(meterListeningCommiter);
144 groupListeningCommiter = close(groupListeningCommiter);
145 tableNotifCommiter = close(tableNotifCommiter);
146 portNotifyCommiter = close(portNotifyCommiter);
147 queueNotifyCommiter = close(queueNotifyCommiter);
148 if (statCollectors != null) {
149 for (StatPermCollector collector : statCollectors) {
150 collector = close(collector);
152 statCollectors = null;
154 rpcMsgManager = close(rpcMsgManager);
155 statRpcMsgManagerExecutor.shutdown();
156 statDataStoreOperationServ.shutdown();
157 txChain = close(txChain);
161 public void enqueue(final StatDataStoreOperation op) {
162 // we don't need to block anything - next statistics come soon
163 final boolean success = dataStoreOperQueue.offer(op);
165 LOG.debug("Stat DS/Operational submitter Queue is full!");
171 /* Neverending cyle - wait for finishing */
172 while ( ! finishing) {
173 StatDataStoreOperation op = null;
175 op = dataStoreOperQueue.take();
176 final ReadWriteTransaction tx = txChain.newReadWriteTransaction();
177 LOG.trace("New operations available, starting transaction {}", tx.getIdentifier());
181 Pair<StatPermCollector, UUID> statPermCollectorUUIDPair = nodeCollectorMap.get(op.getNodeIdentifier());
182 if (statPermCollectorUUIDPair != null && statPermCollectorUUIDPair.getRight().equals(op.getNodeUUID())) {
183 // dont apply operations for nodes which have been disconnected or if there uuids do not match
184 // this can happen if operations are queued and node is removed.
185 // if the uuids dont match, it means that the stat operation are stale and belong to the same node
186 // which got disconnected and connected again.
187 op.applyOperation(tx);
190 LOG.debug("{} not found or UUID mismatch for statistics datastore operation", op.getNodeIdentifier());
193 if (ops < MAX_BATCH) {
194 op = dataStoreOperQueue.poll();
198 } while (op != null);
200 LOG.trace("Processed {} operations, submitting transaction {}", ops, tx.getIdentifier());
202 tx.submit().checkedGet();
203 } catch (final InterruptedException e) {
204 LOG.warn("Stat Manager DS Operation thread interrupted, while " +
205 "waiting for StatDataStore Operation task!", e);
207 } catch (final Exception e) {
208 LOG.warn("Unhandled exception during processing statistics for {}. " +
209 "Restarting transaction chain.",op != null?op.getNodeId().getValue():"",e);
211 txChain = dataBroker.createTransactionChain(StatisticsManagerImpl.this);
212 cleanDataStoreOperQueue();
215 // Drain all events, making sure any blocked threads are unblocked
216 cleanDataStoreOperQueue();
219 private synchronized void cleanDataStoreOperQueue() {
220 // Drain all events, making sure any blocked threads are unblocked
221 while (! dataStoreOperQueue.isEmpty()) {
222 dataStoreOperQueue.poll();
227 public void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction,
228 final Throwable cause) {
229 LOG.warn("Failed to export Flow Capable Statistics, Transaction {} failed.",transaction.getIdentifier(),cause);
233 public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
238 public boolean isProvidedFlowNodeActive(final InstanceIdentifier<Node> nodeIdent) {
239 for (final StatPermCollector collector : statCollectors) {
240 if (collector.isProvidedFlowNodeActive(nodeIdent)) {
248 public void collectNextStatistics(final InstanceIdentifier<Node> nodeIdent, final TransactionId xid) {
249 for (final StatPermCollector collector : statCollectors) {
250 if (collector.isProvidedFlowNodeActive(nodeIdent)) {
251 collector.collectNextStatistics(xid);
257 public void connectedNodeRegistration(final InstanceIdentifier<Node> nodeIdent,
258 final List<StatCapabTypes> statTypes, final Short nrOfSwitchTables) {
261 Pair<StatPermCollector, UUID> collectorUUIDPair = nodeCollectorMap.get(nodeIdent);
262 if (collectorUUIDPair == null) {
263 // no collector contains this node,
264 // check if one of the collectors can accommodate it
265 // if no then add a new collector
267 synchronized(statCollectorLock) {
268 for (int i = statCollectors.size() - 1; i >= 0; i--) {
269 // start from back of the list as most likely previous ones might be full
270 final StatPermCollector aCollector = statCollectors.get(i);
271 if (aCollector.connectedNodeRegistration(nodeIdent, statTypes, nrOfSwitchTables)) {
272 // if the collector returns true after adding node, then return
273 nodeCollectorMap.put(nodeIdent, new Pair(aCollector, UUID.randomUUID()));
274 LOG.debug("NodeAdded: Num Nodes Registered with StatisticsManager:{}",
275 numNodesBeingCollected.incrementAndGet());
279 // no collector was able to add this node
280 LOG.info("No existing collector found for new node. Creating a new collector for {}", nodeIdent);
281 final StatPermCollectorImpl newCollector = new StatPermCollectorImpl(this,
282 statManagerConfig.getMinRequestNetMonitorInterval(), statCollectors.size() + 1,
283 statManagerConfig.getMaxNodesForCollector());
285 final List<StatPermCollector> statCollectorsNew = new ArrayList<>(statCollectors);
286 statCollectorsNew.add(newCollector);
287 statCollectors = Collections.unmodifiableList(statCollectorsNew);
288 nodeCollectorMap.put(nodeIdent, new Pair(newCollector, UUID.randomUUID()));
289 LOG.debug("NodeAdded: Num Nodes Registered with StatisticsManager:{}", numNodesBeingCollected.incrementAndGet());
291 newCollector.connectedNodeRegistration(nodeIdent, statTypes, nrOfSwitchTables);
296 // add to the collector, even if it rejects it.
297 collectorUUIDPair.getLeft().connectedNodeRegistration(nodeIdent, statTypes, nrOfSwitchTables);
303 public void disconnectedNodeUnregistration(final InstanceIdentifier<Node> nodeIdent) {
304 flowListeningCommiter.cleanForDisconnect(nodeIdent);
306 Pair<StatPermCollector, UUID> collectorUUIDPair = nodeCollectorMap.get(nodeIdent);
307 if (collectorUUIDPair != null) {
308 StatPermCollector collector = collectorUUIDPair.getLeft();
309 if (collector != null) {
310 nodeCollectorMap.remove(nodeIdent);
311 LOG.debug("NodeRemoved: Num Nodes Registered with StatisticsManager:{}", numNodesBeingCollected.decrementAndGet());
313 if (collector.disconnectedNodeUnregistration(nodeIdent)) {
314 if (!collector.hasActiveNodes()) {
315 synchronized (statCollectorLock) {
316 if (collector.hasActiveNodes()) {
319 final List<StatPermCollector> newStatColl = new ArrayList<>(statCollectors);
320 newStatColl.remove(collector);
321 statCollectors = Collections.unmodifiableList(newStatColl);
324 LOG.info("Node:{} successfully removed by StatisticsManager ", nodeIdent);
326 LOG.error("Collector not disconnecting for node, no operations will be committed for this node:{}", nodeIdent);
329 LOG.error("Unexpected error, collector not found in collectorUUIDPair for node:{}, UUID:{}", nodeIdent, collectorUUIDPair.getRight());
333 LOG.error("Received node removed for {}, but unable to find it in nodeCollectorMap", nodeIdent);
338 public void registerAdditionalNodeFeature(final InstanceIdentifier<Node> nodeIdent,
339 final StatCapabTypes statCapab) {
340 for (final StatPermCollector collector : statCollectors) {
341 if (collector.registerAdditionalNodeFeature(nodeIdent, statCapab)) {
345 LOG.debug("Node {} has not been extended for feature {}!", nodeIdent, statCapab);
348 /* Getter internal Statistic Manager Job Classes */
350 public StatRpcMsgManager getRpcMsgManager() {
351 return rpcMsgManager;
355 public StatNodeRegistration getNodeRegistrator() {
356 return nodeRegistrator;
360 public StatListeningCommiter<Flow, OpendaylightFlowStatisticsListener> getFlowListenComit() {
361 return flowListeningCommiter;
365 public StatListeningCommiter<Meter, OpendaylightMeterStatisticsListener> getMeterListenCommit() {
366 return meterListeningCommiter;
370 public StatListeningCommiter<Group, OpendaylightGroupStatisticsListener> getGroupListenCommit() {
371 return groupListeningCommiter;
375 public StatListeningCommiter<Queue, OpendaylightQueueStatisticsListener> getQueueNotifyCommit() {
376 return queueNotifyCommiter;
381 public StatNotifyCommiter<OpendaylightFlowTableStatisticsListener> getTableNotifCommit() {
382 return tableNotifCommiter;
386 public StatNotifyCommiter<OpendaylightPortStatisticsListener> getPortNotifyCommit() {
387 return portNotifyCommiter;
391 public StatisticsManagerConfig getConfiguration() {
392 return statManagerConfig;
396 public UUID getGeneratedUUIDForNode(InstanceIdentifier<Node> nodeInstanceIdentifier) {
397 Pair<StatPermCollector, UUID> permCollectorUUIDPair = nodeCollectorMap.get(nodeInstanceIdentifier);
398 if (permCollectorUUIDPair != null) {
399 return permCollectorUUIDPair.getRight();
401 // we dont want to mark operations with null uuid and get NPEs later. So mark them with invalid ones
402 return UUID.fromString("invalid-uuid");