forked from libi/dcron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node_pool.go
97 lines (84 loc) · 1.91 KB
/
node_pool.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
package dcron
import (
"github.com/xiaojun207/dcron/consistenthash"
"github.com/xiaojun207/dcron/driver"
"sync"
"time"
)
//NodePool is a node pool
type NodePool struct {
serviceName string
NodeID string
mu sync.Mutex
nodes *consistenthash.Map
Driver driver.Driver
hashReplicas int
hashFn consistenthash.Hash
updateDuration time.Duration
dcron *Dcron
}
func newNodePool(serverName string, driver driver.Driver, dcron *Dcron, updateDuration time.Duration, hashReplicas int) *NodePool {
err := driver.Ping()
if err != nil {
panic(err)
}
nodePool := &NodePool{
Driver: driver,
serviceName: serverName,
dcron: dcron,
hashReplicas: hashReplicas,
updateDuration: updateDuration,
}
return nodePool
}
func (np *NodePool) StartPool() error {
var err error
np.Driver.SetTimeout(np.updateDuration)
np.NodeID, err = np.Driver.RegisterServiceNode(np.serviceName)
if err != nil {
return err
}
np.Driver.SetHeartBeat(np.NodeID)
err = np.updatePool()
if err != nil {
return err
}
go np.tickerUpdatePool()
return nil
}
func (np *NodePool) updatePool() error {
np.mu.Lock()
defer np.mu.Unlock()
nodes, err := np.Driver.GetServiceNodeList(np.serviceName)
if err != nil {
return err
}
np.nodes = consistenthash.New(np.hashReplicas, np.hashFn)
for _, node := range nodes {
np.nodes.Add(node)
}
return nil
}
func (np *NodePool) tickerUpdatePool() {
tickers := time.NewTicker(time.Second * defaultDuration)
for range tickers.C {
if np.dcron.isRun {
err := np.updatePool()
if err != nil {
np.dcron.err("update node pool error %+v", err)
}
} else {
tickers.Stop()
return
}
}
}
//PickNodeByJobName : 使用一致性hash算法根据任务名获取一个执行节点
func (np *NodePool) PickNodeByJobName(jobName string) string {
np.mu.Lock()
defer np.mu.Unlock()
if np.nodes.IsEmpty() {
return ""
}
return np.nodes.Get(jobName)
}