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 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359
|
import random
import socket
import sys
import threading
import time
from abc import ABC, abstractmethod
from collections import OrderedDict
from copy import copy
from enum import Enum
from itertools import chain
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
from redis._parsers import CommandsParser, Encoder
from redis._parsers.helpers import parse_scan
from redis.backoff import ExponentialWithJitterBackoff, NoBackoff
from redis.cache import CacheConfig, CacheFactory, CacheFactoryInterface, CacheInterface
from redis.client import EMPTY_RESPONSE, CaseInsensitiveDict, PubSub, Redis
from redis.commands import READ_COMMANDS, RedisClusterCommands
from redis.commands.helpers import list_or_args
from redis.connection import (
Connection,
ConnectionPool,
parse_url,
)
from redis.crc import REDIS_CLUSTER_HASH_SLOTS, key_slot
from redis.event import (
AfterPooledConnectionsInstantiationEvent,
AfterPubSubConnectionInstantiationEvent,
ClientType,
EventDispatcher,
)
from redis.exceptions import (
AskError,
AuthenticationError,
ClusterDownError,
ClusterError,
ConnectionError,
CrossSlotTransactionError,
DataError,
ExecAbortError,
InvalidPipelineStack,
MaxConnectionsError,
MovedError,
RedisClusterException,
RedisError,
ResponseError,
SlotNotCoveredError,
TimeoutError,
TryAgainError,
WatchError,
)
from redis.lock import Lock
from redis.retry import Retry
from redis.utils import (
deprecated_args,
dict_merge,
list_keys_to_dict,
merge_result,
safe_str,
str_if_bytes,
truncate_text,
)
def get_node_name(host: str, port: Union[str, int]) -> str:
return f"{host}:{port}"
@deprecated_args(
allowed_args=["redis_node"],
reason="Use get_connection(redis_node) instead",
version="5.3.0",
)
def get_connection(redis_node: Redis, *args, **options) -> Connection:
return redis_node.connection or redis_node.connection_pool.get_connection()
def parse_scan_result(command, res, **options):
cursors = {}
ret = []
for node_name, response in res.items():
cursor, r = parse_scan(response, **options)
cursors[node_name] = cursor
ret += r
return cursors, ret
def parse_pubsub_numsub(command, res, **options):
numsub_d = OrderedDict()
for numsub_tups in res.values():
for channel, numsubbed in numsub_tups:
try:
numsub_d[channel] += numsubbed
except KeyError:
numsub_d[channel] = numsubbed
ret_numsub = [(channel, numsub) for channel, numsub in numsub_d.items()]
return ret_numsub
def parse_cluster_slots(
resp: Any, **options: Any
) -> Dict[Tuple[int, int], Dict[str, Any]]:
current_host = options.get("current_host", "")
def fix_server(*args: Any) -> Tuple[str, Any]:
return str_if_bytes(args[0]) or current_host, args[1]
slots = {}
for slot in resp:
start, end, primary = slot[:3]
replicas = slot[3:]
slots[start, end] = {
"primary": fix_server(*primary),
"replicas": [fix_server(*replica) for replica in replicas],
}
return slots
def parse_cluster_shards(resp, **options):
"""
Parse CLUSTER SHARDS response.
"""
if isinstance(resp[0], dict):
return resp
shards = []
for x in resp:
shard = {"slots": [], "nodes": []}
for i in range(0, len(x[1]), 2):
shard["slots"].append((x[1][i], (x[1][i + 1])))
nodes = x[3]
for node in nodes:
dict_node = {}
for i in range(0, len(node), 2):
dict_node[node[i]] = node[i + 1]
shard["nodes"].append(dict_node)
shards.append(shard)
return shards
def parse_cluster_myshardid(resp, **options):
"""
Parse CLUSTER MYSHARDID response.
"""
return resp.decode("utf-8")
PRIMARY = "primary"
REPLICA = "replica"
SLOT_ID = "slot-id"
REDIS_ALLOWED_KEYS = (
"connection_class",
"connection_pool",
"connection_pool_class",
"client_name",
"credential_provider",
"db",
"decode_responses",
"encoding",
"encoding_errors",
"host",
"lib_name",
"lib_version",
"max_connections",
"nodes_flag",
"redis_connect_func",
"password",
"port",
"queue_class",
"retry",
"retry_on_timeout",
"protocol",
"socket_connect_timeout",
"socket_keepalive",
"socket_keepalive_options",
"socket_timeout",
"ssl",
"ssl_ca_certs",
"ssl_ca_data",
"ssl_certfile",
"ssl_cert_reqs",
"ssl_keyfile",
"ssl_password",
"ssl_check_hostname",
"unix_socket_path",
"username",
"cache",
"cache_config",
)
KWARGS_DISABLED_KEYS = ("host", "port", "retry")
def cleanup_kwargs(**kwargs):
"""
Remove unsupported or disabled keys from kwargs
"""
connection_kwargs = {
k: v
for k, v in kwargs.items()
if k in REDIS_ALLOWED_KEYS and k not in KWARGS_DISABLED_KEYS
}
return connection_kwargs
class AbstractRedisCluster:
RedisClusterRequestTTL = 16
PRIMARIES = "primaries"
REPLICAS = "replicas"
ALL_NODES = "all"
RANDOM = "random"
DEFAULT_NODE = "default-node"
NODE_FLAGS = {PRIMARIES, REPLICAS, ALL_NODES, RANDOM, DEFAULT_NODE}
COMMAND_FLAGS = dict_merge(
list_keys_to_dict(
[
"ACL CAT",
"ACL DELUSER",
"ACL DRYRUN",
"ACL GENPASS",
"ACL GETUSER",
"ACL HELP",
"ACL LIST",
"ACL LOG",
"ACL LOAD",
"ACL SAVE",
"ACL SETUSER",
"ACL USERS",
"ACL WHOAMI",
"AUTH",
"CLIENT LIST",
"CLIENT SETINFO",
"CLIENT SETNAME",
"CLIENT GETNAME",
"CONFIG SET",
"CONFIG REWRITE",
"CONFIG RESETSTAT",
"TIME",
"PUBSUB CHANNELS",
"PUBSUB NUMPAT",
"PUBSUB NUMSUB",
"PUBSUB SHARDCHANNELS",
"PUBSUB SHARDNUMSUB",
"PING",
"INFO",
"SHUTDOWN",
"KEYS",
"DBSIZE",
"BGSAVE",
"SLOWLOG GET",
"SLOWLOG LEN",
"SLOWLOG RESET",
"WAIT",
"WAITAOF",
"SAVE",
"MEMORY PURGE",
"MEMORY MALLOC-STATS",
"MEMORY STATS",
"LASTSAVE",
"CLIENT TRACKINGINFO",
"CLIENT PAUSE",
"CLIENT UNPAUSE",
"CLIENT UNBLOCK",
"CLIENT ID",
"CLIENT REPLY",
"CLIENT GETREDIR",
"CLIENT INFO",
"CLIENT KILL",
"READONLY",
"CLUSTER INFO",
"CLUSTER MEET",
"CLUSTER MYSHARDID",
"CLUSTER NODES",
"CLUSTER REPLICAS",
"CLUSTER RESET",
"CLUSTER SET-CONFIG-EPOCH",
"CLUSTER SLOTS",
"CLUSTER SHARDS",
"CLUSTER COUNT-FAILURE-REPORTS",
"CLUSTER KEYSLOT",
"COMMAND",
"COMMAND COUNT",
"COMMAND LIST",
"COMMAND GETKEYS",
"CONFIG GET",
"DEBUG",
"RANDOMKEY",
"READONLY",
"READWRITE",
"TIME",
"TFUNCTION LOAD",
"TFUNCTION DELETE",
"TFUNCTION LIST",
"TFCALL",
"TFCALLASYNC",
"LATENCY HISTORY",
"LATENCY LATEST",
"LATENCY RESET",
"MODULE LIST",
"MODULE LOAD",
"MODULE UNLOAD",
"MODULE LOADEX",
],
DEFAULT_NODE,
),
list_keys_to_dict(
[
"FLUSHALL",
"FLUSHDB",
"FUNCTION DELETE",
"FUNCTION FLUSH",
"FUNCTION LIST",
"FUNCTION LOAD",
"FUNCTION RESTORE",
"SCAN",
"SCRIPT EXISTS",
"SCRIPT FLUSH",
"SCRIPT LOAD",
],
PRIMARIES,
),
list_keys_to_dict(["FUNCTION DUMP"], RANDOM),
list_keys_to_dict(
[
"CLUSTER COUNTKEYSINSLOT",
"CLUSTER DELSLOTS",
"CLUSTER DELSLOTSRANGE",
"CLUSTER GETKEYSINSLOT",
"CLUSTER SETSLOT",
],
SLOT_ID,
),
)
SEARCH_COMMANDS = (
[
"FT.CREATE",
"FT.SEARCH",
"FT.AGGREGATE",
"FT.EXPLAIN",
"FT.EXPLAINCLI",
"FT,PROFILE",
"FT.ALTER",
"FT.DROPINDEX",
"FT.ALIASADD",
"FT.ALIASUPDATE",
"FT.ALIASDEL",
"FT.TAGVALS",
"FT.SUGADD",
"FT.SUGGET",
"FT.SUGDEL",
"FT.SUGLEN",
"FT.SYNUPDATE",
"FT.SYNDUMP",
"FT.SPELLCHECK",
"FT.DICTADD",
"FT.DICTDEL",
"FT.DICTDUMP",
"FT.INFO",
"FT._LIST",
"FT.CONFIG",
"FT.ADD",
"FT.DEL",
"FT.DROP",
"FT.GET",
"FT.MGET",
"FT.SYNADD",
],
)
CLUSTER_COMMANDS_RESPONSE_CALLBACKS = {
"CLUSTER SLOTS": parse_cluster_slots,
"CLUSTER SHARDS": parse_cluster_shards,
"CLUSTER MYSHARDID": parse_cluster_myshardid,
}
RESULT_CALLBACKS = dict_merge(
list_keys_to_dict(["PUBSUB NUMSUB", "PUBSUB SHARDNUMSUB"], parse_pubsub_numsub),
list_keys_to_dict(
["PUBSUB NUMPAT"], lambda command, res: sum(list(res.values()))
),
list_keys_to_dict(
["KEYS", "PUBSUB CHANNELS", "PUBSUB SHARDCHANNELS"], merge_result
),
list_keys_to_dict(
[
"PING",
"CONFIG SET",
"CONFIG REWRITE",
"CONFIG RESETSTAT",
"CLIENT SETNAME",
"BGSAVE",
"SLOWLOG RESET",
"SAVE",
"MEMORY PURGE",
"CLIENT PAUSE",
"CLIENT UNPAUSE",
],
lambda command, res: all(res.values()) if isinstance(res, dict) else res,
),
list_keys_to_dict(
["DBSIZE", "WAIT"],
lambda command, res: sum(res.values()) if isinstance(res, dict) else res,
),
list_keys_to_dict(
["CLIENT UNBLOCK"], lambda command, res: 1 if sum(res.values()) > 0 else 0
),
list_keys_to_dict(["SCAN"], parse_scan_result),
list_keys_to_dict(
["SCRIPT LOAD"], lambda command, res: list(res.values()).pop()
),
list_keys_to_dict(
["SCRIPT EXISTS"], lambda command, res: [all(k) for k in zip(*res.values())]
),
list_keys_to_dict(["SCRIPT FLUSH"], lambda command, res: all(res.values())),
)
ERRORS_ALLOW_RETRY = (
ConnectionError,
TimeoutError,
ClusterDownError,
SlotNotCoveredError,
)
def replace_default_node(self, target_node: "ClusterNode" = None) -> None:
"""Replace the default cluster node.
A random cluster node will be chosen if target_node isn't passed, and primaries
will be prioritized. The default node will not be changed if there are no other
nodes in the cluster.
Args:
target_node (ClusterNode, optional): Target node to replace the default
node. Defaults to None.
"""
if target_node:
self.nodes_manager.default_node = target_node
else:
curr_node = self.get_default_node()
primaries = [node for node in self.get_primaries() if node != curr_node]
if primaries:
# Choose a primary if the cluster contains different primaries
self.nodes_manager.default_node = random.choice(primaries)
else:
# Otherwise, choose a primary if the cluster contains different primaries
replicas = [node for node in self.get_replicas() if node != curr_node]
if replicas:
self.nodes_manager.default_node = random.choice(replicas)
class RedisCluster(AbstractRedisCluster, RedisClusterCommands):
@classmethod
def from_url(cls, url, **kwargs):
"""
Return a Redis client object configured from the given URL
For example::
redis://[[username]:[password]]@localhost:6379/0
rediss://[[username]:[password]]@localhost:6379/0
unix://[username@]/path/to/socket.sock?db=0[&password=password]
Three URL schemes are supported:
- `redis://` creates a TCP socket connection. See more at:
<https://www.iana.org/assignments/uri-schemes/prov/redis>
- `rediss://` creates a SSL wrapped TCP socket connection. See more at:
<https://www.iana.org/assignments/uri-schemes/prov/rediss>
- ``unix://``: creates a Unix Domain Socket connection.
The username, password, hostname, path and all querystring values
are passed through urllib.parse.unquote in order to replace any
percent-encoded values with their corresponding characters.
There are several ways to specify a database number. The first value
found will be used:
1. A ``db`` querystring option, e.g. redis://localhost?db=0
2. If using the redis:// or rediss:// schemes, the path argument
of the url, e.g. redis://localhost/0
3. A ``db`` keyword argument to this function.
If none of these options are specified, the default db=0 is used.
All querystring options are cast to their appropriate Python types.
Boolean arguments can be specified with string values "True"/"False"
or "Yes"/"No". Values that cannot be properly cast cause a
``ValueError`` to be raised. Once parsed, the querystring arguments
and keyword arguments are passed to the ``ConnectionPool``'s
class initializer. In the case of conflicting arguments, querystring
arguments always win.
"""
return cls(url=url, **kwargs)
@deprecated_args(
args_to_warn=["read_from_replicas"],
reason="Please configure the 'load_balancing_strategy' instead",
version="5.3.0",
)
@deprecated_args(
args_to_warn=[
"cluster_error_retry_attempts",
],
reason="Please configure the 'retry' object instead",
version="6.0.0",
)
def __init__(
self,
host: Optional[str] = None,
port: int = 6379,
startup_nodes: Optional[List["ClusterNode"]] = None,
cluster_error_retry_attempts: int = 3,
retry: Optional["Retry"] = None,
require_full_coverage: bool = True,
reinitialize_steps: int = 5,
read_from_replicas: bool = False,
load_balancing_strategy: Optional["LoadBalancingStrategy"] = None,
dynamic_startup_nodes: bool = True,
url: Optional[str] = None,
address_remap: Optional[Callable[[Tuple[str, int]], Tuple[str, int]]] = None,
cache: Optional[CacheInterface] = None,
cache_config: Optional[CacheConfig] = None,
event_dispatcher: Optional[EventDispatcher] = None,
**kwargs,
):
"""
Initialize a new RedisCluster client.
:param startup_nodes:
List of nodes from which initial bootstrapping can be done
:param host:
Can be used to point to a startup node
:param port:
Can be used to point to a startup node
:param require_full_coverage:
When set to False (default value): the client will not require a
full coverage of the slots. However, if not all slots are covered,
and at least one node has 'cluster-require-full-coverage' set to
'yes,' the server will throw a ClusterDownError for some key-based
commands. See -
https://redis.io/topics/cluster-tutorial#redis-cluster-configuration-parameters
When set to True: all slots must be covered to construct the
cluster client. If not all slots are covered, RedisClusterException
will be thrown.
:param read_from_replicas:
@deprecated - please use load_balancing_strategy instead
Enable read from replicas in READONLY mode. You can read possibly
stale data.
When set to true, read commands will be assigned between the
primary and its replications in a Round-Robin manner.
:param load_balancing_strategy:
Enable read from replicas in READONLY mode and defines the load balancing
strategy that will be used for cluster node selection.
The data read from replicas is eventually consistent with the data in primary nodes.
:param dynamic_startup_nodes:
Set the RedisCluster's startup nodes to all of the discovered nodes.
If true (default value), the cluster's discovered nodes will be used to
determine the cluster nodes-slots mapping in the next topology refresh.
It will remove the initial passed startup nodes if their endpoints aren't
listed in the CLUSTER SLOTS output.
If you use dynamic DNS endpoints for startup nodes but CLUSTER SLOTS lists
specific IP addresses, it is best to set it to false.
:param cluster_error_retry_attempts:
@deprecated - Please configure the 'retry' object instead
In case 'retry' object is set - this argument is ignored!
Number of times to retry before raising an error when
:class:`~.TimeoutError` or :class:`~.ConnectionError`, :class:`~.SlotNotCoveredError` or
:class:`~.ClusterDownError` are encountered
:param retry:
A retry object that defines the retry strategy and the number of
retries for the cluster client.
In current implementation for the cluster client (starting form redis-py version 6.0.0)
the retry object is not yet fully utilized, instead it is used just to determine
the number of retries for the cluster client.
In the future releases the retry object will be used to handle the cluster client retries!
:param reinitialize_steps:
Specifies the number of MOVED errors that need to occur before
reinitializing the whole cluster topology. If a MOVED error occurs
and the cluster does not need to be reinitialized on this current
error handling, only the MOVED slot will be patched with the
redirected node.
To reinitialize the cluster on every MOVED error, set
reinitialize_steps to 1.
To avoid reinitializing the cluster on moved errors, set
reinitialize_steps to 0.
:param address_remap:
An optional callable which, when provided with an internal network
address of a node, e.g. a `(host, port)` tuple, will return the address
where the node is reachable. This can be used to map the addresses at
which the nodes _think_ they are, to addresses at which a client may
reach them, such as when they sit behind a proxy.
:**kwargs:
Extra arguments that will be sent into Redis instance when created
(See Official redis-py doc for supported kwargs - the only limitation
is that you can't provide 'retry' object as part of kwargs.
[https://github.com/andymccurdy/redis-py/blob/master/redis/client.py])
Some kwargs are not supported and will raise a
RedisClusterException:
- db (Redis do not support database SELECT in cluster mode)
"""
if startup_nodes is None:
startup_nodes = []
if "db" in kwargs:
# Argument 'db' is not possible to use in cluster mode
raise RedisClusterException(
"Argument 'db' is not possible to use in cluster mode"
)
if "retry" in kwargs:
# Argument 'retry' is not possible to be used in kwargs when in cluster mode
# the kwargs are set to the lower level connections to the cluster nodes
# and there we provide retry configuration without retries allowed.
# The retries should be handled on cluster client level.
raise RedisClusterException(
"The 'retry' argument cannot be used in kwargs when running in cluster mode."
)
# Get the startup node/s
from_url = False
if url is not None:
from_url = True
url_options = parse_url(url)
if "path" in url_options:
raise RedisClusterException(
"RedisCluster does not currently support Unix Domain "
"Socket connections"
)
if "db" in url_options and url_options["db"] != 0:
# Argument 'db' is not possible to use in cluster mode
raise RedisClusterException(
"A ``db`` querystring option can only be 0 in cluster mode"
)
kwargs.update(url_options)
host = kwargs.get("host")
port = kwargs.get("port", port)
startup_nodes.append(ClusterNode(host, port))
elif host is not None and port is not None:
startup_nodes.append(ClusterNode(host, port))
elif len(startup_nodes) == 0:
# No startup node was provided
raise RedisClusterException(
"RedisCluster requires at least one node to discover the "
"cluster. Please provide one of the followings:\n"
"1. host and port, for example:\n"
" RedisCluster(host='localhost', port=6379)\n"
"2. list of startup nodes, for example:\n"
" RedisCluster(startup_nodes=[ClusterNode('localhost', 6379),"
" ClusterNode('localhost', 6378)])"
)
# Update the connection arguments
# Whenever a new connection is established, RedisCluster's on_connect
# method should be run
# If the user passed on_connect function we'll save it and run it
# inside the RedisCluster.on_connect() function
self.user_on_connect_func = kwargs.pop("redis_connect_func", None)
kwargs.update({"redis_connect_func": self.on_connect})
kwargs = cleanup_kwargs(**kwargs)
if retry:
self.retry = retry
else:
self.retry = Retry(
backoff=ExponentialWithJitterBackoff(base=1, cap=10),
retries=cluster_error_retry_attempts,
)
self.encoder = Encoder(
kwargs.get("encoding", "utf-8"),
kwargs.get("encoding_errors", "strict"),
kwargs.get("decode_responses", False),
)
protocol = kwargs.get("protocol", None)
if (cache_config or cache) and protocol not in [3, "3"]:
raise RedisError("Client caching is only supported with RESP version 3")
self.command_flags = self.__class__.COMMAND_FLAGS.copy()
self.node_flags = self.__class__.NODE_FLAGS.copy()
self.read_from_replicas = read_from_replicas
self.load_balancing_strategy = load_balancing_strategy
self.reinitialize_counter = 0
self.reinitialize_steps = reinitialize_steps
if event_dispatcher is None:
self._event_dispatcher = EventDispatcher()
else:
self._event_dispatcher = event_dispatcher
self.nodes_manager = NodesManager(
startup_nodes=startup_nodes,
from_url=from_url,
require_full_coverage=require_full_coverage,
dynamic_startup_nodes=dynamic_startup_nodes,
address_remap=address_remap,
cache=cache,
cache_config=cache_config,
event_dispatcher=self._event_dispatcher,
**kwargs,
)
self.cluster_response_callbacks = CaseInsensitiveDict(
self.__class__.CLUSTER_COMMANDS_RESPONSE_CALLBACKS
)
self.result_callbacks = CaseInsensitiveDict(self.__class__.RESULT_CALLBACKS)
self.commands_parser = CommandsParser(self)
self._lock = threading.RLock()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def __del__(self):
try:
self.close()
except Exception:
pass
def disconnect_connection_pools(self):
for node in self.get_nodes():
if node.redis_connection:
try:
node.redis_connection.connection_pool.disconnect()
except OSError:
# Client was already disconnected. do nothing
pass
def on_connect(self, connection):
"""
Initialize the connection, authenticate and select a database and send
READONLY if it is set during object initialization.
"""
connection.on_connect()
if self.read_from_replicas or self.load_balancing_strategy:
# Sending READONLY command to server to configure connection as
# readonly. Since each cluster node may change its server type due
# to a failover, we should establish a READONLY connection
# regardless of the server type. If this is a primary connection,
# READONLY would not affect executing write commands.
connection.send_command("READONLY")
if str_if_bytes(connection.read_response()) != "OK":
raise ConnectionError("READONLY command failed")
if self.user_on_connect_func is not None:
self.user_on_connect_func(connection)
def get_redis_connection(self, node: "ClusterNode") -> Redis:
if not node.redis_connection:
with self._lock:
if not node.redis_connection:
self.nodes_manager.create_redis_connections([node])
return node.redis_connection
def get_node(self, host=None, port=None, node_name=None):
return self.nodes_manager.get_node(host, port, node_name)
def get_primaries(self):
return self.nodes_manager.get_nodes_by_server_type(PRIMARY)
def get_replicas(self):
return self.nodes_manager.get_nodes_by_server_type(REPLICA)
def get_random_node(self):
return random.choice(list(self.nodes_manager.nodes_cache.values()))
def get_nodes(self):
return list(self.nodes_manager.nodes_cache.values())
def get_node_from_key(self, key, replica=False):
"""
Get the node that holds the key's slot.
If replica set to True but the slot doesn't have any replicas, None is
returned.
"""
slot = self.keyslot(key)
slot_cache = self.nodes_manager.slots_cache.get(slot)
if slot_cache is None or len(slot_cache) == 0:
raise SlotNotCoveredError(f'Slot "{slot}" is not covered by the cluster.')
if replica and len(self.nodes_manager.slots_cache[slot]) < 2:
return None
elif replica:
node_idx = 1
else:
# primary
node_idx = 0
return slot_cache[node_idx]
def get_default_node(self):
"""
Get the cluster's default node
"""
return self.nodes_manager.default_node
def set_default_node(self, node):
"""
Set the default node of the cluster.
:param node: 'ClusterNode'
:return True if the default node was set, else False
"""
if node is None or self.get_node(node_name=node.name) is None:
return False
self.nodes_manager.default_node = node
return True
def set_retry(self, retry: Retry) -> None:
self.retry = retry
def monitor(self, target_node=None):
"""
Returns a Monitor object for the specified target node.
The default cluster node will be selected if no target node was
specified.
Monitor is useful for handling the MONITOR command to the redis server.
next_command() method returns one command from monitor
listen() method yields commands from monitor.
"""
if target_node is None:
target_node = self.get_default_node()
if target_node.redis_connection is None:
raise RedisClusterException(
f"Cluster Node {target_node.name} has no redis_connection"
)
return target_node.redis_connection.monitor()
def pubsub(self, node=None, host=None, port=None, **kwargs):
"""
Allows passing a ClusterNode, or host&port, to get a pubsub instance
connected to the specified node
"""
return ClusterPubSub(self, node=node, host=host, port=port, **kwargs)
def pipeline(self, transaction=None, shard_hint=None):
"""
Cluster impl:
Pipelines do not work in cluster mode the same way they
do in normal mode. Create a clone of this object so
that simulating pipelines will work correctly. Each
command will be called directly when used and
when calling execute() will only return the result stack.
"""
if shard_hint:
raise RedisClusterException("shard_hint is deprecated in cluster mode")
return ClusterPipeline(
nodes_manager=self.nodes_manager,
commands_parser=self.commands_parser,
startup_nodes=self.nodes_manager.startup_nodes,
result_callbacks=self.result_callbacks,
cluster_response_callbacks=self.cluster_response_callbacks,
read_from_replicas=self.read_from_replicas,
load_balancing_strategy=self.load_balancing_strategy,
reinitialize_steps=self.reinitialize_steps,
retry=self.retry,
lock=self._lock,
transaction=transaction,
)
def lock(
self,
name,
timeout=None,
sleep=0.1,
blocking=True,
blocking_timeout=None,
lock_class=None,
thread_local=True,
raise_on_release_error: bool = True,
):
"""
Return a new Lock object using key ``name`` that mimics
the behavior of threading.Lock.
If specified, ``timeout`` indicates a maximum life for the lock.
By default, it will remain locked until release() is called.
``sleep`` indicates the amount of time to sleep per loop iteration
when the lock is in blocking mode and another client is currently
holding the lock.
``blocking`` indicates whether calling ``acquire`` should block until
the lock has been acquired or to fail immediately, causing ``acquire``
to return False and the lock not being acquired. Defaults to True.
Note this value can be overridden by passing a ``blocking``
argument to ``acquire``.
``blocking_timeout`` indicates the maximum amount of time in seconds to
spend trying to acquire the lock. A value of ``None`` indicates
continue trying forever. ``blocking_timeout`` can be specified as a
float or integer, both representing the number of seconds to wait.
``lock_class`` forces the specified lock implementation. Note that as
of redis-py 3.0, the only lock class we implement is ``Lock`` (which is
a Lua-based lock). So, it's unlikely you'll need this parameter, unless
you have created your own custom lock class.
``thread_local`` indicates whether the lock token is placed in
thread-local storage. By default, the token is placed in thread local
storage so that a thread only sees its token, not a token set by
another thread. Consider the following timeline:
time: 0, thread-1 acquires `my-lock`, with a timeout of 5 seconds.
thread-1 sets the token to "abc"
time: 1, thread-2 blocks trying to acquire `my-lock` using the
Lock instance.
time: 5, thread-1 has not yet completed. redis expires the lock
key.
time: 5, thread-2 acquired `my-lock` now that it's available.
thread-2 sets the token to "xyz"
time: 6, thread-1 finishes its work and calls release(). if the
token is *not* stored in thread local storage, then
thread-1 would see the token value as "xyz" and would be
able to successfully release the thread-2's lock.
``raise_on_release_error`` indicates whether to raise an exception when
the lock is no longer owned when exiting the context manager. By default,
this is True, meaning an exception will be raised. If False, the warning
will be logged and the exception will be suppressed.
In some use cases it's necessary to disable thread local storage. For
example, if you have code where one thread acquires a lock and passes
that lock instance to a worker thread to release later. If thread
local storage isn't disabled in this case, the worker thread won't see
the token set by the thread that acquired the lock. Our assumption
is that these cases aren't common and as such default to using
thread local storage."""
if lock_class is None:
lock_class = Lock
return lock_class(
self,
name,
timeout=timeout,
sleep=sleep,
blocking=blocking,
blocking_timeout=blocking_timeout,
thread_local=thread_local,
raise_on_release_error=raise_on_release_error,
)
def set_response_callback(self, command, callback):
"""Set a custom Response Callback"""
self.cluster_response_callbacks[command] = callback
def _determine_nodes(self, *args, **kwargs) -> List["ClusterNode"]:
# Determine which nodes should be executed the command on.
# Returns a list of target nodes.
command = args[0].upper()
if len(args) >= 2 and f"{args[0]} {args[1]}".upper() in self.command_flags:
command = f"{args[0]} {args[1]}".upper()
nodes_flag = kwargs.pop("nodes_flag", None)
if nodes_flag is not None:
# nodes flag passed by the user
command_flag = nodes_flag
else:
# get the nodes group for this command if it was predefined
command_flag = self.command_flags.get(command)
if command_flag == self.__class__.RANDOM:
# return a random node
return [self.get_random_node()]
elif command_flag == self.__class__.PRIMARIES:
# return all primaries
return self.get_primaries()
elif command_flag == self.__class__.REPLICAS:
# return all replicas
return self.get_replicas()
elif command_flag == self.__class__.ALL_NODES:
# return all nodes
return self.get_nodes()
elif command_flag == self.__class__.DEFAULT_NODE:
# return the cluster's default node
return [self.nodes_manager.default_node]
elif command in self.__class__.SEARCH_COMMANDS[0]:
return [self.nodes_manager.default_node]
else:
# get the node that holds the key's slot
slot = self.determine_slot(*args)
node = self.nodes_manager.get_node_from_slot(
slot,
self.read_from_replicas and command in READ_COMMANDS,
self.load_balancing_strategy if command in READ_COMMANDS else None,
)
return [node]
def _should_reinitialized(self):
# To reinitialize the cluster on every MOVED error,
# set reinitialize_steps to 1.
# To avoid reinitializing the cluster on moved errors, set
# reinitialize_steps to 0.
if self.reinitialize_steps == 0:
return False
else:
return self.reinitialize_counter % self.reinitialize_steps == 0
def keyslot(self, key):
"""
Calculate keyslot for a given key.
See Keys distribution model in https://redis.io/topics/cluster-spec
"""
k = self.encoder.encode(key)
return key_slot(k)
def _get_command_keys(self, *args):
"""
Get the keys in the command. If the command has no keys in in, None is
returned.
NOTE: Due to a bug in redis<7.0, this function does not work properly
for EVAL or EVALSHA when the `numkeys` arg is 0.
- issue: https://github.com/redis/redis/issues/9493
- fix: https://github.com/redis/redis/pull/9733
So, don't use this function with EVAL or EVALSHA.
"""
redis_conn = self.get_default_node().redis_connection
return self.commands_parser.get_keys(redis_conn, *args)
def determine_slot(self, *args) -> int:
"""
Figure out what slot to use based on args.
Raises a RedisClusterException if there's a missing key and we can't
determine what slots to map the command to; or, if the keys don't
all map to the same key slot.
"""
command = args[0]
if self.command_flags.get(command) == SLOT_ID:
# The command contains the slot ID
return args[1]
# Get the keys in the command
# EVAL and EVALSHA are common enough that it's wasteful to go to the
# redis server to parse the keys. Besides, there is a bug in redis<7.0
# where `self._get_command_keys()` fails anyway. So, we special case
# EVAL/EVALSHA.
if command.upper() in ("EVAL", "EVALSHA"):
# command syntax: EVAL "script body" num_keys ...
if len(args) <= 2:
raise RedisClusterException(f"Invalid args in command: {args}")
num_actual_keys = int(args[2])
eval_keys = args[3 : 3 + num_actual_keys]
# if there are 0 keys, that means the script can be run on any node
# so we can just return a random slot
if len(eval_keys) == 0:
return random.randrange(0, REDIS_CLUSTER_HASH_SLOTS)
keys = eval_keys
else:
keys = self._get_command_keys(*args)
if keys is None or len(keys) == 0:
# FCALL can call a function with 0 keys, that means the function
# can be run on any node so we can just return a random slot
if command.upper() in ("FCALL", "FCALL_RO"):
return random.randrange(0, REDIS_CLUSTER_HASH_SLOTS)
raise RedisClusterException(
"No way to dispatch this command to Redis Cluster. "
"Missing key.\nYou can execute the command by specifying "
f"target nodes.\nCommand: {args}"
)
# single key command
if len(keys) == 1:
return self.keyslot(keys[0])
# multi-key command; we need to make sure all keys are mapped to
# the same slot
slots = {self.keyslot(key) for key in keys}
if len(slots) != 1:
raise RedisClusterException(
f"{command} - all keys must map to the same key slot"
)
return slots.pop()
def get_encoder(self):
"""
Get the connections' encoder
"""
return self.encoder
def get_connection_kwargs(self):
"""
Get the connections' key-word arguments
"""
return self.nodes_manager.connection_kwargs
def _is_nodes_flag(self, target_nodes):
return isinstance(target_nodes, str) and target_nodes in self.node_flags
def _parse_target_nodes(self, target_nodes):
if isinstance(target_nodes, list):
nodes = target_nodes
elif isinstance(target_nodes, ClusterNode):
# Supports passing a single ClusterNode as a variable
nodes = [target_nodes]
elif isinstance(target_nodes, dict):
# Supports dictionaries of the format {node_name: node}.
# It enables to execute commands with multi nodes as follows:
# rc.cluster_save_config(rc.get_primaries())
nodes = target_nodes.values()
else:
raise TypeError(
"target_nodes type can be one of the following: "
"node_flag (PRIMARIES, REPLICAS, RANDOM, ALL_NODES),"
"ClusterNode, list<ClusterNode>, or dict<any, ClusterNode>. "
f"The passed type is {type(target_nodes)}"
)
return nodes
def execute_command(self, *args, **kwargs):
return self._internal_execute_command(*args, **kwargs)
def _internal_execute_command(self, *args, **kwargs):
"""
Wrapper for ERRORS_ALLOW_RETRY error handling.
It will try the number of times specified by the retries property from
config option "self.retry" which defaults to 3 unless manually
configured.
If it reaches the number of times, the command will raise the exception
Key argument :target_nodes: can be passed with the following types:
nodes_flag: PRIMARIES, REPLICAS, ALL_NODES, RANDOM
ClusterNode
list<ClusterNode>
dict<Any, ClusterNode>
"""
target_nodes_specified = False
is_default_node = False
target_nodes = None
passed_targets = kwargs.pop("target_nodes", None)
if passed_targets is not None and not self._is_nodes_flag(passed_targets):
target_nodes = self._parse_target_nodes(passed_targets)
target_nodes_specified = True
# If an error that allows retrying was thrown, the nodes and slots
# cache were reinitialized. We will retry executing the command with
# the updated cluster setup only when the target nodes can be
# determined again with the new cache tables. Therefore, when target
# nodes were passed to this function, we cannot retry the command
# execution since the nodes may not be valid anymore after the tables
# were reinitialized. So in case of passed target nodes,
# retry_attempts will be set to 0.
retry_attempts = 0 if target_nodes_specified else self.retry.get_retries()
# Add one for the first execution
execute_attempts = 1 + retry_attempts
for _ in range(execute_attempts):
try:
res = {}
if not target_nodes_specified:
# Determine the nodes to execute the command on
target_nodes = self._determine_nodes(
*args, **kwargs, nodes_flag=passed_targets
)
if not target_nodes:
raise RedisClusterException(
f"No targets were found to execute {args} command on"
)
if (
len(target_nodes) == 1
and target_nodes[0] == self.get_default_node()
):
is_default_node = True
for node in target_nodes:
res[node.name] = self._execute_command(node, *args, **kwargs)
# Return the processed result
return self._process_result(args[0], res, **kwargs)
except Exception as e:
if retry_attempts > 0 and type(e) in self.__class__.ERRORS_ALLOW_RETRY:
if is_default_node:
# Replace the default cluster node
self.replace_default_node()
# The nodes and slots cache were reinitialized.
# Try again with the new cluster setup.
retry_attempts -= 1
continue
else:
# raise the exception
raise e
def _execute_command(self, target_node, *args, **kwargs):
"""
Send a command to a node in the cluster
"""
command = args[0]
redis_node = None
connection = None
redirect_addr = None
asking = False
moved = False
ttl = int(self.RedisClusterRequestTTL)
while ttl > 0:
ttl -= 1
try:
if asking:
target_node = self.get_node(node_name=redirect_addr)
elif moved:
# MOVED occurred and the slots cache was updated,
# refresh the target node
slot = self.determine_slot(*args)
target_node = self.nodes_manager.get_node_from_slot(
slot,
self.read_from_replicas and command in READ_COMMANDS,
self.load_balancing_strategy
if command in READ_COMMANDS
else None,
)
moved = False
redis_node = self.get_redis_connection(target_node)
connection = get_connection(redis_node)
if asking:
connection.send_command("ASKING")
redis_node.parse_response(connection, "ASKING", **kwargs)
asking = False
connection.send_command(*args, **kwargs)
response = redis_node.parse_response(connection, command, **kwargs)
# Remove keys entry, it needs only for cache.
kwargs.pop("keys", None)
if command in self.cluster_response_callbacks:
response = self.cluster_response_callbacks[command](
response, **kwargs
)
return response
except AuthenticationError:
raise
except MaxConnectionsError:
# MaxConnectionsError indicates client-side resource exhaustion
# (too many connections in the pool), not a node failure.
# Don't treat this as a node failure - just re-raise the error
# without reinitializing the cluster.
raise
except (ConnectionError, TimeoutError) as e:
# ConnectionError can also be raised if we couldn't get a
# connection from the pool before timing out, so check that
# this is an actual connection before attempting to disconnect.
if connection is not None:
connection.disconnect()
# Remove the failed node from the startup nodes before we try
# to reinitialize the cluster
self.nodes_manager.startup_nodes.pop(target_node.name, None)
# Reset the cluster node's connection
target_node.redis_connection = None
self.nodes_manager.initialize()
raise e
except MovedError as e:
# First, we will try to patch the slots/nodes cache with the
# redirected node output and try again. If MovedError exceeds
# 'reinitialize_steps' number of times, we will force
# reinitializing the tables, and then try again.
# 'reinitialize_steps' counter will increase faster when
# the same client object is shared between multiple threads. To
# reduce the frequency you can set this variable in the
# RedisCluster constructor.
self.reinitialize_counter += 1
if self._should_reinitialized():
self.nodes_manager.initialize()
# Reset the counter
self.reinitialize_counter = 0
else:
self.nodes_manager.update_moved_exception(e)
moved = True
except TryAgainError:
if ttl < self.RedisClusterRequestTTL / 2:
time.sleep(0.05)
except AskError as e:
redirect_addr = get_node_name(host=e.host, port=e.port)
asking = True
except (ClusterDownError, SlotNotCoveredError):
# ClusterDownError can occur during a failover and to get
# self-healed, we will try to reinitialize the cluster layout
# and retry executing the command
# SlotNotCoveredError can occur when the cluster is not fully
# initialized or can be temporary issue.
# We will try to reinitialize the cluster topology
# and retry executing the command
time.sleep(0.25)
self.nodes_manager.initialize()
raise
except ResponseError:
raise
except Exception as e:
if connection:
connection.disconnect()
raise e
finally:
if connection is not None:
redis_node.connection_pool.release(connection)
raise ClusterError("TTL exhausted.")
def close(self) -> None:
try:
with self._lock:
if self.nodes_manager:
self.nodes_manager.close()
except AttributeError:
# RedisCluster's __init__ can fail before nodes_manager is set
pass
def _process_result(self, command, res, **kwargs):
"""
Process the result of the executed command.
The function would return a dict or a single value.
:type command: str
:type res: dict
`res` should be in the following format:
Dict<node_name, command_result>
"""
if command in self.result_callbacks:
return self.result_callbacks[command](command, res, **kwargs)
elif len(res) == 1:
# When we execute the command on a single node, we can
# remove the dictionary and return a single response
return list(res.values())[0]
else:
return res
def load_external_module(self, funcname, func):
"""
This function can be used to add externally defined redis modules,
and their namespaces to the redis client.
``funcname`` - A string containing the name of the function to create
``func`` - The function, being added to this class.
"""
setattr(self, funcname, func)
def transaction(self, func, *watches, **kwargs):
"""
Convenience method for executing the callable `func` as a transaction
while watching all keys specified in `watches`. The 'func' callable
should expect a single argument which is a Pipeline object.
"""
shard_hint = kwargs.pop("shard_hint", None)
value_from_callable = kwargs.pop("value_from_callable", False)
watch_delay = kwargs.pop("watch_delay", None)
with self.pipeline(True, shard_hint) as pipe:
while True:
try:
if watches:
pipe.watch(*watches)
func_value = func(pipe)
exec_value = pipe.execute()
return func_value if value_from_callable else exec_value
except WatchError:
if watch_delay is not None and watch_delay > 0:
time.sleep(watch_delay)
continue
class ClusterNode:
def __init__(self, host, port, server_type=None, redis_connection=None):
if host == "localhost":
host = socket.gethostbyname(host)
self.host = host
self.port = port
self.name = get_node_name(host, port)
self.server_type = server_type
self.redis_connection = redis_connection
def __repr__(self):
return (
f"[host={self.host},"
f"port={self.port},"
f"name={self.name},"
f"server_type={self.server_type},"
f"redis_connection={self.redis_connection}]"
)
def __eq__(self, obj):
return isinstance(obj, ClusterNode) and obj.name == self.name
def __del__(self):
try:
if self.redis_connection is not None:
self.redis_connection.close()
except Exception:
# Ignore errors when closing the connection
pass
class LoadBalancingStrategy(Enum):
ROUND_ROBIN = "round_robin"
ROUND_ROBIN_REPLICAS = "round_robin_replicas"
RANDOM_REPLICA = "random_replica"
class LoadBalancer:
"""
Round-Robin Load Balancing
"""
def __init__(self, start_index: int = 0) -> None:
self.primary_to_idx = {}
self.start_index = start_index
def get_server_index(
self,
primary: str,
list_size: int,
load_balancing_strategy: LoadBalancingStrategy = LoadBalancingStrategy.ROUND_ROBIN,
) -> int:
if load_balancing_strategy == LoadBalancingStrategy.RANDOM_REPLICA:
return self._get_random_replica_index(list_size)
else:
return self._get_round_robin_index(
primary,
list_size,
load_balancing_strategy == LoadBalancingStrategy.ROUND_ROBIN_REPLICAS,
)
def reset(self) -> None:
self.primary_to_idx.clear()
def _get_random_replica_index(self, list_size: int) -> int:
return random.randint(1, list_size - 1)
def _get_round_robin_index(
self, primary: str, list_size: int, replicas_only: bool
) -> int:
server_index = self.primary_to_idx.setdefault(primary, self.start_index)
if replicas_only and server_index == 0:
# skip the primary node index
server_index = 1
# Update the index for the next round
self.primary_to_idx[primary] = (server_index + 1) % list_size
return server_index
class NodesManager:
def __init__(
self,
startup_nodes,
from_url=False,
require_full_coverage=False,
lock=None,
dynamic_startup_nodes=True,
connection_pool_class=ConnectionPool,
address_remap: Optional[Callable[[Tuple[str, int]], Tuple[str, int]]] = None,
cache: Optional[CacheInterface] = None,
cache_config: Optional[CacheConfig] = None,
cache_factory: Optional[CacheFactoryInterface] = None,
event_dispatcher: Optional[EventDispatcher] = None,
**kwargs,
):
self.nodes_cache: Dict[str, Redis] = {}
self.slots_cache = {}
self.startup_nodes = {}
self.default_node = None
self.populate_startup_nodes(startup_nodes)
self.from_url = from_url
self._require_full_coverage = require_full_coverage
self._dynamic_startup_nodes = dynamic_startup_nodes
self.connection_pool_class = connection_pool_class
self.address_remap = address_remap
self._cache = cache
self._cache_config = cache_config
self._cache_factory = cache_factory
self._moved_exception = None
self.connection_kwargs = kwargs
self.read_load_balancer = LoadBalancer()
if lock is None:
lock = threading.RLock()
self._lock = lock
if event_dispatcher is None:
self._event_dispatcher = EventDispatcher()
else:
self._event_dispatcher = event_dispatcher
self._credential_provider = self.connection_kwargs.get(
"credential_provider", None
)
self.initialize()
def get_node(self, host=None, port=None, node_name=None):
"""
Get the requested node from the cluster's nodes.
nodes.
:return: ClusterNode if the node exists, else None
"""
if host and port:
# the user passed host and port
if host == "localhost":
host = socket.gethostbyname(host)
return self.nodes_cache.get(get_node_name(host=host, port=port))
elif node_name:
return self.nodes_cache.get(node_name)
else:
return None
def update_moved_exception(self, exception):
self._moved_exception = exception
def _update_moved_slots(self):
"""
Update the slot's node with the redirected one
"""
e = self._moved_exception
redirected_node = self.get_node(host=e.host, port=e.port)
if redirected_node is not None:
# The node already exists
if redirected_node.server_type is not PRIMARY:
# Update the node's server type
redirected_node.server_type = PRIMARY
else:
# This is a new node, we will add it to the nodes cache
redirected_node = ClusterNode(e.host, e.port, PRIMARY)
self.nodes_cache[redirected_node.name] = redirected_node
if redirected_node in self.slots_cache[e.slot_id]:
# The MOVED error resulted from a failover, and the new slot owner
# had previously been a replica.
old_primary = self.slots_cache[e.slot_id][0]
# Update the old primary to be a replica and add it to the end of
# the slot's node list
old_primary.server_type = REPLICA
self.slots_cache[e.slot_id].append(old_primary)
# Remove the old replica, which is now a primary, from the slot's
# node list
self.slots_cache[e.slot_id].remove(redirected_node)
# Override the old primary with the new one
self.slots_cache[e.slot_id][0] = redirected_node
if self.default_node == old_primary:
# Update the default node with the new primary
self.default_node = redirected_node
else:
# The new slot owner is a new server, or a server from a different
# shard. We need to remove all current nodes from the slot's list
# (including replications) and add just the new node.
self.slots_cache[e.slot_id] = [redirected_node]
# Reset moved_exception
self._moved_exception = None
@deprecated_args(
args_to_warn=["server_type"],
reason=(
"In case you need select some load balancing strategy "
"that will use replicas, please set it through 'load_balancing_strategy'"
),
version="5.3.0",
)
def get_node_from_slot(
self,
slot,
read_from_replicas=False,
load_balancing_strategy=None,
server_type=None,
) -> ClusterNode:
"""
Gets a node that servers this hash slot
"""
if self._moved_exception:
with self._lock:
if self._moved_exception:
self._update_moved_slots()
if self.slots_cache.get(slot) is None or len(self.slots_cache[slot]) == 0:
raise SlotNotCoveredError(
f'Slot "{slot}" not covered by the cluster. '
f'"require_full_coverage={self._require_full_coverage}"'
)
if read_from_replicas is True and load_balancing_strategy is None:
load_balancing_strategy = LoadBalancingStrategy.ROUND_ROBIN
if len(self.slots_cache[slot]) > 1 and load_balancing_strategy:
# get the server index using the strategy defined in load_balancing_strategy
primary_name = self.slots_cache[slot][0].name
node_idx = self.read_load_balancer.get_server_index(
primary_name, len(self.slots_cache[slot]), load_balancing_strategy
)
elif (
server_type is None
or server_type == PRIMARY
or len(self.slots_cache[slot]) == 1
):
# return a primary
node_idx = 0
else:
# return a replica
# randomly choose one of the replicas
node_idx = random.randint(1, len(self.slots_cache[slot]) - 1)
return self.slots_cache[slot][node_idx]
def get_nodes_by_server_type(self, server_type):
"""
Get all nodes with the specified server type
:param server_type: 'primary' or 'replica'
:return: list of ClusterNode
"""
return [
node
for node in self.nodes_cache.values()
if node.server_type == server_type
]
def populate_startup_nodes(self, nodes):
"""
Populate all startup nodes and filters out any duplicates
"""
for n in nodes:
self.startup_nodes[n.name] = n
def check_slots_coverage(self, slots_cache):
# Validate if all slots are covered or if we should try next
# startup node
for i in range(0, REDIS_CLUSTER_HASH_SLOTS):
if i not in slots_cache:
return False
return True
def create_redis_connections(self, nodes):
"""
This function will create a redis connection to all nodes in :nodes:
"""
connection_pools = []
for node in nodes:
if node.redis_connection is None:
node.redis_connection = self.create_redis_node(
host=node.host, port=node.port, **self.connection_kwargs
)
connection_pools.append(node.redis_connection.connection_pool)
self._event_dispatcher.dispatch(
AfterPooledConnectionsInstantiationEvent(
connection_pools, ClientType.SYNC, self._credential_provider
)
)
def create_redis_node(self, host, port, **kwargs):
# We are configuring the connection pool not to retry
# connections on lower level clients to avoid retrying
# connections to nodes that are not reachable
# and to avoid blocking the connection pool.
# The only error that will have some handling in the lower
# level clients is ConnectionError which will trigger disconnection
# of the socket.
# The retries will be handled on cluster client level
# where we will have proper handling of the cluster topology
node_retry_config = Retry(
backoff=NoBackoff(), retries=0, supported_errors=(ConnectionError,)
)
if self.from_url:
# Create a redis node with a costumed connection pool
kwargs.update({"host": host})
kwargs.update({"port": port})
kwargs.update({"cache": self._cache})
kwargs.update({"retry": node_retry_config})
r = Redis(connection_pool=self.connection_pool_class(**kwargs))
else:
r = Redis(
host=host,
port=port,
cache=self._cache,
retry=node_retry_config,
**kwargs,
)
return r
def _get_or_create_cluster_node(self, host, port, role, tmp_nodes_cache):
node_name = get_node_name(host, port)
# check if we already have this node in the tmp_nodes_cache
target_node = tmp_nodes_cache.get(node_name)
if target_node is None:
# before creating a new cluster node, check if the cluster node already
# exists in the current nodes cache and has a valid connection so we can
# reuse it
target_node = self.nodes_cache.get(node_name)
if target_node is None or target_node.redis_connection is None:
# create new cluster node for this cluster
target_node = ClusterNode(host, port, role)
if target_node.server_type != role:
target_node.server_type = role
# add this node to the nodes cache
tmp_nodes_cache[target_node.name] = target_node
return target_node
def initialize(self):
"""
Initializes the nodes cache, slots cache and redis connections.
:startup_nodes:
Responsible for discovering other nodes in the cluster
"""
self.reset()
tmp_nodes_cache = {}
tmp_slots = {}
disagreements = []
startup_nodes_reachable = False
fully_covered = False
kwargs = self.connection_kwargs
exception = None
# Convert to tuple to prevent RuntimeError if self.startup_nodes
# is modified during iteration
for startup_node in tuple(self.startup_nodes.values()):
try:
if startup_node.redis_connection:
r = startup_node.redis_connection
else:
# Create a new Redis connection
r = self.create_redis_node(
startup_node.host, startup_node.port, **kwargs
)
self.startup_nodes[startup_node.name].redis_connection = r
# Make sure cluster mode is enabled on this node
try:
cluster_slots = str_if_bytes(r.execute_command("CLUSTER SLOTS"))
r.connection_pool.disconnect()
except ResponseError:
raise RedisClusterException(
"Cluster mode is not enabled on this node"
)
startup_nodes_reachable = True
except Exception as e:
# Try the next startup node.
# The exception is saved and raised only if we have no more nodes.
exception = e
continue
# CLUSTER SLOTS command results in the following output:
# [[slot_section[from_slot,to_slot,master,replica1,...,replicaN]]]
# where each node contains the following list: [IP, port, node_id]
# Therefore, cluster_slots[0][2][0] will be the IP address of the
# primary node of the first slot section.
# If there's only one server in the cluster, its ``host`` is ''
# Fix it to the host in startup_nodes
if (
len(cluster_slots) == 1
and len(cluster_slots[0][2][0]) == 0
and len(self.startup_nodes) == 1
):
cluster_slots[0][2][0] = startup_node.host
for slot in cluster_slots:
primary_node = slot[2]
host = str_if_bytes(primary_node[0])
if host == "":
host = startup_node.host
port = int(primary_node[1])
host, port = self.remap_host_port(host, port)
nodes_for_slot = []
target_node = self._get_or_create_cluster_node(
host, port, PRIMARY, tmp_nodes_cache
)
nodes_for_slot.append(target_node)
replica_nodes = slot[3:]
for replica_node in replica_nodes:
host = str_if_bytes(replica_node[0])
port = int(replica_node[1])
host, port = self.remap_host_port(host, port)
target_replica_node = self._get_or_create_cluster_node(
host, port, REPLICA, tmp_nodes_cache
)
nodes_for_slot.append(target_replica_node)
for i in range(int(slot[0]), int(slot[1]) + 1):
if i not in tmp_slots:
tmp_slots[i] = nodes_for_slot
else:
# Validate that 2 nodes want to use the same slot cache
# setup
tmp_slot = tmp_slots[i][0]
if tmp_slot.name != target_node.name:
disagreements.append(
f"{tmp_slot.name} vs {target_node.name} on slot: {i}"
)
if len(disagreements) > 5:
raise RedisClusterException(
f"startup_nodes could not agree on a valid "
f"slots cache: {', '.join(disagreements)}"
)
fully_covered = self.check_slots_coverage(tmp_slots)
if fully_covered:
# Don't need to continue to the next startup node if all
# slots are covered
break
if not startup_nodes_reachable:
raise RedisClusterException(
f"Redis Cluster cannot be connected. Please provide at least "
f"one reachable node: {str(exception)}"
) from exception
if self._cache is None and self._cache_config is not None:
if self._cache_factory is None:
self._cache = CacheFactory(self._cache_config).get_cache()
else:
self._cache = self._cache_factory.get_cache()
# Create Redis connections to all nodes
self.create_redis_connections(list(tmp_nodes_cache.values()))
# Check if the slots are not fully covered
if not fully_covered and self._require_full_coverage:
# Despite the requirement that the slots be covered, there
# isn't a full coverage
raise RedisClusterException(
f"All slots are not covered after query all startup_nodes. "
f"{len(tmp_slots)} of {REDIS_CLUSTER_HASH_SLOTS} "
f"covered..."
)
# Set the tmp variables to the real variables
self.nodes_cache = tmp_nodes_cache
self.slots_cache = tmp_slots
# Set the default node
self.default_node = self.get_nodes_by_server_type(PRIMARY)[0]
if self._dynamic_startup_nodes:
# Populate the startup nodes with all discovered nodes
self.startup_nodes = tmp_nodes_cache
# If initialize was called after a MovedError, clear it
self._moved_exception = None
def close(self) -> None:
self.default_node = None
for node in self.nodes_cache.values():
if node.redis_connection:
node.redis_connection.close()
def reset(self):
try:
self.read_load_balancer.reset()
except TypeError:
# The read_load_balancer is None, do nothing
pass
def remap_host_port(self, host: str, port: int) -> Tuple[str, int]:
"""
Remap the host and port returned from the cluster to a different
internal value. Useful if the client is not connecting directly
to the cluster.
"""
if self.address_remap:
return self.address_remap((host, port))
return host, port
def find_connection_owner(self, connection: Connection) -> Optional[Redis]:
node_name = get_node_name(connection.host, connection.port)
for node in tuple(self.nodes_cache.values()):
if node.redis_connection:
conn_args = node.redis_connection.connection_pool.connection_kwargs
if node_name == get_node_name(
conn_args.get("host"), conn_args.get("port")
):
return node
class ClusterPubSub(PubSub):
"""
Wrapper for PubSub class.
IMPORTANT: before using ClusterPubSub, read about the known limitations
with pubsub in Cluster mode and learn how to workaround them:
https://redis-py-cluster.readthedocs.io/en/stable/pubsub.html
"""
def __init__(
self,
redis_cluster,
node=None,
host=None,
port=None,
push_handler_func=None,
event_dispatcher: Optional["EventDispatcher"] = None,
**kwargs,
):
"""
When a pubsub instance is created without specifying a node, a single
node will be transparently chosen for the pubsub connection on the
first command execution. The node will be determined by:
1. Hashing the channel name in the request to find its keyslot
2. Selecting a node that handles the keyslot: If read_from_replicas is
set to true or load_balancing_strategy is set, a replica can be selected.
:type redis_cluster: RedisCluster
:type node: ClusterNode
:type host: str
:type port: int
"""
self.node = None
self.set_pubsub_node(redis_cluster, node, host, port)
connection_pool = (
None
if self.node is None
else redis_cluster.get_redis_connection(self.node).connection_pool
)
self.cluster = redis_cluster
self.node_pubsub_mapping = {}
self._pubsubs_generator = self._pubsubs_generator()
if event_dispatcher is None:
self._event_dispatcher = EventDispatcher()
else:
self._event_dispatcher = event_dispatcher
super().__init__(
connection_pool=connection_pool,
encoder=redis_cluster.encoder,
push_handler_func=push_handler_func,
event_dispatcher=self._event_dispatcher,
**kwargs,
)
def set_pubsub_node(self, cluster, node=None, host=None, port=None):
"""
The pubsub node will be set according to the passed node, host and port
When none of the node, host, or port are specified - the node is set
to None and will be determined by the keyslot of the channel in the
first command to be executed.
RedisClusterException will be thrown if the passed node does not exist
in the cluster.
If host is passed without port, or vice versa, a DataError will be
thrown.
:type cluster: RedisCluster
:type node: ClusterNode
:type host: str
:type port: int
"""
if node is not None:
# node is passed by the user
self._raise_on_invalid_node(cluster, node, node.host, node.port)
pubsub_node = node
elif host is not None and port is not None:
# host and port passed by the user
node = cluster.get_node(host=host, port=port)
self._raise_on_invalid_node(cluster, node, host, port)
pubsub_node = node
elif any([host, port]) is True:
# only 'host' or 'port' passed
raise DataError("Passing a host requires passing a port, and vice versa")
else:
# nothing passed by the user. set node to None
pubsub_node = None
self.node = pubsub_node
def get_pubsub_node(self):
"""
Get the node that is being used as the pubsub connection
"""
return self.node
def _raise_on_invalid_node(self, redis_cluster, node, host, port):
"""
Raise a RedisClusterException if the node is None or doesn't exist in
the cluster.
"""
if node is None or redis_cluster.get_node(node_name=node.name) is None:
raise RedisClusterException(
f"Node {host}:{port} doesn't exist in the cluster"
)
def execute_command(self, *args):
"""
Execute a subscribe/unsubscribe command.
Taken code from redis-py and tweak to make it work within a cluster.
"""
# NOTE: don't parse the response in this function -- it could pull a
# legitimate message off the stack if the connection is already
# subscribed to one or more channels
if self.connection is None:
if self.connection_pool is None:
if len(args) > 1:
# Hash the first channel and get one of the nodes holding
# this slot
channel = args[1]
slot = self.cluster.keyslot(channel)
node = self.cluster.nodes_manager.get_node_from_slot(
slot,
self.cluster.read_from_replicas,
self.cluster.load_balancing_strategy,
)
else:
# Get a random node
node = self.cluster.get_random_node()
self.node = node
redis_connection = self.cluster.get_redis_connection(node)
self.connection_pool = redis_connection.connection_pool
self.connection = self.connection_pool.get_connection()
# register a callback that re-subscribes to any channels we
# were listening to when we were disconnected
self.connection.register_connect_callback(self.on_connect)
if self.push_handler_func is not None:
self.connection._parser.set_pubsub_push_handler(self.push_handler_func)
self._event_dispatcher.dispatch(
AfterPubSubConnectionInstantiationEvent(
self.connection, self.connection_pool, ClientType.SYNC, self._lock
)
)
connection = self.connection
self._execute(connection, connection.send_command, *args)
def _get_node_pubsub(self, node):
try:
return self.node_pubsub_mapping[node.name]
except KeyError:
pubsub = node.redis_connection.pubsub(
push_handler_func=self.push_handler_func
)
self.node_pubsub_mapping[node.name] = pubsub
return pubsub
def _sharded_message_generator(self):
for _ in range(len(self.node_pubsub_mapping)):
pubsub = next(self._pubsubs_generator)
message = pubsub.get_message()
if message is not None:
return message
return None
def _pubsubs_generator(self):
while True:
yield from self.node_pubsub_mapping.values()
def get_sharded_message(
self, ignore_subscribe_messages=False, timeout=0.0, target_node=None
):
if target_node:
message = self.node_pubsub_mapping[target_node.name].get_message(
ignore_subscribe_messages=ignore_subscribe_messages, timeout=timeout
)
else:
message = self._sharded_message_generator()
if message is None:
return None
elif str_if_bytes(message["type"]) == "sunsubscribe":
if message["channel"] in self.pending_unsubscribe_shard_channels:
self.pending_unsubscribe_shard_channels.remove(message["channel"])
self.shard_channels.pop(message["channel"], None)
node = self.cluster.get_node_from_key(message["channel"])
if self.node_pubsub_mapping[node.name].subscribed is False:
self.node_pubsub_mapping.pop(node.name)
if not self.channels and not self.patterns and not self.shard_channels:
# There are no subscriptions anymore, set subscribed_event flag
# to false
self.subscribed_event.clear()
if self.ignore_subscribe_messages or ignore_subscribe_messages:
return None
return message
def ssubscribe(self, *args, **kwargs):
if args:
args = list_or_args(args[0], args[1:])
s_channels = dict.fromkeys(args)
s_channels.update(kwargs)
for s_channel, handler in s_channels.items():
node = self.cluster.get_node_from_key(s_channel)
pubsub = self._get_node_pubsub(node)
if handler:
pubsub.ssubscribe(**{s_channel: handler})
else:
pubsub.ssubscribe(s_channel)
self.shard_channels.update(pubsub.shard_channels)
self.pending_unsubscribe_shard_channels.difference_update(
self._normalize_keys({s_channel: None})
)
if pubsub.subscribed and not self.subscribed:
self.subscribed_event.set()
self.health_check_response_counter = 0
def sunsubscribe(self, *args):
if args:
args = list_or_args(args[0], args[1:])
else:
args = self.shard_channels
for s_channel in args:
node = self.cluster.get_node_from_key(s_channel)
p = self._get_node_pubsub(node)
p.sunsubscribe(s_channel)
self.pending_unsubscribe_shard_channels.update(
p.pending_unsubscribe_shard_channels
)
def get_redis_connection(self):
"""
Get the Redis connection of the pubsub connected node.
"""
if self.node is not None:
return self.node.redis_connection
def disconnect(self):
"""
Disconnect the pubsub connection.
"""
if self.connection:
self.connection.disconnect()
for pubsub in self.node_pubsub_mapping.values():
pubsub.connection.disconnect()
class ClusterPipeline(RedisCluster):
"""
Support for Redis pipeline
in cluster mode
"""
ERRORS_ALLOW_RETRY = (
ConnectionError,
TimeoutError,
MovedError,
AskError,
TryAgainError,
)
NO_SLOTS_COMMANDS = {"UNWATCH"}
IMMEDIATE_EXECUTE_COMMANDS = {"WATCH", "UNWATCH"}
UNWATCH_COMMANDS = {"DISCARD", "EXEC", "UNWATCH"}
@deprecated_args(
args_to_warn=[
"cluster_error_retry_attempts",
],
reason="Please configure the 'retry' object instead",
version="6.0.0",
)
def __init__(
self,
nodes_manager: "NodesManager",
commands_parser: "CommandsParser",
result_callbacks: Optional[Dict[str, Callable]] = None,
cluster_response_callbacks: Optional[Dict[str, Callable]] = None,
startup_nodes: Optional[List["ClusterNode"]] = None,
read_from_replicas: bool = False,
load_balancing_strategy: Optional[LoadBalancingStrategy] = None,
cluster_error_retry_attempts: int = 3,
reinitialize_steps: int = 5,
retry: Optional[Retry] = None,
lock=None,
transaction=False,
**kwargs,
):
""" """
self.command_stack = []
self.nodes_manager = nodes_manager
self.commands_parser = commands_parser
self.refresh_table_asap = False
self.result_callbacks = (
result_callbacks or self.__class__.RESULT_CALLBACKS.copy()
)
self.startup_nodes = startup_nodes if startup_nodes else []
self.read_from_replicas = read_from_replicas
self.load_balancing_strategy = load_balancing_strategy
self.command_flags = self.__class__.COMMAND_FLAGS.copy()
self.cluster_response_callbacks = cluster_response_callbacks
self.reinitialize_counter = 0
self.reinitialize_steps = reinitialize_steps
if retry is not None:
self.retry = retry
else:
self.retry = Retry(
backoff=ExponentialWithJitterBackoff(base=1, cap=10),
retries=cluster_error_retry_attempts,
)
self.encoder = Encoder(
kwargs.get("encoding", "utf-8"),
kwargs.get("encoding_errors", "strict"),
kwargs.get("decode_responses", False),
)
if lock is None:
lock = threading.RLock()
self._lock = lock
self.parent_execute_command = super().execute_command
self._execution_strategy: ExecutionStrategy = (
PipelineStrategy(self) if not transaction else TransactionStrategy(self)
)
def __repr__(self):
""" """
return f"{type(self).__name__}"
def __enter__(self):
""" """
return self
def __exit__(self, exc_type, exc_value, traceback):
""" """
self.reset()
def __del__(self):
try:
self.reset()
except Exception:
pass
def __len__(self):
""" """
return len(self._execution_strategy.command_queue)
def __bool__(self):
"Pipeline instances should always evaluate to True on Python 3+"
return True
def execute_command(self, *args, **kwargs):
"""
Wrapper function for pipeline_execute_command
"""
return self._execution_strategy.execute_command(*args, **kwargs)
def pipeline_execute_command(self, *args, **options):
"""
Stage a command to be executed when execute() is next called
Returns the current Pipeline object back so commands can be
chained together, such as:
pipe = pipe.set('foo', 'bar').incr('baz').decr('bang')
At some other point, you can then run: pipe.execute(),
which will execute all commands queued in the pipe.
"""
return self._execution_strategy.execute_command(*args, **options)
def annotate_exception(self, exception, number, command):
"""
Provides extra context to the exception prior to it being handled
"""
self._execution_strategy.annotate_exception(exception, number, command)
def execute(self, raise_on_error: bool = True) -> List[Any]:
"""
Execute all the commands in the current pipeline
"""
try:
return self._execution_strategy.execute(raise_on_error)
finally:
self.reset()
def reset(self):
"""
Reset back to empty pipeline.
"""
self._execution_strategy.reset()
def send_cluster_commands(
self, stack, raise_on_error=True, allow_redirections=True
):
return self._execution_strategy.send_cluster_commands(
stack, raise_on_error=raise_on_error, allow_redirections=allow_redirections
)
def exists(self, *keys):
return self._execution_strategy.exists(*keys)
def eval(self):
""" """
return self._execution_strategy.eval()
def multi(self):
"""
Start a transactional block of the pipeline after WATCH commands
are issued. End the transactional block with `execute`.
"""
self._execution_strategy.multi()
def load_scripts(self):
""" """
self._execution_strategy.load_scripts()
def discard(self):
""" """
self._execution_strategy.discard()
def watch(self, *names):
"""Watches the values at keys ``names``"""
self._execution_strategy.watch(*names)
def unwatch(self):
"""Unwatches all previously specified keys"""
self._execution_strategy.unwatch()
def script_load_for_pipeline(self, *args, **kwargs):
self._execution_strategy.script_load_for_pipeline(*args, **kwargs)
def delete(self, *names):
self._execution_strategy.delete(*names)
def unlink(self, *names):
self._execution_strategy.unlink(*names)
def block_pipeline_command(name: str) -> Callable[..., Any]:
"""
Prints error because some pipelined commands should
be blocked when running in cluster-mode
"""
def inner(*args, **kwargs):
raise RedisClusterException(
f"ERROR: Calling pipelined function {name} is blocked "
f"when running redis in cluster mode..."
)
return inner
# Blocked pipeline commands
PIPELINE_BLOCKED_COMMANDS = (
"BGREWRITEAOF",
"BGSAVE",
"BITOP",
"BRPOPLPUSH",
"CLIENT GETNAME",
"CLIENT KILL",
"CLIENT LIST",
"CLIENT SETNAME",
"CLIENT",
"CONFIG GET",
"CONFIG RESETSTAT",
"CONFIG REWRITE",
"CONFIG SET",
"CONFIG",
"DBSIZE",
"ECHO",
"EVALSHA",
"FLUSHALL",
"FLUSHDB",
"INFO",
"KEYS",
"LASTSAVE",
"MGET",
"MGET NONATOMIC",
"MOVE",
"MSET",
"MSET NONATOMIC",
"MSETNX",
"PFCOUNT",
"PFMERGE",
"PING",
"PUBLISH",
"RANDOMKEY",
"READONLY",
"READWRITE",
"RENAME",
"RENAMENX",
"RPOPLPUSH",
"SAVE",
"SCAN",
"SCRIPT EXISTS",
"SCRIPT FLUSH",
"SCRIPT KILL",
"SCRIPT LOAD",
"SCRIPT",
"SDIFF",
"SDIFFSTORE",
"SENTINEL GET MASTER ADDR BY NAME",
"SENTINEL MASTER",
"SENTINEL MASTERS",
"SENTINEL MONITOR",
"SENTINEL REMOVE",
"SENTINEL SENTINELS",
"SENTINEL SET",
"SENTINEL SLAVES",
"SENTINEL",
"SHUTDOWN",
"SINTER",
"SINTERSTORE",
"SLAVEOF",
"SLOWLOG GET",
"SLOWLOG LEN",
"SLOWLOG RESET",
"SLOWLOG",
"SMOVE",
"SORT",
"SUNION",
"SUNIONSTORE",
"TIME",
)
for command in PIPELINE_BLOCKED_COMMANDS:
command = command.replace(" ", "_").lower()
setattr(ClusterPipeline, command, block_pipeline_command(command))
class PipelineCommand:
""" """
def __init__(self, args, options=None, position=None):
self.args = args
if options is None:
options = {}
self.options = options
self.position = position
self.result = None
self.node = None
self.asking = False
class NodeCommands:
""" """
def __init__(self, parse_response, connection_pool, connection):
""" """
self.parse_response = parse_response
self.connection_pool = connection_pool
self.connection = connection
self.commands = []
def append(self, c):
""" """
self.commands.append(c)
def write(self):
"""
Code borrowed from Redis so it can be fixed
"""
connection = self.connection
commands = self.commands
# We are going to clobber the commands with the write, so go ahead
# and ensure that nothing is sitting there from a previous run.
for c in commands:
c.result = None
# build up all commands into a single request to increase network perf
# send all the commands and catch connection and timeout errors.
try:
connection.send_packed_command(
connection.pack_commands([c.args for c in commands])
)
except (ConnectionError, TimeoutError) as e:
for c in commands:
c.result = e
def read(self):
""" """
connection = self.connection
for c in self.commands:
# if there is a result on this command,
# it means we ran into an exception
# like a connection error. Trying to parse
# a response on a connection that
# is no longer open will result in a
# connection error raised by redis-py.
# but redis-py doesn't check in parse_response
# that the sock object is
# still set and if you try to
# read from a closed connection, it will
# result in an AttributeError because
# it will do a readline() call on None.
# This can have all kinds of nasty side-effects.
# Treating this case as a connection error
# is fine because it will dump
# the connection object back into the
# pool and on the next write, it will
# explicitly open the connection and all will be well.
if c.result is None:
try:
c.result = self.parse_response(connection, c.args[0], **c.options)
except (ConnectionError, TimeoutError) as e:
for c in self.commands:
c.result = e
return
except RedisError:
c.result = sys.exc_info()[1]
class ExecutionStrategy(ABC):
@property
@abstractmethod
def command_queue(self):
pass
@abstractmethod
def execute_command(self, *args, **kwargs):
"""
Execution flow for current execution strategy.
See: ClusterPipeline.execute_command()
"""
pass
@abstractmethod
def annotate_exception(self, exception, number, command):
"""
Annotate exception according to current execution strategy.
See: ClusterPipeline.annotate_exception()
"""
pass
@abstractmethod
def pipeline_execute_command(self, *args, **options):
"""
Pipeline execution flow for current execution strategy.
See: ClusterPipeline.pipeline_execute_command()
"""
pass
@abstractmethod
def execute(self, raise_on_error: bool = True) -> List[Any]:
"""
Executes current execution strategy.
See: ClusterPipeline.execute()
"""
pass
@abstractmethod
def send_cluster_commands(
self, stack, raise_on_error=True, allow_redirections=True
):
"""
Sends commands according to current execution strategy.
See: ClusterPipeline.send_cluster_commands()
"""
pass
@abstractmethod
def reset(self):
"""
Resets current execution strategy.
See: ClusterPipeline.reset()
"""
pass
@abstractmethod
def exists(self, *keys):
pass
@abstractmethod
def eval(self):
pass
@abstractmethod
def multi(self):
"""
Starts transactional context.
See: ClusterPipeline.multi()
"""
pass
@abstractmethod
def load_scripts(self):
pass
@abstractmethod
def watch(self, *names):
pass
@abstractmethod
def unwatch(self):
"""
Unwatches all previously specified keys
See: ClusterPipeline.unwatch()
"""
pass
@abstractmethod
def script_load_for_pipeline(self, *args, **kwargs):
pass
@abstractmethod
def delete(self, *names):
"""
"Delete a key specified by ``names``"
See: ClusterPipeline.delete()
"""
pass
@abstractmethod
def unlink(self, *names):
"""
"Unlink a key specified by ``names``"
See: ClusterPipeline.unlink()
"""
pass
@abstractmethod
def discard(self):
pass
class AbstractStrategy(ExecutionStrategy):
def __init__(
self,
pipe: ClusterPipeline,
):
self._command_queue: List[PipelineCommand] = []
self._pipe = pipe
self._nodes_manager = self._pipe.nodes_manager
@property
def command_queue(self):
return self._command_queue
@command_queue.setter
def command_queue(self, queue: List[PipelineCommand]):
self._command_queue = queue
@abstractmethod
def execute_command(self, *args, **kwargs):
pass
def pipeline_execute_command(self, *args, **options):
self._command_queue.append(
PipelineCommand(args, options, len(self._command_queue))
)
return self._pipe
@abstractmethod
def execute(self, raise_on_error: bool = True) -> List[Any]:
pass
@abstractmethod
def send_cluster_commands(
self, stack, raise_on_error=True, allow_redirections=True
):
pass
@abstractmethod
def reset(self):
pass
def exists(self, *keys):
return self.execute_command("EXISTS", *keys)
def eval(self):
""" """
raise RedisClusterException("method eval() is not implemented")
def load_scripts(self):
""" """
raise RedisClusterException("method load_scripts() is not implemented")
def script_load_for_pipeline(self, *args, **kwargs):
""" """
raise RedisClusterException(
"method script_load_for_pipeline() is not implemented"
)
def annotate_exception(self, exception, number, command):
"""
Provides extra context to the exception prior to it being handled
"""
cmd = " ".join(map(safe_str, command))
msg = (
f"Command # {number} ({truncate_text(cmd)}) of pipeline "
f"caused error: {exception.args[0]}"
)
exception.args = (msg,) + exception.args[1:]
class PipelineStrategy(AbstractStrategy):
def __init__(self, pipe: ClusterPipeline):
super().__init__(pipe)
self.command_flags = pipe.command_flags
def execute_command(self, *args, **kwargs):
return self.pipeline_execute_command(*args, **kwargs)
def _raise_first_error(self, stack):
"""
Raise the first exception on the stack
"""
for c in stack:
r = c.result
if isinstance(r, Exception):
self.annotate_exception(r, c.position + 1, c.args)
raise r
def execute(self, raise_on_error: bool = True) -> List[Any]:
stack = self._command_queue
if not stack:
return []
try:
return self.send_cluster_commands(stack, raise_on_error)
finally:
self.reset()
def reset(self):
"""
Reset back to empty pipeline.
"""
self._command_queue = []
def send_cluster_commands(
self, stack, raise_on_error=True, allow_redirections=True
):
"""
Wrapper for RedisCluster.ERRORS_ALLOW_RETRY errors handling.
If one of the retryable exceptions has been thrown we assume that:
- connection_pool was disconnected
- connection_pool was reseted
- refereh_table_asap set to True
It will try the number of times specified by
the retries in config option "self.retry"
which defaults to 3 unless manually configured.
If it reaches the number of times, the command will
raises ClusterDownException.
"""
if not stack:
return []
retry_attempts = self._pipe.retry.get_retries()
while True:
try:
return self._send_cluster_commands(
stack,
raise_on_error=raise_on_error,
allow_redirections=allow_redirections,
)
except RedisCluster.ERRORS_ALLOW_RETRY as e:
if retry_attempts > 0:
# Try again with the new cluster setup. All other errors
# should be raised.
retry_attempts -= 1
pass
else:
raise e
def _send_cluster_commands(
self, stack, raise_on_error=True, allow_redirections=True
):
"""
Send a bunch of cluster commands to the redis cluster.
`allow_redirections` If the pipeline should follow
`ASK` & `MOVED` responses automatically. If set
to false it will raise RedisClusterException.
"""
# the first time sending the commands we send all of
# the commands that were queued up.
# if we have to run through it again, we only retry
# the commands that failed.
attempt = sorted(stack, key=lambda x: x.position)
is_default_node = False
# build a list of node objects based on node names we need to
nodes = {}
# as we move through each command that still needs to be processed,
# we figure out the slot number that command maps to, then from
# the slot determine the node.
for c in attempt:
while True:
# refer to our internal node -> slot table that
# tells us where a given command should route to.
# (it might be possible we have a cached node that no longer
# exists in the cluster, which is why we do this in a loop)
passed_targets = c.options.pop("target_nodes", None)
if passed_targets and not self._is_nodes_flag(passed_targets):
target_nodes = self._parse_target_nodes(passed_targets)
else:
target_nodes = self._determine_nodes(
*c.args, node_flag=passed_targets
)
if not target_nodes:
raise RedisClusterException(
f"No targets were found to execute {c.args} command on"
)
if len(target_nodes) > 1:
raise RedisClusterException(
f"Too many targets for command {c.args}"
)
node = target_nodes[0]
if node == self._pipe.get_default_node():
is_default_node = True
# now that we know the name of the node
# ( it's just a string in the form of host:port )
# we can build a list of commands for each node.
node_name = node.name
if node_name not in nodes:
redis_node = self._pipe.get_redis_connection(node)
try:
connection = get_connection(redis_node)
except (ConnectionError, TimeoutError):
for n in nodes.values():
n.connection_pool.release(n.connection)
# Connection retries are being handled in the node's
# Retry object. Reinitialize the node -> slot table.
self._nodes_manager.initialize()
if is_default_node:
self._pipe.replace_default_node()
raise
nodes[node_name] = NodeCommands(
redis_node.parse_response,
redis_node.connection_pool,
connection,
)
nodes[node_name].append(c)
break
# send the commands in sequence.
# we write to all the open sockets for each node first,
# before reading anything
# this allows us to flush all the requests out across the
# network
# so that we can read them from different sockets as they come back.
# we dont' multiplex on the sockets as they come available,
# but that shouldn't make too much difference.
try:
node_commands = nodes.values()
for n in node_commands:
n.write()
for n in node_commands:
n.read()
finally:
# release all of the redis connections we allocated earlier
# back into the connection pool.
# we used to do this step as part of a try/finally block,
# but it is really dangerous to
# release connections back into the pool if for some
# reason the socket has data still left in it
# from a previous operation. The write and
# read operations already have try/catch around them for
# all known types of errors including connection
# and socket level errors.
# So if we hit an exception, something really bad
# happened and putting any oF
# these connections back into the pool is a very bad idea.
# the socket might have unread buffer still sitting in it,
# and then the next time we read from it we pass the
# buffered result back from a previous command and
# every single request after to that connection will always get
# a mismatched result.
for n in nodes.values():
n.connection_pool.release(n.connection)
# if the response isn't an exception it is a
# valid response from the node
# we're all done with that command, YAY!
# if we have more commands to attempt, we've run into problems.
# collect all the commands we are allowed to retry.
# (MOVED, ASK, or connection errors or timeout errors)
attempt = sorted(
(
c
for c in attempt
if isinstance(c.result, ClusterPipeline.ERRORS_ALLOW_RETRY)
),
key=lambda x: x.position,
)
if attempt and allow_redirections:
# RETRY MAGIC HAPPENS HERE!
# send these remaining commands one at a time using `execute_command`
# in the main client. This keeps our retry logic
# in one place mostly,
# and allows us to be more confident in correctness of behavior.
# at this point any speed gains from pipelining have been lost
# anyway, so we might as well make the best
# attempt to get the correct behavior.
#
# The client command will handle retries for each
# individual command sequentially as we pass each
# one into `execute_command`. Any exceptions
# that bubble out should only appear once all
# retries have been exhausted.
#
# If a lot of commands have failed, we'll be setting the
# flag to rebuild the slots table from scratch.
# So MOVED errors should correct themselves fairly quickly.
self._pipe.reinitialize_counter += 1
if self._pipe._should_reinitialized():
self._nodes_manager.initialize()
if is_default_node:
self._pipe.replace_default_node()
for c in attempt:
try:
# send each command individually like we
# do in the main client.
c.result = self._pipe.parent_execute_command(*c.args, **c.options)
except RedisError as e:
c.result = e
# turn the response back into a simple flat array that corresponds
# to the sequence of commands issued in the stack in pipeline.execute()
response = []
for c in sorted(stack, key=lambda x: x.position):
if c.args[0] in self._pipe.cluster_response_callbacks:
# Remove keys entry, it needs only for cache.
c.options.pop("keys", None)
c.result = self._pipe.cluster_response_callbacks[c.args[0]](
c.result, **c.options
)
response.append(c.result)
if raise_on_error:
self._raise_first_error(stack)
return response
def _is_nodes_flag(self, target_nodes):
return isinstance(target_nodes, str) and target_nodes in self._pipe.node_flags
def _parse_target_nodes(self, target_nodes):
if isinstance(target_nodes, list):
nodes = target_nodes
elif isinstance(target_nodes, ClusterNode):
# Supports passing a single ClusterNode as a variable
nodes = [target_nodes]
elif isinstance(target_nodes, dict):
# Supports dictionaries of the format {node_name: node}.
# It enables to execute commands with multi nodes as follows:
# rc.cluster_save_config(rc.get_primaries())
nodes = target_nodes.values()
else:
raise TypeError(
"target_nodes type can be one of the following: "
"node_flag (PRIMARIES, REPLICAS, RANDOM, ALL_NODES),"
"ClusterNode, list<ClusterNode>, or dict<any, ClusterNode>. "
f"The passed type is {type(target_nodes)}"
)
return nodes
def _determine_nodes(self, *args, **kwargs) -> List["ClusterNode"]:
# Determine which nodes should be executed the command on.
# Returns a list of target nodes.
command = args[0].upper()
if (
len(args) >= 2
and f"{args[0]} {args[1]}".upper() in self._pipe.command_flags
):
command = f"{args[0]} {args[1]}".upper()
nodes_flag = kwargs.pop("nodes_flag", None)
if nodes_flag is not None:
# nodes flag passed by the user
command_flag = nodes_flag
else:
# get the nodes group for this command if it was predefined
command_flag = self._pipe.command_flags.get(command)
if command_flag == self._pipe.RANDOM:
# return a random node
return [self._pipe.get_random_node()]
elif command_flag == self._pipe.PRIMARIES:
# return all primaries
return self._pipe.get_primaries()
elif command_flag == self._pipe.REPLICAS:
# return all replicas
return self._pipe.get_replicas()
elif command_flag == self._pipe.ALL_NODES:
# return all nodes
return self._pipe.get_nodes()
elif command_flag == self._pipe.DEFAULT_NODE:
# return the cluster's default node
return [self._nodes_manager.default_node]
elif command in self._pipe.SEARCH_COMMANDS[0]:
return [self._nodes_manager.default_node]
else:
# get the node that holds the key's slot
slot = self._pipe.determine_slot(*args)
node = self._nodes_manager.get_node_from_slot(
slot,
self._pipe.read_from_replicas and command in READ_COMMANDS,
self._pipe.load_balancing_strategy
if command in READ_COMMANDS
else None,
)
return [node]
def multi(self):
raise RedisClusterException(
"method multi() is not supported outside of transactional context"
)
def discard(self):
raise RedisClusterException(
"method discard() is not supported outside of transactional context"
)
def watch(self, *names):
raise RedisClusterException(
"method watch() is not supported outside of transactional context"
)
def unwatch(self, *names):
raise RedisClusterException(
"method unwatch() is not supported outside of transactional context"
)
def delete(self, *names):
if len(names) != 1:
raise RedisClusterException(
"deleting multiple keys is not implemented in pipeline command"
)
return self.execute_command("DEL", names[0])
def unlink(self, *names):
if len(names) != 1:
raise RedisClusterException(
"unlinking multiple keys is not implemented in pipeline command"
)
return self.execute_command("UNLINK", names[0])
class TransactionStrategy(AbstractStrategy):
NO_SLOTS_COMMANDS = {"UNWATCH"}
IMMEDIATE_EXECUTE_COMMANDS = {"WATCH", "UNWATCH"}
UNWATCH_COMMANDS = {"DISCARD", "EXEC", "UNWATCH"}
SLOT_REDIRECT_ERRORS = (AskError, MovedError)
CONNECTION_ERRORS = (
ConnectionError,
OSError,
ClusterDownError,
SlotNotCoveredError,
)
def __init__(self, pipe: ClusterPipeline):
super().__init__(pipe)
self._explicit_transaction = False
self._watching = False
self._pipeline_slots: Set[int] = set()
self._transaction_connection: Optional[Connection] = None
self._executing = False
self._retry = copy(self._pipe.retry)
self._retry.update_supported_errors(
RedisCluster.ERRORS_ALLOW_RETRY + self.SLOT_REDIRECT_ERRORS
)
def _get_client_and_connection_for_transaction(self) -> Tuple[Redis, Connection]:
"""
Find a connection for a pipeline transaction.
For running an atomic transaction, watch keys ensure that contents have not been
altered as long as the watch commands for those keys were sent over the same
connection. So once we start watching a key, we fetch a connection to the
node that owns that slot and reuse it.
"""
if not self._pipeline_slots:
raise RedisClusterException(
"At least a command with a key is needed to identify a node"
)
node: ClusterNode = self._nodes_manager.get_node_from_slot(
list(self._pipeline_slots)[0], False
)
redis_node: Redis = self._pipe.get_redis_connection(node)
if self._transaction_connection:
if not redis_node.connection_pool.owns_connection(
self._transaction_connection
):
previous_node = self._nodes_manager.find_connection_owner(
self._transaction_connection
)
previous_node.connection_pool.release(self._transaction_connection)
self._transaction_connection = None
if not self._transaction_connection:
self._transaction_connection = get_connection(redis_node)
return redis_node, self._transaction_connection
def execute_command(self, *args, **kwargs):
slot_number: Optional[int] = None
if args[0] not in ClusterPipeline.NO_SLOTS_COMMANDS:
slot_number = self._pipe.determine_slot(*args)
if (
self._watching or args[0] in self.IMMEDIATE_EXECUTE_COMMANDS
) and not self._explicit_transaction:
if args[0] == "WATCH":
self._validate_watch()
if slot_number is not None:
if self._pipeline_slots and slot_number not in self._pipeline_slots:
raise CrossSlotTransactionError(
"Cannot watch or send commands on different slots"
)
self._pipeline_slots.add(slot_number)
elif args[0] not in self.NO_SLOTS_COMMANDS:
raise RedisClusterException(
f"Cannot identify slot number for command: {args[0]},"
"it cannot be triggered in a transaction"
)
return self._immediate_execute_command(*args, **kwargs)
else:
if slot_number is not None:
self._pipeline_slots.add(slot_number)
return self.pipeline_execute_command(*args, **kwargs)
def _validate_watch(self):
if self._explicit_transaction:
raise RedisError("Cannot issue a WATCH after a MULTI")
self._watching = True
def _immediate_execute_command(self, *args, **options):
return self._retry.call_with_retry(
lambda: self._get_connection_and_send_command(*args, **options),
self._reinitialize_on_error,
)
def _get_connection_and_send_command(self, *args, **options):
redis_node, connection = self._get_client_and_connection_for_transaction()
return self._send_command_parse_response(
connection, redis_node, args[0], *args, **options
)
def _send_command_parse_response(
self, conn, redis_node: Redis, command_name, *args, **options
):
"""
Send a command and parse the response
"""
conn.send_command(*args)
output = redis_node.parse_response(conn, command_name, **options)
if command_name in self.UNWATCH_COMMANDS:
self._watching = False
return output
def _reinitialize_on_error(self, error):
if self._watching:
if type(error) in self.SLOT_REDIRECT_ERRORS and self._executing:
raise WatchError("Slot rebalancing occurred while watching keys")
if (
type(error) in self.SLOT_REDIRECT_ERRORS
or type(error) in self.CONNECTION_ERRORS
):
if self._transaction_connection:
self._transaction_connection = None
self._pipe.reinitialize_counter += 1
if self._pipe._should_reinitialized():
self._nodes_manager.initialize()
self.reinitialize_counter = 0
else:
self._nodes_manager.update_moved_exception(error)
self._executing = False
def _raise_first_error(self, responses, stack):
"""
Raise the first exception on the stack
"""
for r, cmd in zip(responses, stack):
if isinstance(r, Exception):
self.annotate_exception(r, cmd.position + 1, cmd.args)
raise r
def execute(self, raise_on_error: bool = True) -> List[Any]:
stack = self._command_queue
if not stack and (not self._watching or not self._pipeline_slots):
return []
return self._execute_transaction_with_retries(stack, raise_on_error)
def _execute_transaction_with_retries(
self, stack: List["PipelineCommand"], raise_on_error: bool
):
return self._retry.call_with_retry(
lambda: self._execute_transaction(stack, raise_on_error),
self._reinitialize_on_error,
)
def _execute_transaction(
self, stack: List["PipelineCommand"], raise_on_error: bool
):
if len(self._pipeline_slots) > 1:
raise CrossSlotTransactionError(
"All keys involved in a cluster transaction must map to the same slot"
)
self._executing = True
redis_node, connection = self._get_client_and_connection_for_transaction()
stack = chain(
[PipelineCommand(("MULTI",))],
stack,
[PipelineCommand(("EXEC",))],
)
commands = [c.args for c in stack if EMPTY_RESPONSE not in c.options]
packed_commands = connection.pack_commands(commands)
connection.send_packed_command(packed_commands)
errors = []
# parse off the response for MULTI
# NOTE: we need to handle ResponseErrors here and continue
# so that we read all the additional command messages from
# the socket
try:
redis_node.parse_response(connection, "MULTI")
except ResponseError as e:
self.annotate_exception(e, 0, "MULTI")
errors.append(e)
except self.CONNECTION_ERRORS as cluster_error:
self.annotate_exception(cluster_error, 0, "MULTI")
raise
# and all the other commands
for i, command in enumerate(self._command_queue):
if EMPTY_RESPONSE in command.options:
errors.append((i, command.options[EMPTY_RESPONSE]))
else:
try:
_ = redis_node.parse_response(connection, "_")
except self.SLOT_REDIRECT_ERRORS as slot_error:
self.annotate_exception(slot_error, i + 1, command.args)
errors.append(slot_error)
except self.CONNECTION_ERRORS as cluster_error:
self.annotate_exception(cluster_error, i + 1, command.args)
raise
except ResponseError as e:
self.annotate_exception(e, i + 1, command.args)
errors.append(e)
response = None
# parse the EXEC.
try:
response = redis_node.parse_response(connection, "EXEC")
except ExecAbortError:
if errors:
raise errors[0]
raise
self._executing = False
# EXEC clears any watched keys
self._watching = False
if response is None:
raise WatchError("Watched variable changed.")
# put any parse errors into the response
for i, e in errors:
response.insert(i, e)
if len(response) != len(self._command_queue):
raise InvalidPipelineStack(
"Unexpected response length for cluster pipeline EXEC."
" Command stack was {} but response had length {}".format(
[c.args[0] for c in self._command_queue], len(response)
)
)
# find any errors in the response and raise if necessary
if raise_on_error or len(errors) > 0:
self._raise_first_error(
response,
self._command_queue,
)
# We have to run response callbacks manually
data = []
for r, cmd in zip(response, self._command_queue):
if not isinstance(r, Exception):
command_name = cmd.args[0]
if command_name in self._pipe.cluster_response_callbacks:
r = self._pipe.cluster_response_callbacks[command_name](
r, **cmd.options
)
data.append(r)
return data
def reset(self):
self._command_queue = []
# make sure to reset the connection state in the event that we were
# watching something
if self._transaction_connection:
try:
if self._watching:
# call this manually since our unwatch or
# immediate_execute_command methods can call reset()
self._transaction_connection.send_command("UNWATCH")
self._transaction_connection.read_response()
# we can safely return the connection to the pool here since we're
# sure we're no longer WATCHing anything
node = self._nodes_manager.find_connection_owner(
self._transaction_connection
)
node.redis_connection.connection_pool.release(
self._transaction_connection
)
self._transaction_connection = None
except self.CONNECTION_ERRORS:
# disconnect will also remove any previous WATCHes
if self._transaction_connection:
self._transaction_connection.disconnect()
# clean up the other instance attributes
self._watching = False
self._explicit_transaction = False
self._pipeline_slots = set()
self._executing = False
def send_cluster_commands(
self, stack, raise_on_error=True, allow_redirections=True
):
raise NotImplementedError(
"send_cluster_commands cannot be executed in transactional context."
)
def multi(self):
if self._explicit_transaction:
raise RedisError("Cannot issue nested calls to MULTI")
if self._command_queue:
raise RedisError(
"Commands without an initial WATCH have already been issued"
)
self._explicit_transaction = True
def watch(self, *names):
if self._explicit_transaction:
raise RedisError("Cannot issue a WATCH after a MULTI")
return self.execute_command("WATCH", *names)
def unwatch(self):
if self._watching:
return self.execute_command("UNWATCH")
return True
def discard(self):
self.reset()
def delete(self, *names):
return self.execute_command("DEL", *names)
def unlink(self, *names):
return self.execute_command("UNLINK", *names)
|