Skip to content

Commit 86ab09e

Browse files
committed
runtime/pprof: generate heap profiles in compressed proto format
When debug is 0, emit the compressed proto format. The debug>0 format stays the same. Updates #16093 Change-Id: I45aa1874a22d34cf44dd4aa78bbff9302381cb34 Reviewed-on: https://go-review.googlesource.com/33422 Run-TryBot: Michael Matloob <[email protected]> Reviewed-by: Russ Cox <[email protected]> TryBot-Result: Gobot Gobot <[email protected]>
1 parent f88a33a commit 86ab09e

File tree

3 files changed

+194
-12
lines changed

3 files changed

+194
-12
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
// Copyright 2016 The Go Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
5+
package protopprof
6+
7+
import (
8+
"internal/pprof/profile"
9+
"math"
10+
"runtime"
11+
"time"
12+
)
13+
14+
// EncodeMemProfile converts MemProfileRecords to a Profile.
15+
func EncodeMemProfile(mr []runtime.MemProfileRecord, rate int64, t time.Time) *profile.Profile {
16+
p := &profile.Profile{
17+
Period: rate,
18+
PeriodType: &profile.ValueType{Type: "space", Unit: "bytes"},
19+
SampleType: []*profile.ValueType{
20+
{Type: "alloc_objects", Unit: "count"},
21+
{Type: "alloc_space", Unit: "bytes"},
22+
{Type: "inuse_objects", Unit: "count"},
23+
{Type: "inuse_space", Unit: "bytes"},
24+
},
25+
TimeNanos: int64(t.UnixNano()),
26+
}
27+
28+
locs := make(map[uintptr]*profile.Location)
29+
for _, r := range mr {
30+
stack := r.Stack()
31+
sloc := make([]*profile.Location, len(stack))
32+
for i, addr := range stack {
33+
loc := locs[addr]
34+
if loc == nil {
35+
loc = &profile.Location{
36+
ID: uint64(len(p.Location) + 1),
37+
Address: uint64(addr),
38+
}
39+
locs[addr] = loc
40+
p.Location = append(p.Location, loc)
41+
}
42+
sloc[i] = loc
43+
}
44+
45+
ao, ab := scaleHeapSample(r.AllocObjects, r.AllocBytes, rate)
46+
uo, ub := scaleHeapSample(r.InUseObjects(), r.InUseBytes(), rate)
47+
48+
p.Sample = append(p.Sample, &profile.Sample{
49+
Value: []int64{ao, ab, uo, ub},
50+
Location: sloc,
51+
})
52+
}
53+
if runtime.GOOS == "linux" {
54+
addMappings(p)
55+
}
56+
return p
57+
}
58+
59+
// scaleHeapSample adjusts the data from a heap Sample to
60+
// account for its probability of appearing in the collected
61+
// data. heap profiles are a sampling of the memory allocations
62+
// requests in a program. We estimate the unsampled value by dividing
63+
// each collected sample by its probability of appearing in the
64+
// profile. heap profiles rely on a poisson process to determine
65+
// which samples to collect, based on the desired average collection
66+
// rate R. The probability of a sample of size S to appear in that
67+
// profile is 1-exp(-S/R).
68+
func scaleHeapSample(count, size, rate int64) (int64, int64) {
69+
if count == 0 || size == 0 {
70+
return 0, 0
71+
}
72+
73+
if rate <= 1 {
74+
// if rate==1 all samples were collected so no adjustment is needed.
75+
// if rate<1 treat as unknown and skip scaling.
76+
return count, size
77+
}
78+
79+
avgSize := float64(size) / float64(count)
80+
scale := 1 / (1 - math.Exp(-avgSize/float64(rate)))
81+
82+
return int64(float64(count) * scale), int64(float64(size) * scale)
83+
}
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
// Copyright 2016 The Go Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
5+
package protopprof
6+
7+
import (
8+
"bytes"
9+
"internal/pprof/profile"
10+
"io/ioutil"
11+
"reflect"
12+
"runtime"
13+
"testing"
14+
"time"
15+
)
16+
17+
// TestSampledHeapAllocProfile tests encoding of a memory profile from
18+
// runtime.MemProfileRecord data.
19+
func TestSampledHeapAllocProfile(t *testing.T) {
20+
if runtime.GOOS != "linux" {
21+
t.Skip("Test requires a system with /proc/self/maps")
22+
}
23+
24+
// Figure out two addresses from /proc/self/maps.
25+
mmap, err := ioutil.ReadFile("/proc/self/maps")
26+
if err != nil {
27+
t.Fatal("Cannot read /proc/self/maps")
28+
}
29+
rd := bytes.NewReader(mmap)
30+
mprof := &profile.Profile{}
31+
if err = mprof.ParseMemoryMap(rd); err != nil {
32+
t.Fatalf("Cannot parse /proc/self/maps")
33+
}
34+
if len(mprof.Mapping) < 2 {
35+
t.Fatalf("Less than two mappings")
36+
}
37+
address1 := mprof.Mapping[0].Start
38+
address2 := mprof.Mapping[1].Start
39+
40+
var buf bytes.Buffer
41+
42+
rec, rate := testMemRecords(address1, address2)
43+
p := EncodeMemProfile(rec, rate, time.Now())
44+
if err := p.Write(&buf); err != nil {
45+
t.Fatalf("Failed to write profile: %v", err)
46+
}
47+
48+
p, err = profile.Parse(&buf)
49+
if err != nil {
50+
t.Fatalf("Could not parse Profile profile: %v", err)
51+
}
52+
53+
// Expected PeriodType, SampleType and Sample.
54+
expectedPeriodType := &profile.ValueType{Type: "space", Unit: "bytes"}
55+
expectedSampleType := []*profile.ValueType{
56+
{Type: "alloc_objects", Unit: "count"},
57+
{Type: "alloc_space", Unit: "bytes"},
58+
{Type: "inuse_objects", Unit: "count"},
59+
{Type: "inuse_space", Unit: "bytes"},
60+
}
61+
// Expected samples, with values unsampled according to the profiling rate.
62+
expectedSample := []*profile.Sample{
63+
{Value: []int64{2050, 2099200, 1537, 1574400}, Location: []*profile.Location{
64+
{ID: 1, Mapping: mprof.Mapping[0], Address: address1},
65+
{ID: 2, Mapping: mprof.Mapping[1], Address: address2},
66+
}},
67+
{Value: []int64{1, 829411, 1, 829411}, Location: []*profile.Location{
68+
{ID: 3, Mapping: mprof.Mapping[1], Address: address2 + 1},
69+
{ID: 4, Mapping: mprof.Mapping[1], Address: address2 + 2},
70+
}},
71+
{Value: []int64{1, 829411, 0, 0}, Location: []*profile.Location{
72+
{ID: 5, Mapping: mprof.Mapping[0], Address: address1 + 1},
73+
{ID: 6, Mapping: mprof.Mapping[0], Address: address1 + 2},
74+
{ID: 7, Mapping: mprof.Mapping[1], Address: address2 + 3},
75+
}},
76+
}
77+
78+
if p.Period != 512*1024 {
79+
t.Fatalf("Sampling periods do not match")
80+
}
81+
if !reflect.DeepEqual(p.PeriodType, expectedPeriodType) {
82+
t.Fatalf("Period types do not match")
83+
}
84+
if !reflect.DeepEqual(p.SampleType, expectedSampleType) {
85+
t.Fatalf("Sample types do not match")
86+
}
87+
if !reflect.DeepEqual(p.Sample, expectedSample) {
88+
t.Fatalf("Samples do not match: Expected: %v, Got:%v", getSampleAsString(expectedSample),
89+
getSampleAsString(p.Sample))
90+
}
91+
}
92+
93+
func testMemRecords(a1, a2 uint64) ([]runtime.MemProfileRecord, int64) {
94+
addr1, addr2 := uintptr(a1), uintptr(a2)
95+
rate := int64(512 * 1024)
96+
rec := []runtime.MemProfileRecord{
97+
{4096, 1024, 4, 1, [32]uintptr{addr1, addr2}},
98+
{512 * 1024, 0, 1, 0, [32]uintptr{addr2 + 1, addr2 + 2}},
99+
{512 * 1024, 512 * 1024, 1, 1, [32]uintptr{addr1 + 1, addr1 + 2, addr2 + 3}},
100+
}
101+
return rec, rate
102+
}

