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.FileYangTextSource;
44 import org.opendaylight.yangtools.yang.model.spi.source.YangIRSchemaSource;
45 import org.opendaylight.yangtools.yang.model.spi.source.YangTextSource;
46 import org.opendaylight.yangtools.yang.parser.api.YangParserConfiguration;
47 import org.opendaylight.yangtools.yang.parser.api.YangParserException;
48 import org.opendaylight.yangtools.yang.parser.api.YangParserFactory;
49 import org.opendaylight.yangtools.yang.parser.api.YangSyntaxErrorException;
50 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToIRTransformer;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53 import org.sonatype.plexus.build.incremental.BuildContext;
54 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
56 // FIXME: rename to Execution
58 class YangToSourcesProcessor {
59 private static final Logger LOG = LoggerFactory.getLogger(YangToSourcesProcessor.class);
60 private static final YangParserFactory DEFAULT_PARSER_FACTORY;
64 DEFAULT_PARSER_FACTORY = ServiceLoader.load(YangParserFactory.class).iterator().next();
65 } catch (NoSuchElementException e) {
66 throw new IllegalStateException("Failed to find a YangParserFactory implementation", e);
70 private static final String META_INF_STR = "META-INF";
71 private static final String YANG_STR = "yang";
73 static final String LOG_PREFIX = "yang-to-sources:";
74 static final String META_INF_YANG_STRING = META_INF_STR + File.separator + YANG_STR;
75 static final String META_INF_YANG_STRING_JAR = META_INF_STR + "/" + YANG_STR;
76 static final String META_INF_YANG_SERVICES_STRING_JAR = META_INF_STR + "/" + "services";
78 private static final YangProvider YANG_PROVIDER = (project, modelsInProject) -> {
79 final var generatedYangDir =
80 // FIXME: why are we generating these in "generated-sources"? At the end of the day YANG files are more
81 // resources (except we do not them to be subject to filtering)
82 new File(new File(project.getBuild().getDirectory(), "generated-sources"), "yang");
83 LOG.debug("Generated dir {}", generatedYangDir);
85 // copy project's src/main/yang/*.yang to ${project.builddir}/generated-sources/yang/META-INF/yang/
86 // This honors setups like a Eclipse-profile derived one
87 final var withMetaInf = new File(generatedYangDir, YangToSourcesProcessor.META_INF_YANG_STRING);
88 Files.createDirectories(withMetaInf.toPath());
90 final var stateListBuilder = ImmutableList.<FileState>builderWithExpectedSize(modelsInProject.size());
91 for (var source : modelsInProject) {
92 final File file = new File(withMetaInf, source.sourceId().toYangFilename());
93 stateListBuilder.add(FileState.ofWrittenFile(file,
94 out -> source.asByteSource(StandardCharsets.UTF_8).copyTo(out)));
95 LOG.debug("Created file {} for {}", file, source.sourceId());
98 ProjectFileAccess.addResourceDir(project, generatedYangDir);
99 LOG.debug("{} YANG files marked as resources: {}", YangToSourcesProcessor.LOG_PREFIX, generatedYangDir);
101 return stateListBuilder.build();
104 private final YangParserFactory parserFactory;
105 private final File yangFilesRootDir;
106 private final Set<File> excludedFiles;
107 private final ImmutableMap<String, FileGeneratorArg> fileGeneratorArgs;
108 private final @NonNull MavenProject project;
109 private final boolean inspectDependencies;
110 private final @NonNull BuildContext buildContext;
111 private final YangProvider yangProvider;
112 private final StateStorage stateStorage;
113 private final String projectBuildDirectory;
115 private YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
116 final Collection<File> excludedFiles, final List<FileGeneratorArg> fileGeneratorsArgs,
117 final MavenProject project, final boolean inspectDependencies, final YangProvider yangProvider) {
118 this.buildContext = requireNonNull(buildContext, "buildContext");
119 this.yangFilesRootDir = requireNonNull(yangFilesRootDir, "yangFilesRootDir");
120 this.excludedFiles = ImmutableSet.copyOf(excludedFiles);
121 //FIXME multiple FileGeneratorArg entries of same identifier became one here
122 fileGeneratorArgs = Maps.uniqueIndex(fileGeneratorsArgs, FileGeneratorArg::getIdentifier);
123 this.project = requireNonNull(project);
124 this.inspectDependencies = inspectDependencies;
125 this.yangProvider = requireNonNull(yangProvider);
126 projectBuildDirectory = project.getBuild().getDirectory();
127 stateStorage = StateStorage.of(buildContext, stateFilePath(projectBuildDirectory));
128 parserFactory = DEFAULT_PARSER_FACTORY;
132 YangToSourcesProcessor(final File yangFilesRootDir, final List<FileGeneratorArg> fileGenerators,
133 final MavenProject project, final YangProvider yangProvider) {
134 this(new DefaultBuildContext(), yangFilesRootDir, List.of(), List.of(), project, false, yangProvider);
137 YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
138 final Collection<File> excludedFiles, final List<FileGeneratorArg> fileGenerators,
139 final MavenProject project, final boolean inspectDependencies) {
140 this(buildContext, yangFilesRootDir, excludedFiles, fileGenerators, project, inspectDependencies,
144 void execute() throws MojoExecutionException, MojoFailureException {
145 YangToSourcesState prevState;
147 prevState = stateStorage.loadState();
148 } catch (IOException e) {
149 throw new MojoFailureException("Failed to restore execution state", e);
151 if (prevState == null) {
152 LOG.debug("{} no previous execution state present", LOG_PREFIX);
153 prevState = new YangToSourcesState(ImmutableMap.of(),
154 FileStateSet.empty(), FileStateSet.empty(), FileStateSet.empty());
157 // Collect all files in the current project.
158 final List<File> yangFilesInProject;
160 yangFilesInProject = listFiles(yangFilesRootDir, excludedFiles);
161 } catch (IOException e) {
162 throw new MojoFailureException("Failed to list project files", e);
165 if (yangFilesInProject.isEmpty()) {
166 // No files to process, skip.
167 LOG.info("{} No input files found", LOG_PREFIX);
168 wipeAllState(prevState);
172 // We need to instantiate all code generators to determine required import resolution mode
173 final var codeGenerators = instantiateGenerators();
174 if (codeGenerators.isEmpty()) {
175 LOG.warn("{} No code generators provided", LOG_PREFIX);
176 wipeAllState(prevState);
180 LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
182 // All files which affect YANG context. This minimally includes all files in the current project, but optionally
183 // may include any YANG files in the dependencies.
184 final List<ScannedDependency> dependencies;
185 if (inspectDependencies) {
186 final Stopwatch watch = Stopwatch.createStarted();
188 dependencies = ScannedDependency.scanDependencies(project);
189 } catch (IOException e) {
190 LOG.error("{} Failed to scan dependencies", LOG_PREFIX, e);
191 throw new MojoExecutionException(LOG_PREFIX + " Failed to scan dependencies ", e);
193 LOG.info("{} Found {} dependencies in {}", LOG_PREFIX, dependencies.size(), watch);
195 dependencies = List.of();
198 // Determine hash/size of YANG input files and dependencies in parallel
199 final var hashTimer = Stopwatch.createStarted();
200 final var projectYangs = new FileStateSet(yangFilesInProject.parallelStream()
203 return FileState.ofFile(file);
204 } catch (IOException e) {
205 throw new IllegalStateException("Failed to read " + file, e);
208 .collect(ImmutableMap.toImmutableMap(FileState::path, Function.identity())));
209 // TODO: this produces false positives for Jar files -- there we want to capture the contents of the YANG files,
210 // not the entire file
211 final var dependencyYangs = new FileStateSet(dependencies.parallelStream()
212 .map(ScannedDependency::file)
215 return FileState.ofFile(file);
216 } catch (IOException e) {
217 throw new IllegalStateException("Failed to read " + file, e);
220 .collect(ImmutableMap.toImmutableMap(FileState::path, Function.identity())));
221 LOG.debug("{} Input state determined in {}", LOG_PREFIX, hashTimer);
223 // We have collected our current inputs and previous state. Instantiate a support object which will guide us for
224 // the rest of the way.
225 final var buildSupport = new IncrementalBuildSupport(prevState,
226 codeGenerators.stream()
227 .collect(ImmutableMap.toImmutableMap(GeneratorTask::getIdentifier, GeneratorTask::arg)),
228 projectYangs, dependencyYangs);
230 // Check if any inputs changed, which is supposed to be fast. If they did not, we need to also validate our
231 // our previous are also up-to-date.
232 if (!buildSupport.inputsChanged()) {
233 final boolean outputsChanged;
235 outputsChanged = buildSupport.outputsChanged(projectBuildDirectory);
236 } catch (IOException e) {
237 throw new MojoFailureException("Failed to reconcile generation outputs", e);
240 if (!outputsChanged) {
241 // FIXME: YANGTOOLS-745: still need to add all resources/directories to maven project
242 LOG.info("{}: Everything is up to date, nothing to do", LOG_PREFIX);
247 final Stopwatch watch = Stopwatch.createStarted();
249 final var parsed = yangFilesInProject.parallelStream()
251 final var textSource = new FileYangTextSource(file.toPath());
253 return Map.entry(textSource, TextToIRTransformer.transformText(textSource));
254 } catch (YangSyntaxErrorException | IOException e) {
255 throw new IllegalArgumentException("Failed to parse " + file, e);
258 .collect(Collectors.toList());
259 LOG.debug("Found project files: {}", yangFilesInProject);
260 LOG.info("{} Project model files found: {} in {}", LOG_PREFIX, yangFilesInProject.size(), watch);
262 final var outputFiles = ImmutableList.<FileState>builder();
263 Collection<YangTextSource> modelsInProject = null;
264 for (var parserConfig : codeGenerators.stream().map(GeneratorTask::parserConfig).collect(Collectors.toSet())) {
265 final var moduleReactor = createReactor(yangFilesInProject, parserConfig, dependencies, parsed);
266 final var yangSw = Stopwatch.createStarted();
268 final ContextHolder holder;
270 holder = moduleReactor.toContext();
271 } catch (YangParserException e) {
272 throw new MojoFailureException("Failed to process reactor " + moduleReactor, e);
273 } catch (IOException e) {
274 throw new MojoExecutionException("Failed to read reactor " + moduleReactor, e);
276 LOG.info("{} {} YANG models processed in {}", LOG_PREFIX, holder.getContext().getModules().size(), yangSw);
278 for (var factory : codeGenerators) {
279 if (!parserConfig.equals(factory.parserConfig())) {
283 final var genSw = Stopwatch.createStarted();
284 final List<FileState> files;
286 files = factory.execute(project, buildContext, holder);
287 } catch (FileGeneratorException e) {
288 throw new MojoFailureException(LOG_PREFIX + " Generator " + factory + " failed", e);
291 outputFiles.addAll(files);
292 LOG.info("{} Sources generated by {}: {} in {}", LOG_PREFIX, factory.generatorName(), files.size(),
296 if (modelsInProject == null) {
297 // FIXME: this is an invariant, we should prepare these separately
298 modelsInProject = moduleReactor.getModelsInProject();
302 // add META_INF/yang once
304 outputFiles.addAll(yangProvider.addYangsToMetaInf(project, modelsInProject));
305 } catch (IOException e) {
306 throw new MojoExecutionException("Failed write model files for " + modelsInProject, e);
309 // add META_INF/services
310 File generatedServicesDir = new File(new File(projectBuildDirectory, "generated-sources"), "spi");
311 ProjectFileAccess.addResourceDir(project, generatedServicesDir);
312 LOG.debug("{} Yang services files from: {} marked as resources: {}", LOG_PREFIX, generatedServicesDir,
313 META_INF_YANG_SERVICES_STRING_JAR);
315 final var uniqueOutputFiles = new LinkedHashMap<String, FileState>();
316 for (var fileHash : outputFiles.build()) {
317 final var prev = uniqueOutputFiles.putIfAbsent(fileHash.path(), fileHash);
319 throw new MojoFailureException("Duplicate files " + prev + " and " + fileHash);
323 // Reconcile push output files into project directory and acquire the execution state
324 final YangToSourcesState outputState;
326 outputState = buildSupport.reconcileOutputFiles(buildContext, projectBuildDirectory, uniqueOutputFiles);
327 } catch (IOException e) {
328 throw new MojoFailureException("Failed to reconcile output files", e);
331 // Store execution state
333 stateStorage.storeState(outputState);
334 } catch (IOException e) {
335 throw new MojoFailureException("Failed to store execution state", e);
339 private void wipeAllState(final YangToSourcesState prevState) throws MojoExecutionException {
341 prevState.deleteOutputFiles();
342 } catch (IOException e) {
343 throw new MojoExecutionException("Failed to delete output files", e);
346 stateStorage.deleteState();
347 } catch (IOException e) {
348 throw new MojoExecutionException("Failed to remove execution state", e);
352 private ImmutableList<@NonNull GeneratorTask> instantiateGenerators() throws MojoExecutionException {
353 // Search for available FileGenerator implementations
354 final var factories = Maps.uniqueIndex(
355 ServiceLoader.load(FileGeneratorFactory.class), FileGeneratorFactory::getIdentifier);
357 // FIXME: iterate over fileGeneratorArg instances (configuration), not factories (environment)
358 // Assign instantiate FileGenerators with appropriate configuration
359 final var builder = ImmutableList.<@NonNull GeneratorTask>builderWithExpectedSize(factories.size());
360 for (var entry : factories.entrySet()) {
361 final var id = entry.getKey();
362 var arg = fileGeneratorArgs.get(id);
364 LOG.debug("{} No configuration for {}, using empty", LOG_PREFIX, id);
365 arg = new FileGeneratorArg(id);
368 final GeneratorTask task;
370 task = new GeneratorTask(entry.getValue(), arg);
371 } catch (FileGeneratorException e) {
372 throw new MojoExecutionException("File generator " + id + " failed", e);
375 LOG.info("{} Code generator {} instantiated", LOG_PREFIX, id);
378 // Notify if no factory found for defined identifiers
379 fileGeneratorArgs.keySet().forEach(
380 fileGenIdentifier -> {
381 if (!factories.containsKey(fileGenIdentifier)) {
382 LOG.warn("{} No generator found for identifier {}", LOG_PREFIX, fileGenIdentifier);
387 return builder.build();
390 @SuppressWarnings("checkstyle:illegalCatch")
391 private @NonNull ProcessorModuleReactor createReactor(final List<File> yangFilesInProject,
392 final YangParserConfiguration parserConfig, final Collection<ScannedDependency> dependencies,
393 final List<Entry<FileYangTextSource, YangIRSchemaSource>> parsed) throws MojoExecutionException {
396 final var sourcesInProject = new ArrayList<YangTextSource>(yangFilesInProject.size());
397 final var parser = parserFactory.createParser(parserConfig);
398 for (var entry : parsed) {
399 final var textSource = entry.getKey();
400 final var astSource = entry.getValue();
401 parser.addSource(astSource);
403 if (!astSource.sourceId().equals(textSource.sourceId())) {
404 // AST indicates a different source identifier, make sure we use that
405 sourcesInProject.add(new DelegatedYangTextSource(astSource.sourceId(), textSource));
407 sourcesInProject.add(textSource);
411 final var moduleReactor = new ProcessorModuleReactor(parser, sourcesInProject, dependencies);
412 LOG.debug("Initialized reactor {} with {}", moduleReactor, yangFilesInProject);
413 return moduleReactor;
414 } catch (IOException | YangSyntaxErrorException | RuntimeException e) {
415 // MojoExecutionException is thrown since execution cannot continue
416 LOG.error("{} Unable to parse YANG files from {}", LOG_PREFIX, yangFilesRootDir, e);
417 throw new MojoExecutionException(LOG_PREFIX + " Unable to parse YANG files from " + yangFilesRootDir,
418 Throwables.getRootCause(e));
422 private static ImmutableList<File> listFiles(final File root, final Collection<File> excludedFiles)
424 if (!root.isDirectory()) {
425 LOG.warn("{} YANG source directory {} not found. No code will be generated.", LOG_PREFIX, root);
426 return ImmutableList.of();
429 return Files.walk(root.toPath())
431 .filter(File::isFile)
433 if (excludedFiles.contains(f)) {
434 LOG.info("{} YANG file excluded {}", LOG_PREFIX, f);
439 .filter(f -> f.getName().endsWith(YangConstants.RFC6020_YANG_FILE_EXTENSION))
440 .collect(ImmutableList.toImmutableList());
444 static @NonNull Path stateFilePath(final String projectBuildDirectory) {
445 // ${project.build.directory}/maven-status/yang-maven-plugin/execution.state
446 return Path.of(projectBuildDirectory, "maven-status", "yang-maven-plugin", "execution.state");