001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *      http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019package org.apache.oozie.util.graph;
020
021import com.google.common.collect.ArrayListMultimap;
022import com.google.common.collect.Multimap;
023import guru.nidi.graphviz.attribute.Color;
024import guru.nidi.graphviz.attribute.RankDir;
025import guru.nidi.graphviz.attribute.Shape;
026import guru.nidi.graphviz.engine.Engine;
027import guru.nidi.graphviz.engine.Format;
028import guru.nidi.graphviz.engine.Graphviz;
029import guru.nidi.graphviz.engine.Rasterizer;
030import guru.nidi.graphviz.model.Factory;
031import guru.nidi.graphviz.model.Graph;
032import guru.nidi.graphviz.model.Node;
033import org.apache.oozie.client.WorkflowAction;
034import org.apache.oozie.service.ConfigurationService;
035
036import java.awt.image.BufferedImage;
037import java.util.LinkedHashMap;
038import java.util.Map;
039import java.util.concurrent.Callable;
040import java.util.concurrent.ExecutionException;
041import java.util.concurrent.ExecutorService;
042import java.util.concurrent.Executors;
043import java.util.concurrent.Future;
044import java.util.concurrent.TimeUnit;
045import java.util.concurrent.TimeoutException;
046
047public class GraphvizRenderer implements GraphRenderer {
048
049    /**
050     * We need this single-thread executor because we have to make sure:
051     * <ul>
052     * <li>all GraphViz rendering operations happen on the same thread.
053     * This is because of {@link com.eclipsesource.v8.V8} thread handling</li>
054     * <li>GraphViz rendering operations don't timeout</li>
055     * <li>GraphViz rendering operations don't overlap</li>
056     * </ul>
057     */
058    private static final ExecutorService EXECUTOR_SERVICE = Executors.newSingleThreadExecutor();
059    private static final long GRAPHVIZ_TIMEOUT_SECONDS = ConfigurationService.getLong("oozie.graphviz.timeout.seconds");
060
061    private Graph graphvizGraph = Factory.graph().graphAttr().with(RankDir.TOP_TO_BOTTOM).directed();
062    private final Map<String, Node> graphvizNodes = new LinkedHashMap<>();
063    private final Multimap<String, String> edges = ArrayListMultimap.create();
064    private int arcCount = 0;
065
066    @Override
067    public void addNode(final WorkflowActionNode node) {
068        final Shape shape = getShape(node.getType());
069        final Color color = getColor(node.getStatus());
070
071        final Node graphvizNode = Factory.node(node.getName()).with(shape).with(color);
072
073        graphvizNodes.put(node.getName(), graphvizNode);
074    }
075
076    private Shape getShape(final String type) {
077        final Shape shape;
078
079        switch (type) {
080            case "start":
081                shape = Shape.CIRCLE;
082                break;
083            case "end":
084                shape = Shape.DOUBLE_CIRCLE;
085                break;
086            case "kill":
087                shape = Shape.OCTAGON;
088                break;
089            case "decision":
090                shape = Shape.DIAMOND;
091                break;
092            case "fork":
093                shape = Shape.TRIANGLE;
094                break;
095            case "join":
096                shape = Shape.INV_TRIANGLE;
097                break;
098            default:
099                shape = Shape.RECTANGLE;
100                break;
101        }
102
103        return shape;
104    }
105
106    private Color getColor(final WorkflowAction.Status status) {
107        if (status == null) {
108            return Color.BLACK;
109        }
110
111        final Color color;
112
113        switch (status) {
114            case PREP:
115            case USER_RETRY:
116            case START_RETRY:
117            case START_MANUAL:
118                color = Color.GREY;
119                break;
120            case RUNNING:
121            case END_RETRY:
122            case END_MANUAL:
123                color = Color.YELLOW;
124                break;
125            case OK:
126            case DONE:
127                color = Color.GREEN;
128                break;
129            case ERROR:
130            case FAILED:
131            case KILLED:
132                color = Color.RED;
133                break;
134            default:
135                color = Color.BLACK;
136        }
137
138        return color;
139    }
140
141    private Node createOrGetGraphvizNode(final WorkflowActionNode node) {
142        if (graphvizNodes.containsKey(node.getName())) {
143            return graphvizNodes.get(node.getName());
144        }
145
146        addNode(node);
147
148        return graphvizNodes.get(node.getName());
149    }
150
151    @Override
152    public void addEdge(final WorkflowActionNode parent, final WorkflowActionNode child) {
153        if (edges.containsEntry(parent.getName(), child.getName())) {
154            return;
155        }
156
157        Node graphvizParent = createOrGetGraphvizNode(parent);
158
159        graphvizParent = graphvizParent.link(
160                Factory.to(createOrGetGraphvizNode(child)).with(calculateEdgeColor(child.getStatus())));
161        graphvizNodes.put(parent.getName(), graphvizParent);
162
163        edges.put(parent.getName(), child.getName());
164        arcCount++;
165    }
166
167    private Color calculateEdgeColor(final WorkflowAction.Status childStatus) {
168        if (childStatus == null) {
169            return Color.BLACK;
170        }
171
172        if (childStatus.equals(WorkflowAction.Status.RUNNING)) {
173            return Color.GREEN;
174        }
175
176        return getColor(childStatus);
177    }
178
179    @Override
180    public void persist(final WorkflowActionNode node) {
181        final Node graphvizNode = graphvizNodes.get(node.getName());
182        graphvizGraph = graphvizGraph.with(graphvizNode);
183    }
184
185    @Override
186    public BufferedImage renderPng() {
187        final Future<BufferedImage> pngFuture = EXECUTOR_SERVICE.submit(new PngRenderer());
188
189        try {
190            return pngFuture.get(GRAPHVIZ_TIMEOUT_SECONDS, TimeUnit.SECONDS);
191        } catch (final InterruptedException | ExecutionException | TimeoutException e) {
192            throw new RuntimeException(e);
193        }
194    }
195
196    private int calculateHeight(final int arcCount) {
197        return Math.min(arcCount * 100, 2000);
198    }
199
200    @Override
201    public String renderDot() {
202        return graphvizGraph.toString();
203    }
204
205    @Override
206    public String renderSvg() {
207        final Future<String> svgFuture = EXECUTOR_SERVICE.submit(new SvgRenderer());
208
209        try {
210            return svgFuture.get(GRAPHVIZ_TIMEOUT_SECONDS, TimeUnit.SECONDS);
211        } catch (final InterruptedException | ExecutionException | TimeoutException e) {
212            throw new RuntimeException(e);
213        }
214    }
215
216    private class PngRenderer implements Callable<BufferedImage> {
217        @Override
218        public BufferedImage call() throws Exception {
219            final Graphviz graphviz = newGraphviz();
220
221            return graphviz.render(Format.PNG).toImage();
222        }
223    }
224
225    private class SvgRenderer implements Callable<String> {
226
227        @Override
228        public String call() throws Exception {
229            final Graphviz graphviz = newGraphviz();
230
231            return graphviz.render(Format.SVG).toString();
232        }
233    }
234
235    private Graphviz newGraphviz() {
236        // Defaults to Rasterizer#BATIK
237        return Graphviz.fromGraph(graphvizGraph)
238                .engine(Engine.DOT)
239                .height(calculateHeight(arcCount));
240    }
241}