Bug 7159: Add yang-test-util artifact
[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.util.NamedFileInputStream;
34 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
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     static final String META_INF_YANG_SERVICES_STRING_JAR = "META-INF" + "/" + "services";
53
54     private final File yangFilesRootDir;
55     private final File[] excludedFiles;
56     private final List<CodeGeneratorArg> codeGenerators;
57     private final MavenProject project;
58     private final boolean inspectDependencies;
59     private final BuildContext buildContext;
60     private final YangProvider yangProvider;
61     private final YangTextSchemaContextResolver resolver;
62
63     @VisibleForTesting
64     YangToSourcesProcessor(final File yangFilesRootDir, final File[] excludedFiles, final List<CodeGeneratorArg> codeGenerators,
65             final MavenProject project, final boolean inspectDependencies, final YangProvider yangProvider) {
66         this(new DefaultBuildContext(), yangFilesRootDir, excludedFiles, codeGenerators, project,
67                 inspectDependencies, yangProvider);
68     }
69
70     private YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir, final File[] excludedFiles,
71             final List<CodeGeneratorArg> codeGenerators, final MavenProject project, final boolean inspectDependencies, final YangProvider
72                                            yangProvider) {
73         this.buildContext = Util.checkNotNull(buildContext, "buildContext");
74         this.yangFilesRootDir = Util.checkNotNull(yangFilesRootDir, "yangFilesRootDir");
75         this.excludedFiles = new File[excludedFiles.length];
76         int i = 0;
77         for (File file : excludedFiles) {
78             this.excludedFiles[i++] = new File(file.getPath());
79         }
80         this.codeGenerators = Collections.unmodifiableList(Util.checkNotNull(codeGenerators, "codeGenerators"));
81         this.project = Util.checkNotNull(project, "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, final File[] excludedFiles,
88                            final List<CodeGeneratorArg> codeGenerators, final MavenProject project, final boolean inspectDependencies) {
89         this(yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, new YangProvider());
90     }
91
92     public void execute() throws MojoExecutionException, MojoFailureException {
93         ContextHolder context = processYang();
94         if (context != null) {
95             generateSources(context);
96             yangProvider.addYangsToMetaInf(project, yangFilesRootDir, excludedFiles);
97         }
98     }
99
100     void conditionalExecute(final boolean skip) throws MojoExecutionException, MojoFailureException {
101         if (skip) {
102             LOG.info("Skipping YANG code generation because property yang.skip is true");
103
104             // But manually add resources
105             // add META_INF/yang
106             yangProvider.addYangsToMetaInf(project, yangFilesRootDir, excludedFiles);
107
108             // add META_INF/services
109             File generatedServicesDir = new File(project.getBasedir(), CodeGeneratorArg.YANG_SERVICES_GENERATED_DIR);
110             YangProvider.setResource(generatedServicesDir, project);
111             LOG.debug("{} Yang services files from: {} marked as resources: {}", LOG_PREFIX, generatedServicesDir,
112                     META_INF_YANG_SERVICES_STRING_JAR);
113
114
115         } else {
116             execute();
117         }
118     }
119
120     private ContextHolder processYang() throws MojoExecutionException {
121         SchemaContext resolveSchemaContext;
122         List<Closeable> closeables = new ArrayList<>();
123         LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
124         try {
125             /*
126              * Collect all files which affect YANG context. This includes all
127              * files in current project and optionally any jars/files in the
128              * dependencies.
129              */
130             final Collection<File> yangFilesInProject = Util.listFiles(yangFilesRootDir, excludedFiles);
131
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             Set<Module> projectYangModules;
178             try {
179                 if (inspectDependencies) {
180                     YangsInZipsResult dependentYangResult = Util.findYangFilesInDependenciesAsStream(project);
181                     Closeable dependentYangResult1 = dependentYangResult;
182                     closeables.add(dependentYangResult1);
183                     List<InputStream> yangStreams = toStreamsWithoutDuplicates(dependentYangResult.getYangStreams());
184                     all.addAll(yangStreams);
185                     closeables.addAll(yangStreams);
186                 }
187
188                 resolveSchemaContext = YangParserTestUtils.parseYangStreams(all);
189
190                 Set<Module> parsedAllYangModules = resolveSchemaContext.getModules();
191                 projectYangModules = new HashSet<>();
192                 for (Module module : parsedAllYangModules) {
193                     final String path = module.getModuleSourcePath();
194                     if (path != null) {
195                         LOG.debug("Looking for source {}", path);
196                         for (NamedFileInputStream is : yangsInProject) {
197                             LOG.debug("In project destination {}", is.getFileDestination());
198                             if (path.equals(is.getFileDestination())) {
199                                 LOG.debug("Module {} belongs to current project", module);
200                                 projectYangModules.add(module);
201                                 break;
202                             }
203                         }
204                     }
205                 }
206             } finally {
207                 for (AutoCloseable closeable : closeables) {
208                     closeable.close();
209                 }
210             }
211
212             LOG.info("{} {} files parsed from {}", LOG_PREFIX, Util.YANG_SUFFIX.toUpperCase(), yangsInProject);
213             return new ContextHolder(resolveSchemaContext, projectYangModules);
214
215             // MojoExecutionException is thrown since execution cannot continue
216         } catch (Exception e) {
217             LOG.error("{} Unable to parse {} files from {}", LOG_PREFIX, Util.YANG_SUFFIX, yangFilesRootDir, e);
218             Throwable rootCause = Throwables.getRootCause(e);
219             throw new MojoExecutionException(LOG_PREFIX + " Unable to parse " + Util.YANG_SUFFIX + " files from " +
220                     yangFilesRootDir, rootCause);
221         }
222     }
223
224     private static List<InputStream> toStreamsWithoutDuplicates(final List<YangSourceFromDependency> list) throws IOException {
225         ConcurrentMap<String, YangSourceFromDependency> byContent = Maps.newConcurrentMap();
226
227         for (YangSourceFromDependency yangFromDependency : list) {
228             try (InputStream dataStream = yangFromDependency.openStream()) {
229                 String contents = IOUtils.toString(dataStream);
230                 byContent.putIfAbsent(contents, yangFromDependency);
231             } catch (IOException e) {
232                 throw new IOException("Exception when reading from: " + yangFromDependency.getDescription(), e);
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(final MavenProject project, final File yangFilesRootDir, final 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 static void addYangsToMetaInf(final MavenProject project, final File yangFilesRootDir,
265                 final File[] excludedFiles, final File generatedYangDir) throws MojoFailureException {
266
267             File withMetaInf = new File(generatedYangDir, META_INF_YANG_STRING);
268             withMetaInf.mkdirs();
269
270             try {
271                 Collection<File> files = Util.listFiles(yangFilesRootDir, excludedFiles);
272                 for (File file : files) {
273                     org.apache.commons.io.FileUtils.copyFile(file, new File(withMetaInf, file.getName()));
274                 }
275             } catch (IOException e) {
276                 LOG.warn("Failed to generate files into root {}", yangFilesRootDir, e);
277                 throw new MojoFailureException("Unable to list yang files into resource folder", e);
278             }
279
280             setResource(generatedYangDir, project);
281
282             LOG.debug("{} Yang files from: {} marked as resources: {}", LOG_PREFIX, yangFilesRootDir,
283                     META_INF_YANG_STRING_JAR);
284         }
285
286         private static void setResource(final File targetYangDir, final MavenProject project) {
287             Resource res = new Resource();
288             res.setDirectory(targetYangDir.getPath());
289             project.addResource(res);
290         }
291     }
292
293     /**
294      * Call generate on every generator from plugin configuration
295      */
296     private void generateSources(final ContextHolder context) throws MojoFailureException {
297         if (codeGenerators.size() == 0) {
298             LOG.warn("{} No code generators provided", LOG_PREFIX);
299             return;
300         }
301
302         Map<String, String> thrown = Maps.newHashMap();
303         for (CodeGeneratorArg codeGenerator : codeGenerators) {
304             try {
305                 generateSourcesWithOneGenerator(context, codeGenerator);
306             } catch (Exception e) {
307                 // try other generators, exception will be thrown after
308                 LOG.error("{} Unable to generate sources with {} generator", LOG_PREFIX, codeGenerator
309                         .getCodeGeneratorClass(), e);
310                 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
311             }
312         }
313
314         if (!thrown.isEmpty()) {
315             String message = " One or more code generators failed, including failed list(generatorClass=exception) ";
316             LOG.error("{}" + message + "{}", LOG_PREFIX, thrown.toString());
317             throw new MojoFailureException(LOG_PREFIX + message + thrown.toString());
318         }
319     }
320
321     /**
322      * Instantiate generator from class and call required method
323      */
324     private void generateSourcesWithOneGenerator(final ContextHolder context, final CodeGeneratorArg codeGeneratorCfg)
325             throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
326
327         codeGeneratorCfg.check();
328
329         BasicCodeGenerator g = Util.getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
330         LOG.info("{} Code generator instantiated from {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass());
331
332         File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
333
334         if (outputDir != null) {
335           project.addCompileSourceRoot(outputDir.getAbsolutePath());
336         } else {
337           throw new NullPointerException("outputBaseDir is null. Please provide a valid outputBaseDir value in the " +
338                   "pom.xml");
339         }
340
341         LOG.info("{} Sources will be generated to {}", LOG_PREFIX, outputDir);
342         LOG.debug("{} Project root dir is {}", LOG_PREFIX, project.getBasedir());
343         LOG.debug("{} Additional configuration picked up for : {}: {}", LOG_PREFIX, codeGeneratorCfg
344                         .getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration());
345
346         if (g instanceof BuildContextAware) {
347             ((BuildContextAware)g).setBuildContext(buildContext);
348         }
349         if (g instanceof MavenProjectAware) {
350             ((MavenProjectAware)g).setMavenProject(project);
351         }
352         g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
353         File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
354
355         YangProvider.setResource(resourceBaseDir, project);
356         g.setResourceBaseDir(resourceBaseDir);
357         LOG.debug("{} Folder: {} marked as resources for generator: {}", LOG_PREFIX, resourceBaseDir,
358                 codeGeneratorCfg.getCodeGeneratorClass());
359
360         Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules());
361
362         LOG.info("{} Sources generated by {}: {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(), generated);
363     }
364
365 }