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