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