forked from lightstep/lightstep-tracer-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
collector_client_http.go
221 lines (185 loc) · 5.71 KB
/
collector_client_http.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
package lightstep
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"time"
"github.com/gogo/protobuf/proto"
"github.com/lightstep/lightstep-tracer-common/golang/gogo/collectorpb"
)
var (
acceptHeader = http.CanonicalHeaderKey("Accept")
contentTypeHeader = http.CanonicalHeaderKey("Content-Type")
)
const (
collectorHTTPMethod = "POST"
collectorHTTPPath = "/api/v2/reports"
protoContentType = "application/octet-stream"
)
// grpcCollectorClient specifies how to send reports back to a LightStep
// collector via grpc.
type httpCollectorClient struct {
// auth and runtime information
reporterID uint64
accessToken string // accessToken is the access token used for explicit trace collection requests.
attributes map[string]string
tlsClientConfig *tls.Config
reportTimeout time.Duration
reportingPeriod time.Duration
// Remote service that will receive reports.
url *url.URL
client *http.Client
// converters
converter *protoConverter
}
type transportCloser struct {
*http.Transport
}
func (closer transportCloser) Close() error {
closer.CloseIdleConnections()
return nil
}
func newHTTPCollectorClient(
opts Options,
reporterID uint64,
attributes map[string]string,
) (*httpCollectorClient, error) {
url, err := url.Parse(opts.Collector.URL())
if err != nil {
fmt.Println("collector config does not produce valid url", err)
return nil, err
}
url.Path = collectorHTTPPath
tlsClientConfig, err := getTLSConfig(opts.Collector.CustomCACertFile)
if err != nil {
fmt.Println("failed to get TLSConfig: ", err)
return nil, err
}
return &httpCollectorClient{
reporterID: reporterID,
accessToken: opts.AccessToken,
attributes: attributes,
tlsClientConfig: tlsClientConfig,
reportTimeout: opts.ReportTimeout,
reportingPeriod: opts.ReportingPeriod,
url: url,
converter: newProtoConverter(opts),
}, nil
}
// getTLSConfig returns a *tls.Config according to whether a user has supplied a customCACertFile. If they have,
// we return a TLSConfig that uses the custom CA cert as the lone Root CA. If not, we return nil which http.Transport
// will interpret as the default system defined Root CAs.
func getTLSConfig(customCACertFile string) (*tls.Config, error) {
if len(customCACertFile) == 0 {
return nil, nil
}
caCerts := x509.NewCertPool()
cert, err := ioutil.ReadFile(customCACertFile)
if err != nil {
return nil, err
}
if !caCerts.AppendCertsFromPEM(cert) {
return nil, fmt.Errorf("credentials: failed to append certificate")
}
return &tls.Config{RootCAs: caCerts}, nil
}
func (client *httpCollectorClient) ConnectClient() (Connection, error) {
// Use a transport independent from http.DefaultTransport to provide sane
// defaults that make sense in the context of the lightstep client. The
// differences are mostly on setting timeouts based on the report timeout
// and period.
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: client.reportTimeout / 2,
DualStack: true,
}).DialContext,
// The collector responses are very small, there is no point asking for
// a compressed payload, explicitly disabling it.
DisableCompression: true,
IdleConnTimeout: 2 * client.reportingPeriod,
TLSHandshakeTimeout: client.reportTimeout / 2,
ResponseHeaderTimeout: client.reportTimeout,
ExpectContinueTimeout: client.reportTimeout,
MaxResponseHeaderBytes: 64 * 1024, // 64 KB, just a safeguard
TLSClientConfig: client.tlsClientConfig,
}
client.client = &http.Client{
Transport: transport,
Timeout: client.reportTimeout,
}
return transportCloser{transport}, nil
}
func (client *httpCollectorClient) ShouldReconnect() bool {
// http.Transport will handle connection reuse under the hood
return false
}
func (client *httpCollectorClient) Report(context context.Context, req reportRequest) (collectorResponse, error) {
if req.httpRequest == nil {
return nil, fmt.Errorf("httpRequest cannot be null")
}
req.httpRequest.Header.Add(accessTokenHeader, client.accessToken)
httpResponse, err := client.client.Do(req.httpRequest.WithContext(context))
if err != nil {
return nil, err
}
defer httpResponse.Body.Close()
response, err := client.toResponse(httpResponse)
if err != nil {
return nil, err
}
return response, nil
}
func (client *httpCollectorClient) Translate(ctx context.Context, buffer *reportBuffer) (reportRequest, error) {
httpRequest, err := client.toRequest(ctx, buffer)
if err != nil {
return reportRequest{}, err
}
return reportRequest{
httpRequest: httpRequest,
}, nil
}
func (client *httpCollectorClient) toRequest(
context context.Context,
buffer *reportBuffer,
) (*http.Request, error) {
protoRequest := client.converter.toReportRequest(
client.reporterID,
client.attributes,
client.accessToken,
buffer,
)
buf, err := proto.Marshal(protoRequest)
if err != nil {
return nil, err
}
requestBody := bytes.NewReader(buf)
request, err := http.NewRequest(collectorHTTPMethod, client.url.String(), requestBody)
if err != nil {
return nil, err
}
request = request.WithContext(context)
request.Header.Set(contentTypeHeader, protoContentType)
request.Header.Set(acceptHeader, protoContentType)
return request, nil
}
func (client *httpCollectorClient) toResponse(response *http.Response) (collectorResponse, error) {
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("status code (%d) is not ok", response.StatusCode)
}
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
resp := &collectorpb.ReportResponse{}
if err := proto.Unmarshal(body, resp); err != nil {
return nil, err
}
return protoResponse{ReportResponse: resp}, nil
}