3db3065d55e1adc2c3e0392cb72892ff09f3883b
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / 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.parser.util;
9
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;
15 import java.net.URI;
16 import java.util.ArrayList;
17 import java.util.Arrays;
18 import java.util.Collection;
19 import java.util.Collections;
20 import java.util.Date;
21 import java.util.HashMap;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Set;
25
26 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
27 import org.opendaylight.yangtools.yang.model.api.Module;
28 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
29 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
30 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
31 import org.opendaylight.yangtools.yang.parser.util.TopologicalSort.Node;
32 import org.opendaylight.yangtools.yang.parser.util.TopologicalSort.NodeImpl;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 /**
37  * Creates a module dependency graph from provided {@link ModuleBuilder}s and
38  * provides a {@link #sort(ModuleBuilder...)} method. It is topological sort and
39  * returns modules in order in which they should be processed (e.g. if A imports
40  * B, sort returns {B, A}).
41  */
42 public final class ModuleDependencySort {
43
44     private static final Date DEFAULT_REVISION = new Date(0);
45     private static final Logger LOGGER = LoggerFactory.getLogger(ModuleDependencySort.class);
46
47     /**
48      * It is not desirable to instance this class
49      */
50     private ModuleDependencySort() {
51     }
52
53     /**
54      * Extracts {@link ModuleBuilder} from a {@link ModuleNodeImpl}.
55      */
56     private static final Function<Node, ModuleBuilder> NODE_TO_MODULEBUILDER = new Function<Node, ModuleBuilder>() {
57         @Override
58         public ModuleBuilder apply(final Node input) {
59             // Cast to ModuleBuilder from Node and return
60             return (ModuleBuilder) ((ModuleNodeImpl) input).getReference();
61         }
62     };
63
64     /**
65      * Topological sort of module builder dependency graph.
66      *
67      * @return Sorted list of Module builders. Modules can be further processed
68      *         in returned order.
69      */
70     public static List<ModuleBuilder> sort(final ModuleBuilder... builders) {
71         List<Node> sorted = sortInternal(Arrays.asList(builders));
72         return Lists.transform(sorted, NODE_TO_MODULEBUILDER);
73     }
74
75     public static List<ModuleBuilder> sort(final Collection<ModuleBuilder> builders) {
76         ModuleBuilder[] array = new ModuleBuilder[builders.size()];
77         builders.toArray(array);
78         return sort(array);
79     }
80
81     public static List<ModuleBuilder> sortWithContext(final SchemaContext context, final ModuleBuilder... builders) {
82         List<Object> modules = new ArrayList<Object>();
83         Collections.addAll(modules, builders);
84         modules.addAll(context.getModules());
85
86         List<Node> sorted = sortInternal(modules);
87         // Cast to ModuleBuilder from Node if possible and return
88         return Lists.transform(sorted, new Function<Node, ModuleBuilder>() {
89
90             @Override
91             public ModuleBuilder apply(final Node input) {
92                 if (((ModuleNodeImpl) input).getReference() instanceof ModuleBuilder) {
93                     return (ModuleBuilder) ((ModuleNodeImpl) input).getReference();
94                 } else {
95                     return null;
96                 }
97             }
98         });
99     }
100
101     /**
102      * Topological sort of module dependency graph.
103      *
104      * @return Sorted list of Modules. Modules can be further processed in
105      *         returned order.
106      */
107     public static List<Module> sort(final Module... modules) {
108         List<Node> sorted = sortInternal(Arrays.asList(modules));
109         // Cast to Module from Node and return
110         return Lists.transform(sorted, new Function<Node, Module>() {
111
112             @Override
113             public Module apply(final Node input) {
114                 return (Module) ((ModuleNodeImpl) input).getReference();
115             }
116         });
117     }
118
119     private static List<Node> sortInternal(final List<?> modules) {
120         Map<String, Map<Date, ModuleNodeImpl>> moduleGraph = createModuleGraph(modules);
121
122         Set<Node> nodes = Sets.newHashSet();
123         for (Map<Date, ModuleNodeImpl> map : moduleGraph.values()) {
124             for (ModuleNodeImpl node : map.values()) {
125                 nodes.add(node);
126             }
127         }
128
129         return TopologicalSort.sort(nodes);
130     }
131
132     @VisibleForTesting
133     static Map<String, Map<Date, ModuleNodeImpl>> createModuleGraph(final List<?> builders) {
134         Map<String, Map<Date, ModuleNodeImpl>> moduleGraph = Maps.newHashMap();
135
136         processModules(moduleGraph, builders);
137         processDependencies(moduleGraph, builders);
138
139         return moduleGraph;
140     }
141
142     /**
143      * Extract module:revision from module builders
144      */
145     private static void processDependencies(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph, final List<?> builders) {
146         Map<URI, Object> allNS = new HashMap<>();
147
148         // Create edges in graph
149         for (Object mb : builders) {
150             Map<String, Date> imported = Maps.newHashMap();
151
152             String fromName = null;
153             Date fromRevision = null;
154             Set<ModuleImport> imports = null;
155             URI ns = null;
156
157             if (mb instanceof Module) {
158                 fromName = ((Module) mb).getName();
159                 fromRevision = ((Module) mb).getRevision();
160                 imports = ((Module) mb).getImports();
161                 ns = ((Module)mb).getNamespace();
162             } else if (mb instanceof ModuleBuilder) {
163                 fromName = ((ModuleBuilder) mb).getName();
164                 fromRevision = ((ModuleBuilder) mb).getRevision();
165                 imports = ((ModuleBuilder) mb).getModuleImports();
166                 ns = ((ModuleBuilder)mb).getNamespace();
167             }
168
169             // check for existence of module with same namespace
170             if (allNS.containsKey(ns)) {
171                 Object mod = allNS.get(ns);
172                 String name = null;
173                 Date revision = null;
174                 if (mod instanceof Module) {
175                     name = ((Module) mod).getName();
176                     revision = ((Module) mod).getRevision();
177                 } else if (mod instanceof ModuleBuilder) {
178                     name = ((ModuleBuilder) mod).getName();
179                     revision = ((ModuleBuilder) mod).getRevision();
180                 }
181                 if (!(fromName.equals(name))) {
182                     LOGGER.warn(
183                             "Error while sorting module [{}, {}]: module with same namespace ({}) already loaded: [{}, {}]",
184                             fromName, fromRevision, ns, name, revision);
185                 }
186             } else {
187                 allNS.put(ns, mb);
188             }
189
190             // no need to check if other Type of object, check is performed in
191             // process modules
192
193             if (fromRevision == null) {
194                 fromRevision = DEFAULT_REVISION;
195             }
196
197             for (ModuleImport imprt : imports) {
198                 String toName = imprt.getModuleName();
199                 Date toRevision = imprt.getRevision() == null ? DEFAULT_REVISION : imprt.getRevision();
200
201                 ModuleNodeImpl from = moduleGraph.get(fromName).get(fromRevision);
202
203                 ModuleNodeImpl to = getModuleByNameAndRevision(moduleGraph, fromName, fromRevision, toName, toRevision);
204
205                 /*
206                  * Check imports: If module is imported twice with different
207                  * revisions then throw exception
208                  */
209                 if (imported.get(toName) != null && !imported.get(toName).equals(toRevision)
210                         && !imported.get(toName).equals(DEFAULT_REVISION) && !toRevision.equals(DEFAULT_REVISION)) {
211                     ex(String.format("Module:%s imported twice with different revisions:%s, %s", toName,
212                             formatRevDate(imported.get(toName)), formatRevDate(toRevision)));
213                 }
214
215                 imported.put(toName, toRevision);
216
217                 from.addEdge(to);
218             }
219         }
220     }
221
222     /**
223      * Get imported module by its name and revision from moduleGraph
224      */
225     private static ModuleNodeImpl getModuleByNameAndRevision(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph,
226             final String fromName, final Date fromRevision, final String toName, final Date toRevision) {
227         ModuleNodeImpl to = null;
228
229         if (moduleGraph.get(toName) == null || !moduleGraph.get(toName).containsKey(toRevision)) {
230             // If revision is not specified in import, but module exists
231             // with different revisions, take first
232             if (moduleGraph.get(toName) != null && !moduleGraph.get(toName).isEmpty()
233                     && toRevision.equals(DEFAULT_REVISION)) {
234                 to = moduleGraph.get(toName).values().iterator().next();
235                 LOGGER.trace(String
236                         .format("Import:%s:%s by module:%s:%s does not specify revision, using:%s:%s for module dependency sort",
237                                 toName, formatRevDate(toRevision), fromName, formatRevDate(fromRevision), to.getName(),
238                                 formatRevDate(to.getRevision())));
239             } else {
240                 LOGGER.warn(String.format("Not existing module imported:%s:%s by:%s:%s", toName,
241                         formatRevDate(toRevision), fromName, formatRevDate(fromRevision)));
242                 LOGGER.warn("Available models: {}", moduleGraph);
243                 ex(String.format("Not existing module imported:%s:%s by:%s:%s", toName, formatRevDate(toRevision),
244                         fromName, formatRevDate(fromRevision)));
245             }
246         } else {
247             to = moduleGraph.get(toName).get(toRevision);
248         }
249         return to;
250     }
251
252     private static void ex(final String message) {
253         throw new YangValidationException(message);
254     }
255
256     /**
257      * Extract dependencies from module builders or modules to fill dependency
258      * graph
259      */
260     private static void processModules(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph, final List<?> builders) {
261
262         // Process nodes
263         for (Object mb : builders) {
264
265             String name = null;
266             Date rev = null;
267
268             if (mb instanceof Module) {
269                 name = ((Module) mb).getName();
270                 rev = ((Module) mb).getRevision();
271             } else if (mb instanceof ModuleBuilder) {
272                 name = ((ModuleBuilder) mb).getName();
273                 rev = ((ModuleBuilder) mb).getRevision();
274             } else {
275                 throw new IllegalStateException(String.format(
276                         "Unexpected type of node for sort, expected only:%s, %s, got:%s", Module.class,
277                         ModuleBuilder.class, mb.getClass()));
278             }
279
280             if (rev == null) {
281                 rev = DEFAULT_REVISION;
282             }
283
284             if (moduleGraph.get(name) == null) {
285                 moduleGraph.put(name, Maps.<Date, ModuleNodeImpl> newHashMap());
286             }
287
288             if (moduleGraph.get(name).get(rev) != null) {
289                 ex(String.format("Module:%s with revision:%s declared twice", name, formatRevDate(rev)));
290             }
291
292             moduleGraph.get(name).put(rev, new ModuleNodeImpl(name, rev, mb));
293         }
294     }
295
296     private static String formatRevDate(final Date rev) {
297         return rev.equals(DEFAULT_REVISION) ? "default" : SimpleDateFormatUtil.getRevisionFormat().format(rev);
298     }
299
300     @VisibleForTesting
301     static class ModuleNodeImpl extends NodeImpl {
302         private final String name;
303         private final Date revision;
304         private final Object originalObject;
305
306         public ModuleNodeImpl(final String name, final Date revision, final Object builder) {
307             this.name = name;
308             this.revision = revision;
309             this.originalObject = builder;
310         }
311
312         public String getName() {
313             return name;
314         }
315
316         public Date getRevision() {
317             return revision;
318         }
319
320         @Override
321         public int hashCode() {
322             final int prime = 31;
323             int result = 1;
324             result = prime * result + ((name == null) ? 0 : name.hashCode());
325             result = prime * result + ((revision == null) ? 0 : revision.hashCode());
326             return result;
327         }
328
329         @Override
330         public boolean equals(final Object obj) {
331             if (this == obj) {
332                 return true;
333             }
334             if (obj == null) {
335                 return false;
336             }
337             if (getClass() != obj.getClass()) {
338                 return false;
339             }
340             ModuleNodeImpl other = (ModuleNodeImpl) obj;
341             if (name == null) {
342                 if (other.name != null) {
343                     return false;
344                 }
345             } else if (!name.equals(other.name)) {
346                 return false;
347             }
348             if (revision == null) {
349                 if (other.revision != null) {
350                     return false;
351                 }
352             } else if (!revision.equals(other.revision)) {
353                 return false;
354             }
355             return true;
356         }
357
358         @Override
359         public String toString() {
360             return "Module [name=" + name + ", revision=" + formatRevDate(revision) + "]";
361         }
362
363         public Object getReference() {
364             return originalObject;
365         }
366
367     }
368
369 }