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