2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.config.yang.store.impl;
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;
30 import javax.annotation.concurrent.GuardedBy;
31 import java.io.IOException;
32 import java.io.InputStream;
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;
41 import java.util.regex.Matcher;
42 import java.util.regex.Pattern;
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.
50 public class ExtenderYangTracker extends BundleTracker<Object> implements YangStoreService, AutoCloseable {
52 private static final Logger logger = LoggerFactory.getLogger(ExtenderYangTracker.class);
54 private final Multimap<Bundle, URL> consistentBundlesToYangURLs = HashMultimap.create();
57 Map of currently problematic yang files that should get fixed eventually after all events are received.
59 private final Multimap<Bundle, URL> inconsistentBundlesToYangURLs = HashMultimap.create();
61 private final YangStoreCache cache = new YangStoreCache();
62 private final MbeParser mbeParser;
65 public ExtenderYangTracker(Optional<Pattern> maybeBlacklist, BundleContext bundleContext) {
66 this(new MbeParser(), maybeBlacklist, bundleContext);
70 private Optional<Pattern> maybeBlacklist;
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;
81 public synchronized Object addingBundle(Bundle bundle, BundleEvent event) {
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)
90 if (maybeBlacklist.isPresent()) {
91 Matcher m = maybeBlacklist.get().matcher(bundle.getSymbolicName());
93 logger.debug("Ignoring {} because it is in blacklist {}", bundle, maybeBlacklist);
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();
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);
112 Preconditions.checkArgument(addedURLs.size() > 0, "No change can occur when no URLs are changed");
114 try(YangStoreSnapshotImpl snapshot = createSnapshot(mbeParser, proposedNewState)) {
115 onSnapshotSuccess(proposedNewState, snapshot);
116 } catch(YangStoreException e) {
117 onSnapshotFailure(bundle, addedURLs, e);
124 private synchronized void onSnapshotFailure(Bundle bundle, List<URL> addedURLs, Exception failureReason) {
125 // inconsistent state
126 inconsistentBundlesToYangURLs.putAll(bundle, addedURLs);
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());
135 private synchronized void onSnapshotSuccess(Multimap<Bundle, URL> proposedNewState, YangStoreSnapshotImpl snapshot) {
138 consistentBundlesToYangURLs.clear();
139 consistentBundlesToYangURLs.putAll(proposedNewState);
140 inconsistentBundlesToYangURLs.clear();
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);
148 private synchronized void updateCache(YangStoreSnapshotImpl snapshot) {
149 cache.cacheYangStore(consistentBundlesToYangURLs, snapshot);
153 public void modifiedBundle(Bundle bundle, BundleEvent event, Object object) {
154 logger.debug("Modified bundle {} {} {}", bundle, event, object);
158 * If removing YANG files makes yang store inconsistent, method {@link #getYangStoreSnapshot()}
159 * will throw exception. There is no rollback.
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);
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();
177 YangStoreSnapshotImpl snapshot = createSnapshot(mbeParser, consistentBundlesToYangURLs);
178 updateCache(snapshot);
182 private static YangStoreSnapshotImpl createSnapshot(MbeParser mbeParser, Multimap<Bundle, URL> multimap) throws YangStoreException {
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();
191 while (cause != null) {
192 causeStr.append(e.getMessage());
193 causeStr.append("\n");
194 cause = e.getCause();
196 throw new YangStoreException("Unable to parse yang files. \n" + causeStr.toString() +
197 "URLs: " + multimap, e);
201 private static Collection<InputStream> fromUrlsToInputStreams(Multimap<Bundle, URL> multimap) {
202 return Collections2.transform(multimap.values(),
203 new Function<URL, InputStream>() {
206 public InputStream apply(URL url) {
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);
218 public synchronized void setMaybeBlacklist(Optional<Pattern> maybeBlacklistPattern) {
219 maybeBlacklist = maybeBlacklistPattern;
224 class YangStoreCache {
225 private static final Logger logger = LoggerFactory.getLogger(YangStoreCache.class);
228 private Set<URL> cachedUrls = null;
230 private Optional<YangStoreSnapshot> cachedYangStoreSnapshot = getInitialSnapshot();
232 private Collection<URL> inconsistentURLsForReporting = Collections.emptySet();
234 synchronized Optional<YangStoreSnapshot> getSnapshotIfPossible(Multimap<Bundle, URL> bundlesToYangURLs) {
235 Set<URL> urls = setFromMultimapValues(bundlesToYangURLs);
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);
243 return Optional.of(freshSnapshot);
246 return Optional.absent();
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());
256 synchronized void cacheYangStore(Multimap<Bundle, URL> urls,
257 YangStoreSnapshot yangStoreSnapshot) {
258 this.cachedUrls = setFromMultimapValues(urls);
259 this.cachedYangStoreSnapshot = Optional.of(yangStoreSnapshot);
262 synchronized void invalidate() {
264 if (cachedYangStoreSnapshot.isPresent()){
265 cachedYangStoreSnapshot.get().close();
266 cachedYangStoreSnapshot = Optional.absent();
270 public synchronized void setInconsistentURLsForReporting(Collection<URL> urls){
271 inconsistentURLsForReporting = urls;
274 private Optional<YangStoreSnapshot> getInitialSnapshot() {
275 YangStoreSnapshot initialSnapshot = new YangStoreSnapshot() {
277 public Map<String, Map<String, ModuleMXBeanEntry>> getModuleMXBeanEntryMap() {
278 return Collections.emptyMap();
282 public Map<String, Map.Entry<Module, String>> getModuleMap() {
283 return Collections.emptyMap();
287 public int countModuleMXBeanEntries() {
292 public void close() {
295 return Optional.of(initialSnapshot);