Reduce verbosity/criticality of inconsistent yangstore messages
[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 org.opendaylight.controller.config.yang.store.api.YangStoreException;
18 import org.opendaylight.controller.config.yang.store.api.YangStoreService;
19 import org.opendaylight.controller.config.yang.store.api.YangStoreSnapshot;
20 import org.osgi.framework.Bundle;
21 import org.osgi.framework.BundleContext;
22 import org.osgi.framework.BundleEvent;
23 import org.osgi.util.tracker.BundleTracker;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26
27 import javax.annotation.concurrent.GuardedBy;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.net.URL;
31 import java.util.ArrayList;
32 import java.util.Collection;
33 import java.util.Collections;
34 import java.util.Enumeration;
35 import java.util.List;
36 import java.util.regex.Matcher;
37 import java.util.regex.Pattern;
38
39 /**
40  * Note on consistency:
41  * When this bundle is activated after other bundles containing yang files, the resolving order
42  * is not preserved. We thus maintain two maps, one containing consistent snapshot, other inconsistent. The
43  * container should eventually send all events and thus making the inconsistent map redundant.
44  */
45 public class ExtenderYangTracker extends BundleTracker<Object> implements YangStoreService, AutoCloseable {
46
47     private static final Logger logger = LoggerFactory.getLogger(ExtenderYangTracker.class);
48
49     private final Multimap<Bundle, URL> consistentBundlesToYangURLs = HashMultimap.create();
50
51     /*
52     Map of currently problematic yang files that should get fixed eventually after all events are received.
53      */
54     private final Multimap<Bundle, URL> inconsistentBundlesToYangURLs = HashMultimap.create();
55
56     private final YangStoreCache cache = new YangStoreCache();
57     private final MbeParser mbeParser;
58
59
60     public ExtenderYangTracker(Optional<Pattern> maybeBlacklist, BundleContext bundleContext) {
61         this(new MbeParser(), maybeBlacklist, bundleContext);
62     }
63
64     @GuardedBy("this")
65     private Optional<Pattern> maybeBlacklist;
66
67     @VisibleForTesting
68     ExtenderYangTracker(MbeParser mbeParser, Optional<Pattern> maybeBlacklist, BundleContext bundleContext) {
69         super(bundleContext, BundleEvent.RESOLVED | BundleEvent.UNRESOLVED, null);
70         this.mbeParser = mbeParser;
71         this.maybeBlacklist = maybeBlacklist;
72         open();
73     }
74
75     @Override
76     public synchronized Object addingBundle(Bundle bundle, BundleEvent event) {
77
78         // Ignore system bundle:
79         // system bundle might have config-api on classpath &&
80         // config-api contains yang files =>
81         // system bundle might contain yang files from that bundle
82         if (bundle.getBundleId() == 0)
83             return bundle;
84
85         if (maybeBlacklist.isPresent()) {
86             Matcher m = maybeBlacklist.get().matcher(bundle.getSymbolicName());
87             if (m.matches()) {
88                 logger.debug("Ignoring {} because it is in blacklist {}", bundle, maybeBlacklist);
89                 return bundle;
90             }
91         }
92
93         Enumeration<URL> enumeration = bundle.findEntries("META-INF/yang", "*.yang", false);
94         if (enumeration != null && enumeration.hasMoreElements()) {
95             synchronized (this) {
96                 List<URL> addedURLs = new ArrayList<>();
97                 while (enumeration.hasMoreElements()) {
98                     URL url = enumeration.nextElement();
99                     addedURLs.add(url);
100                 }
101                 logger.trace("Bundle {} has event {}, bundle state {}, URLs {}", bundle, event, bundle.getState(), addedURLs);
102                 // test that yang store is consistent
103                 Multimap<Bundle, URL> proposedNewState = HashMultimap.create(consistentBundlesToYangURLs);
104                 proposedNewState.putAll(inconsistentBundlesToYangURLs);
105                 proposedNewState.putAll(bundle, addedURLs);
106
107                 Preconditions.checkArgument(addedURLs.size() > 0, "No change can occur when no URLs are changed");
108
109                 try(YangStoreSnapshotImpl snapshot = createSnapshot(mbeParser, proposedNewState)) {
110                     onSnapshotSuccess(proposedNewState, snapshot);
111                 } catch(YangStoreException e) {
112                     onSnapshotFailure(bundle, addedURLs, e);
113                 }
114             }
115         }
116         return bundle;
117     }
118
119     private synchronized void onSnapshotFailure(Bundle bundle, List<URL> addedURLs, Exception failureReason) {
120         // inconsistent state
121         inconsistentBundlesToYangURLs.putAll(bundle, addedURLs);
122
123         logger.debug("Yang store is falling back to last consistent state containing {}, inconsistent yang files {}",
124                 consistentBundlesToYangURLs, inconsistentBundlesToYangURLs, failureReason);
125         logger.info("Yang store is falling back to last consistent state containing {} files, keeping {} inconsistent yang files due to {}",
126                 consistentBundlesToYangURLs.size(), inconsistentBundlesToYangURLs.size(), failureReason.toString());
127         cache.setInconsistentURLsForReporting(inconsistentBundlesToYangURLs.values());
128     }
129
130     private synchronized void onSnapshotSuccess(Multimap<Bundle, URL> proposedNewState, YangStoreSnapshotImpl snapshot) {
131         // consistent state
132         // merge into
133         consistentBundlesToYangURLs.clear();
134         consistentBundlesToYangURLs.putAll(proposedNewState);
135
136         logger.debug("Yang store updated to new consistent state containing {}", consistentBundlesToYangURLs);
137
138         // If we cleared up some inconsistent models, report that
139         if (!inconsistentBundlesToYangURLs.isEmpty()) {
140             inconsistentBundlesToYangURLs.clear();
141             logger.info("Yang store updated to new consistent state containing {} yang files", consistentBundlesToYangURLs.size());
142         }
143
144         updateCache(snapshot);
145         cache.setInconsistentURLsForReporting(Collections.<URL> emptySet());
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 }