/
connection.py
2429 lines (1933 loc) · 90 KB
/
connection.py
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
"""Core connection objects"""
# disable too-many-lines
# pylint: disable=C0302
import abc
import ast
import copy
import functools
import logging
import math
import numbers
import platform
import socket
import warnings
import ssl
from pika import __version__
from pika import callback as pika_callback
import pika.channel
from pika import credentials as pika_credentials
from pika import exceptions
from pika import frame
from pika import heartbeat as pika_heartbeat
from pika import spec
import pika.compat
from pika.compat import (xrange, basestring, # pylint: disable=W0622
url_unquote, dictkeys, dict_itervalues,
dict_iteritems)
BACKPRESSURE_WARNING = ("Pika: Write buffer exceeded warning threshold at "
"%i bytes and an estimated %i frames behind")
PRODUCT = "Pika Python Client Library"
LOGGER = logging.getLogger(__name__)
class Parameters(object): # pylint: disable=R0902
"""Base connection parameters class definition
"""
# Declare slots to protect against accidental assignment of an invalid
# attribute
__slots__ = (
'_backpressure_detection',
'_blocked_connection_timeout',
'_channel_max',
'_client_properties',
'_connection_attempts',
'_credentials',
'_frame_max',
'_heartbeat',
'_host',
'_locale',
'_port',
'_retry_delay',
'_socket_timeout',
'_stack_timeout',
'_ssl_options',
'_virtual_host',
'_tcp_options'
)
DEFAULT_USERNAME = 'guest'
DEFAULT_PASSWORD = 'guest'
DEFAULT_BACKPRESSURE_DETECTION = False
DEFAULT_BLOCKED_CONNECTION_TIMEOUT = None
DEFAULT_CHANNEL_MAX = pika.channel.MAX_CHANNELS
DEFAULT_CLIENT_PROPERTIES = None
DEFAULT_CREDENTIALS = pika_credentials.PlainCredentials(DEFAULT_USERNAME,
DEFAULT_PASSWORD)
DEFAULT_CONNECTION_ATTEMPTS = 1
DEFAULT_FRAME_MAX = spec.FRAME_MAX_SIZE
DEFAULT_HEARTBEAT_TIMEOUT = None # None accepts server's proposal
DEFAULT_HOST = 'localhost'
DEFAULT_LOCALE = 'en_US'
DEFAULT_PORT = 5672
DEFAULT_RETRY_DELAY = 2.0
DEFAULT_SOCKET_TIMEOUT = 10.0 # socket.connect() timeout
DEFAULT_STACK_TIMEOUT = 15.0 # full-stack TCP/[SSl]/AMQP bring-up timeout
DEFAULT_SSL = False
DEFAULT_SSL_OPTIONS = None
DEFAULT_SSL_PORT = 5671
DEFAULT_VIRTUAL_HOST = '/'
DEFAULT_TCP_OPTIONS = None
DEFAULT_HEARTBEAT_INTERVAL = DEFAULT_HEARTBEAT_TIMEOUT # DEPRECATED
def __init__(self):
self._backpressure_detection = None
self.backpressure_detection = self.DEFAULT_BACKPRESSURE_DETECTION
# If not None, blocked_connection_timeout is the timeout, in seconds,
# for the connection to remain blocked; if the timeout expires, the
# connection will be torn down, triggering the connection's
# on_close_callback
self._blocked_connection_timeout = None
self.blocked_connection_timeout = (
self.DEFAULT_BLOCKED_CONNECTION_TIMEOUT)
self._channel_max = None
self.channel_max = self.DEFAULT_CHANNEL_MAX
self._client_properties = None
self.client_properties = self.DEFAULT_CLIENT_PROPERTIES
self._connection_attempts = None
self.connection_attempts = self.DEFAULT_CONNECTION_ATTEMPTS
self._credentials = None
self.credentials = self.DEFAULT_CREDENTIALS
self._frame_max = None
self.frame_max = self.DEFAULT_FRAME_MAX
self._heartbeat = None
self.heartbeat = self.DEFAULT_HEARTBEAT_TIMEOUT
self._host = None
self.host = self.DEFAULT_HOST
self._locale = None
self.locale = self.DEFAULT_LOCALE
self._port = None
self.port = self.DEFAULT_PORT
self._retry_delay = None
self.retry_delay = self.DEFAULT_RETRY_DELAY
self._socket_timeout = None
self.socket_timeout = self.DEFAULT_SOCKET_TIMEOUT
self._stack_timeout = None
self.stack_timeout = self.DEFAULT_STACK_TIMEOUT
self._ssl_options = None
self.ssl_options = self.DEFAULT_SSL_OPTIONS
self._virtual_host = None
self.virtual_host = self.DEFAULT_VIRTUAL_HOST
self._tcp_options = None
self.tcp_options = self.DEFAULT_TCP_OPTIONS
def __repr__(self):
"""Represent the info about the instance.
:rtype: str
"""
return ('<%s host=%s port=%s virtual_host=%s ssl=%s>' %
(self.__class__.__name__, self.host, self.port,
self.virtual_host, bool(self.ssl_options)))
def __eq__(self, other):
if isinstance(other, Parameters):
return (other._host == self._host and other._port == self._port)
return NotImplemented
def __ne__(self, other):
result = self.__eq__(other)
if result is not NotImplemented:
return not result
return NotImplemented
@property
def backpressure_detection(self):
"""
:returns: boolean indicating whether backpressure detection is
enabled. Defaults to `DEFAULT_BACKPRESSURE_DETECTION`.
"""
return self._backpressure_detection
@backpressure_detection.setter
def backpressure_detection(self, value):
"""
:param bool value: boolean indicating whether to enable backpressure
detection
"""
if not isinstance(value, bool):
raise TypeError('backpressure_detection must be a bool, '
'but got %r' % (value,))
self._backpressure_detection = value
@property
def blocked_connection_timeout(self):
"""
:returns: None or float blocked connection timeout. Defaults to
`DEFAULT_BLOCKED_CONNECTION_TIMEOUT`.
"""
return self._blocked_connection_timeout
@blocked_connection_timeout.setter
def blocked_connection_timeout(self, value):
"""
:param value: If not None, blocked_connection_timeout is the timeout, in
seconds, for the connection to remain blocked; if the timeout
expires, the connection will be torn down, triggering the
connection's on_close_callback
"""
if value is not None:
if not isinstance(value, numbers.Real):
raise TypeError('blocked_connection_timeout must be a Real '
'number, but got %r' % (value,))
if value < 0:
raise ValueError('blocked_connection_timeout must be >= 0, but '
'got %r' % (value,))
self._blocked_connection_timeout = value
@property
def channel_max(self):
"""
:returns: max preferred number of channels. Defaults to
`DEFAULT_CHANNEL_MAX`.
:rtype: int
"""
return self._channel_max
@channel_max.setter
def channel_max(self, value):
"""
:param int value: max preferred number of channels, between 1 and
`channel.MAX_CHANNELS`, inclusive
"""
if not isinstance(value, numbers.Integral):
raise TypeError('channel_max must be an int, but got %r' % (value,))
if value < 1 or value > pika.channel.MAX_CHANNELS:
raise ValueError('channel_max must be <= %i and > 0, but got %r' %
(pika.channel.MAX_CHANNELS, value))
self._channel_max = value
@property
def client_properties(self):
"""
:returns: None or dict of client properties used to override the fields
in the default client poperties reported to RabbitMQ via
`Connection.StartOk` method. Defaults to
`DEFAULT_CLIENT_PROPERTIES`.
"""
return self._client_properties
@client_properties.setter
def client_properties(self, value):
"""
:param value: None or dict of client properties used to override the
fields in the default client poperties reported to RabbitMQ via
`Connection.StartOk` method.
"""
if not isinstance(value, (dict, type(None),)):
raise TypeError('client_properties must be dict or None, '
'but got %r' % (value,))
# Copy the mutable object to avoid accidental side-effects
self._client_properties = copy.deepcopy(value)
@property
def connection_attempts(self):
"""
:returns: number of socket connection attempts. Defaults to
`DEFAULT_CONNECTION_ATTEMPTS`. See also `retry_delay`.
"""
return self._connection_attempts
@connection_attempts.setter
def connection_attempts(self, value):
"""
:param int value: number of socket connection attempts of at least 1.
See also `retry_delay`.
"""
if not isinstance(value, numbers.Integral):
raise TypeError('connection_attempts must be an int')
if value < 1:
raise ValueError('connection_attempts must be > 0, but got %r' %
(value,))
self._connection_attempts = value
@property
def credentials(self):
"""
:rtype: one of the classes from `pika.credentials.VALID_TYPES`. Defaults
to `DEFAULT_CREDENTIALS`.
"""
return self._credentials
@credentials.setter
def credentials(self, value):
"""
:param value: authentication credential object of one of the classes
from `pika.credentials.VALID_TYPES`
"""
if not isinstance(value, tuple(pika_credentials.VALID_TYPES)):
raise TypeError('Credentials must be an object of type: %r, but '
'got %r' % (pika_credentials.VALID_TYPES, value))
# Copy the mutable object to avoid accidental side-effects
self._credentials = copy.deepcopy(value)
@property
def frame_max(self):
"""
:returns: desired maximum AMQP frame size to use. Defaults to
`DEFAULT_FRAME_MAX`.
"""
return self._frame_max
@frame_max.setter
def frame_max(self, value):
"""
:param int value: desired maximum AMQP frame size to use between
`spec.FRAME_MIN_SIZE` and `spec.FRAME_MAX_SIZE`, inclusive
"""
if not isinstance(value, numbers.Integral):
raise TypeError('frame_max must be an int, but got %r' % (value,))
if value < spec.FRAME_MIN_SIZE:
raise ValueError('Min AMQP 0.9.1 Frame Size is %i, but got %r' %
(spec.FRAME_MIN_SIZE, value,))
elif value > spec.FRAME_MAX_SIZE:
raise ValueError('Max AMQP 0.9.1 Frame Size is %i, but got %r' %
(spec.FRAME_MAX_SIZE, value,))
self._frame_max = value
@property
def heartbeat(self):
"""
:returns: AMQP connection heartbeat timeout value for negotiation during
connection tuning or callable which is invoked during connection tuning.
None to accept broker's value. 0 turns heartbeat off. Defaults to
`DEFAULT_HEARTBEAT_TIMEOUT`.
:rtype: integer, None or callable
"""
return self._heartbeat
@heartbeat.setter
def heartbeat(self, value):
"""
:param int|None|callable value: Controls AMQP heartbeat timeout negotiation
during connection tuning. An integer value always overrides the value
proposed by broker. Use 0 to deactivate heartbeats and None to always
accept the broker's proposal. If a callable is given, it will be called
with the connection instance and the heartbeat timeout proposed by broker
as its arguments. The callback should return a non-negative integer that
will be used to override the broker's proposal.
"""
if value is not None:
if not isinstance(value, numbers.Integral) and not callable(value):
raise TypeError('heartbeat must be an int or a callable function, but got %r' %
(value,))
if not callable(value) and value < 0:
raise ValueError('heartbeat must >= 0, but got %r' % (value,))
self._heartbeat = value
@property
def host(self):
"""
:returns: hostname or ip address of broker. Defaults to `DEFAULT_HOST`.
:rtype: str
"""
return self._host
@host.setter
def host(self, value):
"""
:param str value: hostname or ip address of broker
"""
if not isinstance(value, basestring):
raise TypeError('host must be a str or unicode str, but got %r' %
(value,))
self._host = value
@property
def locale(self):
"""
:returns: locale value to pass to broker; e.g., 'en_US'. Defaults to
`DEFAULT_LOCALE`.
:rtype: str
"""
return self._locale
@locale.setter
def locale(self, value):
"""
:param str value: locale value to pass to broker; e.g., "en_US"
"""
if not isinstance(value, basestring):
raise TypeError('locale must be a str, but got %r' % (value,))
self._locale = value
@property
def port(self):
"""
:returns: port number of broker's listening socket. Defaults to
`DEFAULT_PORT`.
:rtype: int
"""
return self._port
@port.setter
def port(self, value):
"""
:param int value: port number of broker's listening socket
"""
try:
self._port = int(value)
except (TypeError, ValueError):
raise TypeError('port must be an int, but got %r' % (value,))
@property
def retry_delay(self):
"""
:returns: interval between socket connection attempts; see also
`connection_attempts`. Defaults to `DEFAULT_RETRY_DELAY`.
:rtype: float
"""
return self._retry_delay
@retry_delay.setter
def retry_delay(self, value):
"""
:param int | float value: interval between socket connection attempts;
see also `connection_attempts`.
"""
if not isinstance(value, numbers.Real):
raise TypeError('retry_delay must be a float or int, but got %r' %
(value,))
self._retry_delay = value
@property
def socket_timeout(self):
"""
:returns: socket connect timeout in seconds. Defaults to
`DEFAULT_SOCKET_TIMEOUT`. The value None disables this timeout.
:rtype: float | None
"""
return self._socket_timeout
@socket_timeout.setter
def socket_timeout(self, value):
"""
:param int | float | None value: positive socket connect timeout in
seconds. None to disable this timeout.
"""
if value is not None:
if not isinstance(value, numbers.Real):
raise TypeError('socket_timeout must be a float or int, '
'but got %r' % (value,))
if value <= 0:
raise ValueError('socket_timeout must be > 0, but got %r' %
(value,))
value = float(value)
self._socket_timeout = value
@property
def stack_timeout(self):
"""
:returns: full protocol stack TCP/[SSL]/AMQP bring-up timeout in
seconds. Defaults to `DEFAULT_STACK_TIMEOUT`. The value None
disables this timeout.
:rtype: float
"""
return self._stack_timeout
@stack_timeout.setter
def stack_timeout(self, value):
"""
:param int | float | None value: positive full protocol stack
TCP/[SSL]/AMQP bring-up timeout in seconds. It's recommended to set
this value higher than `socket_timeout`. None to disable this
timeout.
"""
if value is not None:
if not isinstance(value, numbers.Real):
raise TypeError('stack_timeout must be a float or int, '
'but got %r' % (value,))
if value <= 0:
raise ValueError('stack_timeout must be > 0, but got %r' %
(value,))
value = float(value)
self._stack_timeout = value
@property
def ssl_options(self):
"""
:returns: None for plaintext or `pika.SSLOptions` instance for SSL/TLS.
:rtype: `pika.SSLOptions`|None
"""
return self._ssl_options
@ssl_options.setter
def ssl_options(self, value):
"""
:param `pika.SSLOptions`|None value: None for plaintext or
`pika.SSLOptions` instance for SSL/TLS. Defaults to None.
"""
if not isinstance(value, (SSLOptions, type(None))):
raise TypeError(
'ssl_options must be None or SSLOptions but got %r'
% (value, ))
self._ssl_options = value
@property
def virtual_host(self):
"""
:returns: rabbitmq virtual host name. Defaults to
`DEFAULT_VIRTUAL_HOST`.
"""
return self._virtual_host
@virtual_host.setter
def virtual_host(self, value):
"""
:param str value: rabbitmq virtual host name
"""
if not isinstance(value, basestring):
raise TypeError('virtual_host must be a str, but got %r' % (value,))
self._virtual_host = value
@property
def tcp_options(self):
"""
:returns: None or a dict of options to pass to the underlying socket
:rtype: dict|None
"""
return self._tcp_options
@tcp_options.setter
def tcp_options(self, value):
"""
:param dict|None value: None or a dict of options to pass to the underlying
socket. Currently supported are TCP_KEEPIDLE, TCP_KEEPINTVL, TCP_KEEPCNT
and TCP_USER_TIMEOUT. Availability of these may depend on your platform.
"""
if not isinstance(value, (dict, type(None))):
raise TypeError('tcp_options must be a dict or None, but got %r' %
(value,))
self._tcp_options = value
class ConnectionParameters(Parameters):
"""Connection parameters object that is passed into the connection adapter
upon construction.
"""
# Protect against accidental assignment of an invalid attribute
__slots__ = ()
class _DEFAULT(object):
"""Designates default parameter value; internal use"""
pass
def __init__(self, # pylint: disable=R0913,R0914,R0912
host=_DEFAULT,
port=_DEFAULT,
virtual_host=_DEFAULT,
credentials=_DEFAULT,
channel_max=_DEFAULT,
frame_max=_DEFAULT,
heartbeat=_DEFAULT,
ssl_options=_DEFAULT,
connection_attempts=_DEFAULT,
retry_delay=_DEFAULT,
socket_timeout=_DEFAULT,
stack_timeout=_DEFAULT,
locale=_DEFAULT,
backpressure_detection=_DEFAULT,
blocked_connection_timeout=_DEFAULT,
client_properties=_DEFAULT,
tcp_options=_DEFAULT,
**kwargs):
"""Create a new ConnectionParameters instance. See `Parameters` for
default values.
:param str host: Hostname or IP Address to connect to
:param int port: TCP port to connect to
:param str virtual_host: RabbitMQ virtual host to use
:param pika.credentials.Credentials credentials: auth credentials
:param int channel_max: Maximum number of channels to allow
:param int frame_max: The maximum byte size for an AMQP frame
:param int|None|callable value: Controls AMQP heartbeat timeout negotiation
during connection tuning. An integer value always overrides the value
proposed by broker. Use 0 to deactivate heartbeats and None to always
accept the broker's proposal. If a callable is given, it will be called
with the connection instance and the heartbeat timeout proposed by broker
as its arguments. The callback should return a non-negative integer that
will be used to override the broker's proposal.
:param `pika.SSLOptions`|None ssl_options: None for plaintext or
`pika.SSLOptions` instance for SSL/TLS. Defaults to None.
:param int connection_attempts: Maximum number of retry attempts
:param int|float retry_delay: Time to wait in seconds, before the next
:param int|float socket_timeout: Positive socket connect timeout in
seconds.
:param int|float stack_timeout: Positive full protocol stack
(TCP/[SSL]/AMQP) bring-up timeout in seconds. It's recommended to
set this value higher than `socket_timeout`.
:param str locale: Set the locale value
:param bool backpressure_detection: DEPRECATED in favor of
`Connection.Blocked` and `Connection.Unblocked`. See
`Connection.add_on_connection_blocked_callback`.
:param blocked_connection_timeout: If not None,
the value is a non-negative timeout, in seconds, for the
connection to remain blocked (triggered by Connection.Blocked from
broker); if the timeout expires before connection becomes unblocked,
the connection will be torn down, triggering the adapter-specific
mechanism for informing client app about the closed connection:
passing `ConnectionBlockedTimeout` exception to on_close_callback
in asynchronous adapters or raising it in `BlockingConnection`.
:type blocked_connection_timeout: None, int, float
:param client_properties: None or dict of client properties used to
override the fields in the default client properties reported to
RabbitMQ via `Connection.StartOk` method.
:param heartbeat_interval: DEPRECATED; use `heartbeat` instead, and
don't pass both
:param tcp_options: None or a dict of TCP options to set for socket
"""
super(ConnectionParameters, self).__init__()
if backpressure_detection is not self._DEFAULT:
self.backpressure_detection = backpressure_detection
if blocked_connection_timeout is not self._DEFAULT:
self.blocked_connection_timeout = blocked_connection_timeout
if channel_max is not self._DEFAULT:
self.channel_max = channel_max
if client_properties is not self._DEFAULT:
self.client_properties = client_properties
if connection_attempts is not self._DEFAULT:
self.connection_attempts = connection_attempts
if credentials is not self._DEFAULT:
self.credentials = credentials
if frame_max is not self._DEFAULT:
self.frame_max = frame_max
if heartbeat is not self._DEFAULT:
self.heartbeat = heartbeat
try:
heartbeat_interval = kwargs.pop('heartbeat_interval')
except KeyError:
# Good, this one is deprecated
pass
else:
warnings.warn('heartbeat_interval is deprecated, use heartbeat',
DeprecationWarning, stacklevel=2)
if heartbeat is not self._DEFAULT:
raise TypeError('heartbeat and deprecated heartbeat_interval '
'are mutually-exclusive')
self.heartbeat = heartbeat_interval
if host is not self._DEFAULT:
self.host = host
if locale is not self._DEFAULT:
self.locale = locale
if retry_delay is not self._DEFAULT:
self.retry_delay = retry_delay
if socket_timeout is not self._DEFAULT:
self.socket_timeout = socket_timeout
if stack_timeout is not self._DEFAULT:
self.stack_timeout = stack_timeout
if ssl_options is not self._DEFAULT:
self.ssl_options = ssl_options
# Set port after SSL status is known
if port is not self._DEFAULT:
self.port = port
else:
self.port = self.DEFAULT_SSL_PORT if self.ssl_options else self.DEFAULT_PORT
if virtual_host is not self._DEFAULT:
self.virtual_host = virtual_host
if tcp_options is not self._DEFAULT:
self.tcp_options = tcp_options
if kwargs:
raise TypeError('Unexpected kwargs: %r' % (kwargs,))
class URLParameters(Parameters):
"""Connect to RabbitMQ via an AMQP URL in the format::
amqp://username:password@host:port/<virtual_host>[?query-string]
Ensure that the virtual host is URI encoded when specified. For example if
you are using the default "/" virtual host, the value should be `%2f`.
See `Parameters` for default values.
Valid query string values are:
- backpressure_detection:
DEPRECATED in favor of
`Connection.Blocked` and `Connection.Unblocked`. See
`Connection.add_on_connection_blocked_callback`.
- channel_max:
Override the default maximum channel count value
- client_properties:
dict of client properties used to override the fields in the default
client properties reported to RabbitMQ via `Connection.StartOk`
method
- connection_attempts:
Specify how many times pika should try and reconnect before it gives up
- frame_max:
Override the default maximum frame size for communication
- heartbeat:
Desired connection heartbeat timeout for negotiation. If not present
the broker's value is accepted. 0 turns heartbeat off.
- locale:
Override the default `en_US` locale value
- ssl_options:
None for plaintext; for SSL: dict of public ssl context-related
arguments that may be passed to :meth:`ssl.SSLSocket` as kwargs,
except `sock`, `server_side`,`do_handshake_on_connect`, `family`,
`type`, `proto`, `fileno`.
- retry_delay:
The number of seconds to sleep before attempting to connect on
connection failure.
- socket_timeout:
Socket connect timeout value in seconds (float or int)
- stack_timeout:
Positive full protocol stack (TCP/[SSL]/AMQP) bring-up timeout in
seconds. It's recommended to set this value higher than
`socket_timeout`.
- blocked_connection_timeout:
Set the timeout, in seconds, that the connection may remain blocked
(triggered by Connection.Blocked from broker); if the timeout
expires before connection becomes unblocked, the connection will be
torn down, triggering the connection's on_close_callback
- tcp_options:
Set the tcp options for the underlying socket.
:param str url: The AMQP URL to connect to
"""
# Protect against accidental assignment of an invalid attribute
__slots__ = ('_all_url_query_values',)
# The name of the private function for parsing and setting a given URL query
# arg is constructed by catenating the query arg's name to this prefix
_SETTER_PREFIX = '_set_url_'
def __init__(self, url):
"""Create a new URLParameters instance.
:param str url: The URL value
"""
super(URLParameters, self).__init__()
self._all_url_query_values = None
# Handle the Protocol scheme
#
# Fix up scheme amqp(s) to http(s) so urlparse won't barf on python
# prior to 2.7. On Python 2.6.9,
# `urlparse('amqp://127.0.0.1/%2f?socket_timeout=1')` produces an
# incorrect path='/%2f?socket_timeout=1'
if url[0:4].lower() == 'amqp':
url = 'http' + url[4:]
parts = pika.compat.urlparse(url)
if parts.scheme == 'https':
# Create default context which will get overridden by the
# ssl_options URL arg, if any
self.ssl_options = pika.SSLOptions(
context=ssl.create_default_context())
elif parts.scheme == 'http':
self.ssl_options = None
elif parts.scheme:
raise ValueError('Unexpected URL scheme %r; supported scheme '
'values: amqp, amqps' % (parts.scheme,))
if parts.hostname is not None:
self.host = parts.hostname
# Take care of port after SSL status is known
if parts.port is not None:
self.port = parts.port
else:
self.port = (self.DEFAULT_SSL_PORT if self.ssl_options
else self.DEFAULT_PORT)
if parts.username is not None:
self.credentials = pika_credentials.PlainCredentials(url_unquote(parts.username),
url_unquote(parts.password))
# Get the Virtual Host
if len(parts.path) > 1:
self.virtual_host = url_unquote(parts.path.split('/')[1])
# Handle query string values, validating and assigning them
self._all_url_query_values = pika.compat.url_parse_qs(parts.query)
for name, value in dict_iteritems(self._all_url_query_values):
try:
set_value = getattr(self, self._SETTER_PREFIX + name)
except AttributeError:
raise ValueError('Unknown URL parameter: %r' % (name,))
try:
(value,) = value
except ValueError:
raise ValueError('Expected exactly one value for URL parameter '
'%s, but got %i values: %s' % (
name, len(value), value))
set_value(value)
def _set_url_backpressure_detection(self, value):
"""Deserialize and apply the corresponding query string arg"""
try:
backpressure_detection = {'t': True, 'f': False}[value]
except KeyError:
raise ValueError('Invalid backpressure_detection value: %r' %
(value,))
self.backpressure_detection = backpressure_detection
def _set_url_blocked_connection_timeout(self, value):
"""Deserialize and apply the corresponding query string arg"""
try:
blocked_connection_timeout = float(value)
except ValueError as exc:
raise ValueError('Invalid blocked_connection_timeout value %r: %r' %
(value, exc,))
self.blocked_connection_timeout = blocked_connection_timeout
def _set_url_channel_max(self, value):
"""Deserialize and apply the corresponding query string arg"""
try:
channel_max = int(value)
except ValueError as exc:
raise ValueError('Invalid channel_max value %r: %r' % (value, exc,))
self.channel_max = channel_max
def _set_url_client_properties(self, value):
"""Deserialize and apply the corresponding query string arg"""
self.client_properties = ast.literal_eval(value)
def _set_url_connection_attempts(self, value):
"""Deserialize and apply the corresponding query string arg"""
try:
connection_attempts = int(value)
except ValueError as exc:
raise ValueError('Invalid connection_attempts value %r: %r' %
(value, exc,))
self.connection_attempts = connection_attempts
def _set_url_frame_max(self, value):
"""Deserialize and apply the corresponding query string arg"""
try:
frame_max = int(value)
except ValueError as exc:
raise ValueError('Invalid frame_max value %r: %r' % (value, exc,))
self.frame_max = frame_max
def _set_url_heartbeat(self, value):
"""Deserialize and apply the corresponding query string arg"""
if 'heartbeat_interval' in self._all_url_query_values:
raise ValueError('Deprecated URL parameter heartbeat_interval must '
'not be specified together with heartbeat')
try:
heartbeat_timeout = int(value)
except ValueError as exc:
raise ValueError('Invalid heartbeat value %r: %r' % (value, exc,))
self.heartbeat = heartbeat_timeout
def _set_url_heartbeat_interval(self, value):
"""Deserialize and apply the corresponding query string arg"""
warnings.warn('heartbeat_interval is deprecated, use heartbeat',
DeprecationWarning, stacklevel=2)
if 'heartbeat' in self._all_url_query_values:
raise ValueError('Deprecated URL parameter heartbeat_interval must '
'not be specified together with heartbeat')
try:
heartbeat_timeout = int(value)
except ValueError as exc:
raise ValueError('Invalid heartbeat_interval value %r: %r' %
(value, exc,))
self.heartbeat = heartbeat_timeout
def _set_url_locale(self, value):
"""Deserialize and apply the corresponding query string arg"""
self.locale = value
def _set_url_retry_delay(self, value):
"""Deserialize and apply the corresponding query string arg"""
try:
retry_delay = float(value)
except ValueError as exc:
raise ValueError('Invalid retry_delay value %r: %r' % (value, exc,))
self.retry_delay = retry_delay
def _set_url_socket_timeout(self, value):
"""Deserialize and apply the corresponding query string arg"""
try:
socket_timeout = float(value)
except ValueError as exc:
raise ValueError('Invalid socket_timeout value %r: %r' %
(value, exc,))
self.socket_timeout = socket_timeout
def _set_url_stack_timeout(self, value):
"""Deserialize and apply the corresponding query string arg"""
try:
stack_timeout = float(value)
except ValueError as exc:
raise ValueError('Invalid stack_timeout value %r: %r' %
(value, exc,))
self.stack_timeout = stack_timeout
def _set_url_ssl_options(self, value):
"""Deserialize and apply the corresponding query string arg
"""
options = ast.literal_eval(value)
if options is None:
if self.ssl_options is not None:
raise ValueError(
'Specified ssl_options=None URL arg is inconsistent with '
'the specified https URL scheme.')
else:
# Convert options to pika.SSLOptions via ssl.SSLSocket()
sock = socket.socket()
try:
ssl_sock = ssl.SSLSocket(sock=sock, **options)
try:
self.ssl_options = pika.SSLOptions(
context=ssl_sock.context,
server_hostname=ssl_sock.server_hostname)
finally:
ssl_sock.close()
finally:
sock.close()
def _set_url_tcp_options(self, value):
"""Deserialize and apply the corresponding query string arg"""
self.tcp_options = ast.literal_eval(value)
class SSLOptions(object):
"""Class used to provide parameters for optional fine grained control of SSL
socket wrapping.
"""
# Protect against accidental assignment of an invalid attribute
__slots__ = ('context', 'server_hostname')