2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang2sources.plugin;
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;
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;
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;
47 class YangToSourcesProcessor {
48 private static final Logger LOG = LoggerFactory.getLogger(YangToSourcesProcessor.class);
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";
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;
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);
71 private YangToSourcesProcessor(BuildContext buildContext, File yangFilesRootDir, File[] excludedFiles,
72 List<CodeGeneratorArg> codeGenerators, MavenProject project, boolean inspectDependencies, YangProvider
74 this.buildContext = Util.checkNotNull(buildContext, "buildContext");
75 this.yangFilesRootDir = Util.checkNotNull(yangFilesRootDir, "yangFilesRootDir");
76 this.excludedFiles = new File[excludedFiles.length];
78 for (File file : excludedFiles) {
79 this.excludedFiles[i++] = new File(file.getPath());
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");
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());
93 public void execute() throws MojoExecutionException, MojoFailureException {
94 ContextHolder context = processYang();
95 if (context != null) {
96 generateSources(context);
97 yangProvider.addYangsToMetaInf(project, yangFilesRootDir, excludedFiles);
101 void conditionalExecute(boolean skip) throws MojoExecutionException, MojoFailureException {
103 LOG.info("Skipping YANG code generation because property yang.skip is true");
105 // But manually add resources
107 yangProvider.addYangsToMetaInf(project, yangFilesRootDir, excludedFiles);
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);
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);
128 * Collect all files which affect YANG context. This includes all
129 * files in current project and optionally any jars/files in the
132 final Collection<File> yangFilesInProject = Util.listFiles(yangFilesRootDir, excludedFiles);
135 final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
136 if (inspectDependencies) {
137 allFiles.addAll(Util.findYangFilesInDependencies(project));
140 if (allFiles.isEmpty()) {
141 LOG.info("{} No input files found", LOG_PREFIX);
146 * Check if any of the listed files changed. If no changes occurred,
147 * simply return null, which indicates and of execution.
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,
159 LOG.info("{} None of {} input files changed", LOG_PREFIX, allFiles.size());
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()));
169 List<InputStream> all = new ArrayList<>();
170 all.addAll(yangsInProject);
171 closeables.addAll(yangsInProject);
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.
179 Set<Module> projectYangModules;
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);
190 resolveSchemaContext = reactor.buildEffective(all);
192 Set<Module> parsedAllYangModules = resolveSchemaContext.getModules();
193 projectYangModules = new HashSet<>();
194 for (Module module : parsedAllYangModules) {
195 final String path = module.getModuleSourcePath();
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);
209 for (AutoCloseable closeable : closeables) {
214 LOG.info("{} {} files parsed from {}", LOG_PREFIX, Util.YANG_SUFFIX.toUpperCase(), yangsInProject);
215 return new ContextHolder(resolveSchemaContext, projectYangModules);
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);
226 private List<InputStream> toStreamsWithoutDuplicates(List<YangSourceFromDependency> list) throws IOException {
227 ConcurrentMap<String, YangSourceFromDependency> byContent = Maps.newConcurrentMap();
229 for (YangSourceFromDependency yangFromDependency : list) {
230 try (InputStream dataStream = yangFromDependency.openStream()) {
231 String contents = IOUtils.toString(dataStream);
232 byContent.putIfAbsent(contents, yangFromDependency);
236 List<InputStream> inputs = new ArrayList<>(byContent.size());
237 for (YangSourceFromDependency entry : byContent.values()) {
238 inputs.add(entry.openStream());
243 static class YangProvider {
244 private static final Logger LOG = LoggerFactory.getLogger(YangProvider.class);
246 void addYangsToMetaInf(MavenProject project, File yangFilesRootDir, File[] excludedFiles)
247 throws MojoFailureException {
249 // copy project's src/main/yang/*.yang to target/generated-sources/yang/META-INF/yang/*.yang
251 File generatedYangDir = new File(project.getBasedir(), CodeGeneratorArg.YANG_GENERATED_DIR);
252 addYangsToMetaInf(project, yangFilesRootDir, excludedFiles, generatedYangDir);
254 // Also copy to the actual build output dir if different than "target". When running in
255 // Eclipse this can differ (eg "target-ide").
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);
264 private void addYangsToMetaInf(MavenProject project, File yangFilesRootDir,
265 File[] excludedFiles, File generatedYangDir)
266 throws MojoFailureException {
268 File withMetaInf = new File(generatedYangDir, META_INF_YANG_STRING);
269 withMetaInf.mkdirs();
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()));
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);
281 setResource(generatedYangDir, project);
283 LOG.debug("{} Yang files from: {} marked as resources: {}", LOG_PREFIX, yangFilesRootDir,
284 META_INF_YANG_STRING_JAR);
287 private static void setResource(File targetYangDir, MavenProject project) {
288 Resource res = new Resource();
289 res.setDirectory(targetYangDir.getPath());
290 project.addResource(res);
295 * Call generate on every generator from plugin configuration
297 private void generateSources(ContextHolder context) throws MojoFailureException {
298 if (codeGenerators.size() == 0) {
299 LOG.warn("{} No code generators provided", LOG_PREFIX);
303 Map<String, String> thrown = Maps.newHashMap();
304 for (CodeGeneratorArg codeGenerator : codeGenerators) {
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());
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());
323 * Instantiate generator from class and call required method
325 private void generateSourcesWithOneGenerator(ContextHolder context, CodeGeneratorArg codeGeneratorCfg)
326 throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
328 codeGeneratorCfg.check();
330 BasicCodeGenerator g = Util.getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
331 LOG.info("{} Code generator instantiated from {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass());
333 File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
335 if (outputDir != null) {
336 project.addCompileSourceRoot(outputDir.getAbsolutePath());
338 throw new NullPointerException("outputBaseDir is null. Please provide a valid outputBaseDir value in the " +
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());
347 if (g instanceof BuildContextAware) {
348 ((BuildContextAware)g).setBuildContext(buildContext);
350 if (g instanceof MavenProjectAware) {
351 ((MavenProjectAware)g).setMavenProject(project);
353 g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
354 File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
356 YangProvider.setResource(resourceBaseDir, project);
357 g.setResourceBaseDir(resourceBaseDir);
358 LOG.debug("{} Folder: {} marked as resources for generator: {}", LOG_PREFIX, resourceBaseDir,
359 codeGeneratorCfg.getCodeGeneratorClass());
361 Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules());
363 LOG.info("{} Sources generated by {}: {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(), generated);