-
Notifications
You must be signed in to change notification settings - Fork 6
/
endpoint.go
90 lines (79 loc) · 2.09 KB
/
endpoint.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
package eas
import (
"fmt"
"sync"
"time"
)
type Endpoint interface {
Sync()
TryNext(addr string) string
}
type baseEndpoint struct {
lock sync.RWMutex
endpoints map[string]int
scheduler wrrscheduler
}
func newBaseEndpoint() *baseEndpoint {
return &baseEndpoint{
lock: sync.RWMutex{},
endpoints: make(map[string]int),
scheduler: wrrscheduler{inited: false},
}
}
// setEndpoints replaces the local endpoint list, every time we get the response from
// the upstream discovery server, we need to update the endpoint list in local memory.
func (ep *baseEndpoint) setEndpoints(endpoints map[string]int) {
if !ep.changed(endpoints) {
return
}
ep.lock.Lock()
ep.endpoints = endpoints
ep.scheduler = wrrScheduler(ep.endpoints)
ep.lock.Unlock()
}
// get gets an ip address and port using a weight round robin algorithm from endpoint list in local cache.
func (ep *baseEndpoint) get() string {
retryCount := 0
for true {
if ep.scheduler.inited {
break
}
retryCount += 1
if retryCount == 3000 { // 30s timeout
fmt.Printf("Timeout when getting the services' endpoint list from upstream\n")
return ""
}
time.Sleep(10 * time.Millisecond)
}
ep.lock.RLock()
addr := ep.scheduler.getNext()
ep.lock.RUnlock()
return addr
}
// changed checks whether the latest endpoints returned from the upstream discovery server are identically
// equal to the endpoints in local memory cache.
func (ep *baseEndpoint) changed(endpoints map[string]int) bool {
if len(ep.endpoints) != len(endpoints) {
return true
}
for key, val := range endpoints {
if oldVal, exist := ep.endpoints[key]; !exist || oldVal != val {
return true
}
}
return false
}
// TryNext tries to get an new endpoint from the local endpoint list cache, if we get a new endpoint equals
// the last failed one, continue to retry until we find a new endpoint not equals to the last one.
func (ep *baseEndpoint) TryNext(addr string) string {
if len(ep.endpoints) > 1 && len(addr) > 0 {
newAddr := ep.get()
i := 0
for addr == newAddr && i < 100 {
newAddr = ep.get()
i += 1
}
return newAddr
}
return ep.get()
}