d53d06ee18cda46a2deeacf02c873782c8fc8cf0
[yangtools.git] / yang / 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.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static java.util.Objects.requireNonNull;
13
14 import com.google.common.annotations.VisibleForTesting;
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.io.CharStreams;
19 import java.io.File;
20 import java.io.IOException;
21 import java.io.Reader;
22 import java.nio.charset.StandardCharsets;
23 import java.nio.file.Files;
24 import java.nio.file.Path;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.Comparator;
28 import java.util.HashMap;
29 import java.util.Iterator;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Optional;
33 import java.util.ServiceLoader;
34 import java.util.Set;
35 import java.util.stream.Collectors;
36 import org.apache.maven.plugin.MojoExecutionException;
37 import org.apache.maven.plugin.MojoFailureException;
38 import org.apache.maven.project.MavenProject;
39 import org.opendaylight.yangtools.yang.common.YangConstants;
40 import org.opendaylight.yangtools.yang.model.parser.api.YangParser;
41 import org.opendaylight.yangtools.yang.model.parser.api.YangParserException;
42 import org.opendaylight.yangtools.yang.model.parser.api.YangParserFactory;
43 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
44 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.ASTSchemaSource;
45 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToASTTransformer;
46 import org.opendaylight.yangtools.yang2sources.plugin.ConfigArg.CodeGeneratorArg;
47 import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
48 import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
49 import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware;
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
69     static final String META_INF_YANG_STRING = META_INF_STR + File.separator + YANG_STR;
70     static final String META_INF_YANG_STRING_JAR = META_INF_STR + "/" + YANG_STR;
71     static final String META_INF_YANG_SERVICES_STRING_JAR = META_INF_STR + "/" + "services";
72
73     private final YangParserFactory parserFactory;
74     private final File yangFilesRootDir;
75     private final Set<File> excludedFiles;
76     private final List<CodeGeneratorArg> codeGenerators;
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> codeGenerators,
84             final MavenProject project, final boolean inspectDependencies, final YangProvider yangProvider) {
85         this.buildContext = requireNonNull(buildContext, "buildContext");
86         this.yangFilesRootDir = requireNonNull(yangFilesRootDir, "yangFilesRootDir");
87         this.excludedFiles = ImmutableSet.copyOf(excludedFiles);
88         this.codeGenerators = ImmutableList.copyOf(codeGenerators);
89         this.project = requireNonNull(project);
90         this.inspectDependencies = inspectDependencies;
91         this.yangProvider = requireNonNull(yangProvider);
92         this.parserFactory = DEFAULT_PARSER_FACTORY;
93     }
94
95     @VisibleForTesting
96     YangToSourcesProcessor(final File yangFilesRootDir, final Collection<File> excludedFiles,
97             final List<CodeGeneratorArg> codeGenerators, final MavenProject project, final boolean inspectDependencies,
98             final YangProvider yangProvider) {
99         this(new DefaultBuildContext(), yangFilesRootDir, excludedFiles, codeGenerators, project,
100                 inspectDependencies, yangProvider);
101     }
102
103     YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
104                 final Collection<File> excludedFiles, final List<CodeGeneratorArg> codeGenerators,
105                 final MavenProject project, final boolean inspectDependencies) {
106         this(yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, 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         final Optional<ProcessorModuleReactor> optReactor = createReactor();
115         if (!optReactor.isPresent()) {
116             return;
117         }
118
119         final ProcessorModuleReactor reactor = optReactor.get();
120         if (!skip) {
121             final ContextHolder holder;
122
123             try {
124                 holder = createContextHolder(reactor);
125             } catch (YangParserException e) {
126                 throw new MojoFailureException("Failed to process reactor " + reactor, e);
127             } catch (IOException e) {
128                 throw new MojoExecutionException("Failed to read reactor " + reactor, e);
129             }
130
131             generateSources(holder);
132         } else {
133             LOG.info("Skipping YANG code generation because property yang.skip is true");
134         }
135
136         // add META_INF/yang
137         final Collection<YangTextSchemaSource> models = reactor.getModelsInProject();
138         try {
139             yangProvider.addYangsToMetaInf(project, models);
140         } catch (IOException e) {
141             throw new MojoExecutionException("Failed write model files for " + models, e);
142         }
143
144         // add META_INF/services
145         File generatedServicesDir = new GeneratedDirectories(project).getYangServicesDir();
146         YangProvider.setResource(generatedServicesDir, project);
147         LOG.debug("{} Yang services files from: {} marked as resources: {}", LOG_PREFIX, generatedServicesDir,
148             META_INF_YANG_SERVICES_STRING_JAR);
149     }
150
151     @SuppressWarnings("checkstyle:illegalCatch")
152     private Optional<ProcessorModuleReactor> createReactor() throws MojoExecutionException {
153         LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
154         try {
155             /*
156              * Collect all files which affect YANG context. This includes all
157              * files in current project and optionally any jars/files in the
158              * dependencies.
159              */
160             final Collection<File> yangFilesInProject = listFiles(yangFilesRootDir, excludedFiles);
161
162             final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
163             if (inspectDependencies) {
164                 allFiles.addAll(Util.findYangFilesInDependencies(project));
165             }
166
167             if (allFiles.isEmpty()) {
168                 LOG.info("{} No input files found", LOG_PREFIX);
169                 return Optional.empty();
170             }
171
172             /*
173              * Check if any of the listed files changed. If no changes occurred,
174              * simply return null, which indicates and of execution.
175              */
176             if (!allFiles.stream().anyMatch(buildContext::hasDelta)) {
177                 LOG.info("{} None of {} input files changed", LOG_PREFIX, allFiles.size());
178                 return Optional.empty();
179             }
180
181             // FIXME: add correct mode
182             final YangParser parser = parserFactory.createParser();
183             final List<YangTextSchemaSource> sourcesInProject = new ArrayList<>(yangFilesInProject.size());
184             for (final File f : yangFilesInProject) {
185                 final YangTextSchemaSource textSource = YangTextSchemaSource.forFile(f);
186                 final ASTSchemaSource astSource = TextToASTTransformer.transformText(textSource);
187
188                 parser.addSource(astSource);
189
190                 if (!astSource.getIdentifier().equals(textSource.getIdentifier())) {
191                     // AST indicates a different source identifier, make sure we use that
192                     sourcesInProject.add(YangTextSchemaSource.delegateForByteSource(astSource.getIdentifier(),
193                         textSource));
194                 } else {
195                     sourcesInProject.add(textSource);
196                 }
197             }
198
199             LOG.debug("Processed project files: {}", yangFilesInProject);
200             LOG.info("{} Project model files parsed: {}", LOG_PREFIX, yangFilesInProject.size());
201
202             final ProcessorModuleReactor reactor = new ProcessorModuleReactor(parser, sourcesInProject);
203             LOG.debug("Initialized reactor {}", reactor, yangFilesInProject);
204             return Optional.of(reactor);
205         } catch (Exception e) {
206             // MojoExecutionException is thrown since execution cannot continue
207             LOG.error("{} Unable to parse YANG files from {}", LOG_PREFIX, yangFilesRootDir, e);
208             Throwable rootCause = Throwables.getRootCause(e);
209             throw new MojoExecutionException(LOG_PREFIX + " Unable to parse YANG files from " + yangFilesRootDir,
210                 rootCause);
211         }
212     }
213
214     private ContextHolder createContextHolder(final ProcessorModuleReactor reactor) throws MojoFailureException,
215             IOException, YangParserException {
216         /**
217          * Set contains all modules generated from input sources. Number of
218          * modules may differ from number of sources due to submodules
219          * (parsed submodule's data are added to its parent module). Set
220          * cannot contains null values.
221          */
222         if (inspectDependencies) {
223             final List<YangTextSchemaSource> sourcesInDependencies = Util.findYangFilesInDependenciesAsStream(
224                 project);
225             for (YangTextSchemaSource s : toUniqueSources(sourcesInDependencies)) {
226                 reactor.registerSourceFromDependency(s);
227             }
228         }
229
230         return reactor.toContext();
231     }
232
233     private static Collection<File> listFiles(final File root, final Collection<File> excludedFiles)
234             throws IOException {
235         if (!root.isDirectory()) {
236             LOG.warn("{} YANG source directory {} not found. No code will be generated.", LOG_PREFIX, root);
237             return ImmutableList.of();
238         }
239
240         return Files.walk(root.toPath()).map(Path::toFile).filter(File::isFile).filter(f -> {
241             if (excludedFiles.contains(f)) {
242                 LOG.info("{} YANG file excluded {}", LOG_PREFIX, f);
243                 return false;
244             }
245             return true;
246         }).filter(f -> f.getName().endsWith(YangConstants.RFC6020_YANG_FILE_EXTENSION)).collect(Collectors.toList());
247     }
248
249     private static Collection<YangTextSchemaSource> toUniqueSources(final Collection<YangTextSchemaSource> sources)
250             throws IOException {
251         final Map<String, YangTextSchemaSource> byContent = new HashMap<>();
252         for (YangTextSchemaSource s : sources) {
253             try (Reader reader = s.asCharSource(StandardCharsets.UTF_8).openStream()) {
254                 final String contents = CharStreams.toString(reader);
255                 byContent.putIfAbsent(contents, s);
256             }
257         }
258         return byContent.values();
259     }
260
261     /**
262      * Call generate on every generator from plugin configuration.
263      */
264     @SuppressWarnings("checkstyle:illegalCatch")
265     private void generateSources(final ContextHolder context) throws MojoFailureException {
266         if (codeGenerators.isEmpty()) {
267             LOG.warn("{} No code generators provided", LOG_PREFIX);
268             return;
269         }
270
271         final Map<String, String> thrown = new HashMap<>();
272         for (CodeGeneratorArg codeGenerator : codeGenerators) {
273             try {
274                 generateSourcesWithOneGenerator(context, codeGenerator);
275             } catch (Exception e) {
276                 // try other generators, exception will be thrown after
277                 LOG.error("{} Unable to generate sources with {} generator", LOG_PREFIX, codeGenerator
278                         .getCodeGeneratorClass(), e);
279                 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
280             }
281         }
282
283         if (!thrown.isEmpty()) {
284             String message = " One or more code generators failed, including failed list(generatorClass=exception) ";
285             LOG.error("{}{}{}", LOG_PREFIX, message, thrown.toString());
286             throw new MojoFailureException(LOG_PREFIX + message + thrown.toString());
287         }
288     }
289
290     /**
291      * Instantiate generator from class and call required method.
292      */
293     private void generateSourcesWithOneGenerator(final ContextHolder context, final CodeGeneratorArg codeGeneratorCfg)
294             throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
295
296         codeGeneratorCfg.check();
297
298         final BasicCodeGenerator g = getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
299         LOG.info("{} Code generator instantiated from {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass());
300
301         final File outputDir = requireNonNull(codeGeneratorCfg.getOutputBaseDir(project),
302             "outputBaseDir is null. Please provide a valid outputBaseDir value in pom.xml");
303
304         project.addCompileSourceRoot(outputDir.getAbsolutePath());
305
306         LOG.info("{} Sources will be generated to {}", LOG_PREFIX, outputDir);
307         LOG.debug("{} Project root dir is {}", LOG_PREFIX, project.getBasedir());
308         LOG.debug("{} Additional configuration picked up for : {}: {}", LOG_PREFIX, codeGeneratorCfg
309                         .getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration());
310
311         if (g instanceof BuildContextAware) {
312             ((BuildContextAware)g).setBuildContext(buildContext);
313         }
314         if (g instanceof MavenProjectAware) {
315             ((MavenProjectAware)g).setMavenProject(project);
316         }
317         g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
318         File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
319
320         YangProvider.setResource(resourceBaseDir, project);
321         g.setResourceBaseDir(resourceBaseDir);
322         LOG.debug("{} Folder: {} marked as resources for generator: {}", LOG_PREFIX, resourceBaseDir,
323                 codeGeneratorCfg.getCodeGeneratorClass());
324
325         if (outputDir.exists()) {
326             Files.walk(outputDir.toPath()).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
327             LOG.info("{} Succesfully deleted output directory {}", LOG_PREFIX, outputDir);
328         }
329         Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules(),
330             context::moduleToResourcePath);
331
332         LOG.info("{} Sources generated by {}: {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(), generated);
333     }
334
335     /**
336      * Instantiate object from fully qualified class name.
337      */
338     private static <T> T getInstance(final String codeGeneratorClass, final Class<T> baseType) throws
339             ClassNotFoundException, InstantiationException, IllegalAccessException {
340         final Class<?> clazz = Class.forName(codeGeneratorClass);
341         checkArgument(baseType.isAssignableFrom(clazz), "Code generator %s has to implement %s", clazz, baseType);
342         return baseType.cast(clazz.newInstance());
343     }
344 }