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