97c810d751130b8a843cf8021f05a18b949b4409
[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.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Throwables;
14 import com.google.common.collect.ImmutableList;
15 import com.google.common.collect.ImmutableMap;
16 import com.google.common.collect.ImmutableMap.Builder;
17 import com.google.common.collect.ImmutableSet;
18 import com.google.common.io.CharStreams;
19 import java.io.File;
20 import java.io.IOException;
21 import java.io.Reader;
22 import java.nio.charset.StandardCharsets;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Date;
26 import java.util.HashMap;
27 import java.util.HashSet;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Set;
31 import org.apache.maven.plugin.MojoExecutionException;
32 import org.apache.maven.plugin.MojoFailureException;
33 import org.apache.maven.project.MavenProject;
34 import org.codehaus.plexus.util.FileUtils;
35 import org.opendaylight.yangtools.yang.common.QNameModule;
36 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
37 import org.opendaylight.yangtools.yang.model.api.Module;
38 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
39 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
40 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
41 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
42 import org.opendaylight.yangtools.yang.parser.repo.YangTextSchemaContextResolver;
43 import org.opendaylight.yangtools.yang.parser.repo.YangTextSchemaSourceRegistration;
44 import org.opendaylight.yangtools.yang2sources.plugin.ConfigArg.CodeGeneratorArg;
45 import org.opendaylight.yangtools.yang2sources.plugin.Util.ContextHolder;
46 import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
47 import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
48 import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51 import org.sonatype.plexus.build.incremental.BuildContext;
52 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
53
54 class YangToSourcesProcessor {
55     private static final Logger LOG = LoggerFactory.getLogger(YangToSourcesProcessor.class);
56
57     static final String LOG_PREFIX = "yang-to-sources:";
58     private static final String META_INF_STR = "META-INF";
59     private static final String YANG_STR = "yang";
60
61     static final String META_INF_YANG_STRING = META_INF_STR + File.separator + YANG_STR;
62     static final String META_INF_YANG_STRING_JAR = META_INF_STR + "/" + YANG_STR;
63     static final String META_INF_YANG_SERVICES_STRING_JAR = META_INF_STR + "/" + "services";
64
65     private final File yangFilesRootDir;
66     private final Set<File> excludedFiles;
67     private final List<CodeGeneratorArg> codeGenerators;
68     private final MavenProject project;
69     private final boolean inspectDependencies;
70     private final BuildContext buildContext;
71     private final YangProvider yangProvider;
72
73     @VisibleForTesting
74     YangToSourcesProcessor(final File yangFilesRootDir, final Collection<File> excludedFiles,
75             final List<CodeGeneratorArg> codeGenerators, final MavenProject project, final boolean inspectDependencies,
76             final YangProvider yangProvider) {
77         this(new DefaultBuildContext(), yangFilesRootDir, excludedFiles, codeGenerators, project,
78                 inspectDependencies, yangProvider);
79     }
80
81     private YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
82             final Collection<File> excludedFiles, final List<CodeGeneratorArg> codeGenerators,
83             final MavenProject project, final boolean inspectDependencies, final YangProvider yangProvider) {
84         this.buildContext = Preconditions.checkNotNull(buildContext, "buildContext");
85         this.yangFilesRootDir = Preconditions.checkNotNull(yangFilesRootDir, "yangFilesRootDir");
86         this.excludedFiles = ImmutableSet.copyOf(excludedFiles);
87         this.codeGenerators = ImmutableList.copyOf(codeGenerators);
88         this.project = Preconditions.checkNotNull(project);
89         this.inspectDependencies = inspectDependencies;
90         this.yangProvider = yangProvider;
91     }
92
93     YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
94                 final Collection<File> excludedFiles, final List<CodeGeneratorArg> codeGenerators,
95                 final MavenProject project, final boolean inspectDependencies) {
96         this(yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, new YangProvider());
97     }
98
99     public void execute() throws MojoExecutionException, MojoFailureException {
100         ContextHolder context = processYang();
101         if (context != null) {
102             generateSources(context);
103             yangProvider.addYangsToMetaInf(project, yangFilesRootDir, excludedFiles);
104         }
105     }
106
107     void conditionalExecute(final boolean skip) throws MojoExecutionException, MojoFailureException {
108         if (skip) {
109             LOG.info("Skipping YANG code generation because property yang.skip is true");
110
111             // But manually add resources
112             // add META_INF/yang
113             yangProvider.addYangsToMetaInf(project, yangFilesRootDir, excludedFiles);
114
115             // add META_INF/services
116             File generatedServicesDir = new GeneratedDirectories(project).getYangServicesDir();
117             YangProvider.setResource(generatedServicesDir, project);
118             LOG.debug("{} Yang services files from: {} marked as resources: {}", LOG_PREFIX, generatedServicesDir,
119                     META_INF_YANG_SERVICES_STRING_JAR);
120
121
122         } else {
123             execute();
124         }
125     }
126
127     @SuppressWarnings("checkstyle:illegalCatch")
128     private ContextHolder processYang() throws MojoExecutionException {
129         LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
130         try {
131             /*
132              * Collect all files which affect YANG context. This includes all
133              * files in current project and optionally any jars/files in the
134              * dependencies.
135              */
136             final Collection<File> yangFilesInProject = Util.listFiles(yangFilesRootDir, excludedFiles);
137
138             final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
139             if (inspectDependencies) {
140                 allFiles.addAll(Util.findYangFilesInDependencies(project));
141             }
142
143             if (allFiles.isEmpty()) {
144                 LOG.info("{} No input files found", LOG_PREFIX);
145                 return null;
146             }
147
148             /*
149              * Check if any of the listed files changed. If no changes occurred,
150              * simply return null, which indicates and of execution.
151              */
152             boolean noChange = true;
153             for (final File f : allFiles) {
154                 if (buildContext.hasDelta(f)) {
155                     LOG.debug("{} buildContext {} indicates {} changed, forcing regeneration", LOG_PREFIX,
156                             buildContext, f);
157                     noChange = false;
158                 }
159             }
160
161             if (noChange) {
162                 LOG.info("{} None of {} input files changed", LOG_PREFIX, allFiles.size());
163                 return null;
164             }
165
166             final Builder<SourceIdentifier, String> b = ImmutableMap.builder();
167             final YangTextSchemaContextResolver resolver = YangTextSchemaContextResolver.create("maven-plugin");
168             for (final File f : yangFilesInProject) {
169                 final YangTextSchemaSourceRegistration reg = resolver.registerSource(YangTextSchemaSource.forFile(f));
170                 // Registration has an accurate identifier
171                 b.put(reg.getInstance().getIdentifier(), f.getName());
172             }
173
174             final Map<SourceIdentifier, String> sourcesInProject = b.build();
175
176             /**
177              * Set contains all modules generated from input sources. Number of
178              * modules may differ from number of sources due to submodules
179              * (parsed submodule's data are added to its parent module). Set
180              * cannot contains null values.
181              */
182             if (inspectDependencies) {
183                 final List<YangTextSchemaSource> sourcesInDependencies = Util.findYangFilesInDependenciesAsStream(
184                     project);
185                 for (YangTextSchemaSource s : toUniqueSources(sourcesInDependencies)) {
186                     resolver.registerSource(s);
187                 }
188             }
189
190             final SchemaContext schemaContext = resolver.trySchemaContext();
191             final Set<Module> projectYangModules = new HashSet<>();
192             final Map<Module, String> projectYangFiles = new HashMap<>();
193             for (Module module : schemaContext.getModules()) {
194                 final SourceIdentifier modId = moduleToIdentifier(module);
195                 LOG.debug("Looking for source {}", modId);
196                 final String file = sourcesInProject.get(modId);
197                 if (file != null) {
198                     LOG.debug("Module {} belongs to current project", module);
199                     projectYangModules.add(module);
200                     projectYangFiles.put(module, file);
201
202                     for (Module sub : module.getSubmodules()) {
203                         final SourceIdentifier subId = moduleToIdentifier(sub);
204                         final String subFile = sourcesInProject.get(subId);
205                         if (subFile != null) {
206                             LOG.debug("Submodule {} belongs to current project", sub);
207                             projectYangFiles.put(sub, subFile);
208                         } else {
209                             LOG.warn("Submodule {} not found in input files", sub);
210                         }
211                     }
212                 }
213             }
214
215             LOG.debug("Processed project files: {}", yangFilesInProject);
216             LOG.info("{} Project model files parsed: {}", LOG_PREFIX, yangFilesInProject.size());
217             return new ContextHolder(schemaContext, projectYangModules, projectYangFiles);
218         } catch (Exception e) {
219             // MojoExecutionException is thrown since execution cannot continue
220             LOG.error("{} Unable to parse {} files from {}", LOG_PREFIX, Util.YANG_SUFFIX, yangFilesRootDir, e);
221             Throwable rootCause = Throwables.getRootCause(e);
222             throw new MojoExecutionException(LOG_PREFIX + " Unable to parse " + Util.YANG_SUFFIX + " files from "
223                     + yangFilesRootDir, rootCause);
224         }
225     }
226
227     private static SourceIdentifier moduleToIdentifier(final Module module) {
228         final QNameModule mod = module.getQNameModule();
229         final Date rev = mod.getRevision();
230         final Optional<String> optRev;
231         if (!SimpleDateFormatUtil.DEFAULT_DATE_REV.equals(rev)) {
232             optRev = Optional.of(mod.getFormattedRevision());
233         } else {
234             optRev = Optional.absent();
235         }
236
237         return RevisionSourceIdentifier.create(module.getName(), optRev);
238     }
239
240     private static Collection<YangTextSchemaSource> toUniqueSources(final Collection<YangTextSchemaSource> sources)
241             throws IOException {
242         final Map<String, YangTextSchemaSource> byContent = new HashMap<>();
243         for (YangTextSchemaSource s : sources) {
244             try (Reader reader = s.asCharSource(StandardCharsets.UTF_8).openStream()) {
245                 final String contents = CharStreams.toString(reader);
246                 byContent.putIfAbsent(contents, s);
247             }
248         }
249         return byContent.values();
250     }
251
252     /**
253      * Call generate on every generator from plugin configuration.
254      */
255     @SuppressWarnings("checkstyle:illegalCatch")
256     private void generateSources(final ContextHolder context) throws MojoFailureException {
257         if (codeGenerators.size() == 0) {
258             LOG.warn("{} No code generators provided", LOG_PREFIX);
259             return;
260         }
261
262         final Map<String, String> thrown = new HashMap<>();
263         for (CodeGeneratorArg codeGenerator : codeGenerators) {
264             try {
265                 generateSourcesWithOneGenerator(context, codeGenerator);
266             } catch (Exception e) {
267                 // try other generators, exception will be thrown after
268                 LOG.error("{} Unable to generate sources with {} generator", LOG_PREFIX, codeGenerator
269                         .getCodeGeneratorClass(), e);
270                 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
271             }
272         }
273
274         if (!thrown.isEmpty()) {
275             String message = " One or more code generators failed, including failed list(generatorClass=exception) ";
276             LOG.error("{}" + message + "{}", LOG_PREFIX, thrown.toString());
277             throw new MojoFailureException(LOG_PREFIX + message + thrown.toString());
278         }
279     }
280
281     /**
282      * Instantiate generator from class and call required method.
283      */
284     private void generateSourcesWithOneGenerator(final ContextHolder context, final CodeGeneratorArg codeGeneratorCfg)
285             throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
286
287         codeGeneratorCfg.check();
288
289         final BasicCodeGenerator g = getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
290         LOG.info("{} Code generator instantiated from {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass());
291
292         final File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
293
294         if (outputDir == null) {
295             throw new NullPointerException("outputBaseDir is null. Please provide a valid outputBaseDir value in the "
296                     + "pom.xml");
297         }
298
299         project.addCompileSourceRoot(outputDir.getAbsolutePath());
300
301         LOG.info("{} Sources will be generated to {}", LOG_PREFIX, outputDir);
302         LOG.debug("{} Project root dir is {}", LOG_PREFIX, project.getBasedir());
303         LOG.debug("{} Additional configuration picked up for : {}: {}", LOG_PREFIX, codeGeneratorCfg
304                         .getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration());
305
306         if (g instanceof BuildContextAware) {
307             ((BuildContextAware)g).setBuildContext(buildContext);
308         }
309         if (g instanceof MavenProjectAware) {
310             ((MavenProjectAware)g).setMavenProject(project);
311         }
312         g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
313         File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
314
315         YangProvider.setResource(resourceBaseDir, project);
316         g.setResourceBaseDir(resourceBaseDir);
317         LOG.debug("{} Folder: {} marked as resources for generator: {}", LOG_PREFIX, resourceBaseDir,
318                 codeGeneratorCfg.getCodeGeneratorClass());
319
320         FileUtils.deleteDirectory(outputDir);
321         LOG.info("{} Succesfully deleted output directory {}", LOG_PREFIX, outputDir);
322
323         Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules(),
324             context::moduleToResourcePath);
325
326         LOG.info("{} Sources generated by {}: {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(), generated);
327     }
328
329     /**
330      * Instantiate object from fully qualified class name.
331      */
332     private static <T> T getInstance(final String codeGeneratorClass, final Class<T> baseType) throws
333             ClassNotFoundException, InstantiationException, IllegalAccessException {
334         final Class<?> clazz = Class.forName(codeGeneratorClass);
335
336         Preconditions.checkArgument(baseType.isAssignableFrom(clazz), "Code generator %s has to implement %s", clazz,
337             baseType);
338         return baseType.cast(clazz.newInstance());
339     }
340 }