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 java.util.Objects.requireNonNull;
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.base.Stopwatch;
14 import com.google.common.base.Throwables;
15 import com.google.common.collect.ImmutableList;
16 import com.google.common.collect.ImmutableMap;
17 import com.google.common.collect.ImmutableSet;
18 import com.google.common.collect.Maps;
20 import java.io.IOException;
21 import java.nio.file.Files;
22 import java.nio.file.Path;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.LinkedHashMap;
26 import java.util.List;
28 import java.util.Map.Entry;
29 import java.util.NoSuchElementException;
30 import java.util.ServiceLoader;
32 import java.util.function.Function;
33 import java.util.stream.Collectors;
34 import java.util.stream.Stream;
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.YangParserConfiguration;
45 import org.opendaylight.yangtools.yang.parser.api.YangParserException;
46 import org.opendaylight.yangtools.yang.parser.api.YangParserFactory;
47 import org.opendaylight.yangtools.yang.parser.api.YangSyntaxErrorException;
48 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToIRTransformer;
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;
54 class YangToSourcesProcessor {
55 private static final Logger LOG = LoggerFactory.getLogger(YangToSourcesProcessor.class);
56 private static final YangParserFactory DEFAULT_PARSER_FACTORY;
60 DEFAULT_PARSER_FACTORY = ServiceLoader.load(YangParserFactory.class).iterator().next();
61 } catch (NoSuchElementException e) {
62 throw new IllegalStateException("Failed to find a YangParserFactory implementation", e);
66 private static final String META_INF_STR = "META-INF";
67 private static final String YANG_STR = "yang";
69 static final String LOG_PREFIX = "yang-to-sources:";
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 static final YangProvider YANG_PROVIDER = (project, modelsInProject) -> {
75 final var generatedYangDir =
76 // FIXME: why are we generating these in "generated-sources"? At the end of the day YANG files are more
77 // resources (except we do not them to be subject to filtering)
78 new File(new File(project.getBuild().getDirectory(), "generated-sources"), "yang");
79 LOG.debug("Generated dir {}", generatedYangDir);
81 // copy project's src/main/yang/*.yang to ${project.builddir}/generated-sources/yang/META-INF/yang/
82 // This honors setups like a Eclipse-profile derived one
83 final var withMetaInf = new File(generatedYangDir, YangToSourcesProcessor.META_INF_YANG_STRING);
84 final var stateListBuilder = ImmutableList.<FileState>builderWithExpectedSize(modelsInProject.size());
86 for (var source : modelsInProject) {
87 final File file = new File(withMetaInf, source.getIdentifier().toYangFilename());
88 // FIXME: ditch this use
89 com.google.common.io.Files.createParentDirs(file);
91 stateListBuilder.add(FileState.ofWrittenFile(file, source::copyTo));
92 LOG.debug("Created file {} for {}", file, source.getIdentifier());
95 ProjectFileAccess.addResourceDir(project, generatedYangDir);
96 LOG.debug("{} YANG files marked as resources: {}", YangToSourcesProcessor.LOG_PREFIX, generatedYangDir);
98 return stateListBuilder.build();
101 private final YangParserFactory parserFactory;
102 private final File yangFilesRootDir;
103 private final Set<File> excludedFiles;
104 private final ImmutableMap<String, FileGeneratorArg> fileGeneratorArgs;
105 private final @NonNull MavenProject project;
106 private final boolean inspectDependencies;
107 private final BuildContext buildContext;
108 private final YangProvider yangProvider;
109 private final StateStorage stateStorage;
111 private YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
112 final Collection<File> excludedFiles, final List<FileGeneratorArg> fileGeneratorsArgs,
113 final MavenProject project, final boolean inspectDependencies, final YangProvider yangProvider) {
114 this.buildContext = requireNonNull(buildContext, "buildContext");
115 this.yangFilesRootDir = requireNonNull(yangFilesRootDir, "yangFilesRootDir");
116 this.excludedFiles = ImmutableSet.copyOf(excludedFiles);
117 //FIXME multiple FileGeneratorArg entries of same identifier became one here
118 fileGeneratorArgs = Maps.uniqueIndex(fileGeneratorsArgs, FileGeneratorArg::getIdentifier);
119 this.project = requireNonNull(project);
120 this.inspectDependencies = inspectDependencies;
121 this.yangProvider = requireNonNull(yangProvider);
122 stateStorage = StateStorage.of(buildContext, stateFilePath(project.getBuild().getDirectory()));
123 parserFactory = DEFAULT_PARSER_FACTORY;
127 YangToSourcesProcessor(final File yangFilesRootDir, final List<FileGeneratorArg> fileGenerators,
128 final MavenProject project, final YangProvider yangProvider) {
129 this(new DefaultBuildContext(), yangFilesRootDir, List.of(), List.of(), project, false, yangProvider);
132 YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
133 final Collection<File> excludedFiles, final List<FileGeneratorArg> fileGenerators,
134 final MavenProject project, final boolean inspectDependencies) {
135 this(buildContext, yangFilesRootDir, excludedFiles, fileGenerators, project, inspectDependencies,
139 void execute() throws MojoExecutionException, MojoFailureException {
140 final YangToSourcesState prevState;
142 prevState = stateStorage.loadState();
143 } catch (IOException e) {
144 throw new MojoFailureException("Failed to restore execution state", e);
146 if (prevState == null) {
147 LOG.debug("{} no previous execution state present", LOG_PREFIX);
150 // Collect all files in the current project.
151 final List<File> yangFilesInProject;
153 yangFilesInProject = listFiles(yangFilesRootDir, excludedFiles);
154 } catch (IOException e) {
155 throw new MojoFailureException("Failed to list project files", e);
158 if (yangFilesInProject.isEmpty()) {
159 // No files to process, skip.
160 LOG.info("{} No input files found", LOG_PREFIX);
164 // We need to instantiate all code generators to determine required import resolution mode
165 final List<GeneratorTask> codeGenerators = instantiateGenerators();
166 if (codeGenerators.isEmpty()) {
167 LOG.warn("{} No code generators provided", LOG_PREFIX);
171 final Set<YangParserConfiguration> parserConfigs = codeGenerators.stream()
172 .map(GeneratorTask::parserConfig)
173 .collect(Collectors.toUnmodifiableSet());
175 LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
177 // All files which affect YANG context. This minimally includes all files in the current project, but optionally
178 // may include any YANG files in the dependencies.
179 final List<ScannedDependency> dependencies;
180 if (inspectDependencies) {
181 final Stopwatch watch = Stopwatch.createStarted();
183 dependencies = ScannedDependency.scanDependencies(project);
184 } catch (IOException e) {
185 LOG.error("{} Failed to scan dependencies", LOG_PREFIX, e);
186 throw new MojoExecutionException(LOG_PREFIX + " Failed to scan dependencies ", e);
188 LOG.info("{} Found {} dependencies in {}", LOG_PREFIX, dependencies.size(), watch);
190 dependencies = List.of();
194 * Check if any of the listed files changed. If no changes occurred, simply return empty, which indicates
197 // FIXME: YANGTOOLS-745: remove this check FileStates instead
198 if (!Stream.concat(yangFilesInProject.stream(), dependencies.stream().map(ScannedDependency::file))
199 .anyMatch(buildContext::hasDelta)) {
200 LOG.info("{} None of {} input files changed", LOG_PREFIX, yangFilesInProject.size() + dependencies.size());
204 final Stopwatch watch = Stopwatch.createStarted();
205 // Determine hash/size of YANG input files in parallel
206 final var projectYangs = new FileStateSet(yangFilesInProject.parallelStream()
209 return FileState.ofFile(file);
210 } catch (IOException e) {
211 throw new IllegalStateException("Failed to read " + file, e);
214 .collect(ImmutableMap.toImmutableMap(FileState::path, Function.identity())));
216 final List<Entry<YangTextSchemaSource, YangIRSchemaSource>> parsed = yangFilesInProject.parallelStream()
218 final YangTextSchemaSource textSource = YangTextSchemaSource.forPath(file.toPath());
220 return Map.entry(textSource, TextToIRTransformer.transformText(textSource));
221 } catch (YangSyntaxErrorException | IOException e) {
222 throw new IllegalArgumentException("Failed to parse " + file, e);
225 .collect(Collectors.toList());
226 LOG.debug("Found project files: {}", yangFilesInProject);
227 LOG.info("{} Project model files found: {} in {}", LOG_PREFIX, yangFilesInProject.size(), watch);
229 // Determine hash/size of dependency files
230 // TODO: this produces false positives for Jar files -- there we want to capture the contents of the YANG files,
231 // not the entire file
232 final var dependencyYangs = new FileStateSet(dependencies.parallelStream()
233 .map(ScannedDependency::file)
236 return FileState.ofFile(file);
237 } catch (IOException e) {
238 throw new IllegalStateException("Failed to read " + file, e);
241 .collect(ImmutableMap.toImmutableMap(FileState::path, Function.identity())));
243 final var outputFiles = ImmutableList.<FileState>builder();
244 boolean sourcesPersisted = false;
246 for (YangParserConfiguration parserConfig : parserConfigs) {
247 final var moduleReactor = createReactor(yangFilesInProject, parserConfig, dependencies, parsed);
248 final var yangSw = Stopwatch.createStarted();
250 final ContextHolder holder;
252 holder = moduleReactor.toContext();
253 } catch (YangParserException e) {
254 throw new MojoFailureException("Failed to process reactor " + moduleReactor, e);
255 } catch (IOException e) {
256 throw new MojoExecutionException("Failed to read reactor " + moduleReactor, e);
259 LOG.info("{} {} YANG models processed in {}", LOG_PREFIX, holder.getContext().getModules().size(), yangSw);
261 for (var factory : codeGenerators) {
262 if (!parserConfig.equals(factory.parserConfig())) {
266 final var genSw = Stopwatch.createStarted();
267 final List<FileState> files;
269 files = factory.execute(project, buildContext, holder);
270 } catch (FileGeneratorException | IOException e) {
271 throw new MojoFailureException(LOG_PREFIX + " Generator " + factory + " failed", e);
274 outputFiles.addAll(files);
275 LOG.info("{} Sources generated by {}: {} in {}", LOG_PREFIX, factory.generatorName(), files.size(),
279 if (!sourcesPersisted) {
280 // add META_INF/yang once
281 final var models = moduleReactor.getModelsInProject();
282 final Collection<FileState> sourceFileStates;
284 sourceFileStates = yangProvider.addYangsToMetaInf(project, models);
285 } catch (IOException e) {
286 throw new MojoExecutionException("Failed write model files for " + models, e);
289 sourcesPersisted = true;
290 outputFiles.addAll(sourceFileStates);
294 // add META_INF/services
295 File generatedServicesDir = new File(new File(project.getBuild().getDirectory(), "generated-sources"), "spi");
296 ProjectFileAccess.addResourceDir(project, generatedServicesDir);
297 LOG.debug("{} Yang services files from: {} marked as resources: {}", LOG_PREFIX, generatedServicesDir,
298 META_INF_YANG_SERVICES_STRING_JAR);
300 final var uniqueOutputFiles = new LinkedHashMap<String, FileState>();
301 for (var fileHash : outputFiles.build()) {
302 final var prev = uniqueOutputFiles.putIfAbsent(fileHash.path(), fileHash);
304 throw new MojoFailureException("Duplicate files " + prev + " and " + fileHash);
308 final var outputState = new YangToSourcesState(
309 codeGenerators.stream()
310 .collect(ImmutableMap.toImmutableMap(GeneratorTask::getIdentifier, GeneratorTask::arg)),
311 projectYangs, dependencyYangs, new FileStateSet(ImmutableMap.copyOf(uniqueOutputFiles)));
314 stateStorage.storeState(outputState);
315 } catch (IOException e) {
316 throw new MojoFailureException("Failed to store execution state", e);
320 private List<GeneratorTask> instantiateGenerators() throws MojoExecutionException {
321 // Search for available FileGenerator implementations
322 final Map<String, FileGeneratorFactory> factories = Maps.uniqueIndex(
323 ServiceLoader.load(FileGeneratorFactory.class), FileGeneratorFactory::getIdentifier);
325 // FIXME: iterate over fileGeneratorArg instances (configuration), not factories (environment)
326 // Assign instantiate FileGenerators with appropriate configuration
327 final var generators = new ArrayList<GeneratorTask>(factories.size());
328 for (Entry<String, FileGeneratorFactory> entry : factories.entrySet()) {
329 final String id = entry.getKey();
330 FileGeneratorArg arg = fileGeneratorArgs.get(id);
332 LOG.debug("{} No configuration for {}, using empty", LOG_PREFIX, id);
333 arg = new FileGeneratorArg(id);
336 final GeneratorTask task;
338 task = new GeneratorTask(entry.getValue(), arg);
339 } catch (FileGeneratorException e) {
340 throw new MojoExecutionException("File generator " + id + " failed", e);
342 generators.add(task);
343 LOG.info("{} Code generator {} instantiated", LOG_PREFIX, id);
346 // Notify if no factory found for defined identifiers
347 fileGeneratorArgs.keySet().forEach(
348 fileGenIdentifier -> {
349 if (!factories.containsKey(fileGenIdentifier)) {
350 LOG.warn("{} No generator found for identifier {}", LOG_PREFIX, fileGenIdentifier);
358 @SuppressWarnings("checkstyle:illegalCatch")
359 private @NonNull ProcessorModuleReactor createReactor(final List<File> yangFilesInProject,
360 final YangParserConfiguration parserConfig, final Collection<ScannedDependency> dependencies,
361 final List<Entry<YangTextSchemaSource, YangIRSchemaSource>> parsed) throws MojoExecutionException {
364 final var sourcesInProject = new ArrayList<YangTextSchemaSource>(yangFilesInProject.size());
365 final var parser = parserFactory.createParser(parserConfig);
366 for (var entry : parsed) {
367 final var textSource = entry.getKey();
368 final var astSource = entry.getValue();
369 parser.addSource(astSource);
371 if (!astSource.getIdentifier().equals(textSource.getIdentifier())) {
372 // AST indicates a different source identifier, make sure we use that
373 sourcesInProject.add(YangTextSchemaSource.delegateForByteSource(astSource.getIdentifier(),
376 sourcesInProject.add(textSource);
380 final var moduleReactor = new ProcessorModuleReactor(parser, sourcesInProject, dependencies);
381 LOG.debug("Initialized reactor {} with {}", moduleReactor, yangFilesInProject);
382 return moduleReactor;
383 } catch (IOException | YangSyntaxErrorException | RuntimeException e) {
384 // MojoExecutionException is thrown since execution cannot continue
385 LOG.error("{} Unable to parse YANG files from {}", LOG_PREFIX, yangFilesRootDir, e);
386 throw new MojoExecutionException(LOG_PREFIX + " Unable to parse YANG files from " + yangFilesRootDir,
387 Throwables.getRootCause(e));
391 private static ImmutableList<File> listFiles(final File root, final Collection<File> excludedFiles)
393 if (!root.isDirectory()) {
394 LOG.warn("{} YANG source directory {} not found. No code will be generated.", LOG_PREFIX, root);
395 return ImmutableList.of();
398 return Files.walk(root.toPath())
400 .filter(File::isFile)
402 if (excludedFiles.contains(f)) {
403 LOG.info("{} YANG file excluded {}", LOG_PREFIX, f);
408 .filter(f -> f.getName().endsWith(YangConstants.RFC6020_YANG_FILE_EXTENSION))
409 .collect(ImmutableList.toImmutableList());
413 static @NonNull Path stateFilePath(final String projectBuildDirectory) {
414 // ${project.build.directory}/maven-status/yang-maven-plugin/execution.state
415 return Path.of(projectBuildDirectory, "maven-status", "yang-maven-plugin", "execution.state");