/
member.go
1190 lines (1020 loc) · 33.5 KB
/
member.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
/*
* Copyright (c) 2021, 2024 Oracle and/or its affiliates.
* Licensed under the Universal Permissive License v 1.0 as shown at
* https://oss.oracle.com/licenses/upl.
*/
package cmd
import (
"encoding/json"
"errors"
"fmt"
"github.com/oracle/coherence-cli/pkg/config"
"github.com/oracle/coherence-cli/pkg/constants"
"github.com/oracle/coherence-cli/pkg/fetcher"
"github.com/oracle/coherence-cli/pkg/utils"
"github.com/spf13/cobra"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
)
var (
numThreadDumps int32
delayBetweenDumps int32
outputDirectory string
verbose bool
dumpRoleName string
configureRole string
roleName string
threadDumpRole string
threadDump bool
extendedInfo string
attributeName string
attributeValue string
validAttributes = []string{"loggingLevel", "resendDelay", "sendAckDelay",
"trafficJamCount", "trafficJamDelay", "loggingLimit,", "loggingFormat"}
p2pSortByPublisher bool
p2pSortByReceiver bool
memberSummary bool
departedMembers bool
tracingRatio float32
)
const (
dumpClusterHeap = "dump cluster heap"
logClusterState = "log cluster state"
configureTracing = "configure tracing"
unableToDecode = "unable to decode member details"
noNodeID = "no node with node id %s exists in this cluster"
invalidNodeID = "invalid value for node id of %s"
none = "none"
roleNameDescription = "role name to display"
unableToFindMember = "unable to find member with nodeId %s"
)
// getMembersCmd represents the get members command.
var getMembersCmd = &cobra.Command{
Use: "members",
Short: "display members for a cluster",
Long: `The 'get members' command displays the members for a cluster. You
can specify '-o wide' to display addition information.`,
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
return getMembers(cmd, false)
},
}
// getMembers returns the member or network stats depending upon the value of networkStats.
func getMembers(cmd *cobra.Command, networkStats bool) error {
var (
dataFetcher fetcher.Fetcher
connection string
result string
err error
)
connection, dataFetcher, err = GetConnectionAndDataFetcher()
if err != nil {
return err
}
for {
var (
members = config.Members{}
storage = config.StorageDetails{}
cluster = config.Cluster{}
clusterResult []byte
membersResult []byte
storageResult []byte
)
membersResult, err = dataFetcher.GetMemberDetailsJSON(OutputFormat != constants.TABLE && OutputFormat != constants.WIDE)
if err != nil {
return err
}
storageResult, err = dataFetcher.GetStorageDetailsJSON()
if err != nil {
return err
}
clusterResult, err = dataFetcher.GetClusterDetailsJSON()
if err != nil {
return err
}
if strings.Contains(OutputFormat, constants.JSONPATH) {
result, err = utils.GetJSONPathResults(membersResult, OutputFormat)
if err != nil {
return err
}
cmd.Println(result)
} else if OutputFormat == constants.JSON {
cmd.Println(string(membersResult))
} else {
printWatchHeader(cmd)
cmd.Println(FormatCurrentCluster(connection))
err = json.Unmarshal(membersResult, &members)
if err != nil {
return utils.GetError(unableToDecode, err)
}
err = json.Unmarshal(storageResult, &storage)
if err != nil {
return utils.GetError("unable to decode storage details", err)
}
err = json.Unmarshal(clusterResult, &cluster)
if err != nil {
return utils.GetError("unable to decode cluster details", err)
}
storageMap := utils.GetStorageMap(storage)
var filteredMembers []config.Member
// apply any filtering by role
if roleName != all {
filteredMembers = make([]config.Member, 0)
for _, value := range members.Members {
if value.RoleName == roleName {
filteredMembers = append(filteredMembers, value)
}
}
} else {
filteredMembers = make([]config.Member, len(members.Members))
copy(filteredMembers, members.Members)
}
if networkStats {
cmd.Println(FormatNetworkStatistics(filteredMembers))
} else {
if departedMembers {
departedList, err1 := decodeDepartedMembers(cluster.MembersDeparted)
if err1 != nil {
return err1
}
cmd.Println(FormatDepartedMembers(departedList))
} else {
cmd.Print(FormatMembers(filteredMembers, true, storageMap, memberSummary, cluster.MembersDepartureCount))
}
}
}
// check to see if we should exit if we are not watching
if !isWatchEnabled() {
break
}
// we are watching services so sleep and then repeat until CTRL-C
time.Sleep(time.Duration(watchDelay) * time.Second)
}
return nil
}
// getMemberDescriptionCmd represents the get member-description command.
var getMemberDescriptionCmd = &cobra.Command{
Use: "member-description node-id",
Short: "display member description",
Long: `The 'get member-description' command displays information regarding a member.
Only available in most recent Coherence versions.`,
ValidArgsFunction: completionNodeID,
Args: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
displayErrorAndExit(cmd, provideNodeID)
}
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
var (
dataFetcher fetcher.Fetcher
connection string
err error
nodeIDArray []string
)
nodeID := args[0]
if !utils.IsValidInt(nodeID) {
return fmt.Errorf(invalidNodeID, nodeID)
}
connection, dataFetcher, err = GetConnectionAndDataFetcher()
if err != nil {
return err
}
nodeIDArray, err = GetNodeIds(dataFetcher)
if err != nil {
return err
}
if !utils.SliceContains(nodeIDArray, nodeID) {
return fmt.Errorf(unableToFindMember, nodeID)
}
for {
var (
descriptionData []byte
description config.Description
)
descriptionData, err = dataFetcher.GetNodeDescriptionJSON(args[0])
if err != nil {
return err
}
if len(descriptionData) != 0 {
err = json.Unmarshal(descriptionData, &description)
if err != nil {
return err
}
} else {
return nil
}
printWatchHeader(cmd)
cmd.Println(FormatCurrentCluster(connection))
cmd.Println(description.Description)
// check to see if we should exit if we are not watching
if !isWatchEnabled() {
break
}
// we are watching so sleep and then repeat until CTRL-C
time.Sleep(time.Duration(watchDelay) * time.Second)
}
return nil
},
}
// getNetworkStatsCmd represents the get member-stats command.
var getNetworkStatsCmd = &cobra.Command{
Use: "network-stats",
Short: "display all member network statistics for a cluster",
Long: `The 'get network-stats' command displays all member network statistic for a cluster.`,
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
return getMembers(cmd, true)
},
}
// getP2PStatsCmd represents the get p2p-stats command.
var getP2PStatsCmd = &cobra.Command{
Use: "p2p-stats node-id",
Short: "display point-to-point network statistics for a specific member",
Long: `The 'get p2ps-stats' command displays the network statistics from the point
of view of a member and all the members it connects to.`,
ValidArgsFunction: completionNodeID,
Args: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
displayErrorAndExit(cmd, provideNodeID)
}
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
var (
dataFetcher fetcher.Fetcher
connection string
memberResult []byte
members = config.Members{}
err error
member config.Member
)
nodeID := args[0]
if !utils.IsValidInt(nodeID) {
return fmt.Errorf(invalidNodeID, nodeID)
}
// retrieve the current context or the value from "-c"
connection, dataFetcher, err = GetConnectionAndDataFetcher()
if err != nil {
return err
}
if p2pSortByReceiver && p2pSortByPublisher {
return errors.New("you cannot specify to sort by publisher and receiver, please choose only one")
}
memberResult, err = dataFetcher.GetMemberDetailsJSON(false)
if err != nil {
return err
}
err = json.Unmarshal(memberResult, &members)
if err != nil {
return err
}
// check to see the member is valid
var found bool
for _, value := range members.Members {
if value.NodeID == nodeID {
found = true
member = value
break
}
}
if !found {
return fmt.Errorf(unableToFindMember, nodeID)
}
for {
var (
result string
networkStats []byte
statistics config.NetworkStats
details []config.NetworkStatsDetails
)
networkStats, err = dataFetcher.GetNetworkStatsJSON(nodeID)
if err != nil {
return err
}
if strings.Contains(OutputFormat, constants.JSONPATH) {
result, err = utils.GetJSONPathResults(networkStats, OutputFormat)
if err != nil {
return err
}
cmd.Println(result)
} else if OutputFormat == constants.JSON {
cmd.Println(string(networkStats))
} else {
err = json.Unmarshal(networkStats, &statistics)
if err != nil {
return utils.GetError("unable to decode networkStats", err)
}
// decode the network stats
details, err = decodeNetworkStats(statistics)
if err != nil {
return err
}
printWatchHeader(cmd)
cmd.Println(FormatCurrentCluster(connection))
var sb strings.Builder
sb.WriteString(fmt.Sprintf("Viewing Node Id: %s\n", member.NodeID))
sb.WriteString(fmt.Sprintf("Viewing Member Name: %s\n\n", member.MemberName))
sb.WriteString(FormatNetworkStats(details))
cmd.Print(sb.String())
}
// check to see if we should exit if we are not watching
if !isWatchEnabled() {
break
}
// we are watching services so sleep and then repeat until CTRL-C
time.Sleep(time.Duration(watchDelay) * time.Second)
}
return nil
},
}
func decodeNetworkStats(statistics config.NetworkStats) ([]config.NetworkStatsDetails, error) {
var details = make([]config.NetworkStatsDetails, 0)
for _, v := range statistics.ViewerStatistics {
// split on ", "
values := strings.Split(v, ", ")
if len(values) == 0 {
return details, errors.New("invalid response from networkStats")
}
detail := config.NetworkStatsDetails{}
detailMap := make(map[string]string)
// split the key/ values and store in a map
for _, v2 := range values {
kv := strings.Split(v2, "=")
if len(kv) != 2 {
return details, fmt.Errorf("invalid key/value of %s", v2)
}
detailMap[kv[0]] = kv[1]
}
detail.NodeID = detailMap["Member"]
detail.ReceiverSuccessRate = getFloat32Value(detailMap["ReceiverSuccessRate"])
detail.PublisherSuccessRate = getFloat32Value(detailMap["PublisherSuccessRate"])
detail.PauseRate = getFloat32Value(detailMap["PauseRate"])
detail.Threshold = getIn64Value(detailMap["Threshold"])
detail.OutstandingPackets = getIn64Value(detailMap["OutstandingPackets"])
detail.DeferredPackets = getIn64Value(detailMap["DeferredPackets"])
detail.ReadyPackets = getIn64Value(detailMap["ReadyPackets"])
detail.Paused = getBoolValue(detailMap["Paused"])
detail.Deferring = getBoolValue(detailMap["Deferring"])
detail.LastIn = detailMap["LastIn"]
detail.LastOut = detailMap["LastOut"]
detail.LastSlow = detailMap["LastSlow"]
detail.LastHeuristicDeath = detailMap["LastHeuristicDeath"]
details = append(details, detail)
}
return details, nil
}
func getFloat32Value(value string) float32 {
result, _ := strconv.ParseFloat(value, 32)
return float32(result)
}
func getIn64Value(value string) int64 {
result, _ := strconv.ParseInt(value, 10, 64)
return result
}
func getBoolValue(value string) bool {
result, _ := strconv.ParseBool(value)
return result
}
// describeMemberCmd represents the describe member command.
var describeMemberCmd = &cobra.Command{
Use: "member node-id",
Short: "describe a member",
Long: `The 'describe member' command shows information related to a specific member.
To display extended information about a member, the -X option can be specified with a comma
separated list of platform entries to display for. For example:
cohctl describe member 1 -X g1OldGeneration,g1EdenSpace
would display information related to G1 old generation and Eden space.
Full list of options are JVM dependant, but can include the full values or part of the following:
compressedClassSpace, operatingSystem, metaSpace, g1OldGen, g1SurvivorSpace, g1CodeHeapProfiledNMethods,
g1CodeHeapNonNMethods, g1OldGeneration g1MetaSpaceManager, g1YoungGeneration, g1EdenSpace,
g1CodeCacheManager, psScavenge, psEdenSpace, psMarkSweep, codeCache, psOldGen, psSurvivorSpace,
runtime`,
ValidArgsFunction: completionNodeID,
Args: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
displayErrorAndExit(cmd, provideNodeID)
}
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
var (
members = config.Members{}
result []byte
err error
dataFetcher fetcher.Fetcher
extendedData [][]byte
connection string
finalResult []byte
finalExtended []byte
extendedInfoList []string
)
nodeID := args[0]
if !utils.IsValidInt(nodeID) {
return fmt.Errorf(invalidNodeID, nodeID)
}
// retrieve the current context or the value from "-c"
connection, dataFetcher, err = GetConnectionAndDataFetcher()
if err != nil {
return err
}
result, err = dataFetcher.GetMemberDetailsJSON(false)
if err != nil {
return err
}
err = json.Unmarshal(result, &members)
if err != nil {
return err
}
// check to see the member is valid
var found bool
for _, value := range members.Members {
if value.NodeID == nodeID {
found = true
break
}
}
if !found {
return fmt.Errorf(unableToFindMember, nodeID)
}
// we have a valid member id so get the details from fetcher
result, err = dataFetcher.GetSingleMemberDetailsJSON(nodeID)
if err != nil {
return err
}
// retrieve the links for the extended info
if extendedInfo != none {
// retrieve the extended data
extendedInfoList = strings.Split(extendedInfo, ",")
extendedData, err = dataFetcher.GetExtendedMemberInfoJSON(result, nodeID, extendedInfoList)
if err != nil {
return err
}
}
if isJSONPathOrJSON() {
if len(extendedData) > 0 {
finalExtended, err = utils.CombineByteArraysForJSON(extendedData, extendedInfoList)
if err != nil {
return err
}
}
finalResult, err = utils.CombineByteArraysForJSON([][]byte{result, finalExtended}, []string{"member", "extended"})
if err != nil {
return err
}
if err = processJSONOutput(cmd, finalResult); err != nil {
return err
}
} else {
cmd.Println(FormatCurrentCluster(connection))
cmd.Println("MEMBER DETAILS")
cmd.Println("--------------")
value, err := FormatJSONForDescribe(result, true, "Node Id", "Unicast Address",
"Role Name", "Machine Name", "Rack Name", "Site Name")
if err != nil {
return err
}
cmd.Println(value)
if threadDump {
data, err := dataFetcher.GetThreadDump(nodeID)
if err != nil {
return err
}
threadDump, err := UnmarshalThreadDump(data)
if err != nil {
return err
}
cmd.Println("\nTHREAD DUMP")
cmd.Println("-----------")
cmd.Println(threadDump)
}
if extendedInfo != none {
var extendedValue string
cmd.Println("\nEXTENDED INFORMATION")
cmd.Println("--------------------")
// add any extended data
if len(extendedData) > 0 {
for _, value := range extendedData {
if len(value) > 0 {
extendedValue, err = FormatJSONForDescribe(value, true)
if err != nil {
return err
}
cmd.Println(extendedValue)
}
}
}
}
}
return nil
},
}
// setMemberCmd represents the set member command.
var setMemberCmd = &cobra.Command{
Use: "member {node-ids|all}",
Short: "set a member attribute for one or more members",
Long: `The 'set member' command sets an attribute for one or more member nodes.
You can specify 'all' to change the value for all nodes, or specify a comma separated
list of node ids. The following attribute names are allowed:
loggingLevel, resendDelay, sendAckDelay, trafficJamCount, trafficJamDelay, loggingLimit
or loggingFormat.`,
Args: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
displayErrorAndExit(cmd, "you must provide a comma separated list of node id's or 'all' for all nodes")
}
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
var (
dataFetcher fetcher.Fetcher
connection string
err error
nodeIds []string
nodeIDArray []string
confirmMessage string
errorSink = createErrorSink()
wg sync.WaitGroup
loggingNodeIds = args[0]
actualValue interface{}
intValue int
)
if !utils.SliceContains(validAttributes, attributeName) {
return fmt.Errorf("attribute name %s is invalid. Please choose one of\n%v",
attributeName, validAttributes)
}
if attributeName == "loggingFormat" {
// this is the only attribute that is a string
actualValue = attributeValue
} else {
// convert to an int
intValue, err = strconv.Atoi(attributeValue)
if err != nil {
return fmt.Errorf("invalid integer value of %s for attribute %s", attributeValue, attributeName)
}
actualValue = intValue
// carry out some basic validation
if attributeName == "loggingLevel" && (intValue < 1 || intValue > 9) {
return fmt.Errorf("log level must be betweeen 1 and 9")
} else if intValue <= 0 {
return fmt.Errorf("value for attribute %s must be greater than zero", attributeName)
}
}
connection, dataFetcher, err = GetConnectionAndDataFetcher()
if err != nil {
return err
}
cmd.Println(FormatCurrentCluster(connection))
nodeIDArray, err = GetNodeIds(dataFetcher)
if err != nil {
return err
}
if loggingNodeIds == all {
nodeIds = append(nodeIds, nodeIDArray...)
confirmMessage = fmt.Sprintf("all %d nodes", len(nodeIds))
} else {
if nodeIds, err = getNodeIDs(loggingNodeIds, nodeIDArray); err != nil {
return err
}
confirmMessage = fmt.Sprintf("%d node(s)", len(nodeIds))
}
// confirm the operation
if !confirmOperation(cmd, fmt.Sprintf("Are you sure you want to set the value of attribute %s to %s for %s? (y/n) ",
attributeName, attributeValue, confirmMessage)) {
return nil
}
nodeCount := len(nodeIds)
wg.Add(nodeCount)
for _, value := range nodeIds {
go func(nodeId string) {
var err1 error
defer wg.Done()
_, err1 = dataFetcher.SetMemberAttribute(nodeId, attributeName, actualValue)
if err1 != nil {
errorSink.AppendError(err1)
}
}(value)
}
wg.Wait()
errorList := errorSink.GetErrors()
if len(errorList) > 0 {
return utils.GetErrors(errorList)
}
cmd.Println(OperationCompleted)
return nil
},
}
// dumpClusterHeapCmd represents the dump cluster-heap command.
var dumpClusterHeapCmd = &cobra.Command{
Use: "cluster-heap",
Short: "dump the cluster heap for all members or a specific role",
Long: `The 'dump cluster-heap' command issues a heap dump for all members or the selected role
by using the -r flag.`,
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
return issueClusterCommand(cmd, dumpClusterHeap)
},
}
// configureTracingCmd represents the configure tracing command.
var configureTracingCmd = &cobra.Command{
Use: "tracing",
Short: "configure tracing for all members or a specific role",
Long: `The 'configure tracing' command configures tracing for all members or the selected role
by using the -r flag. You can specify a tracingRatio of -1 to turn off tracing.`,
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
return issueClusterCommand(cmd, configureTracing)
},
}
// getTracingCmd represents the get tracing command.
var getTracingCmd = &cobra.Command{
Use: "tracing",
Short: "display tracing for all members",
Long: `The 'get tracing' command displays tracing status for all members.`,
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
var (
dataFetcher fetcher.Fetcher
connection string
err error
members = config.Members{}
)
// retrieve the current context or the value from "-c"
connection, dataFetcher, err = GetConnectionAndDataFetcher()
if err != nil {
return err
}
for {
printWatchHeader(cmd)
membersResult, err := dataFetcher.GetMemberDetailsJSON(OutputFormat != constants.TABLE && OutputFormat != constants.WIDE)
if err != nil {
return err
}
if strings.Contains(OutputFormat, constants.JSONPATH) {
result, err := utils.GetJSONPathResults(membersResult, OutputFormat)
if err != nil {
return err
}
cmd.Println(result)
} else if OutputFormat == constants.JSON {
cmd.Println(string(membersResult))
} else {
cmd.Println(FormatCurrentCluster(connection))
err = json.Unmarshal(membersResult, &members)
if err != nil {
return utils.GetError(unableToDecode, err)
}
cmd.Print(FormatTracing(members.Members))
}
// check to see if we should exit if we are not watching
if !isWatchEnabled() {
break
}
// we are watching services so sleep and then repeat until CTRL-C
time.Sleep(time.Duration(watchDelay) * time.Second)
}
return nil
},
}
// logClusterStateCmd represents the log cluster-state command.
var logClusterStateCmd = &cobra.Command{
Use: "cluster-state",
Short: "Logs the cluster state via a thread dump, for all members or a specific role",
Long: `The 'log cluster-state' command logs a full thread dump and outstanding
polls, in the logs files, for all members or the selected role by using the -r flag.`,
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
return issueClusterCommand(cmd, logClusterState)
},
}
// shutdownMemberCmd represents the shutdown member command.
var shutdownMemberCmd = &cobra.Command{
Use: "member node-id",
Short: "shutdown a members services",
Long: `The 'shutdown member' command shuts down all the clustered services that are
running on a specific member via a controlled shutdown. If the services were started using
DefaultCacheServer, then they will be restarted.`,
ValidArgsFunction: completionNodeID,
Args: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
displayErrorAndExit(cmd, provideNodeID)
}
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
var (
dataFetcher fetcher.Fetcher
connection string
err error
nodeIDArray []string
nodeID = args[0]
)
// retrieve the current context or the value from "-c"
connection, dataFetcher, err = GetConnectionAndDataFetcher()
if err != nil {
return err
}
cmd.Println(FormatCurrentCluster(connection))
nodeIDArray, err = GetNodeIds(dataFetcher)
if err != nil {
return err
}
if !utils.IsValidInt(nodeID) {
return fmt.Errorf(invalidNodeID, nodeID)
}
if !utils.SliceContains(nodeIDArray, nodeID) {
return fmt.Errorf(noNodeID, nodeID)
}
// confirm the operation
if !confirmOperation(cmd, fmt.Sprintf("Are you sure you want to shutdown member %s? (y/n) ", nodeID)) {
return nil
}
_, err = dataFetcher.ShutdownMember(nodeID)
if err != nil {
return err
}
cmd.Println(OperationCompleted)
return nil
},
}
// issueClusterCommand issues a variety of cluster commands.
func issueClusterCommand(cmd *cobra.Command, command string) error {
var (
dataFetcher fetcher.Fetcher
connection string
membersResult []byte
err error
members = config.Members{}
roleCount = 0
message string
tracing = ""
role = dumpRoleName
)
// retrieve the current context or the value from "-c"
connection, dataFetcher, err = GetConnectionAndDataFetcher()
if err != nil {
return err
}
membersResult, err = dataFetcher.GetMemberDetailsJSON(false)
if err != nil {
return err
}
err = json.Unmarshal(membersResult, &members)
if err != nil {
return utils.GetError(unableToDecode, err)
}
cmd.Println(FormatCurrentCluster(connection))
if command == configureTracing {
role = configureRole
// validate the value for tracingRatio
if tracingRatio != -1.0 &&
(tracingRatio < 0 || tracingRatio > 1.0) {
return fmt.Errorf("tracing ratio must be either -1.0 or between 0 and 1.0")
}
tracing = fmt.Sprintf(" to tracing ratio %v", tracingRatio)
}
if role != all && role != "" {
// validate the role
for _, value := range members.Members {
if value.RoleName == role {
roleCount++
}
}
if roleCount == 0 {
return fmt.Errorf("unable to find members with role name of %s", role)
}
message = fmt.Sprintf("%d members with role %s", roleCount, role)
} else {
message = fmt.Sprintf("all %d members", len(members.Members))
}
// confirm the operation
if !confirmOperation(cmd, fmt.Sprintf("Are you sure you want to %s%s for %s? (y/n) ", command, tracing, message)) {
return nil
}
if command == dumpClusterHeap {
_, err = dataFetcher.DumpClusterHeap(role)
} else if command == configureTracing {
_, err = dataFetcher.ConfigureTracing(role, tracingRatio)
} else {
_, err = dataFetcher.LogClusterState(role)
}
if err != nil {
return err
}
cmd.Println("Operation completed. Please see cache server log file for more information")
return nil
}
// retrieveThreadDumpsCmd represents the retrieve thread-dumps command.
var retrieveThreadDumpsCmd = &cobra.Command{
Use: "thread-dumps [node-ids]",
Short: "generate and retrieve thread dumps for all or selected members",
Long: `The 'get thead-dumps' command generates and retrieves thread dumps for all or selected
members and places them in the specified output directory. You are also able to specify
a role to retrieve thread dumps for.`,
Args: func(cmd *cobra.Command, args []string) error {
if threadDumpRole == all && len(args) != 1 {
displayErrorAndExit(cmd, "you must provide a comma separated list of node id's, 'all' for all nodes, or specify a role")
}
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
var (
dataFetcher fetcher.Fetcher
connection string
err error
nodeIds []string
nodesToDump string
wg sync.WaitGroup
errorSink = createErrorSink()
nodeIDArray []string
membersResult []byte
members = config.Members{}
)
if len(args) != 0 {
nodesToDump = args[0]
}
if delayBetweenDumps < 5 {
return errors.New("delay must be 5 seconds or above")
}
// retrieve the current context or the value from "-c"
connection, dataFetcher, err = GetConnectionAndDataFetcher()
if err != nil {
return err
}
cmd.Println(FormatCurrentCluster(connection))
// validate the output directory
if !utils.DirectoryExists(outputDirectory) {
return fmt.Errorf("the output directory '%s' does not exist or is not writabled", outputDirectory)
}
// retrieve the nodes to validate against
nodeIDArray, err = GetNodeIds(dataFetcher)
if err != nil {
return err
}
// retrieve and validate the members
if nodesToDump == all {
nodeIds = append(nodeIds, nodeIDArray...)
} else {