-
Notifications
You must be signed in to change notification settings - Fork 54
/
profiling.go
269 lines (245 loc) · 5.74 KB
/
profiling.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
package profiling
import (
"bytes"
"fmt"
"hash/fnv"
"io"
"net/http"
"net/url"
"os"
"sync"
"time"
"github.com/coroot/coroot-node-agent/common"
"github.com/coroot/coroot-node-agent/containers"
"github.com/go-kit/log"
ebpfspy "github.com/grafana/pyroscope/ebpf"
"github.com/grafana/pyroscope/ebpf/metrics"
"github.com/grafana/pyroscope/ebpf/pprof"
"github.com/grafana/pyroscope/ebpf/sd"
"github.com/grafana/pyroscope/ebpf/symtab"
"github.com/grafana/pyroscope/ebpf/symtab/elf"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/prometheus/model/labels"
"k8s.io/klog/v2"
)
const (
CollectInterval = time.Minute
SampleRate = 100
UploadTimeout = 10 * time.Second
)
var (
constLabels labels.Labels
httpClient = http.Client{
Timeout: UploadTimeout,
}
endpointUrl *url.URL
session ebpfspy.Session
targetFinder = &TargetFinder{
processes: map[uint32]*processInfo{},
}
)
func Init(hostId, hostName string) chan<- containers.ProcessInfo {
endpoint := os.Getenv("PROFILES_ENDPOINT")
if endpoint == "" {
klog.Infoln("no profiles endpoint configured")
return nil
}
klog.Infoln("profiles endpoint:", endpoint)
constLabels = labels.Labels{
{Name: "host.name", Value: hostName},
{Name: "host.id", Value: hostId},
{Name: "profile.source", Value: "ebpf"},
}
var err error
endpointUrl, err = url.Parse(endpoint)
if err != nil {
klog.Exitln(err)
}
reg := prometheus.NewRegistry()
so := ebpfspy.SessionOptions{
CollectUser: true,
CollectKernel: false,
UnknownSymbolModuleOffset: true,
UnknownSymbolAddress: false,
PythonEnabled: true,
CacheOptions: symtab.CacheOptions{
PidCacheOptions: symtab.GCacheOptions{
Size: 256,
KeepRounds: 8,
},
BuildIDCacheOptions: symtab.GCacheOptions{
Size: 256,
KeepRounds: 8,
},
SameFileCacheOptions: symtab.GCacheOptions{
Size: 256,
KeepRounds: 8,
},
SymbolOptions: symtab.SymbolOptions{
GoTableFallback: true,
PythonFullFilePath: false,
DemangleOptions: elf.DemangleFull,
},
},
Metrics: &metrics.Metrics{
Symtab: metrics.NewSymtabMetrics(reg),
Python: metrics.NewPythonMetrics(reg),
},
SampleRate: SampleRate,
}
session, err = ebpfspy.NewSession(log.NewNopLogger(), targetFinder, so)
if err != nil {
klog.Errorln(err)
session = nil
return nil
}
err = session.Start()
if err != nil {
klog.Errorln(err)
session = nil
return nil
}
go collect()
processInfoCh := make(chan containers.ProcessInfo)
targetFinder.start(processInfoCh)
return processInfoCh
}
func Start() {
if session == nil {
return
}
targetFinder.now = time.Now()
session.UpdateTargets(sd.TargetsOptions{})
}
func Stop() {
if session != nil {
session.Stop()
}
}
func collect() {
ticker := time.NewTicker(CollectInterval)
defer ticker.Stop()
for t := range ticker.C {
session.UpdateTargets(sd.TargetsOptions{})
bs := pprof.NewProfileBuilders(SampleRate)
err := session.CollectProfiles(func(target *sd.Target, stack []string, value uint64, pid uint32) {
pi := targetFinder.get(pid)
if pi == nil {
return
}
b := bs.BuilderForTarget(pi.hash, pi.labels)
b.AddSample(stack, value)
})
klog.Infof("collected %d profiles in %s", len(bs.Builders), time.Since(t).Truncate(time.Millisecond))
if err != nil {
klog.Errorln(err)
}
t = time.Now()
var uploaded int
for _, b := range bs.Builders {
err = upload(b)
if err != nil {
klog.Errorln(err)
break
}
uploaded++
}
klog.Infof("uploaded %d profiles in %s", uploaded, time.Since(t).Truncate(time.Millisecond))
}
}
func upload(b *pprof.ProfileBuilder) error {
u := *endpointUrl
q := u.Query()
for _, l := range append(b.Labels, constLabels...) {
q.Set(l.Name, l.Value)
}
u.RawQuery = q.Encode()
b.Profile.DurationNanos = CollectInterval.Nanoseconds()
body := bytes.NewBuffer(nil)
_, err := b.Write(body)
if err != nil {
return err
}
req, err := http.NewRequest("POST", u.String(), body)
if err != nil {
return err
}
resp, err := httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
if resp.StatusCode != 200 {
return fmt.Errorf("failed to upload %d: %s", resp.StatusCode, string(respBody))
}
return nil
}
type TargetFinder struct {
processes map[uint32]*processInfo
lock sync.Mutex
now time.Time
}
func (tf *TargetFinder) start(processInfoCh <-chan containers.ProcessInfo) {
go func() {
for pi := range processInfoCh {
tf.lock.Lock()
tf.processes[pi.Pid] = &processInfo{
containerId: string(pi.ContainerId),
startedAt: pi.StartedAt,
}
tf.lock.Unlock()
}
}()
}
func (tf *TargetFinder) get(pid uint32) *processInfo {
tf.lock.Lock()
pi := tf.processes[pid]
tf.lock.Unlock()
if pi == nil {
return nil
}
if tf.now.Sub(pi.startedAt) < CollectInterval {
return nil
}
if pi.hash == 0 {
pi.calcHashAndLabels()
}
return pi
}
func (tf *TargetFinder) FindTarget(pid uint32) *sd.Target {
p := tf.get(pid)
if p == nil {
return nil
}
return &sd.Target{}
}
func (tf *TargetFinder) RemoveDeadPID(pid uint32) {
tf.lock.Lock()
defer tf.lock.Unlock()
delete(tf.processes, pid)
}
func (tf *TargetFinder) DebugInfo() []string {
return nil
}
func (tf *TargetFinder) Update(_ sd.TargetsOptions) {
tf.now = time.Now()
}
type processInfo struct {
containerId string
startedAt time.Time
labels labels.Labels
hash uint64
}
func (pi *processInfo) calcHashAndLabels() {
hash := fnv.New64a()
_, _ = hash.Write([]byte(pi.containerId))
pi.hash = hash.Sum64()
pi.labels = labels.Labels{
{Name: "service.name", Value: common.ContainerIdToOtelServiceName(pi.containerId)},
{Name: "container.id", Value: pi.containerId},
}
}