2 * Copyright (c) 2016 Red Hat, 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
8 package org.opendaylight.mdsal.trace.impl;
10 import static java.util.Objects.requireNonNull;
12 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
13 import java.io.PrintStream;
14 import java.util.ArrayList;
15 import java.util.List;
17 import org.opendaylight.mdsal.binding.dom.codec.api.BindingCodecTree;
18 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
19 import org.opendaylight.mdsal.dom.api.ClusteredDOMDataTreeChangeListener;
20 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
21 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction;
22 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
23 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
24 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
25 import org.opendaylight.mdsal.trace.api.TracingDOMDataBroker;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.mdsaltrace.rev160908.Config;
27 import org.opendaylight.yangtools.yang.binding.DataObject;
28 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
33 @SuppressWarnings("checkstyle:JavadocStyle")
34 //...because otherwise it whines about the elements in the @code block even though it's completely valid Javadoc
36 * TracingBroker logs "write" operations and listener registrations to the md-sal. It logs the instance identifier path,
37 * the objects themselves, as well as the stack trace of the call invoking the registration or write operation.
38 * It works by operating as a "bump on the stack" between the application and actual DataBroker, intercepting write
39 * and registration calls and writing to the log.
41 * <p>In addition, it (optionally) can also keep track of the stack trace of all new transaction allocations
42 * (including TransactionChains, and transactions created in turn from them), in order to detect and report leaks
43 * from transactions which were not closed.
46 * TracingBroker is designed to be easy to use. In fact, for bundles using Blueprint to inject their DataBroker
47 * TracingBroker can be used without modifying your code at all in two simple steps:
50 * Simply add the dependency "mdsaltrace-features" to
55 * <groupId>org.opendaylight.controller</groupId>
56 * <artifactId>features-mdsal-trace</artifactId>
57 * <version>1.7.0-SNAPSHOT</version>
58 * <classifier>features</classifier>
60 * <scope>runtime</scope>
66 * Then just "feature:install odl-mdsal-trace" before you install your "real" feature(s) and you're done.
67 * Beware that with Karaf 4 due to <a href="https://bugs.opendaylight.org/show_bug.cgi?id=9068">Bug 9068</a>
68 * you'll probably have to use feature:install's --no-auto-refresh flag when installing your "real" feature.
71 * This works because the mdsaltrace-impl bundle registers its service implementing DOMDataBroker with a higher
72 * rank than sal-binding-broker. As such, any OSGi service lookup for DataBroker will receive the TracingBroker.
74 * <h1>Avoiding log bloat:</h1>
75 * TracingBroker can be configured to only print registrations or write ops pertaining to certain subtrees of the
76 * md-sal. This can be done in the code via the methods of this class or via a config file. TracingBroker uses a more
77 * convenient but non-standard representation of the instance identifiers. Each instance identifier segment's
78 * class.getSimpleName() is used separated by a '/'.
80 * <h1>Known issues</h1>
83 * Filtering by paths. For some registrations the codec that converts back from the DOM to binding paths is
84 * busted. As such, an aproximated path is used in the output. For now it is recommended not to use
85 * watchRegistrations and allow all registrations to be logged.
89 public class TracingBroker implements TracingDOMDataBroker {
90 private static final Logger LOG = LoggerFactory.getLogger(TracingBroker.class);
92 private static final int STACK_TRACE_FIRST_RELEVANT_FRAME = 2;
94 private final BindingCodecTree codec;
95 private final DOMDataBroker delegate;
96 private final List<Watch> registrationWatches = new ArrayList<>();
97 private final List<Watch> writeWatches = new ArrayList<>();
99 private final boolean isDebugging;
100 private final CloseTrackedRegistry<TracingTransactionChain> transactionChainsRegistry;
101 private final CloseTrackedRegistry<TracingReadOnlyTransaction> readOnlyTransactionsRegistry;
102 private final CloseTrackedRegistry<TracingWriteTransaction> writeTransactionsRegistry;
103 private final CloseTrackedRegistry<TracingReadWriteTransaction> readWriteTransactionsRegistry;
105 private class Watch {
106 final String iidString;
107 final LogicalDatastoreType store;
109 Watch(final String iidString, final LogicalDatastoreType storeOrNull) {
111 this.iidString = iidString;
114 private String toIidCompString(final YangInstanceIdentifier iid) {
115 StringBuilder builder = new StringBuilder();
116 toPathString(iid, builder);
117 return builder.append('/').toString();
120 private boolean isParent(final String parent, final String child) {
121 int parentOffset = 0;
122 if (parent.length() > 0 && parent.charAt(0) == '<') {
123 parentOffset = parent.indexOf('>') + 1;
127 if (child.length() > 0 && child.charAt(0) == '<') {
128 childOffset = child.indexOf('>') + 1;
131 return child.startsWith(parent.substring(parentOffset), childOffset);
134 @SuppressWarnings({ "checkstyle:hiddenField", "hiding" })
135 public boolean subtreesOverlap(final YangInstanceIdentifier iid, final LogicalDatastoreType store) {
136 if (this.store != null && !this.store.equals(store)) {
140 String otherIidString = toIidCompString(iid);
141 return isParent(iidString, otherIidString) || isParent(otherIidString, iidString);
144 @SuppressWarnings({ "checkstyle:hiddenField", "hiding" })
145 public boolean eventIsOfInterest(final YangInstanceIdentifier iid, final LogicalDatastoreType store) {
146 if (this.store != null && !this.store.equals(store)) {
150 return isParent(iidString, toPathString(iid));
154 public TracingBroker(final DOMDataBroker delegate, final Config config, final BindingCodecTree codec) {
155 this.delegate = requireNonNull(delegate, "delegate");
156 this.codec = requireNonNull(codec, "codec");
159 isDebugging = Boolean.TRUE.equals(config.getTransactionDebugContextEnabled());
160 final String db = "DataBroker";
161 transactionChainsRegistry = new CloseTrackedRegistry<>(db, "createTransactionChain()", isDebugging);
162 readOnlyTransactionsRegistry = new CloseTrackedRegistry<>(db, "newReadOnlyTransaction()", isDebugging);
163 writeTransactionsRegistry = new CloseTrackedRegistry<>(db, "newWriteOnlyTransaction()", isDebugging);
164 readWriteTransactionsRegistry = new CloseTrackedRegistry<>(db, "newReadWriteTransaction()", isDebugging);
167 private void configure(final Config config) {
168 registrationWatches.clear();
169 Set<String> paths = config.getRegistrationWatches();
171 for (String path : paths) {
172 watchRegistrations(path, null);
176 writeWatches.clear();
177 paths = config.getWriteWatches();
179 for (String path : paths) {
180 watchWrites(path, null);
186 * Log registrations to this subtree of the md-sal.
187 * @param iidString the iid path of the root of the subtree
188 * @param store Which LogicalDataStore? or null for both
190 public void watchRegistrations(final String iidString, final LogicalDatastoreType store) {
191 LOG.info("Watching registrations to {} in {}", iidString, store);
192 registrationWatches.add(new Watch(iidString, store));
196 * Log writes to this subtree of the md-sal.
197 * @param iidString the iid path of the root of the subtree
198 * @param store Which LogicalDataStore? or null for both
200 public void watchWrites(final String iidString, final LogicalDatastoreType store) {
201 LOG.info("Watching writes to {} in {}", iidString, store);
202 Watch watch = new Watch(iidString, store);
203 writeWatches.add(watch);
206 private boolean isRegistrationWatched(final YangInstanceIdentifier iid, final LogicalDatastoreType store) {
207 if (registrationWatches.isEmpty()) {
211 for (Watch regInterest : registrationWatches) {
212 if (regInterest.subtreesOverlap(iid, store)) {
220 boolean isWriteWatched(final YangInstanceIdentifier iid, final LogicalDatastoreType store) {
221 if (writeWatches.isEmpty()) {
225 for (Watch watch : writeWatches) {
226 if (watch.eventIsOfInterest(iid, store)) {
234 static void toPathString(final InstanceIdentifier<? extends DataObject> iid, final StringBuilder builder) {
235 for (var pathArg : iid.getPathArguments()) {
236 builder.append('/').append(pathArg.type().getSimpleName());
240 String toPathString(final YangInstanceIdentifier yiid) {
241 StringBuilder sb = new StringBuilder();
242 toPathString(yiid, sb);
243 return sb.toString();
247 private void toPathString(final YangInstanceIdentifier yiid, final StringBuilder sb) {
248 InstanceIdentifier<?> iid = codec.getInstanceIdentifierCodec().toBinding(yiid);
250 reconstructIidPathString(yiid, sb);
252 toPathString(iid, sb);
256 private static void reconstructIidPathString(final YangInstanceIdentifier yiid, final StringBuilder sb) {
257 sb.append("<RECONSTRUCTED FROM: \"").append(yiid.toString()).append("\">");
258 for (YangInstanceIdentifier.PathArgument pathArg : yiid.getPathArguments()) {
259 sb.append('/').append(pathArg.getNodeType().getLocalName());
263 String getStackSummary() {
264 StackTraceElement[] stack = Thread.currentThread().getStackTrace();
266 StringBuilder sb = new StringBuilder();
267 for (int i = STACK_TRACE_FIRST_RELEVANT_FRAME; i < stack.length; i++) {
268 StackTraceElement frame = stack[i];
269 sb.append("\n\t(TracingBroker)\t").append(frame.getClassName()).append('.').append(frame.getMethodName());
272 return sb.toString();
276 public DOMDataTreeReadWriteTransaction newReadWriteTransaction() {
277 return new TracingReadWriteTransaction(delegate.newReadWriteTransaction(), this, readWriteTransactionsRegistry);
281 public DOMDataTreeWriteTransaction newWriteOnlyTransaction() {
282 return new TracingWriteTransaction(delegate.newWriteOnlyTransaction(), this, writeTransactionsRegistry);
286 public DOMTransactionChain createTransactionChain() {
287 return new TracingTransactionChain(delegate.createTransactionChain(), this, transactionChainsRegistry);
291 public DOMTransactionChain createMergingTransactionChain() {
292 return new TracingTransactionChain(delegate.createMergingTransactionChain(), this, transactionChainsRegistry);
296 public DOMDataTreeReadTransaction newReadOnlyTransaction() {
297 return new TracingReadOnlyTransaction(delegate.newReadOnlyTransaction(), readOnlyTransactionsRegistry);
301 public <T extends Extension> T extension(final Class<T> type) {
302 final var ext = delegate.extension(type);
303 if (DataTreeChangeExtension.class.equals(type) && ext instanceof DataTreeChangeExtension treeChange) {
304 return type.cast((DataTreeChangeExtension) (domDataTreeIdentifier, listener) -> {
305 final var rootId = domDataTreeIdentifier.path();
306 if (isRegistrationWatched(rootId, domDataTreeIdentifier.datastore())) {
307 LOG.warn("{} registration (registerDataTreeChangeListener) for {} from {}.",
308 listener instanceof ClusteredDOMDataTreeChangeListener ? "Clustered" : "Non-clustered",
309 toPathString(rootId), getStackSummary());
311 return treeChange.registerDataTreeChangeListener(domDataTreeIdentifier, listener);
318 public boolean printOpenTransactions(final PrintStream ps, final int minOpenTXs) {
319 if (transactionChainsRegistry.getAllUnique().isEmpty()
320 && readOnlyTransactionsRegistry.getAllUnique().isEmpty()
321 && writeTransactionsRegistry.getAllUnique().isEmpty()
322 && readWriteTransactionsRegistry.getAllUnique().isEmpty()) {
324 ps.println("No open transactions, great!");
328 ps.println(getClass().getSimpleName() + " found some not yet (or never..) closed transaction[chain]s!");
329 ps.println("[NB: If no stack traces are shown below, then "
330 + "enable transaction-debug-context-enabled in mdsaltrace_config.xml]");
332 // Flag to track if we really found any real leaks with more (or equal) to minOpenTXs
333 boolean hasFound = print(readOnlyTransactionsRegistry, ps, " ", minOpenTXs);
334 hasFound |= print(writeTransactionsRegistry, ps, " ", minOpenTXs);
335 hasFound |= print(readWriteTransactionsRegistry, ps, " ", minOpenTXs);
337 // Now print details for each non-closed TransactionChain
338 // incl. in turn each ones own read/Write[Only]TransactionsRegistry
339 Set<CloseTrackedRegistryReportEntry<TracingTransactionChain>>
340 entries = transactionChainsRegistry.getAllUnique();
341 if (!entries.isEmpty()) {
342 ps.println(" " + transactionChainsRegistry.getAnchor() + " : "
343 + transactionChainsRegistry.getCreateDescription());
345 for (CloseTrackedRegistryReportEntry<TracingTransactionChain> entry : entries) {
346 ps.println(" " + entry.getNumberAddedNotRemoved() + "x TransactionChains opened but not closed here:");
347 printStackTraceElements(ps, " ", entry.getStackTraceElements());
348 @SuppressWarnings("resource")
349 TracingTransactionChain txChain = (TracingTransactionChain) entry
350 .getExampleCloseTracked().getRealCloseTracked();
351 hasFound |= print(txChain.getReadOnlyTransactionsRegistry(), ps, " ", minOpenTXs);
352 hasFound |= print(txChain.getWriteTransactionsRegistry(), ps, " ", minOpenTXs);
353 hasFound |= print(txChain.getReadWriteTransactionsRegistry(), ps, " ", minOpenTXs);
360 final void logEmptySet(final YangInstanceIdentifier yiid) {
361 if (LOG.isDebugEnabled()) {
362 LOG.debug("Empty data set write to {}", toPathString(yiid));
366 @SuppressFBWarnings(value = "SLF4J_SIGN_ONLY_FORMAT", justification = "pre-formatted logs")
367 static final void logOperations(final Object identifier, final List<?> operations) {
368 if (LOG.isWarnEnabled()) {
369 LOG.warn("Transaction {} contains the following operations:", identifier);
370 for (var operation : operations) {
371 LOG.warn("{}", operation);
376 private <T extends CloseTracked<T>> boolean print(final CloseTrackedRegistry<T> registry, final PrintStream ps,
377 final String indent, final int minOpenTransactions) {
378 Set<CloseTrackedRegistryReportEntry<T>> unsorted = registry.getAllUnique();
379 if (unsorted.size() < minOpenTransactions) {
383 List<CloseTrackedRegistryReportEntry<T>> entries = new ArrayList<>(unsorted);
384 entries.sort((o1, o2) -> Long.compare(o2.getNumberAddedNotRemoved(), o1.getNumberAddedNotRemoved()));
386 if (!entries.isEmpty()) {
387 ps.println(indent + registry.getAnchor() + " : " + registry.getCreateDescription());
389 entries.forEach(entry -> {
390 ps.println(indent + " " + entry.getNumberAddedNotRemoved()
391 + "x transactions opened here, which are not closed:");
392 printStackTraceElements(ps, indent + " ", entry.getStackTraceElements());
394 if (!entries.isEmpty()) {
400 private void printStackTraceElements(final PrintStream ps, final String indent,
401 final List<StackTraceElement> stackTraceElements) {
402 boolean ellipsis = false;
403 for (final StackTraceElement stackTraceElement : stackTraceElements) {
404 if (isStackTraceElementInteresting(stackTraceElement)) {
405 ps.println(indent + stackTraceElement);
407 } else if (!ellipsis) {
408 ps.println(indent + "(...)");
414 private boolean isStackTraceElementInteresting(final StackTraceElement element) {
415 final String className = element.getClassName();
416 return !className.startsWith(getClass().getPackage().getName())
417 && !className.startsWith(CloseTracked.class.getPackage().getName())
418 && !className.startsWith("Proxy")
419 && !className.startsWith("akka")
420 && !className.startsWith("scala")
421 && !className.startsWith("sun.reflect")
422 && !className.startsWith("java.lang.reflect")
423 && !className.startsWith("org.apache.aries.blueprint")
424 && !className.startsWith("org.osgi.util.tracker");