qixiaoning
23 小时以前 03880bf61cf059f063e252ef17dfea50c932c9dc
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
package nodeService
 
import (
    "time"
    "vamicro/config"
    "vamicro/extend/util"
 
    "basic.com/pubsub/protomsg.git"
    "basic.com/valib/bhomedbapi.git"
    "basic.com/valib/logger.git"
)
 
type ClusterNode struct {
    // 当前节点是否为主节点
    IsMaster bool `json:"is_master"`
    // 当前服务状态
    ServerStatus bool `json:"server_status"`
    // 集群ID
    ClusterId string `json:"cluster_id"`
    // 集群名称
    ClusterName string `json:"cluster_name"`
    // 当前节点ID
    NodeId string `json:"node_id"`
    // 集群密码
    Password string `json:"password"`
    // 漂移IP
    VirtualIp string `json:"virtual_ip"`
    // 所有节点列表
    NodeLists []*protomsg.Node `json:"Nodes"`
}
 
// 节点属性
var Node = &ClusterNode{}
 
// 初始化节点属性
func InitNode() {
 
    // 当前节点ID
    Node.NodeId = config.Server.AnalyServerId
    // 初始化集群信息
    var clusterApi bhomedbapi.ClusterApi
    b, c := clusterApi.FindCluster()
    logger.Debugf("InitClusterNodes..., c=%v", c)
    if b && c.Nodes != nil && len(c.Nodes) > 0 {
        logger.Debug("Is cluster...")
        // 是集群
        Node.NodeLists = c.Nodes
        Node.ClusterId = c.ClusterId
        Node.ClusterName = c.ClusterName
        Node.Password = c.Password
        Node.VirtualIp = c.VirtualIp
        for _, n := range c.Nodes {
            if n.NodeId == Node.NodeId {
                // 当前节点是否为主节点
                if n.DriftState == "master" {
                    logger.Debug("Is master...")
                    Node.IsMaster = true
                } else {
                    logger.Debug("Not master...")
                    Node.IsMaster = false
                }
            }
        }
    } else {
        // 不是集群,只有当前节点
        logger.Debug("Not cluster...")
 
        Node.IsMaster = true
        Node.NodeLists = make([]*protomsg.Node, 0)
        ipv4, _, _ := util.GetLocalIP(config.Server.NetworkAdapter)
        Node.NodeLists = append(Node.NodeLists, &protomsg.Node{
            Id:         config.Server.AnalyServerId,
            ClusterId:  "",
            NodeName:   config.Server.ServerName,
            NodeId:     config.Server.AnalyServerId,
            NodeIp:     ipv4,
            IsDelete:   false,
            DriftState: "master",
            DeviceType: config.Server.DeviceType,
        })
    }
    logger.Debug("InitClusterNodes success...", Node)
}
 
// 监测节点变化
func WatchNode() {
    go func() {
        tk := time.NewTicker(15 * time.Second)
        for {
            select {
            case <-tk.C:
                InitNode()
            }
        }
    }()
}