ModuleInfoBackedContext cache
[mdsal.git] / binding / mdsal-binding-generator-impl / src / main / java / org / opendaylight / mdsal / binding / generator / impl / ModuleInfoBackedContext.java
1 /*
2  * Copyright (c) 2014 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.mdsal.binding.generator.impl;
9
10 import com.google.common.annotations.Beta;
11 import com.google.common.cache.CacheBuilder;
12 import com.google.common.cache.CacheLoader;
13 import com.google.common.cache.LoadingCache;
14 import com.google.common.collect.ImmutableSet;
15 import com.google.common.util.concurrent.Futures;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
18 import java.lang.ref.WeakReference;
19 import java.util.Optional;
20 import java.util.Set;
21 import java.util.concurrent.ConcurrentHashMap;
22 import java.util.concurrent.ConcurrentMap;
23 import org.opendaylight.mdsal.binding.generator.api.ClassLoadingStrategy;
24 import org.opendaylight.mdsal.binding.generator.api.ModuleInfoRegistry;
25 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
26 import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
27 import org.opendaylight.yangtools.concepts.ObjectRegistration;
28 import org.opendaylight.yangtools.util.ClassLoaderUtils;
29 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
30 import org.opendaylight.yangtools.yang.common.QName;
31 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
32 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
33 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
34 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
35 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
36 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
37 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
38 import org.opendaylight.yangtools.yang.parser.repo.YangTextSchemaContextResolver;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 public final class ModuleInfoBackedContext extends GeneratedClassLoadingStrategy
43         implements ModuleInfoRegistry, SchemaContextProvider, SchemaSourceProvider<YangTextSchemaSource> {
44
45     private static final LoadingCache<ClassLoadingStrategy,
46         LoadingCache<ImmutableSet<YangModuleInfo>, ModuleInfoBackedContext>> CONTEXT_CACHES = CacheBuilder.newBuilder()
47             .weakKeys().build(new CacheLoader<ClassLoadingStrategy,
48                 LoadingCache<ImmutableSet<YangModuleInfo>, ModuleInfoBackedContext>>() {
49                     @Override
50                     public LoadingCache<ImmutableSet<YangModuleInfo>, ModuleInfoBackedContext> load(
51                             final ClassLoadingStrategy strategy) {
52                         return CacheBuilder.newBuilder().weakValues().build(
53                             new CacheLoader<Set<YangModuleInfo>, ModuleInfoBackedContext>() {
54                                 @Override
55                                 public ModuleInfoBackedContext load(final Set<YangModuleInfo> key) {
56                                     final ModuleInfoBackedContext context = ModuleInfoBackedContext.create(strategy);
57                                     context.addModuleInfos(key);
58                                     return context;
59                                 }
60                             });
61                     }
62             });
63
64     private final YangTextSchemaContextResolver ctxResolver = YangTextSchemaContextResolver.create("binding-context");
65
66     private ModuleInfoBackedContext(final ClassLoadingStrategy loadingStrategy) {
67         this.backingLoadingStrategy = loadingStrategy;
68     }
69
70     @Beta
71     public static ModuleInfoBackedContext cacheContext(final ClassLoadingStrategy loadingStrategy,
72             final ImmutableSet<YangModuleInfo> infos) {
73         return CONTEXT_CACHES.getUnchecked(loadingStrategy).getUnchecked(infos);
74     }
75
76     public static ModuleInfoBackedContext create() {
77         return new ModuleInfoBackedContext(getTCCLClassLoadingStrategy());
78     }
79
80     public static ModuleInfoBackedContext create(final ClassLoadingStrategy loadingStrategy) {
81         return new ModuleInfoBackedContext(loadingStrategy);
82     }
83
84     private static final Logger LOG = LoggerFactory.getLogger(ModuleInfoBackedContext.class);
85
86     private final ConcurrentMap<String, WeakReference<ClassLoader>> packageNameToClassLoader =
87             new ConcurrentHashMap<>();
88     private final ConcurrentMap<SourceIdentifier, YangModuleInfo> sourceIdentifierToModuleInfo =
89             new ConcurrentHashMap<>();
90
91     private final ClassLoadingStrategy backingLoadingStrategy;
92
93     @Override
94     public Class<?> loadClass(final String fullyQualifiedName) throws ClassNotFoundException {
95         final String modulePackageName = BindingReflections.getModelRootPackageName(fullyQualifiedName);
96         final WeakReference<ClassLoader> classLoaderRef = packageNameToClassLoader.get(modulePackageName);
97         if (classLoaderRef != null) {
98             final ClassLoader classLoader = classLoaderRef.get();
99             if (classLoader != null) {
100                 return ClassLoaderUtils.loadClass(classLoader, fullyQualifiedName);
101             }
102         }
103
104         if (backingLoadingStrategy == null) {
105             throw new ClassNotFoundException(fullyQualifiedName);
106         }
107
108         final Class<?> cls = backingLoadingStrategy.loadClass(fullyQualifiedName);
109         if (BindingReflections.isBindingClass(cls)) {
110             resolveModuleInfo(cls);
111         }
112
113         return cls;
114     }
115
116     // TODO finish schema parsing and expose as SchemaService
117     // Unite with current SchemaService
118     // Implement remove ModuleInfo to update SchemaContext
119
120     public Optional<SchemaContext> tryToCreateSchemaContext() {
121         return ctxResolver.getSchemaContext();
122     }
123
124     @SuppressWarnings("checkstyle:illegalCatch")
125     private boolean resolveModuleInfo(final Class<?> cls) {
126         try {
127             return resolveModuleInfo(BindingReflections.getModuleInfo(cls));
128         } catch (Exception e) {
129             throw new IllegalStateException(String.format("Failed to resolve module information for class %s", cls), e);
130         }
131     }
132
133     @SuppressWarnings("checkstyle:illegalCatch")
134     @SuppressFBWarnings("REC_CATCH_EXCEPTION")
135     private boolean resolveModuleInfo(final YangModuleInfo moduleInfo) {
136         final SourceIdentifier identifier = sourceIdentifierFrom(moduleInfo);
137         final YangModuleInfo previous = sourceIdentifierToModuleInfo.putIfAbsent(identifier, moduleInfo);
138         if (previous != null) {
139             return false;
140         }
141
142         ClassLoader moduleClassLoader = moduleInfo.getClass().getClassLoader();
143         try {
144             String modulePackageName = moduleInfo.getClass().getPackage().getName();
145             packageNameToClassLoader.putIfAbsent(modulePackageName, new WeakReference<>(moduleClassLoader));
146             ctxResolver.registerSource(toYangTextSource(identifier, moduleInfo));
147             for (YangModuleInfo importedInfo : moduleInfo.getImportedModules()) {
148                 resolveModuleInfo(importedInfo);
149             }
150         } catch (Exception e) {
151             LOG.error("Not including {} in YANG sources because of error.", moduleInfo, e);
152         }
153         return true;
154     }
155
156     private static YangTextSchemaSource toYangTextSource(final SourceIdentifier identifier,
157             final YangModuleInfo moduleInfo) {
158         return YangTextSchemaSource.delegateForByteSource(identifier, moduleInfo.getYangTextByteSource());
159     }
160
161     private static SourceIdentifier sourceIdentifierFrom(final YangModuleInfo moduleInfo) {
162         final QName name = moduleInfo.getName();
163         return RevisionSourceIdentifier.create(name.getLocalName(), name.getRevision());
164     }
165
166     public void addModuleInfos(final Iterable<? extends YangModuleInfo> moduleInfos) {
167         for (YangModuleInfo yangModuleInfo : moduleInfos) {
168             registerModuleInfo(yangModuleInfo);
169         }
170     }
171
172     @Override
173     public ObjectRegistration<YangModuleInfo> registerModuleInfo(final YangModuleInfo yangModuleInfo) {
174         YangModuleInfoRegistration registration = new YangModuleInfoRegistration(yangModuleInfo, this);
175         resolveModuleInfo(yangModuleInfo);
176         return registration;
177     }
178
179     @Override
180     public ListenableFuture<? extends YangTextSchemaSource> getSource(
181         final SourceIdentifier sourceIdentifier) {
182         final YangModuleInfo yangModuleInfo = sourceIdentifierToModuleInfo.get(sourceIdentifier);
183
184         if (yangModuleInfo == null) {
185             LOG.debug("Unknown schema source requested: {}, available sources: {}", sourceIdentifier,
186                 sourceIdentifierToModuleInfo.keySet());
187             return Futures.immediateFailedFuture(new SchemaSourceException(
188                 "Unknown schema source: " + sourceIdentifier));
189         }
190
191         return Futures.immediateFuture(YangTextSchemaSource.delegateForByteSource(sourceIdentifier,
192             yangModuleInfo.getYangTextByteSource()));
193     }
194
195     private static class YangModuleInfoRegistration extends AbstractObjectRegistration<YangModuleInfo> {
196
197         private final ModuleInfoBackedContext context;
198
199         YangModuleInfoRegistration(final YangModuleInfo instance, final ModuleInfoBackedContext context) {
200             super(instance);
201             this.context = context;
202         }
203
204         @Override
205         protected void removeRegistration() {
206             context.remove(this);
207         }
208
209     }
210
211     private void remove(final YangModuleInfoRegistration registration) {
212         // FIXME implement
213     }
214
215     @Override
216     public SchemaContext getSchemaContext() {
217         final Optional<SchemaContext> contextOptional = tryToCreateSchemaContext();
218         if (contextOptional.isPresent()) {
219             return contextOptional.get();
220
221         }
222         throw new IllegalStateException("Unable to recreate SchemaContext, error while parsing");
223     }
224 }