-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathdiscovery.go
339 lines (308 loc) · 7.38 KB
/
discovery.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
package naming
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"strings"
"sync"
"sync/atomic"
"time"
)
const (
_registerURL = "http://%s/api/register"
_cancelURL = "http://%s/api/cancel"
_renewURL = "http://%s/api/renew"
_fetchURL = "http://%s/api/fetch"
_nodesURL = "http://%s/api/nodes"
)
const (
NodeInterval = 90 * time.Second
RenewInterval = 60 * time.Second
)
type Config struct {
Nodes []string
Env string
}
type Discovery struct {
once *sync.Once
conf *Config
ctx context.Context
cancelFunc context.CancelFunc
//local cache
mutex sync.RWMutex
apps map[string]*FetchData //fetch catch
registry map[string]struct{}
//registry center node
idx uint64 //node index
node atomic.Value //node list
}
func New(conf *Config) *Discovery {
if len(conf.Nodes) == 0 {
panic("conf nodes empty!")
}
ctx, cancel := context.WithCancel(context.Background())
dis := &Discovery{
ctx: ctx,
cancelFunc: cancel,
conf: conf,
apps: map[string]*FetchData{},
registry: map[string]struct{}{},
}
//from conf get node list
dis.node.Store(conf.Nodes)
go dis.updateNode()
return dis
}
func (dis *Discovery) Register(ctx context.Context, instance *Instance) (context.CancelFunc, error) {
var err error
//check local cache
dis.mutex.Lock()
if _, ok := dis.registry[instance.AppId]; ok {
err = errors.New("instance duplicate register")
} else {
dis.registry[instance.AppId] = struct{}{} //register local cache
}
dis.mutex.Unlock()
if err != nil {
return nil, err
}
//http register
ctx, cancel := context.WithCancel(dis.ctx)
if err = dis.register(instance); err != nil {
//fail
dis.mutex.Lock()
delete(dis.registry, instance.AppId)
dis.mutex.Unlock()
return cancel, err
}
ch := make(chan struct{}, 1)
cancelFunc := context.CancelFunc(func() {
cancel()
<-ch
})
//renew&cancel
go func() {
ticker := time.NewTicker(RenewInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
if err := dis.renew(instance); err != nil {
dis.register(instance)
}
case <-ctx.Done():
dis.cancel(instance)
ch <- struct{}{}
}
}
}()
return cancelFunc, nil
}
func (dis *Discovery) register(instance *Instance) error {
uri := fmt.Sprintf(_registerURL, dis.pickNode())
log.Println("discovery - request register url:" + uri)
params := make(map[string]interface{})
params["env"] = dis.conf.Env
params["appid"] = instance.AppId
params["hostname"] = instance.Hostname
params["addrs"] = instance.Addrs
params["version"] = instance.Version
params["status"] = 1
resp, err := HttpPost(uri, params) //ctx
if err != nil {
dis.switchNode()
log.Println("register err: ", err, "url: ", uri)
return err
}
res := Response{}
err = json.Unmarshal([]byte(resp), &res)
if err != nil {
log.Println(err)
return err
}
if res.Code != 200 {
log.Printf("register err, url is (%v), response code (%v)\n", uri, res.Code)
return errors.New("conflict")
}
return nil
}
func (dis *Discovery) renew(instance *Instance) error {
uri := fmt.Sprintf(_renewURL, dis.pickNode())
log.Println("discovery - request renew url:" + uri)
params := make(map[string]interface{})
params["env"] = dis.conf.Env
params["appid"] = instance.AppId
params["hostname"] = instance.Hostname
resp, err := HttpPost(uri, params)
if err != nil {
dis.switchNode()
log.Println("renew err: ", err, "url: ", uri)
return err
}
res := Response{}
err = json.Unmarshal([]byte(resp), &res)
if err != nil {
log.Println(err)
return err
}
if res.Code != 200 {
log.Printf("uri is (%v), response code (%v)\n", uri, res.Code)
return errors.New("not found")
}
return nil
}
func (dis *Discovery) cancel(instance *Instance) error {
//local cache
uri := fmt.Sprintf(_cancelURL, dis.pickNode())
log.Println("discovery - request cancel url:" + uri)
params := make(map[string]interface{})
params["env"] = dis.conf.Env
params["appid"] = instance.AppId
params["hostname"] = instance.Hostname
resp, err := HttpPost(uri, params)
if err != nil {
dis.switchNode()
log.Println("cancel err: ", err, "url: ", uri)
return err
}
res := Response{}
err = json.Unmarshal([]byte(resp), &res)
if err != nil {
log.Println(err)
return err
}
if res.Code != 200 {
log.Printf("uri is (%v), response code (%v)\n", uri, res.Code)
return err
}
return nil
}
func (dis *Discovery) updateNode() {
ticker := time.NewTicker(NodeInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
uri := fmt.Sprintf(_nodesURL, dis.pickNode())
log.Println("discovery - request and update node, url:" + uri)
params := make(map[string]interface{})
params["env"] = dis.conf.Env
resp, err := HttpPost(uri, params)
if err != nil {
dis.switchNode()
log.Println("update node err: ", err, "url: ", uri)
continue
}
res := ResponseFetch{}
err = json.Unmarshal([]byte(resp), &res)
if err != nil {
log.Println(err)
continue
}
newNodes := []string{}
for _, ins := range res.Data.Instances {
for _, addr := range ins.Addrs {
newNodes = append(newNodes, strings.TrimPrefix(addr, "http://"))
}
}
if len(newNodes) == 0 {
continue
}
curNodes := dis.node.Load().([]string)
if !compareNodes(newNodes, curNodes) {
dis.node.Store(newNodes)
log.Println("nodes list changed!", newNodes)
} else {
log.Println("nodes list not change", curNodes)
}
}
}
}
//有重复串问题
func compareNodes(a, b []string) bool {
if len(a) != len(b) {
return false
}
mapB := make(map[string]struct{}, len(b))
for _, node := range b {
mapB[node] = struct{}{}
}
for _, node := range a {
if _, ok := mapB[node]; !ok {
return false
}
}
return true
}
func (dis *Discovery) pickNode() string {
nodes, ok := dis.node.Load().([]string)
if !ok || len(nodes) == 0 {
return dis.conf.Nodes[dis.idx%uint64(len(dis.conf.Nodes))]
}
return nodes[dis.idx%uint64(len(nodes))]
}
func (dis *Discovery) switchNode() {
atomic.AddUint64(&dis.idx, 1)
}
func (dis *Discovery) Fetch(ctx context.Context, appId string) ([]*Instance, bool) {
//from local
dis.mutex.RLock()
fetchData, ok := dis.apps[appId]
dis.mutex.RUnlock()
if ok {
log.Println("get data from local memory, appid:" + appId)
return fetchData.Instances, ok
}
//from remote
uri := fmt.Sprintf(_fetchURL, dis.pickNode())
params := make(map[string]interface{})
params["env"] = dis.conf.Env
params["appid"] = appId
params["status"] = 1 //up
resp, err := HttpPost(uri, params)
if err != nil {
dis.switchNode()
log.Println("fetch err: ", err, "url: ", uri)
return nil, false
}
res := ResponseFetch{}
err = json.Unmarshal([]byte(resp), &res)
if res.Code != 200 {
log.Println("discovery code is:", res.Code)
return nil, false
}
if err != nil {
log.Println(err)
return nil, false
}
var result []*Instance
for _, ins := range res.Data.Instances {
result = append(result, ins)
}
if len(result) > 0 {
ok = true
dis.mutex.Lock()
dis.apps[appId] = &res.Data
dis.mutex.Unlock()
}
return result, ok
}
func (dis *Discovery) Close() error {
//todo close myself
return nil
}
type Response struct {
Code int `json:"code"`
Message string `json:"message"`
Data json.RawMessage `json:"data"`
}
type FetchData struct {
Instances []*Instance `json:"instances"`
LatestTimestamp int64 `json:"latest_timestamp"`
}
type ResponseFetch struct {
Response
Data FetchData `json:"data"`
}