Track META-INF/ files in state
[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         boolean sourcesPersisted = false;
197
198         for (YangParserConfiguration parserConfig : parserConfigs) {
199             final Optional<ProcessorModuleReactor> optReactor = createReactor(yangFilesInProject,
200                 parserConfig, dependencies, parsed);
201             if (optReactor.isPresent()) {
202                 final ProcessorModuleReactor reactor = optReactor.orElseThrow();
203
204                 if (!skip) {
205                     final Stopwatch sw = Stopwatch.createStarted();
206                     final ContextHolder holder;
207
208                     try {
209                         holder = reactor.toContext();
210                     } catch (YangParserException e) {
211                         throw new MojoFailureException("Failed to process reactor " + reactor, e);
212                     } catch (IOException e) {
213                         throw new MojoExecutionException("Failed to read reactor " + reactor, e);
214                     }
215
216                     LOG.info("{} {} YANG models processed in {}", LOG_PREFIX, holder.getContext().getModules().size(),
217                         sw);
218                     outputFiles.addAll(generateSources(holder, codeGenerators, parserConfig));
219
220                     if (!sourcesPersisted) {
221                         // add META_INF/yang once
222                         final var models = reactor.getModelsInProject();
223                         final Collection<FileState> sourceFileStates;
224                         try {
225                             sourceFileStates = yangProvider.addYangsToMetaInf(project, models);
226                         } catch (IOException e) {
227                             throw new MojoExecutionException("Failed write model files for " + models, e);
228                         }
229
230                         sourcesPersisted = true;
231                         outputFiles.addAll(sourceFileStates);
232                     }
233                 } else {
234                     LOG.info("{} Skipping YANG code generation because property yang.skip is true", LOG_PREFIX);
235                 }
236             }
237         }
238
239         // add META_INF/services
240         File generatedServicesDir = new GeneratedDirectories(project).getYangServicesDir();
241         YangProvider.setResource(generatedServicesDir, project);
242         LOG.debug("{} Yang services files from: {} marked as resources: {}", LOG_PREFIX, generatedServicesDir,
243             META_INF_YANG_SERVICES_STRING_JAR);
244
245         final var uniqueOutputFiles = new LinkedHashMap<String, FileState>();
246         for (var fileHash : outputFiles.build()) {
247             final var prev = uniqueOutputFiles.putIfAbsent(fileHash.path(), fileHash);
248             if (prev != null) {
249                 throw new MojoFailureException("Duplicate files " + prev + " and " + fileHash);
250             }
251         }
252
253         // FIXME: store these files into state, so that we can verify/clean up
254         final var outputState = new YangToSourcesState(
255             codeGenerators.stream()
256                 .collect(ImmutableMap.toImmutableMap(GeneratorTaskFactory::getIdentifier, GeneratorTaskFactory::arg)),
257             new FileStateSet(ImmutableMap.copyOf(uniqueOutputFiles)));
258         buildContext.setValue(BUILD_CONTEXT_STATE_NAME, outputState);
259         if (buildContext.getValue(BUILD_CONTEXT_STATE_NAME) == null) {
260             LOG.debug("{} BuildContext did not retain state, persisting", LOG_PREFIX);
261             // FIXME: persist in target/ directory (there is a maven best practice where)
262         }
263     }
264
265     private List<GeneratorTaskFactory> instantiateGenerators() throws MojoExecutionException {
266         // Search for available FileGenerator implementations
267         final Map<String, FileGeneratorFactory> factories = Maps.uniqueIndex(
268             ServiceLoader.load(FileGeneratorFactory.class), FileGeneratorFactory::getIdentifier);
269
270         // FIXME: iterate over fileGeneratorArg instances (configuration), not factories (environment)
271         // Assign instantiate FileGenerators with appropriate configuration
272         final List<GeneratorTaskFactory> generators = new ArrayList<>(factories.size());
273         for (Entry<String, FileGeneratorFactory> entry : factories.entrySet()) {
274             final String id = entry.getKey();
275             FileGeneratorArg arg = fileGeneratorArgs.get(id);
276             if (arg == null) {
277                 LOG.debug("{} No configuration for {}, using empty", LOG_PREFIX, id);
278                 arg = new FileGeneratorArg(id);
279             }
280
281             try {
282                 generators.add(GeneratorTaskFactory.of(entry.getValue(), arg));
283             } catch (FileGeneratorException e) {
284                 throw new MojoExecutionException("File generator " + id + " failed", e);
285             }
286             LOG.info("{} Code generator {} instantiated", LOG_PREFIX, id);
287         }
288
289         // Notify if no factory found for defined identifiers
290         fileGeneratorArgs.keySet().forEach(
291             fileGenIdentifier -> {
292                 if (!factories.containsKey(fileGenIdentifier)) {
293                     LOG.warn("{} No generator found for identifier {}", LOG_PREFIX, fileGenIdentifier);
294                 }
295             }
296         );
297
298         return generators;
299     }
300
301     @SuppressWarnings("checkstyle:illegalCatch")
302     private Optional<ProcessorModuleReactor> createReactor(final List<File> yangFilesInProject,
303             final YangParserConfiguration parserConfig, final Collection<ScannedDependency> dependencies,
304             final List<Entry<YangTextSchemaSource, YangIRSchemaSource>> parsed) throws MojoExecutionException {
305
306         try {
307             final List<YangTextSchemaSource> sourcesInProject = new ArrayList<>(yangFilesInProject.size());
308             final YangParser parser = parserFactory.createParser(parserConfig);
309             for (final Entry<YangTextSchemaSource, YangIRSchemaSource> entry : parsed) {
310                 final YangTextSchemaSource textSource = entry.getKey();
311                 final YangIRSchemaSource astSource = entry.getValue();
312                 parser.addSource(astSource);
313
314                 if (!astSource.getIdentifier().equals(textSource.getIdentifier())) {
315                     // AST indicates a different source identifier, make sure we use that
316                     sourcesInProject.add(YangTextSchemaSource.delegateForByteSource(astSource.getIdentifier(),
317                         textSource));
318                 } else {
319                     sourcesInProject.add(textSource);
320                 }
321             }
322
323             final ProcessorModuleReactor reactor = new ProcessorModuleReactor(parser, sourcesInProject, dependencies);
324             LOG.debug("Initialized reactor {} with {}", reactor, yangFilesInProject);
325             return Optional.of(reactor);
326         } catch (IOException | YangSyntaxErrorException | RuntimeException e) {
327             // MojoExecutionException is thrown since execution cannot continue
328             LOG.error("{} Unable to parse YANG files from {}", LOG_PREFIX, yangFilesRootDir, e);
329             Throwable rootCause = Throwables.getRootCause(e);
330             throw new MojoExecutionException(LOG_PREFIX + " Unable to parse YANG files from " + yangFilesRootDir,
331                 rootCause);
332         }
333     }
334
335     private static List<File> listFiles(final File root, final Collection<File> excludedFiles)
336             throws IOException {
337         if (!root.isDirectory()) {
338             LOG.warn("{} YANG source directory {} not found. No code will be generated.", LOG_PREFIX, root);
339             return ImmutableList.of();
340         }
341
342         return Files.walk(root.toPath()).map(Path::toFile).filter(File::isFile).filter(f -> {
343             if (excludedFiles.contains(f)) {
344                 LOG.info("{} YANG file excluded {}", LOG_PREFIX, f);
345                 return false;
346             }
347             return true;
348         }).filter(f -> f.getName().endsWith(YangConstants.RFC6020_YANG_FILE_EXTENSION)).collect(Collectors.toList());
349     }
350
351     /**
352      * Call generate on every generator from plugin configuration.
353      */
354     private List<FileState> generateSources(final ContextHolder context,
355             final Collection<GeneratorTaskFactory> generators, final YangParserConfiguration parserConfig)
356                 throws MojoFailureException {
357         final var generatorToFiles = ImmutableList.<FileState>builder();
358         for (GeneratorTaskFactory factory : generators) {
359             if (!parserConfig.equals(factory.parserConfig())) {
360                 continue;
361             }
362
363             final Stopwatch sw = Stopwatch.createStarted();
364             final GeneratorTask task = factory.createTask(project, context);
365             LOG.debug("{} Task {} initialized in {}", LOG_PREFIX, task, sw);
366
367             final List<FileState> files;
368             try {
369                 files = task.execute(buildContext);
370             } catch (FileGeneratorException | IOException e) {
371                 throw new MojoFailureException(LOG_PREFIX + " Generator " + factory + " failed", e);
372             }
373
374             final String generatorName = factory.generatorName();
375             LOG.debug("{} Sources generated by {}: {}", LOG_PREFIX, generatorName, files);
376
377             final int fileCount = files.size();
378             generatorToFiles.addAll(files);
379
380             LOG.info("{} Sources generated by {}: {} in {}", LOG_PREFIX, generatorName, fileCount, sw);
381         }
382
383         return generatorToFiles.build();
384     }
385 }