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
|
# Copyright (c) 2010-2012 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for swift.obj.diskfile"""
import pickle
import binascii
import os
import errno
import itertools
from unittest import mock
import unittest
import email
import tempfile
import threading
import uuid
import xattr
import re
import sys
from collections import defaultdict
from random import shuffle, randint
from shutil import rmtree
from time import time
from tempfile import mkdtemp
from contextlib import contextmanager
import pyeclib.ec_iface
from eventlet import hubs, timeout, tpool, spawn, sleep
from swift.obj.diskfile import update_auditor_status, EUCLEAN
from test import BaseTestCase
from test.debug_logger import debug_logger
from test.unit import (mock as unit_mock, temptree, mock_check_drive,
patch_policies, make_timestamp_iter,
DEFAULT_TEST_EC_TYPE, requires_o_tmpfile_support_in_tmp,
encode_frag_archive_bodies, skip_if_no_xattrs)
from swift.obj import diskfile
from swift.common import utils
from swift.common.utils import hash_path, mkdirs, Timestamp, lock_path, \
encode_timestamps, O_TMPFILE, md5 as _md5, MD5_OF_EMPTY_STRING
from swift.common import ring
from swift.common.splice import splice
from swift.common.exceptions import DiskFileNotExist, DiskFileQuarantined, \
DiskFileDeviceUnavailable, DiskFileDeleted, DiskFileNotOpen, \
DiskFileError, ReplicationLockTimeout, DiskFileCollision, \
DiskFileExpired, SwiftException, DiskFileNoSpace, \
DiskFileXattrNotSupported, PartitionLockTimeout, DiskFileStateChanged
from swift.common.storage_policy import (
POLICIES, get_policy_string, StoragePolicy, ECStoragePolicy, REPL_POLICY,
EC_POLICY, PolicyError)
from test.unit.obj.common import write_diskfile
test_policies = [
StoragePolicy(0, name='zero', is_default=True),
ECStoragePolicy(1, name='one', is_default=False,
ec_type=DEFAULT_TEST_EC_TYPE,
ec_ndata=10, ec_nparity=4),
]
class md5(object):
def __init__(self, s=b''):
if not isinstance(s, bytes):
s = s.encode('ascii')
self.md = _md5(s, usedforsecurity=False)
def update(self, s=b''):
if not isinstance(s, bytes):
s = s.encode('ascii')
return self.md.update(s)
@property
def hexdigest(self):
return self.md.hexdigest
@property
def digest(self):
return self.md.digest
def find_paths_with_matching_suffixes(needed_matches=2, needed_suffixes=3):
paths = defaultdict(list)
while True:
path = ('a', 'c', uuid.uuid4().hex)
hash_ = hash_path(*path)
suffix = hash_[-3:]
paths[suffix].append(path)
if len(paths) < needed_suffixes:
# in the extreamly unlikely situation where you land the matches
# you need before you get the total suffixes you need - it's
# simpler to just ignore this suffix for now
continue
if len(paths[suffix]) >= needed_matches:
break
return paths, suffix
def _create_test_ring(path, policy):
ring_name = get_policy_string('object', policy)
testgz = os.path.join(path, ring_name + '.ring.gz')
intended_replica2part2dev_id = [
[0, 1, 2, 3, 4, 5, 6],
[1, 2, 3, 0, 5, 6, 4],
[2, 3, 0, 1, 6, 4, 5]]
intended_devs = [
{'id': 0, 'device': 'sda1', 'region': 1, 'zone': 0, 'ip': '127.0.0.0',
'port': 6200},
{'id': 1, 'device': 'sda1', 'region': 1, 'zone': 1, 'ip': '127.0.0.1',
'port': 6200},
{'id': 2, 'device': 'sda1', 'region': 1, 'zone': 2, 'ip': '127.0.0.2',
'port': 6200},
{'id': 3, 'device': 'sda1', 'region': 1, 'zone': 4, 'ip': '127.0.0.3',
'port': 6200},
{'id': 4, 'device': 'sda1', 'region': 1, 'zone': 5, 'ip': '127.0.0.4',
'port': 6200},
{'id': 5, 'device': 'sda1', 'region': 1, 'zone': 6,
'ip': 'fe80::202:b3ff:fe1e:8329', 'port': 6200},
{'id': 6, 'device': 'sda1', 'region': 1, 'zone': 7,
'ip': '2001:0db8:85a3:0000:0000:8a2e:0370:7334',
'port': 6200}]
intended_part_shift = 30
intended_reload_time = 15
ring.RingData(intended_replica2part2dev_id, intended_devs,
intended_part_shift).save(testgz)
return ring.Ring(path, ring_name=ring_name,
reload_time=intended_reload_time)
def _make_datafilename(timestamp, policy, frag_index=None, durable=False):
if frag_index is None:
frag_index = randint(0, 9)
filename = timestamp.internal
if policy.policy_type == EC_POLICY:
filename += '#%d' % int(frag_index)
if durable:
filename += '#d'
filename += '.data'
return filename
def _make_metafilename(meta_timestamp, ctype_timestamp=None):
filename = meta_timestamp.internal
if ctype_timestamp is not None:
delta = meta_timestamp.raw - ctype_timestamp.raw
filename = '%s-%x' % (filename, delta)
filename += '.meta'
return filename
@patch_policies
class TestDiskFileModuleMethods(unittest.TestCase):
def setUp(self):
skip_if_no_xattrs()
utils.HASH_PATH_SUFFIX = b'endcap'
utils.HASH_PATH_PREFIX = b''
# Setup a test ring per policy (stolen from common/test_ring.py)
self.testdir = tempfile.mkdtemp()
self.devices = os.path.join(self.testdir, 'node')
rmtree(self.testdir, ignore_errors=1)
os.mkdir(self.testdir)
os.mkdir(self.devices)
self.existing_device = 'sda1'
os.mkdir(os.path.join(self.devices, self.existing_device))
self.objects = os.path.join(self.devices, self.existing_device,
'objects')
os.mkdir(self.objects)
self.parts = {}
for part in ['0', '1', '2', '3']:
self.parts[part] = os.path.join(self.objects, part)
os.mkdir(os.path.join(self.objects, part))
self.ring = _create_test_ring(self.testdir, POLICIES.legacy)
self.conf = dict(
swift_dir=self.testdir, devices=self.devices, mount_check='false',
timeout='300', stats_interval='1')
self.logger = debug_logger()
self.df_mgr = diskfile.DiskFileManager(self.conf, logger=self.logger)
def tearDown(self):
rmtree(self.testdir, ignore_errors=1)
def _create_diskfile(self, policy):
return self.df_mgr.get_diskfile(self.existing_device,
'0', 'a', 'c', 'o',
policy=policy)
def test_relink_paths(self):
target_dir = os.path.join(self.testdir, 'd1')
os.mkdir(target_dir)
target_path = os.path.join(target_dir, 'f1')
with open(target_path, 'w') as fd:
fd.write('junk')
new_target_path = os.path.join(self.testdir, 'd2', 'f1')
created = diskfile.relink_paths(target_path, new_target_path)
self.assertTrue(created)
self.assertTrue(os.path.isfile(new_target_path))
with open(new_target_path, 'r') as fd:
self.assertEqual('junk', fd.read())
def test_relink_paths_makedirs_error(self):
target_dir = os.path.join(self.testdir, 'd1')
os.mkdir(target_dir)
target_path = os.path.join(target_dir, 'f1')
with open(target_path, 'w') as fd:
fd.write('junk')
new_target_path = os.path.join(self.testdir, 'd2', 'f1')
with mock.patch('swift.obj.diskfile.os.makedirs',
side_effect=Exception('oops')):
with self.assertRaises(Exception) as cm:
diskfile.relink_paths(target_path, new_target_path)
self.assertEqual('oops', str(cm.exception))
with self.assertRaises(Exception) as cm:
diskfile.relink_paths(target_path, new_target_path,
ignore_missing=False)
self.assertEqual('oops', str(cm.exception))
def test_relink_paths_makedirs_race(self):
# test two concurrent relinks of the same object hash dir with race
# around makedirs
target_dir = os.path.join(self.testdir, 'd1')
# target dir exists
os.mkdir(target_dir)
target_path_1 = os.path.join(target_dir, 't1.data')
target_path_2 = os.path.join(target_dir, 't2.data')
# new target dir and files do not exist
new_target_dir = os.path.join(self.testdir, 'd2')
new_target_path_1 = os.path.join(new_target_dir, 't1.data')
new_target_path_2 = os.path.join(new_target_dir, 't2.data')
created = []
def write_and_relink(target_path, new_target_path):
with open(target_path, 'w') as fd:
fd.write(target_path)
created.append(diskfile.relink_paths(target_path, new_target_path))
calls = []
orig_makedirs = os.makedirs
def mock_makedirs(path, *args):
calls.append(path)
if len(calls) == 1:
# pretend another process jumps in here and relinks same dirs
write_and_relink(target_path_2, new_target_path_2)
return orig_makedirs(path, *args)
with mock.patch('swift.obj.diskfile.os.makedirs', mock_makedirs):
write_and_relink(target_path_1, new_target_path_1)
self.assertEqual([new_target_dir, new_target_dir], calls)
self.assertTrue(os.path.isfile(new_target_path_1))
with open(new_target_path_1, 'r') as fd:
self.assertEqual(target_path_1, fd.read())
self.assertTrue(os.path.isfile(new_target_path_2))
with open(new_target_path_2, 'r') as fd:
self.assertEqual(target_path_2, fd.read())
self.assertEqual([True, True], created)
def test_relink_paths_object_dir_exists_but_not_dir(self):
target_dir = os.path.join(self.testdir, 'd1')
os.mkdir(target_dir)
target_path = os.path.join(target_dir, 't1.data')
with open(target_path, 'w') as fd:
fd.write(target_path)
# make a file where the new object dir should be
new_target_dir = os.path.join(self.testdir, 'd2')
with open(new_target_dir, 'w') as fd:
fd.write(new_target_dir)
new_target_path = os.path.join(new_target_dir, 't1.data')
with self.assertRaises(OSError) as cm:
diskfile.relink_paths(target_path, new_target_path)
self.assertEqual(errno.ENOTDIR, cm.exception.errno)
# make a symlink to target where the new object dir should be
os.unlink(new_target_dir)
os.symlink(target_path, new_target_dir)
with self.assertRaises(OSError) as cm:
diskfile.relink_paths(target_path, new_target_path)
self.assertEqual(errno.ENOTDIR, cm.exception.errno)
def test_relink_paths_os_link_error(self):
# check relink_paths raises exception from os.link
target_dir = os.path.join(self.testdir, 'd1')
os.mkdir(target_dir)
target_path = os.path.join(target_dir, 'f1')
with open(target_path, 'w') as fd:
fd.write('junk')
new_target_path = os.path.join(self.testdir, 'd2', 'f1')
with mock.patch('swift.obj.diskfile.os.link',
side_effect=OSError(errno.EPERM, 'nope')):
with self.assertRaises(Exception) as cm:
diskfile.relink_paths(target_path, new_target_path)
self.assertEqual(errno.EPERM, cm.exception.errno)
def test_relink_paths_target_path_does_not_exist(self):
# check relink_paths does not raise exception
target_dir = os.path.join(self.testdir, 'd1')
os.mkdir(target_dir)
target_path = os.path.join(target_dir, 'f1')
new_target_path = os.path.join(self.testdir, 'd2', 'f1')
created = diskfile.relink_paths(target_path, new_target_path)
self.assertFalse(os.path.exists(target_path))
self.assertFalse(os.path.exists(new_target_path))
self.assertFalse(created)
with self.assertRaises(OSError) as cm:
diskfile.relink_paths(target_path, new_target_path,
ignore_missing=False)
self.assertEqual(errno.ENOENT, cm.exception.errno)
self.assertFalse(os.path.exists(target_path))
self.assertFalse(os.path.exists(new_target_path))
def test_relink_paths_os_link_race(self):
# test two concurrent relinks of the same object hash dir with race
# around os.link
target_dir = os.path.join(self.testdir, 'd1')
# target dir exists
os.mkdir(target_dir)
target_path = os.path.join(target_dir, 't1.data')
# new target dir and file do not exist
new_target_dir = os.path.join(self.testdir, 'd2')
new_target_path = os.path.join(new_target_dir, 't1.data')
created = []
def write_and_relink(target_path, new_target_path):
with open(target_path, 'w') as fd:
fd.write(target_path)
created.append(diskfile.relink_paths(target_path, new_target_path))
calls = []
orig_link = os.link
def mock_link(path, new_path):
calls.append((path, new_path))
if len(calls) == 1:
# pretend another process jumps in here and links same files
write_and_relink(target_path, new_target_path)
return orig_link(path, new_path)
with mock.patch('swift.obj.diskfile.os.link', mock_link):
write_and_relink(target_path, new_target_path)
self.assertEqual([(target_path, new_target_path)] * 2, calls)
self.assertTrue(os.path.isfile(new_target_path))
with open(new_target_path, 'r') as fd:
self.assertEqual(target_path, fd.read())
with open(target_path, 'r') as fd:
self.assertEqual(target_path, fd.read())
self.assertEqual([True, False], created)
def test_relink_paths_different_file_exists(self):
# check for an exception if a hard link cannot be made because a
# different file already exists at new_target_path
target_dir = os.path.join(self.testdir, 'd1')
# target dir and file exists
os.mkdir(target_dir)
target_path = os.path.join(target_dir, 't1.data')
with open(target_path, 'w') as fd:
fd.write(target_path)
# new target dir and different file exist
new_target_dir = os.path.join(self.testdir, 'd2')
os.mkdir(new_target_dir)
new_target_path = os.path.join(new_target_dir, 't1.data')
with open(new_target_path, 'w') as fd:
fd.write(new_target_path)
with self.assertRaises(OSError) as cm:
diskfile.relink_paths(target_path, new_target_path)
self.assertEqual(errno.EEXIST, cm.exception.errno)
# check nothing got deleted...
self.assertTrue(os.path.isfile(target_path))
with open(target_path, 'r') as fd:
self.assertEqual(target_path, fd.read())
self.assertTrue(os.path.isfile(new_target_path))
with open(new_target_path, 'r') as fd:
self.assertEqual(new_target_path, fd.read())
def test_relink_paths_same_file_exists(self):
# check for no exception if a hard link cannot be made because a link
# to the same file already exists at the path
target_dir = os.path.join(self.testdir, 'd1')
# target dir and file exists
os.mkdir(target_dir)
target_path = os.path.join(target_dir, 't1.data')
with open(target_path, 'w') as fd:
fd.write(target_path)
# new target dir and link to same file exist
new_target_dir = os.path.join(self.testdir, 'd2')
os.mkdir(new_target_dir)
new_target_path = os.path.join(new_target_dir, 't1.data')
os.link(target_path, new_target_path)
with open(new_target_path, 'r') as fd:
self.assertEqual(target_path, fd.read()) # sanity check
# existing link checks ok
created = diskfile.relink_paths(target_path, new_target_path)
with open(new_target_path, 'r') as fd:
self.assertEqual(target_path, fd.read()) # sanity check
self.assertFalse(created)
# now pretend there is an error when checking that the link already
# exists - expect the EEXIST exception to be raised
orig_stat = os.stat
def mocked_stat(path):
if path == new_target_path:
raise OSError(errno.EPERM, 'cannot be sure link exists :(')
return orig_stat(path)
with mock.patch('swift.obj.diskfile.os.stat', mocked_stat):
with self.assertRaises(OSError) as cm:
diskfile.relink_paths(target_path, new_target_path)
self.assertEqual(errno.EEXIST, cm.exception.errno, str(cm.exception))
with open(new_target_path, 'r') as fd:
self.assertEqual(target_path, fd.read()) # sanity check
# ...unless while checking for an existing link the target file is
# found to no longer exists, which is ok
def mocked_stat(path):
if path == target_path:
raise OSError(errno.ENOENT, 'target longer here :)')
return orig_stat(path)
with mock.patch('swift.obj.diskfile.os.stat', mocked_stat):
created = diskfile.relink_paths(target_path, new_target_path)
with open(new_target_path, 'r') as fd:
self.assertEqual(target_path, fd.read()) # sanity check
self.assertFalse(created)
def test_extract_policy(self):
# good path names
pn = 'objects/0/606/1984527ed7ef6247c78606/1401379842.14643.data'
self.assertEqual(diskfile.extract_policy(pn), POLICIES[0])
pn = 'objects-1/0/606/198452b6ef6247c78606/1401379842.14643.data'
self.assertEqual(diskfile.extract_policy(pn), POLICIES[1])
# leading slash
pn = '/objects/0/606/1984527ed7ef6247c78606/1401379842.14643.data'
self.assertEqual(diskfile.extract_policy(pn), POLICIES[0])
pn = '/objects-1/0/606/198452b6ef6247c78606/1401379842.14643.data'
self.assertEqual(diskfile.extract_policy(pn), POLICIES[1])
# full paths
good_path = '/srv/node/sda1/objects-1/1/abc/def/1234.data'
self.assertEqual(diskfile.extract_policy(good_path), POLICIES[1])
good_path = '/srv/node/sda1/objects/1/abc/def/1234.data'
self.assertEqual(diskfile.extract_policy(good_path), POLICIES[0])
# short paths
path = '/srv/node/sda1/objects/1/1234.data'
self.assertEqual(diskfile.extract_policy(path), POLICIES[0])
path = '/srv/node/sda1/objects-1/1/1234.data'
self.assertEqual(diskfile.extract_policy(path), POLICIES[1])
# well formatted but, unknown policy index
pn = 'objects-2/0/606/198427efcff042c78606/1401379842.14643.data'
self.assertIsNone(diskfile.extract_policy(pn))
# malformed path
self.assertIsNone(diskfile.extract_policy(''))
bad_path = '/srv/node/sda1/objects-t/1/abc/def/1234.data'
self.assertIsNone(diskfile.extract_policy(bad_path))
pn = 'XXXX/0/606/1984527ed42b6ef6247c78606/1401379842.14643.data'
self.assertIsNone(diskfile.extract_policy(pn))
bad_path = '/srv/node/sda1/foo-1/1/abc/def/1234.data'
self.assertIsNone(diskfile.extract_policy(bad_path))
bad_path = '/srv/node/sda1/obj1/1/abc/def/1234.data'
self.assertIsNone(diskfile.extract_policy(bad_path))
def test_quarantine_renamer(self):
for policy in POLICIES:
# we use this for convenience, not really about a diskfile layout
df = self._create_diskfile(policy=policy)
mkdirs(df._datadir)
exp_dir = os.path.join(self.devices, 'quarantined',
diskfile.get_data_dir(policy),
os.path.basename(df._datadir))
qbit = os.path.join(df._datadir, 'qbit')
with open(qbit, 'w') as f:
f.write('abc')
to_dir = diskfile.quarantine_renamer(self.devices, qbit)
self.assertEqual(to_dir, exp_dir)
self.assertRaises(OSError, diskfile.quarantine_renamer,
self.devices, qbit)
def test_get_data_dir(self):
self.assertEqual(diskfile.get_data_dir(POLICIES[0]),
diskfile.DATADIR_BASE)
self.assertEqual(diskfile.get_data_dir(POLICIES[1]),
diskfile.DATADIR_BASE + "-1")
self.assertRaises(ValueError, diskfile.get_data_dir, 'junk')
self.assertRaises(ValueError, diskfile.get_data_dir, 99)
def test_get_async_dir(self):
self.assertEqual(diskfile.get_async_dir(POLICIES[0]),
diskfile.ASYNCDIR_BASE)
self.assertEqual(diskfile.get_async_dir(POLICIES[1]),
diskfile.ASYNCDIR_BASE + "-1")
self.assertRaises(ValueError, diskfile.get_async_dir, 'junk')
self.assertRaises(ValueError, diskfile.get_async_dir, 99)
def test_get_tmp_dir(self):
self.assertEqual(diskfile.get_tmp_dir(POLICIES[0]),
diskfile.TMP_BASE)
self.assertEqual(diskfile.get_tmp_dir(POLICIES[1]),
diskfile.TMP_BASE + "-1")
self.assertRaises(ValueError, diskfile.get_tmp_dir, 'junk')
self.assertRaises(ValueError, diskfile.get_tmp_dir, 99)
def test_pickle_async_update_tmp_dir(self):
for policy in POLICIES:
if int(policy) == 0:
tmp_part = 'tmp'
else:
tmp_part = 'tmp-%d' % policy
tmp_path = os.path.join(
self.devices, self.existing_device, tmp_part)
self.assertFalse(os.path.isdir(tmp_path))
pickle_args = (self.existing_device, 'a', 'c', 'o',
'data', 0.0, policy)
os.makedirs(tmp_path)
# now create a async update
self.df_mgr.pickle_async_update(*pickle_args)
# check tempdir
self.assertTrue(os.path.isdir(tmp_path))
def test_get_part_path(self):
# partition passed as 'str'
part_dir = diskfile.get_part_path('/srv/node/sda1', POLICIES[0], '123')
exp_dir = '/srv/node/sda1/objects/123'
self.assertEqual(part_dir, exp_dir)
# partition passed as 'int'
part_dir = diskfile.get_part_path('/srv/node/sdb5', POLICIES[1], 123)
exp_dir = '/srv/node/sdb5/objects-1/123'
self.assertEqual(part_dir, exp_dir)
def test_can_read_old_meta(self):
# outputs taken from `xattr -l <diskfile>`
cases = {
'python_2.7.18_swift_2.13_replicated': '''
0000 80 02 7D 71 01 28 55 0E 43 6F 6E 74 65 6E 74 2D ..}q.(U.Content-
0010 4C 65 6E 67 74 68 71 02 55 02 31 33 55 04 6E 61 Lengthq.U.13U.na
0020 6D 65 71 03 55 12 2F 41 55 54 48 5F 74 65 73 74 meq.U./AUTH_test
0030 2F E2 98 83 2F E2 98 83 71 04 55 13 58 2D 4F 62 /.../...q.U.X-Ob
0040 6A 65 63 74 2D 4D 65 74 61 2D 4D 74 69 6D 65 55 ject-Meta-MtimeU
0050 11 31 36 38 32 39 35 39 38 37 34 2E 37 35 36 32 .1682959874.7562
0060 30 35 71 05 55 04 45 54 61 67 71 06 55 20 36 62 05q.U.ETagq.U 6b
0070 37 64 39 61 31 63 35 64 31 36 37 63 63 35 30 30 7d9a1c5d167cc500
0080 33 37 66 32 39 66 32 39 30 62 62 33 37 35 71 07 37f29f290bb375q.
0090 55 0B 58 2D 54 69 6D 65 73 74 61 6D 70 71 08 55 U.X-Timestampq.U
00A0 10 31 36 38 32 39 36 32 36 35 31 2E 39 37 34 39 .1682962651.9749
00B0 34 55 11 58 2D 4F 62 6A 65 63 74 2D 4D 65 74 61 4U.X-Object-Meta
00C0 2D E2 98 83 55 03 E2 98 83 71 09 55 0C 43 6F 6E -...U....q.U.Con
00D0 74 65 6E 74 2D 54 79 70 65 71 0A 55 18 61 70 70 tent-Typeq.U.app
00E0 6C 69 63 61 74 69 6F 6E 2F 6F 63 74 65 74 2D 73 lication/octet-s
00F0 74 72 65 61 6D 71 0B 75 2E treamq.u.
''',
'python_2.7.18_swift_2.13_ec': '''
0000 80 02 7D 71 01 28 55 0E 43 6F 6E 74 65 6E 74 2D ..}q.(U.Content-
0010 4C 65 6E 67 74 68 71 02 55 02 38 34 55 04 6E 61 Lengthq.U.84U.na
0020 6D 65 71 03 55 12 2F 41 55 54 48 5F 74 65 73 74 meq.U./AUTH_test
0030 2F E2 98 83 2F E2 98 83 71 04 58 1E 00 00 00 58 /.../...q.X....X
0040 2D 4F 62 6A 65 63 74 2D 53 79 73 6D 65 74 61 2D -Object-Sysmeta-
0050 45 63 2D 46 72 61 67 2D 49 6E 64 65 78 71 05 55 Ec-Frag-Indexq.U
0060 01 35 55 13 58 2D 4F 62 6A 65 63 74 2D 4D 65 74 .5U.X-Object-Met
0070 61 2D 4D 74 69 6D 65 55 11 31 36 38 32 39 35 39 a-MtimeU.1682959
0080 38 37 34 2E 37 35 36 32 30 35 71 06 58 22 00 00 874.756205q.X"..
0090 00 58 2D 4F 62 6A 65 63 74 2D 53 79 73 6D 65 74 .X-Object-Sysmet
00A0 61 2D 45 63 2D 43 6F 6E 74 65 6E 74 2D 4C 65 6E a-Ec-Content-Len
00B0 67 74 68 71 07 55 02 31 33 71 08 58 18 00 00 00 gthq.U.13q.X....
00C0 58 2D 4F 62 6A 65 63 74 2D 53 79 73 6D 65 74 61 X-Object-Sysmeta
00D0 2D 45 63 2D 45 74 61 67 71 09 55 20 36 62 37 64 -Ec-Etagq.U 6b7d
00E0 39 61 31 63 35 64 31 36 37 63 63 35 30 30 33 37 9a1c5d167cc50037
00F0 66 32 39 66 32 39 30 62 62 33 37 35 71 0A 55 04 f29f290bb375q.U.
0100 45 54 61 67 71 0B 55 20 65 32 66 64 34 33 30 65 ETagq.U e2fd430e
0110 61 66 37 32 32 33 63 32 35 30 33 63 34 65 38 33 af7223c2503c4e83
0120 30 31 63 66 66 33 37 63 71 0C 55 0B 58 2D 54 69 01cff37cq.U.X-Ti
0130 6D 65 73 74 61 6D 70 71 0D 55 10 31 36 38 32 39 mestampq.U.16829
0140 36 32 32 36 32 2E 31 36 31 39 39 55 11 58 2D 4F 62262.16199U.X-O
0150 62 6A 65 63 74 2D 4D 65 74 61 2D E2 98 83 55 03 bject-Meta-...U.
0160 E2 98 83 71 0E 58 1A 00 00 00 58 2D 4F 62 6A 65 ...q.X....X-Obje
0170 63 74 2D 53 79 73 6D 65 74 61 2D 45 63 2D 53 63 ct-Sysmeta-Ec-Sc
0180 68 65 6D 65 71 0F 55 1A 6C 69 62 65 72 61 73 75 hemeq.U.liberasu
0190 72 65 63 6F 64 65 5F 72 73 5F 76 61 6E 64 20 34 recode_rs_vand 4
01A0 2B 32 71 10 55 0C 43 6F 6E 74 65 6E 74 2D 54 79 +2q.U.Content-Ty
01B0 70 65 71 11 55 18 61 70 70 6C 69 63 61 74 69 6F peq.U.applicatio
01C0 6E 2F 6F 63 74 65 74 2D 73 74 72 65 61 6D 71 12 n/octet-streamq.
01D0 58 20 00 00 00 58 2D 4F 62 6A 65 63 74 2D 53 79 X ...X-Object-Sy
01E0 73 6D 65 74 61 2D 45 63 2D 53 65 67 6D 65 6E 74 smeta-Ec-Segment
01F0 2D 53 69 7A 65 71 13 55 07 31 30 34 38 35 37 36 -Sizeq.U.1048576
0200 71 14 75 2E q.u.
''',
'python_2.7.18_swift_2.23_replicated': '''
0000 80 02 7D 71 01 28 55 0E 43 6F 6E 74 65 6E 74 2D ..}q.(U.Content-
0010 4C 65 6E 67 74 68 71 02 55 02 31 33 71 03 55 04 Lengthq.U.13q.U.
0020 6E 61 6D 65 71 04 55 12 2F 41 55 54 48 5F 74 65 nameq.U./AUTH_te
0030 73 74 2F E2 98 83 2F E2 98 83 71 05 55 0C 43 6F st/.../...q.U.Co
0040 6E 74 65 6E 74 2D 54 79 70 65 71 06 55 18 61 70 ntent-Typeq.U.ap
0050 70 6C 69 63 61 74 69 6F 6E 2F 6F 63 74 65 74 2D plication/octet-
0060 73 74 72 65 61 6D 71 07 55 04 45 54 61 67 71 08 streamq.U.ETagq.
0070 55 20 36 62 37 64 39 61 31 63 35 64 31 36 37 63 U 6b7d9a1c5d167c
0080 63 35 30 30 33 37 66 32 39 66 32 39 30 62 62 33 c50037f29f290bb3
0090 37 35 71 09 55 0B 58 2D 54 69 6D 65 73 74 61 6D 75q.U.X-Timestam
00A0 70 71 0A 55 10 31 36 38 32 39 36 33 32 30 39 2E pq.U.1682963209.
00B0 38 32 32 37 32 71 0B 55 11 58 2D 4F 62 6A 65 63 82272q.U.X-Objec
00C0 74 2D 4D 65 74 61 2D E2 98 83 71 0C 55 03 E2 98 t-Meta-...q.U...
00D0 83 71 0D 55 13 58 2D 4F 62 6A 65 63 74 2D 4D 65 .q.U.X-Object-Me
00E0 74 61 2D 4D 74 69 6D 65 71 0E 55 11 31 36 38 32 ta-Mtimeq.U.1682
00F0 39 35 39 38 37 34 2E 37 35 36 32 30 35 71 0F 75 959874.756205q.u
0100 2E .
''',
'python_3.10.6_swift_2.23_replicated': '''
0000 80 02 7D 71 00 28 63 5F 63 6F 64 65 63 73 0A 65 ..}q.(c_codecs.e
0010 6E 63 6F 64 65 0A 71 01 58 0B 00 00 00 58 2D 54 ncode.q.X....X-T
0020 69 6D 65 73 74 61 6D 70 71 02 58 06 00 00 00 6C imestampq.X....l
0030 61 74 69 6E 31 71 03 86 71 04 52 71 05 68 01 58 atin1q..q.Rq.h.X
0040 10 00 00 00 31 36 38 32 39 36 33 30 31 37 2E 31 ....1682963017.1
0050 30 34 37 32 71 06 68 03 86 71 07 52 71 08 68 01 0472q.h..q.Rq.h.
0060 58 0C 00 00 00 43 6F 6E 74 65 6E 74 2D 54 79 70 X....Content-Typ
0070 65 71 09 68 03 86 71 0A 52 71 0B 68 01 58 18 00 eq.h..q.Rq.h.X..
0080 00 00 61 70 70 6C 69 63 61 74 69 6F 6E 2F 6F 63 ..application/oc
0090 74 65 74 2D 73 74 72 65 61 6D 71 0C 68 03 86 71 tet-streamq.h..q
00A0 0D 52 71 0E 68 01 58 0E 00 00 00 43 6F 6E 74 65 .Rq.h.X....Conte
00B0 6E 74 2D 4C 65 6E 67 74 68 71 0F 68 03 86 71 10 nt-Lengthq.h..q.
00C0 52 71 11 68 01 58 02 00 00 00 31 33 71 12 68 03 Rq.h.X....13q.h.
00D0 86 71 13 52 71 14 68 01 58 04 00 00 00 45 54 61 .q.Rq.h.X....ETa
00E0 67 71 15 68 03 86 71 16 52 71 17 68 01 58 20 00 gq.h..q.Rq.h.X .
00F0 00 00 36 62 37 64 39 61 31 63 35 64 31 36 37 63 ..6b7d9a1c5d167c
0100 63 35 30 30 33 37 66 32 39 66 32 39 30 62 62 33 c50037f29f290bb3
0110 37 35 71 18 68 03 86 71 19 52 71 1A 68 01 58 13 75q.h..q.Rq.h.X.
0120 00 00 00 58 2D 4F 62 6A 65 63 74 2D 4D 65 74 61 ...X-Object-Meta
0130 2D 4D 74 69 6D 65 71 1B 68 03 86 71 1C 52 71 1D -Mtimeq.h..q.Rq.
0140 68 01 58 11 00 00 00 31 36 38 32 39 35 39 38 37 h.X....168295987
0150 34 2E 37 35 36 32 30 35 71 1E 68 03 86 71 1F 52 4.756205q.h..q.R
0160 71 20 68 01 58 1A 00 00 00 58 2D 4F 62 6A 65 63 q h.X....X-Objec
0170 74 2D 4D 65 74 61 2D C3 83 C2 A2 C3 82 C2 98 C3 t-Meta-.........
0180 82 C2 83 71 21 68 03 86 71 22 52 71 23 68 01 58 ...q!h..q"Rq#h.X
0190 0C 00 00 00 C3 83 C2 A2 C3 82 C2 98 C3 82 C2 83 ................
01A0 71 24 68 03 86 71 25 52 71 26 68 01 58 04 00 00 q$h..q%Rq&h.X...
01B0 00 6E 61 6D 65 71 27 68 03 86 71 28 52 71 29 68 .nameq'h..q(Rq)h
01C0 01 58 18 00 00 00 2F 41 55 54 48 5F 74 65 73 74 .X..../AUTH_test
01D0 2F C3 A2 C2 98 C2 83 2F C3 A2 C2 98 C2 83 71 2A /....../......q*
01E0 68 03 86 71 2B 52 71 2C 75 2E h..q+Rq,u.
''',
'python_2.7.18_swift_2.23_ec': '''
0000 80 02 7D 71 01 28 55 0E 43 6F 6E 74 65 6E 74 2D ..}q.(U.Content-
0010 4C 65 6E 67 74 68 71 02 55 02 38 34 71 03 55 04 Lengthq.U.84q.U.
0020 6E 61 6D 65 71 04 55 12 2F 41 55 54 48 5F 74 65 nameq.U./AUTH_te
0030 73 74 2F E2 98 83 2F E2 98 83 71 05 55 1E 58 2D st/.../...q.U.X-
0040 4F 62 6A 65 63 74 2D 53 79 73 6D 65 74 61 2D 45 Object-Sysmeta-E
0050 63 2D 46 72 61 67 2D 49 6E 64 65 78 55 01 35 55 c-Frag-IndexU.5U
0060 0C 43 6F 6E 74 65 6E 74 2D 54 79 70 65 71 06 55 .Content-Typeq.U
0070 18 61 70 70 6C 69 63 61 74 69 6F 6E 2F 6F 63 74 .application/oct
0080 65 74 2D 73 74 72 65 61 6D 71 07 55 22 58 2D 4F et-streamq.U"X-O
0090 62 6A 65 63 74 2D 53 79 73 6D 65 74 61 2D 45 63 bject-Sysmeta-Ec
00A0 2D 43 6F 6E 74 65 6E 74 2D 4C 65 6E 67 74 68 55 -Content-LengthU
00B0 02 31 33 71 08 55 18 58 2D 4F 62 6A 65 63 74 2D .13q.U.X-Object-
00C0 53 79 73 6D 65 74 61 2D 45 63 2D 45 74 61 67 55 Sysmeta-Ec-EtagU
00D0 20 36 62 37 64 39 61 31 63 35 64 31 36 37 63 63 6b7d9a1c5d167cc
00E0 35 30 30 33 37 66 32 39 66 32 39 30 62 62 33 37 50037f29f290bb37
00F0 35 71 09 55 04 45 54 61 67 71 0A 55 20 65 32 66 5q.U.ETagq.U e2f
0100 64 34 33 30 65 61 66 37 32 32 33 63 32 35 30 33 d430eaf7223c2503
0110 63 34 65 38 33 30 31 63 66 66 33 37 63 71 0B 55 c4e8301cff37cq.U
0120 0B 58 2D 54 69 6D 65 73 74 61 6D 70 71 0C 55 10 .X-Timestampq.U.
0130 31 36 38 32 39 36 33 31 33 30 2E 33 35 39 38 36 1682963130.35986
0140 71 0D 55 11 58 2D 4F 62 6A 65 63 74 2D 4D 65 74 q.U.X-Object-Met
0150 61 2D E2 98 83 71 0E 55 03 E2 98 83 71 0F 55 1A a-...q.U....q.U.
0160 58 2D 4F 62 6A 65 63 74 2D 53 79 73 6D 65 74 61 X-Object-Sysmeta
0170 2D 45 63 2D 53 63 68 65 6D 65 55 1A 6C 69 62 65 -Ec-SchemeU.libe
0180 72 61 73 75 72 65 63 6F 64 65 5F 72 73 5F 76 61 rasurecode_rs_va
0190 6E 64 20 34 2B 32 71 10 55 13 58 2D 4F 62 6A 65 nd 4+2q.U.X-Obje
01A0 63 74 2D 4D 65 74 61 2D 4D 74 69 6D 65 71 11 55 ct-Meta-Mtimeq.U
01B0 11 31 36 38 32 39 35 39 38 37 34 2E 37 35 36 32 .1682959874.7562
01C0 30 35 71 12 55 20 58 2D 4F 62 6A 65 63 74 2D 53 05q.U X-Object-S
01D0 79 73 6D 65 74 61 2D 45 63 2D 53 65 67 6D 65 6E ysmeta-Ec-Segmen
01E0 74 2D 53 69 7A 65 55 07 31 30 34 38 35 37 36 71 t-SizeU.1048576q
01F0 13 75 2E .u.
''',
'python_3.10.6_swift_2.23_ec': '''
0000 80 02 7D 71 00 28 63 5F 63 6F 64 65 63 73 0A 65 ..}q.(c_codecs.e
0010 6E 63 6F 64 65 0A 71 01 58 0B 00 00 00 58 2D 54 ncode.q.X....X-T
0020 69 6D 65 73 74 61 6D 70 71 02 58 06 00 00 00 6C imestampq.X....l
0030 61 74 69 6E 31 71 03 86 71 04 52 71 05 68 01 58 atin1q..q.Rq.h.X
0040 10 00 00 00 31 36 38 32 39 36 32 39 35 35 2E 33 ....1682962955.3
0050 37 35 34 36 71 06 68 03 86 71 07 52 71 08 68 01 7546q.h..q.Rq.h.
0060 58 0C 00 00 00 43 6F 6E 74 65 6E 74 2D 54 79 70 X....Content-Typ
0070 65 71 09 68 03 86 71 0A 52 71 0B 68 01 58 18 00 eq.h..q.Rq.h.X..
0080 00 00 61 70 70 6C 69 63 61 74 69 6F 6E 2F 6F 63 ..application/oc
0090 74 65 74 2D 73 74 72 65 61 6D 71 0C 68 03 86 71 tet-streamq.h..q
00A0 0D 52 71 0E 68 01 58 0E 00 00 00 43 6F 6E 74 65 .Rq.h.X....Conte
00B0 6E 74 2D 4C 65 6E 67 74 68 71 0F 68 03 86 71 10 nt-Lengthq.h..q.
00C0 52 71 11 68 01 58 02 00 00 00 38 34 71 12 68 03 Rq.h.X....84q.h.
00D0 86 71 13 52 71 14 68 01 58 04 00 00 00 45 54 61 .q.Rq.h.X....ETa
00E0 67 71 15 68 03 86 71 16 52 71 17 68 01 58 20 00 gq.h..q.Rq.h.X .
00F0 00 00 65 32 66 64 34 33 30 65 61 66 37 32 32 33 ..e2fd430eaf7223
0100 63 32 35 30 33 63 34 65 38 33 30 31 63 66 66 33 c2503c4e8301cff3
0110 37 63 71 18 68 03 86 71 19 52 71 1A 68 01 58 13 7cq.h..q.Rq.h.X.
0120 00 00 00 58 2D 4F 62 6A 65 63 74 2D 4D 65 74 61 ...X-Object-Meta
0130 2D 4D 74 69 6D 65 71 1B 68 03 86 71 1C 52 71 1D -Mtimeq.h..q.Rq.
0140 68 01 58 11 00 00 00 31 36 38 32 39 35 39 38 37 h.X....168295987
0150 34 2E 37 35 36 32 30 35 71 1E 68 03 86 71 1F 52 4.756205q.h..q.R
0160 71 20 68 01 58 1A 00 00 00 58 2D 4F 62 6A 65 63 q h.X....X-Objec
0170 74 2D 4D 65 74 61 2D C3 83 C2 A2 C3 82 C2 98 C3 t-Meta-.........
0180 82 C2 83 71 21 68 03 86 71 22 52 71 23 68 01 58 ...q!h..q"Rq#h.X
0190 0C 00 00 00 C3 83 C2 A2 C3 82 C2 98 C3 82 C2 83 ................
01A0 71 24 68 03 86 71 25 52 71 26 68 01 58 18 00 00 q$h..q%Rq&h.X...
01B0 00 58 2D 4F 62 6A 65 63 74 2D 53 79 73 6D 65 74 .X-Object-Sysmet
01C0 61 2D 45 63 2D 45 74 61 67 71 27 68 03 86 71 28 a-Ec-Etagq'h..q(
01D0 52 71 29 68 01 58 20 00 00 00 36 62 37 64 39 61 Rq)h.X ...6b7d9a
01E0 31 63 35 64 31 36 37 63 63 35 30 30 33 37 66 32 1c5d167cc50037f2
01F0 39 66 32 39 30 62 62 33 37 35 71 2A 68 03 86 71 9f290bb375q*h..q
0200 2B 52 71 2C 68 01 58 22 00 00 00 58 2D 4F 62 6A +Rq,h.X"...X-Obj
0210 65 63 74 2D 53 79 73 6D 65 74 61 2D 45 63 2D 43 ect-Sysmeta-Ec-C
0220 6F 6E 74 65 6E 74 2D 4C 65 6E 67 74 68 71 2D 68 ontent-Lengthq-h
0230 03 86 71 2E 52 71 2F 68 01 58 02 00 00 00 31 33 ..q.Rq/h.X....13
0240 71 30 68 03 86 71 31 52 71 32 68 01 58 1E 00 00 q0h..q1Rq2h.X...
0250 00 58 2D 4F 62 6A 65 63 74 2D 53 79 73 6D 65 74 .X-Object-Sysmet
0260 61 2D 45 63 2D 46 72 61 67 2D 49 6E 64 65 78 71 a-Ec-Frag-Indexq
0270 33 68 03 86 71 34 52 71 35 68 01 58 01 00 00 00 3h..q4Rq5h.X....
0280 35 71 36 68 03 86 71 37 52 71 38 68 01 58 1A 00 5q6h..q7Rq8h.X..
0290 00 00 58 2D 4F 62 6A 65 63 74 2D 53 79 73 6D 65 ..X-Object-Sysme
02A0 74 61 2D 45 63 2D 53 63 68 65 6D 65 71 39 68 03 ta-Ec-Schemeq9h.
02B0 86 71 3A 52 71 3B 68 01 58 1A 00 00 00 6C 69 62 .q:Rq;h.X....lib
02C0 65 72 61 73 75 72 65 63 6F 64 65 5F 72 73 5F 76 erasurecode_rs_v
02D0 61 6E 64 20 34 2B 32 71 3C 68 03 86 71 3D 52 71 and 4+2q<h..q=Rq
02E0 3E 68 01 58 20 00 00 00 58 2D 4F 62 6A 65 63 74 >h.X ...X-Object
02F0 2D 53 79 73 6D 65 74 61 2D 45 63 2D 53 65 67 6D -Sysmeta-Ec-Segm
0300 65 6E 74 2D 53 69 7A 65 71 3F 68 03 86 71 40 52 ent-Sizeq?h..q@R
0310 71 41 68 01 58 07 00 00 00 31 30 34 38 35 37 36 qAh.X....1048576
0320 71 42 68 03 86 71 43 52 71 44 68 01 58 04 00 00 qBh..qCRqDh.X...
0330 00 6E 61 6D 65 71 45 68 03 86 71 46 52 71 47 68 .nameqEh..qFRqGh
0340 01 58 18 00 00 00 2F 41 55 54 48 5F 74 65 73 74 .X..../AUTH_test
0350 2F C3 A2 C2 98 C2 83 2F C3 A2 C2 98 C2 83 71 48 /....../......qH
0360 68 03 86 71 49 52 71 4A 75 2E h..qIRqJu.
''',
'python3.8.10_swift_2.31.1_replicated': '''
0000 80 02 7D 71 00 28 63 5F 63 6F 64 65 63 73 0A 65 ..}q.(c_codecs.e
0010 6E 63 6F 64 65 0A 71 01 58 0B 00 00 00 58 2D 54 ncode.q.X....X-T
0020 69 6D 65 73 74 61 6D 70 71 02 58 06 00 00 00 6C imestampq.X....l
0030 61 74 69 6E 31 71 03 86 71 04 52 71 05 68 01 58 atin1q..q.Rq.h.X
0040 10 00 00 00 31 36 38 33 30 36 35 34 37 38 2E 32 ....1683065478.2
0050 35 30 30 34 71 06 68 03 86 71 07 52 71 08 68 01 5004q.h..q.Rq.h.
0060 58 0C 00 00 00 43 6F 6E 74 65 6E 74 2D 54 79 70 X....Content-Typ
0070 65 71 09 68 03 86 71 0A 52 71 0B 68 01 58 18 00 eq.h..q.Rq.h.X..
0080 00 00 61 70 70 6C 69 63 61 74 69 6F 6E 2F 6F 63 ..application/oc
0090 74 65 74 2D 73 74 72 65 61 6D 71 0C 68 03 86 71 tet-streamq.h..q
00A0 0D 52 71 0E 68 01 58 0E 00 00 00 43 6F 6E 74 65 .Rq.h.X....Conte
00B0 6E 74 2D 4C 65 6E 67 74 68 71 0F 68 03 86 71 10 nt-Lengthq.h..q.
00C0 52 71 11 68 01 58 01 00 00 00 38 71 12 68 03 86 Rq.h.X....8q.h..
00D0 71 13 52 71 14 68 01 58 04 00 00 00 45 54 61 67 q.Rq.h.X....ETag
00E0 71 15 68 03 86 71 16 52 71 17 68 01 58 20 00 00 q.h..q.Rq.h.X ..
00F0 00 37 30 63 31 64 62 35 36 66 33 30 31 63 39 65 .70c1db56f301c9e
0100 33 33 37 62 30 30 39 39 62 64 34 31 37 34 62 32 337b0099bd4174b2
0110 38 71 18 68 03 86 71 19 52 71 1A 68 01 58 13 00 8q.h..q.Rq.h.X..
0120 00 00 58 2D 4F 62 6A 65 63 74 2D 4D 65 74 61 2D ..X-Object-Meta-
0130 4D 74 69 6D 65 71 1B 68 03 86 71 1C 52 71 1D 68 Mtimeq.h..q.Rq.h
0140 01 58 11 00 00 00 31 36 38 33 30 36 34 39 33 38 .X....1683064938
0150 2E 36 39 39 30 32 37 71 1E 68 03 86 71 1F 52 71 .699027q.h..q.Rq
0160 20 68 01 58 1A 00 00 00 58 2D 4F 62 6A 65 63 74 h.X....X-Object
0170 2D 4D 65 74 61 2D C3 83 C2 A2 C3 82 C2 98 C3 82 -Meta-..........
0180 C2 83 71 21 68 03 86 71 22 52 71 23 68 01 58 0C ..q!h..q"Rq#h.X.
0190 00 00 00 C3 83 C2 A2 C3 82 C2 98 C3 82 C2 83 71 ...............q
01A0 24 68 03 86 71 25 52 71 26 68 01 58 04 00 00 00 $h..q%Rq&h.X....
01B0 6E 61 6D 65 71 27 68 03 86 71 28 52 71 29 68 01 nameq'h..q(Rq)h.
01C0 58 18 00 00 00 2F 41 55 54 48 5F 74 65 73 74 2F X..../AUTH_test/
01D0 C3 A2 C2 98 C2 83 2F C3 A2 C2 98 C2 83 71 2A 68 ....../......q*h
01E0 03 86 71 2B 52 71 2C 75 2E ..q+Rq,u.
''',
}
def raw_xattr(output):
return binascii.unhexlify(''.join(
line[7:55] for line in output.split('\n')
).replace(' ', ''))
path = os.path.join(self.testdir, str(uuid.uuid4()))
for case, xattr_output in cases.items():
try:
to_write = raw_xattr(xattr_output)
with open(path, 'wb') as fp:
xattr.setxattr(
fp.fileno(), 'user.swift.metadata', to_write)
with open(path, 'rb') as fd:
actual = diskfile.read_metadata(fd)
# name should come out as native strings
self.assertEqual(actual['name'], '/AUTH_test/\u2603/\u2603')
# other meta will be WSGI strings, though
self.assertEqual(
actual['X-Object-Meta-\xe2\x98\x83'], '\xe2\x98\x83')
except Exception:
print('Failure in %s' % case, file=sys.stderr)
raise
def test_write_read_metadata(self):
path = os.path.join(self.testdir, str(uuid.uuid4()))
metadata = {'name': '/a/c/o',
'Content-Length': 99,
u'X-Object-Sysmeta-Ec-Frag-Index': 4,
u'X-Object-Meta-Strange': u'should be bytes',
b'X-Object-Meta-x\xff': b'not utf8 \xff',
u'X-Object-Meta-y\xe8': u'not ascii \xe8'}
as_bytes = {b'name': b'/a/c/o',
b'Content-Length': 99,
b'X-Object-Sysmeta-Ec-Frag-Index': 4,
b'X-Object-Meta-Strange': b'should be bytes',
b'X-Object-Meta-x\xff': b'not utf8 \xff',
b'X-Object-Meta-y\xc3\xa8': b'not ascii \xc3\xa8'}
as_native = dict((k.decode('utf-8', 'surrogateescape'),
v if isinstance(v, int) else
v.decode('utf-8', 'surrogateescape'))
for k, v in as_bytes.items())
def check_metadata(expected, typ):
with open(path, 'rb') as fd:
actual = diskfile.read_metadata(fd)
self.assertEqual(expected, actual)
for k, v in actual.items():
self.assertIsInstance(k, typ)
self.assertIsInstance(v, (typ, int))
# Check can write raw bytes
with open(path, 'wb') as fd:
diskfile.write_metadata(fd, as_bytes)
check_metadata(as_native, str)
# Check can write native (with surrogates on py3)
with open(path, 'wb') as fd:
diskfile.write_metadata(fd, as_native)
check_metadata(as_native, str)
# Check can write some crazy mix
with open(path, 'wb') as fd:
diskfile.write_metadata(fd, metadata)
check_metadata(as_native, str)
def test_read_file_metadata(self):
path = os.path.join(self.testdir, str(uuid.uuid4()))
metadata = {'name': '/a/c/o'}
with open(path, 'wb') as fd:
diskfile.write_metadata(fd, metadata)
actual = diskfile._read_file_metadata(path)
self.assertEqual(metadata, actual)
with open(path, 'rb') as fd:
os.unlink(path)
actual = diskfile._read_file_metadata(fd)
self.assertEqual(metadata, actual)
def test_read_file_metadata_nonexistent_file(self):
with self.assertRaises(DiskFileStateChanged):
diskfile._read_file_metadata('nonexistent')
def test_read_metadata_nonexistent_file(self):
with self.assertRaises(DiskFileNotExist):
diskfile.read_metadata('nonexistent')
@patch_policies
class TestObjectAuditLocationGenerator(unittest.TestCase):
def _make_file(self, path):
try:
os.makedirs(os.path.dirname(path))
except OSError as err:
if err.errno != errno.EEXIST:
raise
with open(path, 'w'):
pass
def test_audit_location_class(self):
al = diskfile.AuditLocation('abc', '123', '_-_',
policy=POLICIES.legacy)
self.assertEqual(str(al), 'abc')
def test_finding_of_hashdirs(self):
with temptree([]) as tmpdir:
# the good
os.makedirs(os.path.join(tmpdir, "sdp", "objects", "1519", "aca",
"5c1fdc1ffb12e5eaf84edc30d8b67aca"))
os.makedirs(os.path.join(tmpdir, "sdp", "objects", "1519", "aca",
"fdfd184d39080020bc8b487f8a7beaca"))
os.makedirs(os.path.join(tmpdir, "sdp", "objects", "1519", "df2",
"b0fe7af831cc7b1af5bf486b1c841df2"))
os.makedirs(os.path.join(tmpdir, "sdp", "objects", "9720", "ca5",
"4a943bc72c2e647c4675923d58cf4ca5"))
os.makedirs(os.path.join(tmpdir, "sdq", "objects", "3071", "8eb",
"fcd938702024c25fef6c32fef05298eb"))
os.makedirs(os.path.join(tmpdir, "sdp", "objects-1", "9970", "ca5",
"4a943bc72c2e647c4675923d58cf4ca5"))
self._make_file(os.path.join(tmpdir, "sdp", "objects", "1519",
"fed"))
self._make_file(os.path.join(tmpdir, "sdq", "objects", "9876"))
# the empty
os.makedirs(os.path.join(tmpdir, "sdr"))
os.makedirs(os.path.join(tmpdir, "sds", "objects"))
os.makedirs(os.path.join(tmpdir, "sdt", "objects", "9601"))
os.makedirs(os.path.join(tmpdir, "sdu", "objects", "6499", "f80"))
# the irrelevant
os.makedirs(os.path.join(tmpdir, "sdv", "accounts", "77", "421",
"4b8c86149a6d532f4af018578fd9f421"))
os.makedirs(os.path.join(tmpdir, "sdw", "containers", "28", "51e",
"4f9eee668b66c6f0250bfa3c7ab9e51e"))
logger = debug_logger()
loc_generators = []
datadirs = ["objects", "objects-1"]
for datadir in datadirs:
loc_generators.append(
diskfile.object_audit_location_generator(
devices=tmpdir, datadir=datadir, mount_check=False,
logger=logger))
all_locs = itertools.chain(*loc_generators)
locations = [(loc.path, loc.device, loc.partition, loc.policy) for
loc in all_locs]
locations.sort()
expected = \
[(os.path.join(tmpdir, "sdp", "objects-1", "9970", "ca5",
"4a943bc72c2e647c4675923d58cf4ca5"),
"sdp", "9970", POLICIES[1]),
(os.path.join(tmpdir, "sdp", "objects", "1519", "aca",
"5c1fdc1ffb12e5eaf84edc30d8b67aca"),
"sdp", "1519", POLICIES[0]),
(os.path.join(tmpdir, "sdp", "objects", "1519", "aca",
"fdfd184d39080020bc8b487f8a7beaca"),
"sdp", "1519", POLICIES[0]),
(os.path.join(tmpdir, "sdp", "objects", "1519", "df2",
"b0fe7af831cc7b1af5bf486b1c841df2"),
"sdp", "1519", POLICIES[0]),
(os.path.join(tmpdir, "sdp", "objects", "9720", "ca5",
"4a943bc72c2e647c4675923d58cf4ca5"),
"sdp", "9720", POLICIES[0]),
(os.path.join(tmpdir, "sdq", "objects", "3071", "8eb",
"fcd938702024c25fef6c32fef05298eb"),
"sdq", "3071", POLICIES[0]),
]
self.assertEqual(locations, expected)
# Reset status file for next run
for datadir in datadirs:
diskfile.clear_auditor_status(tmpdir, datadir)
# now without a logger
for datadir in datadirs:
loc_generators.append(
diskfile.object_audit_location_generator(
devices=tmpdir, datadir=datadir, mount_check=False,
logger=logger))
all_locs = itertools.chain(*loc_generators)
locations = [(loc.path, loc.device, loc.partition, loc.policy) for
loc in all_locs]
locations.sort()
self.assertEqual(locations, expected)
def test_skipping_unmounted_devices(self):
with temptree([]) as tmpdir, mock_check_drive() as mocks:
mocks['ismount'].side_effect = lambda path: path.endswith('sdp')
os.makedirs(os.path.join(tmpdir, "sdp", "objects",
"2607", "df3",
"ec2871fe724411f91787462f97d30df3"))
os.makedirs(os.path.join(tmpdir, "sdq", "objects",
"9785", "a10",
"4993d582f41be9771505a8d4cb237a10"))
locations = [
(loc.path, loc.device, loc.partition, loc.policy)
for loc in diskfile.object_audit_location_generator(
devices=tmpdir, datadir="objects", mount_check=True)]
locations.sort()
self.assertEqual(
locations,
[(os.path.join(tmpdir, "sdp", "objects",
"2607", "df3",
"ec2871fe724411f91787462f97d30df3"),
"sdp", "2607", POLICIES[0])])
# Do it again, this time with a logger.
logger = debug_logger()
locations = [
(loc.path, loc.device, loc.partition, loc.policy)
for loc in diskfile.object_audit_location_generator(
devices=tmpdir, datadir="objects", mount_check=True,
logger=logger)]
debug_lines = logger.get_lines_for_level('debug')
self.assertEqual([
'Skipping: %s/sdq is not mounted' % tmpdir,
], debug_lines)
def test_skipping_files(self):
with temptree([]) as tmpdir:
os.makedirs(os.path.join(tmpdir, "sdp", "objects",
"2607", "df3",
"ec2871fe724411f91787462f97d30df3"))
with open(os.path.join(tmpdir, "garbage"), "wb"):
pass
locations = [
(loc.path, loc.device, loc.partition, loc.policy)
for loc in diskfile.object_audit_location_generator(
devices=tmpdir, datadir="objects", mount_check=False)]
self.assertEqual(
locations,
[(os.path.join(tmpdir, "sdp", "objects",
"2607", "df3",
"ec2871fe724411f91787462f97d30df3"),
"sdp", "2607", POLICIES[0])])
# Do it again, this time with a logger.
logger = debug_logger('test')
locations = [
(loc.path, loc.device, loc.partition, loc.policy)
for loc in diskfile.object_audit_location_generator(
devices=tmpdir, datadir="objects", mount_check=False,
logger=logger)]
debug_lines = logger.get_lines_for_level('debug')
self.assertEqual([
'Skipping: %s/garbage is not a directory' % tmpdir,
], debug_lines)
logger.clear()
with mock_check_drive() as mocks:
mocks['ismount'].side_effect = lambda path: (
False if path.endswith('garbage') else True)
locations = [
(loc.path, loc.device, loc.partition, loc.policy)
for loc in diskfile.object_audit_location_generator(
devices=tmpdir, datadir="objects", mount_check=True,
logger=logger)]
debug_lines = logger.get_lines_for_level('debug')
self.assertEqual([
'Skipping: %s/garbage is not mounted' % tmpdir,
], debug_lines)
def test_only_catch_expected_errors(self):
# Crazy exceptions should still escape object_audit_location_generator
# so that errors get logged and a human can see what's going wrong;
# only normal FS corruption should be skipped over silently.
def list_locations(dirname, datadir):
return [(loc.path, loc.device, loc.partition, loc.policy)
for loc in diskfile.object_audit_location_generator(
devices=dirname, datadir=datadir, mount_check=False)]
real_listdir = os.listdir
def splode_if_endswith(suffix):
def sploder(path):
if path.endswith(suffix):
raise OSError(errno.EACCES, "don't try to ad-lib")
else:
return real_listdir(path)
return sploder
with temptree([]) as tmpdir:
os.makedirs(os.path.join(tmpdir, "sdf", "objects",
"2607", "b54",
"fe450ec990a88cc4b252b181bab04b54"))
with mock.patch('os.listdir', splode_if_endswith("sdf/objects")):
self.assertRaises(OSError, list_locations, tmpdir, "objects")
with mock.patch('os.listdir', splode_if_endswith("2607")):
self.assertRaises(OSError, list_locations, tmpdir, "objects")
with mock.patch('os.listdir', splode_if_endswith("b54")):
self.assertRaises(OSError, list_locations, tmpdir, "objects")
def test_auditor_status(self):
with temptree([]) as tmpdir:
os.makedirs(os.path.join(tmpdir, "sdf", "objects", "1", "a", "b"))
os.makedirs(os.path.join(tmpdir, "sdf", "objects", "2", "a", "b"))
datadir = "objects"
# Pretend that some time passed between each partition
with mock.patch('os.stat') as mock_stat, \
mock_check_drive(isdir=True):
mock_stat.return_value.st_mtime = time() - 60
# Auditor starts, there are two partitions to check
gen = diskfile.object_audit_location_generator(tmpdir,
datadir,
False)
next(gen)
next(gen)
# Auditor stopped for some reason without raising StopIterator in
# the generator and restarts There is now only one remaining
# partition to check
gen = diskfile.object_audit_location_generator(tmpdir, datadir,
False)
with mock_check_drive(isdir=True):
next(gen)
# There are no more remaining partitions
self.assertRaises(StopIteration, next, gen)
# There are no partitions to check if the auditor restarts another
# time and the status files have not been cleared
gen = diskfile.object_audit_location_generator(tmpdir, datadir,
False)
with mock_check_drive(isdir=True):
self.assertRaises(StopIteration, next, gen)
# Reset status file
diskfile.clear_auditor_status(tmpdir, datadir)
# If the auditor restarts another time, we expect to
# check two partitions again, because the remaining
# partitions were empty and a new listdir was executed
gen = diskfile.object_audit_location_generator(tmpdir, datadir,
False)
with mock_check_drive(isdir=True):
next(gen)
next(gen)
def test_update_auditor_status_throttle(self):
# If there are a lot of nearly empty partitions, the
# update_auditor_status will write the status file many times a second,
# creating some unexpected high write load. This test ensures that the
# status file is only written once a minute.
with temptree([]) as tmpdir:
os.makedirs(os.path.join(tmpdir, "sdf", "objects", "1", "a", "b"))
with mock.patch('swift.obj.diskfile.open') as mock_open:
# File does not exist yet - write expected
update_auditor_status(tmpdir, None, ['42'], "ALL")
self.assertEqual(1, mock_open.call_count)
mock_open.reset_mock()
# File exists, updated just now - no write expected
with mock.patch('os.stat') as mock_stat:
mock_stat.return_value.st_mtime = time()
update_auditor_status(tmpdir, None, ['42'], "ALL")
self.assertEqual(0, mock_open.call_count)
mock_open.reset_mock()
# File exists, updated just now, but empty partition list. This
# is a finalizing call, write expected
with mock.patch('os.stat') as mock_stat:
mock_stat.return_value.st_mtime = time()
update_auditor_status(tmpdir, None, [], "ALL")
self.assertEqual(1, mock_open.call_count)
mock_open.reset_mock()
# File updated more than 60 seconds ago - write expected
with mock.patch('os.stat') as mock_stat:
mock_stat.return_value.st_mtime = time() - 61
update_auditor_status(tmpdir, None, ['42'], "ALL")
self.assertEqual(1, mock_open.call_count)
class TestDiskFileRouter(unittest.TestCase):
@patch_policies(test_policies)
def test_policy(self):
conf = {}
logger = debug_logger('test-' + self.__class__.__name__)
df_router = diskfile.DiskFileRouter(conf, logger)
manager_0 = df_router[POLICIES[0]]
self.assertIsInstance(manager_0, diskfile.DiskFileManager)
manager_1 = df_router[POLICIES[1]]
self.assertIsInstance(manager_1, diskfile.ECDiskFileManager)
# The DiskFileRouter should not have to load the policy again
with mock.patch('swift.common.storage_policy.BaseStoragePolicy.' +
'get_diskfile_manager') as mock_load:
manager_3 = df_router[POLICIES[0]]
mock_load.assert_not_called()
self.assertIs(manager_3, manager_0)
self.assertIsInstance(manager_3, diskfile.DiskFileManager)
def test_invalid_policy_config(self):
# verify that invalid policy diskfile configs are detected when the
# DiskfileRouter is created
bad_policy = StoragePolicy(0, name='zero', is_default=True,
diskfile_module='erasure_coding.fs')
with patch_policies([bad_policy]):
with self.assertRaises(PolicyError) as cm:
diskfile.DiskFileRouter({}, debug_logger())
self.assertIn('Invalid diskfile_module erasure_coding.fs',
str(cm.exception))
bad_policy = ECStoragePolicy(0, name='one', is_default=True,
ec_type=DEFAULT_TEST_EC_TYPE,
ec_ndata=10, ec_nparity=4,
diskfile_module='replication.fs')
with patch_policies([bad_policy]):
with self.assertRaises(PolicyError) as cm:
diskfile.DiskFileRouter({}, debug_logger())
self.assertIn('Invalid diskfile_module replication.fs',
str(cm.exception))
bad_policy = StoragePolicy(0, name='zero', is_default=True,
diskfile_module='thin_air.fs')
with patch_policies([bad_policy]):
with self.assertRaises(PolicyError) as cm:
diskfile.DiskFileRouter({}, debug_logger())
self.assertIn('Unable to load diskfile_module thin_air.fs',
str(cm.exception))
class BaseDiskFileTestMixin(object):
"""
Bag of helpers that are useful in the per-policy DiskFile test classes,
plus common setUp and tearDown methods.
"""
# set mgr_cls on subclasses
mgr_cls = None
def setUp(self):
skip_if_no_xattrs()
self.tmpdir = mkdtemp()
self.testdir = os.path.join(
self.tmpdir, 'tmp_test_obj_server_DiskFile')
self.existing_device = 'sda1'
self.existing_device2 = 'sda2'
for policy in POLICIES:
mkdirs(os.path.join(self.testdir, self.existing_device,
diskfile.get_tmp_dir(policy)))
mkdirs(os.path.join(self.testdir, self.existing_device2,
diskfile.get_tmp_dir(policy)))
self._orig_tpool_exc = tpool.execute
tpool.execute = lambda f, *args, **kwargs: f(*args, **kwargs)
self.conf = dict(devices=self.testdir, mount_check='false',
keep_cache_size=2 * 1024, mb_per_sync=1)
self.logger = debug_logger('test-' + self.__class__.__name__)
self.df_mgr = self.mgr_cls(self.conf, self.logger)
self.df_router = diskfile.DiskFileRouter(self.conf, self.logger)
self._ts_iter = (Timestamp(t) for t in
itertools.count(int(time())))
def tearDown(self):
rmtree(self.tmpdir, ignore_errors=True)
tpool.execute = self._orig_tpool_exc
def _manager_mock(self, manager_attribute_name, df=None):
mgr_cls = df._manager.__class__ if df else self.mgr_cls
return '.'.join([
mgr_cls.__module__, mgr_cls.__name__, manager_attribute_name])
class DiskFileManagerMixin(BaseDiskFileTestMixin):
"""
Abstract test method mixin for concrete test cases - this class
won't get picked up by test runners because it doesn't subclass
unittest.TestCase and doesn't have [Tt]est in the name.
"""
def _get_diskfile(self, policy, frag_index=None, **kwargs):
df_mgr = self.df_router[policy]
return df_mgr.get_diskfile('sda1', '0', 'a', 'c', 'o',
policy=policy, frag_index=frag_index,
**kwargs)
def test_init(self):
for policy in POLICIES:
df_router = diskfile.DiskFileRouter({}, self.logger)
df_mgr = df_router[policy]
self.assertEqual('/srv/node', df_mgr.devices)
self.assertEqual(604800, df_mgr.reclaim_age)
self.assertEqual(60.0, df_mgr.commit_window)
self.assertTrue(df_mgr.mount_check)
for policy in POLICIES:
conf = dict(devices=self.testdir,
mount_check='false',
reclaim_age=1000,
commit_window=10.1)
df_router = diskfile.DiskFileRouter(conf, self.logger)
df_mgr = df_router[policy]
self.assertEqual(self.testdir, df_mgr.devices)
self.assertEqual(1000, df_mgr.reclaim_age)
self.assertEqual(10.1, df_mgr.commit_window)
self.assertFalse(df_mgr.mount_check)
def test_init_commit_window(self):
def assert_ok(value, expected):
for policy in POLICIES:
conf = {'commit_window': value}
df_mgr = diskfile.DiskFileRouter(conf, self.logger)[policy]
self.assertEqual(expected, df_mgr.commit_window)
assert_ok(10.1, 10.1)
assert_ok('10.1', 10.1)
assert_ok(0, 0.0)
def assert_invalid(value):
for policy in POLICIES:
conf = {'commit_window': value}
with self.assertRaises(ValueError):
diskfile.DiskFileRouter(conf, self.logger)[policy]
assert_invalid(-1.1)
assert_invalid('-1.1')
assert_invalid('auto')
def test_cleanup_uses_configured_reclaim_age(self):
# verify that the reclaim_age used when cleaning up tombstones is
# either the default or the configured value
def do_test(ts, expect_reclaim):
for policy in POLICIES:
self.df_router = diskfile.DiskFileRouter(
self.conf, self.logger)
df = self._get_diskfile(policy)
df.delete(ts.internal)
tombstone_file = os.path.join(df._datadir, ts.internal + '.ts')
# cleanup_ondisk_files always uses the configured value
df._manager.cleanup_ondisk_files(
os.path.dirname(tombstone_file))
self.assertNotEqual(
expect_reclaim, os.path.exists(tombstone_file))
# reclaim_age not configured so default should be used
do_test(Timestamp(time() - diskfile.DEFAULT_RECLAIM_AGE - 1), True)
do_test(Timestamp(time() - diskfile.DEFAULT_RECLAIM_AGE + 100), False)
# reclaim_age configured value should be used
self.conf['reclaim_age'] = 1000
do_test(Timestamp(time() - diskfile.DEFAULT_RECLAIM_AGE + 100), True)
do_test(Timestamp(time() - 1001), True)
do_test(Timestamp(time() + 100), False)
def _test_get_ondisk_files(self, scenarios, policy,
frag_index=None, **kwargs):
class_under_test = self._get_diskfile(
policy, frag_index=frag_index, **kwargs)
for test in scenarios:
# test => [('filename.ext', '.ext'|False, ...), ...]
expected = {
ext[1:] + '_file': os.path.join(
class_under_test._datadir, filename)
for (filename, ext) in [v[:2] for v in test]
if ext in ('.data', '.meta', '.ts')}
# list(zip(...)) for py3 compatibility (zip is lazy there)
files = list(list(zip(*test))[0])
for _order in ('ordered', 'shuffled', 'shuffled'):
class_under_test = self._get_diskfile(
policy, frag_index=frag_index, **kwargs)
try:
actual = class_under_test._get_ondisk_files(files)
self._assertDictContainsSubset(
expected, actual,
'Expected %s from %s but got %s'
% (expected, files, actual))
except AssertionError as e:
self.fail('%s with files %s' % (str(e), files))
shuffle(files)
def _test_cleanup_ondisk_files(self, scenarios, policy,
reclaim_age=None, commit_window=None):
# check that expected files are left in hashdir after cleanup
for test in scenarios:
class_under_test = self.df_router[policy]
# list(zip(...)) for py3 compatibility (zip is lazy there)
files = list(list(zip(*test))[0])
hashdir = os.path.join(self.testdir, str(uuid.uuid4()))
os.mkdir(hashdir)
for fname in files:
open(os.path.join(hashdir, fname), 'w')
expected_after_cleanup = set([f[0] for f in test
if (f[2] if len(f) > 2 else f[1])])
if commit_window is not None:
class_under_test.commit_window = commit_window
if reclaim_age:
class_under_test.reclaim_age = reclaim_age
class_under_test.cleanup_ondisk_files(hashdir)
else:
with mock.patch('swift.obj.diskfile.time') as mock_time:
# don't reclaim anything
mock_time.time.return_value = 0.0
class_under_test.cleanup_ondisk_files(hashdir)
if expected_after_cleanup:
after_cleanup = set(os.listdir(hashdir))
errmsg = "expected %r, got %r for test %r" % (
sorted(expected_after_cleanup), sorted(after_cleanup), test
)
self.assertEqual(expected_after_cleanup, after_cleanup, errmsg)
else:
self.assertFalse(os.path.exists(hashdir))
def _test_yield_hashes_cleanup(self, scenarios, policy):
# opportunistic test to check that yield_hashes cleans up dir using
# same scenarios as passed to _test_cleanup_ondisk_files_files
for test in scenarios:
class_under_test = self.df_router[policy]
# list(zip(...)) for py3 compatibility (zip is lazy there)
files = list(list(zip(*test))[0])
dev_path = os.path.join(self.testdir, str(uuid.uuid4()))
hashdir = os.path.join(
dev_path, diskfile.get_data_dir(policy),
'0', 'abc', '9373a92d072897b136b3fc06595b4abc')
os.makedirs(hashdir)
for fname in files:
open(os.path.join(hashdir, fname), 'w')
expected_after_cleanup = set([f[0] for f in test
if f[1] or len(f) > 2 and f[2]])
with mock.patch('swift.obj.diskfile.time') as mock_time:
# don't reclaim anything
mock_time.time.return_value = 0.0
mocked = 'swift.obj.diskfile.BaseDiskFileManager.get_dev_path'
with mock.patch(mocked) as mock_path:
mock_path.return_value = dev_path
for _ in class_under_test.yield_hashes(
'ignored', '0', policy, suffixes=['abc']):
# return values are tested in test_yield_hashes_*
pass
if expected_after_cleanup:
after_cleanup = set(os.listdir(hashdir))
errmsg = "expected %r, got %r for test %r" % (
sorted(expected_after_cleanup), sorted(after_cleanup), test
)
self.assertEqual(expected_after_cleanup, after_cleanup, errmsg)
else:
self.assertFalse(os.path.exists(hashdir))
def test_get_ondisk_files_with_empty_dir(self):
files = []
expected = dict(
data_file=None, meta_file=None, ctype_file=None, ts_file=None)
for policy in POLICIES:
for frag_index in (0, None, '13'):
# check manager
df_mgr = self.df_router[policy]
datadir = os.path.join('/srv/node/sdb1/',
diskfile.get_data_dir(policy))
actual = df_mgr.get_ondisk_files(files, datadir)
self._assertDictContainsSubset(expected, actual)
# check diskfile under the hood
df = self._get_diskfile(policy, frag_index=frag_index)
actual = df._get_ondisk_files(files)
self._assertDictContainsSubset(expected, actual)
# check diskfile open
self.assertRaises(DiskFileNotExist, df.open)
def test_get_ondisk_files_with_unexpected_file(self):
unexpected_files = ['junk', 'junk.data', '.junk']
timestamp = next(make_timestamp_iter())
tomb_file = timestamp.internal + '.ts'
for policy in POLICIES:
for unexpected in unexpected_files:
self.logger.clear()
files = [unexpected, tomb_file]
df_mgr = self.df_router[policy]
datadir = os.path.join('/srv/node/sdb1/',
diskfile.get_data_dir(policy))
results = df_mgr.get_ondisk_files(files, datadir)
expected = {'ts_file': os.path.join(datadir, tomb_file)}
self._assertDictContainsSubset(expected, results)
log_lines = df_mgr.logger.get_lines_for_level('warning')
self.assertTrue(
log_lines[0].startswith(
'Unexpected file %s'
% os.path.join(datadir, unexpected)))
def test_get_ondisk_files_no_rsync_temp_file_warning(self):
# get_ondisk_files logs no warnings for rsync temp files
class_under_test = self._get_diskfile(POLICIES[0])
files = [
'.1472017820.44503.data.QBYCYU', # rsync tempfile for a .data
'.total-bs.abcdef', # example of false positive
]
paths = [os.path.join(class_under_test._datadir, f) for f in files]
expected = {'unexpected': paths}
results = class_under_test._get_ondisk_files(files)
for k, v in expected.items():
self.assertEqual(results[k], v)
# no warnings
self.assertFalse(self.logger.get_lines_for_level('warning'))
# but we do get a debug!
lines = self.logger.get_lines_for_level('debug')
for path in paths:
expected_msg = 'Rsync tempfile: %s' % path
self.assertIn(expected_msg, lines)
def test_cleanup_ondisk_files_reclaim_non_data_files(self):
# Each scenario specifies a list of (filename, extension, [survives])
# tuples. If extension is set or 'survives' is True, the filename
# should still be in the dir after cleanup.
much_older = Timestamp(time() - 2000).internal
older = Timestamp(time() - 1001).internal
newer = Timestamp(time() - 900).internal
scenarios = [
[('%s.ts' % older, False, False)],
# fresh tombstone is preserved
[('%s.ts' % newer, '.ts', True)],
# tombstone reclaimed despite junk file
[('junk', False, True),
('%s.ts' % much_older, '.ts', False)],
# fresh .meta not reclaimed even if isolated
[('%s.meta' % newer, '.meta')],
# fresh .meta not reclaimed when tombstone is reclaimed
[('%s.meta' % newer, '.meta'),
('%s.ts' % older, False, False)],
# stale isolated .meta is reclaimed
[('%s.meta' % older, False, False)],
# stale .meta is reclaimed along with tombstone
[('%s.meta' % older, False, False),
('%s.ts' % older, False, False)]]
self._test_cleanup_ondisk_files(scenarios, POLICIES.default,
reclaim_age=1000, commit_window=0)
def test_construct_dev_path(self):
res_path = self.df_mgr.construct_dev_path('abc')
self.assertEqual(os.path.join(self.df_mgr.devices, 'abc'), res_path)
def test_pickle_async_update(self):
self.df_mgr.logger.increment = mock.MagicMock()
ts = Timestamp(10000.0).internal
with mock.patch('swift.obj.diskfile.write_pickle') as wp:
self.df_mgr.pickle_async_update(self.existing_device,
'a', 'c', 'o',
dict(a=1, b=2), ts, POLICIES[0])
dp = self.df_mgr.construct_dev_path(self.existing_device)
ohash = diskfile.hash_path('a', 'c', 'o')
wp.assert_called_with({'a': 1, 'b': 2},
os.path.join(
dp, diskfile.get_async_dir(POLICIES[0]),
ohash[-3:], ohash + '-' + ts),
os.path.join(dp, 'tmp'))
self.df_mgr.logger.increment.assert_called_with('async_pendings')
def test_object_audit_location_generator(self):
locations = list(
self.df_mgr.object_audit_location_generator(POLICIES[0]))
self.assertEqual(locations, [])
def test_replication_one_per_device_deprecation(self):
conf = dict(**self.conf)
mgr = diskfile.DiskFileManager(conf, self.logger)
self.assertEqual(mgr.replication_concurrency_per_device, 1)
conf = dict(replication_concurrency_per_device='0', **self.conf)
mgr = diskfile.DiskFileManager(conf, self.logger)
self.assertEqual(mgr.replication_concurrency_per_device, 0)
conf = dict(replication_concurrency_per_device='2', **self.conf)
mgr = diskfile.DiskFileManager(conf, self.logger)
self.assertEqual(mgr.replication_concurrency_per_device, 2)
conf = dict(replication_concurrency_per_device=2, **self.conf)
mgr = diskfile.DiskFileManager(conf, self.logger)
self.assertEqual(mgr.replication_concurrency_per_device, 2)
# Check backward compatibility
conf = dict(replication_one_per_device='true', **self.conf)
mgr = diskfile.DiskFileManager(conf, self.logger)
self.assertEqual(mgr.replication_concurrency_per_device, 1)
log_lines = mgr.logger.get_lines_for_level('warning')
self.assertIn('replication_one_per_device is deprecated',
log_lines[-1])
conf = dict(replication_one_per_device='false', **self.conf)
mgr = diskfile.DiskFileManager(conf, self.logger)
self.assertEqual(mgr.replication_concurrency_per_device, 0)
log_lines = mgr.logger.get_lines_for_level('warning')
self.assertIn('replication_one_per_device is deprecated',
log_lines[-1])
# If defined, new parameter has precedence
conf = dict(replication_concurrency_per_device='2',
replication_one_per_device='true', **self.conf)
mgr = diskfile.DiskFileManager(conf, self.logger)
self.assertEqual(mgr.replication_concurrency_per_device, 2)
log_lines = mgr.logger.get_lines_for_level('warning')
self.assertIn('replication_one_per_device ignored',
log_lines[-1])
conf = dict(replication_concurrency_per_device='2',
replication_one_per_device='false', **self.conf)
mgr = diskfile.DiskFileManager(conf, self.logger)
self.assertEqual(mgr.replication_concurrency_per_device, 2)
log_lines = mgr.logger.get_lines_for_level('warning')
self.assertIn('replication_one_per_device ignored',
log_lines[-1])
conf = dict(replication_concurrency_per_device='0',
replication_one_per_device='true', **self.conf)
mgr = diskfile.DiskFileManager(conf, self.logger)
self.assertEqual(mgr.replication_concurrency_per_device, 0)
log_lines = mgr.logger.get_lines_for_level('warning')
self.assertIn('replication_one_per_device ignored',
log_lines[-1])
def test_replication_lock_on(self):
# Double check settings
self.df_mgr.replication_concurrency_per_device = 1
self.df_mgr.replication_lock_timeout = 0.1
success = False
with self.df_mgr.replication_lock(self.existing_device,
POLICIES.legacy, '1'):
with self.assertRaises(ReplicationLockTimeout):
with self.df_mgr.replication_lock(self.existing_device,
POLICIES.legacy, '2'):
success = True
self.assertFalse(success)
def test_replication_lock_off(self):
# Double check settings
self.df_mgr.replication_concurrency_per_device = 0
self.df_mgr.replication_lock_timeout = 0.1
# 2 locks must succeed
success = False
with self.df_mgr.replication_lock(self.existing_device,
POLICIES.legacy, '1'):
try:
with self.df_mgr.replication_lock(self.existing_device,
POLICIES.legacy, '2'):
success = True
except ReplicationLockTimeout as err:
self.fail('Unexpected exception: %s' % err)
self.assertTrue(success)
# 3 locks must succeed
success = False
with self.df_mgr.replication_lock(self.existing_device,
POLICIES.legacy, '1'):
with self.df_mgr.replication_lock(self.existing_device,
POLICIES.legacy, '2'):
try:
with self.df_mgr.replication_lock(self.existing_device,
POLICIES.legacy, '3'):
success = True
except ReplicationLockTimeout as err:
self.fail('Unexpected exception: %s' % err)
self.assertTrue(success)
def test_replication_lock_2(self):
# Double check settings
self.df_mgr.replication_concurrency_per_device = 2
self.df_mgr.replication_lock_timeout = 0.1
# 2 locks with replication_concurrency_per_device=2 must succeed
success = False
with self.df_mgr.replication_lock(self.existing_device,
POLICIES.legacy, '1'):
try:
with self.df_mgr.replication_lock(self.existing_device,
POLICIES.legacy, '2'):
success = True
except ReplicationLockTimeout as err:
self.fail('Unexpected exception: %s' % err)
self.assertTrue(success)
# 3 locks with replication_concurrency_per_device=2 must fail
success = False
with self.df_mgr.replication_lock(self.existing_device,
POLICIES.legacy, '1'):
with self.df_mgr.replication_lock(self.existing_device,
POLICIES.legacy, '2'):
with self.assertRaises(ReplicationLockTimeout):
with self.df_mgr.replication_lock(self.existing_device,
POLICIES.legacy, '3'):
success = True
self.assertFalse(success)
def test_replication_lock_another_device_fine(self):
# Double check settings
self.df_mgr.replication_concurrency_per_device = 1
self.df_mgr.replication_lock_timeout = 0.1
success = False
with self.df_mgr.replication_lock(self.existing_device,
POLICIES.legacy, '1'):
try:
with self.df_mgr.replication_lock(self.existing_device2,
POLICIES.legacy, '2'):
success = True
except ReplicationLockTimeout as err:
self.fail('Unexpected exception: %s' % err)
self.assertTrue(success)
def test_replication_lock_same_partition(self):
# Double check settings
self.df_mgr.replication_concurrency_per_device = 2
self.df_mgr.replication_lock_timeout = 0.1
success = False
with self.df_mgr.replication_lock(self.existing_device,
POLICIES.legacy, '1'):
with self.assertRaises(PartitionLockTimeout):
with self.df_mgr.replication_lock(self.existing_device,
POLICIES.legacy, '1'):
success = True
self.assertFalse(success)
def test_partition_lock_same_partition(self):
# Double check settings
self.df_mgr.replication_lock_timeout = 0.1
success = False
with self.df_mgr.partition_lock(self.existing_device,
POLICIES.legacy, '1', name='foo'):
with self.assertRaises(PartitionLockTimeout):
with self.df_mgr.partition_lock(self.existing_device,
POLICIES.legacy, '1',
name='foo'):
success = True
self.assertFalse(success)
def test_partition_lock_same_partition_different_name(self):
# Double check settings
self.df_mgr.replication_lock_timeout = 0.1
success = False
with self.df_mgr.partition_lock(self.existing_device,
POLICIES.legacy, '1', name='foo'):
with self.df_mgr.partition_lock(self.existing_device,
POLICIES.legacy, '1',
name='bar'):
success = True
self.assertTrue(success)
def test_partition_lock_and_replication_lock_same_partition(self):
# Double check settings
self.df_mgr.replication_lock_timeout = 0.1
success = False
with self.df_mgr.partition_lock(self.existing_device,
POLICIES.legacy, '1',
name='replication'):
with self.assertRaises(PartitionLockTimeout):
with self.df_mgr.replication_lock(self.existing_device,
POLICIES.legacy, '1'):
success = True
self.assertFalse(success)
success = False
with self.df_mgr.replication_lock(self.existing_device,
POLICIES.legacy, '1'):
with self.assertRaises(PartitionLockTimeout):
with self.df_mgr.partition_lock(self.existing_device,
POLICIES.legacy, '1',
name='replication'):
success = True
self.assertFalse(success)
def test_missing_splice_warning(self):
with mock.patch('swift.common.splice.splice._c_splice', None):
self.conf['splice'] = 'yes'
mgr = diskfile.DiskFileManager(self.conf, logger=self.logger)
warnings = self.logger.get_lines_for_level('warning')
self.assertGreater(len(warnings), 0)
self.assertTrue('splice()' in warnings[-1])
self.assertFalse(mgr.use_splice)
def test_get_diskfile_from_hash_dev_path_fail(self):
self.df_mgr.get_dev_path = mock.MagicMock(return_value=None)
with mock.patch(self._manager_mock('diskfile_cls')), \
mock.patch(self._manager_mock(
'cleanup_ondisk_files')) as cleanup, \
mock.patch('swift.obj.diskfile.read_metadata') as readmeta:
cleanup.return_value = {'files': ['1381679759.90941.data']}
readmeta.return_value = {'name': '/a/c/o'}
self.assertRaises(
DiskFileDeviceUnavailable,
self.df_mgr.get_diskfile_from_hash,
'dev', '9', '9a7175077c01a23ade5956b8a2bba900', POLICIES[0])
def test_get_diskfile_from_hash_not_dir(self):
self.df_mgr.get_dev_path = mock.MagicMock(return_value='/srv/dev/')
with mock.patch(self._manager_mock('diskfile_cls')), \
mock.patch(self._manager_mock(
'cleanup_ondisk_files')) as cleanup, \
mock.patch('swift.obj.diskfile.read_metadata') as readmeta, \
mock.patch(self._manager_mock(
'quarantine_renamer')) as quarantine_renamer:
osexc = OSError()
osexc.errno = errno.ENOTDIR
cleanup.side_effect = osexc
readmeta.return_value = {'name': '/a/c/o'}
self.assertRaises(
DiskFileNotExist,
self.df_mgr.get_diskfile_from_hash,
'dev', '9', '9a7175077c01a23ade5956b8a2bba900', POLICIES[0])
quarantine_renamer.assert_called_once_with(
'/srv/dev/',
('/srv/dev/objects/9/900/9a7175077c01a23ade5956b8a2bba900/' +
'made-up-filename'))
def test_get_diskfile_from_hash_no_data(self):
self.df_mgr.get_dev_path = mock.MagicMock(return_value='/srv/dev/')
with mock.patch(self._manager_mock('diskfile_cls')), \
mock.patch(self._manager_mock(
'cleanup_ondisk_files')) as cleanup, \
mock.patch('swift.obj.diskfile.read_metadata') as readmeta, \
mock.patch(self._manager_mock(
'quarantine_renamer')) as quarantine_renamer:
osexc = OSError()
osexc.errno = errno.ENODATA
cleanup.side_effect = osexc
readmeta.return_value = {'name': '/a/c/o'}
self.assertRaises(
DiskFileNotExist,
self.df_mgr.get_diskfile_from_hash,
'dev', '9', '9a7175077c01a23ade5956b8a2bba900', POLICIES[0])
quarantine_renamer.assert_called_once_with(
'/srv/dev/',
('/srv/dev/objects/9/900/9a7175077c01a23ade5956b8a2bba900/' +
'made-up-filename'))
def test_get_diskfile_from_hash_unclean(self):
self.df_mgr.get_dev_path = mock.MagicMock(return_value='/srv/dev/')
with mock.patch(self._manager_mock('diskfile_cls')), \
mock.patch(self._manager_mock(
'cleanup_ondisk_files')) as cleanup, \
mock.patch('swift.obj.diskfile.read_metadata') as readmeta, \
mock.patch(self._manager_mock(
'quarantine_renamer')) as quarantine_renamer:
osexc = OSError()
osexc.errno = EUCLEAN
cleanup.side_effect = osexc
readmeta.return_value = {'name': '/a/c/o'}
self.assertRaises(
DiskFileNotExist,
self.df_mgr.get_diskfile_from_hash,
'dev', '9', '9a7175077c01a23ade5956b8a2bba900', POLICIES[0])
quarantine_renamer.assert_called_once_with(
'/srv/dev/',
('/srv/dev/objects/9/900/9a7175077c01a23ade5956b8a2bba900/' +
'made-up-filename'))
def test_get_diskfile_from_hash_no_dir(self):
self.df_mgr.get_dev_path = mock.MagicMock(return_value='/srv/dev/')
with mock.patch(self._manager_mock('diskfile_cls')), \
mock.patch(self._manager_mock(
'cleanup_ondisk_files')) as cleanup, \
mock.patch('swift.obj.diskfile.read_metadata') as readmeta:
osexc = OSError()
osexc.errno = errno.ENOENT
cleanup.side_effect = osexc
readmeta.return_value = {'name': '/a/c/o'}
self.assertRaises(
DiskFileNotExist,
self.df_mgr.get_diskfile_from_hash,
'dev', '9', '9a7175077c01a23ade5956b8a2bba900', POLICIES[0])
def test_get_diskfile_from_hash_other_oserror(self):
self.df_mgr.get_dev_path = mock.MagicMock(return_value='/srv/dev/')
with mock.patch(self._manager_mock('diskfile_cls')), \
mock.patch(self._manager_mock(
'cleanup_ondisk_files')) as cleanup, \
mock.patch('swift.obj.diskfile.read_metadata') as readmeta:
osexc = OSError()
cleanup.side_effect = osexc
readmeta.return_value = {'name': '/a/c/o'}
self.assertRaises(
OSError,
self.df_mgr.get_diskfile_from_hash,
'dev', '9', '9a7175077c01a23ade5956b8a2bba900', POLICIES[0])
def test_get_diskfile_from_hash_no_actual_files(self):
self.df_mgr.get_dev_path = mock.MagicMock(return_value='/srv/dev/')
with mock.patch(self._manager_mock('diskfile_cls')), \
mock.patch(self._manager_mock(
'cleanup_ondisk_files')) as cleanup, \
mock.patch('swift.obj.diskfile.read_metadata') as readmeta:
cleanup.return_value = {'files': []}
readmeta.return_value = {'name': '/a/c/o'}
self.assertRaises(
DiskFileNotExist,
self.df_mgr.get_diskfile_from_hash,
'dev', '9', '9a7175077c01a23ade5956b8a2bba900', POLICIES[0])
def test_get_diskfile_from_hash_read_metadata_problem(self):
self.df_mgr.get_dev_path = mock.MagicMock(return_value='/srv/dev/')
with mock.patch(self._manager_mock('diskfile_cls')), \
mock.patch(self._manager_mock(
'cleanup_ondisk_files')) as cleanup, \
mock.patch('swift.obj.diskfile.read_metadata') as readmeta:
cleanup.return_value = {'files': ['1381679759.90941.data']}
readmeta.side_effect = EOFError()
self.assertRaises(
DiskFileNotExist,
self.df_mgr.get_diskfile_from_hash,
'dev', '9', '9a7175077c01a23ade5956b8a2bba900', POLICIES[0])
def test_get_diskfile_from_hash_no_meta_name(self):
self.df_mgr.get_dev_path = mock.MagicMock(return_value='/srv/dev/')
with mock.patch(self._manager_mock('diskfile_cls')), \
mock.patch(self._manager_mock(
'cleanup_ondisk_files')) as cleanup, \
mock.patch('swift.obj.diskfile.read_metadata') as readmeta:
cleanup.return_value = {'files': ['1381679759.90941.data']}
readmeta.return_value = {}
try:
self.df_mgr.get_diskfile_from_hash(
'dev', '9', '9a7175077c01a23ade5956b8a2bba900',
POLICIES[0])
except DiskFileNotExist as err:
exc = err
self.assertEqual(str(exc), '')
def test_get_diskfile_from_hash_bad_meta_name(self):
self.df_mgr.get_dev_path = mock.MagicMock(return_value='/srv/dev/')
with mock.patch(self._manager_mock('diskfile_cls')), \
mock.patch(self._manager_mock(
'cleanup_ondisk_files')) as cleanup, \
mock.patch('swift.obj.diskfile.read_metadata') as readmeta:
cleanup.return_value = {'files': ['1381679759.90941.data']}
readmeta.return_value = {'name': 'bad'}
try:
self.df_mgr.get_diskfile_from_hash(
'dev', '9', '9a7175077c01a23ade5956b8a2bba900',
POLICIES[0])
except DiskFileNotExist as err:
exc = err
self.assertEqual(str(exc), '')
def test_get_diskfile_from_hash(self):
self.df_mgr.get_dev_path = mock.MagicMock(return_value='/srv/dev/')
mock_return = object()
with mock.patch(self._manager_mock('diskfile_cls'),
return_value=mock_return) as dfclass, \
mock.patch(self._manager_mock(
'cleanup_ondisk_files')) as cleanup, \
mock.patch('swift.obj.diskfile.read_metadata') as readmeta:
cleanup.return_value = {'files': ['1381679759.90941.data']}
readmeta.return_value = {'name': '/a/c/o'}
actual = self.df_mgr.get_diskfile_from_hash(
'dev', '9', '9a7175077c01a23ade5956b8a2bba900', POLICIES[0])
dfclass.assert_called_once_with(
self.df_mgr, '/srv/dev/', '9',
'a', 'c', 'o', policy=POLICIES[0])
cleanup.assert_called_once_with(
'/srv/dev/objects/9/900/9a7175077c01a23ade5956b8a2bba900')
readmeta.assert_called_once_with(
'/srv/dev/objects/9/900/9a7175077c01a23ade5956b8a2bba900/'
'1381679759.90941.data')
self.assertEqual(mock_return, actual)
def test_get_diskfile_and_filenames_from_hash(self):
self.df_mgr.get_dev_path = mock.MagicMock(return_value='/srv/dev/')
mock_return = object()
with mock.patch(self._manager_mock('diskfile_cls'),
return_value=mock_return) as dfclass, \
mock.patch(self._manager_mock(
'cleanup_ondisk_files')) as cleanup, \
mock.patch('swift.obj.diskfile.read_metadata') as readmeta:
cleanup.return_value = {'files': ['1381679759.90941.data']}
readmeta.return_value = {'name': '/a/c/o'}
actual, names = self.df_mgr.get_diskfile_and_filenames_from_hash(
'dev', '9', '9a7175077c01a23ade5956b8a2bba900', POLICIES[0])
dfclass.assert_called_once_with(
self.df_mgr, '/srv/dev/', '9',
'a', 'c', 'o', policy=POLICIES[0])
cleanup.assert_called_once_with(
'/srv/dev/objects/9/900/9a7175077c01a23ade5956b8a2bba900')
readmeta.assert_called_once_with(
'/srv/dev/objects/9/900/9a7175077c01a23ade5956b8a2bba900/'
'1381679759.90941.data')
self.assertEqual(mock_return, actual)
self.assertEqual(['1381679759.90941.data'], names)
def test_listdir_enoent(self):
oserror = OSError()
oserror.errno = errno.ENOENT
self.df_mgr.logger.error = mock.MagicMock()
with mock.patch('os.listdir', side_effect=oserror):
self.assertEqual(self.df_mgr._listdir('path'), [])
self.assertEqual(self.df_mgr.logger.error.mock_calls, [])
def test_listdir_other_oserror(self):
oserror = OSError()
self.df_mgr.logger.error = mock.MagicMock()
with mock.patch('os.listdir', side_effect=oserror):
self.assertEqual(self.df_mgr._listdir('path'), [])
self.df_mgr.logger.error.assert_called_once_with(
'ERROR: Skipping %r due to error with listdir attempt: %s',
'path', oserror)
def test_listdir(self):
self.df_mgr.logger.error = mock.MagicMock()
with mock.patch('os.listdir', return_value=['abc', 'def']):
self.assertEqual(self.df_mgr._listdir('path'), ['abc', 'def'])
self.assertEqual(self.df_mgr.logger.error.mock_calls, [])
def test_yield_suffixes_dev_path_fail(self):
self.df_mgr.get_dev_path = mock.MagicMock(return_value=None)
exc = None
try:
list(self.df_mgr.yield_suffixes(self.existing_device, '9', 0))
except DiskFileDeviceUnavailable as err:
exc = err
self.assertEqual(str(exc), '')
def test_yield_suffixes(self):
self.df_mgr._listdir = mock.MagicMock(return_value=[
'abc', 'def', 'ghi', 'abcd', '012'])
dev = self.existing_device
self.assertEqual(
list(self.df_mgr.yield_suffixes(dev, '9', POLICIES[0])),
[(self.testdir + '/' + dev + '/objects/9/abc', 'abc'),
(self.testdir + '/' + dev + '/objects/9/def', 'def'),
(self.testdir + '/' + dev + '/objects/9/012', '012')])
def test_yield_hashes_dev_path_fail(self):
self.df_mgr.get_dev_path = mock.MagicMock(return_value=None)
exc = None
try:
list(self.df_mgr.yield_hashes(self.existing_device, '9',
POLICIES[0]))
except DiskFileDeviceUnavailable as err:
exc = err
self.assertEqual(str(exc), '')
def test_yield_hashes_empty(self):
def _listdir(path):
return []
with mock.patch('os.listdir', _listdir):
self.assertEqual(list(self.df_mgr.yield_hashes(
self.existing_device, '9', POLICIES[0])), [])
def test_yield_hashes_cleans_up_everything(self):
the_time = [1525354555.657585]
def mock_time():
return the_time[0]
with mock.patch('time.time', mock_time):
# Make a couple of (soon-to-be-)expired tombstones
df1 = self.df_mgr.get_diskfile(
self.existing_device, 0, 'a', 'c', 'o1', POLICIES[0])
df1.delete(Timestamp(the_time[0]))
df1_hash = utils.hash_path('a', 'c', 'o1')
df1_suffix = df1_hash[-3:]
df2 = self.df_mgr.get_diskfile(
self.existing_device, 0, 'a', 'c', 'o2', POLICIES[0])
df2.delete(Timestamp(the_time[0] + 1))
df2_hash = utils.hash_path('a', 'c', 'o2')
df2_suffix = df2_hash[-3:]
# sanity checks
self.assertTrue(os.path.exists(os.path.join(
self.testdir, self.existing_device, 'objects', '0',
df1_suffix, df1_hash,
"1525354555.65758.ts")))
self.assertTrue(os.path.exists(os.path.join(
self.testdir, self.existing_device, 'objects', '0',
df2_suffix, df2_hash,
"1525354556.65758.ts")))
# Cache the hashes and expire the tombstones
self.df_mgr.get_hashes(self.existing_device, '0', [], POLICIES[0])
the_time[0] += 2 * self.df_mgr.reclaim_age
hashes = list(self.df_mgr.yield_hashes(
self.existing_device, '0', POLICIES[0]))
self.assertEqual(hashes, [])
# The tombstones are gone
self.assertFalse(os.path.exists(os.path.join(
self.testdir, self.existing_device, 'objects', '0',
df1_suffix, df1_hash,
"1525354555.65758.ts")))
self.assertFalse(os.path.exists(os.path.join(
self.testdir, self.existing_device, 'objects', '0',
df2_suffix, df2_hash,
"1525354556.65758.ts")))
# The empty hash dirs are gone
self.assertFalse(os.path.exists(os.path.join(
self.testdir, self.existing_device, 'objects', '0',
df1_suffix, df1_hash)))
self.assertFalse(os.path.exists(os.path.join(
self.testdir, self.existing_device, 'objects', '0',
df2_suffix, df2_hash)))
# The empty suffix dirs, and partition are still there
self.assertTrue(os.path.isdir(os.path.join(
self.testdir, self.existing_device, 'objects', '0',
df1_suffix)))
self.assertTrue(os.path.isdir(os.path.join(
self.testdir, self.existing_device, 'objects', '0',
df2_suffix)))
# but the suffixes is invalid
part_dir = os.path.join(
self.testdir, self.existing_device, 'objects', '0')
invalidations_file = os.path.join(
part_dir, diskfile.HASH_INVALIDATIONS_FILE)
with open(invalidations_file) as f:
invalids = f.read().splitlines()
self.assertEqual(sorted((df1_suffix, df2_suffix)),
sorted(invalids)) # sanity
# next time get hashes runs
with mock.patch('time.time', mock_time):
hashes = self.df_mgr.get_hashes(
self.existing_device, '0', [], POLICIES[0])
self.assertEqual(hashes, {})
# ... suffixes will get cleanup
self.assertFalse(os.path.exists(os.path.join(
self.testdir, self.existing_device, 'objects', '0',
df1_suffix)))
self.assertFalse(os.path.exists(os.path.join(
self.testdir, self.existing_device, 'objects', '0',
df2_suffix)))
# but really it's not diskfile's jobs to decide if a partition belongs
# on a node or not
self.assertTrue(os.path.isdir(os.path.join(
self.testdir, self.existing_device, 'objects', '0')))
def test_focused_yield_hashes_does_not_clean_up(self):
the_time = [1525354555.657585]
def mock_time():
return the_time[0]
with mock.patch('time.time', mock_time):
df = self.df_mgr.get_diskfile(
self.existing_device, 0, 'a', 'c', 'o', POLICIES[0])
df.delete(Timestamp(the_time[0]))
df_hash = utils.hash_path('a', 'c', 'o')
df_suffix = df_hash[-3:]
# sanity check
self.assertTrue(os.path.exists(os.path.join(
self.testdir, self.existing_device, 'objects', '0',
df_suffix, df_hash,
"1525354555.65758.ts")))
# Expire the tombstone
the_time[0] += 2 * self.df_mgr.reclaim_age
hashes = list(self.df_mgr.yield_hashes(
self.existing_device, '0', POLICIES[0],
suffixes=[df_suffix]))
self.assertEqual(hashes, [])
# The partition dir is still there. Since we didn't visit all the
# suffix dirs, we didn't learn whether or not the partition dir was
# empty.
self.assertTrue(os.path.exists(os.path.join(
self.testdir, self.existing_device, 'objects', '0')))
def test_yield_hashes_empty_suffixes(self):
def _listdir(path):
return []
with mock.patch('os.listdir', _listdir):
self.assertEqual(
list(self.df_mgr.yield_hashes(self.existing_device, '9',
POLICIES[0],
suffixes=['456'])), [])
def _check_yield_hashes(self, policy, suffix_map, expected, **kwargs):
device = self.existing_device
part = '9'
part_path = os.path.join(
self.testdir, device, diskfile.get_data_dir(policy), part)
def _listdir(path):
if path == part_path:
return suffix_map.keys()
for suff, hash_map in suffix_map.items():
if path == os.path.join(part_path, suff):
return hash_map.keys()
for hash_, files in hash_map.items():
if path == os.path.join(part_path, suff, hash_):
return files
self.fail('Unexpected listdir of %r' % path)
expected_items = [
(hash_, timestamps)
for hash_, timestamps in expected.items()]
with mock.patch('os.listdir', _listdir), \
mock.patch('os.unlink'), \
mock.patch('os.rmdir'):
df_mgr = self.df_router[policy]
hash_items = list(df_mgr.yield_hashes(
device, part, policy, **kwargs))
expected = sorted(expected_items)
actual = sorted(hash_items)
# default list diff easiest to debug
self.assertEqual(expected, actual)
def test_yield_hashes_tombstones(self):
ts_iter = (Timestamp(t) for t in itertools.count(int(time())))
ts1 = next(ts_iter)
ts2 = next(ts_iter)
ts3 = next(ts_iter)
suffix_map = {
'27e': {
'1111111111111111111111111111127e': [
ts1.internal + '.ts'],
'2222222222222222222222222222227e': [
ts2.internal + '.ts'],
},
'd41': {
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaad41': []
},
'd98': {},
'00b': {
'3333333333333333333333333333300b': [
ts1.internal + '.ts',
ts2.internal + '.ts',
ts3.internal + '.ts',
]
},
'204': {
'bbbbbbbbbbbbbbbbbbbbbbbbbbbbb204': [
ts3.internal + '.ts',
]
}
}
expected = {
'1111111111111111111111111111127e': {'ts_data': ts1.internal},
'2222222222222222222222222222227e': {'ts_data': ts2.internal},
'3333333333333333333333333333300b': {'ts_data': ts3.internal},
}
for policy in POLICIES:
self._check_yield_hashes(policy, suffix_map, expected,
suffixes=['27e', '00b'])
@patch_policies
class TestDiskFileManager(DiskFileManagerMixin, BaseTestCase):
mgr_cls = diskfile.DiskFileManager
def test_get_ondisk_files_with_repl_policy(self):
# Each scenario specifies a list of (filename, extension) tuples. If
# extension is set then that filename should be returned by the method
# under test for that extension type.
scenarios = [[('0000000007.00000.data', '.data')],
[('0000000007.00000.ts', '.ts')],
# older tombstone is ignored
[('0000000007.00000.ts', '.ts'),
('0000000006.00000.ts', False)],
# older data is ignored
[('0000000007.00000.data', '.data'),
('0000000006.00000.data', False),
('0000000004.00000.ts', False)],
# newest meta trumps older meta
[('0000000009.00000.meta', '.meta'),
('0000000008.00000.meta', False),
('0000000007.00000.data', '.data'),
('0000000004.00000.ts', False)],
# meta older than data is ignored
[('0000000007.00000.data', '.data'),
('0000000006.00000.meta', False),
('0000000004.00000.ts', False)],
# meta without data is ignored
[('0000000007.00000.meta', False, True),
('0000000006.00000.ts', '.ts'),
('0000000004.00000.data', False)],
# tombstone trumps meta and data at same timestamp
[('0000000006.00000.meta', False),
('0000000006.00000.ts', '.ts'),
('0000000006.00000.data', False)],
]
self._test_get_ondisk_files(scenarios, POLICIES[0], None)
self._test_cleanup_ondisk_files(scenarios, POLICIES[0])
self._test_yield_hashes_cleanup(scenarios, POLICIES[0])
def test_get_ondisk_files_with_stray_meta(self):
# get_ondisk_files ignores a stray .meta file
class_under_test = self._get_diskfile(POLICIES[0])
files = ['0000000007.00000.meta']
with mock.patch('swift.obj.diskfile.os.listdir', lambda *args: files):
self.assertRaises(DiskFileNotExist, class_under_test.open)
def test_verify_ondisk_files(self):
# ._verify_ondisk_files should only return False if get_ondisk_files
# has produced a bad set of files due to a bug, so to test it we need
# to probe it directly.
mgr = self.df_router[POLICIES.default]
ok_scenarios = (
{'ts_file': None, 'data_file': None, 'meta_file': None},
{'ts_file': None, 'data_file': 'a_file', 'meta_file': None},
{'ts_file': None, 'data_file': 'a_file', 'meta_file': 'a_file'},
{'ts_file': 'a_file', 'data_file': None, 'meta_file': None},
)
for scenario in ok_scenarios:
self.assertTrue(mgr._verify_ondisk_files(scenario),
'Unexpected result for scenario %s' % scenario)
# construct every possible invalid combination of results
vals = (None, 'a_file')
for ts_file, data_file, meta_file in [
(a, b, c) for a in vals for b in vals for c in vals]:
scenario = {
'ts_file': ts_file,
'data_file': data_file,
'meta_file': meta_file}
if scenario in ok_scenarios:
continue
self.assertFalse(mgr._verify_ondisk_files(scenario),
'Unexpected result for scenario %s' % scenario)
def test_parse_on_disk_filename(self):
mgr = self.df_router[POLICIES.default]
for ts in (Timestamp('1234567890.00001'),
Timestamp('1234567890.00001', offset=17)):
for ext in ('.meta', '.data', '.ts'):
fname = '%s%s' % (ts.internal, ext)
info = mgr.parse_on_disk_filename(fname, POLICIES.default)
self.assertEqual(ts, info['timestamp'])
self.assertEqual(ext, info['ext'])
def test_parse_on_disk_filename_errors(self):
mgr = self.df_router[POLICIES.default]
with self.assertRaises(DiskFileError) as cm:
mgr.parse_on_disk_filename('junk', POLICIES.default)
self.assertEqual("Invalid Timestamp value in filename 'junk'",
str(cm.exception))
def test_cleanup_ondisk_files_reclaim_with_data_files(self):
# Each scenario specifies a list of (filename, extension, [survives])
# tuples. If extension is set or 'survives' is True, the filename
# should still be in the dir after cleanup.
much_older = Timestamp(time() - 2000).internal
older = Timestamp(time() - 1001).internal
newer = Timestamp(time() - 900).internal
scenarios = [
# .data files are not reclaimed, ever
[('%s.data' % older, '.data', True)],
[('%s.data' % newer, '.data', True)],
# ... and we could have a mixture of fresh and stale .data
[('%s.data' % newer, '.data', True),
('%s.data' % older, False, False)],
# tombstone reclaimed despite newer data
[('%s.data' % newer, '.data', True),
('%s.data' % older, False, False),
('%s.ts' % much_older, '.ts', False)],
# .meta not reclaimed if there is a .data file
[('%s.meta' % older, '.meta'),
('%s.data' % much_older, '.data')]]
self._test_cleanup_ondisk_files(scenarios, POLICIES.default,
reclaim_age=1000)
def test_yield_hashes(self):
old_ts = '1383180000.12345'
fresh_ts = Timestamp(time() - 10).internal
fresher_ts = Timestamp(time() - 1).internal
suffix_map = {
'abc': {
'9373a92d072897b136b3fc06595b4abc': [
fresh_ts + '.ts'],
},
'456': {
'9373a92d072897b136b3fc06595b0456': [
old_ts + '.data'],
'9373a92d072897b136b3fc06595b7456': [
fresh_ts + '.ts',
fresher_ts + '.data'],
},
'def': {},
}
expected = {
'9373a92d072897b136b3fc06595b4abc': {'ts_data': fresh_ts},
'9373a92d072897b136b3fc06595b0456': {'ts_data': old_ts},
'9373a92d072897b136b3fc06595b7456': {'ts_data': fresher_ts},
}
self._check_yield_hashes(POLICIES.default, suffix_map, expected)
def test_yield_hashes_yields_meta_timestamp(self):
ts_iter = (Timestamp(t) for t in itertools.count(int(time())))
ts1 = next(ts_iter)
ts2 = next(ts_iter)
ts3 = next(ts_iter)
suffix_map = {
'abc': {
# only tombstone is yield/sync -able
'9333a92d072897b136b3fc06595b4abc': [
ts1.internal + '.ts',
ts2.internal + '.meta'],
# dangling .meta is not yielded because it cannot be sync'd
'9222a92d072897b136b3fc06595b4abc': [
ts3.internal + '.meta'],
},
'456': {
# only latest metadata timestamp
'9444a92d072897b136b3fc06595b0456': [
ts1.internal + '.data',
ts2.internal + '.meta',
ts3.internal + '.meta'],
# exemplary datadir with .meta
'9555a92d072897b136b3fc06595b7456': [
ts1.internal + '.data',
ts2.internal + '.meta'],
},
}
expected = {
'9333a92d072897b136b3fc06595b4abc':
{'ts_data': ts1},
'9444a92d072897b136b3fc06595b0456':
{'ts_data': ts1, 'ts_meta': ts3},
'9555a92d072897b136b3fc06595b7456':
{'ts_data': ts1, 'ts_meta': ts2},
}
self._check_yield_hashes(POLICIES.default, suffix_map, expected)
def test_yield_hashes_yields_content_type_timestamp(self):
hash_ = '9373a92d072897b136b3fc06595b4abc'
ts_iter = make_timestamp_iter()
ts0, ts1, ts2, ts3, ts4 = (next(ts_iter) for _ in range(5))
data_file = ts1.internal + '.data'
# no content-type delta
meta_file = ts2.internal + '.meta'
suffix_map = {'abc': {hash_: [data_file, meta_file]}}
expected = {hash_: {'ts_data': ts1,
'ts_meta': ts2}}
self._check_yield_hashes(POLICIES.default, suffix_map, expected)
# non-zero content-type delta
delta = ts3.raw - ts2.raw
meta_file = '%s-%x.meta' % (ts3.internal, delta)
suffix_map = {'abc': {hash_: [data_file, meta_file]}}
expected = {hash_: {'ts_data': ts1,
'ts_meta': ts3,
'ts_ctype': ts2}}
self._check_yield_hashes(POLICIES.default, suffix_map, expected)
# zero content-type delta
meta_file = '%s+0.meta' % ts3.internal
suffix_map = {'abc': {hash_: [data_file, meta_file]}}
expected = {hash_: {'ts_data': ts1,
'ts_meta': ts3,
'ts_ctype': ts3}}
self._check_yield_hashes(POLICIES.default, suffix_map, expected)
# content-type in second meta file
delta = ts3.raw - ts2.raw
meta_file1 = '%s-%x.meta' % (ts3.internal, delta)
meta_file2 = '%s.meta' % ts4.internal
suffix_map = {'abc': {hash_: [data_file, meta_file1, meta_file2]}}
expected = {hash_: {'ts_data': ts1,
'ts_meta': ts4,
'ts_ctype': ts2}}
self._check_yield_hashes(POLICIES.default, suffix_map, expected)
# obsolete content-type in second meta file, older than data file
delta = ts3.raw - ts0.raw
meta_file1 = '%s-%x.meta' % (ts3.internal, delta)
meta_file2 = '%s.meta' % ts4.internal
suffix_map = {'abc': {hash_: [data_file, meta_file1, meta_file2]}}
expected = {hash_: {'ts_data': ts1,
'ts_meta': ts4}}
self._check_yield_hashes(POLICIES.default, suffix_map, expected)
# obsolete content-type in second meta file, same time as data file
delta = ts3.raw - ts1.raw
meta_file1 = '%s-%x.meta' % (ts3.internal, delta)
meta_file2 = '%s.meta' % ts4.internal
suffix_map = {'abc': {hash_: [data_file, meta_file1, meta_file2]}}
expected = {hash_: {'ts_data': ts1,
'ts_meta': ts4}}
self._check_yield_hashes(POLICIES.default, suffix_map, expected)
def test_yield_hashes_suffix_filter(self):
# test again with limited suffixes
old_ts = '1383180000.12345'
fresh_ts = Timestamp(time() - 10).internal
fresher_ts = Timestamp(time() - 1).internal
suffix_map = {
'abc': {
'9373a92d072897b136b3fc06595b4abc': [
fresh_ts + '.ts'],
},
'456': {
'9373a92d072897b136b3fc06595b0456': [
old_ts + '.data'],
'9373a92d072897b136b3fc06595b7456': [
fresh_ts + '.ts',
fresher_ts + '.data'],
},
'def': {},
}
expected = {
'9373a92d072897b136b3fc06595b0456': {'ts_data': old_ts},
'9373a92d072897b136b3fc06595b7456': {'ts_data': fresher_ts},
}
self._check_yield_hashes(POLICIES.default, suffix_map, expected,
suffixes=['456'])
def test_yield_hashes_fails_with_bad_ondisk_filesets(self):
ts_iter = (Timestamp(t) for t in itertools.count(int(time())))
ts1 = next(ts_iter)
suffix_map = {
'456': {
'9373a92d072897b136b3fc06595b0456': [
ts1.internal + '.data'],
'9373a92d072897b136b3fc06595ba456': [
ts1.internal + '.meta'],
},
}
expected = {
'9373a92d072897b136b3fc06595b0456': {'ts_data': ts1},
}
try:
self._check_yield_hashes(POLICIES.default, suffix_map, expected,
frag_index=2)
self.fail('Expected AssertionError')
except AssertionError:
pass
def test_check_policy(self):
mock_policy = mock.MagicMock()
mock_policy.policy_type = REPL_POLICY
# sanity, DiskFileManager is ok with REPL_POLICY
diskfile.DiskFileManager.check_policy(mock_policy)
# DiskFileManager raises ValueError with EC_POLICY
mock_policy.policy_type = EC_POLICY
with self.assertRaises(ValueError) as cm:
diskfile.DiskFileManager.check_policy(mock_policy)
self.assertEqual('Invalid policy_type: %s' % EC_POLICY,
str(cm.exception))
@patch_policies(with_ec_default=True)
class TestECDiskFileManager(DiskFileManagerMixin, BaseTestCase):
mgr_cls = diskfile.ECDiskFileManager
def test_get_ondisk_files_with_ec_policy_and_legacy_durable(self):
# Each scenario specifies a list of (filename, extension, [survives])
# tuples. If extension is set then that filename should be returned by
# the method under test for that extension type. If the optional
# 'survives' is True, the filename should still be in the dir after
# cleanup.
scenarios = [
# highest frag index is chosen by default
[('0000000007.00000.durable', '.durable'),
('0000000007.00000#1.data', '.data'),
('0000000007.00000#0.data', False, True)],
# data older than durable is ignored
[('0000000007.00000.durable', '.durable'),
('0000000007.00000#1.data', '.data'),
('0000000006.00000#1.data', False),
('0000000004.00000.ts', False)],
# data older than durable ignored, even if its only data
[('0000000007.00000.durable', False, False),
('0000000006.00000#1.data', False),
('0000000004.00000.ts', False)],
# newer meta trumps older meta
[('0000000009.00000.meta', '.meta'),
('0000000008.00000.meta', False),
('0000000007.00000.durable', '.durable'),
('0000000007.00000#14.data', '.data'),
('0000000004.00000.ts', False)],
# older meta is ignored
[('0000000007.00000.durable', '.durable'),
('0000000007.00000#14.data', '.data'),
('0000000006.00000.meta', False),
('0000000004.00000.ts', False)],
# tombstone trumps meta, data, durable at older timestamp
[('0000000006.00000.ts', '.ts'),
('0000000005.00000.meta', False),
('0000000004.00000.durable', False),
('0000000004.00000#0.data', False)],
# tombstone trumps meta, data, durable at same timestamp
[('0000000006.00000.meta', False),
('0000000006.00000.ts', '.ts'),
('0000000006.00000.durable', False),
('0000000006.00000#0.data', False)]
]
# these scenarios have same outcome regardless of whether any
# fragment preferences are specified
self._test_get_ondisk_files(scenarios, POLICIES.default,
frag_index=None)
self._test_get_ondisk_files(scenarios, POLICIES.default,
frag_index=None, frag_prefs=[])
self._test_cleanup_ondisk_files(scenarios, POLICIES.default)
self._test_yield_hashes_cleanup(scenarios, POLICIES.default)
# next scenarios have different outcomes dependent on whether a
# frag_prefs parameter is passed to diskfile constructor or not
scenarios = [
# data with no durable is ignored
[('0000000007.00000#0.data', False, True)],
# data newer than tombstone with no durable is ignored
[('0000000007.00000#0.data', False, True),
('0000000006.00000.ts', '.ts', True)],
# data newer than durable is ignored
[('0000000009.00000#2.data', False, True),
('0000000009.00000#1.data', False, True),
('0000000008.00000#3.data', False, True),
('0000000007.00000.durable', '.durable'),
('0000000007.00000#1.data', '.data'),
('0000000007.00000#0.data', False, True)],
# data newer than durable ignored, even if its only data
[('0000000008.00000#1.data', False, True),
('0000000007.00000.durable', False, False)],
# missing durable invalidates data, older meta deleted
[('0000000007.00000.meta', False, True),
('0000000006.00000#0.data', False, True),
('0000000005.00000.meta', False, False),
('0000000004.00000#1.data', False, True)]]
self._test_get_ondisk_files(scenarios, POLICIES.default,
frag_index=None)
self._test_cleanup_ondisk_files(scenarios, POLICIES.default)
scenarios = [
# data with no durable is chosen
[('0000000007.00000#0.data', '.data', True)],
# data newer than tombstone with no durable is chosen
[('0000000007.00000#0.data', '.data', True),
('0000000006.00000.ts', False, True)],
# data newer than durable is chosen, older data preserved
[('0000000009.00000#2.data', '.data', True),
('0000000009.00000#1.data', False, True),
('0000000008.00000#3.data', False, True),
('0000000007.00000.durable', False, True),
('0000000007.00000#1.data', False, True),
('0000000007.00000#0.data', False, True)],
# data newer than durable chosen when its only data
[('0000000008.00000#1.data', '.data', True),
('0000000007.00000.durable', False, False)],
# data plus meta chosen without durable, older meta deleted
[('0000000007.00000.meta', '.meta', True),
('0000000006.00000#0.data', '.data', True),
('0000000005.00000.meta', False, False),
('0000000004.00000#1.data', False, True)]]
self._test_get_ondisk_files(scenarios, POLICIES.default,
frag_index=None, frag_prefs=[])
self._test_cleanup_ondisk_files(scenarios, POLICIES.default)
def test_get_ondisk_files_with_ec_policy(self):
# Each scenario specifies a list of (filename, extension, [survives])
# tuples. If extension is set then that filename should be returned by
# the method under test for that extension type. If the optional
# 'survives' is True, the filename should still be in the dir after
# cleanup.
scenarios = [[('0000000007.00000.ts', '.ts')],
[('0000000007.00000.ts', '.ts'),
('0000000006.00000.ts', False)],
# highest frag index is chosen by default
[('0000000007.00000#1#d.data', '.data'),
('0000000007.00000#0.data', False, True)],
# data older than durable is ignored
[('0000000007.00000#1#d.data', '.data'),
('0000000006.00000#1.data', False),
('0000000004.00000.ts', False)],
# newer meta trumps older meta
[('0000000009.00000.meta', '.meta'),
('0000000008.00000.meta', False),
('0000000007.00000#14#d.data', '.data'),
('0000000004.00000.ts', False)],
# older meta is ignored
[('0000000007.00000#14#d.data', '.data'),
('0000000006.00000.meta', False),
('0000000004.00000.ts', False)],
# tombstone trumps meta and data at older timestamp
[('0000000006.00000.ts', '.ts'),
('0000000005.00000.meta', False),
('0000000004.00000#0#d.data', False)],
# tombstone trumps meta and data at same timestamp
[('0000000006.00000.meta', False),
('0000000006.00000.ts', '.ts'),
('0000000006.00000#0#d.data', False)],
]
# these scenarios have same outcome regardless of whether any
# fragment preferences are specified
self._test_get_ondisk_files(scenarios, POLICIES.default,
frag_index=None)
self._test_get_ondisk_files(scenarios, POLICIES.default,
frag_index=None, frag_prefs=[])
self._test_cleanup_ondisk_files(scenarios, POLICIES.default)
self._test_yield_hashes_cleanup(scenarios, POLICIES.default)
# next scenarios have different outcomes dependent on whether a
# frag_prefs parameter is passed to diskfile constructor or not
scenarios = [
# non-durable is ignored
[('0000000007.00000#0.data', False, True)],
# non-durable data newer than tombstone is ignored
[('0000000007.00000#0.data', False, True),
('0000000006.00000.ts', '.ts', True)],
# data newer than durable data is ignored
[('0000000009.00000#2.data', False, True),
('0000000009.00000#1.data', False, True),
('0000000008.00000#3.data', False, True),
('0000000007.00000#1#d.data', '.data'),
('0000000007.00000#0#d.data', False, True)],
# non-durable data ignored, older meta deleted
[('0000000007.00000.meta', False, True),
('0000000006.00000#0.data', False, True),
('0000000005.00000.meta', False, False),
('0000000004.00000#1.data', False, True)]]
self._test_get_ondisk_files(scenarios, POLICIES.default,
frag_index=None)
self._test_cleanup_ondisk_files(scenarios, POLICIES.default)
scenarios = [
# non-durable data is chosen
[('0000000007.00000#0.data', '.data', True)],
# non-durable data newer than tombstone is chosen
[('0000000007.00000#0.data', '.data', True),
('0000000006.00000.ts', False, True)],
# non-durable data newer than durable data is chosen, older data
# preserved
[('0000000009.00000#2.data', '.data', True),
('0000000009.00000#1.data', False, True),
('0000000008.00000#3.data', False, True),
('0000000007.00000#1#d.data', False, True),
('0000000007.00000#0#d.data', False, True)],
# non-durable data plus meta chosen, older meta deleted
[('0000000007.00000.meta', '.meta', True),
('0000000006.00000#0.data', '.data', True),
('0000000005.00000.meta', False, False),
('0000000004.00000#1.data', False, True)]]
self._test_get_ondisk_files(scenarios, POLICIES.default,
frag_index=None, frag_prefs=[])
self._test_cleanup_ondisk_files(scenarios, POLICIES.default)
def test_get_ondisk_files_with_ec_policy_and_frag_index_legacy(self):
# Each scenario specifies a list of (filename, extension, [survives])
# tuples. If extension is set then that filename should be returned by
# the method under test for that extension type.
scenarios = [[('0000000007.00000#2.data', False, True),
('0000000007.00000#1.data', '.data'),
('0000000007.00000#0.data', False, True),
('0000000007.00000.durable', '.durable')],
# specific frag newer than durable is ignored
[('0000000007.00000#2.data', False, True),
('0000000007.00000#1.data', False, True),
('0000000007.00000#0.data', False, True),
('0000000006.00000.durable', False)],
# specific frag older than durable is ignored
[('0000000007.00000#2.data', False),
('0000000007.00000#1.data', False),
('0000000007.00000#0.data', False),
('0000000008.00000.durable', False)],
# specific frag older than newest durable is ignored
# even if is also has a durable
[('0000000007.00000#2.data', False),
('0000000007.00000#1.data', False),
('0000000007.00000.durable', False),
('0000000008.00000#0.data', False, True),
('0000000008.00000.durable', '.durable')],
# meta included when frag index is specified
[('0000000009.00000.meta', '.meta'),
('0000000007.00000#2.data', False, True),
('0000000007.00000#1.data', '.data'),
('0000000007.00000#0.data', False, True),
('0000000007.00000.durable', '.durable')],
# specific frag older than tombstone is ignored
[('0000000009.00000.ts', '.ts'),
('0000000007.00000#2.data', False),
('0000000007.00000#1.data', False),
('0000000007.00000#0.data', False),
('0000000007.00000.durable', False)],
# no data file returned if specific frag index missing
[('0000000007.00000#2.data', False, True),
('0000000007.00000#14.data', False, True),
('0000000007.00000#0.data', False, True),
('0000000007.00000.durable', '.durable')],
# meta ignored if specific frag index missing
[('0000000008.00000.meta', False, True),
('0000000007.00000#14.data', False, True),
('0000000007.00000#0.data', False, True),
('0000000007.00000.durable', '.durable')],
# meta ignored if no data files
# Note: this is anomalous, because we are specifying a
# frag_index, get_ondisk_files will tolerate .meta with
# no .data
[('0000000088.00000.meta', False, True),
('0000000077.00000.durable', False, False)]
]
self._test_get_ondisk_files(scenarios, POLICIES.default, frag_index=1)
self._test_cleanup_ondisk_files(scenarios, POLICIES.default)
# scenarios for empty frag_prefs, meaning durable not required
scenarios = [
# specific frag newer than durable is chosen
[('0000000007.00000#2.data', False, True),
('0000000007.00000#1.data', '.data', True),
('0000000007.00000#0.data', False, True),
('0000000006.00000.durable', False, False)],
]
self._test_get_ondisk_files(scenarios, POLICIES.default, frag_index=1,
frag_prefs=[])
self._test_cleanup_ondisk_files(scenarios, POLICIES.default)
def test_get_ondisk_files_with_ec_policy_and_frag_index(self):
# Each scenario specifies a list of (filename, extension, [survives])
# tuples. If extension is set then that filename should be returned by
# the method under test for that extension type.
scenarios = [[('0000000007.00000#2#d.data', False, True),
('0000000007.00000#1#d.data', '.data'),
('0000000007.00000#0#d.data', False, True)],
# specific frag index 1 is returned as long as one durable
[('0000000007.00000#2.data', False, True),
('0000000007.00000#1.data', '.data', True),
('0000000007.00000#0#d.data', False, True)],
# specific frag newer than durable data is ignored
[('0000000007.00000#2.data', False, True),
('0000000007.00000#1.data', False, True),
('0000000007.00000#0.data', False, True),
('0000000006.00000#0#d.data', False, True)],
# specific frag older than durable data is ignored
[('0000000007.00000#2.data', False),
('0000000007.00000#1.data', False),
('0000000007.00000#0.data', False),
('0000000008.00000#0#d.data', False, True)],
# specific frag older than newest durable data is ignored
# even if is durable
[('0000000007.00000#2#d.data', False),
('0000000007.00000#1#d.data', False),
('0000000008.00000#0#d.data', False, True)],
# meta included when frag index is specified
[('0000000009.00000.meta', '.meta'),
('0000000007.00000#2#d.data', False, True),
('0000000007.00000#1#d.data', '.data'),
('0000000007.00000#0#d.data', False, True)],
# specific frag older than tombstone is ignored
[('0000000009.00000.ts', '.ts'),
('0000000007.00000#2#d.data', False),
('0000000007.00000#1#d.data', False),
('0000000007.00000#0#d.data', False)],
# no data file returned if specific frag index missing
[('0000000007.00000#2#d.data', False, True),
('0000000007.00000#14#d.data', False, True),
('0000000007.00000#0#d.data', False, True)],
# meta ignored if specific frag index missing
[('0000000008.00000.meta', False, True),
('0000000007.00000#14#d.data', False, True),
('0000000007.00000#0#d.data', False, True)],
# meta ignored if no data files
# Note: this is anomalous, because we are specifying a
# frag_index, get_ondisk_files will tolerate .meta with
# no .data
[('0000000088.00000.meta', False, True)]
]
self._test_get_ondisk_files(scenarios, POLICIES.default, frag_index=1)
self._test_cleanup_ondisk_files(scenarios, POLICIES.default)
# scenarios for empty frag_prefs, meaning durable not required
scenarios = [
# specific frag newer than durable is chosen
[('0000000007.00000#2.data', False, True),
('0000000007.00000#1.data', '.data', True),
('0000000007.00000#0.data', False, True)],
]
self._test_get_ondisk_files(scenarios, POLICIES.default, frag_index=1,
frag_prefs=[])
self._test_cleanup_ondisk_files(scenarios, POLICIES.default)
def test_get_ondisk_files_with_ec_policy_some_legacy(self):
# Test mixture of legacy durable files and durable data files that
# might somehow end up in the same object dir.
# Each scenario specifies a list of (filename, extension, [survives])
# tuples. If extension is set then that filename should be returned by
# the method under test for that extension type. If the optional
# 'survives' is True, the filename should still be in the dir after
# cleanup.
scenarios = [
# .durable at same timestamp is ok
[('0000000007.00000#1#d.data', '.data', True),
('0000000007.00000#0#d.data', False, True),
('0000000007.00000.durable', False, True)],
# .durable at same timestamp is ok with non durable wanted frag
[('0000000007.00000#1.data', '.data', True),
('0000000007.00000#0#d.data', False, True),
('0000000007.00000.durable', False, True)],
# older .durable file is cleaned up
[('0000000007.00000#1#d.data', '.data', True),
('0000000007.00000#0#d.data', False, True),
('0000000006.00000.durable', False, False)],
# older .durable does not interfere with non durable wanted frag
[('0000000007.00000#1.data', '.data', True),
('0000000007.00000#0#d.data', False, True),
('0000000006.00000.durable', False, False)],
# ...even if it has accompanying .data file
[('0000000007.00000#1.data', '.data', True),
('0000000007.00000#0#d.data', False, True),
('0000000006.00000#0.data', False, False),
('0000000006.00000.durable', False, False)],
# newer .durable file trumps older durable-data
[('0000000007.00000#1#d.data', False, False),
('0000000007.00000#0#d.data', False, False),
('0000000008.00000#1.data', '.data', True),
('0000000008.00000.durable', False, True)],
# newer .durable file with no .data trumps older durable-data
[('0000000007.00000#1#d.data', False, False),
('0000000007.00000#0#d.data', False, False),
('0000000008.00000.durable', False, False)],
]
self._test_get_ondisk_files(scenarios, POLICIES.default, frag_index=1)
self._test_cleanup_ondisk_files(scenarios, POLICIES.default)
self._test_yield_hashes_cleanup(scenarios, POLICIES.default)
def test_cleanup_ondisk_files_reclaim_with_data_files_legacy_durable(self):
# Each scenario specifies a list of (filename, extension, [survives])
# tuples. If extension is set or 'survives' is True, the filename
# should still be in the dir after cleanup.
much_older = Timestamp(time() - 2000).internal
older = Timestamp(time() - 1001).internal
newer = Timestamp(time() - 900).internal
scenarios = [
# isolated legacy .durable is cleaned up immediately
[('%s.durable' % newer, False, False)],
# ...even when other older files are in dir
[('%s.durable' % older, False, False),
('%s.ts' % much_older, False, False)],
# isolated .data files are cleaned up when stale
# ...even when there is an older legacy durable
[('%s#2.data' % older, False, False),
('%s#4.data' % older, False, False),
('%s#2.data' % much_older, '.data', True),
('%s#4.data' % much_older, False, True),
('%s.durable' % much_older, '.durable', True)],
# tombstone reclaimed despite much older legacy durable
[('%s.ts' % older, '.ts', False),
('%s.durable' % much_older, False, False)],
# .meta not reclaimed if there is legacy durable data
[('%s.meta' % older, '.meta', True),
('%s#4.data' % much_older, False, True),
('%s.durable' % much_older, '.durable', True)],
# stale .meta reclaimed along with stale legacy .durable
[('%s.meta' % older, False, False),
('%s.durable' % much_older, False, False)]]
self._test_cleanup_ondisk_files(scenarios, POLICIES.default,
reclaim_age=1000, commit_window=0)
def test_cleanup_ondisk_files_reclaim_with_data_files(self):
# Each scenario specifies a list of (filename, extension, [survives])
# tuples. If extension is set or 'survives' is True, the filename
# should still be in the dir after cleanup.
much_older = Timestamp(time() - 2000).internal
older = Timestamp(time() - 1001).internal
newer = Timestamp(time() - 900).internal
scenarios = [
# isolated .data files are cleaned up when stale
[('%s#2.data' % older, False, False),
('%s#4.data' % older, False, False)],
# ...even when there is an older durable fileset
[('%s#2.data' % older, False, False),
('%s#4.data' % older, False, False),
('%s#2#d.data' % much_older, '.data', True),
('%s#4#d.data' % much_older, False, True)],
# ... but preserved if still fresh
[('%s#2.data' % newer, False, True),
('%s#4.data' % newer, False, True)],
# ... and we could have a mixture of fresh and stale .data
[('%s#2.data' % newer, False, True),
('%s#4.data' % older, False, False)],
# tombstone reclaimed despite newer non-durable data
[('%s#2.data' % newer, False, True),
('%s#4.data' % older, False, False),
('%s.ts' % much_older, '.ts', False)],
# tombstone reclaimed despite much older durable
[('%s.ts' % older, '.ts', False),
('%s#4#d.data' % much_older, False, False)],
# .meta not reclaimed if there is durable data
[('%s.meta' % older, '.meta', True),
('%s#4#d.data' % much_older, False, True)],
# stale .meta reclaimed along with stale non-durable .data
[('%s.meta' % older, False, False),
('%s#4.data' % much_older, False, False)]]
self._test_cleanup_ondisk_files(scenarios, POLICIES.default,
reclaim_age=1000, commit_window=0)
def test_cleanup_ondisk_files_commit_window(self):
# verify that non-durable files are not reclaimed regardless of
# timestamp if written to disk within commit_window
much_older = Timestamp(time() - 2000).internal
older = Timestamp(time() - 1001).internal
newer = Timestamp(time() - 900).internal
scenarios = [
# recently written nondurables not cleaned up
[('%s#1.data' % older, True),
('%s#2.data' % newer, True),
('%s.meta' % much_older, False),
('%s.ts' % much_older, False)]]
self._test_cleanup_ondisk_files(scenarios, POLICIES.default,
reclaim_age=1000, commit_window=60)
# ... but if commit_window is reduced then recently written files are
# cleaned up
scenarios = [
# older *timestamps* cleaned up
[('%s#1.data' % older, False),
('%s#2.data' % newer, True),
('%s.meta' % much_older, False),
('%s.ts' % much_older, False)]]
self._test_cleanup_ondisk_files(scenarios, POLICIES.default,
reclaim_age=1000, commit_window=0)
def test_get_ondisk_files_with_stray_meta(self):
# get_ondisk_files ignores a stray .meta file
class_under_test = self._get_diskfile(POLICIES.default)
@contextmanager
def create_files(df, files):
os.makedirs(df._datadir)
for fname in files:
fpath = os.path.join(df._datadir, fname)
with open(fpath, 'w') as f:
diskfile.write_metadata(f, {'name': df._name,
'Content-Length': 0})
yield
rmtree(df._datadir, ignore_errors=True)
# sanity
good_files = [
'0000000006.00000.meta',
'0000000006.00000#1#d.data'
]
with create_files(class_under_test, good_files):
class_under_test.open()
scenarios = [['0000000007.00000.meta'],
['0000000007.00000.meta',
'0000000006.00000.durable'], # legacy durable file
['0000000007.00000.meta',
'0000000006.00000#1.data'],
['0000000007.00000.meta',
'0000000006.00000.durable', # legacy durable file
'0000000005.00000#1.data']
]
for files in scenarios:
with create_files(class_under_test, files):
try:
class_under_test.open()
except DiskFileNotExist:
continue
self.fail('expected DiskFileNotExist opening %s with %r' % (
class_under_test.__class__.__name__, files))
# Simulate another process deleting the data after we list contents
# but before we actually open them
orig_listdir = os.listdir
def deleting_listdir(d):
result = orig_listdir(d)
for f in result:
os.unlink(os.path.join(d, f))
return result
with create_files(class_under_test, good_files), \
mock.patch('swift.obj.diskfile.os.listdir',
side_effect=deleting_listdir), \
self.assertRaises(DiskFileStateChanged):
class_under_test.open()
def test_verify_ondisk_files(self):
# _verify_ondisk_files should only return False if get_ondisk_files
# has produced a bad set of files due to a bug, so to test it we need
# to probe it directly.
mgr = self.df_router[POLICIES.default]
ok_scenarios = (
{'ts_file': None, 'data_file': None, 'meta_file': None,
'durable_frag_set': None},
{'ts_file': None, 'data_file': 'a_file', 'meta_file': None,
'durable_frag_set': ['a_file']},
{'ts_file': None, 'data_file': 'a_file', 'meta_file': 'a_file',
'durable_frag_set': ['a_file']},
{'ts_file': 'a_file', 'data_file': None, 'meta_file': None,
'durable_frag_set': None},
)
for scenario in ok_scenarios:
self.assertTrue(mgr._verify_ondisk_files(scenario),
'Unexpected result for scenario %s' % scenario)
# construct every possible invalid combination of results
vals = (None, 'a_file')
for ts_file, data_file, meta_file, durable_frag in [
(a, b, c, d)
for a in vals for b in vals for c in vals for d in vals]:
scenario = {
'ts_file': ts_file,
'data_file': data_file,
'meta_file': meta_file,
'durable_frag_set': [durable_frag] if durable_frag else None}
if scenario in ok_scenarios:
continue
self.assertFalse(mgr._verify_ondisk_files(scenario),
'Unexpected result for scenario %s' % scenario)
def test_parse_on_disk_filename(self):
mgr = self.df_router[POLICIES.default]
for ts in (Timestamp('1234567890.00001'),
Timestamp('1234567890.00001', offset=17)):
# non-durable data file
for frag in (0, 2, 13):
fname = '%s#%s.data' % (ts.internal, frag)
info = mgr.parse_on_disk_filename(fname, POLICIES.default)
self.assertEqual(ts, info['timestamp'])
self.assertEqual('.data', info['ext'])
self.assertEqual(frag, info['frag_index'])
self.assertIs(False, info['durable'])
self.assertEqual(mgr.make_on_disk_filename(**info), fname)
# durable data file
for frag in (0, 2, 13):
fname = '%s#%s#d.data' % (ts.internal, frag)
info = mgr.parse_on_disk_filename(fname, POLICIES.default)
self.assertEqual(ts, info['timestamp'])
self.assertEqual('.data', info['ext'])
self.assertEqual(frag, info['frag_index'])
self.assertIs(True, info['durable'])
self.assertEqual(mgr.make_on_disk_filename(**info), fname)
# data file with unexpected suffix marker, not an error in case
# alternative marker suffixes added in future
for frag in (0, 2, 13):
fname = '%s#%s#junk.data' % (ts.internal, frag)
info = mgr.parse_on_disk_filename(fname, POLICIES.default)
self.assertEqual(ts, info['timestamp'])
self.assertEqual('.data', info['ext'])
self.assertEqual(frag, info['frag_index'])
self.assertIs(False, info['durable'])
expected = '%s#%s.data' % (ts.internal, frag)
self.assertEqual(mgr.make_on_disk_filename(**info), expected)
for ext in ('.meta', '.durable', '.ts'):
fname = '%s%s' % (ts.internal, ext)
info = mgr.parse_on_disk_filename(fname, POLICIES.default)
self.assertEqual(ts, info['timestamp'])
self.assertEqual(ext, info['ext'])
self.assertIsNone(info['frag_index'])
self.assertEqual(mgr.make_on_disk_filename(**info), fname)
def test_parse_on_disk_filename_errors(self):
mgr = self.df_router[POLICIES.default]
for ts in (Timestamp('1234567890.00001'),
Timestamp('1234567890.00001', offset=17)):
fname = '%s.data' % ts.internal
with self.assertRaises(DiskFileError) as cm:
mgr.parse_on_disk_filename(fname, POLICIES.default)
self.assertTrue(str(cm.exception).startswith("Bad fragment index"))
expected = {
'': 'bad',
'foo': 'bad',
'1.314': 'bad',
1.314: 'bad',
-2: 'negative',
'-2': 'negative',
None: 'bad',
'None': 'bad',
}
# non-durable data file
for frag, msg in expected.items():
fname = '%s#%s.data' % (ts.internal, frag)
with self.assertRaises(DiskFileError) as cm:
mgr.parse_on_disk_filename(fname, POLICIES.default)
self.assertIn(msg, str(cm.exception).lower())
# durable data file
for frag, msg in expected.items():
fname = '%s#%s#d.data' % (ts.internal, frag)
with self.assertRaises(DiskFileError) as cm:
mgr.parse_on_disk_filename(fname, POLICIES.default)
self.assertIn(msg, str(cm.exception).lower())
with self.assertRaises(DiskFileError) as cm:
mgr.parse_on_disk_filename('junk', POLICIES.default)
self.assertEqual("Invalid Timestamp value in filename 'junk'",
str(cm.exception))
def test_make_on_disk_filename(self):
mgr = self.df_router[POLICIES.default]
for ts in (Timestamp('1234567890.00001'),
Timestamp('1234567890.00001', offset=17)):
for frag in (0, '0', 2, '2', 13, '13'):
for durable in (True, False):
expected = _make_datafilename(
ts, POLICIES.default, frag_index=frag, durable=durable)
actual = mgr.make_on_disk_filename(
ts, '.data', frag_index=frag, durable=durable)
self.assertEqual(expected, actual)
parsed = mgr.parse_on_disk_filename(
actual, POLICIES.default)
self.assertEqual(parsed, {
'timestamp': ts,
'frag_index': int(frag),
'ext': '.data',
'ctype_timestamp': None,
'durable': durable
})
# these functions are inverse
self.assertEqual(
mgr.make_on_disk_filename(**parsed),
expected)
for ext in ('.meta', '.durable', '.ts'):
expected = '%s%s' % (ts.internal, ext)
# frag index should not be required
actual = mgr.make_on_disk_filename(ts, ext)
self.assertEqual(expected, actual)
# frag index should be ignored
actual = mgr.make_on_disk_filename(
ts, ext, frag_index=frag)
self.assertEqual(expected, actual)
parsed = mgr.parse_on_disk_filename(
actual, POLICIES.default)
self.assertEqual(parsed, {
'timestamp': ts,
'frag_index': None,
'ext': ext,
'ctype_timestamp': None
})
# these functions are inverse
self.assertEqual(
mgr.make_on_disk_filename(**parsed),
expected)
actual = mgr.make_on_disk_filename(ts)
self.assertEqual(ts, actual)
def test_make_on_disk_filename_with_bad_frag_index(self):
mgr = self.df_router[POLICIES.default]
ts = Timestamp('1234567890.00001')
with self.assertRaises(DiskFileError):
# .data requires a frag_index kwarg
mgr.make_on_disk_filename(ts, '.data')
for frag in (None, 'foo', '1.314', 1.314, -2, '-2'):
with self.assertRaises(DiskFileError):
mgr.make_on_disk_filename(ts, '.data', frag_index=frag)
for ext in ('.meta', '.durable', '.ts'):
expected = '%s%s' % (ts.internal, ext)
# bad frag index should be ignored
actual = mgr.make_on_disk_filename(ts, ext, frag_index=frag)
self.assertEqual(expected, actual)
def test_make_on_disk_filename_for_meta_with_content_type(self):
# verify .meta filename encodes content-type timestamp
mgr = self.df_router[POLICIES.default]
time_ = 1234567890.00001
for delta in (0, 1, 111111):
t_meta = Timestamp(time_)
t_type = Timestamp(time_ - delta / 100000.)
sign = '-' if delta else '+'
expected = '%s%s%x.meta' % (t_meta.short, sign, delta)
actual = mgr.make_on_disk_filename(
t_meta, '.meta', ctype_timestamp=t_type)
self.assertEqual(expected, actual)
parsed = mgr.parse_on_disk_filename(actual, POLICIES.default)
self.assertEqual(parsed, {
'timestamp': t_meta,
'frag_index': None,
'ext': '.meta',
'ctype_timestamp': t_type
})
# these functions are inverse
self.assertEqual(
mgr.make_on_disk_filename(**parsed),
expected)
def test_yield_hashes_legacy_durable(self):
old_ts = Timestamp('1383180000.12345')
fresh_ts = Timestamp(time() - 10)
fresher_ts = Timestamp(time() - 1)
suffix_map = {
'abc': {
'9373a92d072897b136b3fc06595b4abc': [
fresh_ts.internal + '.ts'],
},
'456': {
'9373a92d072897b136b3fc06595b0456': [
old_ts.internal + '#2.data',
old_ts.internal + '.durable'],
'9373a92d072897b136b3fc06595b7456': [
fresh_ts.internal + '.ts',
fresher_ts.internal + '#2.data',
fresher_ts.internal + '.durable'],
},
'def': {},
}
expected = {
'9373a92d072897b136b3fc06595b4abc': {'ts_data': fresh_ts},
'9373a92d072897b136b3fc06595b0456': {'ts_data': old_ts,
'durable': True},
'9373a92d072897b136b3fc06595b7456': {'ts_data': fresher_ts,
'durable': True},
}
self._check_yield_hashes(POLICIES.default, suffix_map, expected,
frag_index=2)
def test_yield_hashes(self):
old_ts = Timestamp('1383180000.12345')
fresh_ts = Timestamp(time() - 10)
fresher_ts = Timestamp(time() - 1)
suffix_map = {
'abc': {
'9373a92d072897b136b3fc06595b4abc': [
fresh_ts.internal + '.ts'],
},
'456': {
'9373a92d072897b136b3fc06595b0456': [
old_ts.internal + '#2#d.data'],
'9373a92d072897b136b3fc06595b7456': [
fresh_ts.internal + '.ts',
fresher_ts.internal + '#2#d.data'],
},
'def': {},
}
expected = {
'9373a92d072897b136b3fc06595b4abc': {'ts_data': fresh_ts},
'9373a92d072897b136b3fc06595b0456': {'ts_data': old_ts,
'durable': True},
'9373a92d072897b136b3fc06595b7456': {'ts_data': fresher_ts,
'durable': True},
}
self._check_yield_hashes(POLICIES.default, suffix_map, expected,
frag_index=2)
def test_yield_hashes_yields_meta_timestamp_legacy_durable(self):
ts_iter = (Timestamp(t) for t in itertools.count(int(time())))
ts1 = next(ts_iter)
ts2 = next(ts_iter)
ts3 = next(ts_iter)
suffix_map = {
'abc': {
'9373a92d072897b136b3fc06595b4abc': [
ts1.internal + '.ts',
ts2.internal + '.meta'],
},
'456': {
'9373a92d072897b136b3fc06595b0456': [
ts1.internal + '#2.data',
ts1.internal + '.durable',
ts2.internal + '.meta',
ts3.internal + '.meta'],
'9373a92d072897b136b3fc06595b7456': [
ts1.internal + '#2.data',
ts1.internal + '.durable',
ts2.internal + '.meta'],
},
}
expected = {
'9373a92d072897b136b3fc06595b4abc': {'ts_data': ts1},
'9373a92d072897b136b3fc06595b0456': {'ts_data': ts1,
'ts_meta': ts3,
'durable': True},
'9373a92d072897b136b3fc06595b7456': {'ts_data': ts1,
'ts_meta': ts2,
'durable': True},
}
self._check_yield_hashes(POLICIES.default, suffix_map, expected)
# but meta timestamp is *not* returned if specified frag index
# is not found
expected = {
'9373a92d072897b136b3fc06595b4abc': {'ts_data': ts1},
}
self._check_yield_hashes(POLICIES.default, suffix_map, expected,
frag_index=3)
def test_yield_hashes_yields_meta_timestamp(self):
ts_iter = (Timestamp(t) for t in itertools.count(int(time())))
ts1 = next(ts_iter)
ts2 = next(ts_iter)
ts3 = next(ts_iter)
suffix_map = {
'abc': {
'9373a92d072897b136b3fc06595b4abc': [
ts1.internal + '.ts',
ts2.internal + '.meta'],
},
'456': {
'9373a92d072897b136b3fc06595b0456': [
ts1.internal + '#2#d.data',
ts2.internal + '.meta',
ts3.internal + '.meta'],
'9373a92d072897b136b3fc06595b7456': [
ts1.internal + '#2#d.data',
ts2.internal + '.meta'],
},
}
expected = {
'9373a92d072897b136b3fc06595b4abc': {'ts_data': ts1},
'9373a92d072897b136b3fc06595b0456': {'ts_data': ts1,
'ts_meta': ts3,
'durable': True},
'9373a92d072897b136b3fc06595b7456': {'ts_data': ts1,
'ts_meta': ts2,
'durable': True},
}
self._check_yield_hashes(POLICIES.default, suffix_map, expected)
# but meta timestamp is *not* returned if specified frag index
# is not found
expected = {
'9373a92d072897b136b3fc06595b4abc': {'ts_data': ts1},
}
self._check_yield_hashes(POLICIES.default, suffix_map, expected,
frag_index=3)
def test_yield_hashes_suffix_filter_legacy_durable(self):
# test again with limited suffixes
old_ts = '1383180000.12345'
fresh_ts = Timestamp(time() - 10).internal
fresher_ts = Timestamp(time() - 1).internal
suffix_map = {
'abc': {
'9373a92d072897b136b3fc06595b4abc': [
fresh_ts + '.ts'],
},
'456': {
'9373a92d072897b136b3fc06595b0456': [
old_ts + '#2.data',
old_ts + '.durable'],
'9373a92d072897b136b3fc06595b7456': [
fresh_ts + '.ts',
fresher_ts + '#2.data',
fresher_ts + '.durable'],
},
'def': {},
}
expected = {
'9373a92d072897b136b3fc06595b0456': {'ts_data': old_ts,
'durable': True},
'9373a92d072897b136b3fc06595b7456': {'ts_data': fresher_ts,
'durable': True},
}
self._check_yield_hashes(POLICIES.default, suffix_map, expected,
suffixes=['456'], frag_index=2)
def test_yield_hashes_suffix_filter(self):
# test again with limited suffixes
old_ts = '1383180000.12345'
fresh_ts = Timestamp(time() - 10).internal
fresher_ts = Timestamp(time() - 1).internal
suffix_map = {
'abc': {
'9373a92d072897b136b3fc06595b4abc': [
fresh_ts + '.ts'],
},
'456': {
'9373a92d072897b136b3fc06595b0456': [
old_ts + '#2#d.data'],
'9373a92d072897b136b3fc06595b7456': [
fresh_ts + '.ts',
fresher_ts + '#2#d.data'],
},
'def': {},
}
expected = {
'9373a92d072897b136b3fc06595b0456': {'ts_data': old_ts,
'durable': True},
'9373a92d072897b136b3fc06595b7456': {'ts_data': fresher_ts,
'durable': True},
}
self._check_yield_hashes(POLICIES.default, suffix_map, expected,
suffixes=['456'], frag_index=2)
def test_yield_hashes_skips_non_durable_data(self):
ts_iter = (Timestamp(t) for t in itertools.count(int(time())))
ts1 = next(ts_iter)
suffix_map = {
'456': {
'9373a92d072897b136b3fc06595b0456': [
ts1.internal + '#2#d.data'],
'9373a92d072897b136b3fc06595b7456': [
ts1.internal + '#2.data'],
},
}
expected = {
'9373a92d072897b136b3fc06595b0456': {'ts_data': ts1,
'durable': True},
}
self._check_yield_hashes(POLICIES.default, suffix_map, expected,
frag_index=2)
# if we add a durable it shows up
suffix_map['456']['9373a92d072897b136b3fc06595b7456'] = [
ts1.internal + '#2#d.data']
expected = {
'9373a92d072897b136b3fc06595b0456': {'ts_data': ts1,
'durable': True},
'9373a92d072897b136b3fc06595b7456': {'ts_data': ts1,
'durable': True},
}
self._check_yield_hashes(POLICIES.default, suffix_map, expected,
frag_index=2)
def test_yield_hashes_optionally_yields_non_durable_data(self):
ts_iter = (Timestamp(t) for t in itertools.count(int(time())))
ts1 = next(ts_iter)
ts2 = next(ts_iter)
suffix_map = {
'abc': {
'9373a92d072897b136b3fc06595b4abc': [
ts1.internal + '#2#d.data',
ts2.internal + '#2.data'], # newer non-durable
'9373a92d072897b136b3fc06595b0abc': [
ts1.internal + '#2.data', # older non-durable
ts2.internal + '#2#d.data'],
},
'456': {
'9373a92d072897b136b3fc06595b0456': [
ts1.internal + '#2#d.data'],
'9373a92d072897b136b3fc06595b7456': [
ts2.internal + '#2.data'],
},
}
# sanity check non-durables not yielded
expected = {
'9373a92d072897b136b3fc06595b4abc': {'ts_data': ts1,
'durable': True},
'9373a92d072897b136b3fc06595b0abc': {'ts_data': ts2,
'durable': True},
'9373a92d072897b136b3fc06595b0456': {'ts_data': ts1,
'durable': True},
}
self._check_yield_hashes(POLICIES.default, suffix_map, expected,
frag_index=2, frag_prefs=None)
# an empty frag_prefs list is sufficient to get non-durables yielded
# (in preference over *older* durable)
expected = {
'9373a92d072897b136b3fc06595b4abc': {'ts_data': ts2,
'durable': False},
'9373a92d072897b136b3fc06595b0abc': {'ts_data': ts2,
'durable': True},
'9373a92d072897b136b3fc06595b0456': {'ts_data': ts1,
'durable': True},
'9373a92d072897b136b3fc06595b7456': {'ts_data': ts2,
'durable': False},
}
self._check_yield_hashes(POLICIES.default, suffix_map, expected,
frag_index=2, frag_prefs=[])
def test_yield_hashes_skips_missing_legacy_durable(self):
ts_iter = (Timestamp(t) for t in itertools.count(int(time())))
ts1 = next(ts_iter)
suffix_map = {
'456': {
'9373a92d072897b136b3fc06595b0456': [
ts1.internal + '#2.data',
ts1.internal + '.durable'],
'9373a92d072897b136b3fc06595b7456': [
ts1.internal + '#2.data'],
},
}
expected = {
'9373a92d072897b136b3fc06595b0456': {'ts_data': ts1,
'durable': True},
}
self._check_yield_hashes(POLICIES.default, suffix_map, expected,
frag_index=2)
# if we add a durable it shows up
suffix_map['456']['9373a92d072897b136b3fc06595b7456'].append(
ts1.internal + '.durable')
expected = {
'9373a92d072897b136b3fc06595b0456': {'ts_data': ts1,
'durable': True},
'9373a92d072897b136b3fc06595b7456': {'ts_data': ts1,
'durable': True},
}
self._check_yield_hashes(POLICIES.default, suffix_map, expected,
frag_index=2)
def test_yield_hashes_skips_newer_data_without_legacy_durable(self):
ts_iter = (Timestamp(t) for t in itertools.count(int(time())))
ts1 = next(ts_iter)
ts2 = next(ts_iter)
ts3 = next(ts_iter)
suffix_map = {
'456': {
'9373a92d072897b136b3fc06595b0456': [
ts1.internal + '#2.data',
ts1.internal + '.durable',
ts2.internal + '#2.data',
ts3.internal + '#2.data'],
},
}
expected = {
'9373a92d072897b136b3fc06595b0456': {'ts_data': ts1,
'durable': True},
}
self._check_yield_hashes(POLICIES.default, suffix_map, expected,
frag_index=None)
self._check_yield_hashes(POLICIES.default, suffix_map, expected,
frag_index=2)
# if we add a durable then newer data shows up
suffix_map['456']['9373a92d072897b136b3fc06595b0456'].append(
ts2.internal + '.durable')
expected = {
'9373a92d072897b136b3fc06595b0456': {'ts_data': ts2,
'durable': True},
}
self._check_yield_hashes(POLICIES.default, suffix_map, expected,
frag_index=None)
self._check_yield_hashes(POLICIES.default, suffix_map, expected,
frag_index=2)
def test_yield_hashes_skips_newer_non_durable_data(self):
ts_iter = (Timestamp(t) for t in itertools.count(int(time())))
ts1 = next(ts_iter)
ts2 = next(ts_iter)
ts3 = next(ts_iter)
suffix_map = {
'456': {
'9373a92d072897b136b3fc06595b0456': [
ts1.internal + '#2#d.data',
ts2.internal + '#2.data',
ts3.internal + '#2.data'],
},
}
expected = {
'9373a92d072897b136b3fc06595b0456': {'ts_data': ts1,
'durable': True},
}
self._check_yield_hashes(POLICIES.default, suffix_map, expected,
frag_index=None)
self._check_yield_hashes(POLICIES.default, suffix_map, expected,
frag_index=2)
# if we make it durable then newer data shows up
suffix_map = {
'456': {
'9373a92d072897b136b3fc06595b0456': [
ts1.internal + '#2#d.data',
ts2.internal + '#2#d.data',
ts3.internal + '#2.data'],
},
}
expected = {
'9373a92d072897b136b3fc06595b0456': {'ts_data': ts2,
'durable': True},
}
self._check_yield_hashes(POLICIES.default, suffix_map, expected,
frag_index=None)
self._check_yield_hashes(POLICIES.default, suffix_map, expected,
frag_index=2)
def test_yield_hashes_ignores_bad_ondisk_filesets(self):
# this differs from DiskFileManager.yield_hashes which will fail
# when encountering a bad on-disk file set
ts_iter = (Timestamp(t) for t in itertools.count(int(time())))
ts1 = next(ts_iter)
ts2 = next(ts_iter)
suffix_map = {
'456': {
# this one is fine
'9333a92d072897b136b3fc06595b0456': [
ts1.internal + '#2#d.data'],
# this one is fine, legacy durable
'9333a92d072897b136b3fc06595b1456': [
ts1.internal + '#2.data',
ts1.internal + '.durable'],
# missing frag index
'9444a92d072897b136b3fc06595b7456': [
ts1.internal + '.data'],
# junk
'9555a92d072897b136b3fc06595b8456': [
'junk_file'],
# not durable
'9666a92d072897b136b3fc06595b9456': [
ts1.internal + '#2.data',
ts2.internal + '.meta'],
# .meta files w/o .data files can't be opened, and are ignored
'9777a92d072897b136b3fc06595ba456': [
ts1.internal + '.meta'],
# multiple meta files with no data
'9888a92d072897b136b3fc06595bb456': [
ts1.internal + '.meta',
ts2.internal + '.meta'],
# this is good with meta
'9999a92d072897b136b3fc06595bb456': [
ts1.internal + '#2#d.data',
ts2.internal + '.meta'],
# this is good with meta, legacy durable
'9999a92d072897b136b3fc06595bc456': [
ts1.internal + '#2.data',
ts1.internal + '.durable',
ts2.internal + '.meta'],
# this one is wrong frag index
'9aaaa92d072897b136b3fc06595b0456': [
ts1.internal + '#7#d.data'],
# this one is wrong frag index, legacy durable
'9aaaa92d072897b136b3fc06595b1456': [
ts1.internal + '#7.data',
ts1.internal + '.durable'],
},
}
expected = {
'9333a92d072897b136b3fc06595b0456': {'ts_data': ts1,
'durable': True},
'9999a92d072897b136b3fc06595bb456': {'ts_data': ts1,
'ts_meta': ts2,
'durable': True},
'9333a92d072897b136b3fc06595b1456': {'ts_data': ts1,
'durable': True},
'9999a92d072897b136b3fc06595bc456': {'ts_data': ts1,
'ts_meta': ts2,
'durable': True},
}
self._check_yield_hashes(POLICIES.default, suffix_map, expected,
frag_index=2)
def test_yield_hashes_filters_frag_index(self):
ts_iter = (Timestamp(t) for t in itertools.count(int(time())))
ts1 = next(ts_iter)
ts2 = next(ts_iter)
ts3 = next(ts_iter)
suffix_map = {
'27e': {
'1111111111111111111111111111127e': [
ts1.internal + '#2#d.data',
ts1.internal + '#3#d.data',
],
'2222222222222222222222222222227e': [
ts1.internal + '#2#d.data',
ts2.internal + '#2#d.data',
],
},
'd41': {
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaad41': [
ts1.internal + '#3#d.data',
],
},
'00b': {
'3333333333333333333333333333300b': [
ts1.internal + '#2.data',
ts2.internal + '#2.data',
ts3.internal + '#2#d.data',
],
},
}
expected = {
'1111111111111111111111111111127e': {'ts_data': ts1,
'durable': True},
'2222222222222222222222222222227e': {'ts_data': ts2,
'durable': True},
'3333333333333333333333333333300b': {'ts_data': ts3,
'durable': True},
}
self._check_yield_hashes(POLICIES.default, suffix_map, expected,
frag_index=2)
def test_yield_hashes_filters_frag_index_legacy_durable(self):
ts_iter = (Timestamp(t) for t in itertools.count(int(time())))
ts1 = next(ts_iter)
ts2 = next(ts_iter)
ts3 = next(ts_iter)
suffix_map = {
'27e': {
'1111111111111111111111111111127e': [
ts1.internal + '#2.data',
ts1.internal + '#3.data',
ts1.internal + '.durable',
],
'2222222222222222222222222222227e': [
ts1.internal + '#2.data',
ts1.internal + '.durable',
ts2.internal + '#2.data',
ts2.internal + '.durable',
],
},
'd41': {
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaad41': [
ts1.internal + '#3.data',
ts1.internal + '.durable',
],
},
'00b': {
'3333333333333333333333333333300b': [
ts1.internal + '#2.data',
ts2.internal + '#2.data',
ts3.internal + '#2.data',
ts3.internal + '.durable',
],
},
}
expected = {
'1111111111111111111111111111127e': {'ts_data': ts1,
'durable': True},
'2222222222222222222222222222227e': {'ts_data': ts2,
'durable': True},
'3333333333333333333333333333300b': {'ts_data': ts3,
'durable': True},
}
self._check_yield_hashes(POLICIES.default, suffix_map, expected,
frag_index=2)
def _test_get_diskfile_from_hash_frag_index_filter(self, legacy_durable):
df = self._get_diskfile(POLICIES.default)
hash_ = os.path.basename(df._datadir)
self.assertRaises(DiskFileNotExist,
self.df_mgr.get_diskfile_from_hash,
self.existing_device, '0', hash_,
POLICIES.default) # sanity
timestamp = Timestamp.now()
for frag_index in (4, 7):
write_diskfile(df, timestamp, frag_index=frag_index,
legacy_durable=legacy_durable)
df4 = self.df_mgr.get_diskfile_from_hash(
self.existing_device, '0', hash_, POLICIES.default, frag_index=4)
self.assertEqual(df4._frag_index, 4)
self.assertEqual(
df4.read_metadata()['X-Object-Sysmeta-Ec-Frag-Index'], '4')
df7 = self.df_mgr.get_diskfile_from_hash(
self.existing_device, '0', hash_, POLICIES.default, frag_index=7)
self.assertEqual(df7._frag_index, 7)
self.assertEqual(
df7.read_metadata()['X-Object-Sysmeta-Ec-Frag-Index'], '7')
def test_get_diskfile_from_hash_frag_index_filter(self):
self._test_get_diskfile_from_hash_frag_index_filter(False)
def test_get_diskfile_from_hash_frag_index_filter_legacy_durable(self):
self._test_get_diskfile_from_hash_frag_index_filter(True)
def test_check_policy(self):
mock_policy = mock.MagicMock()
mock_policy.policy_type = EC_POLICY
# sanity, ECDiskFileManager is ok with EC_POLICY
diskfile.ECDiskFileManager.check_policy(mock_policy)
# ECDiskFileManager raises ValueError with REPL_POLICY
mock_policy.policy_type = REPL_POLICY
with self.assertRaises(ValueError) as cm:
diskfile.ECDiskFileManager.check_policy(mock_policy)
self.assertEqual('Invalid policy_type: %s' % REPL_POLICY,
str(cm.exception))
class DiskFileMixin(BaseDiskFileTestMixin):
def ts(self):
"""
Timestamps - forever.
"""
return next(self._ts_iter)
def _create_ondisk_file(self, df, data, timestamp, metadata=None,
ctype_timestamp=None,
ext='.data', legacy_durable=False, commit=True):
mkdirs(df._datadir)
if timestamp is None:
timestamp = time()
timestamp = Timestamp(timestamp)
if not metadata:
metadata = {}
if 'X-Timestamp' not in metadata:
metadata['X-Timestamp'] = timestamp.internal
if 'ETag' not in metadata:
etag = md5()
etag.update(data)
metadata['ETag'] = etag.hexdigest()
if 'name' not in metadata:
metadata['name'] = '/a/c/o'
if 'Content-Length' not in metadata:
metadata['Content-Length'] = str(len(data))
filename = timestamp.internal
if ext == '.data' and df.policy.policy_type == EC_POLICY:
if legacy_durable:
filename = '%s#%s' % (timestamp.internal, df._frag_index)
if commit:
durable_file = os.path.join(
df._datadir, '%s.durable' % timestamp.internal)
with open(durable_file, 'wb') as f:
pass
elif commit:
filename = '%s#%s#d' % (timestamp.internal, df._frag_index)
else:
filename = '%s#%s' % (timestamp.internal, df._frag_index)
if ctype_timestamp:
metadata.update(
{'Content-Type-Timestamp':
Timestamp(ctype_timestamp).internal})
filename = encode_timestamps(timestamp,
Timestamp(ctype_timestamp),
explicit=True)
data_file = os.path.join(df._datadir, filename + ext)
with open(data_file, 'wb') as f:
f.write(data)
xattr.setxattr(f.fileno(), diskfile.METADATA_KEY,
pickle.dumps(metadata, diskfile.PICKLE_PROTOCOL))
def _simple_get_diskfile(self, partition='0', account='a', container='c',
obj='o', policy=None, frag_index=None, **kwargs):
policy = policy or POLICIES.default
df_mgr = self.df_router[policy]
if policy.policy_type == EC_POLICY and frag_index is None:
frag_index = 2
return df_mgr.get_diskfile(self.existing_device, partition,
account, container, obj,
policy=policy, frag_index=frag_index,
**kwargs)
def _create_test_file(self, data, timestamp=None, metadata=None,
account='a', container='c', obj='o', **kwargs):
if not isinstance(data, bytes):
raise ValueError('data must be bytes')
if metadata is None:
metadata = {}
metadata.setdefault('name', '/%s/%s/%s' % (account, container, obj))
df = self._simple_get_diskfile(account=account, container=container,
obj=obj, **kwargs)
if timestamp is None:
timestamp = time()
timestamp = Timestamp(timestamp)
# avoid getting O_TMPFILE warning in logs
if not utils.o_tmpfile_in_tmpdir_supported():
df.manager.use_linkat = False
if df.policy.policy_type == EC_POLICY:
data = encode_frag_archive_bodies(df.policy, data)[df._frag_index]
with df.create() as writer:
new_metadata = {
'ETag': md5(data).hexdigest(),
'X-Timestamp': timestamp.internal,
'Content-Length': len(data),
}
new_metadata.update(metadata)
writer.write(data)
writer.put(new_metadata)
writer.commit(timestamp)
df.open()
return df, data
def test_get_dev_path(self):
self.df_mgr.devices = '/srv'
device = 'sda1'
dev_path = os.path.join(self.df_mgr.devices, device)
mount_check = None
self.df_mgr.mount_check = True
with mock_check_drive(ismount=False):
self.assertEqual(self.df_mgr.get_dev_path(device, mount_check),
None)
with mock_check_drive(ismount=True):
self.assertEqual(self.df_mgr.get_dev_path(device, mount_check),
dev_path)
self.df_mgr.mount_check = False
with mock_check_drive(isdir=False):
self.assertEqual(self.df_mgr.get_dev_path(device, mount_check),
None)
with mock_check_drive(isdir=True):
self.assertEqual(self.df_mgr.get_dev_path(device, mount_check),
dev_path)
mount_check = True
with mock_check_drive(ismount=False):
self.assertEqual(self.df_mgr.get_dev_path(device, mount_check),
None)
with mock_check_drive(ismount=True):
self.assertEqual(self.df_mgr.get_dev_path(device, mount_check),
dev_path)
mount_check = False
self.assertEqual(self.df_mgr.get_dev_path(device, mount_check),
dev_path)
def test_open_not_exist(self):
df = self._simple_get_diskfile()
self.assertRaises(DiskFileNotExist, df.open)
def test_open_expired(self):
self.assertRaises(DiskFileExpired,
self._create_test_file,
b'1234567890', metadata={'X-Delete-At': '0'})
try:
self._create_test_file(b'1234567890', open_expired=True,
metadata={'X-Delete-At': '0',
'X-Object-Meta-Foo': 'bar'})
df = self._simple_get_diskfile(open_expired=True)
md = df.read_metadata()
self.assertEqual(md['X-Object-Meta-Foo'], 'bar')
except SwiftException as err:
self.fail("Unexpected swift exception raised: %r" % err)
def test_open_not_expired(self):
try:
self._create_test_file(
b'1234567890', metadata={'X-Delete-At': str(2 * int(time()))})
except SwiftException as err:
self.fail("Unexpected swift exception raised: %r" % err)
def test_get_metadata(self):
timestamp = self.ts().internal
df, df_data = self._create_test_file(b'1234567890',
timestamp=timestamp)
md = df.get_metadata()
self.assertEqual(md['X-Timestamp'], timestamp)
def test_read_metadata(self):
timestamp = self.ts().internal
self._create_test_file(b'1234567890', timestamp=timestamp)
df = self._simple_get_diskfile()
md = df.read_metadata()
self.assertEqual(md['X-Timestamp'], timestamp)
def test_read_metadata_no_xattr(self):
def mock_getxattr(*args, **kargs):
error_num = errno.ENOTSUP if hasattr(errno, 'ENOTSUP') else \
errno.EOPNOTSUPP
raise IOError(error_num, "Operation not supported")
with mock.patch('xattr.getxattr', mock_getxattr):
self.assertRaises(
DiskFileXattrNotSupported,
diskfile.read_metadata, 'n/a')
def test_get_metadata_not_opened(self):
df = self._simple_get_diskfile()
with self.assertRaises(DiskFileNotOpen):
df.get_metadata()
def test_get_datafile_metadata(self):
ts_iter = make_timestamp_iter()
body = b'1234567890'
ts_data = next(ts_iter)
metadata = {'X-Object-Meta-Test': 'test1',
'X-Object-Sysmeta-Test': 'test1'}
df, df_data = self._create_test_file(body, timestamp=ts_data.internal,
metadata=metadata)
expected = df.get_metadata()
ts_meta = next(ts_iter)
df.write_metadata({'X-Timestamp': ts_meta.internal,
'X-Object-Meta-Test': 'changed',
'X-Object-Sysmeta-Test': 'ignored'})
df.open()
self.assertEqual(expected, df.get_datafile_metadata())
expected.update({'X-Timestamp': ts_meta.internal,
'X-Object-Meta-Test': 'changed'})
self.assertEqual(expected, df.get_metadata())
def test_get_datafile_metadata_not_opened(self):
df = self._simple_get_diskfile()
with self.assertRaises(DiskFileNotOpen):
df.get_datafile_metadata()
def test_get_metafile_metadata(self):
ts_iter = make_timestamp_iter()
body = b'1234567890'
ts_data = next(ts_iter)
metadata = {'X-Object-Meta-Test': 'test1',
'X-Object-Sysmeta-Test': 'test1'}
df, df_data = self._create_test_file(body, timestamp=ts_data.internal,
metadata=metadata)
self.assertIsNone(df.get_metafile_metadata())
# now create a meta file
ts_meta = next(ts_iter)
df.write_metadata({'X-Timestamp': ts_meta.internal,
'X-Object-Meta-Test': 'changed'})
df.open()
expected = {'X-Timestamp': ts_meta.internal,
'X-Object-Meta-Test': 'changed'}
self.assertEqual(expected, df.get_metafile_metadata())
def test_get_metafile_metadata_not_opened(self):
df = self._simple_get_diskfile()
with self.assertRaises(DiskFileNotOpen):
df.get_metafile_metadata()
def test_not_opened(self):
df = self._simple_get_diskfile()
with self.assertRaises(DiskFileNotOpen):
with df:
pass
def test_disk_file_default_disallowed_metadata(self):
# build an object with some meta (at t0+1s)
orig_metadata = {'X-Object-Meta-Key1': 'Value1',
'X-Object-Transient-Sysmeta-KeyA': 'ValueA',
'Content-Type': 'text/garbage'}
df = self._get_open_disk_file(ts=self.ts().internal,
extra_metadata=orig_metadata)
with df.open():
if df.policy.policy_type == EC_POLICY:
expected = df.policy.pyeclib_driver.get_segment_info(
1024, df.policy.ec_segment_size)['fragment_size']
else:
expected = 1024
self.assertEqual(str(expected), df._metadata['Content-Length'])
# write some new metadata (fast POST, don't send orig meta, at t0+1)
df = self._simple_get_diskfile()
df.write_metadata({'X-Timestamp': self.ts().internal,
'X-Object-Transient-Sysmeta-KeyB': 'ValueB',
'X-Object-Meta-Key2': 'Value2'})
df = self._simple_get_diskfile()
with df.open():
# non-fast-post updateable keys are preserved
self.assertEqual('text/garbage', df._metadata['Content-Type'])
# original fast-post updateable keys are removed
self.assertNotIn('X-Object-Meta-Key1', df._metadata)
self.assertNotIn('X-Object-Transient-Sysmeta-KeyA', df._metadata)
# new fast-post updateable keys are added
self.assertEqual('Value2', df._metadata['X-Object-Meta-Key2'])
self.assertEqual('ValueB',
df._metadata['X-Object-Transient-Sysmeta-KeyB'])
def test_disk_file_preserves_sysmeta(self):
# build an object with some meta (at t0)
orig_metadata = {'X-Object-Sysmeta-Key1': 'Value1',
'Content-Type': 'text/garbage'}
df = self._get_open_disk_file(ts=self.ts().internal,
extra_metadata=orig_metadata)
with df.open():
if df.policy.policy_type == EC_POLICY:
expected = df.policy.pyeclib_driver.get_segment_info(
1024, df.policy.ec_segment_size)['fragment_size']
else:
expected = 1024
self.assertEqual(str(expected), df._metadata['Content-Length'])
# write some new metadata (fast POST, don't send orig meta, at t0+1s)
df = self._simple_get_diskfile()
df.write_metadata({'X-Timestamp': self.ts().internal,
'X-Object-Sysmeta-Key1': 'Value2',
'X-Object-Meta-Key3': 'Value3'})
df = self._simple_get_diskfile()
with df.open():
# non-fast-post updateable keys are preserved
self.assertEqual('text/garbage', df._metadata['Content-Type'])
# original sysmeta keys are preserved
self.assertEqual('Value1', df._metadata['X-Object-Sysmeta-Key1'])
def test_disk_file_preserves_slo(self):
# build an object with some meta (at t0)
orig_metadata = {'X-Static-Large-Object': 'True',
'Content-Type': 'text/garbage'}
df = self._get_open_disk_file(ts=self.ts().internal,
extra_metadata=orig_metadata)
# sanity test
with df.open():
self.assertEqual('True', df._metadata['X-Static-Large-Object'])
if df.policy.policy_type == EC_POLICY:
expected = df.policy.pyeclib_driver.get_segment_info(
1024, df.policy.ec_segment_size)['fragment_size']
else:
expected = 1024
self.assertEqual(str(expected), df._metadata['Content-Length'])
# write some new metadata (fast POST, don't send orig meta, at t0+1s)
df = self._simple_get_diskfile()
df.write_metadata({'X-Timestamp': self.ts().internal})
df = self._simple_get_diskfile()
with df.open():
# non-fast-post updateable keys are preserved
self.assertEqual('text/garbage', df._metadata['Content-Type'])
self.assertEqual('True', df._metadata['X-Static-Large-Object'])
def test_disk_file_reader_iter(self):
df, df_data = self._create_test_file(b'1234567890')
quarantine_msgs = []
reader = df.reader(_quarantine_hook=quarantine_msgs.append)
self.assertEqual(b''.join(reader), df_data)
self.assertEqual(quarantine_msgs, [])
def test_disk_file_reader_iter_w_quarantine(self):
df, df_data = self._create_test_file(b'1234567890')
def raise_dfq(m):
raise DiskFileQuarantined(m)
reader = df.reader(_quarantine_hook=raise_dfq)
reader._obj_size += 1
self.assertRaises(DiskFileQuarantined, b''.join, reader)
def test_disk_file_reader_iter_w_io_error(self):
df, df_data = self._create_test_file(b'1234567890')
class FakeFp(object):
def __init__(self, buf):
self.pos = 0
self.buf = buf
def read(self, sz):
if not self.buf:
raise IOError(5, 'Input/output error')
chunk, self.buf = self.buf, b''
self.pos += len(chunk)
return chunk
def close(self):
pass
def tell(self):
return self.pos
def raise_dfq(m):
raise DiskFileQuarantined(m)
reader = df.reader(_quarantine_hook=raise_dfq)
reader._fp = FakeFp(b'1234')
self.assertRaises(DiskFileQuarantined, b''.join, reader)
def test_disk_file_app_iter_corners(self):
df, df_data = self._create_test_file(b'1234567890')
quarantine_msgs = []
reader = df.reader(_quarantine_hook=quarantine_msgs.append)
self.assertEqual(b''.join(reader.app_iter_range(0, None)),
df_data)
self.assertEqual(quarantine_msgs, [])
df = self._simple_get_diskfile()
with df.open():
reader = df.reader()
self.assertEqual(b''.join(reader.app_iter_range(5, None)),
df_data[5:])
def test_disk_file_app_iter_range_w_none(self):
df, df_data = self._create_test_file(b'1234567890')
quarantine_msgs = []
reader = df.reader(_quarantine_hook=quarantine_msgs.append)
self.assertEqual(b''.join(reader.app_iter_range(None, None)),
df_data)
self.assertEqual(quarantine_msgs, [])
def test_disk_file_app_iter_partial_closes(self):
df, df_data = self._create_test_file(b'1234567890')
quarantine_msgs = []
reader = df.reader(_quarantine_hook=quarantine_msgs.append)
it = reader.app_iter_range(0, 5)
self.assertEqual(b''.join(it), df_data[:5])
self.assertEqual(quarantine_msgs, [])
self.assertTrue(reader._fp is None)
def test_disk_file_app_iter_ranges(self):
df, df_data = self._create_test_file(b'012345678911234567892123456789')
quarantine_msgs = []
reader = df.reader(_quarantine_hook=quarantine_msgs.append)
it = reader.app_iter_ranges([(0, 10), (10, 20), (20, 30)],
'plain/text',
'\r\n--someheader\r\n', len(df_data))
value = b''.join(it)
self.assertIn(df_data[:10], value)
self.assertIn(df_data[10:20], value)
self.assertIn(df_data[20:30], value)
self.assertEqual(quarantine_msgs, [])
def test_disk_file_app_iter_ranges_w_quarantine(self):
df, df_data = self._create_test_file(b'012345678911234567892123456789')
quarantine_msgs = []
reader = df.reader(_quarantine_hook=quarantine_msgs.append)
self.assertEqual(len(df_data), reader._obj_size) # sanity check
reader._obj_size += 1
it = reader.app_iter_ranges([(0, len(df_data))],
'plain/text',
'\r\n--someheader\r\n', len(df_data))
value = b''.join(it)
self.assertIn(df_data, value)
self.assertEqual(quarantine_msgs,
["Bytes read: %s, does not match metadata: %s" %
(len(df_data), len(df_data) + 1)])
def test_disk_file_app_iter_ranges_w_no_etag_quarantine(self):
df, df_data = self._create_test_file(b'012345678911234567892123456789')
quarantine_msgs = []
reader = df.reader(_quarantine_hook=quarantine_msgs.append)
it = reader.app_iter_ranges([(0, 10)],
'plain/text',
'\r\n--someheader\r\n', len(df_data))
value = b''.join(it)
self.assertIn(df_data[:10], value)
self.assertEqual(quarantine_msgs, [])
def test_disk_file_app_iter_ranges_edges(self):
df, df_data = self._create_test_file(b'012345678911234567892123456789')
quarantine_msgs = []
reader = df.reader(_quarantine_hook=quarantine_msgs.append)
it = reader.app_iter_ranges([(3, 10), (0, 2)], 'application/whatever',
'\r\n--someheader\r\n', len(df_data))
value = b''.join(it)
self.assertIn(df_data[3:10], value)
self.assertIn(df_data[:2], value)
self.assertEqual(quarantine_msgs, [])
def test_disk_file_large_app_iter_ranges(self):
# This test case is to make sure that the disk file app_iter_ranges
# method all the paths being tested.
long_str = b'01234567890' * 65536
df, df_data = self._create_test_file(long_str)
target_strs = [df_data[3:10], df_data[0:65590]]
quarantine_msgs = []
reader = df.reader(_quarantine_hook=quarantine_msgs.append)
it = reader.app_iter_ranges([(3, 10), (0, 65590)], 'plain/text',
'5e816ff8b8b8e9a5d355497e5d9e0301',
len(df_data))
# The produced string actually missing the MIME headers
# need to add these headers to make it as real MIME message.
# The body of the message is produced by method app_iter_ranges
# off of DiskFile object.
header = b''.join([b'Content-Type: multipart/byteranges;',
b'boundary=',
b'5e816ff8b8b8e9a5d355497e5d9e0301\r\n'])
value = header + b''.join(it)
self.assertEqual(quarantine_msgs, [])
message = email.message_from_bytes(value)
parts = [p.get_payload(decode=True) for p in message.walk()][1:3]
self.assertEqual(parts, target_strs)
def test_disk_file_app_iter_ranges_empty(self):
# This test case tests when empty value passed into app_iter_ranges
# When ranges passed into the method is either empty array or None,
# this method will yield empty string
df, df_data = self._create_test_file(b'012345678911234567892123456789')
quarantine_msgs = []
reader = df.reader(_quarantine_hook=quarantine_msgs.append)
it = reader.app_iter_ranges([], 'application/whatever',
'\r\n--someheader\r\n', len(df_data))
self.assertEqual(b''.join(it), b'')
df = self._simple_get_diskfile()
with df.open():
reader = df.reader()
it = reader.app_iter_ranges(None, 'app/something',
'\r\n--someheader\r\n', 150)
self.assertEqual(b''.join(it), b'')
self.assertEqual(quarantine_msgs, [])
def test_disk_file_mkstemp_creates_dir(self):
for policy in POLICIES:
tmpdir = os.path.join(self.testdir, self.existing_device,
diskfile.get_tmp_dir(policy))
os.rmdir(tmpdir)
df = self._simple_get_diskfile(policy=policy)
df.manager.use_linkat = False
with df.create():
self.assertTrue(os.path.exists(tmpdir))
def test_disk_file_writer(self):
df = self._simple_get_diskfile()
with df.create() as writer:
self.assertIsInstance(writer, diskfile.BaseDiskFileWriter)
# create automatically opens for us
self.assertIsNotNone(writer._fd)
# can't re-open since we're already open
with self.assertRaises(ValueError):
writer.open()
writer.write(b'asdf')
writer.close()
# can't write any more
with self.assertRaises(ValueError):
writer.write(b'asdf')
# can close again
writer.close()
def test_disk_file_concurrent_writes(self):
def threadA(df, events, errors):
try:
ts = self.ts()
with df.create() as writer:
writer.write(b'dataA')
writer.put({
'X-Timestamp': ts.internal,
'Content-Length': 5,
})
events[0].set()
events[1].wait()
writer.commit(ts)
except Exception as e:
errors.append(e)
raise
def threadB(df, events, errors):
try:
events[0].wait()
ts = self.ts()
with df.create() as writer:
writer.write(b'dataB')
writer.put({
'X-Timestamp': ts.internal,
'Content-Length': 5,
})
writer.commit(ts)
events[1].set()
except Exception as e:
errors.append(e)
raise
df = self._simple_get_diskfile()
events = [threading.Event(), threading.Event()]
errors = []
threads = [threading.Thread(target=tgt, args=(df, events, errors))
for tgt in (threadA, threadB)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
self.assertFalse(errors)
with df.open(), open(df._data_file, 'rb') as fp:
self.assertEqual(b'dataB', fp.read())
def test_disk_file_concurrent_marked_durable(self):
ts = self.ts()
def threadA(df, events, errors):
try:
with df.create() as writer:
writer.write(b'dataA')
writer.put({
'X-Timestamp': ts.internal,
'Content-Length': 5,
})
events[0].set()
events[1].wait()
writer.commit(ts)
except Exception as e:
errors.append(e)
raise
def threadB(df, events, errors):
try:
events[0].wait()
# Mark it durable just like in ssync_receiver
with df.create() as writer:
writer.commit(ts)
events[1].set()
except Exception as e:
errors.append(e)
raise
df = self._simple_get_diskfile()
events = [threading.Event(), threading.Event()]
errors = []
threads = [threading.Thread(target=tgt, args=(df, events, errors))
for tgt in (threadA, threadB)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
self.assertFalse(errors)
with df.open(), open(df._data_file, 'rb') as fp:
if df.policy.policy_type == EC_POLICY:
# Confirm that it really *was* marked durable
self.assertTrue(df._data_file.endswith('#d.data'))
self.assertEqual(b'dataA', fp.read())
def test_disk_file_concurrent_delete(self):
def threadA(df, events, errors):
try:
ts = self.ts()
with df.create() as writer:
writer.write(b'dataA')
writer.put({'X-Timestamp': ts.internal})
events[0].set()
events[1].wait()
writer.commit(ts)
except Exception as e:
errors.append(e)
raise
def threadB(df, events, errors):
try:
events[0].wait()
df.delete(self.ts())
events[1].set()
except Exception as e:
errors.append(e)
raise
df = self._simple_get_diskfile()
events = [threading.Event(), threading.Event()]
errors = []
threads = [threading.Thread(target=tgt, args=(df, events, errors))
for tgt in (threadA, threadB)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
self.assertFalse(errors)
self.assertRaises(DiskFileDeleted, df.open)
def _get_open_disk_file(self, invalid_type=None, obj_name='o', fsize=1024,
csize=8, mark_deleted=False, prealloc=False,
ts=None, mount_check=False, extra_metadata=None,
policy=None, frag_index=None, data=None,
commit=True):
'''returns a DiskFile'''
policy = policy or POLICIES.legacy
df = self._simple_get_diskfile(obj=obj_name, policy=policy,
frag_index=frag_index)
data = data or b'0' * fsize
if not isinstance(data, bytes):
raise ValueError('data must be bytes')
if policy.policy_type == EC_POLICY:
archives = encode_frag_archive_bodies(policy, data)
try:
data = archives[df._frag_index]
except IndexError:
data = archives[0]
if ts:
timestamp = Timestamp(ts)
else:
timestamp = Timestamp.now()
if prealloc:
prealloc_size = fsize
else:
prealloc_size = None
with df.create(size=prealloc_size) as writer:
writer.write(data)
upload_size, etag = writer.chunks_finished()
metadata = {
'ETag': etag,
'X-Timestamp': timestamp.internal,
'Content-Length': str(upload_size),
}
metadata.update(extra_metadata or {})
writer.put(metadata)
if invalid_type == 'ETag':
etag = md5()
etag.update('1' + '0' * (fsize - 1))
etag = etag.hexdigest()
metadata['ETag'] = etag
diskfile.write_metadata(writer._fd, metadata)
elif invalid_type == 'Content-Length':
metadata['Content-Length'] = fsize - 1
diskfile.write_metadata(writer._fd, metadata)
elif invalid_type == 'Bad-Content-Length':
metadata['Content-Length'] = 'zero'
diskfile.write_metadata(writer._fd, metadata)
elif invalid_type == 'Missing-Content-Length':
del metadata['Content-Length']
diskfile.write_metadata(writer._fd, metadata)
elif invalid_type == 'Bad-X-Delete-At':
metadata['X-Delete-At'] = 'bad integer'
diskfile.write_metadata(writer._fd, metadata)
if commit:
writer.commit(timestamp)
if mark_deleted:
df.delete(timestamp)
data_files = [os.path.join(df._datadir, fname)
for fname in sorted(os.listdir(df._datadir),
reverse=True)
if fname.endswith('.data')]
if invalid_type == 'Corrupt-Xattrs':
# We have to go below read_metadata/write_metadata to get proper
# corruption.
meta_xattr = xattr.getxattr(data_files[0], "user.swift.metadata")
wrong_byte = b'X' if meta_xattr[:1] != b'X' else b'Y'
xattr.setxattr(data_files[0], "user.swift.metadata",
wrong_byte + meta_xattr[1:])
elif invalid_type == 'Subtly-Corrupt-Xattrs':
# We have to go below read_metadata/write_metadata to get proper
# corruption.
meta_xattr = xattr.getxattr(data_files[0], "user.swift.metadata")
wrong_checksum = md5(meta_xattr + b"some extra stuff").hexdigest()
xattr.setxattr(data_files[0], "user.swift.metadata_checksum",
wrong_checksum.encode())
elif invalid_type == 'Truncated-Xattrs':
meta_xattr = xattr.getxattr(data_files[0], "user.swift.metadata")
xattr.setxattr(data_files[0], "user.swift.metadata",
meta_xattr[:-1])
elif invalid_type == 'Missing-Name':
md = diskfile.read_metadata(data_files[0])
del md['name']
diskfile.write_metadata(data_files[0], md)
elif invalid_type == 'Bad-Name':
md = diskfile.read_metadata(data_files[0])
md['name'] = md['name'] + 'garbage'
diskfile.write_metadata(data_files[0], md)
self.conf['disk_chunk_size'] = csize
self.conf['mount_check'] = mount_check
self.df_mgr = self.mgr_cls(self.conf, self.logger)
self.df_router = diskfile.DiskFileRouter(self.conf, self.logger)
# actual on disk frag_index may have been set by metadata
frag_index = metadata.get('X-Object-Sysmeta-Ec-Frag-Index',
frag_index)
df = self._simple_get_diskfile(obj=obj_name, policy=policy,
frag_index=frag_index)
df.open()
if invalid_type == 'Zero-Byte':
fp = open(df._data_file, 'w')
fp.close()
df.unit_test_len = fsize
return df
def test_keep_cache(self):
df = self._get_open_disk_file(fsize=65)
with mock.patch("swift.obj.diskfile.drop_buffer_cache") as foo:
for _ in df.reader():
pass
self.assertTrue(foo.called)
df = self._get_open_disk_file(fsize=65)
with mock.patch("swift.obj.diskfile.drop_buffer_cache") as bar:
for _ in df.reader(keep_cache=False):
pass
self.assertTrue(bar.called)
df = self._get_open_disk_file(fsize=65)
with mock.patch("swift.obj.diskfile.drop_buffer_cache") as boo:
for _ in df.reader(keep_cache=True):
pass
self.assertFalse(boo.called)
df = self._get_open_disk_file(fsize=50 * 1024, csize=256)
with mock.patch("swift.obj.diskfile.drop_buffer_cache") as goo:
for _ in df.reader(keep_cache=True):
pass
self.assertTrue(goo.called)
def test_quarantine_valids(self):
def verify(*args, **kwargs):
try:
df = self._get_open_disk_file(**kwargs)
reader = df.reader()
for chunk in reader:
pass
except DiskFileQuarantined:
self.fail(
"Unexpected quarantining occurred: args=%r, kwargs=%r" % (
args, kwargs))
else:
pass
verify(obj_name='1')
verify(obj_name='2', csize=1)
verify(obj_name='3', csize=100000)
def run_quarantine_invalids(self, invalid_type):
open_exc = invalid_type in ('Content-Length', 'Bad-Content-Length',
'Subtly-Corrupt-Xattrs',
'Corrupt-Xattrs', 'Truncated-Xattrs',
'Missing-Name', 'Bad-X-Delete-At')
open_collision = invalid_type == 'Bad-Name'
def verify(*args, **kwargs):
quarantine_msgs = []
try:
df = self._get_open_disk_file(**kwargs)
reader = df.reader(_quarantine_hook=quarantine_msgs.append)
except DiskFileQuarantined as err:
if not open_exc:
self.fail(
"Unexpected DiskFileQuarantine raised: %r" % err)
return
except DiskFileCollision as err:
if not open_collision:
self.fail(
"Unexpected DiskFileCollision raised: %r" % err)
return
else:
if open_exc:
self.fail("Expected DiskFileQuarantine exception")
try:
for chunk in reader:
pass
except DiskFileQuarantined as err:
self.fail("Unexpected DiskFileQuarantine raised: :%r" % err)
else:
if not open_exc:
self.assertEqual(1, len(quarantine_msgs))
verify(invalid_type=invalid_type, obj_name='1')
verify(invalid_type=invalid_type, obj_name='2', csize=1)
verify(invalid_type=invalid_type, obj_name='3', csize=100000)
verify(invalid_type=invalid_type, obj_name='4')
def verify_air(params, start=0, adjustment=0):
"""verify (a)pp (i)ter (r)ange"""
try:
df = self._get_open_disk_file(**params)
reader = df.reader()
except DiskFileQuarantined as err:
if not open_exc:
self.fail(
"Unexpected DiskFileQuarantine raised: %r" % err)
return
except DiskFileCollision as err:
if not open_collision:
self.fail(
"Unexpected DiskFileCollision raised: %r" % err)
return
else:
if open_exc:
self.fail("Expected DiskFileQuarantine exception")
try:
for chunk in reader.app_iter_range(
start,
df.unit_test_len + adjustment):
pass
except DiskFileQuarantined as err:
self.fail("Unexpected DiskFileQuarantine raised: :%r" % err)
verify_air(dict(invalid_type=invalid_type, obj_name='5'))
verify_air(dict(invalid_type=invalid_type, obj_name='6'), 0, 100)
verify_air(dict(invalid_type=invalid_type, obj_name='7'), 1)
verify_air(dict(invalid_type=invalid_type, obj_name='8'), 0, -1)
verify_air(dict(invalid_type=invalid_type, obj_name='8'), 1, 1)
def test_quarantine_corrupt_xattrs(self):
self.run_quarantine_invalids('Corrupt-Xattrs')
def test_quarantine_subtly_corrupt_xattrs(self):
# xattrs that unpickle without error, but whose checksum does not
# match
self.run_quarantine_invalids('Subtly-Corrupt-Xattrs')
def test_quarantine_truncated_xattrs(self):
self.run_quarantine_invalids('Truncated-Xattrs')
def test_quarantine_invalid_etag(self):
self.run_quarantine_invalids('ETag')
def test_quarantine_invalid_missing_name(self):
self.run_quarantine_invalids('Missing-Name')
def test_quarantine_invalid_bad_name(self):
self.run_quarantine_invalids('Bad-Name')
def test_quarantine_invalid_bad_x_delete_at(self):
self.run_quarantine_invalids('Bad-X-Delete-At')
def test_quarantine_invalid_content_length(self):
self.run_quarantine_invalids('Content-Length')
def test_quarantine_invalid_content_length_bad(self):
self.run_quarantine_invalids('Bad-Content-Length')
def test_quarantine_invalid_zero_byte(self):
self.run_quarantine_invalids('Zero-Byte')
def test_quarantine_deleted_files(self):
try:
self._get_open_disk_file(invalid_type='Content-Length')
except DiskFileQuarantined:
pass
else:
self.fail("Expected DiskFileQuarantined exception")
try:
self._get_open_disk_file(invalid_type='Content-Length',
mark_deleted=True)
except DiskFileQuarantined as err:
self.fail("Unexpected DiskFileQuarantined exception"
" encountered: %r" % err)
except DiskFileNotExist:
pass
else:
self.fail("Expected DiskFileNotExist exception")
try:
self._get_open_disk_file(invalid_type='Content-Length',
mark_deleted=True)
except DiskFileNotExist:
pass
else:
self.fail("Expected DiskFileNotExist exception")
def test_quarantine_missing_content_length(self):
self.assertRaises(
DiskFileQuarantined,
self._get_open_disk_file,
invalid_type='Missing-Content-Length')
def test_quarantine_bad_content_length(self):
self.assertRaises(
DiskFileQuarantined,
self._get_open_disk_file,
invalid_type='Bad-Content-Length')
def test_quarantine_fstat_oserror(self):
with mock.patch('os.fstat', side_effect=OSError()):
self.assertRaises(
DiskFileQuarantined,
self._get_open_disk_file)
def test_quarantine_ioerror_enodata(self):
df = self._get_open_disk_file()
def my_open(filename, mode, *args, **kwargs):
if mode == 'rb':
raise IOError(errno.ENODATA, '-ENODATA fool!')
return open(filename, mode, *args, **kwargs)
with mock.patch('swift.obj.diskfile.open', my_open):
with self.assertRaises(DiskFileQuarantined) as err:
df.open()
self.assertEqual(
'Failed to open %s: [Errno %d] -ENODATA fool!'
% (df._data_file, errno.ENODATA), str(err.exception))
def test_quarantine_ioerror_euclean(self):
df = self._get_open_disk_file()
def my_open(filename, mode, *args, **kwargs):
if mode == 'rb':
raise IOError(EUCLEAN, '-EUCLEAN fool!')
return open(filename, mode, *args, **kwargs)
with mock.patch('swift.obj.diskfile.open', my_open):
with self.assertRaises(DiskFileQuarantined) as err:
df.open()
self.assertEqual(
'Failed to open %s: [Errno %d] -EUCLEAN fool!'
% (df._data_file, EUCLEAN), str(err.exception))
def test_quarantine_hashdir_not_a_directory(self):
df, df_data = self._create_test_file(b'1234567890', account="abc",
container='123', obj='xyz')
hashdir = df._datadir
rmtree(hashdir)
with open(hashdir, 'w'):
pass
df = self.df_mgr.get_diskfile(self.existing_device, '0', 'abc', '123',
'xyz', policy=POLICIES.legacy)
self.assertRaises(DiskFileQuarantined, df.open)
# make sure the right thing got quarantined; the suffix dir should not
# have moved, as that could have many objects in it
self.assertFalse(os.path.exists(hashdir))
self.assertTrue(os.path.exists(os.path.dirname(hashdir)))
def test_quarantine_hashdir_not_listable(self):
for eno in (errno.ENODATA, EUCLEAN):
df, df_data = self._create_test_file(b'1234567890', account="abc",
container='123', obj='xyz')
hashdir = df._datadir
df = self.df_mgr.get_diskfile(
self.existing_device, '0', 'abc', '123', 'xyz',
policy=POLICIES.legacy)
with mock.patch('os.listdir',
side_effect=OSError(eno, 'nope')):
self.assertRaises(DiskFileQuarantined, df.open)
# make sure the right thing got quarantined; the suffix dir should
# not have moved, as that could have many objects in it
self.assertFalse(os.path.exists(hashdir))
self.assertTrue(os.path.exists(os.path.dirname(hashdir)))
def test_create_prealloc(self):
df = self.df_mgr.get_diskfile(self.existing_device, '0', 'abc', '123',
'xyz', policy=POLICIES.legacy)
with mock.patch("swift.obj.diskfile.fallocate") as fa:
with df.create(size=200) as writer:
used_fd = writer._fd
fa.assert_called_with(used_fd, 200)
def test_create_prealloc_oserror(self):
df = self.df_mgr.get_diskfile(self.existing_device, '0', 'abc', '123',
'xyz', policy=POLICIES.legacy)
for e in (errno.ENOSPC, errno.EDQUOT):
with mock.patch("swift.obj.diskfile.fallocate",
mock.MagicMock(side_effect=OSError(
e, os.strerror(e)))):
try:
with df.create(size=200):
pass
except DiskFileNoSpace:
pass
else:
self.fail("Expected exception DiskFileNoSpace")
# Other OSErrors must not be raised as DiskFileNoSpace
with mock.patch("swift.obj.diskfile.fallocate",
mock.MagicMock(side_effect=OSError(
errno.EACCES, os.strerror(errno.EACCES)))):
try:
with df.create(size=200):
pass
except OSError:
pass
else:
self.fail("Expected exception OSError")
def test_create_mkstemp_no_space(self):
df = self.df_mgr.get_diskfile(self.existing_device, '0', 'abc', '123',
'xyz', policy=POLICIES.legacy)
df.manager.use_linkat = False
for e in (errno.ENOSPC, errno.EDQUOT):
with mock.patch("swift.obj.diskfile.mkstemp",
mock.MagicMock(side_effect=OSError(
e, os.strerror(e)))):
with self.assertRaises(DiskFileNoSpace):
with df.create(size=200):
pass
# Other OSErrors must not be raised as DiskFileNoSpace
with mock.patch("swift.obj.diskfile.mkstemp",
mock.MagicMock(side_effect=OSError(
errno.EACCES, os.strerror(errno.EACCES)))):
with self.assertRaises(OSError) as raised:
with df.create(size=200):
pass
self.assertEqual(raised.exception.errno, errno.EACCES)
def test_create_close_oserror(self):
# This is a horrible hack so you can run this test in isolation.
# Some of the ctypes machinery calls os.close(), and that runs afoul
# of our mock.
with mock.patch.object(utils, '_sys_fallocate', None):
utils.disable_fallocate()
df = self.df_mgr.get_diskfile(self.existing_device, '0', 'abc',
'123', 'xyz', policy=POLICIES.legacy)
with mock.patch("swift.obj.diskfile.os.close",
mock.MagicMock(side_effect=OSError(
errno.EACCES, os.strerror(errno.EACCES)))):
with df.create(size=200):
pass
def test_write_metadata(self):
df, df_data = self._create_test_file(b'1234567890')
file_count = len(os.listdir(df._datadir))
timestamp = Timestamp.now().internal
metadata = {'X-Timestamp': timestamp, 'X-Object-Meta-test': 'data'}
df.write_metadata(metadata)
dl = os.listdir(df._datadir)
self.assertEqual(len(dl), file_count + 1)
exp_name = '%s.meta' % timestamp
self.assertIn(exp_name, set(dl))
def test_write_metadata_with_content_type(self):
# if metadata has content-type then its time should be in file name
df, df_data = self._create_test_file(b'1234567890')
file_count = len(os.listdir(df._datadir))
timestamp = Timestamp.now()
metadata = {'X-Timestamp': timestamp.internal,
'X-Object-Meta-test': 'data',
'Content-Type': 'foo',
'Content-Type-Timestamp': timestamp.internal}
df.write_metadata(metadata)
dl = os.listdir(df._datadir)
self.assertEqual(len(dl), file_count + 1)
exp_name = '%s+0.meta' % timestamp.internal
self.assertTrue(exp_name in set(dl),
'Expected file %s not found in %s' % (exp_name, dl))
def test_write_metadata_with_older_content_type(self):
# if metadata has content-type then its time should be in file name
ts_iter = make_timestamp_iter()
df, df_data = self._create_test_file(b'1234567890',
timestamp=next(ts_iter))
file_count = len(os.listdir(df._datadir))
timestamp = next(ts_iter)
timestamp2 = next(ts_iter)
metadata = {'X-Timestamp': timestamp2.internal,
'X-Object-Meta-test': 'data',
'Content-Type': 'foo',
'Content-Type-Timestamp': timestamp.internal}
df.write_metadata(metadata)
dl = os.listdir(df._datadir)
self.assertEqual(len(dl), file_count + 1, dl)
exp_name = '%s-%x.meta' % (timestamp2.internal,
timestamp2.raw - timestamp.raw)
self.assertTrue(exp_name in set(dl),
'Expected file %s not found in %s' % (exp_name, dl))
def test_write_metadata_with_content_type_removes_same_time_meta(self):
# a meta file without content-type should be cleaned up in favour of
# a meta file at same time with content-type
ts_iter = make_timestamp_iter()
df, df_data = self._create_test_file(b'1234567890',
timestamp=next(ts_iter))
file_count = len(os.listdir(df._datadir))
timestamp = next(ts_iter)
timestamp2 = next(ts_iter)
metadata = {'X-Timestamp': timestamp2.internal,
'X-Object-Meta-test': 'data'}
df.write_metadata(metadata)
metadata = {'X-Timestamp': timestamp2.internal,
'X-Object-Meta-test': 'data',
'Content-Type': 'foo',
'Content-Type-Timestamp': timestamp.internal}
df.write_metadata(metadata)
dl = os.listdir(df._datadir)
self.assertEqual(len(dl), file_count + 1, dl)
exp_name = '%s-%x.meta' % (timestamp2.internal,
timestamp2.raw - timestamp.raw)
self.assertTrue(exp_name in set(dl),
'Expected file %s not found in %s' % (exp_name, dl))
def test_write_metadata_with_content_type_removes_multiple_metas(self):
# a combination of a meta file without content-type and an older meta
# file with content-type should be cleaned up in favour of a meta file
# at newer time with content-type
ts_iter = make_timestamp_iter()
df, df_data = self._create_test_file(b'1234567890',
timestamp=next(ts_iter))
file_count = len(os.listdir(df._datadir))
timestamp = next(ts_iter)
timestamp2 = next(ts_iter)
metadata = {'X-Timestamp': timestamp2.internal,
'X-Object-Meta-test': 'data'}
df.write_metadata(metadata)
metadata = {'X-Timestamp': timestamp.internal,
'X-Object-Meta-test': 'data',
'Content-Type': 'foo',
'Content-Type-Timestamp': timestamp.internal}
df.write_metadata(metadata)
dl = os.listdir(df._datadir)
self.assertEqual(len(dl), file_count + 2, dl)
metadata = {'X-Timestamp': timestamp2.internal,
'X-Object-Meta-test': 'data',
'Content-Type': 'foo',
'Content-Type-Timestamp': timestamp.internal}
df.write_metadata(metadata)
dl = os.listdir(df._datadir)
self.assertEqual(len(dl), file_count + 1, dl)
exp_name = '%s-%x.meta' % (timestamp2.internal,
timestamp2.raw - timestamp.raw)
self.assertTrue(exp_name in set(dl),
'Expected file %s not found in %s' % (exp_name, dl))
def test_write_metadata_no_xattr(self):
timestamp = Timestamp.now().internal
metadata = {'X-Timestamp': timestamp, 'X-Object-Meta-test': 'data'}
def mock_setxattr(*args, **kargs):
error_num = errno.ENOTSUP if hasattr(errno, 'ENOTSUP') else \
errno.EOPNOTSUPP
raise IOError(error_num, "Operation not supported")
with mock.patch('xattr.setxattr', mock_setxattr):
self.assertRaises(
DiskFileXattrNotSupported,
diskfile.write_metadata, 'n/a', metadata)
def test_write_metadata_disk_full(self):
timestamp = Timestamp.now().internal
metadata = {'X-Timestamp': timestamp, 'X-Object-Meta-test': 'data'}
def mock_setxattr_ENOSPC(*args, **kargs):
raise IOError(errno.ENOSPC, "No space left on device")
def mock_setxattr_EDQUOT(*args, **kargs):
raise IOError(errno.EDQUOT, "Exceeded quota")
with mock.patch('xattr.setxattr', mock_setxattr_ENOSPC):
self.assertRaises(
DiskFileNoSpace,
diskfile.write_metadata, 'n/a', metadata)
with mock.patch('xattr.setxattr', mock_setxattr_EDQUOT):
self.assertRaises(
DiskFileNoSpace,
diskfile.write_metadata, 'n/a', metadata)
def _create_diskfile_dir(self, timestamp, policy, legacy_durable=False,
partition=0, next_part_power=None,
expect_error=False):
timestamp = Timestamp(timestamp)
df = self._simple_get_diskfile(account='a', container='c',
obj='o_%s' % policy,
policy=policy,
partition=partition,
next_part_power=next_part_power)
frag_index = None
if policy.policy_type == EC_POLICY:
frag_index = df._frag_index or 7
if expect_error:
with self.assertRaises(Exception):
write_diskfile(df, timestamp, frag_index=frag_index,
legacy_durable=legacy_durable)
else:
write_diskfile(df, timestamp, frag_index=frag_index,
legacy_durable=legacy_durable)
return df._datadir
def test_commit(self):
for policy in POLICIES:
timestamp = Timestamp.now()
df = self._simple_get_diskfile(account='a', container='c',
obj='o_%s' % policy,
policy=policy)
write_diskfile(df, timestamp, frag_index=2)
dl = os.listdir(df._datadir)
expected = [_make_datafilename(
timestamp, policy, frag_index=2, durable=True)]
self.assertEqual(len(dl), len(expected),
'Unexpected dir listing %s' % dl)
self.assertEqual(expected, dl)
if policy.policy_type == EC_POLICY:
self.assertEqual(2, df._frag_index)
def _do_test_write_cleanup(self, policy, legacy_durable=False):
# create first fileset as starting state
timestamp_1 = Timestamp.now()
datadir_1 = self._create_diskfile_dir(
timestamp_1, policy, legacy_durable)
# second write should clean up first fileset
timestamp_2 = Timestamp(time() + 1)
datadir_2 = self._create_diskfile_dir(timestamp_2, policy)
# sanity check
self.assertEqual(datadir_1, datadir_2)
dl = os.listdir(datadir_2)
expected = [_make_datafilename(
timestamp_2, policy, frag_index=2, durable=True)]
self.assertEqual(len(dl), len(expected),
'Unexpected dir listing %s' % dl)
self.assertEqual(expected, dl)
def test_write_cleanup(self):
for policy in POLICIES:
self._do_test_write_cleanup(policy)
def test_write_cleanup_legacy_durable(self):
for policy in POLICIES:
self._do_test_write_cleanup(policy, legacy_durable=True)
@mock.patch("swift.obj.diskfile.BaseDiskFileManager.cleanup_ondisk_files")
def test_write_cleanup_part_power_increase(self, mock_cleanup):
# Without next_part_power set we expect only one cleanup per DiskFile
# and no linking
for policy in POLICIES:
timestamp = Timestamp(time()).internal
df_dir = self._create_diskfile_dir(timestamp, policy)
self.assertEqual(1, mock_cleanup.call_count)
mock_cleanup.assert_called_once_with(df_dir)
mock_cleanup.reset_mock()
# With next_part_power set to part_power + 1 we expect two cleanups per
# DiskFile: first cleanup the current directory, but also cleanup the
# future directory where hardlinks are created
for policy in POLICIES:
timestamp = Timestamp(time()).internal
df_dir = self._create_diskfile_dir(
timestamp, policy, next_part_power=11)
self.assertEqual(2, mock_cleanup.call_count)
mock_cleanup.assert_any_call(df_dir)
# Make sure the translated path is also cleaned up
expected_dir = utils.replace_partition_in_path(
self.conf['devices'], df_dir, 11)
mock_cleanup.assert_any_call(expected_dir)
mock_cleanup.reset_mock()
# With next_part_power set to part_power we expect two cleanups per
# DiskFile: first cleanup the current directory, but also cleanup the
# previous old directory
for policy in POLICIES:
hash_path = utils.hash_path('a', 'c', 'o_%s' % policy)
partition = utils.get_partition_for_hash(hash_path, 10)
timestamp = Timestamp(time()).internal
df_dir = self._create_diskfile_dir(
timestamp, policy, partition=partition, next_part_power=10)
self.assertEqual(2, mock_cleanup.call_count)
mock_cleanup.assert_any_call(df_dir)
# Make sure the path using the old part power is also cleaned up
expected_dir = utils.replace_partition_in_path(
self.conf['devices'], df_dir, 9)
mock_cleanup.assert_any_call(expected_dir)
mock_cleanup.reset_mock()
@mock.patch.object(diskfile.BaseDiskFileManager, 'cleanup_ondisk_files',
side_effect=Exception)
def test_killed_before_cleanup(self, mock_cleanup):
for policy in POLICIES:
timestamp = Timestamp(time()).internal
hash_path = utils.hash_path('a', 'c', 'o_%s' % policy)
partition = utils.get_partition_for_hash(hash_path, 10)
df_dir = self._create_diskfile_dir(timestamp, policy,
partition=partition,
next_part_power=11,
expect_error=True)
expected_dir = utils.replace_partition_in_path(
self.conf['devices'], df_dir, 11)
self.assertEqual(os.listdir(df_dir), os.listdir(expected_dir))
def test_commit_fsync(self):
for policy in POLICIES:
df = self._simple_get_diskfile(account='a', container='c',
obj='o', policy=policy)
timestamp = Timestamp.now()
with df.create() as writer:
metadata = {
'ETag': 'bogus_etag',
'X-Timestamp': timestamp.internal,
'Content-Length': '0',
}
with mock.patch('swift.obj.diskfile.fsync') as mock_fsync:
writer.put(metadata)
self.assertEqual(1, mock_fsync.call_count)
writer.commit(timestamp)
self.assertEqual(1, mock_fsync.call_count)
if policy.policy_type == EC_POLICY:
self.assertIsInstance(mock_fsync.call_args[0][0], int)
def test_commit_ignores_cleanup_ondisk_files_error(self):
for policy in POLICIES:
# Check OSError from cleanup_ondisk_files is caught and ignored
mock_cleanup = mock.MagicMock(side_effect=OSError)
df = self._simple_get_diskfile(account='a', container='c',
obj='o_error', policy=policy)
timestamp = Timestamp.now()
with df.create() as writer:
metadata = {
'ETag': 'bogus_etag',
'X-Timestamp': timestamp.internal,
'Content-Length': '0',
}
writer.put(metadata)
with mock.patch(self._manager_mock(
'cleanup_ondisk_files', df), mock_cleanup):
writer.commit(timestamp)
expected = {
EC_POLICY: 1,
REPL_POLICY: 0,
}[policy.policy_type]
self.assertEqual(expected, mock_cleanup.call_count)
if expected:
self.assertIn(
'Problem cleaning up',
df.manager.logger.get_lines_for_level('error')[0])
expected = [_make_datafilename(
timestamp, policy, frag_index=2, durable=True)]
dl = os.listdir(df._datadir)
self.assertEqual(len(dl), len(expected),
'Unexpected dir listing %s' % dl)
self.assertEqual(expected, dl)
def test_number_calls_to_cleanup_ondisk_files_during_create(self):
# Check how many calls are made to cleanup_ondisk_files, and when,
# during put(), commit() sequence
for policy in POLICIES:
expected = {
EC_POLICY: (0, 1),
REPL_POLICY: (1, 0),
}[policy.policy_type]
df = self._simple_get_diskfile(account='a', container='c',
obj='o_error', policy=policy)
timestamp = Timestamp.now()
with df.create() as writer:
metadata = {
'ETag': 'bogus_etag',
'X-Timestamp': timestamp.internal,
'Content-Length': '0',
}
with mock.patch(self._manager_mock(
'cleanup_ondisk_files', df)) as mock_cleanup:
writer.put(metadata)
self.assertEqual(expected[0], mock_cleanup.call_count)
with mock.patch(self._manager_mock(
'cleanup_ondisk_files', df)) as mock_cleanup:
writer.commit(timestamp)
self.assertEqual(expected[1], mock_cleanup.call_count)
def test_number_calls_to_cleanup_ondisk_files_during_delete(self):
# Check how many calls are made to cleanup_ondisk_files, and when,
# for delete() and necessary prerequisite steps
for policy in POLICIES:
expected = {
EC_POLICY: (0, 1, 1),
REPL_POLICY: (1, 0, 1),
}[policy.policy_type]
df = self._simple_get_diskfile(account='a', container='c',
obj='o_error', policy=policy)
timestamp = Timestamp.now()
with df.create() as writer:
metadata = {
'ETag': 'bogus_etag',
'X-Timestamp': timestamp.internal,
'Content-Length': '0',
}
with mock.patch(self._manager_mock(
'cleanup_ondisk_files', df)) as mock_cleanup:
writer.put(metadata)
self.assertEqual(expected[0], mock_cleanup.call_count)
with mock.patch(self._manager_mock(
'cleanup_ondisk_files', df)) as mock_cleanup:
writer.commit(timestamp)
self.assertEqual(expected[1], mock_cleanup.call_count)
with mock.patch(self._manager_mock(
'cleanup_ondisk_files', df)) as mock_cleanup:
timestamp = Timestamp.now()
df.delete(timestamp)
self.assertEqual(expected[2], mock_cleanup.call_count)
def test_delete(self):
for policy in POLICIES:
if policy.policy_type == EC_POLICY:
metadata = {'X-Object-Sysmeta-Ec-Frag-Index': '1'}
fi = 1
else:
metadata = {}
fi = None
df = self._get_open_disk_file(policy=policy, frag_index=fi,
extra_metadata=metadata)
ts = Timestamp.now()
df.delete(ts)
exp_name = '%s.ts' % ts.internal
dl = os.listdir(df._datadir)
self.assertEqual(len(dl), 1)
self.assertIn(exp_name, set(dl))
# cleanup before next policy
os.unlink(os.path.join(df._datadir, exp_name))
def test_open_deleted(self):
df = self._get_open_disk_file()
ts = time()
df.delete(ts)
exp_name = '%s.ts' % str(Timestamp(ts).internal)
dl = os.listdir(df._datadir)
self.assertEqual(len(dl), 1)
self.assertIn(exp_name, set(dl))
df = self._simple_get_diskfile()
self.assertRaises(DiskFileDeleted, df.open)
def test_open_deleted_with_corrupt_tombstone(self):
df = self._get_open_disk_file()
ts = time()
df.delete(ts)
exp_name = '%s.ts' % str(Timestamp(ts).internal)
dl = os.listdir(df._datadir)
self.assertEqual(len(dl), 1)
self.assertIn(exp_name, set(dl))
# it's pickle-format, so removing the last byte is sufficient to
# corrupt it
ts_fullpath = os.path.join(df._datadir, exp_name)
self.assertTrue(os.path.exists(ts_fullpath)) # sanity check
meta_xattr = xattr.getxattr(ts_fullpath, "user.swift.metadata")
xattr.setxattr(ts_fullpath, "user.swift.metadata", meta_xattr[:-1])
df = self._simple_get_diskfile()
self.assertRaises(DiskFileNotExist, df.open)
self.assertFalse(os.path.exists(ts_fullpath))
def test_open_data_file_concurrently_unlinked(self):
# if a .data file is cleaned up while diskfile is being opened then
# DiskFileStateChanged can be raised
ts_data = self.ts()
ts_meta1 = self.ts()
self._create_test_file(b'1234567890', timestamp=ts_data)
df = self._simple_get_diskfile()
df.write_metadata({'X-Timestamp': ts_meta1.internal, 'test': 'me'})
with df.open():
self.assertEqual(ts_data, df.data_timestamp)
self.assertEqual(ts_meta1, df.timestamp)
df = self._simple_get_diskfile()
orig_get_ondisk_files = df._get_ondisk_files
def fake_get_ondisk_files(files, policy):
# once the datadir has been listed for the open(), unlink the .data
# file
file_info = orig_get_ondisk_files(files, policy)
os.unlink(file_info['data_file'])
return file_info
with mock.patch.object(df, '_get_ondisk_files', fake_get_ondisk_files):
with self.assertRaises(DiskFileStateChanged):
df.open()
def test_open_meta_file_concurrently_unlinked(self):
# if a .meta file is cleaned up while diskfile is being opened then
# DiskFileStateChanged can be raised
ts_data = self.ts()
ts_meta1 = self.ts()
ts_meta2 = self.ts()
self._create_test_file(b'1234567890', timestamp=ts_data)
df = self._simple_get_diskfile()
df.write_metadata({'X-Timestamp': ts_meta1.internal, 'test': 'me'})
with df.open():
self.assertEqual(ts_data, df.data_timestamp)
self.assertEqual(ts_meta1, df.timestamp)
df = self._simple_get_diskfile()
orig_get_ondisk_files = df._get_ondisk_files
def fake_get_ondisk_files(files, policy):
# once the datadir has been listed for the open(), replace the meta
# file with a newer one
file_info = orig_get_ondisk_files(files, policy)
os.unlink(file_info['meta_file'])
df.write_metadata(
{'X-Timestamp': ts_meta2.internal, 'test': 'me'})
return file_info
with mock.patch.object(df, '_get_ondisk_files', fake_get_ondisk_files):
with self.assertRaises(DiskFileStateChanged):
df.open()
df = self._simple_get_diskfile()
with df.open():
self.assertEqual(ts_data, df.data_timestamp)
self.assertEqual(ts_meta2, df.timestamp)
def test_from_audit_location(self):
df, df_data = self._create_test_file(
b'blah blah',
account='three', container='blind', obj='mice')
hashdir = df._datadir
df = self.df_mgr.get_diskfile_from_audit_location(
diskfile.AuditLocation(hashdir, self.existing_device, '0',
policy=POLICIES.default))
df.open()
self.assertEqual(df._name, '/three/blind/mice')
def test_from_audit_location_with_mismatched_hash(self):
df, df_data = self._create_test_file(
b'blah blah',
account='this', container='is', obj='right')
hashdir = df._datadir
datafilename = [f for f in os.listdir(hashdir)
if f.endswith('.data')][0]
datafile = os.path.join(hashdir, datafilename)
meta = diskfile.read_metadata(datafile)
meta['name'] = '/this/is/wrong'
diskfile.write_metadata(datafile, meta)
df = self.df_mgr.get_diskfile_from_audit_location(
diskfile.AuditLocation(hashdir, self.existing_device, '0',
policy=POLICIES.default))
self.assertRaises(DiskFileQuarantined, df.open)
def test_close_error(self):
def mock_handle_close_quarantine():
raise Exception("Bad")
df = self._get_open_disk_file(fsize=1024 * 1024 * 2, csize=1024)
reader = df.reader()
reader._handle_close_quarantine = mock_handle_close_quarantine
for chunk in reader:
pass
# close is called at the end of the iterator
self.assertIsNone(reader._fp)
error_lines = df._logger.get_lines_for_level('error')
self.assertEqual(len(error_lines), 1)
self.assertIn('close failure', error_lines[0])
self.assertIn('Bad', error_lines[0])
def test_mount_checking(self):
def _mock_cm(*args, **kwargs):
return False
with mock.patch("swift.common.constraints.check_mount", _mock_cm):
self.assertRaises(
DiskFileDeviceUnavailable,
self._get_open_disk_file,
mount_check=True)
def test_ondisk_search_loop_ts_meta_data(self):
df = self._simple_get_diskfile()
self._create_ondisk_file(df, b'', ext='.ts', timestamp=10)
self._create_ondisk_file(df, b'', ext='.ts', timestamp=9)
self._create_ondisk_file(df, b'', ext='.meta', timestamp=8)
self._create_ondisk_file(df, b'', ext='.meta', timestamp=7)
self._create_ondisk_file(df, b'B', ext='.data', timestamp=6)
self._create_ondisk_file(df, b'A', ext='.data', timestamp=5)
df = self._simple_get_diskfile()
with self.assertRaises(DiskFileDeleted) as raised:
df.open()
self.assertEqual(raised.exception.timestamp, Timestamp(10).internal)
def test_ondisk_search_loop_meta_ts_data(self):
df = self._simple_get_diskfile()
self._create_ondisk_file(df, b'', ext='.meta', timestamp=10)
self._create_ondisk_file(df, b'', ext='.meta', timestamp=9)
self._create_ondisk_file(df, b'', ext='.ts', timestamp=8)
self._create_ondisk_file(df, b'', ext='.ts', timestamp=7)
self._create_ondisk_file(df, b'B', ext='.data', timestamp=6)
self._create_ondisk_file(df, b'A', ext='.data', timestamp=5)
df = self._simple_get_diskfile()
with self.assertRaises(DiskFileDeleted) as raised:
df.open()
self.assertEqual(raised.exception.timestamp, Timestamp(8).internal)
def _test_ondisk_search_loop_meta_data_ts(self, legacy_durable=False):
df = self._simple_get_diskfile()
self._create_ondisk_file(df, b'', ext='.meta', timestamp=10)
self._create_ondisk_file(df, b'', ext='.meta', timestamp=9)
self._create_ondisk_file(
df, b'B', ext='.data', legacy_durable=legacy_durable, timestamp=8)
self._create_ondisk_file(
df, b'A', ext='.data', legacy_durable=legacy_durable, timestamp=7)
self._create_ondisk_file(df, b'', ext='.ts', timestamp=6)
self._create_ondisk_file(df, b'', ext='.ts', timestamp=5)
df = self._simple_get_diskfile()
with df.open():
self.assertIn('X-Timestamp', df._metadata)
self.assertEqual(df._metadata['X-Timestamp'],
Timestamp(10).internal)
self.assertNotIn('deleted', df._metadata)
def test_ondisk_search_loop_meta_data_ts(self):
self._test_ondisk_search_loop_meta_data_ts()
def test_ondisk_search_loop_meta_data_ts_legacy_durable(self):
self._test_ondisk_search_loop_meta_data_ts(legacy_durable=True)
def _test_ondisk_search_loop_multiple_meta_data(self,
legacy_durable=False):
df = self._simple_get_diskfile()
self._create_ondisk_file(df, b'', ext='.meta', timestamp=10,
metadata={'X-Object-Meta-User': 'user-meta'})
self._create_ondisk_file(df, b'', ext='.meta', timestamp=9,
ctype_timestamp=9,
metadata={'Content-Type': 'newest',
'X-Object-Meta-User': 'blah'})
self._create_ondisk_file(
df, b'B', ext='.data', legacy_durable=legacy_durable, timestamp=8,
metadata={'Content-Type': 'newer'})
self._create_ondisk_file(
df, b'A', ext='.data', legacy_durable=legacy_durable, timestamp=7,
metadata={'Content-Type': 'oldest'})
df = self._simple_get_diskfile()
with df.open():
self.assertTrue('X-Timestamp' in df._metadata)
self.assertEqual(df._metadata['X-Timestamp'],
Timestamp(10).internal)
self.assertTrue('Content-Type' in df._metadata)
self.assertEqual(df._metadata['Content-Type'], 'newest')
self.assertTrue('X-Object-Meta-User' in df._metadata)
self.assertEqual(df._metadata['X-Object-Meta-User'], 'user-meta')
def test_ondisk_search_loop_multiple_meta_data(self):
self._test_ondisk_search_loop_multiple_meta_data()
def test_ondisk_search_loop_multiple_meta_data_legacy_durable(self):
self._test_ondisk_search_loop_multiple_meta_data(legacy_durable=True)
def _test_ondisk_search_loop_stale_meta_data(self, legacy_durable=False):
df = self._simple_get_diskfile()
self._create_ondisk_file(df, b'', ext='.meta', timestamp=10,
metadata={'X-Object-Meta-User': 'user-meta'})
self._create_ondisk_file(df, b'', ext='.meta', timestamp=9,
ctype_timestamp=7,
metadata={'Content-Type': 'older',
'X-Object-Meta-User': 'blah'})
self._create_ondisk_file(
df, b'B', ext='.data', legacy_durable=legacy_durable, timestamp=8,
metadata={'Content-Type': 'newer'})
df = self._simple_get_diskfile()
with df.open():
self.assertTrue('X-Timestamp' in df._metadata)
self.assertEqual(df._metadata['X-Timestamp'],
Timestamp(10).internal)
self.assertTrue('Content-Type' in df._metadata)
self.assertEqual(df._metadata['Content-Type'], 'newer')
self.assertTrue('X-Object-Meta-User' in df._metadata)
self.assertEqual(df._metadata['X-Object-Meta-User'], 'user-meta')
def test_ondisk_search_loop_stale_meta_data(self):
self._test_ondisk_search_loop_stale_meta_data()
def test_ondisk_search_loop_stale_meta_data_legacy_durable(self):
self._test_ondisk_search_loop_stale_meta_data(legacy_durable=True)
def _test_ondisk_search_loop_data_ts_meta(self, legacy_durable=False):
df = self._simple_get_diskfile()
self._create_ondisk_file(
df, b'B', ext='.data', legacy_durable=legacy_durable, timestamp=10)
self._create_ondisk_file(
df, b'A', ext='.data', legacy_durable=legacy_durable, timestamp=9)
self._create_ondisk_file(df, b'', ext='.ts', timestamp=8)
self._create_ondisk_file(df, b'', ext='.ts', timestamp=7)
self._create_ondisk_file(df, b'', ext='.meta', timestamp=6)
self._create_ondisk_file(df, b'', ext='.meta', timestamp=5)
df = self._simple_get_diskfile()
with df.open():
self.assertIn('X-Timestamp', df._metadata)
self.assertEqual(df._metadata['X-Timestamp'],
Timestamp(10).internal)
self.assertNotIn('deleted', df._metadata)
def test_ondisk_search_loop_data_ts_meta(self):
self._test_ondisk_search_loop_data_ts_meta()
def test_ondisk_search_loop_data_ts_meta_legacy_durable(self):
self._test_ondisk_search_loop_data_ts_meta(legacy_durable=True)
def _test_ondisk_search_loop_wayward_files_ignored(self,
legacy_durable=False):
df = self._simple_get_diskfile()
self._create_ondisk_file(df, b'X', ext='.bar', timestamp=11)
self._create_ondisk_file(
df, b'B', ext='.data', legacy_durable=legacy_durable, timestamp=10)
self._create_ondisk_file(
df, b'A', ext='.data', legacy_durable=legacy_durable, timestamp=9)
self._create_ondisk_file(df, b'', ext='.ts', timestamp=8)
self._create_ondisk_file(df, b'', ext='.ts', timestamp=7)
self._create_ondisk_file(df, b'', ext='.meta', timestamp=6)
self._create_ondisk_file(df, b'', ext='.meta', timestamp=5)
df = self._simple_get_diskfile()
with df.open():
self.assertIn('X-Timestamp', df._metadata)
self.assertEqual(df._metadata['X-Timestamp'],
Timestamp(10).internal)
self.assertNotIn('deleted', df._metadata)
def test_ondisk_search_loop_wayward_files_ignored(self):
self._test_ondisk_search_loop_wayward_files_ignored()
def test_ondisk_search_loop_wayward_files_ignored_legacy_durable(self):
self._test_ondisk_search_loop_wayward_files_ignored(
legacy_durable=True)
def _test_ondisk_search_loop_listdir_error(self, legacy_durable=False):
df = self._simple_get_diskfile()
def mock_listdir_exp(*args, **kwargs):
raise OSError(errno.EACCES, os.strerror(errno.EACCES))
with mock.patch("os.listdir", mock_listdir_exp):
self._create_ondisk_file(df, b'X', ext='.bar', timestamp=11)
self._create_ondisk_file(df, b'B', ext='.data', timestamp=10,
legacy_durable=legacy_durable)
self._create_ondisk_file(df, b'A', ext='.data', timestamp=9,
legacy_durable=legacy_durable)
self._create_ondisk_file(df, b'', ext='.ts', timestamp=8)
self._create_ondisk_file(df, b'', ext='.ts', timestamp=7)
self._create_ondisk_file(df, b'', ext='.meta', timestamp=6)
self._create_ondisk_file(df, b'', ext='.meta', timestamp=5)
df = self._simple_get_diskfile()
self.assertRaises(DiskFileError, df.open)
def test_ondisk_search_loop_listdir_error(self):
self._test_ondisk_search_loop_listdir_error()
def test_ondisk_search_loop_listdir_error_legacy_durable(self):
self._test_ondisk_search_loop_listdir_error(legacy_durable=True)
def test_exception_in_handle_close_quarantine(self):
df = self._get_open_disk_file()
def blow_up():
raise Exception('a very special error')
reader = df.reader()
reader._handle_close_quarantine = blow_up
for _ in reader:
pass
reader.close()
log_lines = df._logger.get_lines_for_level('error')
self.assertIn('a very special error', log_lines[-1])
def test_diskfile_names(self):
df = self._simple_get_diskfile()
self.assertEqual(df.account, 'a')
self.assertEqual(df.container, 'c')
self.assertEqual(df.obj, 'o')
def test_diskfile_content_length_not_open(self):
df = self._simple_get_diskfile()
exc = None
try:
df.content_length
except DiskFileNotOpen as err:
exc = err
self.assertEqual(str(exc), '')
def test_diskfile_content_length_deleted(self):
df = self._get_open_disk_file()
ts = time()
df.delete(ts)
exp_name = '%s.ts' % str(Timestamp(ts).internal)
dl = os.listdir(df._datadir)
self.assertEqual(len(dl), 1)
self.assertIn(exp_name, set(dl))
df = self._simple_get_diskfile()
exc = None
try:
with df.open():
df.content_length
except DiskFileDeleted as err:
exc = err
self.assertEqual(str(exc), '')
def test_diskfile_content_length(self):
self._get_open_disk_file()
df = self._simple_get_diskfile()
with df.open():
if df.policy.policy_type == EC_POLICY:
expected = df.policy.pyeclib_driver.get_segment_info(
1024, df.policy.ec_segment_size)['fragment_size']
else:
expected = 1024
self.assertEqual(df.content_length, expected)
def test_diskfile_timestamp_not_open(self):
df = self._simple_get_diskfile()
exc = None
try:
df.timestamp
except DiskFileNotOpen as err:
exc = err
self.assertEqual(str(exc), '')
def test_diskfile_timestamp_deleted(self):
df = self._get_open_disk_file()
ts = time()
df.delete(ts)
exp_name = '%s.ts' % str(Timestamp(ts).internal)
dl = os.listdir(df._datadir)
self.assertEqual(len(dl), 1)
self.assertIn(exp_name, set(dl))
df = self._simple_get_diskfile()
exc = None
try:
with df.open():
df.timestamp
except DiskFileDeleted as err:
exc = err
self.assertEqual(str(exc), '')
def test_diskfile_timestamp(self):
ts_1 = self.ts()
self._get_open_disk_file(ts=ts_1.internal)
df = self._simple_get_diskfile()
with df.open():
self.assertEqual(df.timestamp, ts_1.internal)
ts_2 = self.ts()
df.write_metadata({'X-Timestamp': ts_2.internal})
with df.open():
self.assertEqual(df.timestamp, ts_2.internal)
def test_data_timestamp(self):
ts_1 = self.ts()
self._get_open_disk_file(ts=ts_1.internal)
df = self._simple_get_diskfile()
with df.open():
self.assertEqual(df.data_timestamp, ts_1.internal)
ts_2 = self.ts()
df.write_metadata({'X-Timestamp': ts_2.internal})
with df.open():
self.assertEqual(df.data_timestamp, ts_1.internal)
def test_data_timestamp_not_open(self):
df = self._simple_get_diskfile()
with self.assertRaises(DiskFileNotOpen):
df.data_timestamp
def test_content_type_and_timestamp(self):
ts_1 = self.ts()
self._get_open_disk_file(ts=ts_1.internal,
extra_metadata={'Content-Type': 'image/jpeg'})
df = self._simple_get_diskfile()
with df.open():
self.assertEqual(ts_1.internal, df.data_timestamp)
self.assertEqual(ts_1.internal, df.timestamp)
self.assertEqual(ts_1.internal, df.content_type_timestamp)
self.assertEqual('image/jpeg', df.content_type)
ts_2 = self.ts()
ts_3 = self.ts()
df.write_metadata({'X-Timestamp': ts_3.internal,
'Content-Type': 'image/gif',
'Content-Type-Timestamp': ts_2.internal})
with df.open():
self.assertEqual(ts_1.internal, df.data_timestamp)
self.assertEqual(ts_3.internal, df.timestamp)
self.assertEqual(ts_2.internal, df.content_type_timestamp)
self.assertEqual('image/gif', df.content_type)
def test_content_type_timestamp_not_open(self):
df = self._simple_get_diskfile()
with self.assertRaises(DiskFileNotOpen):
df.content_type_timestamp
def test_content_type_not_open(self):
df = self._simple_get_diskfile()
with self.assertRaises(DiskFileNotOpen):
df.content_type
def _do_test_durable_timestamp(self, legacy_durable):
ts_1 = self.ts()
df = self._simple_get_diskfile(frag_index=2)
write_diskfile(df, ts_1, legacy_durable=legacy_durable)
# get a new instance of the diskfile to ensure timestamp variable is
# set by the open() and not just the write operations
df = self._simple_get_diskfile(frag_index=2)
with df.open():
self.assertEqual(df.durable_timestamp, ts_1.internal)
# verify durable timestamp does not change when metadata is written
ts_2 = self.ts()
df.write_metadata({'X-Timestamp': ts_2.internal})
with df.open():
self.assertEqual(df.durable_timestamp, ts_1.internal)
def test_durable_timestamp(self):
self._do_test_durable_timestamp(False)
def test_durable_timestamp_not_open(self):
df = self._simple_get_diskfile()
with self.assertRaises(DiskFileNotOpen):
df.durable_timestamp
def test_durable_timestamp_no_data_file(self):
df = self._get_open_disk_file(self.ts().internal)
for f in os.listdir(df._datadir):
if f.endswith('.data'):
os.unlink(os.path.join(df._datadir, f))
df = self._simple_get_diskfile()
with self.assertRaises(DiskFileNotExist):
df.open()
# open() was attempted, but no data file so expect None
self.assertIsNone(df.durable_timestamp)
def test_error_in_cleanup_ondisk_files(self):
def mock_cleanup(*args, **kwargs):
raise OSError()
df = self._get_open_disk_file()
file_count = len(os.listdir(df._datadir))
ts = time()
with mock.patch(
self._manager_mock('cleanup_ondisk_files'), mock_cleanup):
# Expect to swallow the OSError
df.delete(ts)
exp_name = '%s.ts' % str(Timestamp(ts).internal)
dl = os.listdir(df._datadir)
self.assertEqual(len(dl), file_count + 1)
self.assertIn(exp_name, set(dl))
def _system_can_zero_copy(self):
if not splice.available:
return False
try:
utils.get_md5_socket()
except IOError:
return False
return True
def test_zero_copy_cache_dropping(self):
if not self._system_can_zero_copy():
raise unittest.SkipTest("zero-copy support is missing")
self.conf['splice'] = 'on'
self.conf['keep_cache_size'] = 16384
self.conf['disk_chunk_size'] = 4096
df = self._get_open_disk_file(fsize=163840)
reader = df.reader()
self.assertTrue(reader.can_zero_copy_send())
with mock.patch("swift.obj.diskfile.drop_buffer_cache") as dbc:
with mock.patch("swift.obj.diskfile.DROP_CACHE_WINDOW", 4095):
with open('/dev/null', 'w') as devnull:
reader.zero_copy_send(devnull.fileno())
if df.policy.policy_type == EC_POLICY:
expected = 4 + 1
else:
expected = (4 * 10) + 1
self.assertEqual(len(dbc.mock_calls), expected)
def test_zero_copy_turns_off_when_md5_sockets_not_supported(self):
if not self._system_can_zero_copy():
raise unittest.SkipTest("zero-copy support is missing")
df_mgr = self.df_router[POLICIES.default]
self.conf['splice'] = 'on'
with mock.patch('swift.obj.diskfile.get_md5_socket') as mock_md5sock:
mock_md5sock.side_effect = IOError(
errno.EAFNOSUPPORT, "MD5 socket busted")
df = self._get_open_disk_file(fsize=128)
reader = df.reader()
self.assertFalse(reader.can_zero_copy_send())
log_lines = df_mgr.logger.get_lines_for_level('warning')
self.assertIn('MD5 sockets', log_lines[-1])
def test_tee_to_md5_pipe_length_mismatch(self):
if not self._system_can_zero_copy():
raise unittest.SkipTest("zero-copy support is missing")
self.conf['splice'] = 'on'
df = self._get_open_disk_file(fsize=16385)
reader = df.reader()
self.assertTrue(reader.can_zero_copy_send())
with mock.patch('swift.obj.diskfile.tee') as mock_tee:
mock_tee.side_effect = lambda _1, _2, _3, cnt: cnt - 1
with open('/dev/null', 'w') as devnull:
exc_re = (r'tee\(\) failed: tried to move \d+ bytes, but only '
r'moved -?\d+')
try:
reader.zero_copy_send(devnull.fileno())
except Exception as e:
self.assertTrue(re.match(exc_re, str(e)))
else:
self.fail('Expected Exception was not raised')
def test_splice_to_wsockfd_blocks(self):
if not self._system_can_zero_copy():
raise unittest.SkipTest("zero-copy support is missing")
self.conf['splice'] = 'on'
df = self._get_open_disk_file(fsize=16385)
reader = df.reader()
self.assertTrue(reader.can_zero_copy_send())
def _run_test():
# Set up mock of `splice`
splice_called = [False] # State hack
def fake_splice(fd_in, off_in, fd_out, off_out, len_, flags):
if fd_out == devnull.fileno() and not splice_called[0]:
splice_called[0] = True
err = errno.EWOULDBLOCK
raise IOError(err, os.strerror(err))
return splice(fd_in, off_in, fd_out, off_out,
len_, flags)
mock_splice.side_effect = fake_splice
# Set up mock of `trampoline`
# There are 2 reasons to mock this:
#
# - We want to ensure it's called with the expected arguments at
# least once
# - When called with our write FD (which points to `/dev/null`), we
# can't actually call `trampoline`, because adding such FD to an
# `epoll` handle results in `EPERM`
def fake_trampoline(fd, read=None, write=None, timeout=None,
timeout_exc=timeout.Timeout,
mark_as_closed=None):
if write and fd == devnull.fileno():
return
else:
hubs.trampoline(fd, read=read, write=write,
timeout=timeout, timeout_exc=timeout_exc,
mark_as_closed=mark_as_closed)
mock_trampoline.side_effect = fake_trampoline
reader.zero_copy_send(devnull.fileno())
# Assert the end of `zero_copy_send` was reached
self.assertTrue(mock_close.called)
# Assert there was at least one call to `trampoline` waiting for
# `write` access to the output FD
mock_trampoline.assert_any_call(devnull.fileno(), write=True)
# Assert at least one call to `splice` with the output FD we expect
for call in mock_splice.call_args_list:
args = call[0]
if args[2] == devnull.fileno():
break
else:
self.fail('`splice` not called with expected arguments')
with mock.patch('swift.obj.diskfile.splice') as mock_splice:
with mock.patch.object(
reader, 'close', side_effect=reader.close) as mock_close:
with open('/dev/null', 'w') as devnull:
with mock.patch('swift.obj.diskfile.trampoline') as \
mock_trampoline:
_run_test()
def test_create_unlink_cleanup_DiskFileNoSpace(self):
# Test cleanup when DiskFileNoSpace() is raised.
df = self.df_mgr.get_diskfile(self.existing_device, '0', 'abc', '123',
'xyz', policy=POLICIES.legacy)
df.manager.use_linkat = False
_m_fallocate = mock.MagicMock(side_effect=OSError(errno.ENOSPC,
os.strerror(errno.ENOSPC)))
_m_unlink = mock.Mock()
with mock.patch("swift.obj.diskfile.fallocate", _m_fallocate):
with mock.patch("os.unlink", _m_unlink):
try:
with df.create(size=100):
pass
except DiskFileNoSpace:
pass
else:
self.fail("Expected exception DiskFileNoSpace")
self.assertTrue(_m_fallocate.called)
self.assertTrue(_m_unlink.called)
self.assertNotIn('error', self.logger.all_log_lines())
def test_create_unlink_cleanup_renamer_fails(self):
# Test cleanup when renamer fails
_m_renamer = mock.MagicMock(side_effect=OSError(errno.ENOENT,
os.strerror(errno.ENOENT)))
_m_unlink = mock.Mock()
df = self._simple_get_diskfile()
df.manager.use_linkat = False
data = b'0' * 100
metadata = {
'ETag': md5(data).hexdigest(),
'X-Timestamp': Timestamp.now().internal,
'Content-Length': str(100),
}
with mock.patch("swift.obj.diskfile.renamer", _m_renamer):
with mock.patch("os.unlink", _m_unlink):
try:
with df.create(size=100) as writer:
writer.write(data)
writer.put(metadata)
except OSError:
pass
else:
self.fail("Expected OSError exception")
self.assertFalse(writer._put_succeeded)
self.assertTrue(_m_renamer.called)
self.assertTrue(_m_unlink.called)
self.assertNotIn('error', self.logger.all_log_lines())
def test_create_unlink_cleanup_logging(self):
# Test logging of os.unlink() failures.
df = self.df_mgr.get_diskfile(self.existing_device, '0', 'abc', '123',
'xyz', policy=POLICIES.legacy)
df.manager.use_linkat = False
_m_fallocate = mock.MagicMock(side_effect=OSError(errno.ENOSPC,
os.strerror(errno.ENOSPC)))
_m_unlink = mock.MagicMock(side_effect=OSError(errno.ENOENT,
os.strerror(errno.ENOENT)))
with mock.patch("swift.obj.diskfile.fallocate", _m_fallocate):
with mock.patch("os.unlink", _m_unlink):
try:
with df.create(size=100):
pass
except DiskFileNoSpace:
pass
else:
self.fail("Expected exception DiskFileNoSpace")
self.assertTrue(_m_fallocate.called)
self.assertTrue(_m_unlink.called)
error_lines = self.logger.get_lines_for_level('error')
for line in error_lines:
self.assertTrue(line.startswith("Error removing tempfile:"))
@requires_o_tmpfile_support_in_tmp
def test_get_tempfile_use_linkat_os_open_called(self):
df = self._simple_get_diskfile()
self.assertTrue(df.manager.use_linkat)
_m_mkstemp = mock.MagicMock()
_m_os_open = mock.Mock(return_value=12345)
_m_mkc = mock.Mock()
with mock.patch("swift.obj.diskfile.mkstemp", _m_mkstemp):
with mock.patch("swift.obj.diskfile.os.open", _m_os_open):
with mock.patch("swift.obj.diskfile.makedirs_count", _m_mkc):
writer = df.writer()
fd, tmppath = writer._get_tempfile()
self.assertTrue(_m_mkc.called)
flags = O_TMPFILE | os.O_WRONLY
_m_os_open.assert_called_once_with(df._datadir, flags)
self.assertIsNone(tmppath)
self.assertEqual(fd, 12345)
self.assertFalse(_m_mkstemp.called)
@requires_o_tmpfile_support_in_tmp
def test_get_tempfile_fallback_to_mkstemp(self):
df = self._simple_get_diskfile()
df._logger = debug_logger()
self.assertTrue(df.manager.use_linkat)
for err in (errno.EOPNOTSUPP, errno.EISDIR, errno.EINVAL):
df.manager.use_linkat = True
_m_open = mock.Mock(side_effect=OSError(err, os.strerror(err)))
_m_mkstemp = mock.MagicMock(return_value=(0, "blah"))
_m_mkc = mock.Mock()
with mock.patch("swift.obj.diskfile.os.open", _m_open):
with mock.patch("swift.obj.diskfile.mkstemp", _m_mkstemp):
with mock.patch("swift.obj.diskfile.makedirs_count",
_m_mkc):
writer = df.writer()
fd, tmppath = writer._get_tempfile()
self.assertTrue(_m_mkc.called)
# Fallback should succeed and mkstemp() should be called.
self.assertTrue(_m_mkstemp.called)
self.assertEqual(tmppath, "blah")
# Once opening file with O_TMPFILE has failed,
# failure is cached to not try again
self.assertFalse(df.manager.use_linkat)
# Now that we try to use O_TMPFILE all the time, log at debug
# instead of warning
log = df.manager.logger.get_lines_for_level('warning')
self.assertFalse(log)
log = df.manager.logger.get_lines_for_level('debug')
self.assertGreater(len(log), 0)
self.assertTrue('O_TMPFILE' in log[-1])
@requires_o_tmpfile_support_in_tmp
def test_get_tmpfile_os_open_other_exceptions_are_raised(self):
df = self._simple_get_diskfile()
_m_open = mock.Mock(side_effect=OSError(errno.ENOSPC,
os.strerror(errno.ENOSPC)))
_m_mkstemp = mock.MagicMock()
_m_mkc = mock.Mock()
with mock.patch("swift.obj.diskfile.os.open", _m_open):
with mock.patch("swift.obj.diskfile.mkstemp", _m_mkstemp):
with mock.patch("swift.obj.diskfile.makedirs_count", _m_mkc):
try:
writer = df.writer()
fd, tmppath = writer._get_tempfile()
except OSError as err:
self.assertEqual(err.errno, errno.ENOSPC)
else:
self.fail("Expecting ENOSPC")
self.assertTrue(_m_mkc.called)
# mkstemp() should not be invoked.
self.assertFalse(_m_mkstemp.called)
@requires_o_tmpfile_support_in_tmp
def test_create_use_linkat_renamer_not_called(self):
df = self._simple_get_diskfile()
data = b'0' * 100
metadata = {
'ETag': md5(data).hexdigest(),
'X-Timestamp': Timestamp.now().internal,
'Content-Length': str(100),
}
_m_renamer = mock.Mock()
with mock.patch("swift.obj.diskfile.renamer", _m_renamer):
with df.create(size=100) as writer:
writer.write(data)
writer.put(metadata)
self.assertTrue(writer._put_succeeded)
self.assertFalse(_m_renamer.called)
@patch_policies(test_policies)
class TestDiskFile(DiskFileMixin, unittest.TestCase):
mgr_cls = diskfile.DiskFileManager
@patch_policies(with_ec_default=True)
class TestECDiskFile(DiskFileMixin, unittest.TestCase):
mgr_cls = diskfile.ECDiskFileManager
def _test_commit_raises_DiskFileError_for_rename_error(self, fake_err):
df = self._simple_get_diskfile(account='a', container='c',
obj='o_rename_err',
policy=POLICIES.default)
timestamp = Timestamp.now()
with df.create() as writer:
metadata = {
'ETag': 'bogus_etag',
'X-Timestamp': timestamp.internal,
'Content-Length': '0',
}
writer.put(metadata)
with mock.patch('swift.obj.diskfile.os.rename',
side_effect=fake_err):
with self.assertRaises(DiskFileError) as cm:
writer.commit(timestamp)
dl = os.listdir(df._datadir)
datafile = _make_datafilename(
timestamp, POLICIES.default, frag_index=2, durable=False)
self.assertEqual([datafile], dl)
return df, cm.exception
def test_commit_raises_DiskFileError_for_rename_ENOSPC_IOError(self):
df, exc = self._test_commit_raises_DiskFileError_for_rename_error(
IOError(errno.ENOSPC, 'ENOSPC'))
self.assertIsInstance(exc, DiskFileNoSpace)
self.assertIn('No space left on device', str(exc))
self.assertIn('No space left on device',
df.manager.logger.get_lines_for_level('error')[0])
self.assertFalse(df.manager.logger.get_lines_for_level('error')[1:])
def test_commit_raises_DiskFileError_for_rename_EDQUOT_IOError(self):
df, exc = self._test_commit_raises_DiskFileError_for_rename_error(
IOError(errno.EDQUOT, 'EDQUOT'))
self.assertIsInstance(exc, DiskFileNoSpace)
self.assertIn('No space left on device', str(exc))
self.assertIn('No space left on device',
df.manager.logger.get_lines_for_level('error')[0])
self.assertFalse(df.manager.logger.get_lines_for_level('error')[1:])
def test_commit_raises_DiskFileError_for_rename_other_IOError(self):
df, exc = self._test_commit_raises_DiskFileError_for_rename_error(
IOError(21, 'Some other IO Error'))
self.assertIn('Problem making data file durable', str(exc))
self.assertIn('Problem making data file durable',
df.manager.logger.get_lines_for_level('error')[0])
self.assertFalse(df.manager.logger.get_lines_for_level('error')[1:])
def test_commit_raises_DiskFileError_for_rename_OSError(self):
df, exc = self._test_commit_raises_DiskFileError_for_rename_error(
OSError(100, 'Some Error'))
self.assertIn('Problem making data file durable', str(exc))
self.assertIn('Problem making data file durable',
df.manager.logger.get_lines_for_level('error')[0])
self.assertFalse(df.manager.logger.get_lines_for_level('error')[1:])
def _test_commit_raises_DiskFileError_for_fsync_dir_errors(self, fake_err):
df = self._simple_get_diskfile(account='a', container='c',
obj='o_fsync_dir_err',
policy=POLICIES.default)
timestamp = Timestamp.now()
with df.create() as writer:
metadata = {
'ETag': 'bogus_etag',
'X-Timestamp': timestamp.internal,
'Content-Length': '0',
}
writer.put(metadata)
with mock.patch('swift.obj.diskfile.fsync_dir',
side_effect=fake_err):
with self.assertRaises(DiskFileError) as cm:
writer.commit(timestamp)
dl = os.listdir(df._datadir)
datafile = _make_datafilename(
timestamp, POLICIES.default, frag_index=2, durable=True)
self.assertEqual([datafile], dl)
self.assertIn('Problem making data file durable', str(cm.exception))
self.assertIn('Problem making data file durable',
df.manager.logger.get_lines_for_level('error')[0])
self.assertFalse(df.manager.logger.get_lines_for_level('error')[1:])
def test_commit_raises_DiskFileError_for_fsync_dir_IOError(self):
self._test_commit_raises_DiskFileError_for_fsync_dir_errors(
IOError(21, 'Some IO Error'))
def test_commit_raises_DiskFileError_for_fsync_dir_OSError(self):
self._test_commit_raises_DiskFileError_for_fsync_dir_errors(
OSError(100, 'Some Error'))
def test_data_file_has_frag_index(self):
policy = POLICIES.default
for good_value in (0, '0', 2, '2', 13, '13'):
# frag_index set by constructor arg
ts = self.ts()
expected = [_make_datafilename(
ts, policy, good_value, durable=True)]
df = self._get_open_disk_file(ts=ts, policy=policy,
frag_index=good_value)
self.assertEqual(expected, sorted(os.listdir(df._datadir)))
# frag index should be added to object sysmeta
actual = df.get_metadata().get('X-Object-Sysmeta-Ec-Frag-Index')
self.assertEqual(int(good_value), int(actual))
# metadata value overrides the constructor arg
ts = self.ts()
expected = [_make_datafilename(
ts, policy, good_value, durable=True)]
meta = {'X-Object-Sysmeta-Ec-Frag-Index': good_value}
df = self._get_open_disk_file(ts=ts, policy=policy,
frag_index='3',
extra_metadata=meta)
self.assertEqual(expected, sorted(os.listdir(df._datadir)))
actual = df.get_metadata().get('X-Object-Sysmeta-Ec-Frag-Index')
self.assertEqual(int(good_value), int(actual))
# metadata value alone is sufficient
ts = self.ts()
expected = [_make_datafilename(
ts, policy, good_value, durable=True)]
meta = {'X-Object-Sysmeta-Ec-Frag-Index': good_value}
df = self._get_open_disk_file(ts=ts, policy=policy,
frag_index=None,
extra_metadata=meta)
self.assertEqual(expected, sorted(os.listdir(df._datadir)))
actual = df.get_metadata().get('X-Object-Sysmeta-Ec-Frag-Index')
self.assertEqual(int(good_value), int(actual))
def test_sysmeta_frag_index_is_immutable(self):
# the X-Object-Sysmeta-Ec-Frag-Index should *only* be set when
# the .data file is written.
policy = POLICIES.default
orig_frag_index = 13
# frag_index set by constructor arg
ts = self.ts()
expected = [_make_datafilename(
ts, policy, frag_index=orig_frag_index, durable=True)]
df = self._get_open_disk_file(ts=ts, policy=policy, obj_name='my_obj',
frag_index=orig_frag_index)
self.assertEqual(expected, sorted(os.listdir(df._datadir)))
# frag index should be added to object sysmeta
actual = df.get_metadata().get('X-Object-Sysmeta-Ec-Frag-Index')
self.assertEqual(int(orig_frag_index), int(actual))
# open the same diskfile with no frag_index passed to constructor
df = self.df_router[policy].get_diskfile(
self.existing_device, 0, 'a', 'c', 'my_obj', policy=policy,
frag_index=None)
df.open()
actual = df.get_metadata().get('X-Object-Sysmeta-Ec-Frag-Index')
self.assertEqual(int(orig_frag_index), int(actual))
# write metadata to a meta file
ts = self.ts()
metadata = {'X-Timestamp': ts.internal,
'X-Object-Meta-Fruit': 'kiwi'}
df.write_metadata(metadata)
# sanity check we did write a meta file
expected.append('%s.meta' % ts.internal)
actual_files = sorted(os.listdir(df._datadir))
self.assertEqual(expected, actual_files)
# open the same diskfile, check frag index is unchanged
df = self.df_router[policy].get_diskfile(
self.existing_device, 0, 'a', 'c', 'my_obj', policy=policy,
frag_index=None)
df.open()
# sanity check we have read the meta file
self.assertEqual(ts, df.get_metadata().get('X-Timestamp'))
self.assertEqual('kiwi', df.get_metadata().get('X-Object-Meta-Fruit'))
# check frag index sysmeta is unchanged
actual = df.get_metadata().get('X-Object-Sysmeta-Ec-Frag-Index')
self.assertEqual(int(orig_frag_index), int(actual))
# attempt to overwrite frag index sysmeta
ts = self.ts()
metadata = {'X-Timestamp': ts.internal,
'X-Object-Sysmeta-Ec-Frag-Index': 99,
'X-Object-Meta-Fruit': 'apple'}
df.write_metadata(metadata)
# open the same diskfile, check frag index is unchanged
df = self.df_router[policy].get_diskfile(
self.existing_device, 0, 'a', 'c', 'my_obj', policy=policy,
frag_index=None)
df.open()
# sanity check we have read the meta file
self.assertEqual(ts, df.get_metadata().get('X-Timestamp'))
self.assertEqual('apple', df.get_metadata().get('X-Object-Meta-Fruit'))
actual = df.get_metadata().get('X-Object-Sysmeta-Ec-Frag-Index')
self.assertEqual(int(orig_frag_index), int(actual))
def test_data_file_errors_bad_frag_index(self):
policy = POLICIES.default
df_mgr = self.df_router[policy]
for bad_value in ('foo', '-2', -2, '3.14', 3.14, '14', 14, '999'):
# check that bad frag_index set by constructor arg raises error
# as soon as diskfile is constructed, before data is written
self.assertRaises(DiskFileError, self._simple_get_diskfile,
policy=policy, frag_index=bad_value)
# bad frag_index set by metadata value
# (drive-by check that it is ok for constructor arg to be None)
df = df_mgr.get_diskfile(self.existing_device, '0', 'a', 'c', 'o',
policy=policy, frag_index=None)
ts = self.ts()
meta = {'X-Object-Sysmeta-Ec-Frag-Index': bad_value,
'X-Timestamp': ts.internal,
'Content-Length': 0,
'Etag': MD5_OF_EMPTY_STRING,
'Content-Type': 'plain/text'}
with df.create() as writer:
try:
writer.put(meta)
self.fail('Expected DiskFileError for frag_index %s'
% bad_value)
except DiskFileError:
pass
# bad frag_index set by metadata value overrides ok constructor arg
df = df_mgr.get_diskfile(self.existing_device, '0', 'a', 'c', 'o',
policy=policy, frag_index=2)
ts = self.ts()
meta = {'X-Object-Sysmeta-Ec-Frag-Index': bad_value,
'X-Timestamp': ts.internal,
'Content-Length': 0,
'Etag': MD5_OF_EMPTY_STRING,
'Content-Type': 'plain/text'}
with df.create() as writer:
try:
writer.put(meta)
self.fail('Expected DiskFileError for frag_index %s'
% bad_value)
except DiskFileError:
pass
def test_purge_one_fragment_index(self):
ts = self.ts()
for frag_index in (1, 2):
df = self._simple_get_diskfile(frag_index=frag_index)
write_diskfile(df, ts)
ts_meta = self.ts()
df.write_metadata({
'X-Timestamp': ts_meta.internal,
'X-Object-Meta-Delete': 'me'
})
# sanity
self.assertEqual(sorted(os.listdir(df._datadir)), [
ts.internal + '#1#d.data',
ts.internal + '#2#d.data',
ts_meta.internal + '.meta',
])
df.purge(ts, 2)
# by default .meta file is not purged
self.assertEqual(sorted(os.listdir(df._datadir)), [
ts.internal + '#1#d.data',
ts_meta.internal + '.meta',
])
def test_purge_final_fragment_index_and_meta(self):
ts = self.ts()
df = self._simple_get_diskfile(frag_index=1)
write_diskfile(df, ts)
ts_meta = self.ts()
df.write_metadata({
'X-Timestamp': ts_meta.internal,
'X-Object-Meta-Delete': 'me',
})
# sanity
self.assertEqual(sorted(os.listdir(df._datadir)), [
ts.internal + '#1#d.data',
ts_meta.internal + '.meta',
])
df.purge(ts, 1, meta_timestamp=ts_meta)
self.assertFalse(os.path.exists(df._datadir))
def test_purge_final_fragment_index_and_not_meta(self):
ts = self.ts()
df = self._simple_get_diskfile(frag_index=1)
write_diskfile(df, ts)
ts_meta = self.ts()
df.write_metadata({
'X-Timestamp': ts_meta.internal,
'X-Object-Meta-Delete': 'me',
})
# sanity
self.assertEqual(sorted(os.listdir(df._datadir)), [
ts.internal + '#1#d.data',
ts_meta.internal + '.meta',
])
df.purge(ts, 1, meta_timestamp=ts)
self.assertEqual(sorted(os.listdir(df._datadir)), [
ts_meta.internal + '.meta',
])
def test_purge_last_fragment_index(self):
ts = self.ts()
frag_index = 0
df = self._simple_get_diskfile(frag_index=frag_index)
write_diskfile(df, ts)
# sanity
self.assertEqual(os.listdir(df._datadir), [
ts.internal + '#0#d.data',
])
df.purge(ts, frag_index)
self.assertFalse(os.path.exists(df._datadir))
def test_purge_last_fragment_index_legacy_durable(self):
# a legacy durable file doesn't get purged in case another fragment is
# relying on it for durability
ts = self.ts()
frag_index = 0
df = self._simple_get_diskfile(frag_index=frag_index)
write_diskfile(df, ts, legacy_durable=True)
# sanity
self.assertEqual(sorted(os.listdir(df._datadir)), [
ts.internal + '#0.data',
ts.internal + '.durable',
])
df.purge(ts, frag_index)
self.assertEqual(sorted(os.listdir(df._datadir)), [
ts.internal + '.durable',
])
def test_purge_non_existent_fragment_index(self):
ts = self.ts()
frag_index = 7
df = self._simple_get_diskfile(frag_index=frag_index)
write_diskfile(df, ts)
# sanity
self.assertEqual(os.listdir(df._datadir), [
ts.internal + '#7#d.data',
])
df.purge(ts, 3)
# no effect
self.assertEqual(os.listdir(df._datadir), [
ts.internal + '#7#d.data',
])
def test_purge_old_timestamp_frag_index(self):
old_ts = self.ts()
ts = self.ts()
frag_index = 1
df = self._simple_get_diskfile(frag_index=frag_index)
write_diskfile(df, ts)
# sanity
self.assertEqual(os.listdir(df._datadir), [
ts.internal + '#1#d.data',
])
df.purge(old_ts, 1)
# no effect
self.assertEqual(os.listdir(df._datadir), [
ts.internal + '#1#d.data',
])
def test_purge_tombstone(self):
ts = self.ts()
df = self._simple_get_diskfile(frag_index=3)
df.delete(ts)
# sanity
self.assertEqual(sorted(os.listdir(df._datadir)), [
ts.internal + '.ts',
])
df.purge(ts, 3)
self.assertFalse(os.path.exists(df._datadir))
def test_purge_without_frag(self):
ts = self.ts()
df = self._simple_get_diskfile()
df.delete(ts)
# sanity
self.assertEqual(sorted(os.listdir(df._datadir)), [
ts.internal + '.ts',
])
df.purge(ts, None)
self.assertEqual(sorted(os.listdir(df._datadir)), [])
def test_purge_old_tombstone(self):
old_ts = self.ts()
ts = self.ts()
df = self._simple_get_diskfile(frag_index=5)
df.delete(ts)
# sanity
self.assertEqual(sorted(os.listdir(df._datadir)), [
ts.internal + '.ts',
])
df.purge(old_ts, 5)
# no effect
self.assertEqual(sorted(os.listdir(df._datadir)), [
ts.internal + '.ts',
])
def test_purge_already_removed(self):
df = self._simple_get_diskfile(frag_index=6)
df.purge(self.ts(), 6) # no errors
# sanity
os.makedirs(df._datadir)
self.assertEqual(sorted(os.listdir(df._datadir)), [])
df.purge(self.ts(), 6)
# the directory was empty and has been removed
self.assertFalse(os.path.exists(df._datadir))
def _do_test_open_most_recent_durable(self, legacy_durable):
policy = POLICIES.default
df_mgr = self.df_router[policy]
df = df_mgr.get_diskfile(self.existing_device, '0',
'a', 'c', 'o', policy=policy)
ts = self.ts()
write_diskfile(df, ts, frag_index=3,
legacy_durable=legacy_durable)
metadata = {
'ETag': md5('test data').hexdigest(),
'X-Timestamp': ts.internal,
'Content-Length': str(len('test data')),
'X-Object-Sysmeta-Ec-Etag': 'fake-etag',
'X-Object-Sysmeta-Ec-Frag-Index': '3',
}
# add some .meta stuff
extra_meta = {
'X-Object-Meta-Foo': 'Bar',
'X-Timestamp': self.ts().internal,
}
df = df_mgr.get_diskfile(self.existing_device, '0',
'a', 'c', 'o', policy=policy)
df.write_metadata(extra_meta)
# sanity
df = df_mgr.get_diskfile(self.existing_device, '0',
'a', 'c', 'o', policy=policy)
metadata.update(extra_meta)
self.assertEqual(metadata, df.read_metadata())
# add a newer datafile
df = df_mgr.get_diskfile(self.existing_device, '0',
'a', 'c', 'o', policy=policy)
ts = self.ts()
write_diskfile(df, ts, frag_index=3, commit=False,
legacy_durable=legacy_durable)
# N.B. don't make it durable
# and we still get the old metadata (same as if no .data!)
df = df_mgr.get_diskfile(self.existing_device, '0',
'a', 'c', 'o', policy=policy)
self.assertEqual(metadata, df.read_metadata())
def test_open_most_recent_durable(self):
self._do_test_open_most_recent_durable(False)
def test_open_most_recent_durable_legacy(self):
self._do_test_open_most_recent_durable(True)
def test_open_most_recent_missing_durable(self):
policy = POLICIES.default
df_mgr = self.df_router[policy]
df = df_mgr.get_diskfile(self.existing_device, '0',
'a', 'c', 'o', policy=policy)
self.assertRaises(DiskFileNotExist, df.read_metadata)
# now create a datafile missing durable
ts = self.ts()
write_diskfile(df, ts, frag_index=3, commit=False)
# add some .meta stuff
extra_meta = {
'X-Object-Meta-Foo': 'Bar',
'X-Timestamp': self.ts().internal,
}
df = df_mgr.get_diskfile(self.existing_device, '0',
'a', 'c', 'o', policy=policy)
df.write_metadata(extra_meta)
# we still get the DiskFileNotExist (same as if no .data!)
df = df_mgr.get_diskfile(self.existing_device, '0',
'a', 'c', 'o', policy=policy,
frag_index=3)
self.assertRaises(DiskFileNotExist, df.read_metadata)
# sanity, without the frag_index kwarg
df = df_mgr.get_diskfile(self.existing_device, '0',
'a', 'c', 'o', policy=policy)
self.assertRaises(DiskFileNotExist, df.read_metadata)
def test_fragments(self):
ts_1 = self.ts()
self._get_open_disk_file(ts=ts_1.internal, frag_index=0)
df = self._get_open_disk_file(ts=ts_1.internal, frag_index=2)
self.assertEqual(df.fragments, {ts_1: [0, 2]})
# now add a newer datafile for frag index 3 but don't write a
# durable with it (so ignore the error when we try to open)
ts_2 = self.ts()
try:
df = self._get_open_disk_file(ts=ts_2.internal, frag_index=3,
commit=False)
except DiskFileNotExist:
pass
# sanity check: should have 3* .data
files = os.listdir(df._datadir)
self.assertEqual(3, len(files))
with df.open():
self.assertEqual(df.fragments, {ts_1: [0, 2], ts_2: [3]})
def test_fragments_available_when_not_durable(self):
# verify frags available even if open fails e.g. if none are durable
ts_1 = self.ts()
ts_2 = self.ts()
for ts, fi in ((ts_1, 0), (ts_1, 2), (ts_2, 3)):
try:
df = self._get_open_disk_file(
ts=ts, frag_index=fi, commit=False)
except DiskFileNotExist:
pass
df = self._simple_get_diskfile()
# sanity check: should have 3* .data
files = os.listdir(df._datadir)
self.assertEqual(3, len(files))
self.assertRaises(DiskFileNotExist, df.open)
self.assertEqual(df.fragments, {ts_1: [0, 2], ts_2: [3]})
def test_fragments_not_open(self):
df = self._simple_get_diskfile()
self.assertIsNone(df.fragments)
def test_durable_timestamp_when_not_durable(self):
try:
self._get_open_disk_file(self.ts().internal, commit=False)
except DiskFileNotExist:
pass
df = self._simple_get_diskfile()
with self.assertRaises(DiskFileNotExist):
df.open()
# open() was attempted, but no durable file so expect None
self.assertIsNone(df.durable_timestamp)
def test_durable_timestamp_missing_frag_index(self):
ts1 = self.ts()
self._get_open_disk_file(ts=ts1.internal, frag_index=1)
df = self._simple_get_diskfile(frag_index=2)
with self.assertRaises(DiskFileNotExist):
df.open()
# open() was attempted, but no data file for frag index so expect None
self.assertIsNone(df.durable_timestamp)
def test_durable_timestamp_newer_non_durable_data_file(self):
ts1 = self.ts()
self._get_open_disk_file(ts=ts1.internal)
ts2 = self.ts()
try:
self._get_open_disk_file(ts=ts2.internal, commit=False)
except DiskFileNotExist:
pass
df = self._simple_get_diskfile()
# sanity check - two .data files
self.assertEqual(2, len(os.listdir(df._datadir)))
df.open()
self.assertEqual(ts1, df.durable_timestamp)
def test_durable_timestamp_legacy_durable(self):
self._do_test_durable_timestamp(True)
def _test_open_with_fragment_preferences(self, legacy_durable=False):
policy = POLICIES.default
df_mgr = self.df_router[policy]
df = df_mgr.get_diskfile(self.existing_device, '0',
'a', 'c', 'o', policy=policy)
ts_1, ts_2, ts_3, ts_4 = (self.ts() for _ in range(4))
# create two durable frags, first with index 0
frag_0_metadata = write_diskfile(df, ts_1, frag_index=0,
legacy_durable=legacy_durable)
# second with index 3
frag_3_metadata = write_diskfile(df, ts_1, frag_index=3,
legacy_durable=legacy_durable)
# sanity check: should have 2 * .data plus possibly a .durable
self.assertEqual(3 if legacy_durable else 2,
len(os.listdir(df._datadir)))
# add some .meta stuff
meta_1_metadata = {
'X-Object-Meta-Foo': 'Bar',
'X-Timestamp': ts_2.internal,
}
df = df_mgr.get_diskfile(self.existing_device, '0',
'a', 'c', 'o', policy=policy)
df.write_metadata(meta_1_metadata)
# sanity check: should have 2 * .data, possibly .durable, .meta
self.assertEqual(4 if legacy_durable else 3,
len(os.listdir(df._datadir)))
# sanity: should get frag index 3
df = df_mgr.get_diskfile(self.existing_device, '0',
'a', 'c', 'o', policy=policy)
expected = dict(frag_3_metadata)
expected.update(meta_1_metadata)
self.assertEqual(expected, df.read_metadata())
# add a newer datafile for frag index 2
# N.B. don't make it durable - skip call to commit()
df = df_mgr.get_diskfile(self.existing_device, '0',
'a', 'c', 'o', policy=policy)
frag_2_metadata = write_diskfile(df, ts_3, frag_index=2, commit=False,
data=b'new test data',
legacy_durable=legacy_durable)
# sanity check: should have 2* .data, possibly .durable, .meta, .data
self.assertEqual(5 if legacy_durable else 4,
len(os.listdir(df._datadir)))
# sanity check: with no frag preferences we get old metadata
df = df_mgr.get_diskfile(self.existing_device, '0', 'a', 'c', 'o',
policy=policy)
self.assertEqual(expected, df.read_metadata())
self.assertEqual(ts_2.internal, df.timestamp)
self.assertEqual(ts_1.internal, df.data_timestamp)
self.assertEqual(ts_1.internal, df.durable_timestamp)
self.assertEqual({ts_1: [0, 3], ts_3: [2]}, df.fragments)
# with empty frag preferences we get metadata from newer non-durable
# data file
df = df_mgr.get_diskfile(self.existing_device, '0', 'a', 'c', 'o',
policy=policy, frag_prefs=[])
self.assertEqual(frag_2_metadata, df.read_metadata())
self.assertEqual(ts_3.internal, df.timestamp)
self.assertEqual(ts_3.internal, df.data_timestamp)
self.assertEqual(ts_1.internal, df.durable_timestamp)
self.assertEqual({ts_1: [0, 3], ts_3: [2]}, df.fragments)
# check we didn't destroy any potentially valid data by opening the
# non-durable data file
df = df_mgr.get_diskfile(self.existing_device, '0', 'a', 'c', 'o',
policy=policy)
self.assertEqual(expected, df.read_metadata())
# now add some newer .meta stuff which should replace older .meta
meta_2_metadata = {
'X-Object-Meta-Foo': 'BarBarBarAnne',
'X-Timestamp': ts_4.internal,
}
df = df_mgr.get_diskfile(self.existing_device, '0',
'a', 'c', 'o', policy=policy)
df.write_metadata(meta_2_metadata)
# sanity check: should have 2 * .data, possibly .durable, .data, .meta
self.assertEqual(5 if legacy_durable else 4,
len(os.listdir(df._datadir)))
# sanity check: with no frag preferences we get newer metadata applied
# to durable data file
expected = dict(frag_3_metadata)
expected.update(meta_2_metadata)
df = df_mgr.get_diskfile(self.existing_device, '0', 'a', 'c', 'o',
policy=policy)
self.assertEqual(expected, df.read_metadata())
self.assertEqual(ts_4.internal, df.timestamp)
self.assertEqual(ts_1.internal, df.data_timestamp)
self.assertEqual(ts_1.internal, df.durable_timestamp)
self.assertEqual({ts_1: [0, 3], ts_3: [2]}, df.fragments)
# with empty frag preferences we still get metadata from newer .meta
# but applied to non-durable data file
expected = dict(frag_2_metadata)
expected.update(meta_2_metadata)
df = df_mgr.get_diskfile(self.existing_device, '0', 'a', 'c', 'o',
policy=policy, frag_prefs=[])
self.assertEqual(expected, df.read_metadata())
self.assertEqual(ts_4.internal, df.timestamp)
self.assertEqual(ts_3.internal, df.data_timestamp)
self.assertEqual(ts_1.internal, df.durable_timestamp)
self.assertEqual({ts_1: [0, 3], ts_3: [2]}, df.fragments)
# check we didn't destroy any potentially valid data by opening the
# non-durable data file
expected = dict(frag_3_metadata)
expected.update(meta_2_metadata)
df = df_mgr.get_diskfile(self.existing_device, '0', 'a', 'c', 'o',
policy=policy)
self.assertEqual(expected, df.read_metadata())
self.assertEqual(ts_4.internal, df.timestamp)
self.assertEqual(ts_1.internal, df.data_timestamp)
self.assertEqual(ts_1.internal, df.durable_timestamp)
self.assertEqual({ts_1: [0, 3], ts_3: [2]}, df.fragments)
# prefer frags at ts_1, exclude no indexes, expect highest frag index
prefs = [{'timestamp': ts_1.internal, 'exclude': []},
{'timestamp': ts_2.internal, 'exclude': []},
{'timestamp': ts_3.internal, 'exclude': []}]
expected = dict(frag_3_metadata)
expected.update(meta_2_metadata)
df = df_mgr.get_diskfile(self.existing_device, '0', 'a', 'c', 'o',
policy=policy, frag_prefs=prefs)
self.assertEqual(expected, df.read_metadata())
self.assertEqual(ts_4.internal, df.timestamp)
self.assertEqual(ts_1.internal, df.data_timestamp)
self.assertEqual(ts_1.internal, df.durable_timestamp)
self.assertEqual({ts_1: [0, 3], ts_3: [2]}, df.fragments)
# prefer frags at ts_1, exclude frag index 3 so expect frag index 0
prefs = [{'timestamp': ts_1.internal, 'exclude': [3]},
{'timestamp': ts_2.internal, 'exclude': []},
{'timestamp': ts_3.internal, 'exclude': []}]
expected = dict(frag_0_metadata)
expected.update(meta_2_metadata)
df = df_mgr.get_diskfile(self.existing_device, '0', 'a', 'c', 'o',
policy=policy, frag_prefs=prefs)
self.assertEqual(expected, df.read_metadata())
self.assertEqual(ts_4.internal, df.timestamp)
self.assertEqual(ts_1.internal, df.data_timestamp)
self.assertEqual(ts_1.internal, df.durable_timestamp)
self.assertEqual({ts_1: [0, 3], ts_3: [2]}, df.fragments)
# now make ts_3 the preferred timestamp, excluded indexes don't exist
prefs = [{'timestamp': ts_3.internal, 'exclude': [4, 5, 6]},
{'timestamp': ts_2.internal, 'exclude': []},
{'timestamp': ts_1.internal, 'exclude': []}]
expected = dict(frag_2_metadata)
expected.update(meta_2_metadata)
df = df_mgr.get_diskfile(self.existing_device, '0', 'a', 'c', 'o',
policy=policy, frag_prefs=prefs)
self.assertEqual(expected, df.read_metadata())
self.assertEqual(ts_4.internal, df.timestamp)
self.assertEqual(ts_3.internal, df.data_timestamp)
self.assertEqual(ts_1.internal, df.durable_timestamp)
self.assertEqual({ts_1: [0, 3], ts_3: [2]}, df.fragments)
# now make ts_2 the preferred timestamp - there are no frags at ts_2,
# next preference is ts_3 but index 2 is excluded, then at ts_1 index 3
# is excluded so we get frag 0 at ts_1
prefs = [{'timestamp': ts_2.internal, 'exclude': [1]},
{'timestamp': ts_3.internal, 'exclude': [2]},
{'timestamp': ts_1.internal, 'exclude': [3]}]
expected = dict(frag_0_metadata)
expected.update(meta_2_metadata)
df = df_mgr.get_diskfile(self.existing_device, '0', 'a', 'c', 'o',
policy=policy, frag_prefs=prefs)
self.assertEqual(expected, df.read_metadata())
self.assertEqual(ts_4.internal, df.timestamp)
self.assertEqual(ts_1.internal, df.data_timestamp)
self.assertEqual(ts_1.internal, df.durable_timestamp)
self.assertEqual({ts_1: [0, 3], ts_3: [2]}, df.fragments)
def test_open_with_fragment_preferences_legacy_durable(self):
self._test_open_with_fragment_preferences(legacy_durable=True)
def test_open_with_fragment_preferences(self):
self._test_open_with_fragment_preferences(legacy_durable=False)
def test_open_with_bad_fragment_preferences(self):
policy = POLICIES.default
df_mgr = self.df_router[policy]
for bad in (
'ouch',
2,
[{'timestamp': '1234.5678', 'excludes': [1]}, {}],
[{'timestamp': 'not a timestamp', 'excludes': [1, 2]}],
[{'timestamp': '1234.5678', 'excludes': [1, -1]}],
[{'timestamp': '1234.5678', 'excludes': 1}],
[{'timestamp': '1234.5678'}],
[{'excludes': [1, 2]}]
):
try:
df_mgr.get_diskfile(self.existing_device, '0', 'a', 'c', 'o',
policy=policy, frag_prefs=bad)
self.fail('Expected DiskFileError for bad frag_prefs: %r'
% bad)
except DiskFileError as e:
self.assertIn('frag_prefs', str(e))
def test_disk_file_app_iter_ranges_checks_only_aligned_frag_data(self):
policy = POLICIES.default
frag_size = policy.fragment_size
# make sure there are two fragment size worth of data on disk
data = b'ab' * policy.ec_segment_size
df, df_data = self._create_test_file(data)
quarantine_msgs = []
reader = df.reader(_quarantine_hook=quarantine_msgs.append)
# each range uses a fresh reader app_iter_range which triggers a disk
# read at the range offset - make sure each of those disk reads will
# fetch an amount of data from disk that is greater than but not equal
# to a fragment size
reader._disk_chunk_size = int(frag_size * 1.5)
with mock.patch.object(
reader._diskfile.policy.pyeclib_driver, 'get_metadata')\
as mock_get_metadata:
it = reader.app_iter_ranges(
[(0, 10), (10, 20),
(frag_size + 20, frag_size + 30)],
'plain/text', '\r\n--someheader\r\n', len(df_data))
value = b''.join(it)
# check that only first range which starts at 0 triggers a frag check
self.assertEqual(1, mock_get_metadata.call_count)
self.assertIn(df_data[:10], value)
self.assertIn(df_data[10:20], value)
self.assertIn(df_data[frag_size + 20:frag_size + 30], value)
self.assertEqual(quarantine_msgs, [])
def test_reader_quarantines_corrupted_ec_archive(self):
# This has same purpose as
# TestAuditor.test_object_audit_checks_EC_fragments just making
# sure that checks happen in DiskFileReader layer.
policy = POLICIES.default
df, df_data = self._create_test_file(b'x' * policy.ec_segment_size,
timestamp=self.ts())
def do_test(corrupted_frag_body, expected_offset, expected_read):
# expected_offset is offset at which corruption should be reported
# expected_read is number of bytes that should be read before the
# exception is raised
ts = self.ts()
write_diskfile(df, ts, corrupted_frag_body)
# at the open for the diskfile, no error occurred
# reading first corrupt frag is sufficient to detect the corruption
df.open()
with self.assertRaises(DiskFileQuarantined) as cm:
reader = df.reader()
reader._disk_chunk_size = int(policy.fragment_size)
bytes_read = 0
for chunk in reader:
bytes_read += len(chunk)
with self.assertRaises(DiskFileNotExist):
df.open()
self.assertEqual(expected_read, bytes_read)
self.assertEqual('Invalid EC metadata at offset 0x%x' %
expected_offset, cm.exception.args[0])
# TODO with liberasurecode < 1.2.0 the EC metadata verification checks
# only the magic number at offset 59 bytes into the frag so we'll
# corrupt up to and including that. Once liberasurecode >= 1.2.0 is
# required we should be able to reduce the corruption length.
corruption_length = 64
# corrupted first frag can be detected
corrupted_frag_body = (b' ' * corruption_length +
df_data[corruption_length:])
do_test(corrupted_frag_body, 0, 0)
# corrupted the second frag can be also detected
corrupted_frag_body = (df_data + b' ' * corruption_length +
df_data[corruption_length:])
do_test(corrupted_frag_body, len(df_data), len(df_data))
# if the second frag is shorter than frag size then corruption is
# detected when the reader is closed
corrupted_frag_body = (df_data + b' ' * corruption_length +
df_data[corruption_length:-10])
do_test(corrupted_frag_body, len(df_data), len(corrupted_frag_body))
def test_reader_ec_exception_causes_quarantine(self):
policy = POLICIES.default
def do_test(exception):
df, df_data = self._create_test_file(b'x' * policy.ec_segment_size,
timestamp=self.ts())
df.manager.logger.clear()
with mock.patch.object(df.policy.pyeclib_driver, 'get_metadata',
side_effect=exception):
df.open()
with self.assertRaises(DiskFileQuarantined) as cm:
for chunk in df.reader():
pass
with self.assertRaises(DiskFileNotExist):
df.open()
self.assertEqual('Invalid EC metadata at offset 0x0',
cm.exception.args[0])
log_lines = df.manager.logger.get_lines_for_level('warning')
self.assertIn('Quarantined object', log_lines[0])
self.assertIn('Invalid EC metadata at offset 0x0', log_lines[0])
do_test(pyeclib.ec_iface.ECInvalidFragmentMetadata('testing'))
do_test(pyeclib.ec_iface.ECBadFragmentChecksum('testing'))
do_test(pyeclib.ec_iface.ECInvalidParameter('testing'))
def test_reader_ec_exception_does_not_cause_quarantine(self):
# ECDriverError should not cause quarantine, only certain subclasses
policy = POLICIES.default
df, df_data = self._create_test_file(b'x' * policy.ec_segment_size,
timestamp=self.ts())
with mock.patch.object(
df.policy.pyeclib_driver, 'get_metadata',
side_effect=pyeclib.ec_iface.ECDriverError('testing')):
df.open()
read_data = b''.join([d for d in df.reader()])
self.assertEqual(df_data, read_data)
log_lines = df.manager.logger.get_lines_for_level('warning')
self.assertIn('Problem checking EC fragment', log_lines[0])
df.open() # not quarantined
def test_reader_frag_check_does_not_quarantine_if_its_not_binary(self):
# This may look weird but for super-safety, check the
# ECDiskFileReader._frag_check doesn't quarantine when non-binary
# type chunk incomming (that would occurre only from coding bug)
policy = POLICIES.default
df, df_data = self._create_test_file(b'x' * policy.ec_segment_size,
timestamp=self.ts())
df.open()
for invalid_type_chunk in (None, [], [[]], 1):
reader = df.reader()
reader._check_frag(invalid_type_chunk)
# None and [] are just skipped and [[]] and 1 are detected as invalid
# chunks
log_lines = df.manager.logger.get_lines_for_level('warning')
self.assertEqual(2, len(log_lines))
for log_line in log_lines:
self.assertIn(
'Unexpected fragment data type (not quarantined)', log_line)
df.open() # not quarantined
def test_ondisk_data_info_has_durable_key(self):
# non-durable; use frag_prefs=[] to allow it to be opened
df = self._simple_get_diskfile(obj='o1', frag_prefs=[])
self._create_ondisk_file(df, b'', ext='.data', timestamp=10,
metadata={'name': '/a/c/o1'}, commit=False)
with df.open():
self.assertIn('durable', df._ondisk_info['data_info'])
self.assertFalse(df._ondisk_info['data_info']['durable'])
# durable
df = self._simple_get_diskfile(obj='o2')
self._create_ondisk_file(df, b'', ext='.data', timestamp=10,
metadata={'name': '/a/c/o2'})
with df.open():
self.assertIn('durable', df._ondisk_info['data_info'])
self.assertTrue(df._ondisk_info['data_info']['durable'])
# legacy durable
df = self._simple_get_diskfile(obj='o3')
self._create_ondisk_file(df, b'', ext='.data', timestamp=10,
metadata={'name': '/a/c/o3'},
legacy_durable=True)
with df.open():
data_info = df._ondisk_info['data_info']
# sanity check it is legacy with no #d part in filename
self.assertEqual(data_info['filename'], '0000000010.00000#2.data')
self.assertIn('durable', data_info)
self.assertTrue(data_info['durable'])
@patch_policies(with_ec_default=True)
class TestSuffixHashes(unittest.TestCase):
"""
This tests all things related to hashing suffixes and therefore
there's also few test methods for cleanup_ondisk_files as well
(because it's used by hash_suffix).
The public interface to suffix hashing is on the Manager::
* cleanup_ondisk_files(hsh_path)
* get_hashes(device, partition, suffixes, policy)
* invalidate_hash(suffix_dir)
The Manager.get_hashes method (used by the REPLICATE verb)
calls Manager._get_hashes (which may be an alias to the module
method get_hashes), which calls hash_suffix, which calls
cleanup_ondisk_files.
Outside of that, cleanup_ondisk_files and invalidate_hash are
used mostly after writing new files via PUT or DELETE.
Test methods are organized by::
* cleanup_ondisk_files tests - behaviors
* cleanup_ondisk_files tests - error handling
* invalidate_hash tests - behavior
* invalidate_hash tests - error handling
* get_hashes tests - hash_suffix behaviors
* get_hashes tests - hash_suffix error handling
* get_hashes tests - behaviors
* get_hashes tests - error handling
"""
def setUp(self):
skip_if_no_xattrs()
self.testdir = tempfile.mkdtemp()
self.logger = debug_logger('suffix-hash-test')
self.devices = os.path.join(self.testdir, 'node')
os.mkdir(self.devices)
self.existing_device = 'sda1'
os.mkdir(os.path.join(self.devices, self.existing_device))
self.conf = {
'swift_dir': self.testdir,
'devices': self.devices,
'mount_check': False,
}
self.df_router = diskfile.DiskFileRouter(self.conf, self.logger)
self._ts_iter = (Timestamp(t) for t in
itertools.count(int(time())))
self.policy = None
def ts(self):
"""
Timestamps - forever.
"""
return next(self._ts_iter)
def fname_to_ts_hash(self, fname):
"""
EC datafiles are only hashed by their timestamp
"""
return md5(fname.split('#', 1)[0]).hexdigest()
def tearDown(self):
rmtree(self.testdir, ignore_errors=1)
def iter_policies(self):
for policy in POLICIES:
self.policy = policy
yield policy
@contextmanager
def policy_in_message(self):
try:
yield
except AssertionError as err:
if not self.policy:
raise
policy_trailer = '\n\n... for policy %r' % self.policy
raise AssertionError(str(err) + policy_trailer)
def assertEqual(self, *args):
with self.policy_in_message():
unittest.TestCase.assertEqual(self, *args)
def get_different_suffix_df(self, df, **kwargs):
# returns diskfile in the same partition with different suffix
suffix_dir = os.path.dirname(df._datadir)
for i in itertools.count():
df2 = df._manager.get_diskfile(
os.path.basename(df._device_path),
df._datadir.split('/')[-3],
df._account,
df._container,
'o%d' % i,
policy=df.policy,
**kwargs)
suffix_dir2 = os.path.dirname(df2._datadir)
if suffix_dir != suffix_dir2:
return df2
def test_valid_suffix(self):
self.assertTrue(diskfile.valid_suffix(u'000'))
self.assertTrue(diskfile.valid_suffix('000'))
self.assertTrue(diskfile.valid_suffix('123'))
self.assertTrue(diskfile.valid_suffix('fff'))
self.assertFalse(diskfile.valid_suffix(list('123')))
self.assertFalse(diskfile.valid_suffix(123))
self.assertFalse(diskfile.valid_suffix(' 12'))
self.assertFalse(diskfile.valid_suffix('-00'))
self.assertFalse(diskfile.valid_suffix(u'-00'))
self.assertFalse(diskfile.valid_suffix('1234'))
def check_cleanup_ondisk_files(self, policy, input_files, output_files):
orig_unlink = os.unlink
file_list = list(input_files)
rmdirs = []
def mock_listdir(path):
return list(file_list)
def mock_unlink(path):
# timestamp 1 is a special tag to pretend a file disappeared
# between the listdir and unlink.
if '/0000000001.00000.' in path:
# Using actual os.unlink for a non-existent name to reproduce
# exactly what OSError it raises in order to prove that
# common.utils.remove_file is squelching the error - but any
# OSError would do.
orig_unlink(uuid.uuid4().hex)
file_list.remove(os.path.basename(path))
df_mgr = self.df_router[policy]
with unit_mock({'os.listdir': mock_listdir, 'os.unlink': mock_unlink,
'os.rmdir': rmdirs.append}):
if isinstance(output_files, Exception):
path = os.path.join(self.testdir, 'does-not-matter')
self.assertRaises(output_files.__class__,
df_mgr.cleanup_ondisk_files, path)
return
df_mgr.commit_window = 0
files = df_mgr.cleanup_ondisk_files('/whatever')['files']
self.assertEqual(files, output_files)
if files:
self.assertEqual(rmdirs, [])
else:
self.assertEqual(rmdirs, ['/whatever'])
# cleanup_ondisk_files tests - behaviors
def test_cleanup_ondisk_files_purge_data_newer_ts(self):
for policy in self.iter_policies():
# purge .data if there's a newer .ts
file1 = _make_datafilename(self.ts(), policy)
file2 = self.ts().internal + '.ts'
file_list = [file1, file2]
self.check_cleanup_ondisk_files(policy, file_list, [file2])
def test_cleanup_ondisk_files_purge_expired_ts(self):
for policy in self.iter_policies():
# purge older .ts files if there's a newer .data
file1 = self.ts().internal + '.ts'
file2 = self.ts().internal + '.ts'
timestamp = self.ts()
file3 = _make_datafilename(timestamp, policy, durable=False)
file_list = [file1, file2, file3]
expected = {
# no durable datafile means you can't get rid of the
# latest tombstone even if datafile is newer
EC_POLICY: [file3, file2],
REPL_POLICY: [file3],
}[policy.policy_type]
self.check_cleanup_ondisk_files(policy, file_list, expected)
def _do_test_cleanup_ondisk_files_purge_ts_newer_data(
self, policy, legacy_durable=False):
# purge .ts if there's a newer .data
file1 = self.ts().internal + '.ts'
timestamp = self.ts()
file2 = _make_datafilename(
timestamp, policy, durable=not legacy_durable)
file_list = [file1, file2]
expected = [file2]
if policy.policy_type == EC_POLICY and legacy_durable:
durable_file = timestamp.internal + '.durable'
file_list.append(durable_file)
expected.insert(0, durable_file)
self.check_cleanup_ondisk_files(policy, file_list, expected)
def test_cleanup_ondisk_files_purge_ts_newer_data(self):
for policy in self.iter_policies():
self._do_test_cleanup_ondisk_files_purge_ts_newer_data(policy)
def test_cleanup_ondisk_files_purge_ts_newer_data_and_legacy_durable(self):
for policy in self.iter_policies():
if policy.policy_type == EC_POLICY:
self._do_test_cleanup_ondisk_files_purge_ts_newer_data(
policy, legacy_durable=True)
def test_cleanup_ondisk_files_purge_older_ts(self):
for policy in self.iter_policies():
file1 = self.ts().internal + '.ts'
file2 = self.ts().internal + '.ts'
file3 = _make_datafilename(self.ts(), policy, durable=False)
file4 = self.ts().internal + '.meta'
expected = {
# no durable means we can only throw out things before
# the latest tombstone
EC_POLICY: [file4, file3, file2],
# keep .meta and .data and purge all .ts files
REPL_POLICY: [file4, file3],
}[policy.policy_type]
file_list = [file1, file2, file3, file4]
self.check_cleanup_ondisk_files(policy, file_list, expected)
def _do_test_cleanup_ondisk_files_keep_meta_data_purge_ts(
self, policy, legacy_durable=False):
file1 = self.ts().internal + '.ts'
file2 = self.ts().internal + '.ts'
timestamp = self.ts()
file3 = _make_datafilename(
timestamp, policy, durable=not legacy_durable)
file_list = [file1, file2, file3]
expected = [file3]
if policy.policy_type == EC_POLICY and legacy_durable:
durable_filename = timestamp.internal + '.durable'
file_list.append(durable_filename)
expected.insert(0, durable_filename)
file4 = self.ts().internal + '.meta'
file_list.append(file4)
expected.insert(0, file4)
# keep .meta and .data if meta newer than data and purge .ts
self.check_cleanup_ondisk_files(policy, file_list, expected)
def test_cleanup_ondisk_files_keep_meta_data_purge_ts(self):
for policy in self.iter_policies():
self._do_test_cleanup_ondisk_files_keep_meta_data_purge_ts(policy)
def test_cleanup_ondisk_files_keep_meta_data_purge_ts_legacy_durable(self):
for policy in self.iter_policies():
if policy.policy_type == EC_POLICY:
self._do_test_cleanup_ondisk_files_keep_meta_data_purge_ts(
policy, legacy_durable=True)
def test_cleanup_ondisk_files_keep_one_ts(self):
for policy in self.iter_policies():
file1, file2, file3 = [self.ts().internal + '.ts'
for i in range(3)]
file_list = [file1, file2, file3]
# keep only latest of multiple .ts files
self.check_cleanup_ondisk_files(policy, file_list, [file3])
def test_cleanup_ondisk_files_multi_data_file(self):
for policy in self.iter_policies():
file1 = _make_datafilename(self.ts(), policy, 1, durable=False)
file2 = _make_datafilename(self.ts(), policy, 2, durable=False)
file3 = _make_datafilename(self.ts(), policy, 3, durable=False)
expected = {
# keep all non-durable datafiles
EC_POLICY: [file3, file2, file1],
# keep only latest of multiple .data files
REPL_POLICY: [file3]
}[policy.policy_type]
file_list = [file1, file2, file3]
self.check_cleanup_ondisk_files(policy, file_list, expected)
def _do_test_cleanup_ondisk_files_keeps_one_datafile(self, policy,
legacy_durable=False):
timestamps = [self.ts() for i in range(3)]
file1 = _make_datafilename(timestamps[0], policy, 1,
durable=not legacy_durable)
file2 = _make_datafilename(timestamps[1], policy, 2,
durable=not legacy_durable)
file3 = _make_datafilename(timestamps[2], policy, 3,
durable=not legacy_durable)
file_list = [file1, file2, file3]
expected = [file3]
if policy.policy_type == EC_POLICY and legacy_durable:
for t in timestamps:
file_list.append(t.internal + '.durable')
expected.insert(0, file_list[-1])
self.check_cleanup_ondisk_files(policy, file_list, expected)
def test_cleanup_ondisk_files_keeps_one_datafile(self):
for policy in self.iter_policies():
self._do_test_cleanup_ondisk_files_keeps_one_datafile(policy)
def test_cleanup_ondisk_files_keeps_one_datafile_and_legacy_durable(self):
for policy in self.iter_policies():
if policy.policy_type == EC_POLICY:
self._do_test_cleanup_ondisk_files_keeps_one_datafile(
policy, legacy_durable=True)
def _do_test_cleanup_ondisk_files_keep_one_meta(self, policy,
legacy_durable=False):
# keep only latest of multiple .meta files
t_data = self.ts()
file1 = _make_datafilename(t_data, policy, durable=not legacy_durable)
file2, file3 = [self.ts().internal + '.meta' for i in range(2)]
file_list = [file1, file2, file3]
expected = [file3, file1]
if policy.policy_type == EC_POLICY and legacy_durable:
durable_file = t_data.internal + '.durable'
file_list.append(durable_file)
expected.insert(1, durable_file)
self.check_cleanup_ondisk_files(policy, file_list, expected)
def test_cleanup_ondisk_files_keep_one_meta(self):
for policy in self.iter_policies():
self._do_test_cleanup_ondisk_files_keep_one_meta(policy)
def test_cleanup_ondisk_files_keep_one_meta_legacy_durable(self):
for policy in self.iter_policies():
if policy.policy_type == EC_POLICY:
self._do_test_cleanup_ondisk_files_keep_one_meta(
policy, legacy_durable=True)
def test_cleanup_ondisk_files_only_meta(self):
for policy in self.iter_policies():
file1, file2 = [self.ts().internal + '.meta' for i in range(2)]
file_list = [file1, file2]
self.check_cleanup_ondisk_files(policy, file_list, [file2])
def test_cleanup_ondisk_files_ignore_orphaned_ts(self):
for policy in self.iter_policies():
# A more recent orphaned .meta file will prevent old .ts files
# from being cleaned up otherwise
file1, file2 = [self.ts().internal + '.ts' for i in range(2)]
file3 = self.ts().internal + '.meta'
file_list = [file1, file2, file3]
self.check_cleanup_ondisk_files(policy, file_list, [file3, file2])
def test_cleanup_ondisk_files_purge_old_data_only(self):
for policy in self.iter_policies():
# Oldest .data will be purge, .meta and .ts won't be touched
file1 = _make_datafilename(self.ts(), policy)
file2 = self.ts().internal + '.ts'
file3 = self.ts().internal + '.meta'
file_list = [file1, file2, file3]
self.check_cleanup_ondisk_files(policy, file_list, [file3, file2])
def test_cleanup_ondisk_files_purge_old_ts(self):
for policy in self.iter_policies():
# A single old .ts file will be removed
old_float = time() - (diskfile.DEFAULT_RECLAIM_AGE + 1)
file1 = Timestamp(old_float).internal + '.ts'
file_list = [file1]
self.check_cleanup_ondisk_files(policy, file_list, [])
def test_cleanup_ondisk_files_keep_isolated_meta_purge_old_ts(self):
for policy in self.iter_policies():
# A single old .ts file will be removed despite presence of a .meta
old_float = time() - (diskfile.DEFAULT_RECLAIM_AGE + 1)
file1 = Timestamp(old_float).internal + '.ts'
file2 = Timestamp(time() + 2).internal + '.meta'
file_list = [file1, file2]
self.check_cleanup_ondisk_files(policy, file_list, [file2])
def test_cleanup_ondisk_files_keep_single_old_data(self):
for policy in self.iter_policies():
old_float = time() - (diskfile.DEFAULT_RECLAIM_AGE + 1)
file1 = _make_datafilename(
Timestamp(old_float), policy, durable=True)
file_list = [file1]
self.check_cleanup_ondisk_files(policy, file_list, file_list)
def test_cleanup_ondisk_drops_old_non_durable_data(self):
for policy in self.iter_policies():
if policy.policy_type == EC_POLICY:
old_float = time() - (diskfile.DEFAULT_RECLAIM_AGE + 1)
file1 = _make_datafilename(
Timestamp(old_float), policy, durable=False)
file_list = [file1]
# for EC an isolated old non-durable .data file is removed
expected = []
self.check_cleanup_ondisk_files(policy, file_list, expected)
def test_cleanup_ondisk_files_drops_isolated_durable(self):
# check behaviour for legacy durable files
for policy in self.iter_policies():
if policy.policy_type == EC_POLICY:
file1 = Timestamp.now().internal + '.durable'
file_list = [file1]
self.check_cleanup_ondisk_files(policy, file_list, [])
def test_cleanup_ondisk_files_purges_single_old_meta(self):
for policy in self.iter_policies():
# A single old .meta file will be removed
old_float = time() - (diskfile.DEFAULT_RECLAIM_AGE + 1)
file1 = Timestamp(old_float).internal + '.meta'
file_list = [file1]
self.check_cleanup_ondisk_files(policy, file_list, [])
# cleanup_ondisk_files tests - error handling
def test_cleanup_ondisk_files_hsh_path_enoent(self):
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
# common.utils.listdir *completely* mutes ENOENT
path = os.path.join(self.testdir, 'does-not-exist')
self.assertEqual(df_mgr.cleanup_ondisk_files(path)['files'], [])
def test_cleanup_ondisk_files_hsh_path_other_oserror(self):
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
with mock.patch('os.listdir') as mock_listdir:
mock_listdir.side_effect = OSError('kaboom!')
# but it will raise other OSErrors
path = os.path.join(self.testdir, 'does-not-matter')
self.assertRaises(OSError, df_mgr.cleanup_ondisk_files,
path)
def test_cleanup_ondisk_files_reclaim_tombstone_remove_file_error(self):
for policy in self.iter_policies():
# Timestamp 1 makes the check routine pretend the file
# disappeared after listdir before unlink.
file1 = '0000000001.00000.ts'
file_list = [file1]
self.check_cleanup_ondisk_files(policy, file_list, [])
def test_cleanup_ondisk_files_older_remove_file_error(self):
for policy in self.iter_policies():
# Timestamp 1 makes the check routine pretend the file
# disappeared after listdir before unlink.
file1 = _make_datafilename(Timestamp(1), policy)
file2 = '0000000002.00000.ts'
file_list = [file1, file2]
self.check_cleanup_ondisk_files(policy, file_list, [])
# invalidate_hash tests - behavior
def test_invalidate_hash_race_with_partition_delete(self):
part_dir = os.path.join(self.testdir, '0')
suffix_dir = os.path.join(part_dir, 'fff')
os.makedirs(suffix_dir)
def replicatorish():
with lock_path(part_dir):
sleep(0.01)
rmtree(part_dir)
sleep(0.01)
spawn(replicatorish)
sleep(0) # make sure thread starts
diskfile.invalidate_hash(suffix_dir)
def test_invalidate_hash_file_does_not_exist(self):
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
df = df_mgr.get_diskfile('sda1', '0', 'a', 'c', 'o',
policy=policy)
suffix_dir = os.path.dirname(df._datadir)
suffix = os.path.basename(suffix_dir)
part_path = os.path.join(self.devices, 'sda1',
diskfile.get_data_dir(policy), '0')
hashes_file = os.path.join(part_path, diskfile.HASH_FILE)
inv_file = os.path.join(
part_path, diskfile.HASH_INVALIDATIONS_FILE)
# sanity, new partition has no suffix hashing artifacts
self.assertFalse(os.path.exists(hashes_file))
self.assertFalse(os.path.exists(inv_file))
# invalidating a hash does not create the hashes_file
with mock.patch(
'swift.obj.diskfile.BaseDiskFileManager.invalidate_hash',
side_effect=diskfile.invalidate_hash) \
as mock_invalidate_hash:
df.delete(self.ts())
self.assertFalse(os.path.exists(hashes_file))
# ... but does invalidate the suffix
self.assertEqual([mock.call(suffix_dir)],
mock_invalidate_hash.call_args_list)
with open(inv_file) as f:
self.assertEqual(suffix, f.read().strip('\n'))
# ... and hashing suffixes finds (and hashes) the new suffix
hashes = df_mgr.get_hashes('sda1', '0', [], policy)
self.assertIn(suffix, hashes)
self.assertTrue(os.path.exists(hashes_file))
self.assertIn(os.path.basename(suffix_dir), hashes)
with open(hashes_file, 'rb') as f:
found_hashes = pickle.load(f)
found_hashes.pop('updated')
self.assertTrue(found_hashes.pop('valid'))
self.assertEqual(hashes, found_hashes)
# ... and truncates the invalidations file
with open(inv_file) as f:
self.assertEqual('', f.read().strip('\n'))
def test_invalidate_hash_empty_file_exists(self):
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
part_path = os.path.join(self.devices, 'sda1',
diskfile.get_data_dir(policy), '0')
mkdirs(part_path)
hashes = df_mgr.get_hashes('sda1', '0', [], policy)
pkl_path = os.path.join(part_path, diskfile.HASH_FILE)
self.assertTrue(os.path.exists(pkl_path))
self.assertEqual(hashes, {})
# create something to hash
df = df_mgr.get_diskfile('sda1', '0', 'a', 'c', 'o',
policy=policy)
df.delete(self.ts())
suffix_dir = os.path.dirname(df._datadir)
suffix = os.path.basename(suffix_dir)
hashes = df_mgr.get_hashes('sda1', '0', [], policy)
self.assertIn(suffix, hashes) # sanity
def test_invalidate_hash_file_not_truncated_when_empty(self):
orig_open = open
def watch_open(*args, **kargs):
name = os.path.basename(args[0])
open_log[name].append(args[1])
return orig_open(*args, **kargs)
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
part_path = os.path.join(self.devices, 'sda1',
diskfile.get_data_dir(policy), '0')
mkdirs(part_path)
inv_file = os.path.join(
part_path, diskfile.HASH_INVALIDATIONS_FILE)
hash_file = os.path.join(
part_path, diskfile.HASH_FILE)
hashes = df_mgr.get_hashes('sda1', '0', [], policy)
self.assertEqual(hashes, {})
self.assertTrue(os.path.exists(hash_file))
# create something to hash
df = df_mgr.get_diskfile('sda1', '0', 'a', 'c', 'o',
policy=policy)
df.delete(self.ts())
self.assertTrue(os.path.exists(inv_file))
# invalidation file created, lets consolidate it
df_mgr.get_hashes('sda1', '0', [], policy)
open_log = defaultdict(list)
with mock.patch('builtins.open', watch_open):
self.assertTrue(os.path.exists(inv_file))
# no new suffixes get invalidated... so no write iop
df_mgr.get_hashes('sda1', '0', [], policy)
# each file is opened once to read
expected = {
'hashes.pkl': ['rb'],
'hashes.invalid': ['r'],
}
self.assertEqual(open_log, expected)
def _test_invalidate_hash_racing_get_hashes_diff_suffix(self, existing):
# a suffix can be changed or created by second process while new pkl is
# being calculated - verify that suffix is correct after next
# get_hashes call
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
part_path = os.path.join(self.devices, 'sda1',
diskfile.get_data_dir(policy), '0')
if existing:
mkdirs(part_path)
# force hashes.pkl to exist
df_mgr.get_hashes('sda1', '0', [], policy)
self.assertTrue(os.path.exists(os.path.join(
part_path, diskfile.HASH_FILE)))
orig_listdir = os.listdir
df = df_mgr.get_diskfile('sda1', '0', 'a', 'c', 'o',
policy=policy)
suffix = os.path.basename(os.path.dirname(df._datadir))
df2 = self.get_different_suffix_df(df)
suffix2 = os.path.basename(os.path.dirname(df2._datadir))
non_local = {'df2touched': False}
df.delete(self.ts())
def mock_listdir(*args, **kwargs):
# simulating an invalidation occurring in another process while
# get_hashes is executing
result = orig_listdir(*args, **kwargs)
if not non_local['df2touched']:
non_local['df2touched'] = True
# other process creates new suffix
df2.delete(self.ts())
return result
if not existing:
self.assertFalse(os.path.exists(os.path.join(
part_path, diskfile.HASH_FILE)))
with mock.patch('swift.obj.diskfile.os.listdir',
mock_listdir):
# creates pkl file if not already there
hashes = df_mgr.get_hashes('sda1', '0', [], policy)
self.assertTrue(os.path.exists(os.path.join(
part_path, diskfile.HASH_FILE)))
# second suffix added after directory listing, it's added later
self.assertIn(suffix, hashes)
self.assertNotIn(suffix2, hashes)
# updates pkl file
hashes = df_mgr.get_hashes('sda1', '0', [], policy)
self.assertIn(suffix, hashes)
self.assertIn(suffix2, hashes)
def test_invalidate_hash_racing_get_hashes_diff_suffix_new_part(self):
self._test_invalidate_hash_racing_get_hashes_diff_suffix(False)
def test_invalidate_hash_racing_get_hashes_diff_suffix_existing_part(self):
self._test_invalidate_hash_racing_get_hashes_diff_suffix(True)
def _check_hash_invalidations_race_get_hashes_same_suffix(self, existing):
# verify that when two processes concurrently call get_hashes, then any
# concurrent hash invalidation will survive and be consolidated on a
# subsequent call to get_hashes (i.e. ensure first get_hashes process
# does not ignore the concurrent hash invalidation that second
# get_hashes might have consolidated to hashes.pkl)
non_local = {}
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
orig_hash_suffix = df_mgr._hash_suffix
if existing:
# create hashes.pkl
part_path = os.path.join(self.devices, 'sda1',
diskfile.get_data_dir(policy), '0')
mkdirs(part_path)
df_mgr.get_hashes('sda1', '0', [], policy)
self.assertTrue(os.path.exists(os.path.join(
part_path, diskfile.HASH_FILE)))
df = df_mgr.get_diskfile('sda1', '0', 'a', 'c', 'o',
policy=policy)
suffix_dir = os.path.dirname(df._datadir)
suffix = os.path.basename(suffix_dir)
part_dir = os.path.dirname(suffix_dir)
invalidations_file = os.path.join(
part_dir, diskfile.HASH_INVALIDATIONS_FILE)
non_local['hash'] = None
non_local['called'] = False
# delete will append suffix to hashes.invalid
df.delete(self.ts())
with open(invalidations_file) as f:
self.assertEqual(suffix, f.read().strip('\n')) # sanity
hash1 = df_mgr._hash_suffix(suffix_dir)
def mock_hash_suffix(*args, **kwargs):
# after first get_hashes has called _hash_suffix, simulate a
# second process invalidating the same suffix, followed by a
# third process calling get_hashes and failing (or yielding)
# after consolidate_hashes has completed
result = orig_hash_suffix(*args, **kwargs)
if not non_local['called']:
non_local['called'] = True
# appends suffix to hashes.invalid
df.delete(self.ts())
# simulate another process calling get_hashes but failing
# after hash invalidation have been consolidated
hashes = df_mgr.consolidate_hashes(part_dir)
if existing:
self.assertTrue(hashes['valid'])
else:
self.assertFalse(hashes['valid'])
# get the updated suffix hash...
non_local['hash'] = orig_hash_suffix(suffix_dir)
return result
with mock.patch.object(df_mgr, '_hash_suffix', mock_hash_suffix):
# repeats listing when pkl modified
hashes = df_mgr.get_hashes('sda1', '0', [], policy)
# first get_hashes should complete with suffix1 state
self.assertIn(suffix, hashes)
# sanity check - the suffix hash has changed...
self.assertNotEqual(hash1, non_local['hash'])
# the invalidation file has been truncated...
with open(invalidations_file, 'r') as f:
self.assertEqual('', f.read())
# so hashes should have the latest suffix hash...
self.assertEqual(hashes[suffix], non_local['hash'])
non_local['called'] = False
with mock.patch.object(df_mgr, '_hash_suffix', mock_hash_suffix):
df_mgr.get_hashes('sda1', '0', [suffix], policy,
skip_rehash=True)
self.assertFalse(non_local['called'])
with open(invalidations_file) as f:
self.assertEqual(suffix, f.read().strip('\n')) # sanity
def test_hash_invalidations_race_get_hashes_same_suffix_new(self):
self._check_hash_invalidations_race_get_hashes_same_suffix(False)
def test_hash_invalidations_race_get_hashes_same_suffix_existing(self):
self._check_hash_invalidations_race_get_hashes_same_suffix(True)
def _check_unpickle_error_and_get_hashes_failure(self, existing):
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
df = df_mgr.get_diskfile('sda1', '0', 'a', 'c', 'o',
policy=policy)
suffix = os.path.basename(os.path.dirname(df._datadir))
# avoid getting O_TMPFILE warning in logs
if not utils.o_tmpfile_in_tmpdir_supported():
df.manager.use_linkat = False
if existing:
df.delete(self.ts())
hashes = df_mgr.get_hashes('sda1', '0', [], policy)
df.delete(self.ts())
part_path = os.path.join(self.devices, 'sda1',
diskfile.get_data_dir(policy), '0')
hashes_file = os.path.join(part_path, diskfile.HASH_FILE)
# write a corrupt hashes.pkl
open(hashes_file, 'w')
# simulate first call to get_hashes failing after attempting to
# consolidate hashes
with mock.patch('swift.obj.diskfile.os.listdir',
side_effect=Exception()):
self.assertRaises(
Exception, df_mgr.get_hashes, 'sda1', '0', [], policy)
# sanity on-disk state is invalid
with open(hashes_file, 'rb') as f:
found_hashes = pickle.load(f)
found_hashes.pop('updated')
self.assertEqual(False, found_hashes.pop('valid'))
# verify subsequent call to get_hashes reaches correct outcome
hashes = df_mgr.get_hashes('sda1', '0', [], policy)
self.assertIn(suffix, hashes)
self.assertEqual([], df_mgr.logger.get_lines_for_level('warning'))
def test_unpickle_error_and_get_hashes_failure_new_part(self):
self._check_unpickle_error_and_get_hashes_failure(False)
def test_unpickle_error_and_get_hashes_failure_existing_part(self):
self._check_unpickle_error_and_get_hashes_failure(True)
def test_invalidate_hash_consolidation(self):
def assert_consolidation(suffixes):
# verify that suffixes are invalidated after consolidation
with mock.patch('swift.obj.diskfile.lock_path') as mock_lock:
hashes = df_mgr.consolidate_hashes(part_path)
self.assertTrue(mock_lock.called)
for suffix in suffixes:
self.assertIn(suffix, hashes)
self.assertIsNone(hashes[suffix])
with open(hashes_file, 'rb') as f:
found_hashes = pickle.load(f)
self.assertTrue(hashes['valid'])
self.assertEqual(hashes, found_hashes)
with open(invalidations_file, 'r') as f:
self.assertEqual("", f.read())
return hashes
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
# create something to hash
df = df_mgr.get_diskfile('sda1', '0', 'a', 'c', 'o',
policy=policy)
df.delete(self.ts())
suffix_dir = os.path.dirname(df._datadir)
suffix = os.path.basename(suffix_dir)
original_hashes = df_mgr.get_hashes('sda1', '0', [], policy)
self.assertIn(suffix, original_hashes) # sanity
self.assertIsNotNone(original_hashes[suffix])
# sanity check hashes file
part_path = os.path.join(self.devices, 'sda1',
diskfile.get_data_dir(policy), '0')
hashes_file = os.path.join(part_path, diskfile.HASH_FILE)
invalidations_file = os.path.join(
part_path, diskfile.HASH_INVALIDATIONS_FILE)
with open(hashes_file, 'rb') as f:
found_hashes = pickle.load(f)
found_hashes.pop('updated')
self.assertTrue(found_hashes.pop('valid'))
self.assertEqual(original_hashes, found_hashes)
# invalidate the hash
with mock.patch('swift.obj.diskfile.lock_path') as mock_lock:
df_mgr.invalidate_hash(suffix_dir)
self.assertTrue(mock_lock.called)
# suffix should be in invalidations file
with open(invalidations_file, 'r') as f:
self.assertEqual(suffix + "\n", f.read())
# hashes file is unchanged
with open(hashes_file, 'rb') as f:
found_hashes = pickle.load(f)
found_hashes.pop('updated')
self.assertTrue(found_hashes.pop('valid'))
self.assertEqual(original_hashes, found_hashes)
# consolidate the hash and the invalidations
hashes = assert_consolidation([suffix])
# invalidate a different suffix hash in same partition but not in
# existing hashes.pkl
df2 = self.get_different_suffix_df(df)
df2.delete(self.ts())
suffix_dir2 = os.path.dirname(df2._datadir)
suffix2 = os.path.basename(suffix_dir2)
# suffix2 should be in invalidations file
with open(invalidations_file, 'r') as f:
self.assertEqual(suffix2 + "\n", f.read())
# hashes file is not yet changed
with open(hashes_file, 'rb') as f:
found_hashes = pickle.load(f)
self.assertTrue(hashes['valid'])
self.assertEqual(hashes, found_hashes)
# consolidate hashes
hashes = assert_consolidation([suffix, suffix2])
# invalidating suffix2 multiple times is ok
df2.delete(self.ts())
df2.delete(self.ts())
# suffix2 should be in invalidations file
with open(invalidations_file, 'r') as f:
invalids = f.read().splitlines()
self.assertEqual(sorted((suffix2, suffix2)),
sorted(invalids)) # sanity
# hashes file is not yet changed
with open(hashes_file, 'rb') as f:
found_hashes = pickle.load(f)
self.assertTrue(hashes['valid'])
self.assertEqual(hashes, found_hashes)
# consolidate hashes
assert_consolidation([suffix, suffix2])
# Might get some garbage in your invalidations file
part_dir = os.path.dirname(suffix_dir)
bad_suffix = "~" + suffix
df_mgr.invalidate_hash(os.path.join(part_dir, bad_suffix))
# Sure enough, it's in there
with open(invalidations_file, 'r') as f:
self.assertEqual(bad_suffix + "\n", f.read())
# ... but it won't taint your pickle
hashes = df_mgr.consolidate_hashes(part_path)
self.assertNotIn(bad_suffix, hashes)
with open(invalidations_file, 'r') as f:
self.assertEqual("", f.read())
# Old code doesn't have that protection
df_mgr.invalidate_hash(os.path.join(part_dir, bad_suffix))
with open(invalidations_file, 'r') as f:
self.assertEqual(bad_suffix + "\n", f.read())
with mock.patch.object(diskfile, 'valid_suffix', lambda s: True):
# ... so it would propogate to the pickle when we consolidate,
# and we ought to be able to deal with that
hashes = assert_consolidation([bad_suffix])
self.assertIn(bad_suffix, hashes)
self.assertIsNone(hashes[bad_suffix])
# When we go to really get hashes, we see the bad,
# throw out the existing pickle, and rehash everything
hashes = df_mgr.get_hashes('sda1', '0', [], policy)
self.assertNotIn(bad_suffix, hashes)
def test_get_hashes_consolidates_suffix_rehash_once(self):
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
df = df_mgr.get_diskfile('sda1', '0', 'a', 'c', 'o',
policy=policy)
df.delete(self.ts())
suffix_dir = os.path.dirname(df._datadir)
with mock.patch.object(df_mgr, 'consolidate_hashes',
side_effect=df_mgr.consolidate_hashes
) as mock_consolidate_hashes, \
mock.patch.object(df_mgr, '_hash_suffix',
side_effect=df_mgr._hash_suffix
) as mock_hash_suffix:
# creates pkl file
df_mgr.get_hashes('sda1', '0', [], policy)
mock_consolidate_hashes.assert_called_once()
self.assertEqual([mock.call(suffix_dir, policy=policy)],
mock_hash_suffix.call_args_list)
# second object in path
df2 = self.get_different_suffix_df(df)
df2.delete(self.ts())
suffix_dir2 = os.path.dirname(df2._datadir)
mock_consolidate_hashes.reset_mock()
mock_hash_suffix.reset_mock()
# updates pkl file
df_mgr.get_hashes('sda1', '0', [], policy)
mock_consolidate_hashes.assert_called_once()
self.assertEqual([mock.call(suffix_dir2, policy=policy)],
mock_hash_suffix.call_args_list)
def test_consolidate_hashes_raises_exception(self):
# verify that if consolidate_hashes raises an exception then suffixes
# are rehashed and a hashes.pkl is written
for policy in self.iter_policies():
part_path = os.path.join(self.devices, 'sda1',
diskfile.get_data_dir(policy), '0')
hashes_file = os.path.join(part_path, diskfile.HASH_FILE)
invalidations_file = os.path.join(
part_path, diskfile.HASH_INVALIDATIONS_FILE)
self.logger.clear()
df_mgr = self.df_router[policy]
# create something to hash
df = df_mgr.get_diskfile('sda1', '0', 'a', 'c', 'o',
policy=policy)
# avoid getting O_TMPFILE warning in logs
if not utils.o_tmpfile_in_tmpdir_supported():
df.manager.use_linkat = False
self.assertFalse(os.path.exists(part_path))
df.delete(self.ts())
self.assertTrue(os.path.exists(invalidations_file))
suffix_dir = os.path.dirname(df._datadir)
suffix = os.path.basename(suffix_dir)
# no pre-existing hashes.pkl
self.assertFalse(os.path.exists(hashes_file))
with mock.patch.object(df_mgr, '_hash_suffix',
return_value='fake hash'):
with mock.patch.object(df_mgr, 'consolidate_hashes',
side_effect=Exception()):
hashes = df_mgr.get_hashes('sda1', '0', [], policy)
self.assertEqual({suffix: 'fake hash'}, hashes)
# sanity check hashes file
with open(hashes_file, 'rb') as f:
found_hashes = pickle.load(f)
found_hashes.pop('updated')
self.assertTrue(found_hashes.pop('valid'))
self.assertEqual(hashes, found_hashes)
# sanity check log warning
warnings = self.logger.get_lines_for_level('warning')
self.assertEqual(warnings, ["Unable to read %r" % hashes_file])
# repeat with pre-existing hashes.pkl
self.logger.clear()
with mock.patch.object(df_mgr, '_hash_suffix',
return_value='new fake hash'):
with mock.patch.object(df_mgr, 'consolidate_hashes',
side_effect=Exception()):
hashes = df_mgr.get_hashes('sda1', '0', [], policy)
self.assertEqual({suffix: 'new fake hash'}, hashes)
# sanity check hashes file
with open(hashes_file, 'rb') as f:
found_hashes = pickle.load(f)
found_hashes.pop('updated')
self.assertTrue(found_hashes.pop('valid'))
self.assertEqual(hashes, found_hashes)
# sanity check log warning
warnings = self.logger.get_lines_for_level('warning')
self.assertEqual(warnings, ["Unable to read %r" % hashes_file])
# invalidate_hash tests - error handling
def test_invalidate_hash_bad_pickle(self):
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
# make some valid data
df = df_mgr.get_diskfile('sda1', '0', 'a', 'c', 'o',
policy=policy)
suffix_dir = os.path.dirname(df._datadir)
suffix = os.path.basename(suffix_dir)
df.delete(self.ts())
# sanity check hashes file
part_path = os.path.join(self.devices, 'sda1',
diskfile.get_data_dir(policy), '0')
hashes_file = os.path.join(part_path, diskfile.HASH_FILE)
self.assertFalse(os.path.exists(hashes_file))
# write some garbage in hashes file
with open(hashes_file, 'w') as f:
f.write('asdf')
# invalidate_hash silently *NOT* repair invalid data
df_mgr.invalidate_hash(suffix_dir)
with open(hashes_file) as f:
self.assertEqual(f.read(), 'asdf')
# ... but get_hashes will
hashes = df_mgr.get_hashes('sda1', '0', [], policy)
self.assertIn(suffix, hashes)
# get_hashes tests - hash_suffix behaviors
def test_hash_suffix_one_tombstone(self):
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
df = df_mgr.get_diskfile(
'sda1', '0', 'a', 'c', 'o', policy=policy)
suffix = os.path.basename(os.path.dirname(df._datadir))
# write a tombstone
timestamp = self.ts()
df.delete(timestamp)
tombstone_hash = md5(timestamp.internal + '.ts').hexdigest()
hashes = df_mgr.get_hashes('sda1', '0', [], policy)
expected = {
REPL_POLICY: {suffix: tombstone_hash},
EC_POLICY: {suffix: {
# fi is None here because we have a tombstone
None: tombstone_hash}},
}[policy.policy_type]
self.assertEqual(hashes, expected)
def test_hash_suffix_one_tombstone_and_one_meta(self):
# A tombstone plus a newer meta file can happen if a tombstone is
# replicated to a node with a newer meta file but older data file. The
# meta file will be ignored when the diskfile is opened so the
# effective state of the disk files is equivalent to only having the
# tombstone. Replication cannot remove the meta file, and the meta file
# cannot be ssync replicated to a node with only the tombstone, so
# we want the get_hashes result to be the same as if the meta file was
# not there.
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
df = df_mgr.get_diskfile(
'sda1', '0', 'a', 'c', 'o', policy=policy)
suffix = os.path.basename(os.path.dirname(df._datadir))
# write a tombstone
timestamp = self.ts()
df.delete(timestamp)
# write a meta file
df.write_metadata({'X-Timestamp': self.ts().internal})
# sanity check
self.assertEqual(2, len(os.listdir(df._datadir)))
tombstone_hash = md5(timestamp.internal + '.ts').hexdigest()
hashes = df_mgr.get_hashes('sda1', '0', [], policy)
expected = {
REPL_POLICY: {suffix: tombstone_hash},
EC_POLICY: {suffix: {
# fi is None here because we have a tombstone
None: tombstone_hash}},
}[policy.policy_type]
self.assertEqual(hashes, expected)
def test_hash_suffix_one_reclaim_tombstone_and_one_meta(self):
# An isolated meta file can happen if a tombstone is replicated to a
# node with a newer meta file but older data file, and the tombstone is
# subsequently reclaimed. The meta file will be ignored when the
# diskfile is opened so the effective state of the disk files is
# equivalent to having no files.
for policy in self.iter_policies():
if policy.policy_type == EC_POLICY:
continue
df_mgr = self.df_router[policy]
df = df_mgr.get_diskfile(
'sda1', '0', 'a', 'c', 'o', policy=policy)
suffix = os.path.basename(os.path.dirname(df._datadir))
now = time()
# write a tombstone that's just a *little* older than reclaim time
df.delete(Timestamp(now - 1001))
# write a meta file that's not quite so old
ts_meta = Timestamp(now - 501)
df.write_metadata({'X-Timestamp': ts_meta.internal})
# sanity check
self.assertEqual(2, len(os.listdir(df._datadir)))
# scale back the df manager's reclaim age a bit to make the
# tombstone reclaimable
df_mgr.reclaim_age = 1000
hashes = df_mgr.get_hashes('sda1', '0', [], policy)
# the tombstone is reclaimed, the meta file remains, the suffix
# hash is not updated BUT the suffix dir cannot be deleted so
# a suffix hash equal to hash of empty string is reported.
# TODO: this is not same result as if the meta file did not exist!
self.assertEqual([ts_meta.internal + '.meta'],
os.listdir(df._datadir))
self.assertEqual(hashes, {suffix: MD5_OF_EMPTY_STRING})
# scale back the df manager's reclaim age even more - call to
# get_hashes does not trigger reclaim because the suffix has
# MD5_OF_EMPTY_STRING in hashes.pkl
df_mgr.reclaim_age = 500
df_mgr.commit_window = 0
hashes = df_mgr.get_hashes('sda1', '0', [], policy)
self.assertEqual([ts_meta.internal + '.meta'],
os.listdir(df._datadir))
self.assertEqual(hashes, {suffix: MD5_OF_EMPTY_STRING})
# call get_hashes with recalculate = [suffix] and the suffix dir
# gets re-hashed so the .meta if finally reclaimed.
hashes = df_mgr.get_hashes('sda1', '0', [suffix], policy)
self.assertFalse(os.path.exists(os.path.dirname(df._datadir)))
self.assertEqual(hashes, {})
def test_hash_suffix_one_reclaim_tombstone(self):
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
df = df_mgr.get_diskfile(
'sda1', '0', 'a', 'c', 'o', policy=policy)
# scale back this tests manager's reclaim age a bit
df_mgr.reclaim_age = 1000
# write a tombstone that's just a *little* older
old_time = time() - 1001
timestamp = Timestamp(old_time)
df.delete(timestamp.internal)
hashes = df_mgr.get_hashes('sda1', '0', [], policy)
self.assertEqual(hashes, {})
def test_hash_suffix_ts_cleanup_after_recalc(self):
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
df = df_mgr.get_diskfile(
'sda1', '0', 'a', 'c', 'o', policy=policy)
suffix_dir = os.path.dirname(df._datadir)
suffix = os.path.basename(suffix_dir)
# scale back reclaim age a bit
df_mgr.reclaim_age = 1000
# write a valid tombstone
old_time = time() - 500
timestamp = Timestamp(old_time)
df.delete(timestamp.internal)
hashes = df_mgr.get_hashes('sda1', '0', [], policy)
self.assertIn(suffix, hashes)
self.assertIsNotNone(hashes[suffix])
# we have tombstone entry
tombstone = '%s.ts' % timestamp.internal
self.assertTrue(os.path.exists(df._datadir))
self.assertIn(tombstone, os.listdir(df._datadir))
# lower reclaim age to force tombstone reclaiming
df_mgr.reclaim_age = 200
# not cleaning up because suffix not invalidated
hashes = df_mgr.get_hashes('sda1', '0', [], policy)
self.assertTrue(os.path.exists(df._datadir))
self.assertIn(tombstone, os.listdir(df._datadir))
self.assertIn(suffix, hashes)
self.assertIsNotNone(hashes[suffix])
# recalculating suffix hash cause cleanup
hashes = df_mgr.get_hashes('sda1', '0', [suffix], policy)
self.assertEqual(hashes, {})
self.assertFalse(os.path.exists(df._datadir))
def test_hash_suffix_ts_cleanup_after_invalidate_hash(self):
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
df = df_mgr.get_diskfile(
'sda1', '0', 'a', 'c', 'o', policy=policy)
suffix_dir = os.path.dirname(df._datadir)
suffix = os.path.basename(suffix_dir)
# scale back reclaim age a bit
df_mgr.reclaim_age = 1000
# write a valid tombstone
old_time = time() - 500
timestamp = Timestamp(old_time)
df.delete(timestamp.internal)
hashes = df_mgr.get_hashes('sda1', '0', [], policy)
self.assertIn(suffix, hashes)
self.assertIsNotNone(hashes[suffix])
# we have tombstone entry
tombstone = '%s.ts' % timestamp.internal
self.assertTrue(os.path.exists(df._datadir))
self.assertIn(tombstone, os.listdir(df._datadir))
# lower reclaim age to force tombstone reclaiming
df_mgr.reclaim_age = 200
# not cleaning up because suffix not invalidated
hashes = df_mgr.get_hashes('sda1', '0', [], policy)
self.assertTrue(os.path.exists(df._datadir))
self.assertIn(tombstone, os.listdir(df._datadir))
self.assertIn(suffix, hashes)
self.assertIsNotNone(hashes[suffix])
# However if we call invalidate_hash for the suffix dir,
# get_hashes can reclaim the tombstone
with mock.patch('swift.obj.diskfile.lock_path'):
df_mgr.invalidate_hash(suffix_dir)
# updating invalidated hashes cause cleanup
hashes = df_mgr.get_hashes('sda1', '0', [], policy)
self.assertEqual(hashes, {})
self.assertFalse(os.path.exists(df._datadir))
def test_hash_suffix_one_reclaim_and_one_valid_tombstone(self):
paths, suffix = find_paths_with_matching_suffixes(2, 1)
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
a, c, o = paths[suffix][0]
df1 = df_mgr.get_diskfile(
'sda1', '0', a, c, o, policy=policy)
# scale back this tests manager's reclaim age a bit
df_mgr.reclaim_age = 1000
# write one tombstone that's just a *little* older
df1.delete(Timestamp(time() - 1001))
# create another tombstone in same suffix dir that's newer
a, c, o = paths[suffix][1]
df2 = df_mgr.get_diskfile(
'sda1', '0', a, c, o, policy=policy)
t_df2 = Timestamp(time() - 900)
df2.delete(t_df2)
hashes = df_mgr.get_hashes('sda1', '0', [], policy)
suffix = os.path.basename(os.path.dirname(df1._datadir))
df2_tombstone_hash = md5(t_df2.internal + '.ts').hexdigest()
expected = {
REPL_POLICY: {suffix: df2_tombstone_hash},
EC_POLICY: {suffix: {
# fi is None here because we have a tombstone
None: df2_tombstone_hash}},
}[policy.policy_type]
self.assertEqual(hashes, expected)
def test_hash_suffix_one_datafile(self):
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
df = df_mgr.get_diskfile(
'sda1', '0', 'a', 'c', 'o', policy=policy, frag_index=7)
suffix = os.path.basename(os.path.dirname(df._datadir))
# write a datafile
timestamp = self.ts()
with df.create() as writer:
test_data = b'test file'
writer.write(test_data)
metadata = {
'X-Timestamp': timestamp.internal,
'ETag': md5(test_data).hexdigest(),
'Content-Length': len(test_data),
}
writer.put(metadata)
# note - no commit so data is non-durable
hashes = df_mgr.get_hashes('sda1', '0', [], policy)
datafile_hash = md5({
EC_POLICY: timestamp.internal,
REPL_POLICY: timestamp.internal + '.data',
}[policy.policy_type]).hexdigest()
expected = {
REPL_POLICY: {suffix: datafile_hash},
EC_POLICY: {suffix: {
# because there's no durable state, we have no hash for
# the None key - only the frag index for the data file
7: datafile_hash}},
}[policy.policy_type]
msg = 'expected %r != %r for policy %r' % (
expected, hashes, policy)
self.assertEqual(hashes, expected, msg)
def test_hash_suffix_multi_file_ends_in_tombstone(self):
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
df = df_mgr.get_diskfile('sda1', '0', 'a', 'c', 'o', policy=policy,
frag_index=4)
suffix = os.path.basename(os.path.dirname(df._datadir))
mkdirs(df._datadir)
now = time()
# go behind the scenes and setup a bunch of weird file names
for tdiff in [500, 100, 10, 1]:
for suff in ['.meta', '.data', '.ts']:
timestamp = Timestamp(now - tdiff)
filename = timestamp.internal
if policy.policy_type == EC_POLICY and suff == '.data':
filename += '#%s' % df._frag_index
filename += suff
open(os.path.join(df._datadir, filename), 'w').close()
tombstone_hash = md5(filename).hexdigest()
# call get_hashes and it should clean things up
hashes = df_mgr.get_hashes('sda1', '0', [], policy)
expected = {
REPL_POLICY: {suffix: tombstone_hash},
EC_POLICY: {suffix: {
# fi is None here because we have a tombstone
None: tombstone_hash}},
}[policy.policy_type]
self.assertEqual(hashes, expected)
# only the tombstone should be left
found_files = os.listdir(df._datadir)
self.assertEqual(found_files, [filename])
def _do_hash_suffix_multi_file_ends_in_datafile(self, policy,
legacy_durable):
# if legacy_durable is True then synthesize legacy durable files
# instead of having a durable marker in the data file name
frag_index = 4
df_mgr = self.df_router[policy]
df = df_mgr.get_diskfile('sda1', '0', 'a', 'c', 'o', policy=policy,
frag_index=frag_index)
suffix = os.path.basename(os.path.dirname(df._datadir))
mkdirs(df._datadir)
now = time()
timestamp = None
# go behind the scenes and setup a bunch of weird file names
for tdiff in [500, 100, 10, 1]:
suffs = ['.meta', '.data']
if tdiff > 50:
suffs.append('.ts')
if policy.policy_type == EC_POLICY and legacy_durable:
suffs.append('.durable')
for suff in suffs:
timestamp = Timestamp(now - tdiff)
if suff == '.data':
filename = _make_datafilename(
timestamp, policy, frag_index,
durable=not legacy_durable)
else:
filename = timestamp.internal + suff
open(os.path.join(df._datadir, filename), 'w').close()
meta_timestamp = Timestamp(now)
metadata_filename = meta_timestamp.internal + '.meta'
open(os.path.join(df._datadir, metadata_filename), 'w').close()
# call get_hashes and it should clean up all but the most recent files
hashes = df_mgr.get_hashes('sda1', '0', [], policy)
# calculate expected outcome
data_filename = _make_datafilename(
timestamp, policy, frag_index, durable=not legacy_durable)
expected_files = [data_filename, metadata_filename]
if policy.policy_type == EC_POLICY:
# note: expected hashes is same with or without legacy durable file
hasher = md5()
hasher.update(metadata_filename)
hasher.update(timestamp.internal + '.durable')
expected = {
suffix: {
# metadata & durable updates are hashed separately
None: hasher.hexdigest(),
4: self.fname_to_ts_hash(data_filename),
}
}
if legacy_durable:
expected_files.append(timestamp.internal + '.durable')
elif policy.policy_type == REPL_POLICY:
hasher = md5()
hasher.update(metadata_filename)
hasher.update(data_filename)
expected = {suffix: hasher.hexdigest()}
else:
self.fail('unknown policy type %r' % policy.policy_type)
self.assertEqual(hashes, expected)
# only the meta and data should be left
self.assertEqual(sorted(os.listdir(df._datadir)),
sorted(expected_files))
def test_hash_suffix_multifile_ends_in_datafile(self):
for policy in self.iter_policies():
self._do_hash_suffix_multi_file_ends_in_datafile(
policy, legacy_durable=False)
def test_hash_suffix_multifile_ends_in_datafile_legacy_durable(self):
for policy in self.iter_policies():
if policy.policy_type == EC_POLICY:
self._do_hash_suffix_multi_file_ends_in_datafile(
policy, legacy_durable=True)
def _verify_get_hashes(self, filenames, ts_data, ts_meta, ts_ctype,
policy):
"""
Helper method to create a set of ondisk files and verify suffix_hashes.
:param filenames: list of filenames to create in an object hash dir
:param ts_data: newest data timestamp, used for expected result
:param ts_meta: newest meta timestamp, used for expected result
:param ts_ctype: newest content-type timestamp, used for expected
result
:param policy: storage policy to use for test
"""
df_mgr = self.df_router[policy]
df = df_mgr.get_diskfile('sda1', '0', 'a', 'c', 'o',
policy=policy, frag_index=4)
suffix = os.path.basename(os.path.dirname(df._datadir))
partition_dir = os.path.dirname(os.path.dirname(df._datadir))
rmtree(partition_dir, ignore_errors=True) # clean dir for each test
mkdirs(df._datadir)
# calculate expected result
hasher = md5()
if policy.policy_type == EC_POLICY:
hasher.update(ts_meta.internal + '.meta')
hasher.update(ts_data.internal + '.durable')
if ts_ctype:
hasher.update(ts_ctype.internal + '_ctype')
expected = {
suffix: {
None: hasher.hexdigest(),
4: md5(ts_data.internal).hexdigest(),
}
}
elif policy.policy_type == REPL_POLICY:
hasher.update(ts_meta.internal + '.meta')
hasher.update(ts_data.internal + '.data')
if ts_ctype:
hasher.update(ts_ctype.internal + '_ctype')
expected = {suffix: hasher.hexdigest()}
else:
self.fail('unknown policy type %r' % policy.policy_type)
for fname in filenames:
open(os.path.join(df._datadir, fname), 'w').close()
hashes = df_mgr.get_hashes('sda1', '0', [], policy)
msg = 'expected %r != %r for policy %r' % (
expected, hashes, policy)
self.assertEqual(hashes, expected, msg)
def test_hash_suffix_with_older_content_type_in_meta(self):
# single meta file having older content-type
def do_test(legacy_durable):
for policy in self.iter_policies():
ts_data, ts_ctype, ts_meta = (
self.ts(), self.ts(), self.ts())
filenames = [_make_datafilename(ts_data, policy, frag_index=4,
durable=not legacy_durable),
_make_metafilename(ts_meta, ts_ctype)]
if policy.policy_type == EC_POLICY and legacy_durable:
filenames.append(ts_data.internal + '.durable')
self._verify_get_hashes(
filenames, ts_data, ts_meta, ts_ctype, policy)
do_test(False)
do_test(True)
def test_hash_suffix_with_same_age_content_type_in_meta(self):
# single meta file having same age content-type
def do_test(legacy_durable):
for policy in self.iter_policies():
ts_data, ts_meta = (self.ts(), self.ts())
filenames = [_make_datafilename(ts_data, policy, frag_index=4,
durable=not legacy_durable),
_make_metafilename(ts_meta, ts_meta)]
if policy.policy_type == EC_POLICY and legacy_durable:
filenames.append(ts_data.internal + '.durable')
self._verify_get_hashes(
filenames, ts_data, ts_meta, ts_meta, policy)
do_test(False)
do_test(True)
def test_hash_suffix_with_obsolete_content_type_in_meta(self):
# After rsync replication we could have a single meta file having
# content-type older than a replicated data file
def do_test(legacy_durable):
for policy in self.iter_policies():
ts_ctype, ts_data, ts_meta = (self.ts(), self.ts(), self.ts())
filenames = [_make_datafilename(ts_data, policy, frag_index=4,
durable=not legacy_durable),
_make_metafilename(ts_meta, ts_ctype)]
if policy.policy_type == EC_POLICY and legacy_durable:
filenames.append(ts_data.internal + '.durable')
self._verify_get_hashes(
filenames, ts_data, ts_meta, None, policy)
do_test(False)
do_test(True)
def test_hash_suffix_with_older_content_type_in_newer_meta(self):
# After rsync replication we could have two meta files: newest
# content-type is in newer meta file, older than newer meta file
def do_test(legacy_durable):
for policy in self.iter_policies():
ts_data, ts_older_meta, ts_ctype, ts_newer_meta = (
self.ts() for _ in range(4))
filenames = [_make_datafilename(ts_data, policy, frag_index=4,
durable=not legacy_durable),
_make_metafilename(ts_older_meta),
_make_metafilename(ts_newer_meta, ts_ctype)]
if policy.policy_type == EC_POLICY and legacy_durable:
filenames.append(ts_data.internal + '.durable')
self._verify_get_hashes(
filenames, ts_data, ts_newer_meta, ts_ctype, policy)
do_test(False)
do_test(True)
def test_hash_suffix_with_same_age_content_type_in_newer_meta(self):
# After rsync replication we could have two meta files: newest
# content-type is in newer meta file, at same age as newer meta file
def do_test(legacy_durable):
for policy in self.iter_policies():
ts_data, ts_older_meta, ts_newer_meta = (
self.ts() for _ in range(3))
filenames = [_make_datafilename(ts_data, policy, frag_index=4,
durable=not legacy_durable),
_make_metafilename(ts_newer_meta, ts_newer_meta)]
if policy.policy_type == EC_POLICY and legacy_durable:
filenames.append(ts_data.internal + '.durable')
self._verify_get_hashes(
filenames, ts_data, ts_newer_meta, ts_newer_meta, policy)
do_test(False)
do_test(True)
def test_hash_suffix_with_older_content_type_in_older_meta(self):
# After rsync replication we could have two meta files: newest
# content-type is in older meta file, older than older meta file
def do_test(legacy_durable):
for policy in self.iter_policies():
ts_data, ts_ctype, ts_older_meta, ts_newer_meta = (
self.ts() for _ in range(4))
filenames = [_make_datafilename(ts_data, policy, frag_index=4,
durable=not legacy_durable),
_make_metafilename(ts_newer_meta),
_make_metafilename(ts_older_meta, ts_ctype)]
if policy.policy_type == EC_POLICY and legacy_durable:
filenames.append(ts_data.internal + '.durable')
self._verify_get_hashes(
filenames, ts_data, ts_newer_meta, ts_ctype, policy)
do_test(False)
do_test(True)
def test_hash_suffix_with_same_age_content_type_in_older_meta(self):
# After rsync replication we could have two meta files: newest
# content-type is in older meta file, at same age as older meta file
def do_test(legacy_durable):
for policy in self.iter_policies():
ts_data, ts_older_meta, ts_newer_meta = (
self.ts() for _ in range(3))
filenames = [_make_datafilename(ts_data, policy, frag_index=4,
durable=not legacy_durable),
_make_metafilename(ts_newer_meta),
_make_metafilename(ts_older_meta, ts_older_meta)]
if policy.policy_type == EC_POLICY and legacy_durable:
filenames.append(ts_data.internal + '.durable')
self._verify_get_hashes(
filenames, ts_data, ts_newer_meta, ts_older_meta, policy)
do_test(False)
do_test(True)
def test_hash_suffix_with_obsolete_content_type_in_older_meta(self):
# After rsync replication we could have two meta files: newest
# content-type is in older meta file, but older than data file
def do_test(legacy_durable):
for policy in self.iter_policies():
ts_ctype, ts_data, ts_older_meta, ts_newer_meta = (
self.ts() for _ in range(4))
filenames = [_make_datafilename(ts_data, policy, frag_index=4,
durable=not legacy_durable),
_make_metafilename(ts_newer_meta),
_make_metafilename(ts_older_meta, ts_ctype)]
if policy.policy_type == EC_POLICY and legacy_durable:
filenames.append(ts_data.internal + '.durable')
self._verify_get_hashes(
filenames, ts_data, ts_newer_meta, None, policy)
do_test(False)
do_test(True)
def test_hash_suffix_removes_empty_hashdir_and_suffix(self):
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
df = df_mgr.get_diskfile('sda1', '0', 'a', 'c', 'o',
policy=policy, frag_index=2)
os.makedirs(df._datadir)
self.assertTrue(os.path.exists(df._datadir)) # sanity
df_mgr.get_hashes('sda1', '0', [], policy)
suffix_dir = os.path.dirname(df._datadir)
self.assertFalse(os.path.exists(suffix_dir))
def test_hash_suffix_removes_empty_hashdirs_in_valid_suffix(self):
paths, suffix = find_paths_with_matching_suffixes(needed_matches=3,
needed_suffixes=0)
matching_paths = paths.pop(suffix)
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
df = df_mgr.get_diskfile('sda1', '0', *matching_paths[0],
policy=policy, frag_index=2)
# create a real, valid hsh_path
df.delete(Timestamp.now())
# and a couple of empty hsh_paths
empty_hsh_paths = []
for path in matching_paths[1:]:
fake_df = df_mgr.get_diskfile('sda1', '0', *path,
policy=policy)
os.makedirs(fake_df._datadir)
empty_hsh_paths.append(fake_df._datadir)
for hsh_path in empty_hsh_paths:
self.assertTrue(os.path.exists(hsh_path)) # sanity
# get_hashes will cleanup empty hsh_path and leave valid one
hashes = df_mgr.get_hashes('sda1', '0', [], policy)
self.assertIn(suffix, hashes)
self.assertTrue(os.path.exists(df._datadir))
for hsh_path in empty_hsh_paths:
self.assertFalse(os.path.exists(hsh_path))
# get_hashes tests - hash_suffix error handling
def test_hash_suffix_listdir_enotdir(self):
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
suffix = '123'
suffix_path = os.path.join(self.devices, 'sda1',
diskfile.get_data_dir(policy), '0',
suffix)
os.makedirs(suffix_path)
self.assertTrue(os.path.exists(suffix_path)) # sanity
hashes = df_mgr.get_hashes('sda1', '0', [suffix], policy)
# suffix dir cleaned up by get_hashes
self.assertFalse(os.path.exists(suffix_path))
expected = {}
msg = 'expected %r != %r for policy %r' % (
expected, hashes, policy)
self.assertEqual(hashes, expected, msg)
# now make the suffix path a file
open(suffix_path, 'w').close()
hashes = df_mgr.get_hashes('sda1', '0', [suffix], policy)
expected = {}
msg = 'expected %r != %r for policy %r' % (
expected, hashes, policy)
self.assertEqual(hashes, expected, msg)
def test_hash_suffix_listdir_enoent(self):
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
part_path = os.path.join(self.devices, 'sda1',
diskfile.get_data_dir(policy), '0')
mkdirs(part_path) # ensure we'll bother writing a pkl at all
orig_listdir = os.listdir
listdir_calls = []
def mock_listdir(path):
success = False
try:
rv = orig_listdir(path)
success = True
return rv
finally:
listdir_calls.append((path, success))
with mock.patch('swift.obj.diskfile.os.listdir',
mock_listdir):
# recalc always forces hash_suffix even if the suffix
# does not exist!
df_mgr.get_hashes('sda1', '0', ['123'], policy)
self.assertEqual(listdir_calls, [
# part path gets created automatically
(part_path, True),
# this one blows up
(os.path.join(part_path, '123'), False),
])
def test_hash_suffix_cleanup_ondisk_files_enotdir_quarantined(self):
for policy in self.iter_policies():
df = self.df_router[policy].get_diskfile(
self.existing_device, '0', 'a', 'c', 'o', policy=policy)
# make the suffix directory
suffix_path = os.path.dirname(df._datadir)
os.makedirs(suffix_path)
suffix = os.path.basename(suffix_path)
# make the df hash path a file
open(df._datadir, 'wb').close()
df_mgr = self.df_router[policy]
hashes = df_mgr.get_hashes(self.existing_device, '0', [suffix],
policy)
self.assertEqual(hashes, {})
# and hash path is quarantined
self.assertFalse(os.path.exists(df._datadir))
# each device a quarantined directory
quarantine_base = os.path.join(self.devices,
self.existing_device, 'quarantined')
# the quarantine path is...
quarantine_path = os.path.join(
quarantine_base, # quarantine root
diskfile.get_data_dir(policy), # per-policy data dir
os.path.basename(df._datadir) # name of quarantined file
)
self.assertTrue(os.path.exists(quarantine_path))
def test_auditor_hashdir_not_listable(self):
def list_locations(dirname, datadir):
return [(loc.path, loc.device, loc.partition, loc.policy)
for loc in diskfile.object_audit_location_generator(
devices=dirname, datadir=datadir, mount_check=False)]
real_listdir = os.listdir
def splode_if_endswith(suffix, err):
def sploder(path):
if path.endswith(suffix):
raise OSError(err, os.strerror(err))
else:
return real_listdir(path)
return sploder
with temptree([]) as tmpdir:
hashdir1 = os.path.join(tmpdir, "sdf", "objects", "2607", "b54",
"fe450ec990a88cc4b252b181bab04b54")
os.makedirs(hashdir1)
with open(os.path.join(hashdir1, '1656032666.98003.ts'), 'w'):
pass
hashdir2 = os.path.join(tmpdir, "sdf", "objects", "2809", "afd",
"7089ab48d955ab0851fc51cc17a34afd")
os.makedirs(hashdir2)
with open(os.path.join(hashdir2, '1656080624.31899.ts'), 'w'):
pass
expected = [(hashdir2, 'sdf', '2809', POLICIES[0])]
# Parts that look like files are just skipped
with mock.patch('os.listdir', splode_if_endswith(
"2607", errno.ENOTDIR)):
self.assertEqual(expected, list_locations(tmpdir, 'objects'))
diskfile.clear_auditor_status(tmpdir, 'objects')
# ENODATA on a suffix is ok
with mock.patch('os.listdir', splode_if_endswith(
"b54", errno.ENODATA)):
self.assertEqual(expected, list_locations(tmpdir, 'objects'))
diskfile.clear_auditor_status(tmpdir, 'objects')
# EUCLEAN too
with mock.patch('os.listdir', splode_if_endswith(
"b54", EUCLEAN)):
self.assertEqual(expected, list_locations(tmpdir, 'objects'))
diskfile.clear_auditor_status(tmpdir, 'objects')
# sanity the other way
expected = [(hashdir1, 'sdf', '2607', POLICIES[0])]
with mock.patch('os.listdir', splode_if_endswith(
"2809", errno.ENODATA)):
self.assertEqual(expected, list_locations(tmpdir, 'objects'))
diskfile.clear_auditor_status(tmpdir, 'objects')
with mock.patch('os.listdir', splode_if_endswith(
"2809", EUCLEAN)):
self.assertEqual(expected, list_locations(tmpdir, 'objects'))
diskfile.clear_auditor_status(tmpdir, 'objects')
with mock.patch('os.listdir', splode_if_endswith(
"afd", errno.ENOTDIR)):
self.assertEqual(expected, list_locations(tmpdir, 'objects'))
diskfile.clear_auditor_status(tmpdir, 'objects')
def test_hash_suffix_cleanup_ondisk_files_enodata_quarantined(self):
for policy in self.iter_policies():
df = self.df_router[policy].get_diskfile(
self.existing_device, '0', 'a', 'c', 'o', policy=policy)
# make everything down to the hash directory
os.makedirs(df._datadir)
suffix = os.path.basename(os.path.dirname(df._datadir))
orig_listdir = os.listdir
def fake_listdir(path):
if path == df._datadir:
raise OSError(errno.ENODATA, 'nope')
return orig_listdir(path)
df_mgr = self.df_router[policy]
with mock.patch('os.listdir', side_effect=fake_listdir):
hashes = df_mgr.get_hashes(self.existing_device, '0', [suffix],
policy)
self.assertEqual(hashes, {})
# and hash path is quarantined
self.assertFalse(os.path.exists(df._datadir))
# each device a quarantined directory
quarantine_base = os.path.join(self.devices,
self.existing_device, 'quarantined')
# the quarantine path is...
quarantine_path = os.path.join(
quarantine_base, # quarantine root
diskfile.get_data_dir(policy), # per-policy data dir
os.path.basename(df._datadir) # name of quarantined file
)
self.assertTrue(os.path.exists(quarantine_path))
def test_hash_suffix_cleanup_ondisk_files_euclean_quarantined(self):
for policy in self.iter_policies():
df = self.df_router[policy].get_diskfile(
self.existing_device, '0', 'a', 'c', 'o', policy=policy)
# make everything down to the hash directory
os.makedirs(df._datadir)
suffix = os.path.basename(os.path.dirname(df._datadir))
orig_listdir = os.listdir
def fake_listdir(path):
if path == df._datadir:
raise OSError(EUCLEAN, 'nope')
return orig_listdir(path)
df_mgr = self.df_router[policy]
with mock.patch('os.listdir', side_effect=fake_listdir):
hashes = df_mgr.get_hashes(self.existing_device, '0', [suffix],
policy)
self.assertEqual(hashes, {})
# and hash path is quarantined
self.assertFalse(os.path.exists(df._datadir))
# each device a quarantined directory
quarantine_base = os.path.join(self.devices,
self.existing_device, 'quarantined')
# the quarantine path is...
quarantine_path = os.path.join(
quarantine_base, # quarantine root
diskfile.get_data_dir(policy), # per-policy data dir
os.path.basename(df._datadir) # name of quarantined file
)
self.assertTrue(os.path.exists(quarantine_path))
def test_hash_suffix_cleanup_ondisk_files_other_oserror(self):
for policy in self.iter_policies():
timestamp = self.ts()
df_mgr = self.df_router[policy]
df = df_mgr.get_diskfile(self.existing_device, '0', 'a', 'c',
'o', policy=policy,
frag_index=7)
suffix = os.path.basename(os.path.dirname(df._datadir))
with df.create() as writer:
test_data = b'test_data'
writer.write(test_data)
metadata = {
'X-Timestamp': timestamp.internal,
'ETag': md5(test_data).hexdigest(),
'Content-Length': len(test_data),
}
writer.put(metadata)
orig_os_listdir = os.listdir
listdir_calls = []
part_path = os.path.join(self.devices, self.existing_device,
diskfile.get_data_dir(policy), '0')
suffix_path = os.path.join(part_path, suffix)
datadir_path = os.path.join(suffix_path, hash_path('a', 'c', 'o'))
def mock_os_listdir(path):
listdir_calls.append(path)
if path == datadir_path:
# we want the part and suffix listdir calls to pass and
# make the cleanup_ondisk_files raise an exception
raise OSError(errno.EACCES, os.strerror(errno.EACCES))
return orig_os_listdir(path)
with mock.patch('os.listdir', mock_os_listdir):
hashes = df_mgr.get_hashes(self.existing_device, '0', [],
policy)
self.assertEqual(listdir_calls, [
part_path,
suffix_path,
datadir_path,
])
expected = {suffix: None}
msg = 'expected %r != %r for policy %r' % (
expected, hashes, policy)
self.assertEqual(hashes, expected, msg)
def test_hash_suffix_rmdir_hsh_path_oserror(self):
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
# make an empty hsh_path to be removed
df = df_mgr.get_diskfile(self.existing_device, '0', 'a', 'c',
'o', policy=policy)
os.makedirs(df._datadir)
suffix = os.path.basename(os.path.dirname(df._datadir))
with mock.patch('os.rmdir', side_effect=OSError()):
hashes = df_mgr.get_hashes(self.existing_device, '0', [],
policy)
expected = {
EC_POLICY: {},
REPL_POLICY: md5().hexdigest(),
}[policy.policy_type]
self.assertEqual(hashes, {suffix: expected})
self.assertTrue(os.path.exists(df._datadir))
def test_hash_suffix_rmdir_suffix_oserror(self):
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
# make an empty hsh_path to be removed
df = df_mgr.get_diskfile(self.existing_device, '0', 'a', 'c',
'o', policy=policy)
os.makedirs(df._datadir)
suffix_path = os.path.dirname(df._datadir)
suffix = os.path.basename(suffix_path)
captured_paths = []
def mock_rmdir(path):
captured_paths.append(path)
if path == suffix_path:
raise OSError('kaboom!')
with mock.patch('os.rmdir', mock_rmdir):
hashes = df_mgr.get_hashes(self.existing_device, '0', [],
policy)
expected = {
EC_POLICY: {},
REPL_POLICY: md5().hexdigest(),
}[policy.policy_type]
self.assertEqual(hashes, {suffix: expected})
self.assertTrue(os.path.exists(suffix_path))
self.assertEqual([
df._datadir,
suffix_path,
], captured_paths)
# get_hashes tests - behaviors
def test_get_hashes_does_not_create_partition(self):
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
hashes = df_mgr.get_hashes(self.existing_device, '0', [],
policy)
self.assertEqual(hashes, {})
part_path = os.path.join(
self.devices, 'sda1', diskfile.get_data_dir(policy), '0')
self.assertFalse(os.path.exists(part_path))
def test_get_hashes_creates_pkl(self):
# like above, but -- if the partition already exists, make the pickle
for policy in self.iter_policies():
part_path = os.path.join(
self.devices, 'sda1', diskfile.get_data_dir(policy), '0')
mkdirs(part_path)
df_mgr = self.df_router[policy]
hashes = df_mgr.get_hashes(self.existing_device, '0', [],
policy)
self.assertEqual(hashes, {})
self.assertTrue(os.path.exists(part_path))
hashes_file = os.path.join(part_path,
diskfile.HASH_FILE)
self.assertTrue(os.path.exists(hashes_file))
# and double check the hashes
new_hashes = df_mgr.get_hashes(self.existing_device, '0', [],
policy)
self.assertEqual(hashes, new_hashes)
def _do_test_get_hashes_new_pkl_finds_new_suffix_dirs(self, device):
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
part_path = os.path.join(
self.devices, self.existing_device,
diskfile.get_data_dir(policy), '0')
hashes_file = os.path.join(part_path,
diskfile.HASH_FILE)
# add something to find
df = df_mgr.get_diskfile(self.existing_device, '0', 'a', 'c',
'o', policy=policy, frag_index=4)
timestamp = self.ts()
df.delete(timestamp)
suffix_dir = os.path.dirname(df._datadir)
suffix = os.path.basename(suffix_dir)
# get_hashes will find the untracked suffix dir
self.assertFalse(os.path.exists(hashes_file)) # sanity
hashes = df_mgr.get_hashes(device, '0', [], policy)
self.assertIn(suffix, hashes)
# ... and create a hashes pickle for it
self.assertTrue(os.path.exists(hashes_file))
# repeat and check there is no rehashing
with mock.patch.object(df_mgr, '_hash_suffix',
return_value=hashes[suffix]) as mocked:
repeat_hashes = df_mgr.get_hashes(device, '0', [], policy)
self.assertEqual(hashes, repeat_hashes)
mocked.assert_not_called()
def test_get_hashes_new_pkl_finds_new_suffix_dirs_unicode(self):
self._do_test_get_hashes_new_pkl_finds_new_suffix_dirs(u'sda1')
def test_get_hashes_new_pkl_finds_new_suffix_dirs(self):
self._do_test_get_hashes_new_pkl_finds_new_suffix_dirs('sda1')
def test_get_hashes_new_pkl_missing_invalid_finds_new_suffix_dirs(self):
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
part_path = os.path.join(
self.devices, self.existing_device,
diskfile.get_data_dir(policy), '0')
hashes_file = os.path.join(part_path,
diskfile.HASH_FILE)
invalidations_file = os.path.join(
part_path, diskfile.HASH_INVALIDATIONS_FILE)
# add something to find
df = df_mgr.get_diskfile(self.existing_device, '0', 'a', 'c',
'o', policy=policy, frag_index=4)
timestamp = self.ts()
df.delete(timestamp)
suffix = os.path.basename(os.path.dirname(df._datadir))
with open(invalidations_file) as f:
self.assertEqual('%s\n' % suffix, f.read())
# even if invalidations_file is missing ...
os.unlink(invalidations_file)
hashes = df_mgr.get_hashes(self.existing_device, '0', [], policy)
# get_hashes will *still* find the untracked suffix dir
self.assertIn(suffix, hashes)
# ... and create a hashes pickle for it
self.assertTrue(os.path.exists(hashes_file))
def test_get_hashes_new_pkl_lying_invalid_finds_new_suffix_dirs(self):
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
part_path = os.path.join(
self.devices, self.existing_device,
diskfile.get_data_dir(policy), '0')
hashes_file = os.path.join(part_path,
diskfile.HASH_FILE)
invalidations_file = os.path.join(
part_path, diskfile.HASH_INVALIDATIONS_FILE)
# add something to find
df = df_mgr.get_diskfile(self.existing_device, '0', 'a', 'c',
'o', policy=policy, frag_index=4)
timestamp = self.ts()
df.delete(timestamp)
suffix = os.path.basename(os.path.dirname(df._datadir))
with open(invalidations_file) as f:
self.assertEqual('%s\n' % suffix, f.read())
# even if invalidations_file is lying ...
with open(invalidations_file, 'w') as f:
f.write('%x\n' % (int(suffix, 16) + 1))
hashes = df_mgr.get_hashes(self.existing_device, '0', [], policy)
# get_hashes will *still* find the untracked suffix dir
self.assertIn(suffix, hashes)
# ... and create a hashes pickle for it
self.assertTrue(os.path.exists(hashes_file))
def test_get_hashes_old_pickle_does_not_find_new_suffix_dirs(self):
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
# create an empty stale pickle
part_path = os.path.join(
self.devices, 'sda1', diskfile.get_data_dir(policy), '0')
mkdirs(part_path)
hashes_file = os.path.join(part_path,
diskfile.HASH_FILE)
hashes = df_mgr.get_hashes(self.existing_device, '0', [], policy)
self.assertEqual(hashes, {})
self.assertTrue(os.path.exists(hashes_file)) # sanity
# add something to find
df = df_mgr.get_diskfile(self.existing_device, '0', 'a', 'c', 'o',
policy=policy, frag_index=4)
os.makedirs(df._datadir)
filename = Timestamp.now().internal + '.ts'
open(os.path.join(df._datadir, filename), 'w').close()
suffix = os.path.basename(os.path.dirname(df._datadir))
# but get_hashes has no reason to find it (because we didn't
# call invalidate_hash)
new_hashes = df_mgr.get_hashes(self.existing_device, '0', [],
policy)
self.assertEqual(new_hashes, hashes)
# ... unless remote end asks for a recalc
hashes = df_mgr.get_hashes(self.existing_device, '0', [suffix],
policy)
self.assertIn(suffix, hashes)
def test_get_hashes_does_not_rehash_known_suffix_dirs(self):
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
df = df_mgr.get_diskfile(self.existing_device, '0', 'a', 'c',
'o', policy=policy, frag_index=4)
suffix = os.path.basename(os.path.dirname(df._datadir))
timestamp = self.ts()
df.delete(timestamp)
# create the baseline hashes file
hashes = df_mgr.get_hashes(self.existing_device, '0', [], policy)
self.assertIn(suffix, hashes)
# now change the contents of the suffix w/o calling
# invalidate_hash
rmtree(df._datadir)
suffix_path = os.path.dirname(df._datadir)
self.assertTrue(os.path.exists(suffix_path)) # sanity
new_hashes = df_mgr.get_hashes(self.existing_device, '0', [],
policy)
# ... and get_hashes is none the wiser
self.assertEqual(new_hashes, hashes)
# ... unless remote end asks for a recalc
hashes = df_mgr.get_hashes(self.existing_device, '0', [suffix],
policy)
self.assertNotEqual(new_hashes, hashes)
# and the empty suffix path is removed
self.assertFalse(os.path.exists(suffix_path))
# ... and the suffix key is removed
expected = {}
self.assertEqual(expected, hashes)
def test_get_hashes_multi_file_multi_suffix(self):
paths, suffix = find_paths_with_matching_suffixes(needed_matches=2,
needed_suffixes=3)
matching_paths = paths.pop(suffix)
matching_paths.sort(key=lambda path: hash_path(*path))
other_paths = []
for suffix, paths in paths.items():
other_paths.append(paths[0])
if len(other_paths) >= 2:
break
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
# first we'll make a tombstone
df = df_mgr.get_diskfile(self.existing_device, '0',
*other_paths[0], policy=policy,
frag_index=4)
timestamp = self.ts()
df.delete(timestamp)
tombstone_hash = md5(timestamp.internal + '.ts').hexdigest()
tombstone_suffix = os.path.basename(os.path.dirname(df._datadir))
# second file in another suffix has a .datafile
df = df_mgr.get_diskfile(self.existing_device, '0',
*other_paths[1], policy=policy,
frag_index=5)
timestamp = self.ts()
with df.create() as writer:
test_data = b'test_file'
writer.write(test_data)
metadata = {
'X-Timestamp': timestamp.internal,
'ETag': md5(test_data).hexdigest(),
'Content-Length': len(test_data),
}
writer.put(metadata)
writer.commit(timestamp)
datafile_name = _make_datafilename(
timestamp, policy, frag_index=5)
durable_hash = md5(timestamp.internal + '.durable').hexdigest()
datafile_suffix = os.path.basename(os.path.dirname(df._datadir))
# in the *third* suffix - two datafiles for different hashes
df = df_mgr.get_diskfile(self.existing_device, '0',
*matching_paths[0], policy=policy,
frag_index=6)
matching_suffix = os.path.basename(os.path.dirname(df._datadir))
timestamp = self.ts()
with df.create() as writer:
test_data = b'test_file'
writer.write(test_data)
metadata = {
'X-Timestamp': timestamp.internal,
'ETag': md5(test_data).hexdigest(),
'Content-Length': len(test_data),
}
writer.put(metadata)
writer.commit(timestamp)
# we'll keep track of file names for hash calculations
filename = _make_datafilename(
timestamp, policy, frag_index=6)
data_filenames = {
6: filename
}
df = df_mgr.get_diskfile(self.existing_device, '0',
*matching_paths[1], policy=policy,
frag_index=7)
self.assertEqual(os.path.basename(os.path.dirname(df._datadir)),
matching_suffix) # sanity
timestamp = self.ts()
with df.create() as writer:
test_data = b'test_file'
writer.write(test_data)
metadata = {
'X-Timestamp': timestamp.internal,
'ETag': md5(test_data).hexdigest(),
'Content-Length': len(test_data),
}
writer.put(metadata)
writer.commit(timestamp)
filename = _make_datafilename(
timestamp, policy, frag_index=7)
data_filenames[7] = filename
# now make up the expected suffixes!
if policy.policy_type == EC_POLICY:
hasher = md5()
for filename in data_filenames.values():
# each data file updates the hasher with durable timestamp
hasher.update(filename.split('#', 1)[0] + '.durable')
expected = {
tombstone_suffix: {
None: tombstone_hash,
},
datafile_suffix: {
None: durable_hash,
5: self.fname_to_ts_hash(datafile_name),
},
matching_suffix: {
None: hasher.hexdigest(),
6: self.fname_to_ts_hash(data_filenames[6]),
7: self.fname_to_ts_hash(data_filenames[7]),
},
}
elif policy.policy_type == REPL_POLICY:
hasher = md5()
for filename in data_filenames.values():
hasher.update(filename)
expected = {
tombstone_suffix: tombstone_hash,
datafile_suffix: md5(datafile_name).hexdigest(),
matching_suffix: hasher.hexdigest(),
}
else:
self.fail('unknown policy type %r' % policy.policy_type)
hashes = df_mgr.get_hashes('sda1', '0', [], policy)
self.assertEqual(hashes, expected)
# get_hashes tests - error handling
def test_get_hashes_bad_dev(self):
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
df_mgr.mount_check = True
with mock_check_drive(ismount=False):
self.assertRaises(
DiskFileDeviceUnavailable,
df_mgr.get_hashes, self.existing_device, '0', ['123'],
policy)
def test_get_hashes_zero_bytes_pickle(self):
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
part_path = os.path.join(self.devices, self.existing_device,
diskfile.get_data_dir(policy), '0')
os.makedirs(part_path)
# create a pre-existing zero-byte file
open(os.path.join(part_path, diskfile.HASH_FILE), 'w').close()
hashes = df_mgr.get_hashes(self.existing_device, '0', [],
policy)
self.assertEqual(hashes, {})
def _test_get_hashes_race(self, hash_breaking_function):
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
df = df_mgr.get_diskfile(self.existing_device, '0', 'a', 'c',
'o', policy=policy, frag_index=3)
suffix = os.path.basename(os.path.dirname(df._datadir))
df2 = self.get_different_suffix_df(df, frag_index=5)
suffix2 = os.path.basename(os.path.dirname(df2._datadir))
part_path = os.path.dirname(os.path.dirname(
os.path.join(df._datadir)))
mkdirs(part_path)
hashfile_path = os.path.join(part_path, diskfile.HASH_FILE)
# create hashes.pkl
hashes = df_mgr.get_hashes(self.existing_device, '0', [],
policy)
self.assertEqual(hashes, {}) # sanity
self.assertTrue(os.path.exists(hashfile_path))
# and optionally tamper with the hashes.pkl...
hash_breaking_function(hashfile_path)
non_local = {'called': False}
orig_hash_suffix = df_mgr._hash_suffix
# then create a suffix
df.delete(self.ts())
def mock_hash_suffix(*args, **kwargs):
# capture first call to mock_hash
if not non_local['called']:
non_local['called'] = True
df2.delete(self.ts())
non_local['other_hashes'] = df_mgr.get_hashes(
self.existing_device, '0', [], policy)
return orig_hash_suffix(*args, **kwargs)
with mock.patch.object(df_mgr, '_hash_suffix', mock_hash_suffix):
hashes = df_mgr.get_hashes(self.existing_device, '0', [],
policy)
self.assertTrue(non_local['called'])
self.assertIn(suffix, hashes)
self.assertIn(suffix2, hashes)
def test_get_hashes_race_invalid_pickle(self):
def hash_breaking_function(hashfile_path):
# create a garbage invalid zero-byte file which can not unpickle
open(hashfile_path, 'w').close()
self._test_get_hashes_race(hash_breaking_function)
def test_get_hashes_race_new_partition(self):
def hash_breaking_function(hashfile_path):
# simulate rebalanced part doing post-rsync REPLICATE
os.unlink(hashfile_path)
part_dir = os.path.dirname(hashfile_path)
os.unlink(os.path.join(part_dir, '.lock'))
# sanity
self.assertEqual([], os.listdir(os.path.dirname(hashfile_path)))
self._test_get_hashes_race(hash_breaking_function)
def test_get_hashes_race_existing_partition(self):
def hash_breaking_function(hashfile_path):
# no-op - simulate ok existing partition
self.assertTrue(os.path.exists(hashfile_path))
self._test_get_hashes_race(hash_breaking_function)
def test_get_hashes_hash_suffix_enotdir(self):
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
# create a real suffix dir
df = df_mgr.get_diskfile(self.existing_device, '0', 'a', 'c',
'o', policy=policy, frag_index=3)
df.delete(Timestamp.now())
suffix = os.path.basename(os.path.dirname(df._datadir))
# touch a bad suffix dir
part_dir = os.path.join(self.devices, self.existing_device,
diskfile.get_data_dir(policy), '0')
open(os.path.join(part_dir, 'bad'), 'w').close()
hashes = df_mgr.get_hashes(self.existing_device, '0', [], policy)
self.assertIn(suffix, hashes)
self.assertNotIn('bad', hashes)
def test_get_hashes_hash_suffix_other_oserror(self):
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
suffix = '123'
suffix_path = os.path.join(self.devices, self.existing_device,
diskfile.get_data_dir(policy), '0',
suffix)
os.makedirs(suffix_path)
self.assertTrue(os.path.exists(suffix_path)) # sanity
hashes = df_mgr.get_hashes(self.existing_device, '0', [suffix],
policy)
expected = {}
msg = 'expected %r != %r for policy %r' % (expected, hashes,
policy)
self.assertEqual(hashes, expected, msg)
# this OSError does *not* raise PathNotDir, and is allowed to leak
# from hash_suffix into get_hashes
mocked_os_listdir = mock.Mock(
side_effect=OSError(errno.EACCES, os.strerror(errno.EACCES)))
with mock.patch("os.listdir", mocked_os_listdir):
with mock.patch('swift.obj.diskfile.logging') as mock_logging:
hashes = df_mgr.get_hashes('sda1', '0', [suffix], policy)
self.assertEqual(mock_logging.method_calls,
[mock.call.exception('Error hashing suffix')])
# recalc always causes a suffix to get reset to None; the listdir
# error prevents the suffix from being rehashed
expected = {'123': None}
msg = 'expected %r != %r for policy %r' % (expected, hashes,
policy)
self.assertEqual(hashes, expected, msg)
def test_get_hashes_modified_recursive_retry(self):
for policy in self.iter_policies():
df_mgr = self.df_router[policy]
part_path = os.path.join(self.devices, self.existing_device,
diskfile.get_data_dir(policy), '0')
mkdirs(part_path)
# first create an empty pickle
df_mgr.get_hashes(self.existing_device, '0', [], policy)
self.assertTrue(os.path.exists(os.path.join(
part_path, diskfile.HASH_FILE)))
non_local = {'suffix_count': 1}
calls = []
def mock_read_hashes(filename):
rv = {'%03x' % i: 'fake'
for i in range(non_local['suffix_count'])}
if len(calls) <= 3:
# this will make the *next* call get slightly
# different content
non_local['suffix_count'] += 1
# track exactly the value for every return
calls.append(dict(rv))
rv['valid'] = True
return rv
with mock.patch('swift.obj.diskfile.read_hashes',
mock_read_hashes):
df_mgr.get_hashes(self.existing_device, '0', ['123'],
policy)
self.assertEqual(calls, [
{'000': 'fake'}, # read
{'000': 'fake', '001': 'fake'}, # modification
{'000': 'fake', '001': 'fake', '002': 'fake'}, # read
{'000': 'fake', '001': 'fake', '002': 'fake',
'003': 'fake'}, # modifed
{'000': 'fake', '001': 'fake', '002': 'fake',
'003': 'fake', '004': 'fake'}, # read
{'000': 'fake', '001': 'fake', '002': 'fake',
'003': 'fake', '004': 'fake'}, # not modifed
])
class TestHashesHelpers(unittest.TestCase):
def setUp(self):
self.testdir = tempfile.mkdtemp()
def tearDown(self):
rmtree(self.testdir, ignore_errors=1)
def test_read_legacy_hashes(self):
hashes = {'fff': 'fake'}
hashes_file = os.path.join(self.testdir, diskfile.HASH_FILE)
with open(hashes_file, 'wb') as f:
pickle.dump(hashes, f)
expected = {
'fff': 'fake',
'updated': -1,
'valid': True,
}
self.assertEqual(expected, diskfile.read_hashes(self.testdir))
def test_write_hashes_valid_updated(self):
hashes = {'888': 'fake', 'valid': True}
now = time()
with mock.patch('swift.obj.diskfile.time.time', return_value=now):
diskfile.write_hashes(self.testdir, hashes)
hashes_file = os.path.join(self.testdir, diskfile.HASH_FILE)
with open(hashes_file, 'rb') as f:
data = pickle.load(f)
expected = {
'888': 'fake',
'updated': now,
'valid': True,
}
self.assertEqual(expected, data)
def test_write_hashes_invalid_updated(self):
hashes = {'valid': False}
now = time()
with mock.patch('swift.obj.diskfile.time.time', return_value=now):
diskfile.write_hashes(self.testdir, hashes)
hashes_file = os.path.join(self.testdir, diskfile.HASH_FILE)
with open(hashes_file, 'rb') as f:
data = pickle.load(f)
expected = {
'updated': now,
'valid': False,
}
self.assertEqual(expected, data)
def test_write_hashes_safe_default(self):
hashes = {}
now = time()
with mock.patch('swift.obj.diskfile.time.time', return_value=now):
diskfile.write_hashes(self.testdir, hashes)
hashes_file = os.path.join(self.testdir, diskfile.HASH_FILE)
with open(hashes_file, 'rb') as f:
data = pickle.load(f)
expected = {
'updated': now,
'valid': False,
}
self.assertEqual(expected, data)
def test_read_write_valid_hashes_mutation_and_transative_equality(self):
hashes = {'000': 'fake', 'valid': True}
diskfile.write_hashes(self.testdir, hashes)
# write_hashes mutates the passed in hashes, it adds the updated key
self.assertIn('updated', hashes)
self.assertTrue(hashes['valid'])
result = diskfile.read_hashes(self.testdir)
# unpickling result in a new object
self.assertNotEqual(id(hashes), id(result))
# with the exactly the same value mutation from write_hashes
self.assertEqual(hashes, result)
def test_read_write_invalid_hashes_mutation_and_transative_equality(self):
hashes = {'valid': False}
diskfile.write_hashes(self.testdir, hashes)
# write_hashes mutates the passed in hashes, it adds the updated key
self.assertIn('updated', hashes)
self.assertFalse(hashes['valid'])
result = diskfile.read_hashes(self.testdir)
# unpickling result in a new object
self.assertNotEqual(id(hashes), id(result))
# with the exactly the same value mutation from write_hashes
self.assertEqual(hashes, result)
def test_ignore_corrupted_hashes(self):
corrupted_hashes = {u'\x00\x00\x00': False, 'valid': True}
diskfile.write_hashes(self.testdir, corrupted_hashes)
result = diskfile.read_hashes(self.testdir)
self.assertFalse(result['valid'])
if __name__ == '__main__':
unittest.main()
|