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.Stopwatch;
16 import com.google.common.base.Throwables;
17 import com.google.common.collect.ImmutableList;
18 import com.google.common.collect.ImmutableSet;
20 import java.io.IOException;
21 import java.nio.file.Files;
22 import java.nio.file.Path;
23 import java.util.AbstractMap.SimpleImmutableEntry;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Comparator;
27 import java.util.HashMap;
28 import java.util.Iterator;
29 import java.util.List;
31 import java.util.Map.Entry;
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.parser.api.YangSyntaxErrorException;
44 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
45 import org.opendaylight.yangtools.yang.model.repo.api.StatementParserMode;
46 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
47 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.ASTSchemaSource;
48 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToASTTransformer;
49 import org.opendaylight.yangtools.yang2sources.plugin.ConfigArg.CodeGeneratorArg;
50 import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
51 import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator.ImportResolutionMode;
52 import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
53 import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56 import org.sonatype.plexus.build.incremental.BuildContext;
57 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
59 class YangToSourcesProcessor {
60 private static final Logger LOG = LoggerFactory.getLogger(YangToSourcesProcessor.class);
61 private static final YangParserFactory DEFAULT_PARSER_FACTORY;
64 final Iterator<YangParserFactory> it = ServiceLoader.load(YangParserFactory.class).iterator();
65 checkState(it.hasNext(), "Failed to find a YangParserFactory implementation");
66 DEFAULT_PARSER_FACTORY = it.next();
69 static final String LOG_PREFIX = "yang-to-sources:";
70 private static final String META_INF_STR = "META-INF";
71 private static final String YANG_STR = "yang";
73 static final String META_INF_YANG_STRING = META_INF_STR + File.separator + YANG_STR;
74 static final String META_INF_YANG_STRING_JAR = META_INF_STR + "/" + YANG_STR;
75 static final String META_INF_YANG_SERVICES_STRING_JAR = META_INF_STR + "/" + "services";
77 private final YangParserFactory parserFactory;
78 private final File yangFilesRootDir;
79 private final Set<File> excludedFiles;
80 private final List<CodeGeneratorArg> codeGeneratorArgs;
81 private final MavenProject project;
82 private final boolean inspectDependencies;
83 private final BuildContext buildContext;
84 private final YangProvider yangProvider;
86 private YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
87 final Collection<File> excludedFiles, final List<CodeGeneratorArg> codeGenerators,
88 final MavenProject project, final boolean inspectDependencies, final YangProvider yangProvider) {
89 this.buildContext = requireNonNull(buildContext, "buildContext");
90 this.yangFilesRootDir = requireNonNull(yangFilesRootDir, "yangFilesRootDir");
91 this.excludedFiles = ImmutableSet.copyOf(excludedFiles);
92 this.codeGeneratorArgs = ImmutableList.copyOf(codeGenerators);
93 this.project = requireNonNull(project);
94 this.inspectDependencies = inspectDependencies;
95 this.yangProvider = requireNonNull(yangProvider);
96 this.parserFactory = DEFAULT_PARSER_FACTORY;
100 YangToSourcesProcessor(final File yangFilesRootDir, final Collection<File> excludedFiles,
101 final List<CodeGeneratorArg> codeGenerators, final MavenProject project, final boolean inspectDependencies,
102 final YangProvider yangProvider) {
103 this(new DefaultBuildContext(), yangFilesRootDir, excludedFiles, codeGenerators, project,
104 inspectDependencies, yangProvider);
107 YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
108 final Collection<File> excludedFiles, final List<CodeGeneratorArg> codeGenerators,
109 final MavenProject project, final boolean inspectDependencies) {
110 this(buildContext, yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies,
111 YangProvider.getInstance());
114 public void execute() throws MojoExecutionException, MojoFailureException {
115 conditionalExecute(false);
118 void conditionalExecute(final boolean skip) throws MojoExecutionException, MojoFailureException {
120 * Collect all files which affect YANG context. This includes all
121 * files in current project and optionally any jars/files in the
124 final List<File> yangFilesInProject;
126 yangFilesInProject = listFiles(yangFilesRootDir, excludedFiles);
127 } catch (IOException e) {
128 throw new MojoFailureException("Failed to list project files", e);
131 if (yangFilesInProject.isEmpty()) {
132 // No files to process, skip.
133 LOG.info("{} No input files found", LOG_PREFIX);
137 // We need to instantiate all code generators to determine required import resolution mode
138 final List<Entry<CodeGeneratorArg, BasicCodeGenerator>> codeGenerators = instantiateGenerators();
139 final StatementParserMode importMode = determineRequiredImportMode(codeGenerators);
140 final Optional<ProcessorModuleReactor> optReactor = createReactor(importMode, yangFilesInProject);
141 if (!optReactor.isPresent()) {
145 final ProcessorModuleReactor reactor = optReactor.get();
147 final Stopwatch watch = Stopwatch.createStarted();
148 final ContextHolder holder;
151 holder = reactor.toContext();
152 } catch (YangParserException e) {
153 throw new MojoFailureException("Failed to process reactor " + reactor, e);
154 } catch (IOException e) {
155 throw new MojoExecutionException("Failed to read reactor " + reactor, e);
158 LOG.info("{} {} YANG models processed in {}", LOG_PREFIX, holder.getContext().getModules().size(), watch);
159 generateSources(holder, codeGenerators);
161 LOG.info("{} Skipping YANG code generation because property yang.skip is true", LOG_PREFIX);
165 final Collection<YangTextSchemaSource> models = reactor.getModelsInProject();
167 yangProvider.addYangsToMetaInf(project, models);
168 } catch (IOException e) {
169 throw new MojoExecutionException("Failed write model files for " + models, e);
172 // add META_INF/services
173 File generatedServicesDir = new GeneratedDirectories(project).getYangServicesDir();
174 YangProvider.setResource(generatedServicesDir, project);
175 LOG.debug("{} Yang services files from: {} marked as resources: {}", LOG_PREFIX, generatedServicesDir,
176 META_INF_YANG_SERVICES_STRING_JAR);
179 private static StatementParserMode determineRequiredImportMode(
180 final Collection<Entry<CodeGeneratorArg, BasicCodeGenerator>> codeGenerators) throws MojoFailureException {
181 ImportResolutionMode requestedMode = null;
182 BasicCodeGenerator requestingGenerator = null;
184 for (Entry<CodeGeneratorArg, BasicCodeGenerator> entry : codeGenerators) {
185 final BasicCodeGenerator generator = entry.getValue();
186 final ImportResolutionMode mode = generator.getImportResolutionMode();
188 // the generator does not care about the mode
192 if (requestedMode == null) {
193 // No mode yet, we have just determined it
194 requestedMode = mode;
195 requestingGenerator = generator;
199 if (mode != requestedMode) {
200 throw new MojoFailureException(String.format(
201 "Import resolution mode conflict between %s (%s) and %s (%s)", requestingGenerator, requestedMode,
206 if (requestedMode == null) {
207 return StatementParserMode.DEFAULT_MODE;
209 switch (requestedMode) {
210 case REVISION_EXACT_OR_LATEST:
211 return StatementParserMode.DEFAULT_MODE;
213 return StatementParserMode.SEMVER_MODE;
215 throw new IllegalStateException("Unhandled import resolution mode " + requestedMode);
219 private List<Entry<CodeGeneratorArg, BasicCodeGenerator>> instantiateGenerators() throws MojoExecutionException {
220 final List<Entry<CodeGeneratorArg, BasicCodeGenerator>> generators = new ArrayList<>(codeGeneratorArgs.size());
221 for (CodeGeneratorArg arg : codeGeneratorArgs) {
224 final BasicCodeGenerator generator;
226 generator = getInstance(arg.getCodeGeneratorClass(), BasicCodeGenerator.class);
227 } catch (ReflectiveOperationException e) {
228 throw new MojoExecutionException("Failed to instantiate code generator "
229 + arg.getCodeGeneratorClass(), e);
232 LOG.info("{} Code generator instantiated from {}", LOG_PREFIX, arg.getCodeGeneratorClass());
233 generators.add(new SimpleImmutableEntry<>(arg, generator));
239 @SuppressWarnings("checkstyle:illegalCatch")
240 private Optional<ProcessorModuleReactor> createReactor(final StatementParserMode parserMode,
241 final List<File> yangFilesInProject) throws MojoExecutionException {
242 LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
245 final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
246 final Collection<ScannedDependency> dependencies;
247 if (inspectDependencies) {
248 dependencies = new ArrayList<>();
249 final Stopwatch watch = Stopwatch.createStarted();
250 ScannedDependency.scanDependencies(project).forEach(dep -> {
251 allFiles.add(dep.file());
252 dependencies.add(dep);
254 LOG.info("{} Found {} dependencies in {}", LOG_PREFIX, dependencies.size(), watch);
256 dependencies = ImmutableList.of();
260 * Check if any of the listed files changed. If no changes occurred,
261 * simply return null, which indicates and of execution.
263 final Stopwatch watch = Stopwatch.createStarted();
264 if (!allFiles.stream().anyMatch(buildContext::hasDelta)) {
265 LOG.info("{} None of {} input files changed", LOG_PREFIX, allFiles.size());
266 return Optional.empty();
269 final YangParser parser = parserFactory.createParser(parserMode);
270 final List<YangTextSchemaSource> sourcesInProject = new ArrayList<>(yangFilesInProject.size());
272 final List<Entry<YangTextSchemaSource, ASTSchemaSource>> parsed = yangFilesInProject.parallelStream()
274 final YangTextSchemaSource textSource = YangTextSchemaSource.forFile(file);
276 return new SimpleImmutableEntry<>(textSource,
277 TextToASTTransformer.transformText(textSource));
278 } catch (YangSyntaxErrorException | SchemaSourceException | IOException e) {
279 throw new IllegalArgumentException("Failed to parse " + file, e);
282 .collect(Collectors.toList());
284 for (final Entry<YangTextSchemaSource, ASTSchemaSource> entry : parsed) {
285 final YangTextSchemaSource textSource = entry.getKey();
286 final ASTSchemaSource astSource = entry.getValue();
287 parser.addSource(astSource);
289 if (!astSource.getIdentifier().equals(textSource.getIdentifier())) {
290 // AST indicates a different source identifier, make sure we use that
291 sourcesInProject.add(YangTextSchemaSource.delegateForByteSource(astSource.getIdentifier(),
294 sourcesInProject.add(textSource);
298 LOG.debug("Found project files: {}", yangFilesInProject);
299 LOG.info("{} Project model files found: {} in {}", LOG_PREFIX, yangFilesInProject.size(), watch);
301 final ProcessorModuleReactor reactor = new ProcessorModuleReactor(parser, sourcesInProject, dependencies);
302 LOG.debug("Initialized reactor {} with {}", reactor, yangFilesInProject);
303 return Optional.of(reactor);
304 } catch (IOException | YangSyntaxErrorException | RuntimeException e) {
305 // MojoExecutionException is thrown since execution cannot continue
306 LOG.error("{} Unable to parse YANG files from {}", LOG_PREFIX, yangFilesRootDir, e);
307 Throwable rootCause = Throwables.getRootCause(e);
308 throw new MojoExecutionException(LOG_PREFIX + " Unable to parse YANG files from " + yangFilesRootDir,
313 private static List<File> listFiles(final File root, final Collection<File> excludedFiles)
315 if (!root.isDirectory()) {
316 LOG.warn("{} YANG source directory {} not found. No code will be generated.", LOG_PREFIX, root);
317 return ImmutableList.of();
320 return Files.walk(root.toPath()).map(Path::toFile).filter(File::isFile).filter(f -> {
321 if (excludedFiles.contains(f)) {
322 LOG.info("{} YANG file excluded {}", LOG_PREFIX, f);
326 }).filter(f -> f.getName().endsWith(YangConstants.RFC6020_YANG_FILE_EXTENSION)).collect(Collectors.toList());
330 * Call generate on every generator from plugin configuration.
332 @SuppressWarnings("checkstyle:illegalCatch")
333 private void generateSources(final ContextHolder context,
334 final Collection<Entry<CodeGeneratorArg, BasicCodeGenerator>> generators) throws MojoFailureException {
335 if (generators.isEmpty()) {
336 LOG.warn("{} No code generators provided", LOG_PREFIX);
340 final Map<String, String> thrown = new HashMap<>();
341 for (Entry<CodeGeneratorArg, BasicCodeGenerator> entry : generators) {
342 final String codeGeneratorClass = entry.getKey().getCodeGeneratorClass();
345 generateSourcesWithOneGenerator(context, entry.getKey(), entry.getValue());
346 } catch (Exception e) {
347 // try other generators, exception will be thrown after
348 LOG.error("{} Unable to generate sources with {} generator", LOG_PREFIX, codeGeneratorClass, e);
349 thrown.put(codeGeneratorClass, e.getClass().getCanonicalName());
353 if (!thrown.isEmpty()) {
354 LOG.error("{} One or more code generators failed, including failed list(generatorClass=exception) {}",
356 throw new MojoFailureException(LOG_PREFIX
357 + " One or more code generators failed, including failed list(generatorClass=exception) " + thrown);
362 * Complete initialization of a code generator and invoke it.
364 private void generateSourcesWithOneGenerator(final ContextHolder context, final CodeGeneratorArg codeGeneratorCfg,
365 final BasicCodeGenerator codeGenerator) throws IOException {
367 final File outputDir = requireNonNull(codeGeneratorCfg.getOutputBaseDir(project),
368 "outputBaseDir is null. Please provide a valid outputBaseDir value in pom.xml");
370 project.addCompileSourceRoot(outputDir.getAbsolutePath());
372 LOG.info("{} Sources will be generated to {}", LOG_PREFIX, outputDir);
373 LOG.debug("{} Project root dir is {}", LOG_PREFIX, project.getBasedir());
374 LOG.debug("{} Additional configuration picked up for : {}: {}", LOG_PREFIX, codeGeneratorCfg
375 .getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration());
377 if (codeGenerator instanceof BuildContextAware) {
378 ((BuildContextAware)codeGenerator).setBuildContext(buildContext);
380 if (codeGenerator instanceof MavenProjectAware) {
381 ((MavenProjectAware)codeGenerator).setMavenProject(project);
383 codeGenerator.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
385 File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
386 YangProvider.setResource(resourceBaseDir, project);
387 codeGenerator.setResourceBaseDir(resourceBaseDir);
388 LOG.debug("{} Folder: {} marked as resources for generator: {}", LOG_PREFIX, resourceBaseDir,
389 codeGeneratorCfg.getCodeGeneratorClass());
391 if (outputDir.exists()) {
392 Files.walk(outputDir.toPath()).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
393 LOG.info("{} Succesfully deleted output directory {}", LOG_PREFIX, outputDir);
395 final Stopwatch watch = Stopwatch.createStarted();
396 Collection<File> generated = codeGenerator.generateSources(context.getContext(), outputDir,
397 context.getYangModules(), context::moduleToResourcePath);
399 LOG.debug("{} Sources generated by {}: {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(), generated);
400 LOG.info("{} Sources generated by {}: {} in {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(),
401 generated == null ? 0 : generated.size(), watch);
405 * Instantiate object from fully qualified class name.
407 private static <T> T getInstance(final String codeGeneratorClass, final Class<T> baseType)
408 throws ReflectiveOperationException {
409 final Class<?> clazz = Class.forName(codeGeneratorClass);
410 checkArgument(baseType.isAssignableFrom(clazz), "Code generator %s has to implement %s", clazz, baseType);
411 return baseType.cast(clazz.getConstructor().newInstance());