-
Notifications
You must be signed in to change notification settings - Fork 57
/
socket.go
415 lines (360 loc) · 9.19 KB
/
socket.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
// Copyright 2018 The go-zeromq Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package zmq4
import (
"context"
"errors"
"fmt"
"log"
"net"
"os"
"sort"
"strings"
"sync"
"time"
)
const (
defaultRetry = 250 * time.Millisecond
defaultTimeout = 5 * time.Minute
defaultMaxRetries = 10
)
var (
errInvalidAddress = errors.New("zmq4: invalid address")
ErrBadProperty = errors.New("zmq4: bad property")
)
// socket implements the ZeroMQ socket interface
type socket struct {
ep string // socket end-point
typ SocketType
id SocketIdentity
retry time.Duration
maxRetries int
sec Security
log *log.Logger
subTopics func() []string
autoReconnect bool
timeout time.Duration
mu sync.RWMutex
conns []*Conn // ZMTP connections
r rpool
w wpool
props map[string]interface{} // properties of this socket
ctx context.Context // life-line of socket
cancel context.CancelFunc
listener net.Listener
dialer net.Dialer
closedConns []*Conn
reaperCond *sync.Cond
reaperStarted bool
}
func newDefaultSocket(ctx context.Context, sockType SocketType) *socket {
if ctx == nil {
ctx = context.Background()
}
ctx, cancel := context.WithCancel(ctx)
return &socket{
typ: sockType,
retry: defaultRetry,
maxRetries: defaultMaxRetries,
timeout: defaultTimeout,
sec: nullSecurity{},
conns: nil,
r: newQReader(ctx),
w: newMWriter(ctx),
props: make(map[string]interface{}),
ctx: ctx,
cancel: cancel,
dialer: net.Dialer{Timeout: defaultTimeout},
reaperCond: sync.NewCond(&sync.Mutex{}),
}
}
func newSocket(ctx context.Context, sockType SocketType, opts ...Option) *socket {
sck := newDefaultSocket(ctx, sockType)
for _, opt := range opts {
opt(sck)
}
if len(sck.id) == 0 {
sck.id = SocketIdentity(newUUID())
}
if sck.log == nil {
sck.log = log.New(os.Stderr, "zmq4: ", 0)
}
return sck
}
func (sck *socket) topics() []string {
var (
keys = make(map[string]struct{})
topics []string
)
sck.mu.RLock()
for _, con := range sck.conns {
con.mu.RLock()
for topic := range con.topics {
if _, dup := keys[topic]; dup {
continue
}
keys[topic] = struct{}{}
topics = append(topics, topic)
}
con.mu.RUnlock()
}
sck.mu.RUnlock()
sort.Strings(topics)
return topics
}
// Close closes the open Socket
func (sck *socket) Close() error {
// The Lock around Signal ensures the connReaper is running
// and is in sck.reaperCond.Wait()
sck.reaperCond.L.Lock()
sck.cancel()
sck.reaperCond.Signal()
sck.reaperCond.L.Unlock()
if sck.listener != nil {
defer sck.listener.Close()
}
sck.mu.RLock()
defer sck.mu.RUnlock()
var err error
for _, conn := range sck.conns {
e := conn.Close()
if e != nil && err == nil {
err = e
}
}
// Remove the unix socket file if created by net.Listen
if sck.listener != nil && strings.HasPrefix(sck.ep, "ipc://") {
os.Remove(sck.ep[len("ipc://"):])
}
return err
}
// Send puts the message on the outbound send queue.
// Send blocks until the message can be queued or the send deadline expires.
func (sck *socket) Send(msg Msg) error {
ctx, cancel := context.WithTimeout(sck.ctx, sck.Timeout())
defer cancel()
return sck.w.write(ctx, msg)
}
// SendMulti puts the message on the outbound send queue.
// SendMulti blocks until the message can be queued or the send deadline expires.
// The message will be sent as a multipart message.
func (sck *socket) SendMulti(msg Msg) error {
msg.multipart = true
ctx, cancel := context.WithTimeout(sck.ctx, sck.Timeout())
defer cancel()
return sck.w.write(ctx, msg)
}
// Recv receives a complete message.
func (sck *socket) Recv() (Msg, error) {
ctx, cancel := context.WithCancel(sck.ctx)
defer cancel()
var msg Msg
err := sck.r.read(ctx, &msg)
return msg, err
}
// Listen connects a local endpoint to the Socket.
func (sck *socket) Listen(endpoint string) error {
sck.ep = endpoint
network, addr, err := splitAddr(endpoint)
if err != nil {
return err
}
trans, ok := drivers.get(network)
if !ok {
return UnknownTransportError{Name: network}
}
l, err := trans.Listen(sck.ctx, addr)
if err != nil {
return fmt.Errorf("zmq4: could not listen to %q: %w", endpoint, err)
}
sck.listener = l
go sck.accept()
if !sck.reaperStarted {
sck.reaperCond.L.Lock()
go sck.connReaper()
sck.reaperStarted = true
}
return nil
}
func (sck *socket) accept() {
ctx, cancel := context.WithCancel(sck.ctx)
defer cancel()
for {
select {
case <-ctx.Done():
return
default:
conn, err := sck.listener.Accept()
if err != nil {
// FIXME(sbinet): maybe bubble up this error to application code?
//sck.log.Printf("error accepting connection from %q: %+v", sck.ep, err)
continue
}
zconn, err := Open(conn, sck.sec, sck.typ, sck.id, true, sck.scheduleRmConn)
if err != nil {
// FIXME(sbinet): maybe bubble up this error to application code?
sck.log.Printf("could not open a ZMTP connection with %q: %+v", sck.ep, err)
continue
}
sck.addConn(zconn)
}
}
}
// Dial connects a remote endpoint to the Socket.
func (sck *socket) Dial(endpoint string) error {
sck.ep = endpoint
network, addr, err := splitAddr(endpoint)
if err != nil {
return err
}
var (
conn net.Conn
trans, ok = drivers.get(network)
retries = 0
)
if !ok {
return UnknownTransportError{Name: network}
}
connect:
conn, err = trans.Dial(sck.ctx, &sck.dialer, addr)
if err != nil {
// retry if retry count is lower than maximum retry count and context has not been canceled
if (sck.maxRetries == -1 || retries < sck.maxRetries) && sck.ctx.Err() == nil {
retries++
time.Sleep(sck.retry)
goto connect
}
return fmt.Errorf("zmq4: could not dial to %q (retry=%v): %w", endpoint, sck.retry, err)
}
if conn == nil {
return fmt.Errorf("zmq4: got a nil dial-conn to %q", endpoint)
}
zconn, err := Open(conn, sck.sec, sck.typ, sck.id, false, sck.scheduleRmConn)
if err != nil {
return fmt.Errorf("zmq4: could not open a ZMTP connection: %w", err)
}
if zconn == nil {
return fmt.Errorf("zmq4: got a nil ZMTP connection to %q", endpoint)
}
if !sck.reaperStarted {
sck.reaperCond.L.Lock()
go sck.connReaper()
sck.reaperStarted = true
}
sck.addConn(zconn)
return nil
}
func (sck *socket) addConn(c *Conn) {
sck.mu.Lock()
defer sck.mu.Unlock()
sck.conns = append(sck.conns, c)
if len(c.Peer.Meta[sysSockID]) == 0 {
switch c.typ {
case Router: // TODO: STREAM type when implemented
// if empty Identity metadata is received from some client
// need to assign an uuid such that router socket can reply to the correct client
c.Peer.Meta[sysSockID] = newUUID()
}
}
if sck.w != nil {
sck.w.addConn(c)
}
if sck.r != nil {
sck.r.addConn(c)
}
// resend subscriptions for topics if there are any
if sck.subTopics != nil {
for _, topic := range sck.subTopics() {
_ = sck.Send(NewMsg(append([]byte{1}, topic...)))
}
}
}
func (sck *socket) rmConn(c *Conn) {
sck.mu.Lock()
defer sck.mu.Unlock()
cur := -1
for i := range sck.conns {
if sck.conns[i] == c {
cur = i
break
}
}
if cur == -1 {
return
}
sck.conns = append(sck.conns[:cur], sck.conns[cur+1:]...)
if sck.r != nil {
sck.r.rmConn(c)
}
if sck.w != nil {
sck.w.rmConn(c)
}
}
func (sck *socket) scheduleRmConn(c *Conn) {
sck.reaperCond.L.Lock()
sck.closedConns = append(sck.closedConns, c)
sck.reaperCond.Signal()
sck.reaperCond.L.Unlock()
if sck.autoReconnect {
sck.Dial(sck.ep)
}
}
// Type returns the type of this Socket (PUB, SUB, ...)
func (sck *socket) Type() SocketType {
return sck.typ
}
// Addr returns the listener's address.
// Addr returns nil if the socket isn't a listener.
func (sck *socket) Addr() net.Addr {
if sck.listener == nil {
return nil
}
return sck.listener.Addr()
}
// GetOption is used to retrieve an option for a socket.
func (sck *socket) GetOption(name string) (interface{}, error) {
v, ok := sck.props[name]
if !ok {
return nil, ErrBadProperty
}
return v, nil
}
// SetOption is used to set an option for a socket.
func (sck *socket) SetOption(name string, value interface{}) error {
// FIXME(sbinet) different socket types support different options.
sck.props[name] = value
return nil
}
func (sck *socket) Timeout() time.Duration {
return sck.timeout
}
func (sck *socket) connReaper() {
// We are not locking here sck.reaperCond.L.Lock()
// as it should be locked prior starting connReaper as goroutine
// That would ensure that sck.reaperCond.Signal()
// would be delivered only when reaper goroutine is really started
// and is in sck.reaperCond.Wait()
defer sck.reaperCond.L.Unlock()
for {
for len(sck.closedConns) == 0 && sck.ctx.Err() == nil {
sck.reaperCond.Wait()
}
if sck.ctx.Err() != nil {
return
}
// Clone the known closed connections to avoid data race
// and remove those under reaper unlocked.
// That should fix the deadlock reported in #149.
cc := append([]*Conn{}, sck.closedConns...) // clone
sck.closedConns = sck.closedConns[:0]
sck.reaperCond.L.Unlock()
for _, c := range cc {
sck.rmConn(c)
}
sck.reaperCond.L.Lock()
}
}
var (
_ Socket = (*socket)(nil)
)