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