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.checkState;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.base.Stopwatch;
15 import com.google.common.base.Throwables;
16 import com.google.common.collect.ImmutableList;
17 import com.google.common.collect.ImmutableMap;
18 import com.google.common.collect.ImmutableSet;
19 import com.google.common.collect.Maps;
21 import java.io.IOException;
22 import java.nio.file.Files;
23 import java.nio.file.Path;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Iterator;
27 import java.util.LinkedHashMap;
28 import java.util.List;
30 import java.util.Map.Entry;
31 import java.util.Optional;
32 import java.util.ServiceLoader;
34 import java.util.stream.Collectors;
35 import org.apache.maven.plugin.MojoExecutionException;
36 import org.apache.maven.plugin.MojoFailureException;
37 import org.apache.maven.project.MavenProject;
38 import org.eclipse.jdt.annotation.NonNull;
39 import org.opendaylight.yangtools.plugin.generator.api.FileGeneratorException;
40 import org.opendaylight.yangtools.plugin.generator.api.FileGeneratorFactory;
41 import org.opendaylight.yangtools.yang.common.YangConstants;
42 import org.opendaylight.yangtools.yang.model.repo.api.YangIRSchemaSource;
43 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
44 import org.opendaylight.yangtools.yang.parser.api.YangParser;
45 import org.opendaylight.yangtools.yang.parser.api.YangParserConfiguration;
46 import org.opendaylight.yangtools.yang.parser.api.YangParserException;
47 import org.opendaylight.yangtools.yang.parser.api.YangParserFactory;
48 import org.opendaylight.yangtools.yang.parser.api.YangSyntaxErrorException;
49 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToIRTransformer;
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";
68 private static final String BUILD_CONTEXT_STATE_NAME = YangToSourcesProcessor.class.getName();
70 static final String META_INF_YANG_STRING = META_INF_STR + File.separator + YANG_STR;
71 static final String META_INF_YANG_STRING_JAR = META_INF_STR + "/" + YANG_STR;
72 static final String META_INF_YANG_SERVICES_STRING_JAR = META_INF_STR + "/" + "services";
74 private final YangParserFactory parserFactory;
75 private final File yangFilesRootDir;
76 private final Set<File> excludedFiles;
77 private final ImmutableMap<String, FileGeneratorArg> fileGeneratorArgs;
78 private final @NonNull MavenProject project;
79 private final boolean inspectDependencies;
80 private final BuildContext buildContext;
81 private final YangProvider yangProvider;
83 private YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
84 final Collection<File> excludedFiles, final List<FileGeneratorArg> fileGeneratorsArgs,
85 final MavenProject project, final boolean inspectDependencies, final YangProvider yangProvider) {
86 this.buildContext = requireNonNull(buildContext, "buildContext");
87 this.yangFilesRootDir = requireNonNull(yangFilesRootDir, "yangFilesRootDir");
88 this.excludedFiles = ImmutableSet.copyOf(excludedFiles);
89 //FIXME multiple FileGeneratorArg entries of same identifier became one here
90 fileGeneratorArgs = Maps.uniqueIndex(fileGeneratorsArgs, FileGeneratorArg::getIdentifier);
91 this.project = requireNonNull(project);
92 this.inspectDependencies = inspectDependencies;
93 this.yangProvider = requireNonNull(yangProvider);
94 parserFactory = DEFAULT_PARSER_FACTORY;
98 YangToSourcesProcessor(final File yangFilesRootDir, final Collection<File> excludedFiles,
99 final List<FileGeneratorArg> fileGenerators, final MavenProject project, final boolean inspectDependencies,
100 final YangProvider yangProvider) {
101 this(new DefaultBuildContext(), yangFilesRootDir, excludedFiles, ImmutableList.of(),
102 project, inspectDependencies, yangProvider);
105 YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
106 final Collection<File> excludedFiles, final List<FileGeneratorArg> fileGenerators,
107 final MavenProject project, final boolean inspectDependencies) {
108 this(buildContext, yangFilesRootDir, excludedFiles, fileGenerators, project, inspectDependencies,
109 YangProvider.getInstance());
112 public void execute() throws MojoExecutionException, MojoFailureException {
113 conditionalExecute(false);
116 void conditionalExecute(final boolean skip) throws MojoExecutionException, MojoFailureException {
117 var prevState = buildContext.getValue(BUILD_CONTEXT_STATE_NAME);
118 if (prevState == null) {
119 LOG.debug("{} BuildContext did not provide state", LOG_PREFIX);
120 // FIXME: look for persisted state and restore it
123 // Collect all files in the current project.
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<GeneratorTaskFactory> codeGenerators = instantiateGenerators();
139 if (codeGenerators.isEmpty()) {
140 LOG.warn("{} No code generators provided", LOG_PREFIX);
144 final Set<YangParserConfiguration> parserConfigs = codeGenerators.stream()
145 .map(GeneratorTaskFactory::parserConfig)
146 .collect(Collectors.toUnmodifiableSet());
148 LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
150 // All files which affect YANG context. This minimally includes all files in the current project, but optionally
151 // may include any YANG files in the dependencies.
152 final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
153 final Collection<ScannedDependency> dependencies;
154 if (inspectDependencies) {
155 dependencies = new ArrayList<>();
156 final Stopwatch watch = Stopwatch.createStarted();
159 ScannedDependency.scanDependencies(project).forEach(dep -> {
160 allFiles.add(dep.file());
161 dependencies.add(dep);
163 } catch (IOException e) {
164 LOG.error("{} Failed to scan dependencies", LOG_PREFIX, e);
165 throw new MojoExecutionException(LOG_PREFIX + " Failed to scan dependencies ", e);
167 LOG.info("{} Found {} dependencies in {}", LOG_PREFIX, dependencies.size(), watch);
169 dependencies = ImmutableList.of();
173 * Check if any of the listed files changed. If no changes occurred, simply return empty, which indicates
176 if (!allFiles.stream().anyMatch(buildContext::hasDelta)) {
177 LOG.info("{} None of {} input files changed", LOG_PREFIX, allFiles.size());
181 final Stopwatch watch = Stopwatch.createStarted();
182 final List<Entry<YangTextSchemaSource, YangIRSchemaSource>> parsed = yangFilesInProject.parallelStream()
184 final YangTextSchemaSource textSource = YangTextSchemaSource.forPath(file.toPath());
186 return Map.entry(textSource, TextToIRTransformer.transformText(textSource));
187 } catch (YangSyntaxErrorException | IOException e) {
188 throw new IllegalArgumentException("Failed to parse " + file, e);
191 .collect(Collectors.toList());
192 LOG.debug("Found project files: {}", yangFilesInProject);
193 LOG.info("{} Project model files found: {} in {}", LOG_PREFIX, yangFilesInProject.size(), watch);
195 final var outputFiles = ImmutableList.<FileState>builder();
196 boolean sourcesPersisted = false;
198 for (YangParserConfiguration parserConfig : parserConfigs) {
199 final Optional<ProcessorModuleReactor> optReactor = createReactor(yangFilesInProject,
200 parserConfig, dependencies, parsed);
201 if (optReactor.isPresent()) {
202 final ProcessorModuleReactor reactor = optReactor.orElseThrow();
205 final Stopwatch sw = Stopwatch.createStarted();
206 final ContextHolder holder;
209 holder = reactor.toContext();
210 } catch (YangParserException e) {
211 throw new MojoFailureException("Failed to process reactor " + reactor, e);
212 } catch (IOException e) {
213 throw new MojoExecutionException("Failed to read reactor " + reactor, e);
216 LOG.info("{} {} YANG models processed in {}", LOG_PREFIX, holder.getContext().getModules().size(),
218 outputFiles.addAll(generateSources(holder, codeGenerators, parserConfig));
220 if (!sourcesPersisted) {
221 // add META_INF/yang once
222 final var models = reactor.getModelsInProject();
223 final Collection<FileState> sourceFileStates;
225 sourceFileStates = yangProvider.addYangsToMetaInf(project, models);
226 } catch (IOException e) {
227 throw new MojoExecutionException("Failed write model files for " + models, e);
230 sourcesPersisted = true;
231 outputFiles.addAll(sourceFileStates);
234 LOG.info("{} Skipping YANG code generation because property yang.skip is true", LOG_PREFIX);
239 // add META_INF/services
240 File generatedServicesDir = new GeneratedDirectories(project).getYangServicesDir();
241 YangProvider.setResource(generatedServicesDir, project);
242 LOG.debug("{} Yang services files from: {} marked as resources: {}", LOG_PREFIX, generatedServicesDir,
243 META_INF_YANG_SERVICES_STRING_JAR);
245 final var uniqueOutputFiles = new LinkedHashMap<String, FileState>();
246 for (var fileHash : outputFiles.build()) {
247 final var prev = uniqueOutputFiles.putIfAbsent(fileHash.path(), fileHash);
249 throw new MojoFailureException("Duplicate files " + prev + " and " + fileHash);
253 // FIXME: store these files into state, so that we can verify/clean up
254 final var outputState = new YangToSourcesState(
255 codeGenerators.stream()
256 .collect(ImmutableMap.toImmutableMap(GeneratorTaskFactory::getIdentifier, GeneratorTaskFactory::arg)),
257 new FileStateSet(ImmutableMap.copyOf(uniqueOutputFiles)));
258 buildContext.setValue(BUILD_CONTEXT_STATE_NAME, outputState);
259 if (buildContext.getValue(BUILD_CONTEXT_STATE_NAME) == null) {
260 LOG.debug("{} BuildContext did not retain state, persisting", LOG_PREFIX);
261 // FIXME: persist in target/ directory (there is a maven best practice where)
265 private List<GeneratorTaskFactory> instantiateGenerators() throws MojoExecutionException {
266 // Search for available FileGenerator implementations
267 final Map<String, FileGeneratorFactory> factories = Maps.uniqueIndex(
268 ServiceLoader.load(FileGeneratorFactory.class), FileGeneratorFactory::getIdentifier);
270 // FIXME: iterate over fileGeneratorArg instances (configuration), not factories (environment)
271 // Assign instantiate FileGenerators with appropriate configuration
272 final List<GeneratorTaskFactory> generators = new ArrayList<>(factories.size());
273 for (Entry<String, FileGeneratorFactory> entry : factories.entrySet()) {
274 final String id = entry.getKey();
275 FileGeneratorArg arg = fileGeneratorArgs.get(id);
277 LOG.debug("{} No configuration for {}, using empty", LOG_PREFIX, id);
278 arg = new FileGeneratorArg(id);
282 generators.add(GeneratorTaskFactory.of(entry.getValue(), arg));
283 } catch (FileGeneratorException e) {
284 throw new MojoExecutionException("File generator " + id + " failed", e);
286 LOG.info("{} Code generator {} instantiated", LOG_PREFIX, id);
289 // Notify if no factory found for defined identifiers
290 fileGeneratorArgs.keySet().forEach(
291 fileGenIdentifier -> {
292 if (!factories.containsKey(fileGenIdentifier)) {
293 LOG.warn("{} No generator found for identifier {}", LOG_PREFIX, fileGenIdentifier);
301 @SuppressWarnings("checkstyle:illegalCatch")
302 private Optional<ProcessorModuleReactor> createReactor(final List<File> yangFilesInProject,
303 final YangParserConfiguration parserConfig, final Collection<ScannedDependency> dependencies,
304 final List<Entry<YangTextSchemaSource, YangIRSchemaSource>> parsed) throws MojoExecutionException {
307 final List<YangTextSchemaSource> sourcesInProject = new ArrayList<>(yangFilesInProject.size());
308 final YangParser parser = parserFactory.createParser(parserConfig);
309 for (final Entry<YangTextSchemaSource, YangIRSchemaSource> entry : parsed) {
310 final YangTextSchemaSource textSource = entry.getKey();
311 final YangIRSchemaSource astSource = entry.getValue();
312 parser.addSource(astSource);
314 if (!astSource.getIdentifier().equals(textSource.getIdentifier())) {
315 // AST indicates a different source identifier, make sure we use that
316 sourcesInProject.add(YangTextSchemaSource.delegateForByteSource(astSource.getIdentifier(),
319 sourcesInProject.add(textSource);
323 final ProcessorModuleReactor reactor = new ProcessorModuleReactor(parser, sourcesInProject, dependencies);
324 LOG.debug("Initialized reactor {} with {}", reactor, yangFilesInProject);
325 return Optional.of(reactor);
326 } catch (IOException | YangSyntaxErrorException | RuntimeException e) {
327 // MojoExecutionException is thrown since execution cannot continue
328 LOG.error("{} Unable to parse YANG files from {}", LOG_PREFIX, yangFilesRootDir, e);
329 Throwable rootCause = Throwables.getRootCause(e);
330 throw new MojoExecutionException(LOG_PREFIX + " Unable to parse YANG files from " + yangFilesRootDir,
335 private static List<File> listFiles(final File root, final Collection<File> excludedFiles)
337 if (!root.isDirectory()) {
338 LOG.warn("{} YANG source directory {} not found. No code will be generated.", LOG_PREFIX, root);
339 return ImmutableList.of();
342 return Files.walk(root.toPath()).map(Path::toFile).filter(File::isFile).filter(f -> {
343 if (excludedFiles.contains(f)) {
344 LOG.info("{} YANG file excluded {}", LOG_PREFIX, f);
348 }).filter(f -> f.getName().endsWith(YangConstants.RFC6020_YANG_FILE_EXTENSION)).collect(Collectors.toList());
352 * Call generate on every generator from plugin configuration.
354 private List<FileState> generateSources(final ContextHolder context,
355 final Collection<GeneratorTaskFactory> generators, final YangParserConfiguration parserConfig)
356 throws MojoFailureException {
357 final var generatorToFiles = ImmutableList.<FileState>builder();
358 for (GeneratorTaskFactory factory : generators) {
359 if (!parserConfig.equals(factory.parserConfig())) {
363 final Stopwatch sw = Stopwatch.createStarted();
364 final GeneratorTask task = factory.createTask(project, context);
365 LOG.debug("{} Task {} initialized in {}", LOG_PREFIX, task, sw);
367 final List<FileState> files;
369 files = task.execute(buildContext);
370 } catch (FileGeneratorException | IOException e) {
371 throw new MojoFailureException(LOG_PREFIX + " Generator " + factory + " failed", e);
374 final String generatorName = factory.generatorName();
375 LOG.debug("{} Sources generated by {}: {}", LOG_PREFIX, generatorName, files);
377 final int fileCount = files.size();
378 generatorToFiles.addAll(files);
380 LOG.info("{} Sources generated by {}: {} in {}", LOG_PREFIX, generatorName, fileCount, sw);
383 return generatorToFiles.build();