-
Notifications
You must be signed in to change notification settings - Fork 1
/
zeromq.go
353 lines (287 loc) · 8.09 KB
/
zeromq.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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
package consistenthashing
import (
"context"
"encoding/json"
"fmt"
"github.com/cenkalti/backoff/v4"
"github.com/pebbe/zmq4"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"io"
"sync/atomic"
"time"
)
type ZeroMqContext struct {
context *zmq4.Context
}
func createZeroMqContext() (*ZeroMqContext, error) {
ctx, err := zmq4.NewContext()
if err != nil {
return nil, err
}
return &ZeroMqContext{ctx}, nil
}
func (c *ZeroMqContext) Close() error {
return c.context.Term()
}
type TcpEndpoint struct {
Name string
port uint16
}
func (e TcpEndpoint) String() string {
return fmt.Sprintf("tcp://%s:%d", e.Name, e.port)
}
type ZeroMqSocket struct {
socket *zmq4.Socket
}
func (s *ZeroMqSocket) bind(port uint16) error {
return s.socket.Bind(TcpEndpoint{Name: "*", port: port}.String())
}
func (s *ZeroMqSocket) connect(endpoint TcpEndpoint) error {
return s.socket.Connect(endpoint.String())
}
func (s *ZeroMqSocket) Close() error {
return s.socket.Close()
}
func readMessage(ctx context.Context, socket *zmq4.Socket) ([]byte, error) {
poller := zmq4.NewPoller()
poller.Add(socket, zmq4.POLLIN)
for {
if ctx.Err() != nil {
return nil, ctx.Err()
}
sockets, err := poller.Poll(1 * time.Second)
if err != nil {
return nil, errors.Wrap(err, "failed to poll consumer socket")
}
if len(sockets) == 0 {
continue
}
return socket.RecvBytes(zmq4.DONTWAIT)
}
}
type ZeroMqReqSocket struct {
*ZeroMqSocket
}
func createZeroMqReqSocket(ctx *ZeroMqContext, identity string) (*ZeroMqReqSocket, error) {
socket, err := ctx.context.NewSocket(zmq4.REQ)
if err != nil {
return nil, err
}
if err = socket.SetIdentity(identity); err != nil {
return nil, err
}
return &ZeroMqReqSocket{&ZeroMqSocket{socket: socket}}, nil
}
func (s *ZeroMqReqSocket) readMessage(ctx context.Context) ([]byte, error) {
if _, err := s.socket.Send("", zmq4.DONTWAIT); err != nil {
return nil, err
}
return readMessage(ctx, s.socket)
}
type ZeroMqPullSocket struct {
*ZeroMqSocket
}
func createZeroMqPullSocket(ctx *ZeroMqContext) (*ZeroMqPullSocket, error) {
socket, err := ctx.context.NewSocket(zmq4.PULL)
if err != nil {
return nil, err
}
return &ZeroMqPullSocket{&ZeroMqSocket{socket: socket}}, nil
}
func (s *ZeroMqPullSocket) readMessage(ctx context.Context) ([]byte, error) {
return readMessage(ctx, s.socket)
}
type ZeroMqPushSocket struct {
*ZeroMqSocket
}
func createZeroMqPushSocket(ctx *ZeroMqContext) (*ZeroMqPushSocket, error) {
socket, err := ctx.context.NewSocket(zmq4.PUSH)
if err != nil {
return nil, err
}
return &ZeroMqPushSocket{&ZeroMqSocket{socket: socket}}, nil
}
func (s *ZeroMqPushSocket) writeMessage(message []byte) error {
_, err := s.socket.SendBytes(message, zmq4.DONTWAIT)
return err
}
type ZeroMqSubSocket struct {
*ZeroMqSocket
}
func createZeroMqSubSocket(ctx *ZeroMqContext, filter string) (*ZeroMqSubSocket, error) {
socket, err := ctx.context.NewSocket(zmq4.SUB)
if err != nil {
return nil, err
}
if err := socket.SetSubscribe(filter); err != nil {
return nil, err
}
return &ZeroMqSubSocket{&ZeroMqSocket{socket: socket}}, nil
}
func (s *ZeroMqSubSocket) readMessage(ctx context.Context) ([]byte, error) {
return readMessage(ctx, s.socket)
}
type ZeroMqPubSocket struct {
*ZeroMqSocket
}
func createZeroMqPubSocket(ctx *ZeroMqContext) (*ZeroMqPubSocket, error) {
socket, err := ctx.context.NewSocket(zmq4.PUB)
if err != nil {
return nil, err
}
return &ZeroMqPubSocket{&ZeroMqSocket{socket: socket}}, nil
}
func (s *ZeroMqPubSocket) writeMessage(message []byte) error {
_, err := s.socket.SendBytes(message, zmq4.DONTWAIT)
return err
}
type ZeroMqRouterSocket struct {
*ZeroMqSocket
}
func createZeroMqRouterSocket(ctx *ZeroMqContext) (*ZeroMqRouterSocket, error) {
socket, err := ctx.context.NewSocket(zmq4.ROUTER)
if err != nil {
return nil, err
}
return &ZeroMqRouterSocket{&ZeroMqSocket{socket: socket}}, nil
}
type consistentHashingLoadBalancer struct {
consumerQueues *consistentHashingQueues
socket *zmq4.Socket
closingChPtr atomic.Value
}
func createConsistentHashingLoadBalancer(socket *ZeroMqRouterSocket) (*consistentHashingLoadBalancer, error) {
res := &consistentHashingLoadBalancer{
consumerQueues: createConsistentHashingQueues(),
socket: socket.socket,
}
go res.startLoadBalancer()
return res, nil
}
func (b *consistentHashingLoadBalancer) Publish(messageId string, message interface{}) error {
if b.closingChPtr.Load() != nil {
return fmt.Errorf("cannot publish after closing")
}
data, err := json.Marshal(message)
if err != nil {
return err
}
return backoff.RetryNotify(
func() error {
return b.consumerQueues.pushMessage(messageId, data)
},
backoff.NewExponentialBackOff(),
func(err error, duration time.Duration) {
log.WithFields(log.Fields{
log.ErrorKey: err,
"messageId": messageId,
"duration": duration},
).Error("failed to push message to queue, waiting")
},
)
}
func (b *consistentHashingLoadBalancer) Close() error {
doneClosing := make(chan interface{})
b.closingChPtr.Store(doneClosing)
log.Info("start closing process, now waiting for consumers")
<-doneClosing
return b.socket.Close()
}
func (b *consistentHashingLoadBalancer) startLoadBalancer() {
waitingConsumers := make([]string, 0)
poller := zmq4.NewPoller()
poller.Add(b.socket, zmq4.POLLIN)
for {
b.registerWaitingConsumer(&waitingConsumers, poller)
consumersWithPendingMessages := b.consumerQueues.getNodesWithPendingMessages()
if len(consumersWithPendingMessages) == 0 {
if consumingCh := b.closingChPtr.Load(); consumingCh != nil {
consumingCh.(chan interface{}) <- true
return
}
continue
}
waitingConsumers = b.sendMessagesToConsumers(waitingConsumers, consumersWithPendingMessages)
}
}
func (b *consistentHashingLoadBalancer) registerWaitingConsumer(waitingConsumers *[]string, poller *zmq4.Poller) {
timeout := time.Duration(-1)
if len(*waitingConsumers) > 0 {
timeout = 1 * time.Second
}
sockets, err := poller.Poll(timeout)
if err != nil {
log.WithError(err).Warning("failed to poll consumer socket")
return
}
if len(sockets) == 0 {
return
}
parts, err := b.socket.RecvMessageBytes(0)
if err != nil {
log.WithError(err).Warning("failed to receive job request")
return
}
consumerId := string(parts[0])
b.consumerQueues.ring.addOrVerify(consumerId)
*waitingConsumers = append(*waitingConsumers, consumerId)
}
func (b *consistentHashingLoadBalancer) sendMessagesToConsumers(waitingConsumers []string, consumersWithPendingMessages map[string]bool) []string {
newWaitingConsumers := make([]string, 0)
for _, consumerId := range waitingConsumers {
if _, ok := consumersWithPendingMessages[consumerId]; !ok {
newWaitingConsumers = append(newWaitingConsumers, consumerId)
continue
}
message := b.consumerQueues.popNodeMessage(consumerId)
if _, err := b.socket.SendMessageDontwait(consumerId, "", message); err != nil {
log.WithError(err).Error("failed to send message")
newWaitingConsumers = append(newWaitingConsumers, consumerId)
}
}
return newWaitingConsumers
}
type WriterSocket interface {
writeMessage(message []byte) error
io.Closer
}
type ZeroMqPublisher struct {
socket WriterSocket
}
func (p *ZeroMqPublisher) Close() error {
return p.socket.Close()
}
func (p *ZeroMqPublisher) Publish(_ string, message interface{}) error {
data, err := json.Marshal(message)
if err != nil {
return err
}
return p.socket.writeMessage(data)
}
type ReaderSocket interface {
readMessage(ctx context.Context) ([]byte, error)
io.Closer
}
type ZeroMqConsumer struct {
socket ReaderSocket
}
func (c *ZeroMqConsumer) Close() error {
return c.socket.Close()
}
func (c *ZeroMqConsumer) Consume(ctx context.Context, incomingMessages chan<- interface{}, newMessagePtr func() interface{}) error {
for {
data, err := c.socket.readMessage(ctx)
if err != nil {
if ctx.Err() != nil {
return nil
}
return errors.Wrap(err, "failed to read message")
}
messagePtr := newMessagePtr()
if err := json.Unmarshal(data, messagePtr); err != nil {
return errors.Wrapf(err, "failed to handle message %v", data)
}
incomingMessages <- messagePtr
}
}