forked from uber-archive/go-torch
/
graph.go
245 lines (217 loc) · 7.92 KB
/
graph.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
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
// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// Package graph transforms a DOT graph text file into the representation
// expected by the visualization package.
//
// The graph is a directed acyclic graph where nodes represent functions and
// directed edges represent how many times a function calls another.
package graph
import (
"bytes"
"errors"
"fmt"
"strconv"
"strings"
log "github.com/Sirupsen/logrus"
ggv "github.com/awalterschulze/gographviz"
"github.com/awalterschulze/gographviz/parser"
)
var errNoActivity = errors.New("Your application is not doing anything right now. Please try again.")
// Grapher handles transforming a DOT graph byte array into the
// representation expected by the visualization package.
type Grapher interface {
GraphAsText([]byte) (string, error)
}
type defaultGrapher struct {
searcher searcher
collectionGetter collectionGetter
}
type searchArgs struct {
root string
path []ggv.Edge
nodeToOutEdges map[string][]*ggv.Edge
nameToNodes map[string]*ggv.Node
buffer *bytes.Buffer
statusMap map[string]discoveryStatus
}
type searcher interface {
dfs(args searchArgs)
}
type defaultSearcher struct {
pathStringer pathStringer
}
type collectionGetter interface {
generateNodeToOutEdges(*ggv.Graph) map[string][]*ggv.Edge
getInDegreeZeroNodes(*ggv.Graph) []string
}
type defaultCollectionGetter struct{}
type pathStringer interface {
pathAsString([]ggv.Edge, map[string]*ggv.Node) string
}
type defaultPathStringer struct{}
// Marking nodes during depth-first search is a standard way of detecting cycles.
// A node is UNDISCOVERED before it has been discovered, ONSTACK when it is on the recursion stack,
// and DISCOVERED when all of its neighbors have been traversed. A edge terminating at a ONSTACK
// node implies a back edge, which also implies a cycle
// (see: https://en.wikipedia.org/wiki/Cycle_(graph_theory)#Cycle_detection).
type discoveryStatus int
const (
UNDISCOVERED discoveryStatus = iota
ONSTACK
DISCOVERED
)
// NewGrapher returns a default grapher struct with default attributes
func NewGrapher() Grapher {
return &defaultGrapher{
searcher: newSearcher(),
collectionGetter: new(defaultCollectionGetter),
}
}
// newSearcher returns a default searcher struct with a default pathStringer
func newSearcher() *defaultSearcher {
return &defaultSearcher{
pathStringer: new(defaultPathStringer),
}
}
// GraphAsText is the standard implementation of Grapher
func (g *defaultGrapher) GraphAsText(dotText []byte) (string, error) {
graphAst, err := parser.ParseBytes(dotText)
if err != nil {
return "", err
}
dag := ggv.NewGraph() // A directed acyclic graph
ggv.Analyse(graphAst, dag)
if len(dag.Edges.Edges) == 0 {
return "", errNoActivity
}
nodeToOutEdges := g.collectionGetter.generateNodeToOutEdges(dag)
inDegreeZeroNodes := g.collectionGetter.getInDegreeZeroNodes(dag)
nameToNodes := dag.Nodes.Lookup
buffer := new(bytes.Buffer)
statusMap := make(map[string]discoveryStatus)
for _, root := range inDegreeZeroNodes {
g.searcher.dfs(searchArgs{
root: root,
path: nil,
nodeToOutEdges: nodeToOutEdges,
nameToNodes: nameToNodes,
buffer: buffer,
statusMap: statusMap,
})
}
return buffer.String(), nil
}
// generateNodeToOutEdges takes a graph and generates a mapping of nodes to
// edges originating from nodes.
func (c *defaultCollectionGetter) generateNodeToOutEdges(dag *ggv.Graph) map[string][]*ggv.Edge {
nodeToOutEdges := make(map[string][]*ggv.Edge)
for _, edge := range dag.Edges.Edges {
nodeToOutEdges[edge.Src] = append(nodeToOutEdges[edge.Src], edge)
}
return nodeToOutEdges
}
// getInDegreeZeroNodes takes a graph and returns a list of nodes with
// in-degree of 0. In other words, no edges terminate at these nodes.
func (c *defaultCollectionGetter) getInDegreeZeroNodes(dag *ggv.Graph) []string {
var inDegreeZeroNodes []string
nodeToInDegree := make(map[string]int)
for _, edge := range dag.Edges.Edges {
dst := edge.Dst
nodeToInDegree[dst]++
}
for _, node := range dag.Nodes.Nodes {
// @HACK This is a hack to fix a bug with gographviz where a cluster
// 'L' is being parsed as a node. This just checks that all node names
// begin with N.
correctPrefix := strings.HasPrefix(node.Name, "N")
if correctPrefix && nodeToInDegree[node.Name] == 0 {
inDegreeZeroNodes = append(inDegreeZeroNodes, node.Name)
}
}
return inDegreeZeroNodes
}
// dfs performs a depth-first search traversal of the graph starting from a
// given root node. When a node with no outgoing edges is reached, the path
// taken to that node is written to a buffer.
func (s *defaultSearcher) dfs(args searchArgs) {
outEdges := args.nodeToOutEdges[args.root]
if args.statusMap[args.root] == ONSTACK {
log.Warn("The input call graph contains a cycle. This can't be represented in a " +
"flame graph, so this path will be ignored. For your record, the ignored path " +
"is:\n" + strings.TrimSpace(s.pathStringer.pathAsString(args.path, args.nameToNodes)))
return
}
if len(outEdges) == 0 {
args.buffer.WriteString(s.pathStringer.pathAsString(args.path, args.nameToNodes))
args.statusMap[args.root] = DISCOVERED
return
}
args.statusMap[args.root] = ONSTACK
for _, edge := range outEdges {
s.dfs(searchArgs{
root: edge.Dst,
path: append(args.path, *edge),
nodeToOutEdges: args.nodeToOutEdges,
nameToNodes: args.nameToNodes,
buffer: args.buffer,
statusMap: args.statusMap,
})
}
args.statusMap[args.root] = DISCOVERED
}
// pathAsString takes a path and a mapping of node names to node structs and
// generates the string representation of the path expected by the
// visualization package.
func (p *defaultPathStringer) pathAsString(path []ggv.Edge, nameToNodes map[string]*ggv.Node) string {
var (
pathBuffer bytes.Buffer
weightSum int
)
for _, edge := range path {
// If the function call represented by the edge happened very rarely,
// the edge's weight will not be recorded. The edge's label will always
// be recorded.
if weightStr, ok := edge.Attrs["weight"]; ok {
weight, err := strconv.Atoi(weightStr)
if err != nil { // This should never happen
log.Panic(err)
}
weightSum += weight
}
functionLabel := getFormattedFunctionLabel(nameToNodes[edge.Src])
pathBuffer.WriteString(functionLabel + ";")
}
if len(path) >= 1 {
lastEdge := path[len(path)-1]
lastFunctionLabel := getFormattedFunctionLabel(nameToNodes[lastEdge.Dst])
pathBuffer.WriteString(lastFunctionLabel + " ")
}
pathBuffer.WriteString(fmt.Sprint(weightSum))
pathBuffer.WriteString("\n")
return pathBuffer.String()
}
// getFormattedFunctionLabel takes a node and returns a formatted function
// label.
func getFormattedFunctionLabel(node *ggv.Node) string {
label := node.Attrs["tooltip"]
label = strings.Replace(label, `\n`, " ", -1)
label = strings.Replace(label, `"`, "", -1)
return label
}