Compare existing and generated output
[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 java.util.Objects.requireNonNull;
11
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.base.Stopwatch;
14 import com.google.common.base.Throwables;
15 import com.google.common.collect.ImmutableList;
16 import com.google.common.collect.ImmutableMap;
17 import com.google.common.collect.ImmutableSet;
18 import com.google.common.collect.Maps;
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.ArrayList;
24 import java.util.Collection;
25 import java.util.LinkedHashMap;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Map.Entry;
29 import java.util.NoSuchElementException;
30 import java.util.ServiceLoader;
31 import java.util.Set;
32 import java.util.function.Function;
33 import java.util.stream.Collectors;
34 import java.util.stream.Stream;
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.YangParserConfiguration;
45 import org.opendaylight.yangtools.yang.parser.api.YangParserException;
46 import org.opendaylight.yangtools.yang.parser.api.YangParserFactory;
47 import org.opendaylight.yangtools.yang.parser.api.YangSyntaxErrorException;
48 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToIRTransformer;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51 import org.sonatype.plexus.build.incremental.BuildContext;
52 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
53
54 class YangToSourcesProcessor {
55     private static final Logger LOG = LoggerFactory.getLogger(YangToSourcesProcessor.class);
56     private static final YangParserFactory DEFAULT_PARSER_FACTORY;
57
58     static {
59         try {
60             DEFAULT_PARSER_FACTORY = ServiceLoader.load(YangParserFactory.class).iterator().next();
61         } catch (NoSuchElementException e) {
62             throw new IllegalStateException("Failed to find a YangParserFactory implementation", e);
63         }
64     }
65
66     private static final String META_INF_STR = "META-INF";
67     private static final String YANG_STR = "yang";
68
69     static final String LOG_PREFIX = "yang-to-sources:";
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 static final YangProvider YANG_PROVIDER = (project, modelsInProject) -> {
75         final var generatedYangDir =
76             // FIXME: why are we generating these in "generated-sources"? At the end of the day YANG files are more
77             //        resources (except we do not them to be subject to filtering)
78             new File(new File(project.getBuild().getDirectory(), "generated-sources"), "yang");
79         LOG.debug("Generated dir {}", generatedYangDir);
80
81         // copy project's src/main/yang/*.yang to ${project.builddir}/generated-sources/yang/META-INF/yang/
82         // This honors setups like a Eclipse-profile derived one
83         final var withMetaInf = new File(generatedYangDir, YangToSourcesProcessor.META_INF_YANG_STRING);
84         final var stateListBuilder = ImmutableList.<FileState>builderWithExpectedSize(modelsInProject.size());
85
86         for (var source : modelsInProject) {
87             final File file = new File(withMetaInf, source.getIdentifier().toYangFilename());
88             // FIXME: ditch this use
89             com.google.common.io.Files.createParentDirs(file);
90
91             stateListBuilder.add(FileState.ofWrittenFile(file, source::copyTo));
92             LOG.debug("Created file {} for {}", file, source.getIdentifier());
93         }
94
95         ProjectFileAccess.addResourceDir(project, generatedYangDir);
96         LOG.debug("{} YANG files marked as resources: {}", YangToSourcesProcessor.LOG_PREFIX, generatedYangDir);
97
98         return stateListBuilder.build();
99     };
100
101     private final YangParserFactory parserFactory;
102     private final File yangFilesRootDir;
103     private final Set<File> excludedFiles;
104     private final ImmutableMap<String, FileGeneratorArg> fileGeneratorArgs;
105     private final @NonNull MavenProject project;
106     private final boolean inspectDependencies;
107     private final BuildContext buildContext;
108     private final YangProvider yangProvider;
109     private final StateStorage stateStorage;
110
111     private YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
112             final Collection<File> excludedFiles, final List<FileGeneratorArg> fileGeneratorsArgs,
113             final MavenProject project, final boolean inspectDependencies, final YangProvider yangProvider) {
114         this.buildContext = requireNonNull(buildContext, "buildContext");
115         this.yangFilesRootDir = requireNonNull(yangFilesRootDir, "yangFilesRootDir");
116         this.excludedFiles = ImmutableSet.copyOf(excludedFiles);
117         //FIXME multiple FileGeneratorArg entries of same identifier became one here
118         fileGeneratorArgs = Maps.uniqueIndex(fileGeneratorsArgs, FileGeneratorArg::getIdentifier);
119         this.project = requireNonNull(project);
120         this.inspectDependencies = inspectDependencies;
121         this.yangProvider = requireNonNull(yangProvider);
122         stateStorage = StateStorage.of(buildContext, stateFilePath(project.getBuild().getDirectory()));
123         parserFactory = DEFAULT_PARSER_FACTORY;
124     }
125
126     @VisibleForTesting
127     YangToSourcesProcessor(final File yangFilesRootDir, final List<FileGeneratorArg> fileGenerators,
128             final MavenProject project, final YangProvider yangProvider) {
129         this(new DefaultBuildContext(), yangFilesRootDir, List.of(), List.of(), project, false, yangProvider);
130     }
131
132     YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
133             final Collection<File> excludedFiles, final List<FileGeneratorArg> fileGenerators,
134             final MavenProject project, final boolean inspectDependencies) {
135         this(buildContext, yangFilesRootDir, excludedFiles, fileGenerators, project, inspectDependencies,
136             YANG_PROVIDER);
137     }
138
139     void execute() throws MojoExecutionException, MojoFailureException {
140         final YangToSourcesState prevState;
141         try {
142             prevState = stateStorage.loadState();
143         } catch (IOException e) {
144             throw new MojoFailureException("Failed to restore execution state", e);
145         }
146         if (prevState == null) {
147             LOG.debug("{} no previous execution state present", LOG_PREFIX);
148         }
149
150         // Collect all files in the current project.
151         final List<File> yangFilesInProject;
152         try {
153             yangFilesInProject = listFiles(yangFilesRootDir, excludedFiles);
154         } catch (IOException e) {
155             throw new MojoFailureException("Failed to list project files", e);
156         }
157
158         if (yangFilesInProject.isEmpty()) {
159             // No files to process, skip.
160             LOG.info("{} No input files found", LOG_PREFIX);
161             return;
162         }
163
164         // We need to instantiate all code generators to determine required import resolution mode
165         final List<GeneratorTask> codeGenerators = instantiateGenerators();
166         if (codeGenerators.isEmpty()) {
167             LOG.warn("{} No code generators provided", LOG_PREFIX);
168             return;
169         }
170
171         final Set<YangParserConfiguration> parserConfigs = codeGenerators.stream()
172             .map(GeneratorTask::parserConfig)
173             .collect(Collectors.toUnmodifiableSet());
174
175         LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
176
177         // All files which affect YANG context. This minimally includes all files in the current project, but optionally
178         // may include any YANG files in the dependencies.
179         final List<ScannedDependency> dependencies;
180         if (inspectDependencies) {
181             final Stopwatch watch = Stopwatch.createStarted();
182             try {
183                 dependencies = ScannedDependency.scanDependencies(project);
184             } catch (IOException e) {
185                 LOG.error("{} Failed to scan dependencies", LOG_PREFIX, e);
186                 throw new MojoExecutionException(LOG_PREFIX + " Failed to scan dependencies ", e);
187             }
188             LOG.info("{} Found {} dependencies in {}", LOG_PREFIX, dependencies.size(), watch);
189         } else {
190             dependencies = List.of();
191         }
192
193         /*
194          * Check if any of the listed files changed. If no changes occurred, simply return empty, which indicates
195          * end of execution.
196          */
197         // FIXME: YANGTOOLS-745: remove this check FileStates instead
198         if (!Stream.concat(yangFilesInProject.stream(), dependencies.stream().map(ScannedDependency::file))
199                 .anyMatch(buildContext::hasDelta)) {
200             LOG.info("{} None of {} input files changed", LOG_PREFIX, yangFilesInProject.size() + dependencies.size());
201             return;
202         }
203
204         final Stopwatch watch = Stopwatch.createStarted();
205         // Determine hash/size of YANG input files in parallel
206         final var projectYangs = new FileStateSet(yangFilesInProject.parallelStream()
207             .map(file -> {
208                 try {
209                     return FileState.ofFile(file);
210                 } catch (IOException e) {
211                     throw new IllegalStateException("Failed to read " + file, e);
212                 }
213             })
214             .collect(ImmutableMap.toImmutableMap(FileState::path, Function.identity())));
215
216         final List<Entry<YangTextSchemaSource, YangIRSchemaSource>> parsed = yangFilesInProject.parallelStream()
217             .map(file -> {
218                 final YangTextSchemaSource textSource = YangTextSchemaSource.forPath(file.toPath());
219                 try {
220                     return Map.entry(textSource, TextToIRTransformer.transformText(textSource));
221                 } catch (YangSyntaxErrorException | IOException e) {
222                     throw new IllegalArgumentException("Failed to parse " + file, e);
223                 }
224             })
225             .collect(Collectors.toList());
226         LOG.debug("Found project files: {}", yangFilesInProject);
227         LOG.info("{} Project model files found: {} in {}", LOG_PREFIX, yangFilesInProject.size(), watch);
228
229         // Determine hash/size of dependency files
230         // TODO: this produces false positives for Jar files -- there we want to capture the contents of the YANG files,
231         //       not the entire file
232         final var dependencyYangs = new FileStateSet(dependencies.parallelStream()
233             .map(ScannedDependency::file)
234             .map(file -> {
235                 try {
236                     return FileState.ofFile(file);
237                 } catch (IOException e) {
238                     throw new IllegalStateException("Failed to read " + file, e);
239                 }
240             })
241             .collect(ImmutableMap.toImmutableMap(FileState::path, Function.identity())));
242
243         final var outputFiles = ImmutableList.<FileState>builder();
244         boolean sourcesPersisted = false;
245
246         for (YangParserConfiguration parserConfig : parserConfigs) {
247             final var moduleReactor = createReactor(yangFilesInProject, parserConfig, dependencies, parsed);
248             final var yangSw = Stopwatch.createStarted();
249
250             final ContextHolder holder;
251             try {
252                 holder = moduleReactor.toContext();
253             } catch (YangParserException e) {
254                 throw new MojoFailureException("Failed to process reactor " + moduleReactor, e);
255             } catch (IOException e) {
256                 throw new MojoExecutionException("Failed to read reactor " + moduleReactor, e);
257             }
258
259             LOG.info("{} {} YANG models processed in {}", LOG_PREFIX, holder.getContext().getModules().size(), yangSw);
260
261             for (var factory : codeGenerators) {
262                 if (!parserConfig.equals(factory.parserConfig())) {
263                     continue;
264                 }
265
266                 final var genSw = Stopwatch.createStarted();
267                 final List<FileState> files;
268                 try {
269                     files = factory.execute(project, buildContext, holder);
270                 } catch (FileGeneratorException | IOException e) {
271                     throw new MojoFailureException(LOG_PREFIX + " Generator " + factory + " failed", e);
272                 }
273
274                 outputFiles.addAll(files);
275                 LOG.info("{} Sources generated by {}: {} in {}", LOG_PREFIX, factory.generatorName(), files.size(),
276                     genSw);
277             }
278
279             if (!sourcesPersisted) {
280                 // add META_INF/yang once
281                 final var models = moduleReactor.getModelsInProject();
282                 final Collection<FileState> sourceFileStates;
283                 try {
284                     sourceFileStates = yangProvider.addYangsToMetaInf(project, models);
285                 } catch (IOException e) {
286                     throw new MojoExecutionException("Failed write model files for " + models, e);
287                 }
288
289                 sourcesPersisted = true;
290                 outputFiles.addAll(sourceFileStates);
291             }
292         }
293
294         // add META_INF/services
295         File generatedServicesDir = new File(new File(project.getBuild().getDirectory(), "generated-sources"), "spi");
296         ProjectFileAccess.addResourceDir(project, generatedServicesDir);
297         LOG.debug("{} Yang services files from: {} marked as resources: {}", LOG_PREFIX, generatedServicesDir,
298             META_INF_YANG_SERVICES_STRING_JAR);
299
300         final var uniqueOutputFiles = new LinkedHashMap<String, FileState>();
301         for (var fileHash : outputFiles.build()) {
302             final var prev = uniqueOutputFiles.putIfAbsent(fileHash.path(), fileHash);
303             if (prev != null) {
304                 throw new MojoFailureException("Duplicate files " + prev + " and " + fileHash);
305             }
306         }
307
308         final var outputState = new YangToSourcesState(
309             codeGenerators.stream()
310                 .collect(ImmutableMap.toImmutableMap(GeneratorTask::getIdentifier, GeneratorTask::arg)),
311             projectYangs, dependencyYangs, new FileStateSet(ImmutableMap.copyOf(uniqueOutputFiles)));
312
313         try {
314             stateStorage.storeState(outputState);
315         } catch (IOException e) {
316             throw new MojoFailureException("Failed to store execution state", e);
317         }
318     }
319
320     private List<GeneratorTask> instantiateGenerators() throws MojoExecutionException {
321         // Search for available FileGenerator implementations
322         final Map<String, FileGeneratorFactory> factories = Maps.uniqueIndex(
323             ServiceLoader.load(FileGeneratorFactory.class), FileGeneratorFactory::getIdentifier);
324
325         // FIXME: iterate over fileGeneratorArg instances (configuration), not factories (environment)
326         // Assign instantiate FileGenerators with appropriate configuration
327         final var generators = new ArrayList<GeneratorTask>(factories.size());
328         for (Entry<String, FileGeneratorFactory> entry : factories.entrySet()) {
329             final String id = entry.getKey();
330             FileGeneratorArg arg = fileGeneratorArgs.get(id);
331             if (arg == null) {
332                 LOG.debug("{} No configuration for {}, using empty", LOG_PREFIX, id);
333                 arg = new FileGeneratorArg(id);
334             }
335
336             final GeneratorTask task;
337             try {
338                 task = new GeneratorTask(entry.getValue(), arg);
339             } catch (FileGeneratorException e) {
340                 throw new MojoExecutionException("File generator " + id + " failed", e);
341             }
342             generators.add(task);
343             LOG.info("{} Code generator {} instantiated", LOG_PREFIX, id);
344         }
345
346         // Notify if no factory found for defined identifiers
347         fileGeneratorArgs.keySet().forEach(
348             fileGenIdentifier -> {
349                 if (!factories.containsKey(fileGenIdentifier)) {
350                     LOG.warn("{} No generator found for identifier {}", LOG_PREFIX, fileGenIdentifier);
351                 }
352             }
353         );
354
355         return generators;
356     }
357
358     @SuppressWarnings("checkstyle:illegalCatch")
359     private @NonNull ProcessorModuleReactor createReactor(final List<File> yangFilesInProject,
360             final YangParserConfiguration parserConfig, final Collection<ScannedDependency> dependencies,
361             final List<Entry<YangTextSchemaSource, YangIRSchemaSource>> parsed) throws MojoExecutionException {
362
363         try {
364             final var sourcesInProject = new ArrayList<YangTextSchemaSource>(yangFilesInProject.size());
365             final var parser = parserFactory.createParser(parserConfig);
366             for (var entry : parsed) {
367                 final var textSource = entry.getKey();
368                 final var astSource = entry.getValue();
369                 parser.addSource(astSource);
370
371                 if (!astSource.getIdentifier().equals(textSource.getIdentifier())) {
372                     // AST indicates a different source identifier, make sure we use that
373                     sourcesInProject.add(YangTextSchemaSource.delegateForByteSource(astSource.getIdentifier(),
374                         textSource));
375                 } else {
376                     sourcesInProject.add(textSource);
377                 }
378             }
379
380             final var moduleReactor = new ProcessorModuleReactor(parser, sourcesInProject, dependencies);
381             LOG.debug("Initialized reactor {} with {}", moduleReactor, yangFilesInProject);
382             return moduleReactor;
383         } catch (IOException | YangSyntaxErrorException | RuntimeException e) {
384             // MojoExecutionException is thrown since execution cannot continue
385             LOG.error("{} Unable to parse YANG files from {}", LOG_PREFIX, yangFilesRootDir, e);
386             throw new MojoExecutionException(LOG_PREFIX + " Unable to parse YANG files from " + yangFilesRootDir,
387                 Throwables.getRootCause(e));
388         }
389     }
390
391     private static ImmutableList<File> listFiles(final File root, final Collection<File> excludedFiles)
392             throws IOException {
393         if (!root.isDirectory()) {
394             LOG.warn("{} YANG source directory {} not found. No code will be generated.", LOG_PREFIX, root);
395             return ImmutableList.of();
396         }
397
398         return Files.walk(root.toPath())
399             .map(Path::toFile)
400             .filter(File::isFile)
401             .filter(f -> {
402                 if (excludedFiles.contains(f)) {
403                     LOG.info("{} YANG file excluded {}", LOG_PREFIX, f);
404                     return false;
405                 }
406                 return true;
407             })
408             .filter(f -> f.getName().endsWith(YangConstants.RFC6020_YANG_FILE_EXTENSION))
409             .collect(ImmutableList.toImmutableList());
410     }
411
412     @VisibleForTesting
413     static @NonNull Path stateFilePath(final String projectBuildDirectory) {
414         // ${project.build.directory}/maven-status/yang-maven-plugin/execution.state
415         return Path.of(projectBuildDirectory, "maven-status", "yang-maven-plugin", "execution.state");
416     }
417 }