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 static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static java.util.Objects.requireNonNull;
14 import com.google.common.annotations.VisibleForTesting;
15 import com.google.common.base.Throwables;
16 import com.google.common.collect.ImmutableList;
17 import com.google.common.collect.ImmutableSet;
18 import com.google.common.io.CharStreams;
20 import java.io.IOException;
21 import java.io.Reader;
22 import java.nio.charset.StandardCharsets;
23 import java.nio.file.Files;
24 import java.nio.file.Path;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.Comparator;
28 import java.util.HashMap;
29 import java.util.Iterator;
30 import java.util.List;
32 import java.util.Optional;
33 import java.util.ServiceLoader;
35 import java.util.stream.Collectors;
36 import org.apache.maven.plugin.MojoExecutionException;
37 import org.apache.maven.plugin.MojoFailureException;
38 import org.apache.maven.project.MavenProject;
39 import org.opendaylight.yangtools.yang.common.YangConstants;
40 import org.opendaylight.yangtools.yang.model.parser.api.YangParser;
41 import org.opendaylight.yangtools.yang.model.parser.api.YangParserException;
42 import org.opendaylight.yangtools.yang.model.parser.api.YangParserFactory;
43 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
44 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.ASTSchemaSource;
45 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToASTTransformer;
46 import org.opendaylight.yangtools.yang2sources.plugin.ConfigArg.CodeGeneratorArg;
47 import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
48 import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
49 import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52 import org.sonatype.plexus.build.incremental.BuildContext;
53 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
55 class YangToSourcesProcessor {
56 private static final Logger LOG = LoggerFactory.getLogger(YangToSourcesProcessor.class);
57 private static final YangParserFactory DEFAULT_PARSER_FACTORY;
60 final Iterator<YangParserFactory> it = ServiceLoader.load(YangParserFactory.class).iterator();
61 checkState(it.hasNext(), "Failed to find a YangParserFactory implementation");
62 DEFAULT_PARSER_FACTORY = it.next();
65 static final String LOG_PREFIX = "yang-to-sources:";
66 private static final String META_INF_STR = "META-INF";
67 private static final String YANG_STR = "yang";
69 static final String META_INF_YANG_STRING = META_INF_STR + File.separator + YANG_STR;
70 static final String META_INF_YANG_STRING_JAR = META_INF_STR + "/" + YANG_STR;
71 static final String META_INF_YANG_SERVICES_STRING_JAR = META_INF_STR + "/" + "services";
73 private final YangParserFactory parserFactory;
74 private final File yangFilesRootDir;
75 private final Set<File> excludedFiles;
76 private final List<CodeGeneratorArg> codeGenerators;
77 private final MavenProject project;
78 private final boolean inspectDependencies;
79 private final BuildContext buildContext;
80 private final YangProvider yangProvider;
82 private YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
83 final Collection<File> excludedFiles, final List<CodeGeneratorArg> codeGenerators,
84 final MavenProject project, final boolean inspectDependencies, final YangProvider yangProvider) {
85 this.buildContext = requireNonNull(buildContext, "buildContext");
86 this.yangFilesRootDir = requireNonNull(yangFilesRootDir, "yangFilesRootDir");
87 this.excludedFiles = ImmutableSet.copyOf(excludedFiles);
88 this.codeGenerators = ImmutableList.copyOf(codeGenerators);
89 this.project = requireNonNull(project);
90 this.inspectDependencies = inspectDependencies;
91 this.yangProvider = requireNonNull(yangProvider);
92 this.parserFactory = DEFAULT_PARSER_FACTORY;
96 YangToSourcesProcessor(final File yangFilesRootDir, final Collection<File> excludedFiles,
97 final List<CodeGeneratorArg> codeGenerators, final MavenProject project, final boolean inspectDependencies,
98 final YangProvider yangProvider) {
99 this(new DefaultBuildContext(), yangFilesRootDir, excludedFiles, codeGenerators, project,
100 inspectDependencies, yangProvider);
103 YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
104 final Collection<File> excludedFiles, final List<CodeGeneratorArg> codeGenerators,
105 final MavenProject project, final boolean inspectDependencies) {
106 this(yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, YangProvider.getInstance());
109 public void execute() throws MojoExecutionException, MojoFailureException {
110 conditionalExecute(false);
113 void conditionalExecute(final boolean skip) throws MojoExecutionException, MojoFailureException {
114 final Optional<ProcessorModuleReactor> optReactor = createReactor();
115 if (!optReactor.isPresent()) {
119 final ProcessorModuleReactor reactor = optReactor.get();
121 final ContextHolder holder;
124 holder = createContextHolder(reactor);
125 } catch (YangParserException e) {
126 throw new MojoFailureException("Failed to process reactor " + reactor, e);
127 } catch (IOException e) {
128 throw new MojoExecutionException("Failed to read reactor " + reactor, e);
131 generateSources(holder);
133 LOG.info("Skipping YANG code generation because property yang.skip is true");
137 final Collection<YangTextSchemaSource> models = reactor.getModelsInProject();
139 yangProvider.addYangsToMetaInf(project, models);
140 } catch (IOException e) {
141 throw new MojoExecutionException("Failed write model files for " + models, e);
144 // add META_INF/services
145 File generatedServicesDir = new GeneratedDirectories(project).getYangServicesDir();
146 YangProvider.setResource(generatedServicesDir, project);
147 LOG.debug("{} Yang services files from: {} marked as resources: {}", LOG_PREFIX, generatedServicesDir,
148 META_INF_YANG_SERVICES_STRING_JAR);
151 @SuppressWarnings("checkstyle:illegalCatch")
152 private Optional<ProcessorModuleReactor> createReactor() throws MojoExecutionException {
153 LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
156 * Collect all files which affect YANG context. This includes all
157 * files in current project and optionally any jars/files in the
160 final Collection<File> yangFilesInProject = listFiles(yangFilesRootDir, excludedFiles);
162 final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
163 if (inspectDependencies) {
164 allFiles.addAll(Util.findYangFilesInDependencies(project));
167 if (allFiles.isEmpty()) {
168 LOG.info("{} No input files found", LOG_PREFIX);
169 return Optional.empty();
173 * Check if any of the listed files changed. If no changes occurred,
174 * simply return null, which indicates and of execution.
176 if (!allFiles.stream().anyMatch(buildContext::hasDelta)) {
177 LOG.info("{} None of {} input files changed", LOG_PREFIX, allFiles.size());
178 return Optional.empty();
181 // FIXME: add correct mode
182 final YangParser parser = parserFactory.createParser();
183 final List<YangTextSchemaSource> sourcesInProject = new ArrayList<>(yangFilesInProject.size());
184 for (final File f : yangFilesInProject) {
185 final YangTextSchemaSource textSource = YangTextSchemaSource.forFile(f);
186 final ASTSchemaSource astSource = TextToASTTransformer.transformText(textSource);
188 parser.addSource(astSource);
190 if (!astSource.getIdentifier().equals(textSource.getIdentifier())) {
191 // AST indicates a different source identifier, make sure we use that
192 sourcesInProject.add(YangTextSchemaSource.delegateForByteSource(astSource.getIdentifier(),
195 sourcesInProject.add(textSource);
199 LOG.debug("Processed project files: {}", yangFilesInProject);
200 LOG.info("{} Project model files parsed: {}", LOG_PREFIX, yangFilesInProject.size());
202 final ProcessorModuleReactor reactor = new ProcessorModuleReactor(parser, sourcesInProject);
203 LOG.debug("Initialized reactor {}", reactor, yangFilesInProject);
204 return Optional.of(reactor);
205 } catch (Exception e) {
206 // MojoExecutionException is thrown since execution cannot continue
207 LOG.error("{} Unable to parse YANG files from {}", LOG_PREFIX, yangFilesRootDir, e);
208 Throwable rootCause = Throwables.getRootCause(e);
209 throw new MojoExecutionException(LOG_PREFIX + " Unable to parse YANG files from " + yangFilesRootDir,
214 private ContextHolder createContextHolder(final ProcessorModuleReactor reactor) throws MojoFailureException,
215 IOException, YangParserException {
217 * Set contains all modules generated from input sources. Number of
218 * modules may differ from number of sources due to submodules
219 * (parsed submodule's data are added to its parent module). Set
220 * cannot contains null values.
222 if (inspectDependencies) {
223 final List<YangTextSchemaSource> sourcesInDependencies = Util.findYangFilesInDependenciesAsStream(
225 for (YangTextSchemaSource s : toUniqueSources(sourcesInDependencies)) {
226 reactor.registerSourceFromDependency(s);
230 return reactor.toContext();
233 private static Collection<File> listFiles(final File root, final Collection<File> excludedFiles)
235 if (!root.isDirectory()) {
236 LOG.warn("{} YANG source directory {} not found. No code will be generated.", LOG_PREFIX, root);
237 return ImmutableList.of();
240 return Files.walk(root.toPath()).map(Path::toFile).filter(File::isFile).filter(f -> {
241 if (excludedFiles.contains(f)) {
242 LOG.info("{} YANG file excluded {}", LOG_PREFIX, f);
246 }).filter(f -> f.getName().endsWith(YangConstants.RFC6020_YANG_FILE_EXTENSION)).collect(Collectors.toList());
249 private static Collection<YangTextSchemaSource> toUniqueSources(final Collection<YangTextSchemaSource> sources)
251 final Map<String, YangTextSchemaSource> byContent = new HashMap<>();
252 for (YangTextSchemaSource s : sources) {
253 try (Reader reader = s.asCharSource(StandardCharsets.UTF_8).openStream()) {
254 final String contents = CharStreams.toString(reader);
255 byContent.putIfAbsent(contents, s);
258 return byContent.values();
262 * Call generate on every generator from plugin configuration.
264 @SuppressWarnings("checkstyle:illegalCatch")
265 private void generateSources(final ContextHolder context) throws MojoFailureException {
266 if (codeGenerators.isEmpty()) {
267 LOG.warn("{} No code generators provided", LOG_PREFIX);
271 final Map<String, String> thrown = new HashMap<>();
272 for (CodeGeneratorArg codeGenerator : codeGenerators) {
274 generateSourcesWithOneGenerator(context, codeGenerator);
275 } catch (Exception e) {
276 // try other generators, exception will be thrown after
277 LOG.error("{} Unable to generate sources with {} generator", LOG_PREFIX, codeGenerator
278 .getCodeGeneratorClass(), e);
279 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
283 if (!thrown.isEmpty()) {
284 String message = " One or more code generators failed, including failed list(generatorClass=exception) ";
285 LOG.error("{}{}{}", LOG_PREFIX, message, thrown.toString());
286 throw new MojoFailureException(LOG_PREFIX + message + thrown.toString());
291 * Instantiate generator from class and call required method.
293 private void generateSourcesWithOneGenerator(final ContextHolder context, final CodeGeneratorArg codeGeneratorCfg)
294 throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
296 codeGeneratorCfg.check();
298 final BasicCodeGenerator g = getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
299 LOG.info("{} Code generator instantiated from {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass());
301 final File outputDir = requireNonNull(codeGeneratorCfg.getOutputBaseDir(project),
302 "outputBaseDir is null. Please provide a valid outputBaseDir value in pom.xml");
304 project.addCompileSourceRoot(outputDir.getAbsolutePath());
306 LOG.info("{} Sources will be generated to {}", LOG_PREFIX, outputDir);
307 LOG.debug("{} Project root dir is {}", LOG_PREFIX, project.getBasedir());
308 LOG.debug("{} Additional configuration picked up for : {}: {}", LOG_PREFIX, codeGeneratorCfg
309 .getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration());
311 if (g instanceof BuildContextAware) {
312 ((BuildContextAware)g).setBuildContext(buildContext);
314 if (g instanceof MavenProjectAware) {
315 ((MavenProjectAware)g).setMavenProject(project);
317 g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
318 File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
320 YangProvider.setResource(resourceBaseDir, project);
321 g.setResourceBaseDir(resourceBaseDir);
322 LOG.debug("{} Folder: {} marked as resources for generator: {}", LOG_PREFIX, resourceBaseDir,
323 codeGeneratorCfg.getCodeGeneratorClass());
325 if (outputDir.exists()) {
326 Files.walk(outputDir.toPath()).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
327 LOG.info("{} Succesfully deleted output directory {}", LOG_PREFIX, outputDir);
329 Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules(),
330 context::moduleToResourcePath);
332 LOG.info("{} Sources generated by {}: {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(), generated);
336 * Instantiate object from fully qualified class name.
338 private static <T> T getInstance(final String codeGeneratorClass, final Class<T> baseType) throws
339 ClassNotFoundException, InstantiationException, IllegalAccessException {
340 final Class<?> clazz = Class.forName(codeGeneratorClass);
341 checkArgument(baseType.isAssignableFrom(clazz), "Code generator %s has to implement %s", clazz, baseType);
342 return baseType.cast(clazz.newInstance());