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.model.util;
10 import com.google.common.annotations.Beta;
11 import com.google.common.collect.HashBasedTable;
12 import com.google.common.collect.Lists;
13 import com.google.common.collect.Table;
15 import java.util.Collection;
16 import java.util.HashMap;
17 import java.util.HashSet;
18 import java.util.List;
20 import java.util.Objects;
21 import java.util.Optional;
22 import org.opendaylight.yangtools.util.TopologicalSort;
23 import org.opendaylight.yangtools.util.TopologicalSort.Node;
24 import org.opendaylight.yangtools.util.TopologicalSort.NodeImpl;
25 import org.opendaylight.yangtools.yang.common.Revision;
26 import org.opendaylight.yangtools.yang.common.YangVersion;
27 import org.opendaylight.yangtools.yang.model.api.Module;
28 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
33 * Creates a module dependency graph from provided {@link Module}s and provides a {@link #sort(Collection)} method.
34 * It is topological sort and returns modules in order in which they should be processed (e.g. if A imports B, sort
38 public final class ModuleDependencySort {
39 private static final Logger LOG = LoggerFactory.getLogger(ModuleDependencySort.class);
42 * It is not desirable to instance this class.
44 private ModuleDependencySort() {
45 throw new UnsupportedOperationException();
49 * Topological sort of module dependency graph.
51 * @param modules YANG modules
52 * @return Sorted list of Modules. Modules can be further processed in returned order.
53 * @throws IllegalArgumentException when provided modules are not consistent.
55 public static List<Module> sort(final Collection<Module> modules) {
56 return sort((Iterable<Module>)modules);
60 * Topological sort of module dependency graph.
62 * @param modules YANG modules
63 * @return Sorted list of Modules. Modules can be further processed in
65 * @throws IllegalArgumentException when provided modules are not consistent.
67 * @deprecated Use {@link #sort(Collection)} instead.
70 public static List<Module> sort(final Iterable<Module> modules) {
71 final List<Node> sorted = sortInternal(modules);
72 // Cast to Module from Node and return
73 return Lists.transform(sorted, input -> input == null ? null : ((ModuleNodeImpl) input).getReference());
76 private static List<Node> sortInternal(final Iterable<Module> modules) {
77 final Table<String, Optional<Revision>, ModuleNodeImpl> moduleGraph = createModuleGraph(modules);
78 return TopologicalSort.sort(new HashSet<>(moduleGraph.values()));
81 private static Table<String, Optional<Revision>, ModuleNodeImpl> createModuleGraph(
82 final Iterable<Module> builders) {
83 final Table<String, Optional<Revision>, ModuleNodeImpl> moduleGraph = HashBasedTable.create();
85 processModules(moduleGraph, builders);
86 processDependencies(moduleGraph, builders);
92 * Extract module:revision from modules.
94 private static void processDependencies(final Table<String, Optional<Revision>, 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, Optional<Revision>> imported = new HashMap<>();
101 final String fromName = module.getName();
102 final URI ns = module.getNamespace();
103 final Optional<Revision> 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 process modules
116 for (final ModuleImport imprt : module.getImports()) {
117 final String toName = imprt.getModuleName();
118 final Optional<Revision> toRevision = imprt.getRevision();
120 final ModuleNodeImpl from = moduleGraph.get(fromName, fromRevision);
121 final ModuleNodeImpl to = getModuleByNameAndRevision(moduleGraph, fromName, fromRevision, toName,
125 * If it is an yang 1 module, check imports: If module is imported twice with different
126 * revisions then throw exception
128 if (module.getYangVersion() == YangVersion.VERSION_1) {
129 final Optional<Revision> impRevision = imported.get(toName);
130 if (impRevision != null && impRevision.isPresent() && !impRevision.equals(toRevision)
131 && toRevision.isPresent()) {
132 throw new IllegalArgumentException(String.format(
133 "Module:%s imported twice with different revisions:%s, %s", toName,
134 formatRevDate(impRevision), formatRevDate(toRevision)));
138 imported.put(toName, toRevision);
146 * Get imported module by its name and revision from moduleGraph.
148 private static ModuleNodeImpl getModuleByNameAndRevision(
149 final Table<String, Optional<Revision>, ModuleNodeImpl> moduleGraph, final String fromName,
150 final Optional<Revision> fromRevision, final String toName, final Optional<Revision> toRevision) {
152 final ModuleNodeImpl exact = moduleGraph.get(toName, toRevision);
157 // If revision is not specified in import, but module exists with different revisions, take first one
158 if (toRevision == null) {
159 final Map<Optional<Revision>, ModuleNodeImpl> modulerevs = moduleGraph.row(toName);
161 if (!modulerevs.isEmpty()) {
162 final ModuleNodeImpl first = modulerevs.values().iterator().next();
163 if (LOG.isTraceEnabled()) {
164 LOG.trace("Import:{}:{} by module:{}:{} does not specify revision, using:{}:{}"
165 + " for module dependency sort", toName, formatRevDate(toRevision), fromName,
166 formatRevDate(fromRevision), first.getName(), formatRevDate(first.getRevision()));
172 LOG.warn("Not existing module imported:{}:{} by:{}:{}", toName, formatRevDate(toRevision), fromName,
173 formatRevDate(fromRevision));
174 LOG.warn("Available models: {}", moduleGraph);
175 throw new IllegalArgumentException(String.format("Not existing module imported:%s:%s by:%s:%s", toName,
176 formatRevDate(toRevision), fromName, formatRevDate(fromRevision)));
180 * Extract dependencies from modules to fill dependency graph.
182 private static void processModules(final Table<String, Optional<Revision>, ModuleNodeImpl> moduleGraph,
183 final Iterable<Module> modules) {
186 for (final Module momb : modules) {
188 final String name = momb.getName();
189 final Optional<Revision> rev = momb.getRevision();
190 final Map<Optional<Revision>, ModuleNodeImpl> revs = moduleGraph.row(name);
191 if (revs.containsKey(rev)) {
192 throw new IllegalArgumentException(String.format("Module:%s with revision:%s declared twice", name,
193 formatRevDate(rev)));
196 revs.put(rev, new ModuleNodeImpl(name, rev.orElse(null), momb));
200 private static String formatRevDate(final Optional<Revision> rev) {
201 return rev.map(Revision::toString).orElse("default");
204 private static final class ModuleNodeImpl extends NodeImpl {
205 private final String name;
206 private final Revision revision;
207 private final Module originalObject;
209 ModuleNodeImpl(final String name, final Revision revision, final Module module) {
211 this.revision = revision;
212 this.originalObject = module;
219 Optional<Revision> getRevision() {
220 return Optional.ofNullable(revision);
224 public int hashCode() {
225 final int prime = 31;
227 result = prime * result + Objects.hashCode(name);
228 result = prime * result + Objects.hashCode(revision);
233 public boolean equals(final Object obj) {
240 if (getClass() != obj.getClass()) {
243 final ModuleNodeImpl other = (ModuleNodeImpl) obj;
245 if (other.name != null) {
248 } else if (!name.equals(other.name)) {
251 if (revision == null) {
252 if (other.revision != null) {
255 } else if (!revision.equals(other.revision)) {
262 public String toString() {
263 return "Module [name=" + name + ", revision=" + formatRevDate(getRevision()) + "]";
266 public Module getReference() {
267 return originalObject;