Capture effective configuration
[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.checkState;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.base.Stopwatch;
15 import com.google.common.base.Throwables;
16 import com.google.common.collect.ImmutableList;
17 import com.google.common.collect.ImmutableMap;
18 import com.google.common.collect.ImmutableSet;
19 import com.google.common.collect.Maps;
20 import java.io.File;
21 import java.io.IOException;
22 import java.nio.file.Files;
23 import java.nio.file.Path;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Iterator;
27 import java.util.LinkedHashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Map.Entry;
31 import java.util.Optional;
32 import java.util.ServiceLoader;
33 import java.util.Set;
34 import java.util.stream.Collectors;
35 import org.apache.maven.plugin.MojoExecutionException;
36 import org.apache.maven.plugin.MojoFailureException;
37 import org.apache.maven.project.MavenProject;
38 import org.eclipse.jdt.annotation.NonNull;
39 import org.opendaylight.yangtools.plugin.generator.api.FileGeneratorException;
40 import org.opendaylight.yangtools.plugin.generator.api.FileGeneratorFactory;
41 import org.opendaylight.yangtools.yang.common.YangConstants;
42 import org.opendaylight.yangtools.yang.model.repo.api.YangIRSchemaSource;
43 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
44 import org.opendaylight.yangtools.yang.parser.api.YangParser;
45 import org.opendaylight.yangtools.yang.parser.api.YangParserConfiguration;
46 import org.opendaylight.yangtools.yang.parser.api.YangParserException;
47 import org.opendaylight.yangtools.yang.parser.api.YangParserFactory;
48 import org.opendaylight.yangtools.yang.parser.api.YangSyntaxErrorException;
49 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToIRTransformer;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52 import org.sonatype.plexus.build.incremental.BuildContext;
53 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
54
55 class YangToSourcesProcessor {
56     private static final Logger LOG = LoggerFactory.getLogger(YangToSourcesProcessor.class);
57     private static final YangParserFactory DEFAULT_PARSER_FACTORY;
58
59     static {
60         final Iterator<YangParserFactory> it = ServiceLoader.load(YangParserFactory.class).iterator();
61         checkState(it.hasNext(), "Failed to find a YangParserFactory implementation");
62         DEFAULT_PARSER_FACTORY = it.next();
63     }
64
65     static final String LOG_PREFIX = "yang-to-sources:";
66     private static final String META_INF_STR = "META-INF";
67     private static final String YANG_STR = "yang";
68     private static final String BUILD_CONTEXT_STATE_NAME = YangToSourcesProcessor.class.getName();
69
70     static final String META_INF_YANG_STRING = META_INF_STR + File.separator + YANG_STR;
71     static final String META_INF_YANG_STRING_JAR = META_INF_STR + "/" + YANG_STR;
72     static final String META_INF_YANG_SERVICES_STRING_JAR = META_INF_STR + "/" + "services";
73
74     private final YangParserFactory parserFactory;
75     private final File yangFilesRootDir;
76     private final Set<File> excludedFiles;
77     private final ImmutableMap<String, FileGeneratorArg> fileGeneratorArgs;
78     private final @NonNull MavenProject project;
79     private final boolean inspectDependencies;
80     private final BuildContext buildContext;
81     private final YangProvider yangProvider;
82
83     private YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
84             final Collection<File> excludedFiles, final List<FileGeneratorArg> fileGeneratorsArgs,
85             final MavenProject project, final boolean inspectDependencies, final YangProvider yangProvider) {
86         this.buildContext = requireNonNull(buildContext, "buildContext");
87         this.yangFilesRootDir = requireNonNull(yangFilesRootDir, "yangFilesRootDir");
88         this.excludedFiles = ImmutableSet.copyOf(excludedFiles);
89         //FIXME multiple FileGeneratorArg entries of same identifier became one here
90         fileGeneratorArgs = Maps.uniqueIndex(fileGeneratorsArgs, FileGeneratorArg::getIdentifier);
91         this.project = requireNonNull(project);
92         this.inspectDependencies = inspectDependencies;
93         this.yangProvider = requireNonNull(yangProvider);
94         parserFactory = DEFAULT_PARSER_FACTORY;
95     }
96
97     @VisibleForTesting
98     YangToSourcesProcessor(final File yangFilesRootDir, final Collection<File> excludedFiles,
99             final List<FileGeneratorArg> fileGenerators, final MavenProject project, final boolean inspectDependencies,
100             final YangProvider yangProvider) {
101         this(new DefaultBuildContext(), yangFilesRootDir, excludedFiles, ImmutableList.of(),
102             project, inspectDependencies, yangProvider);
103     }
104
105     YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
106             final Collection<File> excludedFiles, final List<FileGeneratorArg> fileGenerators,
107             final MavenProject project, final boolean inspectDependencies) {
108         this(buildContext, yangFilesRootDir, excludedFiles, fileGenerators, project, inspectDependencies,
109             YangProvider.getInstance());
110     }
111
112     public void execute() throws MojoExecutionException, MojoFailureException {
113         conditionalExecute(false);
114     }
115
116     void conditionalExecute(final boolean skip) throws MojoExecutionException, MojoFailureException {
117         var prevState = buildContext.getValue(BUILD_CONTEXT_STATE_NAME);
118         if (prevState == null) {
119             LOG.debug("{} BuildContext did not provide state", LOG_PREFIX);
120             // FIXME: look for persisted state and restore it
121         }
122
123         // Collect all files in the current project.
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<GeneratorTaskFactory> codeGenerators = instantiateGenerators();
139         if (codeGenerators.isEmpty()) {
140             LOG.warn("{} No code generators provided", LOG_PREFIX);
141             return;
142         }
143
144         final Set<YangParserConfiguration> parserConfigs = codeGenerators.stream()
145             .map(GeneratorTaskFactory::parserConfig)
146             .collect(Collectors.toUnmodifiableSet());
147
148         LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
149
150         // All files which affect YANG context. This minimally includes all files in the current project, but optionally
151         // may include any YANG files in the dependencies.
152         final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
153         final Collection<ScannedDependency> dependencies;
154         if (inspectDependencies) {
155             dependencies = new ArrayList<>();
156             final Stopwatch watch = Stopwatch.createStarted();
157
158             try {
159                 ScannedDependency.scanDependencies(project).forEach(dep -> {
160                     allFiles.add(dep.file());
161                     dependencies.add(dep);
162                 });
163             } catch (IOException e) {
164                 LOG.error("{} Failed to scan dependencies", LOG_PREFIX, e);
165                 throw new MojoExecutionException(LOG_PREFIX + " Failed to scan dependencies ", e);
166             }
167             LOG.info("{} Found {} dependencies in {}", LOG_PREFIX, dependencies.size(), watch);
168         } else {
169             dependencies = ImmutableList.of();
170         }
171
172         /*
173          * Check if any of the listed files changed. If no changes occurred, simply return empty, which indicates
174          * end of execution.
175          */
176         if (!allFiles.stream().anyMatch(buildContext::hasDelta)) {
177             LOG.info("{} None of {} input files changed", LOG_PREFIX, allFiles.size());
178             return;
179         }
180
181         final Stopwatch watch = Stopwatch.createStarted();
182         final List<Entry<YangTextSchemaSource, YangIRSchemaSource>> parsed = yangFilesInProject.parallelStream()
183             .map(file -> {
184                 final YangTextSchemaSource textSource = YangTextSchemaSource.forPath(file.toPath());
185                 try {
186                     return Map.entry(textSource, TextToIRTransformer.transformText(textSource));
187                 } catch (YangSyntaxErrorException | IOException e) {
188                     throw new IllegalArgumentException("Failed to parse " + file, e);
189                 }
190             })
191             .collect(Collectors.toList());
192         LOG.debug("Found project files: {}", yangFilesInProject);
193         LOG.info("{} Project model files found: {} in {}", LOG_PREFIX, yangFilesInProject.size(), watch);
194
195         final var outputFiles = ImmutableList.<FileState>builder();
196
197         for (YangParserConfiguration parserConfig : parserConfigs) {
198             final Optional<ProcessorModuleReactor> optReactor = createReactor(yangFilesInProject,
199                 parserConfig, dependencies, parsed);
200             if (optReactor.isPresent()) {
201                 final ProcessorModuleReactor reactor = optReactor.orElseThrow();
202
203                 if (!skip) {
204                     final Stopwatch sw = Stopwatch.createStarted();
205                     final ContextHolder holder;
206
207                     try {
208                         holder = reactor.toContext();
209                     } catch (YangParserException e) {
210                         throw new MojoFailureException("Failed to process reactor " + reactor, e);
211                     } catch (IOException e) {
212                         throw new MojoExecutionException("Failed to read reactor " + reactor, e);
213                     }
214
215                     LOG.info("{} {} YANG models processed in {}", LOG_PREFIX, holder.getContext().getModules().size(),
216                         sw);
217                     outputFiles.addAll(generateSources(holder, codeGenerators, parserConfig));
218                 } else {
219                     LOG.info("{} Skipping YANG code generation because property yang.skip is true", LOG_PREFIX);
220                 }
221
222                 // FIXME: this is not right: we should be generating the models exactly once!
223                 // add META_INF/yang
224                 final Collection<YangTextSchemaSource> models = reactor.getModelsInProject();
225                 try {
226                     yangProvider.addYangsToMetaInf(project, models);
227                 } catch (IOException e) {
228                     throw new MojoExecutionException("Failed write model files for " + models, e);
229                 }
230             }
231         }
232
233         // add META_INF/services
234         File generatedServicesDir = new GeneratedDirectories(project).getYangServicesDir();
235         YangProvider.setResource(generatedServicesDir, project);
236         LOG.debug("{} Yang services files from: {} marked as resources: {}", LOG_PREFIX, generatedServicesDir,
237             META_INF_YANG_SERVICES_STRING_JAR);
238
239         final var uniqueOutputFiles = new LinkedHashMap<String, FileState>();
240         for (var fileHash : outputFiles.build()) {
241             final var prev = uniqueOutputFiles.putIfAbsent(fileHash.path(), fileHash);
242             if (prev != null) {
243                 throw new MojoFailureException("Duplicate files " + prev + " and " + fileHash);
244             }
245         }
246
247         // FIXME: store these files into state, so that we can verify/clean up
248         final var outputState = new YangToSourcesState(
249             codeGenerators.stream()
250                 .collect(ImmutableMap.toImmutableMap(GeneratorTaskFactory::getIdentifier, GeneratorTaskFactory::arg)),
251             new FileStateSet(ImmutableMap.copyOf(uniqueOutputFiles)));
252         buildContext.setValue(BUILD_CONTEXT_STATE_NAME, outputState);
253         if (buildContext.getValue(BUILD_CONTEXT_STATE_NAME) == null) {
254             LOG.debug("{} BuildContext did not retain state, persisting", LOG_PREFIX);
255             // FIXME: persist in target/ directory (there is a maven best practice where)
256         }
257     }
258
259     private List<GeneratorTaskFactory> instantiateGenerators() throws MojoExecutionException {
260         // Search for available FileGenerator implementations
261         final Map<String, FileGeneratorFactory> factories = Maps.uniqueIndex(
262             ServiceLoader.load(FileGeneratorFactory.class), FileGeneratorFactory::getIdentifier);
263
264         // FIXME: iterate over fileGeneratorArg instances (configuration), not factories (environment)
265         // Assign instantiate FileGenerators with appropriate configuration
266         final List<GeneratorTaskFactory> generators = new ArrayList<>(factories.size());
267         for (Entry<String, FileGeneratorFactory> entry : factories.entrySet()) {
268             final String id = entry.getKey();
269             FileGeneratorArg arg = fileGeneratorArgs.get(id);
270             if (arg == null) {
271                 LOG.debug("{} No configuration for {}, using empty", LOG_PREFIX, id);
272                 arg = new FileGeneratorArg(id);
273             }
274
275             try {
276                 generators.add(GeneratorTaskFactory.of(entry.getValue(), arg));
277             } catch (FileGeneratorException e) {
278                 throw new MojoExecutionException("File generator " + id + " failed", e);
279             }
280             LOG.info("{} Code generator {} instantiated", LOG_PREFIX, id);
281         }
282
283         // Notify if no factory found for defined identifiers
284         fileGeneratorArgs.keySet().forEach(
285             fileGenIdentifier -> {
286                 if (!factories.containsKey(fileGenIdentifier)) {
287                     LOG.warn("{} No generator found for identifier {}", LOG_PREFIX, fileGenIdentifier);
288                 }
289             }
290         );
291
292         return generators;
293     }
294
295     @SuppressWarnings("checkstyle:illegalCatch")
296     private Optional<ProcessorModuleReactor> createReactor(final List<File> yangFilesInProject,
297             final YangParserConfiguration parserConfig, final Collection<ScannedDependency> dependencies,
298             final List<Entry<YangTextSchemaSource, YangIRSchemaSource>> parsed) throws MojoExecutionException {
299
300         try {
301             final List<YangTextSchemaSource> sourcesInProject = new ArrayList<>(yangFilesInProject.size());
302             final YangParser parser = parserFactory.createParser(parserConfig);
303             for (final Entry<YangTextSchemaSource, YangIRSchemaSource> entry : parsed) {
304                 final YangTextSchemaSource textSource = entry.getKey();
305                 final YangIRSchemaSource astSource = entry.getValue();
306                 parser.addSource(astSource);
307
308                 if (!astSource.getIdentifier().equals(textSource.getIdentifier())) {
309                     // AST indicates a different source identifier, make sure we use that
310                     sourcesInProject.add(YangTextSchemaSource.delegateForByteSource(astSource.getIdentifier(),
311                         textSource));
312                 } else {
313                     sourcesInProject.add(textSource);
314                 }
315             }
316
317             final ProcessorModuleReactor reactor = new ProcessorModuleReactor(parser, sourcesInProject, dependencies);
318             LOG.debug("Initialized reactor {} with {}", reactor, yangFilesInProject);
319             return Optional.of(reactor);
320         } catch (IOException | YangSyntaxErrorException | RuntimeException e) {
321             // MojoExecutionException is thrown since execution cannot continue
322             LOG.error("{} Unable to parse YANG files from {}", LOG_PREFIX, yangFilesRootDir, e);
323             Throwable rootCause = Throwables.getRootCause(e);
324             throw new MojoExecutionException(LOG_PREFIX + " Unable to parse YANG files from " + yangFilesRootDir,
325                 rootCause);
326         }
327     }
328
329     private static List<File> listFiles(final File root, final Collection<File> excludedFiles)
330             throws IOException {
331         if (!root.isDirectory()) {
332             LOG.warn("{} YANG source directory {} not found. No code will be generated.", LOG_PREFIX, root);
333             return ImmutableList.of();
334         }
335
336         return Files.walk(root.toPath()).map(Path::toFile).filter(File::isFile).filter(f -> {
337             if (excludedFiles.contains(f)) {
338                 LOG.info("{} YANG file excluded {}", LOG_PREFIX, f);
339                 return false;
340             }
341             return true;
342         }).filter(f -> f.getName().endsWith(YangConstants.RFC6020_YANG_FILE_EXTENSION)).collect(Collectors.toList());
343     }
344
345     /**
346      * Call generate on every generator from plugin configuration.
347      */
348     private List<FileState> generateSources(final ContextHolder context,
349             final Collection<GeneratorTaskFactory> generators, final YangParserConfiguration parserConfig)
350                 throws MojoFailureException {
351         final var generatorToFiles = ImmutableList.<FileState>builder();
352         for (GeneratorTaskFactory factory : generators) {
353             if (!parserConfig.equals(factory.parserConfig())) {
354                 continue;
355             }
356
357             final Stopwatch sw = Stopwatch.createStarted();
358             final GeneratorTask task = factory.createTask(project, context);
359             LOG.debug("{} Task {} initialized in {}", LOG_PREFIX, task, sw);
360
361             final List<FileState> files;
362             try {
363                 files = task.execute(buildContext);
364             } catch (FileGeneratorException | IOException e) {
365                 throw new MojoFailureException(LOG_PREFIX + " Generator " + factory + " failed", e);
366             }
367
368             final String generatorName = factory.generatorName();
369             LOG.debug("{} Sources generated by {}: {}", LOG_PREFIX, generatorName, files);
370
371             final int fileCount = files.size();
372             generatorToFiles.addAll(files);
373
374             LOG.info("{} Sources generated by {}: {} in {}", LOG_PREFIX, generatorName, fileCount, sw);
375         }
376
377         return generatorToFiles.build();
378     }
379 }