289ff4fa8e85c08f0bf403e9f1ea30f86c7ca438
[mdsal.git] / binding / mdsal-binding-generator-impl / src / main / java / org / opendaylight / yangtools / sal / 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.yangtools.sal.binding.generator.impl;
9
10 import com.google.common.base.Optional;
11 import com.google.common.collect.ImmutableList;
12 import com.google.common.collect.ImmutableSet;
13 import com.google.common.io.ByteSource;
14 import com.google.common.util.concurrent.CheckedFuture;
15 import com.google.common.util.concurrent.Futures;
16 import java.io.IOException;
17 import java.io.InputStream;
18 import java.lang.ref.WeakReference;
19 import java.util.Collection;
20 import java.util.concurrent.ConcurrentHashMap;
21 import java.util.concurrent.ConcurrentMap;
22 import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
23 import org.opendaylight.yangtools.concepts.ObjectRegistration;
24 import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
25 import org.opendaylight.yangtools.sal.binding.generator.api.ModuleInfoRegistry;
26 import org.opendaylight.yangtools.util.ClassLoaderUtils;
27 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
28 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
29 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
30 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
31 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
32 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
33 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
34 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
36 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
37 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
38 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 public class ModuleInfoBackedContext extends GeneratedClassLoadingStrategy
43         implements ModuleInfoRegistry, SchemaContextProvider, SchemaSourceProvider<YangTextSchemaSource> {
44
45     private ModuleInfoBackedContext(final ClassLoadingStrategy loadingStrategy) {
46         this.backingLoadingStrategy = loadingStrategy;
47     }
48
49     public static ModuleInfoBackedContext create() {
50         return new ModuleInfoBackedContext(getTCCLClassLoadingStrategy());
51     }
52
53     public static ModuleInfoBackedContext create(final ClassLoadingStrategy loadingStrategy) {
54         return new ModuleInfoBackedContext(loadingStrategy);
55     }
56
57     private static final Logger LOG = LoggerFactory.getLogger(ModuleInfoBackedContext.class);
58
59     private final ConcurrentMap<String, WeakReference<ClassLoader>> packageNameToClassLoader = new ConcurrentHashMap<>();
60     private final ConcurrentMap<SourceIdentifier, YangModuleInfo> sourceIdentifierToModuleInfo = new ConcurrentHashMap<>();
61
62     private final ClassLoadingStrategy backingLoadingStrategy;
63
64     @Override
65     public Class<?> loadClass(final String fullyQualifiedName) throws ClassNotFoundException {
66         String modulePackageName = BindingReflections.getModelRootPackageName(fullyQualifiedName);
67
68         WeakReference<ClassLoader> classLoaderRef = packageNameToClassLoader.get(modulePackageName);
69         ClassLoader classloader = null;
70         if (classLoaderRef != null && (classloader = classLoaderRef.get()) != null) {
71             return ClassLoaderUtils.loadClass(classloader, fullyQualifiedName);
72         }
73         if (backingLoadingStrategy == null) {
74             throw new ClassNotFoundException(fullyQualifiedName);
75         }
76         Class<?> cls = backingLoadingStrategy.loadClass(fullyQualifiedName);
77         if (BindingReflections.isBindingClass(cls)) {
78             boolean newModule = resolveModuleInfo(cls);
79             if (newModule) {
80                 recreateSchemaContext();
81             }
82         }
83
84         return cls;
85     }
86
87
88     private synchronized Optional<SchemaContext> recreateSchemaContext() {
89         try {
90             Collection<ByteSource> streams = getAvailableStreams();
91             CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR
92                     .newBuild();
93             SchemaContext schemaContext = reactor.buildEffective(streams);
94             return Optional.of(schemaContext);
95         } catch (IOException | SourceException | ReactorException e) {
96             LOG.error("Schema was not recreated.", e);
97         }
98         return Optional.absent();
99     }
100
101     // TODO finish schema parsing and expose as SchemaService
102     // Unite with current SchemaService
103     // Implement remove ModuleInfo to update SchemaContext
104
105     public synchronized Optional<SchemaContext> tryToCreateSchemaContext() {
106         return recreateSchemaContext();
107     }
108
109     private Collection<ByteSource> getAvailableStreams() throws IOException {
110         ImmutableSet<YangModuleInfo> moduleInfos = ImmutableSet.copyOf(sourceIdentifierToModuleInfo.values());
111
112         ImmutableList.Builder<ByteSource> sourceStreams = ImmutableList.<ByteSource> builder();
113         for (final YangModuleInfo moduleInfo : moduleInfos) {
114             sourceStreams.add(new ByteSource() {
115
116                 @Override
117                 public InputStream openStream() throws IOException {
118                     return moduleInfo.getModuleSourceStream();
119                 }
120             });
121             ;
122         }
123         return sourceStreams.build();
124     }
125
126     private boolean resolveModuleInfo(final Class<?> cls) {
127         try {
128             return resolveModuleInfo(BindingReflections.getModuleInfo(cls));
129         } catch (Exception e) {
130             throw new IllegalStateException(String.format("Failed to resolve module information for class %s", cls), e);
131         }
132     }
133
134     private boolean resolveModuleInfo(final YangModuleInfo moduleInfo) {
135
136         SourceIdentifier identifier = sourceIdentifierFrom(moduleInfo);
137         YangModuleInfo previous = sourceIdentifierToModuleInfo.putIfAbsent(identifier, moduleInfo);
138         ClassLoader moduleClassLoader = moduleInfo.getClass().getClassLoader();
139         if (previous == null) {
140             String modulePackageName = moduleInfo.getClass().getPackage().getName();
141             packageNameToClassLoader.putIfAbsent(modulePackageName, new WeakReference<ClassLoader>(moduleClassLoader));
142
143             for (YangModuleInfo importedInfo : moduleInfo.getImportedModules()) {
144                 resolveModuleInfo(importedInfo);
145             }
146         } else {
147             return false;
148         }
149         return true;
150     }
151
152     private static SourceIdentifier sourceIdentifierFrom(final YangModuleInfo moduleInfo) {
153         return SourceIdentifier.create(moduleInfo.getName(), Optional.of(moduleInfo.getRevision()));
154     }
155
156     public void addModuleInfos(final Iterable<? extends YangModuleInfo> moduleInfos) {
157         for (YangModuleInfo yangModuleInfo : moduleInfos) {
158             registerModuleInfo(yangModuleInfo);
159         }
160     }
161
162     @Override
163     public ObjectRegistration<YangModuleInfo> registerModuleInfo(final YangModuleInfo yangModuleInfo) {
164         YangModuleInfoRegistration registration = new YangModuleInfoRegistration(yangModuleInfo, this);
165
166         resolveModuleInfo(yangModuleInfo);
167
168         return registration;
169     }
170
171     @Override public CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> getSource(
172         final SourceIdentifier sourceIdentifier) {
173         final YangModuleInfo yangModuleInfo = sourceIdentifierToModuleInfo.get(sourceIdentifier);
174
175         if (yangModuleInfo == null) {
176             LOG.debug("Unknown schema source requested: {}, available sources: {}", sourceIdentifier, sourceIdentifierToModuleInfo.keySet());
177             return Futures
178                 .immediateFailedCheckedFuture(new SchemaSourceException("Unknown schema source: " + sourceIdentifier));
179         }
180
181         return Futures
182             .immediateCheckedFuture(YangTextSchemaSource.delegateForByteSource(sourceIdentifier, new ByteSource() {
183                 @Override public InputStream openStream() throws IOException {
184                     return yangModuleInfo.getModuleSourceStream();
185                 }
186             }));
187     }
188
189     private static class YangModuleInfoRegistration extends AbstractObjectRegistration<YangModuleInfo> {
190
191         private final ModuleInfoBackedContext context;
192
193         public YangModuleInfoRegistration(final YangModuleInfo instance, final ModuleInfoBackedContext context) {
194             super(instance);
195             this.context = context;
196         }
197
198         @Override
199         protected void removeRegistration() {
200             context.remove(this);
201         }
202
203     }
204
205     private void remove(final YangModuleInfoRegistration registration) {
206         // FIXME implement
207     }
208
209     @Override
210     public SchemaContext getSchemaContext() {
211         final Optional<SchemaContext> contextOptional = tryToCreateSchemaContext();
212         if (contextOptional.isPresent()) {
213             return contextOptional.get();
214
215         }
216         throw new IllegalStateException("Unable to recreate SchemaContext, error while parsing");
217     }
218 }