PageRenderTime 1884ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/pika/connection.py

http://github.com/pika/pika
Python | 2311 lines | 1960 code | 109 blank | 242 comment | 87 complexity | 46aa35f4ce77a37435baf02cb491c79c MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-2.0, MPL-2.0-no-copyleft-exception
  1. """Core connection objects"""
  2. # disable too-many-lines
  3. # pylint: disable=C0302
  4. import abc
  5. import ast
  6. import copy
  7. import functools
  8. import logging
  9. import math
  10. import numbers
  11. import platform
  12. import ssl
  13. import pika.callback
  14. import pika.channel
  15. import pika.compat
  16. import pika.credentials
  17. import pika.exceptions as exceptions
  18. import pika.frame as frame
  19. import pika.heartbeat
  20. import pika.spec as spec
  21. import pika.validators as validators
  22. from pika.compat import (
  23. xrange,
  24. url_unquote,
  25. dictkeys,
  26. dict_itervalues,
  27. dict_iteritems)
  28. PRODUCT = "Pika Python Client Library"
  29. LOGGER = logging.getLogger(__name__)
  30. class Parameters(object): # pylint: disable=R0902
  31. """Base connection parameters class definition
  32. """
  33. # Declare slots to protect against accidental assignment of an invalid
  34. # attribute
  35. __slots__ = ('_blocked_connection_timeout', '_channel_max',
  36. '_client_properties', '_connection_attempts', '_credentials',
  37. '_frame_max', '_heartbeat', '_host', '_locale', '_port',
  38. '_retry_delay', '_socket_timeout', '_stack_timeout',
  39. '_ssl_options', '_virtual_host', '_tcp_options')
  40. DEFAULT_USERNAME = 'guest'
  41. DEFAULT_PASSWORD = 'guest'
  42. DEFAULT_BLOCKED_CONNECTION_TIMEOUT = None
  43. DEFAULT_CHANNEL_MAX = pika.channel.MAX_CHANNELS
  44. DEFAULT_CLIENT_PROPERTIES = None
  45. DEFAULT_CREDENTIALS = pika.credentials.PlainCredentials(
  46. DEFAULT_USERNAME, DEFAULT_PASSWORD)
  47. DEFAULT_CONNECTION_ATTEMPTS = 1
  48. DEFAULT_FRAME_MAX = spec.FRAME_MAX_SIZE
  49. DEFAULT_HEARTBEAT_TIMEOUT = None # None accepts server's proposal
  50. DEFAULT_HOST = 'localhost'
  51. DEFAULT_LOCALE = 'en_US'
  52. DEFAULT_PORT = 5672
  53. DEFAULT_RETRY_DELAY = 2.0
  54. DEFAULT_SOCKET_TIMEOUT = 10.0 # socket.connect() timeout
  55. DEFAULT_STACK_TIMEOUT = 15.0 # full-stack TCP/[SSl]/AMQP bring-up timeout
  56. DEFAULT_SSL = False
  57. DEFAULT_SSL_OPTIONS = None
  58. DEFAULT_SSL_PORT = 5671
  59. DEFAULT_VIRTUAL_HOST = '/'
  60. DEFAULT_TCP_OPTIONS = None
  61. def __init__(self):
  62. # If not None, blocked_connection_timeout is the timeout, in seconds,
  63. # for the connection to remain blocked; if the timeout expires, the
  64. # connection will be torn down, triggering the connection's
  65. # on_close_callback
  66. self._blocked_connection_timeout = None
  67. self.blocked_connection_timeout = (
  68. self.DEFAULT_BLOCKED_CONNECTION_TIMEOUT)
  69. self._channel_max = None
  70. self.channel_max = self.DEFAULT_CHANNEL_MAX
  71. self._client_properties = None
  72. self.client_properties = self.DEFAULT_CLIENT_PROPERTIES
  73. self._connection_attempts = None
  74. self.connection_attempts = self.DEFAULT_CONNECTION_ATTEMPTS
  75. self._credentials = None
  76. self.credentials = self.DEFAULT_CREDENTIALS
  77. self._frame_max = None
  78. self.frame_max = self.DEFAULT_FRAME_MAX
  79. self._heartbeat = None
  80. self.heartbeat = self.DEFAULT_HEARTBEAT_TIMEOUT
  81. self._host = None
  82. self.host = self.DEFAULT_HOST
  83. self._locale = None
  84. self.locale = self.DEFAULT_LOCALE
  85. self._port = None
  86. self.port = self.DEFAULT_PORT
  87. self._retry_delay = None
  88. self.retry_delay = self.DEFAULT_RETRY_DELAY
  89. self._socket_timeout = None
  90. self.socket_timeout = self.DEFAULT_SOCKET_TIMEOUT
  91. self._stack_timeout = None
  92. self.stack_timeout = self.DEFAULT_STACK_TIMEOUT
  93. self._ssl_options = None
  94. self.ssl_options = self.DEFAULT_SSL_OPTIONS
  95. self._virtual_host = None
  96. self.virtual_host = self.DEFAULT_VIRTUAL_HOST
  97. self._tcp_options = None
  98. self.tcp_options = self.DEFAULT_TCP_OPTIONS
  99. def __repr__(self):
  100. """Represent the info about the instance.
  101. :rtype: str
  102. """
  103. return ('<%s host=%s port=%s virtual_host=%s ssl=%s>' %
  104. (self.__class__.__name__, self.host, self.port,
  105. self.virtual_host, bool(self.ssl_options)))
  106. def __eq__(self, other):
  107. if isinstance(other, Parameters):
  108. return self._host == other._host and self._port == other._port # pylint: disable=W0212
  109. return NotImplemented
  110. def __ne__(self, other):
  111. result = self.__eq__(other)
  112. if result is not NotImplemented:
  113. return not result
  114. return NotImplemented
  115. @property
  116. def blocked_connection_timeout(self):
  117. """
  118. :returns: blocked connection timeout. Defaults to
  119. `DEFAULT_BLOCKED_CONNECTION_TIMEOUT`.
  120. :rtype: float|None
  121. """
  122. return self._blocked_connection_timeout
  123. @blocked_connection_timeout.setter
  124. def blocked_connection_timeout(self, value):
  125. """
  126. :param value: If not None, blocked_connection_timeout is the timeout, in
  127. seconds, for the connection to remain blocked; if the timeout
  128. expires, the connection will be torn down, triggering the
  129. connection's on_close_callback
  130. """
  131. if value is not None:
  132. if not isinstance(value, numbers.Real):
  133. raise TypeError('blocked_connection_timeout must be a Real '
  134. 'number, but got %r' % (value,))
  135. if value < 0:
  136. raise ValueError('blocked_connection_timeout must be >= 0, but '
  137. 'got %r' % (value,))
  138. self._blocked_connection_timeout = value
  139. @property
  140. def channel_max(self):
  141. """
  142. :returns: max preferred number of channels. Defaults to
  143. `DEFAULT_CHANNEL_MAX`.
  144. :rtype: int
  145. """
  146. return self._channel_max
  147. @channel_max.setter
  148. def channel_max(self, value):
  149. """
  150. :param int value: max preferred number of channels, between 1 and
  151. `channel.MAX_CHANNELS`, inclusive
  152. """
  153. if not isinstance(value, numbers.Integral):
  154. raise TypeError('channel_max must be an int, but got %r' % (value,))
  155. if value < 1 or value > pika.channel.MAX_CHANNELS:
  156. raise ValueError('channel_max must be <= %i and > 0, but got %r' %
  157. (pika.channel.MAX_CHANNELS, value))
  158. self._channel_max = value
  159. @property
  160. def client_properties(self):
  161. """
  162. :returns: client properties used to override the fields in the default
  163. client properties reported to RabbitMQ via `Connection.StartOk`
  164. method. Defaults to `DEFAULT_CLIENT_PROPERTIES`.
  165. :rtype: dict|None
  166. """
  167. return self._client_properties
  168. @client_properties.setter
  169. def client_properties(self, value):
  170. """
  171. :param value: None or dict of client properties used to override the
  172. fields in the default client properties reported to RabbitMQ via
  173. `Connection.StartOk` method.
  174. """
  175. if not isinstance(value, (
  176. dict,
  177. type(None),
  178. )):
  179. raise TypeError('client_properties must be dict or None, '
  180. 'but got %r' % (value,))
  181. # Copy the mutable object to avoid accidental side-effects
  182. self._client_properties = copy.deepcopy(value)
  183. @property
  184. def connection_attempts(self):
  185. """
  186. :returns: number of socket connection attempts. Defaults to
  187. `DEFAULT_CONNECTION_ATTEMPTS`. See also `retry_delay`.
  188. :rtype: int
  189. """
  190. return self._connection_attempts
  191. @connection_attempts.setter
  192. def connection_attempts(self, value):
  193. """
  194. :param int value: number of socket connection attempts of at least 1.
  195. See also `retry_delay`.
  196. """
  197. if not isinstance(value, numbers.Integral):
  198. raise TypeError('connection_attempts must be an int')
  199. if value < 1:
  200. raise ValueError(
  201. 'connection_attempts must be > 0, but got %r' % (value,))
  202. self._connection_attempts = value
  203. @property
  204. def credentials(self):
  205. """
  206. :rtype: one of the classes from `pika.credentials.VALID_TYPES`. Defaults
  207. to `DEFAULT_CREDENTIALS`.
  208. """
  209. return self._credentials
  210. @credentials.setter
  211. def credentials(self, value):
  212. """
  213. :param value: authentication credential object of one of the classes
  214. from `pika.credentials.VALID_TYPES`
  215. """
  216. if not isinstance(value, tuple(pika.credentials.VALID_TYPES)):
  217. raise TypeError('credentials must be an object of type: %r, but '
  218. 'got %r' % (pika.credentials.VALID_TYPES, value))
  219. # Copy the mutable object to avoid accidental side-effects
  220. self._credentials = copy.deepcopy(value)
  221. @property
  222. def frame_max(self):
  223. """
  224. :returns: desired maximum AMQP frame size to use. Defaults to
  225. `DEFAULT_FRAME_MAX`.
  226. :rtype: int
  227. """
  228. return self._frame_max
  229. @frame_max.setter
  230. def frame_max(self, value):
  231. """
  232. :param int value: desired maximum AMQP frame size to use between
  233. `spec.FRAME_MIN_SIZE` and `spec.FRAME_MAX_SIZE`, inclusive
  234. """
  235. if not isinstance(value, numbers.Integral):
  236. raise TypeError('frame_max must be an int, but got %r' % (value,))
  237. if value < spec.FRAME_MIN_SIZE:
  238. raise ValueError('Min AMQP 0.9.1 Frame Size is %i, but got %r' % (
  239. spec.FRAME_MIN_SIZE,
  240. value,
  241. ))
  242. elif value > spec.FRAME_MAX_SIZE:
  243. raise ValueError('Max AMQP 0.9.1 Frame Size is %i, but got %r' % (
  244. spec.FRAME_MAX_SIZE,
  245. value,
  246. ))
  247. self._frame_max = value
  248. @property
  249. def heartbeat(self):
  250. """
  251. :returns: AMQP connection heartbeat timeout value for negotiation during
  252. connection tuning or callable which is invoked during connection tuning.
  253. None to accept broker's value. 0 turns heartbeat off. Defaults to
  254. `DEFAULT_HEARTBEAT_TIMEOUT`.
  255. :rtype: int|callable|None
  256. """
  257. return self._heartbeat
  258. @heartbeat.setter
  259. def heartbeat(self, value):
  260. """
  261. :param int|None|callable value: Controls AMQP heartbeat timeout negotiation
  262. during connection tuning. An integer value always overrides the value
  263. proposed by broker. Use 0 to deactivate heartbeats and None to always
  264. accept the broker's proposal. If a callable is given, it will be called
  265. with the connection instance and the heartbeat timeout proposed by broker
  266. as its arguments. The callback should return a non-negative integer that
  267. will be used to override the broker's proposal.
  268. """
  269. if value is not None:
  270. if not isinstance(value, numbers.Integral) and not callable(value):
  271. raise TypeError(
  272. 'heartbeat must be an int or a callable function, but got %r'
  273. % (value,))
  274. if not callable(value) and value < 0:
  275. raise ValueError('heartbeat must >= 0, but got %r' % (value,))
  276. self._heartbeat = value
  277. @property
  278. def host(self):
  279. """
  280. :returns: hostname or ip address of broker. Defaults to `DEFAULT_HOST`.
  281. :rtype: str
  282. """
  283. return self._host
  284. @host.setter
  285. def host(self, value):
  286. """
  287. :param str value: hostname or ip address of broker
  288. """
  289. validators.require_string(value, 'host')
  290. self._host = value
  291. @property
  292. def locale(self):
  293. """
  294. :returns: locale value to pass to broker; e.g., 'en_US'. Defaults to
  295. `DEFAULT_LOCALE`.
  296. :rtype: str
  297. """
  298. return self._locale
  299. @locale.setter
  300. def locale(self, value):
  301. """
  302. :param str value: locale value to pass to broker; e.g., "en_US"
  303. """
  304. validators.require_string(value, 'locale')
  305. self._locale = value
  306. @property
  307. def port(self):
  308. """
  309. :returns: port number of broker's listening socket. Defaults to
  310. `DEFAULT_PORT`.
  311. :rtype: int
  312. """
  313. return self._port
  314. @port.setter
  315. def port(self, value):
  316. """
  317. :param int value: port number of broker's listening socket
  318. """
  319. try:
  320. self._port = int(value)
  321. except (TypeError, ValueError):
  322. raise TypeError('port must be an int, but got %r' % (value,))
  323. @property
  324. def retry_delay(self):
  325. """
  326. :returns: interval between socket connection attempts; see also
  327. `connection_attempts`. Defaults to `DEFAULT_RETRY_DELAY`.
  328. :rtype: float
  329. """
  330. return self._retry_delay
  331. @retry_delay.setter
  332. def retry_delay(self, value):
  333. """
  334. :param int | float value: interval between socket connection attempts;
  335. see also `connection_attempts`.
  336. """
  337. if not isinstance(value, numbers.Real):
  338. raise TypeError(
  339. 'retry_delay must be a float or int, but got %r' % (value,))
  340. self._retry_delay = value
  341. @property
  342. def socket_timeout(self):
  343. """
  344. :returns: socket connect timeout in seconds. Defaults to
  345. `DEFAULT_SOCKET_TIMEOUT`. The value None disables this timeout.
  346. :rtype: float|None
  347. """
  348. return self._socket_timeout
  349. @socket_timeout.setter
  350. def socket_timeout(self, value):
  351. """
  352. :param int | float | None value: positive socket connect timeout in
  353. seconds. None to disable this timeout.
  354. """
  355. if value is not None:
  356. if not isinstance(value, numbers.Real):
  357. raise TypeError('socket_timeout must be a float or int, '
  358. 'but got %r' % (value,))
  359. if value <= 0:
  360. raise ValueError(
  361. 'socket_timeout must be > 0, but got %r' % (value,))
  362. value = float(value)
  363. self._socket_timeout = value
  364. @property
  365. def stack_timeout(self):
  366. """
  367. :returns: full protocol stack TCP/[SSL]/AMQP bring-up timeout in
  368. seconds. Defaults to `DEFAULT_STACK_TIMEOUT`. The value None
  369. disables this timeout.
  370. :rtype: float
  371. """
  372. return self._stack_timeout
  373. @stack_timeout.setter
  374. def stack_timeout(self, value):
  375. """
  376. :param int | float | None value: positive full protocol stack
  377. TCP/[SSL]/AMQP bring-up timeout in seconds. It's recommended to set
  378. this value higher than `socket_timeout`. None to disable this
  379. timeout.
  380. """
  381. if value is not None:
  382. if not isinstance(value, numbers.Real):
  383. raise TypeError('stack_timeout must be a float or int, '
  384. 'but got %r' % (value,))
  385. if value <= 0:
  386. raise ValueError(
  387. 'stack_timeout must be > 0, but got %r' % (value,))
  388. value = float(value)
  389. self._stack_timeout = value
  390. @property
  391. def ssl_options(self):
  392. """
  393. :returns: None for plaintext or `pika.SSLOptions` instance for SSL/TLS.
  394. :rtype: `pika.SSLOptions`|None
  395. """
  396. return self._ssl_options
  397. @ssl_options.setter
  398. def ssl_options(self, value):
  399. """
  400. :param `pika.SSLOptions`|None value: None for plaintext or
  401. `pika.SSLOptions` instance for SSL/TLS. Defaults to None.
  402. """
  403. if not isinstance(value, (SSLOptions, type(None))):
  404. raise TypeError(
  405. 'ssl_options must be None or SSLOptions but got %r' % (value,))
  406. self._ssl_options = value
  407. @property
  408. def virtual_host(self):
  409. """
  410. :returns: rabbitmq virtual host name. Defaults to
  411. `DEFAULT_VIRTUAL_HOST`.
  412. :rtype: str
  413. """
  414. return self._virtual_host
  415. @virtual_host.setter
  416. def virtual_host(self, value):
  417. """
  418. :param str value: rabbitmq virtual host name
  419. """
  420. validators.require_string(value, 'virtual_host')
  421. self._virtual_host = value
  422. @property
  423. def tcp_options(self):
  424. """
  425. :returns: None or a dict of options to pass to the underlying socket
  426. :rtype: dict|None
  427. """
  428. return self._tcp_options
  429. @tcp_options.setter
  430. def tcp_options(self, value):
  431. """
  432. :param dict|None value: None or a dict of options to pass to the underlying
  433. socket. Currently supported are TCP_KEEPIDLE, TCP_KEEPINTVL, TCP_KEEPCNT
  434. and TCP_USER_TIMEOUT. Availability of these may depend on your platform.
  435. """
  436. if not isinstance(value, (dict, type(None))):
  437. raise TypeError(
  438. 'tcp_options must be a dict or None, but got %r' % (value,))
  439. self._tcp_options = value
  440. class ConnectionParameters(Parameters):
  441. """Connection parameters object that is passed into the connection adapter
  442. upon construction.
  443. """
  444. # Protect against accidental assignment of an invalid attribute
  445. __slots__ = ()
  446. class _DEFAULT(object):
  447. """Designates default parameter value; internal use"""
  448. def __init__( # pylint: disable=R0913,R0914
  449. self,
  450. host=_DEFAULT,
  451. port=_DEFAULT,
  452. virtual_host=_DEFAULT,
  453. credentials=_DEFAULT,
  454. channel_max=_DEFAULT,
  455. frame_max=_DEFAULT,
  456. heartbeat=_DEFAULT,
  457. ssl_options=_DEFAULT,
  458. connection_attempts=_DEFAULT,
  459. retry_delay=_DEFAULT,
  460. socket_timeout=_DEFAULT,
  461. stack_timeout=_DEFAULT,
  462. locale=_DEFAULT,
  463. blocked_connection_timeout=_DEFAULT,
  464. client_properties=_DEFAULT,
  465. tcp_options=_DEFAULT,
  466. **kwargs):
  467. """Create a new ConnectionParameters instance. See `Parameters` for
  468. default values.
  469. :param str host: Hostname or IP Address to connect to
  470. :param int port: TCP port to connect to
  471. :param str virtual_host: RabbitMQ virtual host to use
  472. :param pika.credentials.Credentials credentials: auth credentials
  473. :param int channel_max: Maximum number of channels to allow
  474. :param int frame_max: The maximum byte size for an AMQP frame
  475. :param int|None|callable heartbeat: Controls AMQP heartbeat timeout negotiation
  476. during connection tuning. An integer value always overrides the value
  477. proposed by broker. Use 0 to deactivate heartbeats and None to always
  478. accept the broker's proposal. If a callable is given, it will be called
  479. with the connection instance and the heartbeat timeout proposed by broker
  480. as its arguments. The callback should return a non-negative integer that
  481. will be used to override the broker's proposal.
  482. :param `pika.SSLOptions`|None ssl_options: None for plaintext or
  483. `pika.SSLOptions` instance for SSL/TLS. Defaults to None.
  484. :param int connection_attempts: Maximum number of retry attempts
  485. :param int|float retry_delay: Time to wait in seconds, before the next
  486. :param int|float socket_timeout: Positive socket connect timeout in
  487. seconds.
  488. :param int|float stack_timeout: Positive full protocol stack
  489. (TCP/[SSL]/AMQP) bring-up timeout in seconds. It's recommended to
  490. set this value higher than `socket_timeout`.
  491. :param str locale: Set the locale value
  492. :param int|float|None blocked_connection_timeout: If not None,
  493. the value is a non-negative timeout, in seconds, for the
  494. connection to remain blocked (triggered by Connection.Blocked from
  495. broker); if the timeout expires before connection becomes unblocked,
  496. the connection will be torn down, triggering the adapter-specific
  497. mechanism for informing client app about the closed connection:
  498. passing `ConnectionBlockedTimeout` exception to on_close_callback
  499. in asynchronous adapters or raising it in `BlockingConnection`.
  500. :param client_properties: None or dict of client properties used to
  501. override the fields in the default client properties reported to
  502. RabbitMQ via `Connection.StartOk` method.
  503. :param tcp_options: None or a dict of TCP options to set for socket
  504. """
  505. super(ConnectionParameters, self).__init__()
  506. if blocked_connection_timeout is not self._DEFAULT:
  507. self.blocked_connection_timeout = blocked_connection_timeout
  508. if channel_max is not self._DEFAULT:
  509. self.channel_max = channel_max
  510. if client_properties is not self._DEFAULT:
  511. self.client_properties = client_properties
  512. if connection_attempts is not self._DEFAULT:
  513. self.connection_attempts = connection_attempts
  514. if credentials is not self._DEFAULT:
  515. self.credentials = credentials
  516. if frame_max is not self._DEFAULT:
  517. self.frame_max = frame_max
  518. if heartbeat is not self._DEFAULT:
  519. self.heartbeat = heartbeat
  520. if host is not self._DEFAULT:
  521. self.host = host
  522. if locale is not self._DEFAULT:
  523. self.locale = locale
  524. if retry_delay is not self._DEFAULT:
  525. self.retry_delay = retry_delay
  526. if socket_timeout is not self._DEFAULT:
  527. self.socket_timeout = socket_timeout
  528. if stack_timeout is not self._DEFAULT:
  529. self.stack_timeout = stack_timeout
  530. if ssl_options is not self._DEFAULT:
  531. self.ssl_options = ssl_options
  532. # Set port after SSL status is known
  533. if port is not self._DEFAULT:
  534. self.port = port
  535. else:
  536. self.port = self.DEFAULT_SSL_PORT if self.ssl_options else self.DEFAULT_PORT
  537. if virtual_host is not self._DEFAULT:
  538. self.virtual_host = virtual_host
  539. if tcp_options is not self._DEFAULT:
  540. self.tcp_options = tcp_options
  541. if kwargs:
  542. raise TypeError('unexpected kwargs: %r' % (kwargs,))
  543. class URLParameters(Parameters):
  544. """Connect to RabbitMQ via an AMQP URL in the format::
  545. amqp://username:password@host:port/<virtual_host>[?query-string]
  546. Ensure that the virtual host is URI encoded when specified. For example if
  547. you are using the default "/" virtual host, the value should be `%2f`.
  548. See `Parameters` for default values.
  549. Valid query string values are:
  550. - channel_max:
  551. Override the default maximum channel count value
  552. - client_properties:
  553. dict of client properties used to override the fields in the default
  554. client properties reported to RabbitMQ via `Connection.StartOk`
  555. method
  556. - connection_attempts:
  557. Specify how many times pika should try and reconnect before it gives up
  558. - frame_max:
  559. Override the default maximum frame size for communication
  560. - heartbeat:
  561. Desired connection heartbeat timeout for negotiation. If not present
  562. the broker's value is accepted. 0 turns heartbeat off.
  563. - locale:
  564. Override the default `en_US` locale value
  565. - ssl_options:
  566. None for plaintext; for SSL: dict of public ssl context-related
  567. arguments that may be passed to :meth:`ssl.SSLSocket` as kwargs,
  568. except `sock`, `server_side`,`do_handshake_on_connect`, `family`,
  569. `type`, `proto`, `fileno`.
  570. - retry_delay:
  571. The number of seconds to sleep before attempting to connect on
  572. connection failure.
  573. - socket_timeout:
  574. Socket connect timeout value in seconds (float or int)
  575. - stack_timeout:
  576. Positive full protocol stack (TCP/[SSL]/AMQP) bring-up timeout in
  577. seconds. It's recommended to set this value higher than
  578. `socket_timeout`.
  579. - blocked_connection_timeout:
  580. Set the timeout, in seconds, that the connection may remain blocked
  581. (triggered by Connection.Blocked from broker); if the timeout
  582. expires before connection becomes unblocked, the connection will be
  583. torn down, triggering the connection's on_close_callback
  584. - tcp_options:
  585. Set the tcp options for the underlying socket.
  586. :param str url: The AMQP URL to connect to
  587. """
  588. # Protect against accidental assignment of an invalid attribute
  589. __slots__ = ('_all_url_query_values',)
  590. # The name of the private function for parsing and setting a given URL query
  591. # arg is constructed by catenating the query arg's name to this prefix
  592. _SETTER_PREFIX = '_set_url_'
  593. def __init__(self, url):
  594. """Create a new URLParameters instance.
  595. :param str url: The URL value
  596. """
  597. super(URLParameters, self).__init__()
  598. self._all_url_query_values = None
  599. # Handle the Protocol scheme
  600. #
  601. # Fix up scheme amqp(s) to http(s) so urlparse won't barf on python
  602. # prior to 2.7. On Python 2.6.9,
  603. # `urlparse('amqp://127.0.0.1/%2f?socket_timeout=1')` produces an
  604. # incorrect path='/%2f?socket_timeout=1'
  605. if url[0:4].lower() == 'amqp':
  606. url = 'http' + url[4:]
  607. parts = pika.compat.urlparse(url)
  608. if parts.scheme == 'https':
  609. # Create default context which will get overridden by the
  610. # ssl_options URL arg, if any
  611. self.ssl_options = pika.SSLOptions(
  612. context=ssl.create_default_context())
  613. elif parts.scheme == 'http':
  614. self.ssl_options = None
  615. elif parts.scheme:
  616. raise ValueError('Unexpected URL scheme %r; supported scheme '
  617. 'values: amqp, amqps' % (parts.scheme,))
  618. if parts.hostname is not None:
  619. self.host = parts.hostname
  620. # Take care of port after SSL status is known
  621. if parts.port is not None:
  622. self.port = parts.port
  623. else:
  624. self.port = (self.DEFAULT_SSL_PORT
  625. if self.ssl_options else self.DEFAULT_PORT)
  626. if parts.username is not None:
  627. self.credentials = pika.credentials.PlainCredentials(
  628. url_unquote(parts.username), url_unquote(parts.password))
  629. # Get the Virtual Host
  630. if len(parts.path) > 1:
  631. self.virtual_host = url_unquote(parts.path.split('/')[1])
  632. # Handle query string values, validating and assigning them
  633. self._all_url_query_values = pika.compat.url_parse_qs(parts.query)
  634. for name, value in dict_iteritems(self._all_url_query_values):
  635. try:
  636. set_value = getattr(self, self._SETTER_PREFIX + name)
  637. except AttributeError:
  638. raise ValueError('Unknown URL parameter: %r' % (name,))
  639. try:
  640. (value,) = value
  641. except ValueError:
  642. raise ValueError(
  643. 'Expected exactly one value for URL parameter '
  644. '%s, but got %i values: %s' % (name, len(value), value))
  645. set_value(value)
  646. def _set_url_blocked_connection_timeout(self, value):
  647. """Deserialize and apply the corresponding query string arg"""
  648. try:
  649. blocked_connection_timeout = float(value)
  650. except ValueError as exc:
  651. raise ValueError(
  652. 'Invalid blocked_connection_timeout value %r: %r' % (
  653. value,
  654. exc,
  655. ))
  656. self.blocked_connection_timeout = blocked_connection_timeout
  657. def _set_url_channel_max(self, value):
  658. """Deserialize and apply the corresponding query string arg"""
  659. try:
  660. channel_max = int(value)
  661. except ValueError as exc:
  662. raise ValueError('Invalid channel_max value %r: %r' % (
  663. value,
  664. exc,
  665. ))
  666. self.channel_max = channel_max
  667. def _set_url_client_properties(self, value):
  668. """Deserialize and apply the corresponding query string arg"""
  669. self.client_properties = ast.literal_eval(value)
  670. def _set_url_connection_attempts(self, value):
  671. """Deserialize and apply the corresponding query string arg"""
  672. try:
  673. connection_attempts = int(value)
  674. except ValueError as exc:
  675. raise ValueError('Invalid connection_attempts value %r: %r' % (
  676. value,
  677. exc,
  678. ))
  679. self.connection_attempts = connection_attempts
  680. def _set_url_frame_max(self, value):
  681. """Deserialize and apply the corresponding query string arg"""
  682. try:
  683. frame_max = int(value)
  684. except ValueError as exc:
  685. raise ValueError('Invalid frame_max value %r: %r' % (
  686. value,
  687. exc,
  688. ))
  689. self.frame_max = frame_max
  690. def _set_url_heartbeat(self, value):
  691. """Deserialize and apply the corresponding query string arg"""
  692. try:
  693. heartbeat_timeout = int(value)
  694. except ValueError as exc:
  695. raise ValueError('Invalid heartbeat value %r: %r' % (
  696. value,
  697. exc,
  698. ))
  699. self.heartbeat = heartbeat_timeout
  700. def _set_url_locale(self, value):
  701. """Deserialize and apply the corresponding query string arg"""
  702. self.locale = value
  703. def _set_url_retry_delay(self, value):
  704. """Deserialize and apply the corresponding query string arg"""
  705. try:
  706. retry_delay = float(value)
  707. except ValueError as exc:
  708. raise ValueError('Invalid retry_delay value %r: %r' % (
  709. value,
  710. exc,
  711. ))
  712. self.retry_delay = retry_delay
  713. def _set_url_socket_timeout(self, value):
  714. """Deserialize and apply the corresponding query string arg"""
  715. try:
  716. socket_timeout = float(value)
  717. except ValueError as exc:
  718. raise ValueError('Invalid socket_timeout value %r: %r' % (
  719. value,
  720. exc,
  721. ))
  722. self.socket_timeout = socket_timeout
  723. def _set_url_stack_timeout(self, value):
  724. """Deserialize and apply the corresponding query string arg"""
  725. try:
  726. stack_timeout = float(value)
  727. except ValueError as exc:
  728. raise ValueError('Invalid stack_timeout value %r: %r' % (
  729. value,
  730. exc,
  731. ))
  732. self.stack_timeout = stack_timeout
  733. def _set_url_ssl_options(self, value):
  734. """Deserialize and apply the corresponding query string arg
  735. """
  736. opts = ast.literal_eval(value)
  737. if opts is None:
  738. if self.ssl_options is not None:
  739. raise ValueError(
  740. 'Specified ssl_options=None URL arg is inconsistent with '
  741. 'the specified https URL scheme.')
  742. else:
  743. # Older versions of Pika would take the opts dict and pass it
  744. # directly as kwargs to the deprecated ssl.wrap_socket method.
  745. # Here, we take the valid options and translate them into args
  746. # for various SSLContext methods.
  747. #
  748. # https://docs.python.org/3/library/ssl.html#ssl.wrap_socket
  749. #
  750. # SSLContext.load_verify_locations(cafile=None, capath=None, cadata=None)
  751. try:
  752. opt_protocol = ssl.PROTOCOL_TLS
  753. except AttributeError:
  754. opt_protocol = ssl.PROTOCOL_TLSv1
  755. if 'protocol' in opts:
  756. opt_protocol = opts['protocol']
  757. cxt = ssl.SSLContext(protocol=opt_protocol)
  758. opt_cafile = opts.get('ca_certs') or opts.get('cafile')
  759. opt_capath = opts.get('ca_path') or opts.get('capath')
  760. opt_cadata = opts.get('ca_data') or opts.get('cadata')
  761. cxt.load_verify_locations(opt_cafile, opt_capath, opt_cadata)
  762. # SSLContext.load_cert_chain(certfile, keyfile=None, password=None)
  763. if 'certfile' in opts:
  764. opt_certfile = opts['certfile']
  765. opt_keyfile = opts.get('keyfile')
  766. opt_password = opts.get('password')
  767. cxt.load_cert_chain(opt_certfile, opt_keyfile, opt_password)
  768. if 'ciphers' in opts:
  769. opt_ciphers = opts['ciphers']
  770. cxt.set_ciphers(opt_ciphers)
  771. server_hostname = opts.get('server_hostname')
  772. self.ssl_options = pika.SSLOptions(
  773. context=cxt, server_hostname=server_hostname)
  774. def _set_url_tcp_options(self, value):
  775. """Deserialize and apply the corresponding query string arg"""
  776. self.tcp_options = ast.literal_eval(value)
  777. class SSLOptions(object):
  778. """Class used to provide parameters for optional fine grained control of SSL
  779. socket wrapping.
  780. """
  781. # Protect against accidental assignment of an invalid attribute
  782. __slots__ = ('context', 'server_hostname')
  783. def __init__(self, context, server_hostname=None):
  784. """
  785. :param ssl.SSLContext context: SSLContext instance
  786. :param str|None server_hostname: SSLContext.wrap_socket, used to enable
  787. SNI
  788. """
  789. if not isinstance(context, ssl.SSLContext):
  790. raise TypeError(
  791. 'context must be of ssl.SSLContext type, but got {!r}'.format(
  792. context))
  793. self.context = context
  794. self.server_hostname = server_hostname
  795. class Connection(pika.compat.AbstractBase):
  796. """This is the core class that implements communication with RabbitMQ. This
  797. class should not be invoked directly but rather through the use of an
  798. adapter such as SelectConnection or BlockingConnection.
  799. """
  800. # Disable pylint messages concerning "method could be a funciton"
  801. # pylint: disable=R0201
  802. ON_CONNECTION_CLOSED = '_on_connection_closed'
  803. ON_CONNECTION_ERROR = '_on_connection_error'
  804. ON_CONNECTION_OPEN_OK = '_on_connection_open_ok'
  805. CONNECTION_CLOSED = 0
  806. CONNECTION_INIT = 1
  807. CONNECTION_PROTOCOL = 2
  808. CONNECTION_START = 3
  809. CONNECTION_TUNE = 4
  810. CONNECTION_OPEN = 5
  811. CONNECTION_CLOSING = 6 # client-initiated close in progress
  812. _STATE_NAMES = {
  813. CONNECTION_CLOSED: 'CLOSED',
  814. CONNECTION_INIT: 'INIT',
  815. CONNECTION_PROTOCOL: 'PROTOCOL',
  816. CONNECTION_START: 'START',
  817. CONNECTION_TUNE: 'TUNE',
  818. CONNECTION_OPEN: 'OPEN',
  819. CONNECTION_CLOSING: 'CLOSING'
  820. }
  821. def __init__(self,
  822. parameters=None,
  823. on_open_callback=None,
  824. on_open_error_callback=None,
  825. on_close_callback=None,
  826. internal_connection_workflow=True):
  827. """Connection initialization expects an object that has implemented the
  828. Parameters class and a callback function to notify when we have
  829. successfully connected to the AMQP Broker.
  830. Available Parameters classes are the ConnectionParameters class and
  831. URLParameters class.
  832. :param pika.connection.Parameters parameters: Read-only connection
  833. parameters.
  834. :param callable on_open_callback: Called when the connection is opened:
  835. on_open_callback(connection)
  836. :param None | method on_open_error_callback: Called if the connection
  837. can't be established or connection establishment is interrupted by
  838. `Connection.close()`: on_open_error_callback(Connection, exception).
  839. :param None | method on_close_callback: Called when a previously fully
  840. open connection is closed:
  841. `on_close_callback(Connection, exception)`, where `exception` is
  842. either an instance of `exceptions.ConnectionClosed` if closed by
  843. user or broker or exception of another type that describes the cause
  844. of connection failure.
  845. :param bool internal_connection_workflow: True for autonomous connection
  846. establishment which is default; False for externally-managed
  847. connection workflow via the `create_connection()` factory.
  848. """
  849. self.connection_state = self.CONNECTION_CLOSED
  850. # Determines whether we invoke the on_open_error_callback or
  851. # on_close_callback. So that we don't lose track when state transitions
  852. # to CONNECTION_CLOSING as the result of Connection.close() call during
  853. # opening.
  854. self._opened = False
  855. # Value to pass to on_open_error_callback or on_close_callback when
  856. # connection fails to be established or becomes closed
  857. self._error = None # type: Exception
  858. # Used to hold timer if configured for Connection.Blocked timeout
  859. self._blocked_conn_timer = None
  860. self._heartbeat_checker = None
  861. # Set our configuration options
  862. if parameters is not None:
  863. # NOTE: Work around inability to copy ssl.SSLContext contained in
  864. # our SSLOptions; ssl.SSLContext fails to implement __getnewargs__
  865. saved_ssl_options = parameters.ssl_options
  866. parameters.ssl_options = None
  867. try:
  868. self.params = copy.deepcopy(parameters)
  869. self.params.ssl_options = saved_ssl_options
  870. finally:
  871. parameters.ssl_options = saved_ssl_options
  872. else:
  873. self.params = ConnectionParameters()
  874. self._internal_connection_workflow = internal_connection_workflow
  875. # Define our callback dictionary
  876. self.callbacks = pika.callback.CallbackManager()
  877. # Attributes that will be properly initialized by _init_connection_state
  878. # and/or during connection handshake.
  879. self.server_capabilities = None
  880. self.server_properties = None
  881. self._body_max_length = None
  882. self.known_hosts = None
  883. self._frame_buffer = None
  884. self._channels = None
  885. self._init_connection_state()
  886. # Add the on connection error callback
  887. self.callbacks.add(
  888. 0, self.ON_CONNECTION_ERROR, on_open_error_callback or
  889. self._default_on_connection_error, False)
  890. # On connection callback
  891. if on_open_callback:
  892. self.add_on_open_callback(on_open_callback)
  893. # On connection callback
  894. if on_close_callback:
  895. self.add_on_close_callback(on_close_callback)
  896. self._set_connection_state(self.CONNECTION_INIT)
  897. if self._internal_connection_workflow:
  898. # Kick off full-stack connection establishment. It will complete
  899. # asynchronously.
  900. self._adapter_connect_stream()
  901. else:
  902. # Externally-managed connection workflow will proceed asynchronously
  903. # using adapter-specific mechanism
  904. LOGGER.debug('Using external connection workflow.')
  905. def _init_connection_state(self):
  906. """Initialize or reset all of the internal state variables for a given
  907. connection. On disconnect or reconnect all of the state needs to
  908. be wiped.
  909. """
  910. # TODO: probably don't need the state recovery logic since we don't
  911. # test re-connection sufficiently (if at all), and users should
  912. # just create a new instance of Connection when needed.
  913. # So, just merge the pertinent logic into the constructor.
  914. # Connection state
  915. self._set_connection_state(self.CONNECTION_CLOSED)
  916. # Negotiated server properties
  917. self.server_properties = None
  918. # Inbound buffer for decoding frames
  919. self._frame_buffer = bytes()
  920. # Dict of open channels
  921. self._channels = dict()
  922. # Data used for Heartbeat checking and back-pressure detection
  923. self.bytes_sent = 0
  924. self.bytes_received = 0
  925. self.frames_sent = 0
  926. self.frames_received = 0
  927. self._heartbeat_checker = None
  928. # When closing, holds reason why
  929. self._error = None
  930. # Our starting point once connected, first frame received
  931. self._add_connection_start_callback()
  932. # Add a callback handler for the Broker telling us to disconnect.
  933. # NOTE: As of RabbitMQ 3.6.0, RabbitMQ broker may send Connection.Close
  934. # to signal error during connection setup (and wait a longish time
  935. # before closing the TCP/IP stream). Earlier RabbitMQ versions
  936. # simply closed the TCP/IP stream.
  937. self.callbacks.add(0, spec.Connection.Close,
  938. self._on_connection_close_from_broker)
  939. if self.params.blocked_connection_timeout is not None:
  940. if self._blocked_conn_timer is not None:
  941. # Blocked connection timer was active when teardown was
  942. # initiated
  943. self._adapter_remove_timeout(self._blocked_conn_timer)
  944. self._blocked_conn_timer = None
  945. self.add_on_connection_blocked_callback(self._on_connection_blocked)
  946. self.add_on_connection_unblocked_callback(
  947. self._on_connection_unblocked)
  948. def add_on_close_callback(self, callback):
  949. """Add a callback notification when the connection has closed. The
  950. callback will be passed the connection and an exception instance. The
  951. exception will either be an instance of `exceptions.ConnectionClosed` if
  952. a fully-open connection was closed by user or broker or exception of
  953. another type that describes the cause of connection closure/failure.
  954. :param callable callback: Callback to call on close, having the signature:
  955. callback(pika.connection.Connection, exception)
  956. """
  957. validators.require_callback(callback)
  958. self.callbacks.add(0, self.ON_CONNECTION_CLOSED, callback, False)
  959. def add_on_connection_blocked_callback(self, callback):
  960. """RabbitMQ AMQP extension - Add a callback to be notified when the
  961. connection gets blocked (`Connection.Blocked` received from RabbitMQ)
  962. due to the broker running low on resources (memory or disk). In this
  963. state RabbitMQ suspends processing incoming data until the connection
  964. is unblocked, so it's a good idea for publishers receiving this
  965. notification to suspend publishing until the connection becomes
  966. unblocked.
  967. See also `Connection.add_on_connection_unblocked_callback()`
  968. See also `ConnectionParameters.blocked_connection_timeout`.
  969. :param callable callback: Callback to call on `Connection.Blocked`,
  970. having the signature `callback(connection, pika.frame.Method)`,
  971. where the method frame's `method` member is of type
  972. `pika.spec.Connection.Blocked`
  973. """
  974. validators.require_callback(callback)
  975. self.callbacks.add(
  976. 0,
  977. spec.Connection.Blocked,
  978. functools.partial(callback, self),
  979. one_shot=False)
  980. def add_on_connection_unblocked_callback(self, callback):
  981. """RabbitMQ AMQP extension - Add a callback to be notified when the
  982. connection gets unblocked (`Connection.Unblocked` frame is received from
  983. RabbitMQ) letting publishers know it's ok to start publishing again.
  984. :param callable callback: Callback to call on
  985. `Connection.Unblocked`, having the signature
  986. `callback(connection, pika.frame.Method)`, where the method frame's
  987. `method` member is of type `pika.spec.Connection.Unblocked`
  988. """
  989. validators.require_callback(callback)
  990. self.callbacks.add(
  991. 0,
  992. spec.Connection.Unblocked,
  993. functools.partial(callback, self),
  994. one_shot=False)
  995. def add_on_open_callback(self, callback):
  996. """Add a callback notification when the connection has opened. The
  997. callback will be passed the connection instance as its only arg.
  998. :param callable callback: Callback to call when open
  999. """
  1000. validators.require_callback(callback)
  1001. self.callbacks.add(0, self.ON_CONNECTION_OPEN_OK, callback, False)
  1002. def add_on_open_error_callback(self, callback, remove_default=True):
  1003. """Add a callback notification when the connection can not be opened.
  1004. The callback method should accept the connection instance that could not
  1005. connect, and either a string or an exception as its second arg.
  1006. :param callable callback: Callback to call when can't connect, having
  1007. the signature _(Connection, Exception)
  1008. :param bool remove_default: Remove default exception raising callback
  1009. """
  1010. validators.require_callback(callback)
  1011. if remove_default:
  1012. self.callbacks.remove(0, self.ON_CONNECTION_ERROR,
  1013. self._default_on_connection_error)
  1014. self.callbacks.add(0, self.ON_CONNECTION_ERROR, callback, False)
  1015. def channel(self, channel_number=None, on_open_callback=None):
  1016. """Create a new channel with the next available channel number or pass
  1017. in a channel number to use. Must be non-zero if you would like to
  1018. specify but it is recommended that you let Pika manage the channel
  1019. numbers.
  1020. :param int channel_number: The channel number to use, defaults to the
  1021. next available.
  1022. :param callable on_open_callback: The callback when the channel is
  1023. opened. The callback will be invoked with the `Channel` instance
  1024. as its only argument.
  1025. :rtype: pika.channel.Channel
  1026. """
  1027. if not self.is_open:
  1028. raise exceptions.ConnectionWrongStateError(
  1029. 'Channel allocation requires an open connection: %s' % self)
  1030. validators.rpc_completion_callback(on_open_callback)
  1031. if not channel_number:
  1032. channel_number = self._next_channel_number()
  1033. self._channels[channel_number] = self._create_channel(
  1034. channel_number, on_open_callback)
  1035. self._add_channel_callbacks(channel_number)
  1036. self._channels[channel_number].open()
  1037. return self._channels[channel_number]
  1038. def close(self, reply_code=200, reply_text='Normal shutdown'):
  1039. """Disconnect from RabbitMQ. If there are any open channels, it will
  1040. attempt to close them prior to fully disconnecting. Channels which
  1041. have active consumers will attempt to send a Basic.Cancel to RabbitMQ
  1042. to cleanly stop the delivery of messages prior to closing the channel.
  1043. :param int reply_code: The code number for the close
  1044. :param str reply_text: The text reason for the close
  1045. :raises pika.exceptions.ConnectionWrongStateError: if connection is
  1046. closed or closing.
  1047. """
  1048. if self.is_closing or self.is_closed:
  1049. msg = ('Illegal close({}, {!r}) request on {} because it '
  1050. 'was called while connection state={}.'.format(
  1051. reply_code, reply_text, self,
  1052. self._STATE_NAMES[self.connection_state]))
  1053. LOGGER.error(msg)
  1054. raise exceptions.ConnectionWrongStateError(msg)
  1055. # NOTE The connection is either in opening or open state
  1056. # Initiate graceful closing of channels that are OPEN or OPENING
  1057. if self._channels:
  1058. self._close_channels(reply_code, reply_text)
  1059. prev_state = self.connection_state
  1060. # Transition to closing
  1061. self._set_connection_state(self.CONNECTION_CLOSING)
  1062. LOGGER.info("Closing connection (%s): %r", reply_code, reply_text)
  1063. if not self._opened:
  1064. # It was opening, but not fully open yet, so we won't attempt
  1065. # graceful AMQP Connection.Close.
  1066. LOGGER.info('Connection.close() is terminating stream and '
  1067. 'bypassing graceful AMQP close, since AMQP is still '
  1068. 'opening.')
  1069. error = exceptions.ConnectionOpenAborted(
  1070. 'Connection.close() called before connection '
  1071. 'finished opening: prev_state={} ({}): {!r}'.format(
  1072. self._STATE_NAMES[prev_state], reply_code, reply_text))
  1073. self._terminate_stream(error)
  1074. else:
  1075. self._error = exceptions.ConnectionClosedByClient(
  1076. reply_code, reply_text)
  1077. # If there are channels that haven't finished closing yet, then
  1078. # _on_close_ready will finally be called from _on_channel_cleanup once
  1079. # all channels have been closed
  1080. if not self._channels:
  1081. # We can initiate graceful closing of the connection right away,
  1082. # since no more channels remain
  1083. self._on_close_ready()
  1084. else:
  1085. LOGGER.info(
  1086. 'Connection.close is waiting for %d channels to close: %s',
  1087. len(self._channels), self)
  1088. #
  1089. # Connection state properties
  1090. #
  1091. @property
  1092. def is_closed(self):
  1093. """
  1094. Returns a boolean reporting the current connection state.
  1095. """
  1096. return self.connection_state == self.CONNECTION_CLOSED
  1097. @property
  1098. def is_closing(self):
  1099. """
  1100. Returns True if connection is in the process of closing due to
  1101. client-initiated `close` request, but closing is not yet complete.
  1102. """
  1103. return self.connection_state == self.CONNECTION_CLOSING
  1104. @property
  1105. def is_open(self):
  1106. """
  1107. Returns a boolean reporting the current connection state.
  1108. """
  1109. return self.connection_state == self.CONNECTION_OPEN
  1110. #
  1111. # Properties that reflect server capabilities for the current connection
  1112. #
  1113. @property
  1114. def basic_nack(self):
  1115. """Specifies if the server supports basic.nack on the active connection.
  1116. :rtype: bool
  1117. """
  1118. return self.server_capabilities.get('basic.nack', False)
  1119. @property
  1120. def consumer_cancel_notify(self):
  1121. """Specifies if the server supports consumer cancel notification on the
  1122. active connection.
  1123. :rtype: bool
  1124. """
  1125. return self.server_capabilities.get('consumer_cancel_notify', False)
  1126. @property
  1127. def exchange_exchange_bindings(self):
  1128. """Specifies if the active connection supports exchange to exchange
  1129. bindings.
  1130. :rtype: bool
  1131. """
  1132. return self.server_capabilities.get('exchange_exchange_bindings', False)
  1133. @property
  1134. def publisher_confirms(self):
  1135. """Specifies if the active connection can use publisher confirmations.
  1136. :rtype: bool
  1137. """
  1138. return self.server_capabilities.get('publisher_confirms', False)
  1139. @abc.abstractmethod
  1140. def _adapter_call_later(self, delay, callback):
  1141. """Adapters should override to call the callback after the
  1142. specified number of seconds have elapsed, using a timer, or a
  1143. thread, or similar.
  1144. :param float|int delay: The number of seconds to wait to call callback
  1145. :param callable callback: The callback will be called without args.
  1146. :returns: Handle that can be passed to `_adapter_remove_timeout()` to
  1147. cancel the callback.
  1148. :rtype: object
  1149. """
  1150. raise NotImplementedError
  1151. @abc.abstractmethod
  1152. def _adapter_remove_timeout(self, timeout_id):
  1153. """Adapters should override: Remove a timeout
  1154. :param opaque timeout_id: The timeout handle to remove
  1155. """
  1156. raise NotImplementedError
  1157. @abc.abstractmethod
  1158. def _adapter_add_callback_threadsafe(self, callback):
  1159. """Requests a call to the given function as soon as possible in the
  1160. context of this connection's IOLoop thread.
  1161. NOTE: This is the only thread-safe method offered by the connection. All
  1162. other manipulations of the connection must be performed from the
  1163. connection's thread.
  1164. :param callable callback: The callback method; must be callable.
  1165. """
  1166. raise NotImplementedError
  1167. #
  1168. # Internal methods for managing the communication process
  1169. #
  1170. @abc.abstractmethod
  1171. def _adapter_connect_stream(self):
  1172. """Subclasses should override to initiate stream connection
  1173. workflow asynchronously. Upon failed or aborted completion, they must
  1174. invoke `Connection._on_stream_terminated()`.
  1175. NOTE: On success, the stack will be up already, so there is no
  1176. corresponding callback.
  1177. """
  1178. raise NotImplementedError
  1179. @abc.abstractmethod
  1180. def _adapter_disconnect_stream(self):
  1181. """Asynchronously bring down the streaming transport layer and invoke
  1182. `Connection._on_stream_terminated()` asynchronously when complete.
  1183. :raises: NotImplementedError
  1184. """
  1185. raise NotImplementedError
  1186. @abc.abstractmethod
  1187. def _adapter_emit_data(self, data):
  1188. """Take ownership of data and send it to AMQP server as soon as
  1189. possible.
  1190. Subclasses must override this
  1191. :param bytes data:
  1192. """
  1193. raise NotImplementedError
  1194. def _add_channel_callbacks(self, channel_number):
  1195. """Add the appropriate callbacks for the specified channel number.
  1196. :param int channel_number: The channel number for the callbacks
  1197. """
  1198. # pylint: disable=W0212
  1199. # This permits us to garbage-collect our reference to the channel
  1200. # regardless of whether it was closed by client or broker, and do so
  1201. # after all channel-close callbacks.
  1202. self._channels[channel_number]._add_on_cleanup_callback(
  1203. self._on_channel_cleanup)
  1204. def _add_connection_start_callback(self):
  1205. """Add a callback for when a Connection.Start frame is received from
  1206. the broker.
  1207. """
  1208. self.callbacks.add(0, spec.Connection.Start, self._on_connection_start)
  1209. def _add_connection_tune_callback(self):
  1210. """Add a callback for when a Connection.Tune frame is received."""
  1211. self.callbacks.add(0, spec.Connection.Tune, self._on_connection_tune)
  1212. def _check_for_protocol_mismatch(self, value):
  1213. """Invoked when starting a connection to make sure it's a supported
  1214. protocol.
  1215. :param pika.frame.Method value: The frame to check
  1216. :raises: ProtocolVersionMismatch
  1217. """
  1218. if ((value.method.version_major, value.method.version_minor) !=
  1219. spec.PROTOCOL_VERSION[0:2]):
  1220. raise exceptions.ProtocolVersionMismatch(frame.ProtocolHeader(),
  1221. value)
  1222. @property
  1223. def _client_properties(self):
  1224. """Return the client properties dictionary.
  1225. :rtype: dict
  1226. """
  1227. properties = {
  1228. 'product': PRODUCT,
  1229. 'platform': 'Python %s' % platform.python_version(),
  1230. 'capabilities': {
  1231. 'authentication_failure_close': True,
  1232. 'basic.nack': True,
  1233. 'connection.blocked': True,
  1234. 'consumer_cancel_notify': True,
  1235. 'publisher_confirms': True
  1236. },
  1237. 'information': 'See http://pika.rtfd.org',
  1238. 'version': pika.__version__
  1239. }
  1240. if self.params.client_properties:
  1241. properties.update(self.params.client_properties)
  1242. return properties
  1243. def _close_channels(self, reply_code, reply_text):
  1244. """Initiate graceful closing of channels that are in OPEN or OPENING
  1245. states, passing reply_code and reply_text.
  1246. :param int reply_code: The code for why the channels are being closed
  1247. :param str reply_text: The text reason for why the channels are closing
  1248. """
  1249. assert self.is_open, str(self)
  1250. for channel_number in dictkeys(self._channels):
  1251. chan = self._channels[channel_number]
  1252. if not (chan.is_closing or chan.is_closed):
  1253. chan.close(reply_code, reply_text)
  1254. def _create_channel(self, channel_number, on_open_callback):
  1255. """Create a new channel using the specified channel number and calling
  1256. back the method specified by on_open_callback
  1257. :param int channel_number: The channel number to use
  1258. :param callable on_open_callback: The callback when the channel is
  1259. opened. The callback will be invoked with the `Channel` instance
  1260. as its only argument.
  1261. """
  1262. LOGGER.debug('Creating channel %s', channel_number)
  1263. return pika.channel.Channel(self, channel_number, on_open_callback)
  1264. def _create_heartbeat_checker(self):
  1265. """Create a heartbeat checker instance if there is a heartbeat interval
  1266. set.
  1267. :rtype: pika.heartbeat.Heartbeat|None
  1268. """
  1269. if self.params.heartbeat is not None and self.params.heartbeat > 0:
  1270. LOGGER.debug('Creating a HeartbeatChecker: %r',
  1271. self.params.heartbeat)
  1272. return pika.heartbeat.HeartbeatChecker(self, self.params.heartbeat)
  1273. return None
  1274. def _remove_heartbeat(self):
  1275. """Stop the heartbeat checker if it exists
  1276. """
  1277. if self._heartbeat_checker:
  1278. self._heartbeat_checker.stop()
  1279. self._heartbeat_checker = None
  1280. def _deliver_frame_to_channel(self, value):
  1281. """Deliver the frame to the channel specified in the frame.
  1282. :param pika.frame.Method value: The frame to deliver
  1283. """
  1284. if not value.channel_number in self._channels:
  1285. # This should never happen and would constitute breach of the
  1286. # protocol
  1287. LOGGER.critical(
  1288. 'Received %s frame for unregistered channel %i on %s',
  1289. value.NAME, value.channel_number, self)
  1290. return
  1291. # pylint: disable=W0212
  1292. self._channels[value.channel_number]._handle_content_frame(value)
  1293. def _ensure_closed(self):
  1294. """If the connection is not closed, close it."""
  1295. if self.is_open:
  1296. self.close()
  1297. def _get_body_frame_max_length(self):
  1298. """Calculate the maximum amount of bytes that can be in a body frame.
  1299. :rtype: int
  1300. """
  1301. return (self.params.frame_max - spec.FRAME_HEADER_SIZE -
  1302. spec.FRAME_END_SIZE)
  1303. def _get_credentials(self, method_frame):
  1304. """Get credentials for authentication.
  1305. :param pika.frame.MethodFrame method_frame: The Connection.Start frame
  1306. :rtype: tuple(str, str)
  1307. """
  1308. (auth_type,
  1309. response) = self.params.credentials.response_for(method_frame.method)
  1310. if not auth_type:
  1311. raise exceptions.AuthenticationError(self.params.credentials.TYPE)
  1312. self.params.credentials.erase_credentials()
  1313. return auth_type, response
  1314. def _has_pending_callbacks(self, value):
  1315. """Return true if there are any callbacks pending for the specified
  1316. frame.
  1317. :param pika.frame.Method value: The frame to check
  1318. :rtype: bool
  1319. """
  1320. return self.callbacks.pending(value.channel_number, value.method)
  1321. def _is_method_frame(self, value):
  1322. """Returns true if the frame is a method frame.
  1323. :param pika.frame.Frame value: The frame to evaluate
  1324. :rtype: bool
  1325. """
  1326. return isinstance(value, frame.Method)
  1327. def _is_protocol_header_frame(self, value):
  1328. """Returns True if it's a protocol header frame.
  1329. :rtype: bool
  1330. """
  1331. return isinstance(value, frame.ProtocolHeader)
  1332. def _next_channel_number(self):
  1333. """Return the next available channel number or raise an exception.
  1334. :rtype: int
  1335. """
  1336. limit = self.params.channel_max or pika.channel.MAX_CHANNELS
  1337. if len(self._channels) >= limit:
  1338. raise exceptions.NoFreeChannels()
  1339. for num in xrange(1, len(self._channels) + 1):
  1340. if num not in self._channels:
  1341. return num
  1342. return len(self._channels) + 1
  1343. def _on_channel_cleanup(self, channel):
  1344. """Remove the channel from the dict of channels when Channel.CloseOk is
  1345. sent. If connection is closing and no more channels remain, proceed to
  1346. `_on_close_ready`.
  1347. :param pika.channel.Channel channel: channel instance
  1348. """
  1349. try:
  1350. del self._channels[channel.channel_number]
  1351. LOGGER.debug('Removed channel %s', channel.channel_number)
  1352. except KeyError:
  1353. LOGGER.error('Channel %r not in channels', channel.channel_number)
  1354. if self.is_closing:
  1355. if not self._channels:
  1356. # Initiate graceful closing of the connection
  1357. self._on_close_ready()
  1358. else:
  1359. # Once Connection enters CLOSING state, all remaining channels
  1360. # should also be in CLOSING state. Deviation from this would
  1361. # prevent Connection from completing its closing procedure.
  1362. channels_not_in_closing_state = [
  1363. chan for chan in dict_itervalues(self._channels)
  1364. if not chan.is_closing
  1365. ]
  1366. if channels_not_in_closing_state:
  1367. LOGGER.critical(
  1368. 'Connection in CLOSING state has non-CLOSING '
  1369. 'channels: %r', channels_not_in_closing_state)
  1370. def _on_close_ready(self):
  1371. """Called when the Connection is in a state that it can close after
  1372. a close has been requested by client. This happens after all of the
  1373. channels are closed that were open when the close request was made.
  1374. """
  1375. if self.is_closed:
  1376. LOGGER.warning('_on_close_ready invoked when already closed')
  1377. return
  1378. # NOTE: Assuming self._error is instance of exceptions.ConnectionClosed
  1379. self._send_connection_close(self._error.reply_code,
  1380. self._error.reply_text)
  1381. def _on_stream_connected(self):
  1382. """Invoked when the socket is connected and it's time to start speaking
  1383. AMQP with the broker.
  1384. """
  1385. self._set_connection_state(self.CONNECTION_PROTOCOL)
  1386. # Start the communication with the RabbitMQ Broker
  1387. self._send_frame(frame.ProtocolHeader())
  1388. def _on_blocked_connection_timeout(self):
  1389. """ Called when the "connection blocked timeout" expires. When this
  1390. happens, we tear down the connection
  1391. """
  1392. self._blocked_conn_timer = None
  1393. self._terminate_stream(
  1394. exceptions.ConnectionBlockedTimeout(
  1395. 'Blocked connection timeout expired.'))
  1396. def _on_connection_blocked(self, _connection, method_frame):
  1397. """Handle Connection.Blocked notification from RabbitMQ broker
  1398. :param pika.frame.Method method_frame: method frame having `method`
  1399. member of type `pika.spec.Connection.Blocked`
  1400. """
  1401. LOGGER.warning('Received %s from broker', method_frame)
  1402. if self._blocked_conn_timer is not None:
  1403. # RabbitMQ is not supposed to repeat Connection.Blocked, but it
  1404. # doesn't hurt to be careful
  1405. LOGGER.warning(
  1406. '_blocked_conn_timer %s already set when '
  1407. '_on_connection_blocked is called', self._blocked_conn_timer)
  1408. else:
  1409. self._blocked_conn_timer = self._adapter_call_later(
  1410. self.params.blocked_connection_timeout,
  1411. self._on_blocked_connection_timeout)
  1412. def _on_connection_unblocked(self, _connection, method_frame):
  1413. """Handle Connection.Unblocked notification from RabbitMQ broker
  1414. :param pika.frame.Method method_frame: method frame having `method`
  1415. member of type `pika.spec.Connection.Blocked`
  1416. """
  1417. LOGGER.info('Received %s from broker', method_frame)
  1418. if self._blocked_conn_timer is None:
  1419. # RabbitMQ is supposed to pair Connection.Blocked/Unblocked, but it
  1420. # doesn't hurt to be careful
  1421. LOGGER.warning('_blocked_conn_timer was not active when '
  1422. '_on_connection_unblocked called')
  1423. else:
  1424. self._adapter_remove_timeout(self._blocked_conn_timer)
  1425. self._blocked_conn_timer = None
  1426. def _on_connection_close_from_broker(self, method_frame):
  1427. """Called when the connection is closed remotely via Connection.Close
  1428. frame from broker.
  1429. :param pika.frame.Method method_frame: The Connection.Close frame
  1430. """
  1431. LOGGER.debug('_on_connection_close_from_broker: frame=%s', method_frame)
  1432. self._terminate_stream(
  1433. exceptions.ConnectionClosedByBroker(method_frame.method.reply_code,
  1434. method_frame.method.reply_text))
  1435. def _on_connection_close_ok(self, method_frame):
  1436. """Called when Connection.CloseOk is received from remote.
  1437. :param pika.frame.Method method_frame: The Connection.CloseOk frame
  1438. """
  1439. LOGGER.debug('_on_connection_close_ok: frame=%s', method_frame)
  1440. self._terminate_stream(None)
  1441. def _default_on_connection_error(self, _connection_unused, error):
  1442. """Default behavior when the connecting connection cannot connect and
  1443. user didn't supply own `on_connection_error` callback.
  1444. :raises: the given error
  1445. """
  1446. raise error
  1447. def _on_connection_open_ok(self, method_frame):
  1448. """
  1449. This is called once we have tuned the connection with the server and
  1450. called the Connection.Open on the server and it has replied with
  1451. Connection.Ok.
  1452. """
  1453. self._opened = True
  1454. self.known_hosts = method_frame.method.known_hosts
  1455. # We're now connected at the AMQP level
  1456. self._set_connection_state(self.CONNECTION_OPEN)
  1457. # Call our initial callback that we're open
  1458. self.callbacks.process(0, self.ON_CONNECTION_OPEN_OK, self, self)
  1459. def _on_connection_start(self, method_frame):
  1460. """This is called as a callback once we have received a Connection.Start
  1461. from the server.
  1462. :param pika.frame.Method method_frame: The frame received
  1463. :raises: UnexpectedFrameError
  1464. """
  1465. self._set_connection_state(self.CONNECTION_START)
  1466. try:
  1467. if self._is_protocol_header_frame(method_frame):
  1468. raise exceptions.UnexpectedFrameError(method_frame)
  1469. self._check_for_protocol_mismatch(method_frame)
  1470. self._set_server_information(method_frame)
  1471. self._add_connection_tune_callback()
  1472. self._send_connection_start_ok(*self._get_credentials(method_frame))
  1473. except Exception as error: # pylint: disable=W0703
  1474. LOGGER.exception('Error processing Connection.Start.')
  1475. self._terminate_stream(error)
  1476. @staticmethod
  1477. def _negotiate_integer_value(client_value, server_value):
  1478. """Negotiates two values. If either of them is 0 or None,
  1479. returns the other one. If both are positive integers, returns the
  1480. smallest one.
  1481. :param int client_value: The client value
  1482. :param int server_value: The server value
  1483. :rtype: int
  1484. """
  1485. if client_value is None:
  1486. client_value = 0
  1487. if server_value is None:
  1488. server_value = 0
  1489. # this is consistent with how Java client and Bunny
  1490. # perform negotiation, see pika/pika#874
  1491. if client_value == 0 or server_value == 0:
  1492. val = max(client_value, server_value)
  1493. else:
  1494. val = min(client_value, server_value)
  1495. return val
  1496. @staticmethod
  1497. def _tune_heartbeat_timeout(client_value, server_value):
  1498. """ Determine heartbeat timeout per AMQP 0-9-1 rules
  1499. Per https://www.rabbitmq.com/resources/specs/amqp0-9-1.pdf,
  1500. > Both peers negotiate the limits to the lowest agreed value as follows:
  1501. > - The server MUST tell the client what limits it proposes.
  1502. > - The client responds and **MAY reduce those limits** for its
  1503. connection
  1504. If the client specifies a value, it always takes precedence.
  1505. :param client_value: None to accept server_value; otherwise, an integral
  1506. number in seconds; 0 (zero) to disable heartbeat.
  1507. :param server_value: integral value of the heartbeat timeout proposed by
  1508. broker; 0 (zero) to disable heartbeat.
  1509. :returns: the value of the heartbeat timeout to use and return to broker
  1510. :rtype: int
  1511. """
  1512. if client_value is None:
  1513. # Accept server's limit
  1514. timeout = server_value
  1515. else:
  1516. timeout = client_value
  1517. return timeout
  1518. def _on_connection_tune(self, method_frame):
  1519. """Once the Broker sends back a Connection.Tune, we will set our tuning
  1520. variables that have been returned to us and kick off the Heartbeat
  1521. monitor if required, send our TuneOk and then the Connection. Open rpc
  1522. call on channel 0.
  1523. :param pika.frame.Method method_frame: The frame received
  1524. """
  1525. self._set_connection_state(self.CONNECTION_TUNE)
  1526. # Get our max channels, frames and heartbeat interval
  1527. self.params.channel_max = Connection._negotiate_integer_value(
  1528. self.params.channel_max, method_frame.method.channel_max)
  1529. self.params.frame_max = Connection._negotiate_integer_value(
  1530. self.params.frame_max, method_frame.method.frame_max)
  1531. if callable(self.params.heartbeat):
  1532. ret_heartbeat = self.params.heartbeat(self,
  1533. method_frame.method.heartbeat)
  1534. if ret_heartbeat is None or callable(ret_heartbeat):
  1535. # Enforce callback-specific restrictions on callback's return value
  1536. raise TypeError('heartbeat callback must not return None '
  1537. 'or callable, but got %r' % (ret_heartbeat,))
  1538. # Leave it to hearbeat setter deal with the rest of the validation
  1539. self.params.heartbeat = ret_heartbeat
  1540. # Negotiate heatbeat timeout
  1541. self.params.heartbeat = self._tune_heartbeat_timeout(
  1542. client_value=self.params.heartbeat,
  1543. server_value=method_frame.method.heartbeat)
  1544. # Calculate the maximum pieces for body frames
  1545. self._body_max_length = self._get_body_frame_max_length()
  1546. # Create a new heartbeat checker if needed
  1547. self._heartbeat_checker = self._create_heartbeat_checker()
  1548. # Send the TuneOk response with what we've agreed upon
  1549. self._send_connection_tune_ok()
  1550. # Send the Connection.Open RPC call for the vhost
  1551. self._send_connection_open()
  1552. def _on_data_available(self, data_in):
  1553. """This is called by our Adapter, passing in the data from the socket.
  1554. As long as we have buffer try and map out frame data.
  1555. :param str data_in: The data that is available to read
  1556. """
  1557. self._frame_buffer += data_in
  1558. while self._frame_buffer:
  1559. consumed_count, frame_value = self._read_frame()
  1560. if not frame_value:
  1561. return
  1562. self._trim_frame_buffer(consumed_count)
  1563. self._process_frame(frame_value)
  1564. def _terminate_stream(self, error):
  1565. """Deactivate heartbeat instance if activated already, and initiate
  1566. termination of the stream (TCP) connection asynchronously.
  1567. When connection terminates, the appropriate user callback will be
  1568. invoked with the given error: "on open error" or "on connection closed".
  1569. :param Exception | None error: exception instance describing the reason
  1570. for termination; None for normal closing, such as upon receipt of
  1571. Connection.CloseOk.
  1572. """
  1573. assert isinstance(error, (type(None), Exception)), \
  1574. 'error arg is neither None nor instance of Exception: {!r}.'.format(
  1575. error)
  1576. if error is not None:
  1577. # Save the exception for user callback once the stream closes
  1578. self._error = error
  1579. else:
  1580. assert self._error is not None, (
  1581. '_terminate_stream() expected self._error to be set when '
  1582. 'passed None error arg.')
  1583. # So it won't mess with the stack
  1584. self._remove_heartbeat()
  1585. # Begin disconnection of stream or termination of connection workflow
  1586. self._adapter_disconnect_stream()
  1587. def _on_stream_terminated(self, error):
  1588. """Handle termination of stack (including TCP layer) or failure to
  1589. establish the stack. Notify registered ON_CONNECTION_ERROR or
  1590. ON_CONNECTION_CLOSED callbacks, depending on whether the connection
  1591. was opening or open.
  1592. :param Exception | None error: None means that the transport was aborted
  1593. internally and exception in `self._error` represents the cause.
  1594. Otherwise it's an exception object that describes the unexpected
  1595. loss of connection.
  1596. """
  1597. LOGGER.info(
  1598. 'AMQP stack terminated, failed to connect, or aborted: '
  1599. 'opened=%r, error-arg=%r; pending-error=%r',
  1600. self._opened, error, self._error)
  1601. if error is not None:
  1602. if self._error is not None:
  1603. LOGGER.debug(
  1604. '_on_stream_terminated(): overriding '
  1605. 'pending-error=%r with %r', self._error, error)
  1606. self._error = error
  1607. else:
  1608. assert self._error is not None, (
  1609. '_on_stream_terminated() expected self._error to be populated '
  1610. 'with reason for terminating stack.')
  1611. # Stop the heartbeat checker if it exists
  1612. self._remove_heartbeat()
  1613. # Remove connection management callbacks
  1614. self._remove_callbacks(0,
  1615. [spec.Connection.Close, spec.Connection.Start])
  1616. if self.params.blocked_connection_timeout is not None:
  1617. self._remove_callbacks(0,
  1618. [spec.Connection.Blocked, spec.Connection.Unblocked])
  1619. if not self._opened and isinstance(self._error,
  1620. (exceptions.StreamLostError, exceptions.ConnectionClosedByBroker)):
  1621. # Heuristically deduce error based on connection state
  1622. if self.connection_state == self.CONNECTION_PROTOCOL:
  1623. LOGGER.error('Probably incompatible Protocol Versions')
  1624. self._error = exceptions.IncompatibleProtocolError(
  1625. repr(self._error))
  1626. elif self.connection_state == self.CONNECTION_START:
  1627. LOGGER.error(
  1628. 'Connection closed while authenticating indicating a '
  1629. 'probable authentication error')
  1630. self._error = exceptions.ProbableAuthenticationError(
  1631. repr(self._error))
  1632. elif self.connection_state == self.CONNECTION_TUNE:
  1633. LOGGER.error('Connection closed while tuning the connection '
  1634. 'indicating a probable permission error when '
  1635. 'accessing a virtual host')
  1636. self._error = exceptions.ProbableAccessDeniedError(
  1637. repr(self._error))
  1638. elif self.connection_state not in [
  1639. self.CONNECTION_OPEN, self.CONNECTION_CLOSED,
  1640. self.CONNECTION_CLOSING
  1641. ]:
  1642. LOGGER.warning('Unexpected connection state on disconnect: %i',
  1643. self.connection_state)
  1644. # Transition to closed state
  1645. self._set_connection_state(self.CONNECTION_CLOSED)
  1646. # Inform our channel proxies, if any are still around
  1647. for channel in dictkeys(self._channels):
  1648. if channel not in self._channels:
  1649. continue
  1650. # pylint: disable=W0212
  1651. self._channels[channel]._on_close_meta(self._error)
  1652. # Inform interested parties
  1653. if not self._opened:
  1654. LOGGER.info('Connection setup terminated due to %r', self._error)
  1655. self.callbacks.process(0, self.ON_CONNECTION_ERROR, self, self,
  1656. self._error)
  1657. else:
  1658. LOGGER.info('Stack terminated due to %r', self._error)
  1659. self.callbacks.process(0, self.ON_CONNECTION_CLOSED, self, self,
  1660. self._error)
  1661. # Reset connection properties
  1662. self._init_connection_state()
  1663. def _process_callbacks(self, frame_value):
  1664. """Process the callbacks for the frame if the frame is a method frame
  1665. and if it has any callbacks pending.
  1666. :param pika.frame.Method frame_value: The frame to process
  1667. :rtype: bool
  1668. """
  1669. if (self._is_method_frame(frame_value) and
  1670. self._has_pending_callbacks(frame_value)):
  1671. self.callbacks.process(
  1672. frame_value.channel_number, # Prefix
  1673. frame_value.method, # Key
  1674. self, # Caller
  1675. frame_value) # Args
  1676. return True
  1677. return False
  1678. def _process_frame(self, frame_value):
  1679. """Process an inbound frame from the socket.
  1680. :param pika.frame.Frame|pika.frame.Method frame_value: The frame to
  1681. process
  1682. """
  1683. # Will receive a frame type of -1 if protocol version mismatch
  1684. if frame_value.frame_type < 0:
  1685. return
  1686. # Keep track of how many frames have been read
  1687. self.frames_received += 1
  1688. # Process any callbacks, if True, exit method
  1689. if self._process_callbacks(frame_value):
  1690. return
  1691. # If a heartbeat is received, update the checker
  1692. if isinstance(frame_value, frame.Heartbeat):
  1693. if self._heartbeat_checker:
  1694. self._heartbeat_checker.received()
  1695. else:
  1696. LOGGER.warning('Received heartbeat frame without a heartbeat '
  1697. 'checker')
  1698. # If the frame has a channel number beyond the base channel, deliver it
  1699. elif frame_value.channel_number > 0:
  1700. self._deliver_frame_to_channel(frame_value)
  1701. def _read_frame(self):
  1702. """Try and read from the frame buffer and decode a frame.
  1703. :rtype tuple: (int, pika.frame.Frame)
  1704. """
  1705. return frame.decode_frame(self._frame_buffer)
  1706. def _remove_callbacks(self, channel_number, method_classes):
  1707. """Remove the callbacks for the specified channel number and list of
  1708. method frames.
  1709. :param int channel_number: The channel number to remove the callback on
  1710. :param sequence method_classes: The method classes (derived from
  1711. `pika.amqp_object.Method`) for the callbacks
  1712. """
  1713. for method_cls in method_classes:
  1714. self.callbacks.remove(str(channel_number), method_cls)
  1715. def _rpc(self,
  1716. channel_number,
  1717. method,
  1718. callback=None,
  1719. acceptable_replies=None):
  1720. """Make an RPC call for the given callback, channel number and method.
  1721. acceptable_replies lists out what responses we'll process from the
  1722. server with the specified callback.
  1723. :param int channel_number: The channel number for the RPC call
  1724. :param pika.amqp_object.Method method: The method frame to call
  1725. :param callable callback: The callback for the RPC response
  1726. :param list acceptable_replies: The replies this RPC call expects
  1727. """
  1728. # Validate that acceptable_replies is a list or None
  1729. if acceptable_replies and not isinstance(acceptable_replies, list):
  1730. raise TypeError('acceptable_replies should be list or None')
  1731. # Validate the callback is callable
  1732. if callback is not None:
  1733. validators.require_callback(callback)
  1734. for reply in acceptable_replies:
  1735. self.callbacks.add(channel_number, reply, callback)
  1736. # Send the rpc call to RabbitMQ
  1737. self._send_method(channel_number, method)
  1738. def _send_connection_close(self, reply_code, reply_text):
  1739. """Send a Connection.Close method frame.
  1740. :param int reply_code: The reason for the close
  1741. :param str reply_text: The text reason for the close
  1742. """
  1743. self._rpc(0, spec.Connection.Close(reply_code, reply_text, 0, 0),
  1744. self._on_connection_close_ok, [spec.Connection.CloseOk])
  1745. def _send_connection_open(self):
  1746. """Send a Connection.Open frame"""
  1747. self._rpc(0, spec.Connection.Open(
  1748. self.params.virtual_host, insist=True), self._on_connection_open_ok,
  1749. [spec.Connection.OpenOk])
  1750. def _send_connection_start_ok(self, authentication_type, response):
  1751. """Send a Connection.StartOk frame
  1752. :param str authentication_type: The auth type value
  1753. :param str response: The encoded value to send
  1754. """
  1755. self._send_method(
  1756. 0,
  1757. spec.Connection.StartOk(self._client_properties,
  1758. authentication_type, response,
  1759. self.params.locale))
  1760. def _send_connection_tune_ok(self):
  1761. """Send a Connection.TuneOk frame"""
  1762. self._send_method(
  1763. 0,
  1764. spec.Connection.TuneOk(self.params.channel_max,
  1765. self.params.frame_max,
  1766. self.params.heartbeat))
  1767. def _send_frame(self, frame_value):
  1768. """This appends the fully generated frame to send to the broker to the
  1769. output buffer which will be then sent via the connection adapter.
  1770. :param pika.frame.Frame|pika.frame.ProtocolHeader frame_value: The
  1771. frame to write
  1772. :raises: exceptions.ConnectionClosed
  1773. """
  1774. if self.is_closed:
  1775. LOGGER.error('Attempted to send frame when closed')
  1776. raise exceptions.ConnectionWrongStateError(
  1777. 'Attempted to send a frame on closed connection.')
  1778. marshaled_frame = frame_value.marshal()
  1779. self._output_marshaled_frames([marshaled_frame])
  1780. def _send_method(self, channel_number, method, content=None):
  1781. """Constructs a RPC method frame and then sends it to the broker.
  1782. :param int channel_number: The channel number for the frame
  1783. :param pika.amqp_object.Method method: The method to send
  1784. :param tuple content: If set, is a content frame, is tuple of
  1785. properties and body.
  1786. """
  1787. if content:
  1788. self._send_message(channel_number, method, content)
  1789. else:
  1790. self._send_frame(frame.Method(channel_number, method))
  1791. def _send_message(self, channel_number, method_frame, content):
  1792. """Publish a message.
  1793. :param int channel_number: The channel number for the frame
  1794. :param pika.object.Method method_frame: The method frame to send
  1795. :param tuple content: A content frame, which is tuple of properties and
  1796. body.
  1797. """
  1798. length = len(content[1])
  1799. marshaled_body_frames = []
  1800. # Note: we construct the Method, Header and Content objects, marshal them
  1801. # *then* output in case the marshaling operation throws an exception
  1802. frame_method = frame.Method(channel_number, method_frame)
  1803. frame_header = frame.Header(channel_number, length, content[0])
  1804. marshaled_body_frames.append(frame_method.marshal())
  1805. marshaled_body_frames.append(frame_header.marshal())
  1806. if content[1]:
  1807. chunks = int(math.ceil(float(length) / self._body_max_length))
  1808. for chunk in xrange(0, chunks):
  1809. start = chunk * self._body_max_length
  1810. end = start + self._body_max_length
  1811. if end > length:
  1812. end = length
  1813. frame_body = frame.Body(channel_number, content[1][start:end])
  1814. marshaled_body_frames.append(frame_body.marshal())
  1815. self._output_marshaled_frames(marshaled_body_frames)
  1816. def _set_connection_state(self, connection_state):
  1817. """Set the connection state.
  1818. :param int connection_state: The connection state to set
  1819. """
  1820. LOGGER.debug('New Connection state: %s (prev=%s)',
  1821. self._STATE_NAMES[connection_state],
  1822. self._STATE_NAMES[self.connection_state])
  1823. self.connection_state = connection_state
  1824. def _set_server_information(self, method_frame):
  1825. """Set the server properties and capabilities
  1826. :param spec.connection.Start method_frame: The Connection.Start frame
  1827. """
  1828. self.server_properties = method_frame.method.server_properties
  1829. self.server_capabilities = self.server_properties.get(
  1830. 'capabilities', dict())
  1831. if hasattr(self.server_properties, 'capabilities'):
  1832. del self.server_properties['capabilities']
  1833. def _trim_frame_buffer(self, byte_count):
  1834. """Trim the leading N bytes off the frame buffer and increment the
  1835. counter that keeps track of how many bytes have been read/used from the
  1836. socket.
  1837. :param int byte_count: The number of bytes consumed
  1838. """
  1839. self._frame_buffer = self._frame_buffer[byte_count:]
  1840. self.bytes_received += byte_count
  1841. def _output_marshaled_frames(self, marshaled_frames):
  1842. """Output list of marshaled frames to buffer and update stats
  1843. :param list marshaled_frames: A list of frames marshaled to bytes
  1844. """
  1845. for marshaled_frame in marshaled_frames:
  1846. self.bytes_sent += len(marshaled_frame)
  1847. self.frames_sent += 1
  1848. self._adapter_emit_data(marshaled_frame)