Bug 4957 TxChainManager lifecycle startup cleaning
[openflowplugin.git] / applications / statistics-manager / src / main / java / org / opendaylight / openflowplugin / applications / statistics / manager / impl / StatisticsManagerImpl.java
1 /**
2  * Copyright (c) 2014 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.openflowplugin.applications.statistics.manager.impl;
10
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;
16 import java.util.Map;
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;
54
55 /**
56 * statistics-manager
57 * org.opendaylight.openflowplugin.applications.statistics.manager.impl
58 *
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.
65 *
66 * @author avishnoi@in.ibm.com <a href="mailto:vdemcak@cisco.com">Vaclav Demcak</a>
67 *
68 */
69 public class StatisticsManagerImpl implements StatisticsManager, Runnable {
70
71    private static final Logger LOG = LoggerFactory.getLogger(StatisticsManagerImpl.class);
72
73    private static final int QUEUE_DEPTH = 5000;
74    private static final int MAX_BATCH = 100;
75
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);
79
80
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;
89
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;
97
98    private final StatisticsManagerConfig statManagerConfig;
99
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);
109    }
110
111    @Override
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);
124
125        statRpcMsgManagerExecutor.execute(rpcMsgManager);
126        statDataStoreOperationServ.execute(this);
127        LOG.info("Statistics Manager started successfully!");
128    }
129
130    private <T extends AutoCloseable> T close(final T closeable) throws Exception {
131        if (closeable != null) {
132            closeable.close();
133        }
134        return null;
135    }
136
137    @Override
138    public void close() throws Exception {
139        LOG.info("StatisticsManager close called");
140        finishing = true;
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);
151            }
152            statCollectors = null;
153        }
154        rpcMsgManager = close(rpcMsgManager);
155        statRpcMsgManagerExecutor.shutdown();
156        statDataStoreOperationServ.shutdown();
157        txChain = close(txChain);
158    }
159
160    @Override
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);
164        if ( ! success) {
165            LOG.debug("Stat DS/Operational submitter Queue is full!");
166        }
167    }
168
169    @Override
170    public void run() {
171        /* Neverending cyle - wait for finishing */
172        while ( ! finishing) {
173            StatDataStoreOperation op = null;
174            try {
175                op = dataStoreOperQueue.take();
176                final ReadWriteTransaction tx = txChain.newReadWriteTransaction();
177                LOG.trace("New operations available, starting transaction {}", tx.getIdentifier());
178
179                int ops = 0;
180                do {
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);
188                        ops++;
189                    } else {
190                        LOG.debug("{} not found or UUID mismatch for statistics datastore operation", op.getNodeIdentifier());
191                    }
192
193                    if (ops < MAX_BATCH) {
194                        op = dataStoreOperQueue.poll();
195                    } else {
196                        op = null;
197                    }
198                } while (op != null);
199
200                LOG.trace("Processed {} operations, submitting transaction {}", ops, tx.getIdentifier());
201
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);
206                finishing = true;
207            } catch (final Exception e) {
208                LOG.warn("Unhandled exception during processing statistics for {}. " +
209                        "Restarting transaction chain.",op != null?op.getNodeId().getValue():"",e);
210                txChain.close();
211                txChain = dataBroker.createTransactionChain(StatisticsManagerImpl.this);
212                cleanDataStoreOperQueue();
213            }
214        }
215        // Drain all events, making sure any blocked threads are unblocked
216        cleanDataStoreOperQueue();
217    }
218
219    private synchronized void cleanDataStoreOperQueue() {
220        // Drain all events, making sure any blocked threads are unblocked
221        while (! dataStoreOperQueue.isEmpty()) {
222            dataStoreOperQueue.poll();
223        }
224    }
225
226    @Override
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);
230    }
231
232    @Override
233    public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
234        // NOOP
235    }
236
237    @Override
238    public boolean isProvidedFlowNodeActive(final InstanceIdentifier<Node> nodeIdent) {
239        for (final StatPermCollector collector : statCollectors) {
240            if (collector.isProvidedFlowNodeActive(nodeIdent)) {
241                return true;
242            }
243        }
244        return false;
245    }
246
247    @Override
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);
252            }
253        }
254    }
255
256     @Override
257     public void connectedNodeRegistration(final InstanceIdentifier<Node> nodeIdent,
258             final List<StatCapabTypes> statTypes, final Short nrOfSwitchTables) {
259
260
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
266
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());
276                         return;
277                     }
278                 }
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());
284
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());
290
291                 newCollector.connectedNodeRegistration(nodeIdent, statTypes, nrOfSwitchTables);
292             }
293
294
295         } else {
296             // add to the collector, even if it rejects it.
297             collectorUUIDPair.getLeft().connectedNodeRegistration(nodeIdent, statTypes, nrOfSwitchTables);
298         }
299     }
300
301
302     @Override
303     public void disconnectedNodeUnregistration(final InstanceIdentifier<Node> nodeIdent) {
304         flowListeningCommiter.cleanForDisconnect(nodeIdent);
305
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());
312
313                 if (collector.disconnectedNodeUnregistration(nodeIdent)) {
314                     if (!collector.hasActiveNodes()) {
315                         synchronized (statCollectorLock) {
316                             if (collector.hasActiveNodes()) {
317                                 return;
318                             }
319                             final List<StatPermCollector> newStatColl = new ArrayList<>(statCollectors);
320                             newStatColl.remove(collector);
321                             statCollectors = Collections.unmodifiableList(newStatColl);
322                         }
323                     }
324                     LOG.info("Node:{} successfully removed by StatisticsManager ", nodeIdent);
325                 } else {
326                     LOG.error("Collector not disconnecting for node, no operations will be committed for this node:{}", nodeIdent);
327                 }
328             } else {
329                 LOG.error("Unexpected error, collector not found in collectorUUIDPair for node:{}, UUID:{}", nodeIdent, collectorUUIDPair.getRight());
330             }
331
332         } else {
333             LOG.error("Received node removed for {}, but unable to find it in nodeCollectorMap", nodeIdent);
334         }
335     }
336
337    @Override
338    public void registerAdditionalNodeFeature(final InstanceIdentifier<Node> nodeIdent,
339            final StatCapabTypes statCapab) {
340        for (final StatPermCollector collector : statCollectors) {
341            if (collector.registerAdditionalNodeFeature(nodeIdent, statCapab)) {
342                return;
343            }
344        }
345        LOG.debug("Node {} has not been extended for feature {}!", nodeIdent, statCapab);
346    }
347
348    /* Getter internal Statistic Manager Job Classes */
349    @Override
350    public StatRpcMsgManager getRpcMsgManager() {
351        return rpcMsgManager;
352    }
353
354    @Override
355    public StatNodeRegistration getNodeRegistrator() {
356        return nodeRegistrator;
357    }
358
359    @Override
360    public StatListeningCommiter<Flow, OpendaylightFlowStatisticsListener> getFlowListenComit() {
361        return flowListeningCommiter;
362    }
363
364    @Override
365    public StatListeningCommiter<Meter, OpendaylightMeterStatisticsListener> getMeterListenCommit() {
366        return meterListeningCommiter;
367    }
368
369    @Override
370    public StatListeningCommiter<Group, OpendaylightGroupStatisticsListener> getGroupListenCommit() {
371        return groupListeningCommiter;
372    }
373
374    @Override
375    public StatListeningCommiter<Queue, OpendaylightQueueStatisticsListener> getQueueNotifyCommit() {
376        return queueNotifyCommiter;
377    }
378
379
380    @Override
381    public StatNotifyCommiter<OpendaylightFlowTableStatisticsListener> getTableNotifCommit() {
382        return tableNotifCommiter;
383    }
384
385    @Override
386    public StatNotifyCommiter<OpendaylightPortStatisticsListener> getPortNotifyCommit() {
387        return portNotifyCommiter;
388    }
389
390     @Override
391     public StatisticsManagerConfig getConfiguration() {
392         return statManagerConfig;
393     }
394
395     @Override
396     public UUID getGeneratedUUIDForNode(InstanceIdentifier<Node> nodeInstanceIdentifier) {
397         Pair<StatPermCollector, UUID> permCollectorUUIDPair = nodeCollectorMap.get(nodeInstanceIdentifier);
398         if (permCollectorUUIDPair != null) {
399             return permCollectorUUIDPair.getRight();
400         }
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");
403     }
404 }
405