forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
elasticsearch.go
276 lines (235 loc) · 5.92 KB
/
elasticsearch.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
package elasticsearch
import (
"errors"
"io"
"math/rand"
"net/url"
"strings"
"time"
"github.com/elastic/beats/libbeat/beat"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/logp"
"github.com/elastic/beats/libbeat/monitoring"
"github.com/elastic/beats/libbeat/monitoring/report"
"github.com/elastic/beats/libbeat/outputs"
esout "github.com/elastic/beats/libbeat/outputs/elasticsearch"
"github.com/elastic/beats/libbeat/outputs/outil"
"github.com/elastic/beats/libbeat/outputs/transport"
"github.com/elastic/beats/libbeat/publisher/pipeline"
"github.com/elastic/beats/libbeat/publisher/queue"
"github.com/elastic/beats/libbeat/publisher/queue/memqueue"
)
type reporter struct {
done *stopper
period time.Duration
checkRetry time.Duration
// event metadata
beatMeta common.MapStr
tags []string
// pipeline
pipeline *pipeline.Pipeline
client beat.Client
out outputs.Group
}
var debugf = logp.MakeDebug("monitoring")
var errNoMonitoring = errors.New("xpack monitoring not available")
// default monitoring api parameters
var defaultParams = map[string]string{
"system_id": "beats",
"system_api_version": "6",
}
func init() {
report.RegisterReporterFactory("elasticsearch", makeReporter)
}
func makeReporter(beat beat.Info, cfg *common.Config) (report.Reporter, error) {
config := defaultConfig
if err := cfg.Unpack(&config); err != nil {
return nil, err
}
// check endpoint availability on startup only every 30 seconds
checkRetry := 30 * time.Second
windowSize := config.BulkMaxSize - 1
if windowSize <= 0 {
windowSize = 1
}
proxyURL, err := parseProxyURL(config.ProxyURL)
if err != nil {
return nil, err
}
if proxyURL != nil {
logp.Info("Using proxy URL: %s", proxyURL)
}
tlsConfig, err := outputs.LoadTLSConfig(config.TLS)
if err != nil {
return nil, err
}
params := map[string]string{}
for k, v := range config.Params {
params[k] = v
}
for k, v := range defaultParams {
params[k] = v
}
params["interval"] = config.Period.String()
out := outputs.Group{
Clients: nil,
BatchSize: windowSize,
Retry: 0, // no retry. on error drop events
}
hosts, err := outputs.ReadHostList(cfg)
if err != nil {
return nil, err
}
for _, host := range hosts {
client, err := makeClient(host, params, proxyURL, tlsConfig, &config)
if err != nil {
return nil, err
}
out.Clients = append(out.Clients, client)
}
queueFactory := func(e queue.Eventer) (queue.Queue, error) {
return memqueue.NewBroker(memqueue.Settings{
Eventer: e,
Events: 20,
}), nil
}
monitoring := monitoring.Default.NewRegistry("xpack.monitoring")
pipeline, err := pipeline.New(
beat,
monitoring,
queueFactory, out, pipeline.Settings{
WaitClose: 0,
WaitCloseMode: pipeline.NoWaitOnClose,
})
if err != nil {
return nil, err
}
client, err := pipeline.Connect()
if err != nil {
pipeline.Close()
return nil, err
}
r := &reporter{
done: newStopper(),
period: config.Period,
beatMeta: makeMeta(beat),
tags: config.Tags,
checkRetry: checkRetry,
pipeline: pipeline,
client: client,
out: out,
}
go r.initLoop()
return r, nil
}
func (r *reporter) Stop() {
r.done.Stop()
r.client.Close()
r.pipeline.Close()
}
func (r *reporter) initLoop() {
logp.Info("Start monitoring endpoint init loop.")
defer logp.Info("Stop monitoring endpoint init loop.")
for {
// Select one configured endpoint by random and check if xpack is available
client := r.out.Clients[rand.Intn(len(r.out.Clients))].(outputs.NetworkClient)
err := client.Connect()
if err == nil {
closing(client)
break
}
select {
case <-r.done.C():
return
case <-time.After(r.checkRetry):
}
}
// Start collector and send loop if monitoring endpoint has been found.
go r.snapshotLoop()
}
func (r *reporter) snapshotLoop() {
ticker := time.NewTicker(r.period)
defer ticker.Stop()
logp.Info("Start monitoring metrics snapshot loop.")
defer logp.Info("Stop monitoring metrics snapshot loop.")
for {
var ts time.Time
select {
case <-r.done.C():
return
case ts = <-ticker.C:
}
snapshot := makeSnapshot(monitoring.Default)
if snapshot == nil {
debugf("Empty snapshot.")
continue
}
fields := common.MapStr{
"beat": r.beatMeta,
"metrics": snapshot,
}
if len(r.tags) > 0 {
fields["tags"] = r.tags
}
r.client.Publish(beat.Event{
Timestamp: ts,
Fields: fields,
})
}
}
func makeClient(
host string,
params map[string]string,
proxyURL *url.URL,
tlsConfig *transport.TLSConfig,
config *config,
) (outputs.NetworkClient, error) {
url, err := common.MakeURL(config.Protocol, "", host, 9200)
if err != nil {
return nil, err
}
esClient, err := esout.NewClient(esout.ClientSettings{
URL: url,
Proxy: proxyURL,
TLS: tlsConfig,
Username: config.Username,
Password: config.Password,
Parameters: params,
Headers: config.Headers,
Index: outil.MakeSelector(outil.ConstSelectorExpr("_xpack")),
Pipeline: nil,
Timeout: config.Timeout,
CompressionLevel: config.CompressionLevel,
}, nil)
if err != nil {
return nil, err
}
return newPublishClient(esClient, params), nil
}
func closing(c io.Closer) {
if err := c.Close(); err != nil {
logp.Warn("Closed failed with: %v", err)
}
}
// TODO: make this reusable. Same definition in elasticsearch monitoring module
func parseProxyURL(raw string) (*url.URL, error) {
if raw == "" {
return nil, nil
}
url, err := url.Parse(raw)
if err == nil && strings.HasPrefix(url.Scheme, "http") {
return url, err
}
// Proxy was bogus. Try prepending "http://" to it and
// see if that parses correctly.
return url.Parse("http://" + raw)
}
func makeMeta(beat beat.Info) common.MapStr {
return common.MapStr{
"type": beat.Beat,
"version": beat.Version,
"name": beat.Name,
"host": beat.Hostname,
"uuid": beat.UUID,
}
}