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.base.Function;
12 import com.google.common.collect.Lists;
13 import com.google.common.collect.Maps;
14 import com.google.common.collect.Sets;
16 import java.util.Arrays;
17 import java.util.Collection;
18 import java.util.Date;
19 import java.util.HashMap;
20 import java.util.List;
22 import java.util.Objects;
24 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
25 import org.opendaylight.yangtools.yang.common.YangVersion;
26 import org.opendaylight.yangtools.yang.model.api.Module;
27 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
28 import org.opendaylight.yangtools.yang.parser.util.TopologicalSort.Node;
29 import org.opendaylight.yangtools.yang.parser.util.TopologicalSort.NodeImpl;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
34 * Creates a module dependency graph from provided {@link Module}s and
35 * provides a {@link #sort(Module...)} method. It is topological sort and
36 * returns modules in order in which they should be processed (e.g. if A imports
37 * B, sort returns {B, A}).
39 public final class ModuleDependencySort {
41 private static final Date DEFAULT_REVISION = SimpleDateFormatUtil.DEFAULT_DATE_REV;
42 private static final Logger LOGGER = LoggerFactory.getLogger(ModuleDependencySort.class);
43 private static final Function<Node, Module> TOPOLOGY_FUNCTION = input -> {
47 return ((ModuleNodeImpl) input).getReference();
51 * It is not desirable to instance this class
53 private ModuleDependencySort() {
57 * Topological sort of module dependency graph.
59 * @param modules YANG modules
60 * @return Sorted list of Modules. Modules can be further processed in
63 public static List<Module> sort(final Module... modules) {
64 return sort(Arrays.asList(modules));
68 * Topological sort of module dependency graph.
70 * @param modules YANG modules
71 * @return Sorted list of Modules. Modules can be further processed in
74 public static List<Module> sort(final Iterable<Module> modules) {
75 final List<TopologicalSort.Node> sorted = sortInternal(modules);
76 // Cast to Module from Node and return
77 return Lists.transform(sorted, TOPOLOGY_FUNCTION);
80 private static List<TopologicalSort.Node> sortInternal(final Iterable<Module> modules) {
81 final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph = createModuleGraph(modules);
83 final Set<TopologicalSort.Node> nodes = Sets.newHashSet();
84 for (final Map<Date, ModuleNodeImpl> map : moduleGraph.values()) {
85 for (final ModuleNodeImpl node : map.values()) {
90 return TopologicalSort.sort(nodes);
94 static Map<String, Map<Date, ModuleNodeImpl>> createModuleGraph(final Iterable<Module> builders) {
95 final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph = Maps.newHashMap();
97 processModules(moduleGraph, builders);
98 processDependencies(moduleGraph, builders);
104 * Extract module:revision from module builders
106 private static void processDependencies(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph,
107 final Iterable<Module> mmbs) {
108 final Map<URI, Module> allNS = new HashMap<>();
110 // Create edges in graph
111 for (final Module module : mmbs) {
112 final Map<String, Date> imported = Maps.newHashMap();
116 Collection<ModuleImport> imports;
119 fromName = module.getName();
120 fromRevision = module.getRevision();
121 imports = module.getImports();
122 ns = module.getNamespace();
124 // check for existence of module with same namespace
125 if (allNS.containsKey(ns)) {
126 final Module mod = allNS.get(ns);
127 final String name = mod.getName();
128 final Date revision = mod.getRevision();
129 if (!fromName.equals(name)) {
131 "Error while sorting module [{}, {}]: module with same namespace ({}) already loaded: [{}, {}]",
132 fromName, fromRevision, ns, name, revision);
135 allNS.put(ns, module);
138 // no need to check if other Type of object, check is performed in
141 if (fromRevision == null) {
142 fromRevision = DEFAULT_REVISION;
145 for (final ModuleImport imprt : imports) {
146 final String toName = imprt.getModuleName();
147 final Date toRevision = imprt.getRevision() == null ? DEFAULT_REVISION : imprt.getRevision();
149 final ModuleNodeImpl from = moduleGraph.get(fromName).get(fromRevision);
151 final ModuleNodeImpl to = getModuleByNameAndRevision(moduleGraph, fromName, fromRevision, toName, toRevision);
154 * If it is an yang 1 module, check imports: If module is imported twice with different
155 * revisions then throw exception
157 if (YangVersion.VERSION_1.toString().equals(module.getYangVersion()) && imported.get(toName) != null
158 && !imported.get(toName).equals(toRevision) && !imported.get(toName).equals(DEFAULT_REVISION)
159 && !toRevision.equals(DEFAULT_REVISION)) {
160 ex(String.format("Module:%s imported twice with different revisions:%s, %s", toName,
161 formatRevDate(imported.get(toName)), formatRevDate(toRevision)));
164 imported.put(toName, toRevision);
172 * Get imported module by its name and revision from moduleGraph
174 private static ModuleNodeImpl getModuleByNameAndRevision(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph,
175 final String fromName, final Date fromRevision, final String toName, final Date toRevision) {
176 ModuleNodeImpl to = null;
178 if (moduleGraph.get(toName) == null || !moduleGraph.get(toName).containsKey(toRevision)) {
179 // If revision is not specified in import, but module exists
180 // with different revisions, take first
181 if (moduleGraph.get(toName) != null && !moduleGraph.get(toName).isEmpty()
182 && toRevision.equals(DEFAULT_REVISION)) {
183 to = moduleGraph.get(toName).values().iterator().next();
185 .format("Import:%s:%s by module:%s:%s does not specify revision, using:%s:%s for module dependency sort",
186 toName, formatRevDate(toRevision), fromName, formatRevDate(fromRevision), to.getName(),
187 formatRevDate(to.getRevision())));
189 LOGGER.warn(String.format("Not existing module imported:%s:%s by:%s:%s", toName,
190 formatRevDate(toRevision), fromName, formatRevDate(fromRevision)));
191 LOGGER.warn("Available models: {}", moduleGraph);
192 ex(String.format("Not existing module imported:%s:%s by:%s:%s", toName, formatRevDate(toRevision),
193 fromName, formatRevDate(fromRevision)));
196 to = moduleGraph.get(toName).get(toRevision);
201 private static void ex(final String message) {
202 throw new YangValidationException(message);
206 * Extract dependencies from module builders or modules to fill dependency
209 private static void processModules(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph,
210 final Iterable<Module> modules) {
213 for (final Module momb : modules) {
215 final String name = momb.getName();
216 Date rev = momb.getRevision();
218 rev = DEFAULT_REVISION;
221 if (moduleGraph.get(name) == null) {
222 moduleGraph.put(name, Maps.newHashMap());
225 if (moduleGraph.get(name).get(rev) != null) {
226 ex(String.format("Module:%s with revision:%s declared twice", name, formatRevDate(rev)));
229 moduleGraph.get(name).put(rev, new ModuleNodeImpl(name, rev, momb));
233 private static String formatRevDate(final Date rev) {
234 return rev.equals(DEFAULT_REVISION) ? "default" : SimpleDateFormatUtil.getRevisionFormat().format(rev);
238 static class ModuleNodeImpl extends NodeImpl {
239 private final String name;
240 private final Date revision;
241 private final Module originalObject;
243 public ModuleNodeImpl(final String name, final Date revision, final Module module) {
245 this.revision = revision;
246 this.originalObject = module;
249 public String getName() {
253 public Date getRevision() {
258 public int hashCode() {
259 final int prime = 31;
261 result = prime * result + Objects.hashCode(name);
262 result = prime * result + Objects.hashCode(revision);
267 public boolean equals(final Object obj) {
274 if (getClass() != obj.getClass()) {
277 final ModuleNodeImpl other = (ModuleNodeImpl) obj;
279 if (other.name != null) {
282 } else if (!name.equals(other.name)) {
285 if (revision == null) {
286 if (other.revision != null) {
289 } else if (!revision.equals(other.revision)) {
296 public String toString() {
297 return "Module [name=" + name + ", revision=" + formatRevDate(revision) + "]";
300 public Module getReference() {
301 return originalObject;