/* * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.yangtools.yang2sources.plugin; import static com.google.common.base.Preconditions.checkState; import static java.util.Objects.requireNonNull; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Stopwatch; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.ServiceLoader; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.project.MavenProject; import org.eclipse.jdt.annotation.NonNull; import org.opendaylight.yangtools.plugin.generator.api.FileGeneratorException; import org.opendaylight.yangtools.plugin.generator.api.FileGeneratorFactory; import org.opendaylight.yangtools.yang.common.YangConstants; import org.opendaylight.yangtools.yang.model.repo.api.YangIRSchemaSource; import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource; import org.opendaylight.yangtools.yang.parser.api.YangParser; import org.opendaylight.yangtools.yang.parser.api.YangParserConfiguration; import org.opendaylight.yangtools.yang.parser.api.YangParserException; import org.opendaylight.yangtools.yang.parser.api.YangParserFactory; import org.opendaylight.yangtools.yang.parser.api.YangSyntaxErrorException; import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToIRTransformer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonatype.plexus.build.incremental.BuildContext; import org.sonatype.plexus.build.incremental.DefaultBuildContext; class YangToSourcesProcessor { private static final Logger LOG = LoggerFactory.getLogger(YangToSourcesProcessor.class); private static final YangParserFactory DEFAULT_PARSER_FACTORY; static { final Iterator it = ServiceLoader.load(YangParserFactory.class).iterator(); checkState(it.hasNext(), "Failed to find a YangParserFactory implementation"); DEFAULT_PARSER_FACTORY = it.next(); } static final String LOG_PREFIX = "yang-to-sources:"; private static final String META_INF_STR = "META-INF"; private static final String YANG_STR = "yang"; static final String META_INF_YANG_STRING = META_INF_STR + File.separator + YANG_STR; static final String META_INF_YANG_STRING_JAR = META_INF_STR + "/" + YANG_STR; static final String META_INF_YANG_SERVICES_STRING_JAR = META_INF_STR + "/" + "services"; private final YangParserFactory parserFactory; private final File yangFilesRootDir; private final Set excludedFiles; private final ImmutableMap fileGeneratorArgs; private final @NonNull MavenProject project; private final boolean inspectDependencies; private final BuildContext buildContext; private final YangProvider yangProvider; private final StateStorage stateStorage; private YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir, final Collection excludedFiles, final List fileGeneratorsArgs, final MavenProject project, final boolean inspectDependencies, final YangProvider yangProvider) { this.buildContext = requireNonNull(buildContext, "buildContext"); this.yangFilesRootDir = requireNonNull(yangFilesRootDir, "yangFilesRootDir"); this.excludedFiles = ImmutableSet.copyOf(excludedFiles); //FIXME multiple FileGeneratorArg entries of same identifier became one here fileGeneratorArgs = Maps.uniqueIndex(fileGeneratorsArgs, FileGeneratorArg::getIdentifier); this.project = requireNonNull(project); this.inspectDependencies = inspectDependencies; this.yangProvider = requireNonNull(yangProvider); stateStorage = StateStorage.of(buildContext, stateFilePath(project.getBuild().getDirectory())); parserFactory = DEFAULT_PARSER_FACTORY; } @VisibleForTesting YangToSourcesProcessor(final File yangFilesRootDir, final Collection excludedFiles, final List fileGenerators, final MavenProject project, final boolean inspectDependencies, final YangProvider yangProvider) { this(new DefaultBuildContext(), yangFilesRootDir, excludedFiles, ImmutableList.of(), project, inspectDependencies, yangProvider); } YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir, final Collection excludedFiles, final List fileGenerators, final MavenProject project, final boolean inspectDependencies) { this(buildContext, yangFilesRootDir, excludedFiles, fileGenerators, project, inspectDependencies, YangProvider.getInstance()); } void execute() throws MojoExecutionException, MojoFailureException { final YangToSourcesState prevState; try { prevState = stateStorage.loadState(); } catch (IOException e) { throw new MojoFailureException("Failed to restore execution state", e); } if (prevState == null) { LOG.debug("{} no previous execution state present", LOG_PREFIX); } // Collect all files in the current project. final List yangFilesInProject; try { yangFilesInProject = listFiles(yangFilesRootDir, excludedFiles); } catch (IOException e) { throw new MojoFailureException("Failed to list project files", e); } if (yangFilesInProject.isEmpty()) { // No files to process, skip. LOG.info("{} No input files found", LOG_PREFIX); return; } // We need to instantiate all code generators to determine required import resolution mode final List codeGenerators = instantiateGenerators(); if (codeGenerators.isEmpty()) { LOG.warn("{} No code generators provided", LOG_PREFIX); return; } final Set parserConfigs = codeGenerators.stream() .map(GeneratorTask::parserConfig) .collect(Collectors.toUnmodifiableSet()); LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir); // All files which affect YANG context. This minimally includes all files in the current project, but optionally // may include any YANG files in the dependencies. final List dependencies; if (inspectDependencies) { final Stopwatch watch = Stopwatch.createStarted(); try { dependencies = ScannedDependency.scanDependencies(project); } catch (IOException e) { LOG.error("{} Failed to scan dependencies", LOG_PREFIX, e); throw new MojoExecutionException(LOG_PREFIX + " Failed to scan dependencies ", e); } LOG.info("{} Found {} dependencies in {}", LOG_PREFIX, dependencies.size(), watch); } else { dependencies = ImmutableList.of(); } /* * Check if any of the listed files changed. If no changes occurred, simply return empty, which indicates * end of execution. */ // FIXME: YANGTOOLS-745: remove this check FileStates instead if (!Stream.concat(yangFilesInProject.stream(), dependencies.stream().map(ScannedDependency::file)) .anyMatch(buildContext::hasDelta)) { LOG.info("{} None of {} input files changed", LOG_PREFIX, yangFilesInProject.size() + dependencies.size()); return; } final Stopwatch watch = Stopwatch.createStarted(); // Determine hash/size of YANG input files in parallel final var projectYangs = new FileStateSet(yangFilesInProject.parallelStream() .map(file -> { try { return FileState.ofFile(file); } catch (IOException e) { throw new IllegalStateException("Failed to read " + file, e); } }) .collect(ImmutableMap.toImmutableMap(FileState::path, Function.identity()))); final List> parsed = yangFilesInProject.parallelStream() .map(file -> { final YangTextSchemaSource textSource = YangTextSchemaSource.forPath(file.toPath()); try { return Map.entry(textSource, TextToIRTransformer.transformText(textSource)); } catch (YangSyntaxErrorException | IOException e) { throw new IllegalArgumentException("Failed to parse " + file, e); } }) .collect(Collectors.toList()); LOG.debug("Found project files: {}", yangFilesInProject); LOG.info("{} Project model files found: {} in {}", LOG_PREFIX, yangFilesInProject.size(), watch); // Determine hash/size of dependency files // TODO: this produces false positives for Jar files -- there we want to capture the contents of the YANG files, // not the entire file final var dependencyYangs = new FileStateSet(dependencies.parallelStream() .map(ScannedDependency::file) .map(file -> { try { return FileState.ofFile(file); } catch (IOException e) { throw new IllegalStateException("Failed to read " + file, e); } }) .collect(ImmutableMap.toImmutableMap(FileState::path, Function.identity()))); final var outputFiles = ImmutableList.builder(); boolean sourcesPersisted = false; for (YangParserConfiguration parserConfig : parserConfigs) { final var moduleReactor = createReactor(yangFilesInProject, parserConfig, dependencies, parsed); final var yangSw = Stopwatch.createStarted(); final ContextHolder holder; try { holder = moduleReactor.toContext(); } catch (YangParserException e) { throw new MojoFailureException("Failed to process reactor " + moduleReactor, e); } catch (IOException e) { throw new MojoExecutionException("Failed to read reactor " + moduleReactor, e); } LOG.info("{} {} YANG models processed in {}", LOG_PREFIX, holder.getContext().getModules().size(), yangSw); for (var factory : codeGenerators) { if (!parserConfig.equals(factory.parserConfig())) { continue; } final var genSw = Stopwatch.createStarted(); final List files; try { files = factory.execute(project, holder); } catch (FileGeneratorException | IOException e) { throw new MojoFailureException(LOG_PREFIX + " Generator " + factory + " failed", e); } files.forEach(state -> buildContext.refresh(new File(state.path()))); outputFiles.addAll(files); LOG.info("{} Sources generated by {}: {} in {}", LOG_PREFIX, factory.generatorName(), files.size(), genSw); } if (!sourcesPersisted) { // add META_INF/yang once final var models = moduleReactor.getModelsInProject(); final Collection sourceFileStates; try { sourceFileStates = yangProvider.addYangsToMetaInf(project, models); } catch (IOException e) { throw new MojoExecutionException("Failed write model files for " + models, e); } sourcesPersisted = true; outputFiles.addAll(sourceFileStates); } } // add META_INF/services File generatedServicesDir = new File(new File(project.getBuild().getDirectory(), "generated-sources"), "spi"); ProjectFileAccess.addResourceDir(project, generatedServicesDir); LOG.debug("{} Yang services files from: {} marked as resources: {}", LOG_PREFIX, generatedServicesDir, META_INF_YANG_SERVICES_STRING_JAR); final var uniqueOutputFiles = new LinkedHashMap(); for (var fileHash : outputFiles.build()) { final var prev = uniqueOutputFiles.putIfAbsent(fileHash.path(), fileHash); if (prev != null) { throw new MojoFailureException("Duplicate files " + prev + " and " + fileHash); } } final var outputState = new YangToSourcesState( codeGenerators.stream() .collect(ImmutableMap.toImmutableMap(GeneratorTask::getIdentifier, GeneratorTask::arg)), projectYangs, dependencyYangs, new FileStateSet(ImmutableMap.copyOf(uniqueOutputFiles))); try { stateStorage.storeState(outputState); } catch (IOException e) { throw new MojoFailureException("Failed to store execution state", e); } } private List instantiateGenerators() throws MojoExecutionException { // Search for available FileGenerator implementations final Map factories = Maps.uniqueIndex( ServiceLoader.load(FileGeneratorFactory.class), FileGeneratorFactory::getIdentifier); // FIXME: iterate over fileGeneratorArg instances (configuration), not factories (environment) // Assign instantiate FileGenerators with appropriate configuration final var generators = new ArrayList(factories.size()); for (Entry entry : factories.entrySet()) { final String id = entry.getKey(); FileGeneratorArg arg = fileGeneratorArgs.get(id); if (arg == null) { LOG.debug("{} No configuration for {}, using empty", LOG_PREFIX, id); arg = new FileGeneratorArg(id); } final GeneratorTask task; try { task = new GeneratorTask(entry.getValue(), arg); } catch (FileGeneratorException e) { throw new MojoExecutionException("File generator " + id + " failed", e); } generators.add(task); LOG.info("{} Code generator {} instantiated", LOG_PREFIX, id); } // Notify if no factory found for defined identifiers fileGeneratorArgs.keySet().forEach( fileGenIdentifier -> { if (!factories.containsKey(fileGenIdentifier)) { LOG.warn("{} No generator found for identifier {}", LOG_PREFIX, fileGenIdentifier); } } ); return generators; } @SuppressWarnings("checkstyle:illegalCatch") private @NonNull ProcessorModuleReactor createReactor(final List yangFilesInProject, final YangParserConfiguration parserConfig, final Collection dependencies, final List> parsed) throws MojoExecutionException { try { final List sourcesInProject = new ArrayList<>(yangFilesInProject.size()); final YangParser parser = parserFactory.createParser(parserConfig); for (final Entry entry : parsed) { final YangTextSchemaSource textSource = entry.getKey(); final YangIRSchemaSource astSource = entry.getValue(); parser.addSource(astSource); if (!astSource.getIdentifier().equals(textSource.getIdentifier())) { // AST indicates a different source identifier, make sure we use that sourcesInProject.add(YangTextSchemaSource.delegateForByteSource(astSource.getIdentifier(), textSource)); } else { sourcesInProject.add(textSource); } } final ProcessorModuleReactor reactor = new ProcessorModuleReactor(parser, sourcesInProject, dependencies); LOG.debug("Initialized reactor {} with {}", reactor, yangFilesInProject); return reactor; } catch (IOException | YangSyntaxErrorException | RuntimeException e) { // MojoExecutionException is thrown since execution cannot continue LOG.error("{} Unable to parse YANG files from {}", LOG_PREFIX, yangFilesRootDir, e); Throwable rootCause = Throwables.getRootCause(e); throw new MojoExecutionException(LOG_PREFIX + " Unable to parse YANG files from " + yangFilesRootDir, rootCause); } } private static ImmutableList listFiles(final File root, final Collection excludedFiles) throws IOException { if (!root.isDirectory()) { LOG.warn("{} YANG source directory {} not found. No code will be generated.", LOG_PREFIX, root); return ImmutableList.of(); } return Files.walk(root.toPath()) .map(Path::toFile) .filter(File::isFile) .filter(f -> { if (excludedFiles.contains(f)) { LOG.info("{} YANG file excluded {}", LOG_PREFIX, f); return false; } return true; }) .filter(f -> f.getName().endsWith(YangConstants.RFC6020_YANG_FILE_EXTENSION)) .collect(ImmutableList.toImmutableList()); } @VisibleForTesting static @NonNull Path stateFilePath(final String projectBuildDirectory) { // ${project.build.directory}/maven-status/yang-maven-plugin/execution.state return Path.of(projectBuildDirectory, "maven-status", "yang-maven-plugin", "execution.state"); } }