Martin Spier 7 роки тому
джерело
коміт
80fc05d903

+ 1
- 1
CONTRIBUTORS Переглянути файл

@@ -11,5 +11,5 @@
11 11
 Raul Silvera <rsilvera@google.com>
12 12
 Tipp Moseley <tipp@google.com>
13 13
 Hyoun Kyu Cho <netforce@google.com>
14
+Martin Spier <spiermar@gmail.com>
14 15
 Taco de Wolff <tacodewolff@gmail.com>
15
-

+ 95
- 0
internal/driver/flamegraph.go Переглянути файл

@@ -0,0 +1,95 @@
1
+// Copyright 2017 Google Inc. All Rights Reserved.
2
+//
3
+// Licensed under the Apache License, Version 2.0 (the "License");
4
+// you may not use this file except in compliance with the License.
5
+// You may obtain a copy of the License at
6
+//
7
+//     http://www.apache.org/licenses/LICENSE-2.0
8
+//
9
+// Unless required by applicable law or agreed to in writing, software
10
+// distributed under the License is distributed on an "AS IS" BASIS,
11
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+// See the License for the specific language governing permissions and
13
+// limitations under the License.
14
+
15
+package driver
16
+
17
+import (
18
+	"encoding/json"
19
+	"html/template"
20
+	"net/http"
21
+	"strings"
22
+
23
+	"github.com/google/pprof/internal/graph"
24
+	"github.com/google/pprof/internal/measurement"
25
+	"github.com/google/pprof/internal/report"
26
+)
27
+
28
+type treeNode struct {
29
+	Name      string      `json:"n"`
30
+	Cum       int64       `json:"v"`
31
+	CumFormat string      `json:"l"`
32
+	Percent   string      `json:"p"`
33
+	Children  []*treeNode `json:"c"`
34
+}
35
+
36
+// flamegraph generates a web page containing a flamegraph.
37
+func (ui *webInterface) flamegraph(w http.ResponseWriter, req *http.Request) {
38
+	// Force the call tree so that the graph is a tree.
39
+	// Also do not trim the tree so that the flame graph contains all functions.
40
+	rpt, errList := ui.makeReport(w, req, []string{"svg"}, "call_tree", "true", "trim", "false")
41
+	if rpt == nil {
42
+		return // error already reported
43
+	}
44
+
45
+	// Generate dot graph.
46
+	g, config := report.GetDOT(rpt)
47
+	var nodes []*treeNode
48
+	nroots := 0
49
+	rootValue := int64(0)
50
+	nodeMap := map[*graph.Node]*treeNode{}
51
+	// Make all nodes and the map, collect the roots.
52
+	for _, n := range g.Nodes {
53
+		v := n.CumValue()
54
+		node := &treeNode{
55
+			Name:      n.Info.PrintableName(),
56
+			Cum:       v,
57
+			CumFormat: config.FormatValue(v),
58
+			Percent:   strings.TrimSpace(measurement.Percentage(v, config.Total)),
59
+		}
60
+		nodes = append(nodes, node)
61
+		if len(n.In) == 0 {
62
+			nodes[nroots], nodes[len(nodes)-1] = nodes[len(nodes)-1], nodes[nroots]
63
+			nroots++
64
+			rootValue += v
65
+		}
66
+		nodeMap[n] = node
67
+	}
68
+	// Populate the child links.
69
+	for _, n := range g.Nodes {
70
+		node := nodeMap[n]
71
+		for child := range n.Out {
72
+			node.Children = append(node.Children, nodeMap[child])
73
+		}
74
+	}
75
+
76
+	rootNode := &treeNode{
77
+		Name:      "root",
78
+		Cum:       rootValue,
79
+		CumFormat: config.FormatValue(rootValue),
80
+		Percent:   strings.TrimSpace(measurement.Percentage(rootValue, config.Total)),
81
+		Children:  nodes[0:nroots],
82
+	}
83
+
84
+	// JSON marshalling flame graph
85
+	b, err := json.Marshal(rootNode)
86
+	if err != nil {
87
+		http.Error(w, "error serializing flame graph", http.StatusInternalServerError)
88
+		ui.options.UI.PrintErr(err)
89
+		return
90
+	}
91
+
92
+	ui.render(w, "/flamegraph", "flamegraph", rpt, errList, config.Labels, webArgs{
93
+		FlameGraph: template.JS(b),
94
+	})
95
+}

+ 120
- 0
internal/driver/webhtml.go Переглянути файл

@@ -15,9 +15,16 @@
15 15
 package driver
16 16
 
17 17
 import "html/template"
18
+import "github.com/google/pprof/third_party/d3"
19
+import "github.com/google/pprof/third_party/d3tip"
20
+import "github.com/google/pprof/third_party/d3flamegraph"
18 21
 
19 22
 // addTemplates adds a set of template definitions to templates.
20 23
 func addTemplates(templates *template.Template) {
24
+	template.Must(templates.Parse(`{{define "d3script"}}` + d3.JSSource + `{{end}}`))
25
+	template.Must(templates.Parse(`{{define "d3tipscript"}}` + d3tip.JSSource + `{{end}}`))
26
+	template.Must(templates.Parse(`{{define "d3flamegraphscript"}}` + d3flamegraph.JSSource + `{{end}}`))
27
+	template.Must(templates.Parse(`{{define "d3flamegraphcss"}}` + d3flamegraph.CSSSource + `{{end}}`))
21 28
 	template.Must(templates.Parse(`
22 29
 {{define "css"}}
23 30
 <style type="text/css">
@@ -245,6 +252,7 @@ View
245 252
 <div class="submenu">
246 253
 <a title="{{.Help.top}}"  href="/top" id="topbtn">Top</a>
247 254
 <a title="{{.Help.graph}}" href="/" id="graphbtn">Graph</a>
255
+<a title="{{.Help.flamegraph}}" href="/flamegraph" id="flamegraph">Flame Graph</a>
248 256
 <a title="{{.Help.peek}}" href="/peek" id="peek">Peek</a>
249 257
 <a title="{{.Help.list}}" href="/source" id="list">Source</a>
250 258
 <a title="{{.Help.disasm}}" href="/disasm" id="disasm">Disassemble</a>
@@ -1016,5 +1024,117 @@ makeTopTable({{.Total}}, {{.Top}})
1016 1024
 </body>
1017 1025
 </html>
1018 1026
 {{end}}
1027
+
1028
+{{define "flamegraph" -}}
1029
+<!DOCTYPE html>
1030
+<html>
1031
+<head>
1032
+<meta charset="utf-8">
1033
+<title>{{.Title}}</title>
1034
+{{template "css" .}}
1035
+<style type="text/css">{{template "d3flamegraphcss" .}}</style>
1036
+<style type="text/css">
1037
+.flamegraph-content {
1038
+    width: 90%;
1039
+    min-width: 80%;
1040
+    margin-left: 5%;
1041
+}
1042
+.flamegraph-details {
1043
+    height: 1.2em;
1044
+    width: 90%;
1045
+    min-width: 90%;
1046
+    margin-left: 5%;
1047
+    padding-bottom: 41px;
1048
+}
1049
+</style>
1050
+</head>
1051
+<body>
1052
+{{template "header" .}}
1053
+<div id="bodycontainer">
1054
+  <div class="flamegraph-content">
1055
+    <div id="chart"></div>
1056
+  </div>
1057
+  <div id="flamegraphdetails" class="flamegraph-details"></div>
1058
+</div>
1059
+{{template "script" .}}
1060
+<script>viewer({{.BaseURL}}, {{.Nodes}})</script>
1061
+<script>{{template "d3script" .}}</script>
1062
+<script>{{template "d3tipscript" .}}</script>
1063
+<script>{{template "d3flamegraphscript" .}}</script>
1064
+<script type="text/javascript">
1065
+    var data = {{.FlameGraph}};
1066
+    var label = function(d) {
1067
+        return d.data.n + " (" + d.data.p + ", " + d.data.l + ")";
1068
+    };
1069
+
1070
+    var width = document.getElementById("chart").clientWidth;
1071
+
1072
+    var flameGraph = d3.flameGraph()
1073
+        .width(width)
1074
+        .cellHeight(18)
1075
+        .minFrameSize(1)
1076
+        .transitionDuration(750)
1077
+        .transitionEase(d3.easeCubic)
1078
+        .sort(true)
1079
+        .title("")
1080
+        .label(label)
1081
+        .details(document.getElementById("flamegraphdetails"));
1082
+
1083
+    var tip = d3.tip()
1084
+        .direction("s")
1085
+        .offset([8, 0])
1086
+        .attr('class', 'd3-flame-graph-tip')
1087
+        .html(function(d) { return "name: " + d.data.n + ", value: " + d.data.l; });
1088
+
1089
+    flameGraph.tooltip(tip);
1090
+
1091
+    d3.select("#chart")
1092
+        .datum(data)
1093
+        .call(flameGraph);
1094
+
1095
+    function clear() {
1096
+        flameGraph.clear();
1097
+    }
1098
+
1099
+    function resetZoom() {
1100
+        flameGraph.resetZoom();
1101
+    }
1102
+
1103
+    window.addEventListener("resize", function() {
1104
+        var width = document.getElementById("chart").clientWidth;
1105
+        var graphs = document.getElementsByClassName("d3-flame-graph");
1106
+        if (graphs.length > 0) {
1107
+            graphs[0].setAttribute("width", width);
1108
+        }
1109
+        flameGraph.width(width);
1110
+        flameGraph.resetZoom();
1111
+    }, true);
1112
+
1113
+    var searchbox = document.getElementById("searchbox");
1114
+    var searchAlarm = null;
1115
+
1116
+    function selectMatching() {
1117
+      searchAlarm = null;
1118
+
1119
+      if (searchbox.value != "") {
1120
+        flameGraph.search(searchbox.value);
1121
+      } else {
1122
+        flameGraph.clear();
1123
+      }
1124
+    }
1125
+
1126
+    function handleSearch() {
1127
+      // Delay expensive processing so a flurry of key strokes is handled once.
1128
+      if (searchAlarm != null) {
1129
+        clearTimeout(searchAlarm);
1130
+      }
1131
+      searchAlarm = setTimeout(selectMatching, 300);
1132
+    }
1133
+
1134
+    searchbox.addEventListener("input", handleSearch);
1135
+</script>
1136
+</body>
1137
+</html>
1138
+{{end}}
1019 1139
 `))
1020 1140
 }

