-
Notifications
You must be signed in to change notification settings - Fork 535
Expand file tree
/
Copy pathtransport.go
More file actions
209 lines (193 loc) · 7.09 KB
/
Copy pathtransport.go
File metadata and controls
209 lines (193 loc) · 7.09 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
// 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 tracer
import (
"bytes"
"fmt"
"io"
"net/http"
"runtime"
"strconv"
"strings"
"time"
pb "github.com/DataDog/datadog-agent/pkg/proto/pbgo/trace"
"github.com/DataDog/dd-trace-go/v2/ddtrace/internal/tracerstats"
"github.com/DataDog/dd-trace-go/v2/internal"
"github.com/DataDog/dd-trace-go/v2/internal/version"
"github.com/tinylib/msgp/msgp"
)
const (
// headerComputedTopLevel specifies that the client has marked top-level spans, when set.
// Any non-empty value will mean 'yes'.
headerComputedTopLevel = "Datadog-Client-Computed-Top-Level"
)
const (
defaultHostname = "localhost"
defaultPort = "8126"
defaultAddress = defaultHostname + ":" + defaultPort
defaultURL = "http://" + defaultAddress
defaultHTTPTimeout = 10 * time.Second // defines the current timeout before giving up with the send process
traceCountHeader = "X-Datadog-Trace-Count" // header containing the number of traces in the payload
obfuscationVersionHeader = "Datadog-Obfuscation-Version" // header containing the version of obfuscation used, if any
tracesAPIPath = "/v0.4/traces"
tracesAPIPathV1 = "/v1.0/traces"
statsAPIPath = "/v0.6/stats"
)
// ddTransport is an interface for communicating data to the Datadog agent
// using Datadog-specific protocols (msgpack traces, stats payloads).
type ddTransport interface {
// send sends the msgpack-encoded payload p to the agent using the transport set up.
// It returns a non-nil response body when no error occurred.
send(p payload) (body io.ReadCloser, err error)
// sendStats sends the given stats payload to the agent.
// tracerObfuscationVersion is the version of obfuscation applied (0 if none was applied)
sendStats(s *pb.ClientStatsPayload, tracerObfuscationVersion int) error
// endpoint returns the URL to which the transport will send traces.
endpoint() string
}
type httpTransport struct {
traceURL string // the delivery URL for traces
statsURL string // the delivery URL for stats
client *http.Client // the HTTP client used in the POST
headers map[string]string // the Transport headers
}
// newHTTPTransport returns a new Transport implementation that sends traces
// to the given traceURL and stats to the given statsURL, using the provided
// *http.Client and headers. The caller is responsible for providing the
// appropriate headers (e.g. datadogHeaders() for Datadog mode, or OTLP
// headers resolved from config).
func newHTTPTransport(traceURL string, statsURL string, client *http.Client, headers map[string]string) *httpTransport {
return &httpTransport{
traceURL: traceURL,
statsURL: statsURL,
client: client,
headers: headers,
}
}
func datadogHeaders() map[string]string {
h := map[string]string{
"Datadog-Meta-Lang": "go",
"Datadog-Meta-Lang-Version": strings.TrimPrefix(runtime.Version(), "go"),
"Datadog-Meta-Lang-Interpreter": runtime.Compiler + "-" + runtime.GOARCH + "-" + runtime.GOOS,
"Datadog-Meta-Tracer-Version": version.Tag,
"Content-Type": "application/msgpack",
}
if cid := internal.ContainerID(); cid != "" {
h["Datadog-Container-ID"] = cid
}
if eid := internal.EntityID(); eid != "" {
h["Datadog-Entity-ID"] = eid
}
if extEnv := internal.ExternalEnvironment(); extEnv != "" {
h["Datadog-External-Env"] = extEnv
}
return h
}
func (t *httpTransport) sendStats(p *pb.ClientStatsPayload, tracerObfuscationVersion int) error {
var buf bytes.Buffer
if err := msgp.Encode(&buf, p); err != nil {
return err
}
req, err := http.NewRequest("POST", t.statsURL, &buf)
if err != nil {
return err
}
for header, value := range t.headers {
req.Header.Set(header, value)
}
if tracerObfuscationVersion > 0 {
req.Header.Set(obfuscationVersionHeader, strconv.Itoa(tracerObfuscationVersion))
}
resp, err := t.client.Do(req)
if err != nil {
reportAPIErrorsMetric(resp, err, statsAPIPath)
return err
}
defer resp.Body.Close()
if code := resp.StatusCode; code >= 400 {
reportAPIErrorsMetric(resp, err, statsAPIPath)
// error, check the body for context information and
// return a nice error.
msg := make([]byte, 1000)
n, _ := resp.Body.Read(msg)
resp.Body.Close()
txt := http.StatusText(code)
if n > 0 {
return fmt.Errorf("%s (Status: %s)", msg[:n], txt)
}
return fmt.Errorf("%s", txt)
}
return nil
}
func (t *httpTransport) send(p payload) (body io.ReadCloser, err error) {
req, err := http.NewRequest("POST", t.traceURL, p)
if err != nil {
return nil, fmt.Errorf("cannot create http request: %s", err)
}
stats := p.stats()
req.ContentLength = int64(stats.size)
for header, value := range t.headers {
req.Header.Set(header, value)
}
req.Header.Set(traceCountHeader, strconv.Itoa(stats.itemCount))
req.Header.Set(headerComputedTopLevel, "t")
if t := getGlobalTracer(); t != nil {
tc := t.TracerConf()
if tc.TracingAsTransport || tc.CanComputeStats {
// tracingAsTransport uses this header to disable the trace agent's stats computation
// while making canComputeStats() always false to also disable client stats computation.
req.Header.Set("Datadog-Client-Computed-Stats", "t")
}
droppedTraces := int(tracerstats.Count(tracerstats.AgentDroppedP0Traces))
partialTraces := int(tracerstats.Count(tracerstats.PartialTraces))
droppedSpans := int(tracerstats.Count(tracerstats.AgentDroppedP0Spans))
if tt, ok := t.(*tracer); ok {
if stats := tt.statsd; stats != nil {
stats.Count("datadog.tracer.dropped_p0_traces", int64(droppedTraces),
[]string{fmt.Sprintf("partial:%s", strconv.FormatBool(partialTraces > 0))}, 1)
stats.Count("datadog.tracer.dropped_p0_spans", int64(droppedSpans), nil, 1)
}
}
req.Header.Set("Datadog-Client-Dropped-P0-Traces", strconv.Itoa(droppedTraces))
req.Header.Set("Datadog-Client-Dropped-P0-Spans", strconv.Itoa(droppedSpans))
}
response, err := t.client.Do(req)
if err != nil {
reportAPIErrorsMetric(response, err, tracesAPIPath)
return nil, err
}
if code := response.StatusCode; code >= 400 {
reportAPIErrorsMetric(response, err, tracesAPIPath)
// error, check the body for context information and
// return a nice error.
msg := make([]byte, 1000)
n, _ := response.Body.Read(msg)
response.Body.Close()
txt := http.StatusText(code)
if n > 0 {
return nil, fmt.Errorf("%s (Status: %s)", msg[:n], txt)
}
return nil, fmt.Errorf("%s", txt)
}
return response.Body, nil
}
func reportAPIErrorsMetric(response *http.Response, err error, endpoint string) {
if t, ok := getGlobalTracer().(*tracer); ok {
var reason string
if err != nil {
reason = "network_failure"
}
if response != nil {
reason = fmt.Sprintf("server_response_%d", response.StatusCode)
}
tags := []string{"reason:" + reason, "endpoint:" + endpoint}
t.statsd.Incr("datadog.tracer.api.errors", tags, 1)
} else {
return
}
}
func (t *httpTransport) endpoint() string {
return t.traceURL
}