-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathhttp.go
296 lines (250 loc) · 6.36 KB
/
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
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
package http
import (
"bytes"
"context"
"errors"
"fmt"
"github.com/crazygreenpenguin/beats-output-http/resolver"
"github.com/elastic/beats/v7/libbeat/beat"
"github.com/elastic/beats/v7/libbeat/common"
"github.com/elastic/beats/v7/libbeat/logp"
"github.com/elastic/beats/v7/libbeat/outputs"
"github.com/elastic/beats/v7/libbeat/outputs/codec"
"github.com/elastic/beats/v7/libbeat/publisher"
"github.com/json-iterator/go"
"io/ioutil"
"net"
"net/http"
"sync"
"time"
)
var json = jsoniter.ConfigCompatibleWithStandardLibrary
var dnsCache = resolver.NewDNSResolver()
func init() {
outputs.RegisterType("http", makeHTTP)
}
type httpOutput struct {
log *logp.Logger
beat beat.Info
observer outputs.Observer
codec codec.Codec
client *http.Client
serialize func(event *publisher.Event) ([]byte, error)
reqPool sync.Pool
conf config
}
// makeHTTP instantiates a new http output instance.
func makeHTTP(
_ outputs.IndexManager,
beat beat.Info,
observer outputs.Observer,
cfg *common.Config,
) (outputs.Group, error) {
config := defaultConfig
if err := cfg.Unpack(&config); err != nil {
return outputs.Fail(err)
}
ho := &httpOutput{
log: logp.NewLogger("http"),
beat: beat,
observer: observer,
conf: config,
}
// disable bulk support in publisher pipeline
if err := cfg.SetInt("bulk_max_size", -1, -1); err != nil {
ho.log.Error("Disable bulk error: ", err)
}
//select serializer
ho.serialize = ho.serializeAll
if config.OnlyFields {
ho.serialize = ho.serializeOnlyFields
}
// init output
if err := ho.init(beat, config); err != nil {
return outputs.Fail(err)
}
return outputs.Success(-1, config.MaxRetries, ho)
}
func (out *httpOutput) init(beat beat.Info, c config) error {
var err error
out.codec, err = codec.CreateEncoder(beat, c.Codec)
if err != nil {
return err
}
tr := &http.Transport{
MaxIdleConns: out.conf.MaxIdleConns,
ResponseHeaderTimeout: time.Duration(out.conf.ResponseHeaderTimeout) * time.Millisecond,
IdleConnTimeout: time.Duration(out.conf.IdleConnTimeout) * time.Second,
DisableCompression: !out.conf.Compression,
DisableKeepAlives: !out.conf.KeepAlive,
DialContext: func(ctx context.Context, network string, addr string) (conn net.Conn, err error) {
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
ips, err := dnsCache.LookupHost(ctx, host)
if err != nil {
return nil, err
}
for _, ip := range ips {
var dialer net.Dialer
conn, err = dialer.DialContext(ctx, network, net.JoinHostPort(ip, port))
if err == nil {
break
}
}
return
},
}
out.client = &http.Client{
Transport: tr,
}
out.reqPool = sync.Pool{
New: func() interface{} {
req, err := http.NewRequest("POST", out.conf.URL, nil)
if err != nil {
return err
}
return req
},
}
out.log.Infof("Initialized http output:\n"+
"url=%v\n"+
"codec=%v\n"+
"only_fields=%v\n"+
"max_retries=%v\n"+
"compression=%v\n"+
"keep_alive=%v\n"+
"max_idle_conns=%v\n"+
"idle_conn_timeout=%vs\n"+
"response_header_timeout=%vms\n"+
"username=%v\n"+
"password=%v\n",
c.URL, c.Codec, c.OnlyFields, c.MaxRetries, c.Compression,
c.KeepAlive, c.MaxIdleConns, c.IdleConnTimeout, c.ResponseHeaderTimeout,
c.Username, maskPass(c.Password))
return nil
}
func maskPass(password string) string {
result := ""
if len(password) <= 8 {
for i := 0; i < len(password); i++ {
result += "*"
}
return result
}
for i, char := range password {
if i > 1 && i < len(password)-2 {
result += "*"
} else {
result += string(char)
}
}
return result
}
// Implement Client
func (out *httpOutput) Close() error {
out.client.CloseIdleConnections()
return nil
}
func (out *httpOutput) serializeOnlyFields(event *publisher.Event) ([]byte, error) {
fields := event.Content.Fields
fields["@timestamp"] = event.Content.Timestamp
for key, val := range out.conf.AddFields {
fields[key] = val
}
serializedEvent, err := json.Marshal(&fields)
if err != nil {
out.log.Error("Serialization error: ", err)
return make([]byte, 0), err
}
return serializedEvent, nil
}
func (out *httpOutput) serializeAll(event *publisher.Event) ([]byte, error) {
serializedEvent, err := out.codec.Encode(out.beat.Beat, &event.Content)
if err != nil {
out.log.Error("Serialization error: ", err)
return make([]byte, 0), err
}
return serializedEvent, nil
}
func (out *httpOutput) Publish(_ context.Context, batch publisher.Batch) error {
st := out.observer
events := batch.Events()
st.NewBatch(len(events))
if len(events) == 0 {
batch.ACK()
return nil
}
for i := range events {
event := events[i]
serializedEvent, err := out.serialize(&event)
if err != nil {
if event.Guaranteed() {
out.log.Errorf("Failed to serialize the event: %+v", err)
} else {
out.log.Warnf("Failed to serialize the event: %+v", err)
}
out.log.Debugf("Failed event: %v", event)
batch.RetryEvents(events)
st.Failed(len(events))
return nil
}
if err = out.send(serializedEvent); err != nil {
if event.Guaranteed() {
out.log.Errorf("Writing event to http failed with: %+v", err)
} else {
out.log.Warnf("Writing event to http failed with: %+v", err)
}
batch.RetryEvents(events)
st.Failed(len(events))
return nil
}
}
batch.ACK()
st.Acked(len(events))
return nil
}
func (out *httpOutput) String() string {
return "http(" + out.conf.URL + ")"
}
func (out *httpOutput) send(data []byte) error {
req, err := out.getReq(data)
if err != nil {
return err
}
defer out.putReq(req)
resp, err := out.client.Do(req)
if err != nil {
return err
}
err = resp.Body.Close()
if err != nil {
out.log.Warn("Close response body error:", err)
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("bad response code: %d", resp.StatusCode)
}
return nil
}
func (out *httpOutput) getReq(data []byte) (*http.Request, error) {
tmp := out.reqPool.Get()
req, ok := tmp.(*http.Request)
if ok {
buf := bytes.NewBuffer(data)
req.Body = ioutil.NopCloser(buf)
req.Header.Set("User-Agent", "beat "+out.beat.Version)
if out.conf.Username != "" {
req.SetBasicAuth(out.conf.Username, out.conf.Password)
}
return req, nil
}
err, ok := tmp.(error)
if ok {
return nil, err
}
return nil, errors.New("pool assertion error")
}
func (out *httpOutput) putReq(req *http.Request) {
out.reqPool.Put(req)
}