+ 17
- 15
internal/driver/webui.go Переглянути файл

@@ -69,16 +69,17 @@ func (ec *errorCatcher) PrintErr(args ...interface{}) {
69 69
 
70 70
 // webArgs contains arguments passed to templates in webhtml.go.
71 71
 type webArgs struct {
72
-	BaseURL  string
73
-	Title    string
74
-	Errors   []string
75
-	Total    int64
76
-	Legend   []string
77
-	Help     map[string]string
78
-	Nodes    []string
79
-	HTMLBody template.HTML
80
-	TextBody string
81
-	Top      []report.TextItem
72
+	BaseURL    string
73
+	Title      string
74
+	Errors     []string
75
+	Total      int64
76
+	Legend     []string
77
+	Help       map[string]string
78
+	Nodes      []string
79
+	HTMLBody   template.HTML
80
+	TextBody   string
81
+	Top        []report.TextItem
82
+	FlameGraph template.JS
82 83
 }
83 84
 
84 85
 func serveWebInterface(hostport string, p *profile.Profile, o *plugin.Options, wantBrowser bool) error {
@@ -115,11 +116,12 @@ func serveWebInterface(hostport string, p *profile.Profile, o *plugin.Options, w
115 116
 		Host:     host,
116 117
 		Port:     port,
117 118
 		Handlers: map[string]http.Handler{
118
-			"/":       http.HandlerFunc(ui.dot),
119
-			"/top":    http.HandlerFunc(ui.top),
120
-			"/disasm": http.HandlerFunc(ui.disasm),
121
-			"/source": http.HandlerFunc(ui.source),
122
-			"/peek":   http.HandlerFunc(ui.peek),
119
+			"/":           http.HandlerFunc(ui.dot),
120
+			"/top":        http.HandlerFunc(ui.top),
121
+			"/disasm":     http.HandlerFunc(ui.disasm),
122
+			"/source":     http.HandlerFunc(ui.source),
123
+			"/peek":       http.HandlerFunc(ui.peek),
124
+			"/flamegraph": http.HandlerFunc(ui.flamegraph),
123 125
 		},
124 126
 	}
125 127
 

+ 1
- 0
internal/driver/webui_test.go Переглянути файл

@@ -80,6 +80,7 @@ func TestWebInterface(t *testing.T) {
80 80
 			[]string{"300ms.*F1", "200ms.*300ms.*F2"}, false},
81 81
 		{"/disasm?f=" + url.QueryEscape("F[12]"),
82 82
 			[]string{"f1:asm", "f2:asm"}, false},
83
+		{"/flamegraph", []string{"File: testbin", "\"n\":\"root\"", "\"n\":\"F1\"", "function tip", "function flameGraph", "function hierarchy"}, false},
83 84
 	}
84 85
 	for _, c := range testcases {
85 86
 		if c.needDot && !haveDot {

+ 27
- 0
third_party/d3/LICENSE Переглянути файл

@@ -0,0 +1,27 @@
1
+Copyright 2010-2017 Mike Bostock
2
+All rights reserved.
3
+
4
+Redistribution and use in source and binary forms, with or without modification,
5
+are permitted provided that the following conditions are met:
6
+
7
+* Redistributions of source code must retain the above copyright notice, this
8
+  list of conditions and the following disclaimer.
9
+
10
+* Redistributions in binary form must reproduce the above copyright notice,
11
+  this list of conditions and the following disclaimer in the documentation
12
+  and/or other materials provided with the distribution.
13
+
14
+* Neither the name of the author nor the names of contributors may be used to
15
+  endorse or promote products derived from this software without specific prior
16
+  written permission.
17
+
18
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
22
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
25
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

+ 119
- 0
third_party/d3/README.md Переглянути файл

@@ -0,0 +1,119 @@
1
+# Building a customized D3.js bundle
2
+
3
+The D3.js version distributed with pprof is customized to only include the modules required by pprof.
4
+
5
+## Dependencies
6
+
7
+First, it's necessary to pull all bundle dependencies. We will use a JavaScript package manager, [npm](https://www.npmjs.com/), to accomplish that. npm dependencies are declared in a `package.json` file, so create one with the following configuration:
8
+
9
+```js
10
+{
11
+  "name": "d3-pprof",
12
+  "version": "1.0.0",
13
+  "description": "A d3.js bundle for pprof.",
14
+  "scripts": {
15
+    "prepare": "rollup -c && uglifyjs d3.js -c -m -o d3.min.js"
16
+  },
17
+  "license": "Apache-2.0",
18
+  "devDependencies": {
19
+    "d3-selection": "1.1.0",
20
+    "d3-hierarchy": "1.1.5",
21
+    "d3-scale": "1.0.6",
22
+    "d3-format": "1.2.0",
23
+    "d3-ease": "1.0.3",
24
+    "d3-array": "1.2.1",
25
+    "d3-collection": "1.0.4",
26
+    "d3-transition": "1.1.0",
27
+    "rollup": "0.51.8",
28
+    "rollup-plugin-node-resolve": "3",
29
+    "uglify-js": "3.1.10"
30
+  }
31
+}
32
+```
33
+
34
+Besides the bundle dependencies, the `package.json` file also specifies a script called `prepare`, which will be executed to create the bundle after `Rollup` is installed.
35
+
36
+## Bundler
37
+
38
+The simplest way of creating a custom bundle is to use a bundler, such as [Rollup](https://rollupjs.org/) or [Webpack](https://webpack.js.org/). Rollup will be used in this example.
39
+
40
+First, create a `rollup.config.js` file, containing the configuration Rollup should use to build the bundle.
41
+
42
+```js
43
+import node from "rollup-plugin-node-resolve";
44
+
45
+export default {
46
+  input: "index.js",
47
+  output: {
48
+    format: "umd",
49
+    file: "d3.js"
50
+  },
51
+  name: "d3",
52
+  plugins: [node()],
53
+  sourcemap: false
54
+};
55
+```
56
+
57
+Then create an `index.js` file containing all the functions that need to be exported in the bundle.
58
+
59
+```js
60
+export {
61
+  select,
62
+  selection,
63
+  event,
64
+} from "d3-selection";
65
+
66
+export {
67
+    hierarchy,
68
+    partition,
69
+} from "d3-hierarchy";
70
+
71
+export {
72
+    scaleLinear,
73
+} from "d3-scale";
74
+
75
+export {
76
+    format,
77
+} from "d3-format";
78
+
79
+export {
80
+    easeCubic,
81
+} from "d3-ease";
82
+
83
+export {
84
+    ascending,
85
+} from "d3-array";
86
+
87
+export {
88
+    map,
89
+} from "d3-collection";
90
+
91
+export {
92
+    transition,
93
+} from "d3-transition";
94
+```
95
+
96
+## Building
97
+
98
+Once all files were created, execute the following commands to pull all dependencies and build the bundle.
99
+
100
+```
101
+% npm install
102
+% npm run prepare
103
+```
104
+
105
+This will create two files, `d3.js` and `d3.min.js`, the custom D3.js bundle and its minified version respectively.
106
+
107
+# References
108
+
109
+## D3 Custom Bundle
110
+
111
+A demonstration of building a custom D3 4.0 bundle using ES2015 modules and Rollup. 
112
+
113
+[bl.ocks.org/mbostock/bb09af4c39c79cffcde4](https://bl.ocks.org/mbostock/bb09af4c39c79cffcde4)
114
+
115
+## d3-pprof
116
+
117
+A repository containing all previously mentioned configuration files and the generated custom bundle.
118
+
119
+[github.com/spiermar/d3-pprof](https://github.com/spiermar/d3-pprof)

+ 4675
- 0
third_party/d3/d3.go
Різницю між файлами не показано, бо вона завелика
Переглянути файл


+ 201
- 0
third_party/d3flamegraph/LICENSE Переглянути файл

@@ -0,0 +1,201 @@
1
+                                 Apache License
2
+                           Version 2.0, January 2004
3
+                        http://www.apache.org/licenses/
4
+
5
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+   1. Definitions.
8
+
9
+      "License" shall mean the terms and conditions for use, reproduction,
10
+      and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+      "Licensor" shall mean the copyright owner or entity authorized by
13
+      the copyright owner that is granting the License.
14
+
15
+      "Legal Entity" shall mean the union of the acting entity and all
16
+      other entities that control, are controlled by, or are under common
17
+      control with that entity. For the purposes of this definition,
18
+      "control" means (i) the power, direct or indirect, to cause the
19
+      direction or management of such entity, whether by contract or
20
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+      outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+      "You" (or "Your") shall mean an individual or Legal Entity
24
+      exercising permissions granted by this License.
25
+
26
+      "Source" form shall mean the preferred form for making modifications,
27
+      including but not limited to software source code, documentation
28
+      source, and configuration files.
29
+
30
+      "Object" form shall mean any form resulting from mechanical
31
+      transformation or translation of a Source form, including but
32
+      not limited to compiled object code, generated documentation,
33
+      and conversions to other media types.
34
+
35
+      "Work" shall mean the work of authorship, whether in Source or
36
+      Object form, made available under the License, as indicated by a
37
+      copyright notice that is included in or attached to the work
38
+      (an example is provided in the Appendix below).
39
+
40
+      "Derivative Works" shall mean any work, whether in Source or Object
41
+      form, that is based on (or derived from) the Work and for which the
42
+      editorial revisions, annotations, elaborations, or other modifications
43
+      represent, as a whole, an original work of authorship. For the purposes
44
+      of this License, Derivative Works shall not include works that remain
45
+      separable from, or merely link (or bind by name) to the interfaces of,
46
+      the Work and Derivative Works thereof.
47
+
48
+      "Contribution" shall mean any work of authorship, including
49
+      the original version of the Work and any modifications or additions
50
+      to that Work or Derivative Works thereof, that is intentionally
51
+      submitted to Licensor for inclusion in the Work by the copyright owner
52
+      or by an individual or Legal Entity authorized to submit on behalf of
53
+      the copyright owner. For the purposes of this definition, "submitted"
54
+      means any form of electronic, verbal, or written communication sent
55
+      to the Licensor or its representatives, including but not limited to
56
+      communication on electronic mailing lists, source code control systems,
57
+      and issue tracking systems that are managed by, or on behalf of, the
58
+      Licensor for the purpose of discussing and improving the Work, but
59
+      excluding communication that is conspicuously marked or otherwise
60
+      designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+      "Contributor" shall mean Licensor and any individual or Legal Entity
63
+      on behalf of whom a Contribution has been received by Licensor and
64
+      subsequently incorporated within the Work.
65
+
66
+   2. Grant of Copyright License. Subject to the terms and conditions of
67
+      this License, each Contributor hereby grants to You a perpetual,
68
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+      copyright license to reproduce, prepare Derivative Works of,
70
+      publicly display, publicly perform, sublicense, and distribute the
71
+      Work and such Derivative Works in Source or Object form.
72
+
73
+   3. Grant of Patent License. Subject to the terms and conditions of
74
+      this License, each Contributor hereby grants to You a perpetual,
75
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+      (except as stated in this section) patent license to make, have made,
77
+      use, offer to sell, sell, import, and otherwise transfer the Work,
78
+      where such license applies only to those patent claims licensable
79
+      by such Contributor that are necessarily infringed by their
80
+      Contribution(s) alone or by combination of their Contribution(s)
81
+      with the Work to which such Contribution(s) was submitted. If You
82
+      institute patent litigation against any entity (including a
83
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+      or a Contribution incorporated within the Work constitutes direct
85
+      or contributory patent infringement, then any patent licenses
86
+      granted to You under this License for that Work shall terminate
87
+      as of the date such litigation is filed.
88
+
89
+   4. Redistribution. You may reproduce and distribute copies of the
90
+      Work or Derivative Works thereof in any medium, with or without
91
+      modifications, and in Source or Object form, provided that You
92
+      meet the following conditions:
93
+
94
+      (a) You must give any other recipients of the Work or
95
+          Derivative Works a copy of this License; and
96
+
97
+      (b) You must cause any modified files to carry prominent notices
98
+          stating that You changed the files; and
99
+
100
+      (c) You must retain, in the Source form of any Derivative Works
101
+          that You distribute, all copyright, patent, trademark, and
102
+          attribution notices from the Source form of the Work,
103
+          excluding those notices that do not pertain to any part of
104
+          the Derivative Works; and
105
+
106
+      (d) If the Work includes a "NOTICE" text file as part of its
107
+          distribution, then any Derivative Works that You distribute must
108
+          include a readable copy of the attribution notices contained
109
+          within such NOTICE file, excluding those notices that do not
110
+          pertain to any part of the Derivative Works, in at least one
111
+          of the following places: within a NOTICE text file distributed
112
+          as part of the Derivative Works; within the Source form or
113
+          documentation, if provided along with the Derivative Works; or,
114
+          within a display generated by the Derivative Works, if and
115
+          wherever such third-party notices normally appear. The contents
116
+          of the NOTICE file are for informational purposes only and
117
+          do not modify the License. You may add Your own attribution
118
+          notices within Derivative Works that You distribute, alongside
119
+          or as an addendum to the NOTICE text from the Work, provided
120
+          that such additional attribution notices cannot be construed
121
+          as modifying the License.
122
+
123
+      You may add Your own copyright statement to Your modifications and
124
+      may provide additional or different license terms and conditions
125
+      for use, reproduction, or distribution of Your modifications, or
126
+      for any such Derivative Works as a whole, provided Your use,
127
+      reproduction, and distribution of the Work otherwise complies with
128
+      the conditions stated in this License.
129
+
130
+   5. Submission of Contributions. Unless You explicitly state otherwise,
131
+      any Contribution intentionally submitted for inclusion in the Work
132
+      by You to the Licensor shall be under the terms and conditions of
133
+      this License, without any additional terms or conditions.
134
+      Notwithstanding the above, nothing herein shall supersede or modify
135
+      the terms of any separate license agreement you may have executed
136
+      with Licensor regarding such Contributions.
137
+
138
+   6. Trademarks. This License does not grant permission to use the trade
139
+      names, trademarks, service marks, or product names of the Licensor,
140
+      except as required for reasonable and customary use in describing the
141
+      origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+   7. Disclaimer of Warranty. Unless required by applicable law or
144
+      agreed to in writing, Licensor provides the Work (and each
145
+      Contributor provides its Contributions) on an "AS IS" BASIS,
146
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+      implied, including, without limitation, any warranties or conditions
148
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+      PARTICULAR PURPOSE. You are solely responsible for determining the
150
+      appropriateness of using or redistributing the Work and assume any
151
+      risks associated with Your exercise of permissions under this License.
152
+
153
+   8. Limitation of Liability. In no event and under no legal theory,
154
+      whether in tort (including negligence), contract, or otherwise,
155
+      unless required by applicable law (such as deliberate and grossly
156
+      negligent acts) or agreed to in writing, shall any Contributor be
157
+      liable to You for damages, including any direct, indirect, special,
158
+      incidental, or consequential damages of any character arising as a
159
+      result of this License or out of the use or inability to use the
160
+      Work (including but not limited to damages for loss of goodwill,
161
+      work stoppage, computer failure or malfunction, or any and all
162
+      other commercial damages or losses), even if such Contributor
163
+      has been advised of the possibility of such damages.
164
+
165
+   9. Accepting Warranty or Additional Liability. While redistributing
166
+      the Work or Derivative Works thereof, You may choose to offer,
167
+      and charge a fee for, acceptance of support, warranty, indemnity,
168
+      or other liability obligations and/or rights consistent with this
169
+      License. However, in accepting such obligations, You may act only
170
+      on Your own behalf and on Your sole responsibility, not on behalf
171
+      of any other Contributor, and only if You agree to indemnify,
172
+      defend, and hold each Contributor harmless for any liability
173
+      incurred by, or claims asserted against, such Contributor by reason
174
+      of your accepting any such warranty or additional liability.
175
+
176
+   END OF TERMS AND CONDITIONS
177
+
178
+   APPENDIX: How to apply the Apache License to your work.
179
+
180
+      To apply the Apache License to your work, attach the following
181
+      boilerplate notice, with the fields enclosed by brackets "{}"
182
+      replaced with your own identifying information. (Don't include
183
+      the brackets!)  The text should be enclosed in the appropriate
184
+      comment syntax for the file format. We also recommend that a
185
+      file or class name and description of purpose be included on the
186
+      same "printed page" as the copyright notice for easier
187
+      identification within third-party archives.
188
+
189
+   Copyright {yyyy} {name of copyright owner}
190
+
191
+   Licensed under the Apache License, Version 2.0 (the "License");
192
+   you may not use this file except in compliance with the License.
193
+   You may obtain a copy of the License at
194
+
195
+       http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+   Unless required by applicable law or agreed to in writing, software
198
+   distributed under the License is distributed on an "AS IS" BASIS,
199
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+   See the License for the specific language governing permissions and
201
+   limitations under the License.

+ 711
- 0
third_party/d3flamegraph/d3_flame_graph.go Переглянути файл

@@ -0,0 +1,711 @@
1
+// A D3.js plugin that produces flame graphs from hierarchical data.
2
+// https://github.com/spiermar/d3-flame-graph
3
+// Version 1.0.11
4
+// See LICENSE file for license details
5
+
6
+package d3flamegraph
7
+
8
+// JSSource returns the d3.flameGraph.js file
9
+const JSSource = `
10
+/**!
11
+*
12
+*  Copyright 2017 Martin Spier <spiermar@gmail.com>
13
+*
14
+*  Licensed under the Apache License, Version 2.0 (the "License");
15
+*  you may not use this file except in compliance with the License.
16
+*  You may obtain a copy of the License at
17
+*
18
+*      http://www.apache.org/licenses/LICENSE-2.0
19
+*
20
+*  Unless required by applicable law or agreed to in writing, software
21
+*  distributed under the License is distributed on an "AS IS" BASIS,
22
+*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23
+*  See the License for the specific language governing permissions and
24
+*  limitations under the License.
25
+*
26
+*/
27
+(function() {
28
+  'use strict';
29
+
30
+  /*jshint eqnull:true */
31
+  // https://tc39.github.io/ecma262/#sec-array.prototype.find
32
+  if (!Array.prototype.find) {
33
+    Object.defineProperty(Array.prototype, 'find', {
34
+      value: function(predicate) {
35
+      // 1. Let O be ? ToObject(this value).
36
+        if (this == null) {
37
+          throw new TypeError('"this" is null or not defined');
38
+        }
39
+
40
+        var o = Object(this);
41
+
42
+        // 2. Let len be ? ToLength(? Get(O, "length")).
43
+        var len = o.length >>> 0;
44
+
45
+        // 3. If IsCallable(predicate) is false, throw a TypeError exception.
46
+        if (typeof predicate !== 'function') {
47
+          throw new TypeError('predicate must be a function');
48
+        }
49
+
50
+        // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
51
+        var thisArg = arguments[1];
52
+
53
+        // 5. Let k be 0.
54
+        var k = 0;
55
+
56
+        // 6. Repeat, while k < len
57
+        while (k < len) {
58
+          // a. Let Pk be ! ToString(k).
59
+          // b. Let kValue be ? Get(O, Pk).
60
+          // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
61
+          // d. If testResult is true, return kValue.
62
+          var kValue = o[k];
63
+          if (predicate.call(thisArg, kValue, k, o)) {
64
+            return kValue;
65
+          }
66
+          // e. Increase k by 1.
67
+          k++;
68
+        }
69
+
70
+        // 7. Return undefined.
71
+        return undefined;
72
+      }
73
+    });
74
+  }
75
+
76
+  if (!Array.prototype.filter)
77
+  Array.prototype.filter = function(func, thisArg) {
78
+    if ( ! ((typeof func === 'function') && this) )
79
+        throw new TypeError();
80
+    
81
+    var len = this.length >>> 0,
82
+        res = new Array(len), // preallocate array
83
+        c = 0, i = -1;
84
+    if (thisArg === undefined)
85
+      while (++i !== len)
86
+        // checks to see if the key was set
87
+        if (i in this)
88
+          if (func(t[i], i, t))
89
+            res[c++] = t[i];
90
+    else
91
+      while (++i !== len)
92
+        // checks to see if the key was set
93
+        if (i in this)
94
+          if (func.call(thisArg, t[i], i, t))
95
+            res[c++] = t[i];
96
+    
97
+    res.length = c; // shrink down array to proper size
98
+    return res;
99
+  };
100
+  /*jshint eqnull:false */
101
+
102
+  // Node/CommonJS - require D3
103
+  if (typeof(module) !== 'undefined' && typeof(exports) !== 'undefined' && typeof(d3) == 'undefined') {
104
+      d3 = require('d3');
105
+  }
106
+
107
+  // Node/CommonJS - require d3-tip
108
+  if (typeof(module) !== 'undefined' && typeof(exports) !== 'undefined' && typeof(d3.tip) == 'undefined') {
109
+      d3.tip = require('d3-tip');
110
+  }
111
+
112
+  function flameGraph() {
113
+
114
+    var w = 960, // graph width
115
+      h = null, // graph height
116
+      c = 18, // cell height
117
+      selection = null, // selection
118
+      tooltip = true, // enable tooltip
119
+      title = "", // graph title
120
+      transitionDuration = 750,
121
+      transitionEase = d3.easeCubic, // tooltip offset
122
+      sort = false,
123
+      reversed = false, // reverse the graph direction
124
+      clickHandler = null,
125
+      minFrameSize = 0,
126
+      details = null;
127
+
128
+    var tip = d3.tip()
129
+      .direction("s")
130
+      .offset([8, 0])
131
+      .attr('class', 'd3-flame-graph-tip')
132
+      .html(function(d) { return label(d); });
133
+
134
+    var svg;
135
+
136
+    function name(d) {
137
+      return d.data.n || d.data.name;
138
+    }
139
+
140
+    function children(d) {
141
+      return d.c || d.children;
142
+    }
143
+
144
+    function value(d) {
145
+      return d.v || d.value;
146
+    }
147
+
148
+    var label = function(d) {
149
+      return name(d) + " (" + d3.format(".3f")(100 * (d.x1 - d.x0), 3) + "%, " + value(d) + " samples)";
150
+    };
151
+
152
+    function setDetails(t) {
153
+      if (details)
154
+        details.innerHTML = t;
155
+    }
156
+
157
+    var colorMapper = function(d) {
158
+      return d.highlight ? "#E600E6" : colorHash(name(d));
159
+    };
160
+
161
+    function generateHash(name) {
162
+      // Return a vector (0.0->1.0) that is a hash of the input string.
163
+      // The hash is computed to favor early characters over later ones, so
164
+      // that strings with similar starts have similar vectors. Only the first
165
+      // 6 characters are considered.
166
+      var hash = 0, weight = 1, max_hash = 0, mod = 10, max_char = 6;
167
+      if (name) {
168
+        for (var i = 0; i < name.length; i++) {
169
+          if (i > max_char) { break; }
170
+          hash += weight * (name.charCodeAt(i) % mod);
171
+          max_hash += weight * (mod - 1);
172
+          weight *= 0.70;
173
+        }
174
+        if (max_hash > 0) { hash = hash / max_hash; }
175
+      }
176
+      return hash;
177
+    }
178
+
179
+    function colorHash(name) {
180
+      // Return an rgb() color string that is a hash of the provided name,
181
+      // and with a warm palette.
182
+      var vector = 0;
183
+      if (name) {
184
+        var nameArr = name.split('` + "`" + `');
185
+        if (nameArr.length > 1) {
186
+          name = nameArr[nameArr.length -1]; // drop module name if present
187
+        }
188
+        name = name.split('(')[0]; // drop extra info
189
+        vector = generateHash(name);
190
+      }
191
+      var r = 200 + Math.round(55 * vector);
192
+      var g = 0 + Math.round(230 * (1 - vector));
193
+      var b = 0 + Math.round(55 * (1 - vector));
194
+      return "rgb(" + r + "," + g + "," + b + ")";
195
+    }
196
+
197
+    function hide(d) {
198
+      d.data.hide = true;
199
+      if(children(d)) {
200
+        children(d).forEach(hide);
201
+      }
202
+    }
203
+
204
+    function show(d) {
205
+      d.data.fade = false;
206
+      d.data.hide = false;
207
+      if(children(d)) {
208
+        children(d).forEach(show);
209
+      }
210
+    }
211
+
212
+    function getSiblings(d) {
213
+      var siblings = [];
214
+      if (d.parent) {
215
+        var me = d.parent.children.indexOf(d);
216
+        siblings = d.parent.children.slice(0);
217
+        siblings.splice(me, 1);
218
+      }
219
+      return siblings;
220
+    }
221
+
222
+    function hideSiblings(d) {
223
+      var siblings = getSiblings(d);
224
+      siblings.forEach(function(s) {
225
+        hide(s);
226
+      });
227
+      if(d.parent) {
228
+        hideSiblings(d.parent);
229
+      }
230
+    }
231
+
232
+    function fadeAncestors(d) {
233
+      if(d.parent) {
234
+        d.parent.data.fade = true;
235
+        fadeAncestors(d.parent);
236
+      }
237
+    }
238
+
239
+    function getRoot(d) {
240
+      if(d.parent) {
241
+        return getRoot(d.parent);
242
+      }
243
+      return d;
244
+    }
245
+
246
+    function zoom(d) {
247
+      tip.hide(d);
248
+      hideSiblings(d);
249
+      show(d);
250
+      fadeAncestors(d);
251
+      update();
252
+      if (typeof clickHandler === 'function') {
253
+        clickHandler(d);
254
+      }
255
+    }
256
+
257
+    function searchTree(d, term) {
258
+      var re = new RegExp(term),
259
+          searchResults = [];
260
+
261
+      function searchInner(d) {
262
+        var label = name(d);
263
+
264
+        if (children(d)) {
265
+          children(d).forEach(function (child) {
266
+            searchInner(child);
267
+          });
268
+        }
269
+
270
+        if (label.match(re)) {
271
+          d.highlight = true;
272
+          searchResults.push(d);
273
+        } else {
274
+          d.highlight = false;
275
+        }
276
+      }
277
+
278
+      searchInner(d);
279
+      return searchResults;
280
+    }
281
+
282
+    function clear(d) {
283
+      d.highlight = false;
284
+      if(children(d)) {
285
+        children(d).forEach(function(child) {
286
+          clear(child);
287
+        });
288
+      }
289
+    }
290
+
291
+    function doSort(a, b) {
292
+      if (typeof sort === 'function') {
293
+        return sort(a, b);
294
+      } else if (sort) {
295
+        return d3.ascending(name(a), name(b));
296
+      }
297
+    }
298
+
299
+    var partition = d3.partition();
300
+
301
+    function filterNodes(root) {
302
+      var nodeList = root.descendants();
303
+      if (minFrameSize > 0) {
304
+        var kx = w / (root.x1 - root.x0);
305
+        nodeList = nodeList.filter(function(el) {
306
+          return ((el.x1 - el.x0) * kx) > minFrameSize;
307
+        });
308
+      }
309
+      return nodeList;
310
+    }
311
+
312
+    function update() {
313
+      selection.each(function(root) {
314
+        var x = d3.scaleLinear().range([0, w]),
315
+            y = d3.scaleLinear().range([0, c]);
316
+
317
+        if (sort) root.sort(doSort);
318
+        root.sum(function(d) {
319
+          if (d.fade || d.hide) {
320
+            return 0;
321
+          }
322
+          // The node's self value is its total value minus all children.
323
+          var v = value(d);
324
+          if (children(d)) {
325
+            var c = children(d);
326
+            for (var i = 0; i < c.length; i++) {
327
+              v -= value(c[i]);
328
+            }
329
+          }
330
+          return v;
331
+        });
332
+        partition(root);
333
+
334
+        var kx = w / (root.x1 - root.x0);
335
+        function width(d) { return (d.x1 - d.x0) * kx; }
336
+
337
+        var descendants = filterNodes(root);
338
+        var g = d3.select(this).select("svg").selectAll("g").data(descendants, function(d) { return d.id; });
339
+
340
+        g.transition()
341
+          .duration(transitionDuration)
342
+          .ease(transitionEase)
343
+          .attr("transform", function(d) { return "translate(" + x(d.x0) + "," + (reversed ? y(d.depth) : (h - y(d.depth) - c)) + ")"; });
344
+
345
+        g.select("rect")
346
+          .attr("width", width);
347
+
348
+        var node = g.enter()
349
+          .append("svg:g")
350
+          .attr("transform", function(d) { return "translate(" + x(d.x0) + "," + (reversed ? y(d.depth) : (h - y(d.depth) - c)) + ")"; });
351
+        
352
+        node.append("svg:rect")
353
+          .transition()
354
+          .delay(transitionDuration / 2)
355
+          .attr("width", width);
356
+        
357
+        if (!tooltip)
358
+          node.append("svg:title");
359
+
360
+        node.append("foreignObject")
361
+          .append("xhtml:div");
362
+
363
+        // Now we have to re-select to see the new elements (why?).
364
+        g = d3.select(this).select("svg").selectAll("g").data(descendants, function(d) { return d.id; });
365
+
366
+        g.attr("width", width)
367
+          .attr("height", function(d) { return c; })
368
+          .attr("name", function(d) { return name(d); })
369
+          .attr("class", function(d) { return d.data.fade ? "frame fade" : "frame"; });
370
+
371
+        g.select("rect")
372
+          .attr("height", function(d) { return c; })
373
+          .attr("fill", function(d) { return colorMapper(d); });
374
+
375
+        if (!tooltip)
376
+          g.select("title")
377
+            .text(label);
378
+
379
+        g.select("foreignObject")
380
+          .attr("width", width)
381
+          .attr("height", function(d) { return c; })
382
+          .select("div")
383
+          .attr("class", "d3-flame-graph-label")
384
+          .style("display", function(d) { return (width(d) < 35) ? "none" : "block";})
385
+          .transition()
386
+          .delay(transitionDuration)
387
+          .text(name);
388
+
389
+        g.on('click', zoom);
390
+
391
+        g.exit()
392
+          .remove();
393
+
394
+        g.on('mouseover', function(d) {
395
+          if (tooltip) tip.show(d);
396
+          setDetails(label(d));
397
+        }).on('mouseout', function(d) {
398
+          if (tooltip) tip.hide(d);
399
+          setDetails("");
400
+        });
401
+      });
402
+    }
403
+
404
+    function merge(data, samples) {
405
+      samples.forEach(function (sample) {
406
+        var node = data.find(function (element) {
407
+          return (element.name === sample.name);
408
+        });
409
+
410
+        if (node) {
411
+          if (node.original) {
412
+            node.original += sample.value;
413
+          } else {
414
+            node.value += sample.value;
415
+          }
416
+          if (sample.children) {
417
+            if (!node.children) {
418
+              node.children = [];
419
+            }
420
+            merge(node.children, sample.children);
421
+          }
422
+        } else {
423
+          data.push(sample);
424
+        }
425
+      });
426
+    }
427
+
428
+    function s4() {
429
+      return Math.floor((1 + Math.random()) * 0x10000)
430
+        .toString(16)
431
+        .substring(1);
432
+    }
433
+
434
+    function injectIds(node) {
435
+      node.id = s4() + "-" + s4() + "-" + "-" + s4() + "-" + s4();
436
+      var children = node.c || node.children || [];
437
+      for (var i = 0; i < children.length; i++) {
438
+        injectIds(children[i]);
439
+      }
440
+    }
441
+
442
+    function chart(s) {
443
+      var root = d3.hierarchy(
444
+        s.datum(), function(d) { return children(d); }
445
+      );
446
+      injectIds(root);
447
+      selection = s.datum(root);
448
+
449
+      if (!arguments.length) return chart;
450
+
451
+      if (!h) {
452
+        h = (root.height + 2) * c;
453
+      }
454
+
455
+      selection.each(function(data) {
456
+
457
+	      if (!svg) {
458
+          svg = d3.select(this)
459
+            .append("svg:svg")
460
+            .attr("width", w)
461
+            .attr("height", h)
462
+            .attr("class", "partition d3-flame-graph")
463
+            .call(tip);
464
+
465
+          svg.append("svg:text")
466
+            .attr("class", "title")
467
+            .attr("text-anchor", "middle")
468
+            .attr("y", "25")
469
+            .attr("x", w/2)
470
+            .attr("fill", "#808080")
471
+            .text(title);
472
+        }
473
+      });
474
+
475
+      // first draw
476
+      update();
477
+    }
478
+
479
+    chart.height = function (_) {
480
+      if (!arguments.length) { return h; }
481
+      h = _;
482
+      return chart;
483
+    };
484
+
485
+    chart.width = function (_) {
486
+      if (!arguments.length) { return w; }
487
+      w = _;
488
+      return chart;
489
+    };
490
+
491
+    chart.cellHeight = function (_) {
492
+      if (!arguments.length) { return c; }
493
+      c = _;
494
+      return chart;
495
+    };
496
+
497
+    chart.tooltip = function (_) {
498
+      if (!arguments.length) { return tooltip; }
499
+      if (typeof _ === "function") {
500
+        tip = _;
501
+      }
502
+      tooltip = !!_;
503
+      return chart;
504
+    };
505
+
506
+    chart.title = function (_) {
507
+      if (!arguments.length) { return title; }
508
+      title = _;
509
+      return chart;
510
+    };
511
+
512
+    chart.transitionDuration = function (_) {
513
+      if (!arguments.length) { return transitionDuration; }
514
+      transitionDuration = _;
515
+      return chart;
516
+    };
517
+
518
+    chart.transitionEase = function (_) {
519
+      if (!arguments.length) { return transitionEase; }
520
+      transitionEase = _;
521
+      return chart;
522
+    };
523
+
524
+    chart.sort = function (_) {
525
+      if (!arguments.length) { return sort; }
526
+      sort = _;
527
+      return chart;
528
+    };
529
+
530
+    chart.reversed = function (_) {
531
+      if (!arguments.length) { return reversed; }
532
+      reversed = _;
533
+      return chart;
534
+    };
535
+
536
+    chart.label = function(_) {
537
+      if (!arguments.length) { return label; }
538
+      label = _;
539
+      return chart;
540
+    };
541
+
542
+    chart.search = function(term) {
543
+      var searchResults = [];
544
+      selection.each(function(data) {
545
+        searchResults = searchTree(data, term);
546
+        update();
547
+      });
548
+      return searchResults;
549
+    };
550
+
551
+    chart.clear = function() {
552
+      selection.each(function(data) {
553
+        clear(data);
554
+        update();
555
+      });
556
+    };
557
+
558
+    chart.zoomTo = function(d) {
559
+      zoom(d);
560
+    };
561
+
562
+    chart.resetZoom = function() {
563
+      selection.each(function (data) {
564
+        zoom(data); // zoom to root
565
+      });
566
+    };
567
+
568
+    chart.onClick = function(_) {
569
+      if (!arguments.length) {
570
+        return clickHandler;
571
+      }
572
+      clickHandler = _;
573
+      return chart;
574
+    };
575
+    
576
+    chart.merge = function(samples) {
577
+      var newRoot; // Need to re-create hierarchy after data changes.
578
+      selection.each(function (root) {
579
+        merge([root.data], [samples]);
580
+        newRoot = d3.hierarchy(root.data, function(d) { return children(d); });
581
+        injectIds(newRoot);
582
+      });
583
+      selection = selection.datum(newRoot);
584
+      update();
585
+    };
586
+    
587
+    chart.color = function(_) {
588
+      if (!arguments.length) { return colorMapper; }
589
+      colorMapper = _;
590
+      return chart;
591
+    };
592
+
593
+    chart.minFrameSize = function (_) {
594
+      if (!arguments.length) { return minFrameSize; }
595
+      minFrameSize = _;
596
+      return chart;
597
+    };
598
+
599
+    chart.details = function (_) {
600
+      if (!arguments.length) { return details; }
601
+      details = _;
602
+      return chart;
603
+    };
604
+
605
+    return chart;
606
+  }
607
+
608
+  // Node/CommonJS exports
609
+  if (typeof(module) !== 'undefined' && typeof(exports) !== 'undefined') {
610
+    module.exports = flameGraph;
611
+  } else {
612
+    d3.flameGraph = flameGraph;
613
+  }
614
+})();
615
+`
616
+
617
+// CSSSource returns the d3.flameGraph.css file
618
+const CSSSource = `
619
+.d3-flame-graph rect {
620
+  stroke: #EEEEEE;
621
+  fill-opacity: .8;
622
+}
623
+
624
+.d3-flame-graph rect:hover {
625
+  stroke: #474747;
626
+  stroke-width: 0.5;
627
+  cursor: pointer;
628
+}
629
+
630
+.d3-flame-graph-label {
631
+  pointer-events: none;
632
+  white-space: nowrap;
633
+  text-overflow: ellipsis;
634
+  overflow: hidden;
635
+  font-size: 12px;
636
+  font-family: Verdana;
637
+  margin-left: 4px;
638
+  margin-right: 4px;
639
+  line-height: 1.5;
640
+  padding: 0 0 0;
641
+  font-weight: 400;
642
+  color: black;
643
+  text-align: left;
644
+}
645
+
646
+.d3-flame-graph .fade {
647
+  opacity: 0.6 !important;
648
+}
649
+
650
+.d3-flame-graph .title {
651
+  font-size: 20px;
652
+  font-family: Verdana;
653
+}
654
+
655
+.d3-flame-graph-tip {
656
+  line-height: 1;
657
+  font-family: Verdana;
658
+  font-size: 12px;
659
+  padding: 12px;
660
+  background: rgba(0, 0, 0, 0.8);
661
+  color: #fff;
662
+  border-radius: 2px;
663
+  pointer-events: none;
664
+}
665
+
666
+/* Creates a small triangle extender for the tooltip */
667
+.d3-flame-graph-tip:after {
668
+  box-sizing: border-box;
669
+  display: inline;
670
+  font-size: 10px;
671
+  width: 100%;
672
+  line-height: 1;
673
+  color: rgba(0, 0, 0, 0.8);
674
+  position: absolute;
675
+  pointer-events: none;
676
+}
677
+
678
+/* Northward tooltips */
679
+.d3-flame-graph-tip.n:after {
680
+  content: "\25BC";
681
+  margin: -1px 0 0 0;
682
+  top: 100%;
683
+  left: 0;
684
+  text-align: center;
685
+}
686
+
687
+/* Eastward tooltips */
688
+.d3-flame-graph-tip.e:after {
689
+  content: "\25C0";
690
+  margin: -4px 0 0 0;
691
+  top: 50%;
692
+  left: -8px;
693
+}
694
+
695
+/* Southward tooltips */
696
+.d3-flame-graph-tip.s:after {
697
+  content: "\25B2";
698
+  margin: 0 0 1px 0;
699
+  top: -8px;
700
+  left: 0;
701
+  text-align: center;
702
+}
703
+
704
+/* Westward tooltips */
705
+.d3-flame-graph-tip.w:after {
706
+  content: "\25B6";
707
+  margin: -4px 0 0 -1px;
708
+  top: 50%;
709
+  left: 100%;
710
+}
711
+`

+ 8
- 0
third_party/d3tip/LICENSE Переглянути файл

@@ -0,0 +1,8 @@
1
+The MIT License (MIT)
2
+Copyright (c) 2013 Justin Palmer
3
+
4
+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:
5
+
6
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+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.

+ 328
- 0
third_party/d3tip/d3_tip.go Переглянути файл

@@ -0,0 +1,328 @@
1
+// Tooltips for d3.js visualizations
2
+// https://github.com/Caged/d3-tip
3
+// Version 0.7.1
4
+// See LICENSE file for license details
5
+
6
+package d3tip
7
+
8
+// JSSource returns the d3-tip.js file
9
+const JSSource = `
10
+(function (root, factory) {
11
+  if (typeof define === 'function' && define.amd) {
12
+    // AMD. Register as an anonymous module with d3 as a dependency.
13
+    define(['d3'], factory)
14
+  } else if (typeof module === 'object' && module.exports) {
15
+    // CommonJS
16
+    var d3 = require('d3')
17
+    module.exports = factory(d3)
18
+  } else {
19
+    // Browser global.
20
+    root.d3.tip = factory(root.d3)
21
+  }
22
+}(this, function (d3) {
23
+
24
+  // Public - contructs a new tooltip
25
+  //
26
+  // Returns a tip
27
+  return function() {
28
+    var direction = d3_tip_direction,
29
+        offset    = d3_tip_offset,
30
+        html      = d3_tip_html,
31
+        node      = initNode(),
32
+        svg       = null,
33
+        point     = null,
34
+        target    = null
35
+
36
+    function tip(vis) {
37
+      svg = getSVGNode(vis)
38
+      point = svg.createSVGPoint()
39
+      document.body.appendChild(node)
40
+    }
41
+
42
+    // Public - show the tooltip on the screen
43
+    //
44
+    // Returns a tip
45
+    tip.show = function() {
46
+      var args = Array.prototype.slice.call(arguments)
47
+      if(args[args.length - 1] instanceof SVGElement) target = args.pop()
48
+
49
+      var content = html.apply(this, args),
50
+          poffset = offset.apply(this, args),
51
+          dir     = direction.apply(this, args),
52
+          nodel   = getNodeEl(),
53
+          i       = directions.length,
54
+          coords,
55
+          scrollTop  = document.documentElement.scrollTop || document.body.scrollTop,
56
+          scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft
57
+
58
+      nodel.html(content)
59
+        .style('opacity', 1).style('pointer-events', 'all')
60
+
61
+      while(i--) nodel.classed(directions[i], false)
62
+      coords = direction_callbacks.get(dir).apply(this)
63
+      nodel.classed(dir, true)
64
+      	.style('top', (coords.top +  poffset[0]) + scrollTop + 'px')
65
+      	.style('left', (coords.left + poffset[1]) + scrollLeft + 'px')
66
+
67
+      return tip;
68
+    };
69
+
70
+    // Public - hide the tooltip
71
+    //
72
+    // Returns a tip
73
+    tip.hide = function() {
74
+      var nodel = getNodeEl()
75
+      nodel.style('opacity', 0).style('pointer-events', 'none')
76
+      return tip
77
+    }
78
+
79
+    // Public: Proxy attr calls to the d3 tip container.  Sets or gets attribute value.
80
+    //
81
+    // n - name of the attribute
82
+    // v - value of the attribute
83
+    //
84
+    // Returns tip or attribute value
85
+    tip.attr = function(n, v) {
86
+      if (arguments.length < 2 && typeof n === 'string') {
87
+        return getNodeEl().attr(n)
88
+      } else {
89
+        var args =  Array.prototype.slice.call(arguments)
90
+        d3.selection.prototype.attr.apply(getNodeEl(), args)
91
+      }
92
+
93
+      return tip
94
+    }
95
+
96
+    // Public: Proxy style calls to the d3 tip container.  Sets or gets a style value.
97
+    //
98
+    // n - name of the property
99
+    // v - value of the property
100
+    //
101
+    // Returns tip or style property value
102
+    tip.style = function(n, v) {
103
+      if (arguments.length < 2 && typeof n === 'string') {
104
+        return getNodeEl().style(n)
105
+      } else {
106
+        var args = Array.prototype.slice.call(arguments)
107
+        d3.selection.prototype.style.apply(getNodeEl(), args)
108
+      }
109
+
110
+      return tip
111
+    }
112
+
113
+    // Public: Set or get the direction of the tooltip
114
+    //
115
+    // v - One of n(north), s(south), e(east), or w(west), nw(northwest),
116
+    //     sw(southwest), ne(northeast) or se(southeast)
117
+    //
118
+    // Returns tip or direction
119
+    tip.direction = function(v) {
120
+      if (!arguments.length) return direction
121
+      direction = v == null ? v : functor(v)
122
+
123
+      return tip
124
+    }
125
+
126
+    // Public: Sets or gets the offset of the tip
127
+    //
128
+    // v - Array of [x, y] offset
129
+    //
130
+    // Returns offset or
131
+    tip.offset = function(v) {
132
+      if (!arguments.length) return offset
133
+      offset = v == null ? v : functor(v)
134
+
135
+      return tip
136
+    }
137
+
138
+    // Public: sets or gets the html value of the tooltip
139
+    //
140
+    // v - String value of the tip
141
+    //
142
+    // Returns html value or tip
143
+    tip.html = function(v) {
144
+      if (!arguments.length) return html
145
+      html = v == null ? v : functor(v)
146
+
147
+      return tip
148
+    }
149
+
150
+    // Public: destroys the tooltip and removes it from the DOM
151
+    //
152
+    // Returns a tip
153
+    tip.destroy = function() {
154
+      if(node) {
155
+        getNodeEl().remove();
156
+        node = null;
157
+      }
158
+      return tip;
159
+    }
160
+
161
+    function d3_tip_direction() { return 'n' }
162
+    function d3_tip_offset() { return [0, 0] }
163
+    function d3_tip_html() { return ' ' }
164
+
165
+    var direction_callbacks = d3.map({
166
+      n:  direction_n,
167
+      s:  direction_s,
168
+      e:  direction_e,
169
+      w:  direction_w,
170
+      nw: direction_nw,
171
+      ne: direction_ne,
172
+      sw: direction_sw,
173
+      se: direction_se
174
+    }),
175
+
176
+    directions = direction_callbacks.keys()
177
+
178
+    function direction_n() {
179
+      var bbox = getScreenBBox()
180
+      return {
181
+        top:  bbox.n.y - node.offsetHeight,
182
+        left: bbox.n.x - node.offsetWidth / 2
183
+      }
184
+    }
185
+
186
+    function direction_s() {
187
+      var bbox = getScreenBBox()
188
+      return {
189
+        top:  bbox.s.y,
190
+        left: bbox.s.x - node.offsetWidth / 2
191
+      }
192
+    }
193
+
194
+    function direction_e() {
195
+      var bbox = getScreenBBox()
196
+      return {
197
+        top:  bbox.e.y - node.offsetHeight / 2,
198
+        left: bbox.e.x
199
+      }
200
+    }
201
+
202
+    function direction_w() {
203
+      var bbox = getScreenBBox()
204
+      return {
205
+        top:  bbox.w.y - node.offsetHeight / 2,
206
+        left: bbox.w.x - node.offsetWidth
207
+      }
208
+    }
209
+
210
+    function direction_nw() {
211
+      var bbox = getScreenBBox()
212
+      return {
213
+        top:  bbox.nw.y - node.offsetHeight,
214
+        left: bbox.nw.x - node.offsetWidth
215
+      }
216
+    }
217
+
218
+    function direction_ne() {
219
+      var bbox = getScreenBBox()
220
+      return {
221
+        top:  bbox.ne.y - node.offsetHeight,
222
+        left: bbox.ne.x
223
+      }
224
+    }
225
+
226
+    function direction_sw() {
227
+      var bbox = getScreenBBox()
228
+      return {
229
+        top:  bbox.sw.y,
230
+        left: bbox.sw.x - node.offsetWidth
231
+      }
232
+    }
233
+
234
+    function direction_se() {
235
+      var bbox = getScreenBBox()
236
+      return {
237
+        top:  bbox.se.y,
238
+        left: bbox.e.x
239
+      }
240
+    }
241
+
242
+    function initNode() {
243
+      var node = d3.select(document.createElement('div'));
244
+      node.style('position', 'absolute').style('top', 0).style('opacity', 0)
245
+      	.style('pointer-events', 'none').style('box-sizing', 'border-box')
246
+
247
+      return node.node()
248
+    }
249
+
250
+    function getSVGNode(el) {
251
+      el = el.node()
252
+      if(el.tagName.toLowerCase() === 'svg')
253
+        return el
254
+
255
+      return el.ownerSVGElement
256
+    }
257
+
258
+    function getNodeEl() {
259
+      if(node === null) {
260
+        node = initNode();
261
+        // re-add node to DOM
262
+        document.body.appendChild(node);
263
+      };
264
+      return d3.select(node);
265
+    }
266
+
267
+    // Private - gets the screen coordinates of a shape
268
+    //
269
+    // Given a shape on the screen, will return an SVGPoint for the directions
270
+    // n(north), s(south), e(east), w(west), ne(northeast), se(southeast), nw(northwest),
271
+    // sw(southwest).
272
+    //
273
+    //    +-+-+
274
+    //    |   |
275
+    //    +   +
276
+    //    |   |
277
+    //    +-+-+
278
+    //
279
+    // Returns an Object {n, s, e, w, nw, sw, ne, se}
280
+    function getScreenBBox() {
281
+      var targetel   = target || d3.event.target;
282
+
283
+      while ('undefined' === typeof targetel.getScreenCTM && 'undefined' === targetel.parentNode) {
284
+          targetel = targetel.parentNode;
285
+      }
286
+
287
+      var bbox       = {},
288
+          matrix     = targetel.getScreenCTM(),
289
+          tbbox      = targetel.getBBox(),
290
+          width      = tbbox.width,
291
+          height     = tbbox.height,
292
+          x          = tbbox.x,
293
+          y          = tbbox.y
294
+
295
+      point.x = x
296
+      point.y = y
297
+      bbox.nw = point.matrixTransform(matrix)
298
+      point.x += width
299
+      bbox.ne = point.matrixTransform(matrix)
300
+      point.y += height
301
+      bbox.se = point.matrixTransform(matrix)
302
+      point.x -= width
303
+      bbox.sw = point.matrixTransform(matrix)
304
+      point.y -= height / 2
305
+      bbox.w  = point.matrixTransform(matrix)
306
+      point.x += width
307
+      bbox.e = point.matrixTransform(matrix)
308
+      point.x -= width / 2
309
+      point.y -= height / 2
310
+      bbox.n = point.matrixTransform(matrix)
311
+      point.y += height
312
+      bbox.s = point.matrixTransform(matrix)
313
+
314
+      return bbox
315
+    }
316
+    
317
+    // Private - replace D3JS 3.X d3.functor() function
318
+    function functor(v) {
319
+    	return typeof v === "function" ? v : function() {
320
+        return v
321
+    	}
322
+    }
323
+
324
+    return tip
325
+  };
326
+
327
+}));
328
+`