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.ImmutableSet;
18 import com.google.common.collect.ImmutableSet.Builder;
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.List;
29 import java.util.Map.Entry;
30 import java.util.Optional;
31 import java.util.ServiceLoader;
33 import java.util.stream.Collectors;
34 import org.apache.maven.plugin.MojoExecutionException;
35 import org.apache.maven.plugin.MojoFailureException;
36 import org.apache.maven.project.MavenProject;
37 import org.opendaylight.yangtools.plugin.generator.api.FileGeneratorException;
38 import org.opendaylight.yangtools.plugin.generator.api.FileGeneratorFactory;
39 import org.opendaylight.yangtools.yang.common.YangConstants;
40 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
41 import org.opendaylight.yangtools.yang.parser.api.YangParser;
42 import org.opendaylight.yangtools.yang.parser.api.YangParserConfiguration;
43 import org.opendaylight.yangtools.yang.parser.api.YangParserException;
44 import org.opendaylight.yangtools.yang.parser.api.YangParserFactory;
45 import org.opendaylight.yangtools.yang.parser.api.YangSyntaxErrorException;
46 import org.opendaylight.yangtools.yang.parser.rfc7950.ir.IRSchemaSource;
47 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToIRTransformer;
48 import org.opendaylight.yangtools.yang2sources.plugin.ConfigArg.CodeGeneratorArg;
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;
59 final Iterator<YangParserFactory> it = ServiceLoader.load(YangParserFactory.class).iterator();
60 checkState(it.hasNext(), "Failed to find a YangParserFactory implementation");
61 DEFAULT_PARSER_FACTORY = it.next();
64 static final String LOG_PREFIX = "yang-to-sources:";
65 private static final String META_INF_STR = "META-INF";
66 private static final String YANG_STR = "yang";
68 static final String META_INF_YANG_STRING = META_INF_STR + File.separator + YANG_STR;
69 static final String META_INF_YANG_STRING_JAR = META_INF_STR + "/" + YANG_STR;
70 static final String META_INF_YANG_SERVICES_STRING_JAR = META_INF_STR + "/" + "services";
72 private final YangParserFactory parserFactory;
73 private final File yangFilesRootDir;
74 private final Set<File> excludedFiles;
75 private final List<CodeGeneratorArg> codeGeneratorArgs;
76 private final Map<String, FileGeneratorArg> fileGeneratorArgs;
77 private final MavenProject project;
78 private final boolean inspectDependencies;
79 private final BuildContext buildContext;
80 private final YangProvider yangProvider;
82 private YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
83 final Collection<File> excludedFiles, final List<CodeGeneratorArg> codeGeneratorArgs,
84 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 this.codeGeneratorArgs = ImmutableList.copyOf(codeGeneratorArgs);
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<CodeGeneratorArg> codeGenerators, final MavenProject project, final boolean inspectDependencies,
100 final YangProvider yangProvider) {
101 this(new DefaultBuildContext(), yangFilesRootDir, excludedFiles, codeGenerators, ImmutableList.of(),
102 project, inspectDependencies, yangProvider);
105 YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
106 final Collection<File> excludedFiles, final List<CodeGeneratorArg> codeGenerators,
107 final List<FileGeneratorArg> fileGenerators, final MavenProject project,
108 final boolean inspectDependencies) {
109 this(buildContext, yangFilesRootDir, excludedFiles, codeGenerators, fileGenerators, project,
110 inspectDependencies, YangProvider.getInstance());
113 public void execute() throws MojoExecutionException, MojoFailureException {
114 conditionalExecute(false);
117 void conditionalExecute(final boolean skip) throws MojoExecutionException, MojoFailureException {
119 * Collect all files which affect YANG context. This includes all
120 * files in current project and optionally any jars/files in the
123 final List<File> yangFilesInProject;
125 yangFilesInProject = listFiles(yangFilesRootDir, excludedFiles);
126 } catch (IOException e) {
127 throw new MojoFailureException("Failed to list project files", e);
130 if (yangFilesInProject.isEmpty()) {
131 // No files to process, skip.
132 LOG.info("{} No input files found", LOG_PREFIX);
136 // We need to instantiate all code generators to determine required import resolution mode
137 final List<GeneratorTaskFactory> codeGenerators = instantiateGenerators();
138 if (codeGenerators.isEmpty()) {
139 LOG.warn("{} No code generators provided", LOG_PREFIX);
143 final Set<YangParserConfiguration> parserConfigs = codeGenerators.stream()
144 .map(GeneratorTaskFactory::parserConfig)
145 .collect(Collectors.toUnmodifiableSet());
147 LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
149 final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
150 final Collection<ScannedDependency> dependencies;
151 if (inspectDependencies) {
152 dependencies = new ArrayList<>();
153 final Stopwatch watch = Stopwatch.createStarted();
156 ScannedDependency.scanDependencies(project).forEach(dep -> {
157 allFiles.add(dep.file());
158 dependencies.add(dep);
160 } catch (IOException e) {
161 LOG.error("{} Failed to scan dependencies", LOG_PREFIX, e);
162 throw new MojoExecutionException(LOG_PREFIX + " Failed to scan dependencies ", e);
164 LOG.info("{} Found {} dependencies in {}", LOG_PREFIX, dependencies.size(), watch);
166 dependencies = ImmutableList.of();
170 * Check if any of the listed files changed. If no changes occurred, simply return empty, which indicates
173 if (!allFiles.stream().anyMatch(buildContext::hasDelta)) {
174 LOG.info("{} None of {} input files changed", LOG_PREFIX, allFiles.size());
178 final Stopwatch watch = Stopwatch.createStarted();
179 final List<Entry<YangTextSchemaSource, IRSchemaSource>> parsed = yangFilesInProject.parallelStream()
181 final YangTextSchemaSource textSource = YangTextSchemaSource.forPath(file.toPath());
183 return Map.entry(textSource,TextToIRTransformer.transformText(textSource));
184 } catch (YangSyntaxErrorException | IOException e) {
185 throw new IllegalArgumentException("Failed to parse " + file, e);
188 .collect(Collectors.toList());
189 LOG.debug("Found project files: {}", yangFilesInProject);
190 LOG.info("{} Project model files found: {} in {}", LOG_PREFIX, yangFilesInProject.size(), watch);
192 // FIXME: store these files into state, so that we can verify/clean up
193 final Builder<File> files = ImmutableSet.builder();
194 for (YangParserConfiguration parserConfig : parserConfigs) {
195 final Optional<ProcessorModuleReactor> optReactor = createReactor(yangFilesInProject,
196 parserConfig, dependencies, parsed);
197 if (optReactor.isPresent()) {
198 final ProcessorModuleReactor reactor = optReactor.orElseThrow();
201 final Stopwatch sw = Stopwatch.createStarted();
202 final ContextHolder holder;
205 holder = reactor.toContext();
206 } catch (YangParserException e) {
207 throw new MojoFailureException("Failed to process reactor " + reactor, e);
208 } catch (IOException e) {
209 throw new MojoExecutionException("Failed to read reactor " + reactor, e);
212 LOG.info("{} {} YANG models processed in {}", LOG_PREFIX, holder.getContext().getModules().size(),
214 files.addAll(generateSources(holder, codeGenerators, parserConfig));
216 LOG.info("{} Skipping YANG code generation because property yang.skip is true", LOG_PREFIX);
219 // FIXME: this is not right: we should be generating the models exactly once!
221 final Collection<YangTextSchemaSource> models = reactor.getModelsInProject();
223 yangProvider.addYangsToMetaInf(project, models);
224 } catch (IOException e) {
225 throw new MojoExecutionException("Failed write model files for " + models, e);
230 // add META_INF/services
231 File generatedServicesDir = new GeneratedDirectories(project).getYangServicesDir();
232 YangProvider.setResource(generatedServicesDir, project);
233 LOG.debug("{} Yang services files from: {} marked as resources: {}", LOG_PREFIX, generatedServicesDir,
234 META_INF_YANG_SERVICES_STRING_JAR);
237 private List<GeneratorTaskFactory> instantiateGenerators() throws MojoExecutionException, MojoFailureException {
238 final List<GeneratorTaskFactory> generators = new ArrayList<>(codeGeneratorArgs.size());
239 for (CodeGeneratorArg arg : codeGeneratorArgs) {
240 generators.add(CodeGeneratorTaskFactory.create(arg));
241 LOG.info("{} Code generator instantiated from {}", LOG_PREFIX, arg.getCodeGeneratorClass());
244 // Search for available FileGenerator implementations
245 final Map<String, FileGeneratorFactory> factories = Maps.uniqueIndex(
246 ServiceLoader.load(FileGeneratorFactory.class), FileGeneratorFactory::getIdentifier);
248 // Assign instantiate FileGenerators with appropriate configurate
249 for (Entry<String, FileGeneratorFactory> entry : factories.entrySet()) {
250 final String id = entry.getKey();
251 FileGeneratorArg arg = fileGeneratorArgs.get(id);
253 LOG.debug("{} No configuration for {}, using empty", LOG_PREFIX, id);
254 arg = new FileGeneratorArg(id);
258 generators.add(FileGeneratorTaskFactory.of(entry.getValue(), arg));
259 } catch (FileGeneratorException e) {
260 throw new MojoExecutionException("File generator " + id + " failed", e);
262 LOG.info("{} Code generator {} instantiated", LOG_PREFIX, id);
268 @SuppressWarnings("checkstyle:illegalCatch")
269 private Optional<ProcessorModuleReactor> createReactor(final List<File> yangFilesInProject,
270 final YangParserConfiguration parserConfig, final Collection<ScannedDependency> dependencies,
271 final List<Entry<YangTextSchemaSource, IRSchemaSource>> parsed) throws MojoExecutionException {
274 final List<YangTextSchemaSource> sourcesInProject = new ArrayList<>(yangFilesInProject.size());
275 final YangParser parser = parserFactory.createParser(parserConfig);
276 for (final Entry<YangTextSchemaSource, IRSchemaSource> entry : parsed) {
277 final YangTextSchemaSource textSource = entry.getKey();
278 final IRSchemaSource astSource = entry.getValue();
279 parser.addSource(astSource);
281 if (!astSource.getIdentifier().equals(textSource.getIdentifier())) {
282 // AST indicates a different source identifier, make sure we use that
283 sourcesInProject.add(YangTextSchemaSource.delegateForByteSource(astSource.getIdentifier(),
286 sourcesInProject.add(textSource);
290 final ProcessorModuleReactor reactor = new ProcessorModuleReactor(parser, sourcesInProject, dependencies);
291 LOG.debug("Initialized reactor {} with {}", reactor, yangFilesInProject);
292 return Optional.of(reactor);
293 } catch (IOException | YangSyntaxErrorException | RuntimeException e) {
294 // MojoExecutionException is thrown since execution cannot continue
295 LOG.error("{} Unable to parse YANG files from {}", LOG_PREFIX, yangFilesRootDir, e);
296 Throwable rootCause = Throwables.getRootCause(e);
297 throw new MojoExecutionException(LOG_PREFIX + " Unable to parse YANG files from " + yangFilesRootDir,
302 private static List<File> listFiles(final File root, final Collection<File> excludedFiles)
304 if (!root.isDirectory()) {
305 LOG.warn("{} YANG source directory {} not found. No code will be generated.", LOG_PREFIX, root);
306 return ImmutableList.of();
309 return Files.walk(root.toPath()).map(Path::toFile).filter(File::isFile).filter(f -> {
310 if (excludedFiles.contains(f)) {
311 LOG.info("{} YANG file excluded {}", LOG_PREFIX, f);
315 }).filter(f -> f.getName().endsWith(YangConstants.RFC6020_YANG_FILE_EXTENSION)).collect(Collectors.toList());
319 * Call generate on every generator from plugin configuration.
321 private Set<File> generateSources(final ContextHolder context, final Collection<GeneratorTaskFactory> generators,
322 final YangParserConfiguration parserConfig) throws MojoFailureException {
323 final Builder<File> allFiles = ImmutableSet.builder();
324 for (GeneratorTaskFactory factory : generators) {
325 if (!parserConfig.equals(factory.parserConfig())) {
329 final Stopwatch sw = Stopwatch.createStarted();
330 final GeneratorTask<?> task = factory.createTask(project, context);
331 LOG.debug("{} Task {} initialized in {}", LOG_PREFIX, task, sw);
333 final Collection<File> files;
335 files = task.execute(buildContext);
336 } catch (FileGeneratorException | IOException e) {
337 throw new MojoFailureException(LOG_PREFIX + " Generator " + factory + " failed", e);
340 LOG.debug("{} Sources generated by {}: {}", LOG_PREFIX, factory.generatorName(), files);
344 fileCount = files.size();
345 allFiles.addAll(files);
350 LOG.info("{} Sources generated by {}: {} in {}", LOG_PREFIX, factory.generatorName(), fileCount, sw);
353 return allFiles.build();