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