forked from uber-archive/go-torch
/
parser.go
282 lines (243 loc) · 7.12 KB
/
parser.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package pprof
import (
"bufio"
"bytes"
"fmt"
"io"
"regexp"
"strconv"
"strings"
"github.com/uber/go-torch/stack"
)
type readState int
const (
ignore readState = iota
samplesHeader
samples
locations
mappings
)
// funcID is the ID of a given Location in the pprof raw output.
type funcID int
type rawParser struct {
// err is the first error encountered by the parser.
err error
state readState
funcNames map[funcID]string
sampleNames []string
records []*stackRecord
}
// ParseRaw parses the raw pprof output and returns call stacks.
func ParseRaw(input []byte) (*stack.Profile, error) {
parser := newRawParser()
if err := parser.parse(input); err != nil {
return nil, err
}
return parser.toProfile()
}
func newRawParser() *rawParser {
return &rawParser{
funcNames: make(map[funcID]string),
}
}
func (p *rawParser) parse(input []byte) error {
reader := bufio.NewReader(bytes.NewReader(input))
for {
line, err := reader.ReadString('\n')
if err != nil {
if err == io.EOF {
if p.state < locations {
p.setError(fmt.Errorf("parser ended before processing locations, state: %v", p.state))
}
break
}
return err
}
p.processLine(strings.TrimSpace(line))
}
return p.err
}
func (p *rawParser) setError(err error) {
if p.err != nil {
return
}
p.err = err
}
func (p *rawParser) processLine(line string) {
switch p.state {
case ignore:
if strings.HasPrefix(line, "Samples") {
p.state = samplesHeader
return
}
case samplesHeader:
p.sampleNames = strings.Split(line, " ")
p.state = samples
case samples:
if strings.HasPrefix(line, "Locations") {
p.state = locations
return
}
p.addSample(line)
case locations:
if strings.HasPrefix(line, "Mappings") {
p.state = mappings
return
}
p.addLocation(line)
case mappings:
// Nothing to process.
}
}
// toProfile aggregates stack sample counts and returns a profile with unique stack samples.
func (p *rawParser) toProfile() (*stack.Profile, error) {
profile, err := stack.NewProfile(p.sampleNames)
if err != nil {
return nil, err
}
samples := make(map[string]*stack.Sample)
for _, r := range p.records {
funcNames := r.funcNames(p.funcNames)
funcKey := strings.Join(funcNames, ";")
if sample, ok := samples[funcKey]; ok {
if err := sample.Add(r.samples); err != nil {
return nil, err
}
continue
}
samples[funcKey] = stack.NewSample(funcNames, r.samples)
}
profile.Samples = make([]*stack.Sample, 0, len(samples))
for _, s := range samples {
profile.Samples = append(profile.Samples, s)
}
return profile, nil
}
// addLocation parses a location that looks like:
// 292: 0x49dee1 github.com/uber/tchannel/golang.(*Frame).ReadIn :0 s=0
// and creates a mapping from funcID to function name.
func (p *rawParser) addLocation(line string) {
parts := splitBySpace(line)
if len(parts) < 4 {
switch {
case len(parts) == 2:
// Some lines just have an ID and an address, we can ignore those.
case len(parts) == 3 && strings.HasPrefix(parts[2], "M="):
// Some lines have an ID, a mapping ID and an address, we can
// ignore those as well.
case len(parts) == 3 && strings.HasPrefix(parts[2], "s="):
// See https://github.com/uber/go-torch/issues/63#issuecomment-315658039.
// The raw "format" sometimes prints multiple lines per location. We can't
// see previous lines here, so for now we just skip them.
default:
p.setError(fmt.Errorf("malformed location line: %v", line))
}
return
}
funcID := p.toFuncID(strings.TrimSuffix(parts[0], ":"))
if strings.HasPrefix(parts[2], "M=") {
p.funcNames[funcID] = parts[3]
} else {
p.funcNames[funcID] = parts[2]
}
}
type stackRecord struct {
samples []int64
stack []funcID
}
// addSample parses a sample that looks like:
// 1 10000000: 1 2 3 4
// and creates a stackRecord for it.
func (p *rawParser) addSample(line string) {
if strings.Contains(line, "bytes:[") {
// Memory profiles have a line of bytes:[size1] which contains the size
// of the object. Skip these lines as we do not use it currently.
return
}
// Split by ":" which separates the data from the function IDs.
lineParts := strings.Split(line, ":")
if len(lineParts) != 2 {
p.setError(fmt.Errorf("malformed sample line: %v", line))
return
}
samples := p.parseInts(lineParts[0])
funcIDs := p.parseFuncIDs(lineParts[1])
if len(samples) != len(p.sampleNames) {
p.setError(fmt.Errorf("line has a different sample count (%v) than sample names (%v): %v",
len(samples), len(p.sampleNames), line))
return
}
p.records = append(p.records, &stackRecord{
samples: samples,
stack: funcIDs,
})
}
func getFunctionName(funcNames map[funcID]string, funcID funcID) string {
if funcName, ok := funcNames[funcID]; ok {
return funcName
}
return fmt.Sprintf("missing-function-%v", funcID)
}
// funcNames returns the function names for this stack sample.
// It returns in parent first order.
func (r *stackRecord) funcNames(funcNames map[funcID]string) []string {
var names []string
for i := len(r.stack) - 1; i >= 0; i-- {
funcID := r.stack[i]
names = append(names, getFunctionName(funcNames, funcID))
}
return names
}
func (p *rawParser) parseFuncIDs(s string) []funcID {
funcInts := p.parseInts(s)
funcIDs := make([]funcID, len(funcInts))
for i, fID := range funcInts {
funcIDs[i] = funcID(fID)
}
return funcIDs
}
func (p *rawParser) parseInts(s string) []int64 {
ss := splitBySpace(s)
samples := make([]int64, len(ss))
for i, s := range ss {
samples[i] = p.parseInt(s)
}
return samples
}
// parseInt converts a string to an int64. It stores any errors using setError.
func (p *rawParser) parseInt(s string) int64 {
v, err := strconv.ParseInt(s, 10, 64)
if err != nil {
p.setError(err)
return 0
}
return v
}
// toFuncID converts a string like "8" to a funcID.
func (p *rawParser) toFuncID(s string) funcID {
return funcID(p.parseInt(s))
}
var spaceSplitter = regexp.MustCompile(`\s+`)
// splitBySpace splits values separated by 1 or more spaces.
func splitBySpace(s string) []string {
return spaceSplitter.Split(strings.TrimSpace(s), -1)
}