-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathcluster.go
1347 lines (975 loc) · 32.2 KB
/
cluster.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 cbcluster
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os/exec"
"path"
"regexp"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/tleyden/go-etcd/etcd"
)
const (
KEY_NODE_STATE = "/couchbase.com/couchbase-node-state"
KEY_NODE_STATE_TTL uint64 = 10
KEY_USER_PASS = "/couchbase.com/userpass"
KEY_REMOVE_REBALANCE_DISABLED = "/couchbase.com/remove-rebalance-disabled"
TTL_NONE = 0
MAX_RETRIES_JOIN_CLUSTER = 10
MAX_RETRIES_START_COUCHBASE = 10
// in order to set the username and password of a cluster
// you must pass these "factory default values"
DEFAULT_ADMIN_USERNAME = "admin"
DEFAULT_ADMIN_PASSWORD = "password"
LOCAL_COUCHBASE_PORT = "8091"
DEFAULT_BUCKET_RAM_MB = "128"
DEFAULT_BUCKET_REPLICA_NUMBER = "0"
DEFAULT_CB_PORT = "8091"
)
type CouchbaseCluster struct {
AdminCredentials
etcdClient *etcd.Client
LocalCouchbaseIp string
LocalCouchbasePort string
LocalCouchbaseVersion string
defaultBucketRamQuotaMB string
defaultBucketReplicaNumber string
EtcdServers []string
}
type AdminCredentials struct {
AdminUsername string
AdminPassword string
}
type bucketParams struct {
Name string
RamQuotaMB string
AuthType string
ReplicaNumber string
}
func NewCouchbaseCluster(etcdServers []string) *CouchbaseCluster {
c := &CouchbaseCluster{}
StupidPortHack(c)
c.defaultBucketRamQuotaMB = DEFAULT_BUCKET_RAM_MB
c.defaultBucketReplicaNumber = DEFAULT_BUCKET_REPLICA_NUMBER
if len(etcdServers) > 0 {
c.EtcdServers = etcdServers
log.Printf("Connect to explicit etcd servers: %v", c.EtcdServers)
} else {
c.EtcdServers = []string{}
log.Printf("Connect to etcd on localhost")
}
c.ConnectToEtcd()
return c
}
func (c *CouchbaseCluster) ConnectToEtcd() {
c.etcdClient = etcd.NewClient(c.EtcdServers)
c.etcdClient.SetConsistency(etcd.STRONG_CONSISTENCY)
}
func (c *CouchbaseCluster) StartCouchbaseSidekick() error {
if c.LocalCouchbaseIp == "" {
return fmt.Errorf("You must define LocalCouchbaseIp before calling")
}
c.LocalCouchbasePort = LOCAL_COUCHBASE_PORT
// if any of the bootstrapping functions error or panic, we don't want to leave a stale KEY_NODE_STATE
// with no ttl, which is the default state inside c.BecomeFirstClusterNode()
defer c.etcdClient.UpdateDir(KEY_NODE_STATE, KEY_NODE_STATE_TTL)
success, err := c.BecomeFirstClusterNode()
if err != nil {
return err
}
if err := c.FetchClusterDetails(); err != nil {
return err
}
switch success {
case true:
log.Printf("We became first cluster node, init cluster and bucket")
if err := c.ClusterInit(); err != nil {
return err
}
if err := c.CreateDefaultBucket(); err != nil {
return err
}
case false:
if err := c.JoinExistingCluster(); err != nil {
return err
}
}
c.EventLoop()
return fmt.Errorf("Event loop died") // should never get here
}
func (c CouchbaseCluster) LocalOtpNode() (otpNode string, err error) {
liveNodeIp, err := c.FindLiveNode()
if err != nil {
return "", err
}
otpNodeList, err := c.OtpNodeList(liveNodeIp)
if err != nil {
return "", err
}
for _, otpNode := range otpNodeList {
if strings.Contains(otpNode, c.LocalCouchbaseIp) {
return otpNode, nil
}
}
return "", fmt.Errorf("No otpnode found with ip %v in %v", c.LocalCouchbaseIp, otpNodeList)
}
func (c CouchbaseCluster) BecomeFirstClusterNode() (bool, error) {
log.Printf("BecomeFirstClusterNode()")
// since we don't knoow how long it will be until we go
// into the event loop, set TTL to 0 (infinite) for now.
_, err := c.etcdClient.CreateDir(KEY_NODE_STATE, TTL_NONE)
if err != nil {
// expected error where someone beat us out
if strings.Contains(err.Error(), "Key already exists") {
log.Printf("Key %v already exists", KEY_NODE_STATE)
return false, nil
}
// otherwise, unexpected error
log.Printf("Unexpected error: %v", err)
return false, err
}
// no error must mean that were were able to create the key
log.Printf("Created key: %v", KEY_NODE_STATE)
return true, nil
}
// Loop over list of machines in etcd cluster and join
// the first node that is up
func (c CouchbaseCluster) JoinExistingCluster() error {
log.Printf("JoinExistingCluster() called")
sleepSeconds := 0
for i := 0; i < MAX_RETRIES_JOIN_CLUSTER; i++ {
log.Printf("Calling FindLiveNode()")
liveNodeIp, err := c.FindLiveNode()
if err != nil {
log.Printf("FindLiveNode returned err: %v. Trying again", err)
}
log.Printf("liveNodeIp: %v", liveNodeIp)
if liveNodeIp != "" {
return c.JoinLiveNode(liveNodeIp)
}
sleepSeconds += 10
log.Printf("Sleeping for %v", sleepSeconds)
<-time.After(time.Second * time.Duration(sleepSeconds))
}
return fmt.Errorf("Failed to join cluster after several retries")
}
// Loop over list of machines in etc cluster and find
// first live node.
func (c CouchbaseCluster) FindLiveNode() (string, error) {
key := path.Join(KEY_NODE_STATE)
response, err := c.etcdClient.Get(key, false, false)
if err != nil {
return "", fmt.Errorf("Error getting key. Err: %v", err)
}
node := response.Node
if node == nil {
log.Printf("node is nil, returning")
return "", nil
}
if len(node.Nodes) == 0 {
log.Printf("len(node.Nodes) == 0, returning")
return "", nil
}
for _, subNode := range node.Nodes {
// the key will be: /node-state/172.17.8.101, but we
// only want the last element in the path
_, subNodeIp := path.Split(subNode.Key)
log.Printf("Couchbase node ip: %v", subNodeIp)
if !verifyRestService(subNodeIp, DEFAULT_CB_PORT) {
log.Printf("Could not connect to REST service on %v, skipping", subNodeIp)
continue
}
return subNodeIp, nil
}
return "", nil
}
func (c *CouchbaseCluster) FetchClusterDetails() error {
for i := 0; i < MAX_RETRIES_JOIN_CLUSTER; i++ {
endpointUrl := fmt.Sprintf(
"http://%v:%v/pools",
c.LocalCouchbaseIp,
c.LocalCouchbasePort,
)
jsonMap := map[string]interface{}{}
if err := c.getJsonData(endpointUrl, &jsonMap); err != nil {
log.Printf("Got error %v trying to fetch details. Assume that the cluster is not up yet, sleeping and will retry", err)
<-time.After(time.Second * 10)
continue
}
implementationVersion := jsonMap["implementationVersion"]
versionStr, ok := implementationVersion.(string)
if !ok {
return fmt.Errorf("Expected implementationVersion to contain a string")
}
log.Printf("Version: %v", versionStr)
c.LocalCouchbaseVersion = versionStr
return nil
}
return fmt.Errorf("Unable to fetch cluster details after several attempts")
}
func verifyRestService(hostIp string, port string) bool {
endpointUrl := fmt.Sprintf("http://%v:%v/", hostIp, port)
log.Printf("Verifying REST service at %v to be up", endpointUrl)
resp, err := http.Get(endpointUrl)
if err != nil {
return false
}
if err == nil {
defer resp.Body.Close()
return resp.StatusCode == 200
}
return true
}
func (c CouchbaseCluster) WaitForRestService() error {
for i := 0; i < MAX_RETRIES_START_COUCHBASE; i++ {
if verifyRestService(c.LocalCouchbaseIp, c.LocalCouchbasePort) {
return nil
}
log.Printf("Not up yet, sleeping and will retry")
<-time.After(time.Second * 10)
}
return fmt.Errorf("Unable to connect to REST api after several attempts")
}
// Figure out if the cluster has already been initialized (a paassword has been set)
// going to /settings/web endpoint and seeing if the factory default username/password
// work. If it works, that means that cluster has not been initialized yet.
func (c CouchbaseCluster) IsClusterPasswordSet() (bool, error) {
log.Printf("IsClusterPasswordSet()")
endpointUrl := fmt.Sprintf("http://%v:%v/settings/web", c.LocalCouchbaseIp, c.LocalCouchbasePort)
client := &http.Client{}
req, err := http.NewRequest("GET", endpointUrl, nil)
if err != nil {
return false, err
}
req.SetBasicAuth(DEFAULT_ADMIN_USERNAME, DEFAULT_ADMIN_PASSWORD)
resp, err := client.Do(req)
if err != nil {
return false, err
}
// if the response status is 401, then we can assume cluster
// has been initialized
return resp.StatusCode == 401, nil
}
func (c CouchbaseCluster) ClusterInit() error {
log.Printf("ClusterInit()")
// have we already done initialization?
isPasswordSet, err := c.IsClusterPasswordSet()
if err != nil {
return err
}
if isPasswordSet {
log.Printf("Cluster password was previously set, skipping rest of ClusterInit()")
return nil
}
if err := c.ClusterSetPassword(); err != nil {
return err
}
if err := c.SetClusterRam(); err != nil {
return err
}
return nil
}
// Set the username and password for the cluster. The same as calling:
// $ couchbase-cli cluster-init ..
//
// Docs: http://docs.couchbase.com/admin/admin/REST/rest-node-set-username.html
func (c CouchbaseCluster) ClusterSetPassword() error {
log.Printf("ClusterSetPassword()")
endpointUrl := fmt.Sprintf("http://%v:%v/settings/web", c.LocalCouchbaseIp, c.LocalCouchbasePort)
data := url.Values{
"username": {c.AdminUsername},
"password": {c.AdminPassword},
"port": {c.LocalCouchbasePort},
}
if err := c.POST(true, endpointUrl, data); err != nil {
return err
}
return nil
}
// What's the major version of Couchbase? ie, 2 or 3 corresponding to v2.x and v3.x
func (c CouchbaseCluster) CouchbaseMajorVersion() (int, error) {
if len(c.LocalCouchbaseVersion) == 0 {
return -1, fmt.Errorf("c.localcouchbaseversion is empty ")
}
firstCharVerion, _ := utf8.DecodeRuneInString(c.LocalCouchbaseVersion)
majorVersion, err := strconv.Atoi(fmt.Sprintf("%v", firstCharVerion))
if err != nil {
return -1, err
}
return majorVersion, nil
}
// in Couchbase 3, we need to also set the cluster ram setting
// See http://docs.couchbase.com/admin/admin/REST/rest-node-provisioning.html
func (c CouchbaseCluster) SetClusterRam() error {
ramMb, err := CalculateClusterRam()
if err != nil {
log.Printf("Warning, failed to calculate cluster ram: %v. Default to 1024 MB", err)
ramMb = "1024"
}
endpointUrl := fmt.Sprintf("http://%v:%v/pools/default", c.LocalCouchbaseIp, c.LocalCouchbasePort)
data := url.Values{
"memoryQuota": {ramMb},
}
log.Printf("Attempting to set cluster ram to: %v MB", ramMb)
return c.POST(false, endpointUrl, data)
}
func CalculateClusterRam() (string, error) {
totalRamMb, err := CalculateTotalRam()
if err != nil {
return "", err
}
log.Printf("Total RAM (MB) on machine: %v", totalRamMb)
clusterRam := (totalRamMb * 75) / 100
return fmt.Sprintf("%v", clusterRam), nil
}
func CalculateTotalRam() (int, error) {
cmd := exec.Command(
"free",
"-m",
)
output, err := cmd.Output()
if err != nil {
return -1, err
}
// The returned output will look something like this:
// total used free shared buffers cached
// Mem: 3768 2601 1166 0 4 1877
// -/+ buffers/cache: 720 3048
// Swap: 0 0 0
re := regexp.MustCompile(`Mem:[ ]*[0-9]*`)
memPair := re.FindString(string(output)) // ie, "Mem: 3768"
if memPair == "" {
return -1, fmt.Errorf("Could not extract Mem total from %v", output)
}
if !strings.Contains(memPair, ":") {
return -1, fmt.Errorf("Could not extract Mem total from %v, no :", output)
}
memPairs := strings.Split(memPair, ":")
outputTrimmed := strings.TrimSpace(memPairs[1])
i, err := strconv.Atoi(outputTrimmed)
if err != nil {
return -1, err
}
return i, nil
}
func (c CouchbaseCluster) CreateDefaultBucket() error {
params := bucketParams{
Name: "default",
RamQuotaMB: c.defaultBucketRamQuotaMB,
AuthType: "none",
ReplicaNumber: c.defaultBucketReplicaNumber,
}
return c.CreateBucketWithRetries(params)
}
func (c CouchbaseCluster) CreateBucket(params bucketParams) error {
return c.CreateBucketWithRetries(params)
}
// In order to workaround "proxyPort":"port is already in use" errors from
// the REST API (I don't understand why I'm getting this when there aren't
// any buckets on the node), start at proxy port 11215 and keep looping
// until we find one that works.
func (c CouchbaseCluster) CreateBucketWithRetries(params bucketParams) error {
log.Printf("CreateBucketWithRetries(): %+v", params)
maxAttempts := 25
sleepSeconds := 0
proxyPort := 11215
worker := func() (finished bool, err error) {
data := url.Values{
"name": {params.Name},
"ramQuotaMB": {params.RamQuotaMB},
"authType": {params.AuthType},
"replicaNumber": {params.ReplicaNumber},
"proxyPort": {fmt.Sprintf("%v", proxyPort)},
}
endpointUrl := fmt.Sprintf("http://%v:%v/pools/default/buckets", c.LocalCouchbaseIp, c.LocalCouchbasePort)
err = c.POST(false, endpointUrl, data)
if err == nil {
log.Printf("CreateBucket succeeded")
return true, nil
}
log.Printf("CreateBucket error: %v", err)
if strings.Contains(err.Error(), "port is already in use") {
proxyPort += 1
return false, nil // try again
}
// got a different error, no point in retrying .. just abort
return false, err
}
sleeper := func(numAttempts int) (bool, int) {
if numAttempts > maxAttempts {
return false, -1
}
return true, sleepSeconds
}
return RetryLoop(worker, sleeper)
}
func (c CouchbaseCluster) HasDefaultBucket() (bool, error) {
log.Printf("HasDefaultBucket()")
endpointUrl := fmt.Sprintf(
"http://%v:%v/pools/default/buckets",
c.LocalCouchbaseIp,
c.LocalCouchbasePort,
)
jsonList := []interface{}{}
if err := c.getJsonData(endpointUrl, &jsonList); err != nil {
return false, err
}
for _, bucketEntry := range jsonList {
bucketEntryMap, ok := bucketEntry.(map[string]interface{})
if !ok {
continue
}
name := bucketEntryMap["name"]
name, ok = name.(string)
if !ok {
continue
}
if name == "default" {
return true, nil
}
}
return false, nil
}
func (c CouchbaseCluster) JoinLiveNode(liveNodeIp string) error {
log.Printf("JoinLiveNode() called with %v", liveNodeIp)
err := c.WaitUntilInClusterAndHealthy(liveNodeIp)
if err != nil {
log.Printf("WaitUntilInClusterAndHealthy() returned error: %v. Call AddNodeRetry()", err)
if err := c.AddNodeRetry(liveNodeIp); err != nil {
return err
}
} else {
log.Printf("WaitUntilInClusterAndHealthy() done. Node is in cluster and healthy")
}
if err := c.WaitUntilNoRebalanceRunning(liveNodeIp, 5); err != nil {
return err
}
// TODO: better coordinate the rebalance, so if N nodes come up at
// roughly the same time, rebalance only happens _once_
if err := c.TriggerRebalance(liveNodeIp); err != nil {
return err
}
return nil
}
func (c CouchbaseCluster) GetLocalClusterNode(liveNodeIp string) (map[string]interface{}, error) {
nodes, err := c.GetClusterNodes(liveNodeIp)
if err != nil {
return nil, err
}
for _, node := range nodes {
nodeMap, ok := node.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("Node had unexpected data type")
}
hostname := nodeMap["hostname"] // ex: "10.231.192.180:8091"
hostnameStr, ok := hostname.(string)
if !ok {
return nil, fmt.Errorf("No hostname string found")
}
if strings.Contains(hostnameStr, c.LocalCouchbaseIp) {
return nodeMap, nil
}
}
return nil, fmt.Errorf("Unable to find node with hostname %v in %+v", c.LocalCouchbaseIp, nodes)
}
func (c CouchbaseCluster) WaitUntilInClusterAndHealthy(liveNodeIp string) error {
maxAttempts := 25
sleepSeconds := 10
worker := func() (finished bool, err error) {
nodeMap, err := c.GetLocalClusterNode(liveNodeIp)
if err != nil {
log.Printf("No cluster node found for %v. Not retrying", c.LocalCouchbaseIp)
return true, err
}
status := nodeMap["status"]
statusStr, ok := status.(string)
if !ok {
return false, fmt.Errorf("No status string found")
}
switch statusStr {
case "healthy":
return true, nil
case "warmup":
log.Printf("Node is warming up, wait a while and retry")
return false, nil
default:
return false, fmt.Errorf("Unexpected status: %v", statusStr)
}
}
sleeper := func(numAttempts int) (bool, int) {
if numAttempts > maxAttempts {
return false, -1
}
return true, sleepSeconds
}
return RetryLoop(worker, sleeper)
}
// Check if at least numNodes nodes in the cluster are healthy. Connect to liveNodeIp.
// To check all nodes without specifying a specific number of nodes, pass -1 for numNodes.
func (c CouchbaseCluster) CheckNumNodesClusterHealthy(numNodes int, liveNodeIp string) (bool, error) {
log.Printf("CheckNumNodesClusterHealthy()")
nodes, err := c.GetClusterNodes(liveNodeIp)
if err != nil {
return false, err
}
if numNodes != -1 && len(nodes) < numNodes {
log.Printf("Not enough nodes are up. Expected %v, got %v", numNodes, len(nodes))
return false, nil
}
for _, node := range nodes {
nodeMap, ok := node.(map[string]interface{})
if !ok {
return false, fmt.Errorf("Node had unexpected data type")
}
status := nodeMap["status"]
statusStr, ok := status.(string)
if !ok {
return false, fmt.Errorf("No status string found")
}
if statusStr != "healthy" {
log.Printf("node %+v status not healthy. Status: %v", nodeMap, statusStr)
return false, nil
}
}
log.Printf("All cluster nodes appear to be healthy")
return true, nil
}
// Check if all nodes in the cluster are healthy. Connect to liveNodeIp.
func (c CouchbaseCluster) CheckAllNodesClusterHealthy(liveNodeIp string) (bool, error) {
return c.CheckNumNodesClusterHealthy(-1, liveNodeIp)
}
// Based on docs: http://docs.couchbase.com/couchbase-manual-2.5/cb-rest-api/#rebalancing-nodes
func (c CouchbaseCluster) TriggerRebalance(liveNodeIp string) error {
log.Printf("TriggerRebalance()")
otpNodeList, err := c.OtpNodeList(liveNodeIp)
if err != nil {
return nil
}
log.Printf("TriggerRebalance otpNodeList: %v", otpNodeList)
liveNodePort := c.LocalCouchbasePort // TODO: we should be getting this from etcd
endpointUrl := fmt.Sprintf("http://%v:%v/controller/rebalance", liveNodeIp, liveNodePort)
otpNodes := strings.Join(otpNodeList, ",")
data := url.Values{
"ejectedNodes": {},
"knownNodes": {otpNodes},
}
log.Printf("TriggerRebalance encoded form value: %v", data.Encode())
return c.POST(false, endpointUrl, data)
}
// Based on docs: http://docs.couchbase.com/couchbase-manual-2.5/cb-rest-api/#rebalancing-nodes
func (c CouchbaseCluster) TriggerRebalanceRemoveLocal(liveNodeIp string) error {
log.Printf("TriggerRebalanceRemoveLocal()")
defer log.Printf("/TriggerRebalanceRemoveLocal()")
otpNodeList, err := c.OtpNodeList(liveNodeIp)
if err != nil {
return err
}
liveNodePort := c.LocalCouchbasePort // TODO: we should be getting this from etcd
endpointUrl := fmt.Sprintf("http://%v:%v/controller/rebalance", liveNodeIp, liveNodePort)
otpNodes := strings.Join(otpNodeList, ",")
localOtpNode, err := c.LocalOtpNode()
if err != nil {
return err
}
data := url.Values{
"ejectedNodes": {localOtpNode},
"knownNodes": {otpNodes},
}
log.Printf("TriggerRebalanceRemoveLocal encoded form value: %v", data.Encode())
return c.POST(false, endpointUrl, data)
}
// The rebalance command needs the current list of nodes, and it wants
// the "otpNode" values, ie: ["ns_1@10.231.192.180", ..]
func (c CouchbaseCluster) OtpNodeList(liveNodeIp string) ([]string, error) {
otpNodeList := []string{}
nodes, err := c.GetClusterNodes(liveNodeIp)
if err != nil {
return otpNodeList, err
}
for _, node := range nodes {
nodeMap, ok := node.(map[string]interface{})
if !ok {
return otpNodeList, fmt.Errorf("Node had unexpected data type")
}
otpNode := nodeMap["otpNode"] // ex: "ns_1@10.231.192.180"
otpNodeStr, ok := otpNode.(string)
log.Printf("OtpNodeList, otpNode: %v", otpNodeStr)
if !ok {
return otpNodeList, fmt.Errorf("No otpNode string found")
}
otpNodeList = append(otpNodeList, otpNodeStr)
}
return otpNodeList, nil
}
func (c CouchbaseCluster) GetClusterNodes(liveNodeIp string) ([]interface{}, error) {
log.Printf("GetClusterNodes() called with: %v", liveNodeIp)
liveNodePort := c.LocalCouchbasePort // TODO: we should be getting this from etcd
endpointUrl := fmt.Sprintf("http://%v:%v/pools/default", liveNodeIp, liveNodePort)
jsonMap := map[string]interface{}{}
if err := c.getJsonData(endpointUrl, &jsonMap); err != nil {
return nil, err
}
nodes := jsonMap["nodes"]
nodeMaps, ok := nodes.([]interface{})
if !ok {
return nil, fmt.Errorf("Unexpected data type in nodes field")
}
return nodeMaps, nil
}
// Since AddNode seems to fail sometimes (I saw a case where it returned a 400 error)
// retry several times before finally giving up.
func (c CouchbaseCluster) AddNodeRetry(liveNodeIp string) error {
numSecondsToSleep := 0
for i := 0; i < MAX_RETRIES_JOIN_CLUSTER; i++ {
numSecondsToSleep += 10
if err := c.AddNode(liveNodeIp); err != nil {
log.Printf("AddNode failed with err: %v. Will retry in %v secs", err, numSecondsToSleep)
} else {
// it worked, we are done
return nil
}
time2wait := time.Second * time.Duration(numSecondsToSleep)
<-time.After(time2wait)
}
return fmt.Errorf("Unable to AddNode after several attempts")
}
func (c CouchbaseCluster) AddNode(liveNodeIp string) error {
log.Printf("AddNode()")
liveNodePort := c.LocalCouchbasePort // TODO: we should be getting this from etcd
endpointUrl := fmt.Sprintf("http://%v:%v/controller/addNode", liveNodeIp, liveNodePort)
data := url.Values{
"hostname": {c.LocalCouchbaseIp},
"user": {c.AdminUsername},
"password": {c.AdminPassword},
}
log.Printf("AddNode posting to %v with data: %v", endpointUrl, data.Encode())
err := c.POST(false, endpointUrl, data)
if err != nil {
if strings.Contains(err.Error(), "Node is already part of cluster") {
// absorb the error in this case, since its harmless
log.Printf("Node was already part of cluster, so no need to add")
} else {
return err
}
}
return nil
}
func (c CouchbaseCluster) WaitUntilNoRebalanceRunning(liveNodeIp string, sleepSeconds int) error {
maxAttempts := 500
worker := func() (finished bool, err error) {
log.Printf("WaitUntilNoRebalanceRunning()")
isRebalancing, err := c.IsRebalancing(liveNodeIp)
if err != nil {
return false, err
}
return !isRebalancing, nil
}
sleeper := func(numAttempts int) (bool, int) {
if numAttempts > maxAttempts {
return false, -1
}
return true, sleepSeconds
}
return RetryLoop(worker, sleeper)
}
func (c CouchbaseCluster) IsRebalancing(liveNodeIp string) (bool, error) {
liveNodePort := c.LocalCouchbasePort // TODO: we should be getting this from etcd
endpointUrl := fmt.Sprintf("http://%v:%v/pools/default/rebalanceProgress", liveNodeIp, liveNodePort)
jsonMap := map[string]interface{}{}
if err := c.getJsonData(endpointUrl, &jsonMap); err != nil {
return true, err
}
rawStatus := jsonMap["status"]
str, ok := rawStatus.(string)
if !ok {
return true, fmt.Errorf("Unexepected type in status field in json")
}
if str == "none" {
return false, nil
}
return true, nil
}
func (c CouchbaseCluster) getJsonData(endpointUrl string, into interface{}) error {
middleware := func(req *http.Request) {
req.SetBasicAuth(c.AdminUsername, c.AdminPassword)
}
return getJsonDataMiddleware(endpointUrl, into, middleware)
}
func (c CouchbaseCluster) POSTWithCreds(creds AdminCredentials, endpointUrl string, data url.Values) error {
log.Printf("POST to %v", endpointUrl)
client := &http.Client{}
req, err := http.NewRequest("POST", endpointUrl, strings.NewReader(data.Encode()))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.SetBasicAuth(creds.AdminUsername, creds.AdminPassword)
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()