-
Notifications
You must be signed in to change notification settings - Fork 95
/
sock.go
471 lines (406 loc) · 11.7 KB
/
sock.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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
package goczmq
/*
#include "czmq.h"
#include <stdlib.h>
#include <string.h>
int Sock_connect(zsock_t *self, const char *format) {return zsock_connect(self, format, NULL);}
int Sock_disconnect(zsock_t *self, const char *format) {return zsock_disconnect(self, format, NULL);}
int Sock_bind(zsock_t *self, const char *format) {return zsock_bind(self, format, NULL);}
int Sock_unbind(zsock_t *self, const char *format) {return zsock_unbind(self, format, NULL);}
int Sock_sendframe(zsock_t *sock, const void *data, size_t size, int flags) {
zframe_t *frame = zframe_new (data, size);
int rc = zframe_send (&frame, sock, flags);
return rc;
}
*/
import "C"
import (
"fmt"
"os"
"runtime"
"strings"
"unsafe"
)
// Sock wraps the CZMQ zsock class.
type Sock struct {
zsockT *C.struct__zsock_t
file string
line int
zType int
clientIDs []string
}
func init() {
if err := os.Setenv("ZSYS_SIGHANDLER", "false"); err != nil {
fmt.Fprintf(os.Stderr, "Failed to set environment variable ZSYS_SIGHANDLER: %s\n", err.Error())
}
}
// GetLastClientID returns the id of the last client you received
// a message from if the underlying socket is a Router socket
// DEPRECATED: See goczmq.ReadWriter
func (s *Sock) GetLastClientID() []byte {
id := []byte(s.clientIDs[0])
s.clientIDs = s.clientIDs[1:]
return id
}
// SetLastClientID lets you manually set the id of the client
// you last received a message from if the underlying socket
// is a Router socket
// DEPRECATED: See goczmq.ReadWriter
func (s *Sock) SetLastClientID(id []byte) {
s.clientIDs = append(s.clientIDs, string(id))
}
// NewSock creates a new socket. The caller source and
// line number are passed so CZMQ can report socket leaks
// intelligently.
func NewSock(t int, options ...SockOption) *Sock {
var s *Sock
_, file, line, ok := runtime.Caller(1)
if ok {
s = &Sock{
file: file,
line: line,
zType: t,
clientIDs: make([]string, 0),
}
} else {
s = &Sock{
file: "",
line: 0,
zType: t,
clientIDs: make([]string, 0),
}
}
cFile := C.CString(s.file)
defer C.free(unsafe.Pointer(cFile))
s.zsockT = C.zsock_new_checked(C.int(s.zType), cFile, C.size_t(s.line))
for _, o := range options {
o(s)
}
return s
}
// SockOption is a type for setting options on the underlying ZeroMQ socket
type SockOption func(*Sock)
// SetOption accepts a SockOption and uses it to set an option on
// the underlying ZeroMQ socket
func (s *Sock) SetOption(o SockOption) {
o(s)
}
// Connect connects a socket to an endpoint
// returns an error if the connect failed.
func (s *Sock) Connect(endpoint string) error {
cEndpoint := C.CString(endpoint)
defer C.free(unsafe.Pointer(cEndpoint))
Connect:
rc, err := C.Sock_connect(s.zsockT, cEndpoint)
if rc != C.int(0) {
if isRetryableError(err) {
goto Connect
}
return ErrConnect
}
return nil
}
// Disconnect disconnects a socket from an endpoint. If returns
// an error if the endpoint was not found
func (s *Sock) Disconnect(endpoint string) error {
cEndpoint := C.CString(endpoint)
defer C.free(unsafe.Pointer(cEndpoint))
rc := C.Sock_disconnect(s.zsockT, cEndpoint)
if int(rc) == -1 {
return ErrDisconnect
}
return nil
}
// Bind binds a socket to an endpoint. On success returns
// the port number used for tcp transports, or 0 for other
// transports. On failure returns a -1 for port, and an error.
func (s *Sock) Bind(endpoint string) (int, error) {
cEndpoint := C.CString(endpoint)
defer C.free(unsafe.Pointer(cEndpoint))
port := C.Sock_bind(s.zsockT, cEndpoint)
if port == C.int(-1) {
return -1, ErrBind
}
return int(port), nil
}
// Unbind unbinds a socket from an endpoint. If returns
// an error if the endpoint was not found
func (s *Sock) Unbind(endpoint string) error {
cEndpoint := C.CString(endpoint)
defer C.free(unsafe.Pointer(cEndpoint))
rc := C.Sock_unbind(s.zsockT, cEndpoint)
if int(rc) == -1 {
return ErrUnbind
}
return nil
}
// Attach attaches a socket to zero or more endpoints. If endpoints is not null,
// parses as list of ZeroMQ endpoints, separated by commas, and prefixed by
// '@' (to bind the socket) or '>' (to attach the socket). If the endpoint
// does not start with '@' or '>', the serverish argument determines whether
// it is used to bind (serverish = true) or connect (serverish = false)
func (s *Sock) Attach(endpoints string, serverish bool) error {
if endpoints == "" {
return ErrSockAttachEmptyEndpoints
}
cEndpoints := C.CString(endpoints)
defer C.free(unsafe.Pointer(cEndpoints))
rc := C.zsock_attach(s.zsockT, cEndpoints, C._Bool(serverish))
if rc == -1 {
return ErrSockAttach
}
return nil
}
// NewPub creates a Pub socket and calls Attach.
// The socket will Bind by default.
func NewPub(endpoints string, options ...SockOption) (*Sock, error) {
s := NewSock(Pub, options...)
return s, s.Attach(endpoints, true)
}
// NewSub creates a Sub socket and calls Attach.
// 'subscribe' is a comma delimited list of topics to subscribe to.
// The socket will Connect by default.
func NewSub(endpoints string, subscribe string, options ...SockOption) (*Sock, error) {
s := NewSock(Sub)
subscriptions := strings.Split(subscribe, ",")
for _, topic := range subscriptions {
s.SetOption(SockSetSubscribe(topic))
}
for _, option := range options {
s.SetOption(option)
}
return s, s.Attach(endpoints, false)
}
// NewRep creates a Rep socket and calls Attach.
// The socket will Bind by default.
func NewRep(endpoints string, options ...SockOption) (*Sock, error) {
s := NewSock(Rep)
return s, s.Attach(endpoints, true)
}
// NewReq creates a Req socket and calls Attach.
// The socket will Connect by default.
func NewReq(endpoints string, options ...SockOption) (*Sock, error) {
s := NewSock(Req)
return s, s.Attach(endpoints, false)
}
// NewPull creates a Pull socket and calls Attach.
// The socket will Bind by default.
func NewPull(endpoints string, options ...SockOption) (*Sock, error) {
s := NewSock(Pull)
return s, s.Attach(endpoints, true)
}
// NewPush creates a Push socket and calls Attach.
// The socket will Connect by default.
func NewPush(endpoints string, options ...SockOption) (*Sock, error) {
s := NewSock(Push)
return s, s.Attach(endpoints, false)
}
// NewRouter creates a Router socket and calls Attach.
// The socket will Bind by default.
func NewRouter(endpoints string, options ...SockOption) (*Sock, error) {
s := NewSock(Router)
return s, s.Attach(endpoints, true)
}
// NewDealer creates a Dealer socket and calls Attach.
// The socket will Connect by default.
func NewDealer(endpoints string, options ...SockOption) (*Sock, error) {
s := NewSock(Dealer)
return s, s.Attach(endpoints, false)
}
// NewXPub creates an XPub socket and calls Attach.
// The socket will Bind by default.
func NewXPub(endpoints string, options ...SockOption) (*Sock, error) {
s := NewSock(XPub)
return s, s.Attach(endpoints, true)
}
// NewXSub creates an XSub socket and calls Attach.
// The socket will Connect by default.
func NewXSub(endpoints string, options ...SockOption) (*Sock, error) {
s := NewSock(XSub)
return s, s.Attach(endpoints, false)
}
// NewPair creates a Pair socket and calls Attach.
// The socket will Connect by default.
func NewPair(endpoints string, options ...SockOption) (*Sock, error) {
s := NewSock(Pair)
return s, s.Attach(endpoints, false)
}
// NewStream creates a Stream socket and calls Attach.
// The socket will Connect by default.
func NewStream(endpoints string, options ...SockOption) (*Sock, error) {
s := NewSock(Stream)
return s, s.Attach(endpoints, false)
}
// Pollin returns true if there is a Pollin
// event on the socket
func (s *Sock) Pollin() bool {
return Events(s)&Pollin == Pollin
}
// Pollout returns true if there is a Pollout
// event on the socket
func (s *Sock) Pollout() bool {
return Events(s)&Pollout == Pollout
}
// SendFrame sends a byte array via the socket. For the flags
// value, use FlagNone (0) for a single message, or FlagMore if it is
// a multi-part message
func (s *Sock) SendFrame(data []byte, flags int) error {
var rc C.int
var err error
SendFrame:
if len(data) == 0 {
rc, err = C.Sock_sendframe(s.zsockT, nil, C.size_t(0), C.int(flags))
} else {
rc, err = C.Sock_sendframe(s.zsockT, unsafe.Pointer(&data[0]), C.size_t(len(data)), C.int(flags))
}
if rc == C.int(-1) {
if isRetryableError(err) {
goto SendFrame
}
return err
}
return nil
}
// RecvFrame reads a frame from the socket and returns it
// as a byte array, along with a more flag and and error
// (if there is an error)
func (s *Sock) RecvFrame() ([]byte, int, error) {
if s.zsockT == nil {
return nil, -1, ErrRecvFrameAfterDestroy
}
RecvFrame:
frame, err := C.zframe_recv(unsafe.Pointer(s.zsockT))
if frame == nil {
if isRetryableError(err) {
goto RecvFrame
}
return []byte{0}, 0, ErrRecvFrame
}
dataSize := C.zframe_size(frame)
dataPtr := C.zframe_data(frame)
b := C.GoBytes(unsafe.Pointer(dataPtr), C.int(dataSize))
more := C.zframe_more(frame)
C.zframe_destroy(&frame)
return b, int(more), nil
}
// RecvFrameNoWait receives a frame from the socket
// and returns it as a byte array if one is waiting.
// Returns an empty frame, a 0 more flag and an error
// if one is not immediately available
func (s *Sock) RecvFrameNoWait() ([]byte, int, error) {
if !s.Pollin() {
return []byte{0}, 0, ErrRecvFrame
}
return s.RecvFrame()
}
// SendMessage accepts an array of byte arrays and
// sends it as a multi-part message.
func (s *Sock) SendMessage(parts [][]byte) error {
var f int
numParts := len(parts)
for i, val := range parts {
if i == numParts-1 {
f = 0
} else {
f = FlagMore
}
err := s.SendFrame(val, f)
if err != nil {
return err
}
}
return nil
}
// RecvMessage receives a full message from the socket
// and returns it as an array of byte arrays.
func (s *Sock) RecvMessage() ([][]byte, error) {
var msg [][]byte
for {
frame, flag, err := s.RecvFrame()
if err != nil {
return msg, err
}
msg = append(msg, frame)
if flag != FlagMore {
break
}
}
return msg, nil
}
// Read provides an io.Reader interface to a zeromq socket
// DEPRECATED: see goczmq.ReadWriter
func (s *Sock) Read(p []byte) (int, error) {
var totalRead int
var totalFrame int
frame, flag, err := s.RecvFrame()
if err != nil {
return totalRead, err
}
if s.GetType() == Router {
s.clientIDs = append(s.clientIDs, string(frame))
} else {
totalRead += copy(p[:], frame[:])
totalFrame += len(frame)
}
for flag == FlagMore {
frame, flag, err = s.RecvFrame()
if err != nil {
return totalRead, err
}
totalRead += copy(p[totalRead:], frame[:])
totalFrame += len(frame)
}
if totalFrame > len(p) {
err = ErrSliceFull
} else {
err = nil
}
return totalRead, err
}
// Write provides an io.Writer interface to a zeromq socket
// DEPRECATED: See goczmq.ReadWriter
func (s *Sock) Write(p []byte) (int, error) {
var total int
if s.GetType() == Router {
err := s.SendFrame(s.GetLastClientID(), FlagMore)
if err != nil {
return total, err
}
}
err := s.SendFrame(p, 0)
if err != nil {
return total, err
}
return len(p), nil
}
// RecvMessageNoWait receives a full message from the socket
// and returns it as an array of byte arrays if one is waiting.
// Returns an empty message and an error if one is not immediately
// available
func (s *Sock) RecvMessageNoWait() ([][]byte, error) {
var msg [][]byte
if !s.Pollin() {
return msg, ErrRecvMessage
}
for {
frame, flag, err := s.RecvFrame()
if err != nil {
return msg, err
}
msg = append(msg, frame)
if flag != FlagMore {
break
}
}
return msg, nil
}
// GetType returns the socket's type
func (s *Sock) GetType() int {
return s.zType
}
// Destroy destroys the underlying zsockT.
func (s *Sock) Destroy() {
cFile := C.CString(s.file)
defer C.free(unsafe.Pointer(cFile))
C.zsock_destroy_checked(&s.zsockT, cFile, C.size_t(s.line))
}