b7b528b636de630f645554e18e5d6fb1a814a1c0
[mdsal.git] / trace / mdsal-trace-impl / src / main / java / org / opendaylight / mdsal / trace / impl / TracingBroker.java
1 /*
2  * Copyright (c) 2016 Red Hat, 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 package org.opendaylight.mdsal.trace.impl;
9
10 import static java.util.Objects.requireNonNull;
11
12 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
13 import java.io.PrintStream;
14 import java.util.ArrayList;
15 import java.util.List;
16 import java.util.Set;
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;
32
33 @SuppressWarnings("checkstyle:JavadocStyle")
34 //...because otherwise it whines about the elements in the @code block even though it's completely valid Javadoc
35 /**
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.
40  *
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.
44  *
45  * <h1>Wiring:</h1>
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:
48  * <ol>
49  * <li>
50  * Simply add the dependency "mdsaltrace-features" to
51  * your Karaf pom:
52  * <pre>
53  * {@code
54  *  <dependency>
55  *    <groupId>org.opendaylight.controller</groupId>
56  *    <artifactId>features-mdsal-trace</artifactId>
57  *    <version>1.7.0-SNAPSHOT</version>
58  *    <classifier>features</classifier>
59  *    <type>xml</type>
60  *    <scope>runtime</scope>
61  *  </dependency>
62  * }
63  * </pre>
64  * </li>
65  * <li>
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.
69  * </li>
70  * </ol>
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.
73  * <p> </p>
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 '/'.
79  * <p> </p>
80  * <h1>Known issues</h1>
81  * <ul>
82  *     <li>
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.
86  *     </li>
87  * </ul>
88  */
89 public class TracingBroker implements TracingDOMDataBroker {
90     private static final Logger LOG = LoggerFactory.getLogger(TracingBroker.class);
91
92     private static final int STACK_TRACE_FIRST_RELEVANT_FRAME = 2;
93
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<>();
98
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;
104
105     private class Watch {
106         final String iidString;
107         final LogicalDatastoreType store;
108
109         Watch(final String iidString, final LogicalDatastoreType storeOrNull) {
110             store = storeOrNull;
111             this.iidString = iidString;
112         }
113
114         private String toIidCompString(final YangInstanceIdentifier iid) {
115             StringBuilder builder = new StringBuilder();
116             toPathString(iid, builder);
117             return builder.append('/').toString();
118         }
119
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;
124             }
125
126             int childOffset = 0;
127             if (child.length() > 0 && child.charAt(0) == '<') {
128                 childOffset = child.indexOf('>') + 1;
129             }
130
131             return child.startsWith(parent.substring(parentOffset), childOffset);
132         }
133
134         @SuppressWarnings({ "checkstyle:hiddenField", "hiding" })
135         public boolean subtreesOverlap(final YangInstanceIdentifier iid, final LogicalDatastoreType store) {
136             if (this.store != null && !this.store.equals(store)) {
137                 return false;
138             }
139
140             String otherIidString = toIidCompString(iid);
141             return isParent(iidString, otherIidString) || isParent(otherIidString, iidString);
142         }
143
144         @SuppressWarnings({ "checkstyle:hiddenField", "hiding" })
145         public boolean eventIsOfInterest(final YangInstanceIdentifier iid, final LogicalDatastoreType store) {
146             if (this.store != null && !this.store.equals(store)) {
147                 return false;
148             }
149
150             return isParent(iidString, toPathString(iid));
151         }
152     }
153
154     public TracingBroker(final DOMDataBroker delegate, final Config config, final BindingCodecTree codec) {
155         this.delegate = requireNonNull(delegate, "delegate");
156         this.codec = requireNonNull(codec, "codec");
157         configure(config);
158
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);
165     }
166
167     private void configure(final Config config) {
168         registrationWatches.clear();
169         Set<String> paths = config.getRegistrationWatches();
170         if (paths != null) {
171             for (String path : paths) {
172                 watchRegistrations(path, null);
173             }
174         }
175
176         writeWatches.clear();
177         paths = config.getWriteWatches();
178         if (paths != null) {
179             for (String path : paths) {
180                 watchWrites(path, null);
181             }
182         }
183     }
184
185     /**
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
189      */
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));
193     }
194
195     /**
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
199      */
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);
204     }
205
206     private boolean isRegistrationWatched(final YangInstanceIdentifier iid, final LogicalDatastoreType store) {
207         if (registrationWatches.isEmpty()) {
208             return true;
209         }
210
211         for (Watch regInterest : registrationWatches) {
212             if (regInterest.subtreesOverlap(iid, store)) {
213                 return true;
214             }
215         }
216
217         return false;
218     }
219
220     boolean isWriteWatched(final YangInstanceIdentifier iid, final LogicalDatastoreType store) {
221         if (writeWatches.isEmpty()) {
222             return true;
223         }
224
225         for (Watch watch : writeWatches) {
226             if (watch.eventIsOfInterest(iid, store)) {
227                 return true;
228             }
229         }
230
231         return false;
232     }
233
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());
237         }
238     }
239
240     String toPathString(final YangInstanceIdentifier  yiid) {
241         StringBuilder sb = new StringBuilder();
242         toPathString(yiid, sb);
243         return sb.toString();
244     }
245
246
247     private void toPathString(final YangInstanceIdentifier yiid, final StringBuilder sb) {
248         InstanceIdentifier<?> iid = codec.getInstanceIdentifierCodec().toBinding(yiid);
249         if (null == iid) {
250             reconstructIidPathString(yiid, sb);
251         } else {
252             toPathString(iid, sb);
253         }
254     }
255
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());
260         }
261     }
262
263     String getStackSummary() {
264         StackTraceElement[] stack = Thread.currentThread().getStackTrace();
265
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());
270         }
271
272         return sb.toString();
273     }
274
275     @Override
276     public DOMDataTreeReadWriteTransaction newReadWriteTransaction() {
277         return new TracingReadWriteTransaction(delegate.newReadWriteTransaction(), this, readWriteTransactionsRegistry);
278     }
279
280     @Override
281     public DOMDataTreeWriteTransaction newWriteOnlyTransaction() {
282         return new TracingWriteTransaction(delegate.newWriteOnlyTransaction(), this, writeTransactionsRegistry);
283     }
284
285     @Override
286     public DOMTransactionChain createTransactionChain() {
287         return new TracingTransactionChain(delegate.createTransactionChain(), this, transactionChainsRegistry);
288     }
289
290     @Override
291     public DOMTransactionChain createMergingTransactionChain() {
292         return new TracingTransactionChain(delegate.createMergingTransactionChain(), this, transactionChainsRegistry);
293     }
294
295     @Override
296     public DOMDataTreeReadTransaction newReadOnlyTransaction() {
297         return new TracingReadOnlyTransaction(delegate.newReadOnlyTransaction(), readOnlyTransactionsRegistry);
298     }
299
300     @Override
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());
310                 }
311                 return treeChange.registerDataTreeChangeListener(domDataTreeIdentifier, listener);
312             });
313         }
314         return ext;
315     }
316
317     @Override
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()) {
323
324             ps.println("No open transactions, great!");
325             return false;
326         }
327
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]");
331         ps.println();
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);
336
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());
344         }
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);
354         }
355         ps.println();
356
357         return hasFound;
358     }
359
360     final void logEmptySet(final YangInstanceIdentifier yiid) {
361         if (LOG.isDebugEnabled()) {
362             LOG.debug("Empty data set write to {}", toPathString(yiid));
363         }
364     }
365
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);
372             }
373         }
374     }
375
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) {
380             return false;
381         }
382
383         List<CloseTrackedRegistryReportEntry<T>> entries = new ArrayList<>(unsorted);
384         entries.sort((o1, o2) -> Long.compare(o2.getNumberAddedNotRemoved(), o1.getNumberAddedNotRemoved()));
385
386         if (!entries.isEmpty()) {
387             ps.println(indent + registry.getAnchor() + " : " + registry.getCreateDescription());
388         }
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());
393         });
394         if (!entries.isEmpty()) {
395             ps.println();
396         }
397         return true;
398     }
399
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);
406                 ellipsis = false;
407             } else if (!ellipsis) {
408                 ps.println(indent + "(...)");
409                 ellipsis = true;
410             }
411         }
412     }
413
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");
425     }
426 }