Add timing information about local file discovery
[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.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.SchemaSourceException;
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(buildContext, yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies,
111             YangProvider.getInstance());
112     }
113
114     public void execute() throws MojoExecutionException, MojoFailureException {
115         conditionalExecute(false);
116     }
117
118     void conditionalExecute(final boolean skip) throws MojoExecutionException, MojoFailureException {
119         /*
120          * Collect all files which affect YANG context. This includes all
121          * files in current project and optionally any jars/files in the
122          * dependencies.
123          */
124         final List<File> yangFilesInProject;
125         try {
126             yangFilesInProject = listFiles(yangFilesRootDir, excludedFiles);
127         } catch (IOException e) {
128             throw new MojoFailureException("Failed to list project files", e);
129         }
130
131         if (yangFilesInProject.isEmpty()) {
132             // No files to process, skip.
133             LOG.info("{} No input files found", LOG_PREFIX);
134             return;
135         }
136
137         // We need to instantiate all code generators to determine required import resolution mode
138         final List<Entry<CodeGeneratorArg, BasicCodeGenerator>> codeGenerators = instantiateGenerators();
139         final StatementParserMode importMode = determineRequiredImportMode(codeGenerators);
140         final Optional<ProcessorModuleReactor> optReactor = createReactor(importMode, yangFilesInProject);
141         if (!optReactor.isPresent()) {
142             return;
143         }
144
145         final ProcessorModuleReactor reactor = optReactor.get();
146         if (!skip) {
147             final Stopwatch watch = Stopwatch.createStarted();
148             final ContextHolder holder;
149
150             try {
151                 holder = reactor.toContext();
152             } catch (YangParserException e) {
153                 throw new MojoFailureException("Failed to process reactor " + reactor, e);
154             } catch (IOException e) {
155                 throw new MojoExecutionException("Failed to read reactor " + reactor, e);
156             }
157
158             LOG.info("{} {} YANG models processed in {}", LOG_PREFIX, holder.getContext().getModules().size(), watch);
159             generateSources(holder, codeGenerators);
160         } else {
161             LOG.info("{} Skipping YANG code generation because property yang.skip is true", LOG_PREFIX);
162         }
163
164         // add META_INF/yang
165         final Collection<YangTextSchemaSource> models = reactor.getModelsInProject();
166         try {
167             yangProvider.addYangsToMetaInf(project, models);
168         } catch (IOException e) {
169             throw new MojoExecutionException("Failed write model files for " + models, e);
170         }
171
172         // add META_INF/services
173         File generatedServicesDir = new GeneratedDirectories(project).getYangServicesDir();
174         YangProvider.setResource(generatedServicesDir, project);
175         LOG.debug("{} Yang services files from: {} marked as resources: {}", LOG_PREFIX, generatedServicesDir,
176             META_INF_YANG_SERVICES_STRING_JAR);
177     }
178
179     private static StatementParserMode determineRequiredImportMode(
180             final Collection<Entry<CodeGeneratorArg, BasicCodeGenerator>> codeGenerators) throws MojoFailureException {
181         ImportResolutionMode requestedMode = null;
182         BasicCodeGenerator requestingGenerator = null;
183
184         for (Entry<CodeGeneratorArg, BasicCodeGenerator> entry : codeGenerators) {
185             final BasicCodeGenerator generator = entry.getValue();
186             final ImportResolutionMode mode = generator.getImportResolutionMode();
187             if (mode == null) {
188                 // the generator does not care about the mode
189                 continue;
190             }
191
192             if (requestedMode == null) {
193                 // No mode yet, we have just determined it
194                 requestedMode = mode;
195                 requestingGenerator = generator;
196                 continue;
197             }
198
199             if (mode != requestedMode) {
200                 throw new MojoFailureException(String.format(
201                     "Import resolution mode conflict between %s (%s) and %s (%s)", requestingGenerator, requestedMode,
202                     generator, mode));
203             }
204         }
205
206         if (requestedMode == null) {
207             return StatementParserMode.DEFAULT_MODE;
208         }
209         switch (requestedMode) {
210             case REVISION_EXACT_OR_LATEST:
211                 return StatementParserMode.DEFAULT_MODE;
212             case SEMVER_LATEST:
213                 return StatementParserMode.SEMVER_MODE;
214             default:
215                 throw new IllegalStateException("Unhandled import resolution mode " + requestedMode);
216         }
217     }
218
219     private List<Entry<CodeGeneratorArg, BasicCodeGenerator>> instantiateGenerators() throws MojoExecutionException {
220         final List<Entry<CodeGeneratorArg, BasicCodeGenerator>> generators = new ArrayList<>(codeGeneratorArgs.size());
221         for (CodeGeneratorArg arg : codeGeneratorArgs) {
222             arg.check();
223
224             final BasicCodeGenerator generator;
225             try {
226                 generator = getInstance(arg.getCodeGeneratorClass(), BasicCodeGenerator.class);
227             } catch (ReflectiveOperationException e) {
228                 throw new MojoExecutionException("Failed to instantiate code generator "
229                         + arg.getCodeGeneratorClass(), e);
230             }
231
232             LOG.info("{} Code generator instantiated from {}", LOG_PREFIX, arg.getCodeGeneratorClass());
233             generators.add(new SimpleImmutableEntry<>(arg, generator));
234         }
235
236         return generators;
237     }
238
239     @SuppressWarnings("checkstyle:illegalCatch")
240     private Optional<ProcessorModuleReactor> createReactor(final StatementParserMode parserMode,
241             final List<File> yangFilesInProject) throws MojoExecutionException {
242         LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
243
244         try {
245             final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
246             final Collection<ScannedDependency> dependencies;
247             if (inspectDependencies) {
248                 dependencies = new ArrayList<>();
249                 final Stopwatch watch = Stopwatch.createStarted();
250                 ScannedDependency.scanDependencies(project).forEach(dep -> {
251                     allFiles.add(dep.file());
252                     dependencies.add(dep);
253                 });
254                 LOG.info("{} Found {} dependencies in {}", LOG_PREFIX, dependencies.size(), watch);
255             } else {
256                 dependencies = ImmutableList.of();
257             }
258
259             /*
260              * Check if any of the listed files changed. If no changes occurred,
261              * simply return null, which indicates and of execution.
262              */
263             final Stopwatch watch = Stopwatch.createStarted();
264             if (!allFiles.stream().anyMatch(buildContext::hasDelta)) {
265                 LOG.info("{} None of {} input files changed", LOG_PREFIX, allFiles.size());
266                 return Optional.empty();
267             }
268
269             final YangParser parser = parserFactory.createParser(parserMode);
270             final List<YangTextSchemaSource> sourcesInProject = new ArrayList<>(yangFilesInProject.size());
271
272             final List<Entry<YangTextSchemaSource, ASTSchemaSource>> parsed = yangFilesInProject.parallelStream()
273                     .map(file -> {
274                         final YangTextSchemaSource textSource = YangTextSchemaSource.forFile(file);
275                         try {
276                             return new SimpleImmutableEntry<>(textSource,
277                                     TextToASTTransformer.transformText(textSource));
278                         } catch (YangSyntaxErrorException | SchemaSourceException | IOException e) {
279                             throw new IllegalArgumentException("Failed to parse " + file, e);
280                         }
281                     })
282                     .collect(Collectors.toList());
283
284             for (final Entry<YangTextSchemaSource, ASTSchemaSource> entry : parsed) {
285                 final YangTextSchemaSource textSource = entry.getKey();
286                 final ASTSchemaSource astSource = entry.getValue();
287                 parser.addSource(astSource);
288
289                 if (!astSource.getIdentifier().equals(textSource.getIdentifier())) {
290                     // AST indicates a different source identifier, make sure we use that
291                     sourcesInProject.add(YangTextSchemaSource.delegateForByteSource(astSource.getIdentifier(),
292                         textSource));
293                 } else {
294                     sourcesInProject.add(textSource);
295                 }
296             }
297
298             LOG.debug("Found project files: {}", yangFilesInProject);
299             LOG.info("{} Project model files found: {} in {}", LOG_PREFIX, yangFilesInProject.size(), watch);
300
301             final ProcessorModuleReactor reactor = new ProcessorModuleReactor(parser, sourcesInProject, dependencies);
302             LOG.debug("Initialized reactor {} with {}", reactor, yangFilesInProject);
303             return Optional.of(reactor);
304         } catch (IOException | YangSyntaxErrorException | RuntimeException e) {
305             // MojoExecutionException is thrown since execution cannot continue
306             LOG.error("{} Unable to parse YANG files from {}", LOG_PREFIX, yangFilesRootDir, e);
307             Throwable rootCause = Throwables.getRootCause(e);
308             throw new MojoExecutionException(LOG_PREFIX + " Unable to parse YANG files from " + yangFilesRootDir,
309                 rootCause);
310         }
311     }
312
313     private static List<File> listFiles(final File root, final Collection<File> excludedFiles)
314             throws IOException {
315         if (!root.isDirectory()) {
316             LOG.warn("{} YANG source directory {} not found. No code will be generated.", LOG_PREFIX, root);
317             return ImmutableList.of();
318         }
319
320         return Files.walk(root.toPath()).map(Path::toFile).filter(File::isFile).filter(f -> {
321             if (excludedFiles.contains(f)) {
322                 LOG.info("{} YANG file excluded {}", LOG_PREFIX, f);
323                 return false;
324             }
325             return true;
326         }).filter(f -> f.getName().endsWith(YangConstants.RFC6020_YANG_FILE_EXTENSION)).collect(Collectors.toList());
327     }
328
329     /**
330      * Call generate on every generator from plugin configuration.
331      */
332     @SuppressWarnings("checkstyle:illegalCatch")
333     private void generateSources(final ContextHolder context,
334             final Collection<Entry<CodeGeneratorArg, BasicCodeGenerator>> generators) throws MojoFailureException {
335         if (generators.isEmpty()) {
336             LOG.warn("{} No code generators provided", LOG_PREFIX);
337             return;
338         }
339
340         final Map<String, String> thrown = new HashMap<>();
341         for (Entry<CodeGeneratorArg, BasicCodeGenerator> entry : generators) {
342             final String codeGeneratorClass = entry.getKey().getCodeGeneratorClass();
343
344             try {
345                 generateSourcesWithOneGenerator(context, entry.getKey(), entry.getValue());
346             } catch (Exception e) {
347                 // try other generators, exception will be thrown after
348                 LOG.error("{} Unable to generate sources with {} generator", LOG_PREFIX, codeGeneratorClass, e);
349                 thrown.put(codeGeneratorClass, e.getClass().getCanonicalName());
350             }
351         }
352
353         if (!thrown.isEmpty()) {
354             LOG.error("{} One or more code generators failed, including failed list(generatorClass=exception) {}",
355                 LOG_PREFIX, thrown);
356             throw new MojoFailureException(LOG_PREFIX
357                 + " One or more code generators failed, including failed list(generatorClass=exception) " + thrown);
358         }
359     }
360
361     /**
362      * Complete initialization of a code generator and invoke it.
363      */
364     private void generateSourcesWithOneGenerator(final ContextHolder context, final CodeGeneratorArg codeGeneratorCfg,
365             final BasicCodeGenerator codeGenerator) throws IOException {
366
367         final File outputDir = requireNonNull(codeGeneratorCfg.getOutputBaseDir(project),
368             "outputBaseDir is null. Please provide a valid outputBaseDir value in pom.xml");
369
370         project.addCompileSourceRoot(outputDir.getAbsolutePath());
371
372         LOG.info("{} Sources will be generated to {}", LOG_PREFIX, outputDir);
373         LOG.debug("{} Project root dir is {}", LOG_PREFIX, project.getBasedir());
374         LOG.debug("{} Additional configuration picked up for : {}: {}", LOG_PREFIX, codeGeneratorCfg
375                         .getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration());
376
377         if (codeGenerator instanceof BuildContextAware) {
378             ((BuildContextAware)codeGenerator).setBuildContext(buildContext);
379         }
380         if (codeGenerator instanceof MavenProjectAware) {
381             ((MavenProjectAware)codeGenerator).setMavenProject(project);
382         }
383         codeGenerator.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
384
385         File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
386         YangProvider.setResource(resourceBaseDir, project);
387         codeGenerator.setResourceBaseDir(resourceBaseDir);
388         LOG.debug("{} Folder: {} marked as resources for generator: {}", LOG_PREFIX, resourceBaseDir,
389                 codeGeneratorCfg.getCodeGeneratorClass());
390
391         if (outputDir.exists()) {
392             Files.walk(outputDir.toPath()).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
393             LOG.info("{} Succesfully deleted output directory {}", LOG_PREFIX, outputDir);
394         }
395         final Stopwatch watch = Stopwatch.createStarted();
396         Collection<File> generated = codeGenerator.generateSources(context.getContext(), outputDir,
397             context.getYangModules(), context::moduleToResourcePath);
398
399         LOG.debug("{} Sources generated by {}: {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(), generated);
400         LOG.info("{} Sources generated by {}: {} in {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(),
401                 generated == null ? 0 : generated.size(), watch);
402     }
403
404     /**
405      * Instantiate object from fully qualified class name.
406      */
407     private static <T> T getInstance(final String codeGeneratorClass, final Class<T> baseType)
408             throws ReflectiveOperationException {
409         final Class<?> clazz = Class.forName(codeGeneratorClass);
410         checkArgument(baseType.isAssignableFrom(clazz), "Code generator %s has to implement %s", clazz, baseType);
411         return baseType.cast(clazz.getConstructor().newInstance());
412     }
413 }