195c7f39ba2c43da6220827b81e3d975a3c24915
[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.URLSchemaContextResolver;
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 URLSchemaContextResolver 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 = URLSchemaContextResolver.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     private ContextHolder processYang() throws MojoExecutionException {
101         final CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR.newBuild();
102         SchemaContext resolveSchemaContext;
103         List<Closeable> closeables = new ArrayList<>();
104         LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
105         try {
106             /*
107              * Collect all files which affect YANG context. This includes all
108              * files in current project and optionally any jars/files in the
109              * dependencies.
110              */
111             final Collection<File> yangFilesInProject = Util.listFiles(yangFilesRootDir, excludedFiles);
112
113
114             final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
115             if (inspectDependencies) {
116                 allFiles.addAll(Util.findYangFilesInDependencies(project));
117             }
118
119             if (allFiles.isEmpty()) {
120                 LOG.info("{} No input files found", LOG_PREFIX);
121                 return null;
122             }
123
124             /*
125              * Check if any of the listed files changed. If no changes occurred,
126              * simply return null, which indicates and of execution.
127              */
128             boolean noChange = true;
129             for (final File f : allFiles) {
130                 if (buildContext.hasDelta(f)) {
131                     LOG.debug("{} buildContext {} indicates {} changed, forcing regeneration", LOG_PREFIX,
132                             buildContext, f);
133                     noChange = false;
134                 }
135             }
136
137             if (noChange) {
138                 LOG.info("{} None of {} input files changed", LOG_PREFIX, allFiles.size());
139                 return null;
140             }
141
142             final List<InputStream> yangsInProject = new ArrayList<>();
143             for (final File f : yangFilesInProject) {
144                 // FIXME: This is hack - normal path should be reported.
145                 yangsInProject.add(new NamedFileInputStream(f, META_INF_YANG_STRING + File.separator + f.getName()));
146             }
147
148             List<InputStream> all = new ArrayList<>(yangsInProject);
149             closeables.addAll(yangsInProject);
150
151             /**
152              * Set contains all modules generated from input sources. Number of
153              * modules may differ from number of sources due to submodules
154              * (parsed submodule's data are added to its parent module). Set
155              * cannot contains null values.
156              */
157             Set<Module> projectYangModules;
158             try {
159                 if (inspectDependencies) {
160                     YangsInZipsResult dependentYangResult = Util.findYangFilesInDependenciesAsStream(project);
161                     Closeable dependentYangResult1 = dependentYangResult;
162                     closeables.add(dependentYangResult1);
163                     List<InputStream> yangStreams = toStreamsWithoutDuplicates(dependentYangResult.getYangStreams());
164                     all.addAll(yangStreams);
165                     closeables.addAll(yangStreams);
166                 }
167
168                 resolveSchemaContext = reactor.buildEffective(all);
169
170                 Set<Module> parsedAllYangModules = resolveSchemaContext.getModules();
171                 projectYangModules = new HashSet<>();
172                 for (Module module : parsedAllYangModules) {
173                     if(module.getModuleSourcePath()!=null) {
174                         projectYangModules.add(module);
175                     }
176                 }
177             } finally {
178                 for (AutoCloseable closeable : closeables) {
179                     closeable.close();
180                 }
181             }
182
183             LOG.info("{} {} files parsed from {}", LOG_PREFIX, Util.YANG_SUFFIX.toUpperCase(), yangsInProject);
184             return new ContextHolder(resolveSchemaContext, projectYangModules);
185
186             // MojoExecutionException is thrown since execution cannot continue
187         } catch (Exception e) {
188             LOG.error("{} Unable to parse {} files from {}", LOG_PREFIX, Util.YANG_SUFFIX, yangFilesRootDir, e);
189             Throwable rootCause = Throwables.getRootCause(e);
190             throw new MojoExecutionException(LOG_PREFIX + " Unable to parse " + Util.YANG_SUFFIX + " files from " +
191                     yangFilesRootDir, rootCause);
192         }
193     }
194
195     private List<InputStream> toStreamsWithoutDuplicates(List<YangSourceFromDependency> list) throws IOException {
196         ConcurrentMap<String, YangSourceFromDependency> byContent = Maps.newConcurrentMap();
197
198         for (YangSourceFromDependency yangFromDependency : list) {
199             try (InputStream dataStream = yangFromDependency.openStream()) {
200                 String contents = IOUtils.toString(dataStream);
201                 byContent.putIfAbsent(contents, yangFromDependency);
202             }
203
204         }
205         List<InputStream> inputs = new ArrayList<>(byContent.size());
206         for (YangSourceFromDependency entry : byContent.values()) {
207             inputs.add(entry.openStream());
208         }
209         return inputs;
210     }
211
212     static class YangProvider {
213         private static final Logger LOG = LoggerFactory.getLogger(YangProvider.class);
214
215         void addYangsToMetaInf(MavenProject project, File yangFilesRootDir, File[] excludedFiles)
216                 throws MojoFailureException {
217
218             // copy project's src/main/yang/*.yang to target/generated-sources/yang/META-INF/yang/*.yang
219
220             File generatedYangDir = new File(project.getBasedir(), CodeGeneratorArg.YANG_GENERATED_DIR);
221             addYangsToMetaInf(project, yangFilesRootDir, excludedFiles, generatedYangDir);
222
223             // Also copy to the actual build output dir if different than "target". When running in
224             // Eclipse this can differ (eg "target-ide").
225
226             File actualGeneratedYangDir = new File(project.getBuild().getDirectory(),
227                     CodeGeneratorArg.YANG_GENERATED_DIR.replace("target" + File.separator, ""));
228             if(!actualGeneratedYangDir.equals(generatedYangDir)) {
229                 addYangsToMetaInf(project, yangFilesRootDir, excludedFiles, actualGeneratedYangDir);
230             }
231         }
232
233         private void addYangsToMetaInf(MavenProject project, File yangFilesRootDir,
234                 File[] excludedFiles, File generatedYangDir)
235                 throws MojoFailureException {
236
237             File withMetaInf = new File(generatedYangDir, META_INF_YANG_STRING);
238             withMetaInf.mkdirs();
239
240             try {
241                 Collection<File> files = Util.listFiles(yangFilesRootDir, excludedFiles);
242                 for (File file : files) {
243                     org.apache.commons.io.FileUtils.copyFile(file, new File(withMetaInf, file.getName()));
244                 }
245             } catch (IOException e) {
246                 LOG.warn("Failed to generate files into root {}", yangFilesRootDir, e);
247                 throw new MojoFailureException("Unable to list yang files into resource folder", e);
248             }
249
250             setResource(generatedYangDir, project);
251
252             LOG.debug("{} Yang files from: {} marked as resources: {}", LOG_PREFIX, yangFilesRootDir,
253                     META_INF_YANG_STRING_JAR);
254         }
255
256         private static void setResource(File targetYangDir, MavenProject project) {
257             Resource res = new Resource();
258             res.setDirectory(targetYangDir.getPath());
259             project.addResource(res);
260         }
261     }
262
263     /**
264      * Call generate on every generator from plugin configuration
265      */
266     private void generateSources(ContextHolder context) throws MojoFailureException {
267         if (codeGenerators.size() == 0) {
268             LOG.warn("{} No code generators provided", LOG_PREFIX);
269             return;
270         }
271
272         Map<String, String> thrown = Maps.newHashMap();
273         for (CodeGeneratorArg codeGenerator : codeGenerators) {
274             try {
275                 generateSourcesWithOneGenerator(context, codeGenerator);
276             } catch (Exception e) {
277                 // try other generators, exception will be thrown after
278                 LOG.error("{} Unable to generate sources with {} generator", LOG_PREFIX, codeGenerator
279                         .getCodeGeneratorClass(), e);
280                 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
281             }
282         }
283
284         if (!thrown.isEmpty()) {
285             String message = " One or more code generators failed, including failed list(generatorClass=exception) ";
286             LOG.error("{}" + message + "{}", LOG_PREFIX, thrown.toString());
287             throw new MojoFailureException(LOG_PREFIX + message + thrown.toString());
288         }
289     }
290
291     /**
292      * Instantiate generator from class and call required method
293      */
294     private void generateSourcesWithOneGenerator(ContextHolder context, CodeGeneratorArg codeGeneratorCfg)
295             throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
296
297         codeGeneratorCfg.check();
298
299         BasicCodeGenerator g = Util.getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
300         LOG.info("{} Code generator instantiated from {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass());
301
302         File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
303
304         if (outputDir != null) {
305           project.addCompileSourceRoot(outputDir.getAbsolutePath());
306         } else {
307           throw new NullPointerException("outputBaseDir is null. Please provide a valid outputBaseDir value in the " +
308                   "pom.xml");
309         }
310
311         LOG.info("{} Sources will be generated to {}", LOG_PREFIX, outputDir);
312         LOG.debug("{} Project root dir is {}", LOG_PREFIX, project.getBasedir());
313         LOG.debug("{} Additional configuration picked up for : {}: {}", LOG_PREFIX, codeGeneratorCfg
314                         .getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration());
315
316         if (g instanceof BuildContextAware) {
317             ((BuildContextAware)g).setBuildContext(buildContext);
318         }
319         if (g instanceof MavenProjectAware) {
320             ((MavenProjectAware)g).setMavenProject(project);
321         }
322         g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
323         File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
324
325         YangProvider.setResource(resourceBaseDir, project);
326         g.setResourceBaseDir(resourceBaseDir);
327         LOG.debug("{} Folder: {} marked as resources for generator: {}", LOG_PREFIX, resourceBaseDir,
328                 codeGeneratorCfg.getCodeGeneratorClass());
329
330         Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules());
331
332         LOG.info("{} Sources generated by {}: {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(), generated);
333     }
334
335 }