connection.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  1. """AMQP Connections."""
  2. # Copyright (C) 2007-2008 Barry Pederson <bp@barryp.org>
  3. from __future__ import absolute_import, unicode_literals
  4. import logging
  5. import socket
  6. import uuid
  7. import warnings
  8. from vine import ensure_promise
  9. from . import __version__, sasl, spec
  10. from .abstract_channel import AbstractChannel
  11. from .channel import Channel
  12. from .exceptions import (AMQPDeprecationWarning, ChannelError, ConnectionError,
  13. ConnectionForced, RecoverableChannelError,
  14. RecoverableConnectionError, ResourceError,
  15. error_for_code)
  16. from .five import array, items, monotonic, range, string, values
  17. from .method_framing import frame_handler, frame_writer
  18. from .transport import Transport
  19. try:
  20. from ssl import SSLError
  21. except ImportError: # pragma: no cover
  22. class SSLError(Exception): # noqa
  23. pass
  24. W_FORCE_CONNECT = """\
  25. The .{attr} attribute on the connection was accessed before
  26. the connection was established. This is supported for now, but will
  27. be deprecated in amqp 2.2.0.
  28. Since amqp 2.0 you have to explicitly call Connection.connect()
  29. before using the connection.
  30. """
  31. START_DEBUG_FMT = """
  32. Start from server, version: %d.%d, properties: %s, mechanisms: %s, locales: %s
  33. """.strip()
  34. __all__ = ['Connection']
  35. AMQP_LOGGER = logging.getLogger('amqp')
  36. #: Default map for :attr:`Connection.library_properties`
  37. LIBRARY_PROPERTIES = {
  38. 'product': 'py-amqp',
  39. 'product_version': __version__,
  40. }
  41. #: Default map for :attr:`Connection.negotiate_capabilities`
  42. NEGOTIATE_CAPABILITIES = {
  43. 'consumer_cancel_notify': True,
  44. 'connection.blocked': True,
  45. 'authentication_failure_close': True,
  46. }
  47. class Connection(AbstractChannel):
  48. """AMQP Connection.
  49. The connection class provides methods for a client to establish a
  50. network connection to a server, and for both peers to operate the
  51. connection thereafter.
  52. GRAMMAR::
  53. connection = open-connection *use-connection close-connection
  54. open-connection = C:protocol-header
  55. S:START C:START-OK
  56. *challenge
  57. S:TUNE C:TUNE-OK
  58. C:OPEN S:OPEN-OK
  59. challenge = S:SECURE C:SECURE-OK
  60. use-connection = *channel
  61. close-connection = C:CLOSE S:CLOSE-OK
  62. / S:CLOSE C:CLOSE-OK
  63. Create a connection to the specified host, which should be
  64. a 'host[:port]', such as 'localhost', or '1.2.3.4:5672'
  65. (defaults to 'localhost', if a port is not specified then
  66. 5672 is used)
  67. Authentication can be controlled by passing one or more
  68. `amqp.sasl.SASL` instances as the `authentication` parameter, or
  69. setting the `login_method` string to one of the supported methods:
  70. 'GSSAPI', 'EXTERNAL', 'AMQPLAIN', or 'PLAIN'.
  71. Otherwise authentication will be performed using any supported method
  72. preferred by the server. Userid and passwords apply to AMQPLAIN and
  73. PLAIN authentication, whereas on GSSAPI only userid will be used as the
  74. client name. For EXTERNAL authentication both userid and password are
  75. ignored.
  76. The 'ssl' parameter may be simply True/False, or for Python >= 2.6
  77. a dictionary of options to pass to ssl.wrap_socket() such as
  78. requiring certain certificates.
  79. The "socket_settings" parameter is a dictionary defining tcp
  80. settings which will be applied as socket options.
  81. When "confirm_publish" is set to True, the channel is put to
  82. confirm mode. In this mode, each published message is
  83. confirmed using Publisher confirms RabbitMQ extention.
  84. """
  85. Channel = Channel
  86. #: Mapping of protocol extensions to enable.
  87. #: The server will report these in server_properties[capabilities],
  88. #: and if a key in this map is present the client will tell the
  89. #: server to either enable or disable the capability depending
  90. #: on the value set in this map.
  91. #: For example with:
  92. #: negotiate_capabilities = {
  93. #: 'consumer_cancel_notify': True,
  94. #: }
  95. #: The client will enable this capability if the server reports
  96. #: support for it, but if the value is False the client will
  97. #: disable the capability.
  98. negotiate_capabilities = NEGOTIATE_CAPABILITIES
  99. #: These are sent to the server to announce what features
  100. #: we support, type of client etc.
  101. library_properties = LIBRARY_PROPERTIES
  102. #: Final heartbeat interval value (in float seconds) after negotiation
  103. heartbeat = None
  104. #: Original heartbeat interval value proposed by client.
  105. client_heartbeat = None
  106. #: Original heartbeat interval proposed by server.
  107. server_heartbeat = None
  108. #: Time of last heartbeat sent (in monotonic time, if available).
  109. last_heartbeat_sent = 0
  110. #: Time of last heartbeat received (in monotonic time, if available).
  111. last_heartbeat_received = 0
  112. #: Number of successful writes to socket.
  113. bytes_sent = 0
  114. #: Number of successful reads from socket.
  115. bytes_recv = 0
  116. #: Number of bytes sent to socket at the last heartbeat check.
  117. prev_sent = None
  118. #: Number of bytes received from socket at the last heartbeat check.
  119. prev_recv = None
  120. _METHODS = {
  121. spec.method(spec.Connection.Start, 'ooFSS'),
  122. spec.method(spec.Connection.OpenOk),
  123. spec.method(spec.Connection.Secure, 's'),
  124. spec.method(spec.Connection.Tune, 'BlB'),
  125. spec.method(spec.Connection.Close, 'BsBB'),
  126. spec.method(spec.Connection.Blocked),
  127. spec.method(spec.Connection.Unblocked),
  128. spec.method(spec.Connection.CloseOk),
  129. }
  130. _METHODS = {m.method_sig: m for m in _METHODS}
  131. connection_errors = (
  132. ConnectionError,
  133. socket.error,
  134. IOError,
  135. OSError,
  136. )
  137. channel_errors = (ChannelError,)
  138. recoverable_connection_errors = (
  139. RecoverableConnectionError,
  140. socket.error,
  141. IOError,
  142. OSError,
  143. )
  144. recoverable_channel_errors = (
  145. RecoverableChannelError,
  146. )
  147. def __init__(self, host='localhost:5672', userid='guest', password='guest',
  148. login_method=None, login_response=None,
  149. authentication=(),
  150. virtual_host='/', locale='en_US', client_properties=None,
  151. ssl=False, connect_timeout=None, channel_max=None,
  152. frame_max=None, heartbeat=0, on_open=None, on_blocked=None,
  153. on_unblocked=None, confirm_publish=False,
  154. on_tune_ok=None, read_timeout=None, write_timeout=None,
  155. socket_settings=None, frame_handler=frame_handler,
  156. frame_writer=frame_writer, **kwargs):
  157. self._connection_id = uuid.uuid4().hex
  158. channel_max = channel_max or 65535
  159. frame_max = frame_max or 131072
  160. if authentication:
  161. if isinstance(authentication, sasl.SASL):
  162. authentication = (authentication,)
  163. self.authentication = authentication
  164. elif login_method is not None:
  165. if login_method == 'GSSAPI':
  166. auth = sasl.GSSAPI(userid)
  167. elif login_method == 'EXTERNAL':
  168. auth = sasl.EXTERNAL()
  169. elif login_method == 'AMQPLAIN':
  170. if userid is None or password is None:
  171. raise ValueError(
  172. "Must supply authentication or userid/password")
  173. auth = sasl.AMQPLAIN(userid, password)
  174. elif login_method == 'PLAIN':
  175. if userid is None or password is None:
  176. raise ValueError(
  177. "Must supply authentication or userid/password")
  178. auth = sasl.PLAIN(userid, password)
  179. elif login_response is not None:
  180. auth = sasl.RAW(login_method, login_response)
  181. else:
  182. raise ValueError("Invalid login method", login_method)
  183. self.authentication = (auth,)
  184. else:
  185. self.authentication = (sasl.GSSAPI(userid, fail_soft=True),
  186. sasl.EXTERNAL(),
  187. sasl.AMQPLAIN(userid, password),
  188. sasl.PLAIN(userid, password))
  189. self.client_properties = dict(
  190. self.library_properties, **client_properties or {}
  191. )
  192. self.locale = locale
  193. self.host = host
  194. self.virtual_host = virtual_host
  195. self.on_tune_ok = ensure_promise(on_tune_ok)
  196. self.frame_handler_cls = frame_handler
  197. self.frame_writer_cls = frame_writer
  198. self._handshake_complete = False
  199. self.channels = {}
  200. # The connection object itself is treated as channel 0
  201. super(Connection, self).__init__(self, 0)
  202. self._frame_writer = None
  203. self._on_inbound_frame = None
  204. self._transport = None
  205. # Properties set in the Tune method
  206. self.channel_max = channel_max
  207. self.frame_max = frame_max
  208. self.client_heartbeat = heartbeat
  209. self.confirm_publish = confirm_publish
  210. self.ssl = ssl
  211. self.read_timeout = read_timeout
  212. self.write_timeout = write_timeout
  213. self.socket_settings = socket_settings
  214. # Callbacks
  215. self.on_blocked = on_blocked
  216. self.on_unblocked = on_unblocked
  217. self.on_open = ensure_promise(on_open)
  218. self._avail_channel_ids = array('H', range(self.channel_max, 0, -1))
  219. # Properties set in the Start method
  220. self.version_major = 0
  221. self.version_minor = 0
  222. self.server_properties = {}
  223. self.mechanisms = []
  224. self.locales = []
  225. self.connect_timeout = connect_timeout
  226. def __enter__(self):
  227. self.connect()
  228. return self
  229. def __exit__(self, *eargs):
  230. self.close()
  231. def then(self, on_success, on_error=None):
  232. return self.on_open.then(on_success, on_error)
  233. def _setup_listeners(self):
  234. self._callbacks.update({
  235. spec.Connection.Start: self._on_start,
  236. spec.Connection.OpenOk: self._on_open_ok,
  237. spec.Connection.Secure: self._on_secure,
  238. spec.Connection.Tune: self._on_tune,
  239. spec.Connection.Close: self._on_close,
  240. spec.Connection.Blocked: self._on_blocked,
  241. spec.Connection.Unblocked: self._on_unblocked,
  242. spec.Connection.CloseOk: self._on_close_ok,
  243. })
  244. def connect(self, callback=None):
  245. # Let the transport.py module setup the actual
  246. # socket connection to the broker.
  247. #
  248. if self.connected:
  249. return callback() if callback else None
  250. try:
  251. self.transport = self.Transport(
  252. self.host, self.connect_timeout, self.ssl,
  253. self.read_timeout, self.write_timeout,
  254. socket_settings=self.socket_settings,
  255. )
  256. self.transport.connect()
  257. self.on_inbound_frame = self.frame_handler_cls(
  258. self, self.on_inbound_method)
  259. self.frame_writer = self.frame_writer_cls(self, self.transport)
  260. while not self._handshake_complete:
  261. self.drain_events(timeout=self.connect_timeout)
  262. except (OSError, IOError, SSLError):
  263. self.collect()
  264. raise
  265. def _warn_force_connect(self, attr):
  266. warnings.warn(AMQPDeprecationWarning(
  267. W_FORCE_CONNECT.format(attr=attr)))
  268. @property
  269. def transport(self):
  270. if self._transport is None:
  271. self._warn_force_connect('transport')
  272. self.connect()
  273. return self._transport
  274. @transport.setter
  275. def transport(self, transport):
  276. self._transport = transport
  277. @property
  278. def on_inbound_frame(self):
  279. if self._on_inbound_frame is None:
  280. self._warn_force_connect('on_inbound_frame')
  281. self.connect()
  282. return self._on_inbound_frame
  283. @on_inbound_frame.setter
  284. def on_inbound_frame(self, on_inbound_frame):
  285. self._on_inbound_frame = on_inbound_frame
  286. @property
  287. def frame_writer(self):
  288. if self._frame_writer is None:
  289. self._warn_force_connect('frame_writer')
  290. self.connect()
  291. return self._frame_writer
  292. @frame_writer.setter
  293. def frame_writer(self, frame_writer):
  294. self._frame_writer = frame_writer
  295. def _on_start(self, version_major, version_minor, server_properties,
  296. mechanisms, locales, argsig='FsSs'):
  297. client_properties = self.client_properties
  298. self.version_major = version_major
  299. self.version_minor = version_minor
  300. self.server_properties = server_properties
  301. if isinstance(mechanisms, string):
  302. mechanisms = mechanisms.encode('utf-8')
  303. self.mechanisms = mechanisms.split(b' ')
  304. self.locales = locales.split(' ')
  305. AMQP_LOGGER.debug(
  306. START_DEBUG_FMT,
  307. self.version_major, self.version_minor,
  308. self.server_properties, self.mechanisms, self.locales,
  309. )
  310. # Negotiate protocol extensions (capabilities)
  311. scap = server_properties.get('capabilities') or {}
  312. cap = client_properties.setdefault('capabilities', {})
  313. cap.update({
  314. wanted_cap: enable_cap
  315. for wanted_cap, enable_cap in items(self.negotiate_capabilities)
  316. if scap.get(wanted_cap)
  317. })
  318. if not cap:
  319. # no capabilities, server may not react well to having
  320. # this key present in client_properties, so we remove it.
  321. client_properties.pop('capabilities', None)
  322. for authentication in self.authentication:
  323. if authentication.mechanism in self.mechanisms:
  324. login_response = authentication.start(self)
  325. if login_response is not NotImplemented:
  326. break
  327. else:
  328. raise ConnectionError(
  329. "Couldn't find appropriate auth mechanism "
  330. "(can offer: {0}; available: {1})".format(
  331. b", ".join(m.mechanism
  332. for m in self.authentication
  333. if m.mechanism).decode(),
  334. b", ".join(self.mechanisms).decode()))
  335. self.send_method(
  336. spec.Connection.StartOk, argsig,
  337. (client_properties, authentication.mechanism,
  338. login_response, self.locale),
  339. )
  340. def _on_secure(self, challenge):
  341. pass
  342. def _on_tune(self, channel_max, frame_max, server_heartbeat, argsig='BlB'):
  343. client_heartbeat = self.client_heartbeat or 0
  344. self.channel_max = channel_max or self.channel_max
  345. self.frame_max = frame_max or self.frame_max
  346. self.server_heartbeat = server_heartbeat or 0
  347. # negotiate the heartbeat interval to the smaller of the
  348. # specified values
  349. if self.server_heartbeat == 0 or client_heartbeat == 0:
  350. self.heartbeat = max(self.server_heartbeat, client_heartbeat)
  351. else:
  352. self.heartbeat = min(self.server_heartbeat, client_heartbeat)
  353. # Ignore server heartbeat if client_heartbeat is disabled
  354. if not self.client_heartbeat:
  355. self.heartbeat = 0
  356. self.send_method(
  357. spec.Connection.TuneOk, argsig,
  358. (self.channel_max, self.frame_max, self.heartbeat),
  359. callback=self._on_tune_sent,
  360. )
  361. def _on_tune_sent(self, argsig='ssb'):
  362. self.send_method(
  363. spec.Connection.Open, argsig, (self.virtual_host, '', False),
  364. )
  365. def _on_open_ok(self):
  366. self._handshake_complete = True
  367. self.on_open(self)
  368. def Transport(self, host, connect_timeout,
  369. ssl=False, read_timeout=None, write_timeout=None,
  370. socket_settings=None, **kwargs):
  371. return Transport(
  372. host, connect_timeout=connect_timeout, ssl=ssl,
  373. read_timeout=read_timeout, write_timeout=write_timeout,
  374. socket_settings=socket_settings, **kwargs)
  375. @property
  376. def connected(self):
  377. return self._transport and self._transport.connected
  378. def collect(self):
  379. try:
  380. if self._transport:
  381. self._transport.close()
  382. temp_list = [x for x in values(self.channels or {})
  383. if x is not self]
  384. for ch in temp_list:
  385. ch.collect()
  386. except socket.error:
  387. pass # connection already closed on the other end
  388. finally:
  389. self._transport = self.connection = self.channels = None
  390. def _get_free_channel_id(self):
  391. try:
  392. return self._avail_channel_ids.pop()
  393. except IndexError:
  394. raise ResourceError(
  395. 'No free channel ids, current={0}, channel_max={1}'.format(
  396. len(self.channels), self.channel_max), spec.Channel.Open)
  397. def _claim_channel_id(self, channel_id):
  398. try:
  399. return self._avail_channel_ids.remove(channel_id)
  400. except ValueError:
  401. raise ConnectionError('Channel %r already open' % (channel_id,))
  402. def channel(self, channel_id=None, callback=None):
  403. """Create new channel.
  404. Fetch a Channel object identified by the numeric channel_id, or
  405. create that object if it doesn't already exist.
  406. """
  407. if self.channels is not None:
  408. try:
  409. return self.channels[channel_id]
  410. except KeyError:
  411. channel = self.Channel(self, channel_id, on_open=callback)
  412. channel.open()
  413. return channel
  414. raise RecoverableConnectionError('Connection already closed.')
  415. def is_alive(self):
  416. raise NotImplementedError('Use AMQP heartbeats')
  417. def drain_events(self, timeout=None):
  418. # read until message is ready
  419. while not self.blocking_read(timeout):
  420. pass
  421. def blocking_read(self, timeout=None):
  422. with self.transport.having_timeout(timeout):
  423. frame = self.transport.read_frame()
  424. return self.on_inbound_frame(frame)
  425. def on_inbound_method(self, channel_id, method_sig, payload, content):
  426. return self.channels[channel_id].dispatch_method(
  427. method_sig, payload, content,
  428. )
  429. def close(self, reply_code=0, reply_text='', method_sig=(0, 0),
  430. argsig='BsBB'):
  431. """Request a connection close.
  432. This method indicates that the sender wants to close the
  433. connection. This may be due to internal conditions (e.g. a
  434. forced shut-down) or due to an error handling a specific
  435. method, i.e. an exception. When a close is due to an
  436. exception, the sender provides the class and method id of the
  437. method which caused the exception.
  438. RULE:
  439. After sending this method any received method except the
  440. Close-OK method MUST be discarded.
  441. RULE:
  442. The peer sending this method MAY use a counter or timeout
  443. to detect failure of the other peer to respond correctly
  444. with the Close-OK method.
  445. RULE:
  446. When a server receives the Close method from a client it
  447. MUST delete all server-side resources associated with the
  448. client's context. A client CANNOT reconnect to a context
  449. after sending or receiving a Close method.
  450. PARAMETERS:
  451. reply_code: short
  452. The reply code. The AMQ reply codes are defined in AMQ
  453. RFC 011.
  454. reply_text: shortstr
  455. The localised reply text. This text can be logged as an
  456. aid to resolving issues.
  457. class_id: short
  458. failing method class
  459. When the close is provoked by a method exception, this
  460. is the class of the method.
  461. method_id: short
  462. failing method ID
  463. When the close is provoked by a method exception, this
  464. is the ID of the method.
  465. """
  466. if self._transport is None:
  467. # already closed
  468. return
  469. try:
  470. self.is_closing = True
  471. return self.send_method(
  472. spec.Connection.Close, argsig,
  473. (reply_code, reply_text, method_sig[0], method_sig[1]),
  474. wait=spec.Connection.CloseOk,
  475. )
  476. except (OSError, IOError, SSLError):
  477. self.is_closing = False
  478. # close connection
  479. self.collect()
  480. raise
  481. def _on_close(self, reply_code, reply_text, class_id, method_id):
  482. """Request a connection close.
  483. This method indicates that the sender wants to close the
  484. connection. This may be due to internal conditions (e.g. a
  485. forced shut-down) or due to an error handling a specific
  486. method, i.e. an exception. When a close is due to an
  487. exception, the sender provides the class and method id of the
  488. method which caused the exception.
  489. RULE:
  490. After sending this method any received method except the
  491. Close-OK method MUST be discarded.
  492. RULE:
  493. The peer sending this method MAY use a counter or timeout
  494. to detect failure of the other peer to respond correctly
  495. with the Close-OK method.
  496. RULE:
  497. When a server receives the Close method from a client it
  498. MUST delete all server-side resources associated with the
  499. client's context. A client CANNOT reconnect to a context
  500. after sending or receiving a Close method.
  501. PARAMETERS:
  502. reply_code: short
  503. The reply code. The AMQ reply codes are defined in AMQ
  504. RFC 011.
  505. reply_text: shortstr
  506. The localised reply text. This text can be logged as an
  507. aid to resolving issues.
  508. class_id: short
  509. failing method class
  510. When the close is provoked by a method exception, this
  511. is the class of the method.
  512. method_id: short
  513. failing method ID
  514. When the close is provoked by a method exception, this
  515. is the ID of the method.
  516. """
  517. self._x_close_ok()
  518. raise error_for_code(reply_code, reply_text,
  519. (class_id, method_id), ConnectionError)
  520. def _x_close_ok(self):
  521. """Confirm a connection close.
  522. This method confirms a Connection.Close method and tells the
  523. recipient that it is safe to release resources for the
  524. connection and close the socket.
  525. RULE:
  526. A peer that detects a socket closure without having
  527. received a Close-Ok handshake method SHOULD log the error.
  528. """
  529. self.send_method(spec.Connection.CloseOk, callback=self._on_close_ok)
  530. def _on_close_ok(self):
  531. """Confirm a connection close.
  532. This method confirms a Connection.Close method and tells the
  533. recipient that it is safe to release resources for the
  534. connection and close the socket.
  535. RULE:
  536. A peer that detects a socket closure without having
  537. received a Close-Ok handshake method SHOULD log the error.
  538. """
  539. self.collect()
  540. def _on_blocked(self):
  541. """Callback called when connection blocked.
  542. Notes:
  543. This is an RabbitMQ Extension.
  544. """
  545. reason = 'connection blocked, see broker logs'
  546. if self.on_blocked:
  547. return self.on_blocked(reason)
  548. def _on_unblocked(self):
  549. if self.on_unblocked:
  550. return self.on_unblocked()
  551. def send_heartbeat(self):
  552. self.frame_writer(8, 0, None, None, None)
  553. def heartbeat_tick(self, rate=2):
  554. """Send heartbeat packets if necessary.
  555. Raises:
  556. ~amqp.exceptions.ConnectionForvced: if none have been
  557. received recently.
  558. Note:
  559. This should be called frequently, on the order of
  560. once per second.
  561. Keyword Arguments:
  562. rate (int): Previously used, but ignored now.
  563. """
  564. AMQP_LOGGER.debug('heartbeat_tick : for connection %s',
  565. self._connection_id)
  566. if not self.heartbeat:
  567. return
  568. # treat actual data exchange in either direction as a heartbeat
  569. sent_now = self.bytes_sent
  570. recv_now = self.bytes_recv
  571. if self.prev_sent is None or self.prev_sent != sent_now:
  572. self.last_heartbeat_sent = monotonic()
  573. if self.prev_recv is None or self.prev_recv != recv_now:
  574. self.last_heartbeat_received = monotonic()
  575. now = monotonic()
  576. AMQP_LOGGER.debug(
  577. 'heartbeat_tick : Prev sent/recv: %s/%s, '
  578. 'now - %s/%s, monotonic - %s, '
  579. 'last_heartbeat_sent - %s, heartbeat int. - %s '
  580. 'for connection %s',
  581. self.prev_sent, self.prev_recv,
  582. sent_now, recv_now, now,
  583. self.last_heartbeat_sent,
  584. self.heartbeat,
  585. self._connection_id,
  586. )
  587. self.prev_sent, self.prev_recv = sent_now, recv_now
  588. # send a heartbeat if it's time to do so
  589. if now > self.last_heartbeat_sent + self.heartbeat:
  590. AMQP_LOGGER.debug(
  591. 'heartbeat_tick: sending heartbeat for connection %s',
  592. self._connection_id)
  593. self.send_heartbeat()
  594. self.last_heartbeat_sent = monotonic()
  595. # if we've missed two intervals' heartbeats, fail; this gives the
  596. # server enough time to send heartbeats a little late
  597. if (self.last_heartbeat_received and
  598. self.last_heartbeat_received + 2 *
  599. self.heartbeat < monotonic()):
  600. raise ConnectionForced('Too many heartbeats missed')
  601. @property
  602. def sock(self):
  603. return self.transport.sock
  604. @property
  605. def server_capabilities(self):
  606. return self.server_properties.get('capabilities') or {}