-
Notifications
You must be signed in to change notification settings - Fork 13
/
elasticsearch.go
481 lines (399 loc) · 12.4 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
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
package elasticsearch
import (
"bytes"
"context"
"crypto/sha256"
_ "embed"
"fmt"
"math"
"net/http"
"net/url"
"strconv"
"strings"
"text/template"
"time"
elastic "github.com/olivere/elastic/v7"
"github.com/circonus-labs/circonus-unified-agent/config"
"github.com/circonus-labs/circonus-unified-agent/cua"
"github.com/circonus-labs/circonus-unified-agent/plugins/common/tls"
"github.com/circonus-labs/circonus-unified-agent/plugins/outputs"
)
// DO NOT REMOVE THE NEXT TWO LINES! This is required to embed the sampleConfig data.
//
//go:embed sample.conf
var sampleConfig string
type Elasticsearch struct {
Log cua.Logger `toml:"-"`
Client *elastic.Client
Username string `toml:"username"`
DefaultPipeline string `toml:"default_pipeline"`
DefaultTagValue string `toml:"default_tag_value"`
UsePipeline string `toml:"use_pipeline"`
FloatHandling string `toml:"float_handling"`
AuthBearerToken string `toml:"auth_bearer_token"`
TemplateName string `toml:"template_name"`
Password string `toml:"password"`
pipelineName string
IndexName string `toml:"index_name"`
tls.ClientConfig
pipelineTagKeys []string
tagKeys []string
URLs []string `toml:"urls"`
FloatReplacement float64 `toml:"float_replacement_value"`
Timeout config.Duration `toml:"timeout"`
majorReleaseNumber int
HealthCheckTimeout config.Duration `toml:"health_check_timeout"`
HealthCheckInterval config.Duration `toml:"health_check_interval"`
OverwriteTemplate bool `toml:"overwrite_template"`
ManageTemplate bool `toml:"manage_template"`
ForceDocumentID bool `toml:"force_document_id"`
EnableSniffer bool `toml:"enable_sniffer"`
EnableGzip bool `toml:"enable_gzip"`
}
const circonusTemplate = `
{
{{ if (lt .Version 6) }}
"template": "{{.TemplatePattern}}",
{{ else }}
"index_patterns" : [ "{{.TemplatePattern}}" ],
{{ end }}
"settings": {
"index": {
"refresh_interval": "10s",
"mapping.total_fields.limit": 5000,
"auto_expand_replicas" : "0-1",
"codec" : "best_compression"
}
},
"mappings" : {
{{ if (lt .Version 7) }}
"metrics" : {
{{ if (lt .Version 6) }}
"_all": { "enabled": false },
{{ end }}
{{ end }}
"properties" : {
"@timestamp" : { "type" : "date" },
"measurement_name" : { "type" : "keyword" }
},
"dynamic_templates": [
{
"tags": {
"match_mapping_type": "string",
"path_match": "tag.*",
"mapping": {
"ignore_above": 512,
"type": "keyword"
}
}
},
{
"metrics_long": {
"match_mapping_type": "long",
"mapping": {
"type": "float",
"index": false
}
}
},
{
"metrics_double": {
"match_mapping_type": "double",
"mapping": {
"type": "float",
"index": false
}
}
},
{
"text_fields": {
"match": "*",
"mapping": {
"norms": false
}
}
}
]
{{ if (lt .Version 7) }}
}
{{ end }}
}
}`
type templatePart struct {
TemplatePattern string
Version int
}
func (*Elasticsearch) SampleConfig() string {
return sampleConfig
}
func (*Elasticsearch) Description() string {
return "Configuration for ElasticSearch output plugin."
}
func (a *Elasticsearch) Connect() error {
if a.URLs == nil || a.IndexName == "" {
return fmt.Errorf("elasticsearch urls or index_name is not defined")
}
// Determine if we should process NaN and inf values
switch a.FloatHandling {
case "", "none":
a.FloatHandling = "none"
case "drop", "replace":
default:
return fmt.Errorf("invalid float_handling type %q", a.FloatHandling)
}
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(a.Timeout))
defer cancel()
var clientOptions []elastic.ClientOptionFunc
tlsCfg, err := a.ClientConfig.TLSConfig()
if err != nil {
return err
}
tr := &http.Transport{
TLSClientConfig: tlsCfg,
}
httpclient := &http.Client{
Transport: tr,
Timeout: time.Duration(a.Timeout),
}
elasticURL, err := url.Parse(a.URLs[0])
if err != nil {
return fmt.Errorf("parsing URL failed: %w", err)
}
clientOptions = append(clientOptions,
elastic.SetHttpClient(httpclient),
elastic.SetSniff(a.EnableSniffer),
elastic.SetScheme(elasticURL.Scheme),
elastic.SetURL(a.URLs...),
elastic.SetHealthcheckInterval(time.Duration(a.HealthCheckInterval)),
elastic.SetHealthcheckTimeout(time.Duration(a.HealthCheckTimeout)),
elastic.SetGzip(a.EnableGzip),
)
if a.Username != "" && a.Password != "" {
clientOptions = append(clientOptions,
elastic.SetBasicAuth(a.Username, a.Password),
)
}
if a.AuthBearerToken != "" {
clientOptions = append(clientOptions,
elastic.SetHeaders(http.Header{
"Authorization": []string{fmt.Sprintf("Bearer %s", a.AuthBearerToken)},
}),
)
}
if time.Duration(a.HealthCheckInterval) == 0 {
clientOptions = append(clientOptions,
elastic.SetHealthcheck(false),
)
a.Log.Debugf("Disabling health check")
}
client, err := elastic.NewClient(clientOptions...)
if err != nil {
return err
}
// check for ES version on first node
esVersion, err := client.ElasticsearchVersion(a.URLs[0])
if err != nil {
return fmt.Errorf("elasticsearch version check failed: %w", err)
}
// quit if ES version is not supported
majorReleaseNumber, err := strconv.Atoi(strings.Split(esVersion, ".")[0])
if err != nil || majorReleaseNumber < 5 {
return fmt.Errorf("elasticsearch version not supported: %s", esVersion)
}
a.Log.Infof("Elasticsearch version: %q", esVersion)
a.Client = client
a.majorReleaseNumber = majorReleaseNumber
if a.ManageTemplate {
err := a.manageTemplate(ctx)
if err != nil {
return err
}
}
a.IndexName, a.tagKeys = a.GetTagKeys(a.IndexName)
a.pipelineName, a.pipelineTagKeys = a.GetTagKeys(a.UsePipeline)
return nil
}
// GetPointID generates a unique ID for a Metric Point
func GetPointID(m cua.Metric) string {
var buffer bytes.Buffer
// Timestamp(ns),measurement name and Series Hash for compute the final SHA256 based hash ID
buffer.WriteString(strconv.FormatInt(m.Time().Local().UnixNano(), 10)) //nolint:revive // from buffer.go: "err is always nil"
buffer.WriteString(m.Name()) //nolint:revive // from buffer.go: "err is always nil"
buffer.WriteString(strconv.FormatUint(m.HashID(), 10)) //nolint:revive // from buffer.go: "err is always nil"
return fmt.Sprintf("%x", sha256.Sum256(buffer.Bytes()))
}
func (a *Elasticsearch) Write(metrics []cua.Metric) (int, error) {
numMetrics := -1
if len(metrics) == 0 {
return numMetrics, nil
}
bulkRequest := a.Client.Bulk()
for _, metric := range metrics {
var name = metric.Name()
// index name has to be re-evaluated each time for circonus-unified-agent
// to send the metric to the correct time-based index
indexName := a.GetIndexName(a.IndexName, metric.Time(), a.tagKeys, metric.Tags())
// Handle NaN and inf field-values
fields := make(map[string]interface{})
for k, value := range metric.Fields() {
v, ok := value.(float64)
if !ok || a.FloatHandling == "none" || !(math.IsNaN(v) || math.IsInf(v, 0)) {
fields[k] = value
continue
}
if a.FloatHandling == "drop" {
continue
}
if math.IsNaN(v) || math.IsInf(v, 1) {
fields[k] = a.FloatReplacement
} else {
fields[k] = -a.FloatReplacement
}
}
m := make(map[string]interface{})
m["@timestamp"] = metric.Time()
m["measurement_name"] = name
m["tag"] = metric.Tags()
m[name] = fields
br := elastic.NewBulkIndexRequest().Index(indexName).Doc(m)
if a.ForceDocumentID {
id := GetPointID(metric)
br.Id(id)
}
if a.majorReleaseNumber <= 6 {
br.Type("metrics")
}
if a.UsePipeline != "" {
if pipelineName := a.getPipelineName(a.pipelineName, a.pipelineTagKeys, metric.Tags()); pipelineName != "" {
br.Pipeline(pipelineName)
}
}
bulkRequest.Add(br)
}
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(a.Timeout))
defer cancel()
res, err := bulkRequest.Do(ctx)
if err != nil {
return numMetrics, fmt.Errorf("error sending bulk request to Elasticsearch: %w", err)
}
if res.Errors {
for id, err := range res.Failed() {
a.Log.Errorf("Elasticsearch indexing failure, id: %d, error: %s, caused by: %s, %s", id, err.Error.Reason, err.Error.CausedBy["reason"], err.Error.CausedBy["type"])
break
}
return numMetrics, fmt.Errorf("elasticsearch failed to index %d metrics", len(res.Failed()))
}
return numMetrics, nil
}
func (a *Elasticsearch) manageTemplate(ctx context.Context) error {
if a.TemplateName == "" {
return fmt.Errorf("elasticsearch template_name configuration not defined")
}
templateExists, errExists := a.Client.IndexTemplateExists(a.TemplateName).Do(ctx) //nolint
if errExists != nil {
return fmt.Errorf("elasticsearch template check failed, template name: %s, error: %w", a.TemplateName, errExists)
}
templatePattern := a.IndexName
if strings.Contains(templatePattern, "%") {
templatePattern = templatePattern[0:strings.Index(templatePattern, "%")]
}
if strings.Contains(templatePattern, "{{") {
templatePattern = templatePattern[0:strings.Index(templatePattern, "{{")]
}
if templatePattern == "" {
return fmt.Errorf("template cannot be created for dynamic index names without an index prefix")
}
if (a.OverwriteTemplate) || (!templateExists) || (templatePattern != "") {
tp := templatePart{
TemplatePattern: templatePattern + "*",
Version: a.majorReleaseNumber,
}
t := template.Must(template.New("template").Parse(circonusTemplate))
var tmpl bytes.Buffer
if err := t.Execute(&tmpl, tp); err != nil {
return err
}
_, errCreateTemplate := a.Client.IndexPutTemplate(a.TemplateName).BodyString(tmpl.String()).Do(ctx) //nolint
if errCreateTemplate != nil {
return fmt.Errorf("elasticsearch failed to create index template %s : %w", a.TemplateName, errCreateTemplate)
}
a.Log.Debugf("Template %s created or updated\n", a.TemplateName)
} else {
a.Log.Debug("Found existing Elasticsearch template. Skipping template management")
}
return nil
}
func (a *Elasticsearch) GetTagKeys(indexName string) (string, []string) {
tagKeys := []string{}
startTag := strings.Index(indexName, "{{")
for startTag >= 0 {
endTag := strings.Index(indexName, "}}")
if endTag < 0 {
startTag = -1
} else {
tagName := indexName[startTag+2 : endTag]
var tagReplacer = strings.NewReplacer(
"{{"+tagName+"}}", "%s",
)
indexName = tagReplacer.Replace(indexName)
tagKeys = append(tagKeys, strings.TrimSpace(tagName))
startTag = strings.Index(indexName, "{{")
}
}
return indexName, tagKeys
}
func (a *Elasticsearch) GetIndexName(indexName string, eventTime time.Time, tagKeys []string, metricTags map[string]string) string {
if strings.Contains(indexName, "%") {
var dateReplacer = strings.NewReplacer(
"%Y", eventTime.UTC().Format("2006"),
"%y", eventTime.UTC().Format("06"),
"%m", eventTime.UTC().Format("01"),
"%d", eventTime.UTC().Format("02"),
"%H", eventTime.UTC().Format("15"),
"%V", getISOWeek(eventTime.UTC()),
)
indexName = dateReplacer.Replace(indexName)
}
tagValues := []interface{}{}
for _, key := range tagKeys {
if value, ok := metricTags[key]; ok {
tagValues = append(tagValues, value)
} else {
a.Log.Debugf("Tag '%s' not found, using '%s' on index name instead\n", key, a.DefaultTagValue)
tagValues = append(tagValues, a.DefaultTagValue)
}
}
return fmt.Sprintf(indexName, tagValues...)
}
func (a *Elasticsearch) getPipelineName(pipelineInput string, tagKeys []string, metricTags map[string]string) string {
if !strings.Contains(pipelineInput, "%") || len(tagKeys) == 0 {
return pipelineInput
}
var tagValues []interface{}
for _, key := range tagKeys {
if value, ok := metricTags[key]; ok {
tagValues = append(tagValues, value)
continue
}
a.Log.Debugf("Tag %s not found, reverting to default pipeline instead.", key)
return a.DefaultPipeline
}
return fmt.Sprintf(pipelineInput, tagValues...)
}
func getISOWeek(eventTime time.Time) string {
_, week := eventTime.ISOWeek()
return strconv.Itoa(week)
}
func (a *Elasticsearch) Close() error {
a.Client = nil
return nil
}
func init() {
outputs.Add("elasticsearch", func() cua.Output {
return &Elasticsearch{
Timeout: config.Duration(time.Second * 5),
HealthCheckInterval: config.Duration(time.Second * 10),
HealthCheckTimeout: config.Duration(time.Second * 1),
}
})
}