src/runtime/pprof/pprof.go

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -485,15 +485,16 @@ func writeHeap(w io.Writer, debug int) error {
485485
// Profile grew; try again.
486486
}
487487

488+
if debug == 0 {
489+
pp := protopprof.EncodeMemProfile(p, int64(runtime.MemProfileRate), time.Now())
490+
return pp.Write(w)
491+
}
492+
488493
sort.Slice(p, func(i, j int) bool { return p[i].InUseBytes() > p[j].InUseBytes() })
489494

490495
b := bufio.NewWriter(w)
491-
var tw *tabwriter.Writer
492-
w = b
493-
if debug > 0 {
494-
tw = tabwriter.NewWriter(w, 1, 8, 1, '\t', 0)
495-
w = tw
496-
}
496+
tw := tabwriter.NewWriter(b, 1, 8, 1, '\t', 0)
497+
w = tw
497498

498499
var total runtime.MemProfileRecord
499500
for i := range p {
@@ -521,9 +522,7 @@ func writeHeap(w io.Writer, debug int) error {
521522
fmt.Fprintf(w, " %#x", pc)
522523
}
523524
fmt.Fprintf(w, "\n")
524-
if debug > 0 {
525-
printStackRecord(w, r.Stack(), false)
526-
}
525+
printStackRecord(w, r.Stack(), false)
527526
}
528527

529528
// Print memstats information too.
@@ -557,9 +556,7 @@ func writeHeap(w io.Writer, debug int) error {
557556
fmt.Fprintf(w, "# NumGC = %d\n", s.NumGC)
558557
fmt.Fprintf(w, "# DebugGC = %v\n", s.DebugGC)
559558

560-
if tw != nil {
561-
tw.Flush()
562-
}
559+
tw.Flush()
563560
return b.Flush()
564561
}
565562

0 commit comments

Comments
 (0)