8291a72c2577157f629bde2c0c2b79034c62b259
[controller.git] / opendaylight / md-sal / mdsal-trace / dom-impl / src / main / java / org / opendaylight / controller / md / sal / trace / dom / 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.controller.md.sal.trace.dom.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.HashMap;
16 import java.util.List;
17 import java.util.Map;
18 import java.util.Set;
19 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
20 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
21 import org.opendaylight.controller.md.sal.dom.api.ClusteredDOMDataTreeChangeListener;
22 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
23 import org.opendaylight.controller.md.sal.dom.api.DOMDataBrokerExtension;
24 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
25 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
26 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener;
27 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeService;
28 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeIdentifier;
29 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
30 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
31 import org.opendaylight.controller.md.sal.trace.api.TracingDOMDataBroker;
32 import org.opendaylight.controller.md.sal.trace.closetracker.impl.CloseTracked;
33 import org.opendaylight.controller.md.sal.trace.closetracker.impl.CloseTrackedRegistry;
34 import org.opendaylight.controller.md.sal.trace.closetracker.impl.CloseTrackedRegistryReportEntry;
35 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.mdsaltrace.rev160908.Config;
37 import org.opendaylight.yangtools.concepts.ListenerRegistration;
38 import org.opendaylight.yangtools.yang.binding.DataObject;
39 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
40 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 @SuppressWarnings("checkstyle:JavadocStyle")
45 //...because otherwise it whines about the elements in the @code block even though it's completely valid Javadoc
46
47 /**
48  * TracingBroker logs "write" operations and listener registrations to the md-sal. It logs the instance identifier path,
49  * the objects themselves, as well as the stack trace of the call invoking the registration or write operation.
50  * It works by operating as a "bump on the stack" between the application and actual DataBroker, intercepting write
51  * and registration calls and writing to the log.
52  *
53  * <p>In addition, it (optionally) can also keep track of the stack trace of all new transaction allocations
54  * (including TransactionChains, and transactions created in turn from them), in order to detect and report leaks
55  * from transactions which were not closed.
56  *
57  * <h1>Wiring:</h1>
58  * TracingBroker is designed to be easy to use. In fact, for bundles using Blueprint to inject their DataBroker
59  * TracingBroker can be used without modifying your code at all in two simple steps:
60  * <ol>
61  * <li>
62  * Simply add the dependency "mdsaltrace-features" to
63  * your Karaf pom:
64  * <pre>
65  * {@code
66  *  <dependency>
67  *    <groupId>org.opendaylight.controller</groupId>
68  *    <artifactId>features-mdsal-trace</artifactId>
69  *    <version>1.7.0-SNAPSHOT</version>
70  *    <classifier>features</classifier>
71  *    <type>xml</type>
72  *    <scope>runtime</scope>
73  *  </dependency>
74  * }
75  * </pre>
76  * </li>
77  * <li>
78  * Then just "feature:install odl-mdsal-trace" before you install your "real" feature(s) and you're done.
79  * Beware that with Karaf 4 due to <a href="https://bugs.opendaylight.org/show_bug.cgi?id=9068">Bug 9068</a>
80  * you'll probably have to use feature:install's --no-auto-refresh flag when installing your "real" feature.
81  * </li>
82  * </ol>
83  * This works because the mdsaltrace-impl bundle registers its service implementing DOMDataBroker with a higher
84  * rank than sal-binding-broker. As such, any OSGi service lookup for DataBroker will receive the TracingBroker.
85  * <p> </p>
86  * <h1>Avoiding log bloat:</h1>
87  * TracingBroker can be configured to only print registrations or write ops pertaining to certain subtrees of the
88  * md-sal. This can be done in the code via the methods of this class or via a config file. TracingBroker uses a more
89  * convenient but non-standard representation of the instance identifiers. Each instance identifier segment's
90  * class.getSimpleName() is used separated by a '/'.
91  * <p> </p>
92  * <h1>Known issues</h1>
93  * <ul>
94  *     <li>
95  *        Filtering by paths. For some registrations the codec that converts back from the DOM to binding paths is
96  *        busted. As such, an aproximated path is used in the output. For now it is recommended not to use
97  *        watchRegistrations and allow all registrations to be logged.
98  *     </li>
99  * </ul>
100  *
101  */
102 public class TracingBroker implements TracingDOMDataBroker {
103     @SuppressFBWarnings("SLF4J_LOGGER_SHOULD_BE_PRIVATE")
104     static final Logger LOG = LoggerFactory.getLogger(TracingBroker.class);
105
106     private static final int STACK_TRACE_FIRST_RELEVANT_FRAME = 2;
107
108     private final String type; // "default" VS "pingpong"
109     private final BindingNormalizedNodeSerializer codec;
110     private final DOMDataBroker delegate;
111     private final List<Watch> registrationWatches = new ArrayList<>();
112     private final List<Watch> writeWatches = new ArrayList<>();
113
114     private final boolean isDebugging;
115     private final CloseTrackedRegistry<TracingTransactionChain> transactionChainsRegistry;
116     private final CloseTrackedRegistry<TracingReadOnlyTransaction> readOnlyTransactionsRegistry;
117     private final CloseTrackedRegistry<TracingWriteTransaction> writeTransactionsRegistry;
118     private final CloseTrackedRegistry<TracingReadWriteTransaction> readWriteTransactionsRegistry;
119
120     private class Watch {
121         final String iidString;
122         final LogicalDatastoreType store;
123
124         Watch(String iidString, LogicalDatastoreType storeOrNull) {
125             this.store = storeOrNull;
126             this.iidString = iidString;
127         }
128
129         private String toIidCompString(YangInstanceIdentifier iid) {
130             StringBuilder builder = new StringBuilder();
131             toPathString(iid, builder);
132             builder.append('/');
133             return builder.toString();
134         }
135
136         private boolean isParent(String parent, String child) {
137             int parentOffset = 0;
138             if (parent.length() > 0 && parent.charAt(0) == '<') {
139                 parentOffset = parent.indexOf('>') + 1;
140             }
141
142             int childOffset = 0;
143             if (child.length() > 0 && child.charAt(0) == '<') {
144                 childOffset = child.indexOf('>') + 1;
145             }
146
147             return child.startsWith(parent.substring(parentOffset), childOffset);
148         }
149
150         @SuppressWarnings({ "checkstyle:hiddenField", "hiding" })
151         public boolean subtreesOverlap(YangInstanceIdentifier iid, LogicalDatastoreType store) {
152             if (this.store != null && !this.store.equals(store)) {
153                 return false;
154             }
155
156             String otherIidString = toIidCompString(iid);
157             return isParent(iidString, otherIidString) || isParent(otherIidString, iidString);
158         }
159
160         @SuppressWarnings({ "checkstyle:hiddenField", "hiding" })
161         public boolean eventIsOfInterest(YangInstanceIdentifier iid, LogicalDatastoreType store) {
162             if (this.store != null && !this.store.equals(store)) {
163                 return false;
164             }
165
166             return isParent(iidString, toPathString(iid));
167         }
168     }
169
170     public TracingBroker(String type, DOMDataBroker delegate, Config config, BindingNormalizedNodeSerializer codec) {
171         this.type = requireNonNull(type, "type");
172         this.delegate = requireNonNull(delegate, "delegate");
173         this.codec = requireNonNull(codec, "codec");
174         configure(config);
175
176         if (config.isTransactionDebugContextEnabled() != null) {
177             this.isDebugging = config.isTransactionDebugContextEnabled();
178         } else {
179             this.isDebugging = false;
180         }
181         final String db = "DataBroker";
182         this.transactionChainsRegistry     = new CloseTrackedRegistry<>(db, "createTransactionChain()", isDebugging);
183         this.readOnlyTransactionsRegistry  = new CloseTrackedRegistry<>(db, "newReadOnlyTransaction()", isDebugging);
184         this.writeTransactionsRegistry     = new CloseTrackedRegistry<>(db, "newWriteOnlyTransaction()", isDebugging);
185         this.readWriteTransactionsRegistry = new CloseTrackedRegistry<>(db, "newReadWriteTransaction()", isDebugging);
186     }
187
188     private void configure(Config config) {
189         registrationWatches.clear();
190         List<String> paths = config.getRegistrationWatches();
191         if (paths != null) {
192             for (String path : paths) {
193                 watchRegistrations(path, null);
194             }
195         }
196
197         writeWatches.clear();
198         paths = config.getWriteWatches();
199         if (paths != null) {
200             for (String path : paths) {
201                 watchWrites(path, null);
202             }
203         }
204     }
205
206     /**
207      * Log registrations to this subtree of the md-sal.
208      * @param iidString the iid path of the root of the subtree
209      * @param store Which LogicalDataStore? or null for both
210      */
211     public void watchRegistrations(String iidString, LogicalDatastoreType store) {
212         LOG.info("Watching registrations to {} in {}", iidString, store);
213         registrationWatches.add(new Watch(iidString, store));
214     }
215
216     /**
217      * Log writes to this subtree of the md-sal.
218      * @param iidString the iid path of the root of the subtree
219      * @param store Which LogicalDataStore? or null for both
220      */
221     public void watchWrites(String iidString, LogicalDatastoreType store) {
222         LOG.info("Watching writes to {} in {}", iidString, store);
223         Watch watch = new Watch(iidString, store);
224         writeWatches.add(watch);
225     }
226
227     private boolean isRegistrationWatched(YangInstanceIdentifier iid, LogicalDatastoreType store) {
228         if (registrationWatches.isEmpty()) {
229             return true;
230         }
231
232         for (Watch regInterest : registrationWatches) {
233             if (regInterest.subtreesOverlap(iid, store)) {
234                 return true;
235             }
236         }
237
238         return false;
239     }
240
241     boolean isWriteWatched(YangInstanceIdentifier iid, LogicalDatastoreType store) {
242         if (writeWatches.isEmpty()) {
243             return true;
244         }
245
246         for (Watch watch : writeWatches) {
247             if (watch.eventIsOfInterest(iid, store)) {
248                 return true;
249             }
250         }
251
252         return false;
253     }
254
255     static void toPathString(InstanceIdentifier<? extends DataObject> iid, StringBuilder builder) {
256         for (InstanceIdentifier.PathArgument pathArg : iid.getPathArguments()) {
257             builder.append('/').append(pathArg.getType().getSimpleName());
258         }
259     }
260
261     String toPathString(YangInstanceIdentifier  yiid) {
262         StringBuilder sb = new StringBuilder();
263         toPathString(yiid, sb);
264         return sb.toString();
265     }
266
267
268     private void toPathString(YangInstanceIdentifier yiid, StringBuilder sb) {
269         InstanceIdentifier<?> iid = codec.fromYangInstanceIdentifier(yiid);
270         if (null == iid) {
271             reconstructIidPathString(yiid, sb);
272         } else {
273             toPathString(iid, sb);
274         }
275     }
276
277     private void reconstructIidPathString(YangInstanceIdentifier yiid, StringBuilder sb) {
278         sb.append("<RECONSTRUCTED FROM: \"").append(yiid.toString()).append("\">");
279         for (YangInstanceIdentifier.PathArgument pathArg : yiid.getPathArguments()) {
280             if (pathArg instanceof YangInstanceIdentifier.AugmentationIdentifier) {
281                 sb.append('/').append("AUGMENTATION");
282                 continue;
283             }
284             sb.append('/').append(pathArg.getNodeType().getLocalName());
285         }
286     }
287
288     String getStackSummary() {
289         StackTraceElement[] stack = Thread.currentThread().getStackTrace();
290
291         StringBuilder sb = new StringBuilder();
292         for (int i = STACK_TRACE_FIRST_RELEVANT_FRAME; i < stack.length; i++) {
293             StackTraceElement frame = stack[i];
294             sb.append("\n\t(TracingBroker)\t").append(frame.getClassName()).append('.').append(frame.getMethodName());
295         }
296
297         return sb.toString();
298     }
299
300     @Override
301     public DOMDataReadWriteTransaction newReadWriteTransaction() {
302         return new TracingReadWriteTransaction(delegate.newReadWriteTransaction(), this, readWriteTransactionsRegistry);
303     }
304
305     @Override
306     public DOMDataWriteTransaction newWriteOnlyTransaction() {
307         return new TracingWriteTransaction(delegate.newWriteOnlyTransaction(), this, writeTransactionsRegistry);
308     }
309
310     @Override
311     public DOMTransactionChain createTransactionChain(TransactionChainListener transactionChainListener) {
312         return new TracingTransactionChain(
313                 delegate.createTransactionChain(transactionChainListener), this, transactionChainsRegistry);
314     }
315
316     @Override
317     public DOMDataReadOnlyTransaction newReadOnlyTransaction() {
318         return new TracingReadOnlyTransaction(delegate.newReadOnlyTransaction(), readOnlyTransactionsRegistry);
319     }
320
321     @Override
322     public Map<Class<? extends DOMDataBrokerExtension>, DOMDataBrokerExtension> getSupportedExtensions() {
323         Map<Class<? extends DOMDataBrokerExtension>, DOMDataBrokerExtension> res = delegate.getSupportedExtensions();
324         DOMDataTreeChangeService treeChangeSvc = (DOMDataTreeChangeService) res.get(DOMDataTreeChangeService.class);
325         if (treeChangeSvc == null) {
326             return res;
327         }
328
329         res = new HashMap<>(res);
330
331         res.put(DOMDataTreeChangeService.class, new DOMDataTreeChangeService() {
332             @Override
333             public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerDataTreeChangeListener(
334                     DOMDataTreeIdentifier domDataTreeIdentifier, L listener) {
335                 if (isRegistrationWatched(domDataTreeIdentifier.getRootIdentifier(),
336                         domDataTreeIdentifier.getDatastoreType())) {
337                     LOG.warn("{} registration (registerDataTreeChangeListener) for {} from {}.",
338                             listener instanceof ClusteredDOMDataTreeChangeListener ? "Clustered" : "Non-clustered",
339                             toPathString(domDataTreeIdentifier.getRootIdentifier()), getStackSummary());
340                 }
341                 return treeChangeSvc.registerDataTreeChangeListener(domDataTreeIdentifier, listener);
342             }
343         });
344
345         return res;
346     }
347
348     @Override
349     public boolean printOpenTransactions(PrintStream ps, int minOpenTXs) {
350         if (transactionChainsRegistry.getAllUnique().isEmpty()
351             && readOnlyTransactionsRegistry.getAllUnique().isEmpty()
352             && writeTransactionsRegistry.getAllUnique().isEmpty()
353             && readWriteTransactionsRegistry.getAllUnique().isEmpty()) {
354
355             ps.println(type + ": No open transactions, great!");
356             return false;
357         }
358
359         ps.println(type + ": " + getClass().getSimpleName()
360                  + " found some not yet (or never..) closed transaction[chain]s!");
361         ps.println("[NB: If no stack traces are shown below, then "
362                  + "enable transaction-debug-context-enabled in mdsaltrace_config.xml]");
363         ps.println();
364         // Flag to track if we really found any real leaks with more (or equal) to minOpenTXs
365         boolean hasFound = print(readOnlyTransactionsRegistry, ps, "  ", minOpenTXs);
366         hasFound |= print(writeTransactionsRegistry, ps, "  ", minOpenTXs);
367         hasFound |= print(readWriteTransactionsRegistry, ps, "  ", minOpenTXs);
368
369         // Now print details for each non-closed TransactionChain
370         // incl. in turn each ones own read/Write[Only]TransactionsRegistry
371         Set<CloseTrackedRegistryReportEntry<TracingTransactionChain>>
372             entries = transactionChainsRegistry.getAllUnique();
373         if (!entries.isEmpty()) {
374             ps.println("  " + transactionChainsRegistry.getAnchor() + " : "
375                     + transactionChainsRegistry.getCreateDescription());
376         }
377         for (CloseTrackedRegistryReportEntry<TracingTransactionChain> entry : entries) {
378             ps.println("    " + entry.getNumberAddedNotRemoved() + "x TransactionChains opened but not closed here:");
379             printStackTraceElements(ps, "      ", entry.getStackTraceElements());
380             @SuppressWarnings("resource")
381             TracingTransactionChain txChain = (TracingTransactionChain) entry
382                 .getExampleCloseTracked().getRealCloseTracked();
383             hasFound |= print(txChain.getReadOnlyTransactionsRegistry(), ps, "        ", minOpenTXs);
384             hasFound |= print(txChain.getWriteTransactionsRegistry(), ps, "        ", minOpenTXs);
385             hasFound |= print(txChain.getReadWriteTransactionsRegistry(), ps, "        ", minOpenTXs);
386         }
387         ps.println();
388
389         return hasFound;
390     }
391
392     private <T extends CloseTracked<T>> boolean print(
393             CloseTrackedRegistry<T> registry, PrintStream ps, String indent, int minOpenTransactions) {
394         Set<CloseTrackedRegistryReportEntry<T>> unsorted = registry.getAllUnique();
395         if (unsorted.size() < minOpenTransactions) {
396             return false;
397         }
398
399         List<CloseTrackedRegistryReportEntry<T>> entries = new ArrayList<>(unsorted);
400         entries.sort((o1, o2) -> Long.compare(o2.getNumberAddedNotRemoved(), o1.getNumberAddedNotRemoved()));
401
402         if (!entries.isEmpty()) {
403             ps.println(indent + registry.getAnchor() + " : " + registry.getCreateDescription());
404         }
405         entries.forEach(entry -> {
406             ps.println(indent + "  " + entry.getNumberAddedNotRemoved()
407                 + "x transactions opened here, which are not closed:");
408             printStackTraceElements(ps, indent + "    ", entry.getStackTraceElements());
409         });
410         if (!entries.isEmpty()) {
411             ps.println();
412         }
413         return true;
414     }
415
416     private void printStackTraceElements(PrintStream ps, String indent, List<StackTraceElement> stackTraceElements) {
417         boolean ellipsis = false;
418         for (final StackTraceElement stackTraceElement : stackTraceElements) {
419             if (isStackTraceElementInteresting(stackTraceElement)) {
420                 ps.println(indent + stackTraceElement);
421                 ellipsis = false;
422             } else if (!ellipsis) {
423                 ps.println(indent + "(...)");
424                 ellipsis = true;
425             }
426         }
427     }
428
429     private boolean isStackTraceElementInteresting(StackTraceElement element) {
430         final String className = element.getClassName();
431         return !className.startsWith(getClass().getPackage().getName())
432             && !className.startsWith(CloseTracked.class.getPackage().getName())
433             && !className.startsWith("Proxy")
434             && !className.startsWith("akka")
435             && !className.startsWith("scala")
436             && !className.startsWith("sun.reflect")
437             && !className.startsWith("java.lang.reflect")
438             && !className.startsWith("org.apache.aries.blueprint")
439             && !className.startsWith("org.osgi.util.tracker");
440     }
441 }