-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathservices_pool.go
285 lines (225 loc) · 6.99 KB
/
services_pool.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
package pool
import (
"fmt"
"time"
"github.com/gateway-fm/scriptorium/logger"
"github.com/gateway-fm/service-pool/discovery"
"github.com/gateway-fm/service-pool/service"
)
// IServicesPool holds information about reachable
// active services, manage connections and discovery
type IServicesPool interface {
// Start run service pool discovering
// and healthchecks loops
Start(healthchecks bool)
// DiscoverServices discover all visible active
// services via service-discovery
DiscoverServices() error
// NextService returns next active service
// to take a connection
NextService() service.IService
// Count return numbers of
// all healthy services in pool
Count() int
// List return ServicesPool ServicesList instance
List() IServicesList
// Close Stop all service pool
Close()
SetOnNewDiscCallback(f ServiceCallbackE)
SetOnDiscRemoveCallback(f ServiceCallback)
SetOnDiscCompletedCallback(f func())
SetMutationNeededCallback(f ServiceCallbackB)
}
// ServicesPool holds information about reachable
// active services, manage connections and discovery
type ServicesPool struct {
// TODO maybe is better to change this field to func
discovery discovery.IServiceDiscovery
discoveryInterval time.Duration
name string
list IServicesList
stop chan struct{}
MutationFnc func(srv service.IService) (service.IService, error)
onNewDiscCallback ServiceCallbackE
onDiscRemoveCallback ServiceCallback
onDiscCompletedCallback func()
mutationNeededCallback ServiceCallbackB
}
// ServicesPoolsOpts is options that needs
// to configure ServicePool instance
type ServicesPoolsOpts struct {
Name string // service name to use in service pool
Discovery discovery.IServiceDiscovery // discovery interface
DiscoveryInterval time.Duration // reconnection interval for unreachable active rediscovery
ListOpts *ServicesListOpts // service list configuration
MutationFnc func(srv service.IService) (service.IService, error)
CustomList IServicesList
}
type ServiceCallbackE func(srv service.IService) error
type ServiceCallback func(srv service.IService)
type ServiceCallbackB func(srv service.IService) bool
// NewServicesPool create new Services Pool
// based on given params
func NewServicesPool(opts *ServicesPoolsOpts) IServicesPool {
pool := &ServicesPool{
discovery: opts.Discovery,
discoveryInterval: opts.DiscoveryInterval,
name: opts.Name,
stop: make(chan struct{}),
MutationFnc: opts.MutationFnc,
}
if opts.CustomList != nil {
pool.list = opts.CustomList
} else {
pool.list = NewServicesList(opts.Name, opts.ListOpts)
}
return pool
}
// Start run service pool discovering
// and healthchecks loops
func (p *ServicesPool) Start(healthchecks bool) {
go p.discoverServicesLoop()
if healthchecks {
go p.list.HealthChecksLoop()
}
}
// DiscoverServices discover all visible active
// services via service-discovery
func (p *ServicesPool) DiscoverServices() error {
newServices, err := p.discovery.Discover(p.name)
if err != nil {
return fmt.Errorf("error discovering %s active: %w", p.name, err)
}
// construct map of newly discovered IDs
// time complexity is O(len(newServices))
newlyDiscoveredIDs := make(map[string]struct{})
for _, newService := range newServices {
newlyDiscoveredIDs[newService.ID()] = struct{}{}
}
// for every health service check whether it was discovered lastly
// if not -- remove it from healthy
// time complexity is O(len(healthy)) + O(1)
for index, srv := range p.list.Healthy() {
if _, wasDiscovered := newlyDiscoveredIDs[srv.ID()]; !wasDiscovered {
p.list.RemoveFromHealthyByIndex(index)
if p.onDiscRemoveCallback != nil {
p.onDiscRemoveCallback(srv)
}
break
}
}
// for every jailed service check whether it was discovered lastly
// if not -- remove it from jailed
// time complexity is O(len(jailed)) + O(1)
for srvID, srv := range p.list.Jailed() {
if _, wasDiscovered := newlyDiscoveredIDs[srvID]; !wasDiscovered {
p.list.RemoveFromJail(srv)
if p.onDiscRemoveCallback != nil {
p.onDiscRemoveCallback(srv)
}
break
}
}
// the total complexity looks like O(n), but not O(n^2) :D
// TODO for the best scaling we need to change this part to map-based compare mechanic
for _, newService := range newServices {
if newService == nil {
logger.Log().Warn("newService is nil during discovery")
continue
}
// if service doesn't exist in pool or if the callback returns true --
// then we do a mutation.
// otherwise we prefer not to mutate srv to prevent spawning unnecessary goroutines
isServiceExists := p.list.IsServiceExists(newService)
weNeedToMutate := !isServiceExists || (p.mutationNeededCallback != nil && p.mutationNeededCallback(newService))
var mutatedService service.IService
if weNeedToMutate {
mutatedService, err = p.MutationFnc(newService)
if err != nil {
logger.Log().Warn(fmt.Sprintf("mutate new discovered service: %s", err))
continue
}
if p.onNewDiscCallback != nil {
if err := p.onNewDiscCallback(mutatedService); err != nil {
logger.Log().Warn(fmt.Sprintf("callback on new discovered service: %s", err))
}
}
}
if isServiceExists {
continue
}
p.list.Add(mutatedService)
}
return nil
}
// NextService returns next active service
// to take a connection
func (p *ServicesPool) NextService() service.IService {
// TODO maybe is better to return error if next service is nill
return p.list.Next()
}
// Count return numbers of
// all healthy services in pool
func (p *ServicesPool) Count() int {
return len(p.list.Healthy())
}
// List return ServicesPool ServicesList instance
func (p *ServicesPool) List() IServicesList {
return p.list
}
// Close Stop all service pool
func (p *ServicesPool) Close() {
p.list.Close()
close(p.stop)
}
func (p *ServicesPool) SetOnNewDiscCallback(f ServiceCallbackE) {
if p == nil {
return
}
p.onNewDiscCallback = f
}
func (p *ServicesPool) SetOnDiscCompletedCallback(f func()) {
if p == nil {
return
}
p.onDiscCompletedCallback = f
}
func (p *ServicesPool) SetOnDiscRemoveCallback(f ServiceCallback) {
if p == nil {
return
}
p.onDiscRemoveCallback = f
}
func (p *ServicesPool) SetMutationNeededCallback(f ServiceCallbackB) {
if p == nil {
return
}
p.mutationNeededCallback = f
}
// discoverServicesLoop spawn discovery for
// services periodically
func (p *ServicesPool) discoverServicesLoop() {
logger.Log().Info("start discovery loop")
onceShuffled := false
for {
select {
case <-p.stop:
logger.Log().Warn("Stop discovery loop")
return
default:
if err := p.DiscoverServices(); err != nil {
logger.Log().Warn(fmt.Errorf("error discovery services: %w", err).Error())
}
// sync.Once won't work in cases when we call Start() then Close()
// and then Start() again
if !onceShuffled {
p.list.Shuffle()
onceShuffled = true
if p.onDiscCompletedCallback != nil {
p.onDiscCompletedCallback()
}
}
Sleep(p.discoveryInterval, p.stop)
}
}
}