-
Notifications
You must be signed in to change notification settings - Fork 55
/
es.go
1825 lines (1468 loc) · 52.8 KB
/
es.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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package vulcanizer
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"net/http"
"regexp"
"sort"
"strings"
"time"
"github.com/jeremywohl/flatten"
"github.com/parnurzeal/gorequest"
"github.com/tidwall/gjson"
)
// Hold the values for what values are in the cluster.allocation.exclude settings.
// Relevant Elasticsearch documentation: https://www.elastic.co/guide/en/elasticsearch/reference/5.6/allocation-filtering.html
type ExcludeSettings struct {
Ips, Hosts, Names []string
}
type Auth struct {
User string
Password string
}
// Hold connection information to a Elasticsearch cluster.
type Client struct {
Host string
Port int
Secure bool
Path string
TLSConfig *tls.Config
Timeout time.Duration
*Auth
}
// Holds information about an Elasticsearch node, based on a combination of the
// _cat/nodes and _cat/allocationAPI: https://www.elastic.co/guide/en/elasticsearch/reference/5.6/cat-nodes.html,
// https://www.elastic.co/guide/en/elasticsearch/reference/5.6/cat-allocation.html
type Node struct {
Name string `json:"name"`
IP string `json:"ip"`
ID string `json:"id"`
Role string `json:"role"`
Master string `json:"master"`
Jdk string `json:"jdk"`
Version string `json:"version"`
Shards string
DiskIndices string
DiskUsed string
DiskAvail string
DiskTotal string
DiskPercent string
}
// Holds a subset of information from the _nodes/stats endpoint:
// https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-nodes-stats.html
type NodeStats struct {
Name string
Role string
JVMStats NodeJVM
}
// Holds information about an Elasticsearch node's JVM settings.
// From _nodes/stats/jvm: https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-nodes-stats.html
type NodeJVM struct {
HeapUsedBytes int `json:"heap_used_in_bytes"`
HeapUsedPercentage int `json:"heap_used_percent"`
HeapMaxBytes int `json:"heap_max_in_bytes"`
NonHeapUsedBytes int `json:"non_heap_used_in_bytes"`
NonHeapCommittedBytes int `json:"non_heap_committed_in_bytes"`
}
// DiskAllocation holds disk allocation information per node, based on _cat/allocation
// API: https://www.elastic.co/guide/en/elasticsearch/reference/5.6/cat-allocation.html
type DiskAllocation struct {
Name string `json:"name"`
IP string `json:"ip"`
Node string `json:"node"`
Shards string `json:"shards"`
DiskIndices string `json:"disk.indices"`
DiskUsed string `json:"disk.used"`
DiskAvail string `json:"disk.avail"`
DiskTotal string `json:"disk.total"`
DiskPercent string `json:"disk.percent"`
}
// Holds information about an Elasticsearch index, based on the _cat/indices
// API: https://www.elastic.co/guide/en/elasticsearch/reference/5.6/cat-indices.html
type Index struct {
Health string `json:"health"`
Status string `json:"status"`
Name string `json:"index"`
PrimaryShards int `json:"pri,string"`
ReplicaCount int `json:"rep,string"`
IndexSize string `json:"store.size"`
DocumentCount int `json:"docs.count,string"`
}
// Holds information about an index shard, based on the _cat/shards
// API: https://www.elastic.co/guide/en/elasticsearch/reference/5.6/cat-shards.html
type Shard struct {
Index string `json:"index"`
Shard string `json:"shard"`
Type string `json:"prirep"`
State string `json:"state"`
Docs string `json:"docs"`
Store string `json:"store"`
IP string `json:"ip"`
Node string `json:"node"`
}
// Holds information about overlapping shards for a given set of cluster nodes
type ShardOverlap struct {
Index string
Shard string
PrimaryFound bool
ReplicasFound int
ReplicasTotal int
}
// Holds information about shard recovery based on the _cat/recovery
// API: https://www.elastic.co/guide/en/elasticsearch/reference/5.6/cat-recovery.html
type ShardRecovery struct {
Index string `json:"index"`
Shard string `json:"shard"`
Time string `json:"time"`
Type string `json:"type"`
Stage string `json:"stage"`
SourceHost string `json:"source_host"`
SourceNode string `json:"source_node"`
TargetHost string `json:"target_host"`
TargetNode string `json:"target_node"`
Repository string `json:"repository"`
Snapshot string `json:"snapshot"`
Files int `json:"files,string"`
FilesRecovered int `json:"files_recovered,string"`
FilesPercent string `json:"files_percent"`
FilesTotal int `json:"files_total,string"`
Bytes int `json:"bytes,string"`
BytesRecovered int `json:"bytes_recovered,string"`
BytesPercent string `json:"bytes_percent"`
BytesTotal int `json:"bytes_total,string"`
TranslogOps int `json:"translog_ops,string"`
TranslogOpsRecovered int `json:"translog_ops_recovered,string"`
TranslogOpsPercent string `json:"translog_ops_percent"`
}
// Holds information about an Elasticsearch alias, based on the _cat/aliases
// API: https://www.elastic.co/guide/en/elasticsearch/reference/5.6/cat-alias.html
type Alias struct {
Name string `json:"alias"`
IndexName string `json:"index"`
Filter string `json:"filter"`
RoutingIndex string `json:"routing.index"`
RoutingSearch string `json:"routing.search"`
}
// Represent the two possible aliases actions: add or remove
type AliasActionType string
const (
AddAlias AliasActionType = "add"
RemoveAlias AliasActionType = "remove"
)
// Holds information needed to perform an alias modification, based on the aliases
// API: https://www.elastic.co/guide/en/elasticsearch/reference/5.6/indices-aliases.html
type AliasAction struct {
ActionType AliasActionType
IndexName string `json:"index"`
AliasName string `json:"alias"`
}
func (ac *AliasAction) MarshalJSON() ([]byte, error) {
return json.Marshal(
&map[AliasActionType]struct {
IndexName string `json:"index"`
AliasName string `json:"alias"`
}{
ac.ActionType: {
IndexName: ac.IndexName,
AliasName: ac.AliasName,
},
},
)
}
// Holds information about the health of an Elasticsearch cluster, based on the
// cluster health API: https://www.elastic.co/guide/en/elasticsearch/reference/5.6/cluster-health.html
type ClusterHealth struct {
Cluster string `json:"cluster_name"`
Status string `json:"status"`
ActiveShards int `json:"active_shards"`
RelocatingShards int `json:"relocating_shards"`
InitializingShards int `json:"initializing_shards"`
UnassignedShards int `json:"unassigned_shards"`
ActiveShardsPercentage float64 `json:"active_shards_percent_as_number"`
Message string
RawIndices map[string]IndexHealth `json:"indices"`
HealthyIndices []IndexHealth
UnhealthyIndices []IndexHealth
}
// Holds information about the health of an Elasticsearch index, based on the index
// level of the cluster health API: https://www.elastic.co/guide/en/elasticsearch/reference/5.6/cluster-health.html
type IndexHealth struct {
Name string
Status string `json:"status"`
ActiveShards int `json:"active_shards"`
RelocatingShards int `json:"relocating_shards"`
InitializingShards int `json:"initializing_shards"`
UnassignedShards int `json:"unassigned_shards"`
}
// Holds slices for persistent and transient cluster settings.
type ClusterSettings struct {
PersistentSettings []Setting
TransientSettings []Setting
}
// A setting name and value with the setting name to be a "collapsed" version of
// the setting. A setting of:
//
// { "indices": { "recovery" : { "max_bytes_per_sec": "10mb" } } }
//
// would be represented by:
//
// ClusterSetting{ Setting: "indices.recovery.max_bytes_per_sec", Value: "10mb" }
type Setting struct {
Setting string
Value string
}
type snapshotWrapper struct {
Snapshots []Snapshot `json:"snapshots"`
}
type acknowledgedResponse struct {
Acknowledged bool `json:"acknowledged"`
}
// Holds information about an Elasticsearch snapshot, based on the snapshot
// API: https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html
type Snapshot struct {
State string `json:"state"`
Name string `json:"snapshot"`
StartTime time.Time `json:"start_time"`
EndTime time.Time `json:"end_time"`
DurationMillis int `json:"duration_in_millis"`
Indices []string `json:"indices"`
Shards struct {
Total int `json:"total"`
Failed int `json:"failed"`
Successful int `json:"successful"`
} `json:"shards"`
Failures []struct {
Index string `json:"index"`
ShardID int `json:"shard_id"`
Reason string `json:"reason"`
NodeID string `json:"node_id"`
Status string `json:"status"`
} `json:"failures"`
}
// Holds information about an Elasticsearch snapshot repository.
type Repository struct {
Name string
Type string
Settings map[string]interface{}
}
// Internal struct for repository requests since Name is part of URL path
type repo struct {
Type string `json:"type"`
Settings map[string]interface{} `json:"settings"`
}
// Holds information about the tokens that Elasticsearch analyzes
type Token struct {
Text string `json:"token"`
StartOffset int `json:"start_offset"`
EndOffset int `json:"end_offset"`
Type string `json:"type"`
Position int `json:"position"`
}
type ReloadSecureSettingsResponse struct {
Summary struct {
Total int `json:"total"`
Failed int `json:"failed"`
Successful int `json:"successful"`
} `json:"_nodes"`
ClusterName string `json:"cluster_name"`
Nodes map[string]struct {
Name string `json:"name"`
ReloadException *struct {
Type string `json:"type"`
Reason string `json:"reason"`
} `json:"reload_exception"`
} `json:"nodes"`
}
// Initialize a new vulcanizer client to use.
// Deprecated: NewClient has been deprecated in favor of using struct initialization.
func NewClient(host string, port int) *Client {
if port > 0 {
return &Client{Host: host, Port: port}
}
return &Client{Host: host}
}
const clusterSettingsPath = "_cluster/settings"
func settingsToStructs(rawJSON string) ([]Setting, error) {
flatSettings, err := flatten.FlattenString(rawJSON, "", flatten.DotStyle)
if err != nil {
return nil, err
}
settingsMap, _ := gjson.Parse(flatSettings).Value().(map[string]interface{})
keys := []string{}
for k, v := range settingsMap {
strValue := v.(string)
if strValue != "" {
keys = append(keys, k)
}
}
sort.Strings(keys)
clusterSettings := make([]Setting, 0, len(keys))
for _, k := range keys {
setting := Setting{
Setting: k,
Value: settingsMap[k].(string),
}
clusterSettings = append(clusterSettings, setting)
}
return clusterSettings, nil
}
func handleErrWithBytes(s *gorequest.SuperAgent) ([]byte, error) {
response, body, errs := s.EndBytes()
if len(errs) > 0 {
return nil, combineErrors(errs)
}
if response.StatusCode != http.StatusOK {
errorMessage := fmt.Sprintf("Bad HTTP Status from Elasticsearch: %v, %s", response.StatusCode, body)
return nil, errors.New(errorMessage)
}
return body, nil
}
func handleErrWithStruct(s *gorequest.SuperAgent, v interface{}) error {
response, body, errs := s.EndStruct(v)
if len(errs) > 0 {
return combineErrors(errs)
}
if response.StatusCode != http.StatusOK {
errorMessage := fmt.Sprintf("Bad HTTP Status from Elasticsearch: %v, %s", response.StatusCode, body)
return errors.New(errorMessage)
}
return nil
}
// Estimate time remaining for recovery
func (s ShardRecovery) TimeRemaining() (time.Duration, error) {
elapsed, err := time.ParseDuration(s.Time)
if err != nil {
return time.Second, err
}
// Calculate the rate of change
rate := float64(s.BytesRecovered) / elapsed.Seconds()
bytesLeft := s.BytesTotal - s.BytesRecovered
// Divide the remaining bytes to recover by the rate of change
return time.Duration(float64(bytesLeft)/rate) * time.Second, nil
}
// Can we safely remove nodes without data loss?
func (s ShardOverlap) SafeToRemove() bool {
return !(s.PrimaryFound && s.ReplicasFound >= s.ReplicasTotal)
}
// Check if we should consider shard as a primary shard
func (s ShardOverlap) isPrimaryShard(shard Shard) bool {
return shard.Type == "p" && (shard.State == "STARTED" || shard.State == "RELOCATING")
}
// Check if we should consider shard as a replica shard
func (s ShardOverlap) isReplicaShard(shard Shard) bool {
return shard.Type == "r" && (shard.State == "STARTED" || shard.State == "RELOCATING")
}
func (c *Client) getAgent(method, path string) *gorequest.SuperAgent {
agent := gorequest.New().Set("Accept", "application/json").Set("Content-Type", "application/json")
agent.Method = method
var protocol string
if c.Secure {
protocol = "https"
} else {
protocol = "http"
}
if c.Path != "" {
path = fmt.Sprintf("%s/%s", c.Path, path)
}
if c.Port > 0 {
agent.Url = fmt.Sprintf("%s://%s:%v/%s", protocol, c.Host, c.Port, path)
} else {
agent.Url = fmt.Sprintf("%s://%s/%s", protocol, c.Host, path)
}
if c.Auth != nil {
agent.SetBasicAuth(c.Auth.User, c.Auth.Password)
}
if c.TLSConfig != nil {
agent.TLSClientConfig(c.TLSConfig)
}
if c.Timeout != 0 {
agent.Timeout(c.Timeout)
} else {
agent.Timeout(1 * time.Minute)
}
return agent
}
func (c *Client) buildGetRequest(path string) *gorequest.SuperAgent {
return c.getAgent(gorequest.GET, path)
}
func (c *Client) buildPutRequest(path string) *gorequest.SuperAgent {
return c.getAgent(gorequest.PUT, path)
}
func (c *Client) buildDeleteRequest(path string) *gorequest.SuperAgent {
return c.getAgent(gorequest.DELETE, path)
}
func (c *Client) buildPostRequest(path string) *gorequest.SuperAgent {
return c.getAgent(gorequest.POST, path)
}
// Get current cluster settings for shard allocation exclusion rules.
func (c *Client) GetClusterExcludeSettings() (ExcludeSettings, error) {
body, err := handleErrWithBytes(c.buildGetRequest(clusterSettingsPath))
if err != nil {
return ExcludeSettings{}, err
}
excludedArray := gjson.GetManyBytes(body, "transient.cluster.routing.allocation.exclude._ip", "transient.cluster.routing.allocation.exclude._name", "transient.cluster.routing.allocation.exclude._host")
excludeSettings := excludeSettingsFromJSON(excludedArray)
return excludeSettings, nil
}
// Set shard allocation exclusion rules such that the Elasticsearch node with
// the name `serverToDrain` is excluded. This should cause Elasticsearch to
// migrate shards away from that node.
//
// Use case: You need to restart an Elasticsearch node. In order to do so safely,
// you should migrate data away from it. Calling `DrainServer` with the node name
// will move data off of the specified node.
func (c *Client) DrainServer(serverToDrain string) (ExcludeSettings, error) {
excludeSettings, err := c.GetClusterExcludeSettings()
if err != nil {
return ExcludeSettings{}, err
}
excludeSettings.Names = append(excludeSettings.Names, serverToDrain)
agent := c.buildPutRequest(clusterSettingsPath).
Set("Content-Type", "application/json").
Send(fmt.Sprintf(`{"transient" : { "cluster.routing.allocation.exclude._name" : "%s"}}`, strings.Join(excludeSettings.Names, ",")))
_, err = handleErrWithBytes(agent)
if err != nil {
return ExcludeSettings{}, err
}
return excludeSettings, nil
}
// Set shard allocation exclusion rules such that the Elasticsearch node with
// the name `serverToFill` is no longer being excluded. This should cause
// Elasticsearch to migrate shards to that node.
//
// Use case: You have completed maintenance on an Elasticsearch node and it's
// ready to hold data again. Calling `FillOneServer` with the node name will
// remove that node name from the shard exclusion rules and allow data to be
// relocated onto the node.
func (c *Client) FillOneServer(serverToFill string) (ExcludeSettings, error) {
// Get the current list of strings
excludeSettings, err := c.GetClusterExcludeSettings()
if err != nil {
return ExcludeSettings{}, err
}
serverToFill = strings.TrimSpace(serverToFill)
newNamesDrained := []string{}
for _, s := range excludeSettings.Names {
if s != serverToFill {
newNamesDrained = append(newNamesDrained, s)
}
}
agent := c.buildPutRequest(clusterSettingsPath).
Set("Content-Type", "application/json").
Send(fmt.Sprintf(`{"transient" : { "cluster.routing.allocation.exclude._name" : "%s"}}`, strings.Join(newNamesDrained, ",")))
_, err = handleErrWithBytes(agent)
if err != nil {
return ExcludeSettings{}, err
}
return c.GetClusterExcludeSettings()
}
// Removes all shard allocation exclusion rules.
//
// Use case: You had been performing maintenance on a number of Elasticsearch
// nodes. They are all ready to receive data again. Calling `FillAll` will
// remove all the allocation exclusion rules on the cluster, allowing
// Elasticsearch to freely allocate shards on the previously excluded nodes.
func (c *Client) FillAll() (ExcludeSettings, error) {
agent := c.buildPutRequest(clusterSettingsPath).
Set("Content-Type", "application/json").
Send(`{"transient" : { "cluster.routing.allocation.exclude" : { "_name" : "", "_ip" : "", "_host" : ""}}}`)
body, err := handleErrWithBytes(agent)
if err != nil {
return ExcludeSettings{}, err
}
excludedArray := gjson.GetManyBytes(body, "transient.cluster.routing.allocation.exclude._ip", "transient.cluster.routing.allocation.exclude._name", "transient.cluster.routing.allocation.exclude._host")
return excludeSettingsFromJSON(excludedArray), nil
}
// Get all the nodes in the cluster.
//
// Use case: You want to see what nodes Elasticsearch considers part of the cluster.
func (c *Client) GetNodes() ([]Node, error) {
var nodes []Node
agent := c.buildGetRequest("_cat/nodes?h=master,role,name,ip,id,jdk,version")
err := handleErrWithStruct(agent, &nodes)
if err != nil {
return nil, err
}
return nodes, nil
}
// Get all the nodes and their allocation/disk usage in the cluster.
//
// Use case: You want to see how much disk is being used by the nodes in the cluster.
func (c *Client) GetNodeAllocations() ([]Node, error) {
var nodes []Node
var nodeErr error
// Get the node info first
nodes, nodeErr = c.GetNodes()
if nodeErr != nil {
return nil, nodeErr
}
// Now get the allocation info and decorate the existing nodes
var allocations []DiskAllocation
agent := c.buildGetRequest("_cat/allocation?v&h=shards,disk.indices,disk.used,disk.avail,disk.total,disk.percent,ip,name,node")
err := handleErrWithStruct(agent, &allocations)
if err != nil {
return nil, err
}
nodes = enrichNodesWithAllocations(nodes, allocations)
return nodes, nil
}
// Get all the nodes' JVM Heap statistics.
//
// Use case: You want to see how much heap each node is using and their max heap size.
func (c *Client) GetNodeJVMStats() ([]NodeStats, error) {
// NodeStats is not the top level of "nodes" as the individual node name
// is the key of each node. Eg. "nodes.H1iBOLqqToyT8CHF9C0W0w.name = es-node-1".
// This is tricky to unmarshal to struct, so let gjson deal with it.
var nodesStats []NodeStats
// Get node stats/jvm
agent := c.buildGetRequest("_nodes/stats/jvm")
bytes, err := handleErrWithBytes(agent)
if err != nil {
return nil, err
}
nodesRes := gjson.GetBytes(bytes, "nodes")
var itErr error
// Iterate over each node.
nodesRes.ForEach(func(key, value gjson.Result) bool {
var jvmStats NodeJVM
memString := value.Get("jvm.mem").String()
err = json.Unmarshal([]byte(memString), &jvmStats)
if err != nil {
itErr = fmt.Errorf("failed to unmarshal mem stats: %w", err)
return false
}
// Let's grab the nodes role(s). Different format depending on version
var role string
if value.Get("attributes.master").Exists() {
// Probably Elasticsearch 1.7
masterRole := value.Get("attributes.master").String()
dataRole := value.Get("attributes.data").String()
if dataRole != "false" {
role = "d"
}
if masterRole == "true" {
role = "M" + role
}
}
if value.Get("roles").Exists() {
// Probably Elasticsearch 5+
// Elasticsearch 5,6 and 7 has quite a few roles, let's collect them
roleRes := value.Get("roles").Array()
for _, res := range roleRes {
sr := res.String()
if sr == "master" {
role = "M" + role
continue
}
role += sr[:1]
}
}
nodeStat := NodeStats{
Name: value.Get("name").String(),
Role: role,
JVMStats: jvmStats,
}
nodesStats = append(nodesStats, nodeStat)
return true
})
if itErr != nil {
return nil, itErr
}
return nodesStats, nil
}
// Get all the indices in the cluster.
//
// Use case: You want to see some basic info on all the indices of the cluster.
func (c *Client) GetAllIndices() ([]Index, error) {
var indices []Index
err := handleErrWithStruct(c.buildGetRequest("_cat/indices?h=health,status,index,pri,rep,store.size,docs.count"), &indices)
if err != nil {
return nil, err
}
return indices, nil
}
// Get a subset of indices
func (c *Client) GetIndices(index string) ([]Index, error) {
var indices []Index
err := handleErrWithStruct(c.buildGetRequest(fmt.Sprintf("_cat/indices/%s?h=health,status,index,pri,rep,store.size,docs.count", index)), &indices)
if err != nil {
return nil, err
}
return indices, nil
}
// Get a subset of indices including hidden ones
func (c *Client) GetHiddenIndices(index string) ([]Index, error) {
var indices []Index
err := handleErrWithStruct(c.buildGetRequest(fmt.Sprintf("_cat/indices/%s?h=health,status,index,pri,rep,store.size,docs.count&expand_wildcards=open,closed,hidden", index)), &indices)
if err != nil {
return nil, err
}
return indices, nil
}
// Get all the aliases in the cluster.
//
// Use case: You want to see some basic info on all the aliases of the cluster
func (c *Client) GetAllAliases() ([]Alias, error) {
var aliases []Alias
err := handleErrWithStruct(c.buildGetRequest("_cat/aliases?h=alias,index,filter,routing.index,routing.search"), &aliases)
if err != nil {
return nil, err
}
return aliases, nil
}
// Get a subset the aliases in the cluster.
//
// Use case: You want to see some basic info on a subset of the aliases of the cluster
func (c *Client) GetAliases(alias string) ([]Alias, error) {
var aliases []Alias
path := fmt.Sprintf("_cat/aliases/%s?h=alias,index,filter,routing.index,routing.search", alias)
err := handleErrWithStruct(c.buildGetRequest(path), &aliases)
if err != nil {
return nil, err
}
return aliases, nil
}
// Interact with aliases in the cluster.
//
// Use case: You want to add, delete or update an index alias
func (c *Client) ModifyAliases(actions []AliasAction) error {
request := map[string][]AliasAction{"actions": actions}
agent := c.buildPostRequest("_aliases").
Set("Content-Type", "application/json").
Send(request)
var response struct {
Acknowledged bool `json:"acknowledged"`
}
err := handleErrWithStruct(agent, &response)
if err != nil {
return err
}
return nil
}
// Delete an index in the cluster.
//
// Use case: You want to remove an index and all of its data.
func (c *Client) DeleteIndex(indexName string) error {
return c.DeleteIndexWithQueryParameters(indexName, nil)
}
// Delete an index in the cluster with query parameters.
//
// Use case: You want to remove an index and all of its data. You also want to
// specify query parameters such as timeout.
func (c *Client) DeleteIndexWithQueryParameters(indexName string, queryParamMap map[string][]string) error {
queryParams := make([]string, 0, len(queryParamMap))
for key, value := range queryParamMap {
queryParams = append(queryParams, fmt.Sprintf("%s=%s", key,
strings.Join(value, ",")))
}
queryString := strings.Join(queryParams, "&")
agent := c.buildDeleteRequest(fmt.Sprintf("%s?%s", indexName, queryString))
var response acknowledgedResponse
err := handleErrWithStruct(agent, &response)
if err != nil {
return err
}
if !response.Acknowledged {
return fmt.Errorf(`Request to delete index "%s" was not acknowledged. %+v`, indexName, response)
}
return nil
}
// Open an index on the cluster
//
// Use case: You want to open a closed index
func (c *Client) OpenIndex(indexName string) error {
// var response acknowledgedResponse
var response struct {
Acknowledged bool `json:"acknowledged"`
}
err := handleErrWithStruct(c.buildPostRequest(fmt.Sprintf("%s/_open", indexName)), &response)
if err != nil {
return err
}
if !response.Acknowledged {
return fmt.Errorf(`Request to open index "%s" was not acknowledged. %+v`, indexName, response)
}
return nil
}
// Close an index on the cluster
//
// Use case: You want to close an opened index
func (c *Client) CloseIndex(indexName string) error {
// var response acknowledgedResponse
var response struct {
Acknowledged bool `json:"acknowledged"`
}
err := handleErrWithStruct(c.buildPostRequest(fmt.Sprintf("%s/_close", indexName)), &response)
if err != nil {
return err
}
if !response.Acknowledged {
return fmt.Errorf(`Request to close index "%s" was not acknowledged. %+v`, indexName, response)
}
return nil
}
// Get the health of the cluster.
//
// Use case: You want to see information needed to determine if the Elasticsearch cluster is healthy (green) or not (yellow/red).
func (c *Client) GetHealth() (ClusterHealth, error) {
var health ClusterHealth
err := handleErrWithStruct(c.buildGetRequest("_cluster/health?level=indices"), &health)
if err != nil {
return ClusterHealth{}, err
}
for indexName, index := range health.RawIndices {
index.Name = indexName
if index.Status == "green" {
health.HealthyIndices = append(health.HealthyIndices, index)
} else {
health.UnhealthyIndices = append(health.UnhealthyIndices, index)
}
}
health.Message = captionHealth(health)
return health, nil
}
// Get all the persistent and transient cluster settings.
//
// Use case: You want to see the current settings in the cluster.
func (c *Client) GetClusterSettings() (ClusterSettings, error) {
clusterSettings := ClusterSettings{}
body, err := handleErrWithBytes(c.buildGetRequest(clusterSettingsPath))
if err != nil {
return clusterSettings, err
}
rawPersistentSettings := gjson.GetBytes(body, "persistent").Raw
rawTransientSettings := gjson.GetBytes(body, "transient").Raw
persisentSettings, err := settingsToStructs(rawPersistentSettings)
if err != nil {
return clusterSettings, err
}
transientSetting, err := settingsToStructs(rawTransientSettings)
if err != nil {
return clusterSettings, err
}
clusterSettings.PersistentSettings = persisentSettings
clusterSettings.TransientSettings = transientSetting
return clusterSettings, nil
}
// Enables or disables allocation for the cluster.
//
// Use case: You are performing an operation the cluster where nodes may be dropping in and out. Elasticsearch will typically try to rebalance immediately but you want the cluster to hold off rebalancing until you complete your task. Calling `SetAllocation("disable")` will disable allocation so Elasticsearch won't move/relocate any shards. Once you complete your task, calling `SetAllocation("enable")` will allow Elasticsearch to relocate shards again.
func (c *Client) SetAllocation(allocation string) (string, error) {
var allocationSetting string
if allocation == "enable" {
allocationSetting = "all"
} else {
allocationSetting = "none"
}
agent := c.buildPutRequest(clusterSettingsPath).
Set("Content-Type", "application/json").
Send(fmt.Sprintf(`{"transient" : { "cluster.routing.allocation.enable" : "%s"}}`, allocationSetting))
body, err := handleErrWithBytes(agent)
if err != nil {
return "", err
}
allocationVal := gjson.GetBytes(body, "transient.cluster.routing.allocation.enable")
return allocationVal.String(), nil
}
// Set a new value for a cluster setting. Returns existing value and new value as well as error, in that order
// If the setting is not set in Elasticsearch (it's falling back to default configuration) SetClusterSetting's existingValue will be nil.
// If the value provided is nil, SetClusterSetting will remove the setting so that Elasticsearch falls back on default configuration for that setting.
//
// Use case: You've doubled the number of nodes in your cluster and you want to increase the number of shards the cluster can relocate at one time. Calling `SetClusterSetting("cluster.routing.allocation.cluster_concurrent_rebalance", "100")` will update that value with the cluster. Once data relocation is complete you can decrease the setting by calling `SetClusterSetting("cluster.routing.allocation.cluster_concurrent_rebalance", "20")`.
func (c *Client) SetClusterSetting(setting string, value *string) (*string, *string, error) {
var existingValue *string
var newValue *string
settingsBody, err := handleErrWithBytes(c.buildGetRequest(clusterSettingsPath))
if err != nil {
return existingValue, newValue, err
}
existingResults := gjson.GetManyBytes(settingsBody, fmt.Sprintf("transient.%s", setting), fmt.Sprintf("persistent.%s", setting))
var newSettingBody string
if value == nil {
newSettingBody = fmt.Sprintf(`{"transient" : { "%s" : null}}`, setting)
} else {
newSettingBody = fmt.Sprintf(`{"transient" : { "%s" : "%s"}}`, setting, *value)
}
agent := c.buildPutRequest(clusterSettingsPath).
Set("Content-Type", "application/json").
Send(newSettingBody)
body, err := handleErrWithBytes(agent)
if err != nil {
return existingValue, newValue, err
}
newResults := gjson.GetBytes(body, fmt.Sprintf("transient.%s", setting)).String()
if newResults != "" {
newValue = &newResults
}
if existingResults[0].String() == "" {
if existingResults[1].String() != "" {
value := existingResults[1].String()
existingValue = &value
}
} else {
value := existingResults[0].String()
existingValue = &value
}
return existingValue, newValue, nil
}
// List the snapshots of the given repository.
//
// Use case: You want to see information on snapshots in a repository.
func (c *Client) GetSnapshots(repository string) ([]Snapshot, error) {
var snapshotWrapper snapshotWrapper
err := handleErrWithStruct(c.buildGetRequest(fmt.Sprintf("_snapshot/%s/_all", repository)), &snapshotWrapper)