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