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.yang.parser.util;
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.collect.Lists;
13 import java.util.Arrays;
14 import java.util.Date;
15 import java.util.HashMap;
16 import java.util.HashSet;
17 import java.util.List;
19 import java.util.Objects;
21 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
22 import org.opendaylight.yangtools.yang.common.YangVersion;
23 import org.opendaylight.yangtools.yang.model.api.Module;
24 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
25 import org.opendaylight.yangtools.yang.parser.util.TopologicalSort.NodeImpl;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
30 * Creates a module dependency graph from provided {@link Module}s and
31 * provides a {@link #sort(Module...)} method. It is topological sort and
32 * returns modules in order in which they should be processed (e.g. if A imports
33 * B, sort returns {B, A}).
35 public final class ModuleDependencySort {
37 private static final Date DEFAULT_REVISION = SimpleDateFormatUtil.DEFAULT_DATE_REV;
38 private static final Logger LOG = LoggerFactory.getLogger(ModuleDependencySort.class);
41 * It is not desirable to instance this class
43 private ModuleDependencySort() {
47 * Topological sort of module dependency graph.
49 * @param modules YANG modules
50 * @return Sorted list of Modules. Modules can be further processed in
53 public static List<Module> sort(final Module... modules) {
54 return sort(Arrays.asList(modules));
58 * Topological sort of module dependency graph.
60 * @param modules YANG modules
61 * @return Sorted list of Modules. Modules can be further processed in
64 public static List<Module> sort(final Iterable<Module> modules) {
65 final List<TopologicalSort.Node> sorted = sortInternal(modules);
66 // Cast to Module from Node and return
67 return Lists.transform(sorted, input -> input == null ? null : ((ModuleNodeImpl) input).getReference());
70 private static List<TopologicalSort.Node> sortInternal(final Iterable<Module> modules) {
71 final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph = createModuleGraph(modules);
73 final Set<TopologicalSort.Node> nodes = new HashSet<>();
74 for (final Map<Date, ModuleNodeImpl> map : moduleGraph.values()) {
75 nodes.addAll(map.values());
78 return TopologicalSort.sort(nodes);
82 static Map<String, Map<Date, ModuleNodeImpl>> createModuleGraph(final Iterable<Module> builders) {
83 final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph = new HashMap<>();
85 processModules(moduleGraph, builders);
86 processDependencies(moduleGraph, builders);
92 * Extract module:revision from module builders
94 private static void processDependencies(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph,
95 final Iterable<Module> mmbs) {
96 final Map<URI, Module> allNS = new HashMap<>();
98 // Create edges in graph
99 for (final Module module : mmbs) {
100 final Map<String, Date> imported = new HashMap<>();
101 final String fromName = module.getName();
102 final URI ns = module.getNamespace();
103 Date fromRevision = module.getRevision();
105 // check for existence of module with same namespace
106 final Module prev = allNS.putIfAbsent(ns, module);
108 final String name = prev.getName();
109 if (!fromName.equals(name)) {
110 LOG.warn("Error while sorting module [{}, {}]: module with same namespace ({}) already loaded:"
111 + " [{}, {}]", fromName, fromRevision, ns, name, prev.getRevision());
115 // no need to check if other Type of object, check is performed in
118 if (fromRevision == null) {
119 fromRevision = DEFAULT_REVISION;
122 for (final ModuleImport imprt : module.getImports()) {
123 final String toName = imprt.getModuleName();
124 final Date toRevision = imprt.getRevision() == null ? DEFAULT_REVISION : imprt.getRevision();
126 final ModuleNodeImpl from = moduleGraph.get(fromName).get(fromRevision);
128 final ModuleNodeImpl to = getModuleByNameAndRevision(moduleGraph, fromName, fromRevision, toName, toRevision);
131 * If it is an yang 1 module, check imports: If module is imported twice with different
132 * revisions then throw exception
134 if (YangVersion.VERSION_1.toString().equals(module.getYangVersion())) {
135 final Date impRevision = imported.get(toName);
136 if (impRevision != null && !impRevision.equals(toRevision)
137 && !DEFAULT_REVISION.equals(impRevision) && !DEFAULT_REVISION.equals(toRevision)) {
138 throw new YangValidationException(String.format(
139 "Module:%s imported twice with different revisions:%s, %s", toName,
140 formatRevDate(impRevision), formatRevDate(toRevision)));
144 imported.put(toName, toRevision);
152 * Get imported module by its name and revision from moduleGraph
154 private static ModuleNodeImpl getModuleByNameAndRevision(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph,
155 final String fromName, final Date fromRevision, final String toName, final Date toRevision) {
157 final Map<Date, ModuleNodeImpl> modulerevs = moduleGraph.get(toName);
158 if (modulerevs != null) {
159 final ModuleNodeImpl exact = modulerevs.get(toRevision);
164 // If revision is not specified in import, but module exists with different revisions, take first one
165 if (DEFAULT_REVISION.equals(toRevision) && !modulerevs.isEmpty()) {
166 final ModuleNodeImpl first = modulerevs.values().iterator().next();
167 if (LOG.isTraceEnabled()) {
168 LOG.trace("Import:{}:{} by module:{}:{} does not specify revision, using:{}:{}"
169 + " for module dependency sort", toName, formatRevDate(toRevision), fromName,
170 formatRevDate(fromRevision), first.getName(), formatRevDate(first.getRevision()));
176 LOG.warn("Not existing module imported:{}:{} by:{}:{}", toName, formatRevDate(toRevision), fromName,
177 formatRevDate(fromRevision));
178 LOG.warn("Available models: {}", moduleGraph);
179 throw new YangValidationException(String.format("Not existing module imported:%s:%s by:%s:%s", toName,
180 formatRevDate(toRevision), fromName, formatRevDate(fromRevision)));
184 * Extract dependencies from module builders or modules to fill dependency
187 private static void processModules(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph,
188 final Iterable<Module> modules) {
191 for (final Module momb : modules) {
193 final String name = momb.getName();
194 Date rev = momb.getRevision();
196 rev = DEFAULT_REVISION;
199 final Map<Date, ModuleNodeImpl> revs = moduleGraph.computeIfAbsent(name, key -> new HashMap<>(2));
200 if (revs.containsKey(rev)) {
201 throw new YangValidationException(String.format("Module:%s with revision:%s declared twice", name,
202 formatRevDate(rev)));
205 revs.put(rev, new ModuleNodeImpl(name, rev, momb));
209 private static String formatRevDate(final Date rev) {
210 return rev.equals(DEFAULT_REVISION) ? "default" : SimpleDateFormatUtil.getRevisionFormat().format(rev);
214 static class ModuleNodeImpl extends NodeImpl {
215 private final String name;
216 private final Date revision;
217 private final Module originalObject;
219 public ModuleNodeImpl(final String name, final Date revision, final Module module) {
221 this.revision = revision;
222 this.originalObject = module;
225 public String getName() {
229 public Date getRevision() {
234 public int hashCode() {
235 final int prime = 31;
237 result = prime * result + Objects.hashCode(name);
238 result = prime * result + Objects.hashCode(revision);
243 public boolean equals(final Object obj) {
250 if (getClass() != obj.getClass()) {
253 final ModuleNodeImpl other = (ModuleNodeImpl) obj;
255 if (other.name != null) {
258 } else if (!name.equals(other.name)) {
261 if (revision == null) {
262 if (other.revision != null) {
265 } else if (!revision.equals(other.revision)) {
272 public String toString() {
273 return "Module [name=" + name + ", revision=" + formatRevDate(revision) + "]";
276 public Module getReference() {
277 return originalObject;