mdsaltrace utility for debugging
[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 java.util.ArrayList;
11 import java.util.HashMap;
12 import java.util.List;
13 import java.util.Map;
14 import java.util.Objects;
15 import javax.annotation.Nonnull;
16
17 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
18 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
19 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
20 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
21 import org.opendaylight.controller.md.sal.dom.api.DOMDataBrokerExtension;
22 import org.opendaylight.controller.md.sal.dom.api.DOMDataChangeListener;
23 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
24 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
25 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener;
26 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeService;
27 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeIdentifier;
28 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
29 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
30 import org.opendaylight.controller.md.sal.trace.api.TracingDOMDataBroker;
31 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.mdsaltrace.rev160908.Config;
33 import org.opendaylight.yangtools.concepts.ListenerRegistration;
34 import org.opendaylight.yangtools.yang.binding.DataObject;
35 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 @SuppressWarnings("checkstyle:JavadocStyle")
41 //...because otherwise it whines about the elements in the @code block even though it's completely valid Javadoc
42
43 /**
44  * TracingBroker logs "write" operations and listener registrations to the md-sal. It logs the instance identifier path,
45  * the objects themselves, as well as the stack trace of the call invoking the registration or write operation.
46  * It works by operating as a "bump on the stack" between the application and actual DataBroker, intercepting write
47  * and registration calls and writing to the log.
48  * <h1>Wiring:</h1>
49  * TracingBroker is designed to be easy to use. In fact, for bundles using Blueprint to inject their DataBroker
50  * TracingBroker can be used without modifying your code at all in two simple steps:
51  * <ol>
52  * <li>
53  * Simply add the dependency "mdsaltrace-features" to
54  * your karaf pom:
55  * <pre>
56  * {@code
57  *  <dependency>
58  *    <groupId>org.opendaylight.controller</groupId>
59  *    <artifactId>mdsal-trace-features</artifactId>
60  *    <classifier>features</classifier>
61  *    <type>xml</type>
62  *    <scope>runtime</scope>
63  *    <version>0.1.5-SNAPSHOT</version>
64  *  </dependency>
65  * }
66  * </pre>
67  * </li>
68  * <li>
69  * Then just load the odl-mdsal-trace feature before your feature and you're done.
70  * </li>
71  * </ol>
72  * This works because the mdsaltrace-impl bundle registers its service implementing DOMDataBroker with a higher
73  * rank than sal-binding-broker. As such, any OSGi service lookup for DataBroker will receive the TracingBroker.
74  * <p> </p>
75  * <h1>Avoiding log bloat:</h1>
76  * TracingBroker can be configured to only print registrations or write ops pertaining to certain subtrees of the
77  * md-sal. This can be done in the code via the methods of this class or via a config file. TracingBroker uses a more
78  * convenient but non-standard representation of the instance identifiers. Each instance identifier segment's
79  * class.getSimpleName() is used separated by a '/'.
80  * <p> </p>
81  * <h1>Known issues</h1>
82  * <ul>
83  *     <li>
84  *        Filtering by paths. For some registrations the codec that converts back from the DOM to binding paths is
85  *        busted. As such, an aproximated path is used in the output. For now it is recommended not to use
86  *        watchRegistrations and allow all registrations to be logged.
87  *     </li>
88  * </ul>
89  *
90  */
91 public class TracingBroker implements TracingDOMDataBroker {
92
93     static final Logger LOG = LoggerFactory.getLogger(TracingBroker.class);
94
95     private static final int STACK_TRACE_FIRST_RELEVANT_FRAME = 2;
96
97     private final BindingNormalizedNodeSerializer codec;
98     private final DOMDataBroker delegate;
99     private List<Watch> registrationWatches = new ArrayList<>();
100     private List<Watch> writeWatches = new ArrayList<>();
101
102
103     private class Watch {
104         final String iidString;
105         final LogicalDatastoreType store;
106
107         Watch(String iidString, LogicalDatastoreType storeOrNull) {
108             this.store = storeOrNull;
109             this.iidString = iidString;
110         }
111
112         private String toIidCompString(YangInstanceIdentifier iid) {
113             StringBuilder builder = new StringBuilder();
114             toPathString(iid, builder);
115             builder.append('/');
116             return builder.toString();
117         }
118
119         private boolean isParent(String parent, String child) {
120             return child.startsWith(parent);
121         }
122
123         public boolean subtreesOverlap(YangInstanceIdentifier iid, LogicalDatastoreType store,
124                                                                 AsyncDataBroker.DataChangeScope scope) {
125             if (this.store != null && !this.store.equals(store)) {
126                 return false;
127             }
128
129             String otherIidString = toIidCompString(iid);
130
131             switch (scope) {
132                 case BASE:
133                     return isParent(iidString, otherIidString);
134                 case ONE: //for now just treat like SUBTREE, even though it's not
135                 case SUBTREE:
136                     return isParent(iidString, otherIidString) || isParent(otherIidString, iidString);
137                 default:
138                     return false;
139             }
140         }
141
142         public boolean eventIsOfInterest(YangInstanceIdentifier iid, LogicalDatastoreType store) {
143             if (this.store != null && !this.store.equals(store)) {
144                 return false;
145             }
146
147             return isParent(iidString, toPathString(iid));
148         }
149     }
150
151     public TracingBroker(DOMDataBroker delegate, Config config, BindingNormalizedNodeSerializer codec) {
152         this.delegate = Objects.requireNonNull(delegate);
153         this.codec = Objects.requireNonNull(codec);
154         configure(config);
155     }
156
157     private void configure(Config config) {
158         registrationWatches.clear();
159         List<String> paths = config.getRegistrationWatches();
160         if (paths != null) {
161             for (String path : paths) {
162                 watchRegistrations(path, null);
163             }
164         }
165
166         writeWatches.clear();
167         paths = config.getWriteWatches();
168         if (paths != null) {
169             for (String path : paths) {
170                 watchWrites(path, null);
171             }
172         }
173     }
174
175     /**
176      * Log registrations to this subtree of the md-sal.
177      * @param iidString the iid path of the root of the subtree
178      * @param store Which LogicalDataStore? or null for both
179      */
180     public void watchRegistrations(String iidString, LogicalDatastoreType store) {
181         registrationWatches.add(new Watch(iidString, store));
182     }
183
184     /**
185      * Log writes to this subtree of the md-sal.
186      * @param iidString the iid path of the root of the subtree
187      * @param store Which LogicalDataStore? or null for both
188      */
189     public void watchWrites(String iidString, LogicalDatastoreType store) {
190         Watch watch = new Watch(iidString, store);
191         writeWatches.add(watch);
192     }
193
194     private boolean isRegistrationWatched(YangInstanceIdentifier iid,
195                                                             LogicalDatastoreType store, DataChangeScope scope) {
196         if (registrationWatches.isEmpty()) {
197             return true;
198         }
199
200         for (Watch regInterest : registrationWatches) {
201             if (regInterest.subtreesOverlap(iid, store, scope)) {
202                 return true;
203             }
204         }
205
206         return false;
207     }
208
209     boolean isWriteWatched(YangInstanceIdentifier iid, LogicalDatastoreType store) {
210         if (writeWatches.isEmpty()) {
211             return true;
212         }
213
214         for (Watch watch : writeWatches) {
215             if (watch.eventIsOfInterest(iid, store)) {
216                 return true;
217             }
218         }
219
220         return false;
221     }
222
223     static void toPathString(InstanceIdentifier<? extends DataObject> iid, StringBuilder builder) {
224         for (InstanceIdentifier.PathArgument pathArg : iid.getPathArguments()) {
225             builder.append('/').append(pathArg.getType().getSimpleName());
226         }
227     }
228
229     String toPathString(YangInstanceIdentifier  yiid) {
230         StringBuilder sb = new StringBuilder();
231         toPathString(yiid, sb);
232         return sb.toString();
233     }
234
235
236     void toPathString(YangInstanceIdentifier yiid, StringBuilder sb) {
237         InstanceIdentifier iid = codec.fromYangInstanceIdentifier(yiid);
238         if (null == iid) {
239             reconstructIidPathString(yiid, sb);
240         } else {
241             toPathString(iid, sb);
242         }
243     }
244
245     private void reconstructIidPathString(YangInstanceIdentifier yiid, StringBuilder sb) {
246         sb.append("RECONSTRUCTED: ");
247         for (YangInstanceIdentifier.PathArgument pathArg : yiid.getPathArguments()) {
248             if (pathArg instanceof YangInstanceIdentifier.AugmentationIdentifier) {
249                 sb.append('/').append("AUGMENTATION");
250                 continue;
251             }
252             sb.append('/').append(pathArg.getNodeType().getLocalName());
253         }
254         sb.append(" ->->-> [[[ ").append(yiid.toString()).append(" ]]]");
255     }
256
257     String getStackSummary() {
258         StackTraceElement[] stack = Thread.currentThread().getStackTrace();
259
260         StringBuilder sb = new StringBuilder();
261         for (int i = STACK_TRACE_FIRST_RELEVANT_FRAME; i < stack.length; i++) {
262             StackTraceElement frame = stack[i];
263             sb.append("\n\t(TracingBroker)\t").append(frame.getClassName()).append('.').append(frame.getMethodName());
264         }
265
266         return sb.toString();
267     }
268
269     @Override
270     public DOMDataReadWriteTransaction newReadWriteTransaction() {
271         return new TracingReadWriteTransaction(delegate.newReadWriteTransaction(), this);
272     }
273
274     @Override
275     public DOMDataWriteTransaction newWriteOnlyTransaction() {
276         return new TracingWriteTransaction(delegate.newWriteOnlyTransaction(), this);
277     }
278
279     @Override
280     public ListenerRegistration<DOMDataChangeListener> registerDataChangeListener(
281                                                         LogicalDatastoreType store, YangInstanceIdentifier yiid,
282                                                         DOMDataChangeListener listener, DataChangeScope scope) {
283         if (isRegistrationWatched(yiid, store, scope)) {
284             LOG.warn("Registration (registerDataChangeListener) for {} from {}",
285                     toPathString(yiid), getStackSummary());
286         }
287         return delegate.registerDataChangeListener(store, yiid, listener, scope);
288     }
289
290     @Override
291     public DOMTransactionChain createTransactionChain(TransactionChainListener transactionChainListener) {
292         return delegate.createTransactionChain(transactionChainListener);
293     }
294
295     @Override
296     public DOMDataReadOnlyTransaction newReadOnlyTransaction() {
297         return delegate.newReadOnlyTransaction();
298     }
299
300     @Nonnull
301     @Override
302     public Map<Class<? extends DOMDataBrokerExtension>, DOMDataBrokerExtension> getSupportedExtensions() {
303         Map<Class<? extends DOMDataBrokerExtension>, DOMDataBrokerExtension> res = delegate.getSupportedExtensions();
304         DOMDataTreeChangeService treeChangeSvc = (DOMDataTreeChangeService) res.get(DOMDataTreeChangeService.class);
305         if (treeChangeSvc == null) {
306             return res;
307         }
308
309         res = new HashMap<>(res);
310
311         res.put(DOMDataTreeChangeService.class, new DOMDataTreeChangeService() {
312             @Nonnull
313             @Override
314             public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerDataTreeChangeListener(
315                     @Nonnull DOMDataTreeIdentifier domDataTreeIdentifier, @Nonnull L listener) {
316                 if (isRegistrationWatched(domDataTreeIdentifier.getRootIdentifier(),
317                         domDataTreeIdentifier.getDatastoreType(), DataChangeScope.SUBTREE)) {
318                     LOG.warn("Registration (registerDataTreeChangeListener) for {} from {}",
319                             toPathString(domDataTreeIdentifier.getRootIdentifier()), getStackSummary());
320                 }
321                 return treeChangeSvc.registerDataTreeChangeListener(domDataTreeIdentifier, listener);
322             }
323         });
324
325         return res;
326     }
327 }