/
manager.go
2205 lines (1947 loc) · 66.5 KB
/
manager.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 cluster implements a cluster state machine. It relies on a cluster
// wide keyvalue store for coordinating the state of the cluster.
// It also stores the state of the cluster in this keyvalue store.
package manager
import (
"container/list"
"context"
"encoding/gob"
"errors"
"fmt"
"net"
"os"
"os/exec"
"path"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/libopenstorage/gossip"
"github.com/libopenstorage/gossip/types"
"github.com/libopenstorage/openstorage/api"
"github.com/libopenstorage/openstorage/cluster"
"github.com/libopenstorage/openstorage/config"
"github.com/libopenstorage/openstorage/objectstore"
"github.com/libopenstorage/openstorage/osdconfig"
"github.com/libopenstorage/openstorage/pkg/auth"
"github.com/libopenstorage/openstorage/pkg/clusterdomain"
"github.com/libopenstorage/openstorage/pkg/dbg"
"github.com/libopenstorage/openstorage/pkg/diags"
"github.com/libopenstorage/openstorage/pkg/job"
"github.com/libopenstorage/openstorage/pkg/nodedrain"
"github.com/libopenstorage/openstorage/pkg/storagepool"
sched "github.com/libopenstorage/openstorage/schedpolicy"
"github.com/libopenstorage/openstorage/secrets"
"github.com/libopenstorage/systemutils"
"github.com/portworx/kvdb"
"github.com/sirupsen/logrus"
)
const (
heartbeatKey = "heartbeat"
clusterLockKey = "/cluster/lock"
gossipVersionKey = "Gossip Version"
decommissionErrMsg = "Node %s must be offline or in maintenance " +
"mode to be decommissioned."
defaultClusterLockTryDuration = 90 * time.Minute
defaultQuorumRetries = 600
)
var (
stopHeartbeat = make(chan bool)
errClusterInitialized = errors.New("openstorage.cluster: already initialized")
errClusterNotInitialized = errors.New("openstorage.cluster: not initialized")
inst *ClusterManager
// Inst returns an instance of an already instantiated cluster manager.
// This function can be overridden for testing purposes
Inst = func() (cluster.Cluster, error) {
return clusterInst()
}
)
// ClusterManager implements the cluster interface
type ClusterManager struct {
size *int64
listeners *list.List
config config.ClusterConfig
kv kvdb.Kvdb
status api.Status
nodeCache map[string]api.Node // Cached info on the nodes in the cluster.
nodeCacheLock sync.Mutex
nodeStatuses map[string]api.Status // Set of nodes currently marked down.
gossip gossip.Gossiper
gossipIntervals types.GossipIntervals
gossipVersion string
gossipPort string
gEnabled bool
selfNode api.Node
selfNodeLock sync.Mutex // Lock that guards data and label of selfNode
system systemutils.System
configManager osdconfig.ConfigCaller
schedManager sched.SchedulePolicyProvider
objstoreManager objectstore.ObjectStore
secretsManager secrets.Secrets
systemTokenManager auth.TokenGenerator
clusterDomainManager clusterdomain.ClusterDomainProvider
storagePoolProvider api.OpenStoragePoolServer
jobProvider job.Provider
nodeDrainProvider nodedrain.Provider
diagsProvider diags.Provider
snapshotPrefixes []string
selfClusterDomain string
// kvdbWatchIndex stores the kvdb index to start the watch
kvdbWatchIndex uint64
}
// Init instantiates a new cluster manager.
func Init(cfg config.ClusterConfig) error {
if inst != nil {
return errClusterInitialized
}
kv := kvdb.Instance()
if kv == nil {
return errors.New("KVDB is not yet initialized. " +
"A valid KVDB instance required for the cluster to start.")
}
inst = &ClusterManager{
size: new(int64),
listeners: list.New(),
config: cfg,
kv: kv,
nodeCache: make(map[string]api.Node),
nodeStatuses: make(map[string]api.Status),
systemTokenManager: auth.SystemTokenManagerInst(),
}
return nil
}
func clusterInst() (cluster.Cluster, error) {
if inst == nil {
return nil, errClusterNotInitialized
}
return inst, nil
}
// ClearInst is used to clear the singleton instance. Use in Tests only
func ClearInst() {
inst = nil
}
type checkFunc func(*cluster.ClusterInfo) error
func ifaceToIp(iface *net.Interface) (string, error) {
addrs, err := iface.Addrs()
if err != nil {
return "", err
}
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
if ip == nil || ip.IsLoopback() {
continue
}
ip = ip.To4()
if ip == nil {
continue // not an ipv4 address
}
if ip.String() == "" {
continue // address is empty string
}
return ip.String(), nil
}
return "", errors.New("Node not connected to the network.")
}
func ifaceNameToIp(ifaceName string) (string, error) {
stdout, err := exec.Command("/usr/sbin/ip", "a", "show", ifaceName, "label", ifaceName).Output()
if err != nil {
return "", err
}
ipOp := string(stdout)
// Parse the output of command /usr/bin/ip a show eth0 label eth0:0
ipOpParts := strings.Fields(ipOp)
for i, tokens := range ipOpParts {
// Only check for ipv4 addresses
if tokens == "inet" {
ip := ipOpParts[i+1]
// Remove the mask
ipAddr := strings.Split(ip, "/")
if strings.Contains(ipAddr[0], "127") {
// Loopback address
continue
}
if ipAddr[0] == "" {
// Address is empty string
continue
}
return ipAddr[0], nil
}
}
return "", fmt.Errorf("Unable to find Ip address for given interface")
}
// ExternalIp returns the mgmt and data ip based on the config
func ExternalIp(config *config.ClusterConfig) (string, string, error) {
mgmtIp := ""
dataIp := ""
var err error
if config.MgmtIp == "" && config.MgtIface != "" {
mgmtIp, err = ifaceNameToIp(config.MgtIface)
if err != nil {
return "", "", errors.New("Invalid data network interface " +
"specified.")
}
} else if config.MgmtIp != "" {
mgmtIp = config.MgmtIp
}
if config.DataIp == "" && config.DataIface != "" {
dataIp, err = ifaceNameToIp(config.DataIface)
if err != nil {
return "", "", errors.New("Invalid data network interface " +
"specified.")
}
} else if config.DataIp != "" {
dataIp = config.DataIp
}
if mgmtIp != "" && dataIp != "" {
return mgmtIp, dataIp, nil
} else if mgmtIp != "" { // dataIp is empty
return mgmtIp, mgmtIp, nil
} else if dataIp != "" { // mgmtIp is empty
return dataIp, dataIp, nil
} // both are empty, try to pick first available interface for both
// No network interface specified, pick first default.
ifaces, err := net.Interfaces()
if err != nil {
return "", "", err
}
for _, iface := range ifaces {
if iface.Flags&net.FlagUp == 0 {
continue // interface down
}
if iface.Flags&net.FlagLoopback != 0 {
continue // loopback interface
}
mgmtIp, err = ifaceToIp(&iface)
if err != nil {
logrus.Printf("Skipping interface without IP: %v: %v",
iface, err)
continue
}
return mgmtIp, mgmtIp, err
}
return "", "", errors.New("Node not connected to the network.")
}
// getNodeEntry is internal helper method, shared between Inspect() and enumerateNodesFromCache()
// Parameter 'clustDBRef' may be a pointer to "empty" struct, in which case it'll be populated, but it must not be NULL.
// Also, it's caller's responsibility to lock the access to the NodeCache.
func (c *ClusterManager) getNodeEntry(nodeID string, clustDBRef *cluster.ClusterInfo) (api.Node, error) {
nodeID, _ = c.nodeIdFromIp(nodeID)
if nodeID == c.selfNode.Id {
return *c.getCurrentState(), nil
}
n, ok := c.nodeCache[nodeID]
if !ok {
return api.Node{}, errors.New("Unable to locate node with provided UUID.")
}
if n.Status == api.Status_STATUS_OFFLINE &&
(n.DataIp == "" || n.MgmtIp == "") {
// cached info unstable, read from DB
if clustDBRef.Id == "" {
// We've been passed "empty" struct, lazy-init before use
clusterDB, _, _ := readClusterInfo()
*clustDBRef = clusterDB
}
// Gossip does not have essential information of
// an offline node. Provide the essential data
// that we have in the cluster db
if v, ok := clustDBRef.NodeEntries[n.Id]; ok {
n.SchedulerNodeName = v.SchedulerNodeName
n.MgmtIp = v.MgmtIp
n.DataIp = v.DataIp
n.Hostname = v.Hostname
n.NodeLabels = v.NodeLabels
n.HWType = v.HWType
n.SecurityStatus = v.SecurityStatus
} else {
logrus.Warnf("Could not query NodeID %v", nodeID)
// Node entry won't be refreshed form DB, will use the "offline" original
}
}
// We don't want to expose our internal pointers to the caller.
// Make a deep copy of the api.Node struct before returning it.
// For the self node, this is done already by c.getCurrentState().
nodeCopy := (&n).Copy()
return *nodeCopy, nil
}
// Inspect inspects given node and returns the state
func (c *ClusterManager) Inspect(nodeID string) (api.Node, error) {
c.nodeCacheLock.Lock()
defer c.nodeCacheLock.Unlock()
nodeState, err := c.getNodeEntry(nodeID, &cluster.ClusterInfo{})
if err != nil {
return nodeState, err
}
// Allow listeners to add/modify data
for e := c.listeners.Front(); e != nil; e = e.Next() {
if err := e.Value.(cluster.ClusterListener).NodeInspect(&nodeState); err != nil {
logrus.Warnf("listener %s inspect failed: %v",
e.Value.(cluster.ClusterListener).String(), err)
continue
}
}
return nodeState, nil
}
// AddEventListener adds a new listener
func (c *ClusterManager) AddEventListener(listener cluster.ClusterListener) error {
logrus.Printf("Adding cluster event listener: %s", listener.String())
c.listeners.PushBack(listener)
return nil
}
// UpdateData updates self node data
func (c *ClusterManager) UpdateData(nodeData map[string]interface{}) error {
c.selfNodeLock.Lock()
defer c.selfNodeLock.Unlock()
for dataKey, dataValue := range nodeData {
c.selfNode.NodeData[dataKey] = dataValue
}
return nil
}
func (c *ClusterManager) UpdateLabels(nodeLabels map[string]string) error {
c.selfNodeLock.Lock()
defer c.selfNodeLock.Unlock()
if c.selfNode.NodeLabels == nil {
c.selfNode.NodeLabels = make(map[string]string)
}
for labelKey, labelValue := range nodeLabels {
c.selfNode.NodeLabels[labelKey] = labelValue
}
return nil
}
func (c *ClusterManager) UpdateSchedulerNodeName(schedulerNodeName string) error {
c.selfNodeLock.Lock()
defer c.selfNodeLock.Unlock()
c.selfNode.SchedulerNodeName = schedulerNodeName
updateCallbackFn := func(db *cluster.ClusterInfo) (bool, error) {
nodeEntry, ok := db.NodeEntries[c.selfNode.Id]
if !ok {
return false, fmt.Errorf("Node not found in cluster database")
}
nodeEntry.SchedulerNodeName = schedulerNodeName
db.NodeEntries[c.selfNode.Id] = nodeEntry
return true, nil
}
return updateDB("update-scheduler-name", c.selfNode.Id, updateCallbackFn)
}
// GetData returns self node's data
func (c *ClusterManager) GetData() (map[string]*api.Node, error) {
nodes := make(map[string]*api.Node)
c.nodeCacheLock.Lock()
defer c.nodeCacheLock.Unlock()
for _, value := range c.nodeCache {
copyValue := value.Copy()
nodes[value.Id] = copyValue
}
return nodes, nil
}
func (c *ClusterManager) nodeIdFromIp(idIp string) (string, error) {
// Caller's responsibility to lock the access to the NodeCache.
for _, n := range c.nodeCache {
if n.DataIp == idIp || n.MgmtIp == idIp {
return n.Id, nil // return Id
}
}
return idIp, errors.New("Failed to locate IP in this cluster.") // return input value
}
// GetNodeIdFromIp returns a Node Id given an IP.
func (c *ClusterManager) GetNodeIdFromIp(idIp string) (string, error) {
addr := net.ParseIP(idIp)
if addr != nil { // Is an IP, lookup Id
c.nodeCacheLock.Lock()
defer c.nodeCacheLock.Unlock()
return c.nodeIdFromIp(idIp)
}
return idIp, nil // return input, assume its an Id
}
// getCurrentState always returns the copy of selfNode that
// cluster manager maintains. It also updates the selfNode
// with latest data.
func (c *ClusterManager) getCurrentState() *api.Node {
c.selfNodeLock.Lock()
defer c.selfNodeLock.Unlock()
c.selfNode.Timestamp = time.Now()
c.selfNode.Cpu, _, _ = c.system.CpuUsage()
c.selfNode.MemTotal, c.selfNode.MemUsed, c.selfNode.MemFree = c.system.MemUsage()
if c.selfNode.HWType == api.HardwareType_UnknownMachine {
c.selfNode.HWType = c.config.HWType
}
c.selfNode.Timestamp = time.Now()
for e := c.listeners.Front(); e != nil; e = e.Next() {
listenerDataMap := e.Value.(cluster.ClusterListener).ListenerData()
if listenerDataMap == nil {
continue
}
for key, val := range listenerDataMap {
c.selfNode.NodeData[key] = val
}
}
nodeCopy := (&c.selfNode).Copy()
return nodeCopy
}
func (c *ClusterManager) getNonDecommisionedPeers(
db cluster.ClusterInfo,
) map[types.NodeId]types.NodeUpdate {
peers := make(map[types.NodeId]types.NodeUpdate)
for _, nodeEntry := range db.NodeEntries {
if nodeEntry.Status == api.Status_STATUS_DECOMMISSION {
continue
}
peers[types.NodeId(nodeEntry.Id)] = types.NodeUpdate{
Addr: net.JoinHostPort(nodeEntry.DataIp, c.gossipPort),
QuorumMember: !nodeEntry.NonQuorumMember,
ClusterDomain: nodeEntry.ClusterDomain,
}
}
return peers
}
// Get the latest config.
func (c *ClusterManager) watchDB(key string, opaque interface{},
kvp *kvdb.KVPair, watchErr error) error {
var (
db cluster.ClusterInfo
kvdbVersion uint64
err error
)
if watchErr != nil {
if c.selfNode.Status == api.Status_STATUS_DECOMMISSION {
logrus.Warnf("Node is decommissioned, got watch error: %v", watchErr)
// node is decommissioned, no need to do anything
return watchErr
}
logrus.Warnf("ClusterManager watch error: %v, getting latest db directly", watchErr)
// since ClusterManager handles multiple updates at once, we should
// be ok to get the latest version of clusterDB and then starting
// watch from that version.
db, kvdbVersion, err = readClusterInfo()
if err != nil {
logrus.Errorf("ClusterManager could not get db directly: %v", err)
// can't do much, try restarting watch
c.startClusterDBWatch(c.kvdbWatchIndex, kvdb.Instance())
return watchErr
} else {
// start the watch
c.kvdbWatchIndex = kvdbVersion
defer c.startClusterDBWatch(0, kvdb.Instance())
}
} else {
db, kvdbVersion, err = unmarshalClusterInfo(kvp)
if err != nil || len(db.NodeEntries) == 0 {
logrus.Errorf("watch returned nil or empty cluster database: %v", kvp)
// cluster database should not be nil, exit since we don't know what happened
os.Exit(1)
}
if kvdbVersion <= c.kvdbWatchIndex {
// skip processing version update
return nil
}
c.kvdbWatchIndex = kvdbVersion
}
// Update all the listeners with the new db
for e := c.listeners.Front(); e != nil; e = e.Next() {
err := e.Value.(cluster.ClusterListener).UpdateCluster(&c.selfNode, &db)
if err != nil {
logrus.Warnln("Failed to notify ", e.Value.(cluster.ClusterListener).String())
}
}
for _, nodeEntry := range db.NodeEntries {
if nodeEntry.Status == api.Status_STATUS_DECOMMISSION {
logrus.Infof("ClusterManager watchDB, node ID "+
"%s state is Decommission.",
nodeEntry.Id)
n, found := c.getNodeCacheEntry(nodeEntry.Id)
if !found {
logrus.Errorf("ClusterManager watchDB, "+
"node ID %s not in node cache",
nodeEntry.Id)
continue
}
if n.Status == api.Status_STATUS_DECOMMISSION {
logrus.Infof("ClusterManager watchDB, "+
"node ID %s is already decommission "+
"on this node",
nodeEntry.Id)
continue
}
logrus.Infof("ClusterManager watchDB, "+
"decommsission node ID %s on this node",
nodeEntry.Id)
n.Status = api.Status_STATUS_DECOMMISSION
c.putNodeCacheEntry(nodeEntry.Id, n)
// We are getting decommissioned!!
if nodeEntry.Id == c.selfNode.Id {
// We are getting decommissioned.
// Stop the heartbeat and stop the watch
stopHeartbeat <- true
c.gossip.Stop(time.Duration(10 * time.Second))
return fmt.Errorf("stop watch")
}
}
}
atomic.StoreInt64(c.size, int64(db.Size))
c.gossip.UpdateCluster(c.getNonDecommisionedPeers(db))
// update the nodeCache and remove any nodes not present in cluster database
c.nodeCacheLock.Lock()
defer c.nodeCacheLock.Unlock()
for _, n := range c.nodeCache {
_, found := db.NodeEntries[n.Id]
if !found {
delete(c.nodeCache, n.Id)
}
}
return watchErr
}
func (c *ClusterManager) getLatestNodeConfig(nodeId string) *cluster.NodeEntry {
db, _, err := readClusterInfo()
if err != nil {
logrus.Warnln("Failed to read the database for updating config")
return nil
}
ne, exists := db.NodeEntries[nodeId]
if !exists {
logrus.Warnln("Could not find info for node with id ", nodeId)
return nil
}
return &ne
}
func (c *ClusterManager) initNode(db *cluster.ClusterInfo) (*api.Node, bool) {
_, exists := db.NodeEntries[c.selfNode.Id]
// Add us into the database.
labels := make(map[string]string)
labels[gossipVersionKey] = c.gossipVersion
nodeEntry := cluster.NodeEntry{
Id: c.selfNode.Id,
SchedulerNodeName: c.selfNode.SchedulerNodeName,
MgmtIp: c.selfNode.MgmtIp,
DataIp: c.selfNode.DataIp,
GenNumber: c.selfNode.GenNumber,
StartTime: c.selfNode.StartTime,
MemTotal: c.selfNode.MemTotal,
Hostname: c.selfNode.Hostname,
NodeLabels: labels,
GossipPort: c.selfNode.GossipPort,
ClusterDomain: c.selfClusterDomain,
HWType: c.config.HWType,
SecurityStatus: c.selfNode.SecurityStatus,
}
db.NodeEntries[c.config.NodeId] = nodeEntry
logrus.Infof("Node %s joining cluster...", c.config.NodeId)
logrus.Infof("Cluster ID: %s", c.config.ClusterId)
logrus.Infof("Node Mgmt IP: %s", c.selfNode.MgmtIp)
logrus.Infof("Node Data IP: %s", c.selfNode.DataIp)
logrus.Infof("Node HWType: %s", c.config.HWType.String())
logrus.Infof("Node SecurityStatus: %v", c.selfNode.SecurityStatus.String())
if len(c.selfClusterDomain) > 0 {
logrus.Infof("Node's Cluster Domain: %s", c.selfClusterDomain)
}
return &c.selfNode, exists
}
func (c *ClusterManager) cleanupInit(db *cluster.ClusterInfo, self *api.Node) error {
var resErr error
var err error
logrus.Infof("Cleanup Init services")
for e := c.listeners.Front(); e != nil; e = e.Next() {
logrus.Warnf("Cleanup Init for service %s.",
e.Value.(cluster.ClusterListener).String())
err = e.Value.(cluster.ClusterListener).CleanupInit(self, db)
if err != nil {
logrus.Warnf("Failed to Cleanup Init %s: %v",
e.Value.(cluster.ClusterListener).String(), err)
resErr = err
}
}
return resErr
}
// Initialize node and alert listeners that we are initializing a node in the cluster.
func (c *ClusterManager) initNodeInCluster(
clusterInfo *cluster.ClusterInfo,
self *api.Node,
exist bool,
nodeInitialized bool,
) ([]cluster.FinalizeInitCb, error) {
// If I am already in the cluster map, don't add me again.
if exist {
return nil, nil
}
if nodeInitialized {
logrus.Errorf(cluster.ErrInitNodeNotFound.Error())
return nil, cluster.ErrInitNodeNotFound
}
// Alert all listeners that we are a new node and we are initializing.
finalizeCbs := make([]cluster.FinalizeInitCb, 0)
for e := c.listeners.Front(); e != nil; e = e.Next() {
finalizeCb, err := e.Value.(cluster.ClusterListener).Init(self, clusterInfo)
if err != nil {
if self.Status != api.Status_STATUS_MAINTENANCE {
self.Status = api.Status_STATUS_ERROR
}
logrus.Warnf("Failed to initialize %s: %v",
e.Value.(cluster.ClusterListener).String(), err)
c.cleanupInit(clusterInfo, self)
return nil, err
}
if finalizeCb != nil {
finalizeCbs = append(finalizeCbs, finalizeCb)
}
}
return finalizeCbs, nil
}
// Alert all listeners that we are joining the cluster
func (c *ClusterManager) joinCluster(
self *api.Node,
) error {
fn := "joinCluster"
// Alert all listeners that we are joining the cluster.
for e := c.listeners.Front(); e != nil; e = e.Next() {
err := e.Value.(cluster.ClusterListener).PreJoin(self)
if err != nil {
logrus.Warnf("Failed to execute PreJoin %s: %v",
e.Value.(cluster.ClusterListener).String(), err)
logrus.Errorln("Failed to join cluster.", err)
return err
}
}
// Listeners may update initial state, so snap again.
// The cluster db may have diverged since we waited for quorum
// in between. Snapshot is created under cluster db lock to make
// sure cluster db updates do not happen during snapshot, otherwise
// there may be a mismatch between db updates from listeners and
// cluster db state.
lockKey := path.Join(c.config.NodeId, self.DataIp, fn)
lockTryDuration := defaultClusterLockTryDuration
if c.config.SnapLockTryDurationInMinutes > 0 {
lockTryDuration = time.Duration(c.config.SnapLockTryDurationInMinutes) * time.Minute
}
kvlock, err := kvdb.Instance().LockWithTimeout(
clusterLockKey,
lockKey,
lockTryDuration,
kvdb.Instance().GetLockTimeout(),
)
if err != nil {
logrus.Warnln("Unable to obtain cluster lock before creating snapshot: ",
err)
return err
}
initState, err := snapAndReadClusterInfo(c.snapshotPrefixes)
kvdb.Instance().Unlock(kvlock)
if err != nil {
dbg.LogErrorAndPanicf(err, "fatal: unable to create snapshot")
return err
}
defer func() {
if initState.Collector != nil {
initState.Collector.Stop()
initState.Collector = nil
}
}()
// Alert all listeners that we are joining the cluster.
for e := c.listeners.Front(); e != nil; e = e.Next() {
err := e.Value.(cluster.ClusterListener).Join(self, initState)
if err != nil {
if self.Status != api.Status_STATUS_MAINTENANCE {
self.Status = api.Status_STATUS_ERROR
}
logrus.Warnf("Failed to initialize Join %s: %v",
e.Value.(cluster.ClusterListener).String(), err)
logrus.Errorln("Failed to join cluster.", err)
return err
}
}
selfNodeEntry, ok := initState.ClusterInfo.NodeEntries[c.config.NodeId]
if !ok {
warnMsg := "fatal: unable to find self node entry in local cache"
dbg.LogErrorAndPanicf(fmt.Errorf(warnMsg), warnMsg)
}
prevNonQuorumMemberState := selfNodeEntry.NonQuorumMember
selfNodeEntry.NonQuorumMember =
selfNodeEntry.Status == api.Status_STATUS_DECOMMISSION ||
!c.quorumMember()
if selfNodeEntry.NonQuorumMember != prevNonQuorumMemberState {
if !selfNodeEntry.NonQuorumMember {
logrus.Infof("This node now participates in quorum decisions")
}
}
updateCallbackFn := func(db *cluster.ClusterInfo) (bool, error) {
db.NodeEntries[selfNodeEntry.Id] = selfNodeEntry
return true, nil
}
return updateDB(fn, selfNodeEntry.Id, updateCallbackFn)
}
func (c *ClusterManager) initClusterForListeners(
self *api.Node,
) error {
err := error(nil)
// Alert all listeners that we are initializing a new cluster.
for e := c.listeners.Front(); e != nil; e = e.Next() {
err = e.Value.(cluster.ClusterListener).ClusterInit(self)
if err != nil {
if self.Status != api.Status_STATUS_MAINTENANCE {
self.Status = api.Status_STATUS_ERROR
}
logrus.Printf("Failed to initialize %s",
e.Value.(cluster.ClusterListener).String())
goto done
}
}
done:
return err
}
func (c *ClusterManager) startClusterDBWatch(lastIndex uint64,
kv kvdb.Kvdb) error {
logrus.Infof("Cluster manager starting watch at version %d", lastIndex)
c.kvdbWatchIndex = lastIndex
go kv.WatchKey(ClusterDBKey, c.kvdbWatchIndex, nil, c.watchDB)
return nil
}
func (c *ClusterManager) startHeartBeat(
clusterInfo *cluster.ClusterInfo,
activeMap types.ClusterDomainsActiveMap,
) {
gossipStoreKey := types.StoreKey(heartbeatKey + c.config.ClusterId)
node := c.getCurrentState()
c.putNodeCacheEntry(c.selfNode.Id, *node)
c.gossip.UpdateSelf(gossipStoreKey, *node)
var nodeIps []string
gossipConfig := types.GossipStartConfiguration{
ActiveMap: activeMap,
}
gossipConfig.Nodes = make(map[types.NodeId]types.GossipNodeConfiguration)
for nodeId, nodeEntry := range clusterInfo.NodeEntries {
if nodeId == node.Id {
continue
}
labels := nodeEntry.NodeLabels
version, ok := labels[gossipVersionKey]
if !ok || version != c.gossipVersion {
// Do not add nodes with mismatched version
continue
}
gossipPort := nodeEntry.GossipPort
if gossipPort == "" {
// The cluster DB does not have the gossip port value
// The probability of this happening is close to 0
// In an event if this happens, lets use our own gossip port
// for this node. If that node has a different port, once that
// node pings us, gossip protocol will automatically update the port
gossipPort = c.gossipPort
}
nodeIp := net.JoinHostPort(nodeEntry.DataIp, gossipPort)
gossipConfig.Nodes[types.NodeId(nodeId)] = types.GossipNodeConfiguration{
KnownUrl: nodeIp,
ClusterDomain: nodeEntry.ClusterDomain,
}
nodeIps = append(nodeIps, nodeIp)
}
if len(nodeIps) > 0 {
logrus.Infof("Starting Gossip... Gossiping to these nodes : %v", nodeIps)
} else {
logrus.Infof("Starting Gossip...")
}
if len(activeMap) > 0 {
gossipConfig.QuorumProviderType = types.QUORUM_PROVIDER_FAILURE_DOMAINS
} else {
gossipConfig.QuorumProviderType = types.QUORUM_PROVIDER_DEFAULT
}
c.gossip.Start(gossipConfig)
c.gossip.UpdateCluster(c.getNonDecommisionedPeers(*clusterInfo))
lastUpdateTs := time.Now()
for {
select {
case <-stopHeartbeat:
return
default:
node = c.getCurrentState()
currTime := time.Now()
diffTime := currTime.Sub(lastUpdateTs)
if diffTime > 10*time.Second {
logrus.Warnln("No gossip update for ", diffTime.Seconds(), "s")
}
c.gossip.UpdateSelf(gossipStoreKey, *node)
lastUpdateTs = currTime
}
time.Sleep(2 * time.Second)
}
}
func (c *ClusterManager) notifyListeners() {
gossipStoreKey := types.StoreKey(heartbeatKey + c.config.ClusterId)
for {
// Process heartbeats from other nodes...
gossipValues := c.gossip.GetStoreKeyValue(gossipStoreKey)
for id, gossipNodeInfo := range gossipValues {
// Special handling for self node
if id == types.NodeId(c.selfNode.Id) {
// TODO: Implement State Machine for node statuses similar to the one in gossip
if c.selfNode.Status == api.Status_STATUS_OK &&
gossipNodeInfo.Status == types.NODE_STATUS_SUSPECT_NOT_IN_QUORUM {
// Current:
// Cluster Manager Status: UP.
// Gossip Status: Suspecting Not in Quorum (stays in this state for quorumTimeout)
// New:
// Cluster Manager: Not in Quorum
// Cluster Manager does not have a Suspect in Quorum status
logrus.Warnf("Can't reach quorum no. of nodes. Suspecting out of quorum...")
c.selfNode.Status = api.Status_STATUS_NOT_IN_QUORUM
c.status = api.Status_STATUS_NOT_IN_QUORUM
// Report to the listeners that this node's status has changed to NotInQuorum
for e := c.listeners.Front(); e != nil && c.gEnabled; e = e.Next() {
err := e.Value.(cluster.ClusterListener).Update(&c.selfNode)
if err != nil {
logrus.Warnln("Failed to notify ",
e.Value.(cluster.ClusterListener).String())
}
}
} else if (c.selfNode.Status == api.Status_STATUS_NOT_IN_QUORUM ||
c.selfNode.Status == api.Status_STATUS_OK) &&
(gossipNodeInfo.Status == types.NODE_STATUS_NOT_IN_QUORUM ||
gossipNodeInfo.Status == types.NODE_STATUS_DOWN) {
// Current:
// Cluster Manager Status: UP or Not in Quorum.
// Gossip Status: Not in Quorum or DOWN
// New:
// Cluster Manager: DOWN
// Gossip waited for quorumTimeout and indicates we are Not in Quorum and should go Down
logrus.Warnf("Not in quorum. Gracefully shutting down...")
c.gossip.UpdateSelfStatus(types.NODE_STATUS_DOWN)
c.selfNode.Status = api.Status_STATUS_OFFLINE
c.status = api.Status_STATUS_NOT_IN_QUORUM
logrus.Fatal(c.Shutdown())
} else if c.selfNode.Status == api.Status_STATUS_NOT_IN_QUORUM &&
gossipNodeInfo.Status == types.NODE_STATUS_UP {
// Current:
// Cluster Manager Status: Not in Quorum
// Gossip Status: Up
// New:
// Cluster Manager : UP
c.selfNode.Status = api.Status_STATUS_OK
c.status = api.Status_STATUS_OK
} else {
// Ignore the update
}
continue
}
// Notify node status change if required.
peerNode, _ := c.gossipNodeToAPINode(id, &gossipNodeInfo)
// Initialize a no-op notify listeners function
notifyListenerFn := func() {}
var peerNodeCopy *api.Node
switch {
case gossipNodeInfo.Status == types.NODE_STATUS_DOWN:
lastStatus, ok := c.nodeStatuses[string(id)]
if !ok {
// This node was probably added recently into gossip node
// map through cluster database and is yet to reach out to us.
// Mark this node down.
logrus.Warnln("Detected new node with ", id,
" to be offline due to inactivity.")
} else {
if lastStatus == peerNode.Status {
break
}
logrus.Warnln("Detected node ", id,
" to be offline due to inactivity.")
}
c.nodeStatuses[string(id)] = peerNode.Status
peerNodeCopy = peerNode.Copy()
notifyListenerFn = func() {
for e := c.listeners.Front(); e != nil && c.gEnabled; e = e.Next() {
err := e.Value.(cluster.ClusterListener).Update(peerNodeCopy)
if err != nil {
logrus.Warnln("Failed to notify ",
e.Value.(cluster.ClusterListener).String())
}
}
}
case gossipNodeInfo.Status == types.NODE_STATUS_UP:
lastStatus, ok := c.nodeStatuses[string(id)]
if ok && lastStatus == peerNode.Status {
break
}
c.nodeStatuses[string(id)] = peerNode.Status
// A node discovered in the cluster.
logrus.Infoln("Detected node", peerNode.Id,
" to be in the cluster.")
peerNodeCopy = peerNode.Copy()
notifyListenerFn = func() {
for e := c.listeners.Front(); e != nil && c.gEnabled; e = e.Next() {
err := e.Value.(cluster.ClusterListener).Add(peerNodeCopy)
if err != nil {
logrus.Warnln("Failed to notify ",
e.Value.(cluster.ClusterListener).String())
}
}
}
}
// Notify the listeners
notifyListenerFn()
}
time.Sleep(2 * time.Second)
}
}
func (c *ClusterManager) updateNodesInCache() {
gossipStoreKey := types.StoreKey(heartbeatKey + c.config.ClusterId)
for {
// Process self node
node := c.getCurrentState()
c.putNodeCacheEntry(node.Id, *node)