/usr/bin/pt-table-sync is in percona-toolkit 2.1.2-1.
This file is owned by root:root, with mode 0o755.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 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 | #!/usr/bin/env perl
# This program is part of Percona Toolkit: http://www.percona.com/software/
# See "COPYRIGHT, LICENSE, AND WARRANTY" at the end of this file for legal
# notices and disclaimers.
use strict;
use warnings FATAL => 'all';
use constant PTDEBUG => $ENV{PTDEBUG} || 0;
# ###########################################################################
# OptionParser package
# This package is a copy without comments from the original. The original
# with comments and its test file can be found in the Bazaar repository at,
# lib/OptionParser.pm
# t/lib/OptionParser.t
# See https://launchpad.net/percona-toolkit for more information.
# ###########################################################################
{
package OptionParser;
use strict;
use warnings FATAL => 'all';
use English qw(-no_match_vars);
use constant PTDEBUG => $ENV{PTDEBUG} || 0;
use List::Util qw(max);
use Getopt::Long;
my $POD_link_re = '[LC]<"?([^">]+)"?>';
sub new {
my ( $class, %args ) = @_;
my @required_args = qw();
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my ($program_name) = $PROGRAM_NAME =~ m/([.A-Za-z-]+)$/;
$program_name ||= $PROGRAM_NAME;
my $home = $ENV{HOME} || $ENV{HOMEPATH} || $ENV{USERPROFILE} || '.';
my %attributes = (
'type' => 1,
'short form' => 1,
'group' => 1,
'default' => 1,
'cumulative' => 1,
'negatable' => 1,
);
my $self = {
head1 => 'OPTIONS', # These args are used internally
skip_rules => 0, # to instantiate another Option-
item => '--(.*)', # Parser obj that parses the
attributes => \%attributes, # DSN OPTIONS section. Tools
parse_attributes => \&_parse_attribs, # don't tinker with these args.
%args,
strict => 1, # disabled by a special rule
program_name => $program_name,
opts => {},
got_opts => 0,
short_opts => {},
defaults => {},
groups => {},
allowed_groups => {},
errors => [],
rules => [], # desc of rules for --help
mutex => [], # rule: opts are mutually exclusive
atleast1 => [], # rule: at least one opt is required
disables => {}, # rule: opt disables other opts
defaults_to => {}, # rule: opt defaults to value of other opt
DSNParser => undef,
default_files => [
"/etc/percona-toolkit/percona-toolkit.conf",
"/etc/percona-toolkit/$program_name.conf",
"$home/.percona-toolkit.conf",
"$home/.$program_name.conf",
],
types => {
string => 's', # standard Getopt type
int => 'i', # standard Getopt type
float => 'f', # standard Getopt type
Hash => 'H', # hash, formed from a comma-separated list
hash => 'h', # hash as above, but only if a value is given
Array => 'A', # array, similar to Hash
array => 'a', # array, similar to hash
DSN => 'd', # DSN
size => 'z', # size with kMG suffix (powers of 2^10)
time => 'm', # time, with an optional suffix of s/h/m/d
},
};
return bless $self, $class;
}
sub get_specs {
my ( $self, $file ) = @_;
$file ||= $self->{file} || __FILE__;
my @specs = $self->_pod_to_specs($file);
$self->_parse_specs(@specs);
open my $fh, "<", $file or die "Cannot open $file: $OS_ERROR";
my $contents = do { local $/ = undef; <$fh> };
close $fh;
if ( $contents =~ m/^=head1 DSN OPTIONS/m ) {
PTDEBUG && _d('Parsing DSN OPTIONS');
my $dsn_attribs = {
dsn => 1,
copy => 1,
};
my $parse_dsn_attribs = sub {
my ( $self, $option, $attribs ) = @_;
map {
my $val = $attribs->{$_};
if ( $val ) {
$val = $val eq 'yes' ? 1
: $val eq 'no' ? 0
: $val;
$attribs->{$_} = $val;
}
} keys %$attribs;
return {
key => $option,
%$attribs,
};
};
my $dsn_o = new OptionParser(
description => 'DSN OPTIONS',
head1 => 'DSN OPTIONS',
dsn => 0, # XXX don't infinitely recurse!
item => '\* (.)', # key opts are a single character
skip_rules => 1, # no rules before opts
attributes => $dsn_attribs,
parse_attributes => $parse_dsn_attribs,
);
my @dsn_opts = map {
my $opts = {
key => $_->{spec}->{key},
dsn => $_->{spec}->{dsn},
copy => $_->{spec}->{copy},
desc => $_->{desc},
};
$opts;
} $dsn_o->_pod_to_specs($file);
$self->{DSNParser} = DSNParser->new(opts => \@dsn_opts);
}
if ( $contents =~ m/^=head1 VERSION\n\n^(.+)$/m ) {
$self->{version} = $1;
PTDEBUG && _d($self->{version});
}
return;
}
sub DSNParser {
my ( $self ) = @_;
return $self->{DSNParser};
};
sub get_defaults_files {
my ( $self ) = @_;
return @{$self->{default_files}};
}
sub _pod_to_specs {
my ( $self, $file ) = @_;
$file ||= $self->{file} || __FILE__;
open my $fh, '<', $file or die "Cannot open $file: $OS_ERROR";
my @specs = ();
my @rules = ();
my $para;
local $INPUT_RECORD_SEPARATOR = '';
while ( $para = <$fh> ) {
next unless $para =~ m/^=head1 $self->{head1}/;
last;
}
while ( $para = <$fh> ) {
last if $para =~ m/^=over/;
next if $self->{skip_rules};
chomp $para;
$para =~ s/\s+/ /g;
$para =~ s/$POD_link_re/$1/go;
PTDEBUG && _d('Option rule:', $para);
push @rules, $para;
}
die "POD has no $self->{head1} section" unless $para;
do {
if ( my ($option) = $para =~ m/^=item $self->{item}/ ) {
chomp $para;
PTDEBUG && _d($para);
my %attribs;
$para = <$fh>; # read next paragraph, possibly attributes
if ( $para =~ m/: / ) { # attributes
$para =~ s/\s+\Z//g;
%attribs = map {
my ( $attrib, $val) = split(/: /, $_);
die "Unrecognized attribute for --$option: $attrib"
unless $self->{attributes}->{$attrib};
($attrib, $val);
} split(/; /, $para);
if ( $attribs{'short form'} ) {
$attribs{'short form'} =~ s/-//;
}
$para = <$fh>; # read next paragraph, probably short help desc
}
else {
PTDEBUG && _d('Option has no attributes');
}
$para =~ s/\s+\Z//g;
$para =~ s/\s+/ /g;
$para =~ s/$POD_link_re/$1/go;
$para =~ s/\.(?:\n.*| [A-Z].*|\Z)//s;
PTDEBUG && _d('Short help:', $para);
die "No description after option spec $option" if $para =~ m/^=item/;
if ( my ($base_option) = $option =~ m/^\[no\](.*)/ ) {
$option = $base_option;
$attribs{'negatable'} = 1;
}
push @specs, {
spec => $self->{parse_attributes}->($self, $option, \%attribs),
desc => $para
. (defined $attribs{default} ? " (default $attribs{default})" : ''),
group => ($attribs{'group'} ? $attribs{'group'} : 'default'),
};
}
while ( $para = <$fh> ) {
last unless $para;
if ( $para =~ m/^=head1/ ) {
$para = undef; # Can't 'last' out of a do {} block.
last;
}
last if $para =~ m/^=item /;
}
} while ( $para );
die "No valid specs in $self->{head1}" unless @specs;
close $fh;
return @specs, @rules;
}
sub _parse_specs {
my ( $self, @specs ) = @_;
my %disables; # special rule that requires deferred checking
foreach my $opt ( @specs ) {
if ( ref $opt ) { # It's an option spec, not a rule.
PTDEBUG && _d('Parsing opt spec:',
map { ($_, '=>', $opt->{$_}) } keys %$opt);
my ( $long, $short ) = $opt->{spec} =~ m/^([\w-]+)(?:\|([^!+=]*))?/;
if ( !$long ) {
die "Cannot parse long option from spec $opt->{spec}";
}
$opt->{long} = $long;
die "Duplicate long option --$long" if exists $self->{opts}->{$long};
$self->{opts}->{$long} = $opt;
if ( length $long == 1 ) {
PTDEBUG && _d('Long opt', $long, 'looks like short opt');
$self->{short_opts}->{$long} = $long;
}
if ( $short ) {
die "Duplicate short option -$short"
if exists $self->{short_opts}->{$short};
$self->{short_opts}->{$short} = $long;
$opt->{short} = $short;
}
else {
$opt->{short} = undef;
}
$opt->{is_negatable} = $opt->{spec} =~ m/!/ ? 1 : 0;
$opt->{is_cumulative} = $opt->{spec} =~ m/\+/ ? 1 : 0;
$opt->{is_required} = $opt->{desc} =~ m/required/ ? 1 : 0;
$opt->{group} ||= 'default';
$self->{groups}->{ $opt->{group} }->{$long} = 1;
$opt->{value} = undef;
$opt->{got} = 0;
my ( $type ) = $opt->{spec} =~ m/=(.)/;
$opt->{type} = $type;
PTDEBUG && _d($long, 'type:', $type);
$opt->{spec} =~ s/=./=s/ if ( $type && $type =~ m/[HhAadzm]/ );
if ( (my ($def) = $opt->{desc} =~ m/default\b(?: ([^)]+))?/) ) {
$self->{defaults}->{$long} = defined $def ? $def : 1;
PTDEBUG && _d($long, 'default:', $def);
}
if ( $long eq 'config' ) {
$self->{defaults}->{$long} = join(',', $self->get_defaults_files());
}
if ( (my ($dis) = $opt->{desc} =~ m/(disables .*)/) ) {
$disables{$long} = $dis;
PTDEBUG && _d('Deferring check of disables rule for', $opt, $dis);
}
$self->{opts}->{$long} = $opt;
}
else { # It's an option rule, not a spec.
PTDEBUG && _d('Parsing rule:', $opt);
push @{$self->{rules}}, $opt;
my @participants = $self->_get_participants($opt);
my $rule_ok = 0;
if ( $opt =~ m/mutually exclusive|one and only one/ ) {
$rule_ok = 1;
push @{$self->{mutex}}, \@participants;
PTDEBUG && _d(@participants, 'are mutually exclusive');
}
if ( $opt =~ m/at least one|one and only one/ ) {
$rule_ok = 1;
push @{$self->{atleast1}}, \@participants;
PTDEBUG && _d(@participants, 'require at least one');
}
if ( $opt =~ m/default to/ ) {
$rule_ok = 1;
$self->{defaults_to}->{$participants[0]} = $participants[1];
PTDEBUG && _d($participants[0], 'defaults to', $participants[1]);
}
if ( $opt =~ m/restricted to option groups/ ) {
$rule_ok = 1;
my ($groups) = $opt =~ m/groups ([\w\s\,]+)/;
my @groups = split(',', $groups);
%{$self->{allowed_groups}->{$participants[0]}} = map {
s/\s+//;
$_ => 1;
} @groups;
}
if( $opt =~ m/accepts additional command-line arguments/ ) {
$rule_ok = 1;
$self->{strict} = 0;
PTDEBUG && _d("Strict mode disabled by rule");
}
die "Unrecognized option rule: $opt" unless $rule_ok;
}
}
foreach my $long ( keys %disables ) {
my @participants = $self->_get_participants($disables{$long});
$self->{disables}->{$long} = \@participants;
PTDEBUG && _d('Option', $long, 'disables', @participants);
}
return;
}
sub _get_participants {
my ( $self, $str ) = @_;
my @participants;
foreach my $long ( $str =~ m/--(?:\[no\])?([\w-]+)/g ) {
die "Option --$long does not exist while processing rule $str"
unless exists $self->{opts}->{$long};
push @participants, $long;
}
PTDEBUG && _d('Participants for', $str, ':', @participants);
return @participants;
}
sub opts {
my ( $self ) = @_;
my %opts = %{$self->{opts}};
return %opts;
}
sub short_opts {
my ( $self ) = @_;
my %short_opts = %{$self->{short_opts}};
return %short_opts;
}
sub set_defaults {
my ( $self, %defaults ) = @_;
$self->{defaults} = {};
foreach my $long ( keys %defaults ) {
die "Cannot set default for nonexistent option $long"
unless exists $self->{opts}->{$long};
$self->{defaults}->{$long} = $defaults{$long};
PTDEBUG && _d('Default val for', $long, ':', $defaults{$long});
}
return;
}
sub get_defaults {
my ( $self ) = @_;
return $self->{defaults};
}
sub get_groups {
my ( $self ) = @_;
return $self->{groups};
}
sub _set_option {
my ( $self, $opt, $val ) = @_;
my $long = exists $self->{opts}->{$opt} ? $opt
: exists $self->{short_opts}->{$opt} ? $self->{short_opts}->{$opt}
: die "Getopt::Long gave a nonexistent option: $opt";
$opt = $self->{opts}->{$long};
if ( $opt->{is_cumulative} ) {
$opt->{value}++;
}
else {
$opt->{value} = $val;
}
$opt->{got} = 1;
PTDEBUG && _d('Got option', $long, '=', $val);
}
sub get_opts {
my ( $self ) = @_;
foreach my $long ( keys %{$self->{opts}} ) {
$self->{opts}->{$long}->{got} = 0;
$self->{opts}->{$long}->{value}
= exists $self->{defaults}->{$long} ? $self->{defaults}->{$long}
: $self->{opts}->{$long}->{is_cumulative} ? 0
: undef;
}
$self->{got_opts} = 0;
$self->{errors} = [];
if ( @ARGV && $ARGV[0] eq "--config" ) {
shift @ARGV;
$self->_set_option('config', shift @ARGV);
}
if ( $self->has('config') ) {
my @extra_args;
foreach my $filename ( split(',', $self->get('config')) ) {
eval {
push @extra_args, $self->_read_config_file($filename);
};
if ( $EVAL_ERROR ) {
if ( $self->got('config') ) {
die $EVAL_ERROR;
}
elsif ( PTDEBUG ) {
_d($EVAL_ERROR);
}
}
}
unshift @ARGV, @extra_args;
}
Getopt::Long::Configure('no_ignore_case', 'bundling');
GetOptions(
map { $_->{spec} => sub { $self->_set_option(@_); } }
grep { $_->{long} ne 'config' } # --config is handled specially above.
values %{$self->{opts}}
) or $self->save_error('Error parsing options');
if ( exists $self->{opts}->{version} && $self->{opts}->{version}->{got} ) {
if ( $self->{version} ) {
print $self->{version}, "\n";
}
else {
print "Error parsing version. See the VERSION section of the tool's documentation.\n";
}
exit 0;
}
if ( @ARGV && $self->{strict} ) {
$self->save_error("Unrecognized command-line options @ARGV");
}
foreach my $mutex ( @{$self->{mutex}} ) {
my @set = grep { $self->{opts}->{$_}->{got} } @$mutex;
if ( @set > 1 ) {
my $err = join(', ', map { "--$self->{opts}->{$_}->{long}" }
@{$mutex}[ 0 .. scalar(@$mutex) - 2] )
. ' and --'.$self->{opts}->{$mutex->[-1]}->{long}
. ' are mutually exclusive.';
$self->save_error($err);
}
}
foreach my $required ( @{$self->{atleast1}} ) {
my @set = grep { $self->{opts}->{$_}->{got} } @$required;
if ( @set == 0 ) {
my $err = join(', ', map { "--$self->{opts}->{$_}->{long}" }
@{$required}[ 0 .. scalar(@$required) - 2] )
.' or --'.$self->{opts}->{$required->[-1]}->{long};
$self->save_error("Specify at least one of $err");
}
}
$self->_check_opts( keys %{$self->{opts}} );
$self->{got_opts} = 1;
return;
}
sub _check_opts {
my ( $self, @long ) = @_;
my $long_last = scalar @long;
while ( @long ) {
foreach my $i ( 0..$#long ) {
my $long = $long[$i];
next unless $long;
my $opt = $self->{opts}->{$long};
if ( $opt->{got} ) {
if ( exists $self->{disables}->{$long} ) {
my @disable_opts = @{$self->{disables}->{$long}};
map { $self->{opts}->{$_}->{value} = undef; } @disable_opts;
PTDEBUG && _d('Unset options', @disable_opts,
'because', $long,'disables them');
}
if ( exists $self->{allowed_groups}->{$long} ) {
my @restricted_groups = grep {
!exists $self->{allowed_groups}->{$long}->{$_}
} keys %{$self->{groups}};
my @restricted_opts;
foreach my $restricted_group ( @restricted_groups ) {
RESTRICTED_OPT:
foreach my $restricted_opt (
keys %{$self->{groups}->{$restricted_group}} )
{
next RESTRICTED_OPT if $restricted_opt eq $long;
push @restricted_opts, $restricted_opt
if $self->{opts}->{$restricted_opt}->{got};
}
}
if ( @restricted_opts ) {
my $err;
if ( @restricted_opts == 1 ) {
$err = "--$restricted_opts[0]";
}
else {
$err = join(', ',
map { "--$self->{opts}->{$_}->{long}" }
grep { $_ }
@restricted_opts[0..scalar(@restricted_opts) - 2]
)
. ' or --'.$self->{opts}->{$restricted_opts[-1]}->{long};
}
$self->save_error("--$long is not allowed with $err");
}
}
}
elsif ( $opt->{is_required} ) {
$self->save_error("Required option --$long must be specified");
}
$self->_validate_type($opt);
if ( $opt->{parsed} ) {
delete $long[$i];
}
else {
PTDEBUG && _d('Temporarily failed to parse', $long);
}
}
die "Failed to parse options, possibly due to circular dependencies"
if @long == $long_last;
$long_last = @long;
}
return;
}
sub _validate_type {
my ( $self, $opt ) = @_;
return unless $opt;
if ( !$opt->{type} ) {
$opt->{parsed} = 1;
return;
}
my $val = $opt->{value};
if ( $val && $opt->{type} eq 'm' ) { # type time
PTDEBUG && _d('Parsing option', $opt->{long}, 'as a time value');
my ( $prefix, $num, $suffix ) = $val =~ m/([+-]?)(\d+)([a-z])?$/;
if ( !$suffix ) {
my ( $s ) = $opt->{desc} =~ m/\(suffix (.)\)/;
$suffix = $s || 's';
PTDEBUG && _d('No suffix given; using', $suffix, 'for',
$opt->{long}, '(value:', $val, ')');
}
if ( $suffix =~ m/[smhd]/ ) {
$val = $suffix eq 's' ? $num # Seconds
: $suffix eq 'm' ? $num * 60 # Minutes
: $suffix eq 'h' ? $num * 3600 # Hours
: $num * 86400; # Days
$opt->{value} = ($prefix || '') . $val;
PTDEBUG && _d('Setting option', $opt->{long}, 'to', $val);
}
else {
$self->save_error("Invalid time suffix for --$opt->{long}");
}
}
elsif ( $val && $opt->{type} eq 'd' ) { # type DSN
PTDEBUG && _d('Parsing option', $opt->{long}, 'as a DSN');
my $prev = {};
my $from_key = $self->{defaults_to}->{ $opt->{long} };
if ( $from_key ) {
PTDEBUG && _d($opt->{long}, 'DSN copies from', $from_key, 'DSN');
if ( $self->{opts}->{$from_key}->{parsed} ) {
$prev = $self->{opts}->{$from_key}->{value};
}
else {
PTDEBUG && _d('Cannot parse', $opt->{long}, 'until',
$from_key, 'parsed');
return;
}
}
my $defaults = $self->{DSNParser}->parse_options($self);
$opt->{value} = $self->{DSNParser}->parse($val, $prev, $defaults);
}
elsif ( $val && $opt->{type} eq 'z' ) { # type size
PTDEBUG && _d('Parsing option', $opt->{long}, 'as a size value');
$self->_parse_size($opt, $val);
}
elsif ( $opt->{type} eq 'H' || (defined $val && $opt->{type} eq 'h') ) {
$opt->{value} = { map { $_ => 1 } split(/(?<!\\),\s*/, ($val || '')) };
}
elsif ( $opt->{type} eq 'A' || (defined $val && $opt->{type} eq 'a') ) {
$opt->{value} = [ split(/(?<!\\),\s*/, ($val || '')) ];
}
else {
PTDEBUG && _d('Nothing to validate for option',
$opt->{long}, 'type', $opt->{type}, 'value', $val);
}
$opt->{parsed} = 1;
return;
}
sub get {
my ( $self, $opt ) = @_;
my $long = (length $opt == 1 ? $self->{short_opts}->{$opt} : $opt);
die "Option $opt does not exist"
unless $long && exists $self->{opts}->{$long};
return $self->{opts}->{$long}->{value};
}
sub got {
my ( $self, $opt ) = @_;
my $long = (length $opt == 1 ? $self->{short_opts}->{$opt} : $opt);
die "Option $opt does not exist"
unless $long && exists $self->{opts}->{$long};
return $self->{opts}->{$long}->{got};
}
sub has {
my ( $self, $opt ) = @_;
my $long = (length $opt == 1 ? $self->{short_opts}->{$opt} : $opt);
return defined $long ? exists $self->{opts}->{$long} : 0;
}
sub set {
my ( $self, $opt, $val ) = @_;
my $long = (length $opt == 1 ? $self->{short_opts}->{$opt} : $opt);
die "Option $opt does not exist"
unless $long && exists $self->{opts}->{$long};
$self->{opts}->{$long}->{value} = $val;
return;
}
sub save_error {
my ( $self, $error ) = @_;
push @{$self->{errors}}, $error;
return;
}
sub errors {
my ( $self ) = @_;
return $self->{errors};
}
sub usage {
my ( $self ) = @_;
warn "No usage string is set" unless $self->{usage}; # XXX
return "Usage: " . ($self->{usage} || '') . "\n";
}
sub descr {
my ( $self ) = @_;
warn "No description string is set" unless $self->{description}; # XXX
my $descr = ($self->{description} || $self->{program_name} || '')
. " For more details, please use the --help option, "
. "or try 'perldoc $PROGRAM_NAME' "
. "for complete documentation.";
$descr = join("\n", $descr =~ m/(.{0,80})(?:\s+|$)/g)
unless $ENV{DONT_BREAK_LINES};
$descr =~ s/ +$//mg;
return $descr;
}
sub usage_or_errors {
my ( $self, $file, $return ) = @_;
$file ||= $self->{file} || __FILE__;
if ( !$self->{description} || !$self->{usage} ) {
PTDEBUG && _d("Getting description and usage from SYNOPSIS in", $file);
my %synop = $self->_parse_synopsis($file);
$self->{description} ||= $synop{description};
$self->{usage} ||= $synop{usage};
PTDEBUG && _d("Description:", $self->{description},
"\nUsage:", $self->{usage});
}
if ( $self->{opts}->{help}->{got} ) {
print $self->print_usage() or die "Cannot print usage: $OS_ERROR";
exit 0 unless $return;
}
elsif ( scalar @{$self->{errors}} ) {
print $self->print_errors() or die "Cannot print errors: $OS_ERROR";
exit 0 unless $return;
}
return;
}
sub print_errors {
my ( $self ) = @_;
my $usage = $self->usage() . "\n";
if ( (my @errors = @{$self->{errors}}) ) {
$usage .= join("\n * ", 'Errors in command-line arguments:', @errors)
. "\n";
}
return $usage . "\n" . $self->descr();
}
sub print_usage {
my ( $self ) = @_;
die "Run get_opts() before print_usage()" unless $self->{got_opts};
my @opts = values %{$self->{opts}};
my $maxl = max(
map {
length($_->{long}) # option long name
+ ($_->{is_negatable} ? 4 : 0) # "[no]" if opt is negatable
+ ($_->{type} ? 2 : 0) # "=x" where x is the opt type
}
@opts);
my $maxs = max(0,
map {
length($_)
+ ($self->{opts}->{$_}->{is_negatable} ? 4 : 0)
+ ($self->{opts}->{$_}->{type} ? 2 : 0)
}
values %{$self->{short_opts}});
my $lcol = max($maxl, ($maxs + 3));
my $rcol = 80 - $lcol - 6;
my $rpad = ' ' x ( 80 - $rcol );
$maxs = max($lcol - 3, $maxs);
my $usage = $self->descr() . "\n" . $self->usage();
my @groups = reverse sort grep { $_ ne 'default'; } keys %{$self->{groups}};
push @groups, 'default';
foreach my $group ( reverse @groups ) {
$usage .= "\n".($group eq 'default' ? 'Options' : $group).":\n\n";
foreach my $opt (
sort { $a->{long} cmp $b->{long} }
grep { $_->{group} eq $group }
@opts )
{
my $long = $opt->{is_negatable} ? "[no]$opt->{long}" : $opt->{long};
my $short = $opt->{short};
my $desc = $opt->{desc};
$long .= $opt->{type} ? "=$opt->{type}" : "";
if ( $opt->{type} && $opt->{type} eq 'm' ) {
my ($s) = $desc =~ m/\(suffix (.)\)/;
$s ||= 's';
$desc =~ s/\s+\(suffix .\)//;
$desc .= ". Optional suffix s=seconds, m=minutes, h=hours, "
. "d=days; if no suffix, $s is used.";
}
$desc = join("\n$rpad", grep { $_ } $desc =~ m/(.{0,$rcol})(?:\s+|$)/g);
$desc =~ s/ +$//mg;
if ( $short ) {
$usage .= sprintf(" --%-${maxs}s -%s %s\n", $long, $short, $desc);
}
else {
$usage .= sprintf(" --%-${lcol}s %s\n", $long, $desc);
}
}
}
$usage .= "\nOption types: s=string, i=integer, f=float, h/H/a/A=comma-separated list, d=DSN, z=size, m=time\n";
if ( (my @rules = @{$self->{rules}}) ) {
$usage .= "\nRules:\n\n";
$usage .= join("\n", map { " $_" } @rules) . "\n";
}
if ( $self->{DSNParser} ) {
$usage .= "\n" . $self->{DSNParser}->usage();
}
$usage .= "\nOptions and values after processing arguments:\n\n";
foreach my $opt ( sort { $a->{long} cmp $b->{long} } @opts ) {
my $val = $opt->{value};
my $type = $opt->{type} || '';
my $bool = $opt->{spec} =~ m/^[\w-]+(?:\|[\w-])?!?$/;
$val = $bool ? ( $val ? 'TRUE' : 'FALSE' )
: !defined $val ? '(No value)'
: $type eq 'd' ? $self->{DSNParser}->as_string($val)
: $type =~ m/H|h/ ? join(',', sort keys %$val)
: $type =~ m/A|a/ ? join(',', @$val)
: $val;
$usage .= sprintf(" --%-${lcol}s %s\n", $opt->{long}, $val);
}
return $usage;
}
sub prompt_noecho {
shift @_ if ref $_[0] eq __PACKAGE__;
my ( $prompt ) = @_;
local $OUTPUT_AUTOFLUSH = 1;
print $prompt
or die "Cannot print: $OS_ERROR";
my $response;
eval {
require Term::ReadKey;
Term::ReadKey::ReadMode('noecho');
chomp($response = <STDIN>);
Term::ReadKey::ReadMode('normal');
print "\n"
or die "Cannot print: $OS_ERROR";
};
if ( $EVAL_ERROR ) {
die "Cannot read response; is Term::ReadKey installed? $EVAL_ERROR";
}
return $response;
}
sub _read_config_file {
my ( $self, $filename ) = @_;
open my $fh, "<", $filename or die "Cannot open $filename: $OS_ERROR\n";
my @args;
my $prefix = '--';
my $parse = 1;
LINE:
while ( my $line = <$fh> ) {
chomp $line;
next LINE if $line =~ m/^\s*(?:\#|\;|$)/;
$line =~ s/\s+#.*$//g;
$line =~ s/^\s+|\s+$//g;
if ( $line eq '--' ) {
$prefix = '';
$parse = 0;
next LINE;
}
if ( $parse
&& (my($opt, $arg) = $line =~ m/^\s*([^=\s]+?)(?:\s*=\s*(.*?)\s*)?$/)
) {
push @args, grep { defined $_ } ("$prefix$opt", $arg);
}
elsif ( $line =~ m/./ ) {
push @args, $line;
}
else {
die "Syntax error in file $filename at line $INPUT_LINE_NUMBER";
}
}
close $fh;
return @args;
}
sub read_para_after {
my ( $self, $file, $regex ) = @_;
open my $fh, "<", $file or die "Can't open $file: $OS_ERROR";
local $INPUT_RECORD_SEPARATOR = '';
my $para;
while ( $para = <$fh> ) {
next unless $para =~ m/^=pod$/m;
last;
}
while ( $para = <$fh> ) {
next unless $para =~ m/$regex/;
last;
}
$para = <$fh>;
chomp($para);
close $fh or die "Can't close $file: $OS_ERROR";
return $para;
}
sub clone {
my ( $self ) = @_;
my %clone = map {
my $hashref = $self->{$_};
my $val_copy = {};
foreach my $key ( keys %$hashref ) {
my $ref = ref $hashref->{$key};
$val_copy->{$key} = !$ref ? $hashref->{$key}
: $ref eq 'HASH' ? { %{$hashref->{$key}} }
: $ref eq 'ARRAY' ? [ @{$hashref->{$key}} ]
: $hashref->{$key};
}
$_ => $val_copy;
} qw(opts short_opts defaults);
foreach my $scalar ( qw(got_opts) ) {
$clone{$scalar} = $self->{$scalar};
}
return bless \%clone;
}
sub _parse_size {
my ( $self, $opt, $val ) = @_;
if ( lc($val || '') eq 'null' ) {
PTDEBUG && _d('NULL size for', $opt->{long});
$opt->{value} = 'null';
return;
}
my %factor_for = (k => 1_024, M => 1_048_576, G => 1_073_741_824);
my ($pre, $num, $factor) = $val =~ m/^([+-])?(\d+)([kMG])?$/;
if ( defined $num ) {
if ( $factor ) {
$num *= $factor_for{$factor};
PTDEBUG && _d('Setting option', $opt->{y},
'to num', $num, '* factor', $factor);
}
$opt->{value} = ($pre || '') . $num;
}
else {
$self->save_error("Invalid size for --$opt->{long}: $val");
}
return;
}
sub _parse_attribs {
my ( $self, $option, $attribs ) = @_;
my $types = $self->{types};
return $option
. ($attribs->{'short form'} ? '|' . $attribs->{'short form'} : '' )
. ($attribs->{'negatable'} ? '!' : '' )
. ($attribs->{'cumulative'} ? '+' : '' )
. ($attribs->{'type'} ? '=' . $types->{$attribs->{type}} : '' );
}
sub _parse_synopsis {
my ( $self, $file ) = @_;
$file ||= $self->{file} || __FILE__;
PTDEBUG && _d("Parsing SYNOPSIS in", $file);
local $INPUT_RECORD_SEPARATOR = ''; # read paragraphs
open my $fh, "<", $file or die "Cannot open $file: $OS_ERROR";
my $para;
1 while defined($para = <$fh>) && $para !~ m/^=head1 SYNOPSIS/;
die "$file does not contain a SYNOPSIS section" unless $para;
my @synop;
for ( 1..2 ) { # 1 for the usage, 2 for the description
my $para = <$fh>;
push @synop, $para;
}
close $fh;
PTDEBUG && _d("Raw SYNOPSIS text:", @synop);
my ($usage, $desc) = @synop;
die "The SYNOPSIS section in $file is not formatted properly"
unless $usage && $desc;
$usage =~ s/^\s*Usage:\s+(.+)/$1/;
chomp $usage;
$desc =~ s/\n/ /g;
$desc =~ s/\s{2,}/ /g;
$desc =~ s/\. ([A-Z][a-z])/. $1/g;
$desc =~ s/\s+$//;
return (
description => $desc,
usage => $usage,
);
};
sub _d {
my ($package, undef, $line) = caller 0;
@_ = map { (my $temp = $_) =~ s/\n/\n# /g; $temp; }
map { defined $_ ? $_ : 'undef' }
@_;
print STDERR "# $package:$line $PID ", join(' ', @_), "\n";
}
if ( PTDEBUG ) {
print '# ', $^X, ' ', $], "\n";
if ( my $uname = `uname -a` ) {
$uname =~ s/\s+/ /g;
print "# $uname\n";
}
print '# Arguments: ',
join(' ', map { my $a = "_[$_]_"; $a =~ s/\n/\n# /g; $a; } @ARGV), "\n";
}
1;
}
# ###########################################################################
# End OptionParser package
# ###########################################################################
# ###########################################################################
# Quoter package
# This package is a copy without comments from the original. The original
# with comments and its test file can be found in the Bazaar repository at,
# lib/Quoter.pm
# t/lib/Quoter.t
# See https://launchpad.net/percona-toolkit for more information.
# ###########################################################################
{
package Quoter;
use strict;
use warnings FATAL => 'all';
use English qw(-no_match_vars);
use constant PTDEBUG => $ENV{PTDEBUG} || 0;
sub new {
my ( $class, %args ) = @_;
return bless {}, $class;
}
sub quote {
my ( $self, @vals ) = @_;
foreach my $val ( @vals ) {
$val =~ s/`/``/g;
}
return join('.', map { '`' . $_ . '`' } @vals);
}
sub quote_val {
my ( $self, $val ) = @_;
return 'NULL' unless defined $val; # undef = NULL
return "''" if $val eq ''; # blank string = ''
return $val if $val =~ m/^0x[0-9a-fA-F]+$/; # hex data
$val =~ s/(['\\])/\\$1/g;
return "'$val'";
}
sub split_unquote {
my ( $self, $db_tbl, $default_db ) = @_;
$db_tbl =~ s/`//g;
my ( $db, $tbl ) = split(/[.]/, $db_tbl);
if ( !$tbl ) {
$tbl = $db;
$db = $default_db;
}
return ($db, $tbl);
}
sub literal_like {
my ( $self, $like ) = @_;
return unless $like;
$like =~ s/([%_])/\\$1/g;
return "'$like'";
}
sub join_quote {
my ( $self, $default_db, $db_tbl ) = @_;
return unless $db_tbl;
my ($db, $tbl) = split(/[.]/, $db_tbl);
if ( !$tbl ) {
$tbl = $db;
$db = $default_db;
}
$db = "`$db`" if $db && $db !~ m/^`/;
$tbl = "`$tbl`" if $tbl && $tbl !~ m/^`/;
return $db ? "$db.$tbl" : $tbl;
}
sub serialize_list {
my ( $self, @args ) = @_;
return unless @args;
return $args[0] if @args == 1 && !defined $args[0];
die "Cannot serialize multiple values with undef/NULL"
if grep { !defined $_ } @args;
return join ',', map { quotemeta } @args;
}
sub deserialize_list {
my ( $self, $string ) = @_;
return $string unless defined $string;
my @escaped_parts = $string =~ /
\G # Start of string, or end of previous match.
( # Each of these is an element in the original list.
[^\\,]* # Anything not a backslash or a comma
(?: # When we get here, we found one of the above.
\\. # A backslash followed by something so we can continue
[^\\,]* # Same as above.
)* # Repeat zero of more times.
)
, # Comma dividing elements
/sxgc;
push @escaped_parts, pos($string) ? substr( $string, pos($string) ) : $string;
my @unescaped_parts = map {
my $part = $_;
my $char_class = utf8::is_utf8($part) # If it's a UTF-8 string,
? qr/(?=\p{ASCII})\W/ # We only care about non-word
: qr/(?=\p{ASCII})\W|[\x{80}-\x{FF}]/; # Otherwise,
$part =~ s/\\($char_class)/$1/g;
$part;
} @escaped_parts;
return @unescaped_parts;
}
1;
}
# ###########################################################################
# End Quoter package
# ###########################################################################
# ###########################################################################
# DSNParser package
# This package is a copy without comments from the original. The original
# with comments and its test file can be found in the Bazaar repository at,
# lib/DSNParser.pm
# t/lib/DSNParser.t
# See https://launchpad.net/percona-toolkit for more information.
# ###########################################################################
{
package DSNParser;
use strict;
use warnings FATAL => 'all';
use English qw(-no_match_vars);
use constant PTDEBUG => $ENV{PTDEBUG} || 0;
use Data::Dumper;
$Data::Dumper::Indent = 0;
$Data::Dumper::Quotekeys = 0;
my $dsn_sep = qr/(?<!\\),/;
eval {
require DBI;
};
my $have_dbi = $EVAL_ERROR ? 0 : 1;
sub new {
my ( $class, %args ) = @_;
foreach my $arg ( qw(opts) ) {
die "I need a $arg argument" unless $args{$arg};
}
my $self = {
opts => {} # h, P, u, etc. Should come from DSN OPTIONS section in POD.
};
foreach my $opt ( @{$args{opts}} ) {
if ( !$opt->{key} || !$opt->{desc} ) {
die "Invalid DSN option: ", Dumper($opt);
}
PTDEBUG && _d('DSN option:',
join(', ',
map { "$_=" . (defined $opt->{$_} ? ($opt->{$_} || '') : 'undef') }
keys %$opt
)
);
$self->{opts}->{$opt->{key}} = {
dsn => $opt->{dsn},
desc => $opt->{desc},
copy => $opt->{copy} || 0,
};
}
return bless $self, $class;
}
sub prop {
my ( $self, $prop, $value ) = @_;
if ( @_ > 2 ) {
PTDEBUG && _d('Setting', $prop, 'property');
$self->{$prop} = $value;
}
return $self->{$prop};
}
sub parse {
my ( $self, $dsn, $prev, $defaults ) = @_;
if ( !$dsn ) {
PTDEBUG && _d('No DSN to parse');
return;
}
PTDEBUG && _d('Parsing', $dsn);
$prev ||= {};
$defaults ||= {};
my %given_props;
my %final_props;
my $opts = $self->{opts};
foreach my $dsn_part ( split($dsn_sep, $dsn) ) {
$dsn_part =~ s/\\,/,/g;
if ( my ($prop_key, $prop_val) = $dsn_part =~ m/^(.)=(.*)$/ ) {
$given_props{$prop_key} = $prop_val;
}
else {
PTDEBUG && _d('Interpreting', $dsn_part, 'as h=', $dsn_part);
$given_props{h} = $dsn_part;
}
}
foreach my $key ( keys %$opts ) {
PTDEBUG && _d('Finding value for', $key);
$final_props{$key} = $given_props{$key};
if ( !defined $final_props{$key}
&& defined $prev->{$key} && $opts->{$key}->{copy} )
{
$final_props{$key} = $prev->{$key};
PTDEBUG && _d('Copying value for', $key, 'from previous DSN');
}
if ( !defined $final_props{$key} ) {
$final_props{$key} = $defaults->{$key};
PTDEBUG && _d('Copying value for', $key, 'from defaults');
}
}
foreach my $key ( keys %given_props ) {
die "Unknown DSN option '$key' in '$dsn'. For more details, "
. "please use the --help option, or try 'perldoc $PROGRAM_NAME' "
. "for complete documentation."
unless exists $opts->{$key};
}
if ( (my $required = $self->prop('required')) ) {
foreach my $key ( keys %$required ) {
die "Missing required DSN option '$key' in '$dsn'. For more details, "
. "please use the --help option, or try 'perldoc $PROGRAM_NAME' "
. "for complete documentation."
unless $final_props{$key};
}
}
return \%final_props;
}
sub parse_options {
my ( $self, $o ) = @_;
die 'I need an OptionParser object' unless ref $o eq 'OptionParser';
my $dsn_string
= join(',',
map { "$_=".$o->get($_); }
grep { $o->has($_) && $o->get($_) }
keys %{$self->{opts}}
);
PTDEBUG && _d('DSN string made from options:', $dsn_string);
return $self->parse($dsn_string);
}
sub as_string {
my ( $self, $dsn, $props ) = @_;
return $dsn unless ref $dsn;
my @keys = $props ? @$props : sort keys %$dsn;
return join(',',
map { "$_=" . ($_ eq 'p' ? '...' : $dsn->{$_}) }
grep {
exists $self->{opts}->{$_}
&& exists $dsn->{$_}
&& defined $dsn->{$_}
} @keys);
}
sub usage {
my ( $self ) = @_;
my $usage
= "DSN syntax is key=value[,key=value...] Allowable DSN keys:\n\n"
. " KEY COPY MEANING\n"
. " === ==== =============================================\n";
my %opts = %{$self->{opts}};
foreach my $key ( sort keys %opts ) {
$usage .= " $key "
. ($opts{$key}->{copy} ? 'yes ' : 'no ')
. ($opts{$key}->{desc} || '[No description]')
. "\n";
}
$usage .= "\n If the DSN is a bareword, the word is treated as the 'h' key.\n";
return $usage;
}
sub get_cxn_params {
my ( $self, $info ) = @_;
my $dsn;
my %opts = %{$self->{opts}};
my $driver = $self->prop('dbidriver') || '';
if ( $driver eq 'Pg' ) {
$dsn = 'DBI:Pg:dbname=' . ( $info->{D} || '' ) . ';'
. join(';', map { "$opts{$_}->{dsn}=$info->{$_}" }
grep { defined $info->{$_} }
qw(h P));
}
else {
$dsn = 'DBI:mysql:' . ( $info->{D} || '' ) . ';'
. join(';', map { "$opts{$_}->{dsn}=$info->{$_}" }
grep { defined $info->{$_} }
qw(F h P S A))
. ';mysql_read_default_group=client';
}
PTDEBUG && _d($dsn);
return ($dsn, $info->{u}, $info->{p});
}
sub fill_in_dsn {
my ( $self, $dbh, $dsn ) = @_;
my $vars = $dbh->selectall_hashref('SHOW VARIABLES', 'Variable_name');
my ($user, $db) = $dbh->selectrow_array('SELECT USER(), DATABASE()');
$user =~ s/@.*//;
$dsn->{h} ||= $vars->{hostname}->{Value};
$dsn->{S} ||= $vars->{'socket'}->{Value};
$dsn->{P} ||= $vars->{port}->{Value};
$dsn->{u} ||= $user;
$dsn->{D} ||= $db;
}
sub get_dbh {
my ( $self, $cxn_string, $user, $pass, $opts ) = @_;
$opts ||= {};
my $defaults = {
AutoCommit => 0,
RaiseError => 1,
PrintError => 0,
ShowErrorStatement => 1,
mysql_enable_utf8 => ($cxn_string =~ m/charset=utf8/i ? 1 : 0),
};
@{$defaults}{ keys %$opts } = values %$opts;
if ( $opts->{mysql_use_result} ) {
$defaults->{mysql_use_result} = 1;
}
if ( !$have_dbi ) {
die "Cannot connect to MySQL because the Perl DBI module is not "
. "installed or not found. Run 'perl -MDBI' to see the directories "
. "that Perl searches for DBI. If DBI is not installed, try:\n"
. " Debian/Ubuntu apt-get install libdbi-perl\n"
. " RHEL/CentOS yum install perl-DBI\n"
. " OpenSolaris pgk install pkg:/SUNWpmdbi\n";
}
my $dbh;
my $tries = 2;
while ( !$dbh && $tries-- ) {
PTDEBUG && _d($cxn_string, ' ', $user, ' ', $pass,
join(', ', map { "$_=>$defaults->{$_}" } keys %$defaults ));
eval {
$dbh = DBI->connect($cxn_string, $user, $pass, $defaults);
if ( $cxn_string =~ m/mysql/i ) {
my $sql;
$sql = 'SELECT @@SQL_MODE';
PTDEBUG && _d($dbh, $sql);
my ($sql_mode) = $dbh->selectrow_array($sql);
$sql = 'SET @@SQL_QUOTE_SHOW_CREATE = 1'
. '/*!40101, @@SQL_MODE=\'NO_AUTO_VALUE_ON_ZERO'
. ($sql_mode ? ",$sql_mode" : '')
. '\'*/';
PTDEBUG && _d($dbh, $sql);
$dbh->do($sql);
if ( my ($charset) = $cxn_string =~ m/charset=(\w+)/ ) {
$sql = "/*!40101 SET NAMES $charset*/";
PTDEBUG && _d($dbh, ':', $sql);
$dbh->do($sql);
PTDEBUG && _d('Enabling charset for STDOUT');
if ( $charset eq 'utf8' ) {
binmode(STDOUT, ':utf8')
or die "Can't binmode(STDOUT, ':utf8'): $OS_ERROR";
}
else {
binmode(STDOUT) or die "Can't binmode(STDOUT): $OS_ERROR";
}
}
if ( $self->prop('set-vars') ) {
$sql = "SET " . $self->prop('set-vars');
PTDEBUG && _d($dbh, ':', $sql);
$dbh->do($sql);
}
}
};
if ( !$dbh && $EVAL_ERROR ) {
PTDEBUG && _d($EVAL_ERROR);
if ( $EVAL_ERROR =~ m/not a compiled character set|character set utf8/ ) {
PTDEBUG && _d('Going to try again without utf8 support');
delete $defaults->{mysql_enable_utf8};
}
elsif ( $EVAL_ERROR =~ m/locate DBD\/mysql/i ) {
die "Cannot connect to MySQL because the Perl DBD::mysql module is "
. "not installed or not found. Run 'perl -MDBD::mysql' to see "
. "the directories that Perl searches for DBD::mysql. If "
. "DBD::mysql is not installed, try:\n"
. " Debian/Ubuntu apt-get install libdbd-mysql-perl\n"
. " RHEL/CentOS yum install perl-DBD-MySQL\n"
. " OpenSolaris pgk install pkg:/SUNWapu13dbd-mysql\n";
}
if ( !$tries ) {
die $EVAL_ERROR;
}
}
}
PTDEBUG && _d('DBH info: ',
$dbh,
Dumper($dbh->selectrow_hashref(
'SELECT DATABASE(), CONNECTION_ID(), VERSION()/*!50038 , @@hostname*/')),
'Connection info:', $dbh->{mysql_hostinfo},
'Character set info:', Dumper($dbh->selectall_arrayref(
"SHOW VARIABLES LIKE 'character_set%'", { Slice => {}})),
'$DBD::mysql::VERSION:', $DBD::mysql::VERSION,
'$DBI::VERSION:', $DBI::VERSION,
);
return $dbh;
}
sub get_hostname {
my ( $self, $dbh ) = @_;
if ( my ($host) = ($dbh->{mysql_hostinfo} || '') =~ m/^(\w+) via/ ) {
return $host;
}
my ( $hostname, $one ) = $dbh->selectrow_array(
'SELECT /*!50038 @@hostname, */ 1');
return $hostname;
}
sub disconnect {
my ( $self, $dbh ) = @_;
PTDEBUG && $self->print_active_handles($dbh);
$dbh->disconnect;
}
sub print_active_handles {
my ( $self, $thing, $level ) = @_;
$level ||= 0;
printf("# Active %sh: %s %s %s\n", ($thing->{Type} || 'undef'), "\t" x $level,
$thing, (($thing->{Type} || '') eq 'st' ? $thing->{Statement} || '' : ''))
or die "Cannot print: $OS_ERROR";
foreach my $handle ( grep {defined} @{ $thing->{ChildHandles} } ) {
$self->print_active_handles( $handle, $level + 1 );
}
}
sub copy {
my ( $self, $dsn_1, $dsn_2, %args ) = @_;
die 'I need a dsn_1 argument' unless $dsn_1;
die 'I need a dsn_2 argument' unless $dsn_2;
my %new_dsn = map {
my $key = $_;
my $val;
if ( $args{overwrite} ) {
$val = defined $dsn_1->{$key} ? $dsn_1->{$key} : $dsn_2->{$key};
}
else {
$val = defined $dsn_2->{$key} ? $dsn_2->{$key} : $dsn_1->{$key};
}
$key => $val;
} keys %{$self->{opts}};
return \%new_dsn;
}
sub _d {
my ($package, undef, $line) = caller 0;
@_ = map { (my $temp = $_) =~ s/\n/\n# /g; $temp; }
map { defined $_ ? $_ : 'undef' }
@_;
print STDERR "# $package:$line $PID ", join(' ', @_), "\n";
}
1;
}
# ###########################################################################
# End DSNParser package
# ###########################################################################
# ###########################################################################
# VersionParser package
# This package is a copy without comments from the original. The original
# with comments and its test file can be found in the Bazaar repository at,
# lib/VersionParser.pm
# t/lib/VersionParser.t
# See https://launchpad.net/percona-toolkit for more information.
# ###########################################################################
{
package VersionParser;
use strict;
use warnings FATAL => 'all';
use English qw(-no_match_vars);
use constant PTDEBUG => $ENV{PTDEBUG} || 0;
sub new {
my ( $class ) = @_;
bless {}, $class;
}
sub parse {
my ( $self, $str ) = @_;
my @version_parts = $str =~ m/(\d+)/g;
@version_parts = map { $_ || 0 } @version_parts[0..2];
my $result = sprintf('%03d%03d%03d', @version_parts);
PTDEBUG && _d($str, 'parses to', $result);
return $result;
}
sub version_cmp {
my ($self, $dbh, $target, $cmp) = @_;
my $version = $self->version($dbh);
my $result;
if ( $cmp eq 'ge' ) {
$result = $self->{$dbh} ge $self->parse($target) ? 1 : 0;
}
elsif ( $cmp eq 'gt' ) {
$result = $self->{$dbh} gt $self->parse($target) ? 1 : 0;
}
elsif ( $cmp eq 'eq' ) {
$result = $self->{$dbh} eq $self->parse($target) ? 1 : 0;
}
elsif ( $cmp eq 'ne' ) {
$result = $self->{$dbh} ne $self->parse($target) ? 1 : 0;
}
elsif ( $cmp eq 'lt' ) {
$result = $self->{$dbh} lt $self->parse($target) ? 1 : 0;
}
elsif ( $cmp eq 'le' ) {
$result = $self->{$dbh} le $self->parse($target) ? 1 : 0;
}
else {
die "Asked for an unknown comparizon: $cmp"
}
PTDEBUG && _d($self->{$dbh}, $cmp, $target, ':', $result);
return $result;
}
sub version_ge {
my ( $self, $dbh, $target ) = @_;
return $self->version_cmp($dbh, $target, 'ge');
}
sub version_gt {
my ( $self, $dbh, $target ) = @_;
return $self->version_cmp($dbh, $target, 'gt');
}
sub version_eq {
my ( $self, $dbh, $target ) = @_;
return $self->version_cmp($dbh, $target, 'eq');
}
sub version_ne {
my ( $self, $dbh, $target ) = @_;
return $self->version_cmp($dbh, $target, 'ne');
}
sub version_lt {
my ( $self, $dbh, $target ) = @_;
return $self->version_cmp($dbh, $target, 'lt');
}
sub version_le {
my ( $self, $dbh, $target ) = @_;
return $self->version_cmp($dbh, $target, 'le');
}
sub version {
my ( $self, $dbh ) = @_;
if ( !$self->{$dbh} ) {
$self->{$dbh} = $self->parse(
$dbh->selectrow_array('SELECT VERSION()'));
}
return $self->{$dbh};
}
sub innodb_version {
my ( $self, $dbh ) = @_;
return unless $dbh;
my $innodb_version = "NO";
my ($innodb) =
grep { $_->{engine} =~ m/InnoDB/i }
map {
my %hash;
@hash{ map { lc $_ } keys %$_ } = values %$_;
\%hash;
}
@{ $dbh->selectall_arrayref("SHOW ENGINES", {Slice=>{}}) };
if ( $innodb ) {
PTDEBUG && _d("InnoDB support:", $innodb->{support});
if ( $innodb->{support} =~ m/YES|DEFAULT/i ) {
my $vars = $dbh->selectrow_hashref(
"SHOW VARIABLES LIKE 'innodb_version'");
$innodb_version = !$vars ? "BUILTIN"
: ($vars->{Value} || $vars->{value});
}
else {
$innodb_version = $innodb->{support}; # probably DISABLED or NO
}
}
PTDEBUG && _d("InnoDB version:", $innodb_version);
return $innodb_version;
}
sub _d {
my ($package, undef, $line) = caller 0;
@_ = map { (my $temp = $_) =~ s/\n/\n# /g; $temp; }
map { defined $_ ? $_ : 'undef' }
@_;
print STDERR "# $package:$line $PID ", join(' ', @_), "\n";
}
1;
}
# ###########################################################################
# End VersionParser package
# ###########################################################################
# ###########################################################################
# TableSyncStream package
# This package is a copy without comments from the original. The original
# with comments and its test file can be found in the Bazaar repository at,
# lib/TableSyncStream.pm
# t/lib/TableSyncStream.t
# See https://launchpad.net/percona-toolkit for more information.
# ###########################################################################
{
package TableSyncStream;
use strict;
use warnings FATAL => 'all';
use English qw(-no_match_vars);
use constant PTDEBUG => $ENV{PTDEBUG} || 0;
sub new {
my ( $class, %args ) = @_;
foreach my $arg ( qw(Quoter) ) {
die "I need a $arg argument" unless $args{$arg};
}
my $self = { %args };
return bless $self, $class;
}
sub name {
return 'Stream';
}
sub can_sync {
return 1; # We can sync anything.
}
sub prepare_to_sync {
my ( $self, %args ) = @_;
my @required_args = qw(cols ChangeHandler);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
$self->{cols} = $args{cols};
$self->{buffer_in_mysql} = $args{buffer_in_mysql};
$self->{ChangeHandler} = $args{ChangeHandler};
$self->{done} = 0;
return;
}
sub uses_checksum {
return 0; # We don't need checksum queries.
}
sub set_checksum_queries {
return; # This shouldn't be called, but just in case.
}
sub prepare_sync_cycle {
my ( $self, $host ) = @_;
return;
}
sub get_sql {
my ( $self, %args ) = @_;
return "SELECT "
. ($self->{buffer_in_mysql} ? 'SQL_BUFFER_RESULT ' : '')
. join(', ', map { $self->{Quoter}->quote($_) } @{$self->{cols}})
. ' FROM ' . $self->{Quoter}->quote(@args{qw(database table)})
. ' WHERE ' . ( $args{where} || '1=1' );
}
sub same_row {
my ( $self, %args ) = @_;
return;
}
sub not_in_right {
my ( $self, %args ) = @_;
$self->{ChangeHandler}->change('INSERT', $args{lr}, $self->key_cols());
}
sub not_in_left {
my ( $self, %args ) = @_;
$self->{ChangeHandler}->change('DELETE', $args{rr}, $self->key_cols());
}
sub done_with_rows {
my ( $self ) = @_;
$self->{done} = 1;
}
sub done {
my ( $self ) = @_;
return $self->{done};
}
sub key_cols {
my ( $self ) = @_;
return $self->{cols};
}
sub pending_changes {
my ( $self ) = @_;
return;
}
sub _d {
my ($package, undef, $line) = caller 0;
@_ = map { (my $temp = $_) =~ s/\n/\n# /g; $temp; }
map { defined $_ ? $_ : 'undef' }
@_;
print STDERR "# $package:$line $PID ", join(' ', @_), "\n";
}
1;
}
# ###########################################################################
# End TableSyncStream package
# ###########################################################################
# ###########################################################################
# TableParser package
# This package is a copy without comments from the original. The original
# with comments and its test file can be found in the Bazaar repository at,
# lib/TableParser.pm
# t/lib/TableParser.t
# See https://launchpad.net/percona-toolkit for more information.
# ###########################################################################
{
package TableParser;
use strict;
use warnings FATAL => 'all';
use English qw(-no_match_vars);
use constant PTDEBUG => $ENV{PTDEBUG} || 0;
use Data::Dumper;
$Data::Dumper::Indent = 1;
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Quotekeys = 0;
sub new {
my ( $class, %args ) = @_;
my @required_args = qw(Quoter);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my $self = { %args };
return bless $self, $class;
}
sub get_create_table {
my ( $self, $dbh, $db, $tbl ) = @_;
die "I need a dbh parameter" unless $dbh;
die "I need a db parameter" unless $db;
die "I need a tbl parameter" unless $tbl;
my $q = $self->{Quoter};
my $new_sql_mode
= '/*!40101 SET @OLD_SQL_MODE := @@SQL_MODE, '
. q{@@SQL_MODE := REPLACE(REPLACE(@@SQL_MODE, 'ANSI_QUOTES', ''), ',,', ','), }
. '@OLD_QUOTE := @@SQL_QUOTE_SHOW_CREATE, '
. '@@SQL_QUOTE_SHOW_CREATE := 1 */';
my $old_sql_mode = '/*!40101 SET @@SQL_MODE := @OLD_SQL_MODE, '
. '@@SQL_QUOTE_SHOW_CREATE := @OLD_QUOTE */';
PTDEBUG && _d($new_sql_mode);
eval { $dbh->do($new_sql_mode); };
PTDEBUG && $EVAL_ERROR && _d($EVAL_ERROR);
my $use_sql = 'USE ' . $q->quote($db);
PTDEBUG && _d($dbh, $use_sql);
$dbh->do($use_sql);
my $show_sql = "SHOW CREATE TABLE " . $q->quote($db, $tbl);
PTDEBUG && _d($show_sql);
my $href;
eval { $href = $dbh->selectrow_hashref($show_sql); };
if ( $EVAL_ERROR ) {
PTDEBUG && _d($EVAL_ERROR);
PTDEBUG && _d($old_sql_mode);
$dbh->do($old_sql_mode);
return;
}
PTDEBUG && _d($old_sql_mode);
$dbh->do($old_sql_mode);
my ($key) = grep { m/create (?:table|view)/i } keys %$href;
if ( !$key ) {
die "Error: no 'Create Table' or 'Create View' in result set from "
. "$show_sql: " . Dumper($href);
}
return $href->{$key};
}
sub parse {
my ( $self, $ddl, $opts ) = @_;
return unless $ddl;
if ( $ddl =~ m/CREATE (?:TEMPORARY )?TABLE "/ ) {
$ddl = $self->ansi_to_legacy($ddl);
}
elsif ( $ddl !~ m/CREATE (?:TEMPORARY )?TABLE `/ ) {
die "TableParser doesn't handle CREATE TABLE without quoting.";
}
my ($name) = $ddl =~ m/CREATE (?:TEMPORARY )?TABLE\s+(`.+?`)/;
(undef, $name) = $self->{Quoter}->split_unquote($name) if $name;
$ddl =~ s/(`[^`]+`)/\L$1/g;
my $engine = $self->get_engine($ddl);
my @defs = $ddl =~ m/^(\s+`.*?),?$/gm;
my @cols = map { $_ =~ m/`([^`]+)`/ } @defs;
PTDEBUG && _d('Table cols:', join(', ', map { "`$_`" } @cols));
my %def_for;
@def_for{@cols} = @defs;
my (@nums, @null);
my (%type_for, %is_nullable, %is_numeric, %is_autoinc);
foreach my $col ( @cols ) {
my $def = $def_for{$col};
my ( $type ) = $def =~ m/`[^`]+`\s([a-z]+)/;
die "Can't determine column type for $def" unless $type;
$type_for{$col} = $type;
if ( $type =~ m/(?:(?:tiny|big|medium|small)?int|float|double|decimal|year)/ ) {
push @nums, $col;
$is_numeric{$col} = 1;
}
if ( $def !~ m/NOT NULL/ ) {
push @null, $col;
$is_nullable{$col} = 1;
}
$is_autoinc{$col} = $def =~ m/AUTO_INCREMENT/i ? 1 : 0;
}
my ($keys, $clustered_key) = $self->get_keys($ddl, $opts, \%is_nullable);
my ($charset) = $ddl =~ m/DEFAULT CHARSET=(\w+)/;
return {
name => $name,
cols => \@cols,
col_posn => { map { $cols[$_] => $_ } 0..$#cols },
is_col => { map { $_ => 1 } @cols },
null_cols => \@null,
is_nullable => \%is_nullable,
is_autoinc => \%is_autoinc,
clustered_key => $clustered_key,
keys => $keys,
defs => \%def_for,
numeric_cols => \@nums,
is_numeric => \%is_numeric,
engine => $engine,
type_for => \%type_for,
charset => $charset,
};
}
sub sort_indexes {
my ( $self, $tbl ) = @_;
my @indexes
= sort {
(($a ne 'PRIMARY') <=> ($b ne 'PRIMARY'))
|| ( !$tbl->{keys}->{$a}->{is_unique} <=> !$tbl->{keys}->{$b}->{is_unique} )
|| ( $tbl->{keys}->{$a}->{is_nullable} <=> $tbl->{keys}->{$b}->{is_nullable} )
|| ( scalar(@{$tbl->{keys}->{$a}->{cols}}) <=> scalar(@{$tbl->{keys}->{$b}->{cols}}) )
}
grep {
$tbl->{keys}->{$_}->{type} eq 'BTREE'
}
sort keys %{$tbl->{keys}};
PTDEBUG && _d('Indexes sorted best-first:', join(', ', @indexes));
return @indexes;
}
sub find_best_index {
my ( $self, $tbl, $index ) = @_;
my $best;
if ( $index ) {
($best) = grep { uc $_ eq uc $index } keys %{$tbl->{keys}};
}
if ( !$best ) {
if ( $index ) {
die "Index '$index' does not exist in table";
}
else {
($best) = $self->sort_indexes($tbl);
}
}
PTDEBUG && _d('Best index found is', $best);
return $best;
}
sub find_possible_keys {
my ( $self, $dbh, $database, $table, $quoter, $where ) = @_;
return () unless $where;
my $sql = 'EXPLAIN SELECT * FROM ' . $quoter->quote($database, $table)
. ' WHERE ' . $where;
PTDEBUG && _d($sql);
my $expl = $dbh->selectrow_hashref($sql);
$expl = { map { lc($_) => $expl->{$_} } keys %$expl };
if ( $expl->{possible_keys} ) {
PTDEBUG && _d('possible_keys =', $expl->{possible_keys});
my @candidates = split(',', $expl->{possible_keys});
my %possible = map { $_ => 1 } @candidates;
if ( $expl->{key} ) {
PTDEBUG && _d('MySQL chose', $expl->{key});
unshift @candidates, grep { $possible{$_} } split(',', $expl->{key});
PTDEBUG && _d('Before deduping:', join(', ', @candidates));
my %seen;
@candidates = grep { !$seen{$_}++ } @candidates;
}
PTDEBUG && _d('Final list:', join(', ', @candidates));
return @candidates;
}
else {
PTDEBUG && _d('No keys in possible_keys');
return ();
}
}
sub check_table {
my ( $self, %args ) = @_;
my @required_args = qw(dbh db tbl);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my ($dbh, $db, $tbl) = @args{@required_args};
my $q = $self->{Quoter};
my $db_tbl = $q->quote($db, $tbl);
PTDEBUG && _d('Checking', $db_tbl);
my $sql = "SHOW TABLES FROM " . $q->quote($db)
. ' LIKE ' . $q->literal_like($tbl);
PTDEBUG && _d($sql);
my $row;
eval {
$row = $dbh->selectrow_arrayref($sql);
};
if ( $EVAL_ERROR ) {
PTDEBUG && _d($EVAL_ERROR);
return 0;
}
if ( !$row->[0] || $row->[0] ne $tbl ) {
PTDEBUG && _d('Table does not exist');
return 0;
}
PTDEBUG && _d('Table exists; no privs to check');
return 1 unless $args{all_privs};
$sql = "SHOW FULL COLUMNS FROM $db_tbl";
PTDEBUG && _d($sql);
eval {
$row = $dbh->selectrow_hashref($sql);
};
if ( $EVAL_ERROR ) {
PTDEBUG && _d($EVAL_ERROR);
return 0;
}
if ( !scalar keys %$row ) {
PTDEBUG && _d('Table has no columns:', Dumper($row));
return 0;
}
my $privs = $row->{privileges} || $row->{Privileges};
$sql = "DELETE FROM $db_tbl LIMIT 0";
PTDEBUG && _d($sql);
eval {
$dbh->do($sql);
};
my $can_delete = $EVAL_ERROR ? 0 : 1;
PTDEBUG && _d('User privs on', $db_tbl, ':', $privs,
($can_delete ? 'delete' : ''));
if ( !($privs =~ m/select/ && $privs =~ m/insert/ && $privs =~ m/update/
&& $can_delete) ) {
PTDEBUG && _d('User does not have all privs');
return 0;
}
PTDEBUG && _d('User has all privs');
return 1;
}
sub get_engine {
my ( $self, $ddl, $opts ) = @_;
my ( $engine ) = $ddl =~ m/\).*?(?:ENGINE|TYPE)=(\w+)/;
PTDEBUG && _d('Storage engine:', $engine);
return $engine || undef;
}
sub get_keys {
my ( $self, $ddl, $opts, $is_nullable ) = @_;
my $engine = $self->get_engine($ddl);
my $keys = {};
my $clustered_key = undef;
KEY:
foreach my $key ( $ddl =~ m/^ ((?:[A-Z]+ )?KEY .*)$/gm ) {
next KEY if $key =~ m/FOREIGN/;
my $key_ddl = $key;
PTDEBUG && _d('Parsed key:', $key_ddl);
if ( !$engine || $engine !~ m/MEMORY|HEAP/ ) {
$key =~ s/USING HASH/USING BTREE/;
}
my ( $type, $cols ) = $key =~ m/(?:USING (\w+))? \((.+)\)/;
my ( $special ) = $key =~ m/(FULLTEXT|SPATIAL)/;
$type = $type || $special || 'BTREE';
if ( $opts->{mysql_version} && $opts->{mysql_version} lt '004001000'
&& $engine =~ m/HEAP|MEMORY/i )
{
$type = 'HASH'; # MySQL pre-4.1 supports only HASH indexes on HEAP
}
my ($name) = $key =~ m/(PRIMARY|`[^`]*`)/;
my $unique = $key =~ m/PRIMARY|UNIQUE/ ? 1 : 0;
my @cols;
my @col_prefixes;
foreach my $col_def ( $cols =~ m/`[^`]+`(?:\(\d+\))?/g ) {
my ($name, $prefix) = $col_def =~ m/`([^`]+)`(?:\((\d+)\))?/;
push @cols, $name;
push @col_prefixes, $prefix;
}
$name =~ s/`//g;
PTDEBUG && _d( $name, 'key cols:', join(', ', map { "`$_`" } @cols));
$keys->{$name} = {
name => $name,
type => $type,
colnames => $cols,
cols => \@cols,
col_prefixes => \@col_prefixes,
is_unique => $unique,
is_nullable => scalar(grep { $is_nullable->{$_} } @cols),
is_col => { map { $_ => 1 } @cols },
ddl => $key_ddl,
};
if ( ($engine || '') =~ m/InnoDB/i && !$clustered_key ) {
my $this_key = $keys->{$name};
if ( $this_key->{name} eq 'PRIMARY' ) {
$clustered_key = 'PRIMARY';
}
elsif ( $this_key->{is_unique} && !$this_key->{is_nullable} ) {
$clustered_key = $this_key->{name};
}
PTDEBUG && $clustered_key && _d('This key is the clustered key');
}
}
return $keys, $clustered_key;
}
sub get_fks {
my ( $self, $ddl, $opts ) = @_;
my $q = $self->{Quoter};
my $fks = {};
foreach my $fk (
$ddl =~ m/CONSTRAINT .* FOREIGN KEY .* REFERENCES [^\)]*\)/mg )
{
my ( $name ) = $fk =~ m/CONSTRAINT `(.*?)`/;
my ( $cols ) = $fk =~ m/FOREIGN KEY \(([^\)]+)\)/;
my ( $parent, $parent_cols ) = $fk =~ m/REFERENCES (\S+) \(([^\)]+)\)/;
my ($db, $tbl) = $q->split_unquote($parent, $opts->{database});
my %parent_tbl = (tbl => $tbl);
$parent_tbl{db} = $db if $db;
if ( $parent !~ m/\./ && $opts->{database} ) {
$parent = $q->quote($opts->{database}) . ".$parent";
}
$fks->{$name} = {
name => $name,
colnames => $cols,
cols => [ map { s/[ `]+//g; $_; } split(',', $cols) ],
parent_tbl => \%parent_tbl,
parent_tblname => $parent,
parent_cols => [ map { s/[ `]+//g; $_; } split(',', $parent_cols) ],
parent_colnames=> $parent_cols,
ddl => $fk,
};
}
return $fks;
}
sub remove_auto_increment {
my ( $self, $ddl ) = @_;
$ddl =~ s/(^\).*?) AUTO_INCREMENT=\d+\b/$1/m;
return $ddl;
}
sub get_table_status {
my ( $self, $dbh, $db, $like ) = @_;
my $q = $self->{Quoter};
my $sql = "SHOW TABLE STATUS FROM " . $q->quote($db);
my @params;
if ( $like ) {
$sql .= ' LIKE ?';
push @params, $like;
}
PTDEBUG && _d($sql, @params);
my $sth = $dbh->prepare($sql);
eval { $sth->execute(@params); };
if ($EVAL_ERROR) {
PTDEBUG && _d($EVAL_ERROR);
return;
}
my @tables = @{$sth->fetchall_arrayref({})};
@tables = map {
my %tbl; # Make a copy with lowercased keys
@tbl{ map { lc $_ } keys %$_ } = values %$_;
$tbl{engine} ||= $tbl{type} || $tbl{comment};
delete $tbl{type};
\%tbl;
} @tables;
return @tables;
}
my $ansi_quote_re = qr/" [^"]* (?: "" [^"]* )* (?<=.) "/ismx;
sub ansi_to_legacy {
my ($self, $ddl) = @_;
$ddl =~ s/($ansi_quote_re)/ansi_quote_replace($1)/ge;
return $ddl;
}
sub ansi_quote_replace {
my ($val) = @_;
$val =~ s/^"|"$//g;
$val =~ s/`/``/g;
$val =~ s/""/"/g;
return "`$val`";
}
sub _d {
my ($package, undef, $line) = caller 0;
@_ = map { (my $temp = $_) =~ s/\n/\n# /g; $temp; }
map { defined $_ ? $_ : 'undef' }
@_;
print STDERR "# $package:$line $PID ", join(' ', @_), "\n";
}
1;
}
# ###########################################################################
# End TableParser package
# ###########################################################################
# ###########################################################################
# RowDiff package
# This package is a copy without comments from the original. The original
# with comments and its test file can be found in the Bazaar repository at,
# lib/RowDiff.pm
# t/lib/RowDiff.t
# See https://launchpad.net/percona-toolkit for more information.
# ###########################################################################
{
package RowDiff;
use strict;
use warnings FATAL => 'all';
use English qw(-no_match_vars);
use constant PTDEBUG => $ENV{PTDEBUG} || 0;
sub new {
my ( $class, %args ) = @_;
die "I need a dbh" unless $args{dbh};
my $self = { %args };
return bless $self, $class;
}
sub compare_sets {
my ( $self, %args ) = @_;
my @required_args = qw(left_sth right_sth syncer tbl_struct);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless defined $args{$arg};
}
my $left_sth = $args{left_sth};
my $right_sth = $args{right_sth};
my $syncer = $args{syncer};
my $tbl_struct = $args{tbl_struct};
my ($lr, $rr); # Current row from the left/right sths.
$args{key_cols} = $syncer->key_cols(); # for key_cmp()
my $left_done = 0;
my $right_done = 0;
my $done = $self->{done};
do {
if ( !$lr && !$left_done ) {
PTDEBUG && _d('Fetching row from left');
eval { $lr = $left_sth->fetchrow_hashref(); };
PTDEBUG && $EVAL_ERROR && _d($EVAL_ERROR);
$left_done = !$lr || $EVAL_ERROR ? 1 : 0;
}
elsif ( PTDEBUG ) {
_d('Left still has rows');
}
if ( !$rr && !$right_done ) {
PTDEBUG && _d('Fetching row from right');
eval { $rr = $right_sth->fetchrow_hashref(); };
PTDEBUG && $EVAL_ERROR && _d($EVAL_ERROR);
$right_done = !$rr || $EVAL_ERROR ? 1 : 0;
}
elsif ( PTDEBUG ) {
_d('Right still has rows');
}
my $cmp;
if ( $lr && $rr ) {
$cmp = $self->key_cmp(%args, lr => $lr, rr => $rr);
PTDEBUG && _d('Key comparison on left and right:', $cmp);
}
if ( $lr || $rr ) {
if ( $lr && $rr && defined $cmp && $cmp == 0 ) {
PTDEBUG && _d('Left and right have the same key');
$syncer->same_row(%args, lr => $lr, rr => $rr);
$self->{same_row}->(%args, lr => $lr, rr => $rr)
if $self->{same_row};
$lr = $rr = undef; # Fetch another row from each side.
}
elsif ( !$rr || ( defined $cmp && $cmp < 0 ) ) {
PTDEBUG && _d('Left is not in right');
$syncer->not_in_right(%args, lr => $lr, rr => $rr);
$self->{not_in_right}->(%args, lr => $lr, rr => $rr)
if $self->{not_in_right};
$lr = undef;
}
else {
PTDEBUG && _d('Right is not in left');
$syncer->not_in_left(%args, lr => $lr, rr => $rr);
$self->{not_in_left}->(%args, lr => $lr, rr => $rr)
if $self->{not_in_left};
$rr = undef;
}
}
$left_done = $right_done = 1 if $done && $done->(%args);
} while ( !($left_done && $right_done) );
PTDEBUG && _d('No more rows');
$syncer->done_with_rows();
}
sub key_cmp {
my ( $self, %args ) = @_;
my @required_args = qw(lr rr key_cols tbl_struct);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless exists $args{$arg};
}
my ($lr, $rr, $key_cols, $tbl_struct) = @args{@required_args};
PTDEBUG && _d('Comparing keys using columns:', join(',', @$key_cols));
my $callback = $self->{key_cmp};
my $trf = $self->{trf};
foreach my $col ( @$key_cols ) {
my $l = $lr->{$col};
my $r = $rr->{$col};
if ( !defined $l || !defined $r ) {
PTDEBUG && _d($col, 'is not defined in both rows');
return defined $l ? 1 : defined $r ? -1 : 0;
}
else {
if ( $tbl_struct->{is_numeric}->{$col} ) { # Numeric column
PTDEBUG && _d($col, 'is numeric');
($l, $r) = $trf->($l, $r, $tbl_struct, $col) if $trf;
my $cmp = $l <=> $r;
if ( $cmp ) {
PTDEBUG && _d('Column', $col, 'differs:', $l, '!=', $r);
$callback->($col, $l, $r) if $callback;
return $cmp;
}
}
elsif ( $l ne $r ) {
my $cmp;
my $coll = $tbl_struct->{collation_for}->{$col};
if ( $coll && ( $coll ne 'latin1_swedish_ci'
|| $l =~ m/[^\040-\177]/ || $r =~ m/[^\040-\177]/) )
{
PTDEBUG && _d('Comparing', $col, 'via MySQL');
$cmp = $self->db_cmp($coll, $l, $r);
}
else {
PTDEBUG && _d('Comparing', $col, 'in lowercase');
$cmp = lc $l cmp lc $r;
}
if ( $cmp ) {
PTDEBUG && _d('Column', $col, 'differs:', $l, 'ne', $r);
$callback->($col, $l, $r) if $callback;
return $cmp;
}
}
}
}
return 0;
}
sub db_cmp {
my ( $self, $collation, $l, $r ) = @_;
if ( !$self->{sth}->{$collation} ) {
if ( !$self->{charset_for} ) {
PTDEBUG && _d('Fetching collations from MySQL');
my @collations = @{$self->{dbh}->selectall_arrayref(
'SHOW COLLATION', {Slice => { collation => 1, charset => 1 }})};
foreach my $collation ( @collations ) {
$self->{charset_for}->{$collation->{collation}}
= $collation->{charset};
}
}
my $sql = "SELECT STRCMP(_$self->{charset_for}->{$collation}? COLLATE $collation, "
. "_$self->{charset_for}->{$collation}? COLLATE $collation) AS res";
PTDEBUG && _d($sql);
$self->{sth}->{$collation} = $self->{dbh}->prepare($sql);
}
my $sth = $self->{sth}->{$collation};
$sth->execute($l, $r);
return $sth->fetchall_arrayref()->[0]->[0];
}
sub _d {
my ($package, undef, $line) = caller 0;
@_ = map { (my $temp = $_) =~ s/\n/\n# /g; $temp; }
map { defined $_ ? $_ : 'undef' }
@_;
print STDERR "# $package:$line $PID ", join(' ', @_), "\n";
}
1;
}
# ###########################################################################
# End RowDiff package
# ###########################################################################
# ###########################################################################
# MySQLDump package
# This package is a copy without comments from the original. The original
# with comments and its test file can be found in the Bazaar repository at,
# lib/MySQLDump.pm
# t/lib/MySQLDump.t
# See https://launchpad.net/percona-toolkit for more information.
# ###########################################################################
{
package MySQLDump;
use strict;
use warnings FATAL => 'all';
use English qw(-no_match_vars);
use constant PTDEBUG => $ENV{PTDEBUG} || 0;
( our $before = <<'EOF') =~ s/^ //gm;
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
EOF
( our $after = <<'EOF') =~ s/^ //gm;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
EOF
sub new {
my ( $class, %args ) = @_;
my $self = {
cache => 0, # Afaik no script uses this cache any longer because
};
return bless $self, $class;
}
sub dump {
my ( $self, $dbh, $quoter, $db, $tbl, $what ) = @_;
if ( $what eq 'table' ) {
my $ddl = $self->get_create_table($dbh, $quoter, $db, $tbl);
return unless $ddl;
if ( $ddl->[0] eq 'table' ) {
return $before
. 'DROP TABLE IF EXISTS ' . $quoter->quote($tbl) . ";\n"
. $ddl->[1] . ";\n";
}
else {
return 'DROP TABLE IF EXISTS ' . $quoter->quote($tbl) . ";\n"
. '/*!50001 DROP VIEW IF EXISTS '
. $quoter->quote($tbl) . "*/;\n/*!50001 "
. $self->get_tmp_table($dbh, $quoter, $db, $tbl) . "*/;\n";
}
}
elsif ( $what eq 'triggers' ) {
my $trgs = $self->get_triggers($dbh, $quoter, $db, $tbl);
if ( $trgs && @$trgs ) {
my $result = $before . "\nDELIMITER ;;\n";
foreach my $trg ( @$trgs ) {
if ( $trg->{sql_mode} ) {
$result .= qq{/*!50003 SET SESSION SQL_MODE='$trg->{sql_mode}' */;;\n};
}
$result .= "/*!50003 CREATE */ ";
if ( $trg->{definer} ) {
my ( $user, $host )
= map { s/'/''/g; "'$_'"; }
split('@', $trg->{definer}, 2);
$result .= "/*!50017 DEFINER=$user\@$host */ ";
}
$result .= sprintf("/*!50003 TRIGGER %s %s %s ON %s\nFOR EACH ROW %s */;;\n\n",
$quoter->quote($trg->{trigger}),
@{$trg}{qw(timing event)},
$quoter->quote($trg->{table}),
$trg->{statement});
}
$result .= "DELIMITER ;\n\n/*!50003 SET SESSION SQL_MODE=\@OLD_SQL_MODE */;\n\n";
return $result;
}
else {
return undef;
}
}
elsif ( $what eq 'view' ) {
my $ddl = $self->get_create_table($dbh, $quoter, $db, $tbl);
return '/*!50001 DROP TABLE IF EXISTS ' . $quoter->quote($tbl) . "*/;\n"
. '/*!50001 DROP VIEW IF EXISTS ' . $quoter->quote($tbl) . "*/;\n"
. '/*!50001 ' . $ddl->[1] . "*/;\n";
}
else {
die "You didn't say what to dump.";
}
}
sub _use_db {
my ( $self, $dbh, $quoter, $new ) = @_;
if ( !$new ) {
PTDEBUG && _d('No new DB to use');
return;
}
my $sql = 'USE ' . $quoter->quote($new);
PTDEBUG && _d($dbh, $sql);
$dbh->do($sql);
return;
}
sub get_create_table {
my ( $self, $dbh, $quoter, $db, $tbl ) = @_;
if ( !$self->{cache} || !$self->{tables}->{$db}->{$tbl} ) {
my $sql = '/*!40101 SET @OLD_SQL_MODE := @@SQL_MODE, '
. q{@@SQL_MODE := REPLACE(REPLACE(@@SQL_MODE, 'ANSI_QUOTES', ''), ',,', ','), }
. '@OLD_QUOTE := @@SQL_QUOTE_SHOW_CREATE, '
. '@@SQL_QUOTE_SHOW_CREATE := 1 */';
PTDEBUG && _d($sql);
eval { $dbh->do($sql); };
PTDEBUG && $EVAL_ERROR && _d($EVAL_ERROR);
$self->_use_db($dbh, $quoter, $db);
$sql = "SHOW CREATE TABLE " . $quoter->quote($db, $tbl);
PTDEBUG && _d($sql);
my $href;
eval { $href = $dbh->selectrow_hashref($sql); };
if ( $EVAL_ERROR ) {
warn "Failed to $sql. The table may be damaged.\nError: $EVAL_ERROR";
return;
}
$sql = '/*!40101 SET @@SQL_MODE := @OLD_SQL_MODE, '
. '@@SQL_QUOTE_SHOW_CREATE := @OLD_QUOTE */';
PTDEBUG && _d($sql);
$dbh->do($sql);
my ($key) = grep { m/create table/i } keys %$href;
if ( $key ) {
PTDEBUG && _d('This table is a base table');
$self->{tables}->{$db}->{$tbl} = [ 'table', $href->{$key} ];
}
else {
PTDEBUG && _d('This table is a view');
($key) = grep { m/create view/i } keys %$href;
$self->{tables}->{$db}->{$tbl} = [ 'view', $href->{$key} ];
}
}
return $self->{tables}->{$db}->{$tbl};
}
sub get_columns {
my ( $self, $dbh, $quoter, $db, $tbl ) = @_;
PTDEBUG && _d('Get columns for', $db, $tbl);
if ( !$self->{cache} || !$self->{columns}->{$db}->{$tbl} ) {
$self->_use_db($dbh, $quoter, $db);
my $sql = "SHOW COLUMNS FROM " . $quoter->quote($db, $tbl);
PTDEBUG && _d($sql);
my $cols = $dbh->selectall_arrayref($sql, { Slice => {} });
$self->{columns}->{$db}->{$tbl} = [
map {
my %row;
@row{ map { lc $_ } keys %$_ } = values %$_;
\%row;
} @$cols
];
}
return $self->{columns}->{$db}->{$tbl};
}
sub get_tmp_table {
my ( $self, $dbh, $quoter, $db, $tbl ) = @_;
my $result = 'CREATE TABLE ' . $quoter->quote($tbl) . " (\n";
$result .= join(",\n",
map { ' ' . $quoter->quote($_->{field}) . ' ' . $_->{type} }
@{$self->get_columns($dbh, $quoter, $db, $tbl)});
$result .= "\n)";
PTDEBUG && _d($result);
return $result;
}
sub get_triggers {
my ( $self, $dbh, $quoter, $db, $tbl ) = @_;
if ( !$self->{cache} || !$self->{triggers}->{$db} ) {
$self->{triggers}->{$db} = {};
my $sql = '/*!40101 SET @OLD_SQL_MODE := @@SQL_MODE, '
. q{@@SQL_MODE := REPLACE(REPLACE(@@SQL_MODE, 'ANSI_QUOTES', ''), ',,', ','), }
. '@OLD_QUOTE := @@SQL_QUOTE_SHOW_CREATE, '
. '@@SQL_QUOTE_SHOW_CREATE := 1 */';
PTDEBUG && _d($sql);
eval { $dbh->do($sql); };
PTDEBUG && $EVAL_ERROR && _d($EVAL_ERROR);
$sql = "SHOW TRIGGERS FROM " . $quoter->quote($db);
PTDEBUG && _d($sql);
my $sth = $dbh->prepare($sql);
$sth->execute();
if ( $sth->rows ) {
my $trgs = $sth->fetchall_arrayref({});
foreach my $trg (@$trgs) {
my %trg;
@trg{ map { lc $_ } keys %$trg } = values %$trg;
push @{ $self->{triggers}->{$db}->{ $trg{table} } }, \%trg;
}
}
$sql = '/*!40101 SET @@SQL_MODE := @OLD_SQL_MODE, '
. '@@SQL_QUOTE_SHOW_CREATE := @OLD_QUOTE */';
PTDEBUG && _d($sql);
$dbh->do($sql);
}
if ( $tbl ) {
return $self->{triggers}->{$db}->{$tbl};
}
return values %{$self->{triggers}->{$db}};
}
sub get_databases {
my ( $self, $dbh, $quoter, $like ) = @_;
if ( !$self->{cache} || !$self->{databases} || $like ) {
my $sql = 'SHOW DATABASES';
my @params;
if ( $like ) {
$sql .= ' LIKE ?';
push @params, $like;
}
my $sth = $dbh->prepare($sql);
PTDEBUG && _d($sql, @params);
$sth->execute( @params );
my @dbs = map { $_->[0] } @{$sth->fetchall_arrayref()};
$self->{databases} = \@dbs unless $like;
return @dbs;
}
return @{$self->{databases}};
}
sub get_table_status {
my ( $self, $dbh, $quoter, $db, $like ) = @_;
if ( !$self->{cache} || !$self->{table_status}->{$db} || $like ) {
my $sql = "SHOW TABLE STATUS FROM " . $quoter->quote($db);
my @params;
if ( $like ) {
$sql .= ' LIKE ?';
push @params, $like;
}
PTDEBUG && _d($sql, @params);
my $sth = $dbh->prepare($sql);
$sth->execute(@params);
my @tables = @{$sth->fetchall_arrayref({})};
@tables = map {
my %tbl; # Make a copy with lowercased keys
@tbl{ map { lc $_ } keys %$_ } = values %$_;
$tbl{engine} ||= $tbl{type} || $tbl{comment};
delete $tbl{type};
\%tbl;
} @tables;
$self->{table_status}->{$db} = \@tables unless $like;
return @tables;
}
return @{$self->{table_status}->{$db}};
}
sub get_table_list {
my ( $self, $dbh, $quoter, $db, $like ) = @_;
if ( !$self->{cache} || !$self->{table_list}->{$db} || $like ) {
my $sql = "SHOW /*!50002 FULL*/ TABLES FROM " . $quoter->quote($db);
my @params;
if ( $like ) {
$sql .= ' LIKE ?';
push @params, $like;
}
PTDEBUG && _d($sql, @params);
my $sth = $dbh->prepare($sql);
$sth->execute(@params);
my @tables = @{$sth->fetchall_arrayref()};
@tables = map {
my %tbl = (
name => $_->[0],
engine => ($_->[1] || '') eq 'VIEW' ? 'VIEW' : '',
);
\%tbl;
} @tables;
$self->{table_list}->{$db} = \@tables unless $like;
return @tables;
}
return @{$self->{table_list}->{$db}};
}
sub _d {
my ($package, undef, $line) = caller 0;
@_ = map { (my $temp = $_) =~ s/\n/\n# /g; $temp; }
map { defined $_ ? $_ : 'undef' }
@_;
print STDERR "# $package:$line $PID ", join(' ', @_), "\n";
}
1;
}
# ###########################################################################
# End MySQLDump package
# ###########################################################################
# ###########################################################################
# ChangeHandler package
# This package is a copy without comments from the original. The original
# with comments and its test file can be found in the Bazaar repository at,
# lib/ChangeHandler.pm
# t/lib/ChangeHandler.t
# See https://launchpad.net/percona-toolkit for more information.
# ###########################################################################
{
package ChangeHandler;
use strict;
use warnings FATAL => 'all';
use English qw(-no_match_vars);
use constant PTDEBUG => $ENV{PTDEBUG} || 0;
my $DUPE_KEY = qr/Duplicate entry/;
our @ACTIONS = qw(DELETE REPLACE INSERT UPDATE);
sub new {
my ( $class, %args ) = @_;
foreach my $arg ( qw(Quoter left_db left_tbl right_db right_tbl
replace queue) ) {
die "I need a $arg argument" unless defined $args{$arg};
}
my $q = $args{Quoter};
my $self = {
hex_blob => 1,
%args,
left_db_tbl => $q->quote(@args{qw(left_db left_tbl)}),
right_db_tbl => $q->quote(@args{qw(right_db right_tbl)}),
};
$self->{src_db_tbl} = $self->{left_db_tbl};
$self->{dst_db_tbl} = $self->{right_db_tbl};
map { $self->{$_} = [] } @ACTIONS;
$self->{changes} = { map { $_ => 0 } @ACTIONS };
return bless $self, $class;
}
sub fetch_back {
my ( $self, $dbh ) = @_;
$self->{fetch_back} = $dbh;
PTDEBUG && _d('Set fetch back dbh', $dbh);
return;
}
sub set_src {
my ( $self, $src, $dbh ) = @_;
die "I need a src argument" unless $src;
if ( lc $src eq 'left' ) {
$self->{src_db_tbl} = $self->{left_db_tbl};
$self->{dst_db_tbl} = $self->{right_db_tbl};
}
elsif ( lc $src eq 'right' ) {
$self->{src_db_tbl} = $self->{right_db_tbl};
$self->{dst_db_tbl} = $self->{left_db_tbl};
}
else {
die "src argument must be either 'left' or 'right'"
}
PTDEBUG && _d('Set src to', $src);
$self->fetch_back($dbh) if $dbh;
return;
}
sub src {
my ( $self ) = @_;
return $self->{src_db_tbl};
}
sub dst {
my ( $self ) = @_;
return $self->{dst_db_tbl};
}
sub _take_action {
my ( $self, $sql, $dbh ) = @_;
PTDEBUG && _d('Calling subroutines on', $dbh, $sql);
foreach my $action ( @{$self->{actions}} ) {
$action->($sql, $dbh);
}
return;
}
sub change {
my ( $self, $action, $row, $cols, $dbh ) = @_;
PTDEBUG && _d($dbh, $action, 'where', $self->make_where_clause($row, $cols));
return unless $action;
$self->{changes}->{
$self->{replace} && $action ne 'DELETE' ? 'REPLACE' : $action
}++;
if ( $self->{queue} ) {
$self->__queue($action, $row, $cols, $dbh);
}
else {
eval {
my $func = "make_$action";
$self->_take_action($self->$func($row, $cols), $dbh);
};
if ( $EVAL_ERROR =~ m/$DUPE_KEY/ ) {
PTDEBUG && _d('Duplicate key violation; will queue and rewrite');
$self->{queue}++;
$self->{replace} = 1;
$self->__queue($action, $row, $cols, $dbh);
}
elsif ( $EVAL_ERROR ) {
die $EVAL_ERROR;
}
}
return;
}
sub __queue {
my ( $self, $action, $row, $cols, $dbh ) = @_;
PTDEBUG && _d('Queueing change for later');
if ( $self->{replace} ) {
$action = $action eq 'DELETE' ? $action : 'REPLACE';
}
push @{$self->{$action}}, [ $row, $cols, $dbh ];
}
sub process_rows {
my ( $self, $queue_level, $trace_msg ) = @_;
my $error_count = 0;
TRY: {
if ( $queue_level && $queue_level < $self->{queue} ) { # see redo below!
PTDEBUG && _d('Not processing now', $queue_level, '<', $self->{queue});
return;
}
PTDEBUG && _d('Processing rows:');
my ($row, $cur_act);
eval {
foreach my $action ( @ACTIONS ) {
my $func = "make_$action";
my $rows = $self->{$action};
PTDEBUG && _d(scalar(@$rows), 'to', $action);
$cur_act = $action;
while ( @$rows ) {
$row = shift @$rows;
my $sql = $self->$func(@$row);
$sql .= " /*percona-toolkit $trace_msg*/" if $trace_msg;
$self->_take_action($sql, $row->[2]);
}
}
$error_count = 0;
};
if ( !$error_count++ && $EVAL_ERROR =~ m/$DUPE_KEY/ ) {
PTDEBUG && _d('Duplicate key violation; re-queueing and rewriting');
$self->{queue}++; # Defer rows to the very end
$self->{replace} = 1;
$self->__queue($cur_act, @$row);
redo TRY;
}
elsif ( $EVAL_ERROR ) {
die $EVAL_ERROR;
}
}
}
sub make_DELETE {
my ( $self, $row, $cols ) = @_;
PTDEBUG && _d('Make DELETE');
return "DELETE FROM $self->{dst_db_tbl} WHERE "
. $self->make_where_clause($row, $cols)
. ' LIMIT 1';
}
sub make_UPDATE {
my ( $self, $row, $cols ) = @_;
PTDEBUG && _d('Make UPDATE');
if ( $self->{replace} ) {
return $self->make_row('REPLACE', $row, $cols);
}
my %in_where = map { $_ => 1 } @$cols;
my $where = $self->make_where_clause($row, $cols);
my @cols;
if ( my $dbh = $self->{fetch_back} ) {
my $sql = $self->make_fetch_back_query($where);
PTDEBUG && _d('Fetching data on dbh', $dbh, 'for UPDATE:', $sql);
my $res = $dbh->selectrow_hashref($sql);
@{$row}{keys %$res} = values %$res;
@cols = $self->sort_cols($res);
}
else {
@cols = $self->sort_cols($row);
}
return "UPDATE $self->{dst_db_tbl} SET "
. join(', ', map {
$self->{Quoter}->quote($_)
. '=' . $self->{Quoter}->quote_val($row->{$_})
} grep { !$in_where{$_} } @cols)
. " WHERE $where LIMIT 1";
}
sub make_INSERT {
my ( $self, $row, $cols ) = @_;
PTDEBUG && _d('Make INSERT');
if ( $self->{replace} ) {
return $self->make_row('REPLACE', $row, $cols);
}
return $self->make_row('INSERT', $row, $cols);
}
sub make_REPLACE {
my ( $self, $row, $cols ) = @_;
PTDEBUG && _d('Make REPLACE');
return $self->make_row('REPLACE', $row, $cols);
}
sub make_row {
my ( $self, $verb, $row, $cols ) = @_;
my @cols;
if ( my $dbh = $self->{fetch_back} ) {
my $where = $self->make_where_clause($row, $cols);
my $sql = $self->make_fetch_back_query($where);
PTDEBUG && _d('Fetching data on dbh', $dbh, 'for', $verb, ':', $sql);
my $res = $dbh->selectrow_hashref($sql);
@{$row}{keys %$res} = values %$res;
@cols = $self->sort_cols($res);
}
else {
@cols = $self->sort_cols($row);
}
my $q = $self->{Quoter};
return "$verb INTO $self->{dst_db_tbl}("
. join(', ', map { $q->quote($_) } @cols)
. ') VALUES ('
. join(', ', map { $q->quote_val($_) } @{$row}{@cols} )
. ')';
}
sub make_where_clause {
my ( $self, $row, $cols ) = @_;
my @clauses = map {
my $val = $row->{$_};
my $sep = defined $val ? '=' : ' IS ';
$self->{Quoter}->quote($_) . $sep . $self->{Quoter}->quote_val($val);
} @$cols;
return join(' AND ', @clauses);
}
sub get_changes {
my ( $self ) = @_;
return %{$self->{changes}};
}
sub sort_cols {
my ( $self, $row ) = @_;
my @cols;
if ( $self->{tbl_struct} ) {
my $pos = $self->{tbl_struct}->{col_posn};
my @not_in_tbl;
@cols = sort {
$pos->{$a} <=> $pos->{$b}
}
grep {
if ( !defined $pos->{$_} ) {
push @not_in_tbl, $_;
0;
}
else {
1;
}
}
keys %$row;
push @cols, @not_in_tbl if @not_in_tbl;
}
else {
@cols = sort keys %$row;
}
return @cols;
}
sub make_fetch_back_query {
my ( $self, $where ) = @_;
die "I need a where argument" unless $where;
my $cols = '*';
my $tbl_struct = $self->{tbl_struct};
if ( $tbl_struct ) {
$cols = join(', ',
map {
my $col = $_;
if ( $self->{hex_blob}
&& $tbl_struct->{type_for}->{$col} =~ m/blob|text|binary/ ) {
$col = "IF(`$col`='', '', CONCAT('0x', HEX(`$col`))) AS `$col`";
}
else {
$col = "`$col`";
}
$col;
} @{ $tbl_struct->{cols} }
);
if ( !$cols ) {
PTDEBUG && _d('Failed to make explicit columns list from tbl struct');
$cols = '*';
}
}
return "SELECT $cols FROM $self->{src_db_tbl} WHERE $where LIMIT 1";
}
sub _d {
my ($package, undef, $line) = caller 0;
@_ = map { (my $temp = $_) =~ s/\n/\n# /g; $temp; }
map { defined $_ ? $_ : 'undef' }
@_;
print STDERR "# $package:$line $PID ", join(' ', @_), "\n";
}
1;
}
# ###########################################################################
# End ChangeHandler package
# ###########################################################################
# ###########################################################################
# TableChunker package
# This package is a copy without comments from the original. The original
# with comments and its test file can be found in the Bazaar repository at,
# lib/TableChunker.pm
# t/lib/TableChunker.t
# See https://launchpad.net/percona-toolkit for more information.
# ###########################################################################
{
package TableChunker;
use strict;
use warnings FATAL => 'all';
use English qw(-no_match_vars);
use constant PTDEBUG => $ENV{PTDEBUG} || 0;
use POSIX qw(floor ceil);
use List::Util qw(min max);
use Data::Dumper;
$Data::Dumper::Indent = 1;
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Quotekeys = 0;
sub new {
my ( $class, %args ) = @_;
foreach my $arg ( qw(Quoter TableParser) ) {
die "I need a $arg argument" unless $args{$arg};
}
my %int_types = map { $_ => 1 } qw(bigint date datetime int mediumint smallint time timestamp tinyint year);
my %real_types = map { $_ => 1 } qw(decimal double float);
my $self = {
%args,
int_types => \%int_types,
real_types => \%real_types,
EPOCH => '1970-01-01',
};
return bless $self, $class;
}
sub find_chunk_columns {
my ( $self, %args ) = @_;
foreach my $arg ( qw(tbl_struct) ) {
die "I need a $arg argument" unless $args{$arg};
}
my $tbl_struct = $args{tbl_struct};
my @possible_indexes;
foreach my $index ( values %{ $tbl_struct->{keys} } ) {
next unless $index->{type} eq 'BTREE';
next if grep { defined } @{$index->{col_prefixes}};
if ( $args{exact} ) {
next unless $index->{is_unique} && @{$index->{cols}} == 1;
}
push @possible_indexes, $index;
}
PTDEBUG && _d('Possible chunk indexes in order:',
join(', ', map { $_->{name} } @possible_indexes));
my $can_chunk_exact = 0;
my @candidate_cols;
foreach my $index ( @possible_indexes ) {
my $col = $index->{cols}->[0];
my $col_type = $tbl_struct->{type_for}->{$col};
next unless $self->{int_types}->{$col_type}
|| $self->{real_types}->{$col_type}
|| $col_type =~ m/char/;
push @candidate_cols, { column => $col, index => $index->{name} };
}
$can_chunk_exact = 1 if $args{exact} && scalar @candidate_cols;
if ( PTDEBUG ) {
my $chunk_type = $args{exact} ? 'Exact' : 'Inexact';
_d($chunk_type, 'chunkable:',
join(', ', map { "$_->{column} on $_->{index}" } @candidate_cols));
}
my @result;
PTDEBUG && _d('Ordering columns by order in tbl, PK first');
if ( $tbl_struct->{keys}->{PRIMARY} ) {
my $pk_first_col = $tbl_struct->{keys}->{PRIMARY}->{cols}->[0];
@result = grep { $_->{column} eq $pk_first_col } @candidate_cols;
@candidate_cols = grep { $_->{column} ne $pk_first_col } @candidate_cols;
}
my $i = 0;
my %col_pos = map { $_ => $i++ } @{$tbl_struct->{cols}};
push @result, sort { $col_pos{$a->{column}} <=> $col_pos{$b->{column}} }
@candidate_cols;
if ( PTDEBUG ) {
_d('Chunkable columns:',
join(', ', map { "$_->{column} on $_->{index}" } @result));
_d('Can chunk exactly:', $can_chunk_exact);
}
return ($can_chunk_exact, @result);
}
sub calculate_chunks {
my ( $self, %args ) = @_;
my @required_args = qw(dbh db tbl tbl_struct chunk_col rows_in_range chunk_size);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless defined $args{$arg};
}
PTDEBUG && _d('Calculate chunks for',
join(", ", map {"$_=".(defined $args{$_} ? $args{$_} : "undef")}
qw(db tbl chunk_col min max rows_in_range chunk_size zero_chunk exact)
));
if ( !$args{rows_in_range} ) {
PTDEBUG && _d("Empty table");
return '1=1';
}
if ( $args{rows_in_range} < $args{chunk_size} ) {
PTDEBUG && _d("Chunk size larger than rows in range");
return '1=1';
}
my $q = $self->{Quoter};
my $dbh = $args{dbh};
my $chunk_col = $args{chunk_col};
my $tbl_struct = $args{tbl_struct};
my $col_type = $tbl_struct->{type_for}->{$chunk_col};
PTDEBUG && _d('chunk col type:', $col_type);
my %chunker;
if ( $tbl_struct->{is_numeric}->{$chunk_col} || $col_type =~ /date|time/ ) {
%chunker = $self->_chunk_numeric(%args);
}
elsif ( $col_type =~ m/char/ ) {
%chunker = $self->_chunk_char(%args);
}
else {
die "Cannot chunk $col_type columns";
}
PTDEBUG && _d("Chunker:", Dumper(\%chunker));
my ($col, $start_point, $end_point, $interval, $range_func)
= @chunker{qw(col start_point end_point interval range_func)};
my @chunks;
if ( $start_point < $end_point ) {
push @chunks, "$col = 0" if $chunker{have_zero_chunk};
my ($beg, $end);
my $iter = 0;
for ( my $i = $start_point; $i < $end_point; $i += $interval ) {
($beg, $end) = $self->$range_func($dbh, $i, $interval, $end_point);
if ( $iter++ == 0 ) {
push @chunks,
($chunker{have_zero_chunk} ? "$col > 0 AND " : "")
."$col < " . $q->quote_val($end);
}
else {
push @chunks, "$col >= " . $q->quote_val($beg) . " AND $col < " . $q->quote_val($end);
}
}
my $chunk_range = lc($args{chunk_range} || 'open');
my $nullable = $args{tbl_struct}->{is_nullable}->{$args{chunk_col}};
pop @chunks;
if ( @chunks ) {
push @chunks, "$col >= " . $q->quote_val($beg)
. ($chunk_range eq 'openclosed'
? " AND $col <= " . $q->quote_val($args{max}) : "");
}
else {
push @chunks, $nullable ? "$col IS NOT NULL" : '1=1';
}
if ( $nullable ) {
push @chunks, "$col IS NULL";
}
}
else {
PTDEBUG && _d('No chunks; using single chunk 1=1');
push @chunks, '1=1';
}
return @chunks;
}
sub _chunk_numeric {
my ( $self, %args ) = @_;
my @required_args = qw(dbh db tbl tbl_struct chunk_col rows_in_range chunk_size);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless defined $args{$arg};
}
my $q = $self->{Quoter};
my $db_tbl = $q->quote($args{db}, $args{tbl});
my $col_type = $args{tbl_struct}->{type_for}->{$args{chunk_col}};
my $range_func;
if ( $col_type =~ m/(?:int|year|float|double|decimal)$/ ) {
$range_func = 'range_num';
}
elsif ( $col_type =~ m/^(?:timestamp|date|time)$/ ) {
$range_func = "range_$col_type";
}
elsif ( $col_type eq 'datetime' ) {
$range_func = 'range_datetime';
}
my ($start_point, $end_point);
eval {
$start_point = $self->value_to_number(
value => $args{min},
column_type => $col_type,
dbh => $args{dbh},
);
$end_point = $self->value_to_number(
value => $args{max},
column_type => $col_type,
dbh => $args{dbh},
);
};
if ( $EVAL_ERROR ) {
if ( $EVAL_ERROR =~ m/don't know how to chunk/ ) {
die $EVAL_ERROR;
}
else {
die "Error calculating chunk start and end points for table "
. "`$args{tbl_struct}->{name}` on column `$args{chunk_col}` "
. "with min/max values "
. join('/',
map { defined $args{$_} ? $args{$_} : 'undef' } qw(min max))
. ":\n\n"
. $EVAL_ERROR
. "\nVerify that the min and max values are valid for the column. "
. "If they are valid, this error could be caused by a bug in the "
. "tool.";
}
}
if ( !defined $start_point ) {
PTDEBUG && _d('Start point is undefined');
$start_point = 0;
}
if ( !defined $end_point || $end_point < $start_point ) {
PTDEBUG && _d('End point is undefined or before start point');
$end_point = 0;
}
PTDEBUG && _d("Actual chunk range:", $start_point, "to", $end_point);
my $have_zero_chunk = 0;
if ( $args{zero_chunk} ) {
if ( $start_point != $end_point && $start_point >= 0 ) {
PTDEBUG && _d('Zero chunking');
my $nonzero_val = $self->get_nonzero_value(
%args,
db_tbl => $db_tbl,
col => $args{chunk_col},
col_type => $col_type,
val => $args{min}
);
$start_point = $self->value_to_number(
value => $nonzero_val,
column_type => $col_type,
dbh => $args{dbh},
);
$have_zero_chunk = 1;
}
else {
PTDEBUG && _d("Cannot zero chunk");
}
}
PTDEBUG && _d("Using chunk range:", $start_point, "to", $end_point);
my $interval = $args{chunk_size}
* ($end_point - $start_point)
/ $args{rows_in_range};
if ( $self->{int_types}->{$col_type} ) {
$interval = ceil($interval);
}
$interval ||= $args{chunk_size};
if ( $args{exact} ) {
$interval = $args{chunk_size};
}
PTDEBUG && _d('Chunk interval:', $interval, 'units');
return (
col => $q->quote($args{chunk_col}),
start_point => $start_point,
end_point => $end_point,
interval => $interval,
range_func => $range_func,
have_zero_chunk => $have_zero_chunk,
);
}
sub _chunk_char {
my ( $self, %args ) = @_;
my @required_args = qw(dbh db tbl tbl_struct chunk_col min max rows_in_range chunk_size);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless defined $args{$arg};
}
my $q = $self->{Quoter};
my $db_tbl = $q->quote($args{db}, $args{tbl});
my $dbh = $args{dbh};
my $chunk_col = $args{chunk_col};
my $qchunk_col = $q->quote($args{chunk_col});
my $row;
my $sql;
my ($min_col, $max_col) = @{args}{qw(min max)};
$sql = "SELECT ORD(?) AS min_col_ord, ORD(?) AS max_col_ord";
PTDEBUG && _d($dbh, $sql);
my $ord_sth = $dbh->prepare($sql); # avoid quoting issues
$ord_sth->execute($min_col, $max_col);
$row = $ord_sth->fetchrow_arrayref();
my ($min_col_ord, $max_col_ord) = ($row->[0], $row->[1]);
PTDEBUG && _d("Min/max col char code:", $min_col_ord, $max_col_ord);
my $base;
my @chars;
PTDEBUG && _d("Table charset:", $args{tbl_struct}->{charset});
if ( ($args{tbl_struct}->{charset} || "") eq "latin1" ) {
my @sorted_latin1_chars = (
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, 123, 124, 125, 126, 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, 215, 216, 222, 223, 247, 255);
my ($first_char, $last_char);
for my $i ( 0..$#sorted_latin1_chars ) {
$first_char = $i and last if $sorted_latin1_chars[$i] >= $min_col_ord;
}
for my $i ( $first_char..$#sorted_latin1_chars ) {
$last_char = $i and last if $sorted_latin1_chars[$i] >= $max_col_ord;
};
@chars = map { chr $_; } @sorted_latin1_chars[$first_char..$last_char];
$base = scalar @chars;
}
else {
my $tmp_tbl = '__maatkit_char_chunking_map';
my $tmp_db_tbl = $q->quote($args{db}, $tmp_tbl);
$sql = "DROP TABLE IF EXISTS $tmp_db_tbl";
PTDEBUG && _d($dbh, $sql);
$dbh->do($sql);
my $col_def = $args{tbl_struct}->{defs}->{$chunk_col};
$sql = "CREATE TEMPORARY TABLE $tmp_db_tbl ($col_def) "
. "ENGINE=MEMORY";
PTDEBUG && _d($dbh, $sql);
$dbh->do($sql);
$sql = "INSERT INTO $tmp_db_tbl VALUES (CHAR(?))";
PTDEBUG && _d($dbh, $sql);
my $ins_char_sth = $dbh->prepare($sql); # avoid quoting issues
for my $char_code ( $min_col_ord..$max_col_ord ) {
$ins_char_sth->execute($char_code);
}
$sql = "SELECT $qchunk_col FROM $tmp_db_tbl "
. "WHERE $qchunk_col BETWEEN ? AND ? "
. "ORDER BY $qchunk_col";
PTDEBUG && _d($dbh, $sql);
my $sel_char_sth = $dbh->prepare($sql);
$sel_char_sth->execute($min_col, $max_col);
@chars = map { $_->[0] } @{ $sel_char_sth->fetchall_arrayref() };
$base = scalar @chars;
$sql = "DROP TABLE $tmp_db_tbl";
PTDEBUG && _d($dbh, $sql);
$dbh->do($sql);
}
PTDEBUG && _d("Base", $base, "chars:", @chars);
$sql = "SELECT MAX(LENGTH($qchunk_col)) FROM $db_tbl "
. ($args{where} ? "WHERE $args{where} " : "")
. "ORDER BY $qchunk_col";
PTDEBUG && _d($dbh, $sql);
$row = $dbh->selectrow_arrayref($sql);
my $max_col_len = $row->[0];
PTDEBUG && _d("Max column value:", $max_col, $max_col_len);
my $n_values;
for my $n_chars ( 1..$max_col_len ) {
$n_values = $base**$n_chars;
if ( $n_values >= $args{chunk_size} ) {
PTDEBUG && _d($n_chars, "chars in base", $base, "expresses",
$n_values, "values");
last;
}
}
my $n_chunks = $args{rows_in_range} / $args{chunk_size};
my $interval = floor($n_values / $n_chunks) || 1;
my $range_func = sub {
my ( $self, $dbh, $start, $interval, $max ) = @_;
my $start_char = $self->base_count(
count_to => $start,
base => $base,
symbols => \@chars,
);
my $end_char = $self->base_count(
count_to => min($max, $start + $interval),
base => $base,
symbols => \@chars,
);
return $start_char, $end_char;
};
return (
col => $qchunk_col,
start_point => 0,
end_point => $n_values,
interval => $interval,
range_func => $range_func,
);
}
sub get_first_chunkable_column {
my ( $self, %args ) = @_;
foreach my $arg ( qw(tbl_struct) ) {
die "I need a $arg argument" unless $args{$arg};
}
my ($exact, @cols) = $self->find_chunk_columns(%args);
my $col = $cols[0]->{column};
my $idx = $cols[0]->{index};
my $wanted_col = $args{chunk_column};
my $wanted_idx = $args{chunk_index};
PTDEBUG && _d("Preferred chunk col/idx:", $wanted_col, $wanted_idx);
if ( $wanted_col && $wanted_idx ) {
foreach my $chunkable_col ( @cols ) {
if ( $wanted_col eq $chunkable_col->{column}
&& $wanted_idx eq $chunkable_col->{index} ) {
$col = $wanted_col;
$idx = $wanted_idx;
last;
}
}
}
elsif ( $wanted_col ) {
foreach my $chunkable_col ( @cols ) {
if ( $wanted_col eq $chunkable_col->{column} ) {
$col = $wanted_col;
$idx = $chunkable_col->{index};
last;
}
}
}
elsif ( $wanted_idx ) {
foreach my $chunkable_col ( @cols ) {
if ( $wanted_idx eq $chunkable_col->{index} ) {
$col = $chunkable_col->{column};
$idx = $wanted_idx;
last;
}
}
}
PTDEBUG && _d('First chunkable col/index:', $col, $idx);
return $col, $idx;
}
sub size_to_rows {
my ( $self, %args ) = @_;
my @required_args = qw(dbh db tbl chunk_size);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my ($dbh, $db, $tbl, $chunk_size) = @args{@required_args};
my $q = $self->{Quoter};
my $tp = $self->{TableParser};
my ($n_rows, $avg_row_length);
my ( $num, $suffix ) = $chunk_size =~ m/^(\d+)([MGk])?$/;
if ( $suffix ) { # Convert to bytes.
$chunk_size = $suffix eq 'k' ? $num * 1_024
: $suffix eq 'M' ? $num * 1_024 * 1_024
: $num * 1_024 * 1_024 * 1_024;
}
elsif ( $num ) {
$n_rows = $num;
}
else {
die "Invalid chunk size $chunk_size; must be an integer "
. "with optional suffix kMG";
}
if ( $suffix || $args{avg_row_length} ) {
my ($status) = $tp->get_table_status($dbh, $db, $tbl);
$avg_row_length = $status->{avg_row_length};
if ( !defined $n_rows ) {
$n_rows = $avg_row_length ? ceil($chunk_size / $avg_row_length) : undef;
}
}
return $n_rows, $avg_row_length;
}
sub get_range_statistics {
my ( $self, %args ) = @_;
my @required_args = qw(dbh db tbl chunk_col tbl_struct);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my ($dbh, $db, $tbl, $col) = @args{@required_args};
my $where = $args{where};
my $q = $self->{Quoter};
my $col_type = $args{tbl_struct}->{type_for}->{$col};
my $col_is_numeric = $args{tbl_struct}->{is_numeric}->{$col};
my $db_tbl = $q->quote($db, $tbl);
$col = $q->quote($col);
my ($min, $max);
eval {
my $sql = "SELECT MIN($col), MAX($col) FROM $db_tbl"
. ($args{index_hint} ? " $args{index_hint}" : "")
. ($where ? " WHERE ($where)" : '');
PTDEBUG && _d($dbh, $sql);
($min, $max) = $dbh->selectrow_array($sql);
PTDEBUG && _d("Actual end points:", $min, $max);
($min, $max) = $self->get_valid_end_points(
%args,
dbh => $dbh,
db_tbl => $db_tbl,
col => $col,
col_type => $col_type,
min => $min,
max => $max,
);
PTDEBUG && _d("Valid end points:", $min, $max);
};
if ( $EVAL_ERROR ) {
die "Error getting min and max values for table $db_tbl "
. "on column $col: $EVAL_ERROR";
}
my $sql = "EXPLAIN SELECT * FROM $db_tbl"
. ($args{index_hint} ? " $args{index_hint}" : "")
. ($where ? " WHERE $where" : '');
PTDEBUG && _d($sql);
my $expl = $dbh->selectrow_hashref($sql);
return (
min => $min,
max => $max,
rows_in_range => $expl->{rows},
);
}
sub inject_chunks {
my ( $self, %args ) = @_;
foreach my $arg ( qw(database table chunks chunk_num query) ) {
die "I need a $arg argument" unless defined $args{$arg};
}
PTDEBUG && _d('Injecting chunk', $args{chunk_num});
my $query = $args{query};
my $comment = sprintf("/*%s.%s:%d/%d*/",
$args{database}, $args{table},
$args{chunk_num} + 1, scalar @{$args{chunks}});
$query =~ s!/\*PROGRESS_COMMENT\*/!$comment!;
my $where = "WHERE (" . $args{chunks}->[$args{chunk_num}] . ')';
if ( $args{where} && grep { $_ } @{$args{where}} ) {
$where .= " AND ("
. join(" AND ", map { "($_)" } grep { $_ } @{$args{where}} )
. ")";
}
my $db_tbl = $self->{Quoter}->quote(@args{qw(database table)});
my $index_hint = $args{index_hint} || '';
PTDEBUG && _d('Parameters:',
Dumper({WHERE => $where, DB_TBL => $db_tbl, INDEX_HINT => $index_hint}));
$query =~ s!/\*WHERE\*/! $where!;
$query =~ s!/\*DB_TBL\*/!$db_tbl!;
$query =~ s!/\*INDEX_HINT\*/! $index_hint!;
$query =~ s!/\*CHUNK_NUM\*/! $args{chunk_num} AS chunk_num,!;
return $query;
}
sub value_to_number {
my ( $self, %args ) = @_;
my @required_args = qw(column_type dbh);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless defined $args{$arg};
}
my $val = $args{value};
my ($col_type, $dbh) = @args{@required_args};
PTDEBUG && _d('Converting MySQL', $col_type, $val);
return unless defined $val; # value is NULL
my %mysql_conv_func_for = (
timestamp => 'UNIX_TIMESTAMP',
date => 'TO_DAYS',
time => 'TIME_TO_SEC',
datetime => 'TO_DAYS',
);
my $num;
if ( $col_type =~ m/(?:int|year|float|double|decimal)$/ ) {
$num = $val;
}
elsif ( $col_type =~ m/^(?:timestamp|date|time)$/ ) {
my $func = $mysql_conv_func_for{$col_type};
my $sql = "SELECT $func(?)";
PTDEBUG && _d($dbh, $sql, $val);
my $sth = $dbh->prepare($sql);
$sth->execute($val);
($num) = $sth->fetchrow_array();
}
elsif ( $col_type eq 'datetime' ) {
$num = $self->timestampdiff($dbh, $val);
}
else {
die "I don't know how to chunk $col_type\n";
}
PTDEBUG && _d('Converts to', $num);
return $num;
}
sub range_num {
my ( $self, $dbh, $start, $interval, $max ) = @_;
my $end = min($max, $start + $interval);
$start = sprintf('%.17f', $start) if $start =~ /e/;
$end = sprintf('%.17f', $end) if $end =~ /e/;
$start =~ s/\.(\d{5}).*$/.$1/;
$end =~ s/\.(\d{5}).*$/.$1/;
if ( $end > $start ) {
return ( $start, $end );
}
else {
die "Chunk size is too small: $end !> $start\n";
}
}
sub range_time {
my ( $self, $dbh, $start, $interval, $max ) = @_;
my $sql = "SELECT SEC_TO_TIME($start), SEC_TO_TIME(LEAST($max, $start + $interval))";
PTDEBUG && _d($sql);
return $dbh->selectrow_array($sql);
}
sub range_date {
my ( $self, $dbh, $start, $interval, $max ) = @_;
my $sql = "SELECT FROM_DAYS($start), FROM_DAYS(LEAST($max, $start + $interval))";
PTDEBUG && _d($sql);
return $dbh->selectrow_array($sql);
}
sub range_datetime {
my ( $self, $dbh, $start, $interval, $max ) = @_;
my $sql = "SELECT DATE_ADD('$self->{EPOCH}', INTERVAL $start SECOND), "
. "DATE_ADD('$self->{EPOCH}', INTERVAL LEAST($max, $start + $interval) SECOND)";
PTDEBUG && _d($sql);
return $dbh->selectrow_array($sql);
}
sub range_timestamp {
my ( $self, $dbh, $start, $interval, $max ) = @_;
my $sql = "SELECT FROM_UNIXTIME($start), FROM_UNIXTIME(LEAST($max, $start + $interval))";
PTDEBUG && _d($sql);
return $dbh->selectrow_array($sql);
}
sub timestampdiff {
my ( $self, $dbh, $time ) = @_;
my $sql = "SELECT (COALESCE(TO_DAYS('$time'), 0) * 86400 + TIME_TO_SEC('$time')) "
. "- TO_DAYS('$self->{EPOCH} 00:00:00') * 86400";
PTDEBUG && _d($sql);
my ( $diff ) = $dbh->selectrow_array($sql);
$sql = "SELECT DATE_ADD('$self->{EPOCH}', INTERVAL $diff SECOND)";
PTDEBUG && _d($sql);
my ( $check ) = $dbh->selectrow_array($sql);
die <<" EOF"
Incorrect datetime math: given $time, calculated $diff but checked to $check.
This could be due to a version of MySQL that overflows on large interval
values to DATE_ADD(), or the given datetime is not a valid date. If not,
please report this as a bug.
EOF
unless $check eq $time;
return $diff;
}
sub get_valid_end_points {
my ( $self, %args ) = @_;
my @required_args = qw(dbh db_tbl col col_type);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my ($dbh, $db_tbl, $col, $col_type) = @args{@required_args};
my ($real_min, $real_max) = @args{qw(min max)};
my $err_fmt = "Error finding a valid %s value for table $db_tbl on "
. "column $col. The real %s value %s is invalid and "
. "no other valid values were found. Verify that the table "
. "has at least one valid value for this column"
. ($args{where} ? " where $args{where}." : ".");
my $valid_min = $real_min;
if ( defined $valid_min ) {
PTDEBUG && _d("Validating min end point:", $real_min);
$valid_min = $self->_get_valid_end_point(
%args,
val => $real_min,
endpoint => 'min',
);
die sprintf($err_fmt, 'minimum', 'minimum',
(defined $real_min ? $real_min : "NULL"))
unless defined $valid_min;
}
my $valid_max = $real_max;
if ( defined $valid_max ) {
PTDEBUG && _d("Validating max end point:", $real_min);
$valid_max = $self->_get_valid_end_point(
%args,
val => $real_max,
endpoint => 'max',
);
die sprintf($err_fmt, 'maximum', 'maximum',
(defined $real_max ? $real_max : "NULL"))
unless defined $valid_max;
}
return $valid_min, $valid_max;
}
sub _get_valid_end_point {
my ( $self, %args ) = @_;
my @required_args = qw(dbh db_tbl col col_type);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my ($dbh, $db_tbl, $col, $col_type) = @args{@required_args};
my $val = $args{val};
return $val unless defined $val;
my $validate = $col_type =~ m/time|date/ ? \&_validate_temporal_value
: undef;
if ( !$validate ) {
PTDEBUG && _d("No validator for", $col_type, "values");
return $val;
}
return $val if defined $validate->($dbh, $val);
PTDEBUG && _d("Value is invalid, getting first valid value");
$val = $self->get_first_valid_value(
%args,
val => $val,
validate => $validate,
);
return $val;
}
sub get_first_valid_value {
my ( $self, %args ) = @_;
my @required_args = qw(dbh db_tbl col validate endpoint);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my ($dbh, $db_tbl, $col, $validate, $endpoint) = @args{@required_args};
my $tries = defined $args{tries} ? $args{tries} : 5;
my $val = $args{val};
return unless defined $val;
my $cmp = $endpoint =~ m/min/i ? '>'
: $endpoint =~ m/max/i ? '<'
: die "Invalid endpoint arg: $endpoint";
my $sql = "SELECT $col FROM $db_tbl "
. ($args{index_hint} ? "$args{index_hint} " : "")
. "WHERE $col $cmp ? AND $col IS NOT NULL "
. ($args{where} ? "AND ($args{where}) " : "")
. "ORDER BY $col LIMIT 1";
PTDEBUG && _d($dbh, $sql);
my $sth = $dbh->prepare($sql);
my $last_val = $val;
while ( $tries-- ) {
$sth->execute($last_val);
my ($next_val) = $sth->fetchrow_array();
PTDEBUG && _d('Next value:', $next_val, '; tries left:', $tries);
if ( !defined $next_val ) {
PTDEBUG && _d('No more rows in table');
last;
}
if ( defined $validate->($dbh, $next_val) ) {
PTDEBUG && _d('First valid value:', $next_val);
$sth->finish();
return $next_val;
}
$last_val = $next_val;
}
$sth->finish();
$val = undef; # no valid value found
return $val;
}
sub _validate_temporal_value {
my ( $dbh, $val ) = @_;
my $sql = "SELECT IF(TIME_FORMAT(?,'%H:%i:%s')=?, TIME_TO_SEC(?), TO_DAYS(?))";
my $res;
eval {
PTDEBUG && _d($dbh, $sql, $val);
my $sth = $dbh->prepare($sql);
$sth->execute($val, $val, $val, $val);
($res) = $sth->fetchrow_array();
$sth->finish();
};
if ( $EVAL_ERROR ) {
PTDEBUG && _d($EVAL_ERROR);
}
return $res;
}
sub get_nonzero_value {
my ( $self, %args ) = @_;
my @required_args = qw(dbh db_tbl col col_type);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my ($dbh, $db_tbl, $col, $col_type) = @args{@required_args};
my $tries = defined $args{tries} ? $args{tries} : 5;
my $val = $args{val};
my $is_nonzero = $col_type =~ m/time|date/ ? \&_validate_temporal_value
: sub { return $_[1]; };
if ( !$is_nonzero->($dbh, $val) ) { # quasi-double-negative, sorry
PTDEBUG && _d('Discarding zero value:', $val);
my $sql = "SELECT $col FROM $db_tbl "
. ($args{index_hint} ? "$args{index_hint} " : "")
. "WHERE $col > ? AND $col IS NOT NULL "
. ($args{where} ? "AND ($args{where}) " : '')
. "ORDER BY $col LIMIT 1";
PTDEBUG && _d($sql);
my $sth = $dbh->prepare($sql);
my $last_val = $val;
while ( $tries-- ) {
$sth->execute($last_val);
my ($next_val) = $sth->fetchrow_array();
if ( $is_nonzero->($dbh, $next_val) ) {
PTDEBUG && _d('First non-zero value:', $next_val);
$sth->finish();
return $next_val;
}
$last_val = $next_val;
}
$sth->finish();
$val = undef; # no non-zero value found
}
return $val;
}
sub base_count {
my ( $self, %args ) = @_;
my @required_args = qw(count_to base symbols);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless defined $args{$arg};
}
my ($n, $base, $symbols) = @args{@required_args};
return $symbols->[0] if $n == 0;
my $highest_power = floor(log($n)/log($base));
if ( $highest_power == 0 ){
return $symbols->[$n];
}
my @base_powers;
for my $power ( 0..$highest_power ) {
push @base_powers, ($base**$power) || 1;
}
my @base_multiples;
foreach my $base_power ( reverse @base_powers ) {
my $multiples = floor($n / $base_power);
push @base_multiples, $multiples;
$n -= $multiples * $base_power;
}
return join('', map { $symbols->[$_] } @base_multiples);
}
sub _d {
my ($package, undef, $line) = caller 0;
@_ = map { (my $temp = $_) =~ s/\n/\n# /g; $temp; }
map { defined $_ ? $_ : 'undef' }
@_;
print STDERR "# $package:$line $PID ", join(' ', @_), "\n";
}
1;
}
# ###########################################################################
# End TableChunker package
# ###########################################################################
# ###########################################################################
# TableChecksum package
# This package is a copy without comments from the original. The original
# with comments and its test file can be found in the Bazaar repository at,
# lib/TableChecksum.pm
# t/lib/TableChecksum.t
# See https://launchpad.net/percona-toolkit for more information.
# ###########################################################################
{
package TableChecksum;
use strict;
use warnings FATAL => 'all';
use English qw(-no_match_vars);
use constant PTDEBUG => $ENV{PTDEBUG} || 0;
use List::Util qw(max);
our %ALGOS = (
CHECKSUM => { pref => 0, hash => 0 },
BIT_XOR => { pref => 2, hash => 1 },
ACCUM => { pref => 3, hash => 1 },
);
sub new {
my ( $class, %args ) = @_;
foreach my $arg ( qw(Quoter VersionParser) ) {
die "I need a $arg argument" unless defined $args{$arg};
}
my $self = { %args };
return bless $self, $class;
}
sub crc32 {
my ( $self, $string ) = @_;
my $poly = 0xEDB88320;
my $crc = 0xFFFFFFFF;
foreach my $char ( split(//, $string) ) {
my $comp = ($crc ^ ord($char)) & 0xFF;
for ( 1 .. 8 ) {
$comp = $comp & 1 ? $poly ^ ($comp >> 1) : $comp >> 1;
}
$crc = (($crc >> 8) & 0x00FFFFFF) ^ $comp;
}
return $crc ^ 0xFFFFFFFF;
}
sub get_crc_wid {
my ( $self, $dbh, $func ) = @_;
my $crc_wid = 16;
if ( uc $func ne 'FNV_64' && uc $func ne 'FNV1A_64' ) {
eval {
my ($val) = $dbh->selectrow_array("SELECT $func('a')");
$crc_wid = max(16, length($val));
};
}
return $crc_wid;
}
sub get_crc_type {
my ( $self, $dbh, $func ) = @_;
my $type = '';
my $length = 0;
my $sql = "SELECT $func('a')";
my $sth = $dbh->prepare($sql);
eval {
$sth->execute();
$type = $sth->{mysql_type_name}->[0];
$length = $sth->{mysql_length}->[0];
PTDEBUG && _d($sql, $type, $length);
if ( $type eq 'bigint' && $length < 20 ) {
$type = 'int';
}
};
$sth->finish;
PTDEBUG && _d('crc_type:', $type, 'length:', $length);
return ($type, $length);
}
sub best_algorithm {
my ( $self, %args ) = @_;
my ( $alg, $dbh ) = @args{ qw(algorithm dbh) };
my $vp = $self->{VersionParser};
my @choices = sort { $ALGOS{$a}->{pref} <=> $ALGOS{$b}->{pref} } keys %ALGOS;
die "Invalid checksum algorithm $alg"
if $alg && !$ALGOS{$alg};
if (
$args{where} || $args{chunk} # CHECKSUM does whole table
|| $args{replicate} # CHECKSUM can't do INSERT.. SELECT
|| !$vp->version_ge($dbh, '4.1.1')) # CHECKSUM doesn't exist
{
PTDEBUG && _d('Cannot use CHECKSUM algorithm');
@choices = grep { $_ ne 'CHECKSUM' } @choices;
}
if ( !$vp->version_ge($dbh, '4.1.1') ) {
PTDEBUG && _d('Cannot use BIT_XOR algorithm because MySQL < 4.1.1');
@choices = grep { $_ ne 'BIT_XOR' } @choices;
}
if ( $alg && grep { $_ eq $alg } @choices ) {
PTDEBUG && _d('User requested', $alg, 'algorithm');
return $alg;
}
if ( $args{count} && grep { $_ ne 'CHECKSUM' } @choices ) {
PTDEBUG && _d('Not using CHECKSUM algorithm because COUNT desired');
@choices = grep { $_ ne 'CHECKSUM' } @choices;
}
PTDEBUG && _d('Algorithms, in order:', @choices);
return $choices[0];
}
sub is_hash_algorithm {
my ( $self, $algorithm ) = @_;
return $ALGOS{$algorithm} && $ALGOS{$algorithm}->{hash};
}
sub choose_hash_func {
my ( $self, %args ) = @_;
my @funcs = qw(CRC32 FNV1A_64 FNV_64 MD5 SHA1);
if ( $args{function} ) {
unshift @funcs, $args{function};
}
my ($result, $error);
do {
my $func;
eval {
$func = shift(@funcs);
my $sql = "SELECT $func('test-string')";
PTDEBUG && _d($sql);
$args{dbh}->do($sql);
$result = $func;
};
if ( $EVAL_ERROR && $EVAL_ERROR =~ m/failed: (.*?) at \S+ line/ ) {
$error .= qq{$func cannot be used because "$1"\n};
PTDEBUG && _d($func, 'cannot be used because', $1);
}
} while ( @funcs && !$result );
die $error unless $result;
PTDEBUG && _d('Chosen hash func:', $result);
return $result;
}
sub optimize_xor {
my ( $self, %args ) = @_;
my ($dbh, $func) = @args{qw(dbh function)};
die "$func never needs the BIT_XOR optimization"
if $func =~ m/^(?:FNV1A_64|FNV_64|CRC32)$/i;
my $opt_slice = 0;
my $unsliced = uc $dbh->selectall_arrayref("SELECT $func('a')")->[0]->[0];
my $sliced = '';
my $start = 1;
my $crc_wid = length($unsliced) < 16 ? 16 : length($unsliced);
do { # Try different positions till sliced result equals non-sliced.
PTDEBUG && _d('Trying slice', $opt_slice);
$dbh->do(q{SET @crc := '', @cnt := 0});
my $slices = $self->make_xor_slices(
query => "\@crc := $func('a')",
crc_wid => $crc_wid,
opt_slice => $opt_slice,
);
my $sql = "SELECT CONCAT($slices) AS TEST FROM (SELECT NULL) AS x";
$sliced = ($dbh->selectrow_array($sql))[0];
if ( $sliced ne $unsliced ) {
PTDEBUG && _d('Slice', $opt_slice, 'does not work');
$start += 16;
++$opt_slice;
}
} while ( $start < $crc_wid && $sliced ne $unsliced );
if ( $sliced eq $unsliced ) {
PTDEBUG && _d('Slice', $opt_slice, 'works');
return $opt_slice;
}
else {
PTDEBUG && _d('No slice works');
return undef;
}
}
sub make_xor_slices {
my ( $self, %args ) = @_;
foreach my $arg ( qw(query crc_wid) ) {
die "I need a $arg argument" unless defined $args{$arg};
}
my ( $query, $crc_wid, $opt_slice ) = @args{qw(query crc_wid opt_slice)};
my @slices;
for ( my $start = 1; $start <= $crc_wid; $start += 16 ) {
my $len = $crc_wid - $start + 1;
if ( $len > 16 ) {
$len = 16;
}
push @slices,
"LPAD(CONV(BIT_XOR("
. "CAST(CONV(SUBSTRING(\@crc, $start, $len), 16, 10) AS UNSIGNED))"
. ", 10, 16), $len, '0')";
}
if ( defined $opt_slice && $opt_slice < @slices ) {
$slices[$opt_slice] =~ s/\@crc/\@crc := $query/;
}
else {
map { s/\@crc/$query/ } @slices;
}
return join(', ', @slices);
}
sub make_row_checksum {
my ( $self, %args ) = @_;
my ( $tbl_struct, $func ) = @args{ qw(tbl_struct function) };
my $q = $self->{Quoter};
my $sep = $args{sep} || '#';
$sep =~ s/'//g;
$sep ||= '#';
my $ignorecols = $args{ignorecols} || {};
my %cols = map { lc($_) => 1 }
grep { !exists $ignorecols->{$_} }
($args{cols} ? @{$args{cols}} : @{$tbl_struct->{cols}});
my %seen;
my @cols =
map {
my $type = $tbl_struct->{type_for}->{$_};
my $result = $q->quote($_);
if ( $type eq 'timestamp' ) {
$result .= ' + 0';
}
elsif ( $args{float_precision} && $type =~ m/float|double/ ) {
$result = "ROUND($result, $args{float_precision})";
}
elsif ( $args{trim} && $type =~ m/varchar/ ) {
$result = "TRIM($result)";
}
$result;
}
grep {
$cols{$_} && !$seen{$_}++
}
@{$tbl_struct->{cols}};
my $query;
if ( !$args{no_cols} ) {
$query = join(', ',
map {
my $col = $_;
if ( $col =~ m/\+ 0/ ) {
my ($real_col) = /^(\S+)/;
$col .= " AS $real_col";
}
elsif ( $col =~ m/TRIM/ ) {
my ($real_col) = m/TRIM\(([^\)]+)\)/;
$col .= " AS $real_col";
}
$col;
} @cols)
. ', ';
}
if ( uc $func ne 'FNV_64' && uc $func ne 'FNV1A_64' ) {
my @nulls = grep { $cols{$_} } @{$tbl_struct->{null_cols}};
if ( @nulls ) {
my $bitmap = "CONCAT("
. join(', ', map { 'ISNULL(' . $q->quote($_) . ')' } @nulls)
. ")";
push @cols, $bitmap;
}
$query .= @cols > 1
? "$func(CONCAT_WS('$sep', " . join(', ', @cols) . '))'
: "$func($cols[0])";
}
else {
my $fnv_func = uc $func;
$query .= "$fnv_func(" . join(', ', @cols) . ')';
}
return $query;
}
sub make_checksum_query {
my ( $self, %args ) = @_;
my @required_args = qw(db tbl tbl_struct algorithm crc_wid crc_type);
foreach my $arg( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my ( $db, $tbl, $tbl_struct, $algorithm,
$crc_wid, $crc_type) = @args{@required_args};
my $func = $args{function};
my $q = $self->{Quoter};
my $result;
die "Invalid or missing checksum algorithm"
unless $algorithm && $ALGOS{$algorithm};
if ( $algorithm eq 'CHECKSUM' ) {
return "CHECKSUM TABLE " . $q->quote($db, $tbl);
}
my $expr = $self->make_row_checksum(%args, no_cols=>1);
if ( $algorithm eq 'BIT_XOR' ) {
if ( $crc_type =~ m/int$/ ) {
$result = "COALESCE(LOWER(CONV(BIT_XOR(CAST($expr AS UNSIGNED)), 10, 16)), 0) AS crc ";
}
else {
my $slices = $self->make_xor_slices( query => $expr, %args );
$result = "COALESCE(LOWER(CONCAT($slices)), 0) AS crc ";
}
}
else {
if ( $crc_type =~ m/int$/ ) {
$result = "COALESCE(RIGHT(MAX("
. "\@crc := CONCAT(LPAD(\@cnt := \@cnt + 1, 16, '0'), "
. "CONV(CAST($func(CONCAT(\@crc, $expr)) AS UNSIGNED), 10, 16))"
. "), $crc_wid), 0) AS crc ";
}
else {
$result = "COALESCE(RIGHT(MAX("
. "\@crc := CONCAT(LPAD(\@cnt := \@cnt + 1, 16, '0'), "
. "$func(CONCAT(\@crc, $expr)))"
. "), $crc_wid), 0) AS crc ";
}
}
if ( $args{replicate} ) {
$result = "REPLACE /*PROGRESS_COMMENT*/ INTO $args{replicate} "
. "(db, tbl, chunk, boundaries, this_cnt, this_crc) "
. "SELECT ?, ?, /*CHUNK_NUM*/ ?, COUNT(*) AS cnt, $result";
}
else {
$result = "SELECT "
. ($args{buffer} ? 'SQL_BUFFER_RESULT ' : '')
. "/*PROGRESS_COMMENT*//*CHUNK_NUM*/ COUNT(*) AS cnt, $result";
}
return $result . "FROM /*DB_TBL*//*INDEX_HINT*//*WHERE*/";
}
sub find_replication_differences {
my ( $self, $dbh, $table ) = @_;
my $sql
= "SELECT db, tbl, CONCAT(db, '.', tbl) AS `table`, "
. "chunk, chunk_index, lower_boundary, upper_boundary, "
. "COALESCE(this_cnt-master_cnt, 0) AS cnt_diff, "
. "COALESCE("
. "this_crc <> master_crc OR ISNULL(master_crc) <> ISNULL(this_crc), 0"
. ") AS crc_diff, this_cnt, master_cnt, this_crc, master_crc "
. "FROM $table "
. "WHERE master_cnt <> this_cnt OR master_crc <> this_crc "
. "OR ISNULL(master_crc) <> ISNULL(this_crc)";
PTDEBUG && _d($sql);
my $diffs = $dbh->selectall_arrayref($sql, { Slice => {} });
return $diffs;
}
sub _d {
my ($package, undef, $line) = caller 0;
@_ = map { (my $temp = $_) =~ s/\n/\n# /g; $temp; }
map { defined $_ ? $_ : 'undef' }
@_;
print STDERR "# $package:$line $PID ", join(' ', @_), "\n";
}
1;
}
# ###########################################################################
# End TableChecksum package
# ###########################################################################
# ###########################################################################
# TableSyncChunk package
# This package is a copy without comments from the original. The original
# with comments and its test file can be found in the Bazaar repository at,
# lib/TableSyncChunk.pm
# t/lib/TableSyncChunk.t
# See https://launchpad.net/percona-toolkit for more information.
# ###########################################################################
{
package TableSyncChunk;
use strict;
use warnings FATAL => 'all';
use English qw(-no_match_vars);
use constant PTDEBUG => $ENV{PTDEBUG} || 0;
use Data::Dumper;
$Data::Dumper::Indent = 1;
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Quotekeys = 0;
sub new {
my ( $class, %args ) = @_;
foreach my $arg ( qw(TableChunker Quoter) ) {
die "I need a $arg argument" unless defined $args{$arg};
}
my $self = { %args };
return bless $self, $class;
}
sub name {
return 'Chunk';
}
sub set_callback {
my ( $self, $callback, $code ) = @_;
$self->{$callback} = $code;
return;
}
sub can_sync {
my ( $self, %args ) = @_;
foreach my $arg ( qw(tbl_struct) ) {
die "I need a $arg argument" unless defined $args{$arg};
}
my ($exact, @chunkable_cols) = $self->{TableChunker}->find_chunk_columns(
%args,
exact => 1,
);
return unless $exact;
my $colno;
if ( $args{chunk_col} || $args{chunk_index} ) {
PTDEBUG && _d('Checking requested col', $args{chunk_col},
'and/or index', $args{chunk_index});
for my $i ( 0..$#chunkable_cols ) {
if ( $args{chunk_col} ) {
next unless $chunkable_cols[$i]->{column} eq $args{chunk_col};
}
if ( $args{chunk_index} ) {
next unless $chunkable_cols[$i]->{index} eq $args{chunk_index};
}
$colno = $i;
last;
}
if ( !$colno ) {
PTDEBUG && _d('Cannot chunk on column', $args{chunk_col},
'and/or using index', $args{chunk_index});
return;
}
}
else {
$colno = 0; # First, best chunkable column/index.
}
PTDEBUG && _d('Can chunk on column', $chunkable_cols[$colno]->{column},
'using index', $chunkable_cols[$colno]->{index});
return (
1,
chunk_col => $chunkable_cols[$colno]->{column},
chunk_index => $chunkable_cols[$colno]->{index},
),
}
sub prepare_to_sync {
my ( $self, %args ) = @_;
my @required_args = qw(dbh db tbl tbl_struct cols chunk_col
chunk_size crc_col ChangeHandler);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless defined $args{$arg};
}
my $chunker = $self->{TableChunker};
$self->{chunk_col} = $args{chunk_col};
$self->{crc_col} = $args{crc_col};
$self->{index_hint} = $args{index_hint};
$self->{buffer_in_mysql} = $args{buffer_in_mysql};
$self->{ChangeHandler} = $args{ChangeHandler};
$self->{ChangeHandler}->fetch_back($args{dbh});
push @{$args{cols}}, $args{chunk_col};
my @chunks;
my %range_params = $chunker->get_range_statistics(%args);
if ( !grep { !defined $range_params{$_} } qw(min max rows_in_range) ) {
($args{chunk_size}) = $chunker->size_to_rows(%args);
@chunks = $chunker->calculate_chunks(%args, %range_params);
}
else {
PTDEBUG && _d('No range statistics; using single chunk 1=1');
@chunks = '1=1';
}
$self->{chunks} = \@chunks;
$self->{chunk_num} = 0;
$self->{state} = 0;
return;
}
sub uses_checksum {
return 1;
}
sub set_checksum_queries {
my ( $self, $chunk_sql, $row_sql ) = @_;
die "I need a chunk_sql argument" unless $chunk_sql;
die "I need a row_sql argument" unless $row_sql;
$self->{chunk_sql} = $chunk_sql;
$self->{row_sql} = $row_sql;
return;
}
sub prepare_sync_cycle {
my ( $self, $host ) = @_;
my $sql = q{SET @crc := '', @cnt := 0};
PTDEBUG && _d($sql);
$host->{dbh}->do($sql);
return;
}
sub get_sql {
my ( $self, %args ) = @_;
if ( $self->{state} ) { # select rows in a chunk
my $q = $self->{Quoter};
return 'SELECT /*rows in chunk*/ '
. ($self->{buffer_in_mysql} ? 'SQL_BUFFER_RESULT ' : '')
. $self->{row_sql} . " AS $self->{crc_col}"
. ' FROM ' . $self->{Quoter}->quote(@args{qw(database table)})
. ' '. ($self->{index_hint} || '')
. ' WHERE (' . $self->{chunks}->[$self->{chunk_num}] . ')'
. ($args{where} ? " AND ($args{where})" : '')
. ' ORDER BY ' . join(', ', map {$q->quote($_) } @{$self->key_cols()});
}
else { # select a chunk of rows
return $self->{TableChunker}->inject_chunks(
database => $args{database},
table => $args{table},
chunks => $self->{chunks},
chunk_num => $self->{chunk_num},
query => $self->{chunk_sql},
index_hint => $self->{index_hint},
where => [ $args{where} ],
);
}
}
sub same_row {
my ( $self, %args ) = @_;
my ($lr, $rr) = @args{qw(lr rr)};
if ( $self->{state} ) { # checksumming rows
if ( $lr->{$self->{crc_col}} ne $rr->{$self->{crc_col}} ) {
my $action = 'UPDATE';
my $auth_row = $lr;
my $change_dbh;
if ( $self->{same_row} ) {
($action, $auth_row, $change_dbh) = $self->{same_row}->(%args);
}
$self->{ChangeHandler}->change(
$action, # Execute the action
$auth_row, # with these row values
$self->key_cols(), # identified by these key cols
$change_dbh, # on this dbh
);
}
}
elsif ( $lr->{cnt} != $rr->{cnt} || $lr->{crc} ne $rr->{crc} ) {
PTDEBUG && _d('Rows:', Dumper($lr, $rr));
PTDEBUG && _d('Will examine this chunk before moving to next');
$self->{state} = 1; # Must examine this chunk row-by-row
}
}
sub not_in_right {
my ( $self, %args ) = @_;
die "Called not_in_right in state 0" unless $self->{state};
my $action = 'INSERT';
my $auth_row = $args{lr};
my $change_dbh;
if ( $self->{not_in_right} ) {
($action, $auth_row, $change_dbh) = $self->{not_in_right}->(%args);
}
$self->{ChangeHandler}->change(
$action, # Execute the action
$auth_row, # with these row values
$self->key_cols(), # identified by these key cols
$change_dbh, # on this dbh
);
return;
}
sub not_in_left {
my ( $self, %args ) = @_;
die "Called not_in_left in state 0" unless $self->{state};
my $action = 'DELETE';
my $auth_row = $args{rr};
my $change_dbh;
if ( $self->{not_in_left} ) {
($action, $auth_row, $change_dbh) = $self->{not_in_left}->(%args);
}
$self->{ChangeHandler}->change(
$action, # Execute the action
$auth_row, # with these row values
$self->key_cols(), # identified by these key cols
$change_dbh, # on this dbh
);
return;
}
sub done_with_rows {
my ( $self ) = @_;
if ( $self->{state} == 1 ) {
$self->{state} = 2;
PTDEBUG && _d('Setting state =', $self->{state});
}
else {
$self->{state} = 0;
$self->{chunk_num}++;
PTDEBUG && _d('Setting state =', $self->{state},
'chunk_num =', $self->{chunk_num});
}
return;
}
sub done {
my ( $self ) = @_;
PTDEBUG && _d('Done with', $self->{chunk_num}, 'of',
scalar(@{$self->{chunks}}), 'chunks');
PTDEBUG && $self->{state} && _d('Chunk differs; must examine rows');
return $self->{state} == 0
&& $self->{chunk_num} >= scalar(@{$self->{chunks}})
}
sub pending_changes {
my ( $self ) = @_;
if ( $self->{state} ) {
PTDEBUG && _d('There are pending changes');
return 1;
}
else {
PTDEBUG && _d('No pending changes');
return 0;
}
}
sub key_cols {
my ( $self ) = @_;
my @cols;
if ( $self->{state} == 0 ) {
@cols = qw(chunk_num);
}
else {
@cols = $self->{chunk_col};
}
PTDEBUG && _d('State', $self->{state},',', 'key cols', join(', ', @cols));
return \@cols;
}
sub _d {
my ($package, undef, $line) = caller 0;
@_ = map { (my $temp = $_) =~ s/\n/\n# /g; $temp; }
map { defined $_ ? $_ : 'undef' }
@_;
print STDERR "# $package:$line $PID ", join(' ', @_), "\n";
}
1;
}
# ###########################################################################
# End TableSyncChunk package
# ###########################################################################
# ###########################################################################
# TableSyncNibble package
# This package is a copy without comments from the original. The original
# with comments and its test file can be found in the Bazaar repository at,
# lib/TableSyncNibble.pm
# t/lib/TableSyncNibble.t
# See https://launchpad.net/percona-toolkit for more information.
# ###########################################################################
{
package TableSyncNibble;
use strict;
use warnings FATAL => 'all';
use English qw(-no_match_vars);
use constant PTDEBUG => $ENV{PTDEBUG} || 0;
use Data::Dumper;
$Data::Dumper::Indent = 1;
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Quotekeys = 0;
sub new {
my ( $class, %args ) = @_;
foreach my $arg ( qw(TableNibbler TableChunker TableParser Quoter) ) {
die "I need a $arg argument" unless defined $args{$arg};
}
my $self = { %args };
return bless $self, $class;
}
sub name {
return 'Nibble';
}
sub can_sync {
my ( $self, %args ) = @_;
foreach my $arg ( qw(tbl_struct) ) {
die "I need a $arg argument" unless defined $args{$arg};
}
my $nibble_index = $self->{TableParser}->find_best_index($args{tbl_struct});
if ( $nibble_index ) {
PTDEBUG && _d('Best nibble index:', Dumper($nibble_index));
if ( !$args{tbl_struct}->{keys}->{$nibble_index}->{is_unique} ) {
PTDEBUG && _d('Best nibble index is not unique');
return;
}
if ( $args{chunk_index} && $args{chunk_index} ne $nibble_index ) {
PTDEBUG && _d('Best nibble index is not requested index',
$args{chunk_index});
return;
}
}
else {
PTDEBUG && _d('No best nibble index returned');
return;
}
my $small_table = 0;
if ( $args{src} && $args{src}->{dbh} ) {
my $dbh = $args{src}->{dbh};
my $db = $args{src}->{db};
my $tbl = $args{src}->{tbl};
my $table_status;
eval {
my $sql = "SHOW TABLE STATUS FROM `$db` LIKE "
. $self->{Quoter}->literal_like($tbl);
PTDEBUG && _d($sql);
$table_status = $dbh->selectrow_hashref($sql);
};
PTDEBUG && $EVAL_ERROR && _d($EVAL_ERROR);
if ( $table_status ) {
my $n_rows = defined $table_status->{Rows} ? $table_status->{Rows}
: defined $table_status->{rows} ? $table_status->{rows}
: undef;
$small_table = 1 if defined $n_rows && $n_rows <= 100;
}
}
PTDEBUG && _d('Small table:', $small_table);
PTDEBUG && _d('Can nibble using index', $nibble_index);
return (
1,
chunk_index => $nibble_index,
key_cols => $args{tbl_struct}->{keys}->{$nibble_index}->{cols},
small_table => $small_table,
);
}
sub prepare_to_sync {
my ( $self, %args ) = @_;
my @required_args = qw(dbh db tbl tbl_struct chunk_index key_cols chunk_size
crc_col ChangeHandler);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless defined $args{$arg};
}
$self->{dbh} = $args{dbh};
$self->{tbl_struct} = $args{tbl_struct};
$self->{crc_col} = $args{crc_col};
$self->{index_hint} = $args{index_hint};
$self->{key_cols} = $args{key_cols};
($self->{chunk_size}) = $self->{TableChunker}->size_to_rows(%args);
$self->{buffer_in_mysql} = $args{buffer_in_mysql};
$self->{small_table} = $args{small_table};
$self->{ChangeHandler} = $args{ChangeHandler};
$self->{ChangeHandler}->fetch_back($args{dbh});
my %seen;
my @ucols = grep { !$seen{$_}++ } @{$args{cols}}, @{$args{key_cols}};
$args{cols} = \@ucols;
$self->{sel_stmt} = $self->{TableNibbler}->generate_asc_stmt(
%args,
index => $args{chunk_index}, # expects an index arg, not chunk_index
asc_only => 1,
);
$self->{nibble} = 0;
$self->{cached_row} = undef;
$self->{cached_nibble} = undef;
$self->{cached_boundaries} = undef;
$self->{state} = 0;
return;
}
sub uses_checksum {
return 1;
}
sub set_checksum_queries {
my ( $self, $nibble_sql, $row_sql ) = @_;
die "I need a nibble_sql argument" unless $nibble_sql;
die "I need a row_sql argument" unless $row_sql;
$self->{nibble_sql} = $nibble_sql;
$self->{row_sql} = $row_sql;
return;
}
sub prepare_sync_cycle {
my ( $self, $host ) = @_;
my $sql = q{SET @crc := '', @cnt := 0};
PTDEBUG && _d($sql);
$host->{dbh}->do($sql);
return;
}
sub get_sql {
my ( $self, %args ) = @_;
if ( $self->{state} ) {
my $q = $self->{Quoter};
return 'SELECT /*rows in nibble*/ '
. ($self->{buffer_in_mysql} ? 'SQL_BUFFER_RESULT ' : '')
. $self->{row_sql} . " AS $self->{crc_col}"
. ' FROM ' . $q->quote(@args{qw(database table)})
. ' ' . ($self->{index_hint} ? $self->{index_hint} : '')
. ' WHERE (' . $self->__get_boundaries(%args) . ')'
. ($args{where} ? " AND ($args{where})" : '')
. ' ORDER BY ' . join(', ', map {$q->quote($_) } @{$self->key_cols()});
}
else {
my $where = $self->__get_boundaries(%args);
return $self->{TableChunker}->inject_chunks(
database => $args{database},
table => $args{table},
chunks => [ $where ],
chunk_num => 0,
query => $self->{nibble_sql},
index_hint => $self->{index_hint},
where => [ $args{where} ],
);
}
}
sub __get_boundaries {
my ( $self, %args ) = @_;
my $q = $self->{Quoter};
my $s = $self->{sel_stmt};
my $lb; # Lower boundary part of WHERE
my $ub; # Upper boundary part of WHERE
my $row; # Next upper boundary row or cached_row
if ( $self->{cached_boundaries} ) {
PTDEBUG && _d('Using cached boundaries');
return $self->{cached_boundaries};
}
if ( $self->{cached_row} && $self->{cached_nibble} == $self->{nibble} ) {
PTDEBUG && _d('Using cached row for boundaries');
$row = $self->{cached_row};
}
else {
PTDEBUG && _d('Getting next upper boundary row');
my $sql;
($sql, $lb) = $self->__make_boundary_sql(%args); # $lb from outer scope!
if ( $self->{nibble} == 0 && !$self->{small_table} ) {
my $explain_index = $self->__get_explain_index($sql);
if ( lc($explain_index || '') ne lc($s->{index}) ) {
die 'Cannot nibble table '.$q->quote($args{database}, $args{table})
. " because MySQL chose "
. ($explain_index ? "the `$explain_index`" : 'no') . ' index'
. " instead of the `$s->{index}` index";
}
}
$row = $self->{dbh}->selectrow_hashref($sql);
PTDEBUG && _d($row ? 'Got a row' : "Didn't get a row");
}
if ( $row ) {
my $i = 0;
$ub = $s->{boundaries}->{'<='};
$ub =~ s/\?/$q->quote_val($row->{$s->{scols}->[$i]}, $self->{tbl_struct}->{is_numeric}->{$s->{scols}->[$i++]} || 0)/eg;
}
else {
PTDEBUG && _d('No upper boundary');
$ub = '1=1';
}
my $where = $lb ? "($lb AND $ub)" : $ub;
$self->{cached_row} = $row;
$self->{cached_nibble} = $self->{nibble};
$self->{cached_boundaries} = $where;
PTDEBUG && _d('WHERE clause:', $where);
return $where;
}
sub __make_boundary_sql {
my ( $self, %args ) = @_;
my $lb;
my $q = $self->{Quoter};
my $s = $self->{sel_stmt};
my $sql = "SELECT /*nibble boundary $self->{nibble}*/ "
. join(',', map { $q->quote($_) } @{$s->{cols}})
. " FROM " . $q->quote($args{database}, $args{table})
. ' ' . ($self->{index_hint} || '')
. ($args{where} ? " WHERE ($args{where})" : "");
if ( $self->{nibble} ) {
my $tmp = $self->{cached_row};
my $i = 0;
$lb = $s->{boundaries}->{'>'};
$lb =~ s/\?/$q->quote_val($tmp->{$s->{scols}->[$i]}, $self->{tbl_struct}->{is_numeric}->{$s->{scols}->[$i++]} || 0)/eg;
$sql .= $args{where} ? " AND $lb" : " WHERE $lb";
}
$sql .= " ORDER BY " . join(',', map { $q->quote($_) } @{$self->{key_cols}})
. ' LIMIT ' . ($self->{chunk_size} - 1) . ', 1';
PTDEBUG && _d('Lower boundary:', $lb);
PTDEBUG && _d('Next boundary sql:', $sql);
return $sql, $lb;
}
sub __get_explain_index {
my ( $self, $sql ) = @_;
return unless $sql;
my $explain;
eval {
$explain = $self->{dbh}->selectall_arrayref("EXPLAIN $sql",{Slice => {}});
};
if ( $EVAL_ERROR ) {
PTDEBUG && _d($EVAL_ERROR);
return;
}
PTDEBUG && _d('EXPLAIN key:', $explain->[0]->{key});
return $explain->[0]->{key};
}
sub same_row {
my ( $self, %args ) = @_;
my ($lr, $rr) = @args{qw(lr rr)};
if ( $self->{state} ) {
if ( $lr->{$self->{crc_col}} ne $rr->{$self->{crc_col}} ) {
$self->{ChangeHandler}->change('UPDATE', $lr, $self->key_cols());
}
}
elsif ( $lr->{cnt} != $rr->{cnt} || $lr->{crc} ne $rr->{crc} ) {
PTDEBUG && _d('Rows:', Dumper($lr, $rr));
PTDEBUG && _d('Will examine this nibble before moving to next');
$self->{state} = 1; # Must examine this nibble row-by-row
}
}
sub not_in_right {
my ( $self, %args ) = @_;
die "Called not_in_right in state 0" unless $self->{state};
$self->{ChangeHandler}->change('INSERT', $args{lr}, $self->key_cols());
}
sub not_in_left {
my ( $self, %args ) = @_;
die "Called not_in_left in state 0" unless $self->{state};
$self->{ChangeHandler}->change('DELETE', $args{rr}, $self->key_cols());
}
sub done_with_rows {
my ( $self ) = @_;
if ( $self->{state} == 1 ) {
$self->{state} = 2;
PTDEBUG && _d('Setting state =', $self->{state});
}
else {
$self->{state} = 0;
$self->{nibble}++;
delete $self->{cached_boundaries};
PTDEBUG && _d('Setting state =', $self->{state},
', nibble =', $self->{nibble});
}
}
sub done {
my ( $self ) = @_;
PTDEBUG && _d('Done with nibble', $self->{nibble});
PTDEBUG && $self->{state} && _d('Nibble differs; must examine rows');
return $self->{state} == 0 && $self->{nibble} && !$self->{cached_row};
}
sub pending_changes {
my ( $self ) = @_;
if ( $self->{state} ) {
PTDEBUG && _d('There are pending changes');
return 1;
}
else {
PTDEBUG && _d('No pending changes');
return 0;
}
}
sub key_cols {
my ( $self ) = @_;
my @cols;
if ( $self->{state} == 0 ) {
@cols = qw(chunk_num);
}
else {
@cols = @{$self->{key_cols}};
}
PTDEBUG && _d('State', $self->{state},',', 'key cols', join(', ', @cols));
return \@cols;
}
sub _d {
my ($package, undef, $line) = caller 0;
@_ = map { (my $temp = $_) =~ s/\n/\n# /g; $temp; }
map { defined $_ ? $_ : 'undef' }
@_;
print STDERR "# $package:$line $PID ", join(' ', @_), "\n";
}
1;
}
# ###########################################################################
# End TableSyncNibble package
# ###########################################################################
# ###########################################################################
# TableSyncGroupBy package
# This package is a copy without comments from the original. The original
# with comments and its test file can be found in the Bazaar repository at,
# lib/TableSyncGroupBy.pm
# t/lib/TableSyncGroupBy.t
# See https://launchpad.net/percona-toolkit for more information.
# ###########################################################################
{
package TableSyncGroupBy;
use strict;
use warnings FATAL => 'all';
use English qw(-no_match_vars);
use constant PTDEBUG => $ENV{PTDEBUG} || 0;
sub new {
my ( $class, %args ) = @_;
foreach my $arg ( qw(Quoter) ) {
die "I need a $arg argument" unless $args{$arg};
}
my $self = { %args };
return bless $self, $class;
}
sub name {
return 'GroupBy';
}
sub can_sync {
return 1; # We can sync anything.
}
sub prepare_to_sync {
my ( $self, %args ) = @_;
my @required_args = qw(tbl_struct cols ChangeHandler);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless defined $args{$arg};
}
$self->{cols} = $args{cols};
$self->{buffer_in_mysql} = $args{buffer_in_mysql};
$self->{ChangeHandler} = $args{ChangeHandler};
$self->{count_col} = '__maatkit_count';
while ( $args{tbl_struct}->{is_col}->{$self->{count_col}} ) {
$self->{count_col} = "_$self->{count_col}";
}
PTDEBUG && _d('COUNT column will be named', $self->{count_col});
$self->{done} = 0;
return;
}
sub uses_checksum {
return 0; # We don't need checksum queries.
}
sub set_checksum_queries {
return; # This shouldn't be called, but just in case.
}
sub prepare_sync_cycle {
my ( $self, $host ) = @_;
return;
}
sub get_sql {
my ( $self, %args ) = @_;
my $cols = join(', ', map { $self->{Quoter}->quote($_) } @{$self->{cols}});
return "SELECT"
. ($self->{buffer_in_mysql} ? ' SQL_BUFFER_RESULT' : '')
. " $cols, COUNT(*) AS $self->{count_col}"
. ' FROM ' . $self->{Quoter}->quote(@args{qw(database table)})
. ' WHERE ' . ( $args{where} || '1=1' )
. " GROUP BY $cols ORDER BY $cols";
}
sub same_row {
my ( $self, %args ) = @_;
my ($lr, $rr) = @args{qw(lr rr)};
my $cc = $self->{count_col};
my $lc = $lr->{$cc};
my $rc = $rr->{$cc};
my $diff = abs($lc - $rc);
return unless $diff;
$lr = { %$lr };
delete $lr->{$cc};
$rr = { %$rr };
delete $rr->{$cc};
foreach my $i ( 1 .. $diff ) {
if ( $lc > $rc ) {
$self->{ChangeHandler}->change('INSERT', $lr, $self->key_cols());
}
else {
$self->{ChangeHandler}->change('DELETE', $rr, $self->key_cols());
}
}
}
sub not_in_right {
my ( $self, %args ) = @_;
my $lr = $args{lr};
$lr = { %$lr };
my $cnt = delete $lr->{$self->{count_col}};
foreach my $i ( 1 .. $cnt ) {
$self->{ChangeHandler}->change('INSERT', $lr, $self->key_cols());
}
}
sub not_in_left {
my ( $self, %args ) = @_;
my $rr = $args{rr};
$rr = { %$rr };
my $cnt = delete $rr->{$self->{count_col}};
foreach my $i ( 1 .. $cnt ) {
$self->{ChangeHandler}->change('DELETE', $rr, $self->key_cols());
}
}
sub done_with_rows {
my ( $self ) = @_;
$self->{done} = 1;
}
sub done {
my ( $self ) = @_;
return $self->{done};
}
sub key_cols {
my ( $self ) = @_;
return $self->{cols};
}
sub pending_changes {
my ( $self ) = @_;
return;
}
sub _d {
my ($package, undef, $line) = caller 0;
@_ = map { (my $temp = $_) =~ s/\n/\n# /g; $temp; }
map { defined $_ ? $_ : 'undef' }
@_;
print STDERR "# $package:$line $PID ", join(' ', @_), "\n";
}
1;
}
# ###########################################################################
# End TableSyncGroupBy package
# ###########################################################################
# ###########################################################################
# TableSyncer package
# This package is a copy without comments from the original. The original
# with comments and its test file can be found in the Bazaar repository at,
# lib/TableSyncer.pm
# t/lib/TableSyncer.t
# See https://launchpad.net/percona-toolkit for more information.
# ###########################################################################
{
package TableSyncer;
use strict;
use warnings FATAL => 'all';
use English qw(-no_match_vars);
use constant PTDEBUG => $ENV{PTDEBUG} || 0;
use Data::Dumper;
$Data::Dumper::Indent = 1;
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Quotekeys = 0;
sub new {
my ( $class, %args ) = @_;
my @required_args = qw(MasterSlave Quoter VersionParser TableChecksum Retry);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless defined $args{$arg};
}
my $self = { %args };
return bless $self, $class;
}
sub get_best_plugin {
my ( $self, %args ) = @_;
foreach my $arg ( qw(plugins tbl_struct) ) {
die "I need a $arg argument" unless $args{$arg};
}
PTDEBUG && _d('Getting best plugin');
foreach my $plugin ( @{$args{plugins}} ) {
PTDEBUG && _d('Trying plugin', $plugin->name);
my ($can_sync, %plugin_args) = $plugin->can_sync(%args);
if ( $can_sync ) {
PTDEBUG && _d('Can sync with', $plugin->name, Dumper(\%plugin_args));
return $plugin, %plugin_args;
}
}
PTDEBUG && _d('No plugin can sync the table');
return;
}
sub sync_table {
my ( $self, %args ) = @_;
my @required_args = qw(plugins src dst tbl_struct cols chunk_size
RowDiff ChangeHandler);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
PTDEBUG && _d('Syncing table with args:',
map { "$_: " . Dumper($args{$_}) }
qw(plugins src dst tbl_struct cols chunk_size));
my ($plugins, $src, $dst, $tbl_struct, $cols, $chunk_size, $rd, $ch)
= @args{@required_args};
my $dp = $self->{DSNParser};
$args{trace} = 1 unless defined $args{trace};
if ( $args{bidirectional} && $args{ChangeHandler}->{queue} ) {
die "Queueing does not work with bidirectional syncing";
}
$args{index_hint} = 1 unless defined $args{index_hint};
$args{lock} ||= 0;
$args{wait} ||= 0;
$args{transaction} ||= 0;
$args{timeout_ok} ||= 0;
my $q = $self->{Quoter};
my $vp = $self->{VersionParser};
my ($plugin, %plugin_args) = $self->get_best_plugin(%args);
die "No plugin can sync $src->{db}.$src->{tbl}" unless $plugin;
my $crc_col = '__crc';
while ( $tbl_struct->{is_col}->{$crc_col} ) {
$crc_col = "_$crc_col"; # Prepend more _ until not a column.
}
PTDEBUG && _d('CRC column:', $crc_col);
my $index_hint;
my $hint = ($vp->version_ge($src->{dbh}, '4.0.9')
&& $vp->version_ge($dst->{dbh}, '4.0.9') ? 'FORCE' : 'USE')
. ' INDEX';
if ( $args{chunk_index} ) {
PTDEBUG && _d('Using given chunk index for index hint');
$index_hint = "$hint (" . $q->quote($args{chunk_index}) . ")";
}
elsif ( $plugin_args{chunk_index} && $args{index_hint} ) {
PTDEBUG && _d('Using chunk index chosen by plugin for index hint');
$index_hint = "$hint (" . $q->quote($plugin_args{chunk_index}) . ")";
}
PTDEBUG && _d('Index hint:', $index_hint);
eval {
$plugin->prepare_to_sync(
%args,
%plugin_args,
dbh => $src->{dbh},
db => $src->{db},
tbl => $src->{tbl},
crc_col => $crc_col,
index_hint => $index_hint,
);
};
if ( $EVAL_ERROR ) {
die 'Failed to prepare TableSync', $plugin->name, ' plugin: ',
$EVAL_ERROR;
}
if ( $plugin->uses_checksum() ) {
eval {
my ($chunk_sql, $row_sql) = $self->make_checksum_queries(%args);
$plugin->set_checksum_queries($chunk_sql, $row_sql);
};
if ( $EVAL_ERROR ) {
die "Failed to make checksum queries: $EVAL_ERROR";
}
}
if ( $args{dry_run} ) {
return $ch->get_changes(), ALGORITHM => $plugin->name;
}
eval {
$src->{dbh}->do("USE `$src->{db}`");
$dst->{dbh}->do("USE `$dst->{db}`");
};
if ( $EVAL_ERROR ) {
die "Failed to USE database on source or destination: $EVAL_ERROR";
}
PTDEBUG && _d('left dbh', $src->{dbh});
PTDEBUG && _d('right dbh', $dst->{dbh});
chomp(my $hostname = `hostname`);
my $trace_msg
= $args{trace} ? "src_db:$src->{db} src_tbl:$src->{tbl} "
. ($dp && $src->{dsn} ? "src_dsn:".$dp->as_string($src->{dsn}) : "")
. " dst_db:$dst->{db} dst_tbl:$dst->{tbl} "
. ($dp && $dst->{dsn} ? "dst_dsn:".$dp->as_string($dst->{dsn}) : "")
. " " . join(" ", map { "$_:" . ($args{$_} || 0) }
qw(lock transaction changing_src replicate bidirectional))
. " pid:$PID "
. ($ENV{USER} ? "user:$ENV{USER} " : "")
. ($hostname ? "host:$hostname" : "")
: "";
PTDEBUG && _d("Binlog trace message:", $trace_msg);
$self->lock_and_wait(%args, lock_level => 2); # per-table lock
my $callback = $args{callback};
my $cycle = 0;
while ( !$plugin->done() ) {
PTDEBUG && _d('Beginning sync cycle', $cycle);
my $src_sql = $plugin->get_sql(
database => $src->{db},
table => $src->{tbl},
where => $args{where},
);
my $dst_sql = $plugin->get_sql(
database => $dst->{db},
table => $dst->{tbl},
where => $args{where},
);
if ( $args{transaction} ) {
if ( $args{bidirectional} ) {
$src_sql .= ' FOR UPDATE';
$dst_sql .= ' FOR UPDATE';
}
elsif ( $args{changing_src} ) {
$src_sql .= ' FOR UPDATE';
$dst_sql .= ' LOCK IN SHARE MODE';
}
else {
$src_sql .= ' LOCK IN SHARE MODE';
$dst_sql .= ' FOR UPDATE';
}
}
PTDEBUG && _d('src:', $src_sql);
PTDEBUG && _d('dst:', $dst_sql);
$callback->($src_sql, $dst_sql) if $callback;
$plugin->prepare_sync_cycle($src);
$plugin->prepare_sync_cycle($dst);
my $src_sth = $src->{dbh}->prepare($src_sql);
my $dst_sth = $dst->{dbh}->prepare($dst_sql);
if ( $args{buffer_to_client} ) {
$src_sth->{mysql_use_result} = 1;
$dst_sth->{mysql_use_result} = 1;
}
my $executed_src = 0;
if ( !$cycle || !$plugin->pending_changes() ) {
$executed_src
= $self->lock_and_wait(%args, src_sth => $src_sth, lock_level => 1);
}
$src_sth->execute() unless $executed_src;
$dst_sth->execute();
$rd->compare_sets(
left_sth => $src_sth,
right_sth => $dst_sth,
left_dbh => $src->{dbh},
right_dbh => $dst->{dbh},
syncer => $plugin,
tbl_struct => $tbl_struct,
);
$ch->process_rows(1, $trace_msg);
PTDEBUG && _d('Finished sync cycle', $cycle);
$cycle++;
}
$ch->process_rows(0, $trace_msg);
$self->unlock(%args, lock_level => 2);
return $ch->get_changes(), ALGORITHM => $plugin->name;
}
sub make_checksum_queries {
my ( $self, %args ) = @_;
my @required_args = qw(src dst tbl_struct);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my ($src, $dst, $tbl_struct) = @args{@required_args};
my $checksum = $self->{TableChecksum};
my $src_algo = $checksum->best_algorithm(
algorithm => 'BIT_XOR',
dbh => $src->{dbh},
where => 1,
chunk => 1,
count => 1,
);
my $dst_algo = $checksum->best_algorithm(
algorithm => 'BIT_XOR',
dbh => $dst->{dbh},
where => 1,
chunk => 1,
count => 1,
);
if ( $src_algo ne $dst_algo ) {
die "Source and destination checksum algorithms are different: ",
"$src_algo on source, $dst_algo on destination"
}
PTDEBUG && _d('Chosen algo:', $src_algo);
my $src_func = $checksum->choose_hash_func(dbh => $src->{dbh}, %args);
my $dst_func = $checksum->choose_hash_func(dbh => $dst->{dbh}, %args);
if ( $src_func ne $dst_func ) {
die "Source and destination hash functions are different: ",
"$src_func on source, $dst_func on destination";
}
PTDEBUG && _d('Chosen hash func:', $src_func);
my $crc_wid = $checksum->get_crc_wid($src->{dbh}, $src_func);
my ($crc_type) = $checksum->get_crc_type($src->{dbh}, $src_func);
my $opt_slice;
if ( $src_algo eq 'BIT_XOR' && $crc_type !~ m/int$/ ) {
$opt_slice = $checksum->optimize_xor(
dbh => $src->{dbh},
function => $src_func
);
}
my $chunk_sql = $checksum->make_checksum_query(
%args,
db => $src->{db},
tbl => $src->{tbl},
algorithm => $src_algo,
function => $src_func,
crc_wid => $crc_wid,
crc_type => $crc_type,
opt_slice => $opt_slice,
replicate => undef, # replicate means something different to this sub
); # than what we use it for; do not pass it!
PTDEBUG && _d('Chunk sql:', $chunk_sql);
my $row_sql = $checksum->make_row_checksum(
%args,
function => $src_func,
);
PTDEBUG && _d('Row sql:', $row_sql);
return $chunk_sql, $row_sql;
}
sub lock_table {
my ( $self, $dbh, $where, $db_tbl, $mode ) = @_;
my $query = "LOCK TABLES $db_tbl $mode";
PTDEBUG && _d($query);
$dbh->do($query);
PTDEBUG && _d('Acquired table lock on', $where, 'in', $mode, 'mode');
}
sub unlock {
my ( $self, %args ) = @_;
foreach my $arg ( qw(src dst lock transaction lock_level) ) {
die "I need a $arg argument" unless defined $args{$arg};
}
my $src = $args{src};
my $dst = $args{dst};
return unless $args{lock} && $args{lock} <= $args{lock_level};
foreach my $dbh ( $src->{dbh}, $dst->{dbh} ) {
if ( $args{transaction} ) {
PTDEBUG && _d('Committing', $dbh);
$dbh->commit();
}
else {
my $sql = 'UNLOCK TABLES';
PTDEBUG && _d($dbh, $sql);
$dbh->do($sql);
}
}
return;
}
sub lock_and_wait {
my ( $self, %args ) = @_;
my $result = 0;
foreach my $arg ( qw(src dst lock lock_level) ) {
die "I need a $arg argument" unless defined $args{$arg};
}
my $src = $args{src};
my $dst = $args{dst};
return unless $args{lock} && $args{lock} == $args{lock_level};
PTDEBUG && _d('lock and wait, lock level', $args{lock});
foreach my $dbh ( $src->{dbh}, $dst->{dbh} ) {
if ( $args{transaction} ) {
PTDEBUG && _d('Committing', $dbh);
$dbh->commit();
}
else {
my $sql = 'UNLOCK TABLES';
PTDEBUG && _d($dbh, $sql);
$dbh->do($sql);
}
}
if ( $args{lock} == 3 ) {
my $sql = 'FLUSH TABLES WITH READ LOCK';
PTDEBUG && _d($src->{dbh}, $sql);
$src->{dbh}->do($sql);
}
else {
if ( $args{transaction} ) {
if ( $args{src_sth} ) {
PTDEBUG && _d('Executing statement on source to lock rows');
my $sql = "START TRANSACTION /*!40108 WITH CONSISTENT SNAPSHOT */";
PTDEBUG && _d($src->{dbh}, $sql);
$src->{dbh}->do($sql);
$args{src_sth}->execute();
$result = 1;
}
}
else {
$self->lock_table($src->{dbh}, 'source',
$self->{Quoter}->quote($src->{db}, $src->{tbl}),
$args{changing_src} ? 'WRITE' : 'READ');
}
}
eval {
if ( my $timeout = $args{wait} ) {
my $ms = $self->{MasterSlave};
my $tries = $args{wait_retry_args}->{tries} || 3;
my $wait;
$self->{Retry}->retry(
tries => $tries,
wait => sub { sleep $args{wait_retry_args}->{wait} || 10 },
try => sub {
my ( %args ) = @_;
if ( $args{tryno} > 1 ) {
warn "Retrying MASTER_POS_WAIT() for --wait $timeout...";
}
$wait = $ms->wait_for_master(
master_status => $ms->get_master_status($src->{misc_dbh}),
slave_dbh => $dst->{dbh},
timeout => $timeout,
);
if ( defined $wait->{result} && $wait->{result} != -1 ) {
return; # slave caught up
}
die; # call fail
},
fail => sub {
my (%args) = @_;
if ( !defined $wait->{result} ) {
my $msg;
if ( $wait->{waited} ) {
$msg = "The slave was stopped while waiting with "
. "MASTER_POS_WAIT().";
}
else {
$msg = "MASTER_POS_WAIT() returned NULL. Verify that "
. "the slave is running.";
}
if ( $tries - $args{tryno} ) {
$msg .= " Sleeping $wait seconds then retrying "
. ($tries - $args{tryno}) . " more times.";
}
warn "$msg\n";
return 1; # call wait, call try
}
elsif ( $wait->{result} == -1 ) {
return 0; # call final_fail
}
},
final_fail => sub {
die "Slave did not catch up to its master after $tries attempts "
. "of waiting $timeout seconds with MASTER_POS_WAIT. "
. "Check that the slave is running, increase the --wait "
. "time, or disable this feature by specifying --wait 0.";
},
); # retry MasterSlave::wait_for_master()
}
if ( $args{changing_src} ) {
PTDEBUG && _d('Not locking destination because changing source ',
'(syncing via replication or sync-to-master)');
}
else {
if ( $args{lock} == 3 ) {
my $sql = 'FLUSH TABLES WITH READ LOCK';
PTDEBUG && _d($dst->{dbh}, ',', $sql);
$dst->{dbh}->do($sql);
}
elsif ( !$args{transaction} ) {
$self->lock_table($dst->{dbh}, 'dest',
$self->{Quoter}->quote($dst->{db}, $dst->{tbl}),
$args{execute} ? 'WRITE' : 'READ');
}
}
};
if ( $EVAL_ERROR ) {
if ( $args{src_sth}->{Active} ) {
$args{src_sth}->finish();
}
foreach my $dbh ( $src->{dbh}, $dst->{dbh}, $src->{misc_dbh} ) {
next unless $dbh;
PTDEBUG && _d('Caught error, unlocking/committing on', $dbh);
$dbh->do('UNLOCK TABLES');
$dbh->commit() unless $dbh->{AutoCommit};
}
die $EVAL_ERROR;
}
return $result;
}
sub have_all_privs {
my ( $self, $dbh, $db, $tbl ) = @_;
my $db_tbl = $self->{Quoter}->quote($db, $tbl);
my $sql = "SHOW FULL COLUMNS FROM $db_tbl";
PTDEBUG && _d('Permissions check:', $sql);
my $cols = $dbh->selectall_arrayref($sql, {Slice => {}});
my ($hdr_name) = grep { m/privileges/i } keys %{$cols->[0]};
my $privs = $cols->[0]->{$hdr_name};
$sql = "DELETE FROM $db_tbl LIMIT 0"; # FULL COLUMNS doesn't show all privs
PTDEBUG && _d('Permissions check:', $sql);
eval { $dbh->do($sql); };
my $can_delete = $EVAL_ERROR ? 0 : 1;
PTDEBUG && _d('User privs on', $db_tbl, ':', $privs,
($can_delete ? 'delete' : ''));
if ( $privs =~ m/select/ && $privs =~ m/insert/ && $privs =~ m/update/
&& $can_delete ) {
PTDEBUG && _d('User has all privs');
return 1;
}
PTDEBUG && _d('User does not have all privs');
return 0;
}
sub _d {
my ($package, undef, $line) = caller 0;
@_ = map { (my $temp = $_) =~ s/\n/\n# /g; $temp; }
map { defined $_ ? $_ : 'undef' }
@_;
print STDERR "# $package:$line $PID ", join(' ', @_), "\n";
}
1;
}
# ###########################################################################
# End TableSyncer package
# ###########################################################################
# ###########################################################################
# TableNibbler package
# This package is a copy without comments from the original. The original
# with comments and its test file can be found in the Bazaar repository at,
# lib/TableNibbler.pm
# t/lib/TableNibbler.t
# See https://launchpad.net/percona-toolkit for more information.
# ###########################################################################
{
package TableNibbler;
use strict;
use warnings FATAL => 'all';
use English qw(-no_match_vars);
use constant PTDEBUG => $ENV{PTDEBUG} || 0;
sub new {
my ( $class, %args ) = @_;
my @required_args = qw(TableParser Quoter);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my $self = { %args };
return bless $self, $class;
}
sub generate_asc_stmt {
my ( $self, %args ) = @_;
my @required_args = qw(tbl_struct index);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless defined $args{$arg};
}
my ($tbl_struct, $index) = @args{@required_args};
my @cols = $args{cols} ? @{$args{cols}} : @{$tbl_struct->{cols}};
my $q = $self->{Quoter};
die "Index '$index' does not exist in table"
unless exists $tbl_struct->{keys}->{$index};
PTDEBUG && _d('Will ascend index', $index);
my @asc_cols = @{$tbl_struct->{keys}->{$index}->{cols}};
if ( $args{asc_first} ) {
PTDEBUG && _d('Ascending only first column');
@asc_cols = $asc_cols[0];
}
elsif ( my $n = $args{n_index_cols} ) {
$n = scalar @asc_cols if $n > @asc_cols;
PTDEBUG && _d('Ascending only first', $n, 'columns');
@asc_cols = @asc_cols[0..($n-1)];
}
PTDEBUG && _d('Will ascend columns', join(', ', @asc_cols));
my @asc_slice;
my %col_posn = do { my $i = 0; map { $_ => $i++ } @cols };
foreach my $col ( @asc_cols ) {
if ( !exists $col_posn{$col} ) {
push @cols, $col;
$col_posn{$col} = $#cols;
}
push @asc_slice, $col_posn{$col};
}
PTDEBUG && _d('Will ascend, in ordinal position:', join(', ', @asc_slice));
my $asc_stmt = {
cols => \@cols,
index => $index,
where => '',
slice => [],
scols => [],
};
if ( @asc_slice ) {
my $cmp_where;
foreach my $cmp ( qw(< <= >= >) ) {
$cmp_where = $self->generate_cmp_where(
type => $cmp,
slice => \@asc_slice,
cols => \@cols,
quoter => $q,
is_nullable => $tbl_struct->{is_nullable},
);
$asc_stmt->{boundaries}->{$cmp} = $cmp_where->{where};
}
my $cmp = $args{asc_only} ? '>' : '>=';
$asc_stmt->{where} = $asc_stmt->{boundaries}->{$cmp};
$asc_stmt->{slice} = $cmp_where->{slice};
$asc_stmt->{scols} = $cmp_where->{scols};
}
return $asc_stmt;
}
sub generate_cmp_where {
my ( $self, %args ) = @_;
foreach my $arg ( qw(type slice cols is_nullable) ) {
die "I need a $arg arg" unless defined $args{$arg};
}
my @slice = @{$args{slice}};
my @cols = @{$args{cols}};
my $is_nullable = $args{is_nullable};
my $type = $args{type};
my $q = $self->{Quoter};
(my $cmp = $type) =~ s/=//;
my @r_slice; # Resulting slice columns, by ordinal
my @r_scols; # Ditto, by name
my @clauses;
foreach my $i ( 0 .. $#slice ) {
my @clause;
foreach my $j ( 0 .. $i - 1 ) {
my $ord = $slice[$j];
my $col = $cols[$ord];
my $quo = $q->quote($col);
if ( $is_nullable->{$col} ) {
push @clause, "((? IS NULL AND $quo IS NULL) OR ($quo = ?))";
push @r_slice, $ord, $ord;
push @r_scols, $col, $col;
}
else {
push @clause, "$quo = ?";
push @r_slice, $ord;
push @r_scols, $col;
}
}
my $ord = $slice[$i];
my $col = $cols[$ord];
my $quo = $q->quote($col);
my $end = $i == $#slice; # Last clause of the whole group.
if ( $is_nullable->{$col} ) {
if ( $type =~ m/=/ && $end ) {
push @clause, "(? IS NULL OR $quo $type ?)";
}
elsif ( $type =~ m/>/ ) {
push @clause, "((? IS NULL AND $quo IS NOT NULL) OR ($quo $cmp ?))";
}
else { # If $type =~ m/</ ) {
push @clause, "((? IS NOT NULL AND $quo IS NULL) OR ($quo $cmp ?))";
}
push @r_slice, $ord, $ord;
push @r_scols, $col, $col;
}
else {
push @r_slice, $ord;
push @r_scols, $col;
push @clause, ($type =~ m/=/ && $end ? "$quo $type ?" : "$quo $cmp ?");
}
push @clauses, '(' . join(' AND ', @clause) . ')';
}
my $result = '(' . join(' OR ', @clauses) . ')';
my $where = {
slice => \@r_slice,
scols => \@r_scols,
where => $result,
};
return $where;
}
sub generate_del_stmt {
my ( $self, %args ) = @_;
my $tbl = $args{tbl_struct};
my @cols = $args{cols} ? @{$args{cols}} : ();
my $tp = $self->{TableParser};
my $q = $self->{Quoter};
my @del_cols;
my @del_slice;
my $index = $tp->find_best_index($tbl, $args{index});
die "Cannot find an ascendable index in table" unless $index;
if ( $index ) {
@del_cols = @{$tbl->{keys}->{$index}->{cols}};
}
else {
@del_cols = @{$tbl->{cols}};
}
PTDEBUG && _d('Columns needed for DELETE:', join(', ', @del_cols));
my %col_posn = do { my $i = 0; map { $_ => $i++ } @cols };
foreach my $col ( @del_cols ) {
if ( !exists $col_posn{$col} ) {
push @cols, $col;
$col_posn{$col} = $#cols;
}
push @del_slice, $col_posn{$col};
}
PTDEBUG && _d('Ordinals needed for DELETE:', join(', ', @del_slice));
my $del_stmt = {
cols => \@cols,
index => $index,
where => '',
slice => [],
scols => [],
};
my @clauses;
foreach my $i ( 0 .. $#del_slice ) {
my $ord = $del_slice[$i];
my $col = $cols[$ord];
my $quo = $q->quote($col);
if ( $tbl->{is_nullable}->{$col} ) {
push @clauses, "((? IS NULL AND $quo IS NULL) OR ($quo = ?))";
push @{$del_stmt->{slice}}, $ord, $ord;
push @{$del_stmt->{scols}}, $col, $col;
}
else {
push @clauses, "$quo = ?";
push @{$del_stmt->{slice}}, $ord;
push @{$del_stmt->{scols}}, $col;
}
}
$del_stmt->{where} = '(' . join(' AND ', @clauses) . ')';
return $del_stmt;
}
sub generate_ins_stmt {
my ( $self, %args ) = @_;
foreach my $arg ( qw(ins_tbl sel_cols) ) {
die "I need a $arg argument" unless $args{$arg};
}
my $ins_tbl = $args{ins_tbl};
my @sel_cols = @{$args{sel_cols}};
die "You didn't specify any SELECT columns" unless @sel_cols;
my @ins_cols;
my @ins_slice;
for my $i ( 0..$#sel_cols ) {
next unless $ins_tbl->{is_col}->{$sel_cols[$i]};
push @ins_cols, $sel_cols[$i];
push @ins_slice, $i;
}
return {
cols => \@ins_cols,
slice => \@ins_slice,
};
}
sub _d {
my ($package, undef, $line) = caller 0;
@_ = map { (my $temp = $_) =~ s/\n/\n# /g; $temp; }
map { defined $_ ? $_ : 'undef' }
@_;
print STDERR "# $package:$line $PID ", join(' ', @_), "\n";
}
1;
}
# ###########################################################################
# End TableNibbler package
# ###########################################################################
# ###########################################################################
# MasterSlave package
# This package is a copy without comments from the original. The original
# with comments and its test file can be found in the Bazaar repository at,
# lib/MasterSlave.pm
# t/lib/MasterSlave.t
# See https://launchpad.net/percona-toolkit for more information.
# ###########################################################################
{
package MasterSlave;
use strict;
use warnings FATAL => 'all';
use English qw(-no_match_vars);
use constant PTDEBUG => $ENV{PTDEBUG} || 0;
sub new {
my ( $class, %args ) = @_;
my $self = {
%args,
replication_thread => {},
};
return bless $self, $class;
}
sub get_slaves {
my ($self, %args) = @_;
my @required_args = qw(make_cxn OptionParser DSNParser Quoter);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my ($make_cxn, $o, $dp) = @args{@required_args};
my $slaves = [];
my $method = $o->get('recursion-method');
PTDEBUG && _d('Slave recursion method:', $method);
if ( !$method || $method =~ m/processlist|hosts/i ) {
my @required_args = qw(dbh dsn);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my ($dbh, $dsn) = @args{@required_args};
$self->recurse_to_slaves(
{ dbh => $dbh,
dsn => $dsn,
dsn_parser => $dp,
recurse => $o->get('recurse'),
method => $o->get('recursion-method'),
callback => sub {
my ( $dsn, $dbh, $level, $parent ) = @_;
return unless $level;
PTDEBUG && _d('Found slave:', $dp->as_string($dsn));
push @$slaves, $make_cxn->(dsn => $dsn, dbh => $dbh);
return;
},
}
);
}
elsif ( $method =~ m/^dsn=/i ) {
my ($dsn_table_dsn) = $method =~ m/^dsn=(.+)/i;
$slaves = $self->get_cxn_from_dsn_table(
%args,
dsn_table_dsn => $dsn_table_dsn,
);
}
elsif ( $method =~ m/none/i ) {
PTDEBUG && _d('Not getting to slaves');
}
else {
die "Invalid --recursion-method: $method. Valid values are: "
. "dsn=DSN, hosts, or processlist.\n";
}
return $slaves;
}
sub recurse_to_slaves {
my ( $self, $args, $level ) = @_;
$level ||= 0;
my $dp = $args->{dsn_parser};
my $dsn = $args->{dsn};
if ( lc($args->{method} || '') eq 'none' ) {
PTDEBUG && _d('Not recursing to slaves');
return;
}
my $dbh;
eval {
$dbh = $args->{dbh} || $dp->get_dbh(
$dp->get_cxn_params($dsn), { AutoCommit => 1 });
PTDEBUG && _d('Connected to', $dp->as_string($dsn));
};
if ( $EVAL_ERROR ) {
print STDERR "Cannot connect to ", $dp->as_string($dsn), "\n"
or die "Cannot print: $OS_ERROR";
return;
}
my $sql = 'SELECT @@SERVER_ID';
PTDEBUG && _d($sql);
my ($id) = $dbh->selectrow_array($sql);
PTDEBUG && _d('Working on server ID', $id);
my $master_thinks_i_am = $dsn->{server_id};
if ( !defined $id
|| ( defined $master_thinks_i_am && $master_thinks_i_am != $id )
|| $args->{server_ids_seen}->{$id}++
) {
PTDEBUG && _d('Server ID seen, or not what master said');
if ( $args->{skip_callback} ) {
$args->{skip_callback}->($dsn, $dbh, $level, $args->{parent});
}
return;
}
$args->{callback}->($dsn, $dbh, $level, $args->{parent});
if ( !defined $args->{recurse} || $level < $args->{recurse} ) {
my @slaves =
grep { !$_->{master_id} || $_->{master_id} == $id } # Only my slaves.
$self->find_slave_hosts($dp, $dbh, $dsn, $args->{method});
foreach my $slave ( @slaves ) {
PTDEBUG && _d('Recursing from',
$dp->as_string($dsn), 'to', $dp->as_string($slave));
$self->recurse_to_slaves(
{ %$args, dsn => $slave, dbh => undef, parent => $dsn }, $level + 1 );
}
}
}
sub find_slave_hosts {
my ( $self, $dsn_parser, $dbh, $dsn, $method ) = @_;
my @methods = qw(processlist hosts);
if ( $method ) {
@methods = grep { $_ ne $method } @methods;
unshift @methods, $method;
}
else {
if ( ($dsn->{P} || 3306) != 3306 ) {
PTDEBUG && _d('Port number is non-standard; using only hosts method');
@methods = qw(hosts);
}
}
PTDEBUG && _d('Looking for slaves on', $dsn_parser->as_string($dsn),
'using methods', @methods);
my @slaves;
METHOD:
foreach my $method ( @methods ) {
my $find_slaves = "_find_slaves_by_$method";
PTDEBUG && _d('Finding slaves with', $find_slaves);
@slaves = $self->$find_slaves($dsn_parser, $dbh, $dsn);
last METHOD if @slaves;
}
PTDEBUG && _d('Found', scalar(@slaves), 'slaves');
return @slaves;
}
sub _find_slaves_by_processlist {
my ( $self, $dsn_parser, $dbh, $dsn ) = @_;
my @slaves = map {
my $slave = $dsn_parser->parse("h=$_", $dsn);
$slave->{source} = 'processlist';
$slave;
}
grep { $_ }
map {
my ( $host ) = $_->{host} =~ m/^([^:]+):/;
if ( $host eq 'localhost' ) {
$host = '127.0.0.1'; # Replication never uses sockets.
}
$host;
} $self->get_connected_slaves($dbh);
return @slaves;
}
sub _find_slaves_by_hosts {
my ( $self, $dsn_parser, $dbh, $dsn ) = @_;
my @slaves;
my $sql = 'SHOW SLAVE HOSTS';
PTDEBUG && _d($dbh, $sql);
@slaves = @{$dbh->selectall_arrayref($sql, { Slice => {} })};
if ( @slaves ) {
PTDEBUG && _d('Found some SHOW SLAVE HOSTS info');
@slaves = map {
my %hash;
@hash{ map { lc $_ } keys %$_ } = values %$_;
my $spec = "h=$hash{host},P=$hash{port}"
. ( $hash{user} ? ",u=$hash{user}" : '')
. ( $hash{password} ? ",p=$hash{password}" : '');
my $dsn = $dsn_parser->parse($spec, $dsn);
$dsn->{server_id} = $hash{server_id};
$dsn->{master_id} = $hash{master_id};
$dsn->{source} = 'hosts';
$dsn;
} @slaves;
}
return @slaves;
}
sub get_connected_slaves {
my ( $self, $dbh ) = @_;
my $show = "SHOW GRANTS FOR ";
my $user = 'CURRENT_USER()';
my $vp = $self->{VersionParser};
if ( $vp && !$vp->version_ge($dbh, '4.1.2') ) {
$user = $dbh->selectrow_arrayref('SELECT USER()')->[0];
$user =~ s/([^@]+)@(.+)/'$1'\@'$2'/;
}
my $sql = $show . $user;
PTDEBUG && _d($dbh, $sql);
my $proc;
eval {
$proc = grep {
m/ALL PRIVILEGES.*?\*\.\*|PROCESS/
} @{$dbh->selectcol_arrayref($sql)};
};
if ( $EVAL_ERROR ) {
if ( $EVAL_ERROR =~ m/no such grant defined for user/ ) {
PTDEBUG && _d('Retrying SHOW GRANTS without host; error:',
$EVAL_ERROR);
($user) = split('@', $user);
$sql = $show . $user;
PTDEBUG && _d($sql);
eval {
$proc = grep {
m/ALL PRIVILEGES.*?\*\.\*|PROCESS/
} @{$dbh->selectcol_arrayref($sql)};
};
}
die "Failed to $sql: $EVAL_ERROR" if $EVAL_ERROR;
}
if ( !$proc ) {
die "You do not have the PROCESS privilege";
}
$sql = 'SHOW PROCESSLIST';
PTDEBUG && _d($dbh, $sql);
grep { $_->{command} =~ m/Binlog Dump/i }
map { # Lowercase the column names
my %hash;
@hash{ map { lc $_ } keys %$_ } = values %$_;
\%hash;
}
@{$dbh->selectall_arrayref($sql, { Slice => {} })};
}
sub is_master_of {
my ( $self, $master, $slave ) = @_;
my $master_status = $self->get_master_status($master)
or die "The server specified as a master is not a master";
my $slave_status = $self->get_slave_status($slave)
or die "The server specified as a slave is not a slave";
my @connected = $self->get_connected_slaves($master)
or die "The server specified as a master has no connected slaves";
my (undef, $port) = $master->selectrow_array("SHOW VARIABLES LIKE 'port'");
if ( $port != $slave_status->{master_port} ) {
die "The slave is connected to $slave_status->{master_port} "
. "but the master's port is $port";
}
if ( !grep { $slave_status->{master_user} eq $_->{user} } @connected ) {
die "I don't see any slave I/O thread connected with user "
. $slave_status->{master_user};
}
if ( ($slave_status->{slave_io_state} || '')
eq 'Waiting for master to send event' )
{
my ( $master_log_name, $master_log_num )
= $master_status->{file} =~ m/^(.*?)\.0*([1-9][0-9]*)$/;
my ( $slave_log_name, $slave_log_num )
= $slave_status->{master_log_file} =~ m/^(.*?)\.0*([1-9][0-9]*)$/;
if ( $master_log_name ne $slave_log_name
|| abs($master_log_num - $slave_log_num) > 1 )
{
die "The slave thinks it is reading from "
. "$slave_status->{master_log_file}, but the "
. "master is writing to $master_status->{file}";
}
}
return 1;
}
sub get_master_dsn {
my ( $self, $dbh, $dsn, $dsn_parser ) = @_;
my $master = $self->get_slave_status($dbh) or return undef;
my $spec = "h=$master->{master_host},P=$master->{master_port}";
return $dsn_parser->parse($spec, $dsn);
}
sub get_slave_status {
my ( $self, $dbh ) = @_;
if ( !$self->{not_a_slave}->{$dbh} ) {
my $sth = $self->{sths}->{$dbh}->{SLAVE_STATUS}
||= $dbh->prepare('SHOW SLAVE STATUS');
PTDEBUG && _d($dbh, 'SHOW SLAVE STATUS');
$sth->execute();
my ($ss) = @{$sth->fetchall_arrayref({})};
if ( $ss && %$ss ) {
$ss = { map { lc($_) => $ss->{$_} } keys %$ss }; # lowercase the keys
return $ss;
}
PTDEBUG && _d('This server returns nothing for SHOW SLAVE STATUS');
$self->{not_a_slave}->{$dbh}++;
}
}
sub get_master_status {
my ( $self, $dbh ) = @_;
if ( $self->{not_a_master}->{$dbh} ) {
PTDEBUG && _d('Server on dbh', $dbh, 'is not a master');
return;
}
my $sth = $self->{sths}->{$dbh}->{MASTER_STATUS}
||= $dbh->prepare('SHOW MASTER STATUS');
PTDEBUG && _d($dbh, 'SHOW MASTER STATUS');
$sth->execute();
my ($ms) = @{$sth->fetchall_arrayref({})};
PTDEBUG && _d(
$ms ? map { "$_=" . (defined $ms->{$_} ? $ms->{$_} : '') } keys %$ms
: '');
if ( !$ms || scalar keys %$ms < 2 ) {
PTDEBUG && _d('Server on dbh', $dbh, 'does not seem to be a master');
$self->{not_a_master}->{$dbh}++;
}
return { map { lc($_) => $ms->{$_} } keys %$ms }; # lowercase the keys
}
sub wait_for_master {
my ( $self, %args ) = @_;
my @required_args = qw(master_status slave_dbh);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my ($master_status, $slave_dbh) = @args{@required_args};
my $timeout = $args{timeout} || 60;
my $result;
my $waited;
if ( $master_status ) {
my $sql = "SELECT MASTER_POS_WAIT('$master_status->{file}', "
. "$master_status->{position}, $timeout)";
PTDEBUG && _d($slave_dbh, $sql);
my $start = time;
($result) = $slave_dbh->selectrow_array($sql);
$waited = time - $start;
PTDEBUG && _d('Result of waiting:', $result);
PTDEBUG && _d("Waited", $waited, "seconds");
}
else {
PTDEBUG && _d('Not waiting: this server is not a master');
}
return {
result => $result,
waited => $waited,
};
}
sub stop_slave {
my ( $self, $dbh ) = @_;
my $sth = $self->{sths}->{$dbh}->{STOP_SLAVE}
||= $dbh->prepare('STOP SLAVE');
PTDEBUG && _d($dbh, $sth->{Statement});
$sth->execute();
}
sub start_slave {
my ( $self, $dbh, $pos ) = @_;
if ( $pos ) {
my $sql = "START SLAVE UNTIL MASTER_LOG_FILE='$pos->{file}', "
. "MASTER_LOG_POS=$pos->{position}";
PTDEBUG && _d($dbh, $sql);
$dbh->do($sql);
}
else {
my $sth = $self->{sths}->{$dbh}->{START_SLAVE}
||= $dbh->prepare('START SLAVE');
PTDEBUG && _d($dbh, $sth->{Statement});
$sth->execute();
}
}
sub catchup_to_master {
my ( $self, $slave, $master, $timeout ) = @_;
$self->stop_slave($master);
$self->stop_slave($slave);
my $slave_status = $self->get_slave_status($slave);
my $slave_pos = $self->repl_posn($slave_status);
my $master_status = $self->get_master_status($master);
my $master_pos = $self->repl_posn($master_status);
PTDEBUG && _d('Master position:', $self->pos_to_string($master_pos),
'Slave position:', $self->pos_to_string($slave_pos));
my $result;
if ( $self->pos_cmp($slave_pos, $master_pos) < 0 ) {
PTDEBUG && _d('Waiting for slave to catch up to master');
$self->start_slave($slave, $master_pos);
$result = $self->wait_for_master(
master_status => $master_status,
slave_dbh => $slave,
timeout => $timeout,
master_status => $master_status
);
if ( !defined $result->{result} ) {
$slave_status = $self->get_slave_status($slave);
if ( !$self->slave_is_running($slave_status) ) {
PTDEBUG && _d('Master position:',
$self->pos_to_string($master_pos),
'Slave position:', $self->pos_to_string($slave_pos));
$slave_pos = $self->repl_posn($slave_status);
if ( $self->pos_cmp($slave_pos, $master_pos) != 0 ) {
die "MASTER_POS_WAIT() returned NULL but slave has not "
. "caught up to master";
}
PTDEBUG && _d('Slave is caught up to master and stopped');
}
else {
die "Slave has not caught up to master and it is still running";
}
}
}
else {
PTDEBUG && _d("Slave is already caught up to master");
}
return $result;
}
sub catchup_to_same_pos {
my ( $self, $s1_dbh, $s2_dbh ) = @_;
$self->stop_slave($s1_dbh);
$self->stop_slave($s2_dbh);
my $s1_status = $self->get_slave_status($s1_dbh);
my $s2_status = $self->get_slave_status($s2_dbh);
my $s1_pos = $self->repl_posn($s1_status);
my $s2_pos = $self->repl_posn($s2_status);
if ( $self->pos_cmp($s1_pos, $s2_pos) < 0 ) {
$self->start_slave($s1_dbh, $s2_pos);
}
elsif ( $self->pos_cmp($s2_pos, $s1_pos) < 0 ) {
$self->start_slave($s2_dbh, $s1_pos);
}
$s1_status = $self->get_slave_status($s1_dbh);
$s2_status = $self->get_slave_status($s2_dbh);
$s1_pos = $self->repl_posn($s1_status);
$s2_pos = $self->repl_posn($s2_status);
if ( $self->slave_is_running($s1_status)
|| $self->slave_is_running($s2_status)
|| $self->pos_cmp($s1_pos, $s2_pos) != 0)
{
die "The servers aren't both stopped at the same position";
}
}
sub slave_is_running {
my ( $self, $slave_status ) = @_;
return ($slave_status->{slave_sql_running} || 'No') eq 'Yes';
}
sub has_slave_updates {
my ( $self, $dbh ) = @_;
my $sql = q{SHOW VARIABLES LIKE 'log_slave_updates'};
PTDEBUG && _d($dbh, $sql);
my ($name, $value) = $dbh->selectrow_array($sql);
return $value && $value =~ m/^(1|ON)$/;
}
sub repl_posn {
my ( $self, $status ) = @_;
if ( exists $status->{file} && exists $status->{position} ) {
return {
file => $status->{file},
position => $status->{position},
};
}
else {
return {
file => $status->{relay_master_log_file},
position => $status->{exec_master_log_pos},
};
}
}
sub get_slave_lag {
my ( $self, $dbh ) = @_;
my $stat = $self->get_slave_status($dbh);
return unless $stat; # server is not a slave
return $stat->{seconds_behind_master};
}
sub pos_cmp {
my ( $self, $a, $b ) = @_;
return $self->pos_to_string($a) cmp $self->pos_to_string($b);
}
sub short_host {
my ( $self, $dsn ) = @_;
my ($host, $port);
if ( $dsn->{master_host} ) {
$host = $dsn->{master_host};
$port = $dsn->{master_port};
}
else {
$host = $dsn->{h};
$port = $dsn->{P};
}
return ($host || '[default]') . ( ($port || 3306) == 3306 ? '' : ":$port" );
}
sub is_replication_thread {
my ( $self, $query, %args ) = @_;
return unless $query;
my $type = lc($args{type} || 'all');
die "Invalid type: $type"
unless $type =~ m/^binlog_dump|slave_io|slave_sql|all$/i;
my $match = 0;
if ( $type =~ m/binlog_dump|all/i ) {
$match = 1
if ($query->{Command} || $query->{command} || '') eq "Binlog Dump";
}
if ( !$match ) {
if ( ($query->{User} || $query->{user} || '') eq "system user" ) {
PTDEBUG && _d("Slave replication thread");
if ( $type ne 'all' ) {
my $state = $query->{State} || $query->{state} || '';
if ( $state =~ m/^init|end$/ ) {
PTDEBUG && _d("Special state:", $state);
$match = 1;
}
else {
my ($slave_sql) = $state =~ m/
^(Waiting\sfor\sthe\snext\sevent
|Reading\sevent\sfrom\sthe\srelay\slog
|Has\sread\sall\srelay\slog;\swaiting
|Making\stemp\sfile
|Waiting\sfor\sslave\smutex\son\sexit)/xi;
$match = $type eq 'slave_sql' && $slave_sql ? 1
: $type eq 'slave_io' && !$slave_sql ? 1
: 0;
}
}
else {
$match = 1;
}
}
else {
PTDEBUG && _d('Not system user');
}
if ( !defined $args{check_known_ids} || $args{check_known_ids} ) {
my $id = $query->{Id} || $query->{id};
if ( $match ) {
$self->{replication_thread}->{$id} = 1;
}
else {
if ( $self->{replication_thread}->{$id} ) {
PTDEBUG && _d("Thread ID is a known replication thread ID");
$match = 1;
}
}
}
}
PTDEBUG && _d('Matches', $type, 'replication thread:',
($match ? 'yes' : 'no'), '; match:', $match);
return $match;
}
sub get_replication_filters {
my ( $self, %args ) = @_;
my @required_args = qw(dbh);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my ($dbh) = @args{@required_args};
my %filters = ();
my $status = $self->get_master_status($dbh);
if ( $status ) {
map { $filters{$_} = $status->{$_} }
grep { defined $status->{$_} && $status->{$_} ne '' }
qw(
binlog_do_db
binlog_ignore_db
);
}
$status = $self->get_slave_status($dbh);
if ( $status ) {
map { $filters{$_} = $status->{$_} }
grep { defined $status->{$_} && $status->{$_} ne '' }
qw(
replicate_do_db
replicate_ignore_db
replicate_do_table
replicate_ignore_table
replicate_wild_do_table
replicate_wild_ignore_table
);
my $sql = "SHOW VARIABLES LIKE 'slave_skip_errors'";
PTDEBUG && _d($dbh, $sql);
my $row = $dbh->selectrow_arrayref($sql);
$filters{slave_skip_errors} = $row->[1] if $row->[1] && $row->[1] ne 'OFF';
}
return \%filters;
}
sub pos_to_string {
my ( $self, $pos ) = @_;
my $fmt = '%s/%020d';
return sprintf($fmt, @{$pos}{qw(file position)});
}
sub reset_known_replication_threads {
my ( $self ) = @_;
$self->{replication_thread} = {};
return;
}
sub get_cxn_from_dsn_table {
my ($self, %args) = @_;
my @required_args = qw(dsn_table_dsn make_cxn DSNParser Quoter);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my ($dsn_table_dsn, $make_cxn, $dp, $q) = @args{@required_args};
PTDEBUG && _d('DSN table DSN:', $dsn_table_dsn);
my $dsn = $dp->parse($dsn_table_dsn);
my $dsn_table;
if ( $dsn->{D} && $dsn->{t} ) {
$dsn_table = $q->quote($dsn->{D}, $dsn->{t});
}
elsif ( $dsn->{t} && $dsn->{t} =~ m/\./ ) {
$dsn_table = $q->quote($q->split_unquote($dsn->{t}));
}
else {
die "DSN table DSN does not specify a database (D) "
. "or a database-qualified table (t)";
}
my $dsn_tbl_cxn = $make_cxn->(dsn => $dsn);
my $dbh = $dsn_tbl_cxn->connect();
my $sql = "SELECT dsn FROM $dsn_table ORDER BY id";
PTDEBUG && _d($sql);
my $dsn_strings = $dbh->selectcol_arrayref($sql);
my @cxn;
if ( $dsn_strings ) {
foreach my $dsn_string ( @$dsn_strings ) {
PTDEBUG && _d('DSN from DSN table:', $dsn_string);
push @cxn, $make_cxn->(dsn_string => $dsn_string);
}
}
return \@cxn;
}
sub _d {
my ($package, undef, $line) = caller 0;
@_ = map { (my $temp = $_) =~ s/\n/\n# /g; $temp; }
map { defined $_ ? $_ : 'undef' }
@_;
print STDERR "# $package:$line $PID ", join(' ', @_), "\n";
}
1;
}
# ###########################################################################
# End MasterSlave package
# ###########################################################################
# ###########################################################################
# Daemon package
# This package is a copy without comments from the original. The original
# with comments and its test file can be found in the Bazaar repository at,
# lib/Daemon.pm
# t/lib/Daemon.t
# See https://launchpad.net/percona-toolkit for more information.
# ###########################################################################
{
package Daemon;
use strict;
use warnings FATAL => 'all';
use English qw(-no_match_vars);
use constant PTDEBUG => $ENV{PTDEBUG} || 0;
use POSIX qw(setsid);
sub new {
my ( $class, %args ) = @_;
foreach my $arg ( qw(o) ) {
die "I need a $arg argument" unless $args{$arg};
}
my $o = $args{o};
my $self = {
o => $o,
log_file => $o->has('log') ? $o->get('log') : undef,
PID_file => $o->has('pid') ? $o->get('pid') : undef,
};
check_PID_file(undef, $self->{PID_file});
PTDEBUG && _d('Daemonized child will log to', $self->{log_file});
return bless $self, $class;
}
sub daemonize {
my ( $self ) = @_;
PTDEBUG && _d('About to fork and daemonize');
defined (my $pid = fork()) or die "Cannot fork: $OS_ERROR";
if ( $pid ) {
PTDEBUG && _d('Parent PID', $PID, 'exiting after forking child PID',$pid);
exit;
}
PTDEBUG && _d('Daemonizing child PID', $PID);
$self->{PID_owner} = $PID;
$self->{child} = 1;
POSIX::setsid() or die "Cannot start a new session: $OS_ERROR";
chdir '/' or die "Cannot chdir to /: $OS_ERROR";
$self->_make_PID_file();
$OUTPUT_AUTOFLUSH = 1;
PTDEBUG && _d('Redirecting STDIN to /dev/null');
close STDIN;
open STDIN, '/dev/null'
or die "Cannot reopen STDIN to /dev/null: $OS_ERROR";
if ( $self->{log_file} ) {
PTDEBUG && _d('Redirecting STDOUT and STDERR to', $self->{log_file});
close STDOUT;
open STDOUT, '>>', $self->{log_file}
or die "Cannot open log file $self->{log_file}: $OS_ERROR";
close STDERR;
open STDERR, ">&STDOUT"
or die "Cannot dupe STDERR to STDOUT: $OS_ERROR";
}
else {
if ( -t STDOUT ) {
PTDEBUG && _d('No log file and STDOUT is a terminal;',
'redirecting to /dev/null');
close STDOUT;
open STDOUT, '>', '/dev/null'
or die "Cannot reopen STDOUT to /dev/null: $OS_ERROR";
}
if ( -t STDERR ) {
PTDEBUG && _d('No log file and STDERR is a terminal;',
'redirecting to /dev/null');
close STDERR;
open STDERR, '>', '/dev/null'
or die "Cannot reopen STDERR to /dev/null: $OS_ERROR";
}
}
return;
}
sub check_PID_file {
my ( $self, $file ) = @_;
my $PID_file = $self ? $self->{PID_file} : $file;
PTDEBUG && _d('Checking PID file', $PID_file);
if ( $PID_file && -f $PID_file ) {
my $pid;
eval { chomp($pid = `cat $PID_file`); };
die "Cannot cat $PID_file: $OS_ERROR" if $EVAL_ERROR;
PTDEBUG && _d('PID file exists; it contains PID', $pid);
if ( $pid ) {
my $pid_is_alive = kill 0, $pid;
if ( $pid_is_alive ) {
die "The PID file $PID_file already exists "
. " and the PID that it contains, $pid, is running";
}
else {
warn "Overwriting PID file $PID_file because the PID that it "
. "contains, $pid, is not running";
}
}
else {
die "The PID file $PID_file already exists but it does not "
. "contain a PID";
}
}
else {
PTDEBUG && _d('No PID file');
}
return;
}
sub make_PID_file {
my ( $self ) = @_;
if ( exists $self->{child} ) {
die "Do not call Daemon::make_PID_file() for daemonized scripts";
}
$self->_make_PID_file();
$self->{PID_owner} = $PID;
return;
}
sub _make_PID_file {
my ( $self ) = @_;
my $PID_file = $self->{PID_file};
if ( !$PID_file ) {
PTDEBUG && _d('No PID file to create');
return;
}
$self->check_PID_file();
open my $PID_FH, '>', $PID_file
or die "Cannot open PID file $PID_file: $OS_ERROR";
print $PID_FH $PID
or die "Cannot print to PID file $PID_file: $OS_ERROR";
close $PID_FH
or die "Cannot close PID file $PID_file: $OS_ERROR";
PTDEBUG && _d('Created PID file:', $self->{PID_file});
return;
}
sub _remove_PID_file {
my ( $self ) = @_;
if ( $self->{PID_file} && -f $self->{PID_file} ) {
unlink $self->{PID_file}
or warn "Cannot remove PID file $self->{PID_file}: $OS_ERROR";
PTDEBUG && _d('Removed PID file');
}
else {
PTDEBUG && _d('No PID to remove');
}
return;
}
sub DESTROY {
my ( $self ) = @_;
$self->_remove_PID_file() if ($self->{PID_owner} || 0) == $PID;
return;
}
sub _d {
my ($package, undef, $line) = caller 0;
@_ = map { (my $temp = $_) =~ s/\n/\n# /g; $temp; }
map { defined $_ ? $_ : 'undef' }
@_;
print STDERR "# $package:$line $PID ", join(' ', @_), "\n";
}
1;
}
# ###########################################################################
# End Daemon package
# ###########################################################################
# ###########################################################################
# SchemaIterator package
# This package is a copy without comments from the original. The original
# with comments and its test file can be found in the Bazaar repository at,
# lib/SchemaIterator.pm
# t/lib/SchemaIterator.t
# See https://launchpad.net/percona-toolkit for more information.
# ###########################################################################
{
package SchemaIterator;
use strict;
use warnings FATAL => 'all';
use English qw(-no_match_vars);
use constant PTDEBUG => $ENV{PTDEBUG} || 0;
use Data::Dumper;
$Data::Dumper::Indent = 1;
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Quotekeys = 0;
my $open_comment = qr{/\*!\d{5} };
my $tbl_name = qr{
CREATE\s+
(?:TEMPORARY\s+)?
TABLE\s+
(?:IF NOT EXISTS\s+)?
([^\(]+)
}x;
sub new {
my ( $class, %args ) = @_;
my @required_args = qw(OptionParser TableParser Quoter);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my ($file_itr, $dbh) = @args{qw(file_itr dbh)};
die "I need either a dbh or file_itr argument"
if (!$dbh && !$file_itr) || ($dbh && $file_itr);
my %resume;
if ( my $table = $args{resume} ) {
PTDEBUG && _d('Will resume from or after', $table);
my ($db, $tbl) = $args{Quoter}->split_unquote($table);
die "Resume table must be database-qualified: $table"
unless $db && $tbl;
$resume{db} = $db;
$resume{tbl} = $tbl;
}
my $self = {
%args,
resume => \%resume,
filters => _make_filters(%args),
};
return bless $self, $class;
}
sub _make_filters {
my ( %args ) = @_;
my @required_args = qw(OptionParser Quoter);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my ($o, $q) = @args{@required_args};
my %filters;
my @simple_filters = qw(
databases tables engines
ignore-databases ignore-tables ignore-engines);
FILTER:
foreach my $filter ( @simple_filters ) {
if ( $o->has($filter) ) {
my $objs = $o->get($filter);
next FILTER unless $objs && scalar keys %$objs;
my $is_table = $filter =~ m/table/ ? 1 : 0;
foreach my $obj ( keys %$objs ) {
die "Undefined value for --$filter" unless $obj;
$obj = lc $obj;
if ( $is_table ) {
my ($db, $tbl) = $q->split_unquote($obj);
$db ||= '*';
PTDEBUG && _d('Filter', $filter, 'value:', $db, $tbl);
$filters{$filter}->{$tbl} = $db;
}
else { # database
PTDEBUG && _d('Filter', $filter, 'value:', $obj);
$filters{$filter}->{$obj} = 1;
}
}
}
}
my @regex_filters = qw(
databases-regex tables-regex
ignore-databases-regex ignore-tables-regex);
REGEX_FILTER:
foreach my $filter ( @regex_filters ) {
if ( $o->has($filter) ) {
my $pat = $o->get($filter);
next REGEX_FILTER unless $pat;
$filters{$filter} = qr/$pat/;
PTDEBUG && _d('Filter', $filter, 'value:', $filters{$filter});
}
}
PTDEBUG && _d('Schema object filters:', Dumper(\%filters));
return \%filters;
}
sub next {
my ( $self ) = @_;
if ( !$self->{initialized} ) {
$self->{initialized} = 1;
if ( $self->{resume}->{tbl}
&& !$self->table_is_allowed(@{$self->{resume}}{qw(db tbl)}) ) {
PTDEBUG && _d('Will resume after',
join('.', @{$self->{resume}}{qw(db tbl)}));
$self->{resume}->{after} = 1;
}
}
my $schema_obj;
if ( $self->{file_itr} ) {
$schema_obj= $self->_iterate_files();
}
else { # dbh
$schema_obj= $self->_iterate_dbh();
}
if ( $schema_obj ) {
if ( my $schema = $self->{Schema} ) {
$schema->add_schema_object($schema_obj);
}
PTDEBUG && _d('Next schema object:',
$schema_obj->{db}, $schema_obj->{tbl});
}
return $schema_obj;
}
sub _iterate_files {
my ( $self ) = @_;
if ( !$self->{fh} ) {
my ($fh, $file) = $self->{file_itr}->();
if ( !$fh ) {
PTDEBUG && _d('No more files to iterate');
return;
}
$self->{fh} = $fh;
$self->{file} = $file;
}
my $fh = $self->{fh};
PTDEBUG && _d('Getting next schema object from', $self->{file});
local $INPUT_RECORD_SEPARATOR = '';
CHUNK:
while (defined(my $chunk = <$fh>)) {
if ($chunk =~ m/Database: (\S+)/) {
my $db = $1; # XXX
$db =~ s/^`//; # strip leading `
$db =~ s/`$//; # and trailing `
if ( $self->database_is_allowed($db)
&& $self->_resume_from_database($db) ) {
$self->{db} = $db;
}
}
elsif ($self->{db} && $chunk =~ m/CREATE TABLE/) {
if ($chunk =~ m/DROP VIEW IF EXISTS/) {
PTDEBUG && _d('Table is a VIEW, skipping');
next CHUNK;
}
my ($tbl) = $chunk =~ m/$tbl_name/;
$tbl =~ s/^\s*`//;
$tbl =~ s/`\s*$//;
if ( $self->_resume_from_table($tbl)
&& $self->table_is_allowed($self->{db}, $tbl) ) {
my ($ddl) = $chunk =~ m/^(?:$open_comment)?(CREATE TABLE.+?;)$/ms;
if ( !$ddl ) {
warn "Failed to parse CREATE TABLE from\n" . $chunk;
next CHUNK;
}
$ddl =~ s/ \*\/;\Z/;/; # remove end of version comment
my $tbl_struct = $self->{TableParser}->parse($ddl);
if ( $self->engine_is_allowed($tbl_struct->{engine}) ) {
return {
db => $self->{db},
tbl => $tbl,
name => $self->{Quoter}->quote($self->{db}, $tbl),
ddl => $ddl,
tbl_struct => $tbl_struct,
};
}
}
}
} # CHUNK
PTDEBUG && _d('No more schema objects in', $self->{file});
close $self->{fh};
$self->{fh} = undef;
return $self->_iterate_files();
}
sub _iterate_dbh {
my ( $self ) = @_;
my $q = $self->{Quoter};
my $tp = $self->{TableParser};
my $dbh = $self->{dbh};
PTDEBUG && _d('Getting next schema object from dbh', $dbh);
if ( !defined $self->{dbs} ) {
my $sql = 'SHOW DATABASES';
PTDEBUG && _d($sql);
my @dbs = grep { $self->database_is_allowed($_) }
@{$dbh->selectcol_arrayref($sql)};
PTDEBUG && _d('Found', scalar @dbs, 'databases');
$self->{dbs} = \@dbs;
}
if ( !$self->{db} ) {
do {
$self->{db} = shift @{$self->{dbs}};
} until $self->_resume_from_database($self->{db});
PTDEBUG && _d('Next database:', $self->{db});
return unless $self->{db};
}
if ( !defined $self->{tbls} ) {
my $sql = 'SHOW /*!50002 FULL*/ TABLES FROM ' . $q->quote($self->{db});
PTDEBUG && _d($sql);
my @tbls = map {
$_->[0]; # (tbl, type)
}
grep {
my ($tbl, $type) = @$_;
(!$type || ($type ne 'VIEW'))
&& $self->_resume_from_table($tbl)
&& $self->table_is_allowed($self->{db}, $tbl);
}
@{$dbh->selectall_arrayref($sql)};
PTDEBUG && _d('Found', scalar @tbls, 'tables in database', $self->{db});
$self->{tbls} = \@tbls;
}
while ( my $tbl = shift @{$self->{tbls}} ) {
my $ddl = $tp->get_create_table($dbh, $self->{db}, $tbl);
my $tbl_struct = $tp->parse($ddl);
if ( $self->engine_is_allowed($tbl_struct->{engine}) ) {
return {
db => $self->{db},
tbl => $tbl,
name => $q->quote($self->{db}, $tbl),
ddl => $ddl,
tbl_struct => $tbl_struct,
};
}
}
PTDEBUG && _d('No more tables in database', $self->{db});
$self->{db} = undef;
$self->{tbls} = undef;
return $self->_iterate_dbh();
}
sub database_is_allowed {
my ( $self, $db ) = @_;
die "I need a db argument" unless $db;
$db = lc $db;
my $filter = $self->{filters};
if ( $db =~ m/information_schema|performance_schema|lost\+found/ ) {
PTDEBUG && _d('Database', $db, 'is a system database, ignoring');
return 0;
}
if ( $self->{filters}->{'ignore-databases'}->{$db} ) {
PTDEBUG && _d('Database', $db, 'is in --ignore-databases list');
return 0;
}
if ( $filter->{'ignore-databases-regex'}
&& $db =~ $filter->{'ignore-databases-regex'} ) {
PTDEBUG && _d('Database', $db, 'matches --ignore-databases-regex');
return 0;
}
if ( $filter->{'databases'}
&& !$filter->{'databases'}->{$db} ) {
PTDEBUG && _d('Database', $db, 'is not in --databases list, ignoring');
return 0;
}
if ( $filter->{'databases-regex'}
&& $db !~ $filter->{'databases-regex'} ) {
PTDEBUG && _d('Database', $db, 'does not match --databases-regex, ignoring');
return 0;
}
return 1;
}
sub table_is_allowed {
my ( $self, $db, $tbl ) = @_;
die "I need a db argument" unless $db;
die "I need a tbl argument" unless $tbl;
$db = lc $db;
$tbl = lc $tbl;
my $filter = $self->{filters};
if ( $db eq 'mysql' && ($tbl eq 'general_log' || $tbl eq 'slow_log') ) {
return 0;
}
if ( $filter->{'ignore-tables'}->{$tbl}
&& ($filter->{'ignore-tables'}->{$tbl} eq '*'
|| $filter->{'ignore-tables'}->{$tbl} eq $db) ) {
PTDEBUG && _d('Table', $tbl, 'is in --ignore-tables list');
return 0;
}
if ( $filter->{'ignore-tables-regex'}
&& $tbl =~ $filter->{'ignore-tables-regex'} ) {
PTDEBUG && _d('Table', $tbl, 'matches --ignore-tables-regex');
return 0;
}
if ( $filter->{'tables'}
&& !$filter->{'tables'}->{$tbl} ) {
PTDEBUG && _d('Table', $tbl, 'is not in --tables list, ignoring');
return 0;
}
if ( $filter->{'tables-regex'}
&& $tbl !~ $filter->{'tables-regex'} ) {
PTDEBUG && _d('Table', $tbl, 'does not match --tables-regex, ignoring');
return 0;
}
if ( $filter->{'tables'}
&& $filter->{'tables'}->{$tbl}
&& $filter->{'tables'}->{$tbl} ne '*'
&& $filter->{'tables'}->{$tbl} ne $db ) {
PTDEBUG && _d('Table', $tbl, 'is only allowed in database',
$filter->{'tables'}->{$tbl});
return 0;
}
return 1;
}
sub engine_is_allowed {
my ( $self, $engine ) = @_;
if ( !$engine ) {
PTDEBUG && _d('No engine specified; allowing the table');
return 1;
}
$engine = lc $engine;
my $filter = $self->{filters};
if ( $filter->{'ignore-engines'}->{$engine} ) {
PTDEBUG && _d('Engine', $engine, 'is in --ignore-databases list');
return 0;
}
if ( $filter->{'engines'}
&& !$filter->{'engines'}->{$engine} ) {
PTDEBUG && _d('Engine', $engine, 'is not in --engines list, ignoring');
return 0;
}
return 1;
}
sub _resume_from_database {
my ($self, $db) = @_;
return 1 unless $self->{resume}->{db};
if ( $db eq $self->{resume}->{db} ) {
PTDEBUG && _d('At resume db', $db);
delete $self->{resume}->{db};
return 1;
}
return 0;
}
sub _resume_from_table {
my ($self, $tbl) = @_;
return 1 unless $self->{resume}->{tbl};
if ( $tbl eq $self->{resume}->{tbl} ) {
if ( !$self->{resume}->{after} ) {
PTDEBUG && _d('Resuming from table', $tbl);
delete $self->{resume}->{tbl};
return 1;
}
else {
PTDEBUG && _d('Resuming after table', $tbl);
delete $self->{resume}->{tbl};
}
}
return 0;
}
sub _d {
my ($package, undef, $line) = caller 0;
@_ = map { (my $temp = $_) =~ s/\n/\n# /g; $temp; }
map { defined $_ ? $_ : 'undef' }
@_;
print STDERR "# $package:$line $PID ", join(' ', @_), "\n";
}
1;
}
# ###########################################################################
# End SchemaIterator package
# ###########################################################################
# ###########################################################################
# Transformers package
# This package is a copy without comments from the original. The original
# with comments and its test file can be found in the Bazaar repository at,
# lib/Transformers.pm
# t/lib/Transformers.t
# See https://launchpad.net/percona-toolkit for more information.
# ###########################################################################
{
package Transformers;
use strict;
use warnings FATAL => 'all';
use English qw(-no_match_vars);
use constant PTDEBUG => $ENV{PTDEBUG} || 0;
use Time::Local qw(timegm timelocal);
use Digest::MD5 qw(md5_hex);
use B qw();
require Exporter;
our @ISA = qw(Exporter);
our %EXPORT_TAGS = ();
our @EXPORT = ();
our @EXPORT_OK = qw(
micro_t
percentage_of
secs_to_time
time_to_secs
shorten
ts
parse_timestamp
unix_timestamp
any_unix_timestamp
make_checksum
crc32
encode_json
);
our $mysql_ts = qr/(\d\d)(\d\d)(\d\d) +(\d+):(\d+):(\d+)(\.\d+)?/;
our $proper_ts = qr/(\d\d\d\d)-(\d\d)-(\d\d)[T ](\d\d):(\d\d):(\d\d)(\.\d+)?/;
our $n_ts = qr/(\d{1,5})([shmd]?)/; # Limit \d{1,5} because \d{6} looks
sub micro_t {
my ( $t, %args ) = @_;
my $p_ms = defined $args{p_ms} ? $args{p_ms} : 0; # precision for ms vals
my $p_s = defined $args{p_s} ? $args{p_s} : 0; # precision for s vals
my $f;
$t = 0 if $t < 0;
$t = sprintf('%.17f', $t) if $t =~ /e/;
$t =~ s/\.(\d{1,6})\d*/\.$1/;
if ($t > 0 && $t <= 0.000999) {
$f = ($t * 1000000) . 'us';
}
elsif ($t >= 0.001000 && $t <= 0.999999) {
$f = sprintf("%.${p_ms}f", $t * 1000);
$f = ($f * 1) . 'ms'; # * 1 to remove insignificant zeros
}
elsif ($t >= 1) {
$f = sprintf("%.${p_s}f", $t);
$f = ($f * 1) . 's'; # * 1 to remove insignificant zeros
}
else {
$f = 0; # $t should = 0 at this point
}
return $f;
}
sub percentage_of {
my ( $is, $of, %args ) = @_;
my $p = $args{p} || 0; # float precision
my $fmt = $p ? "%.${p}f" : "%d";
return sprintf $fmt, ($is * 100) / ($of ||= 1);
}
sub secs_to_time {
my ( $secs, $fmt ) = @_;
$secs ||= 0;
return '00:00' unless $secs;
$fmt ||= $secs >= 86_400 ? 'd'
: $secs >= 3_600 ? 'h'
: 'm';
return
$fmt eq 'd' ? sprintf(
"%d+%02d:%02d:%02d",
int($secs / 86_400),
int(($secs % 86_400) / 3_600),
int(($secs % 3_600) / 60),
$secs % 60)
: $fmt eq 'h' ? sprintf(
"%02d:%02d:%02d",
int(($secs % 86_400) / 3_600),
int(($secs % 3_600) / 60),
$secs % 60)
: sprintf(
"%02d:%02d",
int(($secs % 3_600) / 60),
$secs % 60);
}
sub time_to_secs {
my ( $val, $default_suffix ) = @_;
die "I need a val argument" unless defined $val;
my $t = 0;
my ( $prefix, $num, $suffix ) = $val =~ m/([+-]?)(\d+)([a-z])?$/;
$suffix = $suffix || $default_suffix || 's';
if ( $suffix =~ m/[smhd]/ ) {
$t = $suffix eq 's' ? $num * 1 # Seconds
: $suffix eq 'm' ? $num * 60 # Minutes
: $suffix eq 'h' ? $num * 3600 # Hours
: $num * 86400; # Days
$t *= -1 if $prefix && $prefix eq '-';
}
else {
die "Invalid suffix for $val: $suffix";
}
return $t;
}
sub shorten {
my ( $num, %args ) = @_;
my $p = defined $args{p} ? $args{p} : 2; # float precision
my $d = defined $args{d} ? $args{d} : 1_024; # divisor
my $n = 0;
my @units = ('', qw(k M G T P E Z Y));
while ( $num >= $d && $n < @units - 1 ) {
$num /= $d;
++$n;
}
return sprintf(
$num =~ m/\./ || $n
? "%.${p}f%s"
: '%d',
$num, $units[$n]);
}
sub ts {
my ( $time, $gmt ) = @_;
my ( $sec, $min, $hour, $mday, $mon, $year )
= $gmt ? gmtime($time) : localtime($time);
$mon += 1;
$year += 1900;
my $val = sprintf("%d-%02d-%02dT%02d:%02d:%02d",
$year, $mon, $mday, $hour, $min, $sec);
if ( my ($us) = $time =~ m/(\.\d+)$/ ) {
$us = sprintf("%.6f", $us);
$us =~ s/^0\././;
$val .= $us;
}
return $val;
}
sub parse_timestamp {
my ( $val ) = @_;
if ( my($y, $m, $d, $h, $i, $s, $f)
= $val =~ m/^$mysql_ts$/ )
{
return sprintf "%d-%02d-%02d %02d:%02d:"
. (defined $f ? '%09.6f' : '%02d'),
$y + 2000, $m, $d, $h, $i, (defined $f ? $s + $f : $s);
}
return $val;
}
sub unix_timestamp {
my ( $val, $gmt ) = @_;
if ( my($y, $m, $d, $h, $i, $s, $us) = $val =~ m/^$proper_ts$/ ) {
$val = $gmt
? timegm($s, $i, $h, $d, $m - 1, $y)
: timelocal($s, $i, $h, $d, $m - 1, $y);
if ( defined $us ) {
$us = sprintf('%.6f', $us);
$us =~ s/^0\././;
$val .= $us;
}
}
return $val;
}
sub any_unix_timestamp {
my ( $val, $callback ) = @_;
if ( my ($n, $suffix) = $val =~ m/^$n_ts$/ ) {
$n = $suffix eq 's' ? $n # Seconds
: $suffix eq 'm' ? $n * 60 # Minutes
: $suffix eq 'h' ? $n * 3600 # Hours
: $suffix eq 'd' ? $n * 86400 # Days
: $n; # default: Seconds
PTDEBUG && _d('ts is now - N[shmd]:', $n);
return time - $n;
}
elsif ( $val =~ m/^\d{9,}/ ) {
PTDEBUG && _d('ts is already a unix timestamp');
return $val;
}
elsif ( my ($ymd, $hms) = $val =~ m/^(\d{6})(?:\s+(\d+:\d+:\d+))?/ ) {
PTDEBUG && _d('ts is MySQL slow log timestamp');
$val .= ' 00:00:00' unless $hms;
return unix_timestamp(parse_timestamp($val));
}
elsif ( ($ymd, $hms) = $val =~ m/^(\d{4}-\d\d-\d\d)(?:[T ](\d+:\d+:\d+))?/) {
PTDEBUG && _d('ts is properly formatted timestamp');
$val .= ' 00:00:00' unless $hms;
return unix_timestamp($val);
}
else {
PTDEBUG && _d('ts is MySQL expression');
return $callback->($val) if $callback && ref $callback eq 'CODE';
}
PTDEBUG && _d('Unknown ts type:', $val);
return;
}
sub make_checksum {
my ( $val ) = @_;
my $checksum = uc substr(md5_hex($val), -16);
PTDEBUG && _d($checksum, 'checksum for', $val);
return $checksum;
}
sub crc32 {
my ( $string ) = @_;
return unless $string;
my $poly = 0xEDB88320;
my $crc = 0xFFFFFFFF;
foreach my $char ( split(//, $string) ) {
my $comp = ($crc ^ ord($char)) & 0xFF;
for ( 1 .. 8 ) {
$comp = $comp & 1 ? $poly ^ ($comp >> 1) : $comp >> 1;
}
$crc = (($crc >> 8) & 0x00FFFFFF) ^ $comp;
}
return $crc ^ 0xFFFFFFFF;
}
my $got_json = eval { require JSON };
sub encode_json {
return JSON::encode_json(@_) if $got_json;
my ( $data ) = @_;
return (object_to_json($data) || '');
}
sub object_to_json {
my ($obj) = @_;
my $type = ref($obj);
if($type eq 'HASH'){
return hash_to_json($obj);
}
elsif($type eq 'ARRAY'){
return array_to_json($obj);
}
else {
return value_to_json($obj);
}
}
sub hash_to_json {
my ($obj) = @_;
my @res;
for my $k ( sort { $a cmp $b } keys %$obj ) {
push @res, string_to_json( $k )
. ":"
. ( object_to_json( $obj->{$k} ) || value_to_json( $obj->{$k} ) );
}
return '{' . ( @res ? join( ",", @res ) : '' ) . '}';
}
sub array_to_json {
my ($obj) = @_;
my @res;
for my $v (@$obj) {
push @res, object_to_json($v) || value_to_json($v);
}
return '[' . ( @res ? join( ",", @res ) : '' ) . ']';
}
sub value_to_json {
my ($value) = @_;
return 'null' if(!defined $value);
my $b_obj = B::svref_2object(\$value); # for round trip problem
my $flags = $b_obj->FLAGS;
return $value # as is
if $flags & ( B::SVp_IOK | B::SVp_NOK ) and !( $flags & B::SVp_POK ); # SvTYPE is IV or NV?
my $type = ref($value);
if( !$type ) {
return string_to_json($value);
}
else {
return 'null';
}
}
my %esc = (
"\n" => '\n',
"\r" => '\r',
"\t" => '\t',
"\f" => '\f',
"\b" => '\b',
"\"" => '\"',
"\\" => '\\\\',
"\'" => '\\\'',
);
sub string_to_json {
my ($arg) = @_;
$arg =~ s/([\x22\x5c\n\r\t\f\b])/$esc{$1}/g;
$arg =~ s/\//\\\//g;
$arg =~ s/([\x00-\x08\x0b\x0e-\x1f])/'\\u00' . unpack('H2', $1)/eg;
utf8::upgrade($arg);
utf8::encode($arg);
return '"' . $arg . '"';
}
sub _d {
my ($package, undef, $line) = caller 0;
@_ = map { (my $temp = $_) =~ s/\n/\n# /g; $temp; }
map { defined $_ ? $_ : 'undef' }
@_;
print STDERR "# $package:$line $PID ", join(' ', @_), "\n";
}
1;
}
# ###########################################################################
# End Transformers package
# ###########################################################################
# ###########################################################################
# Retry package
# This package is a copy without comments from the original. The original
# with comments and its test file can be found in the Bazaar repository at,
# lib/Retry.pm
# t/lib/Retry.t
# See https://launchpad.net/percona-toolkit for more information.
# ###########################################################################
{
package Retry;
use strict;
use warnings FATAL => 'all';
use English qw(-no_match_vars);
use constant PTDEBUG => $ENV{PTDEBUG} || 0;
sub new {
my ( $class, %args ) = @_;
my $self = {
%args,
};
return bless $self, $class;
}
sub retry {
my ( $self, %args ) = @_;
my @required_args = qw(try fail final_fail);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
};
my ($try, $fail, $final_fail) = @args{@required_args};
my $wait = $args{wait} || sub { sleep 1; };
my $tries = $args{tries} || 3;
my $last_error;
my $tryno = 0;
TRY:
while ( ++$tryno <= $tries ) {
PTDEBUG && _d("Try", $tryno, "of", $tries);
my $result;
eval {
$result = $try->(tryno=>$tryno);
};
if ( $EVAL_ERROR ) {
PTDEBUG && _d("Try code failed:", $EVAL_ERROR);
$last_error = $EVAL_ERROR;
if ( $tryno < $tries ) { # more retries
my $retry = $fail->(tryno=>$tryno, error=>$last_error);
last TRY unless $retry;
PTDEBUG && _d("Calling wait code");
$wait->(tryno=>$tryno);
}
}
else {
PTDEBUG && _d("Try code succeeded");
return $result;
}
}
PTDEBUG && _d('Try code did not succeed');
return $final_fail->(error=>$last_error);
}
sub _d {
my ($package, undef, $line) = caller 0;
@_ = map { (my $temp = $_) =~ s/\n/\n# /g; $temp; }
map { defined $_ ? $_ : 'undef' }
@_;
print STDERR "# $package:$line $PID ", join(' ', @_), "\n";
}
1;
}
# ###########################################################################
# End Retry package
# ###########################################################################
# ###########################################################################
# This is a combination of modules and programs in one -- a runnable module.
# http://www.perl.com/pub/a/2006/07/13/lightning-articles.html?page=last
# Or, look it up in the Camel book on pages 642 and 643 in the 3rd edition.
#
# Check at the end of this package for the call to main() which actually runs
# the program.
# ###########################################################################
package pt_table_sync;
use English qw(-no_match_vars);
use List::Util qw(sum max min);
use POSIX qw(ceil);
use Data::Dumper;
Transformers->import(qw(time_to_secs any_unix_timestamp));
use constant PTDEBUG => $ENV{PTDEBUG} || 0;
$OUTPUT_AUTOFLUSH = 1;
my %dsn_for;
my $q = new Quoter();
sub main {
local @ARGV = @_; # set global ARGV for this package
# Reset global vars else tests will have weird results.
%dsn_for = ();
# ########################################################################
# Get configuration information.
# ########################################################################
my $vp = new VersionParser();
my $o = new OptionParser();
$o->get_specs();
$o->get_opts();
my $dp = $o->DSNParser();
$dp->prop('set-vars', $o->get('set-vars'));
if ( $o->get('replicate') || $o->get('sync-to-master') ) {
$o->set('wait', 60) unless $o->got('wait');
}
if ( $o->get('wait') ) {
$o->set('lock', 1) unless $o->got('lock');
}
if ( $o->get('dry-run') ) {
$o->set('verbose', 1);
}
# There's a conflict of interests: we added 't' and 'D' parts to dp,
# and there are -t and -D options (--tables, --databases), so parse_options()
# is going to return a DSN with the default values from -t and -D,
# but these are not actually be default dsn vals, they're filters.
# So we have to remove them from $dsn_defaults.
my $dsn_defaults = $dp->parse_options($o);
$dsn_defaults->{D} = undef;
$dsn_defaults->{t} = undef;
my @dsns;
while ( my $arg = shift(@ARGV) ) {
my $dsn = $dp->parse($arg, $dsns[0], $dsn_defaults);
die "You specified a t part, but not a D part in $arg"
if ($dsn->{t} && !$dsn->{D});
if ( $dsn->{D} && !$dsn->{t} ) {
die "You specified a database but not a table in $arg. Are you "
. "trying to sync only tables in the '$dsn->{D}' database? "
. "If so, use '--databases $dsn->{D}' instead.\n";
}
push @dsns, $dsn;
}
if ( !@dsns
|| (@dsns ==1 && !$o->get('replicate') && !$o->get('sync-to-master'))) {
$o->save_error('At least one DSN is required, and at least two are '
. 'required unless --sync-to-master or --replicate is specified');
}
if ( @dsns > 1 && $o->get('sync-to-master') && $o->get('replicate') ) {
$o->save_error('--sync-to-master and --replicate require only one DSN ',
' but ', scalar @dsns, ' where given');
}
if ( $o->get('lock-and-rename') ) {
if ( @dsns != 2 || !$dsns[0]->{t} || !$dsns[1]->{t} ) {
$o->save_error("--lock-and-rename requires exactly two DSNs and they "
. "must each specify a table.");
}
}
if ( $o->get('bidirectional') ) {
if ( $o->get('replicate') || $o->get('sync-to-master') ) {
$o->save_error('--bidirectional does not work with '
. '--replicate or --sync-to-master');
}
if ( @dsns < 2 ) {
$o->save_error('--bidirectional requires at least two DSNs');
}
if ( !$o->get('conflict-column') || !$o->get('conflict-comparison') ) {
$o->save_error('--bidirectional requires --conflict-column '
. 'and --conflict-comparison');
}
my $cc = $o->get('conflict-comparison');
my $cmp = $o->read_para_after(__FILE__, qr/MAGIC_comparisons/);
$cmp =~ s/ //g;
if ( $cc && $cc !~ m/$cmp/ ) {
$o->save_error("--conflict-comparison must be one of $cmp");
}
if ( $cc && $cc =~ m/equals|matches/ && !$o->get('conflict-value') ) {
$o->save_error("--conflict-comparison $cc requires --conflict-value")
}
# Override --algorithms becuase only TableSyncChunk works with
# bidirectional syncing.
$o->set('algorithms', 'Chunk');
$o->set('buffer-to-client', 0);
}
if ( $o->get('explain-hosts') ) {
foreach my $host ( @dsns ) {
print "# DSN: ", $dp->as_string($host), "\n";
}
return 0;
}
$o->usage_or_errors();
# ########################################################################
# If --pid, check it first since we'll die if it already exits.
# ########################################################################
my $daemon;
if ( $o->get('pid') ) {
# We're not daemoninzing, it just handles PID stuff. Keep $daemon
# in the the scope of main() because when it's destroyed it automatically
# removes the PID file.
$daemon = new Daemon(o=>$o);
$daemon->make_PID_file();
}
# ########################################################################
# Do the work.
# ########################################################################
my $tp = new TableParser( Quoter => $q );
my $ms = new MasterSlave(VersionParser => $vp);
my $du = new MySQLDump( cache => 0 );
my $rt = new Retry();
my $chunker = new TableChunker( Quoter => $q, TableParser => $tp );
my $nibbler = new TableNibbler( Quoter => $q, TableParser => $tp );
my $checksum = new TableChecksum( Quoter => $q, VersionParser => $vp );
my $syncer = new TableSyncer(
Quoter => $q,
VersionParser => $vp,
MasterSlave => $ms,
TableChecksum => $checksum,
DSNParser => $dp,
Retry => $rt,
);
my %modules = (
OptionParser => $o,
DSNParser => $dp,
MySQLDump => $du,
TableParser => $tp,
Quoter => $q,
VersionParser => $vp,
TableChunker => $chunker,
TableNibbler => $nibbler,
TableChecksum => $checksum,
MasterSlave => $ms,
TableSyncer => $syncer,
);
# Create the sync plugins.
my $plugins = [];
my %have_plugin = get_plugins();
foreach my $algo ( split(',', $o->get('algorithms')) ) {
my $plugin_name = $have_plugin{lc $algo};
if ( !$plugin_name ) {
die "The $algo algorithm is not available. Available algorithms: "
. join(", ", sort keys %have_plugin);
}
PTDEBUG && _d('Loading', $plugin_name);
my $plugin;
eval {
$plugin = $plugin_name->new(%modules);
};
die "Error loading $plugin_name for $algo algorithm: $EVAL_ERROR"
if $EVAL_ERROR;
push @$plugins, $plugin;
}
# Create callbacks for bidirectional syncing. Currently, this only
# works with TableSyncChunk, so that should be the only plugin because
# --algorithms was overriden earlier.
if ( $o->get('bidirectional') ) {
set_bidirectional_callbacks(
plugin => $plugins->[0],
%modules,
);
}
my $exit_status = 0; # 1: internal error, 2: tables differed, 3: both
# dsn[0] is expected to be the master (i.e. the source). So if
# --sync-to-master, then dsn[0] is a slave. Find its master and
# make the master dsn[0] and the slave dsn[1].
if ( $o->get('sync-to-master') ) {
PTDEBUG && _d('Getting master of', $dp->as_string($dsns[0]));
$dsns[0]->{dbh} = get_cxn($dsns[0], %modules);
my $master = $ms->get_master_dsn($dsns[0]->{dbh}, $dsns[0], $dp)
or die "Can't determine master of " . $dp->as_string($dsns[0]);
unshift @dsns, $master; # dsn[0]=master, dsn[1]=slave
$dsns[0]->{dbh} = get_cxn($dsns[0], %modules);
if ( $o->get('check-master') ) {
$ms->is_master_of($dsns[0]->{dbh}, $dsns[1]->{dbh});
}
}
my %args = (
dsns => \@dsns,
plugins => $plugins,
%modules,
);
if ( $o->get('dry-run') ) {
print "# NOTE: --dry-run does not show if data needs to be synced because it\n"
. "# does not access, compare or sync data. --dry-run only shows\n"
. "# the work that would be done.\n";
}
if ( $o->get('lock-and-rename') ) {
$exit_status = lock_and_rename(%args);
}
elsif ( $dsns[0]->{t} ) {
$exit_status = sync_one_table(%args);
}
elsif ( $o->get('replicate') ) {
$exit_status = sync_via_replication(%args);
}
else {
$exit_status = sync_all(%args);
}
return $exit_status;
}
# ############################################################################
# Subroutines
# ############################################################################
# Sub: lock_and_rename
# Lock and rename a table.
#
# Parameters:
# %args - Arguments
#
# Required Arguments:
# dsns - Arrayref of DSNs
# plugins - Arrayref of TableSync* objects
# OptionParser - <OptionParser> object
# DSNParser - <DSNParser> object
# Quoter - <Quoter> object
#
# Returns:
# Exit status
sub lock_and_rename {
my ( %args ) = @_;
my @required_args = qw(dsns plugins OptionParser DSNParser Quoter
VersionParser);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my $dsns = $args{dsns};
my $o = $args{OptionParser};
my $dp = $args{DSNParser};
my $q = $args{Quoter};
PTDEBUG && _d('Locking and syncing ONE TABLE with rename');
my $src = {
dsn => $dsns->[0],
dbh => $dsns->[0]->{dbh} || get_cxn($dsns->[0], %args),
misc_dbh => get_cxn($dsns->[0], %args),
db => $dsns->[0]->{D},
tbl => $dsns->[0]->{t},
};
my $dst = {
dsn => $dsns->[1],
dbh => $dsns->[1]->{dbh} || get_cxn($dsns->[1], %args),
misc_dbh => get_cxn($dsns->[1], %args),
db => $dsns->[1]->{D},
tbl => $dsns->[1]->{t},
};
my $vp = VersionParser->new();
my %options = ( DSNParser => $dp, OptionParser => $o );
if ( grep { $vp->version_lt($_->{dbh}, '5.5') } $src, $dst ) {
disconnect($src, $dst);
die "--lock-and-rename requires MySQL 5.5 or later";
}
if ( $o->get('verbose') ) {
print_header("# Lock and rename " . $dp->as_string($src->{dsn}));
}
# We don't use lock_server() here because it does the usual stuff wrt
# waiting for slaves to catch up to master, etc, etc.
my $src_db_tbl = $q->quote($src->{db}, $src->{tbl});
my $dst_db_tbl = $q->quote($dst->{db}, $dst->{tbl});
my $tmp_db_tbl = $q->quote($src->{db}, $src->{tbl} . "_tmp_$PID");
my $sql = "LOCK TABLES $src_db_tbl WRITE";
PTDEBUG && _d($sql);
$src->{dbh}->do($sql);
$sql = "LOCK TABLES $dst_db_tbl WRITE";
PTDEBUG && _d($sql);
$dst->{dbh}->do($sql);
my $exit_status = sync_a_table(
src => $src,
dst => $dst,
%args,
);
# Now rename the tables to swap them.
$sql = "ALTER TABLE $src_db_tbl RENAME $tmp_db_tbl";
PTDEBUG && _d($sql);
$src->{dbh}->do($sql);
$sql = "ALTER TABLE $dst_db_tbl RENAME $src_db_tbl";
PTDEBUG && _d($sql);
$dst->{dbh}->do($sql);
$sql = "UNLOCK TABLES";
PTDEBUG && _d($sql);
$src->{dbh}->do($sql);
$sql = "ALTER TABLE $tmp_db_tbl RENAME $dst_db_tbl";
PTDEBUG && _d($sql);
$src->{dbh}->do($sql);
unlock_server(src => $src, dst => $dst, %args);
disconnect($src, $dst);
return $exit_status;
}
# Sub: sync_one_table
# Sync one table between one source host and multiple destination hosts.
# The first DSN in $args{dsns} specifies the source host, database (D),
# and table (t). The other DSNs are the destination hosts. If a destination
# DSN does not specify a database or table, the source database or table
# are used as defaults. Else, the destination-specific database or table
# are used. This allows you to sync tables with different names.
#
# Parameters:
# %args - Arguments
#
# Required Arguments:
# dsns - Arrayref of DSNs
# plugins - Arrayref of TableSync* objects
# OptionParser - <OptionParser> object
# DSNParser - <DSNParser> object
# Quoter - <Quoter> object
# VersionParser - <VersionParser> object
#
# Returns:
# Exit status
sub sync_one_table {
my ( %args ) = @_;
my @required_args = qw(dsns plugins OptionParser DSNParser Quoter
VersionParser);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my @dsns = @{$args{dsns}};
my $o = $args{OptionParser};
my $dp = $args{DSNParser};
PTDEBUG && _d('DSN has t part; syncing ONE TABLE between servers');
my $src = {
dsn => $dsns[0],
dbh => $dsns[0]->{dbh} || get_cxn($dsns[0], %args),
misc_dbh => get_cxn($dsns[0], %args),
db => $dsns[0]->{D},
tbl => $dsns[0]->{t},
};
my $exit_status = 0;
foreach my $dsn ( @dsns[1 .. $#dsns] ) {
my $dst = {
dsn => $dsn,
dbh => $dsn->{dbh} || get_cxn($dsn, %args),
misc_dbh => get_cxn($dsn, %args),
db => $dsn->{D} || $src->{db},
tbl => $dsn->{t} || $src->{tbl},
};
if ( $o->get('verbose') ) {
print_header("# Syncing " . $dp->as_string($dsn)
. ($o->get('dry-run')
? ' in dry-run mode, without accessing or comparing data'
: ''));
}
lock_server(src => $src, dst => $dst, %args);
$exit_status |= sync_a_table(
src => $src,
dst => $dst,
%args,
);
unlock_server(src => $src, dst => $dst, %args);
disconnect($dst);
}
disconnect($src);
return $exit_status;
}
# Sub: sync_via_replication
# Sync multiple destination hosts to one source host via replication.
# The first DSN in $args{dsns} specifies the source host.
# If --sync-to-master is specified, then the source host is a master
# and there is only one destination host which is its slave.
# Else, destination hosts are auto-discovered with
# <MasterSlave::recurse_to_slaves()>.
#
# Parameters:
# %args - Arguments
#
# Required Arguments:
# dsns - Arrayref of DSNs
# plugins - Arrayref of TableSync* objects
# OptionParser - <OptionParser> object
# DSNParser - <DSNParser> object
# Quoter - <Quoter> object
# VersionParser - <VersionParser> object
# TableChecksum - <TableChecksum> object
# MasterSlave - <MasterSlave> object
#
# Returns:
# Exit status
#
# See Also:
# <filter_diffs()>
sub sync_via_replication {
my ( %args ) = @_;
my @required_args = qw(dsns plugins OptionParser DSNParser Quoter
VersionParser TableChecksum MasterSlave);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my $dsns = $args{dsns};
my $o = $args{OptionParser};
my $dp = $args{DSNParser};
my $q = $args{Quoter};
my $checksum = $args{TableChecksum};
my $ms = $args{MasterSlave};
PTDEBUG && _d('Syncing via replication');
my $src = {
dsn => $dsns->[0],
dbh => $dsns->[0]->{dbh} || get_cxn($dsns->[0], %args),
misc_dbh => get_cxn($dsns->[0], %args),
db => undef, # set later
tbl => undef, # set later
};
# Used to filter which tables are synced.
# https://bugs.launchpad.net/percona-toolkit/+bug/1002365
my $schema_iter = new SchemaIterator(
dbh => $src->{dbh},
OptionParser => $o,
TableParser => $args{TableParser},
Quoter => $args{Quoter},
);
my %skip_table;
my $exit_status = 0;
# Connect to the master and treat it as the source, then find
# differences on the slave and sync them.
if ( $o->get('sync-to-master') ) {
my $dst = {
dsn => $dsns->[1],
dbh => $dsns->[1]->{dbh} || get_cxn($dsns->[1], %args),
misc_dbh => get_cxn($dsns->[1], %args),
db => undef, # set later
tbl => undef, # set later
};
# First, check that the master (source) has no discrepancies itself,
# and ignore tables that do.
my $src_diffs = $checksum->find_replication_differences(
$src->{dbh}, $o->get('replicate'));
map { $skip_table{lc $_->{db}}->{lc $_->{tbl}}++ } @$src_diffs;
# Now check the slave for differences and sync them if necessary.
my $dst_diffs = $checksum->find_replication_differences(
$dst->{dbh}, $o->get('replicate'));
my $diffs = filter_diffs(
diffs => $dst_diffs,
SchemaIterator => $schema_iter,
skip_table => \%skip_table,
);
if ( $o->get('verbose') ) {
print_header("# Syncing via replication " .$dp->as_string($dst->{dsn})
. ($o->get('dry-run') ?
' in dry-run mode, without accessing or comparing data' : ''));
}
if ( $diffs && scalar @$diffs ) {
lock_server(src => $src, dst => $dst, %args);
foreach my $diff ( @$diffs ) {
# Clear the tbl_struct if this is a new table. The tbl_struct
# is fetched and parsed in ok_to_sync() if not set. We only
# need to set it once per table to avoid doing this for every
# diff in the same table.
# https://bugs.launchpad.net/percona-toolkit/+bug/1003014
if ( ($src->{db} || '') ne $diff->{db}
|| ($src->{tbl} || '') ne $diff->{tbl} ) {
PTDEBUG && _d('New table:', $diff->{db}, $diff->{tbl});
$src->{tbl_struct} = undef;
}
$src->{db} = $dst->{db} = $diff->{db};
$src->{tbl} = $dst->{tbl} = $diff->{tbl};
$exit_status |= sync_a_table(
src => $src,
dst => $dst,
where => 1, # prevents --where from being used
diff => $diff,
%args,
);
}
unlock_server(src => $src, dst => $dst, %args);
}
else {
PTDEBUG && _d('No checksum differences');
}
disconnect($dst);
} # sync-to-master
# The DSN is the master. Connect to each slave, find differences,
# then sync them.
else {
$ms->recurse_to_slaves(
{ dbh => $src->{dbh},
dsn => $src->{dsn},
dsn_parser => $dp,
recurse => 1,
callback => sub {
my ( $dsn, $dbh, $level, $parent ) = @_;
my $all_diffs = $checksum->find_replication_differences(
$dbh, $o->get('replicate'));
if ( !$level ) {
# This is the master; don't sync any tables that are wrong
# here, for obvious reasons.
map { $skip_table{lc $_->{db}}->{lc $_->{tbl}}++ }
@$all_diffs;
}
else {
# This is a slave.
my $diffs = filter_diffs(
diffs => $all_diffs,
SchemaIterator => $schema_iter,
skip_table => \%skip_table,
);
if ( $o->get('verbose') ) {
print_header("# Syncing via replication "
. $dp->as_string($dsn)
. ($o->get('dry-run')
? ' in dry-run mode, without '
. 'accessing or comparing data'
: ''));
}
if ( $diffs && scalar @$diffs ) {
my $dst = {
dsn => $dsn,
dbh => $dbh,
misc_dbh => get_cxn($dsn, %args),
db => undef, # set later
tbl => undef, # set later
};
lock_server(src => $src, dst => $dst, %args);
foreach my $diff ( @$diffs ) {
# Clear the tbl_struct if this is a new table.
# See the same code block above.
if ( ($src->{db} || '') ne $diff->{db}
|| ($src->{tbl} || '') ne $diff->{tbl} ) {
PTDEBUG && _d('New table:',
$diff->{db}, $diff->{tbl});
$src->{tbl_struct} = undef;
}
$src->{db} = $dst->{db} = $diff->{db};
$src->{tbl} = $dst->{tbl} = $diff->{tbl};
$exit_status |= sync_a_table(
src => $src,
dst => $dst,
where => 1, # prevents --where from being used
diff => $diff,
%args,
);
}
unlock_server(src => $src, dst => $dst, %args);
disconnect($dst);
}
else {
PTDEBUG && _d('No checksum differences');
}
} # this is a slave
return;
}, # recurse_to_slaves() callback
method => $o->get('recursion-method'),
},
);
} # DSN is master
disconnect($src);
return $exit_status;
}
# Sub: sync_all
# Sync every table between one source host and multiple destination hosts.
# The first DSN in $args{dsns} specifies the source host. The other DSNs
# are the destination hosts. Unlike <sync_one_table>, the database and
# table names must be the same on the source and destination hosts.
#
# Parameters:
# %args - Arguments
#
# Required Arguments:
# dsns - Arrayref of DSNs
# plugins - Arrayref of TableSync* objects
# OptionParser - <OptionParser> object
# DSNParser - <DSNParser> object
# Quoter - <Quoter> object
# VersionParser - <VersionParser> object
# TableParser - <TableParser> object
# MySQLDump - <MySQLDump> object
#
# Returns:
# Exit status
sub sync_all {
my ( %args ) = @_;
my @required_args = qw(dsns plugins OptionParser DSNParser Quoter
VersionParser TableParser MySQLDump);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my @dsns = @{$args{dsns}};
my $o = $args{OptionParser};
my $dp = $args{DSNParser};
PTDEBUG && _d('Syncing all dbs and tbls');
my $src = {
dsn => $dsns[0],
dbh => $dsns[0]->{dbh} || get_cxn($dsns[0], %args),
misc_dbh => get_cxn($dsns[0], %args),
db => undef, # set later
tbl => undef, # set later
};
my $schema_iter = new SchemaIterator(
dbh => $src->{dbh},
OptionParser => $o,
TableParser => $args{TableParser},
Quoter => $args{Quoter},
);
# Make a list of all dbs.tbls on the source. It's more efficient this
# way because it avoids open/closing a dbh for each tbl and dsn, unless
# we pre-opened the dsn. It would also cause confusing verbose output.
my @dbs_tbls;
while ( my $tbl = $schema_iter->next() ) {
PTDEBUG && _d('Got table', $tbl->{db}, $tbl->{tbl});
push @dbs_tbls, $tbl;
}
my $exit_status = 0;
foreach my $dsn ( @dsns[1 .. $#dsns] ) {
if ( $o->get('verbose') ) {
print_header("# Syncing " . $dp->as_string($dsn)
. ($o->get('dry-run')
? ' in dry-run mode, without accessing or comparing data' : ''));
}
my $dst = {
dsn => $dsn,
dbh => $dsn->{dbh} || get_cxn($dsn, %args),
misc_dbh => get_cxn($dsn, %args),
db => undef, # set later
tbl => undef, # set later
};
lock_server(src => $src, dst => $dst, %args);
foreach my $db_tbl ( @dbs_tbls ) {
$src->{tbl_struct} = $db_tbl->{tbl_struct};
$src->{db} = $dst->{db} = $db_tbl->{db};
$src->{tbl} = $dst->{tbl} = $db_tbl->{tbl};
$exit_status |= sync_a_table(
src => $src,
dst => $dst,
%args,
);
}
unlock_server(src => $src, dst => $dst, %args);
disconnect($dst);
}
disconnect($src);
return $exit_status;
}
# Sub: lock_server
# Lock a host with FLUSH TABLES WITH READ LOCK. This implements
# --lock 3 by calling <TableSyncer::lock_and_wait()>.
#
# Parameters:
# %args - Arguments
#
# Required Arguments:
# src - Hashref with source host information
# dst - Hashref with destination host information
# OptionParser - <OptionParser> object
# DSNParser - <DSNParser> object
# TableSyncer - <TableSyncer> object
sub lock_server {
my ( %args ) = @_;
foreach my $arg ( qw(src dst OptionParser DSNParser TableSyncer) ) {
die "I need a $arg argument" unless $args{$arg};
}
my $o = $args{OptionParser};
return unless $o->get('lock') && $o->get('lock') == 3;
eval {
$args{TableSyncer}->lock_and_wait(
%args,
lock => 3,
lock_level => 3,
replicate => $o->get('replicate'),
timeout_ok => $o->get('timeout-ok'),
transaction => $o->get('transaction'),
wait => $o->get('wait'),
);
};
if ( $EVAL_ERROR ) {
die "Failed to lock server: $EVAL_ERROR";
}
return;
}
# Sub: unlock_server
# Unlock a host with UNLOCK TABLES. This implements
# --lock 3 by calling <TableSyncer::unlock()>.
#
# Parameters:
# %args - Arguments
#
# Required Arguments:
# src - Hashref with source host information
# dst - Hashref with destination host information
# OptionParser - <OptionParser> object
# DSNParser - <DSNParser> object
# TableSyncer - <TableSyncer> object
sub unlock_server {
my ( %args ) = @_;
my @required_args = qw(src dst OptionParser DSNParser TableSyncer);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my ($src, $dst, $o) = @args{@required_args};
return unless $o->get('lock') && $o->get('lock') == 3;
eval {
# Open connections as needed.
$src->{dbh} ||= get_cxn($src->{dsn}, %args);
$dst->{dbh} ||= get_cxn($dst->{dsn}, %args);
$src->{misc_dbh} ||= get_cxn($src->{dsn}, %args);
$args{TableSyncer}->unlock(
src_dbh => $src->{dbh},
src_db => '',
src_tbl => '',
dst_dbh => $dst->{dbh},
dst_db => '',
dst_tbl => '',
misc_dbh => $src->{misc_dbh},
replicate => $o->get('replicate') || 0,
timeout_ok => $o->get('timeout-ok') || 0,
transaction => $o->get('transaction') || 0,
wait => $o->get('wait') || 0,
lock => 3,
lock_level => 3,
);
};
if ( $EVAL_ERROR ) {
die "Failed to unlock server: $EVAL_ERROR";
}
return;
}
# Sub: sync_a_table
# Sync the destination host table to the source host table. This sub
# is not called directly but indirectly via the other sync_* subs.
# In turn, this sub calls <TableSyncer::sync_table()> which actually
# does the sync work. Calling sync_table() requires a fair amount of
# prep work that this sub does/simplifies. New <RowDiff> and <ChangeHandler>
# objects are created, so those packages need to be available.
#
# Parameters:
# $args - Arguments
#
# Required Arguments:
# src - Hashref with source host information
# dst - Hashref with destination host information
# plugins - Arrayref of TableSync* objects
# OptionParser - <OptionParser> object
# Quoter - <Quoter> object
# TableParser - <TableParser> object
# MySQLDump - <MySQLDump> object
# TableSyncer - <TableSyncer> object
#
# Returns:
# Exit status
sub sync_a_table {
my ( %args ) = @_;
my @required_args = qw(src dst plugins OptionParser Quoter TableParser
MySQLDump TableSyncer);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my ($src, $dst, undef, $o, $q, $tp, $du, $syncer) = @args{@required_args};
my ($start_ts, $end_ts);
my $exit_status = 0;
my %status;
eval {
$start_ts = get_server_time($src->{dbh}) if $o->get('verbose');
# This will either die if there's a problem or return the tbl struct.
ok_to_sync($src, $dst, %args);
my $tbl_struct = $src->{tbl_struct};
if ( my $diff = $args{diff} ) {
PTDEBUG && _d('Converting checksum diff to WHERE:', Dumper($diff));
$args{where} = diff_where(
%args,
tbl_struct => $tbl_struct,
);
}
# If the table is InnoDB, prefer to sync it with transactions, unless
# the user explicitly said not to.
my $use_txn = $o->got('transaction') ? $o->get('transaction')
: $tbl_struct->{engine} eq 'InnoDB' ? 1
: 0;
# Turn off AutoCommit if we're using transactions.
$src->{dbh}->{AutoCommit} = !$use_txn;
$src->{misc_dbh}->{AutoCommit} = !$use_txn;
$dst->{dbh}->{AutoCommit} = !$use_txn;
$dst->{misc_dbh}->{AutoCommit} = !$use_txn;
# Determine which columns to compare.
my $ignore_columns = $o->get('ignore-columns');
my @compare_columns = grep {
!$ignore_columns->{lc $_};
} @{$o->get('columns') || $tbl_struct->{cols}};
# Make sure conflict col is in compare cols else conflicting
# rows won't have the col for --conflict-comparison.
if ( my $conflict_col = $o->get('conflict-column') ) {
push @compare_columns, $conflict_col
unless grep { $_ eq $conflict_col } @compare_columns;
}
# --print --verbose --verbose is the magic formula for having
# all src/dst sql printed so we can see the chunk/row sql.
my $callback;
if ( $o->get('print') && $o->get('verbose') >= 2 ) {
$callback = \&print_sql;
}
# get_change_dbh() may die if, for example, the destination is
# not a slave. Perhaps its work should be part of can_sync()?
my $change_dbh = get_change_dbh(tbl_struct => $tbl_struct, %args);
my $actions = make_action_subs(change_dbh => $change_dbh, %args);
my $rd = new RowDiff(dbh => $src->{misc_dbh});
my $ch = new ChangeHandler(
left_db => $src->{db},
left_tbl => $src->{tbl},
right_db => $dst->{db},
right_tbl => $dst->{tbl},
tbl_struct => $tbl_struct,
hex_blob => $o->get('hex-blob'),
queue => $o->get('buffer-to-client') ? 1 : 0,
replace => $o->get('replace')
|| $o->get('replicate')
|| $o->get('sync-to-master')
|| 0,
actions => $actions,
Quoter => $args{Quoter},
);
%status = $syncer->sync_table(
%args,
tbl_struct => $tbl_struct,
cols => \@compare_columns,
chunk_size => $o->get('chunk-size'),
RowDiff => $rd,
ChangeHandler => $ch,
transaction => $use_txn,
callback => $callback,
where => $args{where} || $o->get('where'),
bidirectional => $o->get('bidirectional'),
buffer_in_mysql => $o->get('buffer-in-mysql'),
buffer_to_client => $o->get('buffer-to-client'),
changing_src => $o->get('replicate')
|| $o->get('sync-to-master')
|| $o->get('bidirectional')
|| 0,
float_precision => $o->get('float-precision'),
index_hint => $o->get('index-hint'),
chunk_index => $o->get('chunk-index'),
chunk_col => $o->get('chunk-column'),
zero_chunk => $o->get('zero-chunk'),
lock => $o->get('lock'),
replace => $o->get('replace'),
replicate => $o->get('replicate'),
dry_run => $o->get('dry-run'),
timeout_ok => $o->get('timeout-ok'),
trim => $o->get('trim'),
wait => $o->get('wait'),
function => $o->get('function'),
);
if ( sum(@status{@ChangeHandler::ACTIONS}) ) {
$exit_status |= 2;
}
};
if ( $EVAL_ERROR ) {
print_err($EVAL_ERROR, $dst->{db}, $dst->{tbl}, $dst->{dsn}->{h});
$exit_status |= 1;
}
# Print this last so that the exit status is its final result.
if ( $o->get('verbose') ) {
$end_ts = get_server_time($src->{dbh}) || "";
print_results(
map { $_ || '0' } @status{@ChangeHandler::ACTIONS, 'ALGORITHM'},
$start_ts, $end_ts,
$exit_status, $src->{db}, $src->{tbl});
}
return $exit_status;
}
# Sub: get_change_dbh
# Return the dbh to write to for syncing changes. Write statements
# are executed on the "change dbh". If --sync-to-master or --replicate
# is specified, the source (master) dbh is the "change dbh". This means
# changes replicate to all slaves. Else, the destination dbh is the
# change dbh. This is the case when two independent servers (or perhaps
# one table on the same server) are synced. This sub implements
# --[no]check-slave because writing to a slave is generally a bad thing.
#
# Parameters:
# %args - Arguments
#
# Required Arguments:
# src - Hashref with source host information
# dst - Hashref with destination host information
# tbl_struct - Hashref returned by <TableParser::parse()>
# OptionParser - <OptionParser> object
# DSNParser - <DSNParser> object
# MasterSlave - <MasterSlave> object
#
# Returns:
# Either $args{src}->{dbh} or $args{dst}->{dbh} if no checks fail.
#
# See Also:
# <make_action_subs()>
sub get_change_dbh {
my ( %args ) = @_;
my @required_args = qw(src dst tbl_struct OptionParser DSNParser
MasterSlave);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my ($src, $dst, $tbl_struct, $o, $dp, $ms) = @args{@required_args};
my $change_dbh = $dst->{dbh}; # The default case: making changes on dst.
if ( $o->get('sync-to-master') || $o->get('replicate') ) {
# Is it possible to make changes on the master (i.e. the source)?
# Only if REPLACE will work.
my $can_replace = grep { $_->{is_unique} } values %{$tbl_struct->{keys}};
PTDEBUG && _d("This table's replace-ability:", $can_replace);
die "Can't make changes on the master because no unique index exists"
unless $can_replace;
$change_dbh = $src->{dbh}; # The alternate case.
PTDEBUG && _d('Will make changes on source', $change_dbh);
}
elsif ( $o->get('check-slave') ) {
# Is it safe to change data on the destination? Only if it's *not*
# a slave. We don't change tables on slaves directly. If we are
# forced to change data on a slave, we require either that 1) binary
# logging is disabled, or 2) the check is bypassed. By the way, just
# because the server is a slave doesn't mean it's not also the master
# of the master (master-master replication).
my $slave_status = $ms->get_slave_status($dst->{dbh});
my (undef, $log_bin) = $dst->{dbh}->selectrow_array(
'SHOW VARIABLES LIKE "log_bin"');
my ($sql_log_bin) = $dst->{dbh}->selectrow_array(
'SELECT @@SQL_LOG_BIN');
PTDEBUG && _d('Variables on destination:',
'log_bin=', (defined $log_bin ? $log_bin : 'NULL'),
' @@SQL_LOG_BIN=', (defined $sql_log_bin ? $sql_log_bin : 'NULL'));
if ( $slave_status && $sql_log_bin && ($log_bin || 'OFF') eq 'ON' ) {
die "Can't make changes on ", $dp->as_string($dst->{dsn}),
" because it's a slave. See the documentation section",
" 'REPLICATION SAFETY' for solutions to this problem.";
}
PTDEBUG && _d('Will make changes on destination', $change_dbh);
}
return $change_dbh;
}
# Sub: make_action_subs
# Make callbacks for <ChangeHandler::new()> actions argument. This
# sub implements --print and --execute.
#
# Parameters:
# %args - Arguments
#
# Required Arguments:
# change_dbh - dbh returned by <get_change_dbh>
# OptionParser - <OptionParser> object
#
# Returns:
# Arrayref of callbacks (coderefs)
sub make_action_subs {
my ( %args ) = @_;
my @required_args = qw(change_dbh OptionParser);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my ($change_dbh, $o) = @args{@required_args};
my @actions;
if ( $o->get('execute') ) {
push @actions, sub {
my ( $sql, $dbh ) = @_;
# Use $dbh if given. It's from a bidirectional callback.
$dbh ||= $change_dbh;
PTDEBUG && _d('Execute on dbh', $dbh, $sql);
$dbh->do($sql);
};
}
if ( $o->get('print') ) {
# Print AFTER executing, so the print isn't misleading in case of an
# index violation etc that doesn't actually get executed.
push @actions, sub {
my ( $sql, $dbh ) = @_;
# Append /*host:port*/ to the sql, if possible, so the user
# can see on which host it was/would be ran.
my $dsn = $dsn_for{$dbh} if $dbh;
if ( $dsn ) {
my $h = $dsn->{h} || $dsn->{S} || '';
my $p = $dsn->{P} || '';
$sql = "/*$h" . ($p ? ":$p" : '') . "*/ $sql";
}
print($sql, ";\n") or die "Cannot print: $OS_ERROR";
};
}
return \@actions;
}
# Sub: print_err
# Try to extract the MySQL error message and print it.
#
# Parameters:
# $msg - Error message
# $database - Database name being synced when error occurred
# $table - Table name being synced when error occurred
# $host - Host name error occurred on
sub print_err {
my ( $msg, $database, $table, $host ) = @_;
return if !defined $msg;
$msg =~ s/^.*?failed: (.*?) at \S+ line (\d+).*$/$1 at line $2/s;
$msg =~ s/\s+/ /g;
if ( $database && $table ) {
$msg .= " while doing $database.$table";
}
if ( $host ) {
$msg .= " on $host";
}
print STDERR $msg, "\n";
}
# Sub: get_cxn
# Connect to host specified by DSN.
#
# Parameters:
# $dsn - Host DSN
# %args - Arguments
#
# Required Arguments:
# OptionaParser - <OptionParser> object
# DSNParser - <DSNParser> object
#
# Returns:
# dbh
sub get_cxn {
my ( $dsn, %args ) = @_;
my @required_args = qw(OptionParser DSNParser);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my ($o, $dp) = @args{@required_args};
if ( !$dsn->{p} && $o->get('ask-pass') ) {
# Just "F=file" is a valid DSN but fill_in_dsn() can't help us
# because we haven't connected yet. If h is not specified,
# then user is relying on F or .my.cnf/system defaults.
# http://code.google.com/p/maatkit/issues/detail?id=947
my $host = $dsn->{h} ? $dsn->{h}
: "DSN ". $dp->as_string($dsn);
$dsn->{p} = OptionParser::prompt_noecho("Enter password for $host: ");
}
my $dbh = $dp->get_dbh(
$dp->get_cxn_params($dsn, {}) # get_cxn_params needs the 2nd arg
);
my $sql;
if ( !$o->get('bin-log') ) {
$sql = "/*!32316 SET SQL_LOG_BIN=0 */";
PTDEBUG && _d($dbh, $sql);
$dbh->do($sql);
}
if ( !$o->get('unique-checks') ) {
$sql = "/*!40014 SET UNIQUE_CHECKS=0 */";
PTDEBUG && _d($dbh, $sql);
$dbh->do($sql);
}
if ( !$o->get('foreign-key-checks') ) {
$sql = "/*!40014 SET FOREIGN_KEY_CHECKS=0 */";
PTDEBUG && _d($dbh, $sql);
$dbh->do($sql);
}
# Disable auto-increment on zero (bug #1919897).
$sql = '/*!40101 SET @@SQL_MODE := CONCAT(@@SQL_MODE, '
. "',NO_AUTO_VALUE_ON_ZERO')*/";
PTDEBUG && _d($dbh, $sql);
$dbh->do($sql);
# Ensure statement-based replication.
# http://code.google.com/p/maatkit/issues/detail?id=95
# https://bugs.launchpad.net/percona-toolkit/+bug/919352
# The tool shouldn't blindly attempt to change binlog_format;
# instead, it should check if it's already set to STATEMENT.
# This is becase starting with MySQL 5.1.29, changing the format
# requires a SUPER user.
my $vp = new VersionParser();
if ( $vp->version_ge($dbh, '5.1.5') ) {
$sql = 'SELECT @@binlog_format';
PTDEBUG && _d($dbh, $sql);
my ($original_binlog_format) = $dbh->selectrow_array($sql);
PTDEBUG && _d('Original binlog_format:', $original_binlog_format);
if ( $original_binlog_format !~ /STATEMENT/i ) {
$sql = q{/*!50108 SET @@binlog_format := 'STATEMENT'*/};
eval {
PTDEBUG && _d($dbh, $sql);
$dbh->do($sql);
};
if ( $EVAL_ERROR ) {
die "Failed to $sql: $EVAL_ERROR\n"
. "This tool requires binlog_format=STATEMENT, "
. "but the current binlog_format is set to "
."$original_binlog_format and an error occurred while "
. "attempting to change it. If running MySQL 5.1.29 or newer, "
. "setting binlog_format requires the SUPER privilege. "
. "You will need to manually set binlog_format to 'STATEMENT' "
. "before running this tool.\n";
}
}
}
if ( $o->get('transaction') ) {
my $sql = "SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ";
eval {
PTDEBUG && _d($dbh, $sql);
$dbh->do($sql);
};
die "Failed to $sql: $EVAL_ERROR" if $EVAL_ERROR;
}
$dsn_for{$dbh} = $dsn;
PTDEBUG && _d('Opened dbh', $dbh);
return $dbh;
}
# Sub: ok_to_sync
# Check that the destination host table can be synced to the source host
# table. All sorts of sanity checks are performed to help ensure that
# syncing the table won't cause problems in <sync_a_table()> or
# <TableSyncer::sync_table()>.
#
# Parameters:
# %args - Arguments
#
# Required Arguments:
# src - Hashref with source host information
# dst - Hashref with destination host information
# DSNParser - <DSNParser> object
# Quoter - <Quoter> object
# VersionParser - <VersionParser> object
# TableParser - <TableParser> object
# MySQLDump - <MySQLDump> object
# TableSyncer - <TableSyncer> object
# OptionParser - <OptionParser> object
#
# Returns:
# Table structure (from <TableParser::parse()>) if ok to sync, else it dies.
sub ok_to_sync {
my ( %args ) = @_;
my @required_args = qw(src dst DSNParser Quoter VersionParser TableParser
MySQLDump TableSyncer OptionParser);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my ($src, $dst, $dp, $q, $vp, $tp, $du, $syncer, $o) = @args{@required_args};
if ( !$src->{tbl_struct} ) {
eval {
$src->{ddl} = $tp->get_create_table(
$src->{dbh}, $src->{db}, $src->{tbl});
$src->{tbl_struct} = $tp->parse($src->{ddl});
};
if ( $EVAL_ERROR ) {
die "Error getting table structure for $src->{db}.$src->{tbl} on "
. $dp->as_string($src->{dsn}) . "$EVAL_ERROR\nEnsure that "
. "the table exists and is accessible.\n";
}
}
# Check that the dst has the table.
my $dst_has_table = $tp->check_table(
dbh => $dst->{dbh},
db => $dst->{db},
tbl => $dst->{tbl},
);
if ( !$dst_has_table ) {
die "Table $dst->{db}.$dst->{tbl} does not exist on "
. $dp->as_string($dst->{dsn}) . "\n";
}
# Check that the user has all the necessary privs on the tbls.
if ( $o->get('check-privileges') ) {
PTDEBUG && _d('Checking privileges');
if ( !$syncer->have_all_privs($src->{dbh}, $src->{db}, $src->{tbl}) ) {
my $user = get_current_user($src->{dbh}) || "";
die "User $user does not have all necessary privileges on ",
$q->quote($src->{db}, $src->{tbl});
}
if ( !$syncer->have_all_privs($dst->{dbh}, $dst->{db}, $dst->{tbl}) ) {
my $user = get_current_user($dst->{dbh}) || "";
die "User $user does not have all necessary privileges on ",
$q->quote($dst->{db}, $dst->{tbl});
}
}
# Check that no triggers are defined on the dst tbl.
if ( $o->get('check-triggers') ) {
PTDEBUG && _d('Checking for triggers');
if ( !defined $dst->{supports_triggers} ) {
$dst->{supports_triggers} = $vp->version_ge($dst->{dbh}, '5.0.2');
}
if ( $dst->{supports_triggers}
&& $du->get_triggers($dst->{dbh}, $q, $dst->{db}, $dst->{tbl}) ) {
die "Triggers are defined on the table";
}
else {
PTDEBUG && _d('Destination does not support triggers',
$dp->as_string($dst->{dsn}));
}
}
return;
}
# Sub: filter_diffs
# Filter different slave tables according to the various schema object
# filters. This sub is called in <sync_via_replication()> to implement
# schema object filters like --databases and --tables.
#
# Returns:
# Arrayref of different slave tables that pass the filters
sub filter_diffs {
my ( %args ) = @_;
my @required_args = qw(diffs SchemaIterator skip_table);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my ($diffs, $si, $skip_table) = @args{@required_args};
my @filtered_diffs;
foreach my $diff ( @$diffs ) {
my $db = lc $diff->{db};
my $tbl = lc $diff->{tbl};
if ( !$skip_table->{$db}->{$tbl}
&& $si->database_is_allowed($db)
&& $si->table_is_allowed($db, $tbl) ) {
push @filtered_diffs, $diff;
}
}
return \@filtered_diffs;
}
# Sub: disconnect
# Disconnect host dbhs created by <get_cxn()>. To make sure all dbh
# are closed, pt-table-sync keeps track of the dbh it opens and this
# sub helps keep track of the dbh that are closed.
#
# Parameters:
# @hosts - Array of hashrefs with host information, one for each host
sub disconnect {
my ( @hosts ) = @_;
foreach my $host ( @hosts ) {
foreach my $thing ( qw(dbh misc_dbh) ) {
my $dbh = $host->{$thing};
next unless $dbh;
delete $dsn_for{$dbh};
$dbh->commit() unless $dbh->{AutoCommit};
$dbh->disconnect();
PTDEBUG && _d('Disconnected dbh', $dbh);
}
}
return;
}
# Sub: print_sql
# Callback for <TableSyncer::sync_table()> if --print --verbose --verbose
# is specified. The callback simply prints the SQL statements passed to
# it by sync_table(). They're usually (always?) identical statements.
#
# Parameters:
# $src_sql - SQL statement to be executed on the sourch host
# $dst_sql - SQL statement to be executed on the destination host
sub print_sql {
my ( $src_sql, $dst_sql ) = @_;
print "# $src_sql\n" if $src_sql;
print "# $dst_sql\n" if $dst_sql;
return;
}
use constant UPDATE_LEFT => -1;
use constant UPDATE_RIGHT => 1;
use constant UPDATE_NEITHER => 0; # neither value equals/matches
use constant FAILED_THRESHOLD => 2; # failed to exceed threshold
# Sub: cmd_conflict_col
# Compare --conflict-column values for --bidirectional. This sub is
# used as a callback in <set_bidirectional_callbacks()>.
#
# Parameters:
# $left_val - Column value from left (usually the source host)
# $right_val - Column value from right (usually the destination host)
# $cmp - Type of conflict comparison, --conflict-comparison
# $val - Value for certain types of comparisons, --conflict-value
# $thr - Threshold for certain types of comparisons,
# --conflict-threshold
#
# Returns:
# One of the constants above, UPDATE_* or FAILED_THRESHOLD
sub cmp_conflict_col {
my ( $left_val, $right_val, $cmp, $val, $thr ) = @_;
PTDEBUG && _d('Compare', @_);
my $res;
if ( $cmp eq 'newest' || $cmp eq 'oldest' ) {
$res = $cmp eq 'newest' ? ($left_val || '') cmp ($right_val || '')
: ($right_val || '') cmp ($left_val || '');
if ( $thr ) {
$thr = time_to_secs($thr);
my $lts = any_unix_timestamp($left_val);
my $rts = any_unix_timestamp($right_val);
my $diff = abs($lts - $rts);
PTDEBUG && _d('Check threshold, lts rts thr abs-diff:',
$lts, $rts, $thr, $diff);
if ( $diff < $thr ) {
PTDEBUG && _d("Failed threshold");
return FAILED_THRESHOLD;
}
}
}
elsif ( $cmp eq 'greatest' || $cmp eq 'least' ) {
$res = $cmp eq 'greatest' ? (($left_val ||0) > ($right_val ||0) ? 1 : -1)
: (($left_val ||0) < ($right_val ||0) ? 1 : -1);
$res = 0 if ($left_val || 0) == ($right_val || 0);
if ( $thr ) {
my $diff = abs($left_val - $right_val);
PTDEBUG && _d('Check threshold, abs-diff:', $diff);
if ( $diff < $thr ) {
PTDEBUG && _d("Failed threshold");
return FAILED_THRESHOLD;
}
}
}
elsif ( $cmp eq 'equals' ) {
$res = ($left_val || '') eq $val ? 1
: ($right_val || '') eq $val ? -1
: 0;
}
elsif ( $cmp eq 'matches' ) {
$res = ($left_val || '') =~ m/$val/ ? 1
: ($right_val || '') =~ m/$val/ ? -1
: 0;
}
else {
# Should happen; caller should have verified this.
die "Invalid comparison: $cmp";
}
return $res;
}
# Sub: set_bidirectional_callbacks
# Set syncer plugin callbacks for --bidirectional.
#
# Parameters:
# %args - Arguments
#
# Required Arguments:
# plugin - TableSync* object
# OptionParser - <OptionParser> object
sub set_bidirectional_callbacks {
my ( %args ) = @_;
foreach my $arg ( qw(plugin OptionParser) ) {
die "I need a $arg argument" unless $args{$arg};
}
my $o = $args{OptionParser};
my $plugin = $args{plugin};
my $col = $o->get('conflict-column');
my $cmp = $o->get('conflict-comparison');
my $val = $o->get('conflict-value');
my $thr = $o->get('conflict-threshold');
# plugin and syncer are actually the same module. For clarity we
# name them differently.
$plugin->set_callback('same_row', sub {
my ( %args ) = @_;
my ($lr, $rr, $syncer) = @args{qw(lr rr syncer)};
my $ch = $syncer->{ChangeHandler};
my $action = 'UPDATE';
my $change_dbh;
my $auth_row;
my $err;
my $left_val = $lr->{$col} || '';
my $right_val = $rr->{$col} || '';
PTDEBUG && _d('left', $col, 'value:', $left_val);
PTDEBUG && _d('right', $col, 'value:', $right_val);
my $res = cmp_conflict_col($left_val, $right_val, $cmp, $val, $thr);
if ( $res == UPDATE_LEFT ) {
PTDEBUG && _d("right dbh $args{right_dbh} $cmp; "
. "update left dbh $args{left_dbh}");
$ch->set_src('right', $args{right_dbh});
$auth_row = $args{rr};
$change_dbh = $args{left_dbh};
}
elsif ( $res == UPDATE_RIGHT ) {
PTDEBUG && _d("left dbh $args{left_dbh} $cmp; "
. "update right dbh $args{right_dbh}");
$ch->set_src('left', $args{left_dbh});
$auth_row = $args{lr};
$change_dbh = $args{right_dbh};
}
elsif ( $res == UPDATE_NEITHER ) {
if ( $cmp eq 'equals' || $cmp eq 'matches' ) {
$err = "neither `$col` value $cmp $val";
}
else {
$err = "`$col` values are the same"
}
}
elsif ( $res == FAILED_THRESHOLD ) {
$err = "`$col` values do not differ by the threhold, $thr."
}
else {
# Shouldn't happen.
die "cmp_conflict_col() returned an invalid result: $res."
}
if ( $err ) {
$action = undef; # skip change in case we just warn
my $where = $ch->make_where_clause($lr, $syncer->key_cols());
$err = "# Cannot resolve conflict WHERE $where: $err\n";
# die here is caught in sync_a_table(). We're deeply nested:
# sync_a_table > sync_table > compare_sets > syncer > here
$o->get('conflict-error') eq 'warn' ? warn $err : die $err;
}
return $action, $auth_row, $change_dbh;
});
$plugin->set_callback('not_in_right', sub {
my ( %args ) = @_;
$args{syncer}->{ChangeHandler}->set_src('left', $args{left_dbh});
return 'INSERT', $args{lr}, $args{right_dbh};
});
$plugin->set_callback('not_in_left', sub {
my ( %args ) = @_;
$args{syncer}->{ChangeHandler}->set_src('right', $args{right_dbh});
return 'INSERT', $args{rr}, $args{left_dbh};
});
return;
}
# Sub: get_plugins
# Get internal TableSync* plugins.
#
# Returns:
# Hash of available algoritms and the plugin/module names that
# implement them, like "chunk => TableSyncChunk".
sub get_plugins {
my ( %args ) = @_;
my $file = __FILE__;
open my $fh, "<", $file or die "Cannot open $file: $OS_ERROR";
my $contents = do { local $/ = undef; <$fh> };
close $fh;
my %local_plugins = map {
my $package = $_;
my ($module, $algo) = $package =~ m/(TableSync(\w+))/;
lc $algo => $module;
} $contents =~ m/^package TableSync\w{3,};/gm;
return %local_plugins;
}
{
# DELETE REPLACE INSERT UPDATE ALGORITHM START END EXIT DATABASE.TABLE
my $hdr = "# %6s %7s %6s %6s %-9s %-8s %-8s %-4s %s.%s\n";
sub print_header {
my ( $title ) = @_;
print "$title\n" if $title;
printf $hdr, @ChangeHandler::ACTIONS,
qw(ALGORITHM START END EXIT DATABASE TABLE);
return;
}
sub print_results {
my ( @values ) = @_;
printf $hdr, @values;
return;
}
}
# Sub: get_server_time
# Return HH:MM:SS of SELECT NOW() from the server.
#
# Parameters:
# $dbh - dbh
sub get_server_time {
my ( $dbh ) = @_;
return unless $dbh;
my $now;
eval {
my $sql = "SELECT NOW()";
PTDEBUG && _d($dbh, $sql);
($now) = $dbh->selectrow_array($sql);
PTDEBUG && _d("Server time:", $now);
$now =~ s/^\S+\s+//;
};
if ( $EVAL_ERROR ) {
PTDEBUG && _d("Failed to get server time:", $EVAL_ERROR);
}
return $now
}
sub get_current_user {
my ( $dbh ) = @_;
return unless $dbh;
my $user;
eval {
my $sql = "SELECT CURRENT_USER()";
PTDEBUG && _d($dbh, $sql);
($user) = $dbh->selectrow_array($sql);
};
if ( $EVAL_ERROR ) {
PTDEBUG && _d("Error getting current user:", $EVAL_ERROR);
}
return $user;
}
{
my %asc_for_table;
sub diff_where {
my (%args) = @_;
my @required_args = qw(diff tbl_struct TableNibbler);
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my ($diff, $tbl_struct, $tn) = @args{@required_args};
my $key = $diff->{chunk_index};
if ( !$key ) {
PTDEBUG && _d('One nibble checksum');
return;
}
my $cols = $tbl_struct->{keys}->{$key}->{cols};
my $asc = $asc_for_table{$diff->{table}};
if ( !$asc ) {
die "Index $key does not exist in table" unless $cols && @$cols;
# NibbleIterator does this to make the boundary statements.
$asc = $args{TableNibbler}->generate_asc_stmt(
%args,
tbl_struct => $tbl_struct,
index => $key,
cols => $cols,
asc_only => 1,
);
$asc_for_table{$diff->{table}} = $asc;
PTDEBUG && _d('Ascend params:', Dumper($asc));
}
my $lb_sql = $asc->{boundaries}->{'>='};
foreach my $val ( $q->deserialize_list($diff->{lower_boundary}) ) {
my $quoted_val = $q->quote_val($val);
$lb_sql =~ s/\?/$quoted_val/;
}
my $ub_sql = $asc->{boundaries}->{'<='};
foreach my $val ( $q->deserialize_list($diff->{upper_boundary}) ) {
my $quoted_val = $q->quote_val($val);
$ub_sql =~ s/\?/$quoted_val/;
}
return "$lb_sql AND $ub_sql";
}
}
sub _d {
my ($package, undef, $line) = caller 0;
@_ = map { (my $temp = $_) =~ s/\n/\n# /g; $temp; }
map { defined $_ ? $_ : 'undef' }
@_;
print STDERR "# $package:$line $PID ", join(' ', @_), "\n";
}
# ############################################################################
# Run the program.
# ############################################################################
if ( !caller ) { exit main(@ARGV); }
1; # Because this is a module as well as a script.
# ############################################################################
# Documentation
# ############################################################################
=pod
=head1 NAME
pt-table-sync - Synchronize MySQL table data efficiently.
=head1 SYNOPSIS
Usage: pt-table-sync [OPTION...] DSN [DSN...]
pt-table-sync synchronizes data efficiently between MySQL tables.
This tool changes data, so for maximum safety, you should back up your data
before you use it. When synchronizing a server that is a replication slave with
the --replicate or --sync-to-master methods, it B<always> makes the changes on
the replication master, B<never> the replication slave directly. This is in
general the only safe way to bring a replica back in sync with its master;
changes to the replica are usually the source of the problems in the first
place. However, the changes it makes on the master should be no-op changes that
set the data to their current values, and actually affect only the replica.
Please read the detailed documentation that follows to learn more about this.
Sync db.tbl on host1 to host2:
pt-table-sync --execute h=host1,D=db,t=tbl h=host2
Sync all tables on host1 to host2 and host3:
pt-table-sync --execute host1 host2 host3
Make slave1 have the same data as its replication master:
pt-table-sync --execute --sync-to-master slave1
Resolve differences that L<pt-table-checksum> found on all slaves of master1:
pt-table-sync --execute --replicate test.checksum master1
Same as above but only resolve differences on slave1:
pt-table-sync --execute --replicate test.checksum \
--sync-to-master slave1
Sync master2 in a master-master replication configuration, where master2's copy
of db.tbl is known or suspected to be incorrect:
pt-table-sync --execute --sync-to-master h=master2,D=db,t=tbl
Note that in the master-master configuration, the following will NOT do what you
want, because it will make changes directly on master2, which will then flow
through replication and change master1's data:
# Don't do this in a master-master setup!
pt-table-sync --execute h=master1,D=db,t=tbl master2
=head1 RISKS
The following section is included to inform users about the potential risks,
whether known or unknown, of using this tool. The two main categories of risks
are those created by the nature of the tool (e.g. read-only tools vs. read-write
tools) and those created by bugs.
With great power comes great responsibility! This tool changes data, so it is a
good idea to back up your data. It is also very powerful, which means it is
very complex, so you should run it with the L<"--dry-run"> option to see what it
will do, until you're familiar with its operation. If you want to see which
rows are different, without changing any data, use L<"--print"> instead of
L<"--execute">.
Be careful when using pt-table-sync in any master-master setup. Master-master
replication is inherently tricky, and it's easy to make mistakes. You need to
be sure you're using the tool correctly for master-master replication. See the
L<"SYNOPSIS"> for the overview of the correct usage.
Also be careful with tables that have foreign key constraints with C<ON DELETE>
or C<ON UPDATE> definitions because these might cause unintended changes on the
child tables.
In general, this tool is best suited when your tables have a primary key or
unique index. Although it can synchronize data in tables lacking a primary key
or unique index, it might be best to synchronize that data by another means.
At the time of this release, due to bugs in earlier versions of MySQL,
L<"--lock-and-rename"> is disabled in versions earlier than 5.5. Consider
using pt-online-schema-change instead.
The authoritative source for updated information is always the online issue
tracking system. Issues that affect this tool will be marked as such. You can
see a list of such issues at the following URL:
L<http://www.percona.com/bugs/pt-table-sync>.
See also L<"BUGS"> for more information on filing bugs and getting help.
=head1 DESCRIPTION
pt-table-sync does one-way and bidirectional synchronization of table data.
It does B<not> synchronize table structures, indexes, or any other schema
objects. The following describes one-way synchronization.
L<"BIDIRECTIONAL SYNCING"> is described later.
This tool is complex and functions in several different ways. To use it
safely and effectively, you should understand three things: the purpose
of L<"--replicate">, finding differences, and specifying hosts. These
three concepts are closely related and determine how the tool will run.
The following is the abbreviated logic:
if DSN has a t part, sync only that table:
if 1 DSN:
if --sync-to-master:
The DSN is a slave. Connect to its master and sync.
if more than 1 DSN:
The first DSN is the source. Sync each DSN in turn.
else if --replicate:
if --sync-to-master:
The DSN is a slave. Connect to its master, find records
of differences, and fix.
else:
The DSN is the master. Find slaves and connect to each,
find records of differences, and fix.
else:
if only 1 DSN and --sync-to-master:
The DSN is a slave. Connect to its master, find tables and
filter with --databases etc, and sync each table to the master.
else:
find tables, filtering with --databases etc, and sync each
DSN to the first.
pt-table-sync can run in one of two ways: with L<"--replicate"> or without.
The default is to run without L<"--replicate"> which causes pt-table-sync
to automatically find differences efficiently with one of several
algorithms (see L<"ALGORITHMS">). Alternatively, the value of
L<"--replicate">, if specified, causes pt-table-sync to use the differences
already found by having previously ran L<pt-table-checksum> with its own
C<--replicate> option. Strictly speaking, you don't need to use
L<"--replicate"> because pt-table-sync can find differences, but many
people use L<"--replicate"> if, for example, they checksum regularly
using L<pt-table-checksum> then fix differences as needed with pt-table-sync.
If you're unsure, read each tool's documentation carefully and decide for
yourself, or consult with an expert.
Regardless of whether L<"--replicate"> is used or not, you need to specify
which hosts to sync. There are two ways: with L<"--sync-to-master"> or
without. Specifying L<"--sync-to-master"> makes pt-table-sync expect
one and only slave DSN on the command line. The tool will automatically
discover the slave's master and sync it so that its data is the same as
its master. This is accomplished by making changes on the master which
then flow through replication and update the slave to resolve its differences.
B<Be careful though>: although this option specifies and syncs a single
slave, if there are other slaves on the same master, they will receive
via replication the changes intended for the slave that you're trying to
sync.
Alternatively, if you do not specify L<"--sync-to-master">, the first
DSN given on the command line is the source host. There is only ever
one source host. If you do not also specify L<"--replicate">, then you
must specify at least one other DSN as the destination host. There
can be one or more destination hosts. Source and destination hosts
must be independent; they cannot be in the same replication topology.
pt-table-sync will die with an error if it detects that a destination
host is a slave because changes are written directly to destination hosts
(and it's not safe to write directly to slaves). Or, if you specify
L<"--replicate"> (but not L<"--sync-to-master">) then pt-table-sync expects
one and only one master DSN on the command line. The tool will automatically
discover all the master's slaves and sync them to the master. This is
the only way to sync several (all) slaves at once (because
L<"--sync-to-master"> only specifies one slave).
Each host on the command line is specified as a DSN. The first DSN
(or only DSN for cases like L<"--sync-to-master">) provides default values
for other DSNs, whether those other DSNs are specified on the command line
or auto-discovered by the tool. So in this example,
pt-table-sync --execute h=host1,u=msandbox,p=msandbox h=host2
the host2 DSN inherits the C<u> and C<p> DSN parts from the host1 DSN.
Use the L<"--explain-hosts"> option to see how pt-table-sync will interpret
the DSNs given on the command line.
=head1 OUTPUT
If you specify the L<"--verbose"> option, you'll see information about the
differences between the tables. There is one row per table. Each server is
printed separately. For example,
# Syncing h=host1,D=test,t=test1
# DELETE REPLACE INSERT UPDATE ALGORITHM START END EXIT DATABASE.TABLE
# 0 0 3 0 Chunk 13:00:00 13:00:17 2 test.test1
Table test.test1 on host1 required 3 C<INSERT> statements to synchronize
and it used the Chunk algorithm (see L<"ALGORITHMS">). The sync operation
for this table started at 13:00:00 and ended 17 seconds later (times taken
from C<NOW()> on the source host). Because differences were found, its
L<"EXIT STATUS"> was 2.
If you specify the L<"--print"> option, you'll see the actual SQL statements
that the script uses to synchronize the table if L<"--execute"> is also
specified.
If you want to see the SQL statements that pt-table-sync is using to select
chunks, nibbles, rows, etc., then specify L<"--print"> once and L<"--verbose">
twice. Be careful though: this can print a lot of SQL statements.
There are cases where no combination of C<INSERT>, C<UPDATE> or C<DELETE>
statements can resolve differences without violating some unique key. For
example, suppose there's a primary key on column a and a unique key on column b.
Then there is no way to sync these two tables with straightforward UPDATE
statements:
+---+---+ +---+---+
| a | b | | a | b |
+---+---+ +---+---+
| 1 | 2 | | 1 | 1 |
| 2 | 1 | | 2 | 2 |
+---+---+ +---+---+
The tool rewrites queries to C<DELETE> and C<REPLACE> in this case. This is
automatically handled after the first index violation, so you don't have to
worry about it.
=head1 REPLICATION SAFETY
Synchronizing a replication master and slave safely is a non-trivial problem, in
general. There are all sorts of issues to think about, such as other processes
changing data, trying to change data on the slave, whether the destination and
source are a master-master pair, and much more.
In general, the safe way to do it is to change the data on the master, and let
the changes flow through replication to the slave like any other changes.
However, this works only if it's possible to REPLACE into the table on the
master. REPLACE works only if there's a unique index on the table (otherwise it
just acts like an ordinary INSERT).
If your table has unique keys, you should use the L<"--sync-to-master"> and/or
L<"--replicate"> options to sync a slave to its master. This will generally do
the right thing. When there is no unique key on the table, there is no choice
but to change the data on the slave, and pt-table-sync will detect that you're
trying to do so. It will complain and die unless you specify
C<--no-check-slave> (see L<"--[no]check-slave">).
If you're syncing a table without a primary or unique key on a master-master
pair, you must change the data on the destination server. Therefore, you need
to specify C<--no-bin-log> for safety (see L<"--[no]bin-log">). If you don't,
the changes you make on the destination server will replicate back to the
source server and change the data there!
The generally safe thing to do on a master-master pair is to use the
L<"--sync-to-master"> option so you don't change the data on the destination
server. You will also need to specify C<--no-check-slave> to keep
pt-table-sync from complaining that it is changing data on a slave.
=head1 ALGORITHMS
pt-table-sync has a generic data-syncing framework which uses different
algorithms to find differences. The tool automatically chooses the best
algorithm for each table based on indexes, column types, and the algorithm
preferences specified by L<"--algorithms">. The following algorithms are
available, listed in their default order of preference:
=over
=item Chunk
Finds an index whose first column is numeric (including date and time types),
and divides the column's range of values into chunks of approximately
L<"--chunk-size"> rows. Syncs a chunk at a time by checksumming the entire
chunk. If the chunk differs on the source and destination, checksums each
chunk's rows individually to find the rows that differ.
It is efficient when the column has sufficient cardinality to make the chunks
end up about the right size.
The initial per-chunk checksum is quite small and results in minimal network
traffic and memory consumption. If a chunk's rows must be examined, only the
primary key columns and a checksum are sent over the network, not the entire
row. If a row is found to be different, the entire row will be fetched, but not
before.
=item Nibble
Finds an index and ascends the index in fixed-size nibbles of L<"--chunk-size">
rows, using a non-backtracking algorithm (see L<pt-archiver> for more on this
algorithm). It is very similar to L<"Chunk">, but instead of pre-calculating
the boundaries of each piece of the table based on index cardinality, it uses
C<LIMIT> to define each nibble's upper limit, and the previous nibble's upper
limit to define the lower limit.
It works in steps: one query finds the row that will define the next nibble's
upper boundary, and the next query checksums the entire nibble. If the nibble
differs between the source and destination, it examines the nibble row-by-row,
just as L<"Chunk"> does.
=item GroupBy
Selects the entire table grouped by all columns, with a COUNT(*) column added.
Compares all columns, and if they're the same, compares the COUNT(*) column's
value to determine how many rows to insert or delete into the destination.
Works on tables with no primary key or unique index.
=item Stream
Selects the entire table in one big stream and compares all columns. Selects
all columns. Much less efficient than the other algorithms, but works when
there is no suitable index for them to use.
=item Future Plans
Possibilities for future algorithms are TempTable (what I originally called
bottom-up in earlier versions of this tool), DrillDown (what I originally
called top-down), and GroupByPrefix (similar to how SqlYOG Job Agent works).
Each algorithm has strengths and weaknesses. If you'd like to implement your
favorite technique for finding differences between two sources of data on
possibly different servers, I'm willing to help. The algorithms adhere to a
simple interface that makes it pretty easy to write your own.
=back
=head1 BIDIRECTIONAL SYNCING
Bidirectional syncing is a new, experimental feature. To make it work
reliably there are a number of strict limitations:
* only works when syncing one server to other independent servers
* does not work in any way with replication
* requires that the table(s) are chunkable with the Chunk algorithm
* is not N-way, only bidirectional between two servers at a time
* does not handle DELETE changes
For example, suppose we have three servers: c1, r1, r2. c1 is the central
server, a pseudo-master to the other servers (viz. r1 and r2 are not slaves
to c1). r1 and r2 are remote servers. Rows in table foo are updated and
inserted on all three servers and we want to synchronize all the changes
between all the servers. Table foo has columns:
id int PRIMARY KEY
ts timestamp auto updated
name varchar
Auto-increment offsets are used so that new rows from any server do not
create conflicting primary key (id) values. In general, newer rows, as
determined by the ts column, take precedence when a same but differing row
is found during the bidirectional sync. "Same but differing" means that
two rows have the same primary key (id) value but different values for some
other column, like the name column in this example. Same but differing
conflicts are resolved by a "conflict". A conflict compares some column of
the competing rows to determine a "winner". The winning row becomes the
source and its values are used to update the other row.
There are subtle differences between three columns used to achieve
bidirectional syncing that you should be familiar with: chunk column
(L<"--chunk-column">), comparison column(s) (L<"--columns">), and conflict
column (L<"--conflict-column">). The chunk column is only used to chunk the
table; e.g. "WHERE id >= 5 AND id < 10". Chunks are checksummed and when
chunk checksums reveal a difference, the tool selects the rows in that
chunk and checksums the L<"--columns"> for each row. If a column checksum
differs, the rows have one or more conflicting column values. In a
traditional unidirectional sync, the conflict is a moot point because it can
be resolved simply by updating the entire destination row with the source
row's values. In a bidirectional sync, however, the L<"--conflict-column">
(in accordance with other C<--conflict-*> options list below) is compared
to determine which row is "correct" or "authoritative"; this row becomes
the "source".
To sync all three servers completely, two runs of pt-table-sync are required.
The first run syncs c1 and r1, then syncs c1 and r2 including any changes
from r1. At this point c1 and r2 are completely in sync, but r1 is missing
any changes from r2 because c1 didn't have these changes when it and r1
were synced. So a second run is needed which syncs the servers in the same
order, but this time when c1 and r1 are synced r1 gets r2's changes.
The tool does not sync N-ways, only bidirectionally between the first DSN
given on the command line and each subsequent DSN in turn. So the tool in
this example would be ran twice like:
pt-table-sync --bidirectional h=c1 h=r1 h=r2
The L<"--bidirectional"> option enables this feature and causes various
sanity checks to be performed. You must specify other options that tell
pt-table-sync how to resolve conflicts for same but differing rows.
These options are:
* --conflict-column
* --conflict-comparison
* --conflict-value
* --conflict-threshold
* --conflict-error"> (optional)
Use L<"--print"> to test this option before L<"--execute">. The printed
SQL statements will have comments saying on which host the statement
would be executed if you used L<"--execute">.
Technical side note: the first DSN is always the "left" server and the other
DSNs are always the "right" server. Since either server can become the source
or destination it's confusing to think of them as "src" and "dst". Therefore,
they're generically referred to as left and right. It's easy to remember
this because the first DSN is always to the left of the other server DSNs on
the command line.
=head1 EXIT STATUS
The following are the exit statuses (also called return values, or return codes)
when pt-table-sync finishes and exits.
STATUS MEANING
====== =======================================================
0 Success.
1 Internal error.
2 At least one table differed on the destination.
3 Combination of 1 and 2.
=head1 OPTIONS
Specify at least one of L<"--print">, L<"--execute">, or L<"--dry-run">.
L<"--where"> and L<"--replicate"> are mutually exclusive.
This tool accepts additional command-line arguments. Refer to the
L<"SYNOPSIS"> and usage information for details.
=over
=item --algorithms
type: string; default: Chunk,Nibble,GroupBy,Stream
Algorithm to use when comparing the tables, in order of preference.
For each table, pt-table-sync will check if the table can be synced with
the given algorithms in the order that they're given. The first algorithm
that can sync the table is used. See L<"ALGORITHMS">.
=item --ask-pass
Prompt for a password when connecting to MySQL.
=item --bidirectional
Enable bidirectional sync between first and subsequent hosts.
See L<"BIDIRECTIONAL SYNCING"> for more information.
=item --[no]bin-log
default: yes
Log to the binary log (C<SET SQL_LOG_BIN=1>).
Specifying C<--no-bin-log> will C<SET SQL_LOG_BIN=0>.
=item --buffer-in-mysql
Instruct MySQL to buffer queries in its memory.
This option adds the C<SQL_BUFFER_RESULT> option to the comparison queries.
This causes MySQL to execute the queries and place them in a temporary table
internally before sending the results back to pt-table-sync. The advantage of
this strategy is that pt-table-sync can fetch rows as desired without using a
lot of memory inside the Perl process, while releasing locks on the MySQL table
(to reduce contention with other queries). The disadvantage is that it uses
more memory on the MySQL server instead.
You probably want to leave L<"--[no]buffer-to-client"> enabled too, because
buffering into a temp table and then fetching it all into Perl's memory is
probably a silly thing to do. This option is most useful for the GroupBy and
Stream algorithms, which may fetch a lot of data from the server.
=item --[no]buffer-to-client
default: yes
Fetch rows one-by-one from MySQL while comparing.
This option enables C<mysql_use_result> which causes MySQL to hold the selected
rows on the server until the tool fetches them. This allows the tool to use
less memory but may keep the rows locked on the server longer.
If this option is disabled by specifying C<--no-buffer-to-client> then
C<mysql_store_result> is used which causes MySQL to send all selected rows to
the tool at once. This may result in the results "cursor" being held open for
a shorter time on the server, but if the tables are large, it could take a long
time anyway, and use all your memory.
For most non-trivial data sizes, you want to leave this option enabled.
This option is disabled when L<"--bidirectional"> is used.
=item --charset
short form: -A; type: string
Default character set. If the value is utf8, sets Perl's binmode on
STDOUT to utf8, passes the mysql_enable_utf8 option to DBD::mysql, and
runs SET NAMES UTF8 after connecting to MySQL. Any other value sets
binmode on STDOUT without the utf8 layer, and runs SET NAMES after
connecting to MySQL.
=item --[no]check-master
default: yes
With L<"--sync-to-master">, try to verify that the detected
master is the real master.
=item --[no]check-privileges
default: yes
Check that user has all necessary privileges on source and destination table.
=item --[no]check-slave
default: yes
Check whether the destination server is a slave.
If the destination server is a slave, it's generally unsafe to make changes on
it. However, sometimes you have to; L<"--replace"> won't work unless there's a
unique index, for example, so you can't make changes on the master in that
scenario. By default pt-table-sync will complain if you try to change data on
a slave. Specify C<--no-check-slave> to disable this check. Use it at your own
risk.
=item --[no]check-triggers
default: yes
Check that no triggers are defined on the destination table.
Triggers were introduced in MySQL v5.0.2, so for older versions this option
has no effect because triggers will not be checked.
=item --chunk-column
type: string
Chunk the table on this column.
=item --chunk-index
type: string
Chunk the table using this index.
=item --chunk-size
type: string; default: 1000
Number of rows or data size per chunk.
The size of each chunk of rows for the L<"Chunk"> and L<"Nibble"> algorithms.
The size can be either a number of rows, or a data size. Data sizes are
specified with a suffix of k=kibibytes, M=mebibytes, G=gibibytes. Data sizes
are converted to a number of rows by dividing by the average row length.
=item --columns
short form: -c; type: array
Compare this comma-separated list of columns.
=item --config
type: Array
Read this comma-separated list of config files; if specified, this must be the
first option on the command line.
=item --conflict-column
type: string
Compare this column when rows conflict during a L<"--bidirectional"> sync.
When a same but differing row is found the value of this column from each
row is compared according to L<"--conflict-comparison">, L<"--conflict-value">
and L<"--conflict-threshold"> to determine which row has the correct data and
becomes the source. The column can be any type for which there is an
appropriate L<"--conflict-comparison"> (this is almost all types except, for
example, blobs).
This option only works with L<"--bidirectional">.
See L<"BIDIRECTIONAL SYNCING"> for more information.
=item --conflict-comparison
type: string
Choose the L<"--conflict-column"> with this property as the source.
The option affects how the L<"--conflict-column"> values from the conflicting
rows are compared. Possible comparisons are one of these MAGIC_comparisons:
newest|oldest|greatest|least|equals|matches
COMPARISON CHOOSES ROW WITH
========== =========================================================
newest Newest temporal --conflict-column value
oldest Oldest temporal --conflict-column value
greatest Greatest numerical "--conflict-column value
least Least numerical --conflict-column value
equals --conflict-column value equal to --conflict-value
matches --conflict-column value matching Perl regex pattern
--conflict-value
This option only works with L<"--bidirectional">.
See L<"BIDIRECTIONAL SYNCING"> for more information.
=item --conflict-error
type: string; default: warn
How to report unresolvable conflicts and conflict errors
This option changes how the user is notified when a conflict cannot be
resolved or causes some kind of error. Possible values are:
* warn: Print a warning to STDERR about the unresolvable conflict
* die: Die, stop syncing, and print a warning to STDERR
This option only works with L<"--bidirectional">.
See L<"BIDIRECTIONAL SYNCING"> for more information.
=item --conflict-threshold
type: string
Amount by which one L<"--conflict-column"> must exceed the other.
The L<"--conflict-threshold"> prevents a conflict from being resolved if
the absolute difference between the two L<"--conflict-column"> values is
less than this amount. For example, if two L<"--conflict-column"> have
timestamp values "2009-12-01 12:00:00" and "2009-12-01 12:05:00" the difference
is 5 minutes. If L<"--conflict-threshold"> is set to "5m" the conflict will
be resolved, but if L<"--conflict-threshold"> is set to "6m" the conflict
will fail to resolve because the difference is not greater than or equal
to 6 minutes. In this latter case, L<"--conflict-error"> will report
the failure.
This option only works with L<"--bidirectional">.
See L<"BIDIRECTIONAL SYNCING"> for more information.
=item --conflict-value
type: string
Use this value for certain L<"--conflict-comparison">.
This option gives the value for C<equals> and C<matches>
L<"--conflict-comparison">.
This option only works with L<"--bidirectional">.
See L<"BIDIRECTIONAL SYNCING"> for more information.
=item --databases
short form: -d; type: hash
Sync only this comma-separated list of databases.
A common request is to sync tables from one database with tables from another
database on the same or different server. This is not yet possible.
L<"--databases"> will not do it, and you can't do it with the D part of the DSN
either because in the absence of a table name it assumes the whole server
should be synced and the D part controls only the connection's default database.
=item --defaults-file
short form: -F; type: string
Only read mysql options from the given file. You must give an absolute pathname.
=item --dry-run
Analyze, decide the sync algorithm to use, print and exit.
Implies L<"--verbose"> so you can see the results. The results are in the same
output format that you'll see from actually running the tool, but there will be
zeros for rows affected. This is because the tool actually executes, but stops
before it compares any data and just returns zeros. The zeros do not mean there
are no changes to be made.
=item --engines
short form: -e; type: hash
Sync only this comma-separated list of storage engines.
=item --execute
Execute queries to make the tables have identical data.
This option makes pt-table-sync actually sync table data by executing all
the queries that it created to resolve table differences. Therefore, B<the
tables will be changed!> And unless you also specify L<"--verbose">, the
changes will be made silently. If this is not what you want, see
L<"--print"> or L<"--dry-run">.
=item --explain-hosts
Print connection information and exit.
Print out a list of hosts to which pt-table-sync will connect, with all
the various connection options, and exit.
=item --float-precision
type: int
Precision for C<FLOAT> and C<DOUBLE> number-to-string conversion. Causes FLOAT
and DOUBLE values to be rounded to the specified number of digits after the
decimal point, with the ROUND() function in MySQL. This can help avoid
checksum mismatches due to different floating-point representations of the same
values on different MySQL versions and hardware. The default is no rounding;
the values are converted to strings by the CONCAT() function, and MySQL chooses
the string representation. If you specify a value of 2, for example, then the
values 1.008 and 1.009 will be rounded to 1.01, and will checksum as equal.
=item --[no]foreign-key-checks
default: yes
Enable foreign key checks (C<SET FOREIGN_KEY_CHECKS=1>).
Specifying C<--no-foreign-key-checks> will C<SET FOREIGN_KEY_CHECKS=0>.
=item --function
type: string
Which hash function you'd like to use for checksums.
The default is C<CRC32>. Other good choices include C<MD5> and C<SHA1>. If you
have installed the C<FNV_64> user-defined function, C<pt-table-sync> will detect
it and prefer to use it, because it is much faster than the built-ins. You can
also use MURMUR_HASH if you've installed that user-defined function. Both of
these are distributed with Maatkit. See L<pt-table-checksum> for more
information and benchmarks.
=item --help
Show help and exit.
=item --[no]hex-blob
default: yes
C<HEX()> C<BLOB>, C<TEXT> and C<BINARY> columns.
When row data from the source is fetched to create queries to sync the
data (i.e. the queries seen with L<"--print"> and executed by L<"--execute">),
binary columns are wrapped in HEX() so the binary data does not produce
an invalid SQL statement. You can disable this option but you probably
shouldn't.
=item --host
short form: -h; type: string
Connect to host.
=item --ignore-columns
type: Hash
Ignore this comma-separated list of column names in comparisons.
This option causes columns not to be compared. However, if a row is determined
to differ between tables, all columns in that row will be synced, regardless.
(It is not currently possible to exclude columns from the sync process itself,
only from the comparison.)
=item --ignore-databases
type: Hash
Ignore this comma-separated list of databases.
=item --ignore-engines
type: Hash; default: FEDERATED,MRG_MyISAM
Ignore this comma-separated list of storage engines.
=item --ignore-tables
type: Hash
Ignore this comma-separated list of tables.
Table names may be qualified with the database name.
=item --[no]index-hint
default: yes
Add FORCE/USE INDEX hints to the chunk and row queries.
By default C<pt-table-sync> adds a FORCE/USE INDEX hint to each SQL statement
to coerce MySQL into using the index chosen by the sync algorithm or specified
by L<"--chunk-index">. This is usually a good thing, but in rare cases the
index may not be the best for the query so you can suppress the index hint
by specifying C<--no-index-hint> and let MySQL choose the index.
This does not affect the queries printed by L<"--print">; it only affects the
chunk and row queries that C<pt-table-sync> uses to select and compare rows.
=item --lock
type: int
Lock tables: 0=none, 1=per sync cycle, 2=per table, or 3=globally.
This uses C<LOCK TABLES>. This can help prevent tables being changed while
you're examining them. The possible values are as follows:
VALUE MEANING
===== =======================================================
0 Never lock tables.
1 Lock and unlock one time per sync cycle (as implemented
by the syncing algorithm). This is the most granular
level of locking available. For example, the Chunk
algorithm will lock each chunk of C<N> rows, and then
unlock them if they are the same on the source and the
destination, before moving on to the next chunk.
2 Lock and unlock before and after each table.
3 Lock and unlock once for every server (DSN) synced, with
C<FLUSH TABLES WITH READ LOCK>.
A replication slave is never locked if L<"--replicate"> or L<"--sync-to-master">
is specified, since in theory locking the table on the master should prevent any
changes from taking place. (You are not changing data on your slave, right?)
If L<"--wait"> is given, the master (source) is locked and then the tool waits
for the slave to catch up to the master before continuing.
If C<--transaction> is specified, C<LOCK TABLES> is not used. Instead, lock
and unlock are implemented by beginning and committing transactions.
The exception is if L<"--lock"> is 3.
If C<--no-transaction> is specified, then C<LOCK TABLES> is used for any
value of L<"--lock">. See L<"--[no]transaction">.
=item --lock-and-rename
Lock the source and destination table, sync, then swap names. This is useful as
a less-blocking ALTER TABLE, once the tables are reasonably in sync with each
other (which you may choose to accomplish via any number of means, including
dump and reload or even something like L<pt-archiver>). It requires exactly two
DSNs and assumes they are on the same server, so it does no waiting for
replication or the like. Tables are locked with LOCK TABLES.
=item --password
short form: -p; type: string
Password to use when connecting.
=item --pid
type: string
Create the given PID file. The file contains the process ID of the script.
The PID file is removed when the script exits. Before starting, the script
checks if the PID file already exists. If it does not, then the script creates
and writes its own PID to it. If it does, then the script checks the following:
if the file contains a PID and a process is running with that PID, then
the script dies; or, if there is no process running with that PID, then the
script overwrites the file with its own PID and starts; else, if the file
contains no PID, then the script dies.
=item --port
short form: -P; type: int
Port number to use for connection.
=item --print
Print queries that will resolve differences.
If you don't trust C<pt-table-sync>, or just want to see what it will do, this
is a good way to be safe. These queries are valid SQL and you can run them
yourself if you want to sync the tables manually.
=item --recursion-method
type: string
Preferred recursion method used to find slaves.
Possible methods are:
METHOD USES
=========== ==================
processlist SHOW PROCESSLIST
hosts SHOW SLAVE HOSTS
none Do not find slaves
The processlist method is preferred because SHOW SLAVE HOSTS is not reliable.
However, the hosts method is required if the server uses a non-standard
port (not 3306). Usually pt-table-sync does the right thing and finds
the slaves, but you may give a preferred method and it will be used first.
If it doesn't find any slaves, the other methods will be tried.
=item --replace
Write all C<INSERT> and C<UPDATE> statements as C<REPLACE>.
This is automatically switched on as needed when there are unique index
violations.
=item --replicate
type: string
Sync tables listed as different in this table.
Specifies that C<pt-table-sync> should examine the specified table to find data
that differs. The table is exactly the same as the argument of the same name to
L<pt-table-checksum>. That is, it contains records of which tables (and ranges
of values) differ between the master and slave.
For each table and range of values that shows differences between the master and
slave, C<pt-table-checksum> will sync that table, with the appropriate C<WHERE>
clause, to its master.
This automatically sets L<"--wait"> to 60 and causes changes to be made on the
master instead of the slave.
If L<"--sync-to-master"> is specified, the tool will assume the server you
specified is the slave, and connect to the master as usual to sync.
Otherwise, it will try to use C<SHOW PROCESSLIST> to find slaves of the server
you specified. If it is unable to find any slaves via C<SHOW PROCESSLIST>, it
will inspect C<SHOW SLAVE HOSTS> instead. You must configure each slave's
C<report-host>, C<report-port> and other options for this to work right. After
finding slaves, it will inspect the specified table on each slave to find data
that needs to be synced, and sync it.
The tool examines the master's copy of the table first, assuming that the master
is potentially a slave as well. Any table that shows differences there will
B<NOT> be synced on the slave(s). For example, suppose your replication is set
up as A->B, B->C, B->D. Suppose you use this argument and specify server B.
The tool will examine server B's copy of the table. If it looks like server B's
data in table C<test.tbl1> is different from server A's copy, the tool will not
sync that table on servers C and D.
=item --set-vars
type: string; default: wait_timeout=10000
Set these MySQL variables. Immediately after connecting to MySQL, this
string will be appended to SET and executed.
=item --socket
short form: -S; type: string
Socket file to use for connection.
=item --sync-to-master
Treat the DSN as a slave and sync it to its master.
Treat the server you specified as a slave. Inspect C<SHOW SLAVE STATUS>,
connect to the server's master, and treat the master as the source and the slave
as the destination. Causes changes to be made on the master. Sets L<"--wait">
to 60 by default, sets L<"--lock"> to 1 by default, and disables
L<"--[no]transaction"> by default. See also L<"--replicate">, which changes
this option's behavior.
=item --tables
short form: -t; type: hash
Sync only this comma-separated list of tables.
Table names may be qualified with the database name.
=item --timeout-ok
Keep going if L<"--wait"> fails.
If you specify L<"--wait"> and the slave doesn't catch up to the master's
position before the wait times out, the default behavior is to abort. This
option makes the tool keep going anyway. B<Warning>: if you are trying to get a
consistent comparison between the two servers, you probably don't want to keep
going after a timeout.
=item --[no]transaction
Use transactions instead of C<LOCK TABLES>.
The granularity of beginning and committing transactions is controlled by
L<"--lock">. This is enabled by default, but since L<"--lock"> is disabled by
default, it has no effect.
Most options that enable locking also disable transactions by default, so if
you want to use transactional locking (via C<LOCK IN SHARE MODE> and C<FOR
UPDATE>, you must specify C<--transaction> explicitly.
If you don't specify C<--transaction> explicitly C<pt-table-sync> will decide on
a per-table basis whether to use transactions or table locks. It currently
uses transactions on InnoDB tables, and table locks on all others.
If C<--no-transaction> is specified, then C<pt-table-sync> will not use
transactions at all (not even for InnoDB tables) and locking is controlled
by L<"--lock">.
When enabled, either explicitly or implicitly, the transaction isolation level
is set C<REPEATABLE READ> and transactions are started C<WITH CONSISTENT
SNAPSHOT>.
=item --trim
C<TRIM()> C<VARCHAR> columns in C<BIT_XOR> and C<ACCUM> modes. Helps when
comparing MySQL 4.1 to >= 5.0.
This is useful when you don't care about the trailing space differences between
MySQL versions which vary in their handling of trailing spaces. MySQL 5.0 and
later all retain trailing spaces in C<VARCHAR>, while previous versions would
remove them.
=item --[no]unique-checks
default: yes
Enable unique key checks (C<SET UNIQUE_CHECKS=1>).
Specifying C<--no-unique-checks> will C<SET UNIQUE_CHECKS=0>.
=item --user
short form: -u; type: string
User for login if not current user.
=item --verbose
short form: -v; cumulative: yes
Print results of sync operations.
See L<"OUTPUT"> for more details about the output.
=item --version
Show version and exit.
=item --wait
short form: -w; type: time
How long to wait for slaves to catch up to their master.
Make the master wait for the slave to catch up in replication before comparing
the tables. The value is the number of seconds to wait before timing out (see
also L<"--timeout-ok">). Sets L<"--lock"> to 1 and L<"--[no]transaction"> to 0
by default. If you see an error such as the following,
MASTER_POS_WAIT returned -1
It means the timeout was exceeded and you need to increase it.
The default value of this option is influenced by other options. To see what
value is in effect, run with L<"--help">.
To disable waiting entirely (except for locks), specify L<"--wait"> 0. This
helps when the slave is lagging on tables that are not being synced.
=item --where
type: string
C<WHERE> clause to restrict syncing to part of the table.
=item --[no]zero-chunk
default: yes
Add a chunk for rows with zero or zero-equivalent values. The only has an
effect when L<"--chunk-size"> is specified. The purpose of the zero chunk
is to capture a potentially large number of zero values that would imbalance
the size of the first chunk. For example, if a lot of negative numbers were
inserted into an unsigned integer column causing them to be stored as zeros,
then these zero values are captured by the zero chunk instead of the first
chunk and all its non-zero values.
=back
=head1 DSN OPTIONS
These DSN options are used to create a DSN. Each option is given like
C<option=value>. The options are case-sensitive, so P and p are not the
same option. There cannot be whitespace before or after the C<=> and
if the value contains whitespace it must be quoted. DSN options are
comma-separated. See the L<percona-toolkit> manpage for full details.
=over
=item * A
dsn: charset; copy: yes
Default character set.
=item * D
dsn: database; copy: yes
Database containing the table to be synced.
=item * F
dsn: mysql_read_default_file; copy: yes
Only read default options from the given file
=item * h
dsn: host; copy: yes
Connect to host.
=item * p
dsn: password; copy: yes
Password to use when connecting.
=item * P
dsn: port; copy: yes
Port number to use for connection.
=item * S
dsn: mysql_socket; copy: yes
Socket file to use for connection.
=item * t
copy: yes
Table to be synced.
=item * u
dsn: user; copy: yes
User for login if not current user.
=back
=head1 ENVIRONMENT
The environment variable C<PTDEBUG> enables verbose debugging output to STDERR.
To enable debugging and capture all output to a file, run the tool like:
PTDEBUG=1 pt-table-sync ... > FILE 2>&1
Be careful: debugging output is voluminous and can generate several megabytes
of output.
=head1 SYSTEM REQUIREMENTS
You need Perl, DBI, DBD::mysql, and some core packages that ought to be
installed in any reasonably new version of Perl.
=head1 BUGS
For a list of known bugs, see L<http://www.percona.com/bugs/pt-table-sync>.
Please report bugs at L<https://bugs.launchpad.net/percona-toolkit>.
Include the following information in your bug report:
=over
=item * Complete command-line used to run the tool
=item * Tool L<"--version">
=item * MySQL version of all servers involved
=item * Output from the tool including STDERR
=item * Input files (log/dump/config files, etc.)
=back
If possible, include debugging output by running the tool with C<PTDEBUG>;
see L<"ENVIRONMENT">.
=head1 DOWNLOADING
Visit L<http://www.percona.com/software/percona-toolkit/> to download the
latest release of Percona Toolkit. Or, get the latest release from the
command line:
wget percona.com/get/percona-toolkit.tar.gz
wget percona.com/get/percona-toolkit.rpm
wget percona.com/get/percona-toolkit.deb
You can also get individual tools from the latest release:
wget percona.com/get/TOOL
Replace C<TOOL> with the name of any tool.
=head1 AUTHORS
Baron Schwartz
=head1 ACKNOWLEDGMENTS
My work is based in part on Giuseppe Maxia's work on distributed databases,
L<http://www.sysadminmag.com/articles/2004/0408/> and code derived from that
article. There is more explanation, and a link to the code, at
L<http://www.perlmonks.org/?node_id=381053>.
Another programmer extended Maxia's work even further. Fabien Coelho changed
and generalized Maxia's technique, introducing symmetry and avoiding some
problems that might have caused too-frequent checksum collisions. This work
grew into pg_comparator, L<http://www.coelho.net/pg_comparator/>. Coelho also
explained the technique further in a paper titled "Remote Comparison of Database
Tables" (L<http://cri.ensmp.fr/classement/doc/A-375.pdf>).
This existing literature mostly addressed how to find the differences between
the tables, not how to resolve them once found. I needed a tool that would not
only find them efficiently, but would then resolve them. I first began thinking
about how to improve the technique further with my article
L<http://tinyurl.com/mysql-data-diff-algorithm>,
where I discussed a number of problems with the Maxia/Coelho "bottom-up"
algorithm. After writing that article, I began to write this tool. I wanted to
actually implement their algorithm with some improvements so I was sure I
understood it completely. I discovered it is not what I thought it was, and is
considerably more complex than it appeared to me at first. Fabien Coelho was
kind enough to address some questions over email.
The first versions of this tool implemented a version of the Coelho/Maxia
algorithm, which I called "bottom-up", and my own, which I called "top-down."
Those algorithms are considerably more complex than the current algorithms and
I have removed them from this tool, and may add them back later. The
improvements to the bottom-up algorithm are my original work, as is the
top-down algorithm. The techniques to actually resolve the differences are
also my own work.
Another tool that can synchronize tables is the SQLyog Job Agent from webyog.
Thanks to Rohit Nadhani, SJA's author, for the conversations about the general
techniques. There is a comparison of pt-table-sync and SJA at
L<http://tinyurl.com/maatkit-vs-sqlyog>
Thanks to the following people and organizations for helping in many ways:
The Rimm-Kaufman Group L<http://www.rimmkaufman.com/>,
MySQL AB L<http://www.mysql.com/>,
Blue Ridge InternetWorks L<http://www.briworks.com/>,
Percona L<http://www.percona.com/>,
Fabien Coelho,
Giuseppe Maxia and others at MySQL AB,
Kristian Koehntopp (MySQL AB),
Rohit Nadhani (WebYog),
The helpful monks at Perlmonks,
And others too numerous to mention.
=head1 ABOUT PERCONA TOOLKIT
This tool is part of Percona Toolkit, a collection of advanced command-line
tools developed by Percona for MySQL support and consulting. Percona Toolkit
was forked from two projects in June, 2011: Maatkit and Aspersa. Those
projects were created by Baron Schwartz and developed primarily by him and
Daniel Nichter, both of whom are employed by Percona. Visit
L<http://www.percona.com/software/> for more software developed by Percona.
=head1 COPYRIGHT, LICENSE, AND WARRANTY
This program is copyright 2007-2011 Baron Schwartz, 2011-2012 Percona Inc.
Feedback and improvements are welcome.
THIS PROGRAM IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, version 2; OR the Perl Artistic License. On UNIX and similar
systems, you can issue `man perlgpl' or `man perlartistic' to read these
licenses.
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., 59 Temple
Place, Suite 330, Boston, MA 02111-1307 USA.
=head1 VERSION
pt-table-sync 2.1.2
=cut
|