-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
348 lines (311 loc) · 9.07 KB
/
client.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
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
// Copyright 2016 The Prometheus 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 otlp
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"net"
"net/url"
"strconv"
"strings"
"time"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/lightstep/opentelemetry-prometheus-sidecar/common"
"github.com/lightstep/opentelemetry-prometheus-sidecar/config"
"github.com/lightstep/opentelemetry-prometheus-sidecar/telemetry"
"github.com/lightstep/opentelemetry-prometheus-sidecar/telemetry/doevery"
metricsService "go.opentelemetry.io/proto/otlp/collector/metrics/v1"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
grpcMetadata "google.golang.org/grpc/metadata"
"google.golang.org/protobuf/proto"
)
const (
// serviceConfig copied from OTel-Go.
// https://github.com/open-telemetry/opentelemetry-go/blob/5ed96e92446d2d58d131e0672da613a84c16af7a/exporters/otlp/grpcoptions.go#L37
serviceConfig = `{
"methodConfig":[{
"name":[
{ "service":"opentelemetry.proto.collector.metrics.v1.MetricsService" },
{ "service":"opentelemetry.proto.collector.trace.v1.TraceService" }
],
"retryPolicy":{
"MaxAttempts":5,
"InitialBackoff":"0.3s",
"MaxBackoff":"5s",
"BackoffMultiplier":2,
"RetryableStatusCodes":[
"UNAVAILABLE",
"CANCELLED",
"DEADLINE_EXCEEDED",
"RESOURCE_EXHAUSTED",
"ABORTED",
"OUT_OF_RANGE",
"UNAVAILABLE",
"DATA_LOSS"
]
}
}]
}`
invalidTrailerPrefix = "otlp-invalid-"
)
var (
exportDuration = telemetry.NewTimer(
"sidecar.export.duration",
"duration of the otlp.Export() call",
)
connectDuration = telemetry.NewTimer(
"sidecar.connect.duration",
"duration of the grpc.Dial() call",
)
errNoSingleCount = fmt.Errorf("no single count")
)
// Client allows reading and writing from/to a remote gRPC endpoint. The
// implementation may hit a single backend, so the application should create a
// number of these clients.
type Client struct {
logger log.Logger
url *url.URL
timeout time.Duration
rootCertificates []string
headers grpcMetadata.MD
compressor string
prometheus config.PromConfig
invalidSet common.FailingReporter
conn *grpc.ClientConn
}
// ClientConfig configures a Client.
type ClientConfig struct {
Logger log.Logger
URL *url.URL
Timeout time.Duration
RootCertificates []string
Headers grpcMetadata.MD
Compressor string
Prometheus config.PromConfig
FailingReporter common.FailingReporter
}
// NewClient creates a new Client.
func NewClient(conf ClientConfig) *Client {
logger := conf.Logger
if logger == nil {
logger = log.NewNopLogger()
}
return &Client{
logger: logger,
url: conf.URL,
timeout: conf.Timeout,
rootCertificates: conf.RootCertificates,
headers: conf.Headers,
compressor: conf.Compressor,
prometheus: conf.Prometheus,
invalidSet: conf.FailingReporter,
}
}
// getConnection will dial a new connection if one is not set. When
// dialing, this function uses its a new context and the same timeout
// used for Store().
func (c *Client) getConnection(ctx context.Context) (_ *grpc.ClientConn, retErr error) {
if c.conn != nil {
return c.conn, nil
}
defer connectDuration.Start(ctx).Stop(&retErr)
ctx, cancel := context.WithTimeout(ctx, c.timeout)
defer cancel()
useAuth := c.url.Scheme != "http"
level.Debug(c.logger).Log(
"msg", "new OTLP connection",
"auth", useAuth,
"url", c.url.String(),
"timeout", c.timeout)
dopts := []grpc.DialOption{
grpc.WithBlock(), // Wait for the connection to be established before using it.
grpc.WithDefaultServiceConfig(serviceConfig),
// Note: The Sidecar->OTel gRPC connection is not traced:
// grpc.WithUnaryInterceptor(otelgrpc.UnaryClientInterceptor()),
}
if useAuth {
var tcfg tls.Config
if len(c.rootCertificates) != 0 {
certPool := x509.NewCertPool()
for _, cert := range c.rootCertificates {
bs, err := ioutil.ReadFile(cert)
if err != nil {
return nil, fmt.Errorf("could not read certificate authority certificate: %s: %w", cert, err)
}
ok := certPool.AppendCertsFromPEM(bs)
if !ok {
return nil, fmt.Errorf("could not parse certificate authority certificate: %s: %w", cert, err)
}
}
tcfg = tls.Config{
ServerName: c.url.Hostname(),
RootCAs: certPool,
}
}
level.Debug(c.logger).Log(
"msg", "TLS configured",
"server", c.url.Hostname(),
"root_certs", fmt.Sprint(c.rootCertificates),
)
dopts = append(dopts, grpc.WithTransportCredentials(credentials.NewTLS(&tcfg)))
} else {
dopts = append(dopts, grpc.WithInsecure())
}
if c.compressor != "" && c.compressor != "none" {
dopts = append(dopts, grpc.WithDefaultCallOptions(grpc.UseCompressor(c.compressor)))
}
address := c.url.Hostname()
if len(c.url.Port()) > 0 {
address = net.JoinHostPort(address, c.url.Port())
}
conn, err := grpc.DialContext(ctx, address, dopts...)
c.conn = conn
if err != nil {
level.Debug(c.logger).Log(
"msg", "connection status",
"address", address,
"err", err,
)
return nil, err
}
return conn, err
}
// Selftest sends an empty request the endpoint.
func (c *Client) Selftest(ctx context.Context) error {
// Loop until the context is canceled, allowing for retryable failures.
for {
conn, err := c.getConnection(ctx)
if err == nil {
service := metricsService.NewMetricsServiceClient(conn)
empty := &metricsService.ExportMetricsServiceRequest{}
_, err = service.Export(c.grpcMetadata(ctx), empty)
if err == nil {
return nil
}
}
select {
case <-ctx.Done():
return ctx.Err()
default:
if isRecoverable(err) {
level.Info(c.logger).Log("msg", "selftest recoverable error, still trying", "err", err)
continue
}
}
return fmt.Errorf(
"non-recoverable failure in selftest: %s",
truncateErrorString(err),
)
}
}
// Store sends a batch of samples to the endpoint.
func (c *Client) Store(req *metricsService.ExportMetricsServiceRequest) error {
tss := req.ResourceMetrics
if len(tss) == 0 {
// Nothing to do, return silently.
return nil
}
// Note the call to getConnection() applies its own timeout for Dial().
ctx := context.Background()
conn, err := c.getConnection(ctx)
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(ctx, c.timeout)
defer cancel()
service := metricsService.NewMetricsServiceClient(conn)
var md grpcMetadata.MD
defer exportDuration.Start(ctx).Stop(&err)
if _, err = service.Export(c.grpcMetadata(ctx), req, grpc.Trailer(&md)); err != nil {
doevery.TimePeriod(config.DefaultNoisyLogPeriod, func() {
level.Error(c.logger).Log(
"msg", "export failure",
"err", truncateErrorString(err),
"size", proto.Size(req),
"trailers", fmt.Sprint(md),
"recoverable", isRecoverable(err),
)
})
return err
}
// Note: Lightstep uses gRPC response Trailers to return
// information about validation errors following a successful
// Export when any points or metrics were dropped.
c.parseResponseMetadata(ctx, md)
doevery.TimePeriod(config.DefaultNoisyLogPeriod, func() {
level.Debug(c.logger).Log(
"msg", "successful write",
"size", proto.Size(req),
"trailers", fmt.Sprint(md),
)
})
return nil
}
func singleCount(values []string) (int, error) {
if len(values) != 1 {
return 0, errNoSingleCount
}
return strconv.Atoi(values[0])
}
func (c *Client) parseResponseMetadata(ctx context.Context, md grpcMetadata.MD) {
for key, values := range md {
key = strings.ToLower(key)
if !strings.HasPrefix(key, "otlp-") {
continue
}
if key == "otlp-points-dropped" {
if points, err := singleCount(values); err == nil {
common.DroppedPoints.Add(
ctx,
int64(points),
common.ReasonKey.String("validation"),
)
}
} else if key == "otlp-metrics-dropped" {
if points, err := singleCount(values); err == nil {
common.DroppedSeries.Add(
ctx,
int64(points),
common.ReasonKey.String("validation"),
)
}
} else if strings.HasPrefix(key, invalidTrailerPrefix) {
key = key[len(invalidTrailerPrefix):]
for _, metricName := range values {
c.invalidSet.Set(key, metricName)
}
} else {
doevery.TimePeriod(config.DefaultNoisyLogPeriod, func() {
level.Info(c.logger).Log(
"msg", "unrecognized trailer",
"key", key,
"values", fmt.Sprint(values),
)
})
}
}
}
func (c *Client) Close() error {
if c.conn == nil {
return nil
}
return c.conn.Close()
}
func (c *Client) grpcMetadata(ctx context.Context) context.Context {
return grpcMetadata.NewOutgoingContext(ctx, c.headers)
}