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 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359
|
/* Copyright (c) 2000, 2025, Oracle and/or its affiliates.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is designed to work with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have either included with
the program or referenced in the documentation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/**
@addtogroup Replication
@{
@file sql/rpl_replica.cc
@brief Code to run the io thread and the sql thread on the
replication slave.
*/
#include "sql/rpl_replica.h"
#include "my_config.h"
#include <errno.h>
#include <fcntl.h>
#include <math.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "include/compression.h"
#include "include/mutex_lock.h"
#include "mysql/components/services/bits/psi_bits.h"
#include "mysql/components/services/bits/psi_memory_bits.h"
#include "mysql/components/services/bits/psi_stage_bits.h"
#include "mysql/components/services/log_builtins.h"
#include "mysql/plugin.h"
#include "mysql/psi/mysql_cond.h"
#include "mysql/psi/mysql_mutex.h"
#include "mysql/status_var.h"
#include "sql/changestreams/apply/replication_thread_status.h"
#include "sql/rpl_channel_service_interface.h"
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#include <time.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <algorithm>
#include <atomic>
#include <deque>
#include <map>
#include <regex>
#include <string>
#include <utility>
#include <vector>
#include "errmsg.h" // CR_*
#include "lex_string.h"
#include "libbinlogevents/include/binlog_event.h"
#include "libbinlogevents/include/control_events.h"
#include "libbinlogevents/include/debug_vars.h"
#include "m_ctype.h"
#include "m_string.h"
#include "mutex_lock.h" // MUTEX_LOCK
#include "my_bitmap.h" // MY_BITMAP
#include "my_byteorder.h"
#include "my_command.h"
#include "my_compiler.h"
#include "my_dbug.h"
#include "my_dir.h"
#include "my_io.h"
#include "my_loglevel.h"
#include "my_macros.h"
#include "my_sys.h"
#include "my_systime.h"
#include "my_thread_local.h" // thread_local_key_t
#include "mysql.h" // MYSQL
#include "mysql/psi/mysql_file.h"
#include "mysql/psi/mysql_memory.h"
#include "mysql/psi/mysql_thread.h"
#include "mysql/service_mysql_alloc.h"
#include "mysql/thread_type.h"
#include "mysql_com.h"
#include "mysqld_error.h"
#include "pfs_thread_provider.h"
#include "prealloced_array.h"
#include "sql-common/net_ns.h"
#include "sql/auth/auth_acls.h"
#include "sql/auth/sql_security_ctx.h"
#include "sql/auto_thd.h"
#include "sql/binlog.h"
#include "sql/binlog_reader.h"
#include "sql/clone_handler.h" // is_provisioning
#include "sql/current_thd.h"
#include "sql/debug_sync.h" // DEBUG_SYNC
#include "sql/derror.h" // ER_THD
#include "sql/dynamic_ids.h" // Server_ids
#include "sql/handler.h"
#include "sql/item.h"
#include "sql/log.h"
#include "sql/log_event.h" // Rotate_log_event
#include "sql/mdl.h"
#include "sql/mysqld.h" // ER
#include "sql/mysqld_thd_manager.h" // Global_THD_manager
#include "sql/protocol.h"
#include "sql/protocol_classic.h"
#include "sql/psi_memory_key.h"
#include "sql/query_options.h"
#include "sql/rpl_applier_reader.h"
#include "sql/rpl_async_conn_failover.h"
#include "sql/rpl_async_conn_failover_configuration_propagation.h"
#include "sql/rpl_filter.h"
#include "sql/rpl_group_replication.h"
#include "sql/rpl_gtid.h"
#include "sql/rpl_handler.h" // RUN_HOOK
#include "sql/rpl_info.h"
#include "sql/rpl_info_factory.h" // Rpl_info_factory
#include "sql/rpl_info_handler.h"
#include "sql/rpl_io_monitor.h"
#include "sql/rpl_mi.h"
#include "sql/rpl_msr.h" // Multisource_info
#include "sql/rpl_mta_submode.h"
#include "sql/rpl_replica_commit_order_manager.h" // Commit_order_manager
#include "sql/rpl_replica_until_options.h"
#include "sql/rpl_reporting.h"
#include "sql/rpl_rli.h" // Relay_log_info
#include "sql/rpl_rli_pdb.h" // Slave_worker
#include "sql/rpl_trx_boundary_parser.h"
#include "sql/rpl_utility.h"
#include "sql/sql_backup_lock.h" // is_instance_backup_locked
#include "sql/sql_class.h" // THD
#include "sql/sql_const.h"
#include "sql/sql_error.h"
#include "sql/sql_lex.h"
#include "sql/sql_list.h"
#include "sql/sql_parse.h" // execute_init_command
#include "sql/sql_plugin.h" // opt_plugin_dir_ptr
#include "sql/system_variables.h"
#include "sql/table.h"
#include "sql/transaction.h" // trans_begin
#include "sql/transaction_info.h"
#include "sql_common.h" // end_server
#include "sql_string.h"
#include "typelib.h"
#ifndef NDEBUG
#include "rpl_debug_points.h"
#endif
#include "scope_guard.h"
struct mysql_cond_t;
struct mysql_mutex_t;
using binary_log::checksum_crc32;
using binary_log::Log_event_header;
using std::max;
using std::min;
#define FLAGSTR(V, F) ((V) & (F) ? #F " " : "")
/*
a parameter of sql_slave_killed() to defer the killed status
*/
#define SLAVE_WAIT_GROUP_DONE 60
bool use_slave_mask = false;
MY_BITMAP slave_error_mask;
char slave_skip_error_names[SHOW_VAR_FUNC_BUFF_SIZE];
char *replica_load_tmpdir = nullptr;
bool replicate_same_server_id;
ulonglong relay_log_space_limit = 0;
const char *relay_log_index = nullptr;
const char *relay_log_basename = nullptr;
/*
MTS load-ballancing parameter.
Max length of one MTS Worker queue. The value also determines the size
of Relay_log_info::gaq (see @c slave_start_workers()).
It can be set to any value in [1, ULONG_MAX - 1] range.
*/
const ulong mts_slave_worker_queue_len_max = 16384;
/*
Statistics go to the error log every # of seconds when
--log_error_verbosity > 2
*/
const long mts_online_stat_period = 60 * 2;
/*
MTS load-ballancing parameter.
Time unit in microsecs to sleep by MTS Coordinator to avoid extra thread
signalling in the case of Worker queues are close to be filled up.
*/
const ulong mts_coordinator_basic_nap = 5;
/*
MTS load-ballancing parameter.
Percent of Worker queue size at which Worker is considered to become
hungry.
C enqueues --+ . underrun level
V "
+----------+-+------------------+--------------+
| empty |.|::::::::::::::::::|xxxxxxxxxxxxxx| ---> Worker dequeues
+----------+-+------------------+--------------+
Like in the above diagram enqueuing to the x-d area would indicate
actual underrruning by Worker.
*/
const ulong mts_worker_underrun_level = 10;
/*
When slave thread exits, we need to remember the temporary tables so we
can re-use them on slave start.
TODO: move the vars below under Master_info
*/
int disconnect_slave_event_count = 0, abort_slave_event_count = 0;
static thread_local Master_info *RPL_MASTER_INFO = nullptr;
/**
Encapsulates the messages and thread stages used for a specific call
to try_to_reconnect. Different Reconnect_messages objects may be
used by the caller of try_to_reconnect in order to make the errors
and stages include text that describes the reason for the reconnect.
*/
struct Reconnect_messages {
/// Stage used while waiting to reconnect
PSI_stage_info &stage_waiting_to_reconnect;
/// Error reported in case the thread is killed while waiting
std::string error_killed_while_waiting;
/// Stage used while reconnecting
PSI_stage_info &stage_reconnecting;
/// Description of the condition that caused the thread to reconnect
std::string triggering_error;
/**
The string representation of the enum_server_command that had been
sent to the source before condition that caused the thread to
reconnect happened.
*/
std::string triggering_command;
};
static Reconnect_messages reconnect_messages_after_failed_registration{
stage_replica_waiting_to_reconnect_after_failed_registration_on_source,
"Replica I/O thread killed while waiting to reconnect after a failed "
"registration on source",
stage_replica_reconnecting_after_failed_registration_on_source,
"failed registering on source, reconnecting to try again, "
"log '%s' at position %s",
"COM_REGISTER_REPLICA"};
static Reconnect_messages reconnect_messages_after_failed_dump{
stage_replica_waiting_to_reconnect_after_failed_binlog_dump_request,
"Replica I/O thread killed while retrying source dump",
stage_replica_reconnecting_after_failed_binlog_dump_request,
"failed dump request, reconnecting to try again, log '%s' at position "
"%s",
"COM_BINLOG_DUMP"};
static Reconnect_messages reconnect_messages_after_failed_event_read{
stage_replica_waiting_to_reconnect_after_failed_event_read,
"Replica I/O thread killed while waiting to reconnect after a failed read",
stage_replica_reconnecting_after_failed_event_read,
"Replica I/O thread: Failed reading log event, reconnecting to retry, "
"log '%s' at position %s",
""};
enum enum_slave_apply_event_and_update_pos_retval {
SLAVE_APPLY_EVENT_AND_UPDATE_POS_OK = 0,
SLAVE_APPLY_EVENT_AND_UPDATE_POS_APPLY_ERROR = 1,
SLAVE_APPLY_EVENT_AND_UPDATE_POS_UPDATE_POS_ERROR = 2,
SLAVE_APPLY_EVENT_AND_UPDATE_POS_APPEND_JOB_ERROR = 3,
SLAVE_APPLY_EVENT_RETRY = 4,
SLAVE_APPLY_EVENT_UNTIL_REACHED = 5,
SLAVE_APPLY_EVENT_AND_UPDATE_POS_MAX
};
static int process_io_rotate(Master_info *mi, Rotate_log_event *rev);
/// @brief Checks whether relay log space will be exceeded after queueing
/// additional 'queued_size' bytes. If yes, function will
/// request relay log purge, rotate the relay log and wait for notification
/// from coordinator
/// @retval true Event may be queued by the receiver
/// @retval false Failed to reclaim required relay log space
static inline bool wait_for_relay_log_space(Relay_log_info *rli,
std::size_t queued_size);
/// @brief Checks whether relay log space limit will be exceeded after queueing
/// additional 'queued_size' bytes
/// @param rli Pointer to connection metadata object for the considered channel
/// @param queued_size Number of bytes we want to queue
/// @retval true Limit exceeded
/// @retval false Current size + 'queued_size' is within limits
static inline bool exceeds_relay_log_limit(Relay_log_info *rli,
std::size_t queued_size);
static inline bool io_slave_killed(THD *thd, Master_info *mi);
static inline bool monitor_io_replica_killed(THD *thd, Master_info *mi);
static inline bool is_autocommit_off_and_infotables(THD *thd);
static void print_replica_skip_errors(void);
static int safe_connect(THD *thd, MYSQL *mysql, Master_info *mi,
const std::string &host = std::string(),
const uint port = 0);
static int safe_reconnect(THD *thd, MYSQL *mysql, Master_info *mi,
bool suppress_warnings,
const std::string &host = std::string(),
const uint port = 0);
static int get_master_version_and_clock(MYSQL *mysql, Master_info *mi);
static int get_master_uuid(MYSQL *mysql, Master_info *mi);
int io_thread_init_commands(MYSQL *mysql, Master_info *mi);
static int terminate_slave_thread(THD *thd, mysql_mutex_t *term_lock,
mysql_cond_t *term_cond,
std::atomic<uint> *slave_running,
ulong *stop_wait_timeout, bool need_lock_term,
bool force = false);
static bool check_io_slave_killed(THD *thd, Master_info *mi, const char *info);
static int mts_event_coord_cmp(LOG_POS_COORD *id1, LOG_POS_COORD *id2);
static int check_slave_sql_config_conflict(const Relay_log_info *rli);
static void group_replication_cleanup_after_clone();
static void check_replica_configuration_restrictions();
static bool check_replica_configuration_errors(Master_info *mi,
int thread_mask);
/*
Applier thread InnoDB priority.
When two transactions conflict inside InnoDB, the one with
greater priority wins.
@param thd Thread handler for slave
@param priority Thread priority
*/
static void set_thd_tx_priority(THD *thd, int priority) {
DBUG_TRACE;
assert(thd->system_thread == SYSTEM_THREAD_SLAVE_SQL ||
thd->system_thread == SYSTEM_THREAD_SLAVE_WORKER);
thd->thd_tx_priority = priority;
DBUG_EXECUTE_IF("dbug_set_high_prio_sql_thread",
{ thd->thd_tx_priority = 1; });
}
/**
Set for the thread options about the memory and size limits when
transactions collect write sets.
@param thd Thread handler
@param ignore_limit if the memory limits should be ignored
@param allow_drop_write_set if this thread does not require WS to always be
logged
*/
static void set_thd_write_set_options(THD *thd, bool ignore_limit,
bool allow_drop_write_set) {
DBUG_TRACE;
thd->get_transaction()
->get_transaction_write_set_ctx()
->set_local_ignore_write_set_memory_limit(ignore_limit);
thd->get_transaction()
->get_transaction_write_set_ctx()
->set_local_allow_drop_write_set(allow_drop_write_set);
}
/*
Function to set the slave's max_allowed_packet based on the value
of replica_max_allowed_packet.
@in_param thd Thread handler for slave
@in_param mysql MySQL connection handle
*/
static void set_replica_max_allowed_packet(THD *thd, MYSQL *mysql) {
DBUG_TRACE;
// thd and mysql must be valid
assert(thd && mysql);
thd->variables.max_allowed_packet = replica_max_allowed_packet;
/*
Adding MAX_LOG_EVENT_HEADER_LEN to the max_packet_size on the I/O
thread and the mysql->option max_allowed_packet, since a
replication event can become this much larger than
the corresponding packet (query) sent from client to master.
*/
thd->get_protocol_classic()->set_max_packet_size(replica_max_allowed_packet +
MAX_LOG_EVENT_HEADER);
/*
Skipping the setting of mysql->net.max_packet size to slave
max_allowed_packet since this is done during mysql_real_connect.
*/
mysql->options.max_allowed_packet =
replica_max_allowed_packet + MAX_LOG_EVENT_HEADER;
}
#ifdef HAVE_PSI_INTERFACE
static PSI_memory_key key_memory_rli_mta_coor;
static PSI_thread_key key_thread_replica_io, key_thread_replica_sql,
key_thread_replica_worker, key_thread_replica_monitor_io;
static PSI_thread_info all_slave_threads[] = {
{&key_thread_replica_io, "replica_io", "rpl_rca_io", PSI_FLAG_THREAD_SYSTEM,
0, PSI_DOCUMENT_ME},
{&key_thread_replica_sql, "replica_sql", "rpl_rca_sql",
PSI_FLAG_THREAD_SYSTEM, 0, PSI_DOCUMENT_ME},
{&key_thread_replica_worker, "replica_worker", "rpl_rca_wkr",
PSI_FLAG_THREAD_SYSTEM, 0, PSI_DOCUMENT_ME},
{&key_thread_replica_monitor_io, "replica_monitor", "rpl_rca_mon",
PSI_FLAG_SINGLETON | PSI_FLAG_THREAD_SYSTEM, 0, PSI_DOCUMENT_ME}};
static PSI_memory_info all_slave_memory[] = {{&key_memory_rli_mta_coor,
"Relay_log_info::mta_coor", 0, 0,
PSI_DOCUMENT_ME}};
#endif /* HAVE_PSI_INTERFACE */
/* Initialize slave structures */
int ReplicaInitializer::get_initialization_code() const { return m_init_code; }
ReplicaInitializer::ReplicaInitializer(bool opt_initialize,
bool opt_skip_replica_start,
Rpl_channel_filters &filters,
char **replica_skip_erors)
: m_opt_initialize_replica(!opt_initialize),
m_opt_skip_replica_start(opt_initialize),
m_thread_mask(SLAVE_SQL | SLAVE_IO) {
if (m_opt_initialize_replica) {
// Make @@replica_skip_errors show the nice human-readable value.
set_replica_skip_errors(replica_skip_erors);
/*
Group replication filters should be discarded before init_replica(),
otherwise the pre-configured filters will be referenced by group
replication channels.
*/
filters.discard_group_replication_filters();
/*
init_replica() must be called after the thread keys are created.
*/
if (server_id != 0) {
m_init_code = init_replica();
}
start_replication_threads(opt_skip_replica_start);
/*
If the user specifies a per-channel replication filter through a
command-line option (or in a configuration file) for a slave
replication channel which does not exist as of now (i.e not
present in slave info tables yet), then the per-channel
replication filter is discarded with a warning.
If the user specifies a per-channel replication filter through
a command-line option (or in a configuration file) for group
replication channels 'group_replication_recovery' and
'group_replication_applier' which is disallowed, then the
per-channel replication filter is discarded with a warning.
*/
filters.discard_all_unattached_filters();
}
}
void ReplicaInitializer::print_channel_info() const {
#ifndef NDEBUG
/* @todo: Print it for all the channels */
{
Master_info *default_mi;
default_mi = channel_map.get_default_channel_mi();
if (default_mi && default_mi->rli) {
DBUG_PRINT(
"info",
("init group source %s %lu group replica %s %lu event %s %lu\n",
default_mi->rli->get_group_master_log_name(),
(ulong)default_mi->rli->get_group_master_log_pos(),
default_mi->rli->get_group_relay_log_name(),
(ulong)default_mi->rli->get_group_relay_log_pos(),
default_mi->rli->get_event_relay_log_name(),
(ulong)default_mi->rli->get_event_relay_log_pos()));
}
}
#endif
}
void ReplicaInitializer::start_replication_threads(bool skip_replica_start) {
if (!m_opt_skip_replica_start && !skip_replica_start) {
start_threads();
}
}
void ReplicaInitializer::start_threads() {
/*
Loop through the channel_map and start slave threads for each channel.
*/
for (mi_map::iterator it = channel_map.begin(); it != channel_map.end();
it++) {
Master_info *mi = it->second;
/* If server id is not set, start_slave_thread() will say it */
if (Master_info::is_configured(mi) && mi->rli->inited) {
/* same as in start_slave() cache the global var values into rli's
* members */
mi->rli->opt_replica_parallel_workers = opt_mts_replica_parallel_workers;
mi->rli->checkpoint_group = opt_mta_checkpoint_group;
if (mts_parallel_option == MTS_PARALLEL_TYPE_DB_NAME)
mi->rli->channel_mts_submode = MTS_PARALLEL_TYPE_DB_NAME;
else
mi->rli->channel_mts_submode = MTS_PARALLEL_TYPE_LOGICAL_CLOCK;
if (mi->is_source_connection_auto_failover())
m_thread_mask |= SLAVE_MONITOR;
if (start_slave_threads(true /*need_lock_slave=true*/,
false /*wait_for_start=false*/, mi,
m_thread_mask)) {
LogErr(ERROR_LEVEL, ER_FAILED_TO_START_REPLICA_THREAD,
mi->get_channel());
}
} else {
LogErr(INFORMATION_LEVEL, ER_FAILED_TO_START_REPLICA_THREAD,
mi->get_channel());
}
}
}
void ReplicaInitializer::init_replica_psi_keys() {
#ifdef HAVE_PSI_INTERFACE
const char *category = "sql";
int count;
count = static_cast<int>(array_elements(all_slave_threads));
mysql_thread_register(category, all_slave_threads, count);
count = static_cast<int>(array_elements(all_slave_memory));
mysql_memory_register(category, all_slave_memory, count);
#endif // HAVE_PSI_INTERFACE
}
int ReplicaInitializer::init_replica() {
DBUG_TRACE;
int error = 0;
#ifdef HAVE_PSI_INTERFACE
init_replica_psi_keys();
#endif
/*
This is called when mysqld starts. Before client connections are
accepted. However bootstrap may conflict with us if it does START SLAVE.
So it's safer to take the lock.
*/
channel_map.wrlock();
Scope_guard channel_map_guard([&error]() {
channel_map.unlock();
if (error)
LogErr(INFORMATION_LEVEL, ER_REPLICA_NOT_STARTED_ON_SOME_CHANNELS);
});
RPL_MASTER_INFO = nullptr;
/*
Create slave info objects by reading repositories of individual
channels and add them into channel_map
*/
if ((error = Rpl_info_factory::create_slave_info_objects(
opt_mi_repository_id, opt_rli_repository_id, m_thread_mask,
&channel_map)))
LogErr(ERROR_LEVEL,
ER_RPL_REPLICA_FAILED_TO_CREATE_OR_RECOVER_INFO_REPOSITORIES);
group_replication_cleanup_after_clone();
print_channel_info();
check_replica_configuration_restrictions();
if (check_slave_sql_config_conflict(nullptr)) {
error = 1;
return error;
}
return error;
}
/**
Function to start a slave for all channels.
Used in Multisource replication.
@param[in] thd THD object of the client.
@retval false success
@retval true error
@todo It is good to continue to start other channels
when a slave start failed for other channels.
@todo The problem with the below code is if the slave is already
stared, we would have multiple warnings
"Replica was already running" for each channel.
A nice warning message would be to add
"Replica for channel '%s' was already running"
but error messages are in different languages and cannot be tampered
with so, we have to handle it case by case basis, whether
only default channel exists or not and properly continue with
starting other channels if one channel fails clearly giving
an error message by displaying failed channels.
*/
bool start_slave(THD *thd) {
DBUG_TRACE;
Master_info *mi;
bool channel_configured, error = false;
if (channel_map.get_num_instances() == 1) {
mi = channel_map.get_default_channel_mi();
assert(mi);
if (start_slave(thd, &thd->lex->slave_connection, &thd->lex->mi,
thd->lex->slave_thd_opt, mi, true))
return true;
} else {
/*
Users cannot start more than one channel's applier thread
if sql_replica_skip_counter > 0. It throws an error to the session.
*/
mysql_mutex_lock(&LOCK_sql_replica_skip_counter);
/* sql_replica_skip_counter > 0 && !(START SLAVE IO_THREAD) */
if (sql_replica_skip_counter > 0 && !(thd->lex->slave_thd_opt & SLAVE_IO)) {
my_error(ER_REPLICA_CHANNEL_SQL_SKIP_COUNTER, MYF(0));
mysql_mutex_unlock(&LOCK_sql_replica_skip_counter);
return true;
}
mysql_mutex_unlock(&LOCK_sql_replica_skip_counter);
for (mi_map::iterator it = channel_map.begin(); it != channel_map.end();
it++) {
mi = it->second;
channel_configured =
mi && // Master_info exists
(mi->inited || mi->reset) // It is inited or was reset
&& mi->host[0]; // host is set
if (channel_configured) {
if (start_slave(thd, &thd->lex->slave_connection, &thd->lex->mi,
thd->lex->slave_thd_opt, mi, true)) {
LogErr(ERROR_LEVEL, ER_RPL_REPLICA_CANT_START_REPLICA_FOR_CHANNEL,
mi->get_channel());
error = true;
}
}
}
}
if (!error) {
/* no error */
my_ok(thd);
}
return error;
}
/**
Function to stop a slave for all channels.
Used in Multisource replication.
@param[in] thd THD object of the client.
@retval 0 success
@retval 1 error
@todo It is good to continue to stop other channels
when a slave start failed for other channels.
*/
int stop_slave(THD *thd) {
DBUG_TRACE;
bool push_temp_table_warning = true;
Master_info *mi = nullptr;
int error = 0;
if (channel_map.get_num_instances() == 1) {
mi = channel_map.get_default_channel_mi();
assert(!strcmp(mi->get_channel(), channel_map.get_default_channel()));
error = stop_slave(thd, mi, true, false /*for_one_channel*/,
&push_temp_table_warning);
} else {
for (mi_map::iterator it = channel_map.begin(); it != channel_map.end();
it++) {
mi = it->second;
if (Master_info::is_configured(mi)) {
if (stop_slave(thd, mi, true, false /*for_one_channel*/,
&push_temp_table_warning)) {
LogErr(ERROR_LEVEL, ER_RPL_REPLICA_CANT_STOP_REPLICA_FOR_CHANNEL,
mi->get_channel());
error = 1;
}
}
}
}
if (!error) {
/* no error */
my_ok(thd);
}
return error;
}
/**
Entry point to the START SLAVE command. The function
decides to start replication threads on several channels
or a single given channel.
@param[in] thd the client thread carrying the command.
@retval false ok
@retval true not ok.
*/
bool start_slave_cmd(THD *thd) {
DBUG_TRACE;
Master_info *mi;
LEX *lex = thd->lex;
bool res = true; /* default, an error */
DEBUG_SYNC(thd, "begin_start_replica");
channel_map.wrlock();
DEBUG_SYNC(thd, "after_locking_channel_map_in_start_replica");
if (!is_slave_configured()) {
my_error(ER_REPLICA_CONFIGURATION, MYF(0));
goto err;
}
if (!lex->mi.for_channel) {
/*
If slave_until options are provided when multiple channels exist
without explicitly providing FOR CHANNEL clause, error out.
*/
if (lex->mi.slave_until && channel_map.get_num_instances() > 1) {
my_error(ER_REPLICA_MULTIPLE_CHANNELS_CMD, MYF(0));
goto err;
}
res = start_slave(thd);
} else {
mi = channel_map.get_mi(lex->mi.channel);
/*
If the channel being used is a group replication channel we need to
disable this command here as, in some cases, group replication does not
support them.
For channel group_replication_applier we disable START SLAVE [IO_THREAD]
command.
For channel group_replication_recovery we disable START SLAVE command
and its two thread variants.
*/
if (mi &&
channel_map.is_group_replication_channel_name(mi->get_channel()) &&
((!thd->lex->slave_thd_opt || (thd->lex->slave_thd_opt & SLAVE_IO)) ||
(!(channel_map.is_group_replication_channel_name(mi->get_channel(),
true)) &&
(thd->lex->slave_thd_opt & SLAVE_SQL)))) {
const char *command = "START REPLICA FOR CHANNEL";
if (thd->lex->slave_thd_opt & SLAVE_IO)
command = "START REPLICA IO_THREAD FOR CHANNEL";
else if (thd->lex->slave_thd_opt & SLAVE_SQL)
command = "START REPLICA SQL_THREAD FOR CHANNEL";
my_error(ER_REPLICA_CHANNEL_OPERATION_NOT_ALLOWED, MYF(0), command,
mi->get_channel());
goto err;
}
/*
START SLAVE for channel group_replication_applier is disallowed while
Group Replication is running.
*/
if (mi &&
channel_map.is_group_replication_channel_name(mi->get_channel(),
true) &&
is_group_replication_running()) {
const char *command =
"START REPLICA FOR CHANNEL while Group Replication is running";
my_error(ER_REPLICA_CHANNEL_OPERATION_NOT_ALLOWED, MYF(0), command,
mi->get_channel());
goto err;
}
if (mi)
res = start_slave(thd, &thd->lex->slave_connection, &thd->lex->mi,
thd->lex->slave_thd_opt, mi, true);
else if (strcmp(channel_map.get_default_channel(), lex->mi.channel))
my_error(ER_REPLICA_CHANNEL_DOES_NOT_EXIST, MYF(0), lex->mi.channel);
if (!res) my_ok(thd);
}
err:
channel_map.unlock();
return res;
}
/**
Entry point for the STOP SLAVE command. This function stops replication
threads for all channels or a single channel based on the command
options supplied.
@param[in] thd the client thread.
@retval false ok
@retval true not ok.
*/
bool stop_slave_cmd(THD *thd) {
DBUG_TRACE;
Master_info *mi;
bool push_temp_table_warning = true;
LEX *lex = thd->lex;
bool res = true; /*default, an error */
channel_map.rdlock();
if (!is_slave_configured()) {
my_error(ER_REPLICA_CONFIGURATION, MYF(0));
channel_map.unlock();
return true;
}
MDL_lock_guard backup_sentry{thd};
/* During provisioning we stop slave after acquiring backup lock. */
if (!Clone_handler::is_provisioning() &&
(!thd->lex->slave_thd_opt || (thd->lex->slave_thd_opt & SLAVE_SQL))) {
if (backup_sentry.lock(MDL_key::BACKUP_LOCK, MDL_INTENTION_EXCLUSIVE)) {
my_error(ER_RPL_CANT_STOP_REPLICA_WHILE_LOCKED_BACKUP, MYF(0));
channel_map.unlock();
return true;
}
}
if (!lex->mi.for_channel)
res = stop_slave(thd);
else {
mi = channel_map.get_mi(lex->mi.channel);
/*
If the channel being used is a group replication channel we need to
disable this command here as, in some cases, group replication does not
support them.
For channel group_replication_applier we disable STOP SLAVE [IO_THREAD]
command.
For channel group_replication_recovery we disable STOP SLAVE command
and its two thread variants.
*/
if (mi &&
channel_map.is_group_replication_channel_name(mi->get_channel()) &&
((!thd->lex->slave_thd_opt || (thd->lex->slave_thd_opt & SLAVE_IO)) ||
(!(channel_map.is_group_replication_channel_name(mi->get_channel(),
true)) &&
(thd->lex->slave_thd_opt & SLAVE_SQL)))) {
const char *command = "STOP REPLICA FOR CHANNEL";
if (thd->lex->slave_thd_opt & SLAVE_IO)
command = "STOP REPLICA IO_THREAD FOR CHANNEL";
else if (thd->lex->slave_thd_opt & SLAVE_SQL)
command = "STOP REPLICA SQL_THREAD FOR CHANNEL";
my_error(ER_REPLICA_CHANNEL_OPERATION_NOT_ALLOWED, MYF(0), command,
mi->get_channel());
channel_map.unlock();
return true;
}
/*
STOP SLAVE for channel group_replication_applier is disallowed while
Group Replication is running.
*/
if (mi &&
channel_map.is_group_replication_channel_name(mi->get_channel(),
true) &&
is_group_replication_running()) {
const char *command =
"STOP REPLICA FOR CHANNEL while Group Replication is running";
my_error(ER_REPLICA_CHANNEL_OPERATION_NOT_ALLOWED, MYF(0), command,
mi->get_channel());
channel_map.unlock();
return true;
}
if (mi)
res = stop_slave(thd, mi, true /*net report */, true /*for_one_channel*/,
&push_temp_table_warning);
else if (strcmp(channel_map.get_default_channel(), lex->mi.channel))
my_error(ER_REPLICA_CHANNEL_DOES_NOT_EXIST, MYF(0), lex->mi.channel);
}
channel_map.unlock();
DBUG_EXECUTE_IF("stop_replica_dont_release_backup_lock", {
rpl_replica_debug_point(DBUG_RPL_S_STOP_SLAVE_BACKUP_LOCK, thd);
});
return res;
}
enum enum_read_rotate_from_relay_log_status {
FOUND_ROTATE,
NOT_FOUND_ROTATE,
ERROR
};
/**
Parse the given relay log and identify the rotate event from the master.
Ignore the Format description event, Previous_gtid log event, ignorable
event and Stop event within the relay log as they are generated by slave.
When a rotate event is found check if it is a rotate that is originated from
the master based on the server_id. Ignore the event if the rotate is from
slave or if it is a fake rotate event. If any other events are encountered
apart from the above events generate an error. From the rotate event
extract the master's binary log name and position.
@param filename
Relay log name which needs to be parsed.
@param[out] master_log_file
Set the master_log_file to the log file name that is extracted from
rotate event. The master_log_file should contain string of len
FN_REFLEN.
@param[out] master_log_pos
Set the master_log_pos to the log position extracted from rotate
event.
@retval FOUND_ROTATE: When rotate event is found in the relay log
@retval NOT_FOUND_ROTATE: When rotate event is not found in the relay log
@retval ERROR: On error
*/
static enum_read_rotate_from_relay_log_status read_rotate_from_relay_log(
char *filename, char *master_log_file, my_off_t *master_log_pos) {
DBUG_TRACE;
Relaylog_file_reader relaylog_file_reader(opt_replica_sql_verify_checksum);
if (relaylog_file_reader.open(filename)) {
LogErr(ERROR_LEVEL, ER_RPL_RECOVERY_ERROR,
relaylog_file_reader.get_error_str());
return ERROR;
}
Log_event *ev = nullptr;
bool done = false;
enum_read_rotate_from_relay_log_status ret = NOT_FOUND_ROTATE;
while (!done && (ev = relaylog_file_reader.read_event_object()) != nullptr) {
DBUG_PRINT("info", ("Read event of type %s", ev->get_type_str()));
switch (ev->get_type_code()) {
case binary_log::FORMAT_DESCRIPTION_EVENT:
break;
case binary_log::ROTATE_EVENT:
/*
Check for rotate event from the master. Ignore the ROTATE event if it
is a fake rotate event with server_id=0.
*/
if (ev->server_id && ev->server_id != ::server_id) {
Rotate_log_event *rotate_ev = (Rotate_log_event *)ev;
assert(FN_REFLEN >= rotate_ev->ident_len + 1);
memcpy(master_log_file, rotate_ev->new_log_ident,
rotate_ev->ident_len + 1);
*master_log_pos = rotate_ev->pos;
ret = FOUND_ROTATE;
done = true;
}
break;
case binary_log::PREVIOUS_GTIDS_LOG_EVENT:
break;
case binary_log::IGNORABLE_LOG_EVENT:
break;
case binary_log::STOP_EVENT:
break;
default:
LogErr(ERROR_LEVEL, ER_RPL_RECOVERY_NO_ROTATE_EVENT_FROM_SOURCE);
ret = ERROR;
done = true;
break;
}
delete ev;
}
if (relaylog_file_reader.has_fatal_error()) {
LogErr(ERROR_LEVEL, ER_RPL_RECOVERY_ERROR_READ_RELAY_LOG, -1);
return ERROR;
}
return ret;
}
/**
Reads relay logs one by one starting from the first relay log. Looks for
the first rotate event from the master. If rotate is not found in the relay
log search continues to next relay log. If rotate event from master is
found then the extracted master_log_file and master_log_pos are used to set
rli->group_master_log_name and rli->group_master_log_pos. If an error has
occurred the error code is returned back.
@param rli
Relay_log_info object to read relay log files and to set
group_master_log_name and group_master_log_pos.
@retval 0 Success - Rotate event was found
@retval 1 Failure - Found some events replicated but no rotate event was
found
@retval 2 When no rotate event from master was found. This can happen when
slave server was restarted immediately after executing CHANGE
MASTER
*/
static int find_first_relay_log_with_rotate_from_master(Relay_log_info *rli) {
DBUG_TRACE;
int error = 0;
LOG_INFO linfo;
bool got_rotate_from_master = false;
int pos;
char master_log_file[FN_REFLEN];
my_off_t master_log_pos = 0;
if (channel_map.is_group_replication_channel_name(rli->get_channel())) {
LogErr(INFORMATION_LEVEL,
ER_RPL_RECOVERY_SKIPPED_GROUP_REPLICATION_CHANNEL);
goto err;
}
for (pos = rli->relay_log.find_log_pos(&linfo, nullptr, true); !pos;
pos = rli->relay_log.find_next_log(&linfo, true)) {
switch (read_rotate_from_relay_log(linfo.log_file_name, master_log_file,
&master_log_pos)) {
case ERROR:
error = 1;
break;
case FOUND_ROTATE:
got_rotate_from_master = true;
break;
case NOT_FOUND_ROTATE:
break;
}
if (error || got_rotate_from_master) break;
}
if (pos == LOG_INFO_IO) {
error = 1;
LogErr(ERROR_LEVEL, ER_RPL_RECOVERY_IO_ERROR_READING_RELAY_LOG_INDEX);
goto err;
}
if (pos == LOG_INFO_EOF) {
error = 2;
LogErr(WARNING_LEVEL, ER_RPL_RECOVERY_NO_ROTATE_EVENT_FROM_SOURCE);
LogErr(WARNING_LEVEL, ER_WARN_RPL_RECOVERY_NO_ROTATE_EVENT_FROM_SOURCE_EOF,
rli->mi->get_channel());
goto err;
}
if (!error && got_rotate_from_master) {
rli->set_group_master_log_name(master_log_file);
rli->set_group_master_log_pos(master_log_pos);
}
err:
return error;
}
/*
Updates the master info based on the information stored in the
relay info and ignores relay logs previously retrieved by the IO
thread, which thus starts fetching again based on to the
master_log_pos and master_log_name. Eventually, the old
relay logs will be purged by the normal purge mechanism.
When GTID's are enabled the "Retrieved GTID" set should be cleared
so that partial read events are discarded and they are
fetched once again
@param mi pointer to Master_info instance
*/
static void recover_relay_log(Master_info *mi) {
Relay_log_info *rli = mi->rli;
// If GTID ONLY is enable the receiver doesn't care about these positions
if (!mi->is_gtid_only_mode()) {
// Set Receiver Thread's positions as per the recovered Applier Thread.
mi->set_master_log_pos(std::max<ulonglong>(
BIN_LOG_HEADER_SIZE, rli->get_group_master_log_pos()));
mi->set_master_log_name(rli->get_group_master_log_name());
LogErr(WARNING_LEVEL, ER_RPL_RECOVERY_FILE_SOURCE_POS_INFO,
(ulong)mi->get_master_log_pos(), mi->get_master_log_name(),
mi->get_for_channel_str(), rli->get_group_relay_log_pos(),
rli->get_group_relay_log_name());
} else {
LogErr(WARNING_LEVEL, ER_RPL_RELAY_LOG_RECOVERY_GTID_ONLY);
}
// Start with a fresh relay log.
rli->set_group_relay_log_name(rli->relay_log.get_log_fname());
rli->set_group_relay_log_pos(BIN_LOG_HEADER_SIZE);
/*
Clear the retrieved GTID set so that events that are written partially
will be fetched again.
*/
if (global_gtid_mode.get() == Gtid_mode::ON &&
!channel_map.is_group_replication_channel_name(rli->get_channel())) {
rli->get_sid_lock()->wrlock();
(const_cast<Gtid_set *>(rli->get_gtid_set()))->clear_set_and_sid_map();
rli->get_sid_lock()->unlock();
}
}
/*
Updates the master info based on the information stored in the
relay info and ignores relay logs previously retrieved by the IO
thread, which thus starts fetching again based on to the
master_log_pos and master_log_name. Eventually, the old
relay logs will be purged by the normal purge mechanism.
There can be a special case where rli->group_master_log_name and
rli->group_master_log_pos are not initialized, as the sql thread was never
started at all. In those cases all the existing relay logs are parsed
starting from the first one and the initial rotate event that was received
from the master is identified. From the rotate event master_log_name and
master_log_pos are extracted and they are set to rli->group_master_log_name
and rli->group_master_log_pos.
In the feature, we should improve this routine in order to avoid throwing
away logs that are safely stored in the disk. Note also that this recovery
routine relies on the correctness of the relay-log.info and only tolerates
coordinate problems in master.info.
In this function, there is no need for a mutex as the caller
(i.e. init_replica) already has one acquired.
Specifically, the following structures are updated:
1 - mi->master_log_pos <-- rli->group_master_log_pos
2 - mi->master_log_name <-- rli->group_master_log_name
3 - It moves the relay log to the new relay log file, by
rli->group_relay_log_pos <-- BIN_LOG_HEADER_SIZE;
rli->event_relay_log_pos <-- BIN_LOG_HEADER_SIZE;
rli->group_relay_log_name <-- rli->relay_log.get_log_fname();
rli->event_relay_log_name <-- rli->relay_log.get_log_fname();
If there is an error, it returns (1), otherwise returns (0).
*/
int init_recovery(Master_info *mi) {
DBUG_TRACE;
int error = 0;
Relay_log_info *rli = mi->rli;
char *group_master_log_name = nullptr;
/*
This is not idempotent and a crash after this function and before
the recovery is actually done may lead the system to an inconsistent
state.
This may happen because the gap is not persitent stored anywhere
and eventually old relay log files will be removed and further
calculations on the gaps will be impossible.
We need to improve this. /Alfranio.
*/
error = mts_recovery_groups(rli);
if (rli->mts_recovery_group_cnt) return error;
group_master_log_name = const_cast<char *>(rli->get_group_master_log_name());
if (!error) {
bool run_relay_log_recovery = true;
if (!group_master_log_name[0] && !rli->mi->is_gtid_only_mode()) {
if (rli->replicate_same_server_id) {
error = 1;
LogErr(ERROR_LEVEL,
ER_RPL_RECOVERY_REPLICATE_SAME_SERVER_ID_REQUIRES_POSITION);
return error;
}
error = find_first_relay_log_with_rotate_from_master(rli);
if (error == 2) {
// No events from the master on relay log - skip relay log recovery
run_relay_log_recovery = false;
error = 0;
} else if (error)
return error;
}
if (run_relay_log_recovery) recover_relay_log(mi);
}
return error;
}
/*
Relay log recovery in the case of MTS, is handled by the following function.
Gaps in MTS execution are filled using implicit execution of
START SLAVE UNTIL SQL_AFTER_MTS_GAPS call. Once slave reaches a consistent
gapless state receiver thread's positions are initialized to applier thread's
positions and the old relay logs are discarded. This completes the recovery
process.
@param mi pointer to Master_info instance.
@retval 0 success
@retval 1 error
*/
static inline int fill_mts_gaps_and_recover(Master_info *mi) {
DBUG_TRACE;
Relay_log_info *rli = mi->rli;
int recovery_error = 0;
rli->is_relay_log_recovery = false;
Until_mts_gap *until_mg = new Until_mts_gap(rli);
rli->set_until_option(until_mg);
rli->until_condition = Relay_log_info::UNTIL_SQL_AFTER_MTS_GAPS;
until_mg->init();
rli->channel_mts_submode = (mts_parallel_option == MTS_PARALLEL_TYPE_DB_NAME)
? MTS_PARALLEL_TYPE_DB_NAME
: MTS_PARALLEL_TYPE_LOGICAL_CLOCK;
LogErr(INFORMATION_LEVEL, ER_RPL_MTA_RECOVERY_STARTING_COORDINATOR);
recovery_error = start_slave_thread(
key_thread_replica_sql, handle_slave_sql, &rli->run_lock, &rli->run_lock,
&rli->start_cond, &rli->slave_running, &rli->slave_run_id, mi);
if (recovery_error) {
LogErr(WARNING_LEVEL, ER_RPL_MTA_RECOVERY_FAILED_TO_START_COORDINATOR);
goto err;
}
mysql_mutex_lock(&rli->run_lock);
mysql_cond_wait(&rli->stop_cond, &rli->run_lock);
mysql_mutex_unlock(&rli->run_lock);
if (rli->until_condition != Relay_log_info::UNTIL_DONE) {
LogErr(WARNING_LEVEL, ER_RPL_MTA_AUTOMATIC_RECOVERY_FAILED);
goto err;
}
rli->clear_until_option();
/*
We need a mutex while we are changing master info parameters to
keep other threads from reading bogus info
*/
mysql_mutex_lock(&mi->data_lock);
mysql_mutex_lock(&rli->data_lock);
recover_relay_log(mi);
if (mi->flush_info(true) ||
rli->flush_info(Relay_log_info::RLI_FLUSH_IGNORE_SYNC_OPT)) {
recovery_error = 1;
mysql_mutex_unlock(&mi->data_lock);
mysql_mutex_unlock(&rli->data_lock);
goto err;
}
rli->inited = true;
rli->error_on_rli_init_info = false;
mysql_mutex_unlock(&mi->data_lock);
mysql_mutex_unlock(&rli->data_lock);
LogErr(INFORMATION_LEVEL, ER_RPL_MTA_RECOVERY_SUCCESSFUL);
return recovery_error;
err:
/*
If recovery failed means we failed to initialize rli object in the case
of MTS. We should not allow the START SLAVE command to work as we do in
the case of STS. i.e if init_recovery call fails then we set inited=0.
*/
rli->end_info();
rli->inited = false;
rli->error_on_rli_init_info = true;
rli->clear_until_option();
return recovery_error;
}
int load_mi_and_rli_from_repositories(Master_info *mi, bool ignore_if_no_info,
int thread_mask,
bool skip_received_gtid_set_recovery,
bool force_load) {
DBUG_TRACE;
assert(mi != nullptr && mi->rli != nullptr);
int init_error = 0;
enum_return_check check_return = ERROR_CHECKING_REPOSITORY;
THD *thd = current_thd;
/*
We need a mutex while we are changing master info parameters to
keep other threads from reading bogus info
*/
mysql_mutex_lock(&mi->data_lock);
mysql_mutex_lock(&mi->rli->data_lock);
/*
When info tables are used and autocommit= 0 we force a new
transaction start to avoid table access deadlocks when START SLAVE
is executed after RESET SLAVE.
*/
if (is_autocommit_off_and_infotables(thd)) {
if (trans_begin(thd)) {
init_error = 1;
goto end;
}
}
/*
This takes care of the startup dependency between the master_info
and relay_info. It initializes the master info if the SLAVE_IO
thread is being started and the relay log info if either the
SLAVE_SQL thread is being started or was not initialized as it is
required by the SLAVE_IO thread.
*/
check_return = mi->check_info();
if (check_return == ERROR_CHECKING_REPOSITORY) {
init_error = 1;
goto end;
}
if (!ignore_if_no_info || check_return != REPOSITORY_DOES_NOT_EXIST) {
if ((thread_mask & SLAVE_IO) != 0) {
if (!mi->inited || force_load) {
if (mi->mi_init_info()) {
init_error = 1;
}
}
}
}
check_return = mi->rli->check_info();
if (check_return == ERROR_CHECKING_REPOSITORY) {
init_error = 1;
goto end;
}
if (!ignore_if_no_info || check_return != REPOSITORY_DOES_NOT_EXIST) {
if ((thread_mask & SLAVE_SQL) != 0 || !(mi->rli->inited)) {
if (!mi->rli->inited || force_load) {
if (mi->rli->rli_init_info(skip_received_gtid_set_recovery)) {
init_error = 1;
} else {
/*
During rli_init_info() above, the relay log is opened (if rli was
not initialized yet). The function below expects the relay log to be
opened to get its coordinates and store as the last flushed relay
log coordinates from I/O thread point of view.
*/
mi->update_flushed_relay_log_info();
}
} else {
// Even if we skip rli_init_info we must check if gaps exist to maintain
// the server behavior in commands like CHANGE REPLICATION SOURCE
if (mi->rli->recovery_parallel_workers ? mts_recovery_groups(mi->rli)
: 0)
init_error = 1;
}
}
}
DBUG_EXECUTE_IF("enable_mta_worker_failure_init",
{ DBUG_SET("+d,mta_worker_thread_init_fails"); });
end:
/*
When info tables are used and autocommit= 0 we force transaction
commit to avoid table access deadlocks when START SLAVE is executed
after RESET SLAVE.
*/
if (is_autocommit_off_and_infotables(thd))
if (trans_commit(thd)) init_error = 1;
mysql_mutex_unlock(&mi->rli->data_lock);
mysql_mutex_unlock(&mi->data_lock);
/*
Handling MTS Relay-log recovery after successful initialization of mi and
rli objects.
MTS Relay-log recovery is handled by SSUG command. In order to start the
slave applier thread rli needs to be inited and mi->rli->data_lock should
be in released state. Hence we do the MTS recovery at this point of time
where both conditions are satisfied.
*/
if (!init_error && mi->rli->is_relay_log_recovery &&
mi->rli->mts_recovery_group_cnt)
init_error = fill_mts_gaps_and_recover(mi);
return init_error;
}
void end_info(Master_info *mi) {
DBUG_TRACE;
assert(mi != nullptr && mi->rli != nullptr);
/*
The previous implementation was not acquiring locks. We do the same here.
However, this is quite strange.
*/
mi->end_info();
mi->rli->end_info();
}
void clear_info(Master_info *mi) {
DBUG_TRACE;
assert(mi != nullptr && mi->rli != nullptr);
/*
Reset errors (the idea is that we forget about the
old master).
*/
mi->clear_error();
mi->rli->clear_error();
if (mi->rli->workers_array_initialized) {
for (size_t i = 0; i < mi->rli->get_worker_count(); i++) {
mi->rli->get_worker(i)->clear_error();
}
}
mi->rli->clear_sql_delay();
end_info(mi);
}
int remove_info(Master_info *mi) {
int error = 1;
DBUG_TRACE;
assert(mi != nullptr && mi->rli != nullptr);
/*
The previous implementation was not acquiring locks.
We do the same here. However, this is quite strange.
*/
clear_info(mi);
if (mi->remove_info() || Rpl_info_factory::reset_workers(mi->rli) ||
mi->rli->remove_info())
goto err;
error = 0;
err:
return error;
}
bool reset_info(Master_info *mi) {
DBUG_TRACE;
assert(mi != nullptr && mi->rli != nullptr);
clear_info(mi);
if (mi->remove_info() || Rpl_info_factory::reset_workers(mi->rli))
return true;
MUTEX_LOCK(mi_lock, &mi->data_lock);
MUTEX_LOCK(rli_lock, &mi->rli->data_lock);
mi->init_master_log_pos();
mi->master_uuid[0] = 0;
if (mi->reset && opt_mi_repository_id == INFO_REPOSITORY_TABLE &&
opt_rli_repository_id == INFO_REPOSITORY_TABLE && mi->flush_info(true)) {
my_error(ER_CONNECTION_METADATA, MYF(0));
return true;
}
bool have_relay_log_data_to_persist = // Only want to keep
(!mi->rli->is_privilege_checks_user_null() || // if PCU is not null
mi->rli->is_row_format_required() || // or RRF is 1
Relay_log_info::PK_CHECK_STREAM != // or RTPKC != STREAM
mi->rli->get_require_table_primary_key_check()) &&
opt_rli_repository_id == INFO_REPOSITORY_TABLE && // in TABLE repository.
opt_mi_repository_id == INFO_REPOSITORY_TABLE;
if ((have_relay_log_data_to_persist && mi->rli->clear_info()) ||
(!have_relay_log_data_to_persist && mi->rli->remove_info())) {
my_error(ER_CONNECTION_METADATA, MYF(0));
return true;
}
return false;
}
int flush_master_info(Master_info *mi, bool force, bool need_lock,
bool do_flush_relay_log, bool skip_repo_persistence) {
DBUG_TRACE;
assert(mi != nullptr && mi->rli != nullptr);
DBUG_EXECUTE_IF("fail_to_flush_source_info", { return 1; });
if (skip_repo_persistence && !do_flush_relay_log) {
return 0;
}
/*
With the appropriate recovery process, we will not need to flush
the content of the current log.
For now, we flush the relay log BEFORE the master.info file, because
if we crash, we will get a duplicate event in the relay log at restart.
If we change the order, there might be missing events.
If we don't do this and the slave server dies when the relay log has
some parts (its last kilobytes) in memory only, with, say, from master's
position 100 to 150 in memory only (not on disk), and with position 150
in master.info, there will be missing information. When the slave restarts,
the I/O thread will fetch binlogs from 150, so in the relay log we will
have "[0, 100] U [150, infinity[" and nobody will notice it, so the SQL
thread will jump from 100 to 150, and replication will silently break.
*/
mysql_mutex_t *log_lock = mi->rli->relay_log.get_log_lock();
mysql_mutex_t *data_lock = &mi->data_lock;
if (need_lock) {
mysql_mutex_lock(log_lock);
mysql_mutex_lock(data_lock);
} else {
mysql_mutex_assert_owner(log_lock);
mysql_mutex_assert_owner(&mi->data_lock);
}
int err = 0;
/*
We can skip flushing the relay log when this function is called from
queue_event(), as after_write_to_relay_log() will already flush it.
*/
if (do_flush_relay_log) err |= mi->rli->flush_current_log();
if (!skip_repo_persistence) err |= mi->flush_info(force);
if (need_lock) {
mysql_mutex_unlock(data_lock);
mysql_mutex_unlock(log_lock);
}
return err;
}
/**
Convert slave skip errors bitmap into a printable string.
*/
static void print_replica_skip_errors(void) {
/*
To be safe, we want 10 characters of room in the buffer for a number
plus terminators. Also, we need some space for constant strings.
10 characters must be sufficient for a number plus {',' | '...'}
plus a NUL terminator. That is a max 6 digit number.
*/
const size_t MIN_ROOM = 10;
DBUG_TRACE;
assert(sizeof(slave_skip_error_names) > MIN_ROOM);
assert(MAX_SLAVE_ERROR <= 999999); // 6 digits
if (!use_slave_mask || bitmap_is_clear_all(&slave_error_mask)) {
/* purecov: begin tested */
memcpy(slave_skip_error_names, STRING_WITH_LEN("OFF"));
/* purecov: end */
} else if (bitmap_is_set_all(&slave_error_mask)) {
/* purecov: begin tested */
memcpy(slave_skip_error_names, STRING_WITH_LEN("ALL"));
/* purecov: end */
} else {
char *buff = slave_skip_error_names;
char *bend = buff + sizeof(slave_skip_error_names);
int errnum;
for (errnum = 0; errnum < MAX_SLAVE_ERROR; errnum++) {
if (bitmap_is_set(&slave_error_mask, errnum)) {
if (buff + MIN_ROOM >= bend) break; /* purecov: tested */
buff = longlong10_to_str(errnum, buff, -10);
*buff++ = ',';
}
}
if (buff != slave_skip_error_names) buff--; // Remove last ','
/*
The range for client side error is [2000-2999]
so if the errnum doesn't lie in that and if less
than MAX_SLAVE_ERROR[10000] we enter the if loop.
*/
if (errnum < MAX_SLAVE_ERROR &&
(errnum < CR_MIN_ERROR || errnum > CR_MAX_ERROR)) {
/* Couldn't show all errors */
buff = my_stpcpy(buff, "..."); /* purecov: tested */
}
*buff = 0;
}
DBUG_PRINT("init", ("error_names: '%s'", slave_skip_error_names));
}
/**
Change arg to the string with the nice, human-readable skip error values.
@param replica_skip_errors_ptr
The pointer to be changed
*/
void set_replica_skip_errors(char **replica_skip_errors_ptr) {
DBUG_TRACE;
print_replica_skip_errors();
*replica_skip_errors_ptr = slave_skip_error_names;
}
/**
Init function to set up array for errors that should be skipped for slave
*/
static void init_replica_skip_errors() {
DBUG_TRACE;
assert(!use_slave_mask); // not already initialized
if (bitmap_init(&slave_error_mask, nullptr, MAX_SLAVE_ERROR)) {
fprintf(stderr, "Badly out of memory, please check your system status\n");
exit(MYSQLD_ABORT_EXIT);
}
use_slave_mask = true;
}
static void add_replica_skip_errors(const uint *errors, uint n_errors) {
DBUG_TRACE;
assert(errors);
assert(use_slave_mask);
for (uint i = 0; i < n_errors; i++) {
const uint err_code = errors[i];
/*
The range for client side error is [2000-2999]
so if the err_code doesn't lie in that and if less
than MAX_SLAVE_ERROR[14000] we enter the if loop.
*/
if (err_code < MAX_SLAVE_ERROR &&
(err_code < CR_MIN_ERROR || err_code > CR_MAX_ERROR))
bitmap_set_bit(&slave_error_mask, err_code);
}
}
/*
Add errors that should be skipped for slave
SYNOPSIS
add_replica_skip_errors()
arg List of errors numbers to be added to skip, separated with ','
NOTES
Called from get_options() in mysqld.cc on start-up
*/
void add_replica_skip_errors(const char *arg) {
const char *p = nullptr;
/*
ALL is only valid when nothing else is provided.
*/
const uchar SKIP_ALL[] = "all";
size_t SIZE_SKIP_ALL = strlen((const char *)SKIP_ALL) + 1;
/*
IGNORE_DDL_ERRORS can be combined with other parameters
but must be the first one provided.
*/
const uchar SKIP_DDL_ERRORS[] = "ddl_exist_errors";
size_t SIZE_SKIP_DDL_ERRORS = strlen((const char *)SKIP_DDL_ERRORS);
DBUG_TRACE;
// initialize mask if not done yet
if (!use_slave_mask) init_replica_skip_errors();
for (; my_isspace(system_charset_info, *arg); ++arg) /* empty */
;
if (!my_strnncoll(system_charset_info, pointer_cast<const uchar *>(arg),
SIZE_SKIP_ALL, SKIP_ALL, SIZE_SKIP_ALL)) {
bitmap_set_all(&slave_error_mask);
return;
}
if (!my_strnncoll(system_charset_info, pointer_cast<const uchar *>(arg),
SIZE_SKIP_DDL_ERRORS, SKIP_DDL_ERRORS,
SIZE_SKIP_DDL_ERRORS)) {
// DDL errors to be skipped for relaxed 'exist' handling
const uint ddl_errors[] = {
// error codes with create/add <schema object>
ER_DB_CREATE_EXISTS, ER_TABLE_EXISTS_ERROR, ER_DUP_KEYNAME,
ER_MULTIPLE_PRI_KEY,
// error codes with change/rename <schema object>
ER_BAD_FIELD_ERROR, ER_NO_SUCH_TABLE, ER_DUP_FIELDNAME,
// error codes with drop <schema object>
ER_DB_DROP_EXISTS, ER_BAD_TABLE_ERROR, ER_CANT_DROP_FIELD_OR_KEY};
add_replica_skip_errors(ddl_errors,
sizeof(ddl_errors) / sizeof(ddl_errors[0]));
/*
After processing the SKIP_DDL_ERRORS, the pointer is
increased to the position after the comma.
*/
if (strlen(arg) > SIZE_SKIP_DDL_ERRORS + 1) arg += SIZE_SKIP_DDL_ERRORS + 1;
}
for (p = arg; *p;) {
long err_code;
if (!(p = str2int(p, 10, 0, LONG_MAX, &err_code))) break;
if (err_code < MAX_SLAVE_ERROR)
bitmap_set_bit(&slave_error_mask, (uint)err_code);
while (!my_isdigit(system_charset_info, *p) && *p) p++;
}
}
static void set_thd_in_use_temporary_tables(Relay_log_info *rli) {
TABLE *table;
for (table = rli->save_temporary_tables; table; table = table->next) {
table->in_use = rli->info_thd;
if (table->file != nullptr) {
/*
Since we are stealing opened temporary tables from one thread to
another, we need to let the performance schema know that, for aggregates
per thread to work properly.
*/
table->file->unbind_psi();
table->file->rebind_psi();
}
}
}
int terminate_slave_threads(Master_info *mi, int thread_mask,
ulong stop_wait_timeout, bool need_lock_term) {
DBUG_TRACE;
if (!mi->inited) return 0; /* successfully do nothing */
int error, force_all = (thread_mask & SLAVE_FORCE_ALL);
mysql_mutex_t *sql_lock{&mi->rli->run_lock}, *io_lock{&mi->run_lock};
mysql_mutex_t *log_lock = mi->rli->relay_log.get_log_lock();
/*
Set it to a variable, so the value is shared by both stop methods.
This guarantees that the user defined value for the timeout value is for
the time the 2 threads take to shutdown, and not the time of each thread
stop operation.
*/
ulong total_stop_wait_timeout = stop_wait_timeout;
if (thread_mask & (SLAVE_SQL | SLAVE_FORCE_ALL)) {
DBUG_PRINT("info", ("Terminating SQL thread"));
mi->rli->abort_slave = true;
DEBUG_SYNC(current_thd,
"terminate_replica_threads_after_set_abort_replica");
if ((error = terminate_slave_thread(
mi->rli->info_thd, sql_lock, &mi->rli->stop_cond,
&mi->rli->slave_running, &total_stop_wait_timeout,
need_lock_term)) &&
!force_all) {
if (error == 1) {
return ER_STOP_REPLICA_SQL_THREAD_TIMEOUT;
}
return error;
}
DBUG_PRINT("info", ("Flushing relay-log info file."));
if (current_thd)
THD_STAGE_INFO(current_thd, stage_flushing_relay_log_info_file);
/*
Flushes the relay log info regardless of the sync_relay_log_info option.
*/
if (mi->rli->flush_info(Relay_log_info::RLI_FLUSH_IGNORE_SYNC_OPT)) {
return ER_ERROR_DURING_FLUSH_LOGS;
}
}
/*
Only stops the monitoring thread if this is the only failover channel
running.
*/
if ((thread_mask & (SLAVE_MONITOR | SLAVE_FORCE_ALL)) &&
channel_map.get_number_of_connection_auto_failover_channels_running() ==
1) {
DBUG_PRINT("info", ("Terminating Monitor IO thread"));
if ((error = Source_IO_monitor::get_instance()
->terminate_monitoring_process()) &&
!force_all) {
if (error == 1) {
return ER_STOP_REPLICA_MONITOR_IO_THREAD_TIMEOUT;
}
return error;
}
}
if (thread_mask & (SLAVE_IO | SLAVE_FORCE_ALL)) {
DBUG_PRINT("info", ("Terminating IO thread"));
mi->abort_slave = true;
DBUG_EXECUTE_IF("pause_after_queue_event",
{ rpl_replica_debug_point(DBUG_RPL_S_PAUSE_QUEUE_EV); });
/*
If the I/O thread is running and waiting for disk space,
the signal above will not make it to stop.
*/
bool io_waiting_disk_space =
mi->slave_running && mi->info_thd->is_waiting_for_disk_space();
/*
If we are shutting down the server and the I/O thread is waiting for
disk space, tell the terminate_slave_thread to forcefully kill the I/O
thread by sending a KILL_CONNECTION signal that will be listened by
my_write function.
*/
bool force_io_stop =
io_waiting_disk_space && (thread_mask & SLAVE_FORCE_ALL);
// If not shutting down, let the user to decide to abort I/O thread or wait
if (io_waiting_disk_space && !force_io_stop) {
LogErr(WARNING_LEVEL, ER_STOP_REPLICA_IO_THREAD_DISK_SPACE,
mi->get_channel());
DBUG_EXECUTE_IF("simulate_io_thd_wait_for_disk_space", {
rpl_replica_debug_point(DBUG_RPL_S_IO_WAIT_FOR_SPACE);
});
}
if ((error = terminate_slave_thread(
mi->info_thd, io_lock, &mi->stop_cond, &mi->slave_running,
&total_stop_wait_timeout, need_lock_term, force_io_stop)) &&
!force_all) {
if (error == 1) {
return ER_STOP_REPLICA_IO_THREAD_TIMEOUT;
}
return error;
}
#ifndef NDEBUG
if (force_io_stop) {
if (DBUG_EVALUATE_IF("simulate_io_thd_wait_for_disk_space", 1, 0)) {
DBUG_SET("-d,simulate_io_thd_wait_for_disk_space");
}
}
#endif
mysql_mutex_lock(log_lock);
DBUG_PRINT("info", ("Flushing relay log and source info repository."));
if (current_thd)
THD_STAGE_INFO(current_thd,
stage_flushing_relay_log_and_source_info_repository);
/*
Flushes the master info regardless of the sync_source_info option and
GTID_ONLY = 0 for this channel
*/
if (!mi->is_gtid_only_mode()) {
mysql_mutex_lock(&mi->data_lock);
if (mi->flush_info(true)) {
mysql_mutex_unlock(&mi->data_lock);
mysql_mutex_unlock(log_lock);
return ER_ERROR_DURING_FLUSH_LOGS;
}
mysql_mutex_unlock(&mi->data_lock);
}
/*
Flushes the relay log regardless of the sync_relay_log option.
*/
if (mi->rli->relay_log.is_open() &&
mi->rli->relay_log.flush_and_sync(true)) {
mysql_mutex_unlock(log_lock);
return ER_ERROR_DURING_FLUSH_LOGS;
}
mysql_mutex_unlock(log_lock);
}
return 0;
}
/**
Wait for a slave thread to terminate.
This function is called after requesting the thread to terminate
(by setting @c abort_slave member of @c Relay_log_info or @c
Master_info structure to 1). Termination of the thread is
controlled with the the predicate <code>*slave_running</code>.
Function will acquire @c term_lock before waiting on the condition
unless @c need_lock_term is false in which case the mutex should be
owned by the caller of this function and will remain acquired after
return from the function.
@param thd
Current session.
@param term_lock
Associated lock to use when waiting for @c term_cond
@param term_cond
Condition that is signalled when the thread has terminated
@param slave_running
Pointer to predicate to check for slave thread termination
@param stop_wait_timeout
A pointer to a variable that denotes the time the thread has
to stop before we time out and throw an error.
@param need_lock_term
If @c false the lock will not be acquired before waiting on
the condition. In this case, it is assumed that the calling
function acquires the lock before calling this function.
@param force
Force the slave thread to stop by sending a KILL_CONNECTION
signal to it. This is used to forcefully stop the I/O thread
when it is waiting for disk space and the server is shutting
down.
@retval 0 All OK, 1 on "STOP REPLICA" command timeout,
ER_REPLICA_CHANNEL_NOT_RUNNING otherwise.
@note If the executing thread has to acquire term_lock
(need_lock_term is true, the negative running status does not
represent any issue therefore no error is reported.
*/
static int terminate_slave_thread(THD *thd, mysql_mutex_t *term_lock,
mysql_cond_t *term_cond,
std::atomic<uint> *slave_running,
ulong *stop_wait_timeout, bool need_lock_term,
bool force) {
DBUG_TRACE;
if (need_lock_term) {
mysql_mutex_lock(term_lock);
} else {
mysql_mutex_assert_owner(term_lock);
}
if (!*slave_running) {
if (need_lock_term) {
/*
if run_lock (term_lock) is acquired locally then either
slave_running status is fine
*/
mysql_mutex_unlock(term_lock);
return 0;
} else {
return ER_REPLICA_CHANNEL_NOT_RUNNING;
}
}
assert(thd != nullptr);
THD_CHECK_SENTRY(thd);
/*
Is is critical to test if the slave is running. Otherwise, we might
be referening freed memory trying to kick it
*/
while (*slave_running) // Should always be true
{
DBUG_PRINT("loop", ("killing replica thread"));
mysql_mutex_lock(&thd->LOCK_thd_data);
/*
Error codes from pthread_kill are:
EINVAL: invalid signal number (can't happen)
ESRCH: thread already killed (can happen, should be ignored)
*/
#ifndef _WIN32
int err [[maybe_unused]] = pthread_kill(thd->real_id, SIGALRM);
assert(err != EINVAL);
#endif
if (force)
thd->awake(THD::KILL_CONNECTION);
else
thd->awake(THD::NOT_KILLED);
mysql_mutex_unlock(&thd->LOCK_thd_data);
DBUG_EXECUTE_IF("block_on_thread_stop_after_awake", {
rpl_replica_debug_point(DBUG_RPL_R_WAIT_AFTER_AWAKE_ON_THREAD_STOP);
});
/*
There is a small chance that slave thread might miss the first
alarm. To protect against it, resend the signal until it reacts
*/
struct timespec abstime;
set_timespec(&abstime, 2);
#ifndef NDEBUG
int error =
#endif
mysql_cond_timedwait(term_cond, term_lock, &abstime);
if ((*stop_wait_timeout) >= 2)
(*stop_wait_timeout) = (*stop_wait_timeout) - 2;
else if (*slave_running) {
if (need_lock_term) mysql_mutex_unlock(term_lock);
return 1;
}
assert(error == ETIMEDOUT || error == 0);
}
assert(*slave_running == 0);
if (need_lock_term) mysql_mutex_unlock(term_lock);
return 0;
}
bool start_slave_thread(PSI_thread_key thread_key, my_start_routine h_func,
mysql_mutex_t *start_lock, mysql_mutex_t *cond_lock,
mysql_cond_t *start_cond,
std::atomic<uint> *slave_running,
std::atomic<ulong> *slave_run_id, Master_info *mi) {
bool is_error = false;
my_thread_handle th;
ulong start_id;
DBUG_TRACE;
if (start_lock) mysql_mutex_lock(start_lock);
if (!server_id) {
if (start_cond) mysql_cond_broadcast(start_cond);
LogErr(ERROR_LEVEL, ER_RPL_SERVER_ID_MISSING, mi->get_for_channel_str());
my_error(ER_BAD_REPLICA, MYF(0));
goto err;
}
if (*slave_running) {
if (start_cond) mysql_cond_broadcast(start_cond);
my_error(ER_REPLICA_CHANNEL_MUST_STOP, MYF(0), mi->get_channel());
goto err;
}
start_id = *slave_run_id;
DBUG_PRINT("info", ("Creating new replica thread"));
if (mysql_thread_create(thread_key, &th, &connection_attrib, h_func,
(void *)mi)) {
LogErr(ERROR_LEVEL, ER_RPL_CANT_CREATE_REPLICA_THREAD,
mi->get_for_channel_str());
my_error(ER_REPLICA_THREAD, MYF(0));
goto err;
}
if (start_cond && cond_lock) // caller has cond_lock
{
THD *thd = current_thd;
while (start_id == *slave_run_id && thd != nullptr) {
DBUG_PRINT("sleep", ("Waiting for replica thread to start"));
PSI_stage_info saved_stage = {0, "", 0, ""};
thd->ENTER_COND(start_cond, cond_lock,
&stage_waiting_for_replica_thread_to_start, &saved_stage);
/*
It is not sufficient to test this at loop bottom. We must test
it after registering the mutex in enter_cond(). If the kill
happens after testing of thd->killed and before the mutex is
registered, we could otherwise go waiting though thd->killed is
set.
*/
if (!thd->killed) mysql_cond_wait(start_cond, cond_lock);
mysql_mutex_unlock(cond_lock);
thd->EXIT_COND(&saved_stage);
mysql_mutex_lock(cond_lock); // re-acquire it
if (thd->killed) {
my_error(thd->killed, MYF(0));
goto err;
}
}
}
goto end;
err:
is_error = true;
end:
if (start_lock) mysql_mutex_unlock(start_lock);
return is_error;
}
/*
start_slave_threads()
NOTES
SLAVE_FORCE_ALL is not implemented here on purpose since it does not make
sense to do that for starting a slave--we always care if it actually
started the threads that were not previously running
*/
bool start_slave_threads(bool need_lock_slave, bool wait_for_start,
Master_info *mi, int thread_mask) {
mysql_mutex_t *lock_io{nullptr}, *lock_sql{nullptr}, *lock_cond_io{nullptr},
*lock_cond_sql{nullptr};
mysql_cond_t *cond_io{nullptr}, *cond_sql{nullptr};
bool is_error{false};
DBUG_TRACE;
DBUG_EXECUTE_IF("uninitialized_source-info_structure", mi->inited = false;);
if (!mi->inited || !mi->rli->inited) {
int error = (!mi->inited ? ER_REPLICA_CM_INIT_REPOSITORY
: ER_REPLICA_AM_INIT_REPOSITORY);
Rpl_info *info = (!mi->inited ? mi : static_cast<Rpl_info *>(mi->rli));
const char *prefix = current_thd ? ER_THD_NONCONST(current_thd, error)
: ER_DEFAULT_NONCONST(error);
info->report(ERROR_LEVEL,
(!mi->inited ? ER_SERVER_REPLICA_CM_INIT_REPOSITORY
: ER_SERVER_REPLICA_AM_INIT_REPOSITORY),
prefix, nullptr);
my_error(error, MYF(0));
return true;
}
if (check_replica_configuration_errors(mi, thread_mask)) return true;
/**
SQL AFTER MTS GAPS has no effect when GTID_MODE=ON and SOURCE_AUTO_POS=1
as no gaps information was collected.
**/
if (global_gtid_mode.get() == Gtid_mode::ON && mi->is_auto_position() &&
mi->rli->until_condition == Relay_log_info::UNTIL_SQL_AFTER_MTS_GAPS) {
if (current_thd) {
push_warning_printf(
current_thd, Sql_condition::SL_WARNING,
ER_WARN_SQL_AFTER_MTS_GAPS_GAP_NOT_CALCULATED,
ER_THD(current_thd, ER_WARN_SQL_AFTER_MTS_GAPS_GAP_NOT_CALCULATED),
mi->get_channel());
}
}
if (need_lock_slave) {
lock_io = &mi->run_lock;
lock_sql = &mi->rli->run_lock;
}
if (wait_for_start) {
cond_io = &mi->start_cond;
cond_sql = &mi->rli->start_cond;
lock_cond_io = &mi->run_lock;
lock_cond_sql = &mi->rli->run_lock;
}
if (thread_mask & SLAVE_IO)
is_error = start_slave_thread(key_thread_replica_io, handle_slave_io,
lock_io, lock_cond_io, cond_io,
&mi->slave_running, &mi->slave_run_id, mi);
if (!is_error && (thread_mask & (SLAVE_IO | SLAVE_MONITOR)) &&
mi->is_source_connection_auto_failover() &&
!Source_IO_monitor::get_instance()->is_monitoring_process_running()) {
is_error = Source_IO_monitor::get_instance()->launch_monitoring_process(
key_thread_replica_monitor_io);
if (is_error)
terminate_slave_threads(mi, thread_mask & (SLAVE_IO | SLAVE_MONITOR),
rpl_stop_replica_timeout, need_lock_slave);
}
if (!is_error && (thread_mask & SLAVE_SQL)) {
/*
MTS-recovery gaps gathering is placed onto common execution path
for either START-SLAVE and --skip-start-replica= 0
*/
if (mi->rli->recovery_parallel_workers != 0) {
if (mts_recovery_groups(mi->rli)) {
is_error = true;
my_error(ER_MTA_RECOVERY_FAILURE, MYF(0));
}
}
if (!is_error)
is_error = start_slave_thread(
key_thread_replica_sql, handle_slave_sql, lock_sql, lock_cond_sql,
cond_sql, &mi->rli->slave_running, &mi->rli->slave_run_id, mi);
if (is_error)
terminate_slave_threads(mi, thread_mask & (SLAVE_IO | SLAVE_MONITOR),
rpl_stop_replica_timeout, need_lock_slave);
}
return is_error;
}
/*
Release slave threads at time of executing shutdown.
SYNOPSIS
end_slave()
*/
void end_slave() {
DBUG_TRACE;
Master_info *mi = nullptr;
/*
This is called when the server terminates, in close_connections().
It terminates slave threads. However, some CHANGE MASTER etc may still be
running presently. If a START SLAVE was in progress, the mutex lock below
will make us wait until slave threads have started, and START SLAVE
returns, then we terminate them here.
*/
channel_map.wrlock();
/* traverse through the map and terminate the threads */
for (mi_map::iterator it = channel_map.begin(); it != channel_map.end();
it++) {
mi = it->second;
if (mi)
terminate_slave_threads(mi, SLAVE_FORCE_ALL, rpl_stop_replica_timeout);
}
channel_map.unlock();
}
/**
Free all resources used by slave threads at time of executing shutdown.
The routine must be called after all possible users of channel_map
have left.
*/
void delete_slave_info_objects() {
DBUG_TRACE;
Master_info *mi = nullptr;
channel_map.wrlock();
for (mi_map::iterator it = channel_map.begin(); it != channel_map.end();
it++) {
mi = it->second;
if (mi) {
mi->channel_wrlock();
end_info(mi);
if (mi->rli) delete mi->rli;
delete mi;
it->second = 0;
}
}
// Clean other types of channel
for (mi_map::iterator it = channel_map.begin(GROUP_REPLICATION_CHANNEL);
it != channel_map.end(GROUP_REPLICATION_CHANNEL); it++) {
mi = it->second;
if (mi) {
mi->channel_wrlock();
end_info(mi);
if (mi->rli) delete mi->rli;
delete mi;
it->second = 0;
}
}
channel_map.unlock();
}
/**
Check if multi-statement transaction mode and master and slave info
repositories are set to table.
@param thd THD object
@retval true Success
@retval false Failure
*/
static bool is_autocommit_off_and_infotables(THD *thd) {
DBUG_TRACE;
return (thd && thd->in_multi_stmt_transaction_mode() &&
(opt_mi_repository_id == INFO_REPOSITORY_TABLE ||
opt_rli_repository_id == INFO_REPOSITORY_TABLE))
? true
: false;
}
static bool monitor_io_replica_killed(THD *thd, Master_info *mi) {
return Source_IO_monitor::get_instance()->is_monitor_killed(thd, mi);
}
static bool io_slave_killed(THD *thd, Master_info *mi) {
DBUG_TRACE;
assert(mi->info_thd == thd);
assert(mi->slave_running); // tracking buffer overrun
return mi->abort_slave || connection_events_loop_aborted() || thd->killed;
}
/**
The function analyzes a possible killed status and makes
a decision whether to accept it or not.
Normally upon accepting the sql thread goes to shutdown.
In the event of deferring decision @c rli->last_event_start_time waiting
timer is set to force the killed status be accepted upon its expiration.
Notice Multi-Threaded-Slave behaves similarly in that when it's being
stopped and the current group of assigned events has not yet scheduled
completely, Coordinator defers to accept to leave its read-distribute
state. The above timeout ensures waiting won't last endlessly, and in
such case an error is reported.
@param thd pointer to a THD instance
@param rli pointer to Relay_log_info instance
@return true the killed status is recognized, false a possible killed
status is deferred.
*/
bool sql_slave_killed(THD *thd, Relay_log_info *rli) {
bool is_parallel_warn = false;
DBUG_TRACE;
assert(rli->info_thd == thd);
assert(rli->slave_running == 1);
if (rli->sql_thread_kill_accepted) return true;
DBUG_EXECUTE_IF("stop_when_mta_in_group", rli->abort_slave = 1;
DBUG_SET("-d,stop_when_mta_in_group");
DBUG_SET("-d,simulate_stop_when_mta_in_group");
return false;);
if (connection_events_loop_aborted() || thd->killed || rli->abort_slave) {
rli->sql_thread_kill_accepted = true;
is_parallel_warn =
(rli->is_parallel_exec() && (rli->is_mts_in_group() || thd->killed));
/*
Slave can execute stop being in one of two MTS or Single-Threaded mode.
The modes define different criteria to accept the stop.
In particular that relates to the concept of groupping.
Killed Coordinator thread expects the worst so it warns on
possible consistency issue.
*/
if (is_parallel_warn || (!rli->is_parallel_exec() &&
thd->get_transaction()->cannot_safely_rollback(
Transaction_ctx::SESSION) &&
rli->is_in_group())) {
char msg_stopped[] =
"... Replica SQL Thread stopped with incomplete event group "
"having non-transactional changes. "
"If the group consists solely of row-based events, you can try "
"to restart the replica with --replica-exec-mode=IDEMPOTENT, which "
"ignores duplicate key, key not found, and similar errors (see "
"documentation for details).";
char msg_stopped_mts[] =
"... The replica coordinator and worker threads are stopped, "
"possibly "
"leaving data in inconsistent state. A restart should "
"restore consistency automatically, although using non-transactional "
"storage for data or info tables or DDL queries could lead to "
"problems. "
"In such cases you have to examine your data (see documentation for "
"details).";
if (rli->abort_slave) {
DBUG_PRINT("info",
("Request to stop replica SQL Thread received while "
"applying an MTA group or a group that "
"has non-transactional "
"changes; waiting for completion of the group ... "));
/*
Slave sql thread shutdown in face of unfinished group modified
Non-trans table is handled via a timer. The slave may eventually
give out to complete the current group and in that case there
might be issues at consequent slave restart, see the error message.
WL#2975 offers a robust solution requiring to store the last exectuted
event's coordinates along with the group's coordianates
instead of waiting with @c last_event_start_time the timer.
*/
if (rli->last_event_start_time == 0)
rli->last_event_start_time = time(nullptr);
rli->sql_thread_kill_accepted =
difftime(time(nullptr), rli->last_event_start_time) <=
SLAVE_WAIT_GROUP_DONE
? false
: true;
DBUG_EXECUTE_IF("stop_replica_middle_group",
DBUG_EXECUTE_IF("incomplete_group_in_relay_log",
rli->sql_thread_kill_accepted =
true;);); // time is over
if (!rli->sql_thread_kill_accepted && !rli->reported_unsafe_warning) {
rli->report(
WARNING_LEVEL, 0,
!is_parallel_warn
? "Request to stop replica SQL Thread received while "
"applying a group that has non-transactional "
"changes; waiting for completion of the group ... "
: "Coordinator thread of multi-threaded replica is being "
"stopped in the middle of assigning a group of events; "
"deferring to exit until the group completion ... ");
rli->reported_unsafe_warning = true;
}
}
if (rli->sql_thread_kill_accepted) {
rli->last_event_start_time = 0;
if (rli->mts_group_status == Relay_log_info::MTS_IN_GROUP) {
rli->mts_group_status = Relay_log_info::MTS_KILLED_GROUP;
}
if (is_parallel_warn)
rli->report(!rli->is_error()
? ERROR_LEVEL
: WARNING_LEVEL, // an error was reported by Worker
ER_MTA_INCONSISTENT_DATA,
ER_THD(thd, ER_MTA_INCONSISTENT_DATA), msg_stopped_mts);
else
rli->report(ERROR_LEVEL, ER_REPLICA_FATAL_ERROR,
ER_THD(thd, ER_REPLICA_FATAL_ERROR), msg_stopped);
}
}
}
return rli->sql_thread_kill_accepted;
}
bool net_request_file(NET *net, const char *fname) {
DBUG_TRACE;
return net_write_command(net, 251, pointer_cast<const uchar *>(fname),
strlen(fname), pointer_cast<const uchar *>(""), 0);
}
/*
From other comments and tests in code, it looks like
sometimes Query_log_event and Load_log_event can have db == 0
(see rewrite_db() above for example)
(cases where this happens are unclear; it may be when the master is 3.23).
*/
const char *print_slave_db_safe(const char *db) {
DBUG_TRACE;
return (db ? db : "");
}
bool is_network_error(uint errorno) {
return errorno == CR_CONNECTION_ERROR || errorno == CR_CONN_HOST_ERROR ||
errorno == CR_SERVER_GONE_ERROR || errorno == CR_SERVER_LOST ||
errorno == ER_CON_COUNT_ERROR || errorno == ER_SERVER_SHUTDOWN ||
errorno == ER_NET_READ_INTERRUPTED ||
errorno == ER_NET_WRITE_INTERRUPTED;
}
enum enum_command_status {
COMMAND_STATUS_OK,
COMMAND_STATUS_ERROR,
COMMAND_STATUS_ALLOWED_ERROR
};
/**
Execute an initialization query for the IO thread.
If there is an error, then this function calls mysql_free_result;
otherwise the MYSQL object holds the result after this call. If
there is an error other than allowed_error, then this function
prints a message and returns -1.
@param mi Master_info object.
@param query Query string.
@param allowed_error Allowed error code, or 0 if no errors are allowed.
@param[out] master_res If this is not NULL and there is no error, then
mysql_store_result() will be called and the result stored in this pointer.
@param[out] master_row If this is not NULL and there is no error, then
mysql_fetch_row() will be called and the result stored in this pointer.
@retval COMMAND_STATUS_OK No error.
@retval COMMAND_STATUS_ALLOWED_ERROR There was an error and the
error code was 'allowed_error'.
@retval COMMAND_STATUS_ERROR There was an error and the error code
was not 'allowed_error'.
*/
static enum_command_status io_thread_init_command(
Master_info *mi, const char *query, int allowed_error,
MYSQL_RES **master_res = nullptr, MYSQL_ROW *master_row = nullptr) {
DBUG_TRACE;
DBUG_PRINT("info", ("IO thread initialization command: '%s'", query));
MYSQL *mysql = mi->mysql;
int ret = mysql_real_query(mysql, query, static_cast<ulong>(strlen(query)));
if (io_slave_killed(mi->info_thd, mi)) {
LogErr(INFORMATION_LEVEL, ER_RPL_REPLICA_IO_THREAD_WAS_KILLED,
mi->get_for_channel_str(), query);
mysql_free_result(mysql_store_result(mysql));
return COMMAND_STATUS_ERROR;
}
if (ret != 0) {
uint err{mysql_errno(mysql)};
mysql_free_result(mysql_store_result(mysql));
if (is_network_error(err)) mi->set_network_error();
if (!err || (int)err != allowed_error) {
mi->report(is_network_error(err) ? WARNING_LEVEL : ERROR_LEVEL, err,
"The replica IO thread stops because the initialization query "
"'%s' failed with error '%s'.",
query, mysql_error(mysql));
return COMMAND_STATUS_ERROR;
}
return COMMAND_STATUS_ALLOWED_ERROR;
}
if (master_res != nullptr) {
if ((*master_res = mysql_store_result(mysql)) == nullptr) {
uint err{mysql_errno(mysql)};
if (is_network_error(err)) mi->set_network_error();
mi->report(WARNING_LEVEL, mysql_errno(mysql),
"The replica IO thread stops because the initialization query "
"'%s' did not return any result.",
query);
return COMMAND_STATUS_ERROR;
}
if (master_row != nullptr) {
if ((*master_row = mysql_fetch_row(*master_res)) == nullptr) {
uint err{mysql_errno(mysql)};
if (is_network_error(err)) mi->set_network_error();
mysql_free_result(*master_res);
mi->report(
WARNING_LEVEL, mysql_errno(mysql),
"The replica IO thread stops because the initialization query "
"'%s' did not return any row.",
query);
return COMMAND_STATUS_ERROR;
}
}
} else
assert(master_row == nullptr);
return COMMAND_STATUS_OK;
}
/**
Set user variables after connecting to the master.
@param mysql MYSQL to request uuid from master.
@param mi Master_info to set master_uuid
@return 0: Success, 1: Fatal error, 2: Transient network error.
*/
int io_thread_init_commands(MYSQL *mysql, Master_info *mi) {
char query[256];
int ret = 0;
DBUG_EXECUTE_IF("fake_5_5_version_replica", return ret;);
mi->reset_network_error();
sprintf(query, "SET @slave_uuid = '%s', @replica_uuid = '%s'", server_uuid,
server_uuid);
if (mysql_real_query(mysql, query, static_cast<ulong>(strlen(query))) &&
!check_io_slave_killed(mi->info_thd, mi, nullptr))
goto err;
mysql_free_result(mysql_store_result(mysql));
return ret;
err:
if (mysql_errno(mysql) && is_network_error(mysql_errno(mysql))) {
mi->report(WARNING_LEVEL, mysql_errno(mysql),
"The initialization command '%s' failed with the following"
" error: '%s'.",
query, mysql_error(mysql));
mi->set_network_error();
ret = 2;
} else {
char errmsg[512];
const char *errmsg_fmt =
"The replica I/O thread stops because a fatal error is encountered "
"when it tries to send query to source(query: %s).";
sprintf(errmsg, errmsg_fmt, query);
mi->report(ERROR_LEVEL, ER_REPLICA_FATAL_ERROR,
ER_THD(current_thd, ER_REPLICA_FATAL_ERROR), errmsg);
ret = 1;
}
mysql_free_result(mysql_store_result(mysql));
return ret;
}
/**
Get master's uuid on connecting.
@param mysql MYSQL to request uuid from master.
@param mi Master_info to set master_uuid
@return 0: Success, 1: Fatal error, 2: Transient network error.
*/
static int get_master_uuid(MYSQL *mysql, Master_info *mi) {
const char *errmsg;
MYSQL_RES *master_res = nullptr;
MYSQL_ROW master_row = nullptr;
int ret = 0;
char query_buf[] = "SELECT @@GLOBAL.SERVER_UUID";
mi->reset_network_error();
DBUG_EXECUTE_IF("dbug.return_null_SOURCE_UUID", {
mi->master_uuid[0] = 0;
return 0;
};);
DBUG_EXECUTE_IF("dbug.before_get_SOURCE_UUID",
{ rpl_replica_debug_point(DBUG_RPL_S_BEFORE_MASTER_UUID); };);
DBUG_EXECUTE_IF("dbug.simulate_busy_io",
{ rpl_replica_debug_point(DBUG_RPL_S_SIMULATE_BUSY_IO); };);
#ifndef NDEBUG
DBUG_EXECUTE_IF("dbug.simulate_no_such_var_server_uuid", {
query_buf[strlen(query_buf) - 1] = '_'; // corrupt the last char
});
#endif
if (!mysql_real_query(mysql, STRING_WITH_LEN(query_buf)) &&
(master_res = mysql_store_result(mysql)) &&
(master_row = mysql_fetch_row(master_res))) {
if (!strcmp(::server_uuid, master_row[0]) &&
!mi->rli->replicate_same_server_id) {
errmsg =
"The replica I/O thread stops because source and replica have equal "
"MySQL server UUIDs; these UUIDs must be different for "
"replication to work.";
mi->report(ERROR_LEVEL, ER_REPLICA_FATAL_ERROR,
ER_THD(current_thd, ER_REPLICA_FATAL_ERROR), errmsg);
// Fatal error
ret = 1;
} else {
if (mi->master_uuid[0] != 0) {
if (strcmp(mi->master_uuid, master_row[0])) {
bool is_host_port_unchanged{false};
char new_source_uuid[UUID_LENGTH + 1];
strncpy(new_source_uuid, master_row[0], UUID_LENGTH);
new_source_uuid[UUID_LENGTH] = 0;
if (!mi->m_uuid_from_host.empty() && mi->m_uuid_from_port != 0) {
if (mi->m_uuid_from_host.compare(mi->host) == 0 &&
mi->m_uuid_from_port == mi->port) {
is_host_port_unchanged = true;
}
}
if (is_host_port_unchanged) {
LogErr(WARNING_LEVEL,
ER_RPL_REPLICA_SOURCE_UUID_HAS_CHANGED_HOST_PORT_UNCHANGED,
mi->host, mi->port, mi->master_uuid, new_source_uuid);
} else {
LogErr(INFORMATION_LEVEL,
ER_RPL_REPLICA_SOURCE_UUID_HOST_PORT_HAS_CHANGED,
mi->m_uuid_from_host.c_str(), mi->m_uuid_from_port,
mi->master_uuid, mi->host, mi->port, new_source_uuid);
}
} else {
if (!mi->m_uuid_from_host.empty() && mi->m_uuid_from_port != 0 &&
mi->m_uuid_from_host.compare(mi->host) != 0 &&
mi->m_uuid_from_port != mi->port) {
LogErr(WARNING_LEVEL, ER_RPL_REPLICA_SOURCE_UUID_HAS_NOT_CHANGED,
mi->m_uuid_from_host.c_str(), mi->m_uuid_from_port, mi->host,
mi->port, mi->master_uuid);
}
}
}
strncpy(mi->master_uuid, master_row[0], UUID_LENGTH);
mi->master_uuid[UUID_LENGTH] = 0;
mi->m_uuid_from_host.assign(mi->host);
mi->m_uuid_from_port = mi->port;
}
} else if (mysql_errno(mysql) != ER_UNKNOWN_SYSTEM_VARIABLE) {
if (is_network_error(mysql_errno(mysql))) {
mi->report(WARNING_LEVEL, mysql_errno(mysql),
"Get source SERVER_UUID failed with error: %s",
mysql_error(mysql));
mi->set_network_error();
ret = 2;
} else {
/* Fatal error */
errmsg =
"The replica I/O thread stops because a fatal error is encountered "
"when it tries to get the value of SERVER_UUID variable from source.";
mi->report(ERROR_LEVEL, ER_REPLICA_FATAL_ERROR,
ER_THD(current_thd, ER_REPLICA_FATAL_ERROR), errmsg);
ret = 1;
}
} else {
mi->master_uuid[0] = 0;
mi->report(
WARNING_LEVEL, ER_UNKNOWN_SYSTEM_VARIABLE,
"Unknown system variable 'SERVER_UUID' on source. "
"A probable cause is that the variable is not supported on the "
"source (version: %s), even though it is on the replica (version: %s)",
mysql->server_version, server_version);
}
if (master_res) mysql_free_result(master_res);
return ret;
}
/*
Note that we rely on the master's version (3.23, 4.0.14 etc) instead of
relying on the binlog's version. This is not perfect: imagine an upgrade
of the master without waiting that all slaves are in sync with the master;
then a slave could be fooled about the binlog's format. This is what happens
when people upgrade a 3.23 master to 4.0 without doing RESET MASTER: 4.0
slaves are fooled. So we do this only to distinguish between 3.23 and more
recent masters (it's too late to change things for 3.23).
RETURNS
0 ok
1 error
2 transient network problem, the caller should try to reconnect
*/
static int get_master_version_and_clock(MYSQL *mysql, Master_info *mi) {
char err_buff[MAX_SLAVE_ERRMSG];
const char *errmsg = nullptr;
int err_code = 0;
int version_number = 0;
version_number = atoi(mysql->server_version);
MYSQL_RES *master_res = nullptr;
MYSQL_ROW master_row;
DBUG_TRACE;
DBUG_EXECUTE_IF("unrecognized_source_version", { version_number = 1; };);
mi->reset_network_error();
if (!my_isdigit(&my_charset_bin, *mysql->server_version) ||
version_number < 5) {
errmsg = "Source reported unrecognized MySQL version";
err_code = ER_REPLICA_FATAL_ERROR;
sprintf(err_buff, ER_THD_NONCONST(current_thd, err_code), errmsg);
goto err;
}
mysql_mutex_lock(mi->rli->relay_log.get_log_lock());
mysql_mutex_lock(&mi->data_lock);
mi->set_mi_description_event(new Format_description_log_event());
/* as we are here, we tried to allocate the event */
if (mi->get_mi_description_event() == nullptr) {
mysql_mutex_unlock(&mi->data_lock);
mysql_mutex_unlock(mi->rli->relay_log.get_log_lock());
errmsg = "default Format_description_log_event";
err_code = ER_REPLICA_CREATE_EVENT_FAILURE;
sprintf(err_buff, ER_THD_NONCONST(current_thd, err_code), errmsg);
goto err;
}
/*
FD_q's (A) is set initially from RL's (A): FD_q.(A) := RL.(A).
It's necessary to adjust FD_q.(A) at this point because in the following
course FD_q is going to be dumped to RL.
Generally FD_q is derived from a received FD_m (roughly FD_q := FD_m)
in queue_event and the master's (A) is installed.
At one step with the assignment the Relay-Log's checksum alg is set to
a new value: RL.(A) := FD_q.(A). If the slave service is stopped
the last time assigned RL.(A) will be passed over to the restarting
service (to the current execution point).
RL.A is a "codec" to verify checksum in queue_event() almost all the time
the first fake Rotate event.
Starting from this point IO thread will executes the following checksum
warmup sequence of actions:
FD_q.A := RL.A,
A_m^0 := master.@@global.binlog_checksum,
{queue_event(R_f): verifies(R_f, A_m^0)},
{queue_event(FD_m): verifies(FD_m, FD_m.A), dump(FD_q), rotate(RL),
FD_q := FD_m, RL.A := FD_q.A)}
See legends definition on MYSQL_BIN_LOG::relay_log_checksum_alg
docs lines (binlog.h).
In above A_m^0 - the value of master's
@@binlog_checksum determined in the upcoming handshake (stored in
mi->checksum_alg_before_fd).
After the warm-up sequence IO gets to "normal" checksum verification mode
to use RL.A in
{queue_event(E_m): verifies(E_m, RL.A)}
until it has received a new FD_m.
*/
mi->get_mi_description_event()->common_footer->checksum_alg =
mi->rli->relay_log.relay_log_checksum_alg;
assert(mi->get_mi_description_event()->common_footer->checksum_alg !=
binary_log::BINLOG_CHECKSUM_ALG_UNDEF);
assert(mi->rli->relay_log.relay_log_checksum_alg !=
binary_log::BINLOG_CHECKSUM_ALG_UNDEF);
mysql_mutex_unlock(&mi->data_lock);
mysql_mutex_unlock(mi->rli->relay_log.get_log_lock());
/*
Compare the master and slave's clock. Do not die if master's clock is
unavailable (very old master not supporting UNIX_TIMESTAMP()?).
*/
DBUG_EXECUTE_IF("dbug.before_get_UNIX_TIMESTAMP", {
rpl_replica_debug_point(DBUG_RPL_S_BEFORE_UNIX_TIMESTAMP);
};);
master_res = nullptr;
if (!mysql_real_query(mysql, STRING_WITH_LEN("SELECT UNIX_TIMESTAMP()")) &&
(master_res = mysql_store_result(mysql)) &&
(master_row = mysql_fetch_row(master_res))) {
mysql_mutex_lock(&mi->data_lock);
mi->clock_diff_with_master =
(long)(time((time_t *)nullptr) - strtoul(master_row[0], nullptr, 10));
DBUG_EXECUTE_IF("dbug.mta.force_clock_diff_eq_0",
mi->clock_diff_with_master = 0;);
mysql_mutex_unlock(&mi->data_lock);
} else if (check_io_slave_killed(mi->info_thd, mi, nullptr))
goto slave_killed_err;
else if (is_network_error(mysql_errno(mysql))) {
mi->report(WARNING_LEVEL, mysql_errno(mysql),
"Get source clock failed with error: %s", mysql_error(mysql));
goto network_err;
} else {
mysql_mutex_lock(&mi->data_lock);
mi->clock_diff_with_master = 0; /* The "most sensible" value */
mysql_mutex_unlock(&mi->data_lock);
LogErr(WARNING_LEVEL, ER_RPL_REPLICA_SECONDS_BEHIND_SOURCE_DUBIOUS,
mysql_error(mysql), mysql_errno(mysql));
}
if (master_res) {
mysql_free_result(master_res);
master_res = nullptr;
}
/*
Check that the master's server id and ours are different. Because if they
are equal (which can result from a simple copy of master's datadir to slave,
thus copying some my.cnf), replication will work but all events will be
skipped.
Do not die if SELECT @@SERVER_ID fails on master (very old master?).
Note: we could have put a @@SERVER_ID in the previous SELECT
UNIX_TIMESTAMP() instead, but this would not have worked on 3.23 masters.
*/
DBUG_EXECUTE_IF("dbug.before_get_SERVER_ID",
{ rpl_replica_debug_point(DBUG_RPL_S_BEFORE_SERVER_ID); };);
master_res = nullptr;
master_row = nullptr;
DBUG_EXECUTE_IF("get_source_server_id.ER_NET_READ_INTERRUPTED", {
DBUG_SET("+d,inject_ER_NET_READ_INTERRUPTED");
DBUG_SET(
"-d,get_source_server_id."
"ER_NET_READ_INTERRUPTED");
});
if (!mysql_real_query(mysql, STRING_WITH_LEN("SELECT @@GLOBAL.SERVER_ID")) &&
(master_res = mysql_store_result(mysql)) &&
(master_row = mysql_fetch_row(master_res))) {
if ((::server_id ==
(mi->master_id = strtoul(master_row[0], nullptr, 10))) &&
!mi->rli->replicate_same_server_id) {
errmsg =
"The replica I/O thread stops because source and replica have equal "
"MySQL server ids; these ids must be different for replication to "
"work (or the --replicate-same-server-id option must be used on "
"replica but this does not always make sense; please check the "
"manual before using it).";
err_code = ER_REPLICA_FATAL_ERROR;
sprintf(err_buff, ER_THD(current_thd, ER_REPLICA_FATAL_ERROR), errmsg);
goto err;
}
} else if (mysql_errno(mysql) != ER_UNKNOWN_SYSTEM_VARIABLE) {
if (check_io_slave_killed(mi->info_thd, mi, nullptr))
goto slave_killed_err;
else if (is_network_error(mysql_errno(mysql))) {
mi->report(WARNING_LEVEL, mysql_errno(mysql),
"Get source SERVER_ID failed with error: %s",
mysql_error(mysql));
goto network_err;
}
/* Fatal error */
errmsg =
"The replica I/O thread stops because a fatal error is encountered "
"when it try to get the value of SERVER_ID variable from source.";
err_code = mysql_errno(mysql);
sprintf(err_buff, "%s Error: %s", errmsg, mysql_error(mysql));
goto err;
} else {
mi->report(WARNING_LEVEL, ER_SERVER_UNKNOWN_SYSTEM_VARIABLE,
"Unknown system variable 'SERVER_ID' on source, maybe it "
"is a *VERY OLD SOURCE*.");
}
if (master_res) {
mysql_free_result(master_res);
master_res = nullptr;
}
if (mi->master_id == 0 && mi->ignore_server_ids->dynamic_ids.size() > 0) {
errmsg =
"Replica configured with server id filtering could not detect the "
"source "
"server id.";
err_code = ER_REPLICA_FATAL_ERROR;
sprintf(err_buff, ER_THD(current_thd, ER_REPLICA_FATAL_ERROR), errmsg);
goto err;
}
if (mi->heartbeat_period != 0.0) {
char llbuf[22];
const char query_format[] =
"SET @master_heartbeat_period = %s, @source_heartbeat_period = %s";
char query[sizeof(query_format) - 2 * 2 + 2 * sizeof(llbuf) + 1];
/*
the period is an ulonglong of nano-secs.
*/
llstr((ulonglong)(mi->heartbeat_period * 1000000000UL), llbuf);
sprintf(query, query_format, llbuf, llbuf);
if (mysql_real_query(mysql, query, static_cast<ulong>(strlen(query)))) {
if (check_io_slave_killed(mi->info_thd, mi, nullptr))
goto slave_killed_err;
if (is_network_error(mysql_errno(mysql))) {
mi->report(
WARNING_LEVEL, mysql_errno(mysql),
"SET @source_heartbeat_period to source failed with error: %s",
mysql_error(mysql));
mysql_free_result(mysql_store_result(mysql));
goto network_err;
} else {
/* Fatal error */
errmsg =
"The replica I/O thread stops because a fatal error is encountered "
" when it tries to SET @source_heartbeat_period on source.";
err_code = ER_REPLICA_FATAL_ERROR;
sprintf(err_buff, "%s Error: %s", errmsg, mysql_error(mysql));
mysql_free_result(mysql_store_result(mysql));
goto err;
}
}
mysql_free_result(mysql_store_result(mysql));
}
/*
Querying if master is capable to checksum and notifying it about own
CRC-awareness. The master's side instant value of @@global.binlog_checksum
is stored in the dump thread's uservar area as well as cached locally
to become known in consensus by master and slave.
*/
if (DBUG_EVALUATE_IF("simulate_replica_unaware_checksum", 0, 1)) {
int rc;
// Set both variables, so that it works equally on both old and new
// source server.
const char query[] =
"SET @master_binlog_checksum = @@global.binlog_checksum, "
"@source_binlog_checksum = @@global.binlog_checksum";
master_res = nullptr;
// initially undefined
mi->checksum_alg_before_fd = binary_log::BINLOG_CHECKSUM_ALG_UNDEF;
/*
@c checksum_alg_before_fd is queried from master in this block.
If master is old checksum-unaware the value stays undefined.
Once the first FD will be received its alg descriptor will replace
the being queried one.
*/
rc = mysql_real_query(mysql, query, static_cast<ulong>(strlen(query)));
if (rc != 0) {
mi->checksum_alg_before_fd = binary_log::BINLOG_CHECKSUM_ALG_OFF;
if (check_io_slave_killed(mi->info_thd, mi, nullptr))
goto slave_killed_err;
if (mysql_errno(mysql) == ER_UNKNOWN_SYSTEM_VARIABLE) {
// this is tolerable as OM -> NS is supported
mi->report(WARNING_LEVEL, mysql_errno(mysql),
"Notifying source by %s failed with "
"error: %s",
query, mysql_error(mysql));
} else {
if (is_network_error(mysql_errno(mysql))) {
mi->report(WARNING_LEVEL, mysql_errno(mysql),
"Notifying source by %s failed with "
"error: %s",
query, mysql_error(mysql));
mysql_free_result(mysql_store_result(mysql));
goto network_err;
} else {
errmsg =
"The replica I/O thread stops because a fatal error is "
"encountered "
"when it tried to SET @source_binlog_checksum on source.";
err_code = ER_REPLICA_FATAL_ERROR;
sprintf(err_buff, "%s Error: %s", errmsg, mysql_error(mysql));
mysql_free_result(mysql_store_result(mysql));
goto err;
}
}
} else {
mysql_free_result(mysql_store_result(mysql));
// Read back the user variable that we just set, to verify that
// the source recognized the checksum algorithm.
if (!mysql_real_query(
mysql, STRING_WITH_LEN("SELECT @source_binlog_checksum")) &&
(master_res = mysql_store_result(mysql)) &&
(master_row = mysql_fetch_row(master_res)) &&
(master_row[0] != nullptr)) {
mi->checksum_alg_before_fd = static_cast<enum_binlog_checksum_alg>(
find_type(master_row[0], &binlog_checksum_typelib, 1) - 1);
DBUG_EXECUTE_IF("undefined_algorithm_on_replica",
mi->checksum_alg_before_fd =
binary_log::BINLOG_CHECKSUM_ALG_UNDEF;);
if (mi->checksum_alg_before_fd ==
binary_log::BINLOG_CHECKSUM_ALG_UNDEF) {
errmsg =
"The replica I/O thread was stopped because a fatal error is "
"encountered "
"The checksum algorithm used by source is unknown to replica.";
err_code = ER_REPLICA_FATAL_ERROR;
sprintf(err_buff, "%s Error: %s", errmsg, mysql_error(mysql));
mysql_free_result(mysql_store_result(mysql));
goto err;
}
// valid outcome is either of
assert(mi->checksum_alg_before_fd ==
binary_log::BINLOG_CHECKSUM_ALG_OFF ||
mi->checksum_alg_before_fd ==
binary_log::BINLOG_CHECKSUM_ALG_CRC32);
} else if (check_io_slave_killed(mi->info_thd, mi, nullptr))
goto slave_killed_err;
else if (is_network_error(mysql_errno(mysql))) {
mi->report(WARNING_LEVEL, mysql_errno(mysql),
"Get source BINLOG_CHECKSUM failed with error: %s",
mysql_error(mysql));
goto network_err;
} else {
errmsg =
"The replica I/O thread stops because a fatal error is encountered "
"when it tried to SELECT @source_binlog_checksum.";
err_code = ER_REPLICA_FATAL_ERROR;
sprintf(err_buff, "%s Error: %s", errmsg, mysql_error(mysql));
mysql_free_result(mysql_store_result(mysql));
goto err;
}
}
if (master_res) {
mysql_free_result(master_res);
master_res = nullptr;
}
} else
mi->checksum_alg_before_fd = binary_log::BINLOG_CHECKSUM_ALG_OFF;
if (DBUG_EVALUATE_IF("bug32442749_simulate_null_checksum", 1, 0)) {
const char query[] = "SET @source_binlog_checksum= NULL";
int rc = mysql_real_query(mysql, query, static_cast<ulong>(strlen(query)));
if (rc != 0) {
errmsg =
"The replica I/O thread stops because a fatal error is encountered "
"when it tried to SET @source_binlog_checksum.";
err_code = ER_REPLICA_FATAL_ERROR;
sprintf(err_buff, "%s Error: %s", errmsg, mysql_error(mysql));
mysql_free_result(mysql_store_result(mysql));
goto err;
}
mysql_free_result(mysql_store_result(mysql));
}
if (DBUG_EVALUATE_IF("simulate_replica_unaware_gtid", 0, 1)) {
auto master_gtid_mode = Gtid_mode::OFF;
auto slave_gtid_mode = global_gtid_mode.get();
switch (io_thread_init_command(mi, "SELECT @@GLOBAL.GTID_MODE",
ER_UNKNOWN_SYSTEM_VARIABLE, &master_res,
&master_row)) {
case COMMAND_STATUS_ERROR:
return 2;
case COMMAND_STATUS_ALLOWED_ERROR:
// master is old and does not have @@GLOBAL.GTID_MODE
master_gtid_mode = Gtid_mode::OFF;
break;
case COMMAND_STATUS_OK: {
const char *master_gtid_mode_string = master_row[0];
DBUG_EXECUTE_IF("simulate_source_has_gtid_mode_on_something",
{ master_gtid_mode_string = "on_something"; });
DBUG_EXECUTE_IF("simulate_source_has_gtid_mode_off_something",
{ master_gtid_mode_string = "off_something"; });
DBUG_EXECUTE_IF("simulate_source_has_unknown_gtid_mode",
{ master_gtid_mode_string = "Krakel Spektakel"; });
bool error;
std::tie(error, master_gtid_mode) =
Gtid_mode::from_string(master_gtid_mode_string);
if (error) {
mi->report(ERROR_LEVEL, ER_REPLICA_FATAL_ERROR,
"The replica IO thread stops because the source has "
"an unknown @@GLOBAL.GTID_MODE '%s'.",
master_gtid_mode_string);
mysql_free_result(master_res);
return 1;
}
mysql_free_result(master_res);
break;
}
}
if ((slave_gtid_mode == Gtid_mode::OFF &&
master_gtid_mode >= Gtid_mode::ON_PERMISSIVE) ||
(slave_gtid_mode == Gtid_mode::ON &&
master_gtid_mode <= Gtid_mode::OFF_PERMISSIVE &&
mi->rli->m_assign_gtids_to_anonymous_transactions_info.get_type() ==
Assign_gtids_to_anonymous_transactions_info::enum_type::
AGAT_OFF)) {
mi->report(ERROR_LEVEL, ER_REPLICA_FATAL_ERROR,
"The replication receiver thread cannot start because "
"the source has GTID_MODE = %.192s and this server has "
"GTID_MODE = %.192s.",
Gtid_mode::to_string(master_gtid_mode),
Gtid_mode::to_string(slave_gtid_mode));
return 1;
}
if (mi->is_auto_position() && master_gtid_mode != Gtid_mode::ON) {
mi->report(ERROR_LEVEL, ER_REPLICA_FATAL_ERROR,
"The replication receiver thread cannot start in "
"AUTO_POSITION mode: the source has GTID_MODE = %.192s "
"instead of ON.",
Gtid_mode::to_string(master_gtid_mode));
return 1;
}
}
err:
if (errmsg) {
if (master_res) mysql_free_result(master_res);
assert(err_code != 0);
mi->report(ERROR_LEVEL, err_code, "%s", err_buff);
return 1;
}
return 0;
network_err:
if (master_res) mysql_free_result(master_res);
mi->set_network_error();
return 2;
slave_killed_err:
if (master_res) mysql_free_result(master_res);
return 2;
}
static bool exceeds_relay_log_limit(Relay_log_info *rli,
std::size_t queued_size) {
return (rli->log_space_limit != 0 &&
rli->log_space_limit < rli->log_space_total + queued_size);
}
static bool wait_for_relay_log_space(Relay_log_info *rli,
std::size_t queued_size) {
bool slave_killed = false;
Master_info *mi = rli->mi;
PSI_stage_info old_stage;
THD *thd = mi->info_thd;
DBUG_TRACE;
// from now on, until the time is_receiver_waiting_for_rl_space is
// cleared, every rotation made by coordinator and executed
// outside of a transaction, will purge the currently rotated log
rli->is_receiver_waiting_for_rl_space.store(true);
// rotate now to avoid deadlock with FLUSH RELAY LOGS, which calls
// rotate_relay_log with a default locking order, see rotate_relay_log
// Before rotation, is_receiver_waiting_for_rl_space is already set, so
// after exiting the rotate_relay_log, coordinator executing rotation
// requested here will see the correct value of the
// 'is_receiver_waiting_for_rl_space' and will purge applied logs
// with force option
rotate_relay_log(mi, true, true, true);
// capture the log name to which we rotated:
mysql_mutex_lock(rli->relay_log.get_log_lock());
std::string receiver_log = rli->relay_log.get_log_fname();
mysql_mutex_unlock(rli->relay_log.get_log_lock());
mysql_mutex_lock(&rli->log_space_lock);
thd->ENTER_COND(&rli->log_space_cond, &rli->log_space_lock,
&stage_waiting_for_relay_log_space, &old_stage);
while (exceeds_relay_log_limit(rli, queued_size) &&
!(slave_killed = io_slave_killed(thd, mi)) &&
rli->coordinator_log_after_purge != receiver_log) {
mysql_cond_wait(&rli->log_space_cond, &rli->log_space_lock);
}
mysql_mutex_unlock(&rli->log_space_lock);
thd->EXIT_COND(&old_stage);
rli->is_receiver_waiting_for_rl_space.store(false);
return slave_killed;
}
/*
Builds a Rotate and writes it to relay log.
The caller must hold mi->data_lock.
@param thd pointer to I/O Thread's Thd.
@param mi point to I/O Thread metadata class.
@param force_flush_mi_info when true, do not respect sync period and flush
information.
when false, flush will only happen if it is time to
flush.
@return 0 if everything went fine, 1 otherwise.
*/
static int write_rotate_to_master_pos_into_relay_log(THD *thd, Master_info *mi,
bool force_flush_mi_info) {
Relay_log_info *rli = mi->rli;
int error = 0;
DBUG_TRACE;
assert(thd == mi->info_thd);
mysql_mutex_assert_owner(rli->relay_log.get_log_lock());
DBUG_PRINT("info", ("writing a Rotate event to the relay log"));
Rotate_log_event *ev = new Rotate_log_event(mi->get_master_log_name(), 0,
mi->get_master_log_pos(),
Rotate_log_event::DUP_NAME);
DBUG_EXECUTE_IF("fail_generating_rotate_event_on_write_rotate_to_source_pos",
{
if (likely((bool)ev)) {
delete ev;
ev = nullptr;
}
});
if (likely((bool)ev)) {
if (mi->get_mi_description_event() != nullptr)
ev->common_footer->checksum_alg =
mi->get_mi_description_event()->common_footer->checksum_alg;
ev->server_id = 0; // don't be ignored by slave SQL thread
if (unlikely(rli->relay_log.write_event(ev, mi) != 0))
mi->report(ERROR_LEVEL, ER_REPLICA_RELAY_LOG_WRITE_FAILURE,
ER_THD(thd, ER_REPLICA_RELAY_LOG_WRITE_FAILURE),
"failed to write a Rotate event"
" to the relay log, SHOW REPLICA STATUS may be"
" inaccurate");
mysql_mutex_lock(&mi->data_lock);
if (flush_master_info(mi, force_flush_mi_info, false, false,
mi->is_gtid_only_mode())) {
error = 1;
LogErr(ERROR_LEVEL, ER_RPL_REPLICA_CANT_FLUSH_CONNECTION_METADATA_REPOS);
}
mysql_mutex_unlock(&mi->data_lock);
delete ev;
} else {
error = 1;
mi->report(ERROR_LEVEL, ER_REPLICA_CREATE_EVENT_FAILURE,
ER_THD(thd, ER_REPLICA_CREATE_EVENT_FAILURE),
"Rotate_event (out of memory?),"
" SHOW REPLICA STATUS may be inaccurate");
}
return error;
}
/*
Builds a Rotate from the ignored events' info and writes it to relay log.
@param thd pointer to I/O Thread's Thd.
@param mi point to I/O Thread metadata class.
@return 0 if everything went fine, 1 otherwise.
*/
static int write_ignored_events_info_to_relay_log(THD *thd, Master_info *mi) {
Relay_log_info *rli = mi->rli;
mysql_mutex_t *end_pos_lock = rli->relay_log.get_binlog_end_pos_lock();
int error = 0;
DBUG_TRACE;
assert(thd == mi->info_thd);
mysql_mutex_lock(rli->relay_log.get_log_lock());
mysql_mutex_lock(end_pos_lock);
if (rli->ign_master_log_name_end[0]) {
DBUG_PRINT("info", ("writing a Rotate event to track down ignored events"));
/*
If the ignored events' info still hold, they should have same info as
the mi->get_master_log_[name|pos].
*/
assert(strcmp(rli->ign_master_log_name_end, mi->get_master_log_name()) ==
0);
assert(rli->ign_master_log_pos_end == mi->get_master_log_pos());
/* Avoid the applier to get the ignored event' info by rli->ign* */
rli->ign_master_log_name_end[0] = 0;
/* can unlock before writing as the relay log will soon have our Rotate */
mysql_mutex_unlock(end_pos_lock);
/* Generate the rotate based on mi position */
error = write_rotate_to_master_pos_into_relay_log(
thd, mi, false /* force_flush_mi_info */);
} else
mysql_mutex_unlock(end_pos_lock);
mysql_mutex_unlock(rli->relay_log.get_log_lock());
return error;
}
static int register_slave_on_master(MYSQL *mysql, Master_info *mi,
bool *suppress_warnings) {
uchar buf[1024], *pos = buf;
size_t report_host_len = 0, report_user_len = 0, report_password_len = 0;
DBUG_TRACE;
*suppress_warnings = false;
if (report_host) report_host_len = strlen(report_host);
if (report_host_len > HOSTNAME_LENGTH) {
LogErr(WARNING_LEVEL, ER_RPL_REPLICA_REPORT_HOST_TOO_LONG, report_host_len,
HOSTNAME_LENGTH, mi->get_for_channel_str());
return 0;
}
if (report_user) report_user_len = strlen(report_user);
if (report_user_len > USERNAME_LENGTH) {
LogErr(WARNING_LEVEL, ER_RPL_REPLICA_REPORT_USER_TOO_LONG, report_user_len,
USERNAME_LENGTH, mi->get_for_channel_str());
return 0;
}
if (report_password) report_password_len = strlen(report_password);
if (report_password_len > MAX_PASSWORD_LENGTH) {
LogErr(WARNING_LEVEL, ER_RPL_REPLICA_REPORT_PASSWORD_TOO_LONG,
report_password_len, MAX_PASSWORD_LENGTH, mi->get_for_channel_str());
return 0;
}
int4store(pos, server_id);
pos += 4;
pos = net_store_data(pos, (uchar *)report_host, report_host_len);
pos = net_store_data(pos, (uchar *)report_user, report_user_len);
pos = net_store_data(pos, (uchar *)report_password, report_password_len);
int2store(pos, (uint16)report_port);
pos += 2;
/*
Fake rpl_recovery_rank, which was removed in BUG#13963,
so that this server can register itself on old servers,
see BUG#49259.
*/
int4store(pos, /* rpl_recovery_rank */ 0);
pos += 4;
/* The master will fill in master_id */
int4store(pos, 0);
pos += 4;
if (simple_command(mysql, COM_REGISTER_SLAVE, buf, (size_t)(pos - buf), 0)) {
uint err{mysql_errno(mysql)};
if (err == ER_NET_READ_INTERRUPTED) {
*suppress_warnings = true; // Suppress reconnect warning
} else if (!check_io_slave_killed(mi->info_thd, mi, nullptr)) {
std::stringstream ss;
ss << mysql_error(mysql) << " (Errno: " << err << ")";
mi->report(ERROR_LEVEL, ER_REPLICA_SOURCE_COM_FAILURE,
ER_THD(current_thd, ER_REPLICA_SOURCE_COM_FAILURE),
"COM_REGISTER_REPLICA", ss.str().c_str());
}
if (is_network_error(err)) mi->set_network_error();
return 1;
}
DBUG_EXECUTE_IF("simulate_register_replica_killed", {
mi->abort_slave = 1;
return 1;
};);
return 0;
}
/**
Function that fills the metadata required for SHOW REPLICA STATUS.
This function shall be used in two cases:
1) SHOW REPLICA STATUS FOR ALL CHANNELS
2) SHOW REPLICA STATUS for a channel
@param[in,out] field_list field_list to fill the metadata
@param[in] io_gtid_set_size the size to be allocated to store
the retrieved gtid set
@param[in] sql_gtid_set_size the size to be allocated to store
the executed gtid set
@todo return a bool after adding catching the exceptions to the
push_back() methods for field_list.
*/
static void show_slave_status_metadata(mem_root_deque<Item *> *field_list,
int io_gtid_set_size,
int sql_gtid_set_size) {
field_list->push_back(new Item_empty_string("Replica_IO_State", 14));
field_list->push_back(
new Item_empty_string("Source_Host", HOSTNAME_LENGTH + 1));
field_list->push_back(
new Item_empty_string("Source_User", USERNAME_LENGTH + 1));
field_list->push_back(new Item_return_int("Source_Port", 7, MYSQL_TYPE_LONG));
field_list->push_back(
new Item_return_int("Connect_Retry", 10, MYSQL_TYPE_LONG));
field_list->push_back(new Item_empty_string("Source_Log_File", FN_REFLEN));
field_list->push_back(
new Item_return_int("Read_Source_Log_Pos", 10, MYSQL_TYPE_LONGLONG));
field_list->push_back(new Item_empty_string("Relay_Log_File", FN_REFLEN));
field_list->push_back(
new Item_return_int("Relay_Log_Pos", 10, MYSQL_TYPE_LONGLONG));
field_list->push_back(
new Item_empty_string("Relay_Source_Log_File", FN_REFLEN));
field_list->push_back(new Item_empty_string("Replica_IO_Running", 3));
field_list->push_back(new Item_empty_string("Replica_SQL_Running", 3));
field_list->push_back(new Item_empty_string("Replicate_Do_DB", 20));
field_list->push_back(new Item_empty_string("Replicate_Ignore_DB", 20));
field_list->push_back(new Item_empty_string("Replicate_Do_Table", 20));
field_list->push_back(new Item_empty_string("Replicate_Ignore_Table", 23));
field_list->push_back(new Item_empty_string("Replicate_Wild_Do_Table", 24));
field_list->push_back(
new Item_empty_string("Replicate_Wild_Ignore_Table", 28));
field_list->push_back(new Item_return_int("Last_Errno", 4, MYSQL_TYPE_LONG));
field_list->push_back(new Item_empty_string("Last_Error", 20));
field_list->push_back(
new Item_return_int("Skip_Counter", 10, MYSQL_TYPE_LONG));
field_list->push_back(
new Item_return_int("Exec_Source_Log_Pos", 10, MYSQL_TYPE_LONGLONG));
field_list->push_back(
new Item_return_int("Relay_Log_Space", 10, MYSQL_TYPE_LONGLONG));
field_list->push_back(new Item_empty_string("Until_Condition", 6));
field_list->push_back(new Item_empty_string("Until_Log_File", FN_REFLEN));
field_list->push_back(
new Item_return_int("Until_Log_Pos", 10, MYSQL_TYPE_LONGLONG));
field_list->push_back(new Item_empty_string("Source_SSL_Allowed", 7));
field_list->push_back(new Item_empty_string("Source_SSL_CA_File", FN_REFLEN));
field_list->push_back(new Item_empty_string("Source_SSL_CA_Path", FN_REFLEN));
field_list->push_back(new Item_empty_string("Source_SSL_Cert", FN_REFLEN));
field_list->push_back(new Item_empty_string("Source_SSL_Cipher", FN_REFLEN));
field_list->push_back(new Item_empty_string("Source_SSL_Key", FN_REFLEN));
field_list->push_back(
new Item_return_int("Seconds_Behind_Source", 10, MYSQL_TYPE_LONGLONG));
field_list->push_back(
new Item_empty_string("Source_SSL_Verify_Server_Cert", 3));
field_list->push_back(
new Item_return_int("Last_IO_Errno", 4, MYSQL_TYPE_LONG));
field_list->push_back(new Item_empty_string("Last_IO_Error", 20));
field_list->push_back(
new Item_return_int("Last_SQL_Errno", 4, MYSQL_TYPE_LONG));
field_list->push_back(new Item_empty_string("Last_SQL_Error", 20));
field_list->push_back(
new Item_empty_string("Replicate_Ignore_Server_Ids", FN_REFLEN));
field_list->push_back(
new Item_return_int("Source_Server_Id", sizeof(ulong), MYSQL_TYPE_LONG));
field_list->push_back(new Item_empty_string("Source_UUID", UUID_LENGTH));
field_list->push_back(
new Item_empty_string("Source_Info_File", 2 * FN_REFLEN));
field_list->push_back(new Item_return_int("SQL_Delay", 10, MYSQL_TYPE_LONG));
field_list->push_back(
new Item_return_int("SQL_Remaining_Delay", 8, MYSQL_TYPE_LONG));
field_list->push_back(new Item_empty_string("Replica_SQL_Running_State", 20));
field_list->push_back(
new Item_return_int("Source_Retry_Count", 10, MYSQL_TYPE_LONGLONG));
field_list->push_back(
new Item_empty_string("Source_Bind", HOSTNAME_LENGTH + 1));
field_list->push_back(new Item_empty_string("Last_IO_Error_Timestamp", 20));
field_list->push_back(new Item_empty_string("Last_SQL_Error_Timestamp", 20));
field_list->push_back(new Item_empty_string("Source_SSL_Crl", FN_REFLEN));
field_list->push_back(new Item_empty_string("Source_SSL_Crlpath", FN_REFLEN));
field_list->push_back(
new Item_empty_string("Retrieved_Gtid_Set", io_gtid_set_size));
field_list->push_back(
new Item_empty_string("Executed_Gtid_Set", sql_gtid_set_size));
field_list->push_back(
new Item_return_int("Auto_Position", sizeof(ulong), MYSQL_TYPE_LONG));
field_list->push_back(new Item_empty_string("Replicate_Rewrite_DB", 24));
field_list->push_back(
new Item_empty_string("Channel_Name", CHANNEL_NAME_LENGTH));
field_list->push_back(new Item_empty_string("Source_TLS_Version", FN_REFLEN));
field_list->push_back(
new Item_empty_string("Source_public_key_path", FN_REFLEN));
field_list->push_back(new Item_return_int("Get_Source_public_key",
sizeof(ulong), MYSQL_TYPE_LONG));
field_list->push_back(
new Item_empty_string("Network_Namespace", NAME_LEN + 1));
}
/**
Send the data to the client of a Master_info during show_slave_status()
This function has to be called after calling show_slave_status_metadata().
Just before sending the data, thd->get_protocol() is prepared to (re)send;
@param[in] thd client thread
@param[in] mi the master info. In the case of multisource
replication, this master info corresponds to a
channel.
@param[in] io_gtid_set_buffer buffer related to Retrieved GTID set
for each channel.
@param[in] sql_gtid_set_buffer buffer related to Executed GTID set
for each channel.
@retval 0 success
@retval 1 Error
*/
static bool show_slave_status_send_data(THD *thd, Master_info *mi,
char *io_gtid_set_buffer,
char *sql_gtid_set_buffer) {
DBUG_TRACE;
Protocol *protocol = thd->get_protocol();
char *slave_sql_running_state = nullptr;
Rpl_filter *rpl_filter = mi->rli->rpl_filter;
DBUG_PRINT("info", ("host is set: '%s'", mi->host));
protocol->start_row();
/*
slave_running can be accessed without run_lock but not other
non-volatile members like mi->info_thd or rli->info_thd, for
them either info_thd_lock or run_lock hold is required.
*/
mysql_mutex_lock(&mi->info_thd_lock);
protocol->store(mi->info_thd ? mi->info_thd->proc_info_session(thd) : "",
&my_charset_bin);
mysql_mutex_unlock(&mi->info_thd_lock);
mysql_mutex_lock(&mi->rli->info_thd_lock);
slave_sql_running_state = const_cast<char *>(
mi->rli->info_thd ? mi->rli->info_thd->proc_info_session(thd) : "");
mysql_mutex_unlock(&mi->rli->info_thd_lock);
mysql_mutex_lock(&mi->data_lock);
mysql_mutex_lock(&mi->rli->data_lock);
mysql_mutex_lock(&mi->err_lock);
mysql_mutex_lock(&mi->rli->err_lock);
DEBUG_SYNC(thd, "wait_after_lock_active_mi_and_rli_data_lock_is_acquired");
protocol->store(mi->host, &my_charset_bin);
protocol->store(mi->get_user(), &my_charset_bin);
protocol->store((uint32)mi->port);
protocol->store((uint32)mi->connect_retry);
protocol->store(mi->get_master_log_name_info(), &my_charset_bin);
protocol->store((ulonglong)mi->get_master_log_pos_info());
protocol->store(mi->rli->get_group_relay_log_name() +
dirname_length(mi->rli->get_group_relay_log_name()),
&my_charset_bin);
protocol->store((ulonglong)mi->rli->get_group_relay_log_pos());
protocol->store(mi->rli->get_group_master_log_name_info(), &my_charset_bin);
protocol->store(
mi->slave_running == MYSQL_SLAVE_RUN_CONNECT
? "Yes"
: (mi->slave_running == MYSQL_SLAVE_RUN_NOT_CONNECT ? "Connecting"
: "No"),
&my_charset_bin);
protocol->store(mi->rli->slave_running ? "Yes" : "No", &my_charset_bin);
/*
Acquire the read lock, because the filter may be modified by
CHANGE REPLICATION FILTER when slave is not running.
*/
rpl_filter->rdlock();
store(protocol, rpl_filter->get_do_db());
store(protocol, rpl_filter->get_ignore_db());
char buf[256];
String tmp(buf, sizeof(buf), &my_charset_bin);
rpl_filter->get_do_table(&tmp);
protocol->store(&tmp);
rpl_filter->get_ignore_table(&tmp);
protocol->store(&tmp);
rpl_filter->get_wild_do_table(&tmp);
protocol->store(&tmp);
rpl_filter->get_wild_ignore_table(&tmp);
protocol->store(&tmp);
protocol->store(mi->rli->last_error().number);
protocol->store(mi->rli->last_error().message, &my_charset_bin);
protocol->store((uint32)mi->rli->slave_skip_counter);
protocol->store((ulonglong)mi->rli->get_group_master_log_pos_info());
protocol->store((ulonglong)mi->rli->log_space_total);
const char *until_type = "";
switch (mi->rli->until_condition) {
case Relay_log_info::UNTIL_NONE:
until_type = "None";
break;
case Relay_log_info::UNTIL_MASTER_POS:
if (thd->lex->is_replication_deprecated_syntax_used())
until_type = "Master";
else
until_type = "Source";
break;
case Relay_log_info::UNTIL_RELAY_POS:
until_type = "Relay";
break;
case Relay_log_info::UNTIL_SQL_BEFORE_GTIDS:
until_type = "SQL_BEFORE_GTIDS";
break;
case Relay_log_info::UNTIL_SQL_AFTER_GTIDS:
until_type = "SQL_AFTER_GTIDS";
break;
case Relay_log_info::UNTIL_SQL_VIEW_ID:
until_type = "SQL_VIEW_ID";
break;
case Relay_log_info::UNTIL_SQL_AFTER_MTS_GAPS:
until_type = "SQL_AFTER_MTS_GAPS";
break;
case Relay_log_info::UNTIL_DONE:
until_type = "DONE";
break;
default:
assert(0);
}
protocol->store(until_type, &my_charset_bin);
protocol->store(mi->rli->get_until_log_name(), &my_charset_bin);
protocol->store((ulonglong)mi->rli->get_until_log_pos());
protocol->store(mi->ssl ? "Yes" : "No", &my_charset_bin);
protocol->store(mi->ssl_ca, &my_charset_bin);
protocol->store(mi->ssl_capath, &my_charset_bin);
protocol->store(mi->ssl_cert, &my_charset_bin);
protocol->store(mi->ssl_cipher, &my_charset_bin);
protocol->store(mi->ssl_key, &my_charset_bin);
/*
The pseudo code to compute Seconds_Behind_Master:
if (SQL thread is running)
{
if (SQL thread processed all the available relay log)
{
if (IO thread is running)
print 0;
else
print NULL;
}
else
compute Seconds_Behind_Master;
}
else
print NULL;
*/
if (mi->rli->slave_running) {
/*
Check if SQL thread is at the end of relay log
Checking should be done using two conditions
condition1: compare the log positions and
condition2: compare the file names (to handle rotation case)
*/
if ((mi->get_master_log_pos() == mi->rli->get_group_master_log_pos()) &&
(!strcmp(mi->get_master_log_name(),
mi->rli->get_group_master_log_name()))) {
if (mi->slave_running == MYSQL_SLAVE_RUN_CONNECT)
protocol->store(0LL);
else
protocol->store_null();
} else {
long time_diff = ((long)(time(nullptr) - mi->rli->last_master_timestamp) -
mi->clock_diff_with_master);
/*
Apparently on some systems time_diff can be <0. Here are possible
reasons related to MySQL:
- the master is itself a slave of another master whose time is ahead.
- somebody used an explicit SET TIMESTAMP on the master.
Possible reason related to granularity-to-second of time functions
(nothing to do with MySQL), which can explain a value of -1:
assume the master's and slave's time are perfectly synchronized, and
that at slave's connection time, when the master's timestamp is read,
it is at the very end of second 1, and (a very short time later) when
the slave's timestamp is read it is at the very beginning of second
2. Then the recorded value for master is 1 and the recorded value for
slave is 2. At SHOW REPLICA STATUS time, assume that the difference
between timestamp of slave and rli->last_master_timestamp is 0
(i.e. they are in the same second), then we get 0-(2-1)=-1 as a result.
This confuses users, so we don't go below 0: hence the max().
last_master_timestamp == 0 (an "impossible" timestamp 1970) is a
special marker to say "consider we have caught up".
*/
protocol->store(
(longlong)(mi->rli->last_master_timestamp ? max(0L, time_diff) : 0));
}
} else {
protocol->store_null();
}
protocol->store(mi->ssl_verify_server_cert ? "Yes" : "No", &my_charset_bin);
// Last_IO_Errno
protocol->store(mi->last_error().number);
// Last_IO_Error
protocol->store(mi->last_error().message, &my_charset_bin);
// Last_SQL_Errno
protocol->store(mi->rli->last_error().number);
// Last_SQL_Error
protocol->store(mi->rli->last_error().message, &my_charset_bin);
// Replicate_Ignore_Server_Ids
{
char buff[FN_REFLEN];
ulong i, cur_len;
for (i = 0, buff[0] = 0, cur_len = 0;
i < mi->ignore_server_ids->dynamic_ids.size(); i++) {
ulong s_id, slen;
char sbuff[FN_REFLEN];
s_id = mi->ignore_server_ids->dynamic_ids[i];
slen = sprintf(sbuff, (i == 0 ? "%lu" : ", %lu"), s_id);
if (cur_len + slen + 4 > FN_REFLEN) {
/*
break the loop whenever remained space could not fit
ellipses on the next cycle
*/
sprintf(buff + cur_len, "...");
break;
}
cur_len += sprintf(buff + cur_len, "%s", sbuff);
}
protocol->store(buff, &my_charset_bin);
}
// Master_Server_id
protocol->store((uint32)mi->master_id);
protocol->store(mi->master_uuid, &my_charset_bin);
// Master_Info_File
protocol->store(mi->get_description_info(), &my_charset_bin);
// SQL_Delay
protocol->store((uint32)mi->rli->get_sql_delay());
// SQL_Remaining_Delay
if (slave_sql_running_state == stage_sql_thd_waiting_until_delay.m_name) {
time_t t = time(nullptr), sql_delay_end = mi->rli->get_sql_delay_end();
protocol->store((uint32)(t < sql_delay_end ? sql_delay_end - t : 0));
} else
protocol->store_null();
// Slave_SQL_Running_State
protocol->store(slave_sql_running_state, &my_charset_bin);
// Master_Retry_Count
protocol->store((ulonglong)mi->retry_count);
// Master_Bind
protocol->store(mi->bind_addr, &my_charset_bin);
// Last_IO_Error_Timestamp
protocol->store(mi->last_error().timestamp, &my_charset_bin);
// Last_SQL_Error_Timestamp
protocol->store(mi->rli->last_error().timestamp, &my_charset_bin);
// Master_Ssl_Crl
protocol->store(mi->ssl_crl, &my_charset_bin);
// Master_Ssl_Crlpath
protocol->store(mi->ssl_crlpath, &my_charset_bin);
// Retrieved_Gtid_Set
protocol->store(io_gtid_set_buffer, &my_charset_bin);
// Executed_Gtid_Set
protocol->store(sql_gtid_set_buffer, &my_charset_bin);
// Auto_Position
protocol->store(mi->is_auto_position() ? 1 : 0);
// Replicate_Rewrite_DB
rpl_filter->get_rewrite_db(&tmp);
protocol->store(&tmp);
// channel_name
protocol->store(mi->get_channel(), &my_charset_bin);
// Master_TLS_Version
protocol->store(mi->tls_version, &my_charset_bin);
// Master_public_key_path
protocol->store(mi->public_key_path, &my_charset_bin);
// Get_master_public_key
protocol->store(mi->get_public_key ? 1 : 0);
protocol->store(mi->network_namespace_str(), &my_charset_bin);
rpl_filter->unlock();
mysql_mutex_unlock(&mi->rli->err_lock);
mysql_mutex_unlock(&mi->err_lock);
mysql_mutex_unlock(&mi->rli->data_lock);
mysql_mutex_unlock(&mi->data_lock);
return false;
}
/**
Method to the show the replication status in all channels.
@param[in] thd the client thread
@retval 0 success
@retval 1 Error
*/
bool show_slave_status(THD *thd) {
Protocol *protocol = thd->get_protocol();
int sql_gtid_set_size = 0, io_gtid_set_size = 0;
Master_info *mi = nullptr;
char *sql_gtid_set_buffer = nullptr;
char **io_gtid_set_buffer_array;
/*
We need the maximum size of the retrieved gtid set (i.e io_gtid_set_size).
This size is needed to reserve the place in show_slave_status_metadata().
So, we travel all the mi's and find out the maximum size of io_gtid_set_size
and pass it through show_slave_status_metadata()
*/
int max_io_gtid_set_size = io_gtid_set_size;
uint idx;
uint num_io_gtid_sets;
bool ret = true;
DBUG_TRACE;
channel_map.assert_some_lock();
num_io_gtid_sets = channel_map.get_num_instances();
io_gtid_set_buffer_array =
(char **)my_malloc(key_memory_show_replica_status_io_gtid_set,
num_io_gtid_sets * sizeof(char *), MYF(MY_WME));
if (io_gtid_set_buffer_array == nullptr) return true;
global_sid_lock->wrlock();
const Gtid_set *sql_gtid_set = gtid_state->get_executed_gtids();
sql_gtid_set_size = sql_gtid_set->to_string(&sql_gtid_set_buffer);
global_sid_lock->unlock();
idx = 0;
for (mi_map::iterator it = channel_map.begin(); it != channel_map.end();
it++) {
mi = it->second;
/*
The following statement is needed because, when mi->host[0]=0
we don't alloc memory for retried_gtid_set. However, we try
to free it at the end, causing a crash. To be on safeside,
we initialize it to NULL, so that my_free() takes care of it.
*/
io_gtid_set_buffer_array[idx] = nullptr;
if (Master_info::is_configured(mi)) {
const Gtid_set *io_gtid_set = mi->rli->get_gtid_set();
mi->rli->get_sid_lock()->wrlock();
/*
@todo: a single memory allocation improves speed,
instead of doing it for each loop
*/
if ((io_gtid_set_size =
io_gtid_set->to_string(&io_gtid_set_buffer_array[idx])) < 0) {
my_eof(thd);
my_free(sql_gtid_set_buffer);
for (uint i = 0; i < idx - 1; i++) {
my_free(io_gtid_set_buffer_array[i]);
}
my_free(io_gtid_set_buffer_array);
mi->rli->get_sid_lock()->unlock();
return true;
} else
max_io_gtid_set_size = max_io_gtid_set_size > io_gtid_set_size
? max_io_gtid_set_size
: io_gtid_set_size;
mi->rli->get_sid_lock()->unlock();
}
idx++;
}
mem_root_deque<Item *> field_list(thd->mem_root);
show_slave_status_metadata(&field_list, max_io_gtid_set_size,
sql_gtid_set_size);
// TODO: once the old syntax is removed, remove this as well.
if (thd->lex->is_replication_deprecated_syntax_used())
rename_fields_use_old_replica_source_terms(thd, field_list);
if (thd->send_result_metadata(field_list,
Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) {
goto err;
}
/* Run through each mi */
idx = 0;
for (mi_map::iterator it = channel_map.begin(); it != channel_map.end();
it++) {
mi = it->second;
if (Master_info::is_configured(mi)) {
if (show_slave_status_send_data(thd, mi, io_gtid_set_buffer_array[idx],
sql_gtid_set_buffer))
goto err;
if (protocol->end_row()) goto err;
}
idx++;
}
ret = false;
err:
my_eof(thd);
for (uint i = 0; i < num_io_gtid_sets; i++) {
my_free(io_gtid_set_buffer_array[i]);
}
my_free(io_gtid_set_buffer_array);
my_free(sql_gtid_set_buffer);
return ret;
}
/**
Execute a SHOW REPLICA STATUS statement.
@param thd Pointer to THD object for the client thread executing the
statement.
@param mi Pointer to Master_info object for the IO thread.
@retval false success
@retval true failure
Currently, show slave status works for a channel too, in multisource
replication. But using performance schema tables is better.
*/
bool show_slave_status(THD *thd, Master_info *mi) {
Protocol *protocol = thd->get_protocol();
char *sql_gtid_set_buffer = nullptr, *io_gtid_set_buffer = nullptr;
int sql_gtid_set_size = 0, io_gtid_set_size = 0;
DBUG_TRACE;
if (mi != nullptr) {
global_sid_lock->wrlock();
const Gtid_set *sql_gtid_set = gtid_state->get_executed_gtids();
sql_gtid_set_size = sql_gtid_set->to_string(&sql_gtid_set_buffer);
global_sid_lock->unlock();
mi->rli->get_sid_lock()->wrlock();
const Gtid_set *io_gtid_set = mi->rli->get_gtid_set();
io_gtid_set_size = io_gtid_set->to_string(&io_gtid_set_buffer);
mi->rli->get_sid_lock()->unlock();
if (sql_gtid_set_size < 0 || io_gtid_set_size < 0) {
my_eof(thd);
my_free(sql_gtid_set_buffer);
my_free(io_gtid_set_buffer);
return true;
}
}
/* Fill the metadata required for show slave status. */
mem_root_deque<Item *> field_list(thd->mem_root);
show_slave_status_metadata(&field_list, io_gtid_set_size, sql_gtid_set_size);
// TODO: once the old syntax is removed, remove this as well.
if (thd->lex->is_replication_deprecated_syntax_used())
rename_fields_use_old_replica_source_terms(thd, field_list);
if (thd->send_result_metadata(field_list,
Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) {
my_free(sql_gtid_set_buffer);
my_free(io_gtid_set_buffer);
return true;
}
if (Master_info::is_configured(mi)) {
if (show_slave_status_send_data(thd, mi, io_gtid_set_buffer,
sql_gtid_set_buffer))
return true;
if (protocol->end_row()) {
my_free(sql_gtid_set_buffer);
my_free(io_gtid_set_buffer);
return true;
}
}
my_eof(thd);
my_free(sql_gtid_set_buffer);
my_free(io_gtid_set_buffer);
return false;
}
/**
Entry point for SHOW REPLICA STATUS command. Function displays
the slave status for all channels or for a single channel
based on the FOR CHANNEL clause.
@param[in] thd the client thread.
@retval false ok
@retval true not ok
*/
bool show_slave_status_cmd(THD *thd) {
Master_info *mi = nullptr;
LEX *lex = thd->lex;
bool res;
DBUG_TRACE;
channel_map.rdlock();
if (!lex->mi.for_channel)
res = show_slave_status(thd);
else {
mi = channel_map.get_mi(lex->mi.channel);
/*
When mi is NULL, that means the channel doesn't exist, SSS
will throw an error.
*/
if (mi == nullptr) {
my_error(ER_REPLICA_CHANNEL_DOES_NOT_EXIST, MYF(0), lex->mi.channel);
channel_map.unlock();
return true;
}
/*
If the channel being used is a group replication applier channel we
need to disable the SHOW REPLICA STATUS command as its output is not
compatible with this command.
*/
if (channel_map.is_group_replication_channel_name(mi->get_channel(),
true)) {
my_error(ER_REPLICA_CHANNEL_OPERATION_NOT_ALLOWED, MYF(0),
"SHOW REPLICA STATUS", mi->get_channel());
channel_map.unlock();
return true;
}
res = show_slave_status(thd, mi);
}
channel_map.unlock();
return res;
}
void set_slave_thread_options(THD *thd) {
DBUG_TRACE;
/*
It's nonsense to constrain the slave threads with max_join_size; if a
query succeeded on master, we HAVE to execute it. So set
OPTION_BIG_SELECTS. Setting max_join_size to HA_POS_ERROR is not enough
(and it's not needed if we have OPTION_BIG_SELECTS) because an INSERT
SELECT examining more than 4 billion rows would still fail (yes, because
when max_join_size is 4G, OPTION_BIG_SELECTS is automatically set, but
only for client threads.
*/
ulonglong options = thd->variables.option_bits | OPTION_BIG_SELECTS;
if (opt_log_replica_updates)
options |= OPTION_BIN_LOG;
else
options &= ~OPTION_BIN_LOG;
thd->variables.option_bits = options;
thd->variables.completion_type = 0;
/* Do not track GTIDs for slave threads to avoid performance issues. */
thd->variables.session_track_gtids = SESSION_TRACK_GTIDS_OFF;
thd->rpl_thd_ctx.session_gtids_ctx()
.update_tracking_activeness_from_session_variable(thd);
/*
Set autocommit= 1 when info tables are used and autocommit == 0 to
avoid trigger asserts on mysql_execute_command(THD *thd) caused by
info tables updates which do not commit, like Rotate, Stop and
skipped events handling.
*/
if ((thd->variables.option_bits & OPTION_NOT_AUTOCOMMIT) &&
(opt_mi_repository_id == INFO_REPOSITORY_TABLE ||
opt_rli_repository_id == INFO_REPOSITORY_TABLE)) {
thd->variables.option_bits |= OPTION_AUTOCOMMIT;
thd->variables.option_bits &= ~OPTION_NOT_AUTOCOMMIT;
thd->server_status |= SERVER_STATUS_AUTOCOMMIT;
}
/*
Set thread InnoDB high priority.
*/
DBUG_EXECUTE_IF("dbug_set_high_prio_sql_thread", {
if (thd->system_thread == SYSTEM_THREAD_SLAVE_SQL ||
thd->system_thread == SYSTEM_THREAD_SLAVE_WORKER)
thd->thd_tx_priority = 1;
});
}
void set_slave_thread_default_charset(THD *thd, Relay_log_info const *rli) {
DBUG_TRACE;
thd->variables.character_set_client =
global_system_variables.character_set_client;
thd->variables.collation_connection =
global_system_variables.collation_connection;
thd->variables.collation_server = global_system_variables.collation_server;
thd->update_charset();
/*
We use a const cast here since the conceptual (and externally
visible) behavior of the function is to set the default charset of
the thread. That the cache has to be invalidated is a secondary
effect.
*/
const_cast<Relay_log_info *>(rli)->cached_charset_invalidate();
}
/*
init_replica_thread()
*/
int init_replica_thread(THD *thd, SLAVE_THD_TYPE thd_type) {
DBUG_TRACE;
#if !defined(NDEBUG)
int simulate_error = 0;
#endif
thd->system_thread = (thd_type == SLAVE_THD_WORKER)
? SYSTEM_THREAD_SLAVE_WORKER
: (thd_type == SLAVE_THD_SQL) ? SYSTEM_THREAD_SLAVE_SQL
: SYSTEM_THREAD_SLAVE_IO;
thd->get_protocol_classic()->init_net(nullptr);
thd->slave_thread = true;
thd->enable_slow_log = opt_log_slow_replica_statements;
set_slave_thread_options(thd);
/*
Replication threads are:
- background threads in the server, not user sessions,
- yet still assigned a PROCESSLIST_ID,
for historical reasons (displayed in SHOW PROCESSLIST).
*/
thd->set_new_thread_id();
#ifdef HAVE_PSI_THREAD_INTERFACE
/*
Populate the PROCESSLIST_ID in the instrumentation.
*/
struct PSI_thread *psi = PSI_THREAD_CALL(get_thread)();
PSI_THREAD_CALL(set_thread_id)(psi, thd->thread_id());
#endif /* HAVE_PSI_THREAD_INTERFACE */
DBUG_EXECUTE_IF("simulate_io_replica_error_on_init",
simulate_error |= (1 << SLAVE_THD_IO););
DBUG_EXECUTE_IF("simulate_sql_replica_error_on_init",
simulate_error |= (1 << SLAVE_THD_SQL););
thd->store_globals();
#if !defined(NDEBUG)
if (simulate_error & (1 << thd_type)) {
return -1;
}
#endif
if (thd_type == SLAVE_THD_SQL) {
THD_STAGE_INFO(thd, stage_waiting_for_the_next_event_in_relay_log);
thd->set_command(
COM_QUERY); // the SQL thread does not use the server protocol
} else {
THD_STAGE_INFO(thd, stage_waiting_for_source_update);
}
thd->set_time();
/* Do not use user-supplied timeout value for system threads. */
thd->variables.lock_wait_timeout = LONG_TIMEOUT;
return 0;
}
/**
Sleep for a given amount of time or until killed.
@param thd Thread context of the current thread.
@param seconds The number of seconds to sleep.
@param func Function object to check if the thread has been killed.
@param info The Rpl_info object associated with this sleep.
@retval True if the thread has been killed, false otherwise.
*/
template <typename killed_func, typename rpl_info>
static inline bool slave_sleep(THD *thd, time_t seconds, killed_func func,
rpl_info info) {
bool ret;
struct timespec abstime;
mysql_mutex_t *lock = &info->sleep_lock;
mysql_cond_t *cond = &info->sleep_cond;
/* Absolute system time at which the sleep time expires. */
set_timespec(&abstime, seconds);
mysql_mutex_lock(lock);
thd->ENTER_COND(cond, lock, nullptr, nullptr);
while (!(ret = func(thd, info))) {
int error = mysql_cond_timedwait(cond, lock, &abstime);
if (is_timeout(error)) break;
}
mysql_mutex_unlock(lock);
thd->EXIT_COND(nullptr);
return ret;
}
/**
Callback function for mysql_binlog_open().
Sets gtid data in the command packet.
@param rpl Replication stream information.
@param packet_gtid_set Pointer to command packet where gtid
data should be stored.
*/
static void fix_gtid_set(MYSQL_RPL *rpl, uchar *packet_gtid_set) {
Gtid_set *gtid_set = (Gtid_set *)rpl->gtid_set_arg;
gtid_set->encode(packet_gtid_set);
}
static int request_dump(THD *thd, MYSQL *mysql, MYSQL_RPL *rpl, Master_info *mi,
bool *suppress_warnings) {
DBUG_TRACE;
enum_server_command command =
mi->is_auto_position() ? COM_BINLOG_DUMP_GTID : COM_BINLOG_DUMP;
/*
Note: binlog_flags is always 0. However, in versions up to 5.6
RC, the master would check the lowest bit and do something
unexpected if it was set; in early versions of 5.6 it would also
use the two next bits. Therefore, for backward compatibility,
if we ever start to use the flags, we should leave the three
lowest bits unused.
*/
uint binlog_flags = 0;
binlog_flags |= USE_HEARTBEAT_EVENT_V2;
*suppress_warnings = false;
if (RUN_HOOK(binlog_relay_io, before_request_transmit,
(thd, mi, binlog_flags)))
return 1;
rpl->server_id = server_id;
rpl->flags = binlog_flags;
Sid_map sid_map(nullptr); /* No lock needed */
/*
Note: should be declared at the same level as the mysql_binlog_open() call,
as the latter might call fix_gtid_set() which in turns calls
gtid_executed->encode().
*/
Gtid_set gtid_executed(&sid_map);
if (command == COM_BINLOG_DUMP_GTID) {
// get set of GTIDs
mi->rli->get_sid_lock()->wrlock();
if (gtid_executed.add_gtid_set(mi->rli->get_gtid_set()) !=
RETURN_STATUS_OK) {
mi->rli->get_sid_lock()->unlock();
return 1;
}
mi->rli->get_sid_lock()->unlock();
global_sid_lock->wrlock();
gtid_state->dbug_print();
if (gtid_executed.add_gtid_set(gtid_state->get_executed_gtids()) !=
RETURN_STATUS_OK) {
global_sid_lock->unlock();
return 1;
}
global_sid_lock->unlock();
rpl->file_name = nullptr; /* No need to set rpl.file_name_length */
rpl->start_position = 4;
rpl->flags |= MYSQL_RPL_GTID;
rpl->gtid_set_encoded_size = gtid_executed.get_encoded_length();
rpl->fix_gtid_set = fix_gtid_set;
rpl->gtid_set_arg = (void *)>id_executed;
} else {
rpl->file_name_length = 0;
rpl->file_name = mi->get_master_log_name();
rpl->start_position = DBUG_EVALUATE_IF("request_source_log_pos_3", 3,
mi->get_master_log_pos());
}
if (mysql_binlog_open(mysql, rpl)) {
/*
Something went wrong, so we will just reconnect and retry later
in the future, we should do a better error analysis, but for
now we just fill up the error log :-)
*/
uint err{mysql_errno(mysql)};
if (err == ER_NET_READ_INTERRUPTED)
*suppress_warnings = true; // Suppress reconnect warning
else
LogErr(ERROR_LEVEL, ER_RPL_REPLICA_ERROR_RETRYING,
Command_names::str_global(command).c_str(), err,
mysql_error(mysql), mi->connect_retry);
if (is_network_error(err)) mi->set_network_error();
return 1;
}
return 0;
}
/**
Read one event from the master.
@param mysql MySQL connection.
@param rpl Replication stream information.
@param mi Master connection information.
@param suppress_warnings true when a normal net read timeout has caused us
to try a reconnect. We do not want to print
anything to the error log in this case because
this an abnormal event in an idle server.
@retval 'packet_error' Error.
@retval number Length of packet.
*/
static ulong read_event(MYSQL *mysql, MYSQL_RPL *rpl, Master_info *mi,
bool *suppress_warnings) {
DBUG_TRACE;
*suppress_warnings = false;
/*
my_real_read() will time us out
We check if we were told to die, and if not, try reading again
*/
#ifndef NDEBUG
if (disconnect_slave_event_count && !(mi->events_until_exit--))
return packet_error;
#endif
if (mysql_binlog_fetch(mysql, rpl)) {
uint err{mysql_errno(mysql)};
if (err == ER_NET_READ_INTERRUPTED) {
/*
We are trying a normal reconnect after a read timeout;
we suppress prints to .err file as long as the reconnect
happens without problems
*/
*suppress_warnings = true;
} else if (!mi->abort_slave) {
LogErr(ERROR_LEVEL, ER_RPL_REPLICA_ERROR_READING_FROM_SERVER,
mi->get_for_channel_str(), mysql_error(mysql), err);
}
if (is_network_error(err)) mi->set_network_error();
return packet_error;
}
/* Check if eof packet */
if (rpl->size == 0) {
LogErr(SYSTEM_LEVEL, ER_RPL_REPLICA_DUMP_THREAD_KILLED_BY_SOURCE,
mi->get_for_channel_str(), ::server_uuid, mysql_error(mysql));
return packet_error;
}
DBUG_PRINT("exit", ("len: %lu net->read_pos[4]: %d", rpl->size,
mysql->net.read_pos[4]));
return rpl->size - 1;
}
/**
If this is a lagging slave (specified with CHANGE MASTER TO MASTER_DELAY = X),
delays accordingly. Also unlocks rli->data_lock.
Design note: this is the place to unlock rli->data_lock. The lock
must be held when reading delay info from rli, but it should not be
held while sleeping.
@param ev Event that is about to be executed.
@param thd The sql thread's THD object.
@param rli The sql thread's Relay_log_info structure.
@retval 0 If the delay timed out and the event shall be executed.
@retval nonzero If the delay was interrupted and the event shall be skipped.
*/
static int sql_delay_event(Log_event *ev, THD *thd, Relay_log_info *rli) {
time_t sql_delay = rli->get_sql_delay();
DBUG_TRACE;
mysql_mutex_assert_owner(&rli->data_lock);
assert(!rli->belongs_to_client());
if (sql_delay) {
int type = ev->get_type_code();
time_t sql_delay_end = 0;
if (rli->commit_timestamps_status == Relay_log_info::COMMIT_TS_UNKNOWN &&
(type == binary_log::GTID_LOG_EVENT ||
type == binary_log::ANONYMOUS_GTID_LOG_EVENT)) {
if (static_cast<Gtid_log_event *>(ev)->has_commit_timestamps &&
DBUG_EVALUATE_IF("sql_delay_without_timestamps", 0, 1)) {
rli->commit_timestamps_status = Relay_log_info::COMMIT_TS_FOUND;
} else {
rli->commit_timestamps_status = Relay_log_info::COMMIT_TS_NOT_FOUND;
}
}
if (rli->commit_timestamps_status == Relay_log_info::COMMIT_TS_FOUND) {
if (type == binary_log::GTID_LOG_EVENT ||
type == binary_log::ANONYMOUS_GTID_LOG_EVENT) {
/*
Calculate when we should execute the event.
The immediate master timestamp is expressed in microseconds.
Delayed replication is defined in seconds.
Hence convert immediate_commit_timestamp to seconds here.
*/
sql_delay_end = ceil((static_cast<Gtid_log_event *>(ev)
->immediate_commit_timestamp) /
1000000.00) +
sql_delay;
}
} else {
/*
the immediate master does not support commit timestamps
in Gtid_log_events
*/
if (type != binary_log::ROTATE_EVENT &&
type != binary_log::FORMAT_DESCRIPTION_EVENT &&
type != binary_log::PREVIOUS_GTIDS_LOG_EVENT) {
// Calculate when we should execute the event.
sql_delay_end = ev->common_header->when.tv_sec +
rli->mi->clock_diff_with_master + sql_delay;
}
}
if (sql_delay_end != 0) {
// The current time.
time_t now = time(nullptr);
// The amount of time we will have to sleep before executing the event.
time_t nap_time = 0;
if (sql_delay_end > now) {
nap_time = sql_delay_end - now;
DBUG_PRINT("info",
("sql_delay= %lu "
"now= %ld "
"sql_delay_end= %ld "
"nap_time= %ld",
sql_delay, (long)now, (long)sql_delay_end, (long)nap_time));
DBUG_PRINT("info", ("delaying replication event %lu secs", nap_time));
rli->start_sql_delay(sql_delay_end);
mysql_mutex_unlock(&rli->data_lock);
return slave_sleep(thd, nap_time, sql_slave_killed, rli);
} else {
DBUG_PRINT("info", ("sql_delay= %lu "
"now= %ld "
"sql_delay_end= %ld ",
sql_delay, (long)now, (long)sql_delay_end));
}
}
}
mysql_mutex_unlock(&rli->data_lock);
return 0;
}
/**
Applies the given event and advances the relay log position.
This is needed by the sql thread to execute events from the binlog,
and by clients executing BINLOG statements. Conceptually, this
function does:
@code
ev->apply_event(rli);
ev->update_pos(rli);
@endcode
It also does the following maintenance:
- Initializes the thread's server_id and time; and the event's
thread.
- If !rli->belongs_to_client() (i.e., if it belongs to the slave
sql thread instead of being used for executing BINLOG
statements), it does the following things: (1) skips events if it
is needed according to the server id or slave_skip_counter; (2)
unlocks rli->data_lock; (3) sleeps if required by 'CHANGE MASTER
TO MASTER_DELAY=X'; (4) maintains the running state of the sql
thread (rli->thread_state).
- Reports errors as needed.
@param ptr_ev a pointer to a reference to the event to apply.
@param thd The client thread that executes the event (i.e., the
slave sql thread if called from a replication slave, or the client
thread if called to execute a BINLOG statement).
@param rli The relay log info (i.e., the slave's rli if called from
a replication slave, or the client's thd->rli_fake if called to
execute a BINLOG statement).
@note MTS can store NULL to @c ptr_ev location to indicate
the event is taken over by a Worker.
@retval SLAVE_APPLY_EVENT_AND_UPDATE_POS_OK
OK.
@retval SLAVE_APPLY_EVENT_AND_UPDATE_POS_APPLY_ERROR
Error calling ev->apply_event().
@retval SLAVE_APPLY_EVENT_AND_UPDATE_POS_UPDATE_POS_ERROR
No error calling ev->apply_event(), but error calling
ev->update_pos().
@retval SLAVE_APPLY_EVENT_AND_UPDATE_POS_APPEND_JOB_ERROR
append_item_to_jobs() failed, thread was killed while waiting
for successful enqueue on worker.
*/
static enum enum_slave_apply_event_and_update_pos_retval
apply_event_and_update_pos(Log_event **ptr_ev, THD *thd, Relay_log_info *rli) {
int exec_res = 0;
bool skip_event = false;
Log_event *ev = *ptr_ev;
Log_event::enum_skip_reason reason = Log_event::EVENT_SKIP_NOT;
DBUG_TRACE;
DBUG_PRINT("exec_event",
("%s(type_code: %d; server_id: %d)", ev->get_type_str(),
ev->get_type_code(), ev->server_id));
DBUG_PRINT("info",
("thd->options: %s%s; rli->last_event_start_time: %lu",
FLAGSTR(thd->variables.option_bits, OPTION_NOT_AUTOCOMMIT),
FLAGSTR(thd->variables.option_bits, OPTION_BEGIN),
(ulong)rli->last_event_start_time));
/*
Execute the event to change the database and update the binary
log coordinates, but first we set some data that is needed for
the thread.
The event will be executed unless it is supposed to be skipped.
Queries originating from this server must be skipped. Low-level
events (Format_description_log_event, Rotate_log_event,
Stop_log_event) from this server must also be skipped. But for
those we don't want to modify 'group_master_log_pos', because
these events did not exist on the master.
Format_description_log_event is not completely skipped.
Skip queries specified by the user in 'slave_skip_counter'. We
can't however skip events that has something to do with the log
files themselves.
Filtering on own server id is extremely important, to ignore
execution of events created by the creation/rotation of the relay
log (remember that now the relay log starts with its Format_desc,
has a Rotate etc).
*/
/*
Set the unmasked and actual server ids from the event
*/
thd->server_id = ev->server_id; // use the original server id for logging
thd->unmasked_server_id = ev->common_header->unmasked_server_id;
thd->set_time(); // time the query
thd->lex->set_current_query_block(nullptr);
if (!ev->common_header->when.tv_sec)
my_micro_time_to_timeval(my_micro_time(), &ev->common_header->when);
ev->thd = thd; // because up to this point, ev->thd == 0
if (!(rli->is_mts_recovery() &&
bitmap_is_set(&rli->recovery_groups, rli->mts_recovery_index))) {
reason = ev->shall_skip(rli);
}
#ifndef NDEBUG
if (rli->is_mts_recovery()) {
DBUG_PRINT("mta",
("Mta is recovering %d, number of bits set %d, "
"bitmap is set %d, index %lu.\n",
rli->is_mts_recovery(), bitmap_bits_set(&rli->recovery_groups),
bitmap_is_set(&rli->recovery_groups, rli->mts_recovery_index),
rli->mts_recovery_index));
}
#endif
if (reason == Log_event::EVENT_SKIP_COUNT) {
--rli->slave_skip_counter;
skip_event = true;
}
set_timespec_nsec(&rli->ts_exec[0], 0);
rli->stats_read_time += diff_timespec(&rli->ts_exec[0], &rli->ts_exec[1]);
if (reason == Log_event::EVENT_SKIP_NOT) {
// Sleeps if needed, and unlocks rli->data_lock.
if (sql_delay_event(ev, thd, rli))
return SLAVE_APPLY_EVENT_AND_UPDATE_POS_OK;
// Setting positions for STA. Worker positions are set on
// slave_worker_exec_job_group
rli->set_group_source_log_start_end_pos(ev);
exec_res = ev->apply_event(rli);
DBUG_EXECUTE_IF("simulate_stop_when_mta_in_group",
if (rli->mts_group_status == Relay_log_info::MTS_IN_GROUP &&
rli->curr_group_seen_begin)
DBUG_SET("+d,stop_when_mta_in_group"););
if (!exec_res && (ev->worker != rli)) {
if (ev->worker) {
Slave_job_item item = {ev, rli->get_event_start_pos(), {'\0'}};
if (rli->get_event_relay_log_name())
strcpy(item.event_relay_log_name, rli->get_event_relay_log_name());
Slave_job_item *job_item = &item;
Slave_worker *w = (Slave_worker *)ev->worker;
// specially marked group typically with OVER_MAX_DBS_IN_EVENT_MTS db:s
bool need_sync = ev->is_mts_group_isolated();
// all events except BEGIN-query must be marked with a non-NULL Worker
assert(((Slave_worker *)ev->worker) == rli->last_assigned_worker);
DBUG_PRINT("Log_event::apply_event:",
("-> job item data %p to W_%lu", job_item->data, w->id));
// Reset mts in-group state
if (rli->mts_group_status == Relay_log_info::MTS_END_GROUP) {
// CGAP cleanup
rli->curr_group_assigned_parts.clear();
// reset the B-group and Gtid-group marker
rli->curr_group_seen_begin = rli->curr_group_seen_gtid = false;
rli->last_assigned_worker = nullptr;
}
/*
Storing GAQ index of the group that the event belongs to
in the event. Deferred events are handled similarly below.
*/
ev->mts_group_idx = rli->gaq->assigned_group_index;
bool append_item_to_jobs_error = false;
if (rli->curr_group_da.size() > 0) {
/*
the current event sorted out which partition the current group
belongs to. It's time now to processed deferred array events.
*/
for (uint i = 0; i < rli->curr_group_da.size(); i++) {
Slave_job_item da_item = rli->curr_group_da[i];
DBUG_PRINT("mta", ("Assigning job %llu to worker %lu",
(da_item.data)->common_header->log_pos, w->id));
da_item.data->mts_group_idx =
rli->gaq->assigned_group_index; // similarly to above
if (!append_item_to_jobs_error)
append_item_to_jobs_error = append_item_to_jobs(&da_item, w, rli);
if (append_item_to_jobs_error) delete da_item.data;
}
rli->curr_group_da.clear();
}
if (append_item_to_jobs_error)
return SLAVE_APPLY_EVENT_AND_UPDATE_POS_APPEND_JOB_ERROR;
DBUG_PRINT("mta", ("Assigning job %llu to worker %lu\n",
job_item->data->common_header->log_pos, w->id));
/* Notice `ev' instance can be destroyed after `append()' */
if (append_item_to_jobs(job_item, w, rli))
return SLAVE_APPLY_EVENT_AND_UPDATE_POS_APPEND_JOB_ERROR;
if (need_sync) {
/*
combination of over-max db:s and end of the current group
forces to wait for the assigned groups completion by assigned
to the event worker.
Indeed MTS group status could be safely set to MTS_NOT_IN_GROUP
after wait_() returns.
No need to know a possible error out of synchronization call.
*/
(void)rli->current_mts_submode->wait_for_workers_to_finish(rli);
}
}
*ptr_ev = nullptr; // announcing the event is passed to w-worker
if (rli->is_parallel_exec() && rli->mts_events_assigned % 1024 == 1) {
time_t my_now = time(nullptr);
if ((my_now - rli->mts_last_online_stat) >= mts_online_stat_period) {
LogErr(INFORMATION_LEVEL, ER_RPL_MTA_STATISTICS,
rli->get_for_channel_str(),
static_cast<unsigned long>(my_now - rli->mts_last_online_stat),
rli->mts_events_assigned, rli->mts_wq_overrun_cnt,
rli->mts_wq_overfill_cnt, rli->wq_size_waits_cnt,
rli->mts_total_wait_overlap.load(),
rli->mts_wq_no_underrun_cnt, rli->mts_total_wait_worker_avail);
rli->mts_last_online_stat = my_now;
}
}
}
} else
mysql_mutex_unlock(&rli->data_lock);
set_timespec_nsec(&rli->ts_exec[1], 0);
rli->stats_exec_time += diff_timespec(&rli->ts_exec[1], &rli->ts_exec[0]);
DBUG_PRINT("info", ("apply_event error = %d", exec_res));
if (exec_res == 0) {
/*
Positions are not updated here when an XID is processed. To make
a slave crash-safe, positions must be updated while processing a
XID event and as such do not need to be updated here again.
However, if the event needs to be skipped, this means that it
will not be processed and then positions need to be updated here.
DDL:s that are not yet committed, as indicated by
@c has_ddl_committed flag, visit the block.
See sql/rpl_rli.h for further details.
*/
int error = 0;
if (*ptr_ev &&
((ev->get_type_code() != binary_log::XID_EVENT &&
!is_committed_ddl(*ptr_ev)) ||
skip_event ||
(rli->is_mts_recovery() && !is_gtid_event(ev) &&
(ev->ends_group() || !rli->mts_recovery_group_seen_begin) &&
bitmap_is_set(&rli->recovery_groups, rli->mts_recovery_index)))) {
#ifndef NDEBUG
/*
This only prints information to the debug trace.
TODO: Print an informational message to the error log?
*/
static const char *const explain[] = {
// EVENT_SKIP_NOT,
"not skipped",
// EVENT_SKIP_IGNORE,
"skipped because event should be ignored",
// EVENT_SKIP_COUNT
"skipped because event skip counter was non-zero"};
DBUG_PRINT("info",
("OPTION_BEGIN: %d; IN_STMT: %d",
static_cast<bool>(thd->variables.option_bits & OPTION_BEGIN),
rli->get_flag(Relay_log_info::IN_STMT)));
DBUG_PRINT("skip_event",
("%s event was %s", ev->get_type_str(), explain[reason]));
#endif
error = ev->update_pos(rli);
/*
Slave skips an event if the slave_skip_counter is greater than zero.
We have to free thd's mem_root here after we update the positions
in the repository table if the event is a skipped event.
Otherwise, imagine a situation where slave_skip_counter is big number
and slave is skipping the events and updating the repository.
All the memory used while these operations are going on is never
freed unless slave starts executing the events (after slave_skip_counter
becomes zero).
Hence we free thd's mem_root here if it is a skipped event.
(freeing mem_root generally happens from Query_log_event::do_apply_event
or Rows_log_event::do_apply_event when they find the end of
the group event).
*/
if (skip_event) thd->mem_root->ClearForReuse();
#ifndef NDEBUG
DBUG_PRINT("info", ("update_pos error = %d", error));
if (!rli->belongs_to_client()) {
char buf[22];
DBUG_PRINT("info",
("group %s %s", llstr(rli->get_group_relay_log_pos(), buf),
rli->get_group_relay_log_name()));
DBUG_PRINT("info",
("event %s %s", llstr(rli->get_event_relay_log_pos(), buf),
rli->get_event_relay_log_name()));
}
#endif
} else {
/*
INTVAR_EVENT, RAND_EVENT, USER_VAR_EVENT and ROWS_QUERY_LOG_EVENT are
deferred event. It means ev->worker is NULL.
*/
assert(*ptr_ev == ev || rli->is_parallel_exec() ||
(!ev->worker &&
(ev->get_type_code() == binary_log::INTVAR_EVENT ||
ev->get_type_code() == binary_log::RAND_EVENT ||
ev->get_type_code() == binary_log::USER_VAR_EVENT ||
ev->get_type_code() == binary_log::ROWS_QUERY_LOG_EVENT)));
rli->inc_event_relay_log_pos();
}
if (!error && rli->is_mts_recovery() &&
ev->get_type_code() != binary_log::ROTATE_EVENT &&
ev->get_type_code() != binary_log::FORMAT_DESCRIPTION_EVENT &&
ev->get_type_code() != binary_log::PREVIOUS_GTIDS_LOG_EVENT) {
if (ev->starts_group()) {
rli->mts_recovery_group_seen_begin = true;
} else if ((ev->ends_group() || !rli->mts_recovery_group_seen_begin) &&
!is_gtid_event(ev)) {
rli->mts_recovery_index++;
if (--rli->mts_recovery_group_cnt == 0) {
rli->mts_recovery_index = 0;
LogErr(INFORMATION_LEVEL, ER_RPL_MTA_RECOVERY_COMPLETE,
rli->get_for_channel_str(), rli->get_group_relay_log_name(),
rli->get_group_relay_log_pos(),
rli->get_group_master_log_name(),
rli->get_group_master_log_pos());
/*
Few tests wait for UNTIL_SQL_AFTER_MTS_GAPS completion.
Due to existing convention the status won't change
prior to slave restarts.
So making of UNTIL_SQL_AFTER_MTS_GAPS completion is done here,
and only in the debug build to make the test to catch the change
despite a faulty design of UNTIL checking before execution.
*/
if (rli->until_condition ==
Relay_log_info::UNTIL_SQL_AFTER_MTS_GAPS) {
rli->until_condition = Relay_log_info::UNTIL_DONE;
}
// reset the Worker tables to remove last slave session time info
if ((error = rli->mts_finalize_recovery())) {
(void)Rpl_info_factory::reset_workers(rli);
}
}
rli->mts_recovery_group_seen_begin = false;
if (!error)
error = rli->flush_info(Relay_log_info::RLI_FLUSH_IGNORE_SYNC_OPT);
}
}
if (error) {
/*
The update should not fail, so print an error message and
return an error code.
TODO: Replace this with a decent error message when merged
with BUG#24954 (which adds several new error message).
*/
char buf[22];
rli->report(ERROR_LEVEL, ER_UNKNOWN_ERROR,
"It was not possible to update the positions"
" of the relay log information: the replica may"
" be in an inconsistent state."
" Stopped in %s position %s",
rli->get_group_relay_log_name(),
llstr(rli->get_group_relay_log_pos(), buf));
return SLAVE_APPLY_EVENT_AND_UPDATE_POS_UPDATE_POS_ERROR;
}
}
return exec_res ? SLAVE_APPLY_EVENT_AND_UPDATE_POS_APPLY_ERROR
: SLAVE_APPLY_EVENT_AND_UPDATE_POS_OK;
}
/**
Let the worker applying the current group to rollback and gracefully
finish its work before.
@param rli The slave's relay log info.
@param ev a pointer to the event on hold before applying this rollback
procedure.
@retval false The rollback succeeded.
@retval true There was an error while injecting events.
*/
static bool coord_handle_partial_binlogged_transaction(Relay_log_info *rli,
const Log_event *ev) {
DBUG_TRACE;
/*
This function is called holding the rli->data_lock.
We must return it still holding this lock, except in the case of returning
error.
*/
mysql_mutex_assert_owner(&rli->data_lock);
THD *thd = rli->info_thd;
if (!rli->curr_group_seen_begin) {
DBUG_PRINT("info", ("Injecting QUERY(BEGIN) to rollback worker"));
Log_event *begin_event = new Query_log_event(thd, STRING_WITH_LEN("BEGIN"),
true, /* using_trans */
false, /* immediate */
true, /* suppress_use */
0, /* error */
true /* ignore_command */);
((Query_log_event *)begin_event)->db = "";
begin_event->common_header->data_written = 0;
begin_event->server_id = ev->server_id;
/*
We must be careful to avoid SQL thread increasing its position
farther than the event that triggered this QUERY(BEGIN).
*/
begin_event->common_header->log_pos = ev->common_header->log_pos;
begin_event->future_event_relay_log_pos = ev->future_event_relay_log_pos;
if (apply_event_and_update_pos(&begin_event, thd, rli) !=
SLAVE_APPLY_EVENT_AND_UPDATE_POS_OK) {
delete begin_event;
return true;
}
mysql_mutex_lock(&rli->data_lock);
}
DBUG_PRINT("info", ("Injecting QUERY(ROLLBACK) to rollback worker"));
Log_event *rollback_event = new Query_log_event(
thd, STRING_WITH_LEN("ROLLBACK"), true, /* using_trans */
false, /* immediate */
true, /* suppress_use */
0, /* error */
true /* ignore_command */);
((Query_log_event *)rollback_event)->db = "";
rollback_event->common_header->data_written = 0;
rollback_event->server_id = ev->server_id;
/*
We must be careful to avoid SQL thread increasing its position
farther than the event that triggered this QUERY(ROLLBACK).
*/
rollback_event->common_header->log_pos = ev->common_header->log_pos;
rollback_event->future_event_relay_log_pos = ev->future_event_relay_log_pos;
((Query_log_event *)rollback_event)->rollback_injected_by_coord = true;
if (apply_event_and_update_pos(&rollback_event, thd, rli) !=
SLAVE_APPLY_EVENT_AND_UPDATE_POS_OK) {
delete rollback_event;
return true;
}
mysql_mutex_lock(&rli->data_lock);
return false;
}
/**
Top-level function for executing the next event in the relay log.
This is called from the SQL thread.
This function reads the event from the relay log, executes it, and
advances the relay log position. It also handles errors, etc.
This function may fail to apply the event for the following reasons:
- The position specified by the UNTIL condition of the START SLAVE
command is reached.
- It was not possible to read the event from the log.
- The slave is killed.
- An error occurred when applying the event, and the event has been
tried slave_trans_retries times. If the event has been retried
fewer times, 0 is returned.
- init_info or init_relay_log_pos failed. (These are called
if a failure occurs when applying the event.)
- An error occurred when updating the binlog position.
@retval 0 The event was applied.
@retval 1 The event was not applied.
*/
static int exec_relay_log_event(THD *thd, Relay_log_info *rli,
Rpl_applier_reader *applier_reader,
Log_event *in) {
DBUG_TRACE;
/*
We acquire this mutex since we need it for all operations except
event execution. But we will release it in places where we will
wait for something for example inside of next_event().
*/
mysql_mutex_lock(&rli->data_lock);
Log_event *ev = nullptr;
#ifndef NDEBUG
if (!abort_slave_event_count || rli->events_until_exit--)
#endif
ev = in;
Log_event **ptr_ev = nullptr;
RLI_current_event_raii rli_c_ev(rli, ev);
if (ev != nullptr) {
/*
To avoid assigned event groups exceeding rli->checkpoint_group, it
need force to compute checkpoint.
*/
bool force = rli->rli_checkpoint_seqno >= rli->checkpoint_group;
if (force || rli->is_time_for_mta_checkpoint()) {
mysql_mutex_unlock(&rli->data_lock);
if (mta_checkpoint_routine(rli, force)) {
delete ev;
return 1;
}
mysql_mutex_lock(&rli->data_lock);
}
}
/*
It should be checked after calling mta_checkpoint_routine(), because that
function could be interrupted by kill while 'force' is true.
*/
if (sql_slave_killed(thd, rli)) {
mysql_mutex_unlock(&rli->data_lock);
delete ev;
LogErr(INFORMATION_LEVEL, ER_RPL_REPLICA_ERROR_READING_RELAY_LOG_EVENTS,
rli->get_for_channel_str(), "replica SQL thread was killed");
return 1;
}
if (ev) {
enum enum_slave_apply_event_and_update_pos_retval exec_res;
ptr_ev = &ev;
/*
Even if we don't execute this event, we keep the master timestamp,
so that seconds behind master shows correct delta (there are events
that are not replayed, so we keep falling behind).
If it is an artificial event, or a relay log event (IO thread generated
event) or ev->when is set to 0, or a FD from master, or a heartbeat
event with server_id '0' then we don't update the last_master_timestamp.
In case of parallel execution last_master_timestamp is only updated when
a job is taken out of GAQ. Thus when last_master_timestamp is 0 (which
indicates that GAQ is empty, all slave workers are waiting for events from
the Coordinator), we need to initialize it with a timestamp from the first
event to be executed in parallel.
*/
if ((!rli->is_parallel_exec() || rli->last_master_timestamp == 0) &&
!(ev->is_artificial_event() || ev->is_relay_log_event() ||
ev->get_type_code() == binary_log::FORMAT_DESCRIPTION_EVENT ||
ev->server_id == 0)) {
rli->last_master_timestamp =
ev->common_header->when.tv_sec + (time_t)ev->exec_time;
assert(rli->last_master_timestamp >= 0);
}
if (rli->is_until_satisfied_before_dispatching_event(ev)) {
/*
Setting abort_slave flag because we do not want additional message about
error in query execution to be printed.
*/
rli->abort_slave = true;
mysql_mutex_unlock(&rli->data_lock);
delete ev;
return SLAVE_APPLY_EVENT_UNTIL_REACHED;
}
{
/**
The following failure injecion works in cooperation
with tests setting @@global.debug= 'd,incomplete_group_in_relay_log'.
Xid or Commit events are not executed to force the slave sql read
hanging if the relay log does not have any more events.
*/
DBUG_EXECUTE_IF(
"incomplete_group_in_relay_log",
if ((ev->get_type_code() == binary_log::XID_EVENT) ||
((ev->get_type_code() == binary_log::QUERY_EVENT) &&
strcmp("COMMIT", ((Query_log_event *)ev)->query) == 0)) {
rli->abort_slave = 1;
mysql_mutex_unlock(&rli->data_lock);
delete ev;
rli->inc_event_relay_log_pos();
return 0;
};);
}
/*
GTID protocol will put a FORMAT_DESCRIPTION_EVENT from the master with
log_pos != 0 after each (re)connection if auto positioning is enabled.
This means that the SQL thread might have already started to apply the
current group but, as the IO thread had to reconnect, it left this
group incomplete and will start it again from the beginning.
So, before applying this FORMAT_DESCRIPTION_EVENT, we must let the
worker roll back the current group and gracefully finish its work,
before starting to apply the new (complete) copy of the group.
*/
if (ev->get_type_code() == binary_log::FORMAT_DESCRIPTION_EVENT &&
ev->server_id != ::server_id && ev->common_header->log_pos != 0 &&
rli->is_parallel_exec() && rli->curr_group_seen_gtid) {
if (coord_handle_partial_binlogged_transaction(rli, ev))
/*
In the case of an error, coord_handle_partial_binlogged_transaction
will not try to get the rli->data_lock again.
*/
return 1;
}
DBUG_EXECUTE_IF("wait_on_exec_relay_log_event", {
if (ev->get_type_code() == binary_log::WRITE_ROWS_EVENT) {
const char act[] =
"now SIGNAL signal.waiting_on_event_execution "
"WAIT_FOR signal.can_continue_execution";
assert(opt_debug_sync_timeout > 0);
assert(!debug_sync_set_action(current_thd, STRING_WITH_LEN(act)));
}
};);
/* ptr_ev can change to NULL indicating MTS coorinator passed to a Worker */
exec_res = apply_event_and_update_pos(ptr_ev, thd, rli);
/*
Note: the above call to apply_event_and_update_pos executes
mysql_mutex_unlock(&rli->data_lock);
*/
/* For deferred events, the ptr_ev is set to NULL
in Deferred_log_events::add() function.
Hence deferred events won't be deleted here.
They will be deleted in Deferred_log_events::rewind() function.
*/
if (*ptr_ev) {
assert(*ptr_ev == ev); // event remains to belong to Coordinator
DBUG_EXECUTE_IF("dbug.calculate_sbm_after_previous_gtid_log_event", {
if (ev->get_type_code() == binary_log::PREVIOUS_GTIDS_LOG_EVENT) {
rpl_replica_debug_point(DBUG_RPL_S_SBM_AFTER_PREVIOUS_GTID_EV, thd);
}
};);
DBUG_EXECUTE_IF("dbug.calculate_sbm_after_fake_rotate_log_event", {
if (ev->get_type_code() == binary_log::ROTATE_EVENT &&
ev->is_artificial_event()) {
rpl_replica_debug_point(DBUG_RPL_S_SBM_AFTER_FAKE_ROTATE_EV, thd);
}
};);
/*
Format_description_log_event should not be deleted because it will be
used to read info about the relay log's format; it will be deleted when
the SQL thread does not need it, i.e. when this thread terminates.
ROWS_QUERY_LOG_EVENT is destroyed at the end of the current statement
clean-up routine.
*/
if (ev->get_type_code() != binary_log::FORMAT_DESCRIPTION_EVENT &&
ev->get_type_code() != binary_log::ROWS_QUERY_LOG_EVENT) {
DBUG_PRINT("info", ("Deleting the event after it has been executed"));
delete ev;
/*
Raii guard is explicitly instructed to invalidate
otherwise bogus association of the execution context with the being
destroyed above event.
*/
ev = rli->current_event = nullptr;
}
}
/*
exec_res == SLAVE_APPLY_EVENT_AND_UPDATE_POS_UPDATE_POS_ERROR
update_log_pos failed: this should not happen, so we
don't retry.
exec_res == SLAVE_APPLY_EVENT_AND_UPDATE_POS_APPEND_JOB_ERROR
append_item_to_jobs() failed, this happened because
thread was killed while waiting for enqueue on worker.
*/
if (exec_res >= SLAVE_APPLY_EVENT_AND_UPDATE_POS_UPDATE_POS_ERROR) {
delete ev;
return 1;
}
if (slave_trans_retries) {
int temp_err = 0;
bool silent = false;
if (exec_res && !is_mts_worker(thd) /* no reexecution in MTS mode */ &&
(temp_err = rli->has_temporary_error(thd, 0, &silent)) &&
!thd->get_transaction()->cannot_safely_rollback(
Transaction_ctx::SESSION)) {
const char *errmsg;
/*
We were in a transaction which has been rolled back because of a
temporary error;
let's seek back to BEGIN log event and retry it all again.
Note, if lock wait timeout (innodb_lock_wait_timeout exceeded)
there is no rollback since 5.0.13 (ref: manual).
We have to not only seek but also
a) init_info(), to seek back to hot relay log's start for later
(for when we will come back to this hot log after re-processing the
possibly existing old logs where BEGIN is: applier_reader will
then need the cache to be at position 0 (see comments at beginning of
init_info()).
b) init_relay_log_pos(), because the BEGIN may be an older relay log.
*/
if (rli->trans_retries < slave_trans_retries) {
/*
The transactions has to be rolled back before
load_mi_and_rli_from_repositories is called. Because
load_mi_and_rli_from_repositories will starts a new
transaction if master_info_repository is TABLE.
*/
rli->cleanup_context(thd, true);
/*
Temporary error status is both unneeded and harmful for following
open-and-lock slave system tables but store its number first for
monitoring purposes.
*/
uint temp_trans_errno = thd->get_stmt_da()->mysql_errno();
thd->clear_error();
applier_reader->close();
/*
We need to figure out if there is a test case that covers
this part. \Alfranio.
*/
if (load_mi_and_rli_from_repositories(rli->mi, false, SLAVE_SQL,
false, true))
LogErr(ERROR_LEVEL,
ER_RPL_REPLICA_FAILED_TO_INIT_CONNECTION_METADATA_STRUCTURE,
rli->get_for_channel_str());
else if (applier_reader->open(&errmsg))
LogErr(ERROR_LEVEL, ER_RPL_REPLICA_CANT_INIT_RELAY_LOG_POSITION,
rli->get_for_channel_str(), errmsg);
else {
exec_res = SLAVE_APPLY_EVENT_RETRY;
/* chance for concurrent connection to get more locks */
slave_sleep(thd,
min<ulong>(rli->trans_retries, MAX_SLAVE_RETRY_PAUSE),
sql_slave_killed, rli);
mysql_mutex_lock(&rli->data_lock); // because of SHOW STATUS
if (!silent) {
rli->trans_retries++;
if (rli->is_processing_trx()) {
rli->retried_processing(temp_trans_errno,
ER_THD_NONCONST(thd, temp_trans_errno),
rli->trans_retries);
}
}
rli->retried_trans++;
mysql_mutex_unlock(&rli->data_lock);
#ifndef NDEBUG
if (rli->trans_retries == 2 || rli->trans_retries == 6)
DBUG_EXECUTE_IF("rpl_ps_tables_worker_retry", {
rpl_replica_debug_point(DBUG_RPL_S_PS_TABLE_WORKER_RETRY);
};);
#endif
DBUG_PRINT("info", ("Replica retries transaction "
"rli->trans_retries: %lu",
rli->trans_retries));
}
} else {
thd->fatal_error();
rli->report(ERROR_LEVEL, thd->get_stmt_da()->mysql_errno(),
"Replica SQL thread retried transaction %lu time(s) "
"in vain, giving up. Consider raising the value of "
"the replica_transaction_retries variable.",
rli->trans_retries);
}
} else if ((exec_res && !temp_err) ||
(opt_using_transactions &&
rli->get_group_relay_log_pos() ==
rli->get_event_relay_log_pos())) {
/*
Only reset the retry counter if the entire group succeeded
or failed with a non-transient error. On a successful
event, the execution will proceed as usual; in the case of a
non-transient error, the slave will stop with an error.
*/
rli->trans_retries = 0; // restart from fresh
DBUG_PRINT("info", ("Resetting retry counter, rli->trans_retries: %lu",
rli->trans_retries));
}
}
if (exec_res) {
delete ev;
/* Raii object is explicitly updated 'cos this branch doesn't end func */
rli->current_event = nullptr;
} else if (rli->is_until_satisfied_after_dispatching_event()) {
mysql_mutex_lock(&rli->data_lock);
rli->abort_slave = true;
mysql_mutex_unlock(&rli->data_lock);
return SLAVE_APPLY_EVENT_UNTIL_REACHED;
}
return exec_res;
}
/*
It is impossible to read next event to finish the event group whenever a
read event error happens. So MTS group status is set to MTS_KILLED_GROUP to
force stop.
*/
if (rli->mts_group_status == Relay_log_info::MTS_IN_GROUP)
rli->mts_group_status = Relay_log_info::MTS_KILLED_GROUP;
mysql_mutex_unlock(&rli->data_lock);
rli->report(ERROR_LEVEL, ER_REPLICA_RELAY_LOG_READ_FAILURE,
ER_THD(thd, ER_REPLICA_RELAY_LOG_READ_FAILURE),
"Could not parse relay log event entry. The possible reasons "
"are: the source's "
"binary log is corrupted (you can check this by running "
"'mysqlbinlog' on the "
"binary log), the replica's relay log is corrupted (you can "
"check this by running "
"'mysqlbinlog' on the relay log), a network problem, the server "
"was unable to "
"fetch a keyring key required to open an encrypted relay log "
"file, or a bug in "
"the source's or replica's MySQL code. If you want to check the "
"source's binary "
"log or replica's relay log, you will be able to know their "
"names by issuing "
"'SHOW REPLICA STATUS' on this replica.");
return SLAVE_APPLY_EVENT_AND_UPDATE_POS_APPLY_ERROR;
}
static bool check_io_slave_killed(THD *thd, Master_info *mi, const char *info) {
if (io_slave_killed(thd, mi)) {
if (info)
LogErr(INFORMATION_LEVEL, ER_RPL_IO_THREAD_KILLED, info,
mi->get_for_channel_str());
return true;
}
return false;
}
/**
@brief Try to reconnect slave IO thread.
@details Terminates current connection to master, sleeps for
@c mi->connect_retry msecs and initiates new connection with
@c safe_reconnect(). Variable pointed by @c retry_count is increased -
if it exceeds @c mi->retry_count then connection is not re-established
and function signals error.
Unless @c suppress_warnings is true, a warning is written to the
server error log when reconnecting. The warning message, the
messages used to report errors, and the thread stages, are taken
from @c rm. In case @c mi->retry_count is exceeded, no messages are
added to the log.
@param[in] thd Thread context.
@param[in] mysql MySQL connection.
@param[in] mi Master connection information.
@param[in,out] retry_count Number of attempts to reconnect.
@param[in] suppress_warnings true when a normal net read timeout
has caused to reconnecting.
@param[in] messages Error/warning messages and thread stage
information. See class Reconnect_messages.
@retval 0 OK.
@retval 1 There was an error.
*/
static int try_to_reconnect(THD *thd, MYSQL *mysql, Master_info *mi,
uint *retry_count, bool suppress_warnings,
const Reconnect_messages &messages) {
mi->slave_running = MYSQL_SLAVE_RUN_NOT_CONNECT;
THD_STAGE_INFO(thd, messages.stage_waiting_to_reconnect);
DBUG_EXECUTE_IF("hang_in_stage_replica_waiting_to_reconnect", {
while (!io_slave_killed(thd, mi)) my_sleep(100000); // 0.1 second
});
thd->clear_active_vio();
end_server(mysql);
if ((*retry_count)++) {
if (*retry_count > mi->retry_count) return 1; // Don't retry forever
slave_sleep(thd, mi->connect_retry, io_slave_killed, mi);
}
if (check_io_slave_killed(thd, mi,
messages.error_killed_while_waiting.c_str()))
return 1;
THD_STAGE_INFO(thd, messages.stage_reconnecting);
DBUG_EXECUTE_IF("hang_in_stage_replica_reconnecting", {
while (!io_slave_killed(thd, mi)) my_sleep(100000); // 0.1 second
});
if (!suppress_warnings) {
char llbuff[22];
/*
Raise a warining during registering on master/requesting dump.
Log a message reading event.
*/
if (messages.triggering_command.length()) {
char buf[256];
snprintf(buf, sizeof(buf), messages.triggering_error.c_str(),
mi->get_io_rpl_log_name(),
llstr(mi->get_master_log_pos(), llbuff));
mi->report(WARNING_LEVEL, ER_REPLICA_SOURCE_COM_FAILURE,
ER_THD(thd, ER_REPLICA_SOURCE_COM_FAILURE),
messages.triggering_command.c_str(), buf);
} else {
LogErr(INFORMATION_LEVEL, ER_REPLICA_RECONNECT_FAILED,
mi->get_io_rpl_log_name(), llstr(mi->get_master_log_pos(), llbuff),
mi->get_for_channel_str());
}
}
if (safe_reconnect(thd, mysql, mi, true) || io_slave_killed(thd, mi)) {
LogErr(INFORMATION_LEVEL, ER_REPLICA_KILLED_AFTER_RECONNECT);
return 1;
}
return 0;
}
/**
Slave IO thread entry point.
@param arg Pointer to Master_info struct that holds information for
the IO thread.
@return Always 0.
*/
extern "C" void *handle_slave_io(void *arg) {
THD *thd{nullptr}; // needs to be first for thread_stack
bool thd_added{false};
MYSQL *mysql;
Master_info *mi = (Master_info *)arg;
Relay_log_info *rli = mi->rli;
char llbuff[22];
uint retry_count;
bool suppress_warnings;
int ret;
Async_conn_failover_manager::SourceQuorumStatus quorum_status{
Async_conn_failover_manager::SourceQuorumStatus::no_error};
Global_THD_manager *thd_manager = Global_THD_manager::get_instance();
// needs to call my_thread_init(), otherwise we get a coredump in DBUG_ stuff
my_thread_init();
{
DBUG_TRACE;
assert(mi->inited);
mysql = nullptr;
mysql_mutex_lock(&mi->run_lock);
/* Inform waiting threads that slave has started */
mi->slave_run_id++;
#ifndef NDEBUG
mi->events_until_exit = disconnect_slave_event_count;
#endif
thd = new THD; // note that constructor of THD uses DBUG_ !
THD_CHECK_SENTRY(thd);
mi->info_thd = thd;
#ifdef HAVE_PSI_THREAD_INTERFACE
// save the instrumentation for IO thread in mi->info_thd
struct PSI_thread *psi = PSI_THREAD_CALL(get_thread)();
thd_set_psi(mi->info_thd, psi);
#endif
mysql_thread_set_psi_THD(thd);
thd->thread_stack = (char *)&thd; // remember where our stack is
mi->clear_error();
mi->slave_running = 1;
if (init_replica_thread(thd, SLAVE_THD_IO)) {
mysql_cond_broadcast(&mi->start_cond);
mysql_mutex_unlock(&mi->run_lock);
mi->report(ERROR_LEVEL, ER_REPLICA_FATAL_ERROR,
ER_THD(thd, ER_REPLICA_FATAL_ERROR),
"Failed during replica I/O thread initialization ");
goto err;
}
thd_manager->add_thd(thd);
thd_added = true;
mi->abort_slave = false;
mysql_mutex_unlock(&mi->run_lock);
mysql_cond_broadcast(&mi->start_cond);
connect_init:
DBUG_PRINT("source_info",
("log_file_name: '%s' position: %s", mi->get_master_log_name(),
llstr(mi->get_master_log_pos(), llbuff)));
/* This must be called before run any binlog_relay_io hooks */
RPL_MASTER_INFO = mi;
if (RUN_HOOK(binlog_relay_io, thread_start, (thd, mi))) {
mi->report(ERROR_LEVEL, ER_REPLICA_FATAL_ERROR,
ER_THD(thd, ER_REPLICA_FATAL_ERROR),
"Failed to run 'thread_start' hook");
goto err;
}
retry_count = 0;
if (!(mi->mysql = mysql = mysql_init(nullptr))) {
mi->report(ERROR_LEVEL, ER_REPLICA_FATAL_ERROR,
ER_THD(thd, ER_REPLICA_FATAL_ERROR), "error in mysql_init()");
goto err;
}
THD_STAGE_INFO(thd, stage_connecting_to_source);
if (safe_connect(thd, mysql, mi)) {
goto err;
}
connected:
/*
When using auto positioning, the slave IO thread will always start reading
a transaction from the beginning of the transaction (transaction's first
event). So, we have to reset the transaction boundary parser after
(re)connecting.
If not using auto positioning, the Relay_log_info::rli_init_info() took
care of putting the mi->transaction_parser in the correct state when
initializing Received_gtid_set from relay log during slave server starts,
as the IO thread might had stopped in the middle of a transaction.
*/
if (mi->is_auto_position()) {
mi->transaction_parser.reset();
mi->clear_queueing_trx(true /* need_lock*/);
}
mi->reset_network_error();
DBUG_EXECUTE_IF("dbug.before_get_running_status_yes", {
rpl_replica_debug_point(DBUG_RPL_S_BEFORE_RUNNING_STATUS, thd);
};);
DBUG_EXECUTE_IF("dbug.calculate_sbm_after_previous_gtid_log_event", {
/* Fake that thread started 3 minutes ago */
thd->start_time.tv_sec -= 180;
};);
DBUG_EXECUTE_IF("dbug.calculate_sbm_after_fake_rotate_log_event", {
/* Fake that thread started 3 minutes ago */
thd->start_time.tv_sec -= 180;
};);
mysql_mutex_lock(&mi->run_lock);
mi->slave_running = MYSQL_SLAVE_RUN_CONNECT;
mysql_mutex_unlock(&mi->run_lock);
THD_STAGE_INFO(thd, stage_checking_source_version);
ret = get_master_version_and_clock(mysql, mi);
if (!ret) {
ret = get_master_uuid(mysql, mi);
}
if (!ret) ret = io_thread_init_commands(mysql, mi);
quorum_status = Async_conn_failover_manager::SourceQuorumStatus::no_error;
if (!ret && mi->is_source_connection_auto_failover()) {
quorum_status =
Async_conn_failover_manager::get_source_quorum_status(mysql, mi);
switch (quorum_status) {
case Async_conn_failover_manager::SourceQuorumStatus::fatal_error:
case Async_conn_failover_manager::SourceQuorumStatus::no_quorum_error:
ret = 1;
break;
case Async_conn_failover_manager::SourceQuorumStatus::
transient_network_error:
ret = 2;
break;
case Async_conn_failover_manager::SourceQuorumStatus::no_error:
default:
break;
}
}
if (DBUG_EVALUATE_IF("simulate_reconnect_after_failed_registration", 1,
0)) {
ret = 2;
}
switch (ret) {
case 0: {
if (mi && mi->is_auto_position()) {
LogErr(SYSTEM_LEVEL,
ER_RPL_REPLICA_CONNECTED_TO_SOURCE_RPL_STARTED_GTID_BASED,
mi->get_for_channel_str(), mi->get_user(), mi->host, mi->port,
mi->master_uuid, mi->master_id);
} else {
LogErr(SYSTEM_LEVEL,
ER_RPL_REPLICA_CONNECTED_TO_SOURCE_RPL_STARTED_FILE_BASED,
mi->get_for_channel_str(), mi->get_user(), mi->host, mi->port,
mi->master_uuid, mi->master_id, mi->get_io_rpl_log_name(),
llstr(mi->get_master_log_pos(), llbuff));
}
break;
}
case 1:
/* Fatal error */
goto err;
break;
case 2: {
if (check_io_slave_killed(
mi->info_thd, mi,
"Replica I/O thread killed "
"while calling get_master_version_and_clock(...)"))
goto err;
suppress_warnings = false;
/* Try to reconnect because the error was caused by a transient network
* problem */
if (try_to_reconnect(thd, mysql, mi, &retry_count, suppress_warnings,
reconnect_messages_after_failed_registration))
goto err;
goto connected;
break;
}
}
/*
Register ourselves with the master.
*/
THD_STAGE_INFO(thd, stage_registering_replica_on_source);
if (register_slave_on_master(mysql, mi, &suppress_warnings)) {
if (!check_io_slave_killed(thd, mi,
"Replica I/O thread killed "
"while registering replica on source")) {
LogErr(ERROR_LEVEL, ER_RPL_REPLICA_IO_THREAD_CANT_REGISTER_ON_SOURCE);
if (try_to_reconnect(thd, mysql, mi, &retry_count, suppress_warnings,
reconnect_messages_after_failed_registration))
goto err;
} else
goto err;
goto connected;
}
DBUG_PRINT("info", ("Starting reading binary log from source"));
while (!io_slave_killed(thd, mi)) {
MYSQL_RPL rpl;
THD_STAGE_INFO(thd, stage_requesting_binlog_dump);
if (request_dump(thd, mysql, &rpl, mi, &suppress_warnings) ||
DBUG_EVALUATE_IF("simulate_reconnect_after_failed_binlog_dump", 1,
0)) {
LogErr(ERROR_LEVEL, ER_RPL_REPLICA_ERROR_REQUESTING_BINLOG_DUMP,
mi->get_for_channel_str());
if (check_io_slave_killed(thd, mi,
"Replica I/O thread killed while "
"requesting source dump") ||
try_to_reconnect(thd, mysql, mi, &retry_count, suppress_warnings,
reconnect_messages_after_failed_dump))
goto err;
goto connected;
}
const char *event_buf;
assert(mi->last_error().number == 0);
while (!io_slave_killed(thd, mi)) {
ulong event_len;
/*
We say "waiting" because read_event() will wait if there's nothing to
read. But if there's something to read, it will not wait. The
important thing is to not confuse users by saying "reading" whereas
we're in fact receiving nothing.
*/
THD_STAGE_INFO(thd, stage_waiting_for_source_to_send_event);
event_len = read_event(mysql, &rpl, mi, &suppress_warnings);
if (check_io_slave_killed(thd, mi,
"Replica I/O thread killed while "
"reading event"))
goto err;
if (event_len == packet_error ||
DBUG_EVALUATE_IF("simulate_reconnect_after_failed_event_read", 1,
0)) {
uint mysql_error_number = mysql_errno(mysql);
switch (mysql_error_number) {
case CR_NET_PACKET_TOO_LARGE:
LogErr(ERROR_LEVEL,
ER_RPL_LOG_ENTRY_EXCEEDS_REPLICA_MAX_ALLOWED_PACKET,
replica_max_allowed_packet);
mi->report(ERROR_LEVEL, ER_SERVER_NET_PACKET_TOO_LARGE, "%s",
"Got a packet bigger than "
"'replica_max_allowed_packet' bytes");
goto err;
case ER_SOURCE_FATAL_ERROR_READING_BINLOG:
mi->report(ERROR_LEVEL,
ER_SERVER_SOURCE_FATAL_ERROR_READING_BINLOG,
ER_THD(thd, ER_SOURCE_FATAL_ERROR_READING_BINLOG),
mysql_error_number, mysql_error(mysql));
goto err;
case ER_OUT_OF_RESOURCES:
LogErr(ERROR_LEVEL, ER_RPL_REPLICA_STOPPING_AS_SOURCE_OOM);
mi->report(ERROR_LEVEL, ER_SERVER_OUT_OF_RESOURCES, "%s",
ER_THD(thd, ER_SERVER_OUT_OF_RESOURCES));
goto err;
}
if (try_to_reconnect(thd, mysql, mi, &retry_count, suppress_warnings,
reconnect_messages_after_failed_event_read))
goto err;
goto connected;
} // if (event_len == packet_error)
retry_count = 0; // ok event, reset retry counter
THD_STAGE_INFO(thd, stage_queueing_source_event_to_the_relay_log);
event_buf = (const char *)mysql->net.read_pos + 1;
DBUG_PRINT("info", ("IO thread received event of type %s",
Log_event::get_type_str(
(Log_event_type)event_buf[EVENT_TYPE_OFFSET])));
if (RUN_HOOK(binlog_relay_io, after_read_event,
(thd, mi, (const char *)mysql->net.read_pos + 1, event_len,
&event_buf, &event_len))) {
mi->report(ERROR_LEVEL, ER_REPLICA_FATAL_ERROR,
ER_THD(thd, ER_REPLICA_FATAL_ERROR),
"Failed to run 'after_read_event' hook");
goto err;
}
/* XXX: 'synced' should be updated by queue_event to indicate
whether event has been synced to disk */
bool synced = false;
#ifndef NDEBUG
bool was_in_trx = false;
if (mi->is_queueing_trx()) {
was_in_trx = true;
DBUG_EXECUTE_IF("rpl_ps_tables_queue", {
rpl_replica_debug_point(DBUG_RPL_S_PS_TABLE_QUEUE);
};);
}
#endif
std::size_t queued_size = event_len;
if (binary_log::Log_event_type_helper::is_any_gtid_event(
static_cast<Log_event_type>(event_buf[EVENT_TYPE_OFFSET]))) {
mysql_mutex_lock(rli->relay_log.get_log_lock());
Gtid_log_event gtid_ev(event_buf, mi->get_mi_description_event());
mysql_mutex_unlock(rli->relay_log.get_log_lock());
if (!gtid_ev.is_valid()) {
mi->report(ERROR_LEVEL, ER_REPLICA_RELAY_LOG_WRITE_FAILURE,
ER_THD(thd, ER_REPLICA_RELAY_LOG_WRITE_FAILURE),
"could not queue event from source");
goto err;
}
queued_size = gtid_ev.get_trx_length();
}
// If the used space exceeds the relay log limit, and the current
// position is on a transaction boundary, and the received event is not
// a FD/rotate event, wait for the applier to free space. The exception
// for FD/rotate events is important in case the server has just
// restarted with the relay log ending in a half transaction. In this
// case, the applier has no information indicating that the transaction
// is half-received, so it cannot rollback the transaction and free disk
// space. But when we write the FD/rotate events, the applier can deduce
// that the transaction is half-received, and then it can rollback and
// free disk space as needed.
if (rli->log_space_limit && exceeds_relay_log_limit(rli, queued_size) &&
!mi->transaction_parser.is_inside_transaction() &&
!(event_buf[EVENT_TYPE_OFFSET] ==
binary_log::FORMAT_DESCRIPTION_EVENT ||
event_buf[EVENT_TYPE_OFFSET] == binary_log::ROTATE_EVENT)) {
if (wait_for_relay_log_space(rli, queued_size)) {
LogErr(
ERROR_LEVEL,
ER_RPL_REPLICA_IO_THREAD_ABORTED_WAITING_FOR_RELAY_LOG_SPACE);
goto err;
}
}
QUEUE_EVENT_RESULT queue_res = queue_event(mi, event_buf, event_len);
if (queue_res == QUEUE_EVENT_ERROR_QUEUING) {
mi->report(ERROR_LEVEL, ER_REPLICA_RELAY_LOG_WRITE_FAILURE,
ER_THD(thd, ER_REPLICA_RELAY_LOG_WRITE_FAILURE),
"could not queue event from source");
goto err;
}
#ifndef NDEBUG
if (was_in_trx && !mi->is_queueing_trx()) {
DBUG_EXECUTE_IF("rpl_ps_tables",
{ rpl_replica_debug_point(DBUG_RPL_S_PS_TABLES); };);
}
#endif
if (RUN_HOOK(binlog_relay_io, after_queue_event,
(thd, mi, event_buf, event_len, synced))) {
mi->report(ERROR_LEVEL, ER_REPLICA_FATAL_ERROR,
ER_THD(thd, ER_REPLICA_FATAL_ERROR),
"Failed to run 'after_queue_event' hook");
goto err;
}
/* The event was queued, but there was a failure flushing master info */
if (queue_res == QUEUE_EVENT_ERROR_FLUSHING_INFO) {
mi->report(ERROR_LEVEL, ER_REPLICA_FATAL_ERROR,
ER_THD(thd, ER_REPLICA_FATAL_ERROR),
"Failed to flush connection metadata.");
goto err;
}
assert(queue_res == QUEUE_EVENT_OK);
/*
Pause the IO thread execution and wait for
'continue_after_queue_event' signal to continue IO thread
execution.
*/
DBUG_EXECUTE_IF("pause_after_queue_event", {
rpl_replica_debug_point(DBUG_RPL_S_PAUSE_AFTER_QUEUE_EV);
};);
/*
See if the relay logs take too much space.
*/
#ifndef NDEBUG
{
char llbuf1[22], llbuf2[22];
DBUG_PRINT("info", ("log_space_limit=%s log_space_total=%s ",
llstr(rli->log_space_limit, llbuf1),
llstr(rli->log_space_total, llbuf2)));
}
#endif
DBUG_EXECUTE_IF("rpl_set_relay_log_limits", {
rli->log_space_limit = 10;
rli->log_space_total = 20;
};);
DBUG_EXECUTE_IF("flush_after_reading_user_var_event", {
if (event_buf[EVENT_TYPE_OFFSET] == binary_log::USER_VAR_EVENT)
rpl_replica_debug_point(DBUG_RPL_S_FLUSH_AFTER_USERV_EV);
});
DBUG_EXECUTE_IF(
"stop_io_after_reading_gtid_log_event",
if (event_buf[EVENT_TYPE_OFFSET] == binary_log::GTID_LOG_EVENT)
thd->killed = THD::KILLED_NO_VALUE;);
DBUG_EXECUTE_IF(
"stop_io_after_reading_query_log_event",
if (event_buf[EVENT_TYPE_OFFSET] == binary_log::QUERY_EVENT)
thd->killed = THD::KILLED_NO_VALUE;);
DBUG_EXECUTE_IF(
"stop_io_after_reading_user_var_log_event",
if (event_buf[EVENT_TYPE_OFFSET] == binary_log::USER_VAR_EVENT)
thd->killed = THD::KILLED_NO_VALUE;);
DBUG_EXECUTE_IF(
"stop_io_after_reading_table_map_event",
if (event_buf[EVENT_TYPE_OFFSET] == binary_log::TABLE_MAP_EVENT)
thd->killed = THD::KILLED_NO_VALUE;);
DBUG_EXECUTE_IF(
"stop_io_after_reading_xid_log_event",
if (event_buf[EVENT_TYPE_OFFSET] == binary_log::XID_EVENT)
thd->killed = THD::KILLED_NO_VALUE;);
DBUG_EXECUTE_IF(
"stop_io_after_reading_write_rows_log_event",
if (event_buf[EVENT_TYPE_OFFSET] == binary_log::WRITE_ROWS_EVENT)
thd->killed = THD::KILLED_NO_VALUE;);
DBUG_EXECUTE_IF(
"stop_io_after_reading_unknown_event",
if (event_buf[EVENT_TYPE_OFFSET] >= binary_log::ENUM_END_EVENT)
thd->killed = THD::KILLED_NO_VALUE;);
DBUG_EXECUTE_IF("stop_io_after_queuing_event",
thd->killed = THD::KILLED_NO_VALUE;);
/*
After event is flushed to relay log file, memory used
by thread's mem_root is not required any more.
Hence adding ClearorReuse() to do the
cleanup, otherwise a long running IO thread can
cause OOM error.
*/
thd->mem_root->ClearForReuse();
}
}
// error = 0;
err:
/*
If source_connection_auto_failover (async connection failover) is
enabled, this server is not a Group Replication SECONDARY and
Replica IO thread is not killed but failed due to network error, a
connection to another source is attempted.
*/
if (mi->is_source_connection_auto_failover() &&
!is_group_replication_member_secondary() && !io_slave_killed(thd, mi) &&
(mi->is_network_error() ||
quorum_status !=
Async_conn_failover_manager::SourceQuorumStatus::no_error)) {
DBUG_EXECUTE_IF("async_conn_failover_crash", DBUG_SUICIDE(););
/*
Channel connection details (host, port) values can change after
call to Async_conn_failover_manager::do_auto_conn_failover() function
to get the next available sender.
*/
std::string old_user(mi->get_user());
std::string old_host(mi->host);
uint old_port = mi->port;
/*
Get the sender to connect to.
If there is a STOP REPLICA ongoing for any channel, that is, a
channel_map lock cannot be acquired by this channel IO thread,
then this channel IO thread does skip the next sender selection.
*/
Async_conn_failover_manager::DoAutoConnFailoverError update_source_error =
Async_conn_failover_manager::DoAutoConnFailoverError::retriable_error;
if (!channel_map.tryrdlock()) {
update_source_error =
Async_conn_failover_manager::do_auto_conn_failover(mi, false);
channel_map.unlock();
}
DBUG_EXECUTE_IF("replica_retry_count_exceed", {
if (Async_conn_failover_manager::DoAutoConnFailoverError::no_error ==
update_source_error) {
rpl_replica_debug_point(DBUG_RPL_S_RETRY_COUNT_EXCEED, thd);
}
});
if (Async_conn_failover_manager::DoAutoConnFailoverError::
no_sources_error != update_source_error) {
/* Wait before reconnect to avoid resources starvation. */
my_sleep(1000000);
/* After waiting, recheck that a STOP REPLICA did not happen. */
if (!check_io_slave_killed(
thd, mi,
"Replica I/O thread killed while "
"attempting asynchronous connection failover")) {
/* Reconnect. */
if (mysql) {
LogErr(SYSTEM_LEVEL, ER_RPL_ASYNC_NEXT_FAILOVER_CHANNEL_SELECTED,
mi->retry_count, old_user.c_str(), old_host.c_str(),
old_port, mi->get_for_channel_str(), mi->get_user(),
mi->host, mi->port);
thd->clear_active_vio();
mysql_close(mysql);
mi->mysql = nullptr;
mysql = nullptr;
}
goto connect_init;
}
}
}
// print the current replication position
LogErr(INFORMATION_LEVEL, ER_RPL_REPLICA_IO_THREAD_EXITING,
mi->get_for_channel_str(), mi->get_io_rpl_log_name(),
llstr(mi->get_master_log_pos(), llbuff));
/* At this point the I/O thread will not try to reconnect anymore. */
mi->atomic_is_stopping = true;
(void)RUN_HOOK(binlog_relay_io, thread_stop, (thd, mi));
/*
Pause the IO thread and wait for 'continue_to_stop_io_thread'
signal to continue to shutdown the IO thread.
*/
DBUG_EXECUTE_IF("pause_after_io_thread_stop_hook", {
rpl_replica_debug_point(DBUG_RPL_S_PAUSE_AFTER_IO_STOP, thd);
};);
thd->reset_query();
thd->reset_db(NULL_CSTR);
if (mysql) {
/*
Here we need to clear the active VIO before closing the
connection with the master. The reason is that THD::awake()
might be called from terminate_slave_thread() because somebody
issued a STOP SLAVE. If that happends, the shutdown_active_vio()
can be called in the middle of closing the VIO associated with
the 'mysql' object, causing a crash.
*/
thd->clear_active_vio();
mysql_close(mysql);
mi->mysql = nullptr;
mysql = nullptr;
}
write_ignored_events_info_to_relay_log(thd, mi);
THD_STAGE_INFO(thd, stage_waiting_for_replica_mutex_on_exit);
mysql_mutex_lock(&mi->run_lock);
/*
Clean information used to start slave in order to avoid
security issues.
*/
mi->reset_start_info();
/* Forget the relay log's format */
mysql_mutex_lock(rli->relay_log.get_log_lock());
mi->set_mi_description_event(nullptr);
mysql_mutex_unlock(rli->relay_log.get_log_lock());
// destructor will not free it, because net.vio is 0
thd->get_protocol_classic()->end_net();
thd->release_resources();
THD_CHECK_SENTRY(thd);
if (thd_added) thd_manager->remove_thd(thd);
mi->abort_slave = false;
mi->slave_running = 0;
mi->atomic_is_stopping = false;
mysql_mutex_lock(&mi->info_thd_lock);
mi->info_thd = nullptr;
mysql_mutex_unlock(&mi->info_thd_lock);
/*
The thd can only be destructed after indirect references
through mi->info_thd are cleared: mi->info_thd= NULL.
For instance, user thread might be issuing show_slave_status
and attempting to read mi->info_thd->proc_info().
Therefore thd must only be deleted after info_thd is set
to NULL.
*/
mysql_thread_set_psi_THD(nullptr);
delete thd;
/*
Note: the order of the two following calls (first broadcast, then unlock)
is important. Otherwise a killer_thread can execute between the calls and
delete the mi structure leading to a crash! (see BUG#25306 for details)
*/
mysql_cond_broadcast(&mi->stop_cond); // tell the world we are done
DBUG_EXECUTE_IF("simulate_replica_delay_at_terminate_bug38694", sleep(5););
mysql_mutex_unlock(&mi->run_lock);
}
my_thread_end();
#if OPENSSL_VERSION_NUMBER < 0x10100000L
ERR_remove_thread_state(0);
#endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */
my_thread_exit(nullptr);
return (nullptr); // Avoid compiler warnings
}
/*
Check the temporary directory used by commands like
LOAD DATA INFILE.
*/
static int check_temp_dir(char *tmp_file, const char *channel_name) {
int fd;
MY_DIR *dirp;
char tmp_dir[FN_REFLEN];
size_t tmp_dir_size;
DBUG_TRACE;
/*
Get the directory from the temporary file.
*/
dirname_part(tmp_dir, tmp_file, &tmp_dir_size);
/*
Check if the directory exists.
*/
if (!(dirp = my_dir(tmp_dir, MYF(MY_WME)))) return 1;
my_dirend(dirp);
/*
Check permissions to create a file.
*/
// append the server UUID to the temp file name.
constexpr uint size_of_tmp_file_name = 768;
static_assert(size_of_tmp_file_name >= FN_REFLEN + TEMP_FILE_MAX_LEN, "");
char *unique_tmp_file_name = (char *)my_malloc(
key_memory_rpl_replica_check_temp_dir, size_of_tmp_file_name, MYF(0));
/*
In the case of Multisource replication, the file create
sometimes fail because of there is a race that a second SQL
thread might create the same file and the creation fails.
TO overcome this, we add a channel name to get a unique file name.
*/
/* @TODO: dangerous. Prevent this buffer flow */
snprintf(unique_tmp_file_name, size_of_tmp_file_name, "%s%s%s", tmp_file,
channel_name, server_uuid);
if ((fd = mysql_file_create(key_file_misc, unique_tmp_file_name, CREATE_MODE,
O_WRONLY | O_EXCL | O_NOFOLLOW, MYF(MY_WME))) < 0)
return 1;
/*
Clean up.
*/
mysql_file_close(fd, MYF(0));
mysql_file_delete(key_file_misc, unique_tmp_file_name, MYF(0));
my_free(unique_tmp_file_name);
return 0;
}
/*
Worker thread for the parallel execution of the replication events.
*/
extern "C" {
static void *handle_slave_worker(void *arg) {
THD *thd; /* needs to be first for thread_stack */
bool thd_added = false;
int error = 0;
Slave_worker *w = (Slave_worker *)arg;
Relay_log_info *rli = w->c_rli;
ulong purge_cnt = 0;
ulonglong purge_size = 0;
struct slave_job_item _item, *job_item = &_item;
Global_THD_manager *thd_manager = Global_THD_manager::get_instance();
#ifdef HAVE_PSI_THREAD_INTERFACE
struct PSI_thread *psi;
#endif
my_thread_init();
DBUG_TRACE;
thd = new THD;
if (!thd) {
LogErr(ERROR_LEVEL, ER_RPL_REPLICA_CANT_INITIALIZE_REPLICA_WORKER,
rli->get_for_channel_str());
goto err;
}
mysql_mutex_lock(&w->info_thd_lock);
w->info_thd = thd;
mysql_mutex_unlock(&w->info_thd_lock);
thd->thread_stack = (char *)&thd;
#ifdef HAVE_PSI_THREAD_INTERFACE
// save the instrumentation for worker thread in w->info_thd
psi = PSI_THREAD_CALL(get_thread)();
thd_set_psi(w->info_thd, psi);
#endif
mysql_thread_set_psi_THD(thd);
if (init_replica_thread(thd, SLAVE_THD_WORKER)) {
// todo make SQL thread killed
LogErr(ERROR_LEVEL, ER_RPL_REPLICA_CANT_INITIALIZE_REPLICA_WORKER,
rli->get_for_channel_str());
goto err;
}
thd->rli_slave = w;
thd->init_query_mem_roots();
if (channel_map.is_group_replication_channel_name(rli->get_channel())) {
if (channel_map.is_group_replication_channel_name(rli->get_channel(),
true)) {
thd->rpl_thd_ctx.set_rpl_channel_type(GR_APPLIER_CHANNEL);
} else {
thd->rpl_thd_ctx.set_rpl_channel_type(GR_RECOVERY_CHANNEL);
}
} else {
thd->rpl_thd_ctx.set_rpl_channel_type(RPL_STANDARD_CHANNEL);
}
w->set_filter(rli->rpl_filter);
if ((w->deferred_events_collecting = w->rpl_filter->is_on()))
w->deferred_events = new Deferred_log_events();
assert(thd->rli_slave->info_thd == thd);
/* Set applier thread InnoDB priority */
set_thd_tx_priority(thd, rli->get_thd_tx_priority());
/* Set write set related options */
set_thd_write_set_options(thd, rli->get_ignore_write_set_memory_limit(),
rli->get_allow_drop_write_set());
thd->variables.require_row_format = rli->is_row_format_required();
if (Relay_log_info::PK_CHECK_STREAM !=
rli->get_require_table_primary_key_check())
thd->variables.sql_require_primary_key =
(rli->get_require_table_primary_key_check() ==
Relay_log_info::PK_CHECK_ON);
w->set_require_table_primary_key_check(
rli->get_require_table_primary_key_check());
thd->variables.sql_generate_invisible_primary_key = false;
if (thd->rpl_thd_ctx.get_rpl_channel_type() != GR_APPLIER_CHANNEL &&
thd->rpl_thd_ctx.get_rpl_channel_type() != GR_RECOVERY_CHANNEL &&
Relay_log_info::PK_CHECK_GENERATE ==
rli->get_require_table_primary_key_check()) {
thd->variables.sql_generate_invisible_primary_key = true;
}
thd_manager->add_thd(thd);
thd_added = true;
if (w->update_is_transactional()) {
rli->report(ERROR_LEVEL, ER_REPLICA_FATAL_ERROR,
ER_THD(thd, ER_REPLICA_FATAL_ERROR),
"Error checking if the worker repository is transactional.");
goto err;
}
if (rli->get_commit_order_manager() != nullptr)
rli->get_commit_order_manager()->init_worker_context(
*w); // Initialize worker context within Commit_order_manager
mysql_mutex_lock(&w->jobs_lock);
w->running_status = Slave_worker::RUNNING;
mysql_cond_signal(&w->jobs_cond);
mysql_mutex_unlock(&w->jobs_lock);
assert(thd->is_slave_error == 0);
w->stats_exec_time = w->stats_read_time = 0;
set_timespec_nsec(&w->ts_exec[0], 0);
set_timespec_nsec(&w->ts_exec[1], 0);
set_timespec_nsec(&w->stats_begin, 0);
// No need to report anything, all error handling will be performed in the
// slave SQL thread.
if (!rli->check_privilege_checks_user())
rli->initialize_security_context(w->info_thd); // Worker security context
// initialization with
// `PRIVILEGE_CHECKS_USER`
while (!error) {
error = slave_worker_exec_job_group(w, rli);
}
/*
Cleanup after an error requires clear_error() go first.
Otherwise assert(!all) in binlog_rollback()
*/
thd->clear_error();
w->cleanup_context(thd, error);
mysql_mutex_lock(&w->jobs_lock);
while (w->jobs.de_queue(job_item)) {
purge_cnt++;
purge_size += job_item->data->common_header->data_written;
assert(job_item->data);
delete job_item->data;
}
assert(w->jobs.get_length() == 0);
mysql_mutex_unlock(&w->jobs_lock);
mysql_mutex_lock(&rli->pending_jobs_lock);
rli->pending_jobs -= purge_cnt;
rli->mts_pending_jobs_size -= purge_size;
assert(rli->mts_pending_jobs_size < rli->mts_pending_jobs_size_max);
mysql_mutex_unlock(&rli->pending_jobs_lock);
/*
In MTS case cleanup_after_session() has be called explicitly.
TODO: to make worker thd be deleted before Slave_worker instance.
*/
if (thd->rli_slave) {
w->cleanup_after_session();
thd->rli_slave = nullptr;
}
mysql_mutex_lock(&w->jobs_lock);
struct timespec stats_end;
set_timespec_nsec(&stats_end, 0);
DBUG_PRINT("info",
("Worker %lu statistics: "
"events processed = %lu "
"online time = %llu "
"events exec time = %llu "
"events read time = %llu "
"hungry waits = %lu "
"priv queue overfills = %llu ",
w->id, w->events_done, diff_timespec(&stats_end, &w->stats_begin),
w->stats_exec_time, w->stats_read_time, w->wq_empty_waits,
w->jobs.waited_overfill));
w->running_status = Slave_worker::NOT_RUNNING;
mysql_cond_signal(&w->jobs_cond); // famous last goodbye
mysql_mutex_unlock(&w->jobs_lock);
err:
if (thd) {
/*
The slave code is very bad. Notice that it is missing
several clean up calls here. I've just added what was
necessary to avoid valgrind errors.
/Alfranio
*/
thd->get_protocol_classic()->end_net();
/*
to avoid close_temporary_tables() closing temp tables as those
are Coordinator's burden.
*/
thd->system_thread = NON_SYSTEM_THREAD;
thd->release_resources();
THD_CHECK_SENTRY(thd);
if (thd_added) thd_manager->remove_thd(thd);
mysql_thread_set_psi_THD(nullptr);
delete thd;
}
my_thread_end();
#if OPENSSL_VERSION_NUMBER < 0x10100000L
ERR_remove_thread_state(0);
#endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */
my_thread_exit(nullptr);
return nullptr;
}
} // extern "C"
/**
Orders jobs by comparing relay log information.
*/
int mts_event_coord_cmp(LOG_POS_COORD *id1, LOG_POS_COORD *id2) {
longlong filecmp = strcmp(id1->file_name, id2->file_name);
longlong poscmp = id1->pos - id2->pos;
return (filecmp < 0
? -1
: (filecmp > 0 ? 1 : (poscmp < 0 ? -1 : (poscmp > 0 ? 1 : 0))));
}
bool mts_recovery_groups(Relay_log_info *rli) {
Log_event *ev = nullptr;
bool is_error = false;
bool flag_group_seen_begin = false;
uint recovery_group_cnt = 0;
bool not_reached_commit = true;
// Value-initialization, to avoid compiler warnings on push_back.
Slave_job_group job_worker = Slave_job_group();
LOG_INFO linfo;
my_off_t offset = 0;
MY_BITMAP *groups = &rli->recovery_groups;
THD *thd = current_thd;
DBUG_TRACE;
assert(rli->replica_parallel_workers == 0);
/*
Although mts_recovery_groups() is reentrant it returns
early if the previous invocation raised any bit in
recovery_groups bitmap.
*/
if (rli->is_mts_recovery()) return false;
/*
The process of relay log recovery for the multi threaded applier
is focused on marking transactions as already executed so they are
skipped when the SQL thread applies them.
This is important as the position stored for the last executed relay log
position may be behind what transactions workers already handled.
When GTID_MODE=ON however we can use the old relay log position, even if
stale as applied transactions will be skipped due to GTIDs auto skip
feature.
*/
if (global_gtid_mode.get() == Gtid_mode::ON && rli->mi &&
rli->mi->is_auto_position()) {
rli->mts_recovery_group_cnt = 0;
return false;
}
/*
Save relay log position to compare with worker's position.
*/
LOG_POS_COORD cp = {const_cast<char *>(rli->get_group_master_log_name()),
rli->get_group_master_log_pos()};
/*
Gathers information on valuable workers and stores it in
above_lwm_jobs in asc ordered by the master binlog coordinates.
*/
Prealloced_array<Slave_job_group, 16> above_lwm_jobs(PSI_NOT_INSTRUMENTED);
above_lwm_jobs.reserve(rli->recovery_parallel_workers);
/*
When info tables are used and autocommit= 0 we force a new
transaction start to avoid table access deadlocks when START SLAVE
is executed after STOP SLAVE with MTS enabled.
*/
if (is_autocommit_off_and_infotables(thd))
if (trans_begin(thd)) goto err;
for (uint id = 0; id < rli->recovery_parallel_workers; id++) {
Slave_worker *worker =
Rpl_info_factory::create_worker(opt_rli_repository_id, id, rli, true);
if (!worker) {
if (is_autocommit_off_and_infotables(thd)) trans_rollback(thd);
goto err;
}
LOG_POS_COORD w_last = {
const_cast<char *>(worker->get_group_master_log_name()),
worker->get_group_master_log_pos()};
if (mts_event_coord_cmp(&w_last, &cp) > 0) {
/*
Inserts information into a dynamic array for further processing.
The jobs/workers are ordered by the last checkpoint positions
workers have seen.
*/
job_worker.worker = worker;
job_worker.checkpoint_log_pos = worker->checkpoint_master_log_pos;
job_worker.checkpoint_log_name = worker->checkpoint_master_log_name;
above_lwm_jobs.push_back(job_worker);
} else {
/*
Deletes the worker because its jobs are included in the latest
checkpoint.
*/
delete worker;
}
}
/*
When info tables are used and autocommit= 0 we force transaction
commit to avoid table access deadlocks when START SLAVE is executed
after STOP SLAVE with MTS enabled.
*/
if (is_autocommit_off_and_infotables(thd))
if (trans_commit(thd)) goto err;
/*
In what follows, the group Recovery Bitmap is constructed.
seek(lwm);
while(w= next(above_lwm_w))
do
read G
if G == w->last_comm
w.B << group_cnt++;
RB |= w.B;
break;
else
group_cnt++;
while(!eof);
continue;
*/
assert(!rli->recovery_groups_inited);
if (!above_lwm_jobs.empty()) {
bitmap_init(groups, nullptr, MTS_MAX_BITS_IN_GROUP);
rli->recovery_groups_inited = true;
bitmap_clear_all(groups);
}
rli->mts_recovery_group_cnt = 0;
for (Slave_job_group *jg = above_lwm_jobs.begin(); jg != above_lwm_jobs.end();
++jg) {
Slave_worker *w = jg->worker;
LOG_POS_COORD w_last = {const_cast<char *>(w->get_group_master_log_name()),
w->get_group_master_log_pos()};
LogErr(INFORMATION_LEVEL,
ER_RPL_MTA_GROUP_RECOVERY_APPLIER_METADATA_FOR_WORKER, w->id,
w->get_group_relay_log_name(), w->get_group_relay_log_pos(),
w->get_group_master_log_name(), w->get_group_master_log_pos());
recovery_group_cnt = 0;
not_reached_commit = true;
if (rli->relay_log.find_log_pos(&linfo, rli->get_group_relay_log_name(),
true)) {
LogErr(ERROR_LEVEL, ER_RPL_ERROR_LOOKING_FOR_LOG,
rli->get_group_relay_log_name());
goto err;
}
offset = rli->get_group_relay_log_pos();
Relaylog_file_reader relaylog_file_reader(opt_replica_sql_verify_checksum);
while (not_reached_commit) {
if (relaylog_file_reader.open(linfo.log_file_name, offset)) {
LogErr(ERROR_LEVEL, ER_BINLOG_FILE_OPEN_FAILED,
relaylog_file_reader.get_error_str());
goto err;
}
while (not_reached_commit &&
(ev = relaylog_file_reader.read_event_object())) {
assert(ev->is_valid());
if (ev->get_type_code() == binary_log::ROTATE_EVENT ||
ev->get_type_code() == binary_log::FORMAT_DESCRIPTION_EVENT ||
ev->get_type_code() == binary_log::PREVIOUS_GTIDS_LOG_EVENT) {
delete ev;
ev = nullptr;
continue;
}
DBUG_PRINT(
"mta",
("Event Recoverying relay log info "
"group_mster_log_name %s, event_source_log_pos %llu type code %u.",
linfo.log_file_name, ev->common_header->log_pos,
ev->get_type_code()));
if (ev->starts_group()) {
flag_group_seen_begin = true;
} else if ((ev->ends_group() || !flag_group_seen_begin) &&
!is_gtid_event(ev)) {
int ret = 0;
LOG_POS_COORD ev_coord = {
const_cast<char *>(rli->get_group_master_log_name()),
ev->common_header->log_pos};
flag_group_seen_begin = false;
recovery_group_cnt++;
LogErr(INFORMATION_LEVEL, ER_RPL_MTA_GROUP_RECOVERY_APPLIER_METADATA,
rli->get_group_master_log_name_info(),
ev->common_header->log_pos);
if ((ret = mts_event_coord_cmp(&ev_coord, &w_last)) == 0) {
#ifndef NDEBUG
for (uint i = 0; i <= w->worker_checkpoint_seqno; i++) {
if (bitmap_is_set(&w->group_executed, i))
DBUG_PRINT("mta", ("Bit %u is set.", i));
else
DBUG_PRINT("mta", ("Bit %u is not set.", i));
}
#endif
DBUG_PRINT("mta",
("Doing a shift ini(%lu) end(%lu).",
(w->worker_checkpoint_seqno + 1) - recovery_group_cnt,
w->worker_checkpoint_seqno));
for (uint i = (w->worker_checkpoint_seqno + 1) - recovery_group_cnt,
j = 0;
i <= w->worker_checkpoint_seqno; i++, j++) {
if (bitmap_is_set(&w->group_executed, i)) {
DBUG_PRINT("mta", ("Setting bit %u.", j));
bitmap_test_and_set(groups, j);
}
}
not_reached_commit = false;
} else
assert(ret < 0);
}
delete ev;
ev = nullptr;
}
relaylog_file_reader.close();
offset = BIN_LOG_HEADER_SIZE;
if (not_reached_commit && rli->relay_log.find_next_log(&linfo, true)) {
LogErr(ERROR_LEVEL, ER_RPL_CANT_FIND_FOLLOWUP_FILE,
linfo.log_file_name);
goto err;
}
}
rli->mts_recovery_group_cnt =
(rli->mts_recovery_group_cnt < recovery_group_cnt
? recovery_group_cnt
: rli->mts_recovery_group_cnt);
}
assert(!rli->recovery_groups_inited ||
rli->mts_recovery_group_cnt <= groups->n_bits);
goto end;
err:
is_error = true;
end:
for (Slave_job_group *jg = above_lwm_jobs.begin(); jg != above_lwm_jobs.end();
++jg) {
delete jg->worker;
}
if (rli->mts_recovery_group_cnt == 0) rli->clear_mts_recovery_groups();
return is_error;
}
bool mta_checkpoint_routine(Relay_log_info *rli, bool force) {
ulong cnt;
bool error = false;
time_t ts = 0;
DBUG_TRACE;
#ifndef NDEBUG
if (DBUG_EVALUATE_IF("check_replica_debug_group", 1, 0)) {
if (!rli->gaq->count_done(rli)) return false;
}
DBUG_EXECUTE_IF("mta_checkpoint", {
rpl_replica_debug_point(DBUG_RPL_S_MTS_CHECKPOINT_START, rli->info_thd);
};);
#endif
/*
rli->checkpoint_group can have two possible values due to
two possible status of the last (being scheduled) group.
*/
assert(!rli->gaq->full() ||
((rli->rli_checkpoint_seqno == rli->checkpoint_group - 1 &&
(rli->mts_group_status == Relay_log_info::MTS_IN_GROUP ||
rli->mts_group_status == Relay_log_info::MTS_KILLED_GROUP)) ||
rli->rli_checkpoint_seqno == rli->checkpoint_group));
do {
if (!is_mts_db_partitioned(rli)) mysql_mutex_lock(&rli->mts_gaq_LOCK);
cnt = rli->gaq->move_queue_head(&rli->workers);
if (!is_mts_db_partitioned(rli)) mysql_mutex_unlock(&rli->mts_gaq_LOCK);
#ifndef NDEBUG
if (DBUG_EVALUATE_IF("check_replica_debug_group", 1, 0) &&
cnt != opt_mta_checkpoint_period)
LogErr(ERROR_LEVEL, ER_RPL_MTA_CHECKPOINT_PERIOD_DIFFERS_FROM_CNT);
#endif
} while (!sql_slave_killed(rli->info_thd, rli) && cnt == 0 && force &&
!DBUG_EVALUATE_IF("check_replica_debug_group", 1, 0) &&
(my_sleep(rli->mts_coordinator_basic_nap), 1));
/*
This checks how many consecutive jobs where processed.
If this value is different than zero the checkpoint
routine can proceed. Otherwise, there is nothing to be
done.
*/
if (cnt == 0) goto end;
/*
The workers have completed cnt jobs from the gaq. This means that we
should increment C->jobs_done by cnt.
*/
if (!is_mts_worker(rli->info_thd) && !is_mts_db_partitioned(rli)) {
DBUG_PRINT("info", ("jobs_done this itr=%ld", cnt));
static_cast<Mts_submode_logical_clock *>(rli->current_mts_submode)
->jobs_done += cnt;
}
mysql_mutex_lock(&rli->data_lock);
/*
"Coordinator::commit_positions"
rli->gaq->lwm has been updated in move_queue_head() and
to contain all but rli->group_master_log_name which
is altered solely by Coordinator at special checkpoints.
*/
rli->set_group_master_log_pos(rli->gaq->lwm.group_master_log_pos);
rli->set_group_relay_log_pos(rli->gaq->lwm.group_relay_log_pos);
DBUG_PRINT(
"mta",
("New checkpoint %llu %llu %s", rli->gaq->lwm.group_master_log_pos,
rli->gaq->lwm.group_relay_log_pos, rli->gaq->lwm.group_relay_log_name));
if (rli->gaq->lwm.group_relay_log_name[0] != 0)
rli->set_group_relay_log_name(rli->gaq->lwm.group_relay_log_name);
/*
todo: uncomment notifies when UNTIL will be supported
rli->notify_group_master_log_name_update();
rli->notify_group_relay_log_name_update();
Todo: optimize with if (wait_flag) broadcast
waiter: set wait_flag; waits....; drops wait_flag;
*/
error = rli->flush_info(Relay_log_info::RLI_FLUSH_IGNORE_SYNC_OPT);
mysql_cond_broadcast(&rli->data_cond);
mysql_mutex_unlock(&rli->data_lock);
/*
We need to ensure that this is never called at this point when
cnt is zero. This value means that the checkpoint information
will be completely reset.
*/
/*
Update the rli->last_master_timestamp for reporting correct
Seconds_behind_master.
If GAQ is empty, set it to zero.
Else, update it with the timestamp of the first job of the Slave_job_queue
which was assigned in the Log_event::get_slave_worker() function.
*/
ts = rli->gaq->empty()
? 0
: reinterpret_cast<Slave_job_group *>(rli->gaq->head_queue())->ts;
rli->reset_notified_checkpoint(cnt, ts, true);
/* end-of "Coordinator::commit_positions" */
end:
error = error || rli->info_thd->killed != THD::NOT_KILLED;
#ifndef NDEBUG
if (DBUG_EVALUATE_IF("check_replica_debug_group", 1, 0)) DBUG_SUICIDE();
DBUG_EXECUTE_IF("mta_checkpoint", {
rpl_replica_debug_point(DBUG_RPL_S_MTS_CHECKPOINT_END, rli->info_thd);
};);
#endif
set_timespec_nsec(&rli->last_clock, 0);
return error;
}
/**
Instantiation of a Slave_worker and forking out a single Worker thread.
@param rli Coordinator's Relay_log_info pointer
@param i identifier of the Worker
@return 0 suppress or 1 if fails
*/
static int slave_start_single_worker(Relay_log_info *rli, ulong i) {
int error = 0;
my_thread_handle th;
Slave_worker *w = nullptr;
mysql_mutex_assert_owner(&rli->run_lock);
if (!(w = Rpl_info_factory::create_worker(opt_rli_repository_id, i, rli,
false))) {
LogErr(ERROR_LEVEL, ER_RPL_REPLICA_WORKER_THREAD_CREATION_FAILED,
rli->get_for_channel_str());
error = 1;
goto err;
}
if (w->init_worker(rli, i)) {
LogErr(ERROR_LEVEL, ER_RPL_REPLICA_WORKER_THREAD_CREATION_FAILED,
rli->get_for_channel_str());
error = 1;
goto err;
}
// We assume that workers are added in sequential order here.
assert(i == rli->workers.size());
if (i >= rli->workers.size()) rli->workers.resize(i + 1);
rli->workers[i] = w;
if (DBUG_EVALUATE_IF("mta_worker_thread_fails", i == 1, 0) ||
(error = mysql_thread_create(key_thread_replica_worker, &th,
&connection_attrib, handle_slave_worker,
(void *)w))) {
LogErr(ERROR_LEVEL, ER_RPL_REPLICA_WORKER_THREAD_CREATION_FAILED_WITH_ERRNO,
rli->get_for_channel_str(), error);
error = 1;
goto err;
}
mysql_mutex_lock(&w->jobs_lock);
if (w->running_status == Slave_worker::NOT_RUNNING)
mysql_cond_wait(&w->jobs_cond, &w->jobs_lock);
mysql_mutex_unlock(&w->jobs_lock);
err:
if (error && w) {
// Free the current submode object
delete w->current_mts_submode;
w->current_mts_submode = nullptr;
delete w;
/*
Any failure after array inserted must follow with deletion
of just created item.
*/
if (rli->workers.size() == i + 1) rli->workers.erase(i);
}
return error;
}
/**
Initialization of the central rli members for Coordinator's role,
communication channels such as Assigned Partition Hash (APH),
and starting the Worker pool.
@param rli Pointer to Coordinator's Relay_log_info instance.
@param n Number of configured Workers in the upcoming session.
@param[out] mts_inited If the initialization processed was started.
@return 0 success
non-zero as failure
*/
static int slave_start_workers(Relay_log_info *rli, ulong n, bool *mts_inited) {
int error = 0;
/**
gtid_monitoring_info must be cleared when MTS is enabled or
workers_copy_pfs has elements
*/
bool clear_gtid_monitoring_info = false;
mysql_mutex_assert_owner(&rli->run_lock);
if (n == 0 && rli->mts_recovery_group_cnt == 0) {
rli->workers.clear();
rli->clear_processing_trx();
goto end;
}
*mts_inited = true;
/*
The requested through argument number of Workers can be different
from the previous time which ended with an error. Thereby
the effective number of configured Workers is max of the two.
*/
rli->init_workers(max(n, rli->recovery_parallel_workers));
rli->last_assigned_worker = nullptr; // associated with curr_group_assigned
/*
GAQ queue holds seqno:s of scheduled groups. C polls workers in
@c opt_mta_checkpoint_period to update GAQ (see @c next_event())
The length of GAQ is set to be equal to checkpoint_group.
Notice, the size matters for mta_checkpoint_routine's progress loop.
*/
rli->gaq = new Slave_committed_queue(rli->checkpoint_group, n);
if (!rli->gaq->inited) return 1;
// length of WQ is actually constant though can be made configurable
rli->mts_slave_worker_queue_len_max = mts_slave_worker_queue_len_max;
rli->mts_pending_jobs_size = 0;
rli->mts_pending_jobs_size_max = ::opt_mts_pending_jobs_size_max;
rli->mts_wq_underrun_w_id = MTS_WORKER_UNDEF;
rli->mts_wq_excess_cnt = 0;
rli->mts_wq_overrun_cnt = 0;
rli->mts_wq_oversize = false;
rli->mts_coordinator_basic_nap = mts_coordinator_basic_nap;
rli->mts_worker_underrun_level = mts_worker_underrun_level;
rli->curr_group_seen_begin = rli->curr_group_seen_gtid = false;
rli->curr_group_isolated = false;
rli->rli_checkpoint_seqno = 0;
rli->mts_last_online_stat = time(nullptr);
rli->mts_group_status = Relay_log_info::MTS_NOT_IN_GROUP;
clear_gtid_monitoring_info = true;
if (init_hash_workers(rli)) // MTS: mapping_db_to_worker
{
LogErr(ERROR_LEVEL, ER_RPL_REPLICA_FAILED_TO_INIT_PARTITIONS_HASH);
error = 1;
goto err;
}
for (uint i = 0; i < n; i++) {
if ((error = slave_start_single_worker(rli, i))) goto err;
rli->replica_parallel_workers++;
}
end:
/*
Free the buffer that was being used to report worker's status through
the table performance_schema.table_replication_applier_status_by_worker
between stop slave and next start slave.
*/
for (int i = static_cast<int>(rli->workers_copy_pfs.size()) - 1; i >= 0;
i--) {
delete rli->workers_copy_pfs[i];
if (!clear_gtid_monitoring_info) clear_gtid_monitoring_info = true;
}
rli->workers_copy_pfs.clear();
// Effective end of the recovery right now when there is no gaps
if (!error && rli->mts_recovery_group_cnt == 0) {
if ((error = rli->mts_finalize_recovery()))
(void)Rpl_info_factory::reset_workers(rli);
if (!error)
error = rli->flush_info(Relay_log_info::RLI_FLUSH_IGNORE_SYNC_OPT);
}
err:
if (clear_gtid_monitoring_info) rli->clear_gtid_monitoring_info();
return error;
}
/*
Ending Worker threads.
Not in case Coordinator is killed itself, it first waits for
Workers have finished their assignments, and then updates checkpoint.
Workers are notified with setting KILLED status
and waited for their acknowledgment as specified by
worker's running_status.
Coordinator finalizes with its MTS running status to reset few objects.
*/
static void slave_stop_workers(Relay_log_info *rli, bool *mts_inited) {
THD *thd = rli->info_thd;
if (!*mts_inited)
return;
else if (rli->replica_parallel_workers == 0)
goto end;
/*
If request for stop slave is received notify worker
to stop.
*/
// Initialize worker exit count and max_updated_index to 0 during each stop.
rli->exit_counter = 0;
rli->max_updated_index = (rli->until_condition != Relay_log_info::UNTIL_NONE)
? rli->mts_groups_assigned
: 0;
if (!rli->workers.empty()) {
for (int i = static_cast<int>(rli->workers.size()) - 1; i >= 0; i--) {
Slave_worker *w = rli->workers[i];
struct slave_job_item item = {nullptr, 0, {'\0'}};
struct slave_job_item *job_item = &item;
mysql_mutex_lock(&w->jobs_lock);
if (w->running_status != Slave_worker::RUNNING) {
mysql_mutex_unlock(&w->jobs_lock);
continue;
}
w->running_status = Slave_worker::STOP;
(void)set_max_updated_index_on_stop(w, job_item);
mysql_cond_signal(&w->jobs_cond);
mysql_mutex_unlock(&w->jobs_lock);
DBUG_PRINT("info", ("Notifying worker %lu%s to exit, thd %p", w->id,
w->get_for_channel_str(), w->info_thd));
}
}
thd_proc_info(thd, "Waiting for workers to exit");
for (Slave_worker **it = rli->workers.begin(); it != rli->workers.end();
++it) {
Slave_worker *w = *it;
mysql_mutex_lock(&w->jobs_lock);
while (w->running_status != Slave_worker::NOT_RUNNING) {
PSI_stage_info old_stage;
assert(w->running_status == Slave_worker::ERROR_LEAVING ||
w->running_status == Slave_worker::STOP ||
w->running_status == Slave_worker::STOP_ACCEPTED);
thd->ENTER_COND(&w->jobs_cond, &w->jobs_lock,
&stage_replica_waiting_workers_to_exit, &old_stage);
mysql_cond_wait(&w->jobs_cond, &w->jobs_lock);
mysql_mutex_unlock(&w->jobs_lock);
thd->EXIT_COND(&old_stage);
mysql_mutex_lock(&w->jobs_lock);
}
mysql_mutex_unlock(&w->jobs_lock);
}
for (Slave_worker **it = rli->workers.begin(); it != rli->workers.end();
++it) {
Slave_worker *w = *it;
/*
Make copies for reporting through the performance schema tables.
This is preserved until the next START SLAVE.
*/
Slave_worker *worker_copy = new Slave_worker(
nullptr,
#ifdef HAVE_PSI_INTERFACE
&key_relay_log_info_run_lock, &key_relay_log_info_data_lock,
&key_relay_log_info_sleep_lock, &key_relay_log_info_thd_lock,
&key_relay_log_info_data_cond, &key_relay_log_info_start_cond,
&key_relay_log_info_stop_cond, &key_relay_log_info_sleep_cond,
#endif
w->id, rli->get_channel());
worker_copy->copy_values_for_PFS(w->id, w->running_status, w->info_thd,
w->last_error(),
w->get_gtid_monitoring_info());
rli->workers_copy_pfs.push_back(worker_copy);
}
/// @todo: consider to propagate an error out of the function
if (thd->killed == THD::NOT_KILLED) (void)mta_checkpoint_routine(rli, false);
{
MUTEX_LOCK(lock, &rli->data_lock);
while (!rli->workers.empty()) {
Slave_worker *w = rli->workers.back();
// Free the current submode object
delete w->current_mts_submode;
w->current_mts_submode = nullptr;
rli->workers.pop_back();
delete w;
}
}
struct timespec stats_end;
set_timespec_nsec(&stats_end, 0);
DBUG_PRINT(
"info",
("Total MTA session statistics: "
"events processed = %llu; "
"online time = %llu "
"worker queues filled over overrun level = %lu "
"waited due a Worker queue full = %lu "
"waited due the total size = %lu "
"total wait at clock conflicts = %llu "
"found (count) workers occupied = %lu "
"waited when workers occupied = %llu",
rli->mts_events_assigned, diff_timespec(&stats_end, &rli->stats_begin),
rli->mts_wq_overrun_cnt, rli->mts_wq_overfill_cnt,
rli->wq_size_waits_cnt, rli->mts_total_wait_overlap.load(),
rli->mts_wq_no_underrun_cnt, rli->mts_total_wait_worker_avail));
assert(rli->pending_jobs == 0);
assert(rli->mts_pending_jobs_size == 0);
end:
rli->mts_group_status = Relay_log_info::MTS_NOT_IN_GROUP;
destroy_hash_workers(rli);
delete rli->gaq;
// Destroy buffered events of the current group prior to exit.
for (uint i = 0; i < rli->curr_group_da.size(); i++)
delete rli->curr_group_da[i].data;
rli->curr_group_da.clear(); // GCDA
rli->curr_group_assigned_parts.clear(); // GCAP
rli->deinit_workers();
rli->workers_array_initialized = false;
rli->replica_parallel_workers = 0;
*mts_inited = false;
}
/**
Processes the outcome of applying an event, logs it properly if it's an error
and return the proper error code to trigger.
@return the error code to bubble up in the execution stack.
*/
static int report_apply_event_error(THD *thd, Relay_log_info *rli) {
DBUG_TRACE;
longlong slave_errno = 0;
/*
retrieve as much info as possible from the thd and, error
codes and warnings and print this to the error log as to
allow the user to locate the error
*/
uint32 const last_errno = rli->last_error().number;
if (thd->is_error()) {
char const *const errmsg = thd->get_stmt_da()->message_text();
DBUG_PRINT("info", ("thd->get_stmt_da()->get_mysql_errno()=%d; "
"rli->last_error.number=%d",
thd->get_stmt_da()->mysql_errno(), last_errno));
if (last_errno == 0) {
/*
This function is reporting an error which was not reported
while executing exec_relay_log_event().
*/
rli->report(ERROR_LEVEL, thd->get_stmt_da()->mysql_errno(), "%s", errmsg);
} else if (last_errno != thd->get_stmt_da()->mysql_errno()) {
/*
* An error was reported while executing exec_relay_log_event()
* however the error code differs from what is in the thread.
* This function prints out more information to help finding
* what caused the problem.
*/
LogErr(ERROR_LEVEL, ER_RPL_REPLICA_ADDITIONAL_ERROR_INFO_FROM_DA, errmsg,
thd->get_stmt_da()->mysql_errno());
}
}
/* Print any warnings issued */
Diagnostics_area::Sql_condition_iterator it =
thd->get_stmt_da()->sql_conditions();
const Sql_condition *err;
/*
Added controlled slave thread cancel for replication
of user-defined variables.
*/
bool udf_error = false;
while ((err = it++)) {
if (err->mysql_errno() == ER_CANT_OPEN_LIBRARY) udf_error = true;
LogErr(WARNING_LEVEL, ER_RPL_REPLICA_ERROR_INFO_FROM_DA,
err->message_text(), err->mysql_errno());
}
if (udf_error)
slave_errno = ER_RPL_REPLICA_ERROR_LOADING_USER_DEFINED_LIBRARY;
else
slave_errno = ER_RPL_REPLICA_ERROR_RUNNING_QUERY;
return slave_errno;
}
/**
Slave SQL thread entry point.
@param arg Pointer to Relay_log_info object that holds information
for the SQL thread.
@return Always 0.
*/
extern "C" void *handle_slave_sql(void *arg) {
THD *thd; /* needs to be first for thread_stack */
bool thd_added = false;
bool main_loop_error = false;
char llbuff[22], llbuff1[22];
char saved_log_name[FN_REFLEN];
char saved_master_log_name[FN_REFLEN];
my_off_t saved_log_pos = 0;
my_off_t saved_master_log_pos = 0;
my_off_t saved_skip = 0;
Relay_log_info *rli = ((Master_info *)arg)->rli;
const char *errmsg;
longlong slave_errno = 0;
bool mts_inited = false;
Global_THD_manager *thd_manager = Global_THD_manager::get_instance();
Commit_order_manager *commit_order_mngr = nullptr;
Rpl_applier_reader applier_reader(rli);
Relay_log_info::enum_priv_checks_status priv_check_status =
Relay_log_info::enum_priv_checks_status::SUCCESS;
// needs to call my_thread_init(), otherwise we get a coredump in DBUG_ stuff
my_thread_init();
{
DBUG_TRACE;
assert(rli->inited);
mysql_mutex_lock(&rli->run_lock);
assert(!rli->slave_running);
errmsg = nullptr;
#ifndef NDEBUG
rli->events_until_exit = abort_slave_event_count;
#endif
thd = new THD; // note that constructor of THD uses DBUG_ !
thd->thread_stack = (char *)&thd; // remember where our stack is
mysql_mutex_lock(&rli->info_thd_lock);
rli->info_thd = thd;
#ifdef HAVE_PSI_THREAD_INTERFACE
// save the instrumentation for SQL thread in rli->info_thd
struct PSI_thread *psi = PSI_THREAD_CALL(get_thread)();
thd_set_psi(rli->info_thd, psi);
#endif
mysql_thread_set_psi_THD(thd);
if (rli->channel_mts_submode != MTS_PARALLEL_TYPE_DB_NAME)
rli->current_mts_submode = new Mts_submode_logical_clock();
else
rli->current_mts_submode = new Mts_submode_database();
// Only use replica preserve commit order if more than 1 worker exists
if (opt_replica_preserve_commit_order && !rli->is_parallel_exec() &&
rli->opt_replica_parallel_workers > 1)
commit_order_mngr =
new Commit_order_manager(rli->opt_replica_parallel_workers);
rli->set_commit_order_manager(commit_order_mngr);
if (channel_map.is_group_replication_channel_name(rli->get_channel())) {
if (channel_map.is_group_replication_channel_name(rli->get_channel(),
true)) {
thd->rpl_thd_ctx.set_rpl_channel_type(GR_APPLIER_CHANNEL);
} else {
thd->rpl_thd_ctx.set_rpl_channel_type(GR_RECOVERY_CHANNEL);
}
} else {
thd->rpl_thd_ctx.set_rpl_channel_type(RPL_STANDARD_CHANNEL);
}
mysql_mutex_unlock(&rli->info_thd_lock);
/* Inform waiting threads that slave has started */
rli->slave_run_id++;
rli->slave_running = 1;
rli->reported_unsafe_warning = false;
rli->sql_thread_kill_accepted = false;
rli->last_event_start_time = 0;
if (init_replica_thread(thd, SLAVE_THD_SQL)) {
/*
TODO: this is currently broken - slave start and change master
will be stuck if we fail here
*/
mysql_cond_broadcast(&rli->start_cond);
mysql_mutex_unlock(&rli->run_lock);
rli->report(ERROR_LEVEL, ER_REPLICA_FATAL_ERROR,
ER_THD(thd, ER_REPLICA_FATAL_ERROR),
"Failed during replica thread initialization");
goto err;
}
thd->init_query_mem_roots();
if ((rli->deferred_events_collecting = rli->rpl_filter->is_on()))
rli->deferred_events = new Deferred_log_events();
thd->rli_slave = rli;
assert(thd->rli_slave->info_thd == thd);
thd->temporary_tables = rli->save_temporary_tables; // restore temp tables
set_thd_in_use_temporary_tables(
rli); // (re)set sql_thd in use for saved temp tables
/* Set applier thread InnoDB priority */
set_thd_tx_priority(thd, rli->get_thd_tx_priority());
/* Set write set related options */
set_thd_write_set_options(thd, rli->get_ignore_write_set_memory_limit(),
rli->get_allow_drop_write_set());
thd->variables.require_row_format = rli->is_row_format_required();
if (Relay_log_info::PK_CHECK_STREAM !=
rli->get_require_table_primary_key_check())
thd->variables.sql_require_primary_key =
(rli->get_require_table_primary_key_check() ==
Relay_log_info::PK_CHECK_ON);
thd->variables.sql_generate_invisible_primary_key = false;
if (thd->rpl_thd_ctx.get_rpl_channel_type() != GR_APPLIER_CHANNEL &&
thd->rpl_thd_ctx.get_rpl_channel_type() != GR_RECOVERY_CHANNEL &&
Relay_log_info::PK_CHECK_GENERATE ==
rli->get_require_table_primary_key_check()) {
thd->variables.sql_generate_invisible_primary_key = true;
}
rli->transaction_parser.reset();
thd_manager->add_thd(thd);
thd_added = true;
rli->stats_exec_time = rli->stats_read_time = 0;
set_timespec_nsec(&rli->ts_exec[0], 0);
set_timespec_nsec(&rli->ts_exec[1], 0);
set_timespec_nsec(&rli->stats_begin, 0);
if (RUN_HOOK(binlog_relay_io, applier_start, (thd, rli->mi))) {
mysql_cond_broadcast(&rli->start_cond);
mysql_mutex_unlock(&rli->run_lock);
rli->report(ERROR_LEVEL, ER_REPLICA_FATAL_ERROR,
ER_THD(thd, ER_REPLICA_FATAL_ERROR),
"Failed to run 'applier_start' hook");
goto err;
}
/* MTS: starting the worker pool */
if (slave_start_workers(rli, rli->opt_replica_parallel_workers,
&mts_inited) != 0) {
mysql_cond_broadcast(&rli->start_cond);
mysql_mutex_unlock(&rli->run_lock);
rli->report(ERROR_LEVEL, ER_REPLICA_FATAL_ERROR,
ER_THD(thd, ER_REPLICA_FATAL_ERROR),
"Failed during replica workers initialization");
goto err;
}
/*
We are going to set slave_running to 1. Assuming slave I/O thread is
alive and connected, this is going to make Seconds_Behind_Master be 0
i.e. "caught up". Even if we're just at start of thread. Well it's ok, at
the moment we start we can think we are caught up, and the next second we
start receiving data so we realize we are not caught up and
Seconds_Behind_Master grows. No big deal.
*/
rli->abort_slave = false;
/*
Reset errors for a clean start (otherwise, if the master is idle, the SQL
thread may execute no Query_log_event, so the error will remain even
though there's no problem anymore). Do not reset the master timestamp
(imagine the slave has caught everything, the STOP SLAVE and START SLAVE:
as we are not sure that we are going to receive a query, we want to
remember the last master timestamp (to say how many seconds behind we are
now.
But the master timestamp is reset by RESET SLAVE & CHANGE MASTER.
*/
rli->clear_error();
if (rli->workers_array_initialized) {
for (size_t i = 0; i < rli->get_worker_count(); i++) {
rli->get_worker(i)->clear_error();
}
}
if (rli->update_is_transactional() ||
DBUG_EVALUATE_IF("simulate_update_is_transactional_error", true,
false)) {
mysql_cond_broadcast(&rli->start_cond);
mysql_mutex_unlock(&rli->run_lock);
rli->report(
ERROR_LEVEL, ER_REPLICA_FATAL_ERROR,
ER_THD(thd, ER_REPLICA_FATAL_ERROR),
"Error checking if the relay log repository is transactional.");
goto err;
}
if (!rli->is_transactional())
rli->report(
WARNING_LEVEL, 0,
"If a crash happens this configuration does not guarantee that "
"the relay "
"log info will be consistent");
mysql_cond_broadcast(&rli->start_cond);
mysql_mutex_unlock(&rli->run_lock);
DEBUG_SYNC(thd, "after_start_replica");
rli->trans_retries = 0; // start from "no error"
DBUG_PRINT("info", ("rli->trans_retries: %lu", rli->trans_retries));
if (applier_reader.open(&errmsg)) {
rli->report(ERROR_LEVEL, ER_REPLICA_FATAL_ERROR, "%s", errmsg);
goto err;
}
THD_CHECK_SENTRY(thd);
assert(rli->info_thd == thd);
DBUG_PRINT("source_info", ("log_file_name: %s position: %s",
rli->get_group_master_log_name(),
llstr(rli->get_group_master_log_pos(), llbuff)));
if (check_temp_dir(rli->slave_patternload_file, rli->get_channel())) {
rli->report(ERROR_LEVEL, thd->get_stmt_da()->mysql_errno(),
"Unable to use replica's temporary directory %s - %s",
replica_load_tmpdir, thd->get_stmt_da()->message_text());
goto err;
}
priv_check_status = rli->check_privilege_checks_user();
if (!!priv_check_status) {
rli->report_privilege_check_error(ERROR_LEVEL, priv_check_status,
false /* to client*/);
rli->set_privilege_checks_user_corrupted(true);
goto err;
}
priv_check_status =
rli->initialize_applier_security_context(); // Applier security context
// initialization with
// `PRIVILEGE_CHECKS_USER`
if (!!priv_check_status) {
rli->report_privilege_check_error(ERROR_LEVEL, priv_check_status,
false /* to client*/);
goto err;
}
if (rli->is_privilege_checks_user_null())
LogErr(INFORMATION_LEVEL, ER_RPL_REPLICA_SQL_THREAD_STARTING,
rli->get_for_channel_str(), rli->get_rpl_log_name(),
llstr(rli->get_group_master_log_pos_info(), llbuff),
rli->get_group_relay_log_name(),
llstr(rli->get_group_relay_log_pos(), llbuff1));
else
LogErr(INFORMATION_LEVEL,
ER_RPL_REPLICA_SQL_THREAD_STARTING_WITH_PRIVILEGE_CHECKS,
rli->get_for_channel_str(), rli->get_rpl_log_name(),
llstr(rli->get_group_master_log_pos_info(), llbuff),
rli->get_group_relay_log_name(),
llstr(rli->get_group_relay_log_pos(), llbuff1),
rli->get_privilege_checks_username().c_str(),
rli->get_privilege_checks_hostname().c_str(),
opt_always_activate_granted_roles == 0 ? "DEFAULT" : "ALL");
/* execute init_replica variable */
if (opt_init_replica.length) {
execute_init_command(thd, &opt_init_replica, &LOCK_sys_init_replica);
if (thd->is_slave_error) {
rli->report(ERROR_LEVEL, ER_SERVER_REPLICA_INIT_QUERY_FAILED,
ER_THD(current_thd, ER_SERVER_REPLICA_INIT_QUERY_FAILED),
thd->get_stmt_da()->mysql_errno(),
thd->get_stmt_da()->message_text());
goto err;
}
}
/*
First check until condition - probably there is nothing to execute. We
do not want to wait for next event in this case.
*/
mysql_mutex_lock(&rli->data_lock);
if (rli->slave_skip_counter) {
strmake(saved_log_name, rli->get_group_relay_log_name(), FN_REFLEN - 1);
strmake(saved_master_log_name, rli->get_group_master_log_name(),
FN_REFLEN - 1);
saved_log_pos = rli->get_group_relay_log_pos();
saved_master_log_pos = rli->get_group_master_log_pos();
saved_skip = rli->slave_skip_counter;
}
if (rli->is_until_satisfied_at_start_slave()) {
mysql_mutex_unlock(&rli->data_lock);
goto err;
}
mysql_mutex_unlock(&rli->data_lock);
/* Read queries from the IO/THREAD until this thread is killed */
while (!main_loop_error && !sql_slave_killed(thd, rli)) {
Log_event *ev = nullptr;
THD_STAGE_INFO(thd, stage_reading_event_from_the_relay_log);
assert(rli->info_thd == thd);
THD_CHECK_SENTRY(thd);
if (saved_skip && rli->slave_skip_counter == 0) {
LogErr(INFORMATION_LEVEL, ER_RPL_REPLICA_SKIP_COUNTER_EXECUTED,
(ulong)saved_skip, saved_log_name, (ulong)saved_log_pos,
saved_master_log_name, (ulong)saved_master_log_pos,
rli->get_group_relay_log_name(),
(ulong)rli->get_group_relay_log_pos(),
rli->get_group_master_log_name_info(),
(ulong)rli->get_group_master_log_pos_info());
saved_skip = 0;
}
// read next event
mysql_mutex_lock(&rli->data_lock);
ev = applier_reader.read_next_event();
mysql_mutex_unlock(&rli->data_lock);
// set additional context as needed by the scheduler before execution
// takes place
if (ev != nullptr && rli->is_parallel_exec() &&
rli->current_mts_submode != nullptr) {
if (rli->current_mts_submode->set_multi_threaded_applier_context(*rli,
*ev)) {
goto err;
}
}
// try to execute the event
switch (exec_relay_log_event(thd, rli, &applier_reader, ev)) {
case SLAVE_APPLY_EVENT_AND_UPDATE_POS_OK:
/** success, we read the next event. */
/** fall through */
case SLAVE_APPLY_EVENT_UNTIL_REACHED:
/** this will make the main loop abort in the next iteration */
/** fall through */
case SLAVE_APPLY_EVENT_RETRY:
/** single threaded applier has to retry.
Next iteration reads the same event. */
break;
case SLAVE_APPLY_EVENT_AND_UPDATE_POS_APPLY_ERROR:
/** fall through */
case SLAVE_APPLY_EVENT_AND_UPDATE_POS_UPDATE_POS_ERROR:
/** fall through */
case SLAVE_APPLY_EVENT_AND_UPDATE_POS_APPEND_JOB_ERROR:
main_loop_error = true;
break;
default:
/* This shall never happen. */
assert(0); /* purecov: inspected */
break;
}
}
err:
// report error
if (main_loop_error == true && !sql_slave_killed(thd, rli))
slave_errno = report_apply_event_error(thd, rli);
/* At this point the SQL thread will not try to work anymore. */
rli->atomic_is_stopping = true;
(void)RUN_HOOK(
binlog_relay_io, applier_stop,
(thd, rli->mi, rli->is_error() || !rli->sql_thread_kill_accepted));
slave_stop_workers(rli, &mts_inited); // stopping worker pool
/* Thread stopped. Print the current replication position to the log */
if (slave_errno)
LogErr(ERROR_LEVEL, slave_errno, rli->get_rpl_log_name(),
llstr(rli->get_group_master_log_pos_info(), llbuff));
else
LogErr(INFORMATION_LEVEL, ER_RPL_REPLICA_SQL_THREAD_EXITING,
rli->get_for_channel_str(), rli->get_rpl_log_name(),
llstr(rli->get_group_master_log_pos_info(), llbuff));
delete rli->current_mts_submode;
rli->current_mts_submode = nullptr;
rli->clear_mts_recovery_groups();
/*
Some events set some playgrounds, which won't be cleared because thread
stops. Stopping of this thread may not be known to these events ("stop"
request is detected only by the present function, not by events), so we
must "proactively" clear playgrounds:
*/
thd->clear_error();
rli->cleanup_context(thd, true);
/*
Some extra safety, which should not been needed (normally, event deletion
should already have done these assignments (each event which sets these
variables is supposed to set them to 0 before terminating)).
*/
thd->set_catalog(NULL_CSTR);
thd->reset_query();
thd->reset_db(NULL_CSTR);
/*
Pause the SQL thread and wait for 'continue_to_stop_sql_thread'
signal to continue to shutdown the SQL thread.
*/
DBUG_EXECUTE_IF("pause_after_sql_thread_stop_hook", {
rpl_replica_debug_point(DBUG_RPL_S_AFTER_SQL_STOP, thd);
};);
THD_STAGE_INFO(thd, stage_waiting_for_replica_mutex_on_exit);
mysql_mutex_lock(&rli->run_lock);
/* We need data_lock, at least to wake up any waiting source_pos_wait() */
mysql_mutex_lock(&rli->data_lock);
applier_reader.close();
assert(rli->slave_running == 1); // tracking buffer overrun
/* When source_pos_wait() wakes up it will check this and terminate */
rli->slave_running = 0;
rli->atomic_is_stopping = false;
/* Forget the relay log's format */
if (rli->set_rli_description_event(nullptr)) {
#ifndef NDEBUG
bool set_rli_description_event_failed = false;
#endif
assert(set_rli_description_event_failed);
}
/* Wake up source_pos_wait() */
DBUG_PRINT("info",
("Signaling possibly waiting source_pos_wait() functions"));
mysql_cond_broadcast(&rli->data_cond);
mysql_mutex_unlock(&rli->data_lock);
/* we die so won't remember charset - re-update them on next thread start */
rli->cached_charset_invalidate();
rli->save_temporary_tables = thd->temporary_tables;
/*
TODO: see if we can do this conditionally in next_event() instead
to avoid unneeded position re-init
*/
thd->temporary_tables =
nullptr; // remove temptation from destructor to close them
// destructor will not free it, because we are weird
thd->get_protocol_classic()->end_net();
assert(rli->info_thd == thd);
THD_CHECK_SENTRY(thd);
mysql_mutex_lock(&rli->info_thd_lock);
rli->info_thd = nullptr;
if (commit_order_mngr) {
rli->set_commit_order_manager(nullptr);
delete commit_order_mngr;
}
mysql_mutex_unlock(&rli->info_thd_lock);
set_thd_in_use_temporary_tables(
rli); // (re)set info_thd in use for saved temp tables
thd->release_resources();
THD_CHECK_SENTRY(thd);
if (thd_added) thd_manager->remove_thd(thd);
/*
The thd can only be destructed after indirect references
through mi->rli->info_thd are cleared: mi->rli->info_thd= NULL.
For instance, user thread might be issuing show_slave_status
and attempting to read mi->rli->info_thd->proc_info().
Therefore thd must only be deleted after info_thd is set
to NULL.
*/
mysql_thread_set_psi_THD(nullptr);
delete thd;
/*
Note: the order of the broadcast and unlock calls below (first broadcast,
then unlock) is important. Otherwise a killer_thread can execute between
the calls and delete the mi structure leading to a crash! (see BUG#25306
for details)
*/
mysql_cond_broadcast(&rli->stop_cond);
DBUG_EXECUTE_IF("simulate_replica_delay_at_terminate_bug38694", sleep(5););
mysql_mutex_unlock(&rli->run_lock); // tell the world we are done
}
my_thread_end();
#if OPENSSL_VERSION_NUMBER < 0x10100000L
ERR_remove_thread_state(0);
#endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */
my_thread_exit(nullptr);
return nullptr; // Avoid compiler warnings
}
/**
Used by the slave IO thread when it receives a rotate event from the
master.
Updates the master info with the place in the next binary log where
we should start reading. Rotate the relay log to avoid mixed-format
relay logs.
@param mi master_info for the slave
@param rev The rotate log event read from the master
@note The caller must hold mi->data_lock before invoking this function.
@retval 0 ok
@retval 1 error
*/
static int process_io_rotate(Master_info *mi, Rotate_log_event *rev) {
DBUG_TRACE;
mysql_mutex_assert_owner(mi->rli->relay_log.get_log_lock());
if (unlikely(!rev->is_valid())) return 1;
#ifndef NDEBUG
/*
If we do not do this, we will be getting the first
rotate event forever, so we need to not disconnect after one.
*/
if (disconnect_slave_event_count) mi->events_until_exit++;
#endif
/*
Master will send a FD event immediately after the Roate event, so don't log
the current FD event.
*/
int ret = rotate_relay_log(mi, false, false, true);
mysql_mutex_lock(&mi->data_lock);
/* Safe copy as 'rev' has been "sanitized" in Rotate_log_event's ctor */
memcpy(const_cast<char *>(mi->get_master_log_name()), rev->new_log_ident,
rev->ident_len + 1);
mi->set_master_log_pos(rev->pos);
DBUG_PRINT("info",
("new (source_log_name, source_log_pos): ('%s', %lu)",
mi->get_master_log_name(), (ulong)mi->get_master_log_pos()));
mysql_mutex_unlock(&mi->data_lock);
return ret;
}
int heartbeat_queue_event(bool is_valid, Master_info *&mi,
std::string binlog_name, uint64_t position,
unsigned long &inc_pos, bool &do_flush_mi) {
if (!is_valid) {
char errbuf[1024];
char llbuf[22];
sprintf(errbuf,
"inconsistent heartbeat event content; the event's data: "
"log_file_name %-.512s log_pos %s",
binlog_name.c_str(), llstr(position, llbuf));
mi->report(ERROR_LEVEL, ER_REPLICA_HEARTBEAT_FAILURE,
ER_THD(current_thd, ER_REPLICA_HEARTBEAT_FAILURE), errbuf);
return 1;
}
mysql_mutex_lock(&mi->data_lock);
mi->received_heartbeats++;
mi->last_heartbeat = my_getsystime() / 10;
std::string mi_log_filename{
mi->get_master_log_name() != nullptr ? mi->get_master_log_name() : ""};
/*
compare local and event's versions of log_file, log_pos.
Heartbeat is sent only after an event corresponding to the coordinates
the heartbeat carries.
Slave can not have a difference in coordinates except in the
special case when mi->get_master_log_name(), mi->get_master_log_pos()
have never been updated by Rotate event i.e when slave does not have
any history with the master (and thereafter mi->get_master_log_pos() is
NULL).
TODO: handling `when' for SHOW REPLICA STATUS' snds behind
*/
if (mi_log_filename.compare(binlog_name) != 0) {
std::ostringstream oss;
oss << "Replication heartbeat event contained the filename '" << binlog_name
<< "' which is different from '" << mi_log_filename
<< "' that was specified in earlier Rotate events.";
mi->report(ERROR_LEVEL, ER_REPLICA_HEARTBEAT_FAILURE,
ER_THD(current_thd, ER_REPLICA_HEARTBEAT_FAILURE),
oss.str().c_str());
return 1;
} else if (mi->get_master_log_pos() > position) {
std::ostringstream oss;
oss << "Replication heartbeat event contained the position " << position
<< " which is smaller than the position " << mi->get_master_log_pos()
<< " that was computed from earlier events received in the stream. "
<< "The filename is '" << mi_log_filename << "'.";
mi->report(ERROR_LEVEL, ER_REPLICA_HEARTBEAT_FAILURE,
ER_THD(current_thd, ER_REPLICA_HEARTBEAT_FAILURE),
oss.str().c_str());
return 1;
}
/*
During GTID protocol, if the master skips transactions,
a heartbeat event is sent to the slave at the end of last
skipped transaction to update coordinates.
I/O thread receives the heartbeat event and updates mi
only if the received heartbeat position is greater than
mi->get_master_log_pos(). This event is written to the
relay log as an ignored Rotate event. SQL thread reads
the rotate event only to update the coordinates corresponding
to the last skipped transaction. Note that,
we update only the positions and not the file names, as a ROTATE
EVENT from the master prior to this will update the file name.
*/
if (mi->is_auto_position() && mi->get_master_log_pos() < position &&
!mi_log_filename.empty()) {
DBUG_EXECUTE_IF("reached_heart_beat_queue_event",
{ rpl_replica_debug_point(DBUG_RPL_S_HEARTBEAT_EV); };);
mi->set_master_log_pos(position);
/*
Put this heartbeat event in the relay log as a Rotate Event.
*/
inc_pos = 0;
mysql_mutex_unlock(&mi->data_lock);
if (write_rotate_to_master_pos_into_relay_log(mi->info_thd, mi, false
/* force_flush_mi_info */))
return 0;
do_flush_mi = false; /* write_rotate_... above flushed master info */
} else
mysql_mutex_unlock(&mi->data_lock);
return 0;
}
/**
Store an event received from the master connection into the relay
log.
@param mi The Master_info object representing this connection.
@param buf Pointer to the event data.
@param event_len Length of event data.
@param do_flush_mi True to flush master info after successfully queuing the
event.
@retval QUEUE_EVENT_OK on success.
@retval QUEUE_EVENT_ERROR_QUEUING if there was an error while queuing.
@retval QUEUE_EVENT_ERROR_FLUSHING_INFO if there was an error while
flushing master info.
@todo Make this a member of Master_info.
*/
QUEUE_EVENT_RESULT queue_event(Master_info *mi, const char *buf,
ulong event_len, bool do_flush_mi) {
QUEUE_EVENT_RESULT res = QUEUE_EVENT_OK;
ulong inc_pos = 0;
Relay_log_info *rli = mi->rli;
mysql_mutex_t *log_lock = rli->relay_log.get_log_lock();
ulong s_id;
int lock_count = 0;
DBUG_EXECUTE_IF("wait_in_the_middle_of_trx", {
/*
See `gr_flush_relay_log_no_split_trx.test`
1) Add a debug sync point that holds and makes the applier thread to
wait, in the middle of a transaction -
`signal.rpl_requested_for_a_flush`.
*/
DBUG_SET("-d,wait_in_the_middle_of_trx");
const char dbug_wait[] = "now WAIT_FOR signal.rpl_requested_for_a_flush";
assert(!debug_sync_set_action(current_thd, STRING_WITH_LEN(dbug_wait)));
});
/*
inside get_master_version_and_clock()
Show-up of FD:s affects checksum_alg at once because
that changes FD_queue.
*/
enum_binlog_checksum_alg checksum_alg =
mi->checksum_alg_before_fd != binary_log::BINLOG_CHECKSUM_ALG_UNDEF
? mi->checksum_alg_before_fd
: mi->rli->relay_log.relay_log_checksum_alg;
const char *save_buf =
nullptr; // needed for checksumming the fake Rotate event
char rot_buf[LOG_EVENT_HEADER_LEN + Binary_log_event::ROTATE_HEADER_LEN +
FN_REFLEN];
Gtid gtid = {0, 0};
ulonglong immediate_commit_timestamp = 0;
ulonglong original_commit_timestamp = 0;
bool info_error{false};
binary_log::Log_event_basic_info log_event_info;
ulonglong compressed_transaction_bytes = 0;
ulonglong uncompressed_transaction_bytes = 0;
auto compression_type = binary_log::transaction::compression::type::NONE;
Log_event_type event_type = (Log_event_type)buf[EVENT_TYPE_OFFSET];
assert(checksum_alg == binary_log::BINLOG_CHECKSUM_ALG_OFF ||
checksum_alg == binary_log::BINLOG_CHECKSUM_ALG_UNDEF ||
checksum_alg == binary_log::BINLOG_CHECKSUM_ALG_CRC32);
DBUG_TRACE;
/*
Pause the IO thread execution and wait for 'continue_queuing_event'
signal to continue IO thread execution.
*/
DBUG_EXECUTE_IF("pause_on_queuing_event",
{ rpl_replica_debug_point(DBUG_RPL_S_PAUSE_QUEUING); };);
/*
FD_queue checksum alg description does not apply in a case of
FD itself. The one carries both parts of the checksum data.
*/
if (event_type == binary_log::FORMAT_DESCRIPTION_EVENT) {
checksum_alg = Log_event_footer::get_checksum_alg(buf, event_len);
}
// does not hold always because of old binlog can work with NM
// assert(checksum_alg != BINLOG_CHECKSUM_ALG_UNDEF);
// should hold unless manipulations with RL. Tests that do that
// will have to refine the clause.
assert(mi->rli->relay_log.relay_log_checksum_alg !=
binary_log::BINLOG_CHECKSUM_ALG_UNDEF);
// Emulate the network corruption
DBUG_EXECUTE_IF(
"corrupt_queue_event",
if (event_type != binary_log::FORMAT_DESCRIPTION_EVENT) {
char *debug_event_buf_c = const_cast<char *>(buf);
int debug_cor_pos = rand() % (event_len - BINLOG_CHECKSUM_LEN);
debug_event_buf_c[debug_cor_pos] = ~debug_event_buf_c[debug_cor_pos];
DBUG_PRINT("info",
("Corrupt the event at queue_event: byte on position %d",
debug_cor_pos));
DBUG_SET("");
});
binary_log_debug::debug_checksum_test =
DBUG_EVALUATE_IF("simulate_checksum_test_failure", true, false);
if (Log_event_footer::event_checksum_test(
const_cast<uchar *>(pointer_cast<const uchar *>(buf)), event_len,
checksum_alg)) {
mi->report(ERROR_LEVEL, ER_NETWORK_READ_EVENT_CHECKSUM_FAILURE, "%s",
ER_THD(current_thd, ER_NETWORK_READ_EVENT_CHECKSUM_FAILURE));
goto err;
}
/*
From now, and up to finishing queuing the event, no other thread is allowed
to write to the relay log, or to rotate it.
*/
mysql_mutex_lock(log_lock);
assert(lock_count == 0);
lock_count = 1;
if (mi->get_mi_description_event() == nullptr) {
LogErr(ERROR_LEVEL, ER_RPL_REPLICA_QUEUE_EVENT_FAILED_INVALID_CONFIGURATION,
mi->get_channel());
goto err;
}
/*
Simulate an unknown ignorable log event by rewriting a Xid
log event before queuing it into relay log.
*/
DBUG_EXECUTE_IF(
"simulate_unknown_ignorable_log_event_with_xid",
if (event_type == binary_log::XID_EVENT) {
uchar *ev_buf = const_cast<uchar *>(pointer_cast<const uchar *>(buf));
/* Overwrite the log event type with an unknown type. */
ev_buf[EVENT_TYPE_OFFSET] = binary_log::ENUM_END_EVENT + 1;
/* Set LOG_EVENT_IGNORABLE_F for the log event. */
int2store(ev_buf + FLAGS_OFFSET,
uint2korr(ev_buf + FLAGS_OFFSET) | LOG_EVENT_IGNORABLE_F);
/* Recalc event's CRC */
ha_checksum ev_crc = checksum_crc32(0L, nullptr, 0);
ev_crc = checksum_crc32(ev_crc, (const uchar *)ev_buf,
event_len - BINLOG_CHECKSUM_LEN);
int4store(&ev_buf[event_len - BINLOG_CHECKSUM_LEN], ev_crc);
/*
We will skip writing this event to the relay log in order to let
the startup procedure to not finding it and assuming this transaction
is incomplete.
But we have to keep the unknown ignorable error to let the
"stop_io_after_reading_unknown_event" debug point to work after
"queuing" this event.
*/
mysql_mutex_lock(&mi->data_lock);
mi->set_master_log_pos(mi->get_master_log_pos() + event_len);
lock_count = 2;
goto end;
});
/*
This transaction parser is used to ensure that the GTID of the transaction
(if it has one) will only be added to the Retrieved_Gtid_Set after the
last event of the transaction be queued.
It will also be used to avoid rotating the relay log in the middle of
a transaction.
*/
std::tie(info_error, log_event_info) = extract_log_event_basic_info(
buf, event_len, mi->get_mi_description_event());
if (info_error || mi->transaction_parser.feed_event(log_event_info, true)) {
/*
The transaction parser detected a problem while changing state and threw
a warning message. We are taking care of avoiding transaction boundary
issues, but it can happen.
Transaction boundary errors might happen mostly because of bad master
positioning in 'CHANGE MASTER TO' (or bad manipulation of master.info)
when GTID auto positioning is off. Errors can also happen when using
cross-version replication, replicating from a master that supports more
event types than this slave.
The IO thread will keep working and queuing events regardless of the
transaction parser error, but we will throw another warning message to
log the relay log file and position of the parser error to help
forensics.
*/
LogErr(WARNING_LEVEL,
ER_RPL_REPLICA_IO_THREAD_DETECTED_UNEXPECTED_EVENT_SEQUENCE,
mi->get_master_log_name(), mi->get_master_log_pos());
}
switch (event_type) {
case binary_log::STOP_EVENT:
/*
We needn't write this event to the relay log. Indeed, it just indicates
a master server shutdown. The only thing this does is cleaning. But
cleaning is already done on a per-master-thread basis (as the master
server is shutting down cleanly, it has written all DROP TEMPORARY TABLE
prepared statements' deletion are TODO only when we binlog prep stmts).
We don't even increment mi->get_master_log_pos(), because we may be just
after a Rotate event. Btw, in a few milliseconds we are going to have a
Start event from the next binlog (unless the master is presently running
without --log-bin).
*/
do_flush_mi = false;
goto end;
case binary_log::ROTATE_EVENT: {
Format_description_log_event *fde = mi->get_mi_description_event();
enum_binlog_checksum_alg fde_checksum_alg = fde->footer()->checksum_alg;
if (fde_checksum_alg != checksum_alg)
fde->footer()->checksum_alg = checksum_alg;
Rotate_log_event rev(buf, fde);
fde->footer()->checksum_alg = fde_checksum_alg;
if (unlikely(process_io_rotate(mi, &rev))) {
// This error will be reported later at handle_slave_io().
goto err;
}
/*
Checksum special cases for the fake Rotate (R_f) event caused by the
protocol of events generation and serialization in RL where Rotate of
master is queued right next to FD of slave. Since it's only FD that
carries the alg desc of FD_s has to apply to R_m. Two special rules
apply only to the first R_f which comes in before any FD_m. The 2nd R_f
should be compatible with the FD_s that must have taken over the last
seen FD_m's (A).
RSC_1: If OM \and fake Rotate \and slave is configured to
to compute checksum for its first FD event for RL
the fake Rotate gets checksummed here.
*/
if (uint4korr(&buf[0]) == 0 &&
checksum_alg == binary_log::BINLOG_CHECKSUM_ALG_OFF &&
mi->rli->relay_log.relay_log_checksum_alg !=
binary_log::BINLOG_CHECKSUM_ALG_OFF) {
ha_checksum rot_crc = checksum_crc32(0L, nullptr, 0);
event_len += BINLOG_CHECKSUM_LEN;
memcpy(rot_buf, buf, event_len - BINLOG_CHECKSUM_LEN);
int4store(&rot_buf[EVENT_LEN_OFFSET],
uint4korr(rot_buf + EVENT_LEN_OFFSET) + BINLOG_CHECKSUM_LEN);
rot_crc = checksum_crc32(rot_crc, (const uchar *)rot_buf,
event_len - BINLOG_CHECKSUM_LEN);
int4store(&rot_buf[event_len - BINLOG_CHECKSUM_LEN], rot_crc);
assert(event_len == uint4korr(&rot_buf[EVENT_LEN_OFFSET]));
assert(mi->get_mi_description_event()->common_footer->checksum_alg ==
mi->rli->relay_log.relay_log_checksum_alg);
/* the first one */
assert(mi->checksum_alg_before_fd !=
binary_log::BINLOG_CHECKSUM_ALG_UNDEF);
save_buf = buf;
buf = rot_buf;
} else
/*
RSC_2: If NM \and fake Rotate \and slave does not compute checksum
the fake Rotate's checksum is stripped off before relay-logging.
*/
if (uint4korr(&buf[0]) == 0 &&
checksum_alg != binary_log::BINLOG_CHECKSUM_ALG_OFF &&
mi->rli->relay_log.relay_log_checksum_alg ==
binary_log::BINLOG_CHECKSUM_ALG_OFF) {
event_len -= BINLOG_CHECKSUM_LEN;
memcpy(rot_buf, buf, event_len);
int4store(
&rot_buf[EVENT_LEN_OFFSET],
uint4korr(rot_buf + EVENT_LEN_OFFSET) - BINLOG_CHECKSUM_LEN);
assert(event_len == uint4korr(&rot_buf[EVENT_LEN_OFFSET]));
assert(mi->get_mi_description_event()->common_footer->checksum_alg ==
mi->rli->relay_log.relay_log_checksum_alg);
/* the first one */
assert(mi->checksum_alg_before_fd !=
binary_log::BINLOG_CHECKSUM_ALG_UNDEF);
save_buf = buf;
buf = rot_buf;
}
/*
Now the I/O thread has just changed its mi->get_master_log_name(), so
incrementing mi->get_master_log_pos() is nonsense.
*/
inc_pos = 0;
break;
}
case binary_log::FORMAT_DESCRIPTION_EVENT: {
/*
Create an event, and save it (when we rotate the relay log, we will have
to write this event again).
*/
/*
We are the only thread which reads/writes mi_description_event.
The relay_log struct does not move (though some members of it can
change), so we needn't any lock (no rli->data_lock, no log lock).
*/
// mark it as undefined that is irrelevant anymore
mi->checksum_alg_before_fd = binary_log::BINLOG_CHECKSUM_ALG_UNDEF;
Format_description_log_event *new_fdle;
Log_event *ev = nullptr;
if (binlog_event_deserialize(reinterpret_cast<const unsigned char *>(buf),
event_len, mi->get_mi_description_event(),
true, &ev) != Binlog_read_error::SUCCESS) {
// This error will be reported later at handle_slave_io().
goto err;
}
new_fdle = dynamic_cast<Format_description_log_event *>(ev);
if (new_fdle->common_footer->checksum_alg ==
binary_log::BINLOG_CHECKSUM_ALG_UNDEF)
new_fdle->common_footer->checksum_alg =
binary_log::BINLOG_CHECKSUM_ALG_OFF;
mi->set_mi_description_event(new_fdle);
/* installing new value of checksum Alg for relay log */
mi->rli->relay_log.relay_log_checksum_alg =
new_fdle->common_footer->checksum_alg;
/*
Though this does some conversion to the slave's format, this will
preserve the master's binlog format version, and number of event types.
*/
/*
If the event was not requested by the slave (the slave did not ask for
it), i.e. has end_log_pos=0, we do not increment
mi->get_master_log_pos()
*/
inc_pos = uint4korr(buf + LOG_POS_OFFSET) ? event_len : 0;
DBUG_PRINT("info", ("binlog format is now %d",
mi->get_mi_description_event()->binlog_version));
} break;
case binary_log::HEARTBEAT_LOG_EVENT: {
/*
HB (heartbeat) cannot come before RL (Relay)
*/
Heartbeat_log_event hb(buf, mi->get_mi_description_event());
std::string mi_log_filename{mi->get_master_log_name() != nullptr
? mi->get_master_log_name()
: ""};
if (heartbeat_queue_event(hb.is_valid(), mi, mi_log_filename,
hb.header()->log_pos, inc_pos, do_flush_mi))
goto err;
else
goto end;
} break;
case binary_log::HEARTBEAT_LOG_EVENT_V2: {
/*
HB (heartbeat) cannot come before RL (Relay)
*/
Heartbeat_log_event_v2 hb(buf, mi->get_mi_description_event());
auto hb_log_filename = hb.get_log_filename();
auto hb_log_position = hb.get_log_position() == 0 ? hb.header()->log_pos
: hb.get_log_position();
std::string mi_log_filename{mi->get_master_log_name() != nullptr
? mi->get_master_log_name()
: ""};
if (heartbeat_queue_event(hb.is_valid(), mi, mi_log_filename,
hb_log_position, inc_pos, do_flush_mi))
goto err;
else
goto end;
} break;
case binary_log::PREVIOUS_GTIDS_LOG_EVENT: {
/*
This event does not have any meaning for the slave and
was just sent to show the slave the master is making
progress and avoid possible deadlocks.
So at this point, the event is replaced by a rotate
event what will make the slave to update what it knows
about the master's coordinates.
*/
inc_pos = 0;
mysql_mutex_lock(&mi->data_lock);
mi->set_master_log_pos(mi->get_master_log_pos() + event_len);
mysql_mutex_unlock(&mi->data_lock);
if (write_rotate_to_master_pos_into_relay_log(
mi->info_thd, mi, true /* force_flush_mi_info */))
goto err;
do_flush_mi = false; /* write_rotate_... above flushed master info */
goto end;
} break;
case binary_log::TRANSACTION_PAYLOAD_EVENT: {
binary_log::Transaction_payload_event tpe(buf,
mi->get_mi_description_event());
compression_type = tpe.get_compression_type();
compressed_transaction_bytes = tpe.get_payload_size();
uncompressed_transaction_bytes = tpe.get_uncompressed_size();
auto gtid_monitoring_info = mi->get_gtid_monitoring_info();
gtid_monitoring_info->update(compression_type,
compressed_transaction_bytes,
uncompressed_transaction_bytes);
inc_pos = event_len;
break;
}
case binary_log::GTID_LOG_EVENT: {
/*
This can happen if the master uses GTID_MODE=OFF_PERMISSIVE, and
sends GTID events to the slave. A possible scenario is that user
does not follow the upgrade procedure for GTIDs, and creates a
topology like A->B->C, where A uses GTID_MODE=ON_PERMISSIVE, B
uses GTID_MODE=OFF_PERMISSIVE, and C uses GTID_MODE=OFF. Each
connection is allowed, but the master A will generate GTID
transactions which will be sent through B to C. Then C will hit
this error.
*/
if (global_gtid_mode.get() == Gtid_mode::OFF) {
mi->report(
ERROR_LEVEL, ER_CANT_REPLICATE_GTID_WITH_GTID_MODE_OFF,
ER_THD(current_thd, ER_CANT_REPLICATE_GTID_WITH_GTID_MODE_OFF),
mi->get_master_log_name(), mi->get_master_log_pos());
goto err;
}
Gtid_log_event gtid_ev(buf, mi->get_mi_description_event());
if (!gtid_ev.is_valid()) goto err;
rli->get_sid_lock()->rdlock();
gtid.sidno = gtid_ev.get_sidno(rli->get_gtid_set()->get_sid_map());
rli->get_sid_lock()->unlock();
if (gtid.sidno < 0) goto err;
gtid.gno = gtid_ev.get_gno();
original_commit_timestamp = gtid_ev.original_commit_timestamp;
immediate_commit_timestamp = gtid_ev.immediate_commit_timestamp;
compressed_transaction_bytes = uncompressed_transaction_bytes =
gtid_ev.transaction_length - gtid_ev.get_event_length();
inc_pos = event_len;
} break;
case binary_log::ANONYMOUS_GTID_LOG_EVENT: {
/*
This cannot normally happen, because the master has a check that
prevents it from sending anonymous events when auto_position is
enabled. However, the master could be something else than
mysqld, which could contain bugs that we have no control over.
So we need this check on the slave to be sure that whoever is on
the other side of the protocol does not break the protocol.
*/
if (mi->is_auto_position()) {
mi->report(
ERROR_LEVEL, ER_CANT_REPLICATE_ANONYMOUS_WITH_AUTO_POSITION,
ER_THD(current_thd, ER_CANT_REPLICATE_ANONYMOUS_WITH_AUTO_POSITION),
mi->get_master_log_name(), mi->get_master_log_pos());
goto err;
}
/*
This can happen if the master uses GTID_MODE=ON_PERMISSIVE, and
sends an anonymous event to the slave. A possible scenario is
that user does not follow the upgrade procedure for GTIDs, and
creates a topology like A->B->C, where A uses
GTID_MODE=OFF_PERMISSIVE, B uses GTID_MODE=ON_PERMISSIVE, and C
uses GTID_MODE=ON. Each connection is allowed, but the master A
will generate anonymous transactions which will be sent through
B to C. Then C will hit this error.
There is a special case where on the slave
ASSIGN_GTIDS_TO_ANONYMOUS_TRANSACTIONS= LOCAL/UUID in that case it is
possible to replicate from a GTID_MODE=OFF master to a GTID_MODE=ON
slave
*/
else if (mi->rli->m_assign_gtids_to_anonymous_transactions_info
.get_type() == Assign_gtids_to_anonymous_transactions_info::
enum_type::AGAT_OFF) {
if (global_gtid_mode.get() == Gtid_mode::ON) {
mi->report(ERROR_LEVEL, ER_CANT_REPLICATE_ANONYMOUS_WITH_GTID_MODE_ON,
ER_THD(current_thd,
ER_CANT_REPLICATE_ANONYMOUS_WITH_GTID_MODE_ON),
mi->get_master_log_name(), mi->get_master_log_pos());
goto err;
}
}
/*
save the original_commit_timestamp and the immediate_commit_timestamp to
be later used for monitoring
*/
Gtid_log_event anon_gtid_ev(buf, mi->get_mi_description_event());
original_commit_timestamp = anon_gtid_ev.original_commit_timestamp;
immediate_commit_timestamp = anon_gtid_ev.immediate_commit_timestamp;
compressed_transaction_bytes = uncompressed_transaction_bytes =
anon_gtid_ev.transaction_length - anon_gtid_ev.get_event_length();
}
[[fallthrough]];
default:
inc_pos = event_len;
break;
}
/*
Simulate an unknown ignorable log event by rewriting the write_rows log
event and previous_gtids log event before writing them in relay log.
*/
DBUG_EXECUTE_IF(
"simulate_unknown_ignorable_log_event",
if (event_type == binary_log::WRITE_ROWS_EVENT ||
event_type == binary_log::PREVIOUS_GTIDS_LOG_EVENT) {
char *event_buf = const_cast<char *>(buf);
/* Overwrite the log event type with an unknown type. */
event_buf[EVENT_TYPE_OFFSET] = binary_log::ENUM_END_EVENT + 1;
/* Set LOG_EVENT_IGNORABLE_F for the log event. */
int2store(event_buf + FLAGS_OFFSET,
uint2korr(event_buf + FLAGS_OFFSET) | LOG_EVENT_IGNORABLE_F);
});
/*
If this event is originating from this server, don't queue it.
We don't check this for 3.23 events because it's simpler like this; 3.23
will be filtered anyway by the SQL slave thread which also tests the
server id (we must also keep this test in the SQL thread, in case somebody
upgrades a 4.0 slave which has a not-filtered relay log).
ANY event coming from ourselves can be ignored: it is obvious for queries;
for STOP_EVENT/ROTATE_EVENT/START_EVENT: these cannot come from ourselves
(--log-replica-updates would not log that) unless this slave is also its
direct master (an unsupported, useless setup!).
*/
s_id = uint4korr(buf + SERVER_ID_OFFSET);
/*
If server_id_bits option is set we need to mask out irrelevant bits
when checking server_id, but we still put the full unmasked server_id
into the Relay log so that it can be accessed when applying the event
*/
s_id &= opt_server_id_mask;
if ((s_id == ::server_id && !mi->rli->replicate_same_server_id) ||
/*
the following conjunction deals with IGNORE_SERVER_IDS, if set
If the master is on the ignore list, execution of
format description log events and rotate events is necessary.
*/
(mi->ignore_server_ids->dynamic_ids.size() > 0 &&
mi->shall_ignore_server_id(s_id) &&
/* everything is filtered out from non-master */
(s_id != mi->master_id ||
/* for the master meta information is necessary */
(event_type != binary_log::FORMAT_DESCRIPTION_EVENT &&
event_type != binary_log::ROTATE_EVENT)))) {
/*
Do not write it to the relay log.
a) We still want to increment mi->get_master_log_pos(), so that we won't
re-read this event from the master if the slave IO thread is now
stopped/restarted (more efficient if the events we are ignoring are big
LOAD DATA INFILE).
b) We want to record that we are skipping events, for the information of
the slave SQL thread, otherwise that thread may let
rli->group_relay_log_pos stay too small if the last binlog's event is
ignored.
But events which were generated by this slave and which do not exist in
the master's binlog (i.e. Format_desc, Rotate & Stop) should not increment
mi->get_master_log_pos().
If the event is originated remotely and is being filtered out by
IGNORE_SERVER_IDS it increments mi->get_master_log_pos()
as well as rli->group_relay_log_pos.
*/
if (!(s_id == ::server_id && !mi->rli->replicate_same_server_id) ||
(event_type != binary_log::FORMAT_DESCRIPTION_EVENT &&
event_type != binary_log::ROTATE_EVENT &&
event_type != binary_log::STOP_EVENT)) {
rli->relay_log.lock_binlog_end_pos();
mi->set_master_log_pos(mi->get_master_log_pos() + inc_pos);
memcpy(rli->ign_master_log_name_end, mi->get_master_log_name(),
FN_REFLEN);
assert(rli->ign_master_log_name_end[0]);
rli->ign_master_log_pos_end = mi->get_master_log_pos();
// the slave SQL thread needs to re-check
rli->relay_log.update_binlog_end_pos(false /*need_lock*/);
rli->relay_log.unlock_binlog_end_pos();
}
DBUG_PRINT(
"info",
("source_log_pos: %lu, event originating from %u server, ignored",
(ulong)mi->get_master_log_pos(), uint4korr(buf + SERVER_ID_OFFSET)));
} else {
bool is_error = false;
/* write the event to the relay log */
if (likely(rli->relay_log.write_buffer(buf, event_len, mi) == 0)) {
DBUG_SIGNAL_WAIT_FOR(current_thd,
"pause_on_queue_event_after_write_buffer",
"receiver_reached_pause_on_queue_event",
"receiver_continue_queuing_event");
mysql_mutex_lock(&mi->data_lock);
lock_count = 2;
mi->set_master_log_pos(mi->get_master_log_pos() + inc_pos);
DBUG_PRINT("info",
("source_log_pos: %lu", (ulong)mi->get_master_log_pos()));
/*
If we are starting an anonymous transaction, we will discard
the GTID of the partial transaction that was not finished (if
there is one) when calling mi->started_queueing().
*/
#ifndef NDEBUG
if (event_type == binary_log::ANONYMOUS_GTID_LOG_EVENT) {
if (!mi->get_queueing_trx_gtid()->is_empty()) {
DBUG_PRINT("info",
("Discarding Gtid(%d, %" PRId64 ") as the transaction "
"wasn't complete and we found an "
"ANONYMOUS_GTID_LOG_EVENT.",
mi->get_queueing_trx_gtid()->sidno,
mi->get_queueing_trx_gtid()->gno));
}
}
#endif
/*
We have to mark this GTID (either anonymous or not) as started
to be queued.
Also, if this event is a GTID_LOG_EVENT, we have to store its GTID to
add to the Retrieved_Gtid_Set later, when the last event of the
transaction be queued. The call to mi->started_queueing() will save
the GTID to be used later.
*/
if (event_type == binary_log::GTID_LOG_EVENT ||
event_type == binary_log::ANONYMOUS_GTID_LOG_EVENT) {
// set the timestamp for the start time of queueing this transaction
mi->started_queueing(gtid, original_commit_timestamp,
immediate_commit_timestamp);
auto gtid_monitoring_info = mi->get_gtid_monitoring_info();
gtid_monitoring_info->update(
binary_log::transaction::compression::type::NONE,
compressed_transaction_bytes, uncompressed_transaction_bytes);
}
} else {
/*
We failed to write the event and didn't updated slave positions.
We have to "rollback" the transaction parser state, or else, when
restarting the I/O thread without GTID auto positing the parser
would assume the failed event as queued.
*/
mi->transaction_parser.rollback();
is_error = true;
}
if (save_buf != nullptr) buf = save_buf;
if (is_error) {
// This error will be reported later at handle_slave_io().
goto err;
}
}
goto end;
err:
res = QUEUE_EVENT_ERROR_QUEUING;
end:
if (res == QUEUE_EVENT_OK && do_flush_mi) {
/*
Take a ride in the already locked LOCK_log to flush master info.
JAG: TODO: Notice that we could only flush master info if we are
not in the middle of a transaction. Having a proper
relay log recovery can allow us to do this.
*/
if (lock_count == 1) {
mysql_mutex_lock(&mi->data_lock);
lock_count = 2;
}
if (flush_master_info(mi, false /*force*/, lock_count == 0 /*need_lock*/,
false /*flush_relay_log*/, mi->is_gtid_only_mode()))
res = QUEUE_EVENT_ERROR_FLUSHING_INFO;
if (mi->is_gtid_only_mode()) {
mi->update_flushed_relay_log_info();
}
}
if (lock_count >= 2) mysql_mutex_unlock(&mi->data_lock);
if (lock_count >= 1) mysql_mutex_unlock(log_lock);
DBUG_PRINT("info", ("queue result: %d", res));
return res;
}
/**
Hook to detach the active VIO before closing a connection handle.
The client API might close the connection (and associated data)
in case it encounters a unrecoverable (network) error. This hook
is called from the client code before the VIO handle is deleted
allows the thread to detach the active vio so it does not point
to freed memory.
Other calls to THD::clear_active_vio throughout this module are
redundant due to the hook but are left in place for illustrative
purposes.
*/
void slave_io_thread_detach_vio() {
THD *thd = current_thd;
if (thd && thd->slave_thread) thd->clear_active_vio();
}
/*
Set network namespace if channel is using network namespace and connect
to master.
@param thd THD context
@param mysql MYSQL connection handler
@param mi Master info corresponding to this channel.
@param reconnect Reconnect if true
@param suppress_warnings suppress warnings if required.
@retval 0 ok.
@retval 1 not ok.
*/
static int connect_to_master_via_namespace(THD *thd, MYSQL *mysql,
Master_info *mi, bool reconnect,
bool suppress_warnings,
const std::string &host,
const uint port) {
if (mi->is_set_network_namespace()) {
#ifdef HAVE_SETNS
if (set_network_namespace(mi->network_namespace)) return 1;
#else
// Network namespace not supported by the platform. Report error.
LogErr(ERROR_LEVEL, ER_NETWORK_NAMESPACES_NOT_SUPPORTED);
return 1;
#endif
// Save default value of network namespace
// Set network namespace before sockets be created
}
int connect_res = connect_to_master(thd, mysql, mi, reconnect,
suppress_warnings, host, port);
// we can get killed during safe_connect
#ifdef HAVE_SETNS
if (mi->is_set_network_namespace()) {
// Restore original network namespace used to be before connection has
// been created
(void)restore_original_network_namespace();
}
#endif
return connect_res;
}
/*
Try to connect until successful or slave killed
SYNPOSIS
safe_connect()
thd Thread handler for slave
mysql MySQL connection handle
mi Replication handle
RETURN
0 ok
# Error
*/
static int safe_connect(THD *thd, MYSQL *mysql, Master_info *mi,
const std::string &host, const uint port) {
DBUG_TRACE;
return connect_to_master_via_namespace(thd, mysql, mi,
/*reconnect=*/false,
/*suppress_warnings=*/false, host,
port);
}
int connect_to_master(THD *thd, MYSQL *mysql, Master_info *mi, bool reconnect,
bool suppress_warnings, const std::string &host,
const uint port, bool is_io_thread) {
int last_errno = -2; // impossible error
ulong err_count = 0;
char llbuff[22];
char password[MAX_PASSWORD_LENGTH + 1];
size_t password_size = sizeof(password);
DBUG_TRACE;
set_replica_max_allowed_packet(thd, mysql);
#ifndef NDEBUG
mi->events_until_exit = disconnect_slave_event_count;
#endif
ulong client_flag = CLIENT_REMEMBER_OPTIONS;
/* Always reset public key to remove cached copy */
mysql_reset_server_public_key();
mysql_options(mysql, MYSQL_OPT_CONNECT_TIMEOUT, (char *)&replica_net_timeout);
mysql_options(mysql, MYSQL_OPT_READ_TIMEOUT, (char *)&replica_net_timeout);
if (mi->bind_addr[0]) {
DBUG_PRINT("info", ("bind_addr: %s", mi->bind_addr));
mysql_options(mysql, MYSQL_OPT_BIND, mi->bind_addr);
}
/* By default the channel is not configured to use SSL */
enum mysql_ssl_mode ssl_mode = SSL_MODE_DISABLED;
if (mi->ssl) {
/* The channel is configured to use SSL */
mysql_options(mysql, MYSQL_OPT_SSL_KEY,
mi->ssl_key[0] ? mi->ssl_key : nullptr);
mysql_options(mysql, MYSQL_OPT_SSL_CERT,
mi->ssl_cert[0] ? mi->ssl_cert : nullptr);
mysql_options(mysql, MYSQL_OPT_SSL_CA,
mi->ssl_ca[0] ? mi->ssl_ca : nullptr);
mysql_options(mysql, MYSQL_OPT_SSL_CAPATH,
mi->ssl_capath[0] ? mi->ssl_capath : nullptr);
mysql_options(mysql, MYSQL_OPT_SSL_CIPHER,
mi->ssl_cipher[0] ? mi->ssl_cipher : nullptr);
mysql_options(mysql, MYSQL_OPT_SSL_CRL,
mi->ssl_crl[0] ? mi->ssl_crl : nullptr);
mysql_options(mysql, MYSQL_OPT_TLS_VERSION,
mi->tls_version[0] ? mi->tls_version : nullptr);
mysql_options(mysql, MYSQL_OPT_TLS_CIPHERSUITES,
mi->tls_ciphersuites.first
? nullptr
: mi->tls_ciphersuites.second.c_str());
mysql_options(mysql, MYSQL_OPT_SSL_CRLPATH,
mi->ssl_crlpath[0] ? mi->ssl_crlpath : nullptr);
if (mi->ssl_verify_server_cert)
ssl_mode = SSL_MODE_VERIFY_IDENTITY;
else if (mi->ssl_ca[0] || mi->ssl_capath[0])
ssl_mode = SSL_MODE_VERIFY_CA;
else
ssl_mode = SSL_MODE_REQUIRED;
}
mysql_options(mysql, MYSQL_OPT_SSL_MODE, &ssl_mode);
mysql_options(mysql, MYSQL_OPT_COMPRESSION_ALGORITHMS,
opt_replica_compressed_protocol ? COMPRESSION_ALGORITHM_ZLIB
: mi->compression_algorithm);
mysql_options(mysql, MYSQL_OPT_ZSTD_COMPRESSION_LEVEL,
&mi->zstd_compression_level);
/*
If server's default charset is not supported (like utf16, utf32) as client
charset, then set client charset to 'latin1' (default client charset).
*/
if (is_supported_parser_charset(default_charset_info))
mysql_options(mysql, MYSQL_SET_CHARSET_NAME, default_charset_info->csname);
else {
LogErr(INFORMATION_LEVEL, ER_RPL_REPLICA_CANT_USE_CHARSET,
default_charset_info->csname, default_client_charset_info->csname);
mysql_options(mysql, MYSQL_SET_CHARSET_NAME,
default_client_charset_info->csname);
}
if (mi->is_start_plugin_auth_configured()) {
DBUG_PRINT("info", ("Slaving is using MYSQL_DEFAULT_AUTH %s",
mi->get_start_plugin_auth()));
mysql_options(mysql, MYSQL_DEFAULT_AUTH, mi->get_start_plugin_auth());
}
if (mi->is_start_plugin_dir_configured()) {
DBUG_PRINT("info", ("Slaving is using MYSQL_PLUGIN_DIR %s",
mi->get_start_plugin_dir()));
mysql_options(mysql, MYSQL_PLUGIN_DIR, mi->get_start_plugin_dir());
}
/* Set MYSQL_PLUGIN_DIR in case master asks for an external authentication
plugin */
else if (opt_plugin_dir_ptr && *opt_plugin_dir_ptr)
mysql_options(mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir_ptr);
if (mi->public_key_path[0]) {
/* Set public key path */
DBUG_PRINT("info", ("Set source's public key path"));
mysql_options(mysql, MYSQL_SERVER_PUBLIC_KEY, mi->public_key_path);
}
/* Get public key from master */
DBUG_PRINT("info", ("Set preference to get public key from source"));
mysql_options(mysql, MYSQL_OPT_GET_SERVER_PUBLIC_KEY, &mi->get_public_key);
if (is_io_thread && !mi->is_start_user_configured())
LogErr(WARNING_LEVEL, ER_RPL_REPLICA_INSECURE_CHANGE_SOURCE);
if (mi->get_password(password, &password_size)) {
mi->report(ERROR_LEVEL, ER_REPLICA_FATAL_ERROR,
ER_THD(thd, ER_REPLICA_FATAL_ERROR),
"Unable to configure password when attempting to "
"connect to the source server. Connection attempt "
"terminated.");
return 1;
}
const char *user = mi->get_user();
if (user == nullptr || user[0] == 0) {
mi->report(ERROR_LEVEL, ER_REPLICA_FATAL_ERROR,
ER_THD(thd, ER_REPLICA_FATAL_ERROR),
"Invalid (empty) username when attempting to "
"connect to the source server. Connection attempt "
"terminated.");
return 1;
}
mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD, "program_name", "mysqld");
mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD, "_client_role",
"binary_log_listener");
mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD,
"_client_replication_channel_name", mi->get_channel());
const char *tmp_host = host.empty() ? mi->host : host.c_str();
uint tmp_port = (port == 0) ? mi->port : port;
bool replica_was_killed{false};
bool connected{false};
while (!connected) {
replica_was_killed = is_io_thread ? io_slave_killed(thd, mi)
: monitor_io_replica_killed(thd, mi);
if (replica_was_killed) {
LogErr(INFORMATION_LEVEL, ER_RPL_REPLICA_IO_THREAD_KILLED,
mi->get_for_channel_str());
break;
}
if (reconnect) {
connected = !mysql_reconnect(mysql);
} else {
// Set this each time mysql_real_connect() is called to make a connection
mysql_extension_set_server_extn(mysql, &mi->server_extn);
connected = mysql_real_connect(mysql, tmp_host, user, password, nullptr,
tmp_port, nullptr, client_flag);
}
if (connected) break;
/*
SHOW REPLICA STATUS will display the number of retries which
would be real retry counts instead of mi->retry_count for
each connection attempt by 'Last_IO_Error' entry.
*/
last_errno = mysql_errno(mysql);
suppress_warnings = false;
if (is_io_thread) {
mi->report(ERROR_LEVEL, last_errno,
"Error %s to source '%s@%s:%d'."
" This was attempt %lu/%lu, with a delay of %d seconds between"
" attempts. Message: %s",
(reconnect ? "reconnecting" : "connecting"), mi->get_user(),
tmp_host, tmp_port, err_count + 1, mi->retry_count,
mi->connect_retry, mysql_error(mysql));
}
/*
By default we try forever. The reason is that failure will trigger
master election, so if the user did not set mi->retry_count we
do not want to have election triggered on the first failure to
connect
*/
if (++err_count == mi->retry_count) {
if (is_network_error(last_errno) && is_io_thread) mi->set_network_error();
replica_was_killed = true;
break;
}
slave_sleep(thd, mi->connect_retry,
is_io_thread ? io_slave_killed : monitor_io_replica_killed, mi);
}
if (!replica_was_killed) {
if (is_io_thread) {
mi->clear_error(); // clear possible left over reconnect error
mi->reset_network_error();
}
if (reconnect) {
if (!suppress_warnings)
LogErr(SYSTEM_LEVEL,
ER_RPL_REPLICA_CONNECTED_TO_SOURCE_REPLICATION_RESUMED,
mi->get_for_channel_str(), mi->get_user(), tmp_host, tmp_port,
mi->get_io_rpl_log_name(),
llstr(mi->get_master_log_pos(), llbuff));
} else {
query_logger.general_log_print(thd, COM_CONNECT_OUT, "%s@%s:%d",
mi->get_user(), tmp_host, tmp_port);
}
thd->set_active_vio(mysql->net.vio);
}
mysql->reconnect = true;
DBUG_PRINT("exit", ("replica_was_killed: %d", replica_was_killed));
return replica_was_killed;
}
/*
safe_reconnect()
IMPLEMENTATION
Try to connect until successful or slave killed or we have retried
mi->retry_count times
*/
static int safe_reconnect(THD *thd, MYSQL *mysql, Master_info *mi,
bool suppress_warnings, const std::string &host,
const uint port) {
DBUG_TRACE;
return connect_to_master_via_namespace(thd, mysql, mi,
/*reconnect=*/true, suppress_warnings,
host, port);
}
int rotate_relay_log(Master_info *mi, bool log_master_fd, bool need_lock,
bool need_log_space_lock) {
DBUG_TRACE;
Relay_log_info *rli = mi->rli;
if (need_lock)
mysql_mutex_lock(rli->relay_log.get_log_lock());
else
mysql_mutex_assert_owner(rli->relay_log.get_log_lock());
DBUG_EXECUTE_IF("crash_before_rotate_relaylog", DBUG_SUICIDE(););
int error = 0;
/*
We need to test inited because otherwise, new_file() will attempt to lock
LOCK_log, which may not be inited (if we're not a slave).
*/
if (!rli->inited) {
DBUG_PRINT("info", ("rli->inited == 0"));
goto end;
}
if (log_master_fd)
error =
rli->relay_log.new_file_without_locking(mi->get_mi_description_event());
else
error = rli->relay_log.new_file_without_locking(nullptr);
if (error != 0) goto end;
/*
We harvest now, because otherwise BIN_LOG_HEADER_SIZE will not immediately
be counted, so imagine a succession of FLUSH LOGS and assume the slave
threads are started:
relay_log_space decreases by the size of the deleted relay log, but does
not increase, so flush-after-flush we may become negative, which is wrong.
Even if this will be corrected as soon as a query is replicated on the
slave (because the I/O thread will then call harvest_bytes_written() which
will harvest all these BIN_LOG_HEADER_SIZE we forgot), it may give strange
output in SHOW REPLICA STATUS meanwhile. So we harvest now.
If the log is closed, then this will just harvest the last writes, probably
0 as they probably have been harvested.
*/
rli->relay_log.harvest_bytes_written(rli, need_log_space_lock);
end:
if (need_lock) mysql_mutex_unlock(rli->relay_log.get_log_lock());
return error;
}
/**
flushes the relay logs of a replication channel.
@param[in] mi Master_info corresponding to the
channel.
@param[in] thd the client thread carrying the command.
@retval 1 fail
@retval 0 ok
@retval -1 deferred flush
*/
int flush_relay_logs(Master_info *mi, THD *thd) {
DBUG_TRACE;
int error = 0;
if (mi) {
Relay_log_info *rli = mi->rli;
if (rli->inited) {
// Rotate immediately if one is true:
if ((!is_group_replication_plugin_loaded() || // GR is disabled
!mi->transaction_parser
.is_inside_transaction() || // not inside a transaction
!channel_map.is_group_replication_channel_name(
mi->get_channel(), true) || // channel isn't GR applier channel
!mi->slave_running) && // the I/O thread isn't running
DBUG_EVALUATE_IF("deferred_flush_relay_log",
!channel_map.is_group_replication_channel_name(
mi->get_channel(), true),
true)) {
if (rotate_relay_log(mi)) error = 1;
}
// Postpone the rotate action, delegating it to the I/O thread
else {
channel_map.unlock();
mi->request_rotate(thd);
channel_map.rdlock();
error = -1;
}
}
}
return error;
}
/**
Entry point for FLUSH RELAYLOGS command or to flush relaylogs for
the FLUSH LOGS command.
FLUSH LOGS or FLUSH RELAYLOGS needs to flush the relaylogs of all
the replciaiton channels in multisource replication.
FLUSH RELAYLOGS FOR CHANNEL flushes only the relaylogs pertaining to
a channel.
@param[in] thd the client thread carrying the command.
@retval true fail
@retval false success
*/
bool flush_relay_logs_cmd(THD *thd) {
DBUG_TRACE;
Master_info *mi = nullptr;
LEX *lex = thd->lex;
bool error = false;
channel_map.rdlock();
/*
lex->mi.channel is NULL, for FLUSH LOGS or when the client thread
is not present. (See tmp_thd in the caller).
When channel is not provided, lex->mi.for_channel is false.
*/
if (!lex->mi.channel || !lex->mi.for_channel) {
bool flush_was_deferred{false};
enum_channel_type channel_types[] = {SLAVE_REPLICATION_CHANNEL,
GROUP_REPLICATION_CHANNEL};
for (auto channel_type : channel_types) {
mi_map already_processed;
do {
flush_was_deferred = false;
for (mi_map::iterator it = channel_map.begin(channel_type);
it != channel_map.end(channel_type); it++) {
if (already_processed.find(it->first) != already_processed.end())
continue;
mi = it->second;
already_processed.insert(std::make_pair(it->first, mi));
int flush_status = flush_relay_logs(mi, thd);
flush_was_deferred = (flush_status == -1);
error = (flush_status == 1);
if (flush_status != 0) break;
}
} while (flush_was_deferred);
}
} else {
mi = channel_map.get_mi(lex->mi.channel);
if (mi) {
error = (flush_relay_logs(mi, thd) == 1);
} else {
if (thd->system_thread == SYSTEM_THREAD_SLAVE_SQL ||
thd->system_thread == SYSTEM_THREAD_SLAVE_WORKER) {
/*
Log warning on SQL or worker threads.
*/
LogErr(WARNING_LEVEL, ER_RPL_REPLICA_INCORRECT_CHANNEL,
lex->mi.channel);
} else {
/*
Return error on client sessions.
*/
error = true;
my_error(ER_REPLICA_CHANNEL_DOES_NOT_EXIST, MYF(0), lex->mi.channel);
}
}
}
channel_map.unlock();
return error;
}
bool reencrypt_relay_logs() {
DBUG_TRACE;
Master_info *mi;
channel_map.rdlock();
enum_channel_type channel_types[] = {SLAVE_REPLICATION_CHANNEL,
GROUP_REPLICATION_CHANNEL};
for (auto channel_type : channel_types) {
for (mi_map::iterator it = channel_map.begin(channel_type);
it != channel_map.end(channel_type); it++) {
mi = it->second;
if (mi != nullptr) {
Relay_log_info *rli = mi->rli;
if (rli != nullptr && rli->inited && rli->relay_log.reencrypt_logs()) {
channel_map.unlock();
return true;
}
}
}
}
channel_map.unlock();
return false;
}
/**
a copy of active_mi->rli->slave_skip_counter, for showing in SHOW GLOBAL
VARIABLES, INFORMATION_SCHEMA.GLOBAL_VARIABLES and @@sql_replica_skip_counter
without taking all the mutexes needed to access
active_mi->rli->slave_skip_counter properly.
*/
uint sql_replica_skip_counter;
/**
Executes a START SLAVE statement.
@param thd Pointer to THD object for the client thread
executing the statement.
@param connection_param Connection parameters for starting threads
@param master_param Master parameters used for starting threads
@param thread_mask_input The thread mask that identifies which threads to
start. If 0 is passed (start no thread) then this
parameter is ignored and all stopped threads are
started
@param mi Pointer to Master_info object for the slave's IO
thread.
@param set_mts_settings If true, the channel uses the server MTS
configured settings when starting the applier
thread.
@retval false success
@retval true error
*/
bool start_slave(THD *thd, LEX_SLAVE_CONNECTION *connection_param,
LEX_MASTER_INFO *master_param, int thread_mask_input,
Master_info *mi, bool set_mts_settings) {
bool is_error = false;
int thread_mask;
DBUG_TRACE;
/*
START SLAVE command should ignore 'read-only' and 'super_read_only'
options so that it can update 'mysql.slave_master_info' and
'mysql.slave_relay_log_info' replication repository tables.
*/
thd->set_skip_readonly_check();
Security_context *sctx = thd->security_context();
if (!sctx->check_access(SUPER_ACL) &&
!sctx->has_global_grant(STRING_WITH_LEN("REPLICATION_SLAVE_ADMIN"))
.first) {
my_error(ER_SPECIFIC_ACCESS_DENIED_ERROR, MYF(0),
"SUPER or REPLICATION_SLAVE_ADMIN");
return true;
}
mi->channel_wrlock();
if (connection_param->user || connection_param->password) {
if (!thd->get_ssl()) {
push_warning(thd, Sql_condition::SL_NOTE, ER_INSECURE_PLAIN_TEXT,
ER_THD(thd, ER_INSECURE_PLAIN_TEXT));
}
}
lock_slave_threads(mi); // this allows us to cleanly read slave_running
// Get a mask of _stopped_ threads
init_thread_mask(&thread_mask, mi, true /* inverse */);
/*
Below we will start all stopped threads. But if the user wants to
start only one thread, do as if the other thread was running (as we
don't want to touch the other thread), so set the bit to 0 for the
other thread
*/
if (thread_mask_input) {
thread_mask &= thread_mask_input;
}
if (thread_mask) // some threads are stopped, start them
{
if (load_mi_and_rli_from_repositories(mi, false, thread_mask)) {
is_error = true;
my_error(ER_CONNECTION_METADATA, MYF(0));
} else if (*mi->host || !(thread_mask & SLAVE_IO)) {
/*
If we will start IO thread we need to take care of possible
options provided through the START SLAVE if there is any.
*/
if (thread_mask & SLAVE_IO) {
if (connection_param->user) {
mi->set_start_user_configured(true);
mi->set_user(connection_param->user);
}
if (connection_param->password) {
mi->set_start_user_configured(true);
mi->set_password(connection_param->password);
}
if (connection_param->plugin_auth)
mi->set_plugin_auth(connection_param->plugin_auth);
if (connection_param->plugin_dir)
mi->set_plugin_dir(connection_param->plugin_dir);
}
/*
If we will start SQL thread we will care about UNTIL options If
not and they are specified we will ignore them and warn user
about this fact.
*/
if (thread_mask & SLAVE_SQL) {
/*
sql_replica_skip_counter only effects the applier thread which is
first started. So after sql_replica_skip_counter is copied to
rli->slave_skip_counter, it is reset to 0.
*/
mysql_mutex_lock(&LOCK_sql_replica_skip_counter);
if (mi->rli->m_assign_gtids_to_anonymous_transactions_info.get_type() !=
Assign_gtids_to_anonymous_transactions_info::enum_type::
AGAT_OFF ||
global_gtid_mode.get() != Gtid_mode::ON)
mi->rli->slave_skip_counter = sql_replica_skip_counter;
sql_replica_skip_counter = 0;
mysql_mutex_unlock(&LOCK_sql_replica_skip_counter);
/*
To cache the MTS system var values and used them in the following
runtime. The system vars can change meanwhile but having no other
effects.
It also allows the per channel definition of this variables.
*/
if (set_mts_settings) {
mi->rli->opt_replica_parallel_workers =
opt_mts_replica_parallel_workers;
if (mi->is_gtid_only_mode() &&
opt_mts_replica_parallel_workers == 0) {
mi->rli->opt_replica_parallel_workers = 1;
}
if (mts_parallel_option == MTS_PARALLEL_TYPE_DB_NAME)
mi->rli->channel_mts_submode = MTS_PARALLEL_TYPE_DB_NAME;
else
mi->rli->channel_mts_submode = MTS_PARALLEL_TYPE_LOGICAL_CLOCK;
#ifndef NDEBUG
if (!DBUG_EVALUATE_IF("check_replica_debug_group", 1, 0))
#endif
mi->rli->checkpoint_group = opt_mta_checkpoint_group;
}
int slave_errno = mi->rli->init_until_option(thd, master_param);
if (slave_errno) {
my_error(slave_errno, MYF(0));
is_error = true;
}
if (!is_error) is_error = check_slave_sql_config_conflict(mi->rli);
} else if (master_param->pos || master_param->relay_log_pos ||
master_param->gtid)
push_warning(thd, Sql_condition::SL_NOTE, ER_UNTIL_COND_IGNORED,
ER_THD(thd, ER_UNTIL_COND_IGNORED));
if (!is_error)
is_error =
start_slave_threads(false /*need_lock_slave=false*/,
true /*wait_for_start=true*/, mi, thread_mask);
} else {
is_error = true;
my_error(ER_BAD_REPLICA, MYF(0));
}
} else {
/* no error if all threads are already started, only a warning */
push_warning_printf(
thd, Sql_condition::SL_NOTE, ER_REPLICA_CHANNEL_WAS_RUNNING,
ER_THD(thd, ER_REPLICA_CHANNEL_WAS_RUNNING), mi->get_channel());
}
/*
Clean up start information if there was an attempt to start
the IO thread to avoid any security issue.
*/
if (is_error && (thread_mask & SLAVE_IO) == SLAVE_IO) mi->reset_start_info();
unlock_slave_threads(mi);
mi->channel_unlock();
return is_error;
}
/**
Execute a STOP SLAVE statement.
@param thd Pointer to THD object for the client thread executing
the statement.
@param mi Pointer to Master_info object for the slave's IO
thread.
@param net_report If true, saves the exit status into Diagnostics_area.
@param for_one_channel If the method is being invoked only for one channel
@param push_temp_tables_warning If it should push a "have temp tables
warning" once having open temp tables. This
avoids multiple warnings when there is more
than one channel with open temp tables.
This parameter can be removed when the
warning is issued with per-channel
information.
@retval 0 success
@retval 1 error
*/
int stop_slave(THD *thd, Master_info *mi, bool net_report, bool for_one_channel,
bool *push_temp_tables_warning) {
DBUG_TRACE;
int slave_errno;
if (!thd) thd = current_thd;
/*
STOP SLAVE command should ignore 'read-only' and 'super_read_only'
options so that it can update 'mysql.slave_master_info' and
'mysql.slave_relay_log_info' replication repository tables.
*/
thd->set_skip_readonly_check();
Security_context *sctx = thd->security_context();
if (!sctx->check_access(SUPER_ACL) &&
!sctx->has_global_grant(STRING_WITH_LEN("REPLICATION_SLAVE_ADMIN"))
.first) {
my_error(ER_SPECIFIC_ACCESS_DENIED_ERROR, MYF(0),
"SUPER or REPLICATION_SLAVE_ADMIN");
return 1;
}
mi->channel_wrlock();
THD_STAGE_INFO(thd, stage_killing_replica);
int thread_mask;
lock_slave_threads(mi);
DBUG_EXECUTE_IF("simulate_hold_run_locks_on_stop_replica",
my_sleep(10000000););
// Get a mask of _running_ threads
init_thread_mask(&thread_mask, mi, false /* not inverse*/);
/*
Below we will stop all running threads.
But if the user wants to stop only one thread, do as if the other thread
was stopped (as we don't want to touch the other thread), so set the
bit to 0 for the other thread
*/
if (thd->lex->slave_thd_opt) {
thread_mask &= thd->lex->slave_thd_opt;
/*
If we are stopping IO thread, we also need to consider
IO Monitor thread.
*/
if ((thread_mask & SLAVE_IO) && mi->is_source_connection_auto_failover()) {
thread_mask |= SLAVE_MONITOR;
}
}
if (thread_mask) {
slave_errno =
terminate_slave_threads(mi, thread_mask, rpl_stop_replica_timeout,
false /*need_lock_term=false*/);
} else {
// no error if both threads are already stopped, only a warning
slave_errno = 0;
push_warning_printf(
thd, Sql_condition::SL_NOTE, ER_REPLICA_CHANNEL_WAS_NOT_RUNNING,
ER_THD(thd, ER_REPLICA_CHANNEL_WAS_NOT_RUNNING), mi->get_channel());
}
/*
If the slave has open temp tables and there is a following CHANGE MASTER
there is a possibility that the temporary tables are left open forever.
Though we dont restrict failover here, we do warn users. In future, we
should have a command to delete open temp tables the slave has replicated.
See WL#7441 regarding this command.
*/
if (mi->rli->atomic_channel_open_temp_tables && *push_temp_tables_warning) {
push_warning(thd, Sql_condition::SL_WARNING,
ER_WARN_OPEN_TEMP_TABLES_MUST_BE_ZERO,
ER_THD(thd, ER_WARN_OPEN_TEMP_TABLES_MUST_BE_ZERO));
*push_temp_tables_warning = false;
}
unlock_slave_threads(mi);
mi->channel_unlock();
if (slave_errno) {
if ((slave_errno == ER_STOP_REPLICA_SQL_THREAD_TIMEOUT) ||
(slave_errno == ER_STOP_REPLICA_MONITOR_IO_THREAD_TIMEOUT) ||
(slave_errno == ER_STOP_REPLICA_IO_THREAD_TIMEOUT)) {
push_warning(thd, Sql_condition::SL_NOTE, slave_errno,
ER_THD_NONCONST(thd, slave_errno));
/*
If new slave_errno is added in the if() condition above then make sure
that there are no % in the error message or change the logging API
to use verbatim() to avoid % substitutions.
*/
longlong log_errno = (slave_errno == ER_STOP_REPLICA_SQL_THREAD_TIMEOUT)
? ER_RPL_REPLICA_SQL_THREAD_STOP_CMD_EXEC_TIMEOUT
: ER_RPL_REPLICA_IO_THREAD_STOP_CMD_EXEC_TIMEOUT;
LogErr(WARNING_LEVEL, log_errno);
}
if (net_report) my_error(slave_errno, MYF(0));
return 1;
} else if (net_report && for_one_channel)
my_ok(thd);
return 0;
}
/**
Execute a RESET SLAVE (for all channels), used in Multisource replication.
If resetting of a particular channel fails, it exits out.
@param[in] thd THD object of the client.
@retval 0 success
@retval 1 error
*/
int reset_slave(THD *thd) {
DBUG_TRACE;
channel_map.assert_some_wrlock();
Master_info *mi = nullptr;
int result = 0;
mi_map::iterator it, gr_channel_map_it;
if (thd->lex->reset_slave_info.all) {
/* First do reset_slave for default channel */
mi = channel_map.get_default_channel_mi();
if (mi && reset_slave(thd, mi, thd->lex->reset_slave_info.all)) return 1;
/* Do while iteration for rest of the channels */
it = channel_map.begin();
while (it != channel_map.end()) {
if (!it->first.compare(channel_map.get_default_channel())) {
it++;
continue;
}
mi = it->second;
assert(mi);
if ((result = reset_slave(thd, mi, thd->lex->reset_slave_info.all)))
break;
it = channel_map.begin();
}
/* RESET group replication specific channels */
gr_channel_map_it = channel_map.begin(GROUP_REPLICATION_CHANNEL);
while (gr_channel_map_it != channel_map.end(GROUP_REPLICATION_CHANNEL)) {
mi = gr_channel_map_it->second;
assert(mi);
/*
We cannot RESET a group replication channel while the group
replication is running.
*/
if (is_group_replication_running()) {
my_error(ER_REPLICA_CHANNEL_OPERATION_NOT_ALLOWED, MYF(0),
"RESET REPLICA ALL FOR CHANNEL", mi->get_channel());
return 1;
}
if ((result = reset_slave(thd, mi, thd->lex->reset_slave_info.all)))
break;
gr_channel_map_it = channel_map.begin(GROUP_REPLICATION_CHANNEL);
}
} else {
it = channel_map.begin();
while (it != channel_map.end()) {
mi = it->second;
assert(mi);
if ((result = reset_slave(thd, mi, thd->lex->reset_slave_info.all)))
break;
it++;
}
/*
RESET group replication specific channels.
We cannot RESET a group replication channel while the group
replication is running.
*/
gr_channel_map_it = channel_map.begin(GROUP_REPLICATION_CHANNEL);
while (gr_channel_map_it != channel_map.end(GROUP_REPLICATION_CHANNEL)) {
mi = gr_channel_map_it->second;
assert(mi);
if (is_group_replication_running()) {
my_error(ER_REPLICA_CHANNEL_OPERATION_NOT_ALLOWED, MYF(0),
"RESET REPLICA FOR CHANNEL", mi->get_channel());
return 1;
}
if ((result = reset_slave(thd, mi, thd->lex->reset_slave_info.all)))
break;
gr_channel_map_it++;
}
}
return result;
}
/**
Execute a RESET REPLICA statement.
Locks slave threads and unlocks the slave threads after executing
reset slave.
The method also takes the mi->channel_wrlock; if this {mi} object
is deleted (when the parameter reset_all is true) its destructor unlocks
the lock. In case of error, the method shall always unlock the
mi channel lock.
@param thd Pointer to THD object of the client thread executing the
statement.
@param mi Pointer to Master_info object for the slave.
@param reset_all Do a full reset or only clean master info structures
@retval 0 success
@retval !=0 error
*/
int reset_slave(THD *thd, Master_info *mi, bool reset_all) {
int thread_mask = 0, error = 0;
const char *errmsg = "Unknown error occurred while reseting replica";
DBUG_TRACE;
bool is_default_channel =
strcmp(mi->get_channel(), channel_map.get_default_channel()) == 0;
/*
RESET SLAVE command should ignore 'read-only' and 'super_read_only'
options so that it can update 'mysql.slave_master_info' and
'mysql.slave_relay_log_info' replication repository tables.
*/
thd->set_skip_readonly_check();
mi->channel_wrlock();
lock_slave_threads(mi);
init_thread_mask(&thread_mask, mi, false /* not inverse */,
true /* ignore_monitor_thread */);
if (thread_mask) // We refuse if any slave thread is running
{
my_error(ER_REPLICA_CHANNEL_MUST_STOP, MYF(0), mi->get_channel());
error = ER_REPLICA_CHANNEL_MUST_STOP;
unlock_slave_threads(mi);
mi->channel_unlock();
goto err;
}
ha_reset_slave(thd);
// delete relay logs, clear relay log coordinates
if ((error = mi->rli->purge_relay_logs(thd, &errmsg,
reset_all && !is_default_channel))) {
my_error(ER_RELAY_LOG_FAIL, MYF(0), errmsg);
error = ER_RELAY_LOG_FAIL;
unlock_slave_threads(mi);
mi->channel_unlock();
goto err;
}
assert(!mi->rli || !mi->rli->slave_running); // none writes in rli table
if ((reset_all && remove_info(mi)) || // Removes all repository information.
(!reset_all && reset_info(mi))) { // Resets log names, positions, etc,
// but keeps configuration information
// needed for a re-connection.
error = ER_UNKNOWN_ERROR;
my_error(ER_UNKNOWN_ERROR, MYF(0));
unlock_slave_threads(mi);
mi->channel_unlock();
goto err;
}
unlock_slave_threads(mi);
(void)RUN_HOOK(binlog_relay_io, after_reset_slave, (thd, mi));
/*
RESET SLAVE ALL deletes the channels(except default channel), so their mi
and rli objects are removed. For default channel, its mi and rli are
deleted and recreated to keep in clear status.
*/
if (reset_all) {
bool is_default =
!strcmp(mi->get_channel(), channel_map.get_default_channel());
rpl_acf_configuration_handler->delete_channel_status(
mi->get_channel(),
Rpl_acf_status_configuration::SOURCE_CONNECTION_AUTO_FAILOVER);
// delete_mi will call mi->channel_unlock in case it succeeds
if (channel_map.delete_mi(mi->get_channel())) {
mi->channel_unlock();
error = ER_UNKNOWN_ERROR;
my_error(ER_UNKNOWN_ERROR, MYF(0));
goto err;
}
if (is_default) {
if (!Rpl_info_factory::create_mi_and_rli_objects(
opt_mi_repository_id, opt_rli_repository_id,
channel_map.get_default_channel(), true, &channel_map)) {
error = ER_CONNECTION_METADATA;
my_message(ER_CONNECTION_METADATA, ER_THD(thd, ER_CONNECTION_METADATA),
MYF(0));
}
}
} else {
mi->channel_unlock();
}
err:
return error;
}
/**
Entry function for RESET SLAVE command. Function either resets
the slave for all channels or for a single channel.
When RESET SLAVE ALL is given, the slave_info_objects (mi, rli & workers)
are destroyed.
@param[in] thd the client thread with the command.
@retval false OK
@retval true not OK
*/
bool reset_slave_cmd(THD *thd) {
DBUG_TRACE;
Master_info *mi;
LEX *lex = thd->lex;
bool res = true; // default, an error
channel_map.wrlock();
if (!is_slave_configured()) {
my_error(ER_REPLICA_CONFIGURATION, MYF(0));
channel_map.unlock();
return res = true;
}
if (!lex->mi.for_channel)
res = reset_slave(thd);
else {
mi = channel_map.get_mi(lex->mi.channel);
/*
If the channel being used is a group replication channel and
group_replication is still running we need to disable RESET SLAVE [ALL]
command.
*/
if (mi &&
channel_map.is_group_replication_channel_name(mi->get_channel(),
true) &&
is_group_replication_running()) {
my_error(ER_REPLICA_CHANNEL_OPERATION_NOT_ALLOWED, MYF(0),
"RESET REPLICA [ALL] FOR CHANNEL", mi->get_channel());
channel_map.unlock();
return true;
}
if (mi)
res = reset_slave(thd, mi, thd->lex->reset_slave_info.all);
else if (strcmp(channel_map.get_default_channel(), lex->mi.channel))
my_error(ER_REPLICA_CHANNEL_DOES_NOT_EXIST, MYF(0), lex->mi.channel);
}
channel_map.unlock();
return res;
}
/**
This function checks if the given CHANGE MASTER/REPLICATION SOURCE command
has any receive option being set or changed.
- used in change_master().
@param lex_mi structure that holds all options given on the
change replication source command.
@retval false No change replication source receive options were found.
@retval true At least one receive option was found.
*/
static bool have_change_replication_source_receive_option(
const LEX_MASTER_INFO *lex_mi) {
bool have_receive_option = false;
DBUG_TRACE;
/* Check if *at least one* receive option is given the command*/
if (lex_mi->host || lex_mi->user || lex_mi->password ||
lex_mi->log_file_name || lex_mi->pos || lex_mi->bind_addr ||
lex_mi->network_namespace || lex_mi->port || lex_mi->connect_retry ||
lex_mi->server_id || lex_mi->ssl != LEX_MASTER_INFO::LEX_MI_UNCHANGED ||
lex_mi->ssl_verify_server_cert != LEX_MASTER_INFO::LEX_MI_UNCHANGED ||
lex_mi->heartbeat_opt != LEX_MASTER_INFO::LEX_MI_UNCHANGED ||
lex_mi->retry_count_opt != LEX_MASTER_INFO::LEX_MI_UNCHANGED ||
lex_mi->ssl_key || lex_mi->ssl_cert || lex_mi->ssl_ca ||
lex_mi->ssl_capath || lex_mi->tls_version ||
lex_mi->tls_ciphersuites != LEX_MASTER_INFO::UNSPECIFIED ||
lex_mi->ssl_cipher || lex_mi->ssl_crl || lex_mi->ssl_crlpath ||
lex_mi->repl_ignore_server_ids_opt == LEX_MASTER_INFO::LEX_MI_ENABLE ||
lex_mi->public_key_path ||
lex_mi->get_public_key != LEX_MASTER_INFO::LEX_MI_UNCHANGED ||
lex_mi->zstd_compression_level || lex_mi->compression_algorithm ||
lex_mi->require_row_format != LEX_MASTER_INFO::LEX_MI_UNCHANGED)
have_receive_option = true;
return have_receive_option;
}
/**
This function checks if the given CHANGE MASTER/REPLICATION SOURCE command
has any execute option being set or changed.
- used in change_master().
@param lex_mi structure that holds all options given on the
change replication source command.
@param[out] need_relay_log_purge
- If relay_log_file/relay_log_pos options are used,
we won't delete relaylogs. We set this boolean flag to false.
- If relay_log_file/relay_log_pos options are NOT used,
we return the boolean flag UNCHANGED.
- Used in change_receive_options() and change_master().
@retval false No change replication source execute option.
@retval true At least one execute option was there.
*/
static bool have_change_replication_source_execute_option(
const LEX_MASTER_INFO *lex_mi, bool *need_relay_log_purge) {
bool have_execute_option = false;
DBUG_TRACE;
/* Check if *at least one* execute option is given on change master command*/
if (lex_mi->relay_log_name || lex_mi->relay_log_pos ||
lex_mi->sql_delay != -1 || lex_mi->privilege_checks_username != nullptr ||
lex_mi->privilege_checks_none ||
lex_mi->require_row_format != LEX_MASTER_INFO::LEX_MI_UNCHANGED ||
lex_mi->require_table_primary_key_check !=
LEX_MASTER_INFO::LEX_MI_PK_CHECK_UNCHANGED)
have_execute_option = true;
if (lex_mi->relay_log_name || lex_mi->relay_log_pos)
*need_relay_log_purge = false;
return have_execute_option;
}
/**
This function checks if the given CHANGE REPLICATION SOURCE command has
any option that affect both the receiver and the applier.
- used in change_master().
@param lex_mi structure that holds all options given on the
change replication source command.
@retval false no option that affects both applier and receiver was found
@retval true At least one option affects both the applier and receiver.
*/
static bool have_change_replication_source_applier_and_receive_option(
const LEX_MASTER_INFO *lex_mi) {
bool have_applier_receive_option = false;
DBUG_TRACE;
/* Check if *at least one* receive option is given to change rep source*/
if (lex_mi->assign_gtids_to_anonymous_transactions_type !=
LEX_MASTER_INFO::LEX_MI_ANONYMOUS_TO_GTID_UNCHANGED ||
lex_mi->auto_position != LEX_MASTER_INFO::LEX_MI_UNCHANGED ||
lex_mi->m_source_connection_auto_failover !=
LEX_MASTER_INFO::LEX_MI_UNCHANGED ||
lex_mi->m_gtid_only != LEX_MASTER_INFO::LEX_MI_UNCHANGED)
have_applier_receive_option = true;
return have_applier_receive_option;
}
/**
This function checks all possible cases in which compression algorithm,
compression level can be configured for a channel.
- used in change_receive_options
@param lex_mi pointer to structure holding all options specified
as part of change master to statement
@param mi pointer to structure holding all options specified
as part of change master to statement after performing
necessary checks
@retval false in case of success
@retval true in case of failures
*/
static bool change_master_set_compression(THD *, const LEX_MASTER_INFO *lex_mi,
Master_info *mi) {
DBUG_TRACE;
if (lex_mi->compression_algorithm) {
if (validate_compression_attributes(lex_mi->compression_algorithm,
lex_mi->channel, false))
return true;
assert(sizeof(mi->compression_algorithm) >
strlen(lex_mi->compression_algorithm));
strcpy(mi->compression_algorithm, lex_mi->compression_algorithm);
}
/* level specified */
if (lex_mi->zstd_compression_level) {
/* vaildate compression level */
if (!is_zstd_compression_level_valid(lex_mi->zstd_compression_level)) {
my_error(ER_CHANGE_SOURCE_WRONG_COMPRESSION_LEVEL_CLIENT, MYF(0),
lex_mi->zstd_compression_level, lex_mi->channel);
return true;
}
mi->zstd_compression_level = lex_mi->zstd_compression_level;
}
return false;
}
/**
This function is called if the change master command had at least one
receive option. This function then sets or alters the receive option(s)
given in the command. The execute options are handled in the function
change_execute_options()
- used in change_master().
- Receiver threads should be stopped when this function is called.
@param thd Pointer to THD object for the client thread executing the
statement.
@param lex_mi structure that holds all change master options given on the
change master command.
Coming from the an executing statement or set directly this
shall contain connection settings like hostname, user, password
and other settings like the number of connection retries.
@param mi Pointer to Master_info object belonging to the replica channel
to be configured
@retval 0 no error i.e., success.
@retval !=0 error.
*/
static int change_receive_options(THD *thd, LEX_MASTER_INFO *lex_mi,
Master_info *mi) {
int ret = 0; /* return value. Set if there is an error. */
DBUG_TRACE;
/*
If the user specified host or port without binlog or position,
reset binlog's name to FIRST and position to 4.
*/
if ((lex_mi->host && strcmp(lex_mi->host, mi->host)) ||
(lex_mi->port && lex_mi->port != mi->port)) {
/*
This is necessary because the primary key, i.e. host or port, has
changed.
The repository does not support direct changes on the primary key,
so the row is dropped and re-inserted with a new primary key. If we
don't do that, the master info repository we will end up with several
rows.
*/
if (mi->clean_info()) {
ret = 1;
goto err;
}
mi->master_uuid[0] = 0;
mi->master_id = 0;
}
if ((lex_mi->host || lex_mi->port) && !lex_mi->log_file_name &&
!lex_mi->pos) {
char *var_master_log_name = nullptr;
var_master_log_name = const_cast<char *>(mi->get_master_log_name());
var_master_log_name[0] = '\0';
mi->set_master_log_pos(BIN_LOG_HEADER_SIZE);
}
if (lex_mi->log_file_name) mi->set_master_log_name(lex_mi->log_file_name);
if (lex_mi->pos) {
mi->set_master_log_pos(lex_mi->pos);
}
if (lex_mi->log_file_name && !lex_mi->pos)
push_warning(thd, Sql_condition::SL_WARNING,
ER_WARN_ONLY_SOURCE_LOG_FILE_NO_POS,
ER_THD(thd, ER_WARN_ONLY_SOURCE_LOG_FILE_NO_POS));
DBUG_PRINT("info", ("source_log_pos: %lu", (ulong)mi->get_master_log_pos()));
if (lex_mi->user || lex_mi->password) {
if (!thd->get_ssl()) {
push_warning(thd, Sql_condition::SL_NOTE, ER_INSECURE_PLAIN_TEXT,
ER_THD(thd, ER_INSECURE_PLAIN_TEXT));
}
push_warning(thd, Sql_condition::SL_NOTE, ER_INSECURE_CHANGE_SOURCE,
ER_THD(thd, ER_INSECURE_CHANGE_SOURCE));
}
if (lex_mi->user) mi->set_user(lex_mi->user);
if (lex_mi->password) mi->set_password(lex_mi->password);
if (lex_mi->host) strmake(mi->host, lex_mi->host, sizeof(mi->host) - 1);
if (lex_mi->bind_addr)
strmake(mi->bind_addr, lex_mi->bind_addr, sizeof(mi->bind_addr) - 1);
if (lex_mi->network_namespace)
strmake(mi->network_namespace, lex_mi->network_namespace,
sizeof(mi->network_namespace) - 1);
/*
Setting channel's port number explicitly to '0' should be allowed.
Eg: 'group_replication_recovery' channel (*after recovery is done*)
or 'group_replication_applier' channel wants to set the port number
to '0' as there is no actual network usage on these channels.
*/
if (lex_mi->port || lex_mi->port_opt == LEX_MASTER_INFO::LEX_MI_ENABLE)
mi->port = lex_mi->port;
if (lex_mi->connect_retry) mi->connect_retry = lex_mi->connect_retry;
if (lex_mi->retry_count_opt != LEX_MASTER_INFO::LEX_MI_UNCHANGED)
mi->retry_count = lex_mi->retry_count;
if (lex_mi->heartbeat_opt != LEX_MASTER_INFO::LEX_MI_UNCHANGED)
mi->heartbeat_period = lex_mi->heartbeat_period;
else if (lex_mi->host || lex_mi->port) {
/*
If the user specified host or port or both without heartbeat_period,
we use default value for heartbeat_period. By default, We want to always
have heartbeat enabled when we switch master unless
master_heartbeat_period is explicitly set to zero (heartbeat disabled).
Here is the default value for heartbeat period if CHANGE MASTER did not
specify it. (no data loss in conversion as hb period has a max)
*/
mi->heartbeat_period = std::min<float>(SLAVE_MAX_HEARTBEAT_PERIOD,
(replica_net_timeout / 2.0f));
assert(mi->heartbeat_period > (float)0.001 || mi->heartbeat_period == 0);
// counter is cleared if master is CHANGED.
mi->received_heartbeats = 0;
// clear timestamp of last heartbeat as well.
mi->last_heartbeat = 0;
}
/*
reset the last time server_id list if the current CHANGE MASTER
is mentioning IGNORE_SERVER_IDS= (...)
*/
if (lex_mi->repl_ignore_server_ids_opt == LEX_MASTER_INFO::LEX_MI_ENABLE)
mi->ignore_server_ids->dynamic_ids.clear();
for (size_t i = 0; i < lex_mi->repl_ignore_server_ids.size(); i++) {
ulong s_id = lex_mi->repl_ignore_server_ids[i];
if (s_id == ::server_id && replicate_same_server_id) {
ret = ER_REPLICA_IGNORE_SERVER_IDS;
my_error(ER_REPLICA_IGNORE_SERVER_IDS, MYF(0), static_cast<int>(s_id));
goto err;
} else {
// Keep the array sorted, ignore duplicates.
mi->ignore_server_ids->dynamic_ids.insert_unique(s_id);
}
}
if (lex_mi->ssl != LEX_MASTER_INFO::LEX_MI_UNCHANGED)
mi->ssl = (lex_mi->ssl == LEX_MASTER_INFO::LEX_MI_ENABLE);
if (lex_mi->ssl_verify_server_cert != LEX_MASTER_INFO::LEX_MI_UNCHANGED)
mi->ssl_verify_server_cert =
(lex_mi->ssl_verify_server_cert == LEX_MASTER_INFO::LEX_MI_ENABLE);
if (lex_mi->public_key_path)
strmake(mi->public_key_path, lex_mi->public_key_path,
sizeof(mi->public_key_path) - 1);
if (lex_mi->get_public_key != LEX_MASTER_INFO::LEX_MI_UNCHANGED)
mi->get_public_key =
(lex_mi->get_public_key == LEX_MASTER_INFO::LEX_MI_ENABLE);
if (lex_mi->ssl_ca)
strmake(mi->ssl_ca, lex_mi->ssl_ca, sizeof(mi->ssl_ca) - 1);
if (lex_mi->ssl_capath)
strmake(mi->ssl_capath, lex_mi->ssl_capath, sizeof(mi->ssl_capath) - 1);
if (lex_mi->tls_version)
strmake(mi->tls_version, lex_mi->tls_version, sizeof(mi->tls_version) - 1);
if (LEX_MASTER_INFO::SPECIFIED_NULL == lex_mi->tls_ciphersuites) {
mi->tls_ciphersuites.first = true;
mi->tls_ciphersuites.second.clear();
} else if (LEX_MASTER_INFO::SPECIFIED_STRING == lex_mi->tls_ciphersuites) {
mi->tls_ciphersuites.first = false;
mi->tls_ciphersuites.second.assign(lex_mi->tls_ciphersuites_string);
}
if (lex_mi->ssl_cert)
strmake(mi->ssl_cert, lex_mi->ssl_cert, sizeof(mi->ssl_cert) - 1);
if (lex_mi->ssl_cipher)
strmake(mi->ssl_cipher, lex_mi->ssl_cipher, sizeof(mi->ssl_cipher) - 1);
if (lex_mi->ssl_key)
strmake(mi->ssl_key, lex_mi->ssl_key, sizeof(mi->ssl_key) - 1);
if (lex_mi->ssl_crl)
strmake(mi->ssl_crl, lex_mi->ssl_crl, sizeof(mi->ssl_crl) - 1);
if (lex_mi->ssl_crlpath)
strmake(mi->ssl_crlpath, lex_mi->ssl_crlpath, sizeof(mi->ssl_crlpath) - 1);
ret = change_master_set_compression(thd, lex_mi, mi);
if (ret) goto err;
err:
return ret;
}
/**
This function is called if the change master command had at least one
execute option. This function then sets or alters the execute option(s)
given in the command. The receive options are handled in the function
change_receive_options()
- used in change_master().
- Execute threads should be stopped before this function is called.
@param lex_mi structure that holds all change master options given on the
change master command.
@param mi Pointer to Master_info object belonging to the replica channel
that will be configured
@return false if the execute options were successfully set and true,
otherwise.
*/
static bool change_execute_options(LEX_MASTER_INFO *lex_mi, Master_info *mi) {
DBUG_TRACE;
if (lex_mi->privilege_checks_username != nullptr ||
lex_mi->privilege_checks_none) {
Relay_log_info::enum_priv_checks_status error{
mi->rli->set_privilege_checks_user(
lex_mi->privilege_checks_username,
lex_mi->privilege_checks_none ? nullptr
: lex_mi->privilege_checks_hostname)};
if (!!error) {
mi->rli->report_privilege_check_error(
ERROR_LEVEL, error, true /* to client*/, mi->rli->get_channel(),
lex_mi->privilege_checks_username, lex_mi->privilege_checks_hostname);
return true;
}
}
if (lex_mi->require_row_format != LEX_MASTER_INFO::LEX_MI_UNCHANGED) {
mi->rli->set_require_row_format(lex_mi->require_row_format ==
LEX_MASTER_INFO::LEX_MI_ENABLE);
}
if (lex_mi->require_table_primary_key_check !=
LEX_MASTER_INFO::LEX_MI_PK_CHECK_UNCHANGED) {
switch (lex_mi->require_table_primary_key_check) {
case (LEX_MASTER_INFO::LEX_MI_PK_CHECK_STREAM):
mi->rli->set_require_table_primary_key_check(
Relay_log_info::PK_CHECK_STREAM);
break;
case (LEX_MASTER_INFO::LEX_MI_PK_CHECK_ON):
mi->rli->set_require_table_primary_key_check(
Relay_log_info::PK_CHECK_ON);
break;
case (LEX_MASTER_INFO::LEX_MI_PK_CHECK_OFF):
mi->rli->set_require_table_primary_key_check(
Relay_log_info::PK_CHECK_OFF);
break;
case (LEX_MASTER_INFO::LEX_MI_PK_CHECK_GENERATE):
if (channel_map.is_group_replication_channel_name(lex_mi->channel)) {
my_error(ER_REQUIRE_TABLE_PRIMARY_KEY_CHECK_GENERATE_WITH_GR, MYF(0));
return true;
}
mi->rli->set_require_table_primary_key_check(
Relay_log_info::PK_CHECK_GENERATE);
break;
default: /* purecov: tested */
assert(0); /* purecov: tested */
break;
}
}
if (lex_mi->relay_log_name) {
char relay_log_name[FN_REFLEN];
mi->rli->relay_log.make_log_name(relay_log_name, lex_mi->relay_log_name);
mi->rli->set_group_relay_log_name(relay_log_name);
mi->rli->is_group_master_log_pos_invalid = true;
}
if (lex_mi->relay_log_pos) {
mi->rli->set_group_relay_log_pos(lex_mi->relay_log_pos);
mi->rli->is_group_master_log_pos_invalid = true;
}
if (lex_mi->sql_delay != -1) mi->rli->set_sql_delay(lex_mi->sql_delay);
return false;
}
/**
This function is called if the change replication source command had at
least one option that affects both the receiver and applier parts.
Pure execute option(s) are handled in change_execute_options()
The receive options are handled in the function change_receive_options()
- used in change_master().
- Both receiver and applier threads should be stopped on invocation
@param lex_mi structure that holds all change replication source options
@param mi Pointer to Master_info object belonging to the replica channel
to be configured
@return false if successfully set, true otherwise.
*/
static bool change_applier_receiver_options(THD *thd, LEX_MASTER_INFO *lex_mi,
Master_info *mi) {
if (lex_mi->m_source_connection_auto_failover !=
LEX_MASTER_INFO::LEX_MI_UNCHANGED) {
if (lex_mi->m_source_connection_auto_failover ==
LEX_MASTER_INFO::LEX_MI_ENABLE) {
mi->set_source_connection_auto_failover();
/*
Send replication channel SOURCE_CONNECTION_AUTO_FAILOVER attribute of
CHANGE REPLICATION SOURCE command status to group replication group
members.
*/
if (rpl_acf_configuration_handler->send_channel_status_and_version_data(
mi->get_channel(),
Rpl_acf_status_configuration::SOURCE_CONNECTION_AUTO_FAILOVER,
1)) {
my_error(ER_GRP_RPL_FAILOVER_CHANNEL_STATUS_PROPAGATION, MYF(0),
mi->get_channel());
mi->unset_source_connection_auto_failover();
return true;
}
/*
If IO thread is running and the monitoring thread is not, start
the monitoring thread.
*/
if (mi->slave_running &&
!Source_IO_monitor::get_instance()->is_monitoring_process_running()) {
if (Source_IO_monitor::get_instance()->launch_monitoring_process(
key_thread_replica_monitor_io)) {
my_error(ER_STARTING_REPLICA_MONITOR_IO_THREAD, MYF(0));
return true;
}
}
} else {
/*
If this is the only channel with source_connection_auto_failover,
then stop the monitoring thread.
*/
if (mi->is_source_connection_auto_failover() && mi->slave_running &&
channel_map
.get_number_of_connection_auto_failover_channels_running() ==
1) {
if (Source_IO_monitor::get_instance()->terminate_monitoring_process()) {
my_error(ER_STOP_REPLICA_MONITOR_IO_THREAD_TIMEOUT, MYF(0));
return true;
}
}
mi->unset_source_connection_auto_failover();
/*
Send replication channel SOURCE_CONNECTION_AUTO_FAILOVER attribute of
CHANGE REPLICATION SOURCE command status to group replication group
members.
*/
if (rpl_acf_configuration_handler->send_channel_status_and_version_data(
mi->get_channel(),
Rpl_acf_status_configuration::SOURCE_CONNECTION_AUTO_FAILOVER,
0)) {
my_error(ER_GRP_RPL_FAILOVER_CHANNEL_STATUS_PROPAGATION, MYF(0),
mi->get_channel());
return true;
}
}
}
if (lex_mi->auto_position != LEX_MASTER_INFO::LEX_MI_UNCHANGED) {
mi->set_auto_position(
(lex_mi->auto_position == LEX_MASTER_INFO::LEX_MI_ENABLE));
}
if (lex_mi->assign_gtids_to_anonymous_transactions_type !=
LEX_MASTER_INFO::LEX_MI_ANONYMOUS_TO_GTID_UNCHANGED) {
if (lex_mi->assign_gtids_to_anonymous_transactions_type >
LEX_MASTER_INFO::LEX_MI_ANONYMOUS_TO_GTID_OFF) {
push_warning(
thd, Sql_condition::SL_NOTE,
ER_USING_ASSIGN_GTIDS_TO_ANONYMOUS_TRANSACTIONS_AS_LOCAL_OR_UUID,
ER_THD(
thd,
ER_USING_ASSIGN_GTIDS_TO_ANONYMOUS_TRANSACTIONS_AS_LOCAL_OR_UUID));
}
switch (lex_mi->assign_gtids_to_anonymous_transactions_type) {
case (LEX_MASTER_INFO::LEX_MI_ANONYMOUS_TO_GTID_LOCAL):
mi->rli->m_assign_gtids_to_anonymous_transactions_info.set_info(
Assign_gtids_to_anonymous_transactions_info::enum_type::AGAT_LOCAL,
::server_uuid);
break;
case (LEX_MASTER_INFO::LEX_MI_ANONYMOUS_TO_GTID_UUID):
if (mi->rli->m_assign_gtids_to_anonymous_transactions_info.set_info(
Assign_gtids_to_anonymous_transactions_info::enum_type::
AGAT_UUID,
lex_mi->assign_gtids_to_anonymous_transactions_manual_uuid))
return true;
break;
case (LEX_MASTER_INFO::LEX_MI_ANONYMOUS_TO_GTID_OFF):
mi->rli->m_assign_gtids_to_anonymous_transactions_info.set_info(
Assign_gtids_to_anonymous_transactions_info::enum_type::AGAT_OFF,
"");
break;
default:
assert(0);
break;
}
}
if (lex_mi->m_gtid_only != LEX_MASTER_INFO::LEX_MI_UNCHANGED) {
mi->set_gtid_only_mode(
(lex_mi->m_gtid_only == LEX_MASTER_INFO::LEX_MI_ENABLE));
}
return false;
}
/**
This function shall issue a deprecation warning if
there are server ids tokenized from the CHANGE MASTER
TO command while @@global.gtid_mode=ON.
*/
static void issue_deprecation_warnings_for_channel(THD *thd) {
LEX_MASTER_INFO *lex_mi = &thd->lex->mi;
/*
Deprecation of GTID_MODE + IGNORE_SERVER_IDS
Generate deprecation warning when user executes CHANGE
MASTER TO IGNORE_SERVER_IDS if GTID_MODE=ON.
*/
if (lex_mi->repl_ignore_server_ids.size() > 0 &&
global_gtid_mode.get() == Gtid_mode::ON) {
push_warning_printf(thd, Sql_condition::SL_WARNING,
ER_WARN_DEPRECATED_SYNTAX,
ER_THD(thd, ER_WARN_DEPRECATED_SYNTAX_NO_REPLACEMENT),
"CHANGE MASTER TO ... IGNORE_SERVER_IDS='...' "
"(when @@GLOBAL.GTID_MODE = ON)");
}
}
/**
This function validates that change replication source options are
valid according to the current GTID_MODE.
This method assumes it will only be called when GTID_MODE != ON
@param lex_mi structure that holds all change replication source options
@param mi Pointer to Master_info object belonging to the replica channel
to be configured
@return false if the configuration is valid
true some configuration option is invalid with GTID_MODE
*/
static int validate_gtid_option_restrictions(const LEX_MASTER_INFO *lex_mi,
Master_info *mi) {
int error = 0;
/*
CHANGE REPLICATION SOURCE TO SOURCE_AUTO_POSITION = 1 requires
GTID_MODE != OFF
*/
if (global_gtid_mode.get() == Gtid_mode::OFF) {
if (lex_mi->auto_position == LEX_MASTER_INFO::LEX_MI_ENABLE) {
error = ER_AUTO_POSITION_REQUIRES_GTID_MODE_NOT_OFF;
my_error(ER_AUTO_POSITION_REQUIRES_GTID_MODE_NOT_OFF, MYF(0));
return error;
}
}
/*
CHANGE REPLICATION SOURCE TO ASSIGN_GTIDS_TO_ANONYMOUS_TRANSACTIONS != OFF
requires GTID_MODE = ON
*/
if (lex_mi->assign_gtids_to_anonymous_transactions_type >
LEX_MASTER_INFO::LEX_MI_ANONYMOUS_TO_GTID_OFF) {
error = ER_ASSIGN_GTIDS_TO_ANONYMOUS_TRANSACTIONS_REQUIRES_GTID_MODE_ON;
my_error(ER_ASSIGN_GTIDS_TO_ANONYMOUS_TRANSACTIONS_REQUIRES_GTID_MODE_ON,
MYF(0));
return error;
}
/*
CHANGE REPLICATION SOURCE TO GTID_ONLY= 1 requires
GTID_MODE = ON
*/
if (lex_mi->m_gtid_only == LEX_MASTER_INFO::LEX_MI_ENABLE) {
error = ER_CHANGE_REPLICATION_SOURCE_NO_OPTIONS_FOR_GTID_ONLY;
my_error(ER_CHANGE_REPLICATION_SOURCE_NO_OPTIONS_FOR_GTID_ONLY, MYF(0),
mi->get_channel());
return error;
}
/*
CHANGE REPLICATION SOURCE TO SOURCE_CONNECTION_AUTO_FAILOVER = 1 requires
GTID_MODE = ON
*/
if (lex_mi->m_source_connection_auto_failover ==
LEX_MASTER_INFO::LEX_MI_ENABLE) {
error = ER_RPL_ASYNC_RECONNECT_GTID_MODE_OFF;
my_error(ER_RPL_ASYNC_RECONNECT_GTID_MODE_OFF, MYF(0));
return error;
}
if (channel_map.is_group_replication_channel_name(lex_mi->channel)) {
error = ER_CHANGE_REP_SOURCE_GR_CHANNEL_WITH_GTID_MODE_NOT_ON;
my_error(error, MYF(0));
return error;
}
return error;
}
/**
This is an helper method for boolean vars like
SOURCE_AUTO_POSITION
REQUIRE_ROW_FORMAT
SOURCE_CONNECTION_AUTO_FAILOVER
It tells if the variable is already enabled or will be by the command
@param base_value the current variable value
@param option_value the configuration input value (UNCHANGED,ENABLED,DISABLE)
@return true if the option was already enable or will be. false otherwise
*/
bool is_option_enabled_or_will_be(bool base_value, int option_value) {
bool var_enabled = base_value;
switch (option_value) {
case LEX_MASTER_INFO::LEX_MI_ENABLE:
var_enabled = true;
break;
case LEX_MASTER_INFO::LEX_MI_DISABLE:
var_enabled = false;
break;
case LEX_MASTER_INFO::LEX_MI_UNCHANGED:
break;
default:
assert(0);
break;
}
return var_enabled;
}
/**
This method evaluates if the different options given to
CHANGE REPLICATION SOURCE TO
are compatible with the current configuration and with one another.
Example: SOURCE_CONNECTION_AUTO_FAILOVER = 1 requires
SOURCE_AUTO_POSITION to be already enabled or to be enabled on this command.
@param lex_mi structure that holds all change replication source options given
on the command
@param mi Pointer to Master_info object for the channel that holds the
the configuration
@return 0 if no issues are found
!= 0 the error number associated to the issue, if one is found
*/
int evaluate_inter_option_dependencies(const LEX_MASTER_INFO *lex_mi,
Master_info *mi) {
int error = 0;
/**
We first define the variables used and then we group the checks for
readability
*/
bool is_or_will_auto_position_be_enabled = is_option_enabled_or_will_be(
mi->is_auto_position(), lex_mi->auto_position);
bool will_auto_position_be_disable =
mi->is_auto_position() &&
lex_mi->auto_position == LEX_MASTER_INFO::LEX_MI_DISABLE;
bool is_or_will_require_row_format_be_enabled = is_option_enabled_or_will_be(
mi->rli->is_row_format_required(), lex_mi->require_row_format);
bool will_require_row_format_be_disable =
mi->rli->is_row_format_required() &&
lex_mi->require_row_format == LEX_MASTER_INFO::LEX_MI_DISABLE;
bool is_or_will_source_connection_auto_failover_be_enabled =
is_option_enabled_or_will_be(mi->is_source_connection_auto_failover(),
lex_mi->m_source_connection_auto_failover);
bool is_or_will_gtid_only_be_enabled = is_option_enabled_or_will_be(
mi->is_gtid_only_mode(), lex_mi->m_gtid_only);
bool will_gtid_only_mode_be_disable =
mi->is_gtid_only_mode() &&
lex_mi->m_gtid_only == LEX_MASTER_INFO::LEX_MI_DISABLE;
auto assign_gtids_to_anonymous_transactions_type =
mi->rli->m_assign_gtids_to_anonymous_transactions_info.get_type();
switch (lex_mi->assign_gtids_to_anonymous_transactions_type) {
case LEX_MASTER_INFO::LEX_MI_ANONYMOUS_TO_GTID_OFF:
assign_gtids_to_anonymous_transactions_type =
Assign_gtids_to_anonymous_transactions_info::enum_type::AGAT_OFF;
break;
case LEX_MASTER_INFO::LEX_MI_ANONYMOUS_TO_GTID_LOCAL:
assign_gtids_to_anonymous_transactions_type =
Assign_gtids_to_anonymous_transactions_info::enum_type::AGAT_LOCAL;
break;
case LEX_MASTER_INFO::LEX_MI_ANONYMOUS_TO_GTID_UUID:
assign_gtids_to_anonymous_transactions_type =
Assign_gtids_to_anonymous_transactions_info::enum_type::AGAT_UUID;
break;
case LEX_MASTER_INFO::LEX_MI_ANONYMOUS_TO_GTID_UNCHANGED:
break;
default:
assert(0);
break;
}
/* Check phase - enabling options */
/*
We cannot specify auto position and set either the coordinates
on source or replica. If we try to do so, an error message is
printed out.
*/
if (lex_mi->log_file_name != nullptr || lex_mi->pos != 0 ||
lex_mi->relay_log_name != nullptr || lex_mi->relay_log_pos != 0) {
if (lex_mi->auto_position == LEX_MASTER_INFO::LEX_MI_ENABLE ||
(lex_mi->auto_position != LEX_MASTER_INFO::LEX_MI_DISABLE &&
mi->is_auto_position())) {
error = ER_BAD_REPLICA_AUTO_POSITION;
my_error(error, MYF(0));
return error;
}
}
/*
CHANGE REPLICATION SOURCE TO ASSIGN_GTIDS_TO_ANONYMOUS_TRANSACTIONS != OFF
requires
SOURCE_AUTO_POSITION = 0
*/
if (assign_gtids_to_anonymous_transactions_type !=
Assign_gtids_to_anonymous_transactions_info::enum_type::AGAT_OFF &&
is_or_will_auto_position_be_enabled) {
error = ER_CANT_COMBINE_ANONYMOUS_TO_GTID_AND_AUTOPOSITION;
my_error(error, MYF(0));
return error;
}
/*
CHANGE REPLICATION SOURCE TO GTID_ONLY = 1 requires
SOURCE_AUTO_POSITION = 1
REQUIRE_ROW_FORMAT = 1
*/
if (lex_mi->m_gtid_only == LEX_MASTER_INFO::LEX_MI_ENABLE &&
(!is_or_will_auto_position_be_enabled ||
!is_or_will_require_row_format_be_enabled)) {
error = ER_CHANGE_REPLICATION_SOURCE_NO_OPTIONS_FOR_GTID_ONLY;
my_error(error, MYF(0), mi->get_channel());
return error;
}
/*
CHANGE REPLICATION SOURCE TO SOURCE_CONNECTION_AUTO_FAILOVER = 1 requires
SOURCE_AUTO_POSITION = 1
*/
if (lex_mi->m_source_connection_auto_failover ==
LEX_MASTER_INFO::LEX_MI_ENABLE &&
!is_or_will_auto_position_be_enabled) {
error = ER_RPL_ASYNC_RECONNECT_AUTO_POSITION_OFF;
my_error(error, MYF(0));
return error;
}
/*
We need to check if there is an empty master_host. Otherwise
change master succeeds, a master.info file is created containing
empty master_host string and when issuing: start replica; an error
is thrown stating that the server is not configured as replica.
(See BUG#28796).
*/
if (lex_mi->host && !*lex_mi->host) {
error = ER_WRONG_ARGUMENTS;
my_error(error, MYF(0), "SOURCE_HOST");
return error;
}
/*
Changing source_connection_auto_failover option is not allowed on group
secondary member.
*/
if (lex_mi->m_source_connection_auto_failover !=
LEX_MASTER_INFO::LEX_MI_UNCHANGED &&
is_group_replication_member_secondary()) {
error = ER_OPERATION_NOT_ALLOWED_ON_GR_SECONDARY;
my_error(error, MYF(0));
return error;
}
/*
CHANGE REPLICATION SOURCE TO ASSIGN_GTIDS_TO_ANONYMOUS_TRANSACTIONS != OFF
can't use the same value as the group replication name or view change uuid
*/
if (lex_mi->assign_gtids_to_anonymous_transactions_type >
LEX_MASTER_INFO::LEX_MI_ANONYMOUS_TO_GTID_OFF) {
std::string group_name = get_group_replication_group_name();
if (group_name.length() > 0) {
bool is_same = false;
auto type = lex_mi->assign_gtids_to_anonymous_transactions_type;
if (type == LEX_MASTER_INFO::LEX_MI_ANONYMOUS_TO_GTID_LOCAL)
if (!(group_name.compare(::server_uuid))) is_same = true;
if (type == LEX_MASTER_INFO::LEX_MI_ANONYMOUS_TO_GTID_UUID)
if (!(group_name.compare(
lex_mi->assign_gtids_to_anonymous_transactions_manual_uuid)))
is_same = true;
if (is_same) {
error = ER_CANT_USE_SAME_UUID_AS_GROUP_NAME;
my_error(error, MYF(0));
return error;
}
std::string view_change_uuid;
if (get_group_replication_view_change_uuid(view_change_uuid)) {
/* purecov: begin inspected */
error = ER_GRP_RPL_VIEW_CHANGE_UUID_FAIL_GET_VARIABLE;
my_error(error, MYF(0));
return error;
/* purecov: end */
} else {
if (type == LEX_MASTER_INFO::LEX_MI_ANONYMOUS_TO_GTID_LOCAL)
if (!(view_change_uuid.compare(::server_uuid))) is_same = true;
if (type == LEX_MASTER_INFO::LEX_MI_ANONYMOUS_TO_GTID_UUID)
if (!(view_change_uuid.compare(
lex_mi->assign_gtids_to_anonymous_transactions_manual_uuid)))
is_same = true;
if (is_same) {
error = ER_CANT_USE_SAME_UUID_AS_VIEW_CHANGE_UUID;
my_error(error, MYF(0));
return error;
}
}
}
}
/* Check phase - disabling options */
/*
CHANGE REPLICATION SOURCE TO ASSIGN_GTIDS_TO_ANONYMOUS_TRANSACTIONS
auto_position cannot be disable if either source_connection_auto_failover
option is enabled or getting enabled in current CHANGE MASTER statement.
*/
if (will_auto_position_be_disable &&
is_or_will_source_connection_auto_failover_be_enabled) {
error = ER_DISABLE_AUTO_POSITION_REQUIRES_ASYNC_RECONNECT_OFF;
my_error(error, MYF(0));
return error;
}
/*
CHANGE REPLICATION SOURCE TO SOURCE_AUTO_POSITION = 0 cannot be done when
GTID_ONLY = 1
*/
if (will_auto_position_be_disable && is_or_will_gtid_only_be_enabled) {
error = ER_CHANGE_REP_SOURCE_CANT_DISABLE_AUTO_POSITION_WITH_GTID_ONLY;
my_error(error, MYF(0), mi->get_channel());
return error;
}
/*
CHANGE REPLICATION SOURCE TO REQUIRE_ROW_FORMAT = 0 cannot be done when
GTID_ONLY = 1
*/
if (will_require_row_format_be_disable && is_or_will_gtid_only_be_enabled) {
error = ER_CHANGE_REP_SOURCE_CANT_DISABLE_REQ_ROW_FORMAT_WITH_GTID_ONLY;
my_error(error, MYF(0), mi->get_channel());
return error;
}
/*
CHANGE REPLICATION SOURCE TO SOURCE_AUTO_POSITION = 0 when
source positions in relation to the source are invalid.
This requires `SOURCE_LOG_FILE` and `SOURCE_LOG_POS`
The message varies if you are also disabling `GTID_ONLY`
*/
if (will_auto_position_be_disable) {
if (mi->is_receiver_position_info_invalid()) {
if (lex_mi->log_file_name == nullptr || lex_mi->pos == 0) {
if (will_gtid_only_mode_be_disable) {
error = ER_CHANGE_REP_SOURCE_CANT_DISABLE_GTID_ONLY_WITHOUT_POSITIONS;
my_error(error, MYF(0), mi->get_channel());
} else {
error = ER_CHANGE_REP_SOURCE_CANT_DISABLE_AUTO_POS_WITHOUT_POSITIONS;
my_error(error, MYF(0), mi->get_channel());
}
return error;
}
}
}
return error;
}
/**
Log a warning in case GTID_ONLY or SOURCE AUTO POSITION are disabled
and the server contains invalid positions.
@param thd the associated thread object
@param lex_mi structure that holds all change replication source options given
on the command
@param mi Pointer to Master_info object
*/
static void log_invalid_position_warning(THD *thd,
const LEX_MASTER_INFO *lex_mi,
Master_info *mi) {
if (lex_mi->m_gtid_only == LEX_MASTER_INFO::LEX_MI_DISABLE ||
lex_mi->auto_position == LEX_MASTER_INFO::LEX_MI_DISABLE) {
if (mi->is_receiver_position_info_invalid() ||
mi->rli->is_applier_source_position_info_invalid()) {
push_warning_printf(
thd, Sql_condition::SL_WARNING,
ER_WARN_C_DISABLE_GTID_ONLY_WITH_SOURCE_AUTO_POS_INVALID_POS,
ER_THD(thd,
ER_WARN_C_DISABLE_GTID_ONLY_WITH_SOURCE_AUTO_POS_INVALID_POS),
mi->get_channel());
LogErr(WARNING_LEVEL,
ER_WARN_L_DISABLE_GTID_ONLY_WITH_SOURCE_AUTO_POS_INVALID_POS,
mi->get_channel());
}
}
}
/**
This method aggregates the validation checks made for the command
CHANGE REPLICATION SOURCE
@param thd Pointer to THD object for the client thread executing the
statement.
@param lex_mi structure that holds all change replication source options given
on the command
@param mi Pointer to Master_info object for the channel that holds the
the configuration
@param thread_mask The thread mask identifying which threads are running
@return A pair of booleans <return_value, remove_mta_info>
return_value: true if an error occurred, false otherwise
remove_mta_info: if true remove MTA worker info
*/
static std::pair<bool, bool> validate_change_replication_source_options(
THD *thd, const LEX_MASTER_INFO *lex_mi, Master_info *mi, int thread_mask) {
bool mta_remove_worker_info = false;
if ((thread_mask & SLAVE_SQL) == 0) // If execute threads are stopped
{
if (mi->rli->mts_recovery_group_cnt) {
/*
Change-Master can't be done if there is a mts group gap.
That requires mts-recovery which START SLAVE provides.
*/
assert(mi->rli->recovery_parallel_workers);
my_error(ER_MTA_CHANGE_SOURCE_CANT_RUN_WITH_GAPS, MYF(0));
return std::make_pair(true, mta_remove_worker_info);
} else {
/*
Lack of mts group gaps makes Workers info stale regardless of
need_relay_log_purge computation. We set the mta_remove_worker_info
flag here and call reset_workers() later to delete the worker info
in mysql.slave_worker_info table.
*/
if (mi->rli->recovery_parallel_workers) mta_remove_worker_info = true;
}
}
/*
When give a warning?
CHANGE MASTER command is used in three ways:
a) To change a connection configuration but remain connected to
the same master.
b) To change positions in binary or relay log(eg: master_log_pos).
c) To change the master you are replicating from.
We give a warning in cases b and c.
*/
if ((lex_mi->host || lex_mi->port || lex_mi->log_file_name || lex_mi->pos ||
lex_mi->relay_log_name || lex_mi->relay_log_pos) &&
(mi->rli->atomic_channel_open_temp_tables > 0))
push_warning(thd, Sql_condition::SL_WARNING,
ER_WARN_OPEN_TEMP_TABLES_MUST_BE_ZERO,
ER_THD(thd, ER_WARN_OPEN_TEMP_TABLES_MUST_BE_ZERO));
/**
Although this check is redone when the user is set, we do an early
check here to avoid failures in the middle of configuration
*/
Relay_log_info::enum_priv_checks_status priv_check_error;
priv_check_error = mi->rli->check_privilege_checks_user(
lex_mi->privilege_checks_username,
lex_mi->privilege_checks_none ? nullptr
: lex_mi->privilege_checks_hostname);
if (!!priv_check_error) {
mi->rli->report_privilege_check_error(
ERROR_LEVEL, priv_check_error, true /* to client*/,
mi->rli->get_channel(), lex_mi->privilege_checks_username,
lex_mi->privilege_checks_hostname);
return std::make_pair(true, mta_remove_worker_info);
}
return std::make_pair(false, mta_remove_worker_info);
}
/**
This method aggregates the the instantiation of options for the command
CHANGE REPLICATION SOURCE
@param thd Pointer to THD object for the client thread executing the
statement.
@param lex_mi structure that holds all change replication source options given
on the command
@param mi Pointer to Master_info object belonging to the replica channel
to be configured
@param have_both_receive_execute_option the command will change options that
affect both the applier and receiver
@param have_execute_option the command will change applier related options
@param have_receive_option the command will change receiver related options
@return returns true if an error occurred, false otherwise
*/
static bool update_change_replication_source_options(
THD *thd, LEX_MASTER_INFO *lex_mi, Master_info *mi,
bool have_both_receive_execute_option, bool have_execute_option,
bool have_receive_option) {
if (have_both_receive_execute_option) {
if (change_applier_receiver_options(thd, lex_mi, mi)) {
return true;
}
}
if (channel_map.is_group_replication_channel_name(lex_mi->channel)) {
mi->set_auto_position(true);
mi->rli->set_require_row_format(true);
mi->set_gtid_only_mode(true);
}
if (have_execute_option && change_execute_options(lex_mi, mi)) return true;
if (have_receive_option) {
if (change_receive_options(thd, lex_mi, mi)) {
return true;
}
}
return false;
}
/**
Execute a CHANGE MASTER statement.
Apart from changing the receive/execute configurations/positions,
this function also does the following:
- May leave replicated open temporary table after warning.
- Purges relay logs if no threads running and no relay log file/pos options.
- Delete worker info in mysql.slave_worker_info table if applier not running.
@param thd Pointer to THD object for the client thread executing
the statement.
@param mi Pointer to Master_info object belonging to the slave's
IO thread.
@param lex_mi Lex information with master connection data.
Coming from the an executing statement or set directly
this shall contain connection settings like hostname,
user, password and other settings like the number of
connection retries.
@param preserve_logs If the decision of purging the logs should be always be
false even if no relay log name/position is given to
the method. The preserve_logs parameter will not be
respected when the relay log info repository is not
initialized.
@retval 0 success
@retval !=0 error
*/
int change_master(THD *thd, Master_info *mi, LEX_MASTER_INFO *lex_mi,
bool preserve_logs) {
int error = 0;
/* Do we have at least one receive related (IO thread) option? */
bool have_receive_option = false;
/* Do we have at least one execute related (SQL/coord/worker) option? */
bool have_execute_option = false;
/* Do we have at least one option that relates to receival and execution? */
bool have_both_receive_execute_option = false;
/** Is there a an error during validation */
bool validation_error = false;
/* If there are no mts gaps, we delete the rows in this table. */
bool mta_remove_worker_info = false;
/* used as a bit mask to indicate running slave threads. */
int thread_mask;
/*
Relay logs are purged only if both receive and execute threads are
stopped before executing CHANGE MASTER and relay_log_file/relay_log_pos
options are not used.
*/
bool need_relay_log_purge = true;
/*
We want to save the old receive configurations so that we can use them to
print the changes in these configurations (from-to form). This is used in
LogErr() later.
*/
char saved_host[HOSTNAME_LENGTH + 1], saved_bind_addr[HOSTNAME_LENGTH + 1];
uint saved_port = 0;
char saved_log_name[FN_REFLEN];
my_off_t saved_log_pos = 0;
DBUG_TRACE;
/*
CHANGE MASTER command should ignore 'read-only' and 'super_read_only'
options so that it can update 'mysql.slave_master_info' replication
repository tables.
*/
thd->set_skip_readonly_check();
mi->channel_wrlock();
/*
When we change master, we first decide which thread is running and
which is not. We dont want this assumption to break while we change master.
Suppose we decide that receiver thread is running and thus it is
safe to change receive related options in mi. By this time if
the receive thread is started, we may have a race condition between
the client thread and receiver thread.
*/
lock_slave_threads(mi);
/*
Get a bit mask for the slave threads that are running.
Since the third argument is 0, thread_mask after the function
returns stands for running threads.
*/
init_thread_mask(&thread_mask, mi, false);
if (thread_mask) /* If any thread is running */
{
/*
Prior to WL#6120, we imposed the condition that STOP SLAVE is required
before CHANGE MASTER. Since the slave threads die on STOP SLAVE, it was
fine if we purged relay logs.
Now that we do allow CHANGE MASTER with a running receiver/applier thread,
we need to make sure that the relay logs are purged only if both
receiver and applier threads are stopped otherwise we could lose events.
The idea behind purging relay logs if both the threads are stopped is to
keep consistency with the old behavior. If the user/application is doing
a CHANGE MASTER without stopping any one thread, the relay log purge
should be controlled via the 'relay_log_purge' option.
*/
need_relay_log_purge = false;
}
/* Check if at least one receive option is given on change master */
have_receive_option = have_change_replication_source_receive_option(lex_mi);
/* Check if at least one execute option is given on change master */
have_execute_option = have_change_replication_source_execute_option(
lex_mi, &need_relay_log_purge);
/* Check if at least one execute option affects both the applier and receiver
*/
have_both_receive_execute_option =
have_change_replication_source_applier_and_receive_option(lex_mi);
/* If either:
+ An option affects both the applier and receiver and one of the threads
is running
+ There are receiver and applier options and both threads are running
Then tell the user the replica must stop
*/
if ((have_both_receive_execute_option &&
((thread_mask & SLAVE_IO) || (thread_mask & SLAVE_SQL))) ||
(have_receive_option && have_execute_option && (thread_mask & SLAVE_IO) &&
(thread_mask & SLAVE_SQL))) {
error = ER_REPLICA_CHANNEL_MUST_STOP;
my_error(ER_REPLICA_CHANNEL_MUST_STOP, MYF(0), mi->get_channel());
goto err;
}
/* With receiver thread running, we dont allow changing receive options. */
if (have_receive_option && (thread_mask & SLAVE_IO)) {
error = ER_REPLICA_CHANNEL_IO_THREAD_MUST_STOP;
my_error(ER_REPLICA_CHANNEL_IO_THREAD_MUST_STOP, MYF(0), mi->get_channel());
goto err;
}
/* With an execute thread running, we don't allow changing execute options. */
if (have_execute_option && (thread_mask & SLAVE_SQL)) {
error = ER_REPLICA_CHANNEL_SQL_THREAD_MUST_STOP;
my_error(ER_REPLICA_CHANNEL_SQL_THREAD_MUST_STOP, MYF(0),
mi->get_channel());
goto err;
}
/* If GTID_MODE is different from ON check if some options are invalid
We hold channel_map lock for the duration of the CHANGE MASTER.
This is important since it prevents that a concurrent
connection changes to GTID_MODE=OFF between this check and the
point where AUTO_POSITION is stored in the table and in mi.
*/
if (global_gtid_mode.get() != Gtid_mode::ON) {
if ((error = validate_gtid_option_restrictions(lex_mi, mi))) {
goto err;
}
}
if ((error = evaluate_inter_option_dependencies(lex_mi, mi))) {
goto err;
}
if (need_relay_log_purge && /* If we should purge the logs for this channel */
preserve_logs && /* And we were asked to keep them */
mi->rli->inited) /* And the channel was initialized properly */
{
need_relay_log_purge = false;
}
THD_STAGE_INFO(thd, stage_changing_source);
int thread_mask_stopped_threads;
/*
Before load_mi_and_rli_from_repositories() call, get a bit mask to indicate
stopped threads in thread_mask_stopped_threads. Since the third argguement
is 1, thread_mask when the function returns stands for stopped threads.
*/
init_thread_mask(&thread_mask_stopped_threads, mi, true);
if (load_mi_and_rli_from_repositories(mi, false, thread_mask_stopped_threads,
need_relay_log_purge)) {
error = ER_CONNECTION_METADATA;
my_error(ER_CONNECTION_METADATA, MYF(0));
goto err;
}
std::tie(validation_error, mta_remove_worker_info) =
validate_change_replication_source_options(thd, lex_mi, mi, thread_mask);
if (validation_error) {
error = 1;
goto err;
}
/*
Validation operations should be above this comment
Try to use the validate_change_replication_source_options method
Changes to variables should be below this comment
Try to use the update_change_replication_source_options method
*/
if (have_receive_option) {
strmake(saved_host, mi->host, HOSTNAME_LENGTH);
strmake(saved_bind_addr, mi->bind_addr, HOSTNAME_LENGTH);
saved_port = mi->port;
strmake(saved_log_name, mi->get_master_log_name(), FN_REFLEN - 1);
saved_log_pos = mi->get_master_log_pos();
}
if (update_change_replication_source_options(
thd, lex_mi, mi, have_both_receive_execute_option,
have_execute_option, have_receive_option)) {
error = 1;
goto err;
}
/*
If user didn't specify neither host nor port nor any log name nor any log
pos, i.e. he specified only user/password/master_connect_retry,
master_delay, he probably wants replication to resume from where it had
left, i.e. from the coordinates of the **SQL** thread (imagine the case
where the I/O is ahead of the SQL; restarting from the coordinates of the
I/O would lose some events which is probably unwanted when you are just
doing minor changes like changing master_connect_retry). Note: coordinates
of the SQL thread must be read before the block which resets them.
*/
if (need_relay_log_purge) {
/*
A side-effect is that if only the I/O thread was started, this thread may
restart from ''/4 after the CHANGE MASTER. That's a minor problem (it is a
much more unlikely situation than the one we are fixing here).
*/
if (!lex_mi->host && !lex_mi->port && !lex_mi->log_file_name &&
!lex_mi->pos && !mi->rli->is_applier_source_position_info_invalid()) {
/*
Sometimes mi->rli->master_log_pos == 0 (it happens when the SQL thread
is not initialized), so we use a max(). What happens to
mi->rli->master_log_pos during the initialization stages of replication
is not 100% clear, so we guard against problems using max().
*/
mi->set_master_log_pos(max<ulonglong>(
BIN_LOG_HEADER_SIZE, mi->rli->get_group_master_log_pos()));
mi->set_master_log_name(mi->rli->get_group_master_log_name());
}
}
if (have_receive_option)
LogErr(SYSTEM_LEVEL, ER_REPLICA_CHANGE_SOURCE_TO_EXECUTED,
mi->get_for_channel_str(true), saved_host, saved_port,
saved_log_name, (ulong)saved_log_pos, saved_bind_addr, mi->host,
mi->port, mi->get_master_log_name(), (ulong)mi->get_master_log_pos(),
mi->bind_addr);
/* If the receiver is stopped, flush master_info to disk. */
if ((thread_mask & SLAVE_IO) == 0 && flush_master_info(mi, true)) {
error = ER_RELAY_LOG_INIT;
my_error(ER_RELAY_LOG_INIT, MYF(0),
"Failed to flush connection metadata repository");
goto err;
}
if ((thread_mask & SLAVE_SQL) == 0) /* Applier module is not executing */
{
if (need_relay_log_purge) {
/*
'if (need_relay_log_purge)' implicitly means that all slave threads are
stopped and there is no use of relay_log_file/relay_log_pos options.
We need not check these here again.
*/
/* purge_relay_log() returns pointer to an error message here. */
const char *errmsg = nullptr;
/*
purge_relay_log() assumes that we have run_lock and no slave threads
are running.
*/
THD_STAGE_INFO(thd, stage_purging_old_relay_logs);
if (mi->rli->purge_relay_logs(thd, &errmsg)) {
error = ER_RELAY_LOG_FAIL;
my_error(ER_RELAY_LOG_FAIL, MYF(0), errmsg);
goto err;
}
/*
Coordinates in rli were spoilt by purge_relay_logs(),
so restore them to good values. If we left them to ''/0, that would
work. But that would fail in the case of 2 successive CHANGE MASTER
(without a START SLAVE in between): because first one would set the
coords in mi to the good values of those in rli, then set those i>n rli
to ''/0, then second CHANGE MASTER would set the coords in mi to those
of rli, i.e. to ''/0: we have lost all copies of the original good
coordinates. That's why we always save good coords in rli.
*/
if (!mi->is_receiver_position_info_invalid()) {
mi->rli->set_group_master_log_pos(mi->get_master_log_pos());
mi->rli->set_group_master_log_name(mi->get_master_log_name());
DBUG_PRINT("info", ("source_log_pos: %llu", mi->get_master_log_pos()));
}
} else {
const char *errmsg = nullptr;
if (mi->rli->is_group_relay_log_name_invalid(&errmsg)) {
error = ER_RELAY_LOG_INIT;
my_error(ER_RELAY_LOG_INIT, MYF(0), errmsg);
goto err;
}
}
char *var_group_master_log_name =
const_cast<char *>(mi->rli->get_group_master_log_name());
if (!var_group_master_log_name[0] && // uninitialized case
!mi->rli->is_applier_source_position_info_invalid())
mi->rli->set_group_master_log_pos(0);
mi->rli->abort_pos_wait++; /* for SOURCE_POS_WAIT() to abort */
/* Clear the errors, for a clean start */
mi->rli->clear_error();
if (mi->rli->workers_array_initialized) {
for (size_t i = 0; i < mi->rli->get_worker_count(); i++) {
mi->rli->get_worker(i)->clear_error();
}
}
/*
If we don't write new coordinates to disk now, then old will remain in
relay-log.info until START SLAVE is issued; but if mysqld is shutdown
before START SLAVE, then old will remain in relay-log.info, and will be
the in-memory value at restart (thus causing errors, as the old relay log
does not exist anymore).
Notice that the rli table is available exclusively as slave is not
running.
*/
if (mi->rli->flush_info(Relay_log_info::RLI_FLUSH_IGNORE_SYNC_OPT |
Relay_log_info::RLI_FLUSH_IGNORE_GTID_ONLY)) {
error = ER_RELAY_LOG_INIT;
my_error(ER_RELAY_LOG_INIT, MYF(0), "Failed to flush relay info file.");
goto err;
}
} /* end 'if (thread_mask & SLAVE_SQL == 0)' */
log_invalid_position_warning(thd, lex_mi, mi);
if (mta_remove_worker_info)
if (Rpl_info_factory::reset_workers(mi->rli)) {
error = ER_MTA_RESET_WORKERS;
my_error(ER_MTA_RESET_WORKERS, MYF(0));
goto err;
}
err:
unlock_slave_threads(mi);
mi->channel_unlock();
return error;
}
/**
This function is first called when the Master_info object
corresponding to a channel in a multisourced slave does not
exist. But before a new channel is created, certain
conditions have to be met. The below function apriorily
checks if all such conditions are met. If all the
conditions are met then it creates a channel i.e
mi<->rli
@param[in,out] mi When new {mi,rli} are created,
the reference is stored in *mi
@param[in] channel The channel on which the change
master was introduced.
*/
int add_new_channel(Master_info **mi, const char *channel) {
DBUG_TRACE;
int error = 0;
Ident_name_check ident_check_status;
/*
Refuse to create a new channel if the repositories does not support this.
*/
if (opt_mi_repository_id == INFO_REPOSITORY_FILE ||
opt_rli_repository_id == INFO_REPOSITORY_FILE) {
LogErr(ERROR_LEVEL,
ER_RPL_REPLICA_NEW_C_M_NEEDS_REPOS_TYPE_OTHER_THAN_FILE);
error = ER_REPLICA_NEW_CHANNEL_WRONG_REPOSITORY;
my_error(ER_REPLICA_NEW_CHANNEL_WRONG_REPOSITORY, MYF(0));
goto err;
}
/*
Return if max num of replication channels exceeded already.
*/
if (!channel_map.is_valid_channel_count()) {
error = ER_REPLICA_MAX_CHANNELS_EXCEEDED;
my_error(ER_REPLICA_MAX_CHANNELS_EXCEEDED, MYF(0));
goto err;
}
/*
Now check the sanity of the channel name. It's length etc. The channel
identifier is similar to table names. So, use check_table_function.
*/
if (channel) {
ident_check_status = check_table_name(channel, strlen(channel));
} else
ident_check_status = Ident_name_check::WRONG;
if (ident_check_status != Ident_name_check::OK) {
error = ER_REPLICA_CHANNEL_NAME_INVALID_OR_TOO_LONG;
my_error(ER_REPLICA_CHANNEL_NAME_INVALID_OR_TOO_LONG, MYF(0));
goto err;
}
if (!((*mi) = Rpl_info_factory::create_mi_and_rli_objects(
opt_mi_repository_id, opt_rli_repository_id, channel, false,
&channel_map))) {
error = ER_CONNECTION_METADATA;
my_error(ER_CONNECTION_METADATA, MYF(0));
goto err;
}
err:
return error;
}
/**
Method used to check if the user is trying to update any other option for
the change master apart from the MASTER_USER and MASTER_PASSWORD.
In case user tries to update any other parameter apart from these two,
this method will return error.
@param lex_mi structure that holds all change master options given on
the change master command.
@retval true - The CHANGE MASTER is updating a unsupported parameter for the
recovery channel.
@retval false - Everything is fine. The CHANGE MASTER can execute with the
given option(s) for the recovery channel.
*/
static bool is_invalid_change_master_for_group_replication_recovery(
const LEX_MASTER_INFO *lex_mi) {
DBUG_TRACE;
bool have_extra_option_received = false;
/* Check if *at least one* receive/execute option is given on change master
* command*/
if (lex_mi->host || lex_mi->log_file_name || lex_mi->pos ||
lex_mi->bind_addr || lex_mi->port || lex_mi->connect_retry ||
lex_mi->server_id ||
lex_mi->auto_position != LEX_MASTER_INFO::LEX_MI_UNCHANGED ||
lex_mi->ssl != LEX_MASTER_INFO::LEX_MI_UNCHANGED ||
lex_mi->ssl_verify_server_cert != LEX_MASTER_INFO::LEX_MI_UNCHANGED ||
lex_mi->heartbeat_opt != LEX_MASTER_INFO::LEX_MI_UNCHANGED ||
lex_mi->retry_count_opt != LEX_MASTER_INFO::LEX_MI_UNCHANGED ||
lex_mi->ssl_key || lex_mi->ssl_cert || lex_mi->ssl_ca ||
lex_mi->ssl_capath || lex_mi->tls_version ||
lex_mi->tls_ciphersuites != LEX_MASTER_INFO::UNSPECIFIED ||
lex_mi->ssl_cipher || lex_mi->ssl_crl || lex_mi->ssl_crlpath ||
lex_mi->repl_ignore_server_ids_opt == LEX_MASTER_INFO::LEX_MI_ENABLE ||
lex_mi->relay_log_name || lex_mi->relay_log_pos ||
lex_mi->sql_delay != -1 || lex_mi->public_key_path ||
lex_mi->get_public_key != LEX_MASTER_INFO::LEX_MI_UNCHANGED ||
lex_mi->zstd_compression_level || lex_mi->compression_algorithm ||
lex_mi->require_row_format != LEX_MASTER_INFO::LEX_MI_UNCHANGED ||
lex_mi->m_source_connection_auto_failover !=
LEX_MASTER_INFO::LEX_MI_UNCHANGED ||
lex_mi->assign_gtids_to_anonymous_transactions_type !=
LEX_MASTER_INFO::LEX_MI_ANONYMOUS_TO_GTID_UNCHANGED ||
lex_mi->m_gtid_only != LEX_MASTER_INFO::LEX_MI_UNCHANGED)
have_extra_option_received = true;
return have_extra_option_received;
}
/**
Method used to check if the user is trying to update any other option for
the change master apart from the PRIVILEGE_CHECKS_USER.
In case user tries to update any other parameter apart from this one, this
method will return error.
@param lex_mi structure that holds all change master options given on
the change master command.
@retval true - The CHANGE MASTER is updating a unsupported parameter for the
recovery channel.
@retval false - Everything is fine. The CHANGE MASTER can execute with the
given option(s) for the recovery channel.
*/
static bool is_invalid_change_master_for_group_replication_applier(
const LEX_MASTER_INFO *lex_mi) {
DBUG_TRACE;
bool have_extra_option_received = false;
/* Check if *at least one* receive/execute option is given on change master
* command*/
if (lex_mi->host || lex_mi->user || lex_mi->password ||
lex_mi->log_file_name || lex_mi->pos || lex_mi->bind_addr ||
lex_mi->port || lex_mi->connect_retry || lex_mi->server_id ||
lex_mi->auto_position != LEX_MASTER_INFO::LEX_MI_UNCHANGED ||
lex_mi->ssl != LEX_MASTER_INFO::LEX_MI_UNCHANGED ||
lex_mi->ssl_verify_server_cert != LEX_MASTER_INFO::LEX_MI_UNCHANGED ||
lex_mi->heartbeat_opt != LEX_MASTER_INFO::LEX_MI_UNCHANGED ||
lex_mi->retry_count_opt != LEX_MASTER_INFO::LEX_MI_UNCHANGED ||
lex_mi->ssl_key || lex_mi->ssl_cert || lex_mi->ssl_ca ||
lex_mi->ssl_capath || lex_mi->tls_version || lex_mi->ssl_cipher ||
lex_mi->ssl_crl || lex_mi->ssl_crlpath ||
lex_mi->repl_ignore_server_ids_opt == LEX_MASTER_INFO::LEX_MI_ENABLE ||
lex_mi->relay_log_name || lex_mi->relay_log_pos ||
lex_mi->sql_delay != -1 || lex_mi->public_key_path ||
lex_mi->get_public_key != LEX_MASTER_INFO::LEX_MI_UNCHANGED ||
lex_mi->zstd_compression_level || lex_mi->compression_algorithm ||
lex_mi->require_row_format != LEX_MASTER_INFO::LEX_MI_UNCHANGED ||
lex_mi->m_source_connection_auto_failover !=
LEX_MASTER_INFO::LEX_MI_UNCHANGED ||
lex_mi->assign_gtids_to_anonymous_transactions_type !=
LEX_MASTER_INFO::LEX_MI_ANONYMOUS_TO_GTID_UNCHANGED ||
lex_mi->m_gtid_only != LEX_MASTER_INFO::LEX_MI_UNCHANGED)
have_extra_option_received = true;
return have_extra_option_received;
}
/**
Entry point for the CHANGE MASTER command. Function
decides to create a new channel or create an existing one.
@param[in] thd the client thread that issued the command.
@retval true fail
@retval false success.
*/
bool change_master_cmd(THD *thd) {
DBUG_TRACE;
Master_info *mi = nullptr;
LEX *lex = thd->lex;
bool res = false;
channel_map.wrlock();
/* The slave must have been initialized to allow CHANGE MASTER statements */
if (!is_slave_configured()) {
my_error(ER_REPLICA_CONFIGURATION, MYF(0));
res = true;
goto err;
}
if (channel_map.is_group_replication_channel_name(lex->mi.channel, true)) {
/*
If the chosen name is for group_replication_applier channel we allow the
channel creation based on the check as to which field is being updated.
*/
LEX_MASTER_INFO *lex_mi = &thd->lex->mi;
if (is_invalid_change_master_for_group_replication_applier(lex_mi)) {
my_error(ER_REPLICA_CHANNEL_OPERATION_NOT_ALLOWED, MYF(0),
"CHANGE REPLICATION SOURCE with the given parameters",
lex->mi.channel);
res = true;
goto err;
}
/*
group_replication_applier channel only has the SQL thread, the IO thread
job is done by GR pipeline, which queues events into the relay log after
going through certification.
Thence for CHANGE MASTER execution pre-conditions we need to check if
the full GR stack is stopped.
*/
if (is_group_replication_running()) {
my_error(ER_GRP_OPERATION_NOT_ALLOWED_GR_MUST_STOP, MYF(0));
res = true;
goto err;
}
}
// If the channel being used is group_replication_recovery we allow the
// channel creation based on the check as to which field is being updated.
if (channel_map.is_group_replication_channel_name(lex->mi.channel) &&
!channel_map.is_group_replication_channel_name(lex->mi.channel, true)) {
LEX_MASTER_INFO *lex_mi = &thd->lex->mi;
if (is_invalid_change_master_for_group_replication_recovery(lex_mi)) {
my_error(ER_REPLICA_CHANNEL_OPERATION_NOT_ALLOWED, MYF(0),
"CHANGE REPLICATION SOURCE with the given parameters",
lex->mi.channel);
res = true;
goto err;
}
}
/*
Error out if number of replication channels are > 1 if FOR CHANNEL
clause is not provided in the CHANGE MASTER command.
*/
if (!lex->mi.for_channel && channel_map.get_num_instances() > 1) {
my_error(ER_REPLICA_MULTIPLE_CHANNELS_CMD, MYF(0));
res = true;
goto err;
}
/* Get the Master_info of the channel */
mi = channel_map.get_mi(lex->mi.channel);
/* create a new channel if doesn't exist */
if (!mi && strcmp(lex->mi.channel, channel_map.get_default_channel())) {
/* The mi will be returned holding mi->channel_lock for writing */
if (add_new_channel(&mi, lex->mi.channel)) goto err;
}
if (mi) {
bool configure_filters = !Master_info::is_configured(mi);
if (!(res = change_master(thd, mi, &thd->lex->mi))) {
/*
If the channel was just created or not configured before this
"CHANGE REPLICATION SOURCE", we need to configure rpl_filter for it.
*/
if (configure_filters) {
if ((res = Rpl_info_factory::configure_channel_replication_filters(
mi->rli, lex->mi.channel)))
goto err;
}
/*
Issuing deprecation warnings after the change (we make
sure that we don't issue warning if there is an error).
*/
issue_deprecation_warnings_for_channel(thd);
my_ok(thd);
}
} else {
/*
Even default channel does not exist. So issue a previous
backward compatible error message (till 5.6).
@TODO: This error message shall be improved.
*/
my_error(ER_REPLICA_CONFIGURATION, MYF(0));
}
err:
channel_map.unlock();
return res;
}
/**
Check if there is any slave SQL config conflict.
@param[in] rli The slave's rli object.
@return 0 is returned if there is no conflict, otherwise 1 is returned.
*/
static int check_slave_sql_config_conflict(const Relay_log_info *rli) {
int channel_mts_submode, replica_parallel_workers;
if (rli) {
channel_mts_submode = rli->channel_mts_submode;
replica_parallel_workers = rli->opt_replica_parallel_workers;
} else {
/*
When the slave is first initialized, we collect the values from the
command line options
*/
channel_mts_submode = mts_parallel_option;
replica_parallel_workers = opt_mts_replica_parallel_workers;
}
if (opt_replica_preserve_commit_order && replica_parallel_workers > 0) {
if (channel_mts_submode == MTS_PARALLEL_TYPE_DB_NAME) {
my_error(ER_DONT_SUPPORT_REPLICA_PRESERVE_COMMIT_ORDER, MYF(0),
"when replica_parallel_type is DATABASE");
return ER_DONT_SUPPORT_REPLICA_PRESERVE_COMMIT_ORDER;
}
}
if (rli) {
const char *channel = const_cast<Relay_log_info *>(rli)->get_channel();
if (replica_parallel_workers > 0 &&
(channel_mts_submode != MTS_PARALLEL_TYPE_LOGICAL_CLOCK ||
(channel_mts_submode == MTS_PARALLEL_TYPE_LOGICAL_CLOCK &&
!opt_replica_preserve_commit_order)) &&
channel_map.is_group_replication_channel_name(channel, true)) {
my_error(ER_REPLICA_CHANNEL_OPERATION_NOT_ALLOWED, MYF(0),
"START REPLICA SQL_THREAD when REPLICA_PARALLEL_WORKERS > 0 "
"and REPLICA_PARALLEL_TYPE != LOGICAL_CLOCK "
"or REPLICA_PRESERVE_COMMIT_ORDER != ON",
channel);
return ER_REPLICA_CHANNEL_OPERATION_NOT_ALLOWED;
}
}
return 0;
}
/**
Purge Group Replication channels relay logs after this server being a
recipient of clone.
*/
static void group_replication_cleanup_after_clone() {
if (clone_startup && get_server_state() == SERVER_BOOTING) {
channel_map.assert_some_wrlock();
Auto_THD thd;
Master_info *mi = channel_map.get_mi("group_replication_applier");
if (nullptr != mi) reset_slave(thd.thd, mi, false);
mi = channel_map.get_mi("group_replication_recovery");
if (nullptr != mi) reset_slave(thd.thd, mi, false);
}
}
/**
@} (end of group Replication)
*/
/**
Checks the current replica configuration against the server GTID mode
If some incompatibility is found a warning is logged.
*/
static void check_replica_configuration_restrictions() {
std::string group_name = get_group_replication_group_name();
if (global_gtid_mode.get() != Gtid_mode::ON || group_name.length() > 0) {
for (auto it : channel_map) {
Master_info *mi = it.second;
if (mi != nullptr) {
if (global_gtid_mode.get() != Gtid_mode::ON) {
// Check if a channel has SOURCE_AUTO POSITION
if (global_gtid_mode.get() == Gtid_mode::OFF &&
mi->is_auto_position()) {
LogErr(WARNING_LEVEL,
ER_RPL_REPLICA_AUTO_POSITION_IS_1_AND_GTID_MODE_IS_OFF,
mi->get_channel(), mi->get_channel());
}
// Check if a channel has SOURCE_CONNECTION_AUTO_FAILOVER
if (mi->is_source_connection_auto_failover()) {
LogErr(WARNING_LEVEL, ER_RPL_ASYNC_RECONNECT_GTID_MODE_OFF_CHANNEL,
mi->get_channel(), mi->get_channel());
}
// Check if a channel has GTID_ONLY
if (mi->is_gtid_only_mode()) {
LogErr(WARNING_LEVEL,
ER_WARN_REPLICA_GTID_ONLY_AND_GTID_MODE_NOT_ON,
mi->get_channel());
}
// Check if a channel has ASSIGN_GTIDS_TO_ANONYMOUS_TRANSACTIONS
if (mi->rli->m_assign_gtids_to_anonymous_transactions_info
.get_type() > Assign_gtids_to_anonymous_transactions_info::
enum_type::AGAT_OFF) {
std::string assign_gtid_type;
if (mi->rli->m_assign_gtids_to_anonymous_transactions_info
.get_type() == Assign_gtids_to_anonymous_transactions_info::
enum_type::AGAT_LOCAL)
assign_gtid_type.assign("LOCAL");
else
assign_gtid_type.assign("a UUID");
LogErr(
WARNING_LEVEL,
ER_REPLICA_ANON_TO_GTID_IS_LOCAL_OR_UUID_AND_GTID_MODE_NOT_ON,
mi->get_channel(), assign_gtid_type.data(),
Gtid_mode::to_string(global_gtid_mode.get()));
}
} else {
// No checks needed if mode is OFF
if (mi->rli->m_assign_gtids_to_anonymous_transactions_info
.get_type() ==
Assign_gtids_to_anonymous_transactions_info::enum_type::AGAT_OFF)
continue;
/*
Check if one of the channels with
ASSIGN_GTIDS_TO_ANONYMOUS_TRANSACTIONS
does not have the same UUID as Group Replication
*/
if (!(group_name.compare(
mi->rli->m_assign_gtids_to_anonymous_transactions_info
.get_value()))) {
LogErr(WARNING_LEVEL,
ER_REPLICA_ANONYMOUS_TO_GTID_UUID_SAME_AS_GROUP_NAME,
mi->get_channel(),
mi->rli->m_assign_gtids_to_anonymous_transactions_info
.get_value()
.c_str());
}
/*
Check if one of the channels with
ASSIGN_GTIDS_TO_ANONYMOUS_TRANSACTIONS
does not have the same UUID as group_replication_view_change_uuid
*/
std::string view_change_uuid;
if (get_group_replication_view_change_uuid(view_change_uuid)) {
/* purecov: begin inspected */
LogErr(WARNING_LEVEL,
ER_WARN_GRP_RPL_VIEW_CHANGE_UUID_FAIL_GET_VARIABLE);
/* purecov: end */
}
if (!(view_change_uuid.compare(
mi->rli->m_assign_gtids_to_anonymous_transactions_info
.get_value()))) {
LogErr(
WARNING_LEVEL,
ER_WARN_REPLICA_ANONYMOUS_TO_GTID_UUID_SAME_AS_VIEW_CHANGE_UUID,
mi->get_channel(),
mi->rli->m_assign_gtids_to_anonymous_transactions_info
.get_value()
.c_str());
}
}
}
}
}
}
/**
Checks the current replica configuration when starting a replication thread
If some incompatibility is found an error is thrown.
@param mi pointer to the source info repository object
@param thread_mask what replication threads are running
@return true if an error occurs, false otherwise
*/
static bool check_replica_configuration_errors(Master_info *mi,
int thread_mask) {
if (global_gtid_mode.get() != Gtid_mode::ON) {
if (mi->is_auto_position() && (thread_mask & SLAVE_IO) &&
global_gtid_mode.get() == Gtid_mode::OFF) {
my_error(ER_CANT_USE_AUTO_POSITION_WITH_GTID_MODE_OFF, MYF(0),
mi->get_for_channel_str());
return true;
}
if (mi->is_source_connection_auto_failover()) {
my_error(ER_RPL_ASYNC_RECONNECT_GTID_MODE_OFF, MYF(0));
return true;
}
if (mi->is_gtid_only_mode()) {
my_error(ER_CANT_USE_GTID_ONLY_WITH_GTID_MODE_NOT_ON, MYF(0),
mi->get_for_channel_str());
return true;
}
if ((mi->rli->m_assign_gtids_to_anonymous_transactions_info.get_type() >
Assign_gtids_to_anonymous_transactions_info::enum_type::AGAT_OFF)) {
/*
This function may be called either during server start (when
--skip-start-replica is not used) or during START SLAVE. The error
should only be generated during START SLAVE. During server start, an
error has already been written to the log for this case (in
init_replica).
*/
if (current_thd)
my_error(ER_CANT_USE_ANONYMOUS_TO_GTID_WITH_GTID_MODE_NOT_ON, MYF(0),
mi->get_for_channel_str());
return true;
}
}
if (mi->rli->m_assign_gtids_to_anonymous_transactions_info.get_type() >
Assign_gtids_to_anonymous_transactions_info::enum_type::AGAT_OFF) {
std::string group_name = get_group_replication_group_name();
if ((group_name.length() > 0) &&
!(group_name.compare(
mi->rli->m_assign_gtids_to_anonymous_transactions_info
.get_value()))) {
my_error(ER_ANONYMOUS_TO_GTID_UUID_SAME_AS_GROUP_NAME, MYF(0),
mi->get_channel());
return true;
}
std::string view_change_uuid;
if (get_group_replication_view_change_uuid(view_change_uuid)) {
/* purecov: begin inspected */
my_error(ER_GRP_RPL_VIEW_CHANGE_UUID_FAIL_GET_VARIABLE, MYF(0));
return true;
/* purecov: end */
} else {
if (!(view_change_uuid.compare(
mi->rli->m_assign_gtids_to_anonymous_transactions_info
.get_value()))) {
my_error(ER_ANONYMOUS_TO_GTID_UUID_SAME_AS_VIEW_CHANGE_UUID, MYF(0),
mi->get_channel());
return true;
}
}
if (mi->rli->until_condition == Relay_log_info::UNTIL_SQL_BEFORE_GTIDS ||
mi->rli->until_condition == Relay_log_info::UNTIL_SQL_AFTER_GTIDS) {
my_error(ER_CANT_SET_SQL_AFTER_OR_BEFORE_GTIDS_WITH_ANONYMOUS_TO_GTID,
MYF(0));
return true;
}
}
return false;
}
|