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.charset.StandardCharsets;
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.LinkedHashMap;
27 import java.util.List;
29 import java.util.Map.Entry;
30 import java.util.NoSuchElementException;
31 import java.util.ServiceLoader;
33 import java.util.function.Function;
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.spi.source.DelegatedYangTextSource;
43 import org.opendaylight.yangtools.yang.model.spi.source.YangIRSchemaSource;
44 import org.opendaylight.yangtools.yang.model.spi.source.YangTextSource;
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 // FIXME: rename to Execution
57 class YangToSourcesProcessor {
58 private static final Logger LOG = LoggerFactory.getLogger(YangToSourcesProcessor.class);
59 private static final YangParserFactory DEFAULT_PARSER_FACTORY;
63 DEFAULT_PARSER_FACTORY = ServiceLoader.load(YangParserFactory.class).iterator().next();
64 } catch (NoSuchElementException e) {
65 throw new IllegalStateException("Failed to find a YangParserFactory implementation", e);
69 private static final String META_INF_STR = "META-INF";
70 private static final String YANG_STR = "yang";
72 static final String LOG_PREFIX = "yang-to-sources:";
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 static final YangProvider YANG_PROVIDER = (project, modelsInProject) -> {
78 final var generatedYangDir =
79 // FIXME: why are we generating these in "generated-sources"? At the end of the day YANG files are more
80 // resources (except we do not them to be subject to filtering)
81 new File(new File(project.getBuild().getDirectory(), "generated-sources"), "yang");
82 LOG.debug("Generated dir {}", generatedYangDir);
84 // copy project's src/main/yang/*.yang to ${project.builddir}/generated-sources/yang/META-INF/yang/
85 // This honors setups like a Eclipse-profile derived one
86 final var withMetaInf = new File(generatedYangDir, YangToSourcesProcessor.META_INF_YANG_STRING);
87 Files.createDirectories(withMetaInf.toPath());
89 final var stateListBuilder = ImmutableList.<FileState>builderWithExpectedSize(modelsInProject.size());
90 for (var source : modelsInProject) {
91 final File file = new File(withMetaInf, source.sourceId().toYangFilename());
92 stateListBuilder.add(FileState.ofWrittenFile(file,
93 out -> source.asByteSource(StandardCharsets.UTF_8).copyTo(out)));
94 LOG.debug("Created file {} for {}", file, source.sourceId());
97 ProjectFileAccess.addResourceDir(project, generatedYangDir);
98 LOG.debug("{} YANG files marked as resources: {}", YangToSourcesProcessor.LOG_PREFIX, generatedYangDir);
100 return stateListBuilder.build();
103 private final YangParserFactory parserFactory;
104 private final File yangFilesRootDir;
105 private final Set<File> excludedFiles;
106 private final ImmutableMap<String, FileGeneratorArg> fileGeneratorArgs;
107 private final @NonNull MavenProject project;
108 private final boolean inspectDependencies;
109 private final @NonNull BuildContext buildContext;
110 private final YangProvider yangProvider;
111 private final StateStorage stateStorage;
112 private final String projectBuildDirectory;
114 private YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
115 final Collection<File> excludedFiles, final List<FileGeneratorArg> fileGeneratorsArgs,
116 final MavenProject project, final boolean inspectDependencies, final YangProvider yangProvider) {
117 this.buildContext = requireNonNull(buildContext, "buildContext");
118 this.yangFilesRootDir = requireNonNull(yangFilesRootDir, "yangFilesRootDir");
119 this.excludedFiles = ImmutableSet.copyOf(excludedFiles);
120 //FIXME multiple FileGeneratorArg entries of same identifier became one here
121 fileGeneratorArgs = Maps.uniqueIndex(fileGeneratorsArgs, FileGeneratorArg::getIdentifier);
122 this.project = requireNonNull(project);
123 this.inspectDependencies = inspectDependencies;
124 this.yangProvider = requireNonNull(yangProvider);
125 projectBuildDirectory = project.getBuild().getDirectory();
126 stateStorage = StateStorage.of(buildContext, stateFilePath(projectBuildDirectory));
127 parserFactory = DEFAULT_PARSER_FACTORY;
131 YangToSourcesProcessor(final File yangFilesRootDir, final List<FileGeneratorArg> fileGenerators,
132 final MavenProject project, final YangProvider yangProvider) {
133 this(new DefaultBuildContext(), yangFilesRootDir, List.of(), List.of(), project, false, yangProvider);
136 YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
137 final Collection<File> excludedFiles, final List<FileGeneratorArg> fileGenerators,
138 final MavenProject project, final boolean inspectDependencies) {
139 this(buildContext, yangFilesRootDir, excludedFiles, fileGenerators, project, inspectDependencies,
143 void execute() throws MojoExecutionException, MojoFailureException {
144 YangToSourcesState prevState;
146 prevState = stateStorage.loadState();
147 } catch (IOException e) {
148 throw new MojoFailureException("Failed to restore execution state", e);
150 if (prevState == null) {
151 LOG.debug("{} no previous execution state present", LOG_PREFIX);
152 prevState = new YangToSourcesState(ImmutableMap.of(),
153 FileStateSet.empty(), FileStateSet.empty(), FileStateSet.empty());
156 // Collect all files in the current project.
157 final List<File> yangFilesInProject;
159 yangFilesInProject = listFiles(yangFilesRootDir, excludedFiles);
160 } catch (IOException e) {
161 throw new MojoFailureException("Failed to list project files", e);
164 if (yangFilesInProject.isEmpty()) {
165 // No files to process, skip.
166 LOG.info("{} No input files found", LOG_PREFIX);
167 wipeAllState(prevState);
171 // We need to instantiate all code generators to determine required import resolution mode
172 final var codeGenerators = instantiateGenerators();
173 if (codeGenerators.isEmpty()) {
174 LOG.warn("{} No code generators provided", LOG_PREFIX);
175 wipeAllState(prevState);
179 LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
181 // All files which affect YANG context. This minimally includes all files in the current project, but optionally
182 // may include any YANG files in the dependencies.
183 final List<ScannedDependency> dependencies;
184 if (inspectDependencies) {
185 final Stopwatch watch = Stopwatch.createStarted();
187 dependencies = ScannedDependency.scanDependencies(project);
188 } catch (IOException e) {
189 LOG.error("{} Failed to scan dependencies", LOG_PREFIX, e);
190 throw new MojoExecutionException(LOG_PREFIX + " Failed to scan dependencies ", e);
192 LOG.info("{} Found {} dependencies in {}", LOG_PREFIX, dependencies.size(), watch);
194 dependencies = List.of();
197 // Determine hash/size of YANG input files and dependencies in parallel
198 final var hashTimer = Stopwatch.createStarted();
199 final var projectYangs = new FileStateSet(yangFilesInProject.parallelStream()
202 return FileState.ofFile(file);
203 } catch (IOException e) {
204 throw new IllegalStateException("Failed to read " + file, e);
207 .collect(ImmutableMap.toImmutableMap(FileState::path, Function.identity())));
208 // TODO: this produces false positives for Jar files -- there we want to capture the contents of the YANG files,
209 // not the entire file
210 final var dependencyYangs = new FileStateSet(dependencies.parallelStream()
211 .map(ScannedDependency::file)
214 return FileState.ofFile(file);
215 } catch (IOException e) {
216 throw new IllegalStateException("Failed to read " + file, e);
219 .collect(ImmutableMap.toImmutableMap(FileState::path, Function.identity())));
220 LOG.debug("{} Input state determined in {}", LOG_PREFIX, hashTimer);
222 // We have collected our current inputs and previous state. Instantiate a support object which will guide us for
223 // the rest of the way.
224 final var buildSupport = new IncrementalBuildSupport(prevState,
225 codeGenerators.stream()
226 .collect(ImmutableMap.toImmutableMap(GeneratorTask::getIdentifier, GeneratorTask::arg)),
227 projectYangs, dependencyYangs);
229 // Check if any inputs changed, which is supposed to be fast. If they did not, we need to also validate our
230 // our previous are also up-to-date.
231 if (!buildSupport.inputsChanged()) {
232 final boolean outputsChanged;
234 outputsChanged = buildSupport.outputsChanged(projectBuildDirectory);
235 } catch (IOException e) {
236 throw new MojoFailureException("Failed to reconcile generation outputs", e);
239 if (!outputsChanged) {
240 // FIXME: YANGTOOLS-745: still need to add all resources/directories to maven project
241 LOG.info("{}: Everything is up to date, nothing to do", LOG_PREFIX);
246 final Stopwatch watch = Stopwatch.createStarted();
248 final List<Entry<YangTextSource, YangIRSchemaSource>> parsed = yangFilesInProject.parallelStream()
250 final var textSource = YangTextSource.forPath(file.toPath());
252 return Map.entry(textSource, TextToIRTransformer.transformText(textSource));
253 } catch (YangSyntaxErrorException | IOException e) {
254 throw new IllegalArgumentException("Failed to parse " + file, e);
257 .collect(Collectors.toList());
258 LOG.debug("Found project files: {}", yangFilesInProject);
259 LOG.info("{} Project model files found: {} in {}", LOG_PREFIX, yangFilesInProject.size(), watch);
261 final var outputFiles = ImmutableList.<FileState>builder();
262 Collection<YangTextSource> modelsInProject = null;
263 for (var parserConfig : codeGenerators.stream().map(GeneratorTask::parserConfig).collect(Collectors.toSet())) {
264 final var moduleReactor = createReactor(yangFilesInProject, parserConfig, dependencies, parsed);
265 final var yangSw = Stopwatch.createStarted();
267 final ContextHolder holder;
269 holder = moduleReactor.toContext();
270 } catch (YangParserException e) {
271 throw new MojoFailureException("Failed to process reactor " + moduleReactor, e);
272 } catch (IOException e) {
273 throw new MojoExecutionException("Failed to read reactor " + moduleReactor, e);
275 LOG.info("{} {} YANG models processed in {}", LOG_PREFIX, holder.getContext().getModules().size(), yangSw);
277 for (var factory : codeGenerators) {
278 if (!parserConfig.equals(factory.parserConfig())) {
282 final var genSw = Stopwatch.createStarted();
283 final List<FileState> files;
285 files = factory.execute(project, buildContext, holder);
286 } catch (FileGeneratorException e) {
287 throw new MojoFailureException(LOG_PREFIX + " Generator " + factory + " failed", e);
290 outputFiles.addAll(files);
291 LOG.info("{} Sources generated by {}: {} in {}", LOG_PREFIX, factory.generatorName(), files.size(),
295 if (modelsInProject == null) {
296 // FIXME: this is an invariant, we should prepare these separately
297 modelsInProject = moduleReactor.getModelsInProject();
301 // add META_INF/yang once
303 outputFiles.addAll(yangProvider.addYangsToMetaInf(project, modelsInProject));
304 } catch (IOException e) {
305 throw new MojoExecutionException("Failed write model files for " + modelsInProject, e);
308 // add META_INF/services
309 File generatedServicesDir = new File(new File(projectBuildDirectory, "generated-sources"), "spi");
310 ProjectFileAccess.addResourceDir(project, generatedServicesDir);
311 LOG.debug("{} Yang services files from: {} marked as resources: {}", LOG_PREFIX, generatedServicesDir,
312 META_INF_YANG_SERVICES_STRING_JAR);
314 final var uniqueOutputFiles = new LinkedHashMap<String, FileState>();
315 for (var fileHash : outputFiles.build()) {
316 final var prev = uniqueOutputFiles.putIfAbsent(fileHash.path(), fileHash);
318 throw new MojoFailureException("Duplicate files " + prev + " and " + fileHash);
322 // Reconcile push output files into project directory and acquire the execution state
323 final YangToSourcesState outputState;
325 outputState = buildSupport.reconcileOutputFiles(buildContext, projectBuildDirectory, uniqueOutputFiles);
326 } catch (IOException e) {
327 throw new MojoFailureException("Failed to reconcile output files", e);
330 // Store execution state
332 stateStorage.storeState(outputState);
333 } catch (IOException e) {
334 throw new MojoFailureException("Failed to store execution state", e);
338 private void wipeAllState(final YangToSourcesState prevState) throws MojoExecutionException {
340 prevState.deleteOutputFiles();
341 } catch (IOException e) {
342 throw new MojoExecutionException("Failed to delete output files", e);
345 stateStorage.deleteState();
346 } catch (IOException e) {
347 throw new MojoExecutionException("Failed to remove execution state", e);
351 private ImmutableList<@NonNull GeneratorTask> instantiateGenerators() throws MojoExecutionException {
352 // Search for available FileGenerator implementations
353 final var factories = Maps.uniqueIndex(
354 ServiceLoader.load(FileGeneratorFactory.class), FileGeneratorFactory::getIdentifier);
356 // FIXME: iterate over fileGeneratorArg instances (configuration), not factories (environment)
357 // Assign instantiate FileGenerators with appropriate configuration
358 final var builder = ImmutableList.<@NonNull GeneratorTask>builderWithExpectedSize(factories.size());
359 for (var entry : factories.entrySet()) {
360 final var id = entry.getKey();
361 var arg = fileGeneratorArgs.get(id);
363 LOG.debug("{} No configuration for {}, using empty", LOG_PREFIX, id);
364 arg = new FileGeneratorArg(id);
367 final GeneratorTask task;
369 task = new GeneratorTask(entry.getValue(), arg);
370 } catch (FileGeneratorException e) {
371 throw new MojoExecutionException("File generator " + id + " failed", e);
374 LOG.info("{} Code generator {} instantiated", LOG_PREFIX, id);
377 // Notify if no factory found for defined identifiers
378 fileGeneratorArgs.keySet().forEach(
379 fileGenIdentifier -> {
380 if (!factories.containsKey(fileGenIdentifier)) {
381 LOG.warn("{} No generator found for identifier {}", LOG_PREFIX, fileGenIdentifier);
386 return builder.build();
389 @SuppressWarnings("checkstyle:illegalCatch")
390 private @NonNull ProcessorModuleReactor createReactor(final List<File> yangFilesInProject,
391 final YangParserConfiguration parserConfig, final Collection<ScannedDependency> dependencies,
392 final List<Entry<YangTextSource, YangIRSchemaSource>> parsed) throws MojoExecutionException {
395 final var sourcesInProject = new ArrayList<YangTextSource>(yangFilesInProject.size());
396 final var parser = parserFactory.createParser(parserConfig);
397 for (var entry : parsed) {
398 final var textSource = entry.getKey();
399 final var astSource = entry.getValue();
400 parser.addSource(astSource);
402 if (!astSource.sourceId().equals(textSource.sourceId())) {
403 // AST indicates a different source identifier, make sure we use that
404 sourcesInProject.add(new DelegatedYangTextSource(astSource.sourceId(), textSource));
406 sourcesInProject.add(textSource);
410 final var moduleReactor = new ProcessorModuleReactor(parser, sourcesInProject, dependencies);
411 LOG.debug("Initialized reactor {} with {}", moduleReactor, yangFilesInProject);
412 return moduleReactor;
413 } catch (IOException | YangSyntaxErrorException | RuntimeException e) {
414 // MojoExecutionException is thrown since execution cannot continue
415 LOG.error("{} Unable to parse YANG files from {}", LOG_PREFIX, yangFilesRootDir, e);
416 throw new MojoExecutionException(LOG_PREFIX + " Unable to parse YANG files from " + yangFilesRootDir,
417 Throwables.getRootCause(e));
421 private static ImmutableList<File> listFiles(final File root, final Collection<File> excludedFiles)
423 if (!root.isDirectory()) {
424 LOG.warn("{} YANG source directory {} not found. No code will be generated.", LOG_PREFIX, root);
425 return ImmutableList.of();
428 return Files.walk(root.toPath())
430 .filter(File::isFile)
432 if (excludedFiles.contains(f)) {
433 LOG.info("{} YANG file excluded {}", LOG_PREFIX, f);
438 .filter(f -> f.getName().endsWith(YangConstants.RFC6020_YANG_FILE_EXTENSION))
439 .collect(ImmutableList.toImmutableList());
443 static @NonNull Path stateFilePath(final String projectBuildDirectory) {
444 // ${project.build.directory}/maven-status/yang-maven-plugin/execution.state
445 return Path.of(projectBuildDirectory, "maven-status", "yang-maven-plugin", "execution.state");