Improve error logging in yang-store-impl
[controller.git] / opendaylight / config / yang-store-impl / src / main / java / org / opendaylight / controller / config / yang / store / impl / ExtenderYangTracker.java
1 /*
2  * Copyright (c) 2013 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 package org.opendaylight.controller.config.yang.store.impl;
9
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Function;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.collect.Collections2;
15 import com.google.common.collect.HashMultimap;
16 import com.google.common.collect.Multimap;
17 import com.google.common.collect.Sets;
18 import org.opendaylight.controller.config.yang.store.api.YangStoreException;
19 import org.opendaylight.controller.config.yang.store.api.YangStoreService;
20 import org.opendaylight.controller.config.yang.store.api.YangStoreSnapshot;
21 import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
22 import org.opendaylight.yangtools.yang.model.api.Module;
23 import org.osgi.framework.Bundle;
24 import org.osgi.framework.BundleContext;
25 import org.osgi.framework.BundleEvent;
26 import org.osgi.util.tracker.BundleTracker;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29
30 import javax.annotation.concurrent.GuardedBy;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.net.URL;
34 import java.util.ArrayList;
35 import java.util.Collection;
36 import java.util.Collections;
37 import java.util.Enumeration;
38 import java.util.List;
39 import java.util.Map;
40 import java.util.Set;
41 import java.util.regex.Matcher;
42 import java.util.regex.Pattern;
43
44 /**
45  * Note on consistency:
46  * When this bundle is activated after other bundles containing yang files, the resolving order
47  * is not preserved. We thus maintain two maps, one containing consistent snapshot, other inconsistent. The
48  * container should eventually send all events and thus making the inconsistent map redundant.
49  */
50 public class ExtenderYangTracker extends BundleTracker<Object> implements YangStoreService, AutoCloseable {
51
52     private static final Logger logger = LoggerFactory.getLogger(ExtenderYangTracker.class);
53
54     private final Multimap<Bundle, URL> consistentBundlesToYangURLs = HashMultimap.create();
55
56     /*
57     Map of currently problematic yang files that should get fixed eventually after all events are received.
58      */
59     private final Multimap<Bundle, URL> inconsistentBundlesToYangURLs = HashMultimap.create();
60
61     private final YangStoreCache cache = new YangStoreCache();
62     private final MbeParser mbeParser;
63
64
65     public ExtenderYangTracker(Optional<Pattern> maybeBlacklist, BundleContext bundleContext) {
66         this(new MbeParser(), maybeBlacklist, bundleContext);
67     }
68
69     @GuardedBy("this")
70     private Optional<Pattern> maybeBlacklist;
71
72     @VisibleForTesting
73     ExtenderYangTracker(MbeParser mbeParser, Optional<Pattern> maybeBlacklist, BundleContext bundleContext) {
74         super(bundleContext, BundleEvent.RESOLVED | BundleEvent.UNRESOLVED, null);
75         this.mbeParser = mbeParser;
76         this.maybeBlacklist = maybeBlacklist;
77         open();
78     }
79
80     @Override
81     public synchronized Object addingBundle(Bundle bundle, BundleEvent event) {
82
83         // Ignore system bundle:
84         // system bundle might have config-api on classpath &&
85         // config-api contains yang files =>
86         // system bundle might contain yang files from that bundle
87         if (bundle.getBundleId() == 0)
88             return bundle;
89
90         if (maybeBlacklist.isPresent()) {
91             Matcher m = maybeBlacklist.get().matcher(bundle.getSymbolicName());
92             if (m.matches()) {
93                 logger.debug("Ignoring {} because it is in blacklist {}", bundle, maybeBlacklist);
94                 return bundle;
95             }
96         }
97
98         Enumeration<URL> enumeration = bundle.findEntries("META-INF/yang", "*.yang", false);
99         if (enumeration != null && enumeration.hasMoreElements()) {
100             synchronized (this) {
101                 List<URL> addedURLs = new ArrayList<>();
102                 while (enumeration.hasMoreElements()) {
103                     URL url = enumeration.nextElement();
104                     addedURLs.add(url);
105                 }
106                 logger.trace("Bundle {} has event {}, bundle state {}, URLs {}", bundle, event, bundle.getState(), addedURLs);
107                 // test that yang store is consistent
108                 Multimap<Bundle, URL> proposedNewState = HashMultimap.create(consistentBundlesToYangURLs);
109                 proposedNewState.putAll(inconsistentBundlesToYangURLs);
110                 proposedNewState.putAll(bundle, addedURLs);
111
112                 Preconditions.checkArgument(addedURLs.size() > 0, "No change can occur when no URLs are changed");
113
114                 try(YangStoreSnapshotImpl snapshot = createSnapshot(mbeParser, proposedNewState)) {
115                     onSnapshotSuccess(proposedNewState, snapshot);
116                 } catch(YangStoreException e) {
117                     onSnapshotFailure(bundle, addedURLs, e);
118                 }
119             }
120         }
121         return bundle;
122     }
123
124     private synchronized void onSnapshotFailure(Bundle bundle, List<URL> addedURLs, Exception failureReason) {
125         // inconsistent state
126         inconsistentBundlesToYangURLs.putAll(bundle, addedURLs);
127
128         logger.debug("Yang store is falling back on last consistent state containing {}, inconsistent yang files {}",
129                 consistentBundlesToYangURLs, inconsistentBundlesToYangURLs, failureReason);
130         logger.warn("Yang store is falling back on last consistent state containing {} files, inconsistent yang files size is {}, reason {}",
131                 consistentBundlesToYangURLs.size(), inconsistentBundlesToYangURLs.size(), failureReason.toString());
132         cache.setInconsistentURLsForReporting(inconsistentBundlesToYangURLs.values());
133     }
134
135     private synchronized void onSnapshotSuccess(Multimap<Bundle, URL> proposedNewState, YangStoreSnapshotImpl snapshot) {
136         // consistent state
137         // merge into
138         consistentBundlesToYangURLs.clear();
139         consistentBundlesToYangURLs.putAll(proposedNewState);
140         inconsistentBundlesToYangURLs.clear();
141
142         updateCache(snapshot);
143         cache.setInconsistentURLsForReporting(Collections.<URL> emptySet());
144         logger.info("Yang store updated to new consistent state containing {} yang files", consistentBundlesToYangURLs.size());
145         logger.debug("Yang store updated to new consistent state containing {}", consistentBundlesToYangURLs);
146     }
147
148     private synchronized void updateCache(YangStoreSnapshotImpl snapshot) {
149         cache.cacheYangStore(consistentBundlesToYangURLs, snapshot);
150     }
151
152     @Override
153     public void modifiedBundle(Bundle bundle, BundleEvent event, Object object) {
154         logger.debug("Modified bundle {} {} {}", bundle, event, object);
155     }
156
157     /**
158      * If removing YANG files makes yang store inconsistent, method {@link #getYangStoreSnapshot()}
159      * will throw exception. There is no rollback.
160      */
161     @Override
162     public synchronized void removedBundle(Bundle bundle, BundleEvent event, Object object) {
163         logger.debug("Removed bundle {} {} {}", bundle, event, object);
164         inconsistentBundlesToYangURLs.removeAll(bundle);
165         consistentBundlesToYangURLs.removeAll(bundle);
166     }
167
168     @Override
169     public synchronized YangStoreSnapshot getYangStoreSnapshot()
170             throws YangStoreException {
171         Optional<YangStoreSnapshot> yangStoreOpt = cache.getSnapshotIfPossible(consistentBundlesToYangURLs);
172         if (yangStoreOpt.isPresent()) {
173             logger.debug("Returning cached yang store {}", yangStoreOpt.get());
174             return yangStoreOpt.get();
175         }
176
177         YangStoreSnapshotImpl snapshot = createSnapshot(mbeParser, consistentBundlesToYangURLs);
178         updateCache(snapshot);
179         return snapshot;
180     }
181
182     private static YangStoreSnapshotImpl createSnapshot(MbeParser mbeParser, Multimap<Bundle, URL> multimap) throws YangStoreException {
183         try {
184             YangStoreSnapshotImpl yangStoreSnapshot = mbeParser.parseYangFiles(fromUrlsToInputStreams(multimap));
185             logger.trace("{} module entries parsed successfully from {} yang files",
186                     yangStoreSnapshot.countModuleMXBeanEntries(), multimap.values().size());
187             return yangStoreSnapshot;
188         } catch (RuntimeException e) {
189             StringBuffer causeStr = new StringBuffer();
190             Throwable cause = e;
191             while (cause != null) {
192                 causeStr.append(e.getMessage());
193                 causeStr.append("\n");
194                 cause = e.getCause();
195             }
196             throw new YangStoreException("Unable to parse yang files. \n" + causeStr.toString() +
197                     "URLs: " + multimap, e);
198         }
199     }
200
201     private static Collection<InputStream> fromUrlsToInputStreams(Multimap<Bundle, URL> multimap) {
202         return Collections2.transform(multimap.values(),
203                 new Function<URL, InputStream>() {
204
205                     @Override
206                     public InputStream apply(URL url) {
207                         try {
208                             return url.openStream();
209                         } catch (IOException e) {
210                             logger.warn("Unable to open stream from {}", url);
211                             throw new IllegalStateException(
212                                     "Unable to open stream from " + url, e);
213                         }
214                     }
215                 });
216     }
217
218     public synchronized void setMaybeBlacklist(Optional<Pattern> maybeBlacklistPattern) {
219         maybeBlacklist = maybeBlacklistPattern;
220         cache.invalidate();
221     }
222 }
223
224 class YangStoreCache {
225     private static final Logger logger = LoggerFactory.getLogger(YangStoreCache.class);
226
227     @GuardedBy("this")
228     private Set<URL> cachedUrls = null;
229     @GuardedBy("this")
230     private Optional<YangStoreSnapshot> cachedYangStoreSnapshot = getInitialSnapshot();
231     @GuardedBy("this")
232     private Collection<URL> inconsistentURLsForReporting = Collections.emptySet();
233
234     synchronized Optional<YangStoreSnapshot> getSnapshotIfPossible(Multimap<Bundle, URL> bundlesToYangURLs) {
235         Set<URL> urls = setFromMultimapValues(bundlesToYangURLs);
236
237         if (cachedUrls==null || cachedUrls.equals(urls)) {
238             Preconditions.checkState(cachedYangStoreSnapshot.isPresent());
239             YangStoreSnapshot freshSnapshot = new YangStoreSnapshotImpl(cachedYangStoreSnapshot.get());
240             if (inconsistentURLsForReporting.size() > 0){
241                 logger.warn("Some yang URLs are ignored: {}", inconsistentURLsForReporting);
242             }
243             return Optional.of(freshSnapshot);
244         }
245
246         return Optional.absent();
247     }
248
249     private static Set<URL> setFromMultimapValues(
250             Multimap<Bundle, URL> bundlesToYangURLs) {
251         Set<URL> urls = Sets.newHashSet(bundlesToYangURLs.values());
252         Preconditions.checkState(bundlesToYangURLs.size() == urls.size());
253         return urls;
254     }
255
256     synchronized void cacheYangStore(Multimap<Bundle, URL> urls,
257                                      YangStoreSnapshot yangStoreSnapshot) {
258         this.cachedUrls = setFromMultimapValues(urls);
259         this.cachedYangStoreSnapshot = Optional.of(yangStoreSnapshot);
260     }
261
262     synchronized void invalidate() {
263         cachedUrls.clear();
264         if (cachedYangStoreSnapshot.isPresent()){
265             cachedYangStoreSnapshot.get().close();
266             cachedYangStoreSnapshot = Optional.absent();
267         }
268     }
269
270     public synchronized void setInconsistentURLsForReporting(Collection<URL> urls){
271         inconsistentURLsForReporting = urls;
272     }
273
274     private Optional<YangStoreSnapshot> getInitialSnapshot() {
275         YangStoreSnapshot initialSnapshot = new YangStoreSnapshot() {
276             @Override
277             public Map<String, Map<String, ModuleMXBeanEntry>> getModuleMXBeanEntryMap() {
278                 return Collections.emptyMap();
279             }
280
281             @Override
282             public Map<String, Map.Entry<Module, String>> getModuleMap() {
283                 return Collections.emptyMap();
284             }
285
286             @Override
287             public int countModuleMXBeanEntries() {
288                 return 0;
289             }
290
291             @Override
292             public void close() {
293             }
294         };
295         return Optional.of(initialSnapshot);
296     }
297 }