58297c2c5804453e510c2e1412c70f6cc108a3bf
[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.Preconditions;
12 import com.google.common.base.Throwables;
13 import com.google.common.collect.ImmutableList;
14 import com.google.common.collect.ImmutableSet;
15 import com.google.common.io.CharStreams;
16 import java.io.Closeable;
17 import java.io.File;
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.io.Reader;
21 import java.nio.charset.StandardCharsets;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Set;
29 import org.apache.maven.plugin.MojoExecutionException;
30 import org.apache.maven.plugin.MojoFailureException;
31 import org.apache.maven.project.MavenProject;
32 import org.codehaus.plexus.util.FileUtils;
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.YangTextSchemaContextResolver;
36 import org.opendaylight.yangtools.yang.parser.util.NamedFileInputStream;
37 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
38 import org.opendaylight.yangtools.yang2sources.plugin.ConfigArg.CodeGeneratorArg;
39 import org.opendaylight.yangtools.yang2sources.plugin.Util.ContextHolder;
40 import org.opendaylight.yangtools.yang2sources.plugin.Util.YangsInZipsResult;
41 import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
42 import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
43 import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46 import org.sonatype.plexus.build.incremental.BuildContext;
47 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
48
49 class YangToSourcesProcessor {
50     private static final Logger LOG = LoggerFactory.getLogger(YangToSourcesProcessor.class);
51
52     static final String LOG_PREFIX = "yang-to-sources:";
53     static final String META_INF_YANG_STRING = "META-INF" + File.separator + "yang";
54     static final String META_INF_YANG_STRING_JAR = "META-INF" + "/" + "yang";
55     static final String META_INF_YANG_SERVICES_STRING_JAR = "META-INF" + "/" + "services";
56
57     private final File yangFilesRootDir;
58     private final Set<File> excludedFiles;
59     private final List<CodeGeneratorArg> codeGenerators;
60     private final MavenProject project;
61     private final boolean inspectDependencies;
62     private final BuildContext buildContext;
63     private final YangProvider yangProvider;
64     private final YangTextSchemaContextResolver resolver;
65
66     @VisibleForTesting
67     YangToSourcesProcessor(final File yangFilesRootDir, final Collection<File> excludedFiles,
68             final List<CodeGeneratorArg> codeGenerators, final MavenProject project, final boolean inspectDependencies,
69             final YangProvider yangProvider) {
70         this(new DefaultBuildContext(), yangFilesRootDir, excludedFiles, codeGenerators, project,
71                 inspectDependencies, yangProvider);
72     }
73
74     private YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
75             final Collection<File> excludedFiles, final List<CodeGeneratorArg> codeGenerators,
76             final MavenProject project, final boolean inspectDependencies, final YangProvider yangProvider) {
77         this.buildContext = Preconditions.checkNotNull(buildContext, "buildContext");
78         this.yangFilesRootDir = Preconditions.checkNotNull(yangFilesRootDir, "yangFilesRootDir");
79         this.excludedFiles = ImmutableSet.copyOf(excludedFiles);
80         this.codeGenerators = ImmutableList.copyOf(codeGenerators);
81         this.project = Preconditions.checkNotNull(project);
82         this.inspectDependencies = inspectDependencies;
83         this.yangProvider = yangProvider;
84         this.resolver = YangTextSchemaContextResolver.create("maven-plugin");
85     }
86
87     YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
88                 final Collection<File> excludedFiles, final List<CodeGeneratorArg> codeGenerators,
89                 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         SchemaContext resolveSchemaContext;
123         List<Closeable> closeables = new ArrayList<>();
124         LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
125         try {
126             /*
127              * Collect all files which affect YANG context. This includes all
128              * files in current project and optionally any jars/files in the
129              * dependencies.
130              */
131             final Collection<File> yangFilesInProject = Util.listFiles(yangFilesRootDir, excludedFiles);
132
133             final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
134             if (inspectDependencies) {
135                 allFiles.addAll(Util.findYangFilesInDependencies(project));
136             }
137
138             if (allFiles.isEmpty()) {
139                 LOG.info("{} No input files found", LOG_PREFIX);
140                 return null;
141             }
142
143             /*
144              * Check if any of the listed files changed. If no changes occurred,
145              * simply return null, which indicates and of execution.
146              */
147             boolean noChange = true;
148             for (final File f : allFiles) {
149                 if (buildContext.hasDelta(f)) {
150                     LOG.debug("{} buildContext {} indicates {} changed, forcing regeneration", LOG_PREFIX,
151                             buildContext, f);
152                     noChange = false;
153                 }
154             }
155
156             if (noChange) {
157                 LOG.info("{} None of {} input files changed", LOG_PREFIX, allFiles.size());
158                 return null;
159             }
160
161             final List<NamedFileInputStream> yangsInProject = new ArrayList<>();
162             for (final File f : yangFilesInProject) {
163                 // FIXME: This is hack - normal path should be reported.
164                 yangsInProject.add(new NamedFileInputStream(f, META_INF_YANG_STRING + File.separator + f.getName()));
165             }
166
167             List<InputStream> all = new ArrayList<>();
168             all.addAll(yangsInProject);
169             closeables.addAll(yangsInProject);
170
171             /**
172              * Set contains all modules generated from input sources. Number of
173              * modules may differ from number of sources due to submodules
174              * (parsed submodule's data are added to its parent module). Set
175              * cannot contains null values.
176              */
177             final Set<Module> projectYangModules = new HashSet<>();
178             final Set<Module> projectYangFiles = new HashSet<>();
179             try {
180                 if (inspectDependencies) {
181                     YangsInZipsResult dependentYangResult = Util.findYangFilesInDependenciesAsStream(project);
182                     Closeable dependentYangResult1 = dependentYangResult;
183                     closeables.add(dependentYangResult1);
184                     List<InputStream> yangStreams = toStreamsWithoutDuplicates(dependentYangResult.getYangStreams());
185                     all.addAll(yangStreams);
186                     closeables.addAll(yangStreams);
187                 }
188
189                 resolveSchemaContext = YangParserTestUtils.parseYangStreams(all);
190
191                 Set<Module> parsedAllYangModules = resolveSchemaContext.getModules();
192                 for (Module module : parsedAllYangModules) {
193                     if (containedInFiles(yangsInProject, module)) {
194                         LOG.debug("Module {} belongs to current project", module);
195                         projectYangModules.add(module);
196                         projectYangFiles.add(module);
197
198                         for (Module sub : module.getSubmodules()) {
199                             if (containedInFiles(yangsInProject, sub)) {
200                                 LOG.debug("Submodule {} belongs to current project", sub);
201                                 projectYangFiles.add(sub);
202                             } else {
203                                 LOG.warn("Submodule {} not found in input files", sub);
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             LOG.debug("Project YANG files: {}", projectYangFiles);
216
217             return new ContextHolder(resolveSchemaContext, projectYangModules, projectYangFiles);
218
219             // MojoExecutionException is thrown since execution cannot continue
220         } catch (Exception e) {
221             LOG.error("{} Unable to parse {} files from {}", LOG_PREFIX, Util.YANG_SUFFIX, yangFilesRootDir, e);
222             Throwable rootCause = Throwables.getRootCause(e);
223             throw new MojoExecutionException(LOG_PREFIX + " Unable to parse " + Util.YANG_SUFFIX + " files from " +
224                     yangFilesRootDir, rootCause);
225         }
226     }
227
228     private static boolean containedInFiles(final List<NamedFileInputStream> files, final Module module) {
229         final String path = module.getModuleSourcePath();
230         if (path != null) {
231             LOG.debug("Looking for source {}", path);
232             for (NamedFileInputStream is : files) {
233                 LOG.debug("In project destination {}", is.getFileDestination());
234                 if (path.equals(is.getFileDestination())) {
235                     return true;
236                 }
237             }
238         }
239
240         return false;
241     }
242
243     private static List<InputStream> toStreamsWithoutDuplicates(final List<YangSourceFromDependency> list)
244             throws IOException {
245         final Map<String, YangSourceFromDependency> byContent = new HashMap<>();
246
247         for (YangSourceFromDependency yangFromDependency : list) {
248             try (Reader reader = yangFromDependency.asCharSource(StandardCharsets.UTF_8).openStream()) {
249                 final String contents = CharStreams.toString(reader);
250                 byContent.putIfAbsent(contents, yangFromDependency);
251             } catch (IOException e) {
252                 throw new IOException("Exception when reading from: " + yangFromDependency.getDescription(), e);
253             }
254
255         }
256         List<InputStream> inputs = new ArrayList<>(byContent.size());
257         for (YangSourceFromDependency entry : byContent.values()) {
258             inputs.add(entry.openStream());
259         }
260         return inputs;
261     }
262
263     /**
264      * Call generate on every generator from plugin configuration
265      */
266     private void generateSources(final ContextHolder context) throws MojoFailureException {
267         if (codeGenerators.size() == 0) {
268             LOG.warn("{} No code generators provided", LOG_PREFIX);
269             return;
270         }
271
272         final Map<String, String> thrown = new HashMap<>();
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(final ContextHolder context, final CodeGeneratorArg codeGeneratorCfg)
295             throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
296
297         codeGeneratorCfg.check();
298
299         BasicCodeGenerator g = getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
300         LOG.info("{} Code generator instantiated from {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass());
301
302         final File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
303
304         if (outputDir == null) {
305             throw new NullPointerException("outputBaseDir is null. Please provide a valid outputBaseDir value in the " +
306                     "pom.xml");
307         }
308
309         project.addCompileSourceRoot(outputDir.getAbsolutePath());
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         FileUtils.deleteDirectory(outputDir);
331         LOG.info("{} Succesfully deleted output directory {}", LOG_PREFIX, outputDir);
332
333         Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules(),
334             context::moduleToResourcePath);
335
336         LOG.info("{} Sources generated by {}: {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(), generated);
337     }
338
339     /**
340      * Instantiate object from fully qualified class name
341      */
342     private static <T> T getInstance(final String codeGeneratorClass, final Class<T> baseType) throws
343             ClassNotFoundException, InstantiationException, IllegalAccessException {
344         final Class<?> clazz = Class.forName(codeGeneratorClass);
345
346         Preconditions.checkArgument(baseType.isAssignableFrom(clazz), "Code generator %s has to implement %s", clazz,
347             baseType);
348         return baseType.cast(clazz.newInstance());
349     }
350 }