-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
elasticsearch.go
632 lines (516 loc) · 16.7 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
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
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package elasticsearch
import (
"encoding/json"
"errors"
"fmt"
"net/url"
"strconv"
"strings"
"sync"
"time"
"github.com/elastic/beats/v7/metricbeat/helper"
"github.com/elastic/beats/v7/metricbeat/helper/elastic"
"github.com/elastic/beats/v7/metricbeat/mb"
"github.com/elastic/elastic-agent-libs/logp"
"github.com/elastic/elastic-agent-libs/mapstr"
"github.com/elastic/elastic-agent-libs/version"
)
func init() {
// Register the ModuleFactory function for this module.
if err := mb.Registry.AddModule(ModuleName, NewModule); err != nil {
panic(err)
}
}
// NewModule creates a new module.
func NewModule(base mb.BaseModule) (mb.Module, error) {
xpackEnabledMetricSets := []string{
"ccr",
"enrich",
"cluster_stats",
"index",
"index_recovery",
"index_summary",
"ml_job",
"node_stats",
"shard",
}
optionalXpackMetricsets := []string{"ingest_pipeline"}
return elastic.NewModule(&base, xpackEnabledMetricSets, optionalXpackMetricsets, logp.NewLogger(ModuleName))
}
var (
// CCRStatsAPIAvailableVersion is the version of Elasticsearch since when the CCR stats API is available.
CCRStatsAPIAvailableVersion = version.MustNew("6.5.0")
// EnrichStatsAPIAvailableVersion is the version of Elasticsearch since when the Enrich stats API is available.
EnrichStatsAPIAvailableVersion = version.MustNew("7.5.0")
// BulkStatsAvailableVersion is the version since when bulk indexing stats are available
BulkStatsAvailableVersion = version.MustNew("8.0.0")
//ExpandWildcardsHiddenAvailableVersion is the version since when the "expand_wildcards" query parameter to
// the Indices Stats API can accept "hidden" as a value.
ExpandWildcardsHiddenAvailableVersion = version.MustNew("7.7.0")
// Global clusterIdCache. Assumption is that the same node id never can belong to a different cluster id.
clusterIDCache = map[string]string{}
)
// ModuleName is the name of this module.
const ModuleName = "elasticsearch"
// Info construct contains the data from the Elasticsearch / endpoint
type Info struct {
ClusterName string `json:"cluster_name"`
ClusterID string `json:"cluster_uuid"`
Version Version `json:"version"`
Name string `json:"name"`
}
// Version contains the semver formatted version of ES
type Version struct {
Number *version.V `json:"number"`
}
// NodeInfo struct cotains data about the node.
type NodeInfo struct {
Host string `json:"host"`
TransportAddress string `json:"transport_address"`
IP string `json:"ip"`
Name string `json:"name"`
ID string
}
// License contains data about the Elasticsearch license
type License struct {
Status string `json:"status"`
ID string `json:"uid"`
Type string `json:"type"`
IssueDate *time.Time `json:"issue_date"`
IssueDateInMillis int `json:"issue_date_in_millis"`
ExpiryDate *time.Time `json:"expiry_date,omitempty"`
ExpiryDateInMillis int `json:"expiry_date_in_millis,omitempty"`
MaxNodes int `json:"max_nodes,omitempty"`
MaxResourceUnits int `json:"max_resource_units,omitempty"`
IssuedTo string `json:"issued_to"`
Issuer string `json:"issuer"`
StartDateInMillis int `json:"start_date_in_millis"`
}
type licenseWrapper struct {
License License `json:"license"`
}
// GetClusterID fetches cluster id for given nodeID.
func GetClusterID(http *helper.HTTP, uri string, nodeID string) (string, error) {
// Check if cluster id already cached. If yes, return it.
if clusterID, ok := clusterIDCache[nodeID]; ok {
return clusterID, nil
}
info, err := GetInfo(http, uri)
if err != nil {
return "", err
}
clusterIDCache[nodeID] = info.ClusterID
return info.ClusterID, nil
}
// isMaster checks if the given node host is a master node.
//
// The detection of the master is done in two steps:
// * Fetch node name from /_nodes/_local/name
// * Fetch current master name from cluster state /_cluster/state/master_node
//
// The two names are compared
func isMaster(http *helper.HTTP, uri string) (bool, error) {
node, err := getNodeName(http, uri)
if err != nil {
return false, err
}
master, err := getMasterName(http, uri)
if err != nil {
return false, err
}
return master == node, nil
}
func getNodeName(http *helper.HTTP, uri string) (string, error) {
content, err := fetchPath(http, uri, "/_nodes/_local/nodes", "")
if err != nil {
return "", err
}
nodesStruct := struct {
Nodes map[string]interface{} `json:"nodes"`
}{}
err = json.Unmarshal(content, &nodesStruct)
if err != nil {
return "", err
}
// _local will only fetch one node info. First entry is node name
for k := range nodesStruct.Nodes {
return k, nil
}
return "", fmt.Errorf("no local node found")
}
func getMasterName(http *helper.HTTP, uri string) (string, error) {
content, err := fetchPath(http, uri, "_cluster/state/master_node", "local=true")
if err != nil {
return "", err
}
clusterStruct := struct {
MasterNode string `json:"master_node"`
}{}
err = json.Unmarshal(content, &clusterStruct)
if err != nil {
return "", err
}
return clusterStruct.MasterNode, nil
}
// GetInfo returns the data for the Elasticsearch / endpoint.
func GetInfo(http *helper.HTTP, uri string) (Info, error) {
content, err := fetchPath(http, uri, "/", "")
if err != nil {
return Info{}, err
}
info := Info{}
err = json.Unmarshal(content, &info)
if err != nil {
return Info{}, err
}
return info, nil
}
func fetchPath(http *helper.HTTP, uri, path string, query string) ([]byte, error) {
defer http.SetURI(uri)
// Parses the uri to replace the path
u, _ := url.Parse(uri)
u.Path = path
u.RawQuery = query
// Http helper includes the HostData with username and password
http.SetURI(u.String())
return http.FetchContent()
}
// GetNodeInfo returns the node information.
func GetNodeInfo(http *helper.HTTP, uri string, nodeID string) (*NodeInfo, error) {
content, err := fetchPath(http, uri, "/_nodes/_local/nodes", "")
if err != nil {
return nil, err
}
nodesStruct := struct {
Nodes map[string]*NodeInfo `json:"nodes"`
}{}
err = json.Unmarshal(content, &nodesStruct)
if err != nil {
return nil, err
}
// _local will only fetch one node info. First entry is node name
for k, v := range nodesStruct.Nodes {
// In case the nodeID is empty, first node info will be returned
if k == nodeID || nodeID == "" {
v.ID = k
return v, nil
}
}
return nil, fmt.Errorf("no node matched id %s", nodeID)
}
// GetLicense returns license information. Since we don't expect license information
// to change frequently, the information is cached for 1 minute to avoid
// hitting Elasticsearch frequently.
func GetLicense(http *helper.HTTP, resetURI string) (*License, error) {
// First, check the cache
license := licenseCache.get()
// License found in cache, return it
if license != nil {
return license, nil
}
// License not found in cache, fetch it from Elasticsearch
content, err := fetchPath(http, resetURI, "_license", "")
if err != nil {
return nil, err
}
var data licenseWrapper
err = json.Unmarshal(content, &data)
if err != nil {
return nil, err
}
// Cache license for a minute
license = &data.License
licenseCache.set(license, time.Minute)
return license, nil
}
// GetClusterState returns cluster state information.
func GetClusterState(http *helper.HTTP, resetURI string, metrics []string) (mapstr.M, error) {
clusterStateURI := "_cluster/state"
if len(metrics) > 0 {
clusterStateURI += "/" + strings.Join(metrics, ",")
}
content, err := fetchPath(http, resetURI, clusterStateURI, "local=true")
if err != nil {
return nil, err
}
var clusterState map[string]interface{}
err = json.Unmarshal(content, &clusterState)
return clusterState, err
}
// GetClusterSettingsWithDefaults returns cluster settings.
func GetClusterSettingsWithDefaults(http *helper.HTTP, resetURI string, filterPaths []string) (mapstr.M, error) {
return GetClusterSettings(http, resetURI, true, filterPaths)
}
// GetClusterSettings returns cluster settings
func GetClusterSettings(http *helper.HTTP, resetURI string, includeDefaults bool, filterPaths []string) (mapstr.M, error) {
clusterSettingsURI := "_cluster/settings"
var queryParams []string
if includeDefaults {
queryParams = append(queryParams, "include_defaults=true")
}
if len(filterPaths) > 0 {
filterPathQueryParam := "filter_path=" + strings.Join(filterPaths, ",")
queryParams = append(queryParams, filterPathQueryParam)
}
queryString := strings.Join(queryParams, "&")
content, err := fetchPath(http, resetURI, clusterSettingsURI, queryString)
if err != nil {
return nil, err
}
var clusterSettings map[string]interface{}
err = json.Unmarshal(content, &clusterSettings)
return clusterSettings, err
}
// GetStackUsage returns stack usage information.
func GetStackUsage(http *helper.HTTP, resetURI string) (map[string]interface{}, error) {
content, err := fetchPath(http, resetURI, "_xpack/usage", "")
if err != nil {
return nil, err
}
var stackUsage map[string]interface{}
err = json.Unmarshal(content, &stackUsage)
return stackUsage, err
}
type XPack struct {
Features struct {
CCR struct {
Enabled bool `json:"enabled"`
} `json:"CCR"`
} `json:"features"`
}
// GetXPack returns information about xpack features.
func GetXPack(http *helper.HTTP, resetURI string) (XPack, error) {
content, err := fetchPath(http, resetURI, "_xpack", "")
if err != nil {
return XPack{}, err
}
var xpack XPack
err = json.Unmarshal(content, &xpack)
return xpack, err
}
type boolStr bool
func (b *boolStr) UnmarshalJSON(raw []byte) error {
var bs string
err := json.Unmarshal(raw, &bs)
if err != nil {
return err
}
bv, err := strconv.ParseBool(bs)
if err != nil {
return err
}
*b = boolStr(bv)
return nil
}
type IndexSettings struct {
Hidden bool
}
// GetIndicesSettings returns a map of index names to their settings.
// Note that as of now it is optimized to fetch only the "hidden" index setting to keep the memory
// footprint of this function call as low as possible.
func GetIndicesSettings(http *helper.HTTP, resetURI string) (map[string]IndexSettings, error) {
content, err := fetchPath(http, resetURI, "*/_settings", "filter_path=*.settings.index.hidden&expand_wildcards=all")
if err != nil {
return nil, fmt.Errorf("could not fetch indices settings: %w", err)
}
var resp map[string]struct {
Settings struct {
Index struct {
Hidden boolStr `json:"hidden"`
} `json:"index"`
} `json:"settings"`
}
err = json.Unmarshal(content, &resp)
if err != nil {
return nil, fmt.Errorf("could not parse indices settings response: %w", err)
}
ret := make(map[string]IndexSettings, len(resp))
for index, settings := range resp {
ret[index] = IndexSettings{
Hidden: bool(settings.Settings.Index.Hidden),
}
}
return ret, nil
}
// IsMLockAllEnabled returns if the given Elasticsearch node has mlockall enabled
func IsMLockAllEnabled(http *helper.HTTP, resetURI, nodeID string) (bool, error) {
content, err := fetchPath(http, resetURI, "_nodes/"+nodeID, "filter_path=nodes.*.process.mlockall")
if err != nil {
return false, err
}
var response map[string]map[string]map[string]map[string]bool
err = json.Unmarshal(content, &response)
if err != nil {
return false, err
}
for _, nodeInfo := range response["nodes"] {
mlockall := nodeInfo["process"]["mlockall"]
return mlockall, nil
}
return false, fmt.Errorf("could not determine if mlockall is enabled on node ID = %v", nodeID)
}
// GetMasterNodeID returns the ID of the Elasticsearch cluster's master node
func GetMasterNodeID(http *helper.HTTP, resetURI string) (string, error) {
content, err := fetchPath(http, resetURI, "_nodes/_master", "filter_path=nodes.*.name")
if err != nil {
return "", err
}
var response struct {
Nodes map[string]interface{} `json:"nodes"`
}
if err := json.Unmarshal(content, &response); err != nil {
return "", err
}
for nodeID := range response.Nodes {
return nodeID, nil
}
return "", errors.New("could not determine master node ID")
}
// PassThruField copies the field at the given path from the given source data object into
// the same path in the given target data object.
func PassThruField(fieldPath string, sourceData, targetData mapstr.M) error {
fieldValue, err := sourceData.GetValue(fieldPath)
if err != nil {
return elastic.MakeErrorForMissingField(fieldPath, elastic.Elasticsearch)
}
targetData.Put(fieldPath, fieldValue)
return nil
}
// MergeClusterSettings merges cluster settings in the correct precedence order
func MergeClusterSettings(clusterSettings mapstr.M) (mapstr.M, error) {
transientSettings, err := getSettingGroup(clusterSettings, "transient")
if err != nil {
return nil, err
}
persistentSettings, err := getSettingGroup(clusterSettings, "persistent")
if err != nil {
return nil, err
}
settings, err := getSettingGroup(clusterSettings, "default")
if err != nil {
return nil, err
}
// Transient settings override persistent settings which override default settings
if settings == nil {
settings = persistentSettings
}
if settings == nil {
settings = transientSettings
}
if settings == nil {
return nil, nil
}
if persistentSettings != nil {
settings.DeepUpdate(persistentSettings)
}
if transientSettings != nil {
settings.DeepUpdate(transientSettings)
}
return settings, nil
}
var (
// Global cache for license information. Assumption is that license information changes infrequently.
licenseCache = &_licenseCache{}
// LicenseCacheEnabled controls whether license caching is enabled or not. Intended for test use.
LicenseCacheEnabled = true
)
type _licenseCache struct {
sync.RWMutex
license *License
cachedOn time.Time
ttl time.Duration
}
func (c *_licenseCache) get() *License {
c.Lock()
defer c.Unlock()
if time.Since(c.cachedOn) > c.ttl {
// We are past the TTL, so invalidate cache
c.license = nil
}
return c.license
}
func (c *_licenseCache) set(license *License, ttl time.Duration) {
if !LicenseCacheEnabled {
return
}
c.Lock()
defer c.Unlock()
c.license = license
c.ttl = ttl
c.cachedOn = time.Now()
}
// IsOneOf returns whether the license is one of the specified candidate licenses
func (l *License) IsOneOf(candidateLicenses ...string) bool {
t := l.Type
for _, candidateLicense := range candidateLicenses {
if candidateLicense == t {
return true
}
}
return false
}
// ToMapStr converts the license to a mapstr.M. This is necessary
// for proper marshaling of the data before it's sent over the wire. In
// particular it ensures that ms-since-epoch values are marshaled as longs
// and not floats in scientific notation as Elasticsearch does not like that.
func (l *License) ToMapStr() mapstr.M {
m := mapstr.M{
"status": l.Status,
"uid": l.ID,
"type": l.Type,
"issue_date": l.IssueDate,
"issue_date_in_millis": l.IssueDateInMillis,
"expiry_date": l.ExpiryDate,
"issued_to": l.IssuedTo,
"issuer": l.Issuer,
"start_date_in_millis": l.StartDateInMillis,
}
if l.ExpiryDateInMillis != 0 {
// We don't want to record a 0 expiry date as this means the license has expired
// in the Stack Monitoring UI
m["expiry_date_in_millis"] = l.ExpiryDateInMillis
}
// Enterprise licenses have max_resource_units. All other licenses have
// max_nodes.
if l.MaxNodes != 0 {
m["max_nodes"] = l.MaxNodes
}
if l.MaxResourceUnits != 0 {
m["max_resource_units"] = l.MaxResourceUnits
}
return m
}
func getSettingGroup(allSettings mapstr.M, groupKey string) (mapstr.M, error) {
hasSettingGroup, err := allSettings.HasKey(groupKey)
if err != nil {
return nil, fmt.Errorf("failure to determine if "+groupKey+" settings exist: %w", err)
}
if !hasSettingGroup {
return nil, nil
}
settings, err := allSettings.GetValue(groupKey)
if err != nil {
return nil, fmt.Errorf("failure to extract "+groupKey+" settings: %w", err)
}
v, ok := settings.(map[string]interface{})
if !ok {
return nil, fmt.Errorf(groupKey + " settings are not a map")
}
return mapstr.M(v), nil
}