forked from DataDog/dd-trace-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
elastictrace.go
158 lines (145 loc) · 5.1 KB
/
elastictrace.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
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016 Datadog, Inc.
// Package elastic provides functions to trace the gopkg.in/olivere/elastic.v{3,5} packages.
package elastic // import "gopkg.in/DataDog/dd-trace-go.v1/contrib/olivere/elastic"
import (
"bufio"
"bytes"
"compress/gzip"
"errors"
"fmt"
"io"
"math"
"net/http"
"regexp"
"strconv"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
"gopkg.in/DataDog/dd-trace-go.v1/internal/log"
"gopkg.in/DataDog/dd-trace-go.v1/internal/telemetry"
)
const componentName = "olivere/elastic"
func init() {
telemetry.LoadIntegration(componentName)
tracer.MarkIntegrationImported("gopkg.in/olivere/elastic.v5")
tracer.MarkIntegrationImported("gopkg.in/olivere/elastic.v3")
}
// NewHTTPClient returns a new http.Client which traces requests under the given service name.
func NewHTTPClient(opts ...ClientOption) *http.Client {
cfg := new(clientConfig)
defaults(cfg)
for _, fn := range opts {
fn(cfg)
}
log.Debug("contrib/olivere/elastic: Configuring HTTP Client: %#v", cfg)
return &http.Client{Transport: &httpTransport{config: cfg}}
}
// httpTransport is a traced HTTP transport that captures Elasticsearch spans.
type httpTransport struct{ config *clientConfig }
// bodyCutoff specifies the maximum number of bytes that will be stored as a tag
// value obtained from an HTTP request or response body.
var bodyCutoff = 5 * 1024
// RoundTrip satisfies the RoundTripper interface, wraps the sub Transport and
// captures a span of the Elasticsearch request.
func (t *httpTransport) RoundTrip(req *http.Request) (*http.Response, error) {
url := req.URL.Path
method := req.Method
resource := t.config.resourceNamer(url, method)
opts := []ddtrace.StartSpanOption{
tracer.ServiceName(t.config.serviceName),
tracer.SpanType(ext.SpanTypeElasticSearch),
tracer.ResourceName(resource),
tracer.Tag("elasticsearch.method", method),
tracer.Tag("elasticsearch.url", url),
tracer.Tag("elasticsearch.params", req.URL.Query().Encode()),
tracer.Tag(ext.Component, componentName),
tracer.Tag(ext.SpanKind, ext.SpanKindClient),
tracer.Tag(ext.DBSystem, ext.DBSystemElasticsearch),
tracer.Tag(ext.NetworkDestinationName, req.URL.Hostname()),
}
if !math.IsNaN(t.config.analyticsRate) {
opts = append(opts, tracer.Tag(ext.EventSampleRate, t.config.analyticsRate))
}
span, _ := tracer.StartSpanFromContext(req.Context(), t.config.spanName, opts...)
defer span.Finish()
contentEncoding := req.Header.Get("Content-Encoding")
snip, rc, err := peek(req.Body, contentEncoding, int(req.ContentLength), bodyCutoff)
if err == nil {
span.SetTag("elasticsearch.body", snip)
}
req.Body = rc
// process using the standard transport
res, err := t.config.transport.RoundTrip(req)
if err != nil {
// roundtrip error
span.SetTag(ext.Error, err)
} else if res.StatusCode < 200 || res.StatusCode > 299 {
// HTTP error
snip, rc, err := peek(res.Body, contentEncoding, int(res.ContentLength), bodyCutoff)
if err != nil {
snip = http.StatusText(res.StatusCode)
}
span.SetTag(ext.Error, errors.New(snip))
res.Body = rc
}
if res != nil {
span.SetTag(ext.HTTPCode, strconv.Itoa(res.StatusCode))
}
return res, err
}
var (
idRegexp = regexp.MustCompile("/([0-9]+)([/\\?]|$)")
idPlaceholder = []byte("/?$2")
indexRegexp = regexp.MustCompile("[0-9]{2,}")
indexPlaceholder = []byte("?")
)
// quantize quantizes an Elasticsearch to extract a meaningful resource from the request.
// We quantize based on the method+url with some cleanup applied to the URL.
// URLs with an ID will be generalized as will (potential) timestamped indices.
func quantize(url, method string) string {
quantizedURL := idRegexp.ReplaceAll([]byte(url), idPlaceholder)
quantizedURL = indexRegexp.ReplaceAll(quantizedURL, indexPlaceholder)
return fmt.Sprintf("%s %s", method, quantizedURL)
}
// peek attempts to return the first n bytes, as a string, from the provided io.ReadCloser.
// It returns a new io.ReadCloser which points to the same underlying stream and can be read
// from to access the entire data including the snippet. max is used to specify the length
// of the stream contained in the reader. If unknown, it should be -1. If 0 < max < n it
// will override n.
func peek(rc io.ReadCloser, encoding string, max, n int) (string, io.ReadCloser, error) {
if rc == nil {
return "", rc, errors.New("empty stream")
}
if max > 0 && max < n {
n = max
}
r := bufio.NewReaderSize(rc, n)
rc2 := struct {
io.Reader
io.Closer
}{
Reader: r,
Closer: rc,
}
snip, err := r.Peek(n)
if err == io.EOF {
err = nil
}
if err != nil {
return string(snip), rc2, err
}
if encoding == "gzip" {
// unpack the snippet
gzr, err2 := gzip.NewReader(bytes.NewReader(snip))
if err2 != nil {
// snip wasn't gzip; return it as is
return string(snip), rc2, nil
}
defer gzr.Close()
snip, err = io.ReadAll(gzr)
}
return string(snip), rc2, err
}