-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
283 lines (265 loc) · 7.71 KB
/
client.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
package adaptiveservice
import (
"fmt"
"math/rand"
"sort"
"strings"
"sync"
"time"
)
// Client uses services.
type Client struct {
*conf
providerSelectionMethods []ProviderSelectionMethod
discoverTimeout int // in seconds
deepCopy bool
}
// NewClient creates a client which discovers services.
func NewClient(options ...Option) *Client {
c := &Client{
conf: newConf(),
discoverTimeout: -1,
}
for _, o := range options {
o(c.conf)
}
mTraceHelper.init(c.lg)
c.lg.Debugf("new client created")
return c
}
type providerScoreInfo struct {
addr string
mqi *MsgQInfo
score float32
latency time.Duration
}
func (pi *providerScoreInfo) String() string {
return fmt.Sprintf("providerScoreInfo:{addr: %v msgQinfo: %+v score: %v latency: %v}",
pi.addr, *pi.mqi, pi.score, pi.latency)
}
// Discover discovers the wanted service and returns the connection channel,
// from which user can get one or more connections.
// Each connection represents a connection to one of the service providers
// providing the wanted micro service.
//
// Only one service(identified by publisher name and service name) can exist in
// ScopeProcess and ScopeOS, but in ScopeLAN and ScopeWAN there can be many systems
// providing the same service, each systeam(called provider) has an unique provider ID.
//
// Use providerIDs to select target providers in ScopeLAN or ScopeWAN,
// if no provider id presents, discover searches scopes by distance that is
// in the order of ScopeProcess, ScopeOS, ScopeLAN, ScopeWAN, and returns
// only one connection towards the found service which may have been randomly selected
// if more than one services were found.
//
// If any of publisher or service or provider ids contains "*", discover will return
// all currently available connections of the wanted service(s). Make sure to close
// ALL the connections it returns after use.
func (c *Client) Discover(publisher, service string, providerIDs ...string) <-chan Connection {
connections := make(chan Connection)
has := func(target string) bool {
if len(providerIDs) == 0 { // match all
return true
}
if len(target) == 0 {
return false
}
// str can be wildcard
for _, str := range providerIDs {
if wildcardMatch(str, target) {
return true
}
}
return false
}
expect := 1
if strings.Contains(publisher+service, "*") {
expect = -1
}
if len(providerIDs) != 0 {
expect = len(providerIDs)
if strings.Contains(strings.Join(providerIDs, " "), "*") {
expect = -1
}
if len(c.providerID) == 0 {
providerID, err := discoverProviderID(c.lg)
if err != nil {
providerID = "NA"
}
c.providerID = providerID
}
}
findWithinOS := func() (found int) {
if !has(c.providerID) {
return 0
}
if c.scope&ScopeProcess == ScopeProcess {
c.lg.Debugf("finding %s_%s in ScopeProcess", publisher, service)
ccts := c.lookupServiceChan(publisher, service)
for _, cct := range ccts {
connections <- cct.newConnection()
c.lg.Debugf("channel transport connected")
found++
if found == expect {
return
}
}
}
if c.scope&ScopeOS == ScopeOS {
c.lg.Debugf("finding %s_%s in ScopeOS", publisher, service)
addrs := lookupServiceUDS(publisher, service)
for _, addr := range addrs {
conn, err := c.newUDSConnection(addr)
if err != nil {
c.lg.Errorf("dial " + addr + " failed")
} else {
connections <- conn
c.lg.Debugf("unix domain socket connected to: %s", addr)
found++
if found == expect {
return
}
}
}
}
return
}
findNetwork := func(expect int) (found int) {
connect := func(addrs []string) {
for i := 0; i < len(addrs) && found != expect; i++ {
addr := addrs[i]
conn, err := c.newTCPConnection(addr)
if err != nil {
c.lg.Warnf("dial " + addr + " failed")
} else {
connections <- conn
c.lg.Debugf("tcp socket connected to: %s", addr)
found++
}
}
}
selectAndConnect := func(addrs []string) {
rand.Shuffle(len(addrs), func(i, j int) { addrs[i], addrs[j] = addrs[j], addrs[i] })
if len(c.providerSelectionMethods) != 0 {
providerScoreInfoChan := make(chan *providerScoreInfo, len(addrs))
var wg sync.WaitGroup
for _, addr := range addrs {
wg.Add(1)
go func(addr string) {
defer wg.Done()
conn, err := c.newTCPConnection(addr)
if err != nil {
c.lg.Warnf("dial " + addr + " failed")
return
}
defer conn.Close()
conn.SetRecvTimeout(3 * time.Second)
var mqi MsgQInfo
pinfo := providerScoreInfo{
addr: addr,
mqi: &mqi,
}
ts := time.Now()
for i := 0; i < 4; i++ {
err := conn.SendRecv(QueryMsgQInfo{}, &mqi)
if err != nil {
c.lg.Warnf("%v", err)
return
}
}
pinfo.latency = time.Now().Sub(ts) / 4
if mqi.QueueWeight > 0 {
pinfo.score = float32(mqi.NumCPU) / float32(mqi.QueueLen/mqi.QueueWeight+mqi.ResidentWorkers+mqi.BusyWorkerNum)
} else {
workableCPU := mqi.ResidentWorkers
if workableCPU > mqi.NumCPU {
workableCPU = mqi.NumCPU
}
pinfo.score = 0 - float32(mqi.IdleWorkerNum+workableCPU)/float32(mqi.IdleWorkerNum*workableCPU)
}
providerScoreInfoChan <- &pinfo
}(addr)
}
wg.Wait()
close(providerScoreInfoChan)
c.lg.Debugf("provider msgQ info scaned")
providerScoreInfos := make([]*providerScoreInfo, 0, len(providerScoreInfoChan))
for pinfo := range providerScoreInfoChan {
providerScoreInfos = append(providerScoreInfos, pinfo)
}
sorted := false
for _, method := range c.providerSelectionMethods {
switch method {
case Capacity:
c.lg.Debugf("sort %v by Capacity", providerScoreInfos)
providerScoreInfos := providerScoreInfos
if sorted {
providerScoreInfos = providerScoreInfos[:len(providerScoreInfos)/2]
}
sort.SliceStable(providerScoreInfos, func(i, j int) bool {
return providerScoreInfos[i].score > providerScoreInfos[j].score
})
sorted = true
case Latency:
c.lg.Debugf("sort %v by Latency", providerScoreInfos)
providerScoreInfos := providerScoreInfos
if sorted {
providerScoreInfos = providerScoreInfos[:len(providerScoreInfos)/2]
}
sort.SliceStable(providerScoreInfos, func(i, j int) bool {
return providerScoreInfos[i].latency < providerScoreInfos[j].latency
})
sorted = true
}
}
c.lg.Debugf("sorted providerScoreInfos: %v", providerScoreInfos)
addrs = make([]string, 0, len(addrs))
for _, pinfo := range providerScoreInfos {
addrs = append(addrs, pinfo.addr)
}
}
connect(addrs)
}
if found != expect && c.scope&ScopeLAN == ScopeLAN {
c.lg.Debugf("finding %s_%s in ScopeLAN", publisher, service)
addrs := c.lookupServiceLAN(publisher, service, providerIDs...)
selectAndConnect(addrs)
}
if found != expect && c.scope&ScopeWAN == ScopeWAN {
c.lg.Debugf("finding %s_%s in ScopeWAN", publisher, service)
if len(c.registryAddr) == 0 {
addr, err := discoverRegistryAddr(c.lg)
if err != nil {
addr = "NA"
}
c.registryAddr = addr
c.lg.Debugf("discovered registry address: %s", addr)
}
if c.registryAddr != "NA" {
addrs := c.lookupServiceWAN(publisher, service, providerIDs...)
selectAndConnect(addrs)
}
}
return found
}
go func() {
defer close(connections)
found := 0
timeout := c.discoverTimeout
for found == 0 {
if found += findWithinOS(); found == expect {
break
}
if found += findNetwork(expect - found); found == expect {
break
}
if timeout == 0 {
break
}
c.lg.Debugf("waiting for service: %s_%s", publisher, service)
time.Sleep(time.Second)
timeout--
}
}()
return connections
}