/usr/lib/python3/dist-packages/pika/connection.py is in python3-pika 0.11.0-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 | """Core connection objects"""
import ast
import sys
import collections
import copy
import logging
import math
import numbers
import platform
import warnings
if sys.version_info > (3,):
import urllib.parse as urlparse # pylint: disable=E0611,F0401
else:
import urlparse
from pika import __version__
from pika import callback
import pika.channel
from pika import credentials as pika_credentials
from pika import exceptions
from pika import frame
from pika import heartbeat
from pika import utils
from pika import spec
from pika.compat import (xrange, basestring, # pylint: disable=W0622
url_unquote, dictkeys, dict_itervalues,
dict_iteritems)
BACKPRESSURE_WARNING = ("Pika: Write buffer exceeded warning threshold at "
"%i bytes and an estimated %i frames behind")
PRODUCT = "Pika Python Client Library"
LOGGER = logging.getLogger(__name__)
class InternalCloseReasons(object):
"""Internal reason codes passed to the user's on_close_callback when the
connection is terminated abruptly, without reply code/text from the broker.
AMQP 0.9.1 specification cites IETF RFC 821 for reply codes. To avoid
conflict, the `InternalCloseReasons` namespace uses negative integers. These
are invalid for sending to the broker.
"""
SOCKET_ERROR = -1
BLOCKED_CONNECTION_TIMEOUT = -2
class Parameters(object): # pylint: disable=R0902
"""Base connection parameters class definition
:param bool backpressure_detection: `DEFAULT_BACKPRESSURE_DETECTION`
:param float|None blocked_connection_timeout:
`DEFAULT_BLOCKED_CONNECTION_TIMEOUT`
:param int channel_max: `DEFAULT_CHANNEL_MAX`
:param int connection_attempts: `DEFAULT_CONNECTION_ATTEMPTS`
:param credentials: `DEFAULT_CREDENTIALS`
:param int frame_max: `DEFAULT_FRAME_MAX`
:param int heartbeat: `DEFAULT_HEARTBEAT_TIMEOUT`
:param str host: `DEFAULT_HOST`
:param str locale: `DEFAULT_LOCALE`
:param int port: `DEFAULT_PORT`
:param float retry_delay: `DEFAULT_RETRY_DELAY`
:param float socket_timeout: `DEFAULT_SOCKET_TIMEOUT`
:param bool ssl: `DEFAULT_SSL`
:param dict ssl_options: `DEFAULT_SSL_OPTIONS`
:param str virtual_host: `DEFAULT_VIRTUAL_HOST`
"""
# Declare slots to protect against accidental assignment of an invalid
# attribute
__slots__ = (
'_backpressure_detection',
'_blocked_connection_timeout',
'_channel_max',
'_client_properties',
'_connection_attempts',
'_credentials',
'_frame_max',
'_heartbeat',
'_host',
'_locale',
'_port',
'_retry_delay',
'_socket_timeout',
'_ssl',
'_ssl_options',
'_virtual_host'
)
DEFAULT_USERNAME = 'guest'
DEFAULT_PASSWORD = 'guest'
DEFAULT_BACKPRESSURE_DETECTION = False
DEFAULT_BLOCKED_CONNECTION_TIMEOUT = None
DEFAULT_CHANNEL_MAX = pika.channel.MAX_CHANNELS
DEFAULT_CLIENT_PROPERTIES = None
DEFAULT_CREDENTIALS = pika_credentials.PlainCredentials(DEFAULT_USERNAME,
DEFAULT_PASSWORD)
DEFAULT_CONNECTION_ATTEMPTS = 1
DEFAULT_FRAME_MAX = spec.FRAME_MAX_SIZE
DEFAULT_HEARTBEAT_TIMEOUT = None # None accepts server's proposal
DEFAULT_HOST = 'localhost'
DEFAULT_LOCALE = 'en_US'
DEFAULT_PORT = 5672
DEFAULT_RETRY_DELAY = 2.0
DEFAULT_SOCKET_TIMEOUT = 0.25
DEFAULT_SSL = False
DEFAULT_SSL_OPTIONS = None
DEFAULT_SSL_PORT = 5671
DEFAULT_VIRTUAL_HOST = '/'
DEFAULT_HEARTBEAT_INTERVAL = DEFAULT_HEARTBEAT_TIMEOUT # DEPRECATED
def __init__(self):
self._backpressure_detection = None
self.backpressure_detection = self.DEFAULT_BACKPRESSURE_DETECTION
# If not None, blocked_connection_timeout is the timeout, in seconds,
# for the connection to remain blocked; if the timeout expires, the
# connection will be torn down, triggering the connection's
# on_close_callback
self._blocked_connection_timeout = None
self.blocked_connection_timeout = (
self.DEFAULT_BLOCKED_CONNECTION_TIMEOUT)
self._channel_max = None
self.channel_max = self.DEFAULT_CHANNEL_MAX
self._client_properties = None
self.client_properties = self.DEFAULT_CLIENT_PROPERTIES
self._connection_attempts = None
self.connection_attempts = self.DEFAULT_CONNECTION_ATTEMPTS
self._credentials = None
self.credentials = self.DEFAULT_CREDENTIALS
self._frame_max = None
self.frame_max = self.DEFAULT_FRAME_MAX
self._heartbeat = None
self.heartbeat = self.DEFAULT_HEARTBEAT_TIMEOUT
self._host = None
self.host = self.DEFAULT_HOST
self._locale = None
self.locale = self.DEFAULT_LOCALE
self._port = None
self.port = self.DEFAULT_PORT
self._retry_delay = None
self.retry_delay = self.DEFAULT_RETRY_DELAY
self._socket_timeout = None
self.socket_timeout = self.DEFAULT_SOCKET_TIMEOUT
self._ssl = None
self.ssl = self.DEFAULT_SSL
self._ssl_options = None
self.ssl_options = self.DEFAULT_SSL_OPTIONS
self._virtual_host = None
self.virtual_host = self.DEFAULT_VIRTUAL_HOST
def __repr__(self):
"""Represent the info about the instance.
:rtype: str
"""
return ('<%s host=%s port=%s virtual_host=%s ssl=%s>' %
(self.__class__.__name__, self.host, self.port,
self.virtual_host, self.ssl))
@property
def backpressure_detection(self):
"""
:returns: boolean indicating whether backpressure detection is
enabled. Defaults to `DEFAULT_BACKPRESSURE_DETECTION`.
"""
return self._backpressure_detection
@backpressure_detection.setter
def backpressure_detection(self, value):
"""
:param bool value: boolean indicating whether to enable backpressure
detection
"""
if not isinstance(value, bool):
raise TypeError('backpressure_detection must be a bool, '
'but got %r' % (value,))
self._backpressure_detection = value
@property
def blocked_connection_timeout(self):
"""
:returns: None or float blocked connection timeout. Defaults to
`DEFAULT_BLOCKED_CONNECTION_TIMEOUT`.
"""
return self._blocked_connection_timeout
@blocked_connection_timeout.setter
def blocked_connection_timeout(self, value):
"""
:param value: If not None, blocked_connection_timeout is the timeout, in
seconds, for the connection to remain blocked; if the timeout
expires, the connection will be torn down, triggering the
connection's on_close_callback
"""
if value is not None:
if not isinstance(value, numbers.Real):
raise TypeError('blocked_connection_timeout must be a Real '
'number, but got %r' % (value,))
if value < 0:
raise ValueError('blocked_connection_timeout must be >= 0, but '
'got %r' % (value,))
self._blocked_connection_timeout = value
@property
def channel_max(self):
"""
:returns: max preferred number of channels. Defaults to
`DEFAULT_CHANNEL_MAX`.
:rtype: int
"""
return self._channel_max
@channel_max.setter
def channel_max(self, value):
"""
:param int value: max preferred number of channels, between 1 and
`channel.MAX_CHANNELS`, inclusive
"""
if not isinstance(value, numbers.Integral):
raise TypeError('channel_max must be an int, but got %r' % (value,))
if value < 1 or value > pika.channel.MAX_CHANNELS:
raise ValueError('channel_max must be <= %i and > 0, but got %r' %
(pika.channel.MAX_CHANNELS, value))
self._channel_max = value
@property
def client_properties(self):
"""
:returns: None or dict of client properties used to override the fields
in the default client poperties reported to RabbitMQ via
`Connection.StartOk` method. Defaults to
`DEFAULT_CLIENT_PROPERTIES`.
"""
return self._client_properties
@client_properties.setter
def client_properties(self, value):
"""
:param value: None or dict of client properties used to override the
fields in the default client poperties reported to RabbitMQ via
`Connection.StartOk` method.
"""
if not isinstance(value, (dict, type(None),)):
raise TypeError('client_properties must be dict or None, '
'but got %r' % (value,))
# Copy the mutable object to avoid accidental side-effects
self._client_properties = copy.deepcopy(value)
@property
def connection_attempts(self):
"""
:returns: number of socket connection attempts. Defaults to
`DEFAULT_CONNECTION_ATTEMPTS`.
"""
return self._connection_attempts
@connection_attempts.setter
def connection_attempts(self, value):
"""
:param int value: number of socket connection attempts of at least 1
"""
if not isinstance(value, numbers.Integral):
raise TypeError('connection_attempts must be an int')
if value < 1:
raise ValueError('connection_attempts must be > 0, but got %r' %
(value,))
self._connection_attempts = value
@property
def credentials(self):
"""
:rtype: one of the classes from `pika.credentials.VALID_TYPES`. Defaults
to `DEFAULT_CREDENTIALS`.
"""
return self._credentials
@credentials.setter
def credentials(self, value):
"""
:param value: authentication credential object of one of the classes
from `pika.credentials.VALID_TYPES`
"""
if not isinstance(value, tuple(pika_credentials.VALID_TYPES)):
raise TypeError('Credentials must be an object of type: %r, but '
'got %r' % (pika_credentials.VALID_TYPES, value))
# Copy the mutable object to avoid accidental side-effects
self._credentials = copy.deepcopy(value)
@property
def frame_max(self):
"""
:returns: desired maximum AMQP frame size to use. Defaults to
`DEFAULT_FRAME_MAX`.
"""
return self._frame_max
@frame_max.setter
def frame_max(self, value):
"""
:param int value: desired maximum AMQP frame size to use between
`spec.FRAME_MIN_SIZE` and `spec.FRAME_MAX_SIZE`, inclusive
"""
if not isinstance(value, numbers.Integral):
raise TypeError('frame_max must be an int, but got %r' % (value,))
if value < spec.FRAME_MIN_SIZE:
raise ValueError('Min AMQP 0.9.1 Frame Size is %i, but got %r',
(spec.FRAME_MIN_SIZE, value,))
elif value > spec.FRAME_MAX_SIZE:
raise ValueError('Max AMQP 0.9.1 Frame Size is %i, but got %r',
(spec.FRAME_MAX_SIZE, value,))
self._frame_max = value
@property
def heartbeat(self):
"""
:returns: desired connection heartbeat timeout for negotiation or
None to accept broker's value. 0 turns heartbeat off. Defaults to
`DEFAULT_HEARTBEAT_TIMEOUT`.
:rtype: integer, float, or None
"""
return self._heartbeat
@heartbeat.setter
def heartbeat(self, value):
"""
:param value: desired connection heartbeat timeout for negotiation or
None to accept broker's value. 0 turns heartbeat off.
"""
if value is not None:
if not isinstance(value, numbers.Integral):
raise TypeError('heartbeat must be an int, but got %r' %
(value,))
if value < 0:
raise ValueError('heartbeat must >= 0, but got %r' % (value,))
self._heartbeat = value
@property
def host(self):
"""
:returns: hostname or ip address of broker. Defaults to `DEFAULT_HOST`.
:rtype: str
"""
return self._host
@host.setter
def host(self, value):
"""
:param str value: hostname or ip address of broker
"""
if not isinstance(value, basestring):
raise TypeError('host must be a str or unicode str, but got %r' %
(value,))
self._host = value
@property
def locale(self):
"""
:returns: locale value to pass to broker; e.g., 'en_US'. Defaults to
`DEFAULT_LOCALE`.
:rtype: str
"""
return self._locale
@locale.setter
def locale(self, value):
"""
:param str value: locale value to pass to broker; e.g., "en_US"
"""
if not isinstance(value, basestring):
raise TypeError('locale must be a str, but got %r' % (value,))
self._locale = value
@property
def port(self):
"""
:returns: port number of broker's listening socket. Defaults to
`DEFAULT_PORT`.
:rtype: int
"""
return self._port
@port.setter
def port(self, value):
"""
:param int value: port number of broker's listening socket
"""
if not isinstance(value, numbers.Integral):
raise TypeError('port must be an int, but got %r' % (value,))
self._port = value
@property
def retry_delay(self):
"""
:returns: interval between socket connection attempts; see also
`connection_attempts`. Defaults to `DEFAULT_RETRY_DELAY`.
:rtype: float
"""
return self._retry_delay
@retry_delay.setter
def retry_delay(self, value):
"""
:param float value: interval between socket connection attempts; see
also `connection_attempts`.
"""
if not isinstance(value, numbers.Real):
raise TypeError('retry_delay must be a float or int, but got %r' %
(value,))
self._retry_delay = value
@property
def socket_timeout(self):
"""
:returns: socket timeout value. Defaults to `DEFAULT_SOCKET_TIMEOUT`.
:rtype: float
"""
return self._socket_timeout
@socket_timeout.setter
def socket_timeout(self, value):
"""
:param float value: socket timeout value; NOTE: this is mostly unused
now, owing to switchover to to non-blocking socket setting after
initial socket connection establishment.
"""
if value is not None:
if not isinstance(value, numbers.Real):
raise TypeError('socket_timeout must be a float or int, '
'but got %r' % (value,))
if not value > 0:
raise ValueError('socket_timeout must be > 0, but got %r' %
(value,))
self._socket_timeout = value
@property
def ssl(self):
"""
:returns: boolean indicating whether to connect via SSL. Defaults to
`DEFAULT_SSL`.
"""
return self._ssl
@ssl.setter
def ssl(self, value):
"""
:param bool value: boolean indicating whether to connect via SSL
"""
if not isinstance(value, bool):
raise TypeError('ssl must be a bool, but got %r' % (value,))
self._ssl = value
@property
def ssl_options(self):
"""
:returns: None or a dict of options to pass to `ssl.wrap_socket`.
Defaults to `DEFAULT_SSL_OPTIONS`.
"""
return self._ssl_options
@ssl_options.setter
def ssl_options(self, value):
"""
:param value: None or a dict of options to pass to `ssl.wrap_socket`.
"""
if not isinstance(value, (dict, type(None))):
raise TypeError('ssl_options must be a dict or None, but got %r' %
(value,))
# Copy the mutable object to avoid accidental side-effects
self._ssl_options = copy.deepcopy(value)
@property
def virtual_host(self):
"""
:returns: rabbitmq virtual host name. Defaults to
`DEFAULT_VIRTUAL_HOST`.
"""
return self._virtual_host
@virtual_host.setter
def virtual_host(self, value):
"""
:param str value: rabbitmq virtual host name
"""
if not isinstance(value, basestring):
raise TypeError('virtual_host must be a str, but got %r' % (value,))
self._virtual_host = value
class ConnectionParameters(Parameters):
"""Connection parameters object that is passed into the connection adapter
upon construction.
"""
# Protect against accidental assignment of an invalid attribute
__slots__ = ()
class _DEFAULT(object):
"""Designates default parameter value; internal use"""
pass
def __init__(self, # pylint: disable=R0913,R0914,R0912
host=_DEFAULT,
port=_DEFAULT,
virtual_host=_DEFAULT,
credentials=_DEFAULT,
channel_max=_DEFAULT,
frame_max=_DEFAULT,
heartbeat=_DEFAULT,
ssl=_DEFAULT,
ssl_options=_DEFAULT,
connection_attempts=_DEFAULT,
retry_delay=_DEFAULT,
socket_timeout=_DEFAULT,
locale=_DEFAULT,
backpressure_detection=_DEFAULT,
blocked_connection_timeout=_DEFAULT,
client_properties=_DEFAULT,
**kwargs):
"""Create a new ConnectionParameters instance. See `Parameters` for
default values.
:param str host: Hostname or IP Address to connect to
:param int port: TCP port to connect to
:param str virtual_host: RabbitMQ virtual host to use
:param pika.credentials.Credentials credentials: auth credentials
:param int channel_max: Maximum number of channels to allow
:param int frame_max: The maximum byte size for an AMQP frame
:param int heartbeat: Heartbeat timeout. Max between this value
and server's proposal will be used as the heartbeat timeout. Use 0
to deactivate heartbeats and None to accept server's proposal.
:param bool ssl: Enable SSL
:param dict ssl_options: None or a dict of arguments to be passed to
ssl.wrap_socket
:param int connection_attempts: Maximum number of retry attempts
:param int|float retry_delay: Time to wait in seconds, before the next
:param int|float socket_timeout: Use for high latency networks
:param str locale: Set the locale value
:param bool backpressure_detection: DEPRECATED in favor of
`Connection.Blocked` and `Connection.Unblocked`. See
`Connection.add_on_connection_blocked_callback`.
:param blocked_connection_timeout: If not None,
the value is a non-negative timeout, in seconds, for the
connection to remain blocked (triggered by Connection.Blocked from
broker); if the timeout expires before connection becomes unblocked,
the connection will be torn down, triggering the adapter-specific
mechanism for informing client app about the closed connection (
e.g., on_close_callback or ConnectionClosed exception) with
`reason_code` of `InternalCloseReasons.BLOCKED_CONNECTION_TIMEOUT`.
:type blocked_connection_timeout: None, int, float
:param client_properties: None or dict of client properties used to
override the fields in the default client properties reported to
RabbitMQ via `Connection.StartOk` method.
:param heartbeat_interval: DEPRECATED; use `heartbeat` instead, and
don't pass both
"""
super(ConnectionParameters, self).__init__()
if backpressure_detection is not self._DEFAULT:
self.backpressure_detection = backpressure_detection
if blocked_connection_timeout is not self._DEFAULT:
self.blocked_connection_timeout = blocked_connection_timeout
if channel_max is not self._DEFAULT:
self.channel_max = channel_max
if client_properties is not self._DEFAULT:
self.client_properties = client_properties
if connection_attempts is not self._DEFAULT:
self.connection_attempts = connection_attempts
if credentials is not self._DEFAULT:
self.credentials = credentials
if frame_max is not self._DEFAULT:
self.frame_max = frame_max
if heartbeat is not self._DEFAULT:
self.heartbeat = heartbeat
try:
heartbeat_interval = kwargs.pop('heartbeat_interval')
except KeyError:
# Good, this one is deprecated
pass
else:
warnings.warn('heartbeat_interval is deprecated, use heartbeat',
DeprecationWarning, stacklevel=2)
if heartbeat is not self._DEFAULT:
raise TypeError('heartbeat and deprecated heartbeat_interval '
'are mutually-exclusive')
self.heartbeat = heartbeat_interval
if host is not self._DEFAULT:
self.host = host
if locale is not self._DEFAULT:
self.locale = locale
if retry_delay is not self._DEFAULT:
self.retry_delay = retry_delay
if socket_timeout is not self._DEFAULT:
self.socket_timeout = socket_timeout
if ssl is not self._DEFAULT:
self.ssl = ssl
if ssl_options is not self._DEFAULT:
self.ssl_options = ssl_options
# Set port after SSL status is known
if port is not self._DEFAULT:
self.port = port
elif ssl is not self._DEFAULT:
self.port = self.DEFAULT_SSL_PORT if self.ssl else self.DEFAULT_PORT
if virtual_host is not self._DEFAULT:
self.virtual_host = virtual_host
if kwargs:
raise TypeError('Unexpected kwargs: %r' % (kwargs,))
class URLParameters(Parameters):
"""Connect to RabbitMQ via an AMQP URL in the format::
amqp://username:password@host:port/<virtual_host>[?query-string]
Ensure that the virtual host is URI encoded when specified. For example if
you are using the default "/" virtual host, the value should be `%2f`.
See `Parameters` for default values.
Valid query string values are:
- backpressure_detection:
DEPRECATED in favor of
`Connection.Blocked` and `Connection.Unblocked`. See
`Connection.add_on_connection_blocked_callback`.
- channel_max:
Override the default maximum channel count value
- client_properties:
dict of client properties used to override the fields in the default
client properties reported to RabbitMQ via `Connection.StartOk`
method
- connection_attempts:
Specify how many times pika should try and reconnect before it gives up
- frame_max:
Override the default maximum frame size for communication
- heartbeat:
Specify the number of seconds between heartbeat frames to ensure that
the link between RabbitMQ and your application is up
- locale:
Override the default `en_US` locale value
- ssl:
Toggle SSL, possible values are `t`, `f`
- ssl_options:
Arguments passed to :meth:`ssl.wrap_socket`
- retry_delay:
The number of seconds to sleep before attempting to connect on
connection failure.
- socket_timeout:
Override low level socket timeout value
- blocked_connection_timeout:
Set the timeout, in seconds, that the connection may remain blocked
(triggered by Connection.Blocked from broker); if the timeout
expires before connection becomes unblocked, the connection will be
torn down, triggering the connection's on_close_callback
:param str url: The AMQP URL to connect to
"""
# Protect against accidental assignment of an invalid attribute
__slots__ = ('_all_url_query_values',)
# The name of the private function for parsing and setting a given URL query
# arg is constructed by catenating the query arg's name to this prefix
_SETTER_PREFIX = '_set_url_'
def __init__(self, url):
"""Create a new URLParameters instance.
:param str url: The URL value
"""
super(URLParameters, self).__init__()
self._all_url_query_values = None
# Handle the Protocol scheme
#
# Fix up scheme amqp(s) to http(s) so urlparse won't barf on python
# prior to 2.7. On Python 2.6.9,
# `urlparse('amqp://127.0.0.1/%2f?socket_timeout=1')` produces an
# incorrect path='/%2f?socket_timeout=1'
if url[0:4].lower() == 'amqp':
url = 'http' + url[4:]
# TODO Is support for the alternative http(s) schemes intentional?
parts = urlparse.urlparse(url)
if parts.scheme == 'https':
self.ssl = True
elif parts.scheme == 'http':
self.ssl = False
elif parts.scheme:
raise ValueError('Unexpected URL scheme %r; supported scheme '
'values: amqp, amqps' % (parts.scheme,))
if parts.hostname is not None:
self.host = parts.hostname
# Take care of port after SSL status is known
if parts.port is not None:
self.port = parts.port
else:
self.port = self.DEFAULT_SSL_PORT if self.ssl else self.DEFAULT_PORT
if parts.username is not None:
self.credentials = pika_credentials.PlainCredentials(url_unquote(parts.username),
url_unquote(parts.password))
# Get the Virtual Host
if len(parts.path) > 1:
self.virtual_host = url_unquote(parts.path.split('/')[1])
# Handle query string values, validating and assigning them
self._all_url_query_values = urlparse.parse_qs(parts.query)
for name, value in dict_iteritems(self._all_url_query_values):
try:
set_value = getattr(self, self._SETTER_PREFIX + name)
except AttributeError:
raise ValueError('Unknown URL parameter: %r' % (name,))
try:
(value,) = value
except ValueError:
raise ValueError('Expected exactly one value for URL parameter '
'%s, but got %i values: %s' % (
name, len(value), value))
set_value(value)
def _set_url_backpressure_detection(self, value):
"""Deserialize and apply the corresponding query string arg"""
try:
backpressure_detection = {'t': True, 'f': False}[value]
except KeyError:
raise ValueError('Invalid backpressure_detection value: %r' %
(value,))
self.backpressure_detection = backpressure_detection
def _set_url_blocked_connection_timeout(self, value):
"""Deserialize and apply the corresponding query string arg"""
try:
blocked_connection_timeout = float(value)
except ValueError as exc:
raise ValueError('Invalid blocked_connection_timeout value %r: %r' %
(value, exc,))
self.blocked_connection_timeout = blocked_connection_timeout
def _set_url_channel_max(self, value):
"""Deserialize and apply the corresponding query string arg"""
try:
channel_max = int(value)
except ValueError as exc:
raise ValueError('Invalid channel_max value %r: %r' % (value, exc,))
self.channel_max = channel_max
def _set_url_client_properties(self, value):
"""Deserialize and apply the corresponding query string arg"""
self.client_properties = ast.literal_eval(value)
def _set_url_connection_attempts(self, value):
"""Deserialize and apply the corresponding query string arg"""
try:
connection_attempts = int(value)
except ValueError as exc:
raise ValueError('Invalid connection_attempts value %r: %r' %
(value, exc,))
self.connection_attempts = connection_attempts
def _set_url_frame_max(self, value):
"""Deserialize and apply the corresponding query string arg"""
try:
frame_max = int(value)
except ValueError as exc:
raise ValueError('Invalid frame_max value %r: %r' % (value, exc,))
self.frame_max = frame_max
def _set_url_heartbeat(self, value):
"""Deserialize and apply the corresponding query string arg"""
if 'heartbeat_interval' in self._all_url_query_values:
raise ValueError('Deprecated URL parameter heartbeat_interval must '
'not be specified together with heartbeat')
try:
heartbeat_timeout = int(value)
except ValueError as exc:
raise ValueError('Invalid heartbeat value %r: %r' % (value, exc,))
self.heartbeat = heartbeat_timeout
def _set_url_heartbeat_interval(self, value):
"""Deserialize and apply the corresponding query string arg"""
warnings.warn('heartbeat_interval is deprecated, use heartbeat',
DeprecationWarning, stacklevel=2)
if 'heartbeat' in self._all_url_query_values:
raise ValueError('Deprecated URL parameter heartbeat_interval must '
'not be specified together with heartbeat')
try:
heartbeat_timeout = int(value)
except ValueError as exc:
raise ValueError('Invalid heartbeat_interval value %r: %r' %
(value, exc,))
self.heartbeat = heartbeat_timeout
def _set_url_locale(self, value):
"""Deserialize and apply the corresponding query string arg"""
self.locale = value
def _set_url_retry_delay(self, value):
"""Deserialize and apply the corresponding query string arg"""
try:
retry_delay = float(value)
except ValueError as exc:
raise ValueError('Invalid retry_delay value %r: %r' % (value, exc,))
self.retry_delay = retry_delay
def _set_url_socket_timeout(self, value):
"""Deserialize and apply the corresponding query string arg"""
try:
socket_timeout = float(value)
except ValueError as exc:
raise ValueError('Invalid socket_timeout value %r: %r' %
(value, exc,))
self.socket_timeout = socket_timeout
def _set_url_ssl_options(self, value):
"""Deserialize and apply the corresponding query string arg"""
self.ssl_options = ast.literal_eval(value)
class Connection(object):
"""This is the core class that implements communication with RabbitMQ. This
class should not be invoked directly but rather through the use of an
adapter such as SelectConnection or BlockingConnection.
:param pika.connection.Parameters parameters: Connection parameters
:param method on_open_callback: Called when the connection is opened
:param method on_open_error_callback: Called if the connection cant
be opened
:param method on_close_callback: Called when the connection is closed
"""
# Disable pylint messages concerning "method could be a funciton"
# pylint: disable=R0201
ON_CONNECTION_BACKPRESSURE = '_on_connection_backpressure'
ON_CONNECTION_BLOCKED = '_on_connection_blocked'
ON_CONNECTION_CLOSED = '_on_connection_closed'
ON_CONNECTION_ERROR = '_on_connection_error'
ON_CONNECTION_OPEN = '_on_connection_open'
ON_CONNECTION_UNBLOCKED = '_on_connection_unblocked'
CONNECTION_CLOSED = 0
CONNECTION_INIT = 1
CONNECTION_PROTOCOL = 2
CONNECTION_START = 3
CONNECTION_TUNE = 4
CONNECTION_OPEN = 5
CONNECTION_CLOSING = 6 # client-initiated close in progress
_STATE_NAMES = {
CONNECTION_CLOSED: 'CLOSED',
CONNECTION_INIT: 'INIT',
CONNECTION_PROTOCOL: 'PROTOCOL',
CONNECTION_START: 'START',
CONNECTION_TUNE: 'TUNE',
CONNECTION_OPEN: 'OPEN',
CONNECTION_CLOSING: 'CLOSING'
}
def __init__(self,
parameters=None,
on_open_callback=None,
on_open_error_callback=None,
on_close_callback=None):
"""Connection initialization expects an object that has implemented the
Parameters class and a callback function to notify when we have
successfully connected to the AMQP Broker.
Available Parameters classes are the ConnectionParameters class and
URLParameters class.
:param pika.connection.Parameters parameters: Connection parameters
:param method on_open_callback: Called when the connection is opened
:param method on_open_error_callback: Called if the connection can't
be established: on_open_error_callback(connection, str|exception)
:param method on_close_callback: Called when the connection is closed:
`on_close_callback(connection, reason_code, reason_text)`, where
`reason_code` is either an IETF RFC 821 reply code for AMQP-level
closures or a value from `pika.connection.InternalCloseReasons` for
internal causes, such as socket errors.
"""
self.connection_state = self.CONNECTION_CLOSED
# Holds timer when the initial connect or reconnect is scheduled
self._connection_attempt_timer = None
# Used to hold timer if configured for Connection.Blocked timeout
self._blocked_conn_timer = None
self.heartbeat = None
# Set our configuration options
self.params = (copy.deepcopy(parameters) if parameters is not None else
ConnectionParameters())
# Define our callback dictionary
self.callbacks = callback.CallbackManager()
# Attributes that will be properly initialized by _init_connection_state
# and/or during connection handshake.
self.server_capabilities = None
self.server_properties = None
self._body_max_length = None
self.known_hosts = None
self.closing = None
self._frame_buffer = None
self._channels = None
self._backpressure_multiplier = None
self.remaining_connection_attempts = None
self._init_connection_state()
# Add the on connection error callback
self.callbacks.add(0, self.ON_CONNECTION_ERROR,
on_open_error_callback or self._on_connection_error,
False)
# On connection callback
if on_open_callback:
self.add_on_open_callback(on_open_callback)
# On connection callback
if on_close_callback:
self.add_on_close_callback(on_close_callback)
self.connect()
def add_backpressure_callback(self, callback_method):
"""Call method "callback" when pika believes backpressure is being
applied.
:param method callback_method: The method to call
"""
self.callbacks.add(0, self.ON_CONNECTION_BACKPRESSURE, callback_method,
False)
def add_on_close_callback(self, callback_method):
"""Add a callback notification when the connection has closed. The
callback will be passed the connection, the reply_code (int) and the
reply_text (str), if sent by the remote server.
:param method callback_method: Callback to call on close
"""
self.callbacks.add(0, self.ON_CONNECTION_CLOSED, callback_method, False)
def add_on_connection_blocked_callback(self, callback_method):
"""Add a callback to be notified when RabbitMQ has sent a
``Connection.Blocked`` frame indicating that RabbitMQ is low on
resources. Publishers can use this to voluntarily suspend publishing,
instead of relying on back pressure throttling. The callback
will be passed the ``Connection.Blocked`` method frame.
See also `ConnectionParameters.blocked_connection_timeout`.
:param method callback_method: Callback to call on `Connection.Blocked`,
having the signature `callback_method(pika.frame.Method)`, where the
method frame's `method` member is of type
`pika.spec.Connection.Blocked`
"""
self.callbacks.add(0, spec.Connection.Blocked, callback_method, False)
def add_on_connection_unblocked_callback(self, callback_method):
"""Add a callback to be notified when RabbitMQ has sent a
``Connection.Unblocked`` frame letting publishers know it's ok
to start publishing again. The callback will be passed the
``Connection.Unblocked`` method frame.
:param method callback_method: Callback to call on
`Connection.Unblocked`, having the signature
`callback_method(pika.frame.Method)`, where the method frame's
`method` member is of type `pika.spec.Connection.Unblocked`
"""
self.callbacks.add(0, spec.Connection.Unblocked, callback_method, False)
def add_on_open_callback(self, callback_method):
"""Add a callback notification when the connection has opened.
:param method callback_method: Callback to call when open
"""
self.callbacks.add(0, self.ON_CONNECTION_OPEN, callback_method, False)
def add_on_open_error_callback(self, callback_method, remove_default=True):
"""Add a callback notification when the connection can not be opened.
The callback method should accept the connection object that could not
connect, and an optional error message.
:param method callback_method: Callback to call when can't connect
:param bool remove_default: Remove default exception raising callback
"""
if remove_default:
self.callbacks.remove(0, self.ON_CONNECTION_ERROR,
self._on_connection_error)
self.callbacks.add(0, self.ON_CONNECTION_ERROR, callback_method, False)
def add_timeout(self, deadline, callback_method):
"""Adapters should override to call the callback after the
specified number of seconds have elapsed, using a timer, or a
thread, or similar.
:param int deadline: The number of seconds to wait to call callback
:param method callback_method: The callback method
"""
raise NotImplementedError
def channel(self, on_open_callback, channel_number=None):
"""Create a new channel with the next available channel number or pass
in a channel number to use. Must be non-zero if you would like to
specify but it is recommended that you let Pika manage the channel
numbers.
:param method on_open_callback: The callback when the channel is opened
:param int channel_number: The channel number to use, defaults to the
next available.
:rtype: pika.channel.Channel
"""
if not self.is_open:
# TODO if state is OPENING, then ConnectionClosed might be wrong
raise exceptions.ConnectionClosed(
'Channel allocation requires an open connection: %s' % self)
if not channel_number:
channel_number = self._next_channel_number()
self._channels[channel_number] = self._create_channel(channel_number,
on_open_callback)
self._add_channel_callbacks(channel_number)
self._channels[channel_number].open()
return self._channels[channel_number]
def close(self, reply_code=200, reply_text='Normal shutdown'):
"""Disconnect from RabbitMQ. If there are any open channels, it will
attempt to close them prior to fully disconnecting. Channels which
have active consumers will attempt to send a Basic.Cancel to RabbitMQ
to cleanly stop the delivery of messages prior to closing the channel.
:param int reply_code: The code number for the close
:param str reply_text: The text reason for the close
"""
if self.is_closing or self.is_closed:
LOGGER.warning('Suppressing close request on %s', self)
return
# Initiate graceful closing of channels that are OPEN or OPENING
self._close_channels(reply_code, reply_text)
# Set our connection state
self._set_connection_state(self.CONNECTION_CLOSING)
LOGGER.info("Closing connection (%s): %s", reply_code, reply_text)
self.closing = reply_code, reply_text
# If there are channels that haven't finished closing yet, then
# _on_close_ready will finally be called from _on_channel_cleanup once
# all channels have been closed
if not self._channels:
# We can initiate graceful closing of the connection right away,
# since no more channels remain
self._on_close_ready()
else:
LOGGER.info('Connection.close is waiting for '
'%d channels to close: %s', len(self._channels), self)
def connect(self):
"""Invoke if trying to reconnect to a RabbitMQ server. Constructing the
Connection object should connect on its own.
"""
assert self._connection_attempt_timer is None, (
'connect timer was already scheduled')
assert self.is_closed, (
'connect expected CLOSED state, but got: {}'.format(
self._STATE_NAMES[self.connection_state]))
self._set_connection_state(self.CONNECTION_INIT)
# Schedule a timer callback to start the actual connection logic from
# event loop's context, thus avoiding error callbacks in the context of
# the caller, which could be the constructor.
self._connection_attempt_timer = self.add_timeout(
0,
self._on_connect_timer)
def remove_timeout(self, timeout_id):
"""Adapters should override: Remove a timeout
:param str timeout_id: The timeout id to remove
"""
raise NotImplementedError
def set_backpressure_multiplier(self, value=10):
"""Alter the backpressure multiplier value. We set this to 10 by default.
This value is used to raise warnings and trigger the backpressure
callback.
:param int value: The multiplier value to set
"""
self._backpressure_multiplier = value
#
# Connections state properties
#
@property
def is_closed(self):
"""
Returns a boolean reporting the current connection state.
"""
return self.connection_state == self.CONNECTION_CLOSED
@property
def is_closing(self):
"""
Returns True if connection is in the process of closing due to
client-initiated `close` request, but closing is not yet complete.
"""
return self.connection_state == self.CONNECTION_CLOSING
@property
def is_open(self):
"""
Returns a boolean reporting the current connection state.
"""
return self.connection_state == self.CONNECTION_OPEN
#
# Properties that reflect server capabilities for the current connection
#
@property
def basic_nack(self):
"""Specifies if the server supports basic.nack on the active connection.
:rtype: bool
"""
return self.server_capabilities.get('basic.nack', False)
@property
def consumer_cancel_notify(self):
"""Specifies if the server supports consumer cancel notification on the
active connection.
:rtype: bool
"""
return self.server_capabilities.get('consumer_cancel_notify', False)
@property
def exchange_exchange_bindings(self):
"""Specifies if the active connection supports exchange to exchange
bindings.
:rtype: bool
"""
return self.server_capabilities.get('exchange_exchange_bindings', False)
@property
def publisher_confirms(self):
"""Specifies if the active connection can use publisher confirmations.
:rtype: bool
"""
return self.server_capabilities.get('publisher_confirms', False)
#
# Internal methods for managing the communication process
#
def _adapter_connect(self):
"""Subclasses should override to set up the outbound socket connection.
:raises: NotImplementedError
"""
raise NotImplementedError
def _adapter_disconnect(self):
"""Subclasses should override this to cause the underlying transport
(socket) to close.
:raises: NotImplementedError
"""
raise NotImplementedError
def _add_channel_callbacks(self, channel_number):
"""Add the appropriate callbacks for the specified channel number.
:param int channel_number: The channel number for the callbacks
"""
# pylint: disable=W0212
# This permits us to garbage-collect our reference to the channel
# regardless of whether it was closed by client or broker, and do so
# after all channel-close callbacks.
self._channels[channel_number]._add_on_cleanup_callback(
self._on_channel_cleanup)
def _add_connection_start_callback(self):
"""Add a callback for when a Connection.Start frame is received from
the broker.
"""
self.callbacks.add(0, spec.Connection.Start, self._on_connection_start)
def _add_connection_tune_callback(self):
"""Add a callback for when a Connection.Tune frame is received."""
self.callbacks.add(0, spec.Connection.Tune, self._on_connection_tune)
def _append_frame_buffer(self, value):
"""Append the bytes to the frame buffer.
:param str value: The bytes to append to the frame buffer
"""
self._frame_buffer += value
@property
def _buffer_size(self):
"""Return the suggested buffer size from the connection state/tune or
the default if that is None.
:rtype: int
"""
return self.params.frame_max or spec.FRAME_MAX_SIZE
def _check_for_protocol_mismatch(self, value):
"""Invoked when starting a connection to make sure it's a supported
protocol.
:param pika.frame.Method value: The frame to check
:raises: ProtocolVersionMismatch
"""
if (value.method.version_major,
value.method.version_minor) != spec.PROTOCOL_VERSION[0:2]:
# TODO This should call _on_terminate for proper callbacks and
# cleanup
raise exceptions.ProtocolVersionMismatch(frame.ProtocolHeader(),
value)
@property
def _client_properties(self):
"""Return the client properties dictionary.
:rtype: dict
"""
properties = {
'product': PRODUCT,
'platform': 'Python %s' % platform.python_version(),
'capabilities': {
'authentication_failure_close': True,
'basic.nack': True,
'connection.blocked': True,
'consumer_cancel_notify': True,
'publisher_confirms': True
},
'information': 'See http://pika.rtfd.org',
'version': __version__
}
if self.params.client_properties:
properties.update(self.params.client_properties)
return properties
def _close_channels(self, reply_code, reply_text):
"""Initiate graceful closing of channels that are in OPEN or OPENING
states, passing reply_code and reply_text.
:param int reply_code: The code for why the channels are being closed
:param str reply_text: The text reason for why the channels are closing
"""
assert self.is_open, str(self)
for channel_number in dictkeys(self._channels):
chan = self._channels[channel_number]
if not (chan.is_closing or chan.is_closed):
chan.close(reply_code, reply_text)
def _combine(self, val1, val2):
"""Pass in two values, if a is 0, return b otherwise if b is 0,
return a. If neither case matches return the smallest value.
:param int val1: The first value
:param int val2: The second value
:rtype: int
"""
return min(val1, val2) or (val1 or val2)
def _connect(self):
"""Attempt to connect to RabbitMQ
:rtype: bool
"""
warnings.warn('This method is deprecated, use Connection.connect',
DeprecationWarning)
def _create_channel(self, channel_number, on_open_callback):
"""Create a new channel using the specified channel number and calling
back the method specified by on_open_callback
:param int channel_number: The channel number to use
:param method on_open_callback: The callback when the channel is opened
"""
LOGGER.debug('Creating channel %s', channel_number)
return pika.channel.Channel(self, channel_number, on_open_callback)
def _create_heartbeat_checker(self):
"""Create a heartbeat checker instance if there is a heartbeat interval
set.
:rtype: pika.heartbeat.Heartbeat
"""
if self.params.heartbeat is not None and self.params.heartbeat > 0:
LOGGER.debug('Creating a HeartbeatChecker: %r',
self.params.heartbeat)
return heartbeat.HeartbeatChecker(self, self.params.heartbeat)
def _remove_heartbeat(self):
"""Stop the heartbeat checker if it exists
"""
if self.heartbeat:
self.heartbeat.stop()
self.heartbeat = None
def _deliver_frame_to_channel(self, value):
"""Deliver the frame to the channel specified in the frame.
:param pika.frame.Method value: The frame to deliver
"""
if not value.channel_number in self._channels:
# This should never happen and would constitute breach of the
# protocol
LOGGER.critical(
'Received %s frame for unregistered channel %i on %s',
value.NAME, value.channel_number, self)
return
# pylint: disable=W0212
self._channels[value.channel_number]._handle_content_frame(value)
def _detect_backpressure(self):
"""Attempt to calculate if TCP backpressure is being applied due to
our outbound buffer being larger than the average frame size over
a window of frames.
"""
avg_frame_size = self.bytes_sent / self.frames_sent
buffer_size = sum([len(f) for f in self.outbound_buffer])
if buffer_size > (avg_frame_size * self._backpressure_multiplier):
LOGGER.warning(BACKPRESSURE_WARNING, buffer_size,
int(buffer_size / avg_frame_size))
self.callbacks.process(0, self.ON_CONNECTION_BACKPRESSURE, self)
def _ensure_closed(self):
"""If the connection is not closed, close it."""
if self.is_open:
self.close()
def _flush_outbound(self):
"""Adapters should override to flush the contents of outbound_buffer
out along the socket.
:raises: NotImplementedError
"""
raise NotImplementedError
def _get_body_frame_max_length(self):
"""Calculate the maximum amount of bytes that can be in a body frame.
:rtype: int
"""
return (
self.params.frame_max - spec.FRAME_HEADER_SIZE - spec.FRAME_END_SIZE
)
def _get_credentials(self, method_frame):
"""Get credentials for authentication.
:param pika.frame.MethodFrame method_frame: The Connection.Start frame
:rtype: tuple(str, str)
"""
(auth_type,
response) = self.params.credentials.response_for(method_frame.method)
if not auth_type:
# TODO this should call _on_terminate for proper callbacks and
# cleanup instead
raise exceptions.AuthenticationError(self.params.credentials.TYPE)
self.params.credentials.erase_credentials()
return auth_type, response
def _has_pending_callbacks(self, value):
"""Return true if there are any callbacks pending for the specified
frame.
:param pika.frame.Method value: The frame to check
:rtype: bool
"""
return self.callbacks.pending(value.channel_number, value.method)
def _init_connection_state(self):
"""Initialize or reset all of the internal state variables for a given
connection. On disconnect or reconnect all of the state needs to
be wiped.
"""
# Connection state
self._set_connection_state(self.CONNECTION_CLOSED)
# Negotiated server properties
self.server_properties = None
# Outbound buffer for buffering writes until we're able to send them
self.outbound_buffer = collections.deque([])
# Inbound buffer for decoding frames
self._frame_buffer = bytes()
# Dict of open channels
self._channels = dict()
# Remaining connection attempts
self.remaining_connection_attempts = self.params.connection_attempts
# Data used for Heartbeat checking and back-pressure detection
self.bytes_sent = 0
self.bytes_received = 0
self.frames_sent = 0
self.frames_received = 0
self.heartbeat = None
# Default back-pressure multiplier value
self._backpressure_multiplier = 10
# When closing, hold reason why
self.closing = 0, 'Not specified'
# Our starting point once connected, first frame received
self._add_connection_start_callback()
# Add a callback handler for the Broker telling us to disconnect.
# NOTE: As of RabbitMQ 3.6.0, RabbitMQ broker may send Connection.Close
# to signal error during connection setup (and wait a longish time
# before closing the TCP/IP stream). Earlier RabbitMQ versions
# simply closed the TCP/IP stream.
self.callbacks.add(0, spec.Connection.Close, self._on_connection_close)
if self._connection_attempt_timer is not None:
# Connection attempt timer was active when teardown was initiated
self.remove_timeout(self._connection_attempt_timer)
self._connection_attempt_timer = None
if self.params.blocked_connection_timeout is not None:
if self._blocked_conn_timer is not None:
# Blocked connection timer was active when teardown was
# initiated
self.remove_timeout(self._blocked_conn_timer)
self._blocked_conn_timer = None
self.add_on_connection_blocked_callback(
self._on_connection_blocked)
self.add_on_connection_unblocked_callback(
self._on_connection_unblocked)
def _is_method_frame(self, value):
"""Returns true if the frame is a method frame.
:param pika.frame.Frame value: The frame to evaluate
:rtype: bool
"""
return isinstance(value, frame.Method)
def _is_protocol_header_frame(self, value):
"""Returns True if it's a protocol header frame.
:rtype: bool
"""
return isinstance(value, frame.ProtocolHeader)
def _next_channel_number(self):
"""Return the next available channel number or raise an exception.
:rtype: int
"""
limit = self.params.channel_max or pika.channel.MAX_CHANNELS
if len(self._channels) >= limit:
raise exceptions.NoFreeChannels()
for num in xrange(1, len(self._channels) + 1):
if num not in self._channels:
return num
return len(self._channels) + 1
def _on_channel_cleanup(self, channel):
"""Remove the channel from the dict of channels when Channel.CloseOk is
sent. If connection is closing and no more channels remain, proceed to
`_on_close_ready`.
:param pika.channel.Channel channel: channel instance
"""
try:
del self._channels[channel.channel_number]
LOGGER.debug('Removed channel %s', channel.channel_number)
except KeyError:
LOGGER.error('Channel %r not in channels',
channel.channel_number)
if self.is_closing:
if not self._channels:
# Initiate graceful closing of the connection
self._on_close_ready()
else:
# Once Connection enters CLOSING state, all remaining channels
# should also be in CLOSING state. Deviation from this would
# prevent Connection from completing its closing procedure.
channels_not_in_closing_state = [
chan for chan in dict_itervalues(self._channels)
if not chan.is_closing]
if channels_not_in_closing_state:
LOGGER.critical(
'Connection in CLOSING state has non-CLOSING '
'channels: %r', channels_not_in_closing_state)
def _on_close_ready(self):
"""Called when the Connection is in a state that it can close after
a close has been requested. This happens, for example, when all of the
channels are closed that were open when the close request was made.
"""
if self.is_closed:
LOGGER.warning('_on_close_ready invoked when already closed')
return
self._send_connection_close(self.closing[0], self.closing[1])
def _on_connected(self):
"""Invoked when the socket is connected and it's time to start speaking
AMQP with the broker.
"""
self._set_connection_state(self.CONNECTION_PROTOCOL)
# Start the communication with the RabbitMQ Broker
self._send_frame(frame.ProtocolHeader())
def _on_blocked_connection_timeout(self):
""" Called when the "connection blocked timeout" expires. When this
happens, we tear down the connection
"""
self._blocked_conn_timer = None
self._on_terminate(InternalCloseReasons.BLOCKED_CONNECTION_TIMEOUT,
'Blocked connection timeout expired')
def _on_connection_blocked(self, method_frame):
"""Handle Connection.Blocked notification from RabbitMQ broker
:param pika.frame.Method method_frame: method frame having `method`
member of type `pika.spec.Connection.Blocked`
"""
LOGGER.warning('Received %s from broker', method_frame)
if self._blocked_conn_timer is not None:
# RabbitMQ is not supposed to repeat Connection.Blocked, but it
# doesn't hurt to be careful
LOGGER.warning('_blocked_conn_timer %s already set when '
'_on_connection_blocked is called',
self._blocked_conn_timer)
else:
self._blocked_conn_timer = self.add_timeout(
self.params.blocked_connection_timeout,
self._on_blocked_connection_timeout)
def _on_connection_unblocked(self, method_frame):
"""Handle Connection.Unblocked notification from RabbitMQ broker
:param pika.frame.Method method_frame: method frame having `method`
member of type `pika.spec.Connection.Blocked`
"""
LOGGER.info('Received %s from broker', method_frame)
if self._blocked_conn_timer is None:
# RabbitMQ is supposed to pair Connection.Blocked/Unblocked, but it
# doesn't hurt to be careful
LOGGER.warning('_blocked_conn_timer was not active when '
'_on_connection_unblocked called')
else:
self.remove_timeout(self._blocked_conn_timer)
self._blocked_conn_timer = None
def _on_connection_close(self, method_frame):
"""Called when the connection is closed remotely via Connection.Close
frame from broker.
:param pika.frame.Method method_frame: The Connection.Close frame
"""
LOGGER.debug('_on_connection_close: frame=%s', method_frame)
self.closing = (method_frame.method.reply_code,
method_frame.method.reply_text)
self._on_terminate(self.closing[0], self.closing[1])
def _on_connection_close_ok(self, method_frame):
"""Called when Connection.CloseOk is received from remote.
:param pika.frame.Method method_frame: The Connection.CloseOk frame
"""
LOGGER.debug('_on_connection_close_ok: frame=%s', method_frame)
self._on_terminate(self.closing[0], self.closing[1])
def _on_connection_error(self, _connection_unused, error_message=None):
"""Default behavior when the connecting connection can not connect.
:raises: exceptions.AMQPConnectionError
"""
raise exceptions.AMQPConnectionError(error_message or
self.params.connection_attempts)
def _on_connection_open(self, method_frame):
"""
This is called once we have tuned the connection with the server and
called the Connection.Open on the server and it has replied with
Connection.Ok.
"""
# TODO _on_connection_open - what if user started closing it already?
# It shouldn't transition to OPEN if in closing state. Just log and skip
# the rest.
self.known_hosts = method_frame.method.known_hosts
# We're now connected at the AMQP level
self._set_connection_state(self.CONNECTION_OPEN)
# Call our initial callback that we're open
self.callbacks.process(0, self.ON_CONNECTION_OPEN, self, self)
def _on_connection_start(self, method_frame):
"""This is called as a callback once we have received a Connection.Start
from the server.
:param pika.frame.Method method_frame: The frame received
:raises: UnexpectedFrameError
"""
self._set_connection_state(self.CONNECTION_START)
if self._is_protocol_header_frame(method_frame):
raise exceptions.UnexpectedFrameError
self._check_for_protocol_mismatch(method_frame)
self._set_server_information(method_frame)
self._add_connection_tune_callback()
self._send_connection_start_ok(*self._get_credentials(method_frame))
def _on_connect_timer(self):
"""Callback for self._connection_attempt_timer: initiate connection
attempt in the context of the event loop
"""
self._connection_attempt_timer = None
error = self._adapter_connect()
if not error:
return self._on_connected()
self.remaining_connection_attempts -= 1
LOGGER.warning('Could not connect, %i attempts left',
self.remaining_connection_attempts)
if self.remaining_connection_attempts > 0:
LOGGER.info('Retrying in %i seconds', self.params.retry_delay)
self._connection_attempt_timer = self.add_timeout(
self.params.retry_delay,
self._on_connect_timer)
else:
# TODO connect must not call failure callback from constructor. The
# current behavior is error-prone, because the user code may get a
# callback upon socket connection failure before user's other state
# may be sufficiently initialized. Constructors must either succeed
# or raise an exception. To be forward-compatible with failure
# reporting from fully non-blocking connection establishment,
# connect() should set INIT state and schedule a 0-second timer to
# continue the rest of the logic in a private method. The private
# method should use itself instead of connect() as the callback for
# scheduling retries.
# TODO This should use _on_terminate for consistent behavior/cleanup
self.callbacks.process(0, self.ON_CONNECTION_ERROR, self, self,
error)
self.remaining_connection_attempts = self.params.connection_attempts
self._set_connection_state(self.CONNECTION_CLOSED)
@staticmethod
def _tune_heartbeat_timeout(client_value, server_value):
""" Determine heartbeat timeout per AMQP 0-9-1 rules
Per https://www.rabbitmq.com/resources/specs/amqp0-9-1.pdf,
> Both peers negotiate the limits to the lowest agreed value as follows:
> - The server MUST tell the client what limits it proposes.
> - The client responds and **MAY reduce those limits** for its
connection
When negotiating heartbeat timeout, the reasoning needs to be reversed.
The way I think it makes sense to interpret this rule for heartbeats is
that the consumable resource is the frequency of heartbeats, which is
the inverse of the timeout. The more frequent heartbeats consume more
resources than less frequent heartbeats. So, when both heartbeat
timeouts are non-zero, we should pick the max heartbeat timeout rather
than the min. The heartbeat timeout value 0 (zero) has a special
meaning - it's supposed to disable the timeout. This makes zero a
setting for the least frequent heartbeats (i.e., never); therefore, if
any (or both) of the two is zero, then the above rules would suggest
that negotiation should yield 0 value for heartbeat, effectively turning
it off.
:param client_value: None to accept server_value; otherwise, an integral
number in seconds; 0 (zero) to disable heartbeat.
:param server_value: integral value of the heartbeat timeout proposed by
broker; 0 (zero) to disable heartbeat.
:returns: the value of the heartbeat timeout to use and return to broker
"""
if client_value is None:
# Accept server's limit
timeout = server_value
elif client_value == 0 or server_value == 0:
# 0 has a special meaning "disable heartbeats", which makes it the
# least frequent heartbeat value there is
timeout = 0
else:
# Pick the one with the bigger heartbeat timeout (i.e., the less
# frequent one)
timeout = max(client_value, server_value)
return timeout
def _on_connection_tune(self, method_frame):
"""Once the Broker sends back a Connection.Tune, we will set our tuning
variables that have been returned to us and kick off the Heartbeat
monitor if required, send our TuneOk and then the Connection. Open rpc
call on channel 0.
:param pika.frame.Method method_frame: The frame received
"""
self._set_connection_state(self.CONNECTION_TUNE)
# Get our max channels, frames and heartbeat interval
self.params.channel_max = self._combine(self.params.channel_max,
method_frame.method.channel_max)
self.params.frame_max = self._combine(self.params.frame_max,
method_frame.method.frame_max)
# Negotiate heatbeat timeout
self.params.heartbeat = self._tune_heartbeat_timeout(
client_value=self.params.heartbeat,
server_value=method_frame.method.heartbeat)
# Calculate the maximum pieces for body frames
self._body_max_length = self._get_body_frame_max_length()
# Create a new heartbeat checker if needed
self.heartbeat = self._create_heartbeat_checker()
# Send the TuneOk response with what we've agreed upon
self._send_connection_tune_ok()
# Send the Connection.Open RPC call for the vhost
self._send_connection_open()
def _on_data_available(self, data_in):
"""This is called by our Adapter, passing in the data from the socket.
As long as we have buffer try and map out frame data.
:param str data_in: The data that is available to read
"""
self._append_frame_buffer(data_in)
while self._frame_buffer:
consumed_count, frame_value = self._read_frame()
if not frame_value:
return
self._trim_frame_buffer(consumed_count)
self._process_frame(frame_value)
def _on_terminate(self, reason_code, reason_text):
"""Terminate the connection and notify registered ON_CONNECTION_ERROR
and/or ON_CONNECTION_CLOSED callbacks
:param integer reason_code: either IETF RFC 821 reply code for
AMQP-level closures or a value from `InternalCloseReasons` for
internal causes, such as socket errors
:param str reason_text: human-readable text message describing the error
"""
LOGGER.info(
'Disconnected from RabbitMQ at %s:%i (%s): %s',
self.params.host, self.params.port, reason_code,
reason_text)
if not isinstance(reason_code, numbers.Integral):
raise TypeError('reason_code must be an integer, but got %r'
% (reason_code,))
# Stop the heartbeat checker if it exists
self._remove_heartbeat()
# Remove connection management callbacks
# TODO This call was moved here verbatim from legacy code and the
# following doesn't seem to be right: `Connection.Open` here is
# unexpected, we don't appear to ever register it, and the broker
# shouldn't be sending `Connection.Open` to us, anyway.
self._remove_callbacks(0, [spec.Connection.Close, spec.Connection.Start,
spec.Connection.Open])
if self.params.blocked_connection_timeout is not None:
self._remove_callbacks(0, [spec.Connection.Blocked,
spec.Connection.Unblocked])
# Close the socket
self._adapter_disconnect()
# Determine whether this was an error during connection setup
connection_error = None
if self.connection_state == self.CONNECTION_PROTOCOL:
LOGGER.error('Incompatible Protocol Versions')
connection_error = exceptions.IncompatibleProtocolError(
reason_code,
reason_text)
elif self.connection_state == self.CONNECTION_START:
LOGGER.error('Connection closed while authenticating indicating a '
'probable authentication error')
connection_error = exceptions.ProbableAuthenticationError(
reason_code,
reason_text)
elif self.connection_state == self.CONNECTION_TUNE:
LOGGER.error('Connection closed while tuning the connection '
'indicating a probable permission error when '
'accessing a virtual host')
connection_error = exceptions.ProbableAccessDeniedError(
reason_code,
reason_text)
elif self.connection_state not in [self.CONNECTION_OPEN,
self.CONNECTION_CLOSED,
self.CONNECTION_CLOSING]:
LOGGER.warning('Unexpected connection state on disconnect: %i',
self.connection_state)
# Transition to closed state
self._set_connection_state(self.CONNECTION_CLOSED)
# Inform our channel proxies
for channel in dictkeys(self._channels):
if channel not in self._channels:
continue
# pylint: disable=W0212
self._channels[channel]._on_close_meta(reason_code, reason_text)
# Inform interested parties
if connection_error is not None:
LOGGER.error('Connection setup failed due to %r', connection_error)
self.callbacks.process(0,
self.ON_CONNECTION_ERROR,
self, self,
connection_error)
self.callbacks.process(0, self.ON_CONNECTION_CLOSED, self, self,
reason_code, reason_text)
# Reset connection properties
self._init_connection_state()
def _process_callbacks(self, frame_value):
"""Process the callbacks for the frame if the frame is a method frame
and if it has any callbacks pending.
:param pika.frame.Method frame_value: The frame to process
:rtype: bool
"""
if (self._is_method_frame(frame_value) and
self._has_pending_callbacks(frame_value)):
self.callbacks.process(frame_value.channel_number, # Prefix
frame_value.method, # Key
self, # Caller
frame_value) # Args
return True
return False
def _process_frame(self, frame_value):
"""Process an inbound frame from the socket.
:param frame_value: The frame to process
:type frame_value: pika.frame.Frame | pika.frame.Method
"""
# Will receive a frame type of -1 if protocol version mismatch
if frame_value.frame_type < 0:
return
# Keep track of how many frames have been read
self.frames_received += 1
# Process any callbacks, if True, exit method
if self._process_callbacks(frame_value):
return
# If a heartbeat is received, update the checker
if isinstance(frame_value, frame.Heartbeat):
if self.heartbeat:
self.heartbeat.received()
else:
LOGGER.warning('Received heartbeat frame without a heartbeat '
'checker')
# If the frame has a channel number beyond the base channel, deliver it
elif frame_value.channel_number > 0:
self._deliver_frame_to_channel(frame_value)
def _read_frame(self):
"""Try and read from the frame buffer and decode a frame.
:rtype tuple: (int, pika.frame.Frame)
"""
return frame.decode_frame(self._frame_buffer)
def _remove_callback(self, channel_number, method_class):
"""Remove the specified method_frame callback if it is set for the
specified channel number.
:param int channel_number: The channel number to remove the callback on
:param pika.amqp_object.Method method_class: The method class for the
callback
"""
self.callbacks.remove(str(channel_number), method_class)
def _remove_callbacks(self, channel_number, method_classes):
"""Remove the callbacks for the specified channel number and list of
method frames.
:param int channel_number: The channel number to remove the callback on
:param sequence method_classes: The method classes (derived from
`pika.amqp_object.Method`) for the callbacks
"""
for method_frame in method_classes:
self._remove_callback(channel_number, method_frame)
def _rpc(self, channel_number, method,
callback_method=None,
acceptable_replies=None):
"""Make an RPC call for the given callback, channel number and method.
acceptable_replies lists out what responses we'll process from the
server with the specified callback.
:param int channel_number: The channel number for the RPC call
:param pika.amqp_object.Method method: The method frame to call
:param method callback_method: The callback for the RPC response
:param list acceptable_replies: The replies this RPC call expects
"""
# Validate that acceptable_replies is a list or None
if acceptable_replies and not isinstance(acceptable_replies, list):
raise TypeError('acceptable_replies should be list or None')
# Validate the callback is callable
if callback_method:
if not utils.is_callable(callback_method):
raise TypeError('callback should be None, function or method.')
for reply in acceptable_replies:
self.callbacks.add(channel_number, reply, callback_method)
# Send the rpc call to RabbitMQ
self._send_method(channel_number, method)
def _send_connection_close(self, reply_code, reply_text):
"""Send a Connection.Close method frame.
:param int reply_code: The reason for the close
:param str reply_text: The text reason for the close
"""
self._rpc(0, spec.Connection.Close(reply_code, reply_text, 0, 0),
self._on_connection_close_ok, [spec.Connection.CloseOk])
def _send_connection_open(self):
"""Send a Connection.Open frame"""
self._rpc(0, spec.Connection.Open(self.params.virtual_host,
insist=True),
self._on_connection_open, [spec.Connection.OpenOk])
def _send_connection_start_ok(self, authentication_type, response):
"""Send a Connection.StartOk frame
:param str authentication_type: The auth type value
:param str response: The encoded value to send
"""
self._send_method(0,
spec.Connection.StartOk(self._client_properties,
authentication_type, response,
self.params.locale))
def _send_connection_tune_ok(self):
"""Send a Connection.TuneOk frame"""
self._send_method(0, spec.Connection.TuneOk(self.params.channel_max,
self.params.frame_max,
self.params.heartbeat))
def _send_frame(self, frame_value):
"""This appends the fully generated frame to send to the broker to the
output buffer which will be then sent via the connection adapter.
:param frame_value: The frame to write
:type frame_value: pika.frame.Frame|pika.frame.ProtocolHeader
:raises: exceptions.ConnectionClosed
"""
if self.is_closed:
LOGGER.error('Attempted to send frame when closed')
raise exceptions.ConnectionClosed
marshaled_frame = frame_value.marshal()
self.bytes_sent += len(marshaled_frame)
self.frames_sent += 1
self.outbound_buffer.append(marshaled_frame)
self._flush_outbound()
if self.params.backpressure_detection:
self._detect_backpressure()
def _send_method(self, channel_number, method, content=None):
"""Constructs a RPC method frame and then sends it to the broker.
:param int channel_number: The channel number for the frame
:param pika.amqp_object.Method method: The method to send
:param tuple content: If set, is a content frame, is tuple of
properties and body.
"""
if content:
self._send_message(channel_number, method, content)
else:
self._send_frame(frame.Method(channel_number, method))
def _send_message(self, channel_number, method, content=None):
"""Send the message directly, bypassing the single _send_frame
invocation by directly appending to the output buffer and flushing
within a lock.
:param int channel_number: The channel number for the frame
:param pika.amqp_object.Method method: The method frame to send
:param tuple content: If set, is a content frame, is tuple of
properties and body.
"""
length = len(content[1])
write_buffer = [frame.Method(channel_number, method).marshal(),
frame.Header(channel_number, length,
content[0]).marshal()]
if content[1]:
chunks = int(math.ceil(float(length) / self._body_max_length))
for chunk in xrange(0, chunks):
start = chunk * self._body_max_length
end = start + self._body_max_length
if end > length:
end = length
write_buffer.append(frame.Body(channel_number,
content[1][start:end]).marshal())
self.outbound_buffer += write_buffer
self.frames_sent += len(write_buffer)
self.bytes_sent += sum(len(frame) for frame in write_buffer)
self._flush_outbound()
if self.params.backpressure_detection:
self._detect_backpressure()
def _set_connection_state(self, connection_state):
"""Set the connection state.
:param int connection_state: The connection state to set
"""
self.connection_state = connection_state
def _set_server_information(self, method_frame):
"""Set the server properties and capabilities
:param spec.connection.Start method_frame: The Connection.Start frame
"""
self.server_properties = method_frame.method.server_properties
self.server_capabilities = self.server_properties.get('capabilities',
dict())
if hasattr(self.server_properties, 'capabilities'):
del self.server_properties['capabilities']
def _trim_frame_buffer(self, byte_count):
"""Trim the leading N bytes off the frame buffer and increment the
counter that keeps track of how many bytes have been read/used from the
socket.
:param int byte_count: The number of bytes consumed
"""
self._frame_buffer = self._frame_buffer[byte_count:]
self.bytes_received += byte_count
|