DependencyGraph.java 10.3 KB
Newer Older
1 2
package hudson.model;

3 4 5 6 7 8 9 10
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.graph_layouter.Layout;
import org.kohsuke.graph_layouter.Navigator;
import org.kohsuke.graph_layouter.Direction;

import javax.servlet.ServletOutputStream;
import javax.imageio.ImageIO;
11 12 13 14 15 16 17
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
K
kohsuke 已提交
18 19 20
import java.util.Set;
import java.util.HashSet;
import java.util.Stack;
21
import java.util.Map.Entry;
22 23 24 25 26 27 28 29 30 31 32
import java.io.IOException;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.Graphics2D;
import java.awt.Color;
import java.awt.Point;
import java.awt.HeadlessException;
import java.awt.FontMetrics;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127

/**
 * Maintains the build dependencies between {@link AbstractProject}s
 * for efficient dependency computation.
 *
 * <p>
 * The "master" data of dependencies are owned/persisted/maintained by
 * individual {@link AbstractProject}s, but because of that, it's relatively
 * slow  to compute backward edges.
 *
 * <p>
 * This class builds the complete bi-directional dependency graph
 * by collecting information from all {@link AbstractProject}s.
 *
 * <p>
 * Once built, {@link DependencyGraph} is immutable, and every time
 * there's a change (which is relatively rare), a new instance
 * will be created. This eliminates the need of synchronization.
 *
 * @author Kohsuke Kawaguchi
 */
public final class DependencyGraph {

    private Map<AbstractProject, List<AbstractProject>> forward = new HashMap<AbstractProject, List<AbstractProject>>();
    private Map<AbstractProject, List<AbstractProject>> backward = new HashMap<AbstractProject, List<AbstractProject>>();

    private boolean built;

    /**
     * Builds the dependency graph.
     */
    public DependencyGraph() {
        for( AbstractProject p : Hudson.getInstance().getAllItems(AbstractProject.class) )
            p.buildDependencyGraph(this);

        forward = finalize(forward);
        backward = finalize(backward);

        built = true;
    }

    /**
     * Special constructor for creating an empty graph
     */
    private DependencyGraph(boolean dummy) {
        forward = backward = Collections.emptyMap();
        built = true;
    }

    /**
     * Gets all the immediate downstream projects (IOW forward edges) of the given project.
     *
     * @return
     *      can be empty but never null.
     */
    public List<AbstractProject> getDownstream(AbstractProject p) {
        return get(forward,p);
    }

    /**
     * Gets all the immediate upstream projects (IOW backward edges) of the given project.
     *
     * @return
     *      can be empty but never null.
     */
    public List<AbstractProject> getUpstream(AbstractProject p) {
        return get(backward,p);
    }

    private List<AbstractProject> get(Map<AbstractProject, List<AbstractProject>> map, AbstractProject src) {
        List<AbstractProject> v = map.get(src);
        if(v!=null) return v;
        else        return Collections.emptyList();
    }

    /**
     * Called during the dependency graph build phase to add a dependency edge.
     */
    public void addDependency(AbstractProject from, AbstractProject to) {
        if(built)
            throw new IllegalStateException();
        add(forward,from,to);
        add(backward,to,from);
    }

    public void addDependency(AbstractProject from, Collection<? extends AbstractProject> to) {
        for (AbstractProject p : to)
            addDependency(from,p);
    }

    public void addDependency(Collection<? extends AbstractProject> from, AbstractProject to) {
        for (AbstractProject p : from)
            addDependency(p,to);
    }

K
kohsuke 已提交
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
    /**
     * Returns true if a project has a non-direct dependency to another project.
     * <p>
     * A non-direct dependency is a path of dependency "edge"s from the source to the destination,
     * where the length is greater than 1.
     */
    public boolean hasIndirectDependencies(AbstractProject src, AbstractProject dst) {
        Set<AbstractProject> visited = new HashSet<AbstractProject>();
        Stack<AbstractProject> queue = new Stack<AbstractProject>();

        queue.addAll(getDownstream(src));
        queue.remove(dst);

        while(!queue.isEmpty()) {
            AbstractProject p = queue.pop();
            if(p==dst)
                return true;
            if(visited.add(p))
                queue.addAll(getDownstream(p));
        }

        return false;
    }

152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
    /**
     * Gets all the direct and indirect upstream dependencies of the given project.
     */
    public Set<AbstractProject> getTransitiveUpstream(AbstractProject src) {
        return getTransitive(backward,src);
    }

    /**
     * Gets all the direct and indirect downstream dependencies of the given project.
     */
    public Set<AbstractProject> getTransitiveDownstream(AbstractProject src) {
        return getTransitive(forward,src);
    }

