8b6c5c35373de9bab8700eb61a5b5957d57672fe
[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 java.util.HashSet;
11 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
12 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline;
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.base.Throwables;
15 import com.google.common.collect.Maps;
16 import java.io.Closeable;
17 import java.io.File;
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Set;
26 import java.util.concurrent.ConcurrentMap;
27 import org.apache.commons.io.IOUtils;
28 import org.apache.maven.model.Resource;
29 import org.apache.maven.plugin.MojoExecutionException;
30 import org.apache.maven.plugin.MojoFailureException;
31 import org.apache.maven.project.MavenProject;
32 import org.opendaylight.yangtools.yang.model.api.Module;
33 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
34 import org.opendaylight.yangtools.yang.parser.repo.YangTextSchemaContextResolver;
35 import org.opendaylight.yangtools.yang.parser.util.NamedFileInputStream;
36 import org.opendaylight.yangtools.yang2sources.plugin.ConfigArg.CodeGeneratorArg;
37 import org.opendaylight.yangtools.yang2sources.plugin.Util.ContextHolder;
38 import org.opendaylight.yangtools.yang2sources.plugin.Util.YangsInZipsResult;
39 import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
40 import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
41 import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import org.sonatype.plexus.build.incremental.BuildContext;
45 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
46
47 class YangToSourcesProcessor {
48     private static final Logger LOG = LoggerFactory.getLogger(YangToSourcesProcessor.class);
49
50     static final String LOG_PREFIX = "yang-to-sources:";
51     static final String META_INF_YANG_STRING = "META-INF" + File.separator + "yang";
52     static final String META_INF_YANG_STRING_JAR = "META-INF" + "/" + "yang";
53
54     private final File yangFilesRootDir;
55     private final File[] excludedFiles;
56     private final List<CodeGeneratorArg> codeGenerators;
57     private final MavenProject project;
58     private final boolean inspectDependencies;
59     private final BuildContext buildContext;
60     private final YangProvider yangProvider;
61     private final YangTextSchemaContextResolver resolver;
62
63     @VisibleForTesting
64     YangToSourcesProcessor(File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
65             MavenProject project, boolean inspectDependencies, YangProvider yangProvider) {
66         this(new DefaultBuildContext(), yangFilesRootDir, excludedFiles, codeGenerators, project,
67                 inspectDependencies, yangProvider);
68     }
69
70     private YangToSourcesProcessor(BuildContext buildContext, File yangFilesRootDir, File[] excludedFiles,
71             List<CodeGeneratorArg> codeGenerators, MavenProject project, boolean inspectDependencies, YangProvider
72                                            yangProvider) {
73         this.buildContext = Util.checkNotNull(buildContext, "buildContext");
74         this.yangFilesRootDir = Util.checkNotNull(yangFilesRootDir, "yangFilesRootDir");
75         this.excludedFiles = new File[excludedFiles.length];
76         int i = 0;
77         for (File file : excludedFiles) {
78             this.excludedFiles[i++] = new File(file.getPath());
79         }
80         this.codeGenerators = Collections.unmodifiableList(Util.checkNotNull(codeGenerators, "codeGenerators"));
81         this.project = Util.checkNotNull(project, "project");
82         this.inspectDependencies = inspectDependencies;
83         this.yangProvider = yangProvider;
84         this.resolver = YangTextSchemaContextResolver.create("maven-plugin");
85     }
86
87     YangToSourcesProcessor(BuildContext buildContext, File yangFilesRootDir, File[] excludedFiles,
88                            List<CodeGeneratorArg> codeGenerators, MavenProject project, boolean inspectDependencies) {
89         this(yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, new YangProvider());
90     }
91
92     public void execute() throws MojoExecutionException, MojoFailureException {
93         ContextHolder context = processYang();
94         if (context != null) {
95             generateSources(context);
96             yangProvider.addYangsToMetaInf(project, yangFilesRootDir, excludedFiles);
97         }
98     }
99
100     void conditionalExecute(boolean skip) throws MojoExecutionException, MojoFailureException {
101         if (skip) {
102             LOG.info("Skipping YANG code generation because property yang.skip is true");
103         } else {
104             execute();
105         }
106     }
107
108     private ContextHolder processYang() throws MojoExecutionException {
109         final CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR.newBuild();
110         SchemaContext resolveSchemaContext;
111         List<Closeable> closeables = new ArrayList<>();
112         LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
113         try {
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 Collection<File> yangFilesInProject = Util.listFiles(yangFilesRootDir, excludedFiles);
120
121
122             final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
123             if (inspectDependencies) {
124                 allFiles.addAll(Util.findYangFilesInDependencies(project));
125             }
126
127             if (allFiles.isEmpty()) {
128                 LOG.info("{} No input files found", LOG_PREFIX);
129                 return null;
130             }
131
132             /*
133              * Check if any of the listed files changed. If no changes occurred,
134              * simply return null, which indicates and of execution.
135              */
136             boolean noChange = true;
137             for (final File f : allFiles) {
138                 if (buildContext.hasDelta(f)) {
139                     LOG.debug("{} buildContext {} indicates {} changed, forcing regeneration", LOG_PREFIX,
140                             buildContext, f);
141                     noChange = false;
142                 }
143             }
144
145             if (noChange) {
146                 LOG.info("{} None of {} input files changed", LOG_PREFIX, allFiles.size());
147                 return null;
148             }
149
150             final List<NamedFileInputStream> yangsInProject = new ArrayList<>();
151             for (final File f : yangFilesInProject) {
152                 // FIXME: This is hack - normal path should be reported.
153                 yangsInProject.add(new NamedFileInputStream(f, META_INF_YANG_STRING + File.separator + f.getName()));
154             }
155
156             List<InputStream> all = new ArrayList<>();
157             all.addAll(yangsInProject);
158             closeables.addAll(yangsInProject);
159
160             /**
161              * Set contains all modules generated from input sources. Number of
162              * modules may differ from number of sources due to submodules
163              * (parsed submodule's data are added to its parent module). Set
164              * cannot contains null values.
165              */
166             Set<Module> projectYangModules;
167             try {
168                 if (inspectDependencies) {
169                     YangsInZipsResult dependentYangResult = Util.findYangFilesInDependenciesAsStream(project);
170                     Closeable dependentYangResult1 = dependentYangResult;
171                     closeables.add(dependentYangResult1);
172                     List<InputStream> yangStreams = toStreamsWithoutDuplicates(dependentYangResult.getYangStreams());
173                     all.addAll(yangStreams);
174                     closeables.addAll(yangStreams);
175                 }
176
177                 resolveSchemaContext = reactor.buildEffective(all);
178
179                 Set<Module> parsedAllYangModules = resolveSchemaContext.getModules();
180                 projectYangModules = new HashSet<>();
181                 for (Module module : parsedAllYangModules) {
182                     final String path = module.getModuleSourcePath();
183                     if (path != null) {
184                         LOG.debug("Looking for source {}", path);
185                         for (NamedFileInputStream is : yangsInProject) {
186                             LOG.debug("In project destination {}", is.getFileDestination());
187                             if (path.equals(is.getFileDestination())) {
188                                 LOG.debug("Module {} belongs to current project", module);
189                                 projectYangModules.add(module);
190                                 break;
191                             }
192                         }
193                     }
194                 }
195             } finally {
196                 for (AutoCloseable closeable : closeables) {
197                     closeable.close();
198                 }
199             }
200
201             LOG.info("{} {} files parsed from {}", LOG_PREFIX, Util.YANG_SUFFIX.toUpperCase(), yangsInProject);
202             return new ContextHolder(resolveSchemaContext, projectYangModules);
203
204             // MojoExecutionException is thrown since execution cannot continue
205         } catch (Exception e) {
206             LOG.error("{} Unable to parse {} files from {}", LOG_PREFIX, Util.YANG_SUFFIX, yangFilesRootDir, e);
207             Throwable rootCause = Throwables.getRootCause(e);
208             throw new MojoExecutionException(LOG_PREFIX + " Unable to parse " + Util.YANG_SUFFIX + " files from " +
209                     yangFilesRootDir, rootCause);
210         }
211     }
212
213     private List<InputStream> toStreamsWithoutDuplicates(List<YangSourceFromDependency> list) throws IOException {
214         ConcurrentMap<String, YangSourceFromDependency> byContent = Maps.newConcurrentMap();
215
216         for (YangSourceFromDependency yangFromDependency : list) {
217             try (InputStream dataStream = yangFromDependency.openStream()) {
218                 String contents = IOUtils.toString(dataStream);
219                 byContent.putIfAbsent(contents, yangFromDependency);
220             }
221
222         }
223         List<InputStream> inputs = new ArrayList<>(byContent.size());
224         for (YangSourceFromDependency entry : byContent.values()) {
225             inputs.add(entry.openStream());
226         }
227         return inputs;
228     }
229
230     static class YangProvider {
231         private static final Logger LOG = LoggerFactory.getLogger(YangProvider.class);
232
233         void addYangsToMetaInf(MavenProject project, File yangFilesRootDir, File[] excludedFiles)
234                 throws MojoFailureException {
235
236             // copy project's src/main/yang/*.yang to target/generated-sources/yang/META-INF/yang/*.yang
237
238             File generatedYangDir = new File(project.getBasedir(), CodeGeneratorArg.YANG_GENERATED_DIR);
239             addYangsToMetaInf(project, yangFilesRootDir, excludedFiles, generatedYangDir);
240
241             // Also copy to the actual build output dir if different than "target". When running in
242             // Eclipse this can differ (eg "target-ide").
243
244             File actualGeneratedYangDir = new File(project.getBuild().getDirectory(),
245                     CodeGeneratorArg.YANG_GENERATED_DIR.replace("target" + File.separator, ""));
246             if (!actualGeneratedYangDir.equals(generatedYangDir)) {
247                 addYangsToMetaInf(project, yangFilesRootDir, excludedFiles, actualGeneratedYangDir);
248             }
249         }
250
251         private void addYangsToMetaInf(MavenProject project, File yangFilesRootDir,
252                 File[] excludedFiles, File generatedYangDir)
253                 throws MojoFailureException {
254
255             File withMetaInf = new File(generatedYangDir, META_INF_YANG_STRING);
256             withMetaInf.mkdirs();
257
258             try {
259                 Collection<File> files = Util.listFiles(yangFilesRootDir, excludedFiles);
260                 for (File file : files) {
261                     org.apache.commons.io.FileUtils.copyFile(file, new File(withMetaInf, file.getName()));
262                 }
263             } catch (IOException e) {
264                 LOG.warn("Failed to generate files into root {}", yangFilesRootDir, e);
265                 throw new MojoFailureException("Unable to list yang files into resource folder", e);
266             }
267
268             setResource(generatedYangDir, project);
269
270             LOG.debug("{} Yang files from: {} marked as resources: {}", LOG_PREFIX, yangFilesRootDir,
271                     META_INF_YANG_STRING_JAR);
272         }
273
274         private static void setResource(File targetYangDir, MavenProject project) {
275             Resource res = new Resource();
276             res.setDirectory(targetYangDir.getPath());
277             project.addResource(res);
278         }
279     }
280
281     /**
282      * Call generate on every generator from plugin configuration
283      */
284     private void generateSources(ContextHolder context) throws MojoFailureException {
285         if (codeGenerators.size() == 0) {
286             LOG.warn("{} No code generators provided", LOG_PREFIX);
287             return;
288         }
289
290         Map<String, String> thrown = Maps.newHashMap();
291         for (CodeGeneratorArg codeGenerator : codeGenerators) {
292             try {
293                 generateSourcesWithOneGenerator(context, codeGenerator);
294             } catch (Exception e) {
295                 // try other generators, exception will be thrown after
296                 LOG.error("{} Unable to generate sources with {} generator", LOG_PREFIX, codeGenerator
297                         .getCodeGeneratorClass(), e);
298                 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
299             }
300         }
301
302         if (!thrown.isEmpty()) {
303             String message = " One or more code generators failed, including failed list(generatorClass=exception) ";
304             LOG.error("{}" + message + "{}", LOG_PREFIX, thrown.toString());
305             throw new MojoFailureException(LOG_PREFIX + message + thrown.toString());
306         }
307     }
308
309     /**
310      * Instantiate generator from class and call required method
311      */
312     private void generateSourcesWithOneGenerator(ContextHolder context, CodeGeneratorArg codeGeneratorCfg)
313             throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
314
315         codeGeneratorCfg.check();
316
317         BasicCodeGenerator g = Util.getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
318         LOG.info("{} Code generator instantiated from {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass());
319
320         File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
321
322         if (outputDir != null) {
323           project.addCompileSourceRoot(outputDir.getAbsolutePath());
324         } else {
325           throw new NullPointerException("outputBaseDir is null. Please provide a valid outputBaseDir value in the " +
326                   "pom.xml");
327         }
328
329         LOG.info("{} Sources will be generated to {}", LOG_PREFIX, outputDir);
330         LOG.debug("{} Project root dir is {}", LOG_PREFIX, project.getBasedir());
331         LOG.debug("{} Additional configuration picked up for : {}: {}", LOG_PREFIX, codeGeneratorCfg
332                         .getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration());
333
334         if (g instanceof BuildContextAware) {
335             ((BuildContextAware)g).setBuildContext(buildContext);
336         }
337         if (g instanceof MavenProjectAware) {
338             ((MavenProjectAware)g).setMavenProject(project);
339         }
340         g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
341         File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
342
343         YangProvider.setResource(resourceBaseDir, project);
344         g.setResourceBaseDir(resourceBaseDir);
345         LOG.debug("{} Folder: {} marked as resources for generator: {}", LOG_PREFIX, resourceBaseDir,
346                 codeGeneratorCfg.getCodeGeneratorClass());
347
348         Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules());
349
350         LOG.info("{} Sources generated by {}: {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(), generated);
351     }
352
353 }