-
-
Notifications
You must be signed in to change notification settings - Fork 396
/
pool.go
334 lines (278 loc) · 7.8 KB
/
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
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
/*
* Copyright (C) 2017 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy ofthe License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specificlanguage governing permissions and
* limitations under the License.
*
*/
package websocket
import (
fmt "fmt"
"math/rand"
"reflect"
"sync"
"sync/atomic"
"github.com/safchain/insanelock"
"github.com/skydive-project/skydive/graffiti/logging"
"github.com/skydive-project/skydive/graffiti/service"
)
// SpeakerPool is the interface that Speaker pools have to implement.
type SpeakerPool interface {
AddClient(c Speaker) error
RemoveClient(c Speaker) bool
AddEventHandler(h SpeakerEventHandler)
GetSpeakers() []Speaker
GetSpeakerByRemoteHost(host string) (Speaker, error)
PickConnectedSpeaker() Speaker
BroadcastMessage(m Message)
SendMessageTo(m Message, host string) error
}
// PoolOpts defines pool options
type PoolOpts struct {
Logger logging.Logger
}
// Pool is a connection container. It embed a list of Speaker.
type Pool struct {
insanelock.RWMutex
name string
wg sync.WaitGroup
running atomic.Value
eventHandlers []SpeakerEventHandler
eventHandlersLock insanelock.RWMutex
speakers []Speaker
opts PoolOpts
}
// ClientPool is a pool of out going Speaker meaning connection to a remote
// Server.
type ClientPool struct {
*Pool
}
// incomerPool is used to store incoming Speaker meaning remote client connected
// to a local Speaker.
type incomerPool struct {
*Pool
}
func (s *Pool) cloneEventHandlers() (handlers []SpeakerEventHandler) {
s.eventHandlersLock.RLock()
handlers = append(handlers, s.eventHandlers...)
s.eventHandlersLock.RUnlock()
return
}
// OnConnected forwards the OnConnected event to event listeners of the pool.
func (s *Pool) OnConnected(c Speaker) error {
var notified []SpeakerEventHandler
for _, h := range s.cloneEventHandlers() {
if err := h.OnConnected(c); err != nil {
for _, h := range notified {
h.OnDisconnected(c)
}
return err
}
notified = append(notified, h)
}
return nil
}
// OnDisconnected forwards the OnDisconnected event to event listeners of the pool.
func (s *Pool) OnDisconnected(c Speaker) {
s.opts.Logger.Debugf("OnDisconnected %s for pool %s ", c.GetRemoteHost(), s.GetName())
for _, h := range s.cloneEventHandlers() {
h.OnDisconnected(c)
}
}
// OnDisconnected forwards the OnDisconnected event to event listeners of the pool.
func (s *incomerPool) OnDisconnected(c Speaker) {
s.Pool.OnDisconnected(c)
s.RemoveClient(c)
}
// AddClient adds the given Speaker to the pool.
func (s *Pool) AddClient(c Speaker) error {
s.opts.Logger.Debugf("AddClient %s for pool %s", c.GetHost(), s.GetName())
s.Lock()
s.speakers = append(s.speakers, c)
s.Unlock()
// This is to call SpeakerPool.On{Message,Disconnected}
c.AddEventHandler(s)
return nil
}
// AddClient adds the given Speaker to the incomerPool.
func (s *incomerPool) AddClient(c Speaker) error {
s.opts.Logger.Debugf("AddClient %s for pool %s", c.GetRemoteHost(), s.GetName())
s.Lock()
s.speakers = append(s.speakers, c)
s.Unlock()
// This is to call SpeakerPool.On{Message,Disconnected}
c.AddEventHandler(s)
return nil
}
// OnMessage forwards the OnMessage event to event listeners of the pool.
func (s *Pool) OnMessage(c Speaker, m Message) {
for _, h := range s.cloneEventHandlers() {
h.OnMessage(c, m)
}
}
// RemoveClient removes client from the pool
func (s *Pool) RemoveClient(c Speaker) bool {
s.Lock()
defer s.Unlock()
host := c.GetRemoteHost()
for i, ic := range s.speakers {
if ic.GetRemoteHost() == host {
s.opts.Logger.Debugf("Successfully removed client %s for pool %s", host, s.GetName())
s.speakers = append(s.speakers[:i], s.speakers[i+1:]...)
return true
}
}
s.opts.Logger.Debugf("Failed to remove client %s for pool %s", host, s.GetName())
return false
}
// GetStatus returns the states of the WebSocket clients
func (s *Pool) GetStatus() map[string]ConnStatus {
clients := make(map[string]ConnStatus)
for _, client := range s.GetSpeakers() {
clients[client.GetRemoteHost()] = client.GetStatus()
}
return clients
}
// GetName returns the name of the pool
func (s *Pool) GetName() string {
return s.name + " type : [" + (reflect.TypeOf(s).String()) + "]"
}
// GetSpeakers returns the Speakers of the pool.
func (s *Pool) GetSpeakers() (speakers []Speaker) {
s.RLock()
speakers = append(speakers, s.speakers...)
s.RUnlock()
return
}
// PickConnectedSpeaker returns randomly a connected Speaker
func (s *Pool) PickConnectedSpeaker() Speaker {
s.RLock()
defer s.RUnlock()
length := len(s.speakers)
if length == 0 {
return nil
}
index := rand.Intn(length)
for i := 0; i != length; i++ {
if c := s.speakers[index]; c != nil && c.IsConnected() {
return c
}
if index+1 >= length {
index = 0
} else {
index++
}
}
return nil
}
// DisconnectAll disconnects all the Speaker
func (s *Pool) DisconnectAll() {
s.eventHandlersLock.Lock()
s.eventHandlers = s.eventHandlers[:0]
s.eventHandlersLock.Unlock()
var wg sync.WaitGroup
s.RLock()
for _, c := range s.speakers {
wg.Add(1)
go func(c Speaker) {
c.StopAndWait()
wg.Done()
}(c)
}
s.RUnlock()
wg.Wait()
}
// GetSpeakersByType returns Speakers matching the given type.
func (s *Pool) GetSpeakersByType(serviceType service.Type) (speakers []Speaker) {
s.RLock()
for _, c := range s.speakers {
if c.GetServiceType() == serviceType {
speakers = append(speakers, c)
}
}
s.RUnlock()
return
}
// GetSpeakerByRemoteHost returns the Speaker for the given remote host.
func (s *Pool) GetSpeakerByRemoteHost(host string) (Speaker, error) {
s.RLock()
defer s.RUnlock()
for _, c := range s.speakers {
if c.GetRemoteHost() == host {
return c, nil
}
}
return nil, fmt.Errorf("No speaker found for host '%s'", host)
}
// SendMessageTo sends message to Speaker for the given remote host.
func (s *Pool) SendMessageTo(m Message, host string) error {
c, err := s.GetSpeakerByRemoteHost(host)
if err != nil {
return err
}
return c.SendMessage(m)
}
// BroadcastMessage broadcasts the given message.
func (s *Pool) BroadcastMessage(m Message) {
s.RLock()
defer s.RUnlock()
for _, c := range s.speakers {
if err := c.SendMessage(m); err != nil {
s.opts.Logger.Errorf("Unable to send message from pool %s to %s: %s", s.name, c.GetRemoteHost(), err)
}
}
}
// AddEventHandler registers a new event handler.
func (s *Pool) AddEventHandler(h SpeakerEventHandler) {
s.eventHandlersLock.Lock()
s.eventHandlers = append(s.eventHandlers, h)
s.eventHandlersLock.Unlock()
}
// Start starts the pool in a goroutine.
func (s *Pool) Start() {
}
// Stop stops the pool and wait until stopped.
func (s *Pool) Stop() {
s.DisconnectAll()
}
// ConnectAll calls connect to all the wSSpeakers of the pool.
func (s *ClientPool) ConnectAll() {
s.RLock()
// shuffle connections to avoid election of the same client as master
indexes := rand.Perm(len(s.speakers))
for _, i := range indexes {
s.speakers[i].Start()
}
s.RUnlock()
}
func newPool(name string, opts PoolOpts) *Pool {
return &Pool{
name: name,
opts: opts,
}
}
func newIncomerPool(name string, opts PoolOpts) *incomerPool {
return &incomerPool{
Pool: newPool(name, opts),
}
}
// NewClientPool returns a new ClientPool meaning a pool of outgoing Client.
func NewClientPool(name string, opts PoolOpts) *ClientPool {
if opts.Logger == nil {
opts.Logger = logging.GetLogger()
}
s := &ClientPool{
Pool: newPool(name, opts),
}
s.Start()
return s
}