-
Notifications
You must be signed in to change notification settings - Fork 248
Expand file tree
/
Copy pathdebuginfod.go
More file actions
527 lines (435 loc) · 15.3 KB
/
debuginfod.go
File metadata and controls
527 lines (435 loc) · 15.3 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
// Copyright 2022-2025 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 debuginfo
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptrace"
"net/url"
"path"
"sync"
"time"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/thanos-io/objstore"
"go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
debuginfopb "github.com/parca-dev/parca/gen/proto/go/parca/debuginfo/v1alpha1"
"github.com/parca-dev/parca/pkg/cache"
)
type DebuginfodClients interface {
Get(ctx context.Context, server, buildid string) (io.ReadCloser, error)
GetSource(ctx context.Context, server, buildid, file string) (io.ReadCloser, error)
Exists(ctx context.Context, buildid string) ([]string, error)
}
type NopDebuginfodClients struct{}
func (NopDebuginfodClients) Get(context.Context, string, string) (io.ReadCloser, error) {
return io.NopCloser(bytes.NewReader(nil)), ErrDebuginfoNotFound
}
func (NopDebuginfodClients) GetSource(context.Context, string, string, string) (io.ReadCloser, error) {
return io.NopCloser(bytes.NewReader(nil)), ErrDebuginfoNotFound
}
func (NopDebuginfodClients) Exists(context.Context, string) ([]string, error) {
return nil, nil
}
type DebuginfodClient interface {
Get(ctx context.Context, buildid string) (io.ReadCloser, error)
GetSource(ctx context.Context, buildid, file string) (io.ReadCloser, error)
Exists(ctx context.Context, buildid string) (bool, error)
}
type NopDebuginfodClient struct{}
func (NopDebuginfodClient) Get(context.Context, string) (io.ReadCloser, error) {
return io.NopCloser(bytes.NewReader(nil)), ErrDebuginfoNotFound
}
func (NopDebuginfodClient) GetSource(context.Context, string, string) (io.ReadCloser, error) {
return io.NopCloser(bytes.NewReader(nil)), ErrDebuginfoNotFound
}
func (NopDebuginfodClient) Exists(context.Context, string) (bool, error) {
return false, nil
}
type DebuginfodClientConfig struct {
Host string
Client DebuginfodClient
}
type ParallelDebuginfodClients struct {
clientsMap map[string]DebuginfodClient
clients []DebuginfodClientConfig
}
func NewDebuginfodClients(
logger log.Logger,
reg prometheus.Registerer,
tracerProvider trace.TracerProvider,
upstreamServerHosts []string,
rt http.RoundTripper,
timeout time.Duration,
bucket objstore.Bucket,
) DebuginfodClients {
clients := make([]DebuginfodClientConfig, 0, len(upstreamServerHosts))
for _, host := range upstreamServerHosts {
clients = append(clients, DebuginfodClientConfig{
Host: host,
Client: NewDebuginfodTracingClient(
tracerProvider.Tracer("debuginfod-client"),
NewDebuginfodExistsClientCache(
prometheus.WrapRegistererWith(prometheus.Labels{"cache": "debuginfod_exists", "debuginfod_host": host}, reg),
8*1024,
NewDebuginfodClientWithObjectStorageCache(
logger,
objstore.NewPrefixedBucket(bucket, host),
NewHTTPDebuginfodClient(
tracerProvider,
&http.Client{
Timeout: timeout,
Transport: promhttp.InstrumentRoundTripperCounter(
promauto.With(reg).NewCounterVec(prometheus.CounterOpts{
Name: "parca_debuginfo_client_requests_total",
Help: "Total number of requests sent by the debuginfo client.",
ConstLabels: prometheus.Labels{
"debuginfod_host": host,
},
}, []string{"code", "method"}),
rt,
),
},
url.URL{Scheme: "https", Host: host},
),
),
),
),
})
}
return NewParallelDebuginfodClients(clients)
}
func NewParallelDebuginfodClients(clients []DebuginfodClientConfig) *ParallelDebuginfodClients {
clientsMap := make(map[string]DebuginfodClient, len(clients))
for _, c := range clients {
clientsMap[c.Host] = c.Client
}
return &ParallelDebuginfodClients{
clientsMap: clientsMap,
clients: clients,
}
}
func (c *ParallelDebuginfodClients) Get(ctx context.Context, server, buildid string) (io.ReadCloser, error) {
client, ok := c.clientsMap[server]
if !ok {
return nil, fmt.Errorf("no client for server %q", server)
}
return client.Get(ctx, buildid)
}
func (c *ParallelDebuginfodClients) GetSource(ctx context.Context, server, buildid, file string) (io.ReadCloser, error) {
client, ok := c.clientsMap[server]
if !ok {
return nil, fmt.Errorf("no client for server %q", server)
}
return client.GetSource(ctx, buildid, file)
}
func (c *ParallelDebuginfodClients) Exists(ctx context.Context, buildid string) ([]string, error) {
availability := make([]bool, len(c.clients))
availabilityCount := 0
var g sync.WaitGroup
for i, cfg := range c.clients {
g.Add(1)
go func(i int, cfg DebuginfodClientConfig) {
defer g.Done()
exists, err := cfg.Client.Exists(ctx, buildid)
if err != nil {
// Error is already recorded in the debuginfod client tracing.
return
}
if exists {
availability[i] = true
availabilityCount++
}
}(i, cfg)
}
g.Wait()
// We do this to preserve the order of servers as we want the order to
// preserve the precedence.
res := make([]string, 0, availabilityCount)
for i, cfg := range c.clients {
if availability[i] {
res = append(res, cfg.Host)
}
}
return res, nil
}
type HTTPDebuginfodClient struct {
tp trace.TracerProvider
tracer trace.Tracer
client *http.Client
upstreamServer url.URL
}
type DebuginfodClientObjectStorageCache struct {
logger log.Logger
client DebuginfodClient
bucket objstore.Bucket
}
// NewHTTPDebuginfodClient returns a new HTTP debug info client.
func NewHTTPDebuginfodClient(
tp trace.TracerProvider,
client *http.Client,
url url.URL,
) *HTTPDebuginfodClient {
return &HTTPDebuginfodClient{
tracer: tp.Tracer("debuginfod-http-client"),
tp: tp,
upstreamServer: url,
client: client,
}
}
// NewDebuginfodClientWithObjectStorageCache creates a new DebuginfodClient that caches the debug information in the object storage.
func NewDebuginfodClientWithObjectStorageCache(
logger log.Logger,
bucket objstore.Bucket,
client DebuginfodClient,
) DebuginfodClient {
return &DebuginfodClientObjectStorageCache{
client: client,
bucket: bucket,
logger: logger,
}
}
// Get returns debuginfo for given buildid while caching it in object storage.
func (c *DebuginfodClientObjectStorageCache) Get(ctx context.Context, buildID string) (io.ReadCloser, error) {
rc, err := c.bucket.Get(ctx, objectPath(buildID, debuginfopb.DebuginfoType_DEBUGINFO_TYPE_DEBUGINFO_UNSPECIFIED))
if err != nil {
if c.bucket.IsObjNotFoundErr(err) {
return c.getAndCache(ctx, buildID)
}
return nil, err
}
return rc, nil
}
// GetSource returns source file for given buildid and file while caching it in object storage.
func (c *DebuginfodClientObjectStorageCache) GetSource(ctx context.Context, buildID, file string) (io.ReadCloser, error) {
rc, err := c.bucket.Get(ctx, debuginfodSourcePath(buildID, file))
if err != nil {
if c.bucket.IsObjNotFoundErr(err) {
return c.getSourceAndCache(ctx, buildID, file)
}
return nil, err
}
return rc, nil
}
func (c *DebuginfodClientObjectStorageCache) getAndCache(ctx context.Context, buildID string) (io.ReadCloser, error) {
r, err := c.client.Get(ctx, buildID)
if err != nil {
return nil, err
}
defer r.Close()
if err := c.bucket.Upload(ctx, objectPath(buildID, debuginfopb.DebuginfoType_DEBUGINFO_TYPE_DEBUGINFO_UNSPECIFIED), r); err != nil {
level.Error(c.logger).Log("msg", "failed to upload downloaded debuginfod file", "err", err, "build_id", buildID)
}
r, err = c.bucket.Get(ctx, objectPath(buildID, debuginfopb.DebuginfoType_DEBUGINFO_TYPE_DEBUGINFO_UNSPECIFIED))
if err != nil {
return nil, err
}
return r, nil
}
func (c *DebuginfodClientObjectStorageCache) getSourceAndCache(ctx context.Context, buildID, file string) (io.ReadCloser, error) {
r, err := c.client.GetSource(ctx, buildID, file)
if err != nil {
return nil, err
}
defer r.Close()
if err := c.bucket.Upload(ctx, debuginfodSourcePath(buildID, file), r); err != nil {
level.Error(c.logger).Log("msg", "failed to upload downloaded debuginfod file", "err", err, "build_id", buildID, "file", file)
}
r, err = c.bucket.Get(ctx, debuginfodSourcePath(buildID, file))
if err != nil {
return nil, err
}
return r, nil
}
// Exists returns true if debuginfo for given buildid exists.
func (c *DebuginfodClientObjectStorageCache) Exists(ctx context.Context, buildID string) (bool, error) {
exists, err := c.bucket.Exists(ctx, objectPath(buildID, debuginfopb.DebuginfoType_DEBUGINFO_TYPE_DEBUGINFO_UNSPECIFIED))
if err != nil {
return false, err
}
if exists {
return true, nil
}
return c.client.Exists(ctx, buildID)
}
// Get returns debug information file for given buildID by downloading it from upstream servers.
func (c *HTTPDebuginfodClient) Get(ctx context.Context, buildID string) (io.ReadCloser, error) {
return c.debuginfoRequest(ctx, buildID)
}
func (c *HTTPDebuginfodClient) debuginfoRequest(ctx context.Context, buildID string) (io.ReadCloser, error) {
// https://www.mankier.com/8/debuginfod#Webapi
// Endpoint: /buildid/BUILDID/debuginfo
// If the given buildid is known to the server,
// this request will result in a binary object that contains the customary .*debug_* sections.
u := c.upstreamServer
u.Path = path.Join(u.Path, "buildid", buildID, "debuginfo")
return c.request(ctx, u.String())
}
// GetSource returns source file for given buildID and file by downloading it from upstream servers.
func (c *HTTPDebuginfodClient) GetSource(ctx context.Context, buildID, file string) (io.ReadCloser, error) {
// https://www.mankier.com/8/debuginfod#Webapi
// Endpoint: /buildid/BUILDID/source/FILE
// If the given buildid and file combination is known to the server,
// this request will result in a text file that contains the source code.
u := c.upstreamServer
u.Path = path.Join(u.Path, "buildid", buildID, "source", file)
return c.request(ctx, u.String())
}
func (c *HTTPDebuginfodClient) request(ctx context.Context, fullUrl string) (io.ReadCloser, error) {
ctx = httptrace.WithClientTrace(ctx, otelhttptrace.NewClientTrace(ctx, otelhttptrace.WithTracerProvider(c.tp)))
resp, err := c.doRequest(ctx, fullUrl)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
return c.handleResponse(ctx, resp)
}
func (c *HTTPDebuginfodClient) Exists(ctx context.Context, buildID string) (bool, error) {
r, err := c.Get(ctx, buildID)
if err != nil {
if err == ErrDebuginfoNotFound {
return false, nil
}
return false, err
}
return true, r.Close()
}
func (c *HTTPDebuginfodClient) doRequest(ctx context.Context, url string) (*http.Response, error) {
ctx, span := c.tracer.Start(ctx, "debuginfod-http-request")
defer span.End()
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return nil, fmt.Errorf("create request: %w", err)
}
span.SetAttributes(attribute.String("http.url.host", req.URL.Host))
span.SetAttributes(attribute.String("http.url", req.URL.String()))
resp, err := c.client.Do(req)
if err != nil {
span.RecordError(err)
return nil, err
}
span.SetAttributes(attribute.Int("http.status_code", resp.StatusCode))
return resp, nil
}
func (c *HTTPDebuginfodClient) handleResponse(ctx context.Context, resp *http.Response) (io.ReadCloser, error) {
var err error
// Follow at most 2 redirects.
for i := 0; i < 2; i++ {
switch resp.StatusCode / 100 {
case 2:
return resp.Body, nil
case 3:
resp, err = c.doRequest(ctx, resp.Header.Get("Location"))
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
continue
case 4:
if resp.StatusCode == http.StatusNotFound {
return nil, ErrDebuginfoNotFound
}
return nil, fmt.Errorf("client error: %s", resp.Status)
case 5:
return nil, fmt.Errorf("server error: %s", resp.Status)
default:
return nil, fmt.Errorf("unexpected status code: %s", resp.Status)
}
}
return nil, errors.New("too many redirects")
}
type debuginfodResponse struct {
lastResponseTime time.Time
lastResponseError error
lastResponse bool
}
type DebuginfodExistsClientCache struct {
lruCache *cache.LRUCache[string, debuginfodResponse]
client DebuginfodClient
}
func NewDebuginfodExistsClientCache(
reg prometheus.Registerer,
cacheSize int,
client DebuginfodClient,
) *DebuginfodExistsClientCache {
return &DebuginfodExistsClientCache{
lruCache: cache.NewLRUCache[string, debuginfodResponse](reg, cacheSize),
client: client,
}
}
func (c *DebuginfodExistsClientCache) Get(ctx context.Context, buildID string) (io.ReadCloser, error) {
return c.client.Get(ctx, buildID)
}
func (c *DebuginfodExistsClientCache) GetSource(ctx context.Context, buildID, file string) (io.ReadCloser, error) {
return c.client.GetSource(ctx, buildID, file)
}
func (c *DebuginfodExistsClientCache) Exists(ctx context.Context, buildID string) (bool, error) {
if v, ok := c.lruCache.Get(buildID); ok {
if v.lastResponseError == nil || time.Since(v.lastResponseTime) < 10*time.Minute {
// If there was no error in the last response then we can safely
// return the cached value. That means we definitively know whether
// the build ID exists or not. If there was an error in the last
// response then we use this as a backoff mechanism to only try the
// same build ID once every 10 minutes.
return v.lastResponse, v.lastResponseError
}
// This means we saw an error last time trying and the 10 minute back
// off has expired.
}
exists, err := c.client.Exists(ctx, buildID)
c.lruCache.Add(buildID, debuginfodResponse{
lastResponseTime: time.Now(),
lastResponseError: err,
lastResponse: exists,
})
return exists, err
}
type DebuginfodTracingClient struct {
tracer trace.Tracer
client DebuginfodClient
}
func NewDebuginfodTracingClient(
tracer trace.Tracer,
client DebuginfodClient,
) *DebuginfodTracingClient {
return &DebuginfodTracingClient{
tracer: tracer,
client: client,
}
}
func (c *DebuginfodTracingClient) Get(ctx context.Context, buildID string) (io.ReadCloser, error) {
ctx, span := c.tracer.Start(ctx, "DebuginfodClient.Get")
defer span.End()
span.SetAttributes(attribute.String("buildid", buildID))
return c.client.Get(ctx, buildID)
}
func (c *DebuginfodTracingClient) GetSource(ctx context.Context, buildID, file string) (io.ReadCloser, error) {
ctx, span := c.tracer.Start(ctx, "DebuginfodClient.GetSource")
defer span.End()
span.SetAttributes(attribute.String("buildid", buildID))
span.SetAttributes(attribute.String("file", file))
return c.client.GetSource(ctx, buildID, file)
}
func (c *DebuginfodTracingClient) Exists(ctx context.Context, buildID string) (bool, error) {
ctx, span := c.tracer.Start(ctx, "DebuginfodClient.Exists")
defer span.End()
span.SetAttributes(attribute.String("buildid", buildID))
return c.client.Exists(ctx, buildID)
}