-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathinput.go
1383 lines (1275 loc) · 43.4 KB
/
input.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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License;
// you may not use this file except in compliance with the Elastic License.
// Package cel implements an input that uses the Common Expression Language to
// perform requests and do endpoint processing of events. The cel package exposes
// the github.com/elastic/mito/lib CEL extension library.
package cel
import (
"compress/gzip"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"reflect"
"regexp"
"slices"
"strconv"
"strings"
"time"
"github.com/hashicorp/go-retryablehttp"
"github.com/icholy/digest"
"github.com/rcrowley/go-metrics"
"go.elastic.co/ecszap"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"golang.org/x/time/rate"
"github.com/google/cel-go/cel"
"github.com/google/cel-go/checker/decls"
"google.golang.org/protobuf/types/known/structpb"
v2 "github.com/elastic/beats/v7/filebeat/input/v2"
inputcursor "github.com/elastic/beats/v7/filebeat/input/v2/input-cursor"
"github.com/elastic/beats/v7/libbeat/beat"
"github.com/elastic/beats/v7/libbeat/feature"
"github.com/elastic/beats/v7/libbeat/management/status"
"github.com/elastic/beats/v7/libbeat/monitoring/inputmon"
"github.com/elastic/beats/v7/libbeat/version"
"github.com/elastic/beats/v7/x-pack/filebeat/input/internal/httplog"
"github.com/elastic/beats/v7/x-pack/filebeat/input/internal/httpmon"
"github.com/elastic/elastic-agent-libs/logp"
"github.com/elastic/elastic-agent-libs/mapstr"
"github.com/elastic/elastic-agent-libs/monitoring"
"github.com/elastic/elastic-agent-libs/monitoring/adapter"
"github.com/elastic/elastic-agent-libs/transport"
"github.com/elastic/elastic-agent-libs/transport/httpcommon"
"github.com/elastic/elastic-agent-libs/useragent"
"github.com/elastic/go-concert/ctxtool"
"github.com/elastic/go-concert/timed"
"github.com/elastic/mito/lib"
)
const (
// inputName is the name of the input processor.
inputName = "cel"
// root is the label of the object through which the input state is
// exposed to the CEL program.
root = "state"
)
// The Filebeat user-agent is provided to the program as useragent. If a request
// is not given a user-agent string, this user agent is added to the request.
var userAgent = useragent.UserAgent("Filebeat", version.GetDefaultVersion(), version.Commit(), version.BuildTime().String())
func Plugin(log *logp.Logger, store inputcursor.StateStore) v2.Plugin {
return v2.Plugin{
Name: inputName,
Stability: feature.Stable,
Manager: NewInputManager(log, store),
}
}
type input struct {
time func() time.Time
}
// now is time.Now with a modifiable time source.
func (i input) now() time.Time {
if i.time == nil {
return time.Now()
}
return i.time()
}
func (input) Name() string { return inputName }
func (input) Test(src inputcursor.Source, _ v2.TestContext) error {
cfg := src.(*source).cfg
if !wantClient(cfg) {
return nil
}
return test(cfg.Resource.URL.URL)
}
// Run starts the input and blocks until it ends completes. It will return on
// context cancellation or type invalidity errors, any other error will be retried.
func (input) Run(env v2.Context, src inputcursor.Source, crsr inputcursor.Cursor, pub inputcursor.Publisher) error {
var cursor map[string]interface{}
env.UpdateStatus(status.Starting, "")
if !crsr.IsNew() { // Allow the user to bootstrap the program if needed.
err := crsr.Unpack(&cursor)
if err != nil {
env.UpdateStatus(status.Failed, "failed to unpack cursor: "+err.Error())
return err
}
}
err := input{}.run(env, src.(*source), cursor, pub)
if err != nil {
env.UpdateStatus(status.Failed, "failed to run: "+err.Error())
return err
}
env.UpdateStatus(status.Stopped, "")
return nil
}
// sanitizeFileName returns name with ":" and "/" replaced with "_", removing repeated instances.
// The request.tracer.filename may have ":" when a cel input has cursor config and
// the macOS Finder will treat this as path-separator and causes to show up strange filepaths.
func sanitizeFileName(name string) string {
name = strings.ReplaceAll(name, ":", string(filepath.Separator))
name = filepath.Clean(name)
return strings.ReplaceAll(name, string(filepath.Separator), "_")
}
func (i input) run(env v2.Context, src *source, cursor map[string]interface{}, pub inputcursor.Publisher) error {
cfg := src.cfg
log := env.Logger.With("input_url", cfg.Resource.URL)
metrics, reg := newInputMetrics(env.ID)
defer metrics.Close()
ctx := ctxtool.FromCanceller(env.Cancelation)
if cfg.Resource.Tracer != nil {
id := sanitizeFileName(env.IDWithoutName)
cfg.Resource.Tracer.Filename = strings.ReplaceAll(cfg.Resource.Tracer.Filename, "*", id)
}
client, trace, err := newClient(ctx, cfg, log, reg)
if err != nil {
return err
}
limiter := newRateLimiterFromConfig(cfg.Resource)
patterns, err := regexpsFromConfig(cfg)
if err != nil {
return err
}
var auth *lib.BasicAuth
if cfg.Auth.Basic.isEnabled() {
auth = &lib.BasicAuth{
Username: cfg.Auth.Basic.User,
Password: cfg.Auth.Basic.Password,
}
}
wantDump := cfg.FailureDump.enabled() && cfg.FailureDump.Filename != ""
doCov := cfg.RecordCoverage && log.IsDebug()
prg, ast, cov, err := newProgram(ctx, cfg.Program, root, getEnv(cfg.AllowedEnvironment), client, limiter, auth, patterns, cfg.XSDs, log, trace, wantDump, doCov)
if err != nil {
return err
}
var state map[string]interface{}
if cfg.State == nil {
state = make(map[string]interface{})
} else {
state = cfg.State
}
if cursor != nil {
state["cursor"] = cursor
}
goodCursor := cursor
goodURL := cfg.Resource.URL.String()
state["url"] = goodURL
metrics.resource.Set(goodURL)
env.UpdateStatus(status.Running, "")
// On entry, state is expected to be in the shape:
//
// {
// "url": <resource address>,
// "cursor": { ... },
// ...
// }
//
// The url field must be present and can be an HTTP end-point
// or a file path. It is currently the responsibility of the
// program to handle removing the scheme from a file url if it
// is present. The url may be mutated during execution of the
// program but the mutated state will not be persisted between
// restarts and the url must be present in the returned value
// to ensure that it is available in the next evaluation unless
// the program has the resource address hard-coded in or it is
// available from the cursor.
//
// Additional fields may be present at the root of the object
// and if the program tolerates it, the cursor value may be
// absent. Only the cursor is persisted over restarts, but
// all fields in state are retained between iterations of
// the processing loop except for the produced events array,
// see discussion below.
//
// If the cursor is present the program should perform and
// process requests based on its value. If cursor is not
// present the program must have alternative logic to
// determine what requests to make.
//
// In addition to this and the functions and globals available
// from mito/lib, a global, useragent, is available to use
// in requests.
err = periodically(ctx, cfg.Interval, func() error {
log.Info("process repeated request")
var (
budget = *cfg.MaxExecutions
waitUntil time.Time
)
// Keep track of whether CEL is degraded for this periodic run.
var isDegraded bool
if doCov {
defer func() {
// If doCov is true, log the updated coverage details.
// Updates are a running aggregate for each call to run
// as cov is shared via the program compilation.
log.Debugw("coverage", "details", cov.Details())
}()
}
for {
if wait := time.Until(waitUntil); wait > 0 {
// We have a special-case wait for when we have a zero limit.
// x/time/rate allow a burst through even when the limit is zero
// so in order to ensure that we don't try until we are out of
// purgatory we calculate how long we should wait according to
// the retry after for a 429 and rate limit headers if we have
// a zero rate quota. See handleResponse below.
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(wait):
}
} else if err = ctx.Err(); err != nil {
// Otherwise exit if we have been cancelled.
return err
}
// Process a set of event requests.
if trace != nil {
log.Debugw("previous transaction", "transaction.id", trace.TxID())
}
log.Debugw("request state", logp.Namespace("cel"), "state", redactor{state: state, cfg: cfg.Redact})
metrics.executions.Add(1)
start := i.now().In(time.UTC)
state, err = evalWith(ctx, prg, ast, state, start, wantDump)
log.Debugw("response state", logp.Namespace("cel"), "state", redactor{state: state, cfg: cfg.Redact})
if err != nil {
var dump dumpError
switch {
case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded):
return err
case errors.As(err, &dump):
path := strings.ReplaceAll(cfg.FailureDump.Filename, "*", sanitizeFileName(env.IDWithoutName))
dir := filepath.Dir(path)
base := filepath.Base(path)
ext := filepath.Ext(base)
prefix := strings.TrimSuffix(base, ext)
path = filepath.Join(dir, prefix+"-"+i.now().In(time.UTC).Format("2006-01-02T15-04-05.000")+ext)
log.Debugw("writing failure dump file", "path", path)
err := dump.writeToFile(path)
if err != nil {
log.Errorw("failed to write failure dump", "path", path, "error", err)
}
}
log.Errorw("failed evaluation", "error", err)
env.UpdateStatus(status.Degraded, "failed evaluation: "+err.Error())
}
isDegraded = err != nil
metrics.celProcessingTime.Update(time.Since(start).Nanoseconds())
if trace != nil {
log.Debugw("final transaction", "transaction.id", trace.TxID())
}
// On exit, state is expected to be in the shape:
//
// {
// "cursor": [
// {...},
// ...
// ],
// "events": [
// {...},
// ...
// ],
// "url": <resource address>,
// "status_code": <HTTP request status code if a network request>,
// "header": <HTTP response headers if a network request>,
// "rate_limit": <HTTP rate limit map if required by API>,
// "want_more": bool
// }
//
// The "events" array must be present, but may be empty or null.
// In the case of an error condition in the CEL program it is
// acceptable to return a single object which will be wrapped as
// an array below. It is the responsibility of the downstream
// processor to handle this object correctly (which may be to drop
// the event). The error event will also be logged.
// If it is not empty, it must only have objects as elements.
// Additional fields may be present at the root of the object.
// The evaluation is repeated with the new state, after removing
// the events field, if the "want_more" field is present and true
// and a non-zero events array is returned.
//
// If cursor is present it must be either a single object or an
// array with the same length as events; each element i of the
// cursor array will be the details for obtaining the events at or
// beyond event i in events. If the cursor is a single object it
// is will be the details for obtaining events after the last
// event in the events array and will only be retained on
// successful publication of all the events in the array.
//
// If rate_limit is present it should be a map with numeric fields
// rate and burst. It may also have a string error field and
// other fields which will be logged. If it has an error field
// the rate and burst will not be used to set rate limit behaviour.
//
// The status code and rate_limit values may be omitted if they do
// not contribute to control.
//
// The following details how a cursor array works:
//
// Result after request resulting in 5 events. Each c obtained with
// an e points to the ~next e.
//
// +----+ +----+ +----+
// | e1 | | c1 | | e1 |
// +----+ +----+ +----+ +----+
// | e2 | | c2 | | e2 | < | c1 |
// +----+ +----+ +----+ +----+
// | e3 | | c3 | | e3 | < | c2 |
// +----+ +----+ => +----+ +----+
// | e4 | | c4 | | e4 | < | c3 |
// +----+ +----+ +----+ +----+
// | e5 | | c5 | | e5 | < | c4 |
// +----+ +----+ +----+ +----+
// |next| < | c5 |
// +----+ +----+
//
// After a successful publication this will leave a single c and
// and empty events array. So the next evaluation has a boot.
//
// If the publication fails or execution is terminated at some
// point during the events array, we may end up with, e.g.
//
// +----+ +----+ +----+ +----+
// | e3 | | c3 | |next| < | c3 |
// +----+ +----+ +----+ +----+
// | e4 | | c4 | =>
// +----+ +----+ lost events
// | e5 | | c5 |
// +----+ +----+
//
// At this point, the c3 cursor (or at worst the c2 cursor) has
// been stored and we can continue from that point, recovering
// the lost events and potentially re-requesting e3.
var ok bool
ok, waitUntil, err = handleResponse(log, state, limiter)
if err != nil {
return err
}
if !ok {
continue
}
_, ok = state["url"]
if !ok && goodURL != "" {
state["url"] = goodURL
log.Debugw("adding missing url from last valid value: state did not contain a url", "last_valid_url", goodURL)
}
e, ok := state["events"]
if !ok {
return errors.New("unexpected missing events array from evaluation")
}
var events []interface{}
switch e := e.(type) {
case []interface{}:
if len(e) == 0 {
return nil
}
events = e
case map[string]interface{}:
if e == nil {
return nil
}
log.Errorw("single event object returned by evaluation", "event", e)
if err, ok := e["error"]; ok {
env.UpdateStatus(status.Degraded, fmt.Sprintf("single event error object returned by evaluation: %s", mapstr.M{"error": err}))
} else {
env.UpdateStatus(status.Degraded, "single event object returned by evaluation")
}
isDegraded = true
events = []interface{}{e}
// Make sure the cursor is not updated.
delete(state, "cursor")
default:
return fmt.Errorf("unexpected type returned for evaluation events: %T", e)
}
// We have a non-empty batch of events to process.
metrics.batchesReceived.Add(1)
metrics.eventsReceived.Add(uint64(len(events)))
// Drop events from state. If we fail during the publication,
// we will re-request these events.
delete(state, "events")
// Get cursors if they exist.
var (
cursors []interface{}
singleCursor bool
)
if c, ok := state["cursor"]; ok {
cursors, ok = c.([]interface{})
if ok {
if len(cursors) != len(events) {
log.Errorw("unexpected cursor list length", "cursors", len(cursors), "events", len(events))
env.UpdateStatus(status.Degraded, "unexpected cursor list length")
isDegraded = true
// But try to continue.
if len(cursors) < len(events) {
cursors = nil
}
}
} else {
cursors = []interface{}{c}
singleCursor = true
}
}
// Drop old cursor from state. This will be replaced with
// the current cursor object below; it is an array now.
delete(state, "cursor")
start = time.Now()
var hadPublicationError bool
for i, e := range events {
event, ok := e.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected type returned for evaluation events: %T", e)
}
var pubCursor interface{}
if cursors != nil {
if singleCursor {
// Only set the cursor for publication at the last event
// when a single cursor object has been provided.
if i == len(events)-1 {
goodCursor = cursor
cursor, ok = cursors[0].(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected type returned for evaluation cursor element: %T", cursors[0])
}
pubCursor = cursor
}
} else {
goodCursor = cursor
cursor, ok = cursors[i].(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected type returned for evaluation cursor element: %T", cursors[i])
}
pubCursor = cursor
}
}
err = pub.Publish(beat.Event{
Timestamp: time.Now(),
Fields: event,
}, pubCursor)
if err != nil {
hadPublicationError = true
log.Errorw("error publishing event", "error", err)
env.UpdateStatus(status.Degraded, "error publishing event: "+err.Error())
isDegraded = true
cursors = nil // We are lost, so retry with this event's cursor,
continue // but continue with the events that we have without
// advancing the cursor. This allows us to potentially publish the
// events we have now, with a fallback to the last guaranteed
// correctly published cursor.
}
if i == 0 {
metrics.batchesPublished.Add(1)
}
metrics.eventsPublished.Add(1)
err = ctx.Err()
if err != nil {
return err
}
}
if !isDegraded {
env.UpdateStatus(status.Running, "")
}
metrics.batchProcessingTime.Update(time.Since(start).Nanoseconds())
// Advance the cursor to the final state if there was no error during
// publications. This is needed to transition to the next set of events.
if !hadPublicationError {
goodCursor = cursor
}
// Replace the last known good cursor.
state["cursor"] = goodCursor
if more, _ := state["want_more"].(bool); !more {
return nil
}
// Check we have a remaining execution budget.
budget--
if budget <= 0 {
log.Warnw("exceeding maximum number of CEL executions", "limit", *cfg.MaxExecutions)
env.UpdateStatus(status.Degraded, "exceeding maximum number of CEL executions")
return nil
}
}
})
switch {
case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded):
log.Infof("input stopped because context was cancelled with: %v", err)
err = nil
}
return err
}
func periodically(ctx context.Context, each time.Duration, fn func() error) error {
err := fn()
if err != nil {
return err
}
return timed.Periodic(ctx, each, fn)
}
// handleResponse checks the response status code and handles rate limit changes.
// It returns ok=true if the response is valid, otherwise false for a retry.
func handleResponse(log *logp.Logger, state map[string]interface{}, limiter *rate.Limiter) (ok bool, waitUntil time.Time, err error) {
var header http.Header
h, ok := state["header"]
if ok {
delete(state, "header")
switch h := h.(type) {
case http.Header:
header = h
case map[string][]string:
header = h
case map[string]interface{}:
header = make(http.Header)
for k, v := range h {
switch v := v.(type) {
case []string:
header[k] = v
case []interface{}:
vals := make([]string, len(v))
for i, e := range v {
vals[i], ok = e.(string)
if !ok {
return false, time.Time{}, fmt.Errorf("unexpected type returned for response header value: %T", v)
}
}
header[k] = vals
default:
return false, waitUntil, fmt.Errorf("unexpected type returned for response header value set: %T", v)
}
}
default:
return false, waitUntil, fmt.Errorf("unexpected type returned for response header: %T", h)
}
}
r, ok := state["rate_limit"]
if ok {
delete(state, "rate_limit")
switch r := r.(type) {
case map[string]interface{}:
// The state of rate-limit headers is a disaster. This needs to be
// more robust, but there is no real consensus and the RFC is not
// past draft yet. The draft is more sane than what we have now, but
// still has a lot of complexity. Note that the RFC draft says that
// this behaviour should be in the common path, not just in the 429
// path.
waitUntil = handleRateLimit(log, r, header, limiter)
default:
return false, waitUntil, fmt.Errorf("unexpected type returned for response header: %T", h)
}
}
sc, ok := state["status_code"]
if ok {
delete(state, "status_code")
var statusCode int
switch sc := sc.(type) {
case int:
statusCode = sc
case int64:
statusCode = int(sc)
case float64:
statusCode = int(sc)
default:
return false, waitUntil, fmt.Errorf("unexpected type returned for request status code: %T", sc)
}
switch statusCode {
case http.StatusOK:
return true, time.Time{}, nil
case http.StatusTooManyRequests:
// https://datatracker.ietf.org/doc/html/rfc6585#page-3
retry := header.Get("Retry-After")
if d, err := strconv.Atoi(retry); err == nil {
t := time.Now().Add(time.Duration(d) * time.Second)
if t.After(waitUntil) {
waitUntil = t
}
} else if t, err := time.Parse(http.TimeFormat, retry); err == nil {
if t.After(waitUntil) {
waitUntil = t
}
}
return false, waitUntil, nil
default:
status := http.StatusText(statusCode)
if status == "" {
status = "unknown status code"
}
state["events"] = errorMessage(fmt.Sprintf("failed http request with %s: %d", status, statusCode))
return true, time.Time{}, nil
}
}
return true, waitUntil, nil
}
func handleRateLimit(log *logp.Logger, rateLimit map[string]interface{}, header http.Header, limiter *rate.Limiter) (waitUntil time.Time) {
if e, ok := rateLimit["error"]; ok {
// The error field should be a string, but we won't quibble here.
log.Errorw("rate limit error", "error", e, "rate_limit", mapstr.M(rateLimit), "header", header)
return waitUntil
}
limit, ok := getLimit("rate", rateLimit, log)
if !ok {
return waitUntil
}
var burst int
b, ok := rateLimit["burst"]
if !ok {
log.Warnw("rate limit missing burst", "rate_limit", mapstr.M(rateLimit))
}
switch b := b.(type) {
case int:
burst = b
case int64:
burst = int(b)
case float64:
burst = int(b)
default:
log.Errorw("unexpected type returned for rate limit burst", "type", fmt.Sprintf("%T", b), "rate_limit", mapstr.M(rateLimit))
}
if burst < 1 {
// Make sure we can make at least one new request, even if we fail
// to get a non-zero rate.Limit. We could set to zero for the case
// that limit=rate.Inf, but that detail is not important.
burst = 1
}
// Process reset if we need to wait until reset to avoid a request against a zero quota.
if limit <= 0 {
w, ok := rateLimit["reset"]
if ok {
switch w := w.(type) {
case time.Time:
waitUntil = w
next, ok := getLimit("next", rateLimit, log)
if !ok {
return waitUntil
}
limiter.SetLimitAt(waitUntil, next)
limiter.SetBurstAt(waitUntil, burst)
case string:
t, err := time.Parse(time.RFC3339, w)
if err != nil {
log.Errorw("unexpected value returned for rate limit reset", "value", w, "rate_limit", mapstr.M(rateLimit))
return waitUntil
}
waitUntil = t
next, ok := getLimit("next", rateLimit, log)
if !ok {
return waitUntil
}
limiter.SetLimitAt(waitUntil, next)
limiter.SetBurstAt(waitUntil, burst)
default:
log.Errorw("unexpected type returned for rate limit reset", "type", reflect.TypeOf(w).String(), "rate_limit", mapstr.M(rateLimit))
}
}
return waitUntil
}
limiter.SetLimit(limit)
limiter.SetBurst(burst)
return waitUntil
}
func getLimit(which string, rateLimit map[string]interface{}, log *logp.Logger) (limit rate.Limit, ok bool) {
r, ok := rateLimit[which]
if !ok {
log.Errorw("rate limit missing "+which, "rate_limit", mapstr.M(rateLimit))
return limit, false
}
switch r := r.(type) {
case rate.Limit:
limit = r
case int:
limit = rate.Limit(r)
case int64:
limit = rate.Limit(r)
case float64:
limit = rate.Limit(r)
case string:
if !strings.EqualFold(strings.TrimPrefix(r, "+"), "inf") && !strings.EqualFold(strings.TrimPrefix(r, "+"), "infinity") {
log.Errorw("unexpected value returned for rate limit "+which, "value", r, "rate_limit", mapstr.M(rateLimit))
return limit, false
}
limit = rate.Inf
default:
log.Errorw("unexpected type returned for rate limit "+which, "type", reflect.TypeOf(r).String(), "rate_limit", mapstr.M(rateLimit))
}
return limit, true
}
// lumberjackTimestamp is a glob expression matching the time format string used
// by lumberjack when rolling over logs, "2006-01-02T15-04-05.000".
// https://github.com/natefinch/lumberjack/blob/4cb27fcfbb0f35cb48c542c5ea80b7c1d18933d0/lumberjack.go#L39
const lumberjackTimestamp = "[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]-[0-9][0-9]-[0-9][0-9].[0-9][0-9][0-9]"
func newClient(ctx context.Context, cfg config, log *logp.Logger, reg *monitoring.Registry) (*http.Client, *httplog.LoggingRoundTripper, error) {
c, err := cfg.Resource.Transport.Client(clientOptions(cfg.Resource.URL.URL, cfg.Resource.KeepAlive.settings())...)
if err != nil {
return nil, nil, err
}
if cfg.Auth.Digest.isEnabled() {
var noReuse bool
if cfg.Auth.Digest.NoReuse != nil {
noReuse = *cfg.Auth.Digest.NoReuse
}
c.Transport = &digest.Transport{
Transport: c.Transport,
Username: cfg.Auth.Digest.User,
Password: cfg.Auth.Digest.Password,
NoReuse: noReuse,
}
}
var trace *httplog.LoggingRoundTripper
if cfg.Resource.Tracer.enabled() {
w := zapcore.AddSync(cfg.Resource.Tracer)
go func() {
// Close the logger when we are done.
<-ctx.Done()
cfg.Resource.Tracer.Close()
}()
core := ecszap.NewCore(
ecszap.NewDefaultEncoderConfig(),
w,
zap.DebugLevel,
)
traceLogger := zap.New(core)
const margin = 10e3 // 1OkB ought to be enough room for all the remainder of the trace details.
maxSize := cfg.Resource.Tracer.MaxSize * 1e6
trace = httplog.NewLoggingRoundTripper(c.Transport, traceLogger, max(0, maxSize-margin), log)
c.Transport = trace
} else if cfg.Resource.Tracer != nil {
// We have a trace log name, but we are not enabled,
// so remove all trace logs we own.
err = os.Remove(cfg.Resource.Tracer.Filename)
if err != nil && !errors.Is(err, fs.ErrNotExist) {
log.Errorw("failed to remove request trace log", "path", cfg.Resource.Tracer.Filename, "error", err)
}
ext := filepath.Ext(cfg.Resource.Tracer.Filename)
base := strings.TrimSuffix(cfg.Resource.Tracer.Filename, ext)
paths, err := filepath.Glob(base + "-" + lumberjackTimestamp + ext)
if err != nil {
log.Errorw("failed to collect request trace log path names", "error", err)
}
for _, p := range paths {
err = os.Remove(p)
if err != nil && !errors.Is(err, fs.ErrNotExist) {
log.Errorw("failed to remove request trace log", "path", p, "error", err)
}
}
}
if !cfg.FailureDump.enabled() && cfg.FailureDump != nil && cfg.FailureDump.Filename != "" {
// We have a fail-dump name, but we are not enabled,
// so remove all dumps we own.
err = os.Remove(cfg.FailureDump.Filename)
if err != nil && !errors.Is(err, fs.ErrNotExist) {
log.Errorw("failed to remove request trace log", "path", cfg.FailureDump.Filename, "error", err)
}
ext := filepath.Ext(cfg.FailureDump.Filename)
base := strings.TrimSuffix(cfg.FailureDump.Filename, ext)
paths, err := filepath.Glob(base + "-" + lumberjackTimestamp + ext)
if err != nil {
log.Errorw("failed to collect request trace log path names", "error", err)
}
for _, p := range paths {
err = os.Remove(p)
if err != nil && !errors.Is(err, fs.ErrNotExist) {
log.Errorw("failed to remove request trace log", "path", p, "error", err)
}
}
}
if reg != nil {
c.Transport = httpmon.NewMetricsRoundTripper(c.Transport, reg)
}
c.CheckRedirect = checkRedirect(cfg.Resource, log)
if cfg.Resource.Retry.getMaxAttempts() > 1 {
maxAttempts := cfg.Resource.Retry.getMaxAttempts()
c = (&retryablehttp.Client{
HTTPClient: c,
Logger: newRetryLog(log),
RetryWaitMin: cfg.Resource.Retry.getWaitMin(),
RetryWaitMax: cfg.Resource.Retry.getWaitMax(),
RetryMax: maxAttempts,
CheckRetry: retryablehttp.DefaultRetryPolicy,
Backoff: retryablehttp.DefaultBackoff,
ErrorHandler: retryErrorHandler(maxAttempts, log),
}).StandardClient()
}
if cfg.Auth.OAuth2.isEnabled() {
authClient, err := cfg.Auth.OAuth2.client(ctx, c)
if err != nil {
return nil, nil, err
}
return authClient, trace, nil
}
c.Transport = userAgentDecorator{
UserAgent: userAgent,
Transport: c.Transport,
}
return c, trace, nil
}
func wantClient(cfg config) bool {
switch scheme, _, _ := strings.Cut(cfg.Resource.URL.Scheme, "+"); scheme {
case "http", "https":
return true
default:
return false
}
}
// clientOption returns constructed client configuration options, including
// setting up http+unix and http+npipe transports if requested.
func clientOptions(u *url.URL, keepalive httpcommon.WithKeepaliveSettings) []httpcommon.TransportOption {
scheme, trans, ok := strings.Cut(u.Scheme, "+")
var dialer transport.Dialer
switch {
default:
fallthrough
case !ok:
return []httpcommon.TransportOption{
httpcommon.WithAPMHTTPInstrumentation(),
keepalive,
}
// We set the host for the unix socket and Windows named
// pipes schemes because the http.Transport expects to
// have a host and will error out if it is not present.
// The values here are just non-zero with a helpful name.
// They are not used in any logic.
case trans == "unix":
u.Host = "unix-socket"
dialer = socketDialer{u.Path}
case trans == "npipe":
u.Host = "windows-npipe"
dialer = npipeDialer{u.Path}
}
u.Scheme = scheme
return []httpcommon.TransportOption{
httpcommon.WithAPMHTTPInstrumentation(),
keepalive,
httpcommon.WithBaseDialer(dialer),
}
}
// socketDialer implements transport.Dialer to a constant socket path.
type socketDialer struct {
path string
}
func (d socketDialer) Dial(_, _ string) (net.Conn, error) {
return net.Dial("unix", d.path)
}
func (d socketDialer) DialContext(ctx context.Context, _, _ string) (net.Conn, error) {
var nd net.Dialer
return nd.DialContext(ctx, "unix", d.path)
}
func checkRedirect(cfg *ResourceConfig, log *logp.Logger) func(*http.Request, []*http.Request) error {
return func(req *http.Request, via []*http.Request) error {
log.Debug("http client: checking redirect")
if len(via) >= cfg.RedirectMaxRedirects {
log.Debug("http client: max redirects exceeded")
return fmt.Errorf("stopped after %d redirects", cfg.RedirectMaxRedirects)
}
if !cfg.RedirectForwardHeaders || len(via) == 0 {
log.Debugf("http client: nothing to do while checking redirects - forward_headers: %v, via: %#v", cfg.RedirectForwardHeaders, via)
return nil
}
prev := via[len(via)-1] // previous request to get headers from
log.Debugf("http client: forwarding headers from previous request: %#v", prev.Header)
req.Header = prev.Header.Clone()
for _, k := range cfg.RedirectHeadersBanList {
log.Debugf("http client: ban header %v", k)
req.Header.Del(k)
}
return nil
}
}
// retryErrorHandler returns a retryablehttp.ErrorHandler that will log retry resignation
// but return the last retry attempt's response and a nil error so that the CEL code
// can evaluate the response status itself. Any error passed to the retryablehttp.ErrorHandler
// is returned unaltered. Despite not being documented so, the error handler may be passed
// a nil resp. retryErrorHandler will handle this case.
func retryErrorHandler(max int, log *logp.Logger) retryablehttp.ErrorHandler {
return func(resp *http.Response, err error, numTries int) (*http.Response, error) {
if resp != nil && resp.Request != nil {
reqURL := "unavailable"
if resp.Request.URL != nil {
reqURL = resp.Request.URL.String()
}
log.Warnw("giving up retries", "method", resp.Request.Method, "url", reqURL, "retries", max+1)
} else {
log.Warnw("giving up retries: no response available", "retries", max+1)
}
return resp, err
}
}
type userAgentDecorator struct {
UserAgent string
Transport http.RoundTripper
}
func (t userAgentDecorator) RoundTrip(r *http.Request) (*http.Response, error) {
if _, ok := r.Header["User-Agent"]; !ok {
r.Header.Set("User-Agent", t.UserAgent)
}
return t.Transport.RoundTrip(r)
}
func newRateLimiterFromConfig(cfg *ResourceConfig) *rate.Limiter {
r := rate.Inf
b := 1
if cfg != nil && cfg.RateLimit != nil {
if cfg.RateLimit.Limit != nil {
r = rate.Limit(*cfg.RateLimit.Limit)
}
if cfg.RateLimit.Burst != nil {
b = *cfg.RateLimit.Burst
}
}
return rate.NewLimiter(r, b)
}
func regexpsFromConfig(cfg config) (map[string]*regexp.Regexp, error) {
if len(cfg.Regexps) == 0 {