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