Merge branch 'master' of ../controller
[yangtools.git] / yang / yang-model-util / src / main / java / org / opendaylight / yangtools / yang / model / util / ModuleDependencySort.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.model.util;
9
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;
14 import java.net.URI;
15 import java.util.Arrays;
16 import java.util.Collection;
17 import java.util.HashMap;
18 import java.util.HashSet;
19 import java.util.LinkedHashSet;
20 import java.util.List;
21 import java.util.Map;
22 import java.util.Objects;
23 import java.util.Optional;
24 import org.opendaylight.yangtools.util.TopologicalSort;
25 import org.opendaylight.yangtools.util.TopologicalSort.Node;
26 import org.opendaylight.yangtools.util.TopologicalSort.NodeImpl;
27 import org.opendaylight.yangtools.yang.common.Revision;
28 import org.opendaylight.yangtools.yang.common.YangVersion;
29 import org.opendaylight.yangtools.yang.model.api.Module;
30 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 /**
35  * Creates a module dependency graph from provided {@link Module}s and provides a {@link #sort(Collection)} method.
36  * It is topological sort and returns modules in order in which they should be processed (e.g. if A imports B, sort
37  * returns {B, A}).
38  */
39 @Beta
40 public final class ModuleDependencySort {
41     private static final Logger LOG = LoggerFactory.getLogger(ModuleDependencySort.class);
42
43     /**
44      * It is not desirable to instance this class.
45      */
46     private ModuleDependencySort() {
47         throw new UnsupportedOperationException();
48     }
49
50     /**
51      * Topological sort of module dependency graph.
52      *
53      * @param modules YANG modules
54      * @return Sorted list of Modules. Modules can be further processed in returned order.
55      * @throws IllegalArgumentException when provided modules are not consistent.
56      */
57     public static List<Module> sort(final Module... modules) {
58         return sort(Arrays.asList(modules));
59     }
60
61     /**
62      * Topological sort of module dependency graph.
63      *
64      * @param modules YANG modules
65      * @return Sorted list of Modules. Modules can be further processed in returned order.
66      * @throws IllegalArgumentException when provided modules are not consistent.
67      */
68     public static List<Module> sort(final Collection<Module> modules) {
69         final List<Node> sorted = sortInternal(modules);
70         // Cast to Module from Node and return
71         return Lists.transform(sorted, input -> input == null ? null : ((ModuleNodeImpl) input).getReference());
72     }
73
74     private static List<Node> sortInternal(final Collection<Module> modules) {
75         final Table<String, Optional<Revision>, ModuleNodeImpl> moduleGraph = createModuleGraph(modules);
76         return TopologicalSort.sort(new HashSet<>(moduleGraph.values()));
77     }
78
79     private static Table<String, Optional<Revision>, ModuleNodeImpl> createModuleGraph(
80             final Collection<Module> builders) {
81         final Table<String, Optional<Revision>, ModuleNodeImpl> moduleGraph = HashBasedTable.create();
82
83         processModules(moduleGraph, builders);
84         processDependencies(moduleGraph, builders);
85
86         return moduleGraph;
87     }
88
89     /**
90      * Extract module:revision from modules.
91      */
92     private static void processDependencies(final Table<String, Optional<Revision>, ModuleNodeImpl> moduleGraph,
93             final Collection<Module> mmbs) {
94         final Map<URI, Module> allNS = new HashMap<>();
95
96         // Create edges in graph
97         for (final Module module : mmbs) {
98             final Map<String, Optional<Revision>> imported = new HashMap<>();
99             final String fromName = module.getName();
100             final URI ns = module.getNamespace();
101             final Optional<Revision> fromRevision = module.getRevision();
102
103             // check for existence of module with same namespace
104             final Module prev = allNS.putIfAbsent(ns, module);
105             if (prev != null) {
106                 final String name = prev.getName();
107                 if (!fromName.equals(name)) {
108                     LOG.warn("Error while sorting module [{}, {}]: module with same namespace ({}) already loaded:"
109                         + " [{}, {}]", fromName, fromRevision, ns, name, prev.getRevision());
110                 }
111             }
112
113             // no need to check if other Type of object, check is performed in process modules
114             for (final ModuleImport imprt : allImports(module)) {
115                 final String toName = imprt.getModuleName();
116                 final Optional<Revision> toRevision = imprt.getRevision();
117
118                 final ModuleNodeImpl from = moduleGraph.get(fromName, fromRevision);
119                 final ModuleNodeImpl to = getModuleByNameAndRevision(moduleGraph, fromName, fromRevision, toName,
120                     toRevision);
121
122                 /*
123                  * If it is an yang 1 module, check imports: If module is imported twice with different
124                  * revisions then throw exception
125                  */
126                 if (module.getYangVersion() == YangVersion.VERSION_1) {
127                     final Optional<Revision> impRevision = imported.get(toName);
128                     if (impRevision != null && impRevision.isPresent() && !impRevision.equals(toRevision)
129                             && toRevision.isPresent()) {
130                         throw new IllegalArgumentException(String.format(
131                             "Module:%s imported twice with different revisions:%s, %s", toName,
132                             formatRevDate(impRevision), formatRevDate(toRevision)));
133                     }
134                 }
135
136                 imported.put(toName, toRevision);
137
138                 from.addEdge(to);
139             }
140         }
141     }
142
143     private static Collection<ModuleImport> allImports(final Module mod) {
144         if (mod.getSubmodules().isEmpty()) {
145             return mod.getImports();
146         }
147
148         final Collection<ModuleImport> concat = new LinkedHashSet<>();
149         concat.addAll(mod.getImports());
150         for (Module sub : mod.getSubmodules()) {
151             concat.addAll(sub.getImports());
152         }
153         return concat;
154     }
155
156     /**
157      * Get imported module by its name and revision from moduleGraph.
158      */
159     private static ModuleNodeImpl getModuleByNameAndRevision(
160             final Table<String, Optional<Revision>, ModuleNodeImpl> moduleGraph, final String fromName,
161             final Optional<Revision> fromRevision, final String toName, final Optional<Revision> toRevision) {
162
163         final ModuleNodeImpl exact = moduleGraph.get(toName, toRevision);
164         if (exact != null) {
165             return exact;
166         }
167
168         // If revision is not specified in import, but module exists with different revisions, take first one
169         if (toRevision.isEmpty()) {
170             final Map<Optional<Revision>, ModuleNodeImpl> modulerevs = moduleGraph.row(toName);
171
172             if (!modulerevs.isEmpty()) {
173                 final ModuleNodeImpl first = modulerevs.values().iterator().next();
174                 if (LOG.isTraceEnabled()) {
175                     LOG.trace("Import:{}:{} by module:{}:{} does not specify revision, using:{}:{}"
176                             + " for module dependency sort", toName, formatRevDate(toRevision), fromName,
177                             formatRevDate(fromRevision), first.getName(), formatRevDate(first.getRevision()));
178                 }
179                 return first;
180             }
181         }
182
183         LOG.warn("Not existing module imported:{}:{} by:{}:{}", toName, formatRevDate(toRevision), fromName,
184             formatRevDate(fromRevision));
185         LOG.warn("Available models: {}", moduleGraph);
186         throw new IllegalArgumentException(String.format("Not existing module imported:%s:%s by:%s:%s", toName,
187             formatRevDate(toRevision), fromName, formatRevDate(fromRevision)));
188     }
189
190     /**
191      * Extract dependencies from modules to fill dependency graph.
192      */
193     private static void processModules(final Table<String, Optional<Revision>, ModuleNodeImpl> moduleGraph,
194             final Iterable<Module> modules) {
195
196         // Process nodes
197         for (final Module momb : modules) {
198
199             final String name = momb.getName();
200             final Optional<Revision> rev = momb.getRevision();
201             final Map<Optional<Revision>, ModuleNodeImpl> revs = moduleGraph.row(name);
202             if (revs.containsKey(rev)) {
203                 throw new IllegalArgumentException(String.format("Module:%s with revision:%s declared twice", name,
204                     formatRevDate(rev)));
205             }
206
207             revs.put(rev, new ModuleNodeImpl(name, rev.orElse(null), momb));
208         }
209     }
210
211     private static String formatRevDate(final Optional<Revision> rev) {
212         return rev.map(Revision::toString).orElse("default");
213     }
214
215     private static final class ModuleNodeImpl extends NodeImpl {
216         private final String name;
217         private final Revision revision;
218         private final Module originalObject;
219
220         ModuleNodeImpl(final String name, final Revision revision, final Module module) {
221             this.name = name;
222             this.revision = revision;
223             this.originalObject = module;
224         }
225
226         String getName() {
227             return name;
228         }
229
230         Optional<Revision> getRevision() {
231             return Optional.ofNullable(revision);
232         }
233
234         @Override
235         public int hashCode() {
236             final int prime = 31;
237             int result = 1;
238             result = prime * result + Objects.hashCode(name);
239             result = prime * result + Objects.hashCode(revision);
240             return result;
241         }
242
243         @Override
244         public boolean equals(final Object obj) {
245             if (this == obj) {
246                 return true;
247             }
248             if (obj == null) {
249                 return false;
250             }
251             if (getClass() != obj.getClass()) {
252                 return false;
253             }
254             final ModuleNodeImpl other = (ModuleNodeImpl) obj;
255             if (name == null) {
256                 if (other.name != null) {
257                     return false;
258                 }
259             } else if (!name.equals(other.name)) {
260                 return false;
261             }
262             if (revision == null) {
263                 if (other.revision != null) {
264                     return false;
265                 }
266             } else if (!revision.equals(other.revision)) {
267                 return false;
268             }
269             return true;
270         }
271
272         @Override
273         public String toString() {
274             return "Module [name=" + name + ", revision=" + formatRevDate(getRevision()) + "]";
275         }
276
277         public Module getReference() {
278             return originalObject;
279         }
280     }
281 }