    private Set<AbstractProject> getTransitive(Map<AbstractProject, List<AbstractProject>> direction, AbstractProject src) {
        Set<AbstractProject> visited = new HashSet<AbstractProject>();
        Stack<AbstractProject> queue = new Stack<AbstractProject>();

        queue.add(src);

        while(!queue.isEmpty()) {
            AbstractProject p = queue.pop();

            for (AbstractProject child : get(direction,p)) {
                if(visited.add(child))
                    queue.add(child);
            }
        }

        return visited;
    }

184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
    private void add(Map<AbstractProject, List<AbstractProject>> map, AbstractProject src, AbstractProject dst) {
        List<AbstractProject> set = map.get(src);
        if(set==null) {
            set = new ArrayList<AbstractProject>();
            map.put(src,set);
        }
        set.add(dst);
    }

    private Map<AbstractProject, List<AbstractProject>> finalize(Map<AbstractProject, List<AbstractProject>> m) {
        for (Entry<AbstractProject, List<AbstractProject>> e : m.entrySet()) {
            Collections.sort( e.getValue(), NAME_COMPARATOR );
            e.setValue( Collections.unmodifiableList(e.getValue()) );
        }
        return Collections.unmodifiableMap(m);
    }

201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
    /**
     * Experimental visualization of project dependencies.
     */
    public void doGraph( StaplerRequest req, StaplerResponse rsp ) throws IOException {
        try {

            // creates a dummy graphics just so that we can measure font metrics
            BufferedImage emptyImage = new BufferedImage(1,1, BufferedImage.TYPE_INT_RGB );
            Graphics2D graphics = emptyImage.createGraphics();
            graphics.setFont(FONT);
            final FontMetrics fontMetrics = graphics.getFontMetrics();

            // TODO: timestamp check
            Layout<AbstractProject> layout = new Layout<AbstractProject>(new Navigator<AbstractProject>() {
                public Collection<AbstractProject> vertices() {
                    // only include projects that have some dependency
                    List<AbstractProject> r = new ArrayList<AbstractProject>();
                    for (AbstractProject p : Hudson.getInstance().getAllItems(AbstractProject.class)) {
                        if(!getDownstream(p).isEmpty() || !getUpstream(p).isEmpty())
                            r.add(p);
                    }
                    return r;
                }

                public Collection<AbstractProject> edge(AbstractProject p) {
                    return getDownstream(p);
                }

                public Dimension getSize(AbstractProject p) {
                    int w = fontMetrics.stringWidth(p.getDisplayName()) + MARGIN*2;
                    return new Dimension(w, fontMetrics.getHeight() + MARGIN*2);
                }
            }, Direction.LEFTRIGHT);

            Rectangle area = layout.calcDrawingArea();
            area.grow(4,4); // give it a bit of margin
            BufferedImage image = new BufferedImage(area.width, area.height, BufferedImage.TYPE_INT_RGB );
            Graphics2D g2 = image.createGraphics();
            g2.setTransform(AffineTransform.getTranslateInstance(-area.x,-area.y));
            g2.setPaint(Color.WHITE);
            g2.fill(area);
            g2.setFont(FONT);

            g2.setPaint(Color.BLACK);
            for( AbstractProject p : layout.vertices() ) {
                final Point sp = center(layout.vertex(p));

                for (AbstractProject q : layout.edges(p)) {
                    Point cur=sp;
                    for( Point pt : layout.edge(p,q) ) {
                        g2.drawLine(cur.x, cur.y, pt.x, pt.y);
                        cur=pt;
                    }

                    final Point ep = center(layout.vertex(q));
                    g2.drawLine(cur.x, cur.y, ep.x, ep.y);
                }
            }

            int diff = fontMetrics.getAscent()+fontMetrics.getLeading()/2;
            
            for( AbstractProject p : layout.vertices() ) {
                Rectangle r = layout.vertex(p);
                g2.setPaint(Color.WHITE);
                g2.fillRect(r.x, r.y, r.width, r.height);
                g2.setPaint(Color.BLACK);
                g2.drawRect(r.x, r.y, r.width, r.height);
                g2.drawString(p.getDisplayName(), r.x+MARGIN, r.y+MARGIN+ diff);
            }

            rsp.setContentType("image/png");
            ServletOutputStream os = rsp.getOutputStream();
            ImageIO.write(image, "PNG", os);
            os.close();
        } catch(HeadlessException e) {
            // not available. send out error message
            rsp.sendRedirect2(req.getContextPath()+"/images/headless.png");
        }
    }

    private Point center(Rectangle r) {
        return new Point(r.x+r.width/2,r.y+r.height/2);
    }

    private static final Font FONT = new Font("TimesRoman", Font.PLAIN, 10);
    /**
     * Margins between the project name and its bounding box.
     */
    private static final int MARGIN = 4;


292 293 294 295 296 297 298 299
    private static final Comparator<AbstractProject> NAME_COMPARATOR = new Comparator<AbstractProject>() {
        public int compare(AbstractProject lhs, AbstractProject rhs) {
            return lhs.getName().compareTo(rhs.getName());
        }
    };

    public static final DependencyGraph EMPTY = new DependencyGraph(false);
}