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.HashBasedTable;
12 import com.google.common.collect.Lists;
13 import com.google.common.collect.Table;
15 import java.util.Arrays;
16 import java.util.Date;
17 import java.util.HashMap;
18 import java.util.HashSet;
19 import java.util.List;
21 import java.util.Objects;
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.SimpleDateFormatUtil;
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
34 * provides a {@link #sort(Module...)} method. It is topological sort and
35 * returns modules in order in which they should be processed (e.g. if A imports
36 * B, sort returns {B, A}).
38 public final class ModuleDependencySort {
40 private static final Date DEFAULT_REVISION = SimpleDateFormatUtil.DEFAULT_DATE_REV;
41 private static final Logger LOG = LoggerFactory.getLogger(ModuleDependencySort.class);
44 * It is not desirable to instance this class
46 private ModuleDependencySort() {
50 * Topological sort of module dependency graph.
52 * @param modules YANG modules
53 * @return Sorted list of Modules. Modules can be further processed in
56 public static List<Module> sort(final Module... modules) {
57 return sort(Arrays.asList(modules));
61 * Topological sort of module dependency graph.
63 * @param modules YANG modules
64 * @return Sorted list of Modules. Modules can be further processed in
67 public static List<Module> sort(final Iterable<Module> modules) {
68 final List<Node> sorted = sortInternal(modules);
69 // Cast to Module from Node and return
70 return Lists.transform(sorted, input -> input == null ? null : ((ModuleNodeImpl) input).getReference());
73 private static List<Node> sortInternal(final Iterable<Module> modules) {
74 final Table<String, Date, ModuleNodeImpl> moduleGraph = createModuleGraph(modules);
75 return TopologicalSort.sort(new HashSet<>(moduleGraph.values()));
79 static Table<String, Date, ModuleNodeImpl> createModuleGraph(final Iterable<Module> builders) {
80 final Table<String, Date, ModuleNodeImpl> moduleGraph = HashBasedTable.create();
82 processModules(moduleGraph, builders);
83 processDependencies(moduleGraph, builders);
89 * Extract module:revision from module builders
91 private static void processDependencies(final Table<String, Date, ModuleNodeImpl> moduleGraph,
92 final Iterable<Module> mmbs) {
93 final Map<URI, Module> allNS = new HashMap<>();
95 // Create edges in graph
96 for (final Module module : mmbs) {
97 final Map<String, Date> imported = new HashMap<>();
98 final String fromName = module.getName();
99 final URI ns = module.getNamespace();
100 Date fromRevision = module.getRevision();
102 // check for existence of module with same namespace
103 final Module prev = allNS.putIfAbsent(ns, module);
105 final String name = prev.getName();
106 if (!fromName.equals(name)) {
107 LOG.warn("Error while sorting module [{}, {}]: module with same namespace ({}) already loaded:"
108 + " [{}, {}]", fromName, fromRevision, ns, name, prev.getRevision());
112 // no need to check if other Type of object, check is performed in
115 if (fromRevision == null) {
116 fromRevision = DEFAULT_REVISION;
119 for (final ModuleImport imprt : module.getImports()) {
120 final String toName = imprt.getModuleName();
121 final Date toRevision = imprt.getRevision() == null ? DEFAULT_REVISION : imprt.getRevision();
123 final ModuleNodeImpl from = moduleGraph.get(fromName, fromRevision);
125 final ModuleNodeImpl to = getModuleByNameAndRevision(moduleGraph, fromName, fromRevision, toName, toRevision);
128 * If it is an yang 1 module, check imports: If module is imported twice with different
129 * revisions then throw exception
131 if (YangVersion.VERSION_1.toString().equals(module.getYangVersion())) {
132 final Date impRevision = imported.get(toName);
133 if (impRevision != null && !impRevision.equals(toRevision)
134 && !DEFAULT_REVISION.equals(impRevision) && !DEFAULT_REVISION.equals(toRevision)) {
135 throw new YangValidationException(String.format(
136 "Module:%s imported twice with different revisions:%s, %s", toName,
137 formatRevDate(impRevision), formatRevDate(toRevision)));
141 imported.put(toName, toRevision);
149 * Get imported module by its name and revision from moduleGraph
151 private static ModuleNodeImpl getModuleByNameAndRevision(final Table<String, Date, ModuleNodeImpl> moduleGraph,
152 final String fromName, final Date fromRevision, final String toName, final Date toRevision) {
154 final ModuleNodeImpl exact = moduleGraph.get(toName, toRevision);
159 // If revision is not specified in import, but module exists with different revisions, take first one
160 if (DEFAULT_REVISION.equals(toRevision)) {
161 final Map<Date, ModuleNodeImpl> modulerevs = moduleGraph.row(toName);
163 if (!modulerevs.isEmpty()) {
164 final ModuleNodeImpl first = modulerevs.values().iterator().next();
165 if (LOG.isTraceEnabled()) {
166 LOG.trace("Import:{}:{} by module:{}:{} does not specify revision, using:{}:{}"
167 + " for module dependency sort", toName, formatRevDate(toRevision), fromName,
168 formatRevDate(fromRevision), first.getName(), formatRevDate(first.getRevision()));
174 LOG.warn("Not existing module imported:{}:{} by:{}:{}", toName, formatRevDate(toRevision), fromName,
175 formatRevDate(fromRevision));
176 LOG.warn("Available models: {}", moduleGraph);
177 throw new YangValidationException(String.format("Not existing module imported:%s:%s by:%s:%s", toName,
178 formatRevDate(toRevision), fromName, formatRevDate(fromRevision)));
182 * Extract dependencies from module builders or modules to fill dependency
185 private static void processModules(final Table<String, Date, ModuleNodeImpl> moduleGraph,
186 final Iterable<Module> modules) {
189 for (final Module momb : modules) {
191 final String name = momb.getName();
192 Date rev = momb.getRevision();
194 rev = DEFAULT_REVISION;
197 final Map<Date, ModuleNodeImpl> revs = moduleGraph.row(name);
198 if (revs.containsKey(rev)) {
199 throw new YangValidationException(String.format("Module:%s with revision:%s declared twice", name,
200 formatRevDate(rev)));
203 revs.put(rev, new ModuleNodeImpl(name, rev, momb));
207 private static String formatRevDate(final Date rev) {
208 return rev.equals(DEFAULT_REVISION) ? "default" : SimpleDateFormatUtil.getRevisionFormat().format(rev);
212 static class ModuleNodeImpl extends NodeImpl {
213 private final String name;
214 private final Date revision;
215 private final Module originalObject;
217 public ModuleNodeImpl(final String name, final Date revision, final Module module) {
219 this.revision = revision;
220 this.originalObject = module;
223 public String getName() {
227 public Date getRevision() {
232 public int hashCode() {
233 final int prime = 31;
235 result = prime * result + Objects.hashCode(name);
236 result = prime * result + Objects.hashCode(revision);
241 public boolean equals(final Object obj) {
248 if (getClass() != obj.getClass()) {
251 final ModuleNodeImpl other = (ModuleNodeImpl) obj;
253 if (other.name != null) {
256 } else if (!name.equals(other.name)) {
259 if (revision == null) {
260 if (other.revision != null) {
263 } else if (!revision.equals(other.revision)) {
270 public String toString() {
271 return "Module [name=" + name + ", revision=" + formatRevDate(revision) + "]";
274 public Module getReference() {
275 return originalObject;