/
node.go
341 lines (309 loc) · 7.22 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
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
package riff
import (
"bytes"
"crypto/sha1"
"fmt"
"github.com/gimke/riff/api"
"github.com/gimke/riff/common"
"gopkg.in/yaml.v2"
"io"
"io/ioutil"
"net"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
)
type Nodes struct {
nodes sync.Map
}
type Digest struct {
Name string
SnapShot string
}
func (s *Server) Keys() []string {
var keys = make([]string, 0, 0)
s.nodes.Range(func(key, value interface{}) bool {
keys = append(keys, key.(string))
return true
})
/*sort.Slice(keys, func(i, j int) bool {
var validID = regexp.MustCompile(`^(\S+)([0-9]+)$`)
if validID.MatchString(keys[i]) && validID.MatchString(keys[j]) {
arri := validID.FindAllStringSubmatch(keys[i],-1)
arrj := validID.FindAllStringSubmatch(keys[j],-1)
if arri[0][1] == arrj[0][1] {
inti,_ := strconv.Atoi(arri[0][2])
intj,_ := strconv.Atoi(arrj[0][2])
return inti < intj
} else {
return arri[0][1] < arrj[0][1]
}
} else {
return keys[i] < keys[j]
}
})*/
sort.Strings(keys)
return keys
}
func (s *Server) Slice() []*Node {
keys := s.Keys()
nodes := make([]*Node, 0)
for _, key := range keys {
if n := s.GetNode(key); n != nil {
nodes = append(nodes, n)
}
}
return nodes
}
func (s *Server) ServicesSlice() []string {
keys := s.Keys()
helper := make(map[string]string, 0)
services := []string{}
for _, key := range keys {
if n := s.GetNode(key); n != nil {
for name, _ := range n.Services {
if _, ok := helper[name]; !ok {
helper[name] = name
services = append(services, name)
}
}
}
}
return services
}
func (s *Server) GetService(findName string) interface{} {
keys := s.Keys()
var service map[string]interface{}
nodes := []string{}
for _, key := range keys {
if n := s.GetNode(key); n != nil {
for name, s := range n.Services {
if name == findName {
if service == nil {
service = map[string]interface{}{
"Name": name,
}
}
if n.State == api.StateAlive {
nodes = append(nodes, s.Address())
}
}
}
}
}
if service != nil {
service["Nodes"] = nodes
}
return service
}
func (s *Server) Range(f func(string, *Node) bool) {
s.nodes.Range(func(key, value interface{}) bool {
return f(key.(string), value.(*Node))
})
}
func (s *Server) GetNode(key string) *Node {
if n, _ := s.nodes.Load(key); n != nil {
return n.(*Node)
}
return nil
}
func (s *Server) AddNode(n *Node) {
n.Shutter()
s.nodes.Store(n.Name, n)
//watch
s.watch.Dispatch(WatchParam{
Name: n.Name,
WatchType: NodeChanged,
})
}
func (s *Server) AddService(service *Service) {
s.Self.Services[service.Name] = service
}
func (s *Server) DeleteNode(key string) {
s.nodes.Delete(key)
//watch
s.watch.Dispatch(WatchParam{
Name: key,
WatchType: NodeChanged,
})
}
func (s *Server) RemoveNodeDelay(n *Node) {
if n.timeoutFn == nil {
n.timeoutFn = func() {
//delete this node
if n.State == api.StateDead {
s.Logger.Printf(infoServerPrefix+"remove dead node %s\n", n.Name)
s.DeleteNode(n.Name)
//clear fn
n.timeoutFn = nil
}
}
timeout := 5 * 60 * time.Second
n.timer = time.AfterFunc(timeout, n.timeoutFn)
}
}
// set node state version inc and shutter node return version
func (s *Server) SetStateOnly(n *Node, state api.StateType) uint64 {
n.State = state
n.Shutter()
return n.VersionGet()
}
// set node state version inc and shutter node return version++
func (s *Server) SetState(n *Node, state api.StateType) uint64 {
n.State = state
v := n.VersionInc()
n.Shutter()
return v
}
// SetState and make a snapsort return version ++
func (s *Server) SetStateWithShutter(n *Node, state api.StateType) uint64 {
v := s.SetState(n, state)
s.Shutter()
return v
}
// get random nodes
func (s *Server) randomNodes(fanout int, filterFn func(*Node) bool) []*Node {
nodes := s.Keys()
n := len(nodes)
RNodes := make([]*Node, 0, fanout)
OUTER:
for i := 0; i < 3*n && len(RNodes) < fanout; i++ {
idx := common.RandomNumber(n)
n := s.GetNode(nodes[idx])
if n == nil {
continue OUTER
} //filter nodes
if filterFn != nil && filterFn(n) {
continue OUTER
}
// Check if we have this node already
for j := 0; j < len(RNodes); j++ {
if n == RNodes[j] {
continue OUTER
}
}
RNodes = append(RNodes, n)
}
return RNodes
}
type Node struct {
Name string
DataCenter string
IP string
RpcPort int
HttpPort int
Version uint64
State api.StateType // Current state
StateChange time.Time // Time last state change happened
SnapShot string
Services
IsSelf bool
nodeLock sync.RWMutex
timer *time.Timer
timeoutFn func()
}
func (n *Node) VersionGet() uint64 {
return atomic.LoadUint64(&n.Version)
}
func (n *Node) VersionInc() uint64 {
return atomic.AddUint64(&n.Version, 1)
}
// Witness is called to update our local clock if necessary after
// witnessing a clock value received from another process
func (n *Node) VersionSet(v uint64) {
WITNESS:
// If the other value is old, we do not need to do anything
cur := atomic.LoadUint64(&n.Version)
other := uint64(v)
if other < cur {
return
}
// Ensure that our local clock is at least one ahead.
if !atomic.CompareAndSwapUint64(&n.Version, cur, other) {
// The CAS failed, so we just retry. Eventually our CAS should
// succeed or a future witness will pass us by and our witness
// will end.
goto WITNESS
}
}
func (n *Node) Address() string {
return net.JoinHostPort(n.IP, strconv.Itoa(int(n.RpcPort)))
}
func (n *Node) String() string {
buff := bytes.NewBuffer(nil)
io.WriteString(buff, n.Name+":"+strconv.FormatUint(n.Version, 10)+":{")
//write service name and version
keys := n.Services.Keys()
for i, sk := range keys {
s := n.Services[sk]
io.WriteString(buff, s.Name+":{"+s.Address()+","+s.State.Name()+","+strconv.Itoa(int(s.Progress.Current))+"}")
if i != len(keys)-1 {
io.WriteString(buff, ",")
}
}
io.WriteString(buff, "}")
return buff.String()
}
func (n *Node) Shutter() {
h := sha1.New()
io.WriteString(h, n.String())
n.SnapShot = fmt.Sprintf("%x", h.Sum(nil))
}
func (n *Node) LoadServices() {
if n.Services == nil {
n.Services = make(map[string]*Service)
}
files, err := ioutil.ReadDir(common.BinDir + "/config")
if err == nil {
for _, file := range files {
basename := file.Name()
if basename == "riff.yml" {
continue
}
if strings.HasPrefix(basename, ".") {
continue
}
name := strings.TrimSuffix(basename, filepath.Ext(basename))
s := n.LoadService(name)
if s != nil {
n.Services[s.Name] = s
}
}
}
n.Shutter()
}
func (n *Node) rewriteConfig(service *Service) {
//rewrite name port ip
}
func (n *Node) LoadService(name string) *Service {
file := common.BinDir + "/config/" + name + ".yml"
if !common.IsExist(file) {
return nil
}
content, _ := ioutil.ReadFile(file)
var s = &Service{}
var c = &ServiceConfig{}
err := yaml.Unmarshal(content, &c)
if err != nil {
server.Logger.Printf(errorServicePrefix+"%s config file error: %v", name, err)
return nil
}
s.Config = string(content)
s.ServiceConfig = c
s.StateChange = time.Now()
s.StartTime = time.Now()
s.Progress = &Progress{
Current: 0,
Total: 0,
InProgress: false,
}
//rewrite name port ip
s.rewriteConfig()
s.runAtLoad()
s.checkState()
return s
}