1 /*
   2  * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 package com.sun.tools.jdeps;
  26 
  27 import static java.lang.module.ModuleDescriptor.Requires.Modifier.*;
  28 import static java.util.stream.Collectors.*;
  29 
  30 import java.io.BufferedWriter;
  31 import java.io.IOException;
  32 import java.io.PrintWriter;
  33 import java.lang.module.Configuration;
  34 import java.lang.module.ModuleDescriptor;
  35 import java.lang.module.ModuleFinder;
  36 import java.lang.module.ModuleReference;
  37 import java.lang.module.ResolvedModule;
  38 import java.nio.file.Files;
  39 import java.nio.file.Path;
  40 import java.util.ArrayDeque;
  41 import java.util.ArrayList;
  42 import java.util.Deque;
  43 import java.util.HashMap;
  44 import java.util.HashSet;
  45 import java.util.List;
  46 import java.util.Map;
  47 import java.util.Objects;
  48 import java.util.Set;
  49 import java.util.TreeSet;
  50 import java.util.function.Function;
  51 import java.util.stream.Collectors;
  52 import java.util.stream.Stream;
  53 
  54 /**
  55  * Generate dot graph for modules
  56  */
  57 public class ModuleDotGraph {
  58     private final Map<String, Configuration> configurations;
  59     private final boolean apiOnly;
  60     public ModuleDotGraph(JdepsConfiguration config, boolean apiOnly) {
  61         this(config.rootModules().stream()
  62                    .map(Module::name)
  63                    .sorted()
  64                    .collect(toMap(Function.identity(), mn -> config.resolve(Set.of(mn)))),
  65              apiOnly);
  66     }
  67 
  68     public ModuleDotGraph(Map<String, Configuration> configurations, boolean apiOnly) {
  69         this.configurations = configurations;
  70         this.apiOnly = apiOnly;
  71     }
  72 
  73     /**
  74      * Generate dotfile for all modules
  75      *
  76      * @param dir output directory
  77      */
  78     public boolean genDotFiles(Path dir) throws IOException {
  79         Files.createDirectories(dir);
  80         for (String mn : configurations.keySet()) {
  81             Path path = dir.resolve(mn + ".dot");
  82             genDotFile(path, mn, configurations.get(mn));
  83         }
  84         return true;
  85     }
  86 
  87     /**
  88      * Generate dotfile of the given path
  89      */
  90     public void genDotFile(Path path, String name, Configuration configuration)
  91         throws IOException
  92     {
  93         // transitive reduction
  94         Graph<String> graph = apiOnly
  95                 ? requiresTransitiveGraph(configuration, Set.of(name))
  96                 : gengraph(configuration);
  97 
  98         DotGraphBuilder builder = new DotGraphBuilder(name, graph);
  99         builder.descriptors(graph.nodes().stream()
 100                                  .map(mn -> configuration.findModule(mn).get()
 101                                                 .reference().descriptor()));
 102         builder.subgraph("se", "java", DotGraphBuilder.ORANGE,
 103                          DotGraphBuilder.JAVA_SE_SUBGRAPH);
 104         builder.subgraph("jdk", "jdk",
 105                          DotGraphBuilder.BLUE, DotGraphBuilder.JDK_SUBGRAPH);
 106         builder.build(path);
 107     }
 108 
 109     /**
 110      * Returns a Graph of the given Configuration after transitive reduction.
 111      *
 112      * Transitive reduction of requires transitive edge and requires edge have
 113      * to be applied separately to prevent the requires transitive edges
 114      * (e.g. U -> V) from being reduced by a path (U -> X -> Y -> V)
 115      * in which  V would not be re-exported from U.
 116      */
 117     private Graph<String> gengraph(Configuration cf) {
 118         Graph.Builder<String> builder = new Graph.Builder<>();
 119         cf.modules().stream()
 120             .forEach(resolvedModule -> {
 121                 String mn = resolvedModule.reference().descriptor().name();
 122                 builder.addNode(mn);
 123                 resolvedModule.reads().stream()
 124                     .map(ResolvedModule::name)
 125                     .forEach(target -> builder.addEdge(mn, target));
 126             });
 127 
 128         Graph<String> rpg = requiresTransitiveGraph(cf, builder.nodes);
 129         return builder.build().reduce(rpg);
 130     }
 131 
 132 
 133     /**
 134      * Returns a Graph containing only requires transitive edges
 135      * with transitive reduction.
 136      */
 137     public Graph<String> requiresTransitiveGraph(Configuration cf,
 138                                                  Set<String> roots)
 139     {
 140         Deque<String> deque = new ArrayDeque<>(roots);
 141         Set<String> visited = new HashSet<>();
 142         Graph.Builder<String> builder = new Graph.Builder<>();
 143 
 144         while (deque.peek() != null) {
 145             String mn = deque.pop();
 146             if (visited.contains(mn))
 147                 continue;
 148 
 149             visited.add(mn);
 150             builder.addNode(mn);
 151             ModuleDescriptor descriptor = cf.findModule(mn).get()
 152                 .reference().descriptor();
 153             descriptor.requires().stream()
 154                 .filter(d -> d.modifiers().contains(TRANSITIVE)
 155                                 || d.name().equals("java.base"))
 156                 .map(d -> d.name())
 157                 .forEach(d -> {
 158                     deque.add(d);
 159                     builder.addEdge(mn, d);
 160                 });
 161         }
 162 
 163         return builder.build().reduce();
 164     }
 165 
 166     public static class DotGraphBuilder {
 167         static final Set<String> JAVA_SE_SUBGRAPH = javaSE();
 168         static final Set<String> JDK_SUBGRAPH = jdk();
 169 
 170         private static Set<String> javaSE() {
 171             String root = "java.se.ee";
 172             ModuleFinder system = ModuleFinder.ofSystem();
 173             if (system.find(root).isPresent()) {
 174                 return Stream.concat(Stream.of(root),
 175                                      Configuration.empty().resolve(system,
 176                                                                    ModuleFinder.of(),
 177                                                                    Set.of(root))
 178                                                   .findModule(root).get()
 179                                                   .reads().stream()
 180                                                   .map(ResolvedModule::name))
 181                              .collect(toSet());
 182             } else {
 183                 // approximation
 184                 return system.findAll().stream()
 185                     .map(ModuleReference::descriptor)
 186                     .map(ModuleDescriptor::name)
 187                     .filter(name -> name.startsWith("java.") &&
 188                                         !name.equals("java.smartcardio"))
 189                     .collect(Collectors.toSet());
 190             }
 191         }
 192 
 193         private static Set<String> jdk() {
 194             return ModuleFinder.ofSystem().findAll().stream()
 195                     .map(ModuleReference::descriptor)
 196                     .map(ModuleDescriptor::name)
 197                     .filter(name -> !JAVA_SE_SUBGRAPH.contains(name) &&
 198                                         (name.startsWith("java.") ||
 199                                             name.startsWith("jdk.") ||
 200                                             name.startsWith("javafx.")))
 201                     .collect(Collectors.toSet());
 202         }
 203 
 204         static class SubGraph {
 205             final String name;
 206             final String group;
 207             final String color;
 208             final Set<String> nodes;
 209             SubGraph(String name, String group, String color, Set<String> nodes) {
 210                 this.name = Objects.requireNonNull(name);
 211                 this.group = Objects.requireNonNull(group);
 212                 this.color = Objects.requireNonNull(color);
 213                 this.nodes = Objects.requireNonNull(nodes);
 214             }
 215         }
 216 
 217         static final String ORANGE = "#e76f00";
 218         static final String BLUE = "#437291";
 219         static final String GRAY = "#dddddd";
 220         static final String BLACK = "#000000";
 221 
 222         static final String FONT_NAME = "DejaVuSans";
 223         static final int FONT_SIZE = 12;
 224         static final int ARROW_SIZE = 1;
 225         static final int ARROW_WIDTH = 2;
 226         static final int RANK_SEP = 1;
 227 
 228         static final String REEXPORTS = "";
 229         static final String REQUIRES = "style=\"dashed\"";
 230         static final String REQUIRES_BASE = "color=\"" + GRAY + "\"";
 231 
 232         // can be configured
 233         static double rankSep   = RANK_SEP;
 234         static String fontColor = BLACK;
 235         static String fontName  = FONT_NAME;
 236         static int fontsize     = FONT_SIZE;
 237         static int arrowWidth   = ARROW_WIDTH;
 238         static int arrowSize    = ARROW_SIZE;
 239         static final Map<String, Integer> weights = new HashMap<>();
 240         static final List<Set<String>> ranks = new ArrayList<>();
 241 
 242         private final String name;
 243         private final Graph<String> graph;
 244         private final Set<ModuleDescriptor> descriptors = new TreeSet<>();
 245         private final List<SubGraph> subgraphs = new ArrayList<>();
 246         public DotGraphBuilder(String name, Graph<String> graph) {
 247             this.name = name;
 248             this.graph = graph;
 249         }
 250 
 251         public DotGraphBuilder descriptors(Stream<ModuleDescriptor> descriptors) {
 252             descriptors.forEach(this.descriptors::add);
 253             return this;
 254         }
 255 
 256         public void build(Path filename) throws IOException {
 257             try (BufferedWriter writer = Files.newBufferedWriter(filename);
 258                  PrintWriter out = new PrintWriter(writer)) {
 259 
 260                 out.format("digraph \"%s\" {%n", name);
 261                 out.format("  nodesep=.5;%n");
 262                 out.format("  ranksep=%f;%n", rankSep);
 263                 out.format("  pencolor=transparent;%n");
 264                 out.format("  node [shape=plaintext, fontname=\"%s\", fontsize=%d, margin=\".2,.2\"];%n",
 265                            fontName, fontsize);
 266                 out.format("  edge [penwidth=%d, color=\"#999999\", arrowhead=open, arrowsize=%d];%n",
 267                            arrowWidth, arrowSize);
 268 
 269                 // same RANKS
 270                 ranks.stream()
 271                      .map(nodes -> descriptors.stream()
 272                                         .map(ModuleDescriptor::name)
 273                                         .filter(nodes::contains)
 274                                         .map(mn -> "\"" + mn + "\"")
 275                                         .collect(joining(",")))
 276                      .filter(group -> group.length() > 0)
 277                      .forEach(group -> out.format("  {rank=same %s}%n", group));
 278 
 279                 subgraphs.forEach(subgraph -> {
 280                     out.format("  subgraph %s {%n", subgraph.name);
 281                     descriptors.stream()
 282                         .map(ModuleDescriptor::name)
 283                         .filter(subgraph.nodes::contains)
 284                         .forEach(mn -> printNode(out, mn, subgraph.color, subgraph.group));
 285                     out.format("  }%n");
 286                 });
 287 
 288                 descriptors.stream()
 289                     .filter(md -> graph.contains(md.name()) &&
 290                                     !graph.adjacentNodes(md.name()).isEmpty())
 291                     .forEach(md -> printNode(out, md, graph.adjacentNodes(md.name())));
 292 
 293                 out.println("}");
 294             }
 295         }
 296 
 297         public DotGraphBuilder subgraph(String name, String group, String color,
 298                                  Set<String> nodes) {
 299             subgraphs.add(new SubGraph(name, group, color, nodes));
 300             return this;
 301         }
 302 
 303         public void printNode(PrintWriter out, String node, String color, String group) {
 304             out.format("  \"%s\" [fontcolor=\"%s\", group=%s];%n",
 305                        node, color, group);
 306         }
 307 
 308         public void printNode(PrintWriter out, ModuleDescriptor md, Set<String> edges) {
 309             Set<String> requiresTransitive = md.requires().stream()
 310                 .filter(d -> d.modifiers().contains(TRANSITIVE))
 311                 .map(d -> d.name())
 312                 .collect(toSet());
 313 
 314             String mn = md.name();
 315             edges.stream().forEach(dn -> {
 316                 String attr = dn.equals("java.base") ? REQUIRES_BASE
 317                     : (requiresTransitive.contains(dn) ? REEXPORTS : REQUIRES);
 318 
 319                 int w = weightOf(mn, dn);
 320                 if (w > 1) {
 321                     if (!attr.isEmpty())
 322                         attr += ", ";
 323 
 324                     attr += "weight=" + w;
 325                 }
 326                 out.format("  \"%s\" -> \"%s\" [%s];%n", mn, dn, attr);
 327             });
 328         }
 329 
 330         public int weightOf(String s, String t) {
 331             int w = weights.getOrDefault(s + ":" + t, 1);
 332             if (w != 1)
 333                 return w;
 334             if (s.startsWith("java.") && t.startsWith("java."))
 335                 return 10;
 336             return 1;
 337         }
 338 
 339         public static void sameRankNodes(Set<String> nodes) {
 340             ranks.add(nodes);
 341         }
 342 
 343         public static void weight(String s, String t, int w) {
 344             weights.put(s + ":" + t, w);
 345         }
 346 
 347         public static void setRankSep(double value) {
 348             rankSep = value;
 349         }
 350 
 351         public static void setFontSize(int size) {
 352             fontsize = size;
 353         }
 354 
 355         public static void setFontColor(String color) {
 356             fontColor = color;
 357         }
 358 
 359         public static void setArrowSize(int size) {
 360             arrowSize = size;
 361         }
 362 
 363         public static void setArrowWidth(int width) {
 364             arrowWidth = width;
 365         }
 366     }
 367 }