a708c412b9415ba58abe0dc4fc52835a2b89a860
[yangtools.git] / yang / yang-maven-plugin / src / main / java / org / opendaylight / yangtools / yang2sources / plugin / YangToSourcesProcessor.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.yangtools.yang2sources.plugin;
9
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Throwables;
13 import com.google.common.collect.ImmutableList;
14 import com.google.common.collect.ImmutableSet;
15 import com.google.common.io.CharStreams;
16 import java.io.File;
17 import java.io.IOException;
18 import java.io.Reader;
19 import java.nio.charset.StandardCharsets;
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.HashMap;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Optional;
26 import java.util.Set;
27 import org.apache.maven.plugin.MojoExecutionException;
28 import org.apache.maven.plugin.MojoFailureException;
29 import org.apache.maven.project.MavenProject;
30 import org.codehaus.plexus.util.FileUtils;
31 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
32 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
33 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
34 import org.opendaylight.yangtools.yang.parser.repo.YangTextSchemaContextResolver;
35 import org.opendaylight.yangtools.yang2sources.plugin.ConfigArg.CodeGeneratorArg;
36 import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
37 import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
38 import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41 import org.sonatype.plexus.build.incremental.BuildContext;
42 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
43
44 class YangToSourcesProcessor {
45     private static final Logger LOG = LoggerFactory.getLogger(YangToSourcesProcessor.class);
46
47     static final String LOG_PREFIX = "yang-to-sources:";
48     private static final String META_INF_STR = "META-INF";
49     private static final String YANG_STR = "yang";
50
51     static final String META_INF_YANG_STRING = META_INF_STR + File.separator + YANG_STR;
52     static final String META_INF_YANG_STRING_JAR = META_INF_STR + "/" + YANG_STR;
53     static final String META_INF_YANG_SERVICES_STRING_JAR = META_INF_STR + "/" + "services";
54
55     private final File yangFilesRootDir;
56     private final Set<File> excludedFiles;
57     private final List<CodeGeneratorArg> codeGenerators;
58     private final MavenProject project;
59     private final boolean inspectDependencies;
60     private final BuildContext buildContext;
61     private final YangProvider yangProvider;
62
63     private YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
64             final Collection<File> excludedFiles, final List<CodeGeneratorArg> codeGenerators,
65             final MavenProject project, final boolean inspectDependencies, final YangProvider yangProvider) {
66         this.buildContext = Preconditions.checkNotNull(buildContext, "buildContext");
67         this.yangFilesRootDir = Preconditions.checkNotNull(yangFilesRootDir, "yangFilesRootDir");
68         this.excludedFiles = ImmutableSet.copyOf(excludedFiles);
69         this.codeGenerators = ImmutableList.copyOf(codeGenerators);
70         this.project = Preconditions.checkNotNull(project);
71         this.inspectDependencies = inspectDependencies;
72         this.yangProvider = Preconditions.checkNotNull(yangProvider);
73     }
74
75     @VisibleForTesting
76     YangToSourcesProcessor(final File yangFilesRootDir, final Collection<File> excludedFiles,
77             final List<CodeGeneratorArg> codeGenerators, final MavenProject project, final boolean inspectDependencies,
78             final YangProvider yangProvider) {
79         this(new DefaultBuildContext(), yangFilesRootDir, excludedFiles, codeGenerators, project,
80                 inspectDependencies, yangProvider);
81     }
82
83     YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
84                 final Collection<File> excludedFiles, final List<CodeGeneratorArg> codeGenerators,
85                 final MavenProject project, final boolean inspectDependencies) {
86         this(yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, YangProvider.getInstance());
87     }
88
89     public void execute() throws MojoExecutionException, MojoFailureException {
90         conditionalExecute(false);
91     }
92
93     void conditionalExecute(final boolean skip) throws MojoExecutionException, MojoFailureException {
94         final Optional<ProcessorModuleReactor> optReactor = createReactor();
95         if (!optReactor.isPresent()) {
96             return;
97         }
98
99         final ProcessorModuleReactor reactor = optReactor.get();
100         if (!skip) {
101             final ContextHolder holder;
102
103             try {
104                 holder = createContextHolder(reactor);
105             } catch (SchemaSourceException | YangSyntaxErrorException e) {
106                 throw new MojoFailureException("Failed to process reactor " + reactor, e);
107             } catch (IOException e) {
108                 throw new MojoExecutionException("Failed to read reactor " + reactor, e);
109             }
110
111             generateSources(holder);
112         } else {
113             LOG.info("Skipping YANG code generation because property yang.skip is true");
114         }
115
116         // add META_INF/yang
117         final Collection<YangTextSchemaSource> models = reactor.getModelsInProject();
118         try {
119             yangProvider.addYangsToMetaInf(project, models);
120         } catch (IOException e) {
121             throw new MojoExecutionException("Failed write model files for " + models, e);
122         }
123
124         // add META_INF/services
125         File generatedServicesDir = new GeneratedDirectories(project).getYangServicesDir();
126         YangProvider.setResource(generatedServicesDir, project);
127         LOG.debug("{} Yang services files from: {} marked as resources: {}", LOG_PREFIX, generatedServicesDir,
128             META_INF_YANG_SERVICES_STRING_JAR);
129     }
130
131     @SuppressWarnings("checkstyle:illegalCatch")
132     private Optional<ProcessorModuleReactor> createReactor() throws MojoExecutionException {
133         LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
134         try {
135             /*
136              * Collect all files which affect YANG context. This includes all
137              * files in current project and optionally any jars/files in the
138              * dependencies.
139              */
140             final Collection<File> yangFilesInProject = Util.listFiles(yangFilesRootDir, excludedFiles);
141
142             final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
143             if (inspectDependencies) {
144                 allFiles.addAll(Util.findYangFilesInDependencies(project));
145             }
146
147             if (allFiles.isEmpty()) {
148                 LOG.info("{} No input files found", LOG_PREFIX);
149                 return Optional.empty();
150             }
151
152             /*
153              * Check if any of the listed files changed. If no changes occurred,
154              * simply return null, which indicates and of execution.
155              */
156             boolean noChange = true;
157             for (final File f : allFiles) {
158                 if (buildContext.hasDelta(f)) {
159                     LOG.debug("{} buildContext {} indicates {} changed, forcing regeneration", LOG_PREFIX,
160                             buildContext, f);
161                     noChange = false;
162                 }
163             }
164
165             if (noChange) {
166                 LOG.info("{} None of {} input files changed", LOG_PREFIX, allFiles.size());
167                 return Optional.empty();
168             }
169
170             final YangTextSchemaContextResolver resolver = YangTextSchemaContextResolver.create("maven-plugin");
171             for (final File f : yangFilesInProject) {
172                 resolver.registerSource(YangTextSchemaSource.forFile(f));
173             }
174
175             LOG.debug("Processed project files: {}", yangFilesInProject);
176             LOG.info("{} Project model files parsed: {}", LOG_PREFIX, yangFilesInProject.size());
177
178             final ProcessorModuleReactor reactor = new ProcessorModuleReactor(resolver);
179             LOG.debug("Initialized reactor {}", reactor, yangFilesInProject);
180             return Optional.of(reactor);
181         } catch (Exception e) {
182             // MojoExecutionException is thrown since execution cannot continue
183             LOG.error("{} Unable to parse {} files from {}", LOG_PREFIX, Util.YANG_SUFFIX, yangFilesRootDir, e);
184             Throwable rootCause = Throwables.getRootCause(e);
185             throw new MojoExecutionException(LOG_PREFIX + " Unable to parse " + Util.YANG_SUFFIX + " files from "
186                     + yangFilesRootDir, rootCause);
187         }
188     }
189
190     private ContextHolder createContextHolder(final ProcessorModuleReactor reactor) throws MojoFailureException,
191             IOException, SchemaSourceException, YangSyntaxErrorException {
192         /**
193          * Set contains all modules generated from input sources. Number of
194          * modules may differ from number of sources due to submodules
195          * (parsed submodule's data are added to its parent module). Set
196          * cannot contains null values.
197          */
198         if (inspectDependencies) {
199             final List<YangTextSchemaSource> sourcesInDependencies = Util.findYangFilesInDependenciesAsStream(
200                 project);
201             for (YangTextSchemaSource s : toUniqueSources(sourcesInDependencies)) {
202                 reactor.registerSource(s);
203             }
204         }
205
206         return reactor.toContext();
207     }
208
209     private static Collection<YangTextSchemaSource> toUniqueSources(final Collection<YangTextSchemaSource> sources)
210             throws IOException {
211         final Map<String, YangTextSchemaSource> byContent = new HashMap<>();
212         for (YangTextSchemaSource s : sources) {
213             try (Reader reader = s.asCharSource(StandardCharsets.UTF_8).openStream()) {
214                 final String contents = CharStreams.toString(reader);
215                 byContent.putIfAbsent(contents, s);
216             }
217         }
218         return byContent.values();
219     }
220
221     /**
222      * Call generate on every generator from plugin configuration.
223      */
224     @SuppressWarnings("checkstyle:illegalCatch")
225     private void generateSources(final ContextHolder context) throws MojoFailureException {
226         if (codeGenerators.size() == 0) {
227             LOG.warn("{} No code generators provided", LOG_PREFIX);
228             return;
229         }
230
231         final Map<String, String> thrown = new HashMap<>();
232         for (CodeGeneratorArg codeGenerator : codeGenerators) {
233             try {
234                 generateSourcesWithOneGenerator(context, codeGenerator);
235             } catch (Exception e) {
236                 // try other generators, exception will be thrown after
237                 LOG.error("{} Unable to generate sources with {} generator", LOG_PREFIX, codeGenerator
238                         .getCodeGeneratorClass(), e);
239                 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
240             }
241         }
242
243         if (!thrown.isEmpty()) {
244             String message = " One or more code generators failed, including failed list(generatorClass=exception) ";
245             LOG.error("{}" + message + "{}", LOG_PREFIX, thrown.toString());
246             throw new MojoFailureException(LOG_PREFIX + message + thrown.toString());
247         }
248     }
249
250     /**
251      * Instantiate generator from class and call required method.
252      */
253     private void generateSourcesWithOneGenerator(final ContextHolder context, final CodeGeneratorArg codeGeneratorCfg)
254             throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
255
256         codeGeneratorCfg.check();
257
258         final BasicCodeGenerator g = getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
259         LOG.info("{} Code generator instantiated from {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass());
260
261         final File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
262
263         if (outputDir == null) {
264             throw new NullPointerException("outputBaseDir is null. Please provide a valid outputBaseDir value in the "
265                     + "pom.xml");
266         }
267
268         project.addCompileSourceRoot(outputDir.getAbsolutePath());
269
270         LOG.info("{} Sources will be generated to {}", LOG_PREFIX, outputDir);
271         LOG.debug("{} Project root dir is {}", LOG_PREFIX, project.getBasedir());
272         LOG.debug("{} Additional configuration picked up for : {}: {}", LOG_PREFIX, codeGeneratorCfg
273                         .getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration());
274
275         if (g instanceof BuildContextAware) {
276             ((BuildContextAware)g).setBuildContext(buildContext);
277         }
278         if (g instanceof MavenProjectAware) {
279             ((MavenProjectAware)g).setMavenProject(project);
280         }
281         g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
282         File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
283
284         YangProvider.setResource(resourceBaseDir, project);
285         g.setResourceBaseDir(resourceBaseDir);
286         LOG.debug("{} Folder: {} marked as resources for generator: {}", LOG_PREFIX, resourceBaseDir,
287                 codeGeneratorCfg.getCodeGeneratorClass());
288
289         FileUtils.deleteDirectory(outputDir);
290         LOG.info("{} Succesfully deleted output directory {}", LOG_PREFIX, outputDir);
291
292         Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules(),
293             context::moduleToResourcePath);
294
295         LOG.info("{} Sources generated by {}: {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(), generated);
296     }
297
298     /**
299      * Instantiate object from fully qualified class name.
300      */
301     private static <T> T getInstance(final String codeGeneratorClass, final Class<T> baseType) throws
302             ClassNotFoundException, InstantiationException, IllegalAccessException {
303         final Class<?> clazz = Class.forName(codeGeneratorClass);
304
305         Preconditions.checkArgument(baseType.isAssignableFrom(clazz), "Code generator %s has to implement %s", clazz,
306             baseType);
307         return baseType.cast(clazz.newInstance());
308     }
309 }