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