cmd/vendor/github.com/google/pprof: refresh from upstream

Updating to commit 0e0e5b7254e076a62326ab7305ba49e8515f0c91
from github.com/google/pprof

Recent modifications to the vendored pprof, such as skipping
TestWebInterface to avoid starting a web browser, have all been fixed
upstream.

Change-Id: I72e11108c438e1573bf2f9216e76d157378e8d45
Reviewed-on: https://go-review.googlesource.com/93375
Run-TryBot: Daniel Martí <mvdan@mvdan.cc>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
This commit is contained in:
Daniel Martí 2018-02-12 16:34:48 +00:00
parent afb9fc1de9
commit e7cbbbe9bb
46 changed files with 7670 additions and 836 deletions

View file

@ -1,8 +0,0 @@
.DS_Store
*~
*.orig
*.exe
.*.swp
core
coverage.txt
pprof

View file

@ -1,27 +1,77 @@
Want to contribute? Great! First, read this page (including the small print at the end).
Want to contribute? Great: read the page (including the small print at the end).
### Before you contribute
# Before you contribute
Before we can use your code, you must sign the
[Google Individual Contributor License Agreement](https://cla.developers.google.com/about/google-individual)
(CLA), which you can do online. The CLA is necessary mainly because you own the
copyright to your changes, even after your contribution becomes part of our
codebase, so we need your permission to use and distribute your code. We also
need to be sure of various other things—for instance that you'll tell us if you
know that your code infringes on other people's patents. You don't have to sign
the CLA until after you've submitted your code for review and a member has
approved it, but you must do it before we can put your code into our codebase.
Before you start working on a larger contribution, you should get in touch with
us first through the issue tracker with your idea so that we can help out and
possibly guide you. Coordinating up front makes it much easier to avoid
frustration later on.
As an individual, sign the [Google Individual Contributor License
Agreement](https://cla.developers.google.com/about/google-individual) (CLA)
online. This is required for any of your code to be accepted.
### Code reviews
Before you start working on a larger contribution, get in touch with us first
through the issue tracker with your idea so that we can help out and possibly
guide you. Coordinating up front makes it much easier to avoid frustration later
on.
All submissions, including submissions by project members, require review.
We use Github pull requests for this purpose.
# Development
### The small print
Make sure `GOPATH` is set in your current shell. The common way is to have
something like `export GOPATH=$HOME/gocode` in your `.bashrc` file so that it's
automatically set in all console sessions.
Contributions made by corporations are covered by a different agreement than the one above,
the [Software Grant and Corporate Contributor License Agreement](https://cla.developers.google.com/about/google-corporate).
To get the source code, run
```
go get github.com/google/pprof
```
To run the tests, do
```
cd $GOPATH/src/github.com/google/pprof
go test -v ./...
```
When you wish to work with your own fork of the source (which is required to be
able to create a pull request), you'll want to get your fork repo as another Git
remote in the same `github.com/google/pprof` directory. Otherwise, if you'll `go
get` your fork directly, you'll be getting errors like `use of internal package
not allowed` when running tests. To set up the remote do something like
```
cd $GOPATH/src/github.com/google/pprof
git remote add aalexand git@github.com:aalexand/pprof.git
git fetch aalexand
git checkout -b my-new-feature
# hack hack hack
go test -v ./...
git commit -a -m "Add new feature."
git push aalexand
```
where `aalexand` is your GitHub user ID. Then proceed to the GitHub UI to send a
code review.
# Code reviews
All submissions, including submissions by project members, require review.
We use GitHub pull requests for this purpose.
The pprof source code is in Go with a bit of JavaScript, CSS and HTML. If you
are new to Go, read [Effective Go](https://golang.org/doc/effective_go.html) and
the [summary on typical comments during Go code
reviews](https://github.com/golang/go/wiki/CodeReviewComments).
Cover all new functionality with tests. Enable Travis on your forked repo,
enable builds of branches and make sure Travis is happily green for the branch
with your changes.
The code coverage is measured for each pull request. The code coverage is
expected to go up with every change.
Pull requests not meeting the above guidelines will get less attention than good
ones, so make sure your submissions are high quality.
# The small print
Contributions made by corporations are covered by a different agreement than the
one above, the [Software Grant and Corporate Contributor License
Agreement](https://cla.developers.google.com/about/google-corporate).

View file

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

View file

@ -175,20 +175,35 @@ func (bu *Binutils) Open(name string, start, limit, offset uint64) (plugin.ObjFi
func (b *binrep) openMachO(name string, start, limit, offset uint64) (plugin.ObjFile, error) {
of, err := macho.Open(name)
if err != nil {
return nil, fmt.Errorf("Parsing %s: %v", name, err)
return nil, fmt.Errorf("error parsing %s: %v", name, err)
}
defer of.Close()
if b.fast || (!b.addr2lineFound && !b.llvmSymbolizerFound) {
return &fileNM{file: file{b: b, name: name}}, nil
// Subtract the load address of the __TEXT section. Usually 0 for shared
// libraries or 0x100000000 for executables. You can check this value by
// running `objdump -private-headers <file>`.
textSegment := of.Segment("__TEXT")
if textSegment == nil {
return nil, fmt.Errorf("could not identify base for %s: no __TEXT segment", name)
}
return &fileAddr2Line{file: file{b: b, name: name}}, nil
if textSegment.Addr > start {
return nil, fmt.Errorf("could not identify base for %s: __TEXT segment address (0x%x) > mapping start address (0x%x)",
name, textSegment.Addr, start)
}
base := start - textSegment.Addr
if b.fast || (!b.addr2lineFound && !b.llvmSymbolizerFound) {
return &fileNM{file: file{b: b, name: name, base: base}}, nil
}
return &fileAddr2Line{file: file{b: b, name: name, base: base}}, nil
}
func (b *binrep) openELF(name string, start, limit, offset uint64) (plugin.ObjFile, error) {
ef, err := elf.Open(name)
if err != nil {
return nil, fmt.Errorf("Parsing %s: %v", name, err)
return nil, fmt.Errorf("error parsing %s: %v", name, err)
}
defer ef.Close()
@ -215,9 +230,9 @@ func (b *binrep) openELF(name string, start, limit, offset uint64) (plugin.ObjFi
}
}
base, err := elfexec.GetBase(&ef.FileHeader, nil, stextOffset, start, limit, offset)
base, err := elfexec.GetBase(&ef.FileHeader, elfexec.FindTextProgHeader(ef), stextOffset, start, limit, offset)
if err != nil {
return nil, fmt.Errorf("Could not identify base for %s: %v", name, err)
return nil, fmt.Errorf("could not identify base for %s: %v", name, err)
}
buildID := ""

View file

@ -177,14 +177,20 @@ func TestSetFastSymbolization(t *testing.T) {
func skipUnlessLinuxAmd64(t *testing.T) {
if runtime.GOOS != "linux" || runtime.GOARCH != "amd64" {
t.Skip("Disasm only tested on x86-64 linux")
t.Skip("This test only works on x86-64 Linux")
}
}
func skipUnlessDarwinAmd64(t *testing.T) {
if runtime.GOOS != "darwin" || runtime.GOARCH != "amd64" {
t.Skip("This test only works on x86-64 Mac")
}
}
func TestDisasm(t *testing.T) {
skipUnlessLinuxAmd64(t)
bu := &Binutils{}
insts, err := bu.Disasm(filepath.Join("testdata", "hello"), 0, math.MaxUint64)
insts, err := bu.Disasm(filepath.Join("testdata", "exe_linux_64"), 0, math.MaxUint64)
if err != nil {
t.Fatalf("Disasm: unexpected error %v", err)
}
@ -199,42 +205,119 @@ func TestDisasm(t *testing.T) {
}
}
func TestObjFile(t *testing.T) {
skipUnlessLinuxAmd64(t)
bu := &Binutils{}
f, err := bu.Open(filepath.Join("testdata", "hello"), 0, math.MaxUint64, 0)
if err != nil {
t.Fatalf("Open: unexpected error %v", err)
}
defer f.Close()
syms, err := f.Symbols(regexp.MustCompile("main"), 0)
if err != nil {
t.Fatalf("Symbols: unexpected error %v", err)
}
find := func(name string) *plugin.Sym {
for _, s := range syms {
for _, n := range s.Name {
if n == name {
return s
}
func findSymbol(syms []*plugin.Sym, name string) *plugin.Sym {
for _, s := range syms {
for _, n := range s.Name {
if n == name {
return s
}
}
return nil
}
m := find("main")
if m == nil {
t.Fatalf("Symbols: did not find main")
return nil
}
func TestObjFile(t *testing.T) {
skipUnlessLinuxAmd64(t)
for _, tc := range []struct {
desc string
start, limit, offset uint64
addr uint64
}{
{"fake mapping", 0, math.MaxUint64, 0, 0x40052d},
{"fixed load address", 0x400000, 0x4006fc, 0, 0x40052d},
// True user-mode ASLR binaries are ET_DYN rather than ET_EXEC so this case
// is a bit artificial except that it approximates the
// vmlinux-with-kernel-ASLR case where the binary *is* ET_EXEC.
{"simulated ASLR address", 0x500000, 0x5006fc, 0, 0x50052d},
} {
t.Run(tc.desc, func(t *testing.T) {
bu := &Binutils{}
f, err := bu.Open(filepath.Join("testdata", "exe_linux_64"), tc.start, tc.limit, tc.offset)
if err != nil {
t.Fatalf("Open: unexpected error %v", err)
}
defer f.Close()
syms, err := f.Symbols(regexp.MustCompile("main"), 0)
if err != nil {
t.Fatalf("Symbols: unexpected error %v", err)
}
m := findSymbol(syms, "main")
if m == nil {
t.Fatalf("Symbols: did not find main")
}
for _, addr := range []uint64{m.Start + f.Base(), tc.addr} {
gotFrames, err := f.SourceLine(addr)
if err != nil {
t.Fatalf("SourceLine: unexpected error %v", err)
}
wantFrames := []plugin.Frame{
{Func: "main", File: "/tmp/hello.c", Line: 3},
}
if !reflect.DeepEqual(gotFrames, wantFrames) {
t.Fatalf("SourceLine for main: got %v; want %v\n", gotFrames, wantFrames)
}
}
})
}
frames, err := f.SourceLine(m.Start)
if err != nil {
t.Fatalf("SourceLine: unexpected error %v", err)
}
expect := []plugin.Frame{
{Func: "main", File: "/tmp/hello.c", Line: 3},
}
if !reflect.DeepEqual(frames, expect) {
t.Fatalf("SourceLine for main: expect %v; got %v\n", expect, frames)
}
func TestMachoFiles(t *testing.T) {
skipUnlessDarwinAmd64(t)
t.Skip("Disabled because of issues with addr2line (see https://github.com/google/pprof/pull/313#issuecomment-364073010)")
// Load `file`, pretending it was mapped at `start`. Then get the symbol
// table. Check that it contains the symbol `sym` and that the address
// `addr` gives the `expected` stack trace.
for _, tc := range []struct {
desc string
file string
start, limit, offset uint64
addr uint64
sym string
expected []plugin.Frame
}{
{"normal mapping", "exe_mac_64", 0x100000000, math.MaxUint64, 0,
0x100000f50, "_main",
[]plugin.Frame{
{Func: "main", File: "/tmp/hello.c", Line: 3},
}},
{"other mapping", "exe_mac_64", 0x200000000, math.MaxUint64, 0,
0x200000f50, "_main",
[]plugin.Frame{
{Func: "main", File: "/tmp/hello.c", Line: 3},
}},
{"lib normal mapping", "lib_mac_64", 0, math.MaxUint64, 0,
0xfa0, "_bar",
[]plugin.Frame{
{Func: "bar", File: "/tmp/lib.c", Line: 6},
}},
} {
t.Run(tc.desc, func(t *testing.T) {
bu := &Binutils{}
f, err := bu.Open(filepath.Join("testdata", tc.file), tc.start, tc.limit, tc.offset)
if err != nil {
t.Fatalf("Open: unexpected error %v", err)
}
defer f.Close()
syms, err := f.Symbols(nil, 0)
if err != nil {
t.Fatalf("Symbols: unexpected error %v", err)
}
m := findSymbol(syms, tc.sym)
if m == nil {
t.Fatalf("Symbols: could not find symbol %v", tc.sym)
}
gotFrames, err := f.SourceLine(tc.addr)
if err != nil {
t.Fatalf("SourceLine: unexpected error %v", err)
}
if !reflect.DeepEqual(gotFrames, tc.expected) {
t.Fatalf("SourceLine for main: got %v; want %v\n", gotFrames, tc.expected)
}
})
}
}

View file

@ -34,24 +34,48 @@ var (
func findSymbols(syms []byte, file string, r *regexp.Regexp, address uint64) ([]*plugin.Sym, error) {
// Collect all symbols from the nm output, grouping names mapped to
// the same address into a single symbol.
// The symbols to return.
var symbols []*plugin.Sym
// The current group of symbol names, and the address they are all at.
names, start := []string{}, uint64(0)
buf := bytes.NewBuffer(syms)
for symAddr, name, err := nextSymbol(buf); err == nil; symAddr, name, err = nextSymbol(buf) {
for {
symAddr, name, err := nextSymbol(buf)
if err == io.EOF {
// Done. If there was an unfinished group, append it.
if len(names) != 0 {
if match := matchSymbol(names, start, symAddr-1, r, address); match != nil {
symbols = append(symbols, &plugin.Sym{Name: match, File: file, Start: start, End: symAddr - 1})
}
}
// And return the symbols.
return symbols, nil
}
if err != nil {
// There was some kind of serious error reading nm's output.
return nil, err
}
if start == symAddr {
// If this symbol is at the same address as the current group, add it to the group.
if symAddr == start {
names = append(names, name)
continue
}
// Otherwise append the current group to the list of symbols.
if match := matchSymbol(names, start, symAddr-1, r, address); match != nil {
symbols = append(symbols, &plugin.Sym{Name: match, File: file, Start: start, End: symAddr - 1})
}
// And start a new group.
names, start = []string{name}, symAddr
}
return symbols, nil
}
// matchSymbol checks if a symbol is to be selected by checking its
@ -62,7 +86,7 @@ func matchSymbol(names []string, start, end uint64, r *regexp.Regexp, address ui
return names
}
for _, name := range names {
if r.MatchString(name) {
if r == nil || r.MatchString(name) {
return []string{name}
}

View file

@ -28,7 +28,6 @@ import (
"github.com/google/pprof/internal/plugin"
"github.com/google/pprof/internal/report"
"github.com/google/pprof/third_party/svg"
)
// commands describes the commands accepted by pprof.
@ -398,7 +397,7 @@ func massageDotSVG() PostProcessor {
if err := generateSVG(input, baseSVG, ui); err != nil {
return err
}
_, err := output.Write([]byte(svg.Massage(baseSVG.String())))
_, err := output.Write([]byte(massageSVG(baseSVG.String())))
return err
}
}

View file

@ -54,7 +54,7 @@ func PProf(eo *plugin.Options) error {
}
if src.HTTPHostport != "" {
return serveWebInterface(src.HTTPHostport, p, o)
return serveWebInterface(src.HTTPHostport, p, o, true)
}
return interactive(p, o)
}

View file

@ -1487,8 +1487,14 @@ func (m *mockFile) Symbols(r *regexp.Regexp, addr uint64) ([]*plugin.Sym, error)
switch r.String() {
case "line[13]":
return []*plugin.Sym{
{[]string{"line1000"}, m.name, 0x1000, 0x1003},
{[]string{"line3000"}, m.name, 0x3000, 0x3004},
{
Name: []string{"line1000"}, File: m.name,
Start: 0x1000, End: 0x1003,
},
{
Name: []string{"line3000"}, File: m.name,
Start: 0x3000, End: 0x3004,
},
}, nil
}
return nil, fmt.Errorf("unimplemented")

View file

@ -423,16 +423,9 @@ func TestHttpsInsecure(t *testing.T) {
Timeout: 10,
Symbolize: "remote",
}
rx := "Saved profile in"
if runtime.GOOS == "darwin" && (runtime.GOARCH == "arm" || runtime.GOARCH == "arm64") ||
runtime.GOOS == "android" {
// On iOS, $HOME points to the app root directory and is not writable.
// On Android, $HOME points to / which is not writable.
rx += "|Could not use temp dir"
}
o := &plugin.Options{
Obj: &binutils.Binutils{},
UI: &proftest.TestUI{T: t, AllowRx: rx},
UI: &proftest.TestUI{T: t, AllowRx: "Saved profile in"},
}
o.Sym = &symbolizer.Symbolizer{Obj: o.Obj, UI: o.UI}
p, err := fetchProfiles(s, o)

View file

@ -0,0 +1,99 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package driver
import (
"encoding/json"
"html/template"
"net/http"
"strings"
"github.com/google/pprof/internal/graph"
"github.com/google/pprof/internal/measurement"
"github.com/google/pprof/internal/report"
)
type treeNode struct {
Name string `json:"n"`
Cum int64 `json:"v"`
CumFormat string `json:"l"`
Percent string `json:"p"`
Children []*treeNode `json:"c"`
}
// flamegraph generates a web page containing a flamegraph.
func (ui *webInterface) flamegraph(w http.ResponseWriter, req *http.Request) {
// Force the call tree so that the graph is a tree.
// Also do not trim the tree so that the flame graph contains all functions.
rpt, errList := ui.makeReport(w, req, []string{"svg"}, "call_tree", "true", "trim", "false")
if rpt == nil {
return // error already reported
}
// Generate dot graph.
g, config := report.GetDOT(rpt)
var nodes []*treeNode
nroots := 0
rootValue := int64(0)
nodeArr := []string{}
nodeMap := map[*graph.Node]*treeNode{}
// Make all nodes and the map, collect the roots.
for _, n := range g.Nodes {
v := n.CumValue()
node := &treeNode{
Name: n.Info.PrintableName(),
Cum: v,
CumFormat: config.FormatValue(v),
Percent: strings.TrimSpace(measurement.Percentage(v, config.Total)),
}
nodes = append(nodes, node)
if len(n.In) == 0 {
nodes[nroots], nodes[len(nodes)-1] = nodes[len(nodes)-1], nodes[nroots]
nroots++
rootValue += v
}
nodeMap[n] = node
// Get all node names into an array.
nodeArr = append(nodeArr, n.Info.Name)
}
// Populate the child links.
for _, n := range g.Nodes {
node := nodeMap[n]
for child := range n.Out {
node.Children = append(node.Children, nodeMap[child])
}
}
rootNode := &treeNode{
Name: "root",
Cum: rootValue,
CumFormat: config.FormatValue(rootValue),
Percent: strings.TrimSpace(measurement.Percentage(rootValue, config.Total)),
Children: nodes[0:nroots],
}
// JSON marshalling flame graph
b, err := json.Marshal(rootNode)
if err != nil {
http.Error(w, "error serializing flame graph", http.StatusInternalServerError)
ui.options.UI.PrintErr(err)
return
}
ui.render(w, "/flamegraph", "flamegraph", rpt, errList, config.Labels, webArgs{
FlameGraph: template.JS(b),
Nodes: nodeArr,
})
}

View file

@ -42,6 +42,9 @@ func interactive(p *profile.Profile, o *plugin.Options) error {
interactiveMode = true
shortcuts := profileShortcuts(p)
// Get all groups in pprofVariables to allow for clearer error messages.
groups := groupOptions(pprofVariables)
greetings(p, o.UI)
for {
input, err := o.UI.ReadLine("(pprof) ")
@ -87,6 +90,9 @@ func interactive(p *profile.Profile, o *plugin.Options) error {
o.UI.PrintErr(err)
}
continue
} else if okValues := groups[name]; okValues != nil {
o.UI.PrintErr(fmt.Errorf("Unrecognized value for %s: %q. Use one of %s", name, value, strings.Join(okValues, ", ")))
continue
}
}
@ -118,6 +124,23 @@ func interactive(p *profile.Profile, o *plugin.Options) error {
}
}
// groupOptions returns a map containing all non-empty groups
// mapped to an array of the option names in that group in
// sorted order.
func groupOptions(vars variables) map[string][]string {
groups := make(map[string][]string)
for name, option := range vars {
group := option.group
if group != "" {
groups[group] = append(groups[group], name)
}
}
for _, names := range groups {
sort.Strings(names)
}
return groups
}
var generateReportWrapper = generateReport // For testing purposes.
// greetings prints a brief welcome and some overall profile

View file

@ -16,12 +16,12 @@ package driver
import (
"fmt"
"io"
"math/rand"
"strings"
"testing"
"github.com/google/pprof/internal/plugin"
"github.com/google/pprof/internal/proftest"
"github.com/google/pprof/internal/report"
"github.com/google/pprof/profile"
)
@ -70,6 +70,21 @@ func TestShell(t *testing.T) {
t.Error("second shortcut attempt:", err)
}
// Group with invalid value
pprofVariables = testVariables(savedVariables)
ui := &proftest.TestUI{
T: t,
Input: []string{"cumulative=this"},
AllowRx: `Unrecognized value for cumulative: "this". Use one of cum, flat`,
}
o.UI = ui
if err := interactive(p, o); err != nil {
t.Error("invalid group value:", err)
}
// Confirm error message written out once.
if ui.NumAllowRxMatches != 1 {
t.Errorf("want error message to be printed 1 time, got %v", ui.NumAllowRxMatches)
}
// Verify propagation of IO errors
pprofVariables = testVariables(savedVariables)
o.UI = newUI(t, []string{"**error**"})
@ -144,47 +159,12 @@ func makeShortcuts(input []string, seed int) (shortcuts, []string) {
}
func newUI(t *testing.T, input []string) plugin.UI {
return &testUI{
t: t,
input: input,
return &proftest.TestUI{
T: t,
Input: input,
}
}
type testUI struct {
t *testing.T
input []string
index int
}
func (ui *testUI) ReadLine(_ string) (string, error) {
if ui.index >= len(ui.input) {
return "", io.EOF
}
input := ui.input[ui.index]
if input == "**error**" {
return "", fmt.Errorf("Error: %s", input)
}
ui.index++
return input, nil
}
func (ui *testUI) Print(args ...interface{}) {
}
func (ui *testUI) PrintErr(args ...interface{}) {
output := fmt.Sprint(args)
if output != "" {
ui.t.Error(output)
}
}
func (ui *testUI) IsTerminal() bool {
return false
}
func (ui *testUI) SetAutoComplete(func(string) string) {
}
func checkValue(p *profile.Profile, cmd []string, vars variables, o *plugin.Options) error {
if len(cmd) != 2 {
return fmt.Errorf("expected len(cmd)==2, got %v", cmd)

View file

@ -12,12 +12,13 @@
// See the License for the specific language governing permissions and
// limitations under the License.
// Package svg provides tools related to handling of SVG files
package svg
package driver
import (
"regexp"
"strings"
"github.com/google/pprof/third_party/svgpan"
)
var (
@ -26,15 +27,15 @@ var (
svgClose = regexp.MustCompile(`</svg>`)
)
// Massage enhances the SVG output from DOT to provide better
// panning inside a web browser. It uses the SVGPan library, which is
// embedded into the svgPanJS variable.
func Massage(svg string) string {
// massageSVG enhances the SVG output from DOT to provide better
// panning inside a web browser. It uses the svgpan library, which is
// embedded into the svgpan.JSSource variable.
func massageSVG(svg string) string {
// Work around for dot bug which misses quoting some ampersands,
// resulting on unparsable SVG.
svg = strings.Replace(svg, "&;", "&amp;;", -1)
//Dot's SVG output is
// Dot's SVG output is
//
// <svg width="___" height="___"
// viewBox="___" xmlns=...>
@ -48,7 +49,7 @@ func Massage(svg string) string {
// <svg width="100%" height="100%"
// xmlns=...>
// <script type="text/ecmascript"><![CDATA[` ..$(svgPanJS)... `]]></script>`
// <script type="text/ecmascript"><![CDATA[` ..$(svgpan.JSSource)... `]]></script>`
// <g id="viewport" transform="translate(0,0)">
// <g id="graph0" transform="...">
// ...
@ -64,7 +65,7 @@ func Massage(svg string) string {
if loc := graphID.FindStringIndex(svg); loc != nil {
svg = svg[:loc[0]] +
`<script type="text/ecmascript"><![CDATA[` + string(svgPanJS) + `]]></script>` +
`<script type="text/ecmascript"><![CDATA[` + string(svgpan.JSSource) + `]]></script>` +
`<g id="viewport" transform="scale(0.5,0.5) translate(0,0)">` +
svg[loc[0]:]
}

View file

@ -61,7 +61,7 @@ function pprof_toggle_asm(e) {
<div class="legend">File: testbinary<br>
Type: cpu<br>
Duration: 10s, Total samples = 1.12s (11.20%)<br>Total: 1.12s</div><h1>line1000</h1>testdata/file1000.src
Duration: 10s, Total samples = 1.12s (11.20%)<br>Total: 1.12s</div><h2>line1000</h2><p class="filename">testdata/file1000.src</p>
<pre onClick="pprof_toggle_asm(event)">
Total: 1.10s 1.10s (flat, cum) 98.21%
<span class=line> 1</span> <span class=deadsrc> 1.10s 1.10s line1 </span><span class=asm> 1.10s 1.10s 1000: instruction one <span class=unimportant>file1000.src:1</span>
@ -77,7 +77,7 @@ Duration: 10s, Total samples = 1.12s (11.20%)<br>Total: 1.12s</div><h1>line1000<
<span class=line> 6</span> <span class=nop> . . line6 </span>
<span class=line> 7</span> <span class=nop> . . line7 </span>
</pre>
<h1>line3000</h1>testdata/file3000.src
<h2>line3000</h2><p class="filename">testdata/file3000.src</p>
<pre onClick="pprof_toggle_asm(event)">
Total: 10ms 1.12s (flat, cum) 100%
<span class=line> 1</span> <span class=nop> . . line1 </span>

File diff suppressed because it is too large Load diff

View file

@ -69,31 +69,24 @@ func (ec *errorCatcher) PrintErr(args ...interface{}) {
// webArgs contains arguments passed to templates in webhtml.go.
type webArgs struct {
BaseURL string
Title string
Errors []string
Total int64
Legend []string
Help map[string]string
Nodes []string
HTMLBody template.HTML
TextBody string
Top []report.TextItem
BaseURL string
Title string
Errors []string
Total int64
Legend []string
Help map[string]string
Nodes []string
HTMLBody template.HTML
TextBody string
Top []report.TextItem
FlameGraph template.JS
}
func serveWebInterface(hostport string, p *profile.Profile, o *plugin.Options) error {
host, portStr, err := net.SplitHostPort(hostport)
func serveWebInterface(hostport string, p *profile.Profile, o *plugin.Options, wantBrowser bool) error {
host, port, err := getHostAndPort(hostport)
if err != nil {
return fmt.Errorf("could not split http address: %v", err)
return err
}
port, err := strconv.Atoi(portStr)
if err != nil {
return fmt.Errorf("invalid port number: %v", err)
}
if host == "" {
host = "localhost"
}
interactiveMode = true
ui := makeWebInterface(p, o)
for n, c := range pprofCommands {
@ -111,22 +104,52 @@ func serveWebInterface(hostport string, p *profile.Profile, o *plugin.Options) e
server = defaultWebServer
}
args := &plugin.HTTPServerArgs{
Hostport: net.JoinHostPort(host, portStr),
Hostport: net.JoinHostPort(host, strconv.Itoa(port)),
Host: host,
Port: port,
Handlers: map[string]http.Handler{
"/": http.HandlerFunc(ui.dot),
"/top": http.HandlerFunc(ui.top),
"/disasm": http.HandlerFunc(ui.disasm),
"/source": http.HandlerFunc(ui.source),
"/peek": http.HandlerFunc(ui.peek),
"/": http.HandlerFunc(ui.dot),
"/top": http.HandlerFunc(ui.top),
"/disasm": http.HandlerFunc(ui.disasm),
"/source": http.HandlerFunc(ui.source),
"/peek": http.HandlerFunc(ui.peek),
"/flamegraph": http.HandlerFunc(ui.flamegraph),
},
}
go openBrowser("http://"+args.Hostport, o)
if wantBrowser {
go openBrowser("http://"+args.Hostport, o)
}
return server(args)
}
func getHostAndPort(hostport string) (string, int, error) {
host, portStr, err := net.SplitHostPort(hostport)
if err != nil {
return "", 0, fmt.Errorf("could not split http address: %v", err)
}
if host == "" {
host = "localhost"
}
var port int
if portStr == "" {
ln, err := net.Listen("tcp", net.JoinHostPort(host, "0"))
if err != nil {
return "", 0, fmt.Errorf("could not generate random port: %v", err)
}
port = ln.Addr().(*net.TCPAddr).Port
err = ln.Close()
if err != nil {
return "", 0, fmt.Errorf("could not generate random port: %v", err)
}
} else {
port, err = strconv.Atoi(portStr)
if err != nil {
return "", 0, fmt.Errorf("invalid port number: %v", err)
}
}
return host, port, nil
}
func defaultWebServer(args *plugin.HTTPServerArgs) error {
ln, err := net.Listen("tcp", args.Hostport)
if err != nil {

View file

@ -23,24 +23,15 @@ import (
"net/url"
"os/exec"
"regexp"
"runtime"
"sync"
"testing"
"time"
"runtime"
"github.com/google/pprof/internal/plugin"
"github.com/google/pprof/profile"
)
func TestWebInterface(t *testing.T) {
// This test starts a web browser in a background goroutine
// after a 500ms delay. Sometimes the test exits before it
// can run the browser, but sometimes the browser does open.
// That's obviously unacceptable.
defer time.Sleep(2 * time.Second) // to see the browser open
t.Skip("golang.org/issue/22651")
if runtime.GOOS == "nacl" {
t.Skip("test assumes tcp available")
}
@ -66,7 +57,7 @@ func TestWebInterface(t *testing.T) {
Obj: fakeObjTool{},
UI: &stdUI{},
HTTPServer: creator,
})
}, false)
<-serverCreated
defer server.Close()
@ -89,6 +80,7 @@ func TestWebInterface(t *testing.T) {
[]string{"300ms.*F1", "200ms.*300ms.*F2"}, false},
{"/disasm?f=" + url.QueryEscape("F[12]"),
[]string{"f1:asm", "f2:asm"}, false},
{"/flamegraph", []string{"File: testbin", "\"n\":\"root\"", "\"n\":\"F1\"", "function tip", "function flameGraph", "function hierarchy"}, false},
}
for _, c := range testcases {
if c.needDot && !haveDot {
@ -127,14 +119,19 @@ func TestWebInterface(t *testing.T) {
for count := 0; count < 2; count++ {
wg.Add(1)
go func() {
http.Get(path)
wg.Done()
defer wg.Done()
res, err := http.Get(path)
if err != nil {
t.Error("could not fetch", c.path, err)
return
}
if _, err = ioutil.ReadAll(res.Body); err != nil {
t.Error("could not read response", c.path, err)
}
}()
}
}
wg.Wait()
time.Sleep(5 * time.Second)
}
// Implement fake object file support.
@ -153,9 +150,18 @@ func (f fakeObj) SourceLine(addr uint64) ([]plugin.Frame, error) {
}
func (f fakeObj) Symbols(r *regexp.Regexp, addr uint64) ([]*plugin.Sym, error) {
return []*plugin.Sym{
{[]string{"F1"}, fakeSource, addrBase, addrBase + 10},
{[]string{"F2"}, fakeSource, addrBase + 10, addrBase + 20},
{[]string{"F3"}, fakeSource, addrBase + 20, addrBase + 30},
{
Name: []string{"F1"}, File: fakeSource,
Start: addrBase, End: addrBase + 10,
},
{
Name: []string{"F2"}, File: fakeSource,
Start: addrBase + 10, End: addrBase + 20,
},
{
Name: []string{"F3"}, File: fakeSource,
Start: addrBase + 20, End: addrBase + 30,
},
}, nil
}
@ -229,6 +235,41 @@ func makeFakeProfile() *profile.Profile {
}
}
func TestGetHostAndPort(t *testing.T) {
if runtime.GOOS == "nacl" {
t.Skip("test assumes tcp available")
}
type testCase struct {
hostport string
wantHost string
wantPort int
wantRandomPort bool
}
testCases := []testCase{
{":", "localhost", 0, true},
{":4681", "localhost", 4681, false},
{"localhost:4681", "localhost", 4681, false},
}
for _, tc := range testCases {
host, port, err := getHostAndPort(tc.hostport)
if err != nil {
t.Errorf("could not get host and port for %q: %v", tc.hostport, err)
}
if got, want := host, tc.wantHost; got != want {
t.Errorf("for %s, got host %s, want %s", tc.hostport, got, want)
continue
}
if !tc.wantRandomPort {
if got, want := port, tc.wantPort; got != want {
t.Errorf("for %s, got port %d, want %d", tc.hostport, got, want)
continue
}
}
}
}
func TestIsLocalHost(t *testing.T) {
for _, s := range []string{"localhost:10000", "[::1]:10000", "127.0.0.1:10000"} {
host, _, err := net.SplitHostPort(s)

View file

@ -259,3 +259,19 @@ func GetBase(fh *elf.FileHeader, loadSegment *elf.ProgHeader, stextOffset *uint6
}
return 0, fmt.Errorf("Don't know how to handle FileHeader.Type %v", fh.Type)
}
// FindTextProgHeader finds the program segment header containing the .text
// section or nil if the segment cannot be found.
func FindTextProgHeader(f *elf.File) *elf.ProgHeader {
for _, s := range f.Sections {
if s.Name == ".text" {
// Find the LOAD segment containing the .text section.
for _, p := range f.Progs {
if p.Type == elf.PT_LOAD && p.Flags&elf.PF_X != 0 && s.Addr >= p.Vaddr && s.Addr < p.Vaddr+p.Memsz {
return &p.ProgHeader
}
}
}
}
return nil
}

View file

@ -154,7 +154,7 @@ func (b *builder) addNode(node *Node, nodeID int, maxFlat float64) {
if flat != 0 {
label = label + fmt.Sprintf(`%s (%s)`,
flatValue,
strings.TrimSpace(percentage(flat, b.config.Total)))
strings.TrimSpace(measurement.Percentage(flat, b.config.Total)))
} else {
label = label + "0"
}
@ -168,7 +168,7 @@ func (b *builder) addNode(node *Node, nodeID int, maxFlat float64) {
cumValue = b.config.FormatValue(cum)
label = label + fmt.Sprintf(`of %s (%s)`,
cumValue,
strings.TrimSpace(percentage(cum, b.config.Total)))
strings.TrimSpace(measurement.Percentage(cum, b.config.Total)))
}
// Scale font sizes from 8 to 24 based on percentage of flat frequency.
@ -380,23 +380,6 @@ func dotColor(score float64, isBackground bool) string {
return fmt.Sprintf("#%02x%02x%02x", uint8(r*255.0), uint8(g*255.0), uint8(b*255.0))
}
// percentage computes the percentage of total of a value, and encodes
// it as a string. At least two digits of precision are printed.
func percentage(value, total int64) string {
var ratio float64
if total != 0 {
ratio = math.Abs(float64(value)/float64(total)) * 100
}
switch {
case math.Abs(ratio) >= 99.95 && math.Abs(ratio) <= 100.05:
return " 100%"
case math.Abs(ratio) >= 1.0:
return fmt.Sprintf("%5.2f%%", ratio)
default:
return fmt.Sprintf("%5.2g%%", ratio)
}
}
func multilinePrintableName(info *NodeInfo) string {
infoCopy := *info
infoCopy.Name = strings.Replace(infoCopy.Name, "::", `\n`, -1)

View file

@ -17,6 +17,7 @@ package measurement
import (
"fmt"
"math"
"strings"
"time"
@ -154,6 +155,23 @@ func ScaledLabel(value int64, fromUnit, toUnit string) string {
return sv + u
}
// Percentage computes the percentage of total of a value, and encodes
// it as a string. At least two digits of precision are printed.
func Percentage(value, total int64) string {
var ratio float64
if total != 0 {
ratio = math.Abs(float64(value)/float64(total)) * 100
}
switch {
case math.Abs(ratio) >= 99.95 && math.Abs(ratio) <= 100.05:
return " 100%"
case math.Abs(ratio) >= 1.0:
return fmt.Sprintf("%5.2f%%", ratio)
default:
return fmt.Sprintf("%5.2g%%", ratio)
}
}
// isMemoryUnit returns whether a name is recognized as a memory size
// unit.
func isMemoryUnit(unit string) bool {

View file

@ -19,6 +19,7 @@ package proftest
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
@ -80,11 +81,21 @@ type TestUI struct {
Ignore int
AllowRx string
NumAllowRxMatches int
Input []string
index int
}
// ReadLine returns no input, as no input is expected during testing.
func (ui *TestUI) ReadLine(_ string) (string, error) {
return "", fmt.Errorf("no input")
if ui.index >= len(ui.Input) {
return "", io.EOF
}
input := ui.Input[ui.index]
ui.index++
if input == "**error**" {
return "", fmt.Errorf("Error: %s", input)
}
return input, nil
}
// Print messages are discarded by the test UI.

View file

@ -19,7 +19,6 @@ package report
import (
"fmt"
"io"
"math"
"path/filepath"
"regexp"
"sort"
@ -425,7 +424,7 @@ func PrintAssembly(w io.Writer, rpt *Report, obj plugin.ObjTool, maxFuncs int) e
}
fmt.Fprintf(w, "%10s %10s (flat, cum) %s of Total\n",
rpt.formatValue(flatSum), rpt.formatValue(cumSum),
percentage(cumSum, rpt.total))
measurement.Percentage(cumSum, rpt.total))
function, file, line := "", "", 0
for _, n := range ns {
@ -704,7 +703,7 @@ func printTags(w io.Writer, rpt *Report) error {
for _, t := range graph.SortTags(tags, true) {
f, u := measurement.Scale(t.FlatValue(), o.SampleUnit, o.OutputUnit)
if total > 0 {
fmt.Fprintf(tabw, " \t%.1f%s (%s):\t %s\n", f, u, percentage(t.FlatValue(), total), t.Name)
fmt.Fprintf(tabw, " \t%.1f%s (%s):\t %s\n", f, u, measurement.Percentage(t.FlatValue(), total), t.Name)
} else {
fmt.Fprintf(tabw, " \t%.1f%s:\t %s\n", f, u, t.Name)
}
@ -789,9 +788,9 @@ func printText(w io.Writer, rpt *Report) error {
}
flatSum += item.Flat
fmt.Fprintf(w, "%10s %s %s %10s %s %s%s\n",
item.FlatFormat, percentage(item.Flat, rpt.total),
percentage(flatSum, rpt.total),
item.CumFormat, percentage(item.Cum, rpt.total),
item.FlatFormat, measurement.Percentage(item.Flat, rpt.total),
measurement.Percentage(flatSum, rpt.total),
item.CumFormat, measurement.Percentage(item.Cum, rpt.total),
item.Name, inl)
}
return nil
@ -1030,17 +1029,17 @@ func printTree(w io.Writer, rpt *Report) error {
inline = " (inline)"
}
fmt.Fprintf(w, "%50s %s | %s%s\n", rpt.formatValue(in.Weight),
percentage(in.Weight, cum), in.Src.Info.PrintableName(), inline)
measurement.Percentage(in.Weight, cum), in.Src.Info.PrintableName(), inline)
}
// Print current node.
flatSum += flat
fmt.Fprintf(w, "%10s %s %s %10s %s | %s\n",
rpt.formatValue(flat),
percentage(flat, rpt.total),
percentage(flatSum, rpt.total),
measurement.Percentage(flat, rpt.total),
measurement.Percentage(flatSum, rpt.total),
rpt.formatValue(cum),
percentage(cum, rpt.total),
measurement.Percentage(cum, rpt.total),
name)
// Print outgoing edges.
@ -1051,7 +1050,7 @@ func printTree(w io.Writer, rpt *Report) error {
inline = " (inline)"
}
fmt.Fprintf(w, "%50s %s | %s%s\n", rpt.formatValue(out.Weight),
percentage(out.Weight, cum), out.Dest.Info.PrintableName(), inline)
measurement.Percentage(out.Weight, cum), out.Dest.Info.PrintableName(), inline)
}
}
if len(g.Nodes) > 0 {
@ -1083,23 +1082,6 @@ func printDOT(w io.Writer, rpt *Report) error {
return nil
}
// percentage computes the percentage of total of a value, and encodes
// it as a string. At least two digits of precision are printed.
func percentage(value, total int64) string {
var ratio float64
if total != 0 {
ratio = math.Abs(float64(value)/float64(total)) * 100
}
switch {
case math.Abs(ratio) >= 99.95 && math.Abs(ratio) <= 100.05:
return " 100%"
case math.Abs(ratio) >= 1.0:
return fmt.Sprintf("%5.2f%%", ratio)
default:
return fmt.Sprintf("%5.2g%%", ratio)
}
}
// ProfileLabels returns printable labels for a profile.
func ProfileLabels(rpt *Report) []string {
label := []string{}
@ -1131,7 +1113,7 @@ func ProfileLabels(rpt *Report) []string {
totalNanos, totalUnit := measurement.Scale(rpt.total, o.SampleUnit, "nanoseconds")
var ratio string
if totalUnit == "ns" && totalNanos != 0 {
ratio = "(" + percentage(int64(totalNanos), prof.DurationNanos) + ")"
ratio = "(" + measurement.Percentage(int64(totalNanos), prof.DurationNanos) + ")"
}
label = append(label, fmt.Sprintf("Duration: %s, Total samples = %s %s", duration, rpt.formatValue(rpt.total), ratio))
}
@ -1162,7 +1144,7 @@ func reportLabels(rpt *Report, g *graph.Graph, origCount, droppedNodes, droppedE
label = append(label, activeFilters...)
}
label = append(label, fmt.Sprintf("Showing nodes accounting for %s, %s of %s total", rpt.formatValue(flatSum), strings.TrimSpace(percentage(flatSum, rpt.total)), rpt.formatValue(rpt.total)))
label = append(label, fmt.Sprintf("Showing nodes accounting for %s, %s of %s total", rpt.formatValue(flatSum), strings.TrimSpace(measurement.Percentage(flatSum, rpt.total)), rpt.formatValue(rpt.total)))
if rpt.total != 0 {
if droppedNodes > 0 {

View file

@ -68,8 +68,8 @@ func TestSource(t *testing.T) {
want: path + "source.dot",
},
} {
b := bytes.NewBuffer(nil)
if err := Generate(b, tc.rpt, &binutils.Binutils{}); err != nil {
var b bytes.Buffer
if err := Generate(&b, tc.rpt, &binutils.Binutils{}); err != nil {
t.Fatalf("%s: %v", tc.want, err)
}

View file

@ -28,6 +28,7 @@ import (
"strings"
"github.com/google/pprof/internal/graph"
"github.com/google/pprof/internal/measurement"
"github.com/google/pprof/internal/plugin"
)
@ -99,7 +100,7 @@ func printSource(w io.Writer, rpt *Report) error {
fmt.Fprintf(w, "ROUTINE ======================== %s in %s\n", name, filename)
fmt.Fprintf(w, "%10s %10s (flat, cum) %s of Total\n",
rpt.formatValue(flatSum), rpt.formatValue(cumSum),
percentage(cumSum, rpt.total))
measurement.Percentage(cumSum, rpt.total))
if err != nil {
fmt.Fprintf(w, " Error: %v\n", err)
@ -337,13 +338,13 @@ func printHeader(w io.Writer, rpt *Report) {
// printFunctionHeader prints a function header for a weblist report.
func printFunctionHeader(w io.Writer, name, path string, flatSum, cumSum int64, rpt *Report) {
fmt.Fprintf(w, `<h1>%s</h1>%s
fmt.Fprintf(w, `<h2>%s</h2><p class="filename">%s</p>
<pre onClick="pprof_toggle_asm(event)">
Total: %10s %10s (flat, cum) %s
`,
template.HTMLEscapeString(name), template.HTMLEscapeString(path),
rpt.formatValue(flatSum), rpt.formatValue(cumSum),
percentage(cumSum, rpt.total))
measurement.Percentage(cumSum, rpt.total))
}
// printFunctionSourceLine prints a source line and the corresponding assembly.

View file

@ -25,8 +25,8 @@ func TestWebList(t *testing.T) {
SampleValue: func(v []int64) int64 { return v[1] },
SampleUnit: cpu.SampleType[1].Unit,
})
buf := bytes.NewBuffer(nil)
if err := Generate(buf, rpt, &binutils.Binutils{}); err != nil {
var buf bytes.Buffer
if err := Generate(&buf, rpt, &binutils.Binutils{}); err != nil {
t.Fatalf("could not generate weblist: %v", err)
}
output := buf.String()

View file

@ -168,6 +168,7 @@ func doLocalSymbolize(prof *profile.Profile, fast, force bool, obj plugin.ObjToo
}
l.Line = make([]profile.Line, len(stack))
l.IsFolded = false
for i, frame := range stack {
if frame.Func != "" {
m.HasFunctions = true

View file

@ -63,10 +63,29 @@ func Symbolize(p *profile.Profile, force bool, sources plugin.MappingSources, sy
return nil
}
// Check whether path ends with one of the suffixes listed in
// pprof_remote_servers.html from the gperftools distribution
func hasGperftoolsSuffix(path string) bool {
suffixes := []string{
"/pprof/heap",
"/pprof/growth",
"/pprof/profile",
"/pprof/pmuprofile",
"/pprof/contention",
}
for _, s := range suffixes {
if strings.HasSuffix(path, s) {
return true
}
}
return false
}
// symbolz returns the corresponding symbolz source for a profile URL.
func symbolz(source string) string {
if url, err := url.Parse(source); err == nil && url.Host != "" {
if strings.Contains(url.Path, "/debug/pprof/") {
// All paths in the net/http/pprof Go package contain /debug/pprof/
if strings.Contains(url.Path, "/debug/pprof/") || hasGperftoolsSuffix(url.Path) {
url.Path = path.Clean(url.Path + "/../symbol")
} else {
url.Path = "/symbolz"

View file

@ -34,6 +34,17 @@ func TestSymbolzURL(t *testing.T) {
"http://host:8000/debug/pprof/profile?seconds=10": "http://host:8000/debug/pprof/symbol",
"http://host:8000/debug/pprof/heap": "http://host:8000/debug/pprof/symbol",
"http://some.host:8080/some/deeper/path/debug/pprof/endpoint?param=value": "http://some.host:8080/some/deeper/path/debug/pprof/symbol",
"http://host:8000/pprof/profile": "http://host:8000/pprof/symbol",
"http://host:8000/pprof/profile?seconds=15": "http://host:8000/pprof/symbol",
"http://host:8000/pprof/heap": "http://host:8000/pprof/symbol",
"http://host:8000/debug/pprof/block": "http://host:8000/debug/pprof/symbol",
"http://host:8000/debug/pprof/trace?seconds=5": "http://host:8000/debug/pprof/symbol",
"http://host:8000/debug/pprof/mutex": "http://host:8000/debug/pprof/symbol",
"http://host/whatever/pprof/heap": "http://host/whatever/pprof/symbol",
"http://host/whatever/pprof/growth": "http://host/whatever/pprof/symbol",
"http://host/whatever/pprof/profile": "http://host/whatever/pprof/symbol",
"http://host/whatever/pprof/pmuprofile": "http://host/whatever/pprof/symbol",
"http://host/whatever/pprof/contention": "http://host/whatever/pprof/symbol",
} {
if got := symbolz(try); got != want {
t.Errorf(`symbolz(%s)=%s, want "%s"`, try, got, want)

View file

@ -214,7 +214,12 @@ var profileDecoder = []decoder{
// int64 keep_frames = 8
func(b *buffer, m message) error { return decodeInt64(b, &m.(*Profile).keepFramesX) },
// int64 time_nanos = 9
func(b *buffer, m message) error { return decodeInt64(b, &m.(*Profile).TimeNanos) },
func(b *buffer, m message) error {
if m.(*Profile).TimeNanos != 0 {
return errConcatProfile
}
return decodeInt64(b, &m.(*Profile).TimeNanos)
},
// int64 duration_nanos = 10
func(b *buffer, m message) error { return decodeInt64(b, &m.(*Profile).DurationNanos) },
// ValueType period_type = 11
@ -480,6 +485,7 @@ func (p *Location) encode(b *buffer) {
for i := range p.Line {
encodeMessage(b, 4, &p.Line[i])
}
encodeBoolOpt(b, 5, p.IsFolded)
}
var locationDecoder = []decoder{
@ -493,6 +499,7 @@ var locationDecoder = []decoder{
pp.Line = append(pp.Line, Line{})
return decodeMessage(b, &pp.Line[n])
},
func(b *buffer, m message) error { return decodeBool(b, &m.(*Location).IsFolded) }, // optional bool is_folded = 5;
}
func (p *Line) decoder() []decoder {

View file

@ -64,7 +64,7 @@ func Merge(srcs []*Profile) (*Profile, error) {
// represents the main binary. Take the first Mapping we see,
// otherwise the operations below will add mappings in an
// arbitrary order.
pm.mapMapping(srcs[0].Mapping[0])
pm.mapMapping(src.Mapping[0])
}
for _, s := range src.Sample {
@ -234,10 +234,11 @@ func (pm *profileMerger) mapLocation(src *Location) *Location {
mi := pm.mapMapping(src.Mapping)
l := &Location{
ID: uint64(len(pm.p.Location) + 1),
Mapping: mi.m,
Address: uint64(int64(src.Address) + mi.offset),
Line: make([]Line, len(src.Line)),
ID: uint64(len(pm.p.Location) + 1),
Mapping: mi.m,
Address: uint64(int64(src.Address) + mi.offset),
Line: make([]Line, len(src.Line)),
IsFolded: src.IsFolded,
}
for i, ln := range src.Line {
l.Line[i] = pm.mapLine(ln)
@ -258,7 +259,8 @@ func (pm *profileMerger) mapLocation(src *Location) *Location {
// key generates locationKey to be used as a key for maps.
func (l *Location) key() locationKey {
key := locationKey{
addr: l.Address,
addr: l.Address,
isFolded: l.IsFolded,
}
if l.Mapping != nil {
// Normalizes address to handle address space randomization.
@ -279,6 +281,7 @@ func (l *Location) key() locationKey {
type locationKey struct {
addr, mappingID uint64
lines string
isFolded bool
}
func (pm *profileMerger) mapMapping(src *Mapping) mapInfo {
@ -422,6 +425,7 @@ func combineHeaders(srcs []*Profile) (*Profile, error) {
var timeNanos, durationNanos, period int64
var comments []string
seenComments := map[string]bool{}
var defaultSampleType string
for _, s := range srcs {
if timeNanos == 0 || s.TimeNanos < timeNanos {
@ -431,7 +435,12 @@ func combineHeaders(srcs []*Profile) (*Profile, error) {
if period == 0 || period < s.Period {
period = s.Period
}
comments = append(comments, s.Comments...)
for _, c := range s.Comments {
if seen := seenComments[c]; !seen {
comments = append(comments, c)
seenComments[c] = true
}
}
if defaultSampleType == "" {
defaultSampleType = s.DefaultSampleType
}

View file

@ -109,10 +109,11 @@ type Mapping struct {
// Location corresponds to Profile.Location
type Location struct {
ID uint64
Mapping *Mapping
Address uint64
Line []Line
ID uint64
Mapping *Mapping
Address uint64
Line []Line
IsFolded bool
mappingIDX uint64
}
@ -163,7 +164,7 @@ func ParseData(data []byte) (*Profile, error) {
return nil, fmt.Errorf("decompressing profile: %v", err)
}
}
if p, err = ParseUncompressed(data); err != nil && err != errNoData {
if p, err = ParseUncompressed(data); err != nil && err != errNoData && err != errConcatProfile {
p, err = parseLegacy(data)
}
@ -180,6 +181,7 @@ func ParseData(data []byte) (*Profile, error) {
var errUnrecognized = fmt.Errorf("unrecognized profile format")
var errMalformed = fmt.Errorf("malformed profile format")
var errNoData = fmt.Errorf("empty input file")
var errConcatProfile = fmt.Errorf("concatenated profiles detected")
func parseLegacy(data []byte) (*Profile, error) {
parsers := []func([]byte) (*Profile, error){
@ -591,6 +593,9 @@ func (l *Location) string() string {
if m := l.Mapping; m != nil {
locStr = locStr + fmt.Sprintf("M=%d ", m.ID)
}
if l.IsFolded {
locStr = locStr + "[F] "
}
if len(l.Line) == 0 {
ss = append(ss, locStr)
}

View file

@ -73,11 +73,11 @@ func TestParse(t *testing.T) {
}
// Reencode and decode.
bw := bytes.NewBuffer(nil)
if err := p.Write(bw); err != nil {
var bw bytes.Buffer
if err := p.Write(&bw); err != nil {
t.Fatalf("%s: %v", source, err)
}
if p, err = Parse(bw); err != nil {
if p, err = Parse(&bw); err != nil {
t.Fatalf("%s: %v", source, err)
}
js2 := p.String()
@ -108,6 +108,21 @@ func TestParseError(t *testing.T) {
}
}
func TestParseConcatentated(t *testing.T) {
prof := testProfile1.Copy()
// Write the profile twice to buffer to create concatented profile.
var buf bytes.Buffer
prof.Write(&buf)
prof.Write(&buf)
_, err := Parse(&buf)
if err == nil {
t.Fatalf("got nil, want error")
}
if got, want := err.Error(), "parsing profile: concatenated profiles detected"; want != got {
t.Fatalf("got error %q, want error %q", got, want)
}
}
func TestCheckValid(t *testing.T) {
const path = "testdata/java.cpu"
@ -276,6 +291,7 @@ var cpuL = []*Location{
}
var testProfile1 = &Profile{
TimeNanos: 10000,
PeriodType: &ValueType{Type: "cpu", Unit: "milliseconds"},
Period: 1,
DurationNanos: 10e9,
@ -330,6 +346,60 @@ var testProfile1 = &Profile{
Mapping: cpuM,
}
var testProfile1NoMapping = &Profile{
PeriodType: &ValueType{Type: "cpu", Unit: "milliseconds"},
Period: 1,
DurationNanos: 10e9,
SampleType: []*ValueType{
{Type: "samples", Unit: "count"},
{Type: "cpu", Unit: "milliseconds"},
},
Sample: []*Sample{
{
Location: []*Location{cpuL[0]},
Value: []int64{1000, 1000},
Label: map[string][]string{
"key1": {"tag1"},
"key2": {"tag1"},
},
},
{
Location: []*Location{cpuL[1], cpuL[0]},
Value: []int64{100, 100},
Label: map[string][]string{
"key1": {"tag2"},
"key3": {"tag2"},
},
},
{
Location: []*Location{cpuL[2], cpuL[0]},
Value: []int64{10, 10},
Label: map[string][]string{
"key1": {"tag3"},
"key2": {"tag2"},
},
},
{
Location: []*Location{cpuL[3], cpuL[0]},
Value: []int64{10000, 10000},
Label: map[string][]string{
"key1": {"tag4"},
"key2": {"tag1"},
},
},
{
Location: []*Location{cpuL[4], cpuL[0]},
Value: []int64{1, 1},
Label: map[string][]string{
"key1": {"tag4"},
"key2": {"tag1"},
},
},
},
Location: cpuL,
Function: cpuF,
}
var testProfile2 = &Profile{
PeriodType: &ValueType{Type: "cpu", Unit: "milliseconds"},
Period: 1,
@ -577,6 +647,7 @@ func TestMerge(t *testing.T) {
// location should add up to 0).
prof := testProfile1.Copy()
prof.Comments = []string{"comment1"}
p1, err := Merge([]*Profile{prof, prof})
if err != nil {
t.Errorf("merge error: %v", err)
@ -586,6 +657,9 @@ func TestMerge(t *testing.T) {
if err != nil {
t.Errorf("merge error: %v", err)
}
if got, want := len(prof.Comments), 1; got != want {
t.Errorf("len(prof.Comments) = %d, want %d", got, want)
}
// Use aggregation to merge locations at function granularity.
if err := prof.Aggregate(false, true, false, false, false); err != nil {
@ -627,6 +701,39 @@ func TestMergeAll(t *testing.T) {
}
}
func TestIsFoldedMerge(t *testing.T) {
testProfile1Folded := testProfile1.Copy()
testProfile1Folded.Location[0].IsFolded = true
testProfile1Folded.Location[1].IsFolded = true
for _, tc := range []struct {
name string
profs []*Profile
wantLocationLen int
}{
{
name: "folded and non-folded locations not merged",
profs: []*Profile{testProfile1.Copy(), testProfile1Folded.Copy()},
wantLocationLen: 7,
},
{
name: "identical folded locations are merged",
profs: []*Profile{testProfile1Folded.Copy(), testProfile1Folded.Copy()},
wantLocationLen: 5,
},
} {
t.Run(tc.name, func(t *testing.T) {
prof, err := Merge(tc.profs)
if err != nil {
t.Fatalf("merge error: %v", err)
}
if got, want := len(prof.Location), tc.wantLocationLen; got != want {
t.Fatalf("got %d locations, want %d locations", got, want)
}
})
}
}
func TestNumLabelMerge(t *testing.T) {
for _, tc := range []struct {
name string
@ -684,6 +791,40 @@ func TestNumLabelMerge(t *testing.T) {
}
}
func TestEmptyMappingMerge(t *testing.T) {
// Aggregate a profile with itself and once again with a factor of
// -2. Should end up with an empty profile (all samples for a
// location should add up to 0).
prof1 := testProfile1.Copy()
prof2 := testProfile1NoMapping.Copy()
p1, err := Merge([]*Profile{prof2, prof1})
if err != nil {
t.Errorf("merge error: %v", err)
}
prof2.Scale(-2)
prof, err := Merge([]*Profile{p1, prof2})
if err != nil {
t.Errorf("merge error: %v", err)
}
// Use aggregation to merge locations at function granularity.
if err := prof.Aggregate(false, true, false, false, false); err != nil {
t.Errorf("aggregating after merge: %v", err)
}
samples := make(map[string]int64)
for _, s := range prof.Sample {
tb := locationHash(s)
samples[tb] = samples[tb] + s.Value[0]
}
for s, v := range samples {
if v != 0 {
t.Errorf("nonzero value for sample %s: %d", s, v)
}
}
}
func TestNormalizeBySameProfile(t *testing.T) {
pb := testProfile1.Copy()
p := testProfile1.Copy()

View file

@ -52,6 +52,8 @@ var testF = []*Function{
{ID: 1, Name: "func1", SystemName: "func1", Filename: "file1"},
{ID: 2, Name: "func2", SystemName: "func2", Filename: "file1"},
{ID: 3, Name: "func3", SystemName: "func3", Filename: "file2"},
{ID: 4, Name: "func4", SystemName: "func4", Filename: "file3"},
{ID: 5, Name: "func5", SystemName: "func5", Filename: "file4"},
}
var testL = []*Location{
@ -86,6 +88,22 @@ var testL = []*Location{
Mapping: testM[1],
Address: 12,
},
{
ID: 4,
Mapping: testM[1],
Address: 12,
Line: []Line{
{
Function: testF[4],
Line: 6,
},
{
Function: testF[4],
Line: 6,
},
},
IsFolded: true,
},
}
var all = &Profile{
@ -133,9 +151,9 @@ var all = &Profile{
func TestMarshalUnmarshal(t *testing.T) {
// Write the profile, parse it, and ensure they're equal.
buf := bytes.NewBuffer(nil)
all.Write(buf)
all2, err := Parse(buf)
var buf bytes.Buffer
all.Write(&buf)
all2, err := Parse(&buf)
if err != nil {
t.Fatal(err)
}

View file

@ -1,3 +1,8 @@
// Copyright (c) 2016, Google Inc.
// All rights reserved.
//
////////////////////////////////////////////////////////////////////////////////
// Profile is a common stacktrace profile format.
//
// Measurements represented with this format should follow the
@ -151,7 +156,7 @@ message Location {
// instruction addresses or any integer sequence as ids.
uint64 id = 1;
// The id of the corresponding profile.Mapping for this location.
// If can be unset if the mapping is unknown or not applicable for
// It can be unset if the mapping is unknown or not applicable for
// this profile type.
uint64 mapping_id = 2;
// The instruction address for this location, if available. It
@ -168,6 +173,12 @@ message Location {
// line[0].function_name == "memcpy"
// line[1].function_name == "printf"
repeated Line line = 4;
// Provides an indication that multiple symbols map to this location's
// address, for example due to identical code folding by the linker. In that
// case the line information above represents one of the multiple
// symbols. This field must be recomputed when the symbolization state of the
// profile changes.
bool is_folded = 5;
}
message Line {

View file

@ -1,13 +1,19 @@
#!/usr/bin/env bash
set -e
set -x
MODE=atomic
echo "mode: $MODE" > coverage.txt
PKG=$(go list ./... | grep -v /vendor/)
# All packages.
PKG=$(go list ./...)
staticcheck $PKG
unused $PKG
# Packages that have any tests.
PKG=$(go list -f '{{if .TestGoFiles}} {{.ImportPath}} {{end}}' ./...)
go test -v $PKG
for d in $PKG; do
@ -17,3 +23,4 @@ for d in $PKG; do
rm profile.out
fi
done

View file

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

View file

@ -0,0 +1,119 @@
# Building a customized D3.js bundle
The D3.js version distributed with pprof is customized to only include the modules required by pprof.
## Dependencies
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:
```js
{
"name": "d3-pprof",
"version": "1.0.0",
"description": "A d3.js bundle for pprof.",
"scripts": {
"prepare": "rollup -c && uglifyjs d3.js -c -m -o d3.min.js"
},
"license": "Apache-2.0",
"devDependencies": {
"d3-selection": "1.1.0",
"d3-hierarchy": "1.1.5",
"d3-scale": "1.0.6",
"d3-format": "1.2.0",
"d3-ease": "1.0.3",
"d3-array": "1.2.1",
"d3-collection": "1.0.4",
"d3-transition": "1.1.0",
"rollup": "0.51.8",
"rollup-plugin-node-resolve": "3",
"uglify-js": "3.1.10"
}
}
```
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.
## Bundler
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.
First, create a `rollup.config.js` file, containing the configuration Rollup should use to build the bundle.
```js
import node from "rollup-plugin-node-resolve";
export default {
input: "index.js",
output: {
format: "umd",
file: "d3.js"
},
name: "d3",
plugins: [node()],
sourcemap: false
};
```
Then create an `index.js` file containing all the functions that need to be exported in the bundle.
```js
export {
select,
selection,
event,
} from "d3-selection";
export {
hierarchy,
partition,
} from "d3-hierarchy";
export {
scaleLinear,
} from "d3-scale";
export {
format,
} from "d3-format";
export {
easeCubic,
} from "d3-ease";
export {
ascending,
} from "d3-array";
export {
map,
} from "d3-collection";
export {
transition,
} from "d3-transition";
```
## Building
Once all files were created, execute the following commands to pull all dependencies and build the bundle.
```
% npm install
% npm run prepare
```
This will create two files, `d3.js` and `d3.min.js`, the custom D3.js bundle and its minified version respectively.
# References
## D3 Custom Bundle
A demonstration of building a custom D3 4.0 bundle using ES2015 modules and Rollup.
[bl.ocks.org/mbostock/bb09af4c39c79cffcde4](https://bl.ocks.org/mbostock/bb09af4c39c79cffcde4)
## d3-pprof
A repository containing all previously mentioned configuration files and the generated custom bundle.
[github.com/spiermar/d3-pprof](https://github.com/spiermar/d3-pprof)

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View file

@ -0,0 +1,711 @@
// A D3.js plugin that produces flame graphs from hierarchical data.
// https://github.com/spiermar/d3-flame-graph
// Version 1.0.11
// See LICENSE file for license details
package d3flamegraph
// JSSource returns the d3.flameGraph.js file
const JSSource = `
/**!
*
* Copyright 2017 Martin Spier <spiermar@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
(function() {
'use strict';
/*jshint eqnull:true */
// https://tc39.github.io/ecma262/#sec-array.prototype.find
if (!Array.prototype.find) {
Object.defineProperty(Array.prototype, 'find', {
value: function(predicate) {
// 1. Let O be ? ToObject(this value).
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var o = Object(this);
// 2. Let len be ? ToLength(? Get(O, "length")).
var len = o.length >>> 0;
// 3. If IsCallable(predicate) is false, throw a TypeError exception.
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
// 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
var thisArg = arguments[1];
// 5. Let k be 0.
var k = 0;
// 6. Repeat, while k < len
while (k < len) {
// a. Let Pk be ! ToString(k).
// b. Let kValue be ? Get(O, Pk).
// c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
// d. If testResult is true, return kValue.
var kValue = o[k];
if (predicate.call(thisArg, kValue, k, o)) {
return kValue;
}
// e. Increase k by 1.
k++;
}
// 7. Return undefined.
return undefined;
}
});
}
if (!Array.prototype.filter)
Array.prototype.filter = function(func, thisArg) {
if ( ! ((typeof func === 'function') && this) )
throw new TypeError();
var len = this.length >>> 0,
res = new Array(len), // preallocate array
c = 0, i = -1;
if (thisArg === undefined)
while (++i !== len)
// checks to see if the key was set
if (i in this)
if (func(t[i], i, t))
res[c++] = t[i];
else
while (++i !== len)
// checks to see if the key was set
if (i in this)
if (func.call(thisArg, t[i], i, t))
res[c++] = t[i];
res.length = c; // shrink down array to proper size
return res;
};
/*jshint eqnull:false */
// Node/CommonJS - require D3
if (typeof(module) !== 'undefined' && typeof(exports) !== 'undefined' && typeof(d3) == 'undefined') {
d3 = require('d3');
}
// Node/CommonJS - require d3-tip
if (typeof(module) !== 'undefined' && typeof(exports) !== 'undefined' && typeof(d3.tip) == 'undefined') {
d3.tip = require('d3-tip');
}
function flameGraph() {
var w = 960, // graph width
h = null, // graph height
c = 18, // cell height
selection = null, // selection
tooltip = true, // enable tooltip
title = "", // graph title
transitionDuration = 750,
transitionEase = d3.easeCubic, // tooltip offset
sort = false,
reversed = false, // reverse the graph direction
clickHandler = null,
minFrameSize = 0,
details = null;
var tip = d3.tip()
.direction("s")
.offset([8, 0])
.attr('class', 'd3-flame-graph-tip')
.html(function(d) { return label(d); });
var svg;
function name(d) {
return d.data.n || d.data.name;
}
function children(d) {
return d.c || d.children;
}
function value(d) {
return d.v || d.value;
}
var label = function(d) {
return name(d) + " (" + d3.format(".3f")(100 * (d.x1 - d.x0), 3) + "%, " + value(d) + " samples)";
};
function setDetails(t) {
if (details)
details.innerHTML = t;
}
var colorMapper = function(d) {
return d.highlight ? "#E600E6" : colorHash(name(d));
};
function generateHash(name) {
// Return a vector (0.0->1.0) that is a hash of the input string.
// The hash is computed to favor early characters over later ones, so
// that strings with similar starts have similar vectors. Only the first
// 6 characters are considered.
var hash = 0, weight = 1, max_hash = 0, mod = 10, max_char = 6;
if (name) {
for (var i = 0; i < name.length; i++) {
if (i > max_char) { break; }
hash += weight * (name.charCodeAt(i) % mod);
max_hash += weight * (mod - 1);
weight *= 0.70;
}
if (max_hash > 0) { hash = hash / max_hash; }
}
return hash;
}
function colorHash(name) {
// Return an rgb() color string that is a hash of the provided name,
// and with a warm palette.
var vector = 0;
if (name) {
var nameArr = name.split('` + "`" + `');
if (nameArr.length > 1) {
name = nameArr[nameArr.length -1]; // drop module name if present
}
name = name.split('(')[0]; // drop extra info
vector = generateHash(name);
}
var r = 200 + Math.round(55 * vector);
var g = 0 + Math.round(230 * (1 - vector));
var b = 0 + Math.round(55 * (1 - vector));
return "rgb(" + r + "," + g + "," + b + ")";
}
function hide(d) {
d.data.hide = true;
if(children(d)) {
children(d).forEach(hide);
}
}
function show(d) {
d.data.fade = false;
d.data.hide = false;
if(children(d)) {
children(d).forEach(show);
}
}
function getSiblings(d) {
var siblings = [];
if (d.parent) {
var me = d.parent.children.indexOf(d);
siblings = d.parent.children.slice(0);
siblings.splice(me, 1);
}
return siblings;
}
function hideSiblings(d) {
var siblings = getSiblings(d);
siblings.forEach(function(s) {
hide(s);
});
if(d.parent) {
hideSiblings(d.parent);
}
}
function fadeAncestors(d) {
if(d.parent) {
d.parent.data.fade = true;
fadeAncestors(d.parent);
}
}
function getRoot(d) {
if(d.parent) {
return getRoot(d.parent);
}
return d;
}
function zoom(d) {
tip.hide(d);
hideSiblings(d);
show(d);
fadeAncestors(d);
update();
if (typeof clickHandler === 'function') {
clickHandler(d);
}
}
function searchTree(d, term) {
var re = new RegExp(term),
searchResults = [];
function searchInner(d) {
var label = name(d);
if (children(d)) {
children(d).forEach(function (child) {
searchInner(child);
});
}
if (label.match(re)) {
d.highlight = true;
searchResults.push(d);
} else {
d.highlight = false;
}
}
searchInner(d);
return searchResults;
}
function clear(d) {
d.highlight = false;
if(children(d)) {
children(d).forEach(function(child) {
clear(child);
});
}
}
function doSort(a, b) {
if (typeof sort === 'function') {
return sort(a, b);
} else if (sort) {
return d3.ascending(name(a), name(b));
}
}
var partition = d3.partition();
function filterNodes(root) {
var nodeList = root.descendants();
if (minFrameSize > 0) {
var kx = w / (root.x1 - root.x0);
nodeList = nodeList.filter(function(el) {
return ((el.x1 - el.x0) * kx) > minFrameSize;
});
}
return nodeList;
}
function update() {
selection.each(function(root) {
var x = d3.scaleLinear().range([0, w]),
y = d3.scaleLinear().range([0, c]);
if (sort) root.sort(doSort);
root.sum(function(d) {
if (d.fade || d.hide) {
return 0;
}
// The node's self value is its total value minus all children.
var v = value(d);
if (children(d)) {
var c = children(d);
for (var i = 0; i < c.length; i++) {
v -= value(c[i]);
}
}
return v;
});
partition(root);
var kx = w / (root.x1 - root.x0);
function width(d) { return (d.x1 - d.x0) * kx; }
var descendants = filterNodes(root);
var g = d3.select(this).select("svg").selectAll("g").data(descendants, function(d) { return d.id; });
g.transition()
.duration(transitionDuration)
.ease(transitionEase)
.attr("transform", function(d) { return "translate(" + x(d.x0) + "," + (reversed ? y(d.depth) : (h - y(d.depth) - c)) + ")"; });
g.select("rect")
.attr("width", width);
var node = g.enter()
.append("svg:g")
.attr("transform", function(d) { return "translate(" + x(d.x0) + "," + (reversed ? y(d.depth) : (h - y(d.depth) - c)) + ")"; });
node.append("svg:rect")
.transition()
.delay(transitionDuration / 2)
.attr("width", width);
if (!tooltip)
node.append("svg:title");
node.append("foreignObject")
.append("xhtml:div");
// Now we have to re-select to see the new elements (why?).
g = d3.select(this).select("svg").selectAll("g").data(descendants, function(d) { return d.id; });
g.attr("width", width)
.attr("height", function(d) { return c; })
.attr("name", function(d) { return name(d); })
.attr("class", function(d) { return d.data.fade ? "frame fade" : "frame"; });
g.select("rect")
.attr("height", function(d) { return c; })
.attr("fill", function(d) { return colorMapper(d); });
if (!tooltip)
g.select("title")
.text(label);
g.select("foreignObject")
.attr("width", width)
.attr("height", function(d) { return c; })
.select("div")
.attr("class", "d3-flame-graph-label")
.style("display", function(d) { return (width(d) < 35) ? "none" : "block";})
.transition()
.delay(transitionDuration)
.text(name);
g.on('click', zoom);
g.exit()
.remove();
g.on('mouseover', function(d) {
if (tooltip) tip.show(d);
setDetails(label(d));
}).on('mouseout', function(d) {
if (tooltip) tip.hide(d);
setDetails("");
});
});
}
function merge(data, samples) {
samples.forEach(function (sample) {
var node = data.find(function (element) {
return (element.name === sample.name);
});
if (node) {
if (node.original) {
node.original += sample.value;
} else {
node.value += sample.value;
}
if (sample.children) {
if (!node.children) {
node.children = [];
}
merge(node.children, sample.children);
}
} else {
data.push(sample);
}
});
}
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
function injectIds(node) {
node.id = s4() + "-" + s4() + "-" + "-" + s4() + "-" + s4();
var children = node.c || node.children || [];
for (var i = 0; i < children.length; i++) {
injectIds(children[i]);
}
}
function chart(s) {
var root = d3.hierarchy(
s.datum(), function(d) { return children(d); }
);
injectIds(root);
selection = s.datum(root);
if (!arguments.length) return chart;
if (!h) {
h = (root.height + 2) * c;
}
selection.each(function(data) {
if (!svg) {
svg = d3.select(this)
.append("svg:svg")
.attr("width", w)
.attr("height", h)
.attr("class", "partition d3-flame-graph")
.call(tip);
svg.append("svg:text")
.attr("class", "title")
.attr("text-anchor", "middle")
.attr("y", "25")
.attr("x", w/2)
.attr("fill", "#808080")
.text(title);
}
});
// first draw
update();
}
chart.height = function (_) {
if (!arguments.length) { return h; }
h = _;
return chart;
};
chart.width = function (_) {
if (!arguments.length) { return w; }
w = _;
return chart;
};
chart.cellHeight = function (_) {
if (!arguments.length) { return c; }
c = _;
return chart;
};
chart.tooltip = function (_) {
if (!arguments.length) { return tooltip; }
if (typeof _ === "function") {
tip = _;
}
tooltip = !!_;
return chart;
};
chart.title = function (_) {
if (!arguments.length) { return title; }
title = _;
return chart;
};
chart.transitionDuration = function (_) {
if (!arguments.length) { return transitionDuration; }
transitionDuration = _;
return chart;
};
chart.transitionEase = function (_) {
if (!arguments.length) { return transitionEase; }
transitionEase = _;
return chart;
};
chart.sort = function (_) {
if (!arguments.length) { return sort; }
sort = _;
return chart;
};
chart.reversed = function (_) {
if (!arguments.length) { return reversed; }
reversed = _;
return chart;
};
chart.label = function(_) {
if (!arguments.length) { return label; }
label = _;
return chart;
};
chart.search = function(term) {
var searchResults = [];
selection.each(function(data) {
searchResults = searchTree(data, term);
update();
});
return searchResults;
};
chart.clear = function() {
selection.each(function(data) {
clear(data);
update();
});
};
chart.zoomTo = function(d) {
zoom(d);
};
chart.resetZoom = function() {
selection.each(function (data) {
zoom(data); // zoom to root
});
};
chart.onClick = function(_) {
if (!arguments.length) {
return clickHandler;
}
clickHandler = _;
return chart;
};
chart.merge = function(samples) {
var newRoot; // Need to re-create hierarchy after data changes.
selection.each(function (root) {
merge([root.data], [samples]);
newRoot = d3.hierarchy(root.data, function(d) { return children(d); });
injectIds(newRoot);
});
selection = selection.datum(newRoot);
update();
};
chart.color = function(_) {
if (!arguments.length) { return colorMapper; }
colorMapper = _;
return chart;
};
chart.minFrameSize = function (_) {
if (!arguments.length) { return minFrameSize; }
minFrameSize = _;
return chart;
};
chart.details = function (_) {
if (!arguments.length) { return details; }
details = _;
return chart;
};
return chart;
}
// Node/CommonJS exports
if (typeof(module) !== 'undefined' && typeof(exports) !== 'undefined') {
module.exports = flameGraph;
} else {
d3.flameGraph = flameGraph;
}
})();
`
// CSSSource returns the d3.flameGraph.css file
const CSSSource = `
.d3-flame-graph rect {
stroke: #EEEEEE;
fill-opacity: .8;
}
.d3-flame-graph rect:hover {
stroke: #474747;
stroke-width: 0.5;
cursor: pointer;
}
.d3-flame-graph-label {
pointer-events: none;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
font-size: 12px;
font-family: Verdana;
margin-left: 4px;
margin-right: 4px;
line-height: 1.5;
padding: 0 0 0;
font-weight: 400;
color: black;
text-align: left;
}
.d3-flame-graph .fade {
opacity: 0.6 !important;
}
.d3-flame-graph .title {
font-size: 20px;
font-family: Verdana;
}
.d3-flame-graph-tip {
line-height: 1;
font-family: Verdana;
font-size: 12px;
padding: 12px;
background: rgba(0, 0, 0, 0.8);
color: #fff;
border-radius: 2px;
pointer-events: none;
}
/* Creates a small triangle extender for the tooltip */
.d3-flame-graph-tip:after {
box-sizing: border-box;
display: inline;
font-size: 10px;
width: 100%;
line-height: 1;
color: rgba(0, 0, 0, 0.8);
position: absolute;
pointer-events: none;
}
/* Northward tooltips */
.d3-flame-graph-tip.n:after {
content: "\25BC";
margin: -1px 0 0 0;
top: 100%;
left: 0;
text-align: center;
}
/* Eastward tooltips */
.d3-flame-graph-tip.e:after {
content: "\25C0";
margin: -4px 0 0 0;
top: 50%;
left: -8px;
}
/* Southward tooltips */
.d3-flame-graph-tip.s:after {
content: "\25B2";
margin: 0 0 1px 0;
top: -8px;
left: 0;
text-align: center;
}
/* Westward tooltips */
.d3-flame-graph-tip.w:after {
content: "\25B6";
margin: -4px 0 0 -1px;
top: 50%;
left: 100%;
}
`

View file

@ -0,0 +1,8 @@
The MIT License (MIT)
Copyright (c) 2013 Justin Palmer
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.

View file

@ -0,0 +1,328 @@
// Tooltips for d3.js visualizations
// https://github.com/Caged/d3-tip
// Version 0.7.1
// See LICENSE file for license details
package d3tip
// JSSource returns the d3-tip.js file
const JSSource = `
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module with d3 as a dependency.
define(['d3'], factory)
} else if (typeof module === 'object' && module.exports) {
// CommonJS
var d3 = require('d3')
module.exports = factory(d3)
} else {
// Browser global.
root.d3.tip = factory(root.d3)
}
}(this, function (d3) {
// Public - contructs a new tooltip
//
// Returns a tip
return function() {
var direction = d3_tip_direction,
offset = d3_tip_offset,
html = d3_tip_html,
node = initNode(),
svg = null,
point = null,
target = null
function tip(vis) {
svg = getSVGNode(vis)
point = svg.createSVGPoint()
document.body.appendChild(node)
}
// Public - show the tooltip on the screen
//
// Returns a tip
tip.show = function() {
var args = Array.prototype.slice.call(arguments)
if(args[args.length - 1] instanceof SVGElement) target = args.pop()
var content = html.apply(this, args),
poffset = offset.apply(this, args),
dir = direction.apply(this, args),
nodel = getNodeEl(),
i = directions.length,
coords,
scrollTop = document.documentElement.scrollTop || document.body.scrollTop,
scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft
nodel.html(content)
.style('opacity', 1).style('pointer-events', 'all')
while(i--) nodel.classed(directions[i], false)
coords = direction_callbacks.get(dir).apply(this)
nodel.classed(dir, true)
.style('top', (coords.top + poffset[0]) + scrollTop + 'px')
.style('left', (coords.left + poffset[1]) + scrollLeft + 'px')
return tip;
};
// Public - hide the tooltip
//
// Returns a tip
tip.hide = function() {
var nodel = getNodeEl()
nodel.style('opacity', 0).style('pointer-events', 'none')
return tip
}
// Public: Proxy attr calls to the d3 tip container. Sets or gets attribute value.
//
// n - name of the attribute
// v - value of the attribute
//
// Returns tip or attribute value
tip.attr = function(n, v) {
if (arguments.length < 2 && typeof n === 'string') {
return getNodeEl().attr(n)
} else {
var args = Array.prototype.slice.call(arguments)
d3.selection.prototype.attr.apply(getNodeEl(), args)
}
return tip
}
// Public: Proxy style calls to the d3 tip container. Sets or gets a style value.
//
// n - name of the property
// v - value of the property
//
// Returns tip or style property value
tip.style = function(n, v) {
if (arguments.length < 2 && typeof n === 'string') {
return getNodeEl().style(n)
} else {
var args = Array.prototype.slice.call(arguments)
d3.selection.prototype.style.apply(getNodeEl(), args)
}
return tip
}
// Public: Set or get the direction of the tooltip
//
// v - One of n(north), s(south), e(east), or w(west), nw(northwest),
// sw(southwest), ne(northeast) or se(southeast)
//
// Returns tip or direction
tip.direction = function(v) {
if (!arguments.length) return direction
direction = v == null ? v : functor(v)
return tip
}
// Public: Sets or gets the offset of the tip
//
// v - Array of [x, y] offset
//
// Returns offset or
tip.offset = function(v) {
if (!arguments.length) return offset
offset = v == null ? v : functor(v)
return tip
}
// Public: sets or gets the html value of the tooltip
//
// v - String value of the tip
//
// Returns html value or tip
tip.html = function(v) {
if (!arguments.length) return html
html = v == null ? v : functor(v)
return tip
}
// Public: destroys the tooltip and removes it from the DOM
//
// Returns a tip
tip.destroy = function() {
if(node) {
getNodeEl().remove();
node = null;
}
return tip;
}
function d3_tip_direction() { return 'n' }
function d3_tip_offset() { return [0, 0] }
function d3_tip_html() { return ' ' }
var direction_callbacks = d3.map({
n: direction_n,
s: direction_s,
e: direction_e,
w: direction_w,
nw: direction_nw,
ne: direction_ne,
sw: direction_sw,
se: direction_se
}),
directions = direction_callbacks.keys()
function direction_n() {
var bbox = getScreenBBox()
return {
top: bbox.n.y - node.offsetHeight,
left: bbox.n.x - node.offsetWidth / 2
}
}
function direction_s() {
var bbox = getScreenBBox()
return {
top: bbox.s.y,
left: bbox.s.x - node.offsetWidth / 2
}
}
function direction_e() {
var bbox = getScreenBBox()
return {
top: bbox.e.y - node.offsetHeight / 2,
left: bbox.e.x
}
}
function direction_w() {
var bbox = getScreenBBox()
return {
top: bbox.w.y - node.offsetHeight / 2,
left: bbox.w.x - node.offsetWidth
}
}
function direction_nw() {
var bbox = getScreenBBox()
return {
top: bbox.nw.y - node.offsetHeight,
left: bbox.nw.x - node.offsetWidth
}
}
function direction_ne() {
var bbox = getScreenBBox()
return {
top: bbox.ne.y - node.offsetHeight,
left: bbox.ne.x
}
}
function direction_sw() {
var bbox = getScreenBBox()
return {
top: bbox.sw.y,
left: bbox.sw.x - node.offsetWidth
}
}
function direction_se() {
var bbox = getScreenBBox()
return {
top: bbox.se.y,
left: bbox.e.x
}
}
function initNode() {
var node = d3.select(document.createElement('div'));
node.style('position', 'absolute').style('top', 0).style('opacity', 0)
.style('pointer-events', 'none').style('box-sizing', 'border-box')
return node.node()
}
function getSVGNode(el) {
el = el.node()
if(el.tagName.toLowerCase() === 'svg')
return el
return el.ownerSVGElement
}
function getNodeEl() {
if(node === null) {
node = initNode();
// re-add node to DOM
document.body.appendChild(node);
};
return d3.select(node);
}
// Private - gets the screen coordinates of a shape
//
// Given a shape on the screen, will return an SVGPoint for the directions
// n(north), s(south), e(east), w(west), ne(northeast), se(southeast), nw(northwest),
// sw(southwest).
//
// +-+-+
// | |
// + +
// | |
// +-+-+
//
// Returns an Object {n, s, e, w, nw, sw, ne, se}
function getScreenBBox() {
var targetel = target || d3.event.target;
while ('undefined' === typeof targetel.getScreenCTM && 'undefined' === targetel.parentNode) {
targetel = targetel.parentNode;
}
var bbox = {},
matrix = targetel.getScreenCTM(),
tbbox = targetel.getBBox(),
width = tbbox.width,
height = tbbox.height,
x = tbbox.x,
y = tbbox.y
point.x = x
point.y = y
bbox.nw = point.matrixTransform(matrix)
point.x += width
bbox.ne = point.matrixTransform(matrix)
point.y += height
bbox.se = point.matrixTransform(matrix)
point.x -= width
bbox.sw = point.matrixTransform(matrix)
point.y -= height / 2
bbox.w = point.matrixTransform(matrix)
point.x += width
bbox.e = point.matrixTransform(matrix)
point.x -= width / 2
point.y -= height / 2
bbox.n = point.matrixTransform(matrix)
point.y += height
bbox.s = point.matrixTransform(matrix)
return bbox
}
// Private - replace D3JS 3.X d3.functor() function
function functor(v) {
return typeof v === "function" ? v : function() {
return v
}
}
return tip
};
}));
`

View file

@ -0,0 +1,27 @@
Copyright 2009-2017 Andrea Leofreddi <a.leofreddi@vleo.net>. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those of the
authors and should not be interpreted as representing official policies, either expressed
or implied, of Andrea Leofreddi.

View file

@ -1,17 +1,19 @@
// SVG pan and zoom library.
// See copyright notice in string constant below.
package svg
package svgpan
// https://www.cyberz.org/projects/SVGPan/SVGPan.js
// https://github.com/aleofreddi/svgpan
const svgPanJS = `
/**
* SVGPan library 1.2.1
// JSSource returns the svgpan.js file
const JSSource = `
/**
* SVGPan library 1.2.2
* ======================
*
* Given an unique existing element with id "viewport" (or when missing, the first g
* element), including the the library into any SVG adds the following capabilities:
* Given an unique existing element with id "viewport" (or when missing, the
* first g-element), including the the library into any SVG adds the following
* capabilities:
*
* - Mouse panning
* - Mouse zooming (using the wheel)
@ -26,6 +28,10 @@ const svgPanJS = `
*
* Releases:
*
* 1.2.2, Tue Aug 30 17:21:56 CEST 2011, Andrea Leofreddi
* - Fixed viewBox on root tag (#7)
* - Improved zoom speed (#2)
*
* 1.2.1, Mon Jul 4 00:33:18 CEST 2011, Andrea Leofreddi
* - Fixed a regression with mouse wheel (now working on Firefox 5)
* - Working with viewBox attribute (#4)
@ -43,28 +49,30 @@ const svgPanJS = `
*
* This code is licensed under the following BSD license:
*
* Copyright 2009-2010 Andrea Leofreddi <a.leofreddi@itcharm.com>. All rights reserved.
*
* Copyright 2009-2017 Andrea Leofreddi <a.leofreddi@vleo.net>. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY Andrea Leofreddi ` + "``AS IS''" + ` AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Andrea Leofreddi OR
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of Andrea Leofreddi.
@ -72,19 +80,20 @@ const svgPanJS = `
"use strict";
/// CONFIGURATION
/// CONFIGURATION
/// ====>
var enablePan = 1; // 1 or 0: enable or disable panning (default enabled)
var enableZoom = 1; // 1 or 0: enable or disable zooming (default enabled)
var enableDrag = 0; // 1 or 0: enable or disable dragging (default disabled)
var zoomScale = 0.2; // Zoom sensitivity
/// <====
/// END OF CONFIGURATION
/// END OF CONFIGURATION
var root = document.documentElement;
var state = 'none', svgRoot, stateTarget, stateOrigin, stateTf;
var state = 'none', svgRoot = null, stateTarget, stateOrigin, stateTf;
setupHandlers(root);
@ -109,22 +118,20 @@ function setupHandlers(root){
* Retrieves the root element for SVG manipulation. The element is then cached into the svgRoot global variable.
*/
function getRoot(root) {
if(typeof(svgRoot) == "undefined") {
var g = null;
if(svgRoot == null) {
var r = root.getElementById("viewport") ? root.getElementById("viewport") : root.documentElement, t = r;
g = root.getElementById("viewport");
while(t != root) {
if(t.getAttribute("viewBox")) {
setCTM(r, t.getCTM());
if(g == null)
g = root.getElementsByTagName('g')[0];
t.removeAttribute("viewBox");
}
if(g == null)
alert('Unable to obtain SVG root element');
t = t.parentNode;
}
setCTM(g, g.getCTM());
g.removeAttribute("viewBox");
svgRoot = g;
svgRoot = r;
}
return svgRoot;
@ -185,11 +192,11 @@ function handleMouseWheel(evt) {
var delta;
if(evt.wheelDelta)
delta = evt.wheelDelta / 3600; // Chrome/Safari
delta = evt.wheelDelta / 360; // Chrome/Safari
else
delta = evt.detail / -90; // Mozilla
delta = evt.detail / -9; // Mozilla
var z = 1 + delta; // Zoom factor: 0.9/1.1
var z = Math.pow(1 + zoomScale, delta);
var g = getRoot(svgDoc);
@ -250,8 +257,8 @@ function handleMouseDown(evt) {
var g = getRoot(svgDoc);
if(
evt.target.tagName == "svg"
|| !enableDrag // Pan anyway when drag is disabled and the user clicked on an element
evt.target.tagName == "svg"
|| !enableDrag // Pan anyway when drag is disabled and the user clicked on an element
) {
// Pan mode
state = 'pan';
@ -287,5 +294,4 @@ function handleMouseUp(evt) {
state = '';
}
}
`