-
Notifications
You must be signed in to change notification settings - Fork 201
/
node.go
119 lines (98 loc) · 2.03 KB
/
node.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
package discovery
import (
"fmt"
"github.com/eolinker/eosc/eocontext"
"sync/atomic"
"time"
)
// NodeStatus 节点状态类型
type NodeStatus = eocontext.NodeStatus
const (
//Running 节点运行中状态
Running = eocontext.Running
//Down 节点不可用状态
Down = eocontext.Down
//Leave 节点离开状态
Leave = eocontext.Leave
)
type INode interface {
IP() string
ID() string
Addr() string
Port() int
Status() NodeStatus
Last() time.Time
Up()
Down()
Leave()
}
type _INodeStatusCheck interface {
status(status NodeStatus) NodeStatus
}
type _BaseNode struct {
id string
ip string
port int
status NodeStatus
lastTime atomic.Pointer[time.Time]
statusChecker _INodeStatusCheck
}
func (n *_BaseNode) Last() time.Time {
t := n.lastTime.Load()
if t != nil {
now := time.Now()
n.lastTime.Store(&now)
t = n.lastTime.Load()
}
return *t
}
func newBaseNode(ip string, port int, statusChecker _INodeStatusCheck) *_BaseNode {
return &_BaseNode{ip: ip, port: port, status: Running, statusChecker: statusChecker}
}
func (n *_BaseNode) ID() string {
return n.id
}
func (n *_BaseNode) IP() string {
return n.ip
}
func (n *_BaseNode) Port() int {
return n.port
}
func (n *_BaseNode) Status() eocontext.NodeStatus {
return n.statusChecker.status(n.status)
}
// Addr 返回节点地址
func (n *_BaseNode) Addr() string {
if n.port == 0 {
return n.ip
}
return fmt.Sprintf("%s:%d", n.ip, n.port)
}
// Up 将节点状态置为运行中
func (n *_BaseNode) Up() {
n.status = Running
}
// Down 将节点状态置为不可用
func (n *_BaseNode) Down() {
n.status = Down
}
// Leave 将节点状态置为离开
func (n *_BaseNode) Leave() {
n.status = Leave
}
// Attrs 属性集合
type Attrs = eocontext.Attrs
type Node struct {
INode
label Attrs
}
func NewNode(INode INode, label Attrs) eocontext.INode {
return &Node{INode: INode, label: label}
}
func (n *Node) GetAttrs() eocontext.Attrs {
return n.label
}
func (n *Node) GetAttrByName(name string) (string, bool) {
v, h := n.label[name]
return v, h
}