-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathparca_reporter.go
More file actions
2108 lines (1827 loc) · 64.5 KB
/
Copy pathparca_reporter.go
File metadata and controls
2108 lines (1827 loc) · 64.5 KB
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Apache License 2.0.
* See the file "LICENSE" for details.
*/
package reporter
import (
"bytes"
"context"
"debug/elf"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"io"
"os"
"path"
"strings"
"sync"
"time"
"unicode/utf8"
debuginfogrpc "buf.build/gen/go/parca-dev/parca/grpc/go/parca/debuginfo/v1alpha1/debuginfov1alpha1grpc"
profilestoregrpc "buf.build/gen/go/parca-dev/parca/grpc/go/parca/profilestore/v1alpha1/profilestorev1alpha1grpc"
profilestorepb "buf.build/gen/go/parca-dev/parca/protocolbuffers/go/parca/profilestore/v1alpha1"
"github.com/apache/arrow-go/v18/arrow"
"github.com/apache/arrow-go/v18/arrow/array"
"github.com/apache/arrow-go/v18/arrow/ipc"
"github.com/apache/arrow-go/v18/arrow/memory"
lru "github.com/elastic/go-freelru"
"github.com/klauspost/compress/zstd"
"github.com/parca-dev/oomprof/oomprof"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/model/relabel"
log "github.com/sirupsen/logrus"
"github.com/xyproto/ainur"
"github.com/zeebo/xxh3"
"go.opentelemetry.io/ebpf-profiler/interpreter/gpu"
"go.opentelemetry.io/ebpf-profiler/libpf"
otelmetrics "go.opentelemetry.io/ebpf-profiler/metrics"
"go.opentelemetry.io/ebpf-profiler/process"
"go.opentelemetry.io/ebpf-profiler/reporter"
"go.opentelemetry.io/ebpf-profiler/reporter/samples"
"go.opentelemetry.io/ebpf-profiler/support"
"go.opentelemetry.io/ebpf-profiler/traceutil"
otellog "go.opentelemetry.io/otel/log"
lognoop "go.opentelemetry.io/otel/log/noop"
sdklog "go.opentelemetry.io/otel/sdk/log"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/parca-dev/parca-agent/metrics"
"github.com/parca-dev/parca-agent/reporter/metadata"
)
// Assert that we implement the full ParcaReporter interface (which itself
// embeds otel's reporter.Reporter, so the otel contract is covered too).
var _ ParcaReporter = (*arrowReporter)(nil)
// GPU sample reporting. PC samples are reported as a raw sample count
// (gpu_pcsample/count); the per-sample weight — NsPerSample = 2^SamplingFactor
// / clock_hz, derived from the per-pid GpuConfig emitted by parcagpu's
// gpu_config USDT probe — is carried in the period, mirroring CPU sampling
// (samples/count : cpu/nanoseconds). value × period totals nanoseconds of GPU
// time, but the value itself is the honest sample count and stays correct even
// before the GpuConfig arrives (only the period is unknown until then).
//
// PC sampling observes all PC activity — normally scheduled instructions as
// well as stalls — so the sample_type is gpu_pcsample, not a "stall time".
//
// When mergeGpuProfiles is true (legacy), kernel timings and PC samples are
// folded into a single gpu_time/nanoseconds sample_type differentiated by a
// gpu_view label; there the PC count is converted to nanoseconds inline so both
// views stay summable in one time unit. When false (default), they go into
// separate sample_types: gpu_kernel_time/nanoseconds for exact kernel
// durations, gpu_pcsample/count for PC sample counts.
//
// The sample_type/unit and gpu_view label strings are written as literals at
// the call sites (matching the cpu/off-cpu cases above) so the full
// profile-type tuple and view label are visible where they're emitted.
// gpuNsPerSample looks up the per-pid GpuConfig (populated from parcagpu's
// gpu_config USDT probe) and returns the nanoseconds of GPU time attributable
// to one PC sample observation, or 0 if the config has not yet arrived. The
// non-merged path uses it as the sample's period (the raw PC count from
// TraceEventMeta.OffTime stays the value); the merged path multiplies the raw
// count by it to convert to nanoseconds.
func (r *arrowReporter) gpuNsPerSample(pid libpf.PID) int64 {
cfg, ok := gpu.LoadGpuConfig(uint32(pid))
if !ok {
gpu.WarnMissingGpuConfig(uint32(pid))
return 0
}
return cfg.NsPerSample()
}
// processInfo stores metadata about the process.
type processInfo struct {
comm string
mainExecutable libpf.FileID
}
// labelRetrievalResult is a result of a label retrieval.
type labelRetrievalResult struct {
labels labels.Labels
keep bool
}
// arrowReporter is the concrete arrow-row builder behind the
// ParcaReporter interface. It transforms otel trace events and
// parca-agent-specific memory traces into OTLP/profiles-compliant arrow
// records and ships them to the configured backend.
type arrowReporter struct {
// client for the connection to the receiver.
client profilestoregrpc.ProfileStoreServiceClient
// stopSignal is the stop signal for shutting down all background tasks.
stopSignal chan libpf.Void
// To fill in the profiles signal with the relevant information,
// this structure holds in long-term storage information that might
// be duplicated in other places but not accessible for arrowReporter.
// executables stores metadata for executables.
executables *lru.SyncedLRU[libpf.FileID, metadata.ExecInfo]
// labels stores labels about the process, keyed by PID.
labels *lru.SyncedLRU[libpf.PID, labelRetrievalResult]
// Per-sample label disable flags.
disableCPULabel bool
disableThreadIDLabel bool
disableThreadCommLabel bool
// samples stores the so far received samples (v1 schema).
sampleWriter *SampleWriter
sampleWriterMu sync.Mutex
// v2 schema support
useV2Schema bool
sampleWriterV2 *SampleWriterV2
sampleWriterV2Mu sync.Mutex
// mergeGpuProfiles reports GPU kernel timing and GPU PC sampling under a
// single gpu_time/nanoseconds sample_type, with a gpu_view label
// distinguishing the two views.
mergeGpuProfiles bool
// stacks stores known stacks.
stacks *lru.SyncedLRU[libpf.TraceHash, libpf.Frames]
// uploader uploads debuginfo to the backend.
uploader *ParcaSymbolUploader
// the apache arrow allocator to use.
mem memory.Allocator
// additional labels to attach to all profiling data.
externalLabels []Label
// samplesPerSecond is the number of samples per second.
samplesPerSecond int64
// disableSymbolUpload disables the symbol upload.
disableSymbolUpload bool
// reportInterval is the interval at which to report data.
reportInterval time.Duration
// relabelConfigs are the relabel configurations to apply to the labels.
relabelConfigs []*relabel.Config
// node name
nodeName string
// metadata providers
metadataProviders []metadata.MetadataProvider
// Prometheus metrics registry
reg prometheus.Registerer
// Metrics that we have seen via ReportMetrics
otelLibraryMetrics map[string]prometheus.Metric
// Our own metrics
sampleWrites prometheus.Counter
sampleWriteRequestBytes prometheus.Counter
stacktraceWriteRequestBytes prometheus.Counter
debuginfoUploadRequestBytes prometheus.Counter
emptySamples prometheus.Counter
skippedByRelabeling prometheus.Counter
writeRequestsTotal *prometheus.CounterVec
// Pre-created sample counters by type (avoid WithLabelValues allocations)
cpuSamples prometheus.Counter
gpuSamples prometheus.Counter
gpuPCSamples prometheus.Counter
offcpuSamples prometheus.Counter
memorySamples prometheus.Counter
offlineModeConfig *OfflineModeConfig
// Protects the log file,
// which is accessed from both the main reporter loop
// and the rotator
offlineModeLogMu sync.Mutex
offlineModeLogFile *os.File
offlineModeLogPath string
offlineModeNBatchesInCurrentFile uint16
// Set of stacks that are already in the current log,
// meaning we don't need to log them again.
offlineModeLoggedStacks *lru.SyncedLRU[libpf.TraceHash, struct{}]
oomState *oomprof.State
reportAllocs bool // whether to report allocs in memory profiles
// logProvider is set when the reporter was constructed with a non-nil
// gRPC conn; otherwise Logger() hands out the OTel no-op logger and
// emit calls are silently dropped. Owned by the reporter so Shutdown can
// flush + close it when the reporter is torn down.
logProvider *sdklog.LoggerProvider
}
// Assert that *arrowReporter satisfies the ParcaReporter interface.
var _ ParcaReporter = (*arrowReporter)(nil)
// Logger returns an OTel logs Logger bound to the given scope name.
// In offline mode (no gRPC conn was supplied at construction) the SDK
// LoggerProvider is nil; we return the OTel no-op Logger so callers can
// treat Logger as unconditional and Emit calls become inert.
func (r *arrowReporter) Logger(scope string) otellog.Logger {
if r.logProvider == nil {
return lognoop.NewLoggerProvider().Logger(scope)
}
return r.logProvider.Logger(scope)
}
// hashString is a helper function for LRUs that use string as a key.
// Xxh3 turned out to be the fastest hash function for strings in the FreeLRU benchmarks.
// It was only outperformed by the AES hash function, which is implemented in Plan9 assembly.
func hashString(s string) uint32 {
return uint32(xxh3.HashString(s))
}
func (r *arrowReporter) SupportsReportTraceEvent() bool { return true }
// maybeFixTruncation fixes string truncation done at the byte level
// (at maxLen) to be done at the rune level instead.
//
// It returns the correctly truncated utf-8 string if possible;
// otherwise "", false.
func maybeFixTruncation(s string, maxLen int) (string, bool) {
if utf8.ValidString(s) {
return s, true
}
// maybe we truncated in the middle of a rune -- if that's the case,
// truncate the entire rune.
plausibleTruncatedRuneBegin := -1
if len(s) == maxLen {
i := 0
for ; i < 2; i += 1 {
idx := maxLen - i - 1
if s[idx]&0xC0 != 0x80 {
plausibleTruncatedRuneBegin = idx
break
}
}
}
if plausibleTruncatedRuneBegin != -1 {
s = s[0:plausibleTruncatedRuneBegin]
if !utf8.ValidString(s) {
return "", false
}
} else {
return "", false
}
return s, true
}
// ReportTraceEvent enqueues reported trace events for the OTLP reporter.
//
// Memory-origin traces do not flow through this method — they take the
// dedicated ReportMemoryTraces path so a memory batch can hold the writer
// lock once for many rows.
func (r *arrowReporter) ReportTraceEvent(trace *libpf.Trace,
meta *samples.TraceEventMeta,
) error {
traceHash := traceutil.HashTrace(trace)
// This is an LRU so we need to check every time if the stack is already
// known, as it might have been evicted.
if _, exists := r.stacks.Get(traceHash); !exists {
// Store the Frames directly, no allocation needed
r.stacks.Add(traceHash, trace.Frames)
}
labelRetrievalResult := r.labelsForTID(meta.TID, meta.PID, meta.Comm, meta.CPU, meta.Origin, meta.EnvVars)
if !labelRetrievalResult.keep {
r.skippedByRelabeling.Inc()
log.Debugf("Skipping trace event for PID %d, as it was filtered out by relabeling", meta.PID)
return nil
}
if len(trace.Frames) == 0 {
r.emptySamples.Inc()
}
// Dispatch to v2 path if enabled
if r.useV2Schema {
return r.reportTraceEventV2(trace, traceHash, meta, labelRetrievalResult)
}
r.sampleWriterMu.Lock()
defer r.sampleWriterMu.Unlock()
buf := [16]byte{}
traceHash.PutBytes16(&buf)
writeSample := func(value int64, duration int64, per int64, producer, sampleType, sampleUnit, periodType, periodUnit string) {
// Write labels
for _, lbl := range labelRetrievalResult.labels {
r.sampleWriter.Label(lbl.Name).AppendString(lbl.Value)
}
// Write custom labels
for k, v := range trace.CustomLabels {
if !utf8.ValidString(k.String()) {
log.Warnf("ignoring non-UTF8 label: %s", hex.EncodeToString([]byte(k.String())))
continue
}
v, ok := maybeFixTruncation(v.String(), support.CustomLabelMaxValLen-1)
if !ok {
log.Warnf("ignoring non-UTF8 value for label %s: %s", k, hex.EncodeToString([]byte(v)))
continue
}
r.sampleWriter.Label(k.String()).AppendString(v)
}
// Write sample data
r.sampleWriter.StacktraceID.Append(buf[:])
r.sampleWriter.Timestamp.Append(int64(meta.Timestamp))
r.sampleWriter.Value.Append(value)
r.sampleWriter.SampleType.AppendString(sampleType)
r.sampleWriter.SampleUnit.AppendString(sampleUnit)
r.sampleWriter.PeriodType.AppendString(periodType)
r.sampleWriter.PeriodUnit.AppendString(periodUnit)
r.sampleWriter.Producer.AppendString(producer)
r.sampleWriter.Duration.Append(duration)
r.sampleWriter.Period.Append(per)
}
switch meta.Origin {
case support.TraceOriginSampling:
writeSample(1, int64(time.Second.Nanoseconds()), 1e9/int64(r.samplesPerSecond), "parca_agent", "samples", "count", "cpu", "nanoseconds")
r.sampleWriter.Temporality.AppendString("delta")
r.cpuSamples.Inc()
case support.TraceOriginOffCPU:
writeSample(meta.Value, int64(time.Second.Nanoseconds()), 1e9/int64(r.samplesPerSecond), "parca_agent", "wallclock", "nanoseconds", "samples", "count")
r.sampleWriter.Temporality.AppendString("delta")
r.offcpuSamples.Inc()
case support.TraceOriginCuda:
if r.mergeGpuProfiles {
r.sampleWriter.Label("gpu_view").AppendString("kernel_time")
writeSample(meta.Value, time.Second.Nanoseconds(), 1,
"parca_agent", "gpu_time", "nanoseconds", "gpu_time", "nanoseconds")
} else {
writeSample(meta.Value, time.Second.Nanoseconds(), 1,
"parca_agent", "gpu_kernel_time", "nanoseconds", "gpu_kernel_time", "nanoseconds")
}
r.sampleWriter.Temporality.AppendString("delta")
r.gpuSamples.Inc()
case support.TraceOriginGpuPC:
nsPerSample := r.gpuNsPerSample(meta.PID)
if r.mergeGpuProfiles {
value := meta.Value
if nsPerSample > 0 {
value *= nsPerSample
}
r.sampleWriter.Label("gpu_view").AppendString("pc_sample")
writeSample(value, time.Second.Nanoseconds(), 1,
"parca_agent", "gpu_time", "nanoseconds", "gpu_time", "nanoseconds")
} else {
writeSample(meta.Value, time.Second.Nanoseconds(), nsPerSample,
"parca_agent", "gpu_pcsample", "count", "gpu_pcsample", "nanoseconds")
}
r.sampleWriter.Temporality.AppendString("delta")
r.gpuPCSamples.Inc()
default:
log.Warnf("unknown trace origin: %d", meta.Origin)
}
return nil
}
// reportTraceEventV2 handles trace events using the v2 schema with inline
// stacktraces. Memory-origin traces do not pass through this method —
// they are written by ReportMemoryTraces.
func (r *arrowReporter) reportTraceEventV2(trace *libpf.Trace, traceHash libpf.TraceHash,
meta *samples.TraceEventMeta, labelResult labelRetrievalResult,
) error {
r.sampleWriterV2Mu.Lock()
defer r.sampleWriterV2Mu.Unlock()
switch meta.Origin {
case support.TraceOriginSampling:
r.writeSampleV2(trace, traceHash, meta, labelResult, 1, uint64(time.Second.Nanoseconds()), 1e9/int64(r.samplesPerSecond), true, "parca_agent", "samples", "count", "cpu", "nanoseconds")
r.cpuSamples.Inc()
case support.TraceOriginOffCPU:
r.writeSampleV2(trace, traceHash, meta, labelResult, meta.Value, uint64(time.Second.Nanoseconds()), 0, true, "parca_agent", "wallclock", "nanoseconds", "samples", "count")
r.offcpuSamples.Inc()
case support.TraceOriginCuda:
if r.mergeGpuProfiles {
r.sampleWriterV2.Label("gpu_view").AppendString("kernel_time")
r.writeSampleV2(trace, traceHash, meta, labelResult, meta.Value,
uint64(time.Second.Nanoseconds()), 1, true,
"parca_agent", "gpu_time", "nanoseconds", "gpu_time", "nanoseconds")
} else {
r.writeSampleV2(trace, traceHash, meta, labelResult, meta.Value,
uint64(time.Second.Nanoseconds()), 1, true,
"parca_agent", "gpu_kernel_time", "nanoseconds", "gpu_kernel_time", "nanoseconds")
}
r.gpuSamples.Inc()
case support.TraceOriginGpuPC:
nsPerSample := r.gpuNsPerSample(meta.PID)
if r.mergeGpuProfiles {
value := meta.Value
if nsPerSample > 0 {
value *= nsPerSample
}
r.sampleWriterV2.Label("gpu_view").AppendString("pc_sample")
r.writeSampleV2(trace, traceHash, meta, labelResult, value,
uint64(time.Second.Nanoseconds()), 1, true,
"parca_agent", "gpu_time", "nanoseconds", "gpu_time", "nanoseconds")
} else {
r.writeSampleV2(trace, traceHash, meta, labelResult, meta.Value,
uint64(time.Second.Nanoseconds()), nsPerSample, true,
"parca_agent", "gpu_pcsample", "count", "gpu_pcsample", "nanoseconds")
}
r.gpuPCSamples.Inc()
default:
log.Warnf("unknown trace origin: %d", meta.Origin)
}
return nil
}
func (r *arrowReporter) writeSampleV2(
trace *libpf.Trace,
traceHash libpf.TraceHash,
meta *samples.TraceEventMeta,
labelResult labelRetrievalResult,
value int64, duration uint64, per int64,
delta bool,
producer, sampleType, sampleUnit, periodType, periodUnit string,
) {
for _, lbl := range labelResult.labels {
r.sampleWriterV2.Label(lbl.Name).AppendString(lbl.Value)
}
for k, v := range trace.CustomLabels {
ks := k.String()
if !utf8.ValidString(ks) {
log.Warnf("ignoring non-UTF8 label: %s", hex.EncodeToString([]byte(ks)))
continue
}
vs, ok := maybeFixTruncation(v.String(), support.CustomLabelMaxValLen-1)
if !ok {
log.Warnf("ignoring non-UTF8 value for label %s: %s", ks, hex.EncodeToString([]byte(vs)))
continue
}
r.sampleWriterV2.Label(ks).AppendString(vs)
}
r.sampleWriterV2.Stacktrace.AppendStacktrace(traceHash, trace.Frames, r.appendLocationV2)
r.sampleWriterV2.StacktraceID.AppendBytes([16]byte(traceHash.Bytes()))
r.sampleWriterV2.Timestamp.Append(arrow.Timestamp(int64(meta.Timestamp)))
r.sampleWriterV2.Value.Append(value)
r.sampleWriterV2.SampleType.AppendString(sampleType)
r.sampleWriterV2.SampleUnit.AppendString(sampleUnit)
r.sampleWriterV2.PeriodType.AppendString(periodType)
r.sampleWriterV2.PeriodUnit.AppendString(periodUnit)
r.sampleWriterV2.Producer.AppendString(producer)
r.sampleWriterV2.Duration.Append(duration)
r.sampleWriterV2.Period.Append(per)
if delta {
r.sampleWriterV2.Temporality.AppendString("delta")
} else {
r.sampleWriterV2.Temporality.AppendNull()
}
}
// appendLocationV2 resolves a frame and appends it to the location dictionary.
// It uses the libpf.Frame value as the deduplication key, skipping resolution
// and arrow writes when the frame has already been seen.
// Functions are dictionary-encoded via FunctionDictBuilderV2.
func (r *arrowReporter) appendLocationV2(frame libpf.Frame) uint32 {
b := r.sampleWriterV2.Stacktrace
if idx, ok := b.LocationIndex[frame]; ok {
return idx
}
idx := uint32(len(b.LocationIndex))
b.LocationIndex[frame] = idx
// Record line list offset for this location (before writing any lines)
b.lineListOffsets.Append(int32(b.lineNumber.Len()))
b.locAddress.Append(uint64(frame.AddressOrLineno))
if frame.Type.IsAbort() {
b.locFrameType.AppendString(frame.Type.String())
b.locMappingFile.AppendString("agent-internal-error-frame")
b.locMappingID.AppendNull()
b.lineNumber.Append(0)
b.lineColumn.Append(0)
b.funcIndices.Append(b.funcDict.AppendFunction(FunctionV2{
SystemName: "aborted",
Filename: "",
StartLine: 0,
}))
return idx
}
switch frameKind := frame.Type; frameKind {
case libpf.NativeFrame:
b.locFrameType.AppendString(frame.Type.String())
var execInfo metadata.ExecInfo
var fid libpf.FileID
var exists bool
if frame.Mapping.Valid() {
m := frame.Mapping.Value()
if m.File != (libpf.FrameMappingFile{}) {
mf := m.File.Value()
fid = mf.FileID
execInfo, exists = r.executables.Get(mf.FileID)
}
}
if exists {
b.locMappingFile.AppendString(execInfo.FileName)
if execInfo.BuildID != "" {
b.locMappingID.AppendString(execInfo.BuildID)
} else {
b.locMappingID.AppendString(fid.StringNoQuotes())
}
} else {
b.locMappingFile.AppendString("UNKNOWN")
b.locMappingID.AppendNull()
}
// No lines for native frames
case libpf.KernelFrame:
b.locFrameType.AppendString(frame.Type.String())
b.locMappingFile.AppendString("[kernel.kallsyms]")
b.locMappingID.AppendNull()
var execInfo metadata.ExecInfo
var exists bool
if frame.Mapping.Valid() {
m := frame.Mapping.Value()
if m.File != (libpf.FrameMappingFile{}) {
mf := m.File.Value()
execInfo, exists = r.executables.Get(mf.FileID)
}
}
var moduleName string
if exists {
moduleName = execInfo.FileName
} else {
moduleName = "vmlinux"
}
var symbol string
var lineNumber uint64
if frame.FunctionName.String() != "" {
symbol = frame.FunctionName.String()
lineNumber = uint64(frame.SourceLine)
} else {
symbol = "UNKNOWN"
}
b.lineNumber.Append(lineNumber)
b.lineColumn.Append(0)
b.funcIndices.Append(b.funcDict.AppendFunction(FunctionV2{
SystemName: symbol,
Filename: moduleName,
StartLine: 0,
}))
case libpf.CUDAPCFrame:
// CUDA PC sample: a function-relative kernel offset. One mapping per
// cubin (build ID = cubin CRC FileID, never a per-function ID). The
// kernel's mangled name rides as the system name of a placeholder line
// (line 0); the backend resolves the real source line per function,
// gated downstream on the "cuda-pc" frame type.
b.locFrameType.AppendString(frame.Type.String())
var fid libpf.FileID
if frame.Mapping.Valid() {
mf := frame.Mapping.Value().File.Value()
fid = mf.FileID
b.locMappingFile.AppendString(mf.FileName.String())
} else {
b.locMappingFile.AppendNull()
}
b.locMappingID.AppendString(fid.StringNoQuotes())
b.lineNumber.Append(0)
b.lineColumn.Append(0)
b.funcIndices.Append(b.funcDict.AppendFunction(FunctionV2{
SystemName: frame.FunctionName.String(),
Filename: "",
StartLine: 0,
}))
default:
// Interpreted frames (Python, Ruby, V8 etc.)
// Forward the Mapping's GnuBuildID when present so the
// backend can do sourcemap resolution.
b.locFrameType.AppendString(frame.Type.String())
b.locMappingFile.AppendNull()
if frame.Mapping.Valid() && frame.Mapping.Value().File.Value().GnuBuildID != "" {
b.locMappingID.AppendString(frame.Mapping.Value().File.Value().GnuBuildID)
} else {
b.locMappingID.AppendNull()
}
var lineNumber uint64
var functionName, filePath string
if frame.FunctionName.String() != "" {
functionName = frame.FunctionName.String()
filePath = frame.SourceFile.String()
lineNumber = uint64(frame.SourceLine)
} else {
functionName = "UNREPORTED"
filePath = "UNREPORTED"
}
// Empty path causes the backend to crash
if filePath == "" {
filePath = "UNKNOWN"
}
b.lineNumber.Append(lineNumber)
b.lineColumn.Append(uint64(frame.SourceColumn))
b.funcIndices.Append(b.funcDict.AppendFunction(FunctionV2{
SystemName: functionName,
Filename: filePath,
StartLine: 0,
}))
}
return idx
}
func (r *arrowReporter) addMetadataForPID(ctx context.Context, pid libpf.PID, lb *labels.Builder) bool {
cache := true
for _, p := range r.metadataProviders {
cacheable := p.AddMetadata(ctx, pid, lb)
cache = cache && cacheable
}
return cache
}
func (r *arrowReporter) labelsForTID(tid, pid libpf.PID, comm libpf.String, cpu uint32, origin libpf.Origin, envVars map[libpf.String]libpf.String) labelRetrievalResult {
cached, hit := r.labels.Get(pid)
if !hit {
lb := &labels.Builder{}
lb.Set("node", r.nodeName)
for k, v := range envVars {
lb.Set("__meta_env_var_"+k.String(), v.String())
}
if r.oomState != nil && r.oomState.PidOomd(uint32(pid)) {
lb.Set("job", "oomprof")
}
cacheable := r.addMetadataForPID(context.TODO(), pid, lb)
keep := relabel.ProcessBuilder(lb, r.relabelConfigs...)
// Meta labels are deleted after relabelling. Other internal labels propagate to
// the target which decides whether they will be part of their label set.
lb.Range(func(l labels.Label) {
if strings.HasPrefix(l.Name, model.MetaLabelPrefix) {
lb.Del(l.Name)
}
})
cached = labelRetrievalResult{
labels: lb.Labels(),
keep: keep,
}
if cacheable {
log.Debugf("adding labels for PID %d to cache: %s", pid, lb.Labels())
r.labels.Add(pid, cached)
}
}
// Skip per-sample label patching if relabeling dropped this process.
if !cached.keep {
return cached
}
// Probe samples additionally run through a per-sample relabel pass so
// rules can derive custom labels (or drop) from per-sample fields. We
// gate this on probe origin only — CPU/off-CPU/memory/cuda samples
// keep the cheap "patch and ship" path (see commit 34c9ed7a).
perSampleRelabel := origin == support.TraceOriginProbe && len(r.relabelConfigs) > 0
// Nothing per-sample to do: no patches and no per-sample relabel.
if r.disableCPULabel && r.disableThreadIDLabel && r.disableThreadCommLabel &&
!perSampleRelabel {
return cached
}
// Patch per-sample fields onto a copy of the cached labels.
lb := labels.NewBuilder(cached.labels)
if !r.disableCPULabel {
lb.Set("cpu", fmt.Sprint(cpu))
}
if !r.disableThreadIDLabel {
lb.Set("thread_id", fmt.Sprint(tid))
}
if !r.disableThreadCommLabel {
lb.Set("thread_name", comm.String())
}
// Per-sample relabel pass for probe samples. The per-PID pass already
// ran against cached metadata; here the relabeler additionally sees
// the final label names (thread_id, thread_name, cpu). Rules that only
// consume per-PID inputs are idempotent across the two passes.
keep := true
if perSampleRelabel {
keep = relabel.ProcessBuilder(lb, r.relabelConfigs...)
lb.Range(func(l labels.Label) {
if strings.HasPrefix(l.Name, model.MetaLabelPrefix) {
lb.Del(l.Name)
}
})
}
return labelRetrievalResult{
labels: lb.Labels(),
keep: keep,
}
}
// ReportFramesForTrace is a NOP for arrowReporter.
func (r *arrowReporter) ReportFramesForTrace(_ *libpf.Trace) {}
// ReportCountForTrace is a NOP for arrowReporter.
func (r *arrowReporter) ReportCountForTrace(_ libpf.TraceHash, _ uint16, _ *samples.TraceEventMeta) {
}
// ExecutableKnown returns true if the metadata of the Executable specified by fileID is
// cached in the reporter.
func (r *arrowReporter) ExecutableKnown(fileID libpf.FileID) bool {
_, known := r.executables.Get(fileID)
return known
}
// ExecutableMetadata accepts a fileID with the corresponding filename
// and caches this information.
func (r *arrowReporter) ReportExecutable(args *reporter.ExecutableMetadata) {
mf := args.MappingFile.Value()
if !args.IsElf {
r.executables.Add(mf.FileID, metadata.ExecInfo{
FileName: mf.FileName.String(),
BuildID: mf.GnuBuildID,
})
return
}
// Always attempt to upload, the uploader is responsible for deduplication.
open := func() (process.ReadAtCloser, error) {
return args.Process.OpenMappingFile(args.Mapping)
}
if !r.disableSymbolUpload {
r.uploader.Upload(context.TODO(), mf.FileID, mf.FileName.String(), mf.GnuBuildID, open)
}
if _, exists := r.executables.Get(mf.FileID); exists {
return
}
f, err := open()
if err != nil {
log.Debugf("Failed to open file %s: %v", mf.FileName, err)
return
}
defer f.Close()
ef, err := elf.NewFile(f)
if err != nil {
log.Debugf("Failed to open ELF file %s: %v", mf.FileName, err)
return
}
r.executables.Add(mf.FileID, metadata.ExecInfo{
FileName: mf.FileName.String(),
BuildID: mf.GnuBuildID,
Compiler: ainur.Compiler(ef),
Static: ainur.Static(ef),
Stripped: ainur.Stripped(ef),
})
}
// ReportHostMetadata enqueues host metadata.
func (r *arrowReporter) ReportHostMetadata(metadataMap map[string]string) {
// noop
}
// ReportHostMetadataBlocking enqueues host metadata.
func (r *arrowReporter) ReportHostMetadataBlocking(_ context.Context,
metadataMap map[string]string, _ int, _ time.Duration,
) error {
// noop
return nil
}
// memorySamplePeriod is the assumed inter-allocation period used as the
// pprof "period" for memory rows. 512 KiB matches the previous behavior;
// long term this should be derived from the target process.
const memorySamplePeriod int64 = 512 * 1024
// ReportMemoryTraces emits inuse / alloc rows for a batch of memory-
// attributed traces. All samples share `meta` (one process snapshot), so
// labels are computed once and the v2 writer lock is taken once for the
// whole call.
//
// The agent v2 schema is the only target — memory profiles never went
// through the v1 path in production. The trace's call stack is encoded as
// a libpf.Trace of native frames with the build ID stashed on
// FunctionName so the location builder can synthesize a mapping for the
// possibly-gone process.
func (r *arrowReporter) ReportMemoryTraces(
memSamples []oomprof.Sample, meta oomprof.SampleMeta,
) error {
if !r.useV2Schema {
// v1 never carried memory profiles end-to-end; drop loudly so
// misconfigurations are obvious.
return fmt.Errorf("ReportMemoryTraces requires the v2 schema; v1 memory reporting is unsupported")
}
if len(memSamples) == 0 {
return nil
}
log.Debugf("Received %d oomprof samples for PID %d, comm: %s", len(memSamples), meta.PID, meta.Comm)
pid := libpf.PID(meta.PID)
comm := libpf.Intern(meta.Comm)
labelResult := r.labelsForTID(pid, pid, comm, 0, support.TraceOriginUnknown, nil)
if !labelResult.keep {
r.skippedByRelabeling.Inc()
log.Debugf("Skipping %d memory traces for PID %d, filtered by relabeling", len(memSamples), meta.PID)
return nil
}
// Intern the per-process attributes once for the whole batch.
buildID := libpf.Intern(meta.BuildID)
execPath := libpf.Intern(meta.ExecutablePath)
var customLabels map[libpf.String]libpf.String
if len(meta.CustomLabels) > 0 {
customLabels = make(map[libpf.String]libpf.String, len(meta.CustomLabels))
for k, v := range meta.CustomLabels {
customLabels[libpf.Intern(k)] = libpf.Intern(v)
}
}
traceEventMeta := &samples.TraceEventMeta{
Timestamp: libpf.UnixTime64(meta.Timestamp),
Comm: comm,
Origin: support.TraceOriginUnknown,
ProcessName: libpf.Intern(meta.ProcessName),
ExecutablePath: execPath,
PID: pid,
TID: pid, // oomprof samples carry the process, not a single TID.
}
r.sampleWriterV2Mu.Lock()
defer r.sampleWriterV2Mu.Unlock()
for i := range memSamples {
s := &memSamples[i]
t := &libpf.Trace{CustomLabels: customLabels}
for _, addr := range s.Addresses {
t.Frames.Append(&libpf.Frame{
Type: libpf.NativeFrame,
AddressOrLineno: libpf.AddressOrLineno(addr),
FunctionName: buildID, // Stash the BuildID for the location builder.
SourceFile: execPath, // Stash the executable path.
})
}
traceHash := traceutil.HashTrace(t)
if s.Allocs != s.Frees {
r.writeSampleV2(t, traceHash, traceEventMeta, labelResult,
int64(s.Allocs-s.Frees), 0, memorySamplePeriod, false,
"memory", "inuse_objects", "count", "space", "bytes")
}
if s.AllocBytes != s.FreeBytes {
r.writeSampleV2(t, traceHash, traceEventMeta, labelResult,
int64(s.AllocBytes-s.FreeBytes), 0, memorySamplePeriod, false,
"memory", "inuse_space", "bytes", "space", "bytes")
}
if r.reportAllocs {
r.writeSampleV2(t, traceHash, traceEventMeta, labelResult,
int64(s.Allocs), 0, memorySamplePeriod, false,
"memory", "alloc_objects", "count", "space", "bytes")
r.writeSampleV2(t, traceHash, traceEventMeta, labelResult,
int64(s.AllocBytes), 0, memorySamplePeriod, false,
"memory", "alloc_space", "bytes", "space", "bytes")
}
r.memorySamples.Inc()
}
return nil
}
// ReportMetrics records metrics.
func (r *arrowReporter) ReportMetrics(_ uint32, ids []uint32, values []int64) {
for i := 0; i < len(ids) && i < len(values); i++ {
id := ids[i]
val := values[i]
field, ok := metrics.AllMetrics[otelmetrics.MetricID(id)]
if !ok {
log.Warnf("Unknown metric ID: %d", id)
continue
}
f := strings.Replace(field.Field, ".", "_", -1)
switch field.Type {
case metrics.MetricTypeGauge:
m, ok := r.otelLibraryMetrics[f]
if !ok {
m = prometheus.NewGauge(prometheus.GaugeOpts{
Name: f,
Help: field.Desc,
})
r.reg.MustRegister(m.(prometheus.Gauge))
r.otelLibraryMetrics[f] = m
}
m.(prometheus.Gauge).Set(float64(val))
case metrics.MetricTypeCounter:
m, ok := r.otelLibraryMetrics[f]
if !ok {
m = prometheus.NewCounter(prometheus.CounterOpts{
Name: f,
Help: field.Desc,
})
r.reg.MustRegister(m.(prometheus.Counter))
r.otelLibraryMetrics[f] = m
}
m.(prometheus.Counter).Add(float64(val))
default:
log.Warnf("Unknown metric type: %d", field.Type)
}
}
}
// Stop triggers a graceful shutdown of arrowReporter.
func (r *arrowReporter) Stop() {
close(r.stopSignal)
if r.oomState != nil {
r.oomState.Close()
r.oomState = nil
}
}
type Label struct {
Name string
Value string
}
type Labels []Label
func (l Labels) String() string {
var buf bytes.Buffer