Fix yang.skip feature to include all files needed
[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     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(File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
66             MavenProject project, boolean inspectDependencies, YangProvider yangProvider) {
67         this(new DefaultBuildContext(), yangFilesRootDir, excludedFiles, codeGenerators, project,
68                 inspectDependencies, yangProvider);
69     }
70
71     private YangToSourcesProcessor(BuildContext buildContext, File yangFilesRootDir, File[] excludedFiles,
72             List<CodeGeneratorArg> codeGenerators, MavenProject project, boolean inspectDependencies, 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(BuildContext buildContext, File yangFilesRootDir, File[] excludedFiles,
89                            List<CodeGeneratorArg> codeGenerators, MavenProject project, 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(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 List<InputStream> toStreamsWithoutDuplicates(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             }
234
235         }
236         List<InputStream> inputs = new ArrayList<>(byContent.size());
237         for (YangSourceFromDependency entry : byContent.values()) {
238             inputs.add(entry.openStream());
239         }
240         return inputs;
241     }
242
243     static class YangProvider {
244         private static final Logger LOG = LoggerFactory.getLogger(YangProvider.class);
245
246         void addYangsToMetaInf(MavenProject project, File yangFilesRootDir, File[] excludedFiles)
247                 throws MojoFailureException {
248
249             // copy project's src/main/yang/*.yang to target/generated-sources/yang/META-INF/yang/*.yang
250
251             File generatedYangDir = new File(project.getBasedir(), CodeGeneratorArg.YANG_GENERATED_DIR);
252             addYangsToMetaInf(project, yangFilesRootDir, excludedFiles, generatedYangDir);
253
254             // Also copy to the actual build output dir if different than "target". When running in
255             // Eclipse this can differ (eg "target-ide").
256
257             File actualGeneratedYangDir = new File(project.getBuild().getDirectory(),
258                     CodeGeneratorArg.YANG_GENERATED_DIR.replace("target" + File.separator, ""));
259             if (!actualGeneratedYangDir.equals(generatedYangDir)) {
260                 addYangsToMetaInf(project, yangFilesRootDir, excludedFiles, actualGeneratedYangDir);
261             }
262         }
263
264         private void addYangsToMetaInf(MavenProject project, File yangFilesRootDir,
265                 File[] excludedFiles, File generatedYangDir)
266                 throws MojoFailureException {
267
268             File withMetaInf = new File(generatedYangDir, META_INF_YANG_STRING);
269             withMetaInf.mkdirs();
270
271             try {
272                 Collection<File> files = Util.listFiles(yangFilesRootDir, excludedFiles);
273                 for (File file : files) {
274                     org.apache.commons.io.FileUtils.copyFile(file, new File(withMetaInf, file.getName()));
275                 }
276             } catch (IOException e) {
277                 LOG.warn("Failed to generate files into root {}", yangFilesRootDir, e);
278                 throw new MojoFailureException("Unable to list yang files into resource folder", e);
279             }
280
281             setResource(generatedYangDir, project);
282
283             LOG.debug("{} Yang files from: {} marked as resources: {}", LOG_PREFIX, yangFilesRootDir,
284                     META_INF_YANG_STRING_JAR);
285         }
286
287         private static void setResource(File targetYangDir, MavenProject project) {
288             Resource res = new Resource();
289             res.setDirectory(targetYangDir.getPath());
290             project.addResource(res);
291         }
292     }
293
294     /**
295      * Call generate on every generator from plugin configuration
296      */
297     private void generateSources(ContextHolder context) throws MojoFailureException {
298         if (codeGenerators.size() == 0) {
299             LOG.warn("{} No code generators provided", LOG_PREFIX);
300             return;
301         }
302
303         Map<String, String> thrown = Maps.newHashMap();
304         for (CodeGeneratorArg codeGenerator : codeGenerators) {
305             try {
306                 generateSourcesWithOneGenerator(context, codeGenerator);
307             } catch (Exception e) {
308                 // try other generators, exception will be thrown after
309                 LOG.error("{} Unable to generate sources with {} generator", LOG_PREFIX, codeGenerator
310                         .getCodeGeneratorClass(), e);
311                 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
312             }
313         }
314
315         if (!thrown.isEmpty()) {
316             String message = " One or more code generators failed, including failed list(generatorClass=exception) ";
317             LOG.error("{}" + message + "{}", LOG_PREFIX, thrown.toString());
318             throw new MojoFailureException(LOG_PREFIX + message + thrown.toString());
319         }
320     }
321
322     /**
323      * Instantiate generator from class and call required method
324      */
325     private void generateSourcesWithOneGenerator(ContextHolder context, CodeGeneratorArg codeGeneratorCfg)
326             throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
327
328         codeGeneratorCfg.check();
329
330         BasicCodeGenerator g = Util.getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
331         LOG.info("{} Code generator instantiated from {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass());
332
333         File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
334
335         if (outputDir != null) {
336           project.addCompileSourceRoot(outputDir.getAbsolutePath());
337         } else {
338           throw new NullPointerException("outputBaseDir is null. Please provide a valid outputBaseDir value in the " +
339                   "pom.xml");
340         }
341
342         LOG.info("{} Sources will be generated to {}", LOG_PREFIX, outputDir);
343         LOG.debug("{} Project root dir is {}", LOG_PREFIX, project.getBasedir());
344         LOG.debug("{} Additional configuration picked up for : {}: {}", LOG_PREFIX, codeGeneratorCfg
345                         .getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration());
346
347         if (g instanceof BuildContextAware) {
348             ((BuildContextAware)g).setBuildContext(buildContext);
349         }
350         if (g instanceof MavenProjectAware) {
351             ((MavenProjectAware)g).setMavenProject(project);
352         }
353         g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
354         File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
355
356         YangProvider.setResource(resourceBaseDir, project);
357         g.setResourceBaseDir(resourceBaseDir);
358         LOG.debug("{} Folder: {} marked as resources for generator: {}", LOG_PREFIX, resourceBaseDir,
359                 codeGeneratorCfg.getCodeGeneratorClass());
360
361         Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules());
362
363         LOG.info("{} Sources generated by {}: {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(), generated);
364     }
365
366 }