-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathcolumnarcomponent.go
586 lines (490 loc) · 14.7 KB
/
columnarcomponent.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
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
package gocbcore
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"github.com/google/uuid"
"io"
"math"
"math/rand"
"net"
"net/http"
"sync"
"time"
)
// ColumnarQueryOptions represents the various options available for a columnar query.
type ColumnarQueryOptions struct {
Payload map[string]interface{}
Priority *int
// Internal: This should never be used and is not supported.
User string
TraceContext RequestSpanContext
}
// ColumnarRowReader providers access to the rows of a columnar query
type ColumnarRowReader struct {
streamer *queryStreamer
statement string
endpoint string
statusCode int
peeked []byte
}
// NextRow reads the next rows bytes from the stream
func (q *ColumnarRowReader) NextRow() []byte {
if len(q.peeked) > 0 {
peeked := q.peeked
q.peeked = nil
return peeked
}
return q.streamer.NextRow()
}
// Err returns any errors that occurred during streaming.
func (q *ColumnarRowReader) Err() error {
err := q.streamer.Err()
if err != nil {
return err
}
meta, metaErr := q.streamer.MetaData()
if metaErr != nil {
return metaErr
}
cErr := parseColumnarErrorResponse(meta, q.statement, q.endpoint, q.statusCode, 0, "")
if cErr != nil {
return cErr
}
return nil
}
// MetaData fetches the non-row bytes streamed in the response.
func (q *ColumnarRowReader) MetaData() ([]byte, error) {
return q.streamer.MetaData()
}
// Close immediately shuts down the connection
func (q *ColumnarRowReader) Close() error {
return q.streamer.Close()
}
type columnarComponent struct {
cli *http.Client
muxer *columnarMux
userAgent string
// We can't use an atomic here because error can be different types.
bootstrapErrLock sync.Mutex
bootstrapErr error
}
type columnarComponentProps struct {
UserAgent string
}
type columnarHTTPClientProps struct {
ConnectTimeout time.Duration
MaxIdleConns int
MaxIdleConnsPerHost int
IdleTimeout time.Duration
MaxConnsPerHost int
}
func newColumnarComponent(props columnarComponentProps, clientProps columnarHTTPClientProps, muxer *columnarMux) *columnarComponent {
cc := &columnarComponent{
muxer: muxer,
userAgent: props.UserAgent,
}
cc.cli = cc.createHTTPClient(clientProps.MaxIdleConns, clientProps.MaxIdleConnsPerHost, clientProps.MaxConnsPerHost,
clientProps.IdleTimeout, clientProps.ConnectTimeout)
return cc
}
func (cc *columnarComponent) SetBootstrapError(err error) {
if errors.Is(err, ErrTimeout) {
return
}
cc.bootstrapErrLock.Lock()
cc.bootstrapErr = err
cc.bootstrapErrLock.Unlock()
}
func (cc *columnarComponent) Close() {
if tsport, ok := cc.cli.Transport.(*http.Transport); ok {
tsport.CloseIdleConnections()
} else {
logDebugf("Could not close idle connections for transport")
}
}
func (cc *columnarComponent) Query(ctx context.Context, opts ColumnarQueryOptions) (*ColumnarRowReader, error) {
if ctx == nil {
ctx = context.Background()
}
statement := getMapValueString(opts.Payload, "statement", "")
body, err := json.Marshal(opts.Payload)
if err != nil {
return nil, fmt.Errorf("failed to marshal query payload: %v", err)
}
header := make(http.Header)
header.Set("Content-Type", "application/json")
if len(opts.User) > 0 {
header.Set("cb-on-behalf-of", opts.User)
}
if opts.Priority != nil {
header.Set("Analytics-Priority", fmt.Sprintf("%d", *opts.Priority))
}
ctxDeadline, _ := ctx.Deadline()
var serverTimeout time.Duration
st, ok := opts.Payload["timeout"]
if ok {
var err error
serverTimeout, err = time.ParseDuration(st.(string))
if err != nil {
return nil, fmt.Errorf("failed to parse server timeout: %v", err)
}
}
err = cc.waitForConfig(ctx, serverTimeout)
if err != nil {
return nil, newColumnarError(err, statement, "", 0).withWasNotDispatched()
}
var uniqueID string
clientContextID, ok := opts.Payload["client_context_id"]
if ok {
uniqueID = clientContextID.(string)
} else {
uniqueID = uuid.NewString()
}
var lastCode uint32
var lastMessage string
var retries uint32
backoff := columnarExponentialBackoffWithJitter(100*time.Millisecond, 1*time.Minute, 2)
var denylist []string
for {
routeEp, err := cc.getColumnarEp(denylist)
if err != nil {
return nil, err
}
endpoint := routeEp.Address
auth := cc.muxer.Auth()
if auth == nil {
// Shouldn't happen but if it does then probably better to not panic with a nil pointer.
return nil, errCliInternalError
}
creds, err := auth.Credentials(AuthCredsRequest{
Service: CbasService,
Endpoint: endpoint,
})
if err != nil {
denylist = append(denylist, endpoint)
continue
}
reqURI := fmt.Sprintf("%s/api/v1/request", endpoint)
req, err := http.NewRequestWithContext(ctx, "POST", reqURI, io.NopCloser(bytes.NewReader(body)))
if err != nil {
return nil, err
}
req.Header = header
req.SetBasicAuth(creds[0].Username, creds[0].Password)
// we can't close the body of this response as it's long-lived beyond the function
logSchedf("Writing HTTP request to %s ID=%s", req.URL, uniqueID)
resp, err := cc.cli.Do(req) // nolint: bodyclose
if err != nil {
logDebugf("Received HTTP Response for ID=%s, errored: %v", uniqueID, err)
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return nil, newColumnarError(err, statement, endpoint, 0)
}
newBody, err := handleMaybeRetryColumnar(ctxDeadline, serverTimeout, backoff, retries, opts.Payload)
if err != nil {
return nil, newColumnarError(err, statement, endpoint, 0).withLastDetail(lastCode, lastMessage)
}
body = newBody
retries++
continue
}
logDebugf("Received HTTP Response for ID=%s, status code: %v", uniqueID, resp.StatusCode)
resp = wrapHttpResponse(resp) // nolint: bodyclose
if resp.StatusCode != 200 {
respBody, readErr := io.ReadAll(resp.Body)
if readErr != nil {
return nil, newColumnarError(fmt.Errorf("failed to read response body: %s", readErr), statement, endpoint, resp.StatusCode)
}
cErr := parseColumnarErrorResponse(respBody, statement, endpoint, resp.StatusCode, lastCode, lastMessage)
if cErr != nil {
first, retriable := isColumnarErrorRetriable(cErr)
if !retriable {
return nil, cErr
}
if first != nil {
lastCode = first.Code
lastMessage = first.Message
}
newBody, err := handleMaybeRetryColumnar(ctxDeadline, serverTimeout, backoff, retries, opts.Payload)
if err != nil {
return nil, newColumnarError(err, statement, endpoint, resp.StatusCode).
withErrors(cErr.Errors).
withErrorText(string(respBody)).
withLastDetail(lastCode, lastMessage)
}
body = newBody
retries++
continue
}
return nil, newColumnarError(
fmt.Errorf("query returned non-200 status code but no errors in body"),
statement,
endpoint,
resp.StatusCode).
withErrorText(string(respBody)).
withLastDetail(lastCode, lastMessage)
}
streamer, err := newQueryStreamer(resp.Body, "results")
if err != nil {
respBody, readErr := io.ReadAll(resp.Body)
if readErr != nil {
logDebugf("Failed to read response body: %v", readErr)
}
return nil, ColumnarError{
InnerError: fmt.Errorf("failed to parse success response body: %s", readErr),
Statement: statement,
Errors: nil,
Endpoint: endpoint,
ErrorText: string(respBody),
HTTPResponseCode: resp.StatusCode,
}
}
peeked := streamer.NextRow()
if peeked == nil {
err := streamer.Err()
if err != nil {
return nil, ColumnarError{
InnerError: err,
Statement: statement,
Errors: nil,
Endpoint: endpoint,
ErrorText: "",
HTTPResponseCode: resp.StatusCode,
}
}
meta, metaErr := streamer.MetaData()
if metaErr != nil {
return nil, ColumnarError{
InnerError: metaErr,
Statement: statement,
Errors: nil,
Endpoint: endpoint,
ErrorText: "",
HTTPResponseCode: resp.StatusCode,
}
}
cErr := parseColumnarErrorResponse(meta, statement, endpoint, resp.StatusCode, lastCode, lastMessage)
if cErr != nil {
first, retriable := isColumnarErrorRetriable(cErr)
if !retriable {
return nil, cErr
}
if first != nil {
lastCode = first.Code
lastMessage = first.Message
}
newBody, err := handleMaybeRetryColumnar(ctxDeadline, serverTimeout, backoff, retries, opts.Payload)
if err != nil {
return nil, newColumnarError(err, statement, endpoint, resp.StatusCode).
withErrors(cErr.Errors).
withErrorText(string(meta)).
withLastDetail(lastCode, lastMessage)
}
body = newBody
retries++
continue
}
}
return &ColumnarRowReader{
streamer: streamer,
statement: statement,
endpoint: endpoint,
statusCode: resp.StatusCode,
peeked: peeked,
}, nil
}
}
func (cc *columnarComponent) getColumnarEp(denylist []string) (routeEndpoint, error) {
return randFromServiceEndpoints(cc.muxer.ColumnarEps(), denylist)
}
func parseColumnarErrorResponse(respBody []byte, statement, endpoint string, statusCode int, lastCode uint32, lastMsg string) *ColumnarError {
var rawRespParse jsonAnalyticsErrorResponse
parseErr := json.Unmarshal(respBody, &rawRespParse)
if parseErr != nil {
return newColumnarError(fmt.Errorf("failed to parse response errors: %s", parseErr), statement, endpoint, statusCode).
withLastDetail(lastCode, lastMsg).
withErrorText(string(respBody))
}
if len(rawRespParse.Errors) == 0 {
return nil
}
var respParse []jsonAnalyticsError
parseErr = json.Unmarshal(rawRespParse.Errors, &respParse)
if parseErr != nil {
return newColumnarError(fmt.Errorf("failed to parse response errors: %s", parseErr), statement, endpoint, statusCode).
withLastDetail(lastCode, lastMsg).
withErrorText(string(respBody))
}
if len(respParse) == 0 {
return nil
}
errDescs := make([]ColumnarErrorDesc, len(respParse))
for i, jsonErr := range respParse {
errDescs[i] = ColumnarErrorDesc{
Code: jsonErr.Code,
Message: jsonErr.Msg,
Retry: jsonErr.Retry,
}
}
return newColumnarError(errColumnar, statement, endpoint, statusCode).
withLastDetail(lastCode, lastMsg).
withErrorText(string(respBody)).
withErrors(errDescs)
}
func isColumnarErrorRetriable(cErr *ColumnarError) (*ColumnarErrorDesc, bool) {
var first *ColumnarErrorDesc
allRetriable := true
for _, err := range cErr.Errors {
if !err.Retry {
allRetriable = false
if first == nil {
first = &ColumnarErrorDesc{
Code: err.Code,
Message: err.Message,
}
}
}
}
if !allRetriable {
return nil, false
}
if first == nil && len(cErr.Errors) > 0 {
first = &cErr.Errors[0]
}
return first, true
}
// Note in the interest of keeping this signature sane, we return a raw base error here.
func handleMaybeRetryColumnar(ctxDeadline time.Time, serverTimeout time.Duration, calc BackoffCalculator,
retries uint32, payload map[string]interface{}) ([]byte, error) {
b := calc(retries)
var body []byte
if !ctxDeadline.IsZero() {
if time.Now().Add(b).Before(ctxDeadline.Add(-b)) {
return nil, errDeadlineWouldBeExceeded
}
}
if serverTimeout > 0 {
if time.Now().Add(b).Before(time.Now().Add(serverTimeout)) {
return nil, errTimeout
}
serverTimeout = serverTimeout - b
payload["timeout"] = serverTimeout.String()
var err error
body, err = json.Marshal(payload)
if err != nil {
logWarnf("Failed to marshal query payload: %v", err)
}
}
time.Sleep(b)
return body, nil
}
func (cc *columnarComponent) createHTTPClient(maxIdleConns, maxIdleConnsPerHost, maxConnsPerHost int, idleTimeout time.Duration, connectTimeout time.Duration) *http.Client {
httpDialer := &net.Dialer{
Timeout: connectTimeout,
KeepAlive: 30 * time.Second,
}
// We set ForceAttemptHTTP2, which will update the base-config to support HTTP2
// automatically, so that all configs from it will look for that.
httpTransport := &http.Transport{
ForceAttemptHTTP2: true,
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return httpDialer.DialContext(ctx, network, addr)
},
DialTLSContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
tcpConn, err := httpDialer.DialContext(ctx, network, addr)
if err != nil {
return nil, err
}
// We set up the transport to point at the BaseConfig from the dynamic TLS system.
httpTLSConfig := cc.muxer.Get().tlsConfig
if httpTLSConfig == nil {
return nil, errors.New("TLS is not configured on this Agent")
}
srvTLSConfig, err := httpTLSConfig.MakeForAddr(addr)
if err != nil {
return nil, err
}
tlsConn := tls.Client(tcpConn, srvTLSConfig)
return tlsConn, nil
},
MaxIdleConns: maxIdleConns,
MaxIdleConnsPerHost: maxIdleConnsPerHost,
IdleConnTimeout: idleTimeout,
MaxConnsPerHost: maxConnsPerHost,
}
httpCli := &http.Client{
Transport: httpTransport,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
// All that we're doing here is setting auth on any redirects.
// For that reason we can just pull it off the oldest (first) request.
if len(via) >= 10 {
// Just duplicate the default behaviour for maximum redirects.
return errors.New("stopped after 10 redirects")
}
oldest := via[0]
auth := oldest.Header.Get("Authorization")
if auth != "" {
req.Header.Set("Authorization", auth)
}
return nil
},
}
return httpCli
}
func (cc *columnarComponent) waitForConfig(ctx context.Context, queryTimeout time.Duration) error {
var timeoutCh <-chan time.Time
if queryTimeout > 0 {
timeoutCh = time.After(queryTimeout)
}
for {
revID, err := cc.muxer.ConfigRev()
if err != nil {
return err
}
if revID > -1 {
return nil
}
cc.bootstrapErrLock.Lock()
err = cc.bootstrapErr
cc.bootstrapErrLock.Unlock()
if err != nil {
return err
}
// We've not successfully been set up with a cluster map yet.
select {
case <-ctx.Done():
return ctx.Err()
case <-timeoutCh:
return errTimeout
case <-time.After(500 * time.Microsecond):
}
}
}
func columnarExponentialBackoffWithJitter(min, max time.Duration, backoffFactor float64) BackoffCalculator {
var minBackoff float64 = 1000000 // 1 Millisecond
var maxBackoff float64 = 500000000 // 500 Milliseconds
var factor float64 = 2
if min > 0 {
minBackoff = float64(min)
}
if max > 0 {
maxBackoff = float64(max)
}
if backoffFactor > 0 {
factor = backoffFactor
}
return func(retryAttempts uint32) time.Duration {
backoff := minBackoff * (math.Pow(factor, float64(retryAttempts)))
backoff = rand.Float64() * (backoff) // #nosec G404
if backoff > maxBackoff {
backoff = maxBackoff
}
if backoff < minBackoff {
backoff = minBackoff
}
return time.Duration(backoff)
}
}