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