-
Notifications
You must be signed in to change notification settings - Fork 665
Expand file tree
/
Copy path_zmq.py
More file actions
2053 lines (1758 loc) · 61.1 KB
/
_zmq.py
File metadata and controls
2053 lines (1758 loc) · 61.1 KB
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# cython: language_level = 3str
# cython: freethreading_compatible = True
# cython: subinterpreters_compatible = own_gil
"""Cython backend for pyzmq"""
# Copyright (C) PyZMQ Developers
# Distributed under the terms of the Modified BSD License.
from __future__ import annotations
try:
import cython
if not cython.compiled:
raise ImportError()
except ImportError:
from pathlib import Path
zmq_root = Path(__file__).parents[3]
msg = f"""
Attempting to import zmq Cython backend, which has not been compiled.
This probably means you are importing zmq from its source tree.
if this is what you want, make sure to do an in-place build first:
pip install -e '{zmq_root}'
If it is not, then '{zmq_root}' is probably on your sys.path,
when it shouldn't be. Is that your current working directory?
If neither of those is true and this file is actually installed,
something seems to have gone wrong with the install!
Please report at https://github.com/zeromq/pyzmq/issues
"""
raise ImportError(msg)
import warnings
from threading import Event
from time import monotonic
from weakref import ref
import cython as C
from cython import (
NULL,
Py_ssize_t,
address,
bint,
cast,
cclass,
cfunc,
char,
declare,
exceptval,
inline,
nogil,
p_char,
p_void,
pointer,
size_t,
sizeof,
)
from cython.cimports.cpython.buffer import (
Py_buffer,
PyBUF_ANY_CONTIGUOUS,
PyBUF_WRITABLE,
PyBuffer_Release,
PyObject_GetBuffer,
)
from cython.cimports.cpython.bytes import (
PyBytes_AsString,
PyBytes_FromStringAndSize,
PyBytes_Size,
)
from cython.cimports.cpython.exc import PyErr_CheckSignals
from cython.cimports.libc.errno import EAGAIN, EINTR, ENAMETOOLONG, ENOENT, ENOTSOCK
from cython.cimports.libc.stdint import uint32_t
from cython.cimports.libc.stdio import fprintf
from cython.cimports.libc.stdio import stderr as cstderr
from cython.cimports.libc.stdlib import free, malloc
from cython.cimports.libc.string import memcpy
from cython.cimports.zmq.backend.cython import libzmq
from cython.cimports.zmq.backend.cython._externs import (
get_ipc_path_max_len,
getpid,
mutex_allocate,
mutex_lock,
mutex_t,
mutex_unlock,
)
from cython.cimports.zmq.backend.cython.libzmq import (
ZMQ_ENOTSOCK,
ZMQ_ETERM,
ZMQ_EVENT_ALL,
ZMQ_FD,
ZMQ_IDENTITY,
ZMQ_IO_THREADS,
ZMQ_LINGER,
ZMQ_POLLIN,
ZMQ_POLLOUT,
ZMQ_RCVMORE,
ZMQ_ROUTER,
ZMQ_SNDMORE,
ZMQ_THREAD_SAFE,
ZMQ_TYPE,
_zmq_version,
fd_t,
int64_t,
zmq_bind,
zmq_close,
zmq_connect,
zmq_ctx_destroy,
zmq_ctx_get,
zmq_ctx_new,
zmq_ctx_set,
zmq_curve_keypair,
zmq_curve_public,
zmq_disconnect,
zmq_free_fn,
zmq_getsockopt,
zmq_has,
zmq_join,
zmq_leave,
zmq_msg_close,
zmq_msg_copy,
zmq_msg_data,
zmq_msg_get,
zmq_msg_gets,
zmq_msg_group,
zmq_msg_init,
zmq_msg_init_data,
zmq_msg_init_size,
zmq_msg_recv,
zmq_msg_routing_id,
zmq_msg_send,
zmq_msg_set,
zmq_msg_set_group,
zmq_msg_set_routing_id,
zmq_msg_size,
zmq_msg_t,
zmq_poller_add,
zmq_poller_destroy,
zmq_poller_fd,
zmq_poller_new,
zmq_pollitem_t,
zmq_proxy,
zmq_proxy_steerable,
zmq_recv,
zmq_setsockopt,
zmq_socket,
zmq_socket_monitor,
zmq_strerror,
zmq_unbind,
)
from cython.cimports.zmq.backend.cython.libzmq import zmq_errno as _zmq_errno
from cython.cimports.zmq.backend.cython.libzmq import zmq_poll as zmq_poll_c
import zmq
from zmq.constants import SocketOption, _OptType
from zmq.error import (
Again,
ContextTerminated,
InterruptedSystemCall,
ZMQError,
_check_version,
)
IPC_PATH_MAX_LEN: int = get_ipc_path_max_len()
PYZMQ_DRAFT_API: bool = bool(libzmq.PYZMQ_DRAFT_API)
@cfunc
@inline
@exceptval(-1)
def _check_rc(rc: C.int, error_without_errno: bint = False) -> C.int:
"""internal utility for checking zmq return condition
and raising the appropriate Exception class
"""
errno: C.int = _zmq_errno()
PyErr_CheckSignals()
if errno == 0 and not error_without_errno:
return 0
if rc == -1: # if rc < -1, it's a bug in libzmq. Should we warn?
if errno == EINTR:
raise InterruptedSystemCall(errno)
elif errno == EAGAIN:
raise Again(errno)
elif errno == ZMQ_ETERM:
raise ContextTerminated(errno)
else:
raise ZMQError(errno)
return 0
# message Frame class
_zhint = C.struct(
sock=p_void,
mutex=pointer(mutex_t),
id=size_t,
)
@cfunc
@nogil
def free_python_msg(data: p_void, vhint: p_void) -> C.int:
"""A pure-C function for DECREF'ing Python-owned message data.
Sends a message on a PUSH socket
The hint is a `zhint` struct with two values:
sock (void *): pointer to the Garbage Collector's PUSH socket
id (size_t): the id to be used to construct a zmq_msg_t that should be sent on a PUSH socket,
signaling the Garbage Collector to remove its reference to the object.
When the Garbage Collector's PULL socket receives the message,
it deletes its reference to the object,
allowing Python to free the memory.
"""
msg = declare(zmq_msg_t)
msg_ptr: pointer(zmq_msg_t) = address(msg)
hint: pointer(_zhint) = cast(pointer(_zhint), vhint)
rc: C.int
if hint != NULL:
zmq_msg_init_size(msg_ptr, sizeof(size_t))
memcpy(zmq_msg_data(msg_ptr), address(hint.id), sizeof(size_t))
rc = mutex_lock(hint.mutex)
if rc != 0:
fprintf(cstderr, "pyzmq-gc mutex lock failed rc=%d\n", rc)
rc = zmq_msg_send(msg_ptr, hint.sock, 0)
if rc < 0:
# gc socket could have been closed, e.g. during process teardown.
# If so, ignore the failure because there's nothing to do.
if _zmq_errno() != ZMQ_ENOTSOCK:
fprintf(
cstderr, "pyzmq-gc send failed: %s\n", zmq_strerror(_zmq_errno())
)
rc = mutex_unlock(hint.mutex)
if rc != 0:
fprintf(cstderr, "pyzmq-gc mutex unlock failed rc=%d\n", rc)
zmq_msg_close(msg_ptr)
free(hint)
return 0
@cfunc
@inline
def _copy_zmq_msg_bytes(zmq_msg: pointer(zmq_msg_t)) -> bytes:
"""Copy the data from a zmq_msg_t"""
data_c: p_char = NULL
data_len_c: Py_ssize_t
data_c = cast(p_char, zmq_msg_data(zmq_msg))
data_len_c = zmq_msg_size(zmq_msg)
return PyBytes_FromStringAndSize(data_c, data_len_c)
@cfunc
@inline
def _asbuffer(obj, data_c: pointer(p_void), writable: bint = False) -> size_t:
"""Get a C buffer from a memoryview"""
pybuf = declare(Py_buffer)
flags: C.int = PyBUF_ANY_CONTIGUOUS
if writable:
flags |= PyBUF_WRITABLE
rc: C.int = PyObject_GetBuffer(obj, address(pybuf), flags)
if rc < 0:
raise ValueError("Couldn't create buffer")
data_c[0] = pybuf.buf
data_size: size_t = pybuf.len
PyBuffer_Release(address(pybuf))
return data_size
_gc = None
@cclass
class Frame:
def __init__(
self, data=None, track=False, copy=None, copy_threshold=None, **kwargs
):
rc: C.int
data_c: p_char = NULL
data_len_c: Py_ssize_t = 0
hint: pointer(_zhint)
if copy_threshold is None:
copy_threshold = zmq.COPY_THRESHOLD
c_copy_threshold: C.size_t = 0
if copy_threshold is not None:
c_copy_threshold = copy_threshold
zmq_msg_ptr: pointer(zmq_msg_t) = address(self.zmq_msg)
# init more as False
self.more = False
# Save the data object in case the user wants the the data as a str.
self._data = data
self._failed_init = True # bool switch for dealloc
self._buffer = None # buffer view of data
self._bytes = None # bytes copy of data
self.tracker_event = None
self.tracker = None
# self.tracker should start finished
# except in the case where we are sharing memory with libzmq
if track:
self.tracker = zmq._FINISHED_TRACKER
if isinstance(data, str):
raise TypeError("Str objects not allowed. Only: bytes, buffer interfaces.")
if data is None:
rc = zmq_msg_init(zmq_msg_ptr)
_check_rc(rc)
self._failed_init = False
return
data_len_c = _asbuffer(data, cast(pointer(p_void), address(data_c)))
# copy unspecified, apply copy_threshold
c_copy: bint = True
if copy is None:
if c_copy_threshold and data_len_c < c_copy_threshold:
c_copy = True
else:
c_copy = False
else:
c_copy = copy
if c_copy:
# copy message data instead of sharing memory
rc = zmq_msg_init_size(zmq_msg_ptr, data_len_c)
_check_rc(rc)
memcpy(zmq_msg_data(zmq_msg_ptr), data_c, data_len_c)
self._failed_init = False
return
# Getting here means that we are doing a true zero-copy Frame,
# where libzmq and Python are sharing memory.
# Hook up garbage collection with MessageTracker and zmq_free_fn
# Event and MessageTracker for monitoring when zmq is done with data:
if track:
evt = Event()
self.tracker_event = evt
self.tracker = zmq.MessageTracker(evt)
# create the hint for zmq_free_fn
# two pointers: the gc context and a message to be sent to the gc PULL socket
# allows libzmq to signal to Python when it is done with Python-owned memory.
global _gc
if _gc is None:
from zmq.utils.garbage import gc as _gc
hint: pointer(_zhint) = cast(pointer(_zhint), malloc(sizeof(_zhint)))
hint.id = _gc.store(data, self.tracker_event)
if not _gc._push_mutex:
hint.mutex = mutex_allocate()
_gc._push_mutex = cast(size_t, hint.mutex)
else:
hint.mutex = cast(pointer(mutex_t), cast(size_t, _gc._push_mutex))
hint.sock = cast(p_void, cast(size_t, _gc._push_socket.underlying))
rc = zmq_msg_init_data(
zmq_msg_ptr,
cast(p_void, data_c),
data_len_c,
cast(pointer(zmq_free_fn), free_python_msg),
cast(p_void, hint),
)
if rc != 0:
free(hint)
_check_rc(rc)
self._failed_init = False
def __dealloc__(self):
if self._failed_init:
return
# decrease the 0MQ ref-count of zmq_msg
with nogil:
rc: C.int = zmq_msg_close(address(self.zmq_msg))
_check_rc(rc)
def __copy__(self):
return self.fast_copy()
def fast_copy(self) -> Frame:
new_msg: Frame = Frame()
# This does not copy the contents, but just increases the ref-count
# of the zmq_msg by one.
zmq_msg_copy(address(new_msg.zmq_msg), address(self.zmq_msg))
# Copy the ref to data so the copy won't create a copy when str is
# called.
if self._data is not None:
new_msg._data = self._data
if self._buffer is not None:
new_msg._buffer = self._buffer
if self._bytes is not None:
new_msg._bytes = self._bytes
# Frame copies share the tracker and tracker_event
new_msg.tracker_event = self.tracker_event
new_msg.tracker = self.tracker
return new_msg
# buffer interface code adapted from petsc4py by Lisandro Dalcin, a BSD project
def __getbuffer__(self, buffer: pointer(Py_buffer), flags: C.int): # noqa: F821
# new-style (memoryview) buffer interface
buffer.buf = zmq_msg_data(address(self.zmq_msg))
buffer.len = zmq_msg_size(address(self.zmq_msg))
buffer.obj = self
buffer.readonly = 0
buffer.format = "B"
buffer.ndim = 1
buffer.shape = address(buffer.len)
buffer.strides = NULL
buffer.suboffsets = NULL
buffer.itemsize = 1
buffer.internal = NULL
def __len__(self) -> size_t:
"""Return the length of the message in bytes."""
sz: size_t = zmq_msg_size(address(self.zmq_msg))
return sz
@property
def buffer(self):
"""A memoryview of the message contents."""
_buffer = self._buffer and self._buffer()
if _buffer is not None:
return _buffer
_buffer = memoryview(self)
self._buffer = ref(_buffer)
return _buffer
@property
def bytes(self):
"""The message content as a Python bytes object.
The first time this property is accessed, a copy of the message
contents is made. From then on that same copy of the message is
returned.
"""
if self._bytes is None:
self._bytes = _copy_zmq_msg_bytes(address(self.zmq_msg))
return self._bytes
def get(self, option):
"""
Get a Frame option or property.
See the 0MQ API documentation for zmq_msg_get and zmq_msg_gets
for details on specific options.
.. versionadded:: libzmq-3.2
.. versionadded:: 13.0
.. versionchanged:: 14.3
add support for zmq_msg_gets (requires libzmq-4.1)
All message properties are strings.
.. versionchanged:: 17.0
Added support for `routing_id` and `group`.
Only available if draft API is enabled
with libzmq >= 4.2.
"""
rc: C.int = 0
property_c: p_char = NULL
# zmq_msg_get
if isinstance(option, int):
rc = zmq_msg_get(address(self.zmq_msg), option)
_check_rc(rc)
return rc
if option == 'routing_id':
routing_id: uint32_t = zmq_msg_routing_id(address(self.zmq_msg))
if routing_id == 0:
_check_rc(-1)
return routing_id
elif option == 'group':
buf = zmq_msg_group(address(self.zmq_msg))
if buf == NULL:
_check_rc(-1)
return buf.decode('utf8')
# zmq_msg_gets
_check_version((4, 1), "get string properties")
if isinstance(option, str):
option = option.encode('utf8')
if not isinstance(option, bytes):
raise TypeError(f"expected str, got: {option!r}")
property_c = option
result: p_char = cast(p_char, zmq_msg_gets(address(self.zmq_msg), property_c))
if result == NULL:
_check_rc(-1)
return result.decode('utf8')
def set(self, option, value):
"""Set a Frame option.
See the 0MQ API documentation for zmq_msg_set
for details on specific options.
.. versionadded:: libzmq-3.2
.. versionadded:: 13.0
.. versionchanged:: 17.0
Added support for `routing_id` and `group`.
Only available if draft API is enabled
with libzmq >= 4.2.
"""
rc: C.int
if option == 'routing_id':
routing_id: uint32_t = value
rc = zmq_msg_set_routing_id(address(self.zmq_msg), routing_id)
_check_rc(rc)
return
elif option == 'group':
if isinstance(value, str):
value = value.encode('utf8')
rc = zmq_msg_set_group(address(self.zmq_msg), value)
_check_rc(rc)
return
rc = zmq_msg_set(address(self.zmq_msg), option, value)
_check_rc(rc)
@cclass
class Context:
"""
Manage the lifecycle of a 0MQ context.
Parameters
----------
io_threads : int
The number of IO threads.
"""
def __init__(self, io_threads: C.int = 1, shadow: size_t = 0):
self.handle = NULL
self._pid = 0
self._shadow = False
if shadow:
self.handle = cast(p_void, shadow)
self._shadow = True
else:
self._shadow = False
self.handle = zmq_ctx_new()
if self.handle == NULL:
raise ZMQError()
rc: C.int = 0
if not self._shadow:
rc = zmq_ctx_set(self.handle, ZMQ_IO_THREADS, io_threads)
_check_rc(rc)
self.closed = False
self._pid = getpid()
@property
def underlying(self):
"""The address of the underlying libzmq context"""
return cast(size_t, self.handle)
@cfunc
@inline
def _term(self) -> C.int:
rc: C.int = 0
if self.handle != NULL and not self.closed and getpid() == self._pid:
with nogil:
rc = zmq_ctx_destroy(self.handle)
self.handle = NULL
return rc
def term(self):
"""
Close or terminate the context.
This can be called to close the context by hand. If this is not called,
the context will automatically be closed when it is garbage collected.
"""
rc: C.int = self._term()
try:
_check_rc(rc)
except InterruptedSystemCall:
# ignore interrupted term
# see PEP 475 notes about close & EINTR for why
pass
self.closed = True
def set(self, option: C.int, optval):
"""
Set a context option.
See the 0MQ API documentation for zmq_ctx_set
for details on specific options.
.. versionadded:: libzmq-3.2
.. versionadded:: 13.0
Parameters
----------
option : int
The option to set. Available values will depend on your
version of libzmq. Examples include::
zmq.IO_THREADS, zmq.MAX_SOCKETS
optval : int
The value of the option to set.
"""
optval_int_c: C.int
rc: C.int
if self.closed:
raise RuntimeError("Context has been destroyed")
if not isinstance(optval, int):
raise TypeError(f'expected int, got: {optval!r}')
optval_int_c = optval
rc = zmq_ctx_set(self.handle, option, optval_int_c)
_check_rc(rc)
def get(self, option: C.int):
"""
Get the value of a context option.
See the 0MQ API documentation for zmq_ctx_get
for details on specific options.
.. versionadded:: libzmq-3.2
.. versionadded:: 13.0
Parameters
----------
option : int
The option to get. Available values will depend on your
version of libzmq. Examples include::
zmq.IO_THREADS, zmq.MAX_SOCKETS
Returns
-------
optval : int
The value of the option as an integer.
"""
rc: C.int
if self.closed:
raise RuntimeError("Context has been destroyed")
rc = zmq_ctx_get(self.handle, option)
_check_rc(rc, error_without_errno=False)
return rc
@cfunc
@inline
def _c_addr(addr) -> bytes:
"""cast an address input to bytes
Expects a str, but accepts bytes
and raises informative TypeError otherwise.
"""
if isinstance(addr, str):
addr = addr.encode("utf-8")
try:
c_addr: bytes = addr
except TypeError:
raise TypeError(f"Expected addr to be str, got addr={addr!r}")
return c_addr
@cclass
class Socket:
"""
A 0MQ socket.
These objects will generally be constructed via the socket() method of a Context object.
Note: 0MQ Sockets are *not* threadsafe. **DO NOT** share them across threads.
Parameters
----------
context : Context
The 0MQ Context this Socket belongs to.
socket_type : int
The socket type, which can be any of the 0MQ socket types:
REQ, REP, PUB, SUB, PAIR, DEALER, ROUTER, PULL, PUSH, XPUB, XSUB.
See Also
--------
.Context.socket : method for creating a socket bound to a Context.
"""
def __init__(
self,
context=None,
socket_type: C.int = -1,
shadow: size_t = 0,
copy_threshold=None,
):
# pre-init
self.handle = NULL
self._draft_poller = NULL
self._pid = 0
self._shadow = False
self.context = None
if copy_threshold is None:
copy_threshold = zmq.COPY_THRESHOLD
self.copy_threshold = copy_threshold
self.handle = NULL
self.context = context
if shadow:
self._shadow = True
self.handle = cast(p_void, shadow)
else:
if context is None:
raise TypeError("context must be specified")
if socket_type < 0:
raise TypeError("socket_type must be specified")
self._shadow = False
self.handle = zmq_socket(self.context.handle, socket_type)
if self.handle == NULL:
raise ZMQError()
self._closed = False
self._pid = getpid()
@property
def underlying(self):
"""The address of the underlying libzmq socket"""
return cast(size_t, self.handle)
@property
def closed(self):
"""Whether the socket is closed"""
return _check_closed_deep(self)
def close(self, linger: int | None = None):
"""
Close the socket.
If linger is specified, LINGER sockopt will be set prior to closing.
This can be called to close the socket by hand. If this is not
called, the socket will automatically be closed when it is
garbage collected.
"""
rc: C.int = 0
linger_c: C.int
setlinger: bint = False
if linger is not None:
linger_c = linger
setlinger = True
if self.handle != NULL and not self._closed and getpid() == self._pid:
if setlinger:
zmq_setsockopt(self.handle, ZMQ_LINGER, address(linger_c), sizeof(int))
# teardown draft poller
if self._draft_poller != NULL:
zmq_poller_destroy(address(self._draft_poller))
self._draft_poller = NULL
rc = zmq_close(self.handle)
if rc < 0 and _zmq_errno() != ENOTSOCK:
# ignore ENOTSOCK (closed by Context)
_check_rc(rc)
self._closed = True
self.handle = NULL
def set(self, option: C.int, optval):
"""
Set socket options.
See the 0MQ API documentation for details on specific options.
Parameters
----------
option : int
The option to set. Available values will depend on your
version of libzmq. Examples include::
zmq.SUBSCRIBE, UNSUBSCRIBE, IDENTITY, HWM, LINGER, FD
optval : int or bytes
The value of the option to set.
Notes
-----
.. warning::
All options other than zmq.SUBSCRIBE, zmq.UNSUBSCRIBE and
zmq.LINGER only take effect for subsequent socket bind/connects.
"""
optval_int64_c: int64_t
optval_int_c: C.int
optval_c: p_char
sz: Py_ssize_t
_check_closed(self)
if isinstance(optval, str):
raise TypeError("unicode not allowed, use setsockopt_string")
try:
sopt = SocketOption(option)
except ValueError:
# unrecognized option,
# assume from the future,
# let EINVAL raise
opt_type = _OptType.int
else:
opt_type = sopt._opt_type
if opt_type == _OptType.bytes:
if not isinstance(optval, bytes):
raise TypeError(f'expected bytes, got: {optval!r}')
optval_c = PyBytes_AsString(optval)
sz = PyBytes_Size(optval)
_setsockopt(self.handle, option, optval_c, sz)
elif opt_type == _OptType.int64:
if not isinstance(optval, int):
raise TypeError(f'expected int, got: {optval!r}')
optval_int64_c = optval
_setsockopt(self.handle, option, address(optval_int64_c), sizeof(int64_t))
else:
# default is to assume int, which is what most new sockopts will be
# this lets pyzmq work with newer libzmq which may add constants
# pyzmq has not yet added, rather than artificially raising. Invalid
# sockopts will still raise just the same, but it will be libzmq doing
# the raising.
if not isinstance(optval, int):
raise TypeError(f'expected int, got: {optval!r}')
optval_int_c = optval
_setsockopt(self.handle, option, address(optval_int_c), sizeof(int))
def get(self, option: C.int):
"""
Get the value of a socket option.
See the 0MQ API documentation for details on specific options.
.. versionchanged:: 27
Added experimental support for ZMQ_FD for draft sockets via `zmq_poller_fd`.
Requires libzmq >=4.3.2 built with draft support.
Parameters
----------
option : int
The option to get. Available values will depend on your
version of libzmq. Examples include::
zmq.IDENTITY, HWM, LINGER, FD, EVENTS
Returns
-------
optval : int or bytes
The value of the option as a bytestring or int.
"""
optval_int64_c = declare(int64_t)
optval_int_c = declare(C.int)
optval_fd_c = declare(fd_t)
identity_str_c = declare(char[255])
sz: size_t
_check_closed(self)
try:
sopt = SocketOption(option)
except ValueError:
# unrecognized option,
# assume from the future,
# let EINVAL raise
opt_type = _OptType.int
else:
opt_type = sopt._opt_type
if opt_type == _OptType.bytes:
sz = 255
_getsockopt(self.handle, option, cast(p_void, identity_str_c), address(sz))
# strip null-terminated strings *except* identity
if (
option != ZMQ_IDENTITY
and sz > 0
and (cast(p_char, identity_str_c))[sz - 1] == b'\0'
):
sz -= 1
result = PyBytes_FromStringAndSize(cast(p_char, identity_str_c), sz)
elif opt_type == _OptType.int64:
sz = sizeof(int64_t)
_getsockopt(
self.handle, option, cast(p_void, address(optval_int64_c)), address(sz)
)
result = optval_int64_c
elif option == ZMQ_FD and self._draft_poller != NULL:
# draft sockets use FD of a draft zmq_poller as proxy
rc = zmq_poller_fd(self._draft_poller, address(optval_fd_c))
_check_rc(rc)
result = optval_fd_c
elif opt_type == _OptType.fd:
sz = sizeof(fd_t)
try:
_getsockopt(
self.handle, option, cast(p_void, address(optval_fd_c)), address(sz)
)
except ZMQError as e:
# threadsafe sockets don't support ZMQ_FD (yet!)
# fallback on zmq_poller_fd as proxy with the same behavior
# until libzmq fixes this.
# if upstream fixes it, this branch will never be taken
if (
option == ZMQ_FD
and e.errno == zmq.Errno.EINVAL
and self.get(ZMQ_THREAD_SAFE)
):
_check_version(
(4, 3, 2), "draft socket FD support via zmq_poller_fd"
)
if not zmq.DRAFT_API:
raise RuntimeError(
"libzmq and pyzmq must be built with draft support"
)
warnings.warn(zmq.error.DraftFDWarning(), stacklevel=2)
# create a poller and retrieve its fd
self._draft_poller = zmq_poller_new()
if self._draft_poller == NULL:
# failed (why?), raise original error
raise
# register self with poller
rc = zmq_poller_add(
self._draft_poller, self.handle, NULL, ZMQ_POLLIN | ZMQ_POLLOUT
)
_check_rc(rc)
# use poller fd as proxy for ours
rc = zmq_poller_fd(self._draft_poller, address(optval_fd_c))
_check_rc(rc)
else:
raise
result = optval_fd_c
else:
# default is to assume int, which is what most new sockopts will be
# this lets pyzmq work with newer libzmq which may add constants
# pyzmq has not yet added, rather than artificially raising. Invalid
# sockopts will still raise just the same, but it will be libzmq doing
# the raising.
sz = sizeof(int)
_getsockopt(
self.handle, option, cast(p_void, address(optval_int_c)), address(sz)
)
result = optval_int_c
return result
def bind(self, addr: str | bytes):
"""
Bind the socket to an address.
This causes the socket to listen on a network port. Sockets on the
other side of this connection will use ``Socket.connect(addr)`` to
connect to this socket.
Parameters
----------
addr : str
The address string. This has the form 'protocol://interface:port',
for example 'tcp://127.0.0.1:5555'. Protocols supported include
tcp, udp, pgm, epgm, inproc and ipc. If the address is unicode, it is
encoded to utf-8 first.
"""
_addr_bytes: bytes = _c_addr(addr)
c_addr: p_char = _addr_bytes
_check_closed(self)
rc: C.int = zmq_bind(self.handle, c_addr)
if rc != 0:
_errno: C.int = _zmq_errno()
_ipc_max: C.int = get_ipc_path_max_len()
if _ipc_max and _errno == ENAMETOOLONG:
path = addr.split('://', 1)[-1]
msg = (
f'ipc path "{path}" is longer than {_ipc_max} '