Fix maven plugin ignoring import resolution mode
[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 static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static java.util.Objects.requireNonNull;
13
14 import com.google.common.annotations.VisibleForTesting;
15 import com.google.common.base.Throwables;
16 import com.google.common.collect.ImmutableList;
17 import com.google.common.collect.ImmutableSet;
18 import com.google.common.io.CharStreams;
19 import java.io.File;
20 import java.io.IOException;
21 import java.io.Reader;
22 import java.nio.charset.StandardCharsets;
23 import java.nio.file.Files;
24 import java.nio.file.Path;
25 import java.util.AbstractMap.SimpleImmutableEntry;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.Comparator;
29 import java.util.HashMap;
30 import java.util.Iterator;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.Map.Entry;
34 import java.util.Optional;
35 import java.util.ServiceLoader;
36 import java.util.Set;
37 import java.util.stream.Collectors;
38 import org.apache.maven.plugin.MojoExecutionException;
39 import org.apache.maven.plugin.MojoFailureException;
40 import org.apache.maven.project.MavenProject;
41 import org.opendaylight.yangtools.yang.common.YangConstants;
42 import org.opendaylight.yangtools.yang.model.parser.api.YangParser;
43 import org.opendaylight.yangtools.yang.model.parser.api.YangParserException;
44 import org.opendaylight.yangtools.yang.model.parser.api.YangParserFactory;
45 import org.opendaylight.yangtools.yang.model.repo.api.StatementParserMode;
46 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
47 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.ASTSchemaSource;
48 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToASTTransformer;
49 import org.opendaylight.yangtools.yang2sources.plugin.ConfigArg.CodeGeneratorArg;
50 import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
51 import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator.ImportResolutionMode;
52 import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
53 import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56 import org.sonatype.plexus.build.incremental.BuildContext;
57 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
58
59 class YangToSourcesProcessor {
60     private static final Logger LOG = LoggerFactory.getLogger(YangToSourcesProcessor.class);
61     private static final YangParserFactory DEFAULT_PARSER_FACTORY;
62
63     static {
64         final Iterator<YangParserFactory> it = ServiceLoader.load(YangParserFactory.class).iterator();
65         checkState(it.hasNext(), "Failed to find a YangParserFactory implementation");
66         DEFAULT_PARSER_FACTORY = it.next();
67     }
68
69     static final String LOG_PREFIX = "yang-to-sources:";
70     private static final String META_INF_STR = "META-INF";
71     private static final String YANG_STR = "yang";
72
73     static final String META_INF_YANG_STRING = META_INF_STR + File.separator + YANG_STR;
74     static final String META_INF_YANG_STRING_JAR = META_INF_STR + "/" + YANG_STR;
75     static final String META_INF_YANG_SERVICES_STRING_JAR = META_INF_STR + "/" + "services";
76
77     private final YangParserFactory parserFactory;
78     private final File yangFilesRootDir;
79     private final Set<File> excludedFiles;
80     private final List<CodeGeneratorArg> codeGeneratorArgs;
81     private final MavenProject project;
82     private final boolean inspectDependencies;
83     private final BuildContext buildContext;
84     private final YangProvider yangProvider;
85
86     private YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
87             final Collection<File> excludedFiles, final List<CodeGeneratorArg> codeGenerators,
88             final MavenProject project, final boolean inspectDependencies, final YangProvider yangProvider) {
89         this.buildContext = requireNonNull(buildContext, "buildContext");
90         this.yangFilesRootDir = requireNonNull(yangFilesRootDir, "yangFilesRootDir");
91         this.excludedFiles = ImmutableSet.copyOf(excludedFiles);
92         this.codeGeneratorArgs = ImmutableList.copyOf(codeGenerators);
93         this.project = requireNonNull(project);
94         this.inspectDependencies = inspectDependencies;
95         this.yangProvider = requireNonNull(yangProvider);
96         this.parserFactory = DEFAULT_PARSER_FACTORY;
97     }
98
99     @VisibleForTesting
100     YangToSourcesProcessor(final File yangFilesRootDir, final Collection<File> excludedFiles,
101             final List<CodeGeneratorArg> codeGenerators, final MavenProject project, final boolean inspectDependencies,
102             final YangProvider yangProvider) {
103         this(new DefaultBuildContext(), yangFilesRootDir, excludedFiles, codeGenerators, project,
104                 inspectDependencies, yangProvider);
105     }
106
107     YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
108                 final Collection<File> excludedFiles, final List<CodeGeneratorArg> codeGenerators,
109                 final MavenProject project, final boolean inspectDependencies) {
110         this(yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, YangProvider.getInstance());
111     }
112
113     public void execute() throws MojoExecutionException, MojoFailureException {
114         conditionalExecute(false);
115     }
116
117     void conditionalExecute(final boolean skip) throws MojoExecutionException, MojoFailureException {
118         /*
119          * Collect all files which affect YANG context. This includes all
120          * files in current project and optionally any jars/files in the
121          * dependencies.
122          */
123         final List<File> yangFilesInProject;
124         try {
125             yangFilesInProject = listFiles(yangFilesRootDir, excludedFiles);
126         } catch (IOException e) {
127             throw new MojoFailureException("Failed to list project files", e);
128         }
129
130         if (yangFilesInProject.isEmpty()) {
131             // No files to process, skip.
132             LOG.info("{} No input files found", LOG_PREFIX);
133             return;
134         }
135
136         // We need to instantiate all code generators to determine required import resolution mode
137         final List<Entry<CodeGeneratorArg, BasicCodeGenerator>> codeGenerators = instantiateGenerators();
138         final StatementParserMode importMode = determineRequiredImportMode(codeGenerators);
139         final Optional<ProcessorModuleReactor> optReactor = createReactor(importMode, yangFilesInProject);
140         if (!optReactor.isPresent()) {
141             return;
142         }
143
144         final ProcessorModuleReactor reactor = optReactor.get();
145         if (!skip) {
146             final ContextHolder holder;
147
148             try {
149                 holder = createContextHolder(reactor);
150             } catch (YangParserException e) {
151                 throw new MojoFailureException("Failed to process reactor " + reactor, e);
152             } catch (IOException e) {
153                 throw new MojoExecutionException("Failed to read reactor " + reactor, e);
154             }
155
156             generateSources(holder, codeGenerators);
157         } else {
158             LOG.info("Skipping YANG code generation because property yang.skip is true");
159         }
160
161         // add META_INF/yang
162         final Collection<YangTextSchemaSource> models = reactor.getModelsInProject();
163         try {
164             yangProvider.addYangsToMetaInf(project, models);
165         } catch (IOException e) {
166             throw new MojoExecutionException("Failed write model files for " + models, e);
167         }
168
169         // add META_INF/services
170         File generatedServicesDir = new GeneratedDirectories(project).getYangServicesDir();
171         YangProvider.setResource(generatedServicesDir, project);
172         LOG.debug("{} Yang services files from: {} marked as resources: {}", LOG_PREFIX, generatedServicesDir,
173             META_INF_YANG_SERVICES_STRING_JAR);
174     }
175
176     private static StatementParserMode determineRequiredImportMode(
177             final Collection<Entry<CodeGeneratorArg, BasicCodeGenerator>> codeGenerators) throws MojoFailureException {
178         ImportResolutionMode requestedMode = null;
179         BasicCodeGenerator requestingGenerator = null;
180
181         for (Entry<CodeGeneratorArg, BasicCodeGenerator> entry : codeGenerators) {
182             final BasicCodeGenerator generator = entry.getValue();
183             final ImportResolutionMode mode = generator.getImportResolutionMode();
184             if (mode == null) {
185                 // the generator does not care about the mode
186                 continue;
187             }
188
189             if (requestedMode == null) {
190                 // No mode yet, we have just determined it
191                 requestedMode = mode;
192                 requestingGenerator = generator;
193                 continue;
194             }
195
196             if (mode != requestedMode) {
197                 throw new MojoFailureException(String.format(
198                     "Import resolution mode conflict between %s (%s) and %s (%s)", requestingGenerator, requestedMode,
199                     generator, mode));
200             }
201         }
202
203         if (requestedMode == null) {
204             return StatementParserMode.DEFAULT_MODE;
205         }
206         switch (requestedMode) {
207             case REVISION_EXACT_OR_LATEST:
208                 return StatementParserMode.DEFAULT_MODE;
209             case SEMVER_LATEST:
210                 return StatementParserMode.SEMVER_MODE;
211             default:
212                 throw new IllegalStateException("Unhandled import resolution mode " + requestedMode);
213         }
214     }
215
216     private List<Entry<CodeGeneratorArg, BasicCodeGenerator>> instantiateGenerators() throws MojoExecutionException {
217         final List<Entry<CodeGeneratorArg, BasicCodeGenerator>> generators = new ArrayList<>(codeGeneratorArgs.size());
218         for (CodeGeneratorArg arg : codeGeneratorArgs) {
219             arg.check();
220
221             final BasicCodeGenerator generator;
222             try {
223                 generator = getInstance(arg.getCodeGeneratorClass(), BasicCodeGenerator.class);
224             } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
225                 throw new MojoExecutionException("Failed to instantiate code generator "
226                         + arg.getCodeGeneratorClass(), e);
227             }
228
229             LOG.info("{} Code generator instantiated from {}", LOG_PREFIX, arg.getCodeGeneratorClass());
230             generators.add(new SimpleImmutableEntry<>(arg, generator));
231         }
232
233         return generators;
234     }
235
236     @SuppressWarnings("checkstyle:illegalCatch")
237     private Optional<ProcessorModuleReactor> createReactor(final StatementParserMode parserMode,
238             final List<File> yangFilesInProject) throws MojoExecutionException {
239         LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
240         try {
241
242             final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
243             if (inspectDependencies) {
244                 allFiles.addAll(Util.findYangFilesInDependencies(project));
245             }
246
247             /*
248              * Check if any of the listed files changed. If no changes occurred,
249              * simply return null, which indicates and of execution.
250              */
251             if (!allFiles.stream().anyMatch(buildContext::hasDelta)) {
252                 LOG.info("{} None of {} input files changed", LOG_PREFIX, allFiles.size());
253                 return Optional.empty();
254             }
255
256             final YangParser parser = parserFactory.createParser(parserMode);
257             final List<YangTextSchemaSource> sourcesInProject = new ArrayList<>(yangFilesInProject.size());
258             for (final File f : yangFilesInProject) {
259                 final YangTextSchemaSource textSource = YangTextSchemaSource.forFile(f);
260                 final ASTSchemaSource astSource = TextToASTTransformer.transformText(textSource);
261
262                 parser.addSource(astSource);
263
264                 if (!astSource.getIdentifier().equals(textSource.getIdentifier())) {
265                     // AST indicates a different source identifier, make sure we use that
266                     sourcesInProject.add(YangTextSchemaSource.delegateForByteSource(astSource.getIdentifier(),
267                         textSource));
268                 } else {
269                     sourcesInProject.add(textSource);
270                 }
271             }
272
273             LOG.debug("Processed project files: {}", yangFilesInProject);
274             LOG.info("{} Project model files parsed: {}", LOG_PREFIX, yangFilesInProject.size());
275
276             final ProcessorModuleReactor reactor = new ProcessorModuleReactor(parser, sourcesInProject);
277             LOG.debug("Initialized reactor {}", reactor, yangFilesInProject);
278             return Optional.of(reactor);
279         } catch (Exception e) {
280             // MojoExecutionException is thrown since execution cannot continue
281             LOG.error("{} Unable to parse YANG files from {}", LOG_PREFIX, yangFilesRootDir, e);
282             Throwable rootCause = Throwables.getRootCause(e);
283             throw new MojoExecutionException(LOG_PREFIX + " Unable to parse YANG files from " + yangFilesRootDir,
284                 rootCause);
285         }
286     }
287
288     private ContextHolder createContextHolder(final ProcessorModuleReactor reactor) throws MojoFailureException,
289             IOException, YangParserException {
290         /**
291          * Set contains all modules generated from input sources. Number of
292          * modules may differ from number of sources due to submodules
293          * (parsed submodule's data are added to its parent module). Set
294          * cannot contains null values.
295          */
296         if (inspectDependencies) {
297             final List<YangTextSchemaSource> sourcesInDependencies = Util.findYangFilesInDependenciesAsStream(
298                 project);
299             for (YangTextSchemaSource s : toUniqueSources(sourcesInDependencies)) {
300                 reactor.registerSourceFromDependency(s);
301             }
302         }
303
304         return reactor.toContext();
305     }
306
307     private static List<File> listFiles(final File root, final Collection<File> excludedFiles)
308             throws IOException {
309         if (!root.isDirectory()) {
310             LOG.warn("{} YANG source directory {} not found. No code will be generated.", LOG_PREFIX, root);
311             return ImmutableList.of();
312         }
313
314         return Files.walk(root.toPath()).map(Path::toFile).filter(File::isFile).filter(f -> {
315             if (excludedFiles.contains(f)) {
316                 LOG.info("{} YANG file excluded {}", LOG_PREFIX, f);
317                 return false;
318             }
319             return true;
320         }).filter(f -> f.getName().endsWith(YangConstants.RFC6020_YANG_FILE_EXTENSION)).collect(Collectors.toList());
321     }
322
323     private static Collection<YangTextSchemaSource> toUniqueSources(final Collection<YangTextSchemaSource> sources)
324             throws IOException {
325         final Map<String, YangTextSchemaSource> byContent = new HashMap<>();
326         for (YangTextSchemaSource s : sources) {
327             try (Reader reader = s.asCharSource(StandardCharsets.UTF_8).openStream()) {
328                 final String contents = CharStreams.toString(reader);
329                 byContent.putIfAbsent(contents, s);
330             }
331         }
332         return byContent.values();
333     }
334
335     /**
336      * Call generate on every generator from plugin configuration.
337      */
338     @SuppressWarnings("checkstyle:illegalCatch")
339     private void generateSources(final ContextHolder context,
340             final Collection<Entry<CodeGeneratorArg, BasicCodeGenerator>> generators) throws MojoFailureException {
341         if (generators.isEmpty()) {
342             LOG.warn("{} No code generators provided", LOG_PREFIX);
343             return;
344         }
345
346         final Map<String, String> thrown = new HashMap<>();
347         for (Entry<CodeGeneratorArg, BasicCodeGenerator> entry : generators) {
348             final String codeGeneratorClass = entry.getKey().getCodeGeneratorClass();
349
350             try {
351                 generateSourcesWithOneGenerator(context, entry.getKey(), entry.getValue());
352             } catch (Exception e) {
353                 // try other generators, exception will be thrown after
354                 LOG.error("{} Unable to generate sources with {} generator", LOG_PREFIX, codeGeneratorClass, e);
355                 thrown.put(codeGeneratorClass, e.getClass().getCanonicalName());
356             }
357         }
358
359         if (!thrown.isEmpty()) {
360             String message = " One or more code generators failed, including failed list(generatorClass=exception) ";
361             LOG.error("{}{}{}", LOG_PREFIX, message, thrown.toString());
362             throw new MojoFailureException(LOG_PREFIX + message + thrown.toString());
363         }
364     }
365
366     /**
367      * Complete initialization of a code generator and invoke it.
368      */
369     private void generateSourcesWithOneGenerator(final ContextHolder context, final CodeGeneratorArg codeGeneratorCfg,
370             final BasicCodeGenerator codeGenerator) throws IOException {
371
372         final File outputDir = requireNonNull(codeGeneratorCfg.getOutputBaseDir(project),
373             "outputBaseDir is null. Please provide a valid outputBaseDir value in pom.xml");
374
375         project.addCompileSourceRoot(outputDir.getAbsolutePath());
376
377         LOG.info("{} Sources will be generated to {}", LOG_PREFIX, outputDir);
378         LOG.debug("{} Project root dir is {}", LOG_PREFIX, project.getBasedir());
379         LOG.debug("{} Additional configuration picked up for : {}: {}", LOG_PREFIX, codeGeneratorCfg
380                         .getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration());
381
382         if (codeGenerator instanceof BuildContextAware) {
383             ((BuildContextAware)codeGenerator).setBuildContext(buildContext);
384         }
385         if (codeGenerator instanceof MavenProjectAware) {
386             ((MavenProjectAware)codeGenerator).setMavenProject(project);
387         }
388         codeGenerator.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
389         File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
390
391         YangProvider.setResource(resourceBaseDir, project);
392         codeGenerator.setResourceBaseDir(resourceBaseDir);
393         LOG.debug("{} Folder: {} marked as resources for generator: {}", LOG_PREFIX, resourceBaseDir,
394                 codeGeneratorCfg.getCodeGeneratorClass());
395
396         if (outputDir.exists()) {
397             Files.walk(outputDir.toPath()).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
398             LOG.info("{} Succesfully deleted output directory {}", LOG_PREFIX, outputDir);
399         }
400         Collection<File> generated = codeGenerator.generateSources(context.getContext(), outputDir,
401             context.getYangModules(), context::moduleToResourcePath);
402
403         LOG.info("{} Sources generated by {}: {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(), generated);
404     }
405
406     /**
407      * Instantiate object from fully qualified class name.
408      */
409     private static <T> T getInstance(final String codeGeneratorClass, final Class<T> baseType) throws
410             ClassNotFoundException, InstantiationException, IllegalAccessException {
411         final Class<?> clazz = Class.forName(codeGeneratorClass);
412         checkArgument(baseType.isAssignableFrom(clazz), "Code generator %s has to implement %s", clazz, baseType);
413         return baseType.cast(clazz.newInstance());
414     }
415 }