forked from redpanda-data/connect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
type.go
432 lines (378 loc) · 12.1 KB
/
type.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
// Copyright (c) 2018 Ashley Jeffs
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package client
import (
"bytes"
"crypto/tls"
"fmt"
"io"
"mime"
"mime/multipart"
"net/http"
"net/textproto"
"strings"
"sync"
"time"
"github.com/Jeffail/benthos/lib/log"
"github.com/Jeffail/benthos/lib/metrics"
"github.com/Jeffail/benthos/lib/types"
"github.com/Jeffail/benthos/lib/util/http/auth"
"github.com/Jeffail/benthos/lib/util/throttle"
)
//------------------------------------------------------------------------------
// Config is a configuration struct for an HTTP client.
type Config struct {
URL string `json:"url" yaml:"url"`
Verb string `json:"verb" yaml:"verb"`
Headers map[string]string `json:"headers" yaml:"headers"`
TimeoutMS int64 `json:"timeout_ms" yaml:"timeout_ms"`
RetryMS int64 `json:"retry_period_ms" yaml:"retry_period_ms"`
MaxBackoffMS int64 `json:"max_retry_backoff_ms" yaml:"max_retry_backoff_ms"`
NumRetries int `json:"retries" yaml:"retries"`
BackoffOn []int `json:"backoff_on" yaml:"backoff_on"`
DropOn []int `json:"drop_on" yaml:"drop_on"`
SkipCertVerify bool `json:"skip_cert_verify" yaml:"skip_cert_verify"`
auth.Config `json:",inline" yaml:",inline"`
}
// NewConfig creates a new Config with default values.
func NewConfig() Config {
return Config{
URL: "http://localhost:4195/post",
Verb: "POST",
Headers: map[string]string{
"Content-Type": "application/octet-stream",
},
TimeoutMS: 5000,
RetryMS: 1000,
MaxBackoffMS: 300000,
NumRetries: 3,
BackoffOn: []int{429},
DropOn: []int{},
SkipCertVerify: false,
Config: auth.NewConfig(),
}
}
//------------------------------------------------------------------------------
// Type is an output type that pushes messages to Type.
type Type struct {
client http.Client
backoffOn map[int]struct{}
dropOn map[int]struct{}
URL string
conf Config
retryThrottle *throttle.Type
log log.Modular
stats metrics.Type
mCount metrics.StatCounter
mErr metrics.StatCounter
mErrReq metrics.StatCounter
mErrRes metrics.StatCounter
mSucc metrics.StatCounter
mLatency metrics.StatTimer
mCodes map[int]metrics.StatCounter
codesMut sync.RWMutex
closeChan <-chan struct{}
}
// New creates a new Type.
func New(conf Config, opts ...func(*Type)) *Type {
h := Type{
URL: conf.URL,
conf: conf,
log: log.Noop(),
stats: metrics.Noop(),
backoffOn: map[int]struct{}{},
dropOn: map[int]struct{}{},
}
h.client.Timeout = time.Duration(h.conf.TimeoutMS) * time.Millisecond
if h.conf.SkipCertVerify {
h.client.Transport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
}
for _, c := range conf.BackoffOn {
h.backoffOn[c] = struct{}{}
}
for _, c := range conf.DropOn {
h.dropOn[c] = struct{}{}
}
for _, opt := range opts {
opt(&h)
}
h.mCount = h.stats.GetCounter("client.http.count")
h.mErr = h.stats.GetCounter("client.http.error")
h.mErrReq = h.stats.GetCounter("client.http.error.request")
h.mErrRes = h.stats.GetCounter("client.http.error.response")
h.mLatency = h.stats.GetTimer("client.http.latency")
h.mSucc = h.stats.GetCounter("client.http.success")
h.mCodes = map[int]metrics.StatCounter{}
h.retryThrottle = throttle.New(
throttle.OptMaxUnthrottledRetries(0),
throttle.OptCloseChan(h.closeChan),
throttle.OptThrottlePeriod(time.Millisecond*time.Duration(conf.RetryMS)),
throttle.OptMaxExponentPeriod(time.Millisecond*time.Duration(conf.MaxBackoffMS)),
)
return &h
}
//------------------------------------------------------------------------------
// OptSetCloseChan sets a channel that when closed will interrupt any blocking
// calls within the client.
func OptSetCloseChan(c <-chan struct{}) func(*Type) {
return func(t *Type) {
t.closeChan = c
}
}
// OptSetLogger sets the logger to use.
func OptSetLogger(log log.Modular) func(*Type) {
return func(t *Type) {
t.log = log.NewModule(".client.http")
}
}
// OptSetStats sets the metrics aggregator to use.
func OptSetStats(stats metrics.Type) func(*Type) {
return func(t *Type) {
t.stats = stats
}
}
//------------------------------------------------------------------------------
func (h *Type) incrCode(code int) {
h.codesMut.RLock()
ctr, exists := h.mCodes[code]
h.codesMut.RUnlock()
if exists {
ctr.Incr(1)
return
}
ctr = h.stats.GetCounter(fmt.Sprintf("client.http.code.%v", code))
ctr.Incr(1)
h.codesMut.Lock()
h.mCodes[code] = ctr
h.codesMut.Unlock()
}
// CreateRequest creates an HTTP request out of a single message.
func (h *Type) CreateRequest(msg types.Message) (req *http.Request, err error) {
return h.CreateRequestWithURL(h.URL, msg)
}
// CreateRequestWithURL creates an HTTP request out of a single message.
func (h *Type) CreateRequestWithURL(url string, msg types.Message) (req *http.Request, err error) {
if msg == nil || msg.Len() == 0 {
if req, err = http.NewRequest(h.conf.Verb, url, nil); err == nil {
for k, v := range h.conf.Headers {
req.Header.Add(k, v)
}
}
} else if msg.Len() == 1 {
body := bytes.NewBuffer(msg.GetAll()[0])
if req, err = http.NewRequest(h.conf.Verb, url, body); err == nil {
for k, v := range h.conf.Headers {
req.Header.Add(k, v)
}
}
} else {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
for i := 0; i < msg.Len() && err == nil; i++ {
contentType := "application/octet-stream"
if v, exists := h.conf.Headers["Content-Type"]; exists {
contentType = v
}
var part io.Writer
if part, err = writer.CreatePart(textproto.MIMEHeader{
"Content-Type": []string{contentType},
}); err == nil {
_, err = io.Copy(part, bytes.NewReader(msg.Get(i)))
}
}
writer.Close()
if req, err = http.NewRequest(h.conf.Verb, url, body); err == nil {
for k, v := range h.conf.Headers {
req.Header.Add(k, v)
}
req.Header.Del("Content-Type")
req.Header.Add("Content-Type", writer.FormDataContentType())
}
}
err = h.conf.Config.Sign(req)
return
}
// ParseResponse attempts to parse an HTTP response into a 2D slice of bytes.
func (h *Type) ParseResponse(res *http.Response) (resMsg types.Message, err error) {
if res.Body == nil {
return nil, nil
}
contentType := res.Header.Get("Content-Type")
var mediaType string
var params map[string]string
if len(contentType) > 0 {
if mediaType, params, err = mime.ParseMediaType(res.Header.Get("Content-Type")); err != nil {
h.mErrRes.Incr(1)
h.mErr.Incr(1)
h.log.Errorf("Failed to parse media type: %v\n", err)
return
}
}
var buffer bytes.Buffer
if strings.HasPrefix(mediaType, "multipart/") {
resMsg = types.NewMessage(nil)
mr := multipart.NewReader(res.Body, params["boundary"])
var bufferIndex int64
for {
var p *multipart.Part
if p, err = mr.NextPart(); err != nil {
if err == io.EOF {
err = nil
break
}
return
}
var bytesRead int64
if bytesRead, err = buffer.ReadFrom(p); err != nil {
h.mErrRes.Incr(1)
h.mErr.Incr(1)
h.log.Errorf("Failed to read response: %v\n", err)
return
}
resMsg.Append(buffer.Bytes()[bufferIndex : bufferIndex+bytesRead])
bufferIndex += bytesRead
}
} else {
var bytesRead int64
if bytesRead, err = buffer.ReadFrom(res.Body); err != nil {
h.mErrRes.Incr(1)
h.mErr.Incr(1)
h.log.Errorf("Failed to read response: %v\n", err)
return
}
if bytesRead > 0 {
resMsg = types.NewMessage([][]byte{buffer.Bytes()[:bytesRead]})
}
}
res.Body.Close()
return
}
// checkStatus compares a returned status code against configured logic
// determining whether the send is resolved, and if not whether the retry should
// be linear.
func (h *Type) checkStatus(code int) (resolved bool, linearRetry bool) {
if _, exists := h.dropOn[code]; exists {
return true, false
}
if _, exists := h.backoffOn[code]; exists {
return false, false
}
if code < 200 || code > 299 {
return false, true
}
return true, false
}
// Do attempts to create and perform an HTTP request from a message payload.
// This attempt may include retries, and if all retries fail an error is
// returned.
func (h *Type) Do(msg types.Message) (res *http.Response, err error) {
return h.DoWithURL(h.URL, msg)
}
// DoWithURL attempts to create and perform an HTTP request from a message
// payload. This attempt may include retries, and if all retries fail an error
// is returned.
func (h *Type) DoWithURL(url string, msg types.Message) (res *http.Response, err error) {
h.mCount.Incr(1)
var req *http.Request
if req, err = h.CreateRequestWithURL(url, msg); err != nil {
h.mErrReq.Incr(1)
h.mErr.Incr(1)
return nil, err
}
startedAt := time.Now()
rateLimited := false
if res, err = h.client.Do(req); err == nil {
h.incrCode(res.StatusCode)
if resolved, linear := h.checkStatus(res.StatusCode); !resolved {
rateLimited = !linear
err = types.ErrUnexpectedHTTPRes{Code: res.StatusCode, S: res.Status}
if res.Body != nil {
res.Body.Close()
}
}
}
i, j := 0, h.conf.NumRetries
for i < j && err != nil {
h.mErrRes.Incr(1)
h.mErr.Incr(1)
req, err = h.CreateRequestWithURL(url, msg)
if err != nil {
h.mErrReq.Incr(1)
h.mErr.Incr(1)
continue
}
if rateLimited {
if !h.retryThrottle.ExponentialRetry() {
return nil, types.ErrTypeClosed
}
} else {
if !h.retryThrottle.Retry() {
return nil, types.ErrTypeClosed
}
}
rateLimited = false
if res, err = h.client.Do(req); err == nil {
h.incrCode(res.StatusCode)
if resolved, linear := h.checkStatus(res.StatusCode); !resolved {
rateLimited = !linear
err = types.ErrUnexpectedHTTPRes{Code: res.StatusCode, S: res.Status}
if res.Body != nil {
res.Body.Close()
}
}
}
i++
}
if err != nil {
h.mErrRes.Incr(1)
h.mErr.Incr(1)
return nil, err
}
h.mLatency.Timing(int64(time.Since(startedAt)))
h.mSucc.Incr(1)
h.retryThrottle.Reset()
return res, nil
}
// Send attempts to send a message to an HTTP server, this attempt may include
// retries, and if all retries fail an error is returned. The message payload
// can be nil, in which case an empty body is sent. The response will be parsed
// back into a message, meaning mulitpart content handling is done for you.
//
// If the response body is empty the message returned is nil.
func (h *Type) Send(msg types.Message) (types.Message, error) {
return h.SendWithURL(h.URL, msg)
}
// SendWithURL attempts to send a message to an HTTP server with a specific URL,
// this attempt may include retries, and if all retries fail an error is
// returned. The message payload can be nil, in which case an empty body is
// sent. The response will be parsed back into a message, meaning mulitpart
// content handling is done for you.
//
// If the response body is empty the message returned is nil.
func (h *Type) SendWithURL(url string, msg types.Message) (types.Message, error) {
res, err := h.DoWithURL(url, msg)
if err != nil {
return nil, err
}
return h.ParseResponse(res)
}
//------------------------------------------------------------------------------