Split out YangIRSchemaSource
[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.ImmutableSet;
18 import com.google.common.collect.ImmutableSet.Builder;
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.List;
28 import java.util.Map;
29 import java.util.Map.Entry;
30 import java.util.Optional;
31 import java.util.ServiceLoader;
32 import java.util.Set;
33 import java.util.stream.Collectors;
34 import org.apache.maven.plugin.MojoExecutionException;
35 import org.apache.maven.plugin.MojoFailureException;
36 import org.apache.maven.project.MavenProject;
37 import org.opendaylight.yangtools.plugin.generator.api.FileGeneratorException;
38 import org.opendaylight.yangtools.plugin.generator.api.FileGeneratorFactory;
39 import org.opendaylight.yangtools.yang.common.YangConstants;
40 import org.opendaylight.yangtools.yang.model.repo.api.YangIRSchemaSource;
41 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
42 import org.opendaylight.yangtools.yang.parser.api.YangParser;
43 import org.opendaylight.yangtools.yang.parser.api.YangParserConfiguration;
44 import org.opendaylight.yangtools.yang.parser.api.YangParserException;
45 import org.opendaylight.yangtools.yang.parser.api.YangParserFactory;
46 import org.opendaylight.yangtools.yang.parser.api.YangSyntaxErrorException;
47 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToIRTransformer;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import org.sonatype.plexus.build.incremental.BuildContext;
51 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
52
53 class YangToSourcesProcessor {
54     private static final Logger LOG = LoggerFactory.getLogger(YangToSourcesProcessor.class);
55     private static final YangParserFactory DEFAULT_PARSER_FACTORY;
56
57     static {
58         final Iterator<YangParserFactory> it = ServiceLoader.load(YangParserFactory.class).iterator();
59         checkState(it.hasNext(), "Failed to find a YangParserFactory implementation");
60         DEFAULT_PARSER_FACTORY = it.next();
61     }
62
63     static final String LOG_PREFIX = "yang-to-sources:";
64     private static final String META_INF_STR = "META-INF";
65     private static final String YANG_STR = "yang";
66
67     static final String META_INF_YANG_STRING = META_INF_STR + File.separator + YANG_STR;
68     static final String META_INF_YANG_STRING_JAR = META_INF_STR + "/" + YANG_STR;
69     static final String META_INF_YANG_SERVICES_STRING_JAR = META_INF_STR + "/" + "services";
70
71     private final YangParserFactory parserFactory;
72     private final File yangFilesRootDir;
73     private final Set<File> excludedFiles;
74     private final Map<String, FileGeneratorArg> fileGeneratorArgs;
75     private final MavenProject project;
76     private final boolean inspectDependencies;
77     private final BuildContext buildContext;
78     private final YangProvider yangProvider;
79
80     private YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
81             final Collection<File> excludedFiles, final List<FileGeneratorArg> fileGeneratorsArgs,
82             final MavenProject project, final boolean inspectDependencies, final YangProvider yangProvider) {
83         this.buildContext = requireNonNull(buildContext, "buildContext");
84         this.yangFilesRootDir = requireNonNull(yangFilesRootDir, "yangFilesRootDir");
85         this.excludedFiles = ImmutableSet.copyOf(excludedFiles);
86         //FIXME multiple FileGeneratorArg entries of same identifier became one here
87         fileGeneratorArgs = Maps.uniqueIndex(fileGeneratorsArgs, FileGeneratorArg::getIdentifier);
88         this.project = requireNonNull(project);
89         this.inspectDependencies = inspectDependencies;
90         this.yangProvider = requireNonNull(yangProvider);
91         parserFactory = DEFAULT_PARSER_FACTORY;
92     }
93
94     @VisibleForTesting
95     YangToSourcesProcessor(final File yangFilesRootDir, final Collection<File> excludedFiles,
96             final List<FileGeneratorArg> fileGenerators, final MavenProject project, final boolean inspectDependencies,
97             final YangProvider yangProvider) {
98         this(new DefaultBuildContext(), yangFilesRootDir, excludedFiles, ImmutableList.of(),
99             project, inspectDependencies, yangProvider);
100     }
101
102     YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
103             final Collection<File> excludedFiles, final List<FileGeneratorArg> fileGenerators,
104             final MavenProject project, final boolean inspectDependencies) {
105         this(buildContext, yangFilesRootDir, excludedFiles, fileGenerators, project, inspectDependencies,
106             YangProvider.getInstance());
107     }
108
109     public void execute() throws MojoExecutionException, MojoFailureException {
110         conditionalExecute(false);
111     }
112
113     void conditionalExecute(final boolean skip) throws MojoExecutionException, MojoFailureException {
114         /*
115          * Collect all files which affect YANG context. This includes all
116          * files in current project and optionally any jars/files in the
117          * dependencies.
118          */
119         final List<File> yangFilesInProject;
120         try {
121             yangFilesInProject = listFiles(yangFilesRootDir, excludedFiles);
122         } catch (IOException e) {
123             throw new MojoFailureException("Failed to list project files", e);
124         }
125
126         if (yangFilesInProject.isEmpty()) {
127             // No files to process, skip.
128             LOG.info("{} No input files found", LOG_PREFIX);
129             return;
130         }
131
132         // We need to instantiate all code generators to determine required import resolution mode
133         final List<GeneratorTaskFactory> codeGenerators = instantiateGenerators();
134         if (codeGenerators.isEmpty()) {
135             LOG.warn("{} No code generators provided", LOG_PREFIX);
136             return;
137         }
138
139         final Set<YangParserConfiguration> parserConfigs = codeGenerators.stream()
140             .map(GeneratorTaskFactory::parserConfig)
141             .collect(Collectors.toUnmodifiableSet());
142
143         LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
144
145         final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
146         final Collection<ScannedDependency> dependencies;
147         if (inspectDependencies) {
148             dependencies = new ArrayList<>();
149             final Stopwatch watch = Stopwatch.createStarted();
150
151             try {
152                 ScannedDependency.scanDependencies(project).forEach(dep -> {
153                     allFiles.add(dep.file());
154                     dependencies.add(dep);
155                 });
156             } catch (IOException e) {
157                 LOG.error("{} Failed to scan dependencies", LOG_PREFIX, e);
158                 throw new MojoExecutionException(LOG_PREFIX + " Failed to scan dependencies ", e);
159             }
160             LOG.info("{} Found {} dependencies in {}", LOG_PREFIX, dependencies.size(), watch);
161         } else {
162             dependencies = ImmutableList.of();
163         }
164
165         /*
166          * Check if any of the listed files changed. If no changes occurred, simply return empty, which indicates
167          * end of execution.
168          */
169         if (!allFiles.stream().anyMatch(buildContext::hasDelta)) {
170             LOG.info("{} None of {} input files changed", LOG_PREFIX, allFiles.size());
171             return;
172         }
173
174         final Stopwatch watch = Stopwatch.createStarted();
175         final List<Entry<YangTextSchemaSource, YangIRSchemaSource>> parsed = yangFilesInProject.parallelStream()
176             .map(file -> {
177                 final YangTextSchemaSource textSource = YangTextSchemaSource.forPath(file.toPath());
178                 try {
179                     return Map.entry(textSource, TextToIRTransformer.transformText(textSource));
180                 } catch (YangSyntaxErrorException | IOException e) {
181                     throw new IllegalArgumentException("Failed to parse " + file, e);
182                 }
183             })
184             .collect(Collectors.toList());
185         LOG.debug("Found project files: {}", yangFilesInProject);
186         LOG.info("{} Project model files found: {} in {}", LOG_PREFIX, yangFilesInProject.size(), watch);
187
188         // FIXME: store these files into state, so that we can verify/clean up
189         final Builder<File> files = ImmutableSet.builder();
190         for (YangParserConfiguration parserConfig : parserConfigs) {
191             final Optional<ProcessorModuleReactor> optReactor = createReactor(yangFilesInProject,
192                 parserConfig, dependencies, parsed);
193             if (optReactor.isPresent()) {
194                 final ProcessorModuleReactor reactor = optReactor.orElseThrow();
195
196                 if (!skip) {
197                     final Stopwatch sw = Stopwatch.createStarted();
198                     final ContextHolder holder;
199
200                     try {
201                         holder = reactor.toContext();
202                     } catch (YangParserException e) {
203                         throw new MojoFailureException("Failed to process reactor " + reactor, e);
204                     } catch (IOException e) {
205                         throw new MojoExecutionException("Failed to read reactor " + reactor, e);
206                     }
207
208                     LOG.info("{} {} YANG models processed in {}", LOG_PREFIX, holder.getContext().getModules().size(),
209                         sw);
210                     files.addAll(generateSources(holder, codeGenerators, parserConfig));
211                 } else {
212                     LOG.info("{} Skipping YANG code generation because property yang.skip is true", LOG_PREFIX);
213                 }
214
215                 // FIXME: this is not right: we should be generating the models exactly once!
216                 // add META_INF/yang
217                 final Collection<YangTextSchemaSource> models = reactor.getModelsInProject();
218                 try {
219                     yangProvider.addYangsToMetaInf(project, models);
220                 } catch (IOException e) {
221                     throw new MojoExecutionException("Failed write model files for " + models, e);
222                 }
223             }
224         }
225
226         // add META_INF/services
227         File generatedServicesDir = new GeneratedDirectories(project).getYangServicesDir();
228         YangProvider.setResource(generatedServicesDir, project);
229         LOG.debug("{} Yang services files from: {} marked as resources: {}", LOG_PREFIX, generatedServicesDir,
230             META_INF_YANG_SERVICES_STRING_JAR);
231     }
232
233     private List<GeneratorTaskFactory> instantiateGenerators() throws MojoExecutionException, MojoFailureException {
234         // Search for available FileGenerator implementations
235         final Map<String, FileGeneratorFactory> factories = Maps.uniqueIndex(
236             ServiceLoader.load(FileGeneratorFactory.class), FileGeneratorFactory::getIdentifier);
237
238         // FIXME: iterate over fileGeneratorArg instances (configuration), not factories (environment)
239         // Assign instantiate FileGenerators with appropriate configuration
240         final List<GeneratorTaskFactory> generators = new ArrayList<>(factories.size());
241         for (Entry<String, FileGeneratorFactory> entry : factories.entrySet()) {
242             final String id = entry.getKey();
243             FileGeneratorArg arg = fileGeneratorArgs.get(id);
244             if (arg == null) {
245                 LOG.debug("{} No configuration for {}, using empty", LOG_PREFIX, id);
246                 arg = new FileGeneratorArg(id);
247             }
248
249             try {
250                 generators.add(FileGeneratorTaskFactory.of(entry.getValue(), arg));
251             } catch (FileGeneratorException e) {
252                 throw new MojoExecutionException("File generator " + id + " failed", e);
253             }
254             LOG.info("{} Code generator {} instantiated", LOG_PREFIX, id);
255         }
256
257         // Notify if no factory found for defined identifiers
258         fileGeneratorArgs.keySet().forEach(
259             fileGenIdentifier -> {
260                 if (!factories.containsKey(fileGenIdentifier)) {
261                     LOG.warn("{} No generator found for identifier {}", LOG_PREFIX, fileGenIdentifier);
262                 }
263             }
264         );
265
266         return generators;
267     }
268
269     @SuppressWarnings("checkstyle:illegalCatch")
270     private Optional<ProcessorModuleReactor> createReactor(final List<File> yangFilesInProject,
271             final YangParserConfiguration parserConfig, final Collection<ScannedDependency> dependencies,
272             final List<Entry<YangTextSchemaSource, YangIRSchemaSource>> parsed) throws MojoExecutionException {
273
274         try {
275             final List<YangTextSchemaSource> sourcesInProject = new ArrayList<>(yangFilesInProject.size());
276             final YangParser parser = parserFactory.createParser(parserConfig);
277             for (final Entry<YangTextSchemaSource, YangIRSchemaSource> entry : parsed) {
278                 final YangTextSchemaSource textSource = entry.getKey();
279                 final YangIRSchemaSource astSource = entry.getValue();
280                 parser.addSource(astSource);
281
282                 if (!astSource.getIdentifier().equals(textSource.getIdentifier())) {
283                     // AST indicates a different source identifier, make sure we use that
284                     sourcesInProject.add(YangTextSchemaSource.delegateForByteSource(astSource.getIdentifier(),
285                         textSource));
286                 } else {
287                     sourcesInProject.add(textSource);
288                 }
289             }
290
291             final ProcessorModuleReactor reactor = new ProcessorModuleReactor(parser, sourcesInProject, dependencies);
292             LOG.debug("Initialized reactor {} with {}", reactor, yangFilesInProject);
293             return Optional.of(reactor);
294         } catch (IOException | YangSyntaxErrorException | RuntimeException e) {
295             // MojoExecutionException is thrown since execution cannot continue
296             LOG.error("{} Unable to parse YANG files from {}", LOG_PREFIX, yangFilesRootDir, e);
297             Throwable rootCause = Throwables.getRootCause(e);
298             throw new MojoExecutionException(LOG_PREFIX + " Unable to parse YANG files from " + yangFilesRootDir,
299                 rootCause);
300         }
301     }
302
303     private static List<File> listFiles(final File root, final Collection<File> excludedFiles)
304             throws IOException {
305         if (!root.isDirectory()) {
306             LOG.warn("{} YANG source directory {} not found. No code will be generated.", LOG_PREFIX, root);
307             return ImmutableList.of();
308         }
309
310         return Files.walk(root.toPath()).map(Path::toFile).filter(File::isFile).filter(f -> {
311             if (excludedFiles.contains(f)) {
312                 LOG.info("{} YANG file excluded {}", LOG_PREFIX, f);
313                 return false;
314             }
315             return true;
316         }).filter(f -> f.getName().endsWith(YangConstants.RFC6020_YANG_FILE_EXTENSION)).collect(Collectors.toList());
317     }
318
319     /**
320      * Call generate on every generator from plugin configuration.
321      */
322     private Set<File> generateSources(final ContextHolder context, final Collection<GeneratorTaskFactory> generators,
323             final YangParserConfiguration parserConfig) throws MojoFailureException {
324         final Builder<File> allFiles = ImmutableSet.builder();
325         for (GeneratorTaskFactory factory : generators) {
326             if (!parserConfig.equals(factory.parserConfig())) {
327                 continue;
328             }
329
330             final Stopwatch sw = Stopwatch.createStarted();
331             final GeneratorTask<?> task = factory.createTask(project, context);
332             LOG.debug("{} Task {} initialized in {}", LOG_PREFIX, task, sw);
333
334             final Collection<File> files;
335             try {
336                 files = task.execute(buildContext);
337             } catch (FileGeneratorException | IOException e) {
338                 throw new MojoFailureException(LOG_PREFIX + " Generator " + factory + " failed", e);
339             }
340
341             LOG.debug("{} Sources generated by {}: {}", LOG_PREFIX, factory.generatorName(), files);
342
343             final int fileCount;
344             if (files != null) {
345                 fileCount = files.size();
346                 allFiles.addAll(files);
347             } else {
348                 fileCount = 0;
349             }
350
351             LOG.info("{} Sources generated by {}: {} in {}", LOG_PREFIX, factory.generatorName(), fileCount, sw);
352         }
353
354         return allFiles.build();
355     }
356 }