-
Notifications
You must be signed in to change notification settings - Fork 97
/
Copy pathprobe.go
356 lines (314 loc) · 10.1 KB
/
probe.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
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package global
import (
"bytes"
"encoding/binary"
"fmt"
"log/slog"
"math"
"go.opentelemetry.io/collector/pdata/pcommon"
"go.opentelemetry.io/collector/pdata/ptrace"
"go.opentelemetry.io/auto/internal/pkg/inject"
"go.opentelemetry.io/auto/internal/pkg/instrumentation/probe"
"go.opentelemetry.io/auto/internal/pkg/instrumentation/utils"
"go.opentelemetry.io/auto/internal/pkg/process"
"go.opentelemetry.io/auto/internal/pkg/structfield"
"github.com/cilium/ebpf/perf"
"github.com/hashicorp/go-version"
"golang.org/x/sys/unix"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
"go.opentelemetry.io/auto/internal/pkg/instrumentation/context"
)
//go:generate go run github.com/cilium/ebpf/cmd/bpf2go -target amd64,arm64 bpf ./bpf/probe.bpf.c
const (
// pkg is the package being instrumented.
pkg = "go.opentelemetry.io/otel/internal/global"
// Minimum version of go.opentelemetry.io/otel that supports using the
// go.opentelemetry.io/auto/sdk in the global API.
minAutoSDK = "1.33.0"
)
var (
otelWithAutoSDK = probe.PackageConstrainst{
Package: "go.opentelemetry.io/otel",
Constraints: version.MustConstraints(
version.NewConstraint(fmt.Sprintf(">= %s", minAutoSDK)),
),
FailureMode: probe.FailureModeIgnore,
}
otelWithoutAutoSDK = probe.PackageConstrainst{
Package: "go.opentelemetry.io/otel",
Constraints: version.MustConstraints(
version.NewConstraint(fmt.Sprintf("< %s", minAutoSDK)),
),
FailureMode: probe.FailureModeIgnore,
}
)
// New returns a new [probe.Probe].
func New(logger *slog.Logger) probe.Probe {
id := probe.ID{
SpanKind: trace.SpanKindClient,
InstrumentedPkg: pkg,
}
uprobeNewStart := &probe.Uprobe{
Sym: "go.opentelemetry.io/otel/internal/global.(*tracer).newSpan",
EntryProbe: "uprobe_newStart",
PackageConstrainsts: []probe.PackageConstrainst{
otelWithAutoSDK,
},
}
c := &converter{
logger: logger,
uprobeNewStart: uprobeNewStart,
}
return &probe.TraceProducer[bpfObjects, event]{
Base: probe.Base[bpfObjects, event]{
ID: id,
Logger: logger,
Consts: []probe.Const{
probe.RegistersABIConst{},
probe.AllocationConst{},
probe.KeyValConst{
Key: "attr_type_invalid",
Val: uint64(attribute.INVALID),
},
probe.KeyValConst{
Key: "attr_type_bool",
Val: uint64(attribute.BOOL),
},
probe.KeyValConst{
Key: "attr_type_int64",
Val: uint64(attribute.INT64),
},
probe.KeyValConst{
Key: "attr_type_float64",
Val: uint64(attribute.FLOAT64),
},
probe.KeyValConst{
Key: "attr_type_string",
Val: uint64(attribute.STRING),
},
probe.KeyValConst{
Key: "attr_type_boolslice",
Val: uint64(attribute.BOOLSLICE),
},
probe.KeyValConst{
Key: "attr_type_int64slice",
Val: uint64(attribute.INT64SLICE),
},
probe.KeyValConst{
Key: "attr_type_float64slice",
Val: uint64(attribute.FLOAT64SLICE),
},
probe.KeyValConst{
Key: "attr_type_stringslice",
Val: uint64(attribute.STRINGSLICE),
},
probe.StructFieldConst{
Key: "tracer_delegate_pos",
Val: structfield.NewID("go.opentelemetry.io/otel", "go.opentelemetry.io/otel/internal/global", "tracer", "delegate"),
},
probe.StructFieldConst{
Key: "tracer_name_pos",
Val: structfield.NewID("go.opentelemetry.io/otel", "go.opentelemetry.io/otel/internal/global", "tracer", "name"),
},
probe.StructFieldConst{
Key: "tracer_provider_pos",
Val: structfield.NewID("go.opentelemetry.io/otel", "go.opentelemetry.io/otel/internal/global", "tracer", "provider"),
},
probe.StructFieldConst{
Key: "tracer_provider_tracers_pos",
Val: structfield.NewID("go.opentelemetry.io/otel", "go.opentelemetry.io/otel/internal/global", "tracerProvider", "tracers"),
},
probe.StructFieldConst{
Key: "buckets_ptr_pos",
Val: structfield.NewID("std", "runtime", "hmap", "buckets"),
},
tracerIDContainsSchemaURL{},
tracerIDContainsScopeAttributes{},
},
Uprobes: []*probe.Uprobe{
uprobeNewStart,
{
Sym: "go.opentelemetry.io/otel/internal/global.(*tracer).Start",
EntryProbe: "uprobe_Start",
ReturnProbe: "uprobe_Start_Returns",
PackageConstrainsts: []probe.PackageConstrainst{
otelWithoutAutoSDK,
},
},
{
Sym: "go.opentelemetry.io/otel/internal/global.(*nonRecordingSpan).End",
EntryProbe: "uprobe_End",
PackageConstrainsts: []probe.PackageConstrainst{
otelWithoutAutoSDK,
},
},
{
Sym: "go.opentelemetry.io/otel/internal/global.(*nonRecordingSpan).SetAttributes",
EntryProbe: "uprobe_SetAttributes",
FailureMode: probe.FailureModeIgnore,
PackageConstrainsts: []probe.PackageConstrainst{
otelWithoutAutoSDK,
},
},
{
Sym: "go.opentelemetry.io/otel/internal/global.(*nonRecordingSpan).SetStatus",
EntryProbe: "uprobe_SetStatus",
FailureMode: probe.FailureModeIgnore,
PackageConstrainsts: []probe.PackageConstrainst{
otelWithoutAutoSDK,
},
},
{
Sym: "go.opentelemetry.io/otel/internal/global.(*nonRecordingSpan).SetName",
EntryProbe: "uprobe_SetName",
FailureMode: probe.FailureModeIgnore,
PackageConstrainsts: []probe.PackageConstrainst{
otelWithoutAutoSDK,
},
},
},
SpecFn: loadBpf,
ProcessRecord: c.decodeEvent,
},
ProcessFn: processFn,
}
}
type recordKind uint32
const (
recordKindTelemetry recordKind = iota
recordKindConrol
)
type converter struct {
logger *slog.Logger
uprobeNewStart *probe.Uprobe
}
func (c *converter) decodeEvent(record perf.Record) (*event, error) {
reader := bytes.NewReader(record.RawSample)
var kind recordKind
err := binary.Read(reader, binary.LittleEndian, &kind)
if err != nil {
return nil, err
}
var e *event
switch kind {
case recordKindTelemetry:
e = new(event)
reader.Reset(record.RawSample)
err = binary.Read(reader, binary.LittleEndian, e)
case recordKindConrol:
if c.uprobeNewStart != nil {
err = c.uprobeNewStart.Close()
c.uprobeNewStart = nil
}
default:
err = fmt.Errorf("unknown record kind: %d", kind)
}
return e, err
}
// tracerIDContainsSchemaURL is a Probe Const defining whether the tracer key contains schemaURL.
type tracerIDContainsSchemaURL struct{}
// Prior to v1.28 the tracer key did not contain schemaURL. However, in that version a
// change was made to include it.
// https://github.com/open-telemetry/opentelemetry-go/pull/5426/files
var schemaAddedToTracerKeyVer = version.Must(version.NewVersion("1.28.0"))
func (c tracerIDContainsSchemaURL) InjectOption(td *process.TargetDetails) (inject.Option, error) {
ver, ok := td.Libraries["go.opentelemetry.io/otel"]
if !ok {
return nil, fmt.Errorf("unknown module version: %s", pkg)
}
return inject.WithKeyValue("tracer_id_contains_schemaURL", ver.GreaterThanOrEqual(schemaAddedToTracerKeyVer)), nil
}
// In v1.32.0 the tracer key was updated to include the scope attributes.
// https://github.com/open-telemetry/opentelemetry-go/pull/5924/files
var scopeAttributesAddedToTracerKeyVer = version.Must(version.NewVersion("1.32.0"))
// tracerIDContainsScopeAttributes is a Probe Const defining whether the tracer key contains scope attributes.
type tracerIDContainsScopeAttributes struct{}
func (c tracerIDContainsScopeAttributes) InjectOption(td *process.TargetDetails) (inject.Option, error) {
ver, ok := td.Libraries["go.opentelemetry.io/otel"]
if !ok {
return nil, fmt.Errorf("unknown module version: %s", pkg)
}
return inject.WithKeyValue("tracer_id_contains_scope_attributes", ver.GreaterThanOrEqual(scopeAttributesAddedToTracerKeyVer)), nil
}
type attributeKeyVal struct {
ValLength uint16
Vtype uint8
Reserved uint8
Key [32]byte
Value [128]byte
}
type attributesBuffer struct {
AttrsKv [16]attributeKeyVal
ValidAttrs uint8
}
type status struct {
Code uint32
Description [64]byte
}
type tracerID struct {
Name [128]byte
Version [32]byte
SchemaURL [128]byte
}
// event represents a manual span created by the user.
type event struct {
context.BaseSpanProperties
SpanName [64]byte
Status status
Attributes attributesBuffer
TracerID tracerID
}
func processFn(e *event) ptrace.ScopeSpans {
ss := ptrace.NewScopeSpans()
scope := ss.Scope()
scope.SetName(unix.ByteSliceToString(e.TracerID.Name[:]))
scope.SetVersion(unix.ByteSliceToString(e.TracerID.Version[:]))
ss.SetSchemaUrl(unix.ByteSliceToString(e.TracerID.SchemaURL[:]))
span := ss.Spans().AppendEmpty()
span.SetName(unix.ByteSliceToString(e.SpanName[:]))
span.SetKind(ptrace.SpanKindClient)
span.SetStartTimestamp(utils.BootOffsetToTimestamp(e.StartTime))
span.SetEndTimestamp(utils.BootOffsetToTimestamp(e.EndTime))
span.SetTraceID(pcommon.TraceID(e.SpanContext.TraceID))
span.SetSpanID(pcommon.SpanID(e.SpanContext.SpanID))
span.SetFlags(uint32(trace.FlagsSampled))
if e.ParentSpanContext.SpanID.IsValid() {
span.SetParentSpanID(pcommon.SpanID(e.ParentSpanContext.SpanID))
}
setAttributes(span.Attributes(), e.Attributes)
setStatus(span.Status(), e.Status)
return ss
}
func setStatus(dest ptrace.Status, stat status) {
switch codes.Code(stat.Code) {
case codes.Unset:
dest.SetCode(ptrace.StatusCodeUnset)
case codes.Ok:
dest.SetCode(ptrace.StatusCodeOk)
case codes.Error:
dest.SetCode(ptrace.StatusCodeError)
}
dest.SetMessage(string(unix.ByteSliceToString(stat.Description[:])))
}
func setAttributes(dest pcommon.Map, ab attributesBuffer) {
for i := 0; i < int(ab.ValidAttrs); i++ {
akv := ab.AttrsKv[i]
key := unix.ByteSliceToString(akv.Key[:])
switch akv.Vtype {
case uint8(attribute.BOOL):
dest.PutBool(key, akv.Value[0] != 0)
case uint8(attribute.INT64):
v := int64(binary.LittleEndian.Uint64(akv.Value[:8]))
dest.PutInt(key, v)
case uint8(attribute.FLOAT64):
v := math.Float64frombits(binary.LittleEndian.Uint64(akv.Value[:8]))
dest.PutDouble(key, v)
case uint8(attribute.STRING):
dest.PutStr(key, unix.ByteSliceToString(akv.Value[:]))
}
}
}