-
Notifications
You must be signed in to change notification settings - Fork 66
/
profiler.go
545 lines (469 loc) · 14.3 KB
/
profiler.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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
// Copyright 2021 The Parca Authors
// 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 profiler
import (
"bytes"
"context"
_ "embed"
"encoding/binary"
"fmt"
"io"
"os"
"runtime"
"strings"
"sync"
"time"
"unsafe"
"C" //nolint:typecheck
bpf "github.com/aquasecurity/libbpfgo"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/google/pprof/profile"
profilestorepb "github.com/parca-dev/parca/gen/proto/go/parca/profilestore/v1alpha1"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/common/model"
"golang.org/x/sys/unix"
"github.com/parca-dev/parca-agent/pkg/agent"
"github.com/parca-dev/parca-agent/pkg/byteorder"
"github.com/parca-dev/parca-agent/pkg/debuginfo"
"github.com/parca-dev/parca-agent/pkg/ksym"
"github.com/parca-dev/parca-agent/pkg/maps"
"github.com/parca-dev/parca-agent/pkg/perf"
)
//go:embed parca-agent.bpf.o
var bpfObj []byte
const (
stackDepth = 127 // Always needs to be sync with MAX_STACK_DEPTH in parca-agent.bpf.c
doubleStackDepth = 254
)
type CgroupProfiler struct {
logger log.Logger
missingStacks *prometheus.CounterVec
ksymCache *ksym.Cache
target model.LabelSet
profilingDuration time.Duration
cancel func()
pidMappingFileCache *maps.PidMappingFileCache
writeClient profilestorepb.ProfileStoreServiceClient
debugInfoExtractor *debuginfo.Extractor
mtx *sync.RWMutex
lastProfileTakenAt time.Time
lastError error
perfCache *perf.Cache
}
func NewCgroupProfiler(
logger log.Logger,
reg prometheus.Registerer,
ksymCache *ksym.Cache,
writeClient profilestorepb.ProfileStoreServiceClient,
debugInfoClient debuginfo.Client,
target model.LabelSet,
profilingDuration time.Duration,
tmp string,
) *CgroupProfiler {
return &CgroupProfiler{
logger: log.With(logger, "labels", target.String()),
ksymCache: ksymCache,
target: target,
profilingDuration: profilingDuration,
pidMappingFileCache: maps.NewPidMappingFileCache(logger),
perfCache: perf.NewPerfCache(logger),
writeClient: writeClient,
debugInfoExtractor: debuginfo.NewExtractor(
log.With(logger, "component", "debuginfoextractor"),
debugInfoClient,
tmp,
),
mtx: &sync.RWMutex{},
missingStacks: promauto.With(reg).NewCounterVec(
prometheus.CounterOpts{
Name: "parca_agent_profiler_missing_stacks_total",
Help: "Number of missing profile stacks",
ConstLabels: map[string]string{"target": target.String()},
},
[]string{"type"}),
}
}
func (p *CgroupProfiler) loopReport(lastProfileTakenAt time.Time, lastError error) {
p.mtx.Lock()
defer p.mtx.Unlock()
p.lastProfileTakenAt = lastProfileTakenAt
p.lastError = lastError
}
func (p *CgroupProfiler) LastProfileTakenAt() time.Time {
p.mtx.RLock()
defer p.mtx.RUnlock()
return p.lastProfileTakenAt
}
func (p *CgroupProfiler) LastError() error {
p.mtx.RLock()
defer p.mtx.RUnlock()
return p.lastError
}
func (p *CgroupProfiler) Stop() {
p.mtx.Lock()
defer p.mtx.Unlock()
level.Debug(p.logger).Log("msg", "stopping cgroup profiler")
if p.cancel != nil {
p.cancel()
}
}
func (p *CgroupProfiler) Labels() model.LabelSet {
labels := model.LabelSet{
"__name__": "parca_agent_cpu",
}
for labelname, labelvalue := range p.target {
if !strings.HasPrefix(string(labelname), "__") {
labels[labelname] = labelvalue
}
}
return labels
}
func (p *CgroupProfiler) Run(ctx context.Context) error {
level.Debug(p.logger).Log("msg", "starting cgroup profiler")
p.mtx.Lock()
ctx, p.cancel = context.WithCancel(ctx)
p.mtx.Unlock()
m, err := bpf.NewModuleFromBufferArgs(bpf.NewModuleArgs{
BPFObjBuff: bpfObj,
BPFObjName: "parca",
})
if err != nil {
return fmt.Errorf("new bpf module: %w", err)
}
defer m.Close()
err = m.BPFLoadObject()
if err != nil {
return fmt.Errorf("load bpf object: %w", err)
}
cgroup, err := os.Open(string(p.target[agent.CgroupPathLabelName]))
if err != nil {
return fmt.Errorf("open cgroup: %w", err)
}
defer cgroup.Close()
cpus := runtime.NumCPU()
for i := 0; i < cpus; i++ {
// TODO(branz): Close the returned fd
fd, err := unix.PerfEventOpen(&unix.PerfEventAttr{
Type: unix.PERF_TYPE_SOFTWARE,
Config: unix.PERF_COUNT_SW_CPU_CLOCK,
Size: uint32(unsafe.Sizeof(unix.PerfEventAttr{})),
Sample: 100,
Bits: unix.PerfBitDisabled | unix.PerfBitFreq,
}, int(cgroup.Fd()), i, -1, unix.PERF_FLAG_PID_CGROUP)
if err != nil {
return fmt.Errorf("open perf event: %w", err)
}
prog, err := m.GetProgram("do_sample")
if err != nil {
return fmt.Errorf("get bpf program: %w", err)
}
// Because this is fd based, even if our program crashes or is ended
// without proper shutdown, things get cleaned up appropriately.
// TODO(brancz): destroy the returned link via bpf_link__destroy
_, err = prog.AttachPerfEvent(fd)
if err != nil {
return fmt.Errorf("attach perf event: %w", err)
}
}
counts, err := m.GetMap("counts")
if err != nil {
return fmt.Errorf("get counts map: %w", err)
}
stackTraces, err := m.GetMap("stack_traces")
if err != nil {
return fmt.Errorf("get stack traces map: %w", err)
}
ticker := time.NewTicker(p.profilingDuration)
defer ticker.Stop()
level.Debug(p.logger).Log("msg", "start profiling loop")
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
}
t := time.Now()
err := p.profileLoop(ctx, t, counts, stackTraces)
if err != nil {
level.Debug(p.logger).Log("msg", "profile loop error", "err", err)
}
p.loopReport(t, err)
}
}
func (p *CgroupProfiler) profileLoop(ctx context.Context, now time.Time, counts, stackTraces *bpf.BPFMap) error {
prof := &profile.Profile{
SampleType: []*profile.ValueType{{
Type: "samples",
Unit: "count",
}},
TimeNanos: now.UnixNano(),
DurationNanos: int64(p.profilingDuration),
// We sample at 100Hz, which is every 10 Million nanoseconds.
PeriodType: &profile.ValueType{
Type: "cpu",
Unit: "nanoseconds",
},
Period: 10000000,
}
mapping := maps.NewMapping(p.pidMappingFileCache)
kernelMapping := &profile.Mapping{
File: "[kernel.kallsyms]",
}
kernelFunctions := map[uint64]*profile.Function{}
userFunctions := map[[2]uint64]*profile.Function{}
// 2 uint64 1 for PID and 1 for Addr
locations := []*profile.Location{}
kernelLocations := []*profile.Location{}
kernelAddresses := map[uint64]struct{}{}
locationIndices := map[[2]uint64]int{}
samples := map[[doubleStackDepth]uint64]*profile.Sample{}
// TODO(brancz): What was this for?
// has_collision := false
it := counts.Iterator()
byteOrder := byteorder.GetHostByteOrder()
// TODO(brancz): Use libbpf batch functions.
for it.Next() {
// This byte slice is only valid for this iteration, so it must be
// copied if we want to do anything with it outside of this loop.
keyBytes := it.Key()
r := bytes.NewBuffer(keyBytes)
pidBytes := make([]byte, 4)
if _, err := io.ReadFull(r, pidBytes); err != nil {
return fmt.Errorf("read pid bytes: %w", err)
}
pid := byteOrder.Uint32(pidBytes)
userStackIDBytes := make([]byte, 4)
if _, err := io.ReadFull(r, userStackIDBytes); err != nil {
return fmt.Errorf("read user stack ID bytes: %w", err)
}
userStackID := int32(byteOrder.Uint32(userStackIDBytes))
kernelStackIDBytes := make([]byte, 4)
if _, err := io.ReadFull(r, kernelStackIDBytes); err != nil {
return fmt.Errorf("read kernel stack ID bytes: %w", err)
}
kernelStackID := int32(byteOrder.Uint32(kernelStackIDBytes))
valueBytes, err := counts.GetValue(unsafe.Pointer(&keyBytes[0]))
if err != nil {
return fmt.Errorf("get count value: %w", err)
}
value := byteOrder.Uint64(valueBytes)
stackBytes, err := stackTraces.GetValue(unsafe.Pointer(&userStackID))
if err != nil {
p.missingStacks.WithLabelValues("user").Inc()
continue
}
// Twice the stack depth because we have a user and a potential Kernel stack.
stack := [doubleStackDepth]uint64{}
err = binary.Read(bytes.NewBuffer(stackBytes), byteOrder, stack[:stackDepth])
if err != nil {
return fmt.Errorf("read user stack trace: %w", err)
}
if kernelStackID >= 0 {
stackBytes, err = stackTraces.GetValue(unsafe.Pointer(&kernelStackID))
if err != nil {
p.missingStacks.WithLabelValues("kernel").Inc()
continue
}
err = binary.Read(bytes.NewBuffer(stackBytes), byteOrder, stack[stackDepth:])
if err != nil {
return fmt.Errorf("read kernel stack trace: %w", err)
}
}
sample, ok := samples[stack]
if ok {
// We already have a sample with this stack trace, so just add
// it to the previous one.
sample.Value[0] += int64(value)
continue
}
sampleLocations := []*profile.Location{}
// Kernel stack
for _, addr := range stack[stackDepth:] {
if addr != uint64(0) {
key := [2]uint64{0, addr}
// PID 0 not possible so we'll use it to identify the kernel.
locationIndex, ok := locationIndices[key]
if !ok {
locationIndex = len(locations)
l := &profile.Location{
ID: uint64(locationIndex + 1),
Address: addr,
Mapping: kernelMapping,
}
locations = append(locations, l)
kernelLocations = append(kernelLocations, l)
kernelAddresses[addr] = struct{}{}
locationIndices[key] = locationIndex
}
sampleLocations = append(sampleLocations, locations[locationIndex])
}
}
// User stack
perfMap, err := p.perfCache.CacheForPid(pid)
if err != nil {
// We expect only a minority of processes to have a JIT and produce
// the perf map.
level.Debug(p.logger).Log("msg", "no perfmap", "err", err)
}
for _, addr := range stack[:stackDepth] {
if addr != uint64(0) {
key := [2]uint64{uint64(pid), addr}
locationIndex, ok := locationIndices[key]
if !ok {
locationIndex = len(locations)
m, err := mapping.PidAddrMapping(pid, addr)
if err != nil {
level.Debug(p.logger).Log("msg", "failed to get mapping", "err", err)
}
l := &profile.Location{
ID: uint64(locationIndex + 1),
Address: addr,
Mapping: m,
}
// Does this addr point to JITed code?
if perfMap != nil {
// TODO(zecke): Log errors other than perf.ErrNoSymbolFound
jitFunction, ok := userFunctions[key]
if !ok {
if sym, err := perfMap.Lookup(addr); err == nil {
jitFunction = &profile.Function{Name: sym}
userFunctions[key] = jitFunction
}
}
if jitFunction != nil {
l.Line = []profile.Line{{Function: jitFunction}}
}
}
locations = append(locations, l)
locationIndices[key] = locationIndex
}
sampleLocations = append(sampleLocations, locations[locationIndex])
}
}
sample = &profile.Sample{
Value: []int64{int64(value)},
Location: sampleLocations,
}
samples[stack] = sample
}
if it.Err() != nil {
return fmt.Errorf("failed iterator: %w", it.Err())
}
// Build Profile from samples, locations and mappings.
for _, s := range samples {
prof.Sample = append(prof.Sample, s)
}
var buildIDFiles map[string]maps.BuildIDFile
prof.Mapping, buildIDFiles = mapping.AllMappings()
prof.Location = locations
kernelSymbols, err := p.ksymCache.Resolve(kernelAddresses)
if err != nil {
return fmt.Errorf("resolve kernel symbols: %w", err)
}
for _, l := range kernelLocations {
kernelFunction, ok := kernelFunctions[l.Address]
if !ok {
name := kernelSymbols[l.Address]
if name == "" {
name = "not found"
}
kernelFunction = &profile.Function{
Name: name,
}
kernelFunctions[l.Address] = kernelFunction
}
if kernelFunction != nil {
l.Line = []profile.Line{{Function: kernelFunction}}
}
}
for _, f := range kernelFunctions {
f.ID = uint64(len(prof.Function)) + 1
prof.Function = append(prof.Function, f)
}
kernelMapping.ID = uint64(len(prof.Mapping)) + 1
prof.Mapping = append(prof.Mapping, kernelMapping)
for _, f := range userFunctions {
f.ID = uint64(len(prof.Function)) + 1
prof.Function = append(prof.Function, f)
}
go p.debugInfoExtractor.EnsureUploaded(ctx, buildIDFiles)
buf := bytes.NewBuffer(nil)
err = prof.Write(buf)
if err != nil {
return err
}
labels := p.Labels()
var labeloldformat []*profilestorepb.Label
for key, value := range labels {
labeloldformat = append(labeloldformat,
&profilestorepb.Label{
Name: string(key),
Value: string(value),
})
}
_, err = p.writeClient.WriteRaw(ctx, &profilestorepb.WriteRawRequest{
Series: []*profilestorepb.RawProfileSeries{{
Labels: &profilestorepb.LabelSet{Labels: labeloldformat},
Samples: []*profilestorepb.RawSample{{
RawProfile: buf.Bytes(),
}},
}},
})
if err != nil {
level.Error(p.logger).Log("msg", "failed to send profile", "err", err)
}
// BPF iterators need the previous value to iterate to the next, so we
// can only delete the "previous" item once we've already iterated to
// the next.
it = stackTraces.Iterator()
var prev []byte = nil
for it.Next() {
if prev != nil {
err := stackTraces.DeleteKey(unsafe.Pointer(&prev[0]))
if err != nil {
level.Warn(p.logger).Log("msg", "failed to delete stack trace", "err", err)
}
}
key := it.Key()
prev = make([]byte, len(key))
copy(prev, key)
}
if prev != nil {
err := stackTraces.DeleteKey(unsafe.Pointer(&prev[0]))
if err != nil {
level.Warn(p.logger).Log("msg", "failed to delete stack trace", "err", err)
}
}
it = counts.Iterator()
prev = nil
for it.Next() {
if prev != nil {
err := counts.DeleteKey(unsafe.Pointer(&prev[0]))
if err != nil {
level.Warn(p.logger).Log("msg", "failed to delete count", "err", err)
}
}
key := it.Key()
prev = make([]byte, len(key))
copy(prev, key)
}
if prev != nil {
err := counts.DeleteKey(unsafe.Pointer(&prev[0]))
if err != nil {
level.Warn(p.logger).Log("msg", "failed to delete count", "err", err)
}
}
return nil
}