summaryrefslogtreecommitdiff
path: root/test/unit/obj/test_reconstructor.py
blob: a350a77681206a42d2e855ab326f8688ba4ef24a (plain)
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
# 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.
import itertools
import json
import unittest
import os
from hashlib import md5
import mock
import six
import six.moves.cPickle as pickle
import tempfile
import time
import shutil
import re
import random
import struct
import collections
from eventlet import Timeout, sleep, spawn
from eventlet.green import threading

from contextlib import closing, contextmanager
from gzip import GzipFile
from shutil import rmtree
from six.moves.urllib.parse import unquote
from swift.common import utils
from swift.common.exceptions import DiskFileError
from swift.common.header_key_dict import HeaderKeyDict
from swift.common.utils import dump_recon_cache
from swift.obj import diskfile, reconstructor as object_reconstructor
from swift.common import ring
from swift.common.storage_policy import (StoragePolicy, ECStoragePolicy,
                                         POLICIES, EC_POLICY)
from swift.obj.reconstructor import SYNC, REVERT

from test.unit import (patch_policies, debug_logger, mocked_http_conn,
                       FabricatedRing, make_timestamp_iter,
                       DEFAULT_TEST_EC_TYPE, encode_frag_archive_bodies,
                       quiet_eventlet_exceptions, skip_if_no_xattrs)
from test.unit.obj.common import write_diskfile


@contextmanager
def mock_ssync_sender(ssync_calls=None, response_callback=None, **kwargs):
    def fake_ssync(daemon, node, job, suffixes):
        if ssync_calls is not None:
            ssync_calls.append(
                {'node': node, 'job': job, 'suffixes': suffixes})

        def fake_call():
            if response_callback:
                response = response_callback(node, job, suffixes)
            else:
                response = True, {}
            return response
        return fake_call

    with mock.patch('swift.obj.reconstructor.ssync_sender', fake_ssync):
        yield fake_ssync


def make_ec_archive_bodies(policy, test_body):
    segment_size = policy.ec_segment_size
    # split up the body into buffers
    chunks = [test_body[x:x + segment_size]
              for x in range(0, len(test_body), segment_size)]
    # encode the buffers into fragment payloads
    fragment_payloads = []
    for chunk in chunks:
        fragments = \
            policy.pyeclib_driver.encode(chunk) * policy.ec_duplication_factor
        if not fragments:
            break
        fragment_payloads.append(fragments)

    # join up the fragment payloads per node
    ec_archive_bodies = [''.join(frags) for frags in zip(*fragment_payloads)]
    return ec_archive_bodies


def _create_test_rings(path, next_part_power=None):
    testgz = os.path.join(path, 'object.ring.gz')
    intended_replica2part2dev_id = [
        [0, 1, 2],
        [1, 2, 3],
        [2, 3, 0]
    ]

    intended_devs = [
        {'id': 0, 'device': 'sda1', 'zone': 0, 'ip': '127.0.0.0',
         'port': 6200},
        {'id': 1, 'device': 'sda1', 'zone': 1, 'ip': '127.0.0.1',
         'port': 6200},
        {'id': 2, 'device': 'sda1', 'zone': 2, 'ip': '127.0.0.2',
         'port': 6200},
        {'id': 3, 'device': 'sda1', 'zone': 4, 'ip': '127.0.0.3',
         'port': 6200}
    ]
    intended_part_shift = 30
    with closing(GzipFile(testgz, 'wb')) as f:
        pickle.dump(
            ring.RingData(intended_replica2part2dev_id,
                          intended_devs, intended_part_shift,
                          next_part_power),
            f)

    testgz = os.path.join(path, 'object-1.ring.gz')
    with closing(GzipFile(testgz, 'wb')) as f:
        pickle.dump(
            ring.RingData(intended_replica2part2dev_id,
                          intended_devs, intended_part_shift,
                          next_part_power),
            f)


def count_stats(logger, key, metric):
    count = 0
    for record in logger.log_dict[key]:
        log_args, log_kwargs = record
        m = log_args[0]
        if re.match(metric, m):
            count += 1
    return count


def get_header_frag_index(self, body):
    metadata = self.policy.pyeclib_driver.get_metadata(body)
    frag_index = struct.unpack('h', metadata[:2])[0]
    return {
        'X-Object-Sysmeta-Ec-Frag-Index': frag_index,
    }


@patch_policies([StoragePolicy(0, name='zero', is_default=True),
                 ECStoragePolicy(1, name='one',
                                 ec_type=DEFAULT_TEST_EC_TYPE,
                                 ec_ndata=3, ec_nparity=2)])
class TestGlobalSetupObjectReconstructor(unittest.TestCase):
    # Tests for reconstructor using real objects in test partition directories.
    legacy_durable = False

    def setUp(self):
        skip_if_no_xattrs()
        self.testdir = tempfile.mkdtemp()
        POLICIES[0].object_ring = FabricatedRing(3)
        POLICIES[1].object_ring = FabricatedRing(5)
        utils.HASH_PATH_SUFFIX = b'endcap'
        utils.HASH_PATH_PREFIX = b''
        self.devices = os.path.join(self.testdir, 'node')
        os.makedirs(self.devices)
        os.mkdir(os.path.join(self.devices, 'sda1'))
        self.objects = os.path.join(self.devices, 'sda1',
                                    diskfile.get_data_dir(POLICIES[0]))
        self.objects_1 = os.path.join(self.devices, 'sda1',
                                      diskfile.get_data_dir(POLICIES[1]))
        os.mkdir(self.objects)
        os.mkdir(self.objects_1)
        self.parts = {}
        self.parts_1 = {}
        self.part_nums = ['0', '1', '2']
        for part in self.part_nums:
            self.parts[part] = os.path.join(self.objects, part)
            os.mkdir(self.parts[part])
            self.parts_1[part] = os.path.join(self.objects_1, part)
            os.mkdir(self.parts_1[part])

        self.conf = dict(
            swift_dir=self.testdir, devices=self.devices, mount_check='false',
            timeout='300', stats_interval='1',
            bind_ip='10.0.0.1', bind_port=6200)
        self.logger = debug_logger('test-reconstructor')
        self.reconstructor = object_reconstructor.ObjectReconstructor(
            self.conf, logger=self.logger)

        self.policy = POLICIES[1]

        # most of the reconstructor test methods require that there be
        # real objects in place, not just part dirs, so we'll create them
        # all here....
        # part 0: 3C1/hash/xxx#1#d.data  <-- job: sync_only - partners (FI 1)
        #         061/hash/xxx#1#d.data  <-- included in earlier job (FI 1)
        #                 /xxx#2#d.data  <-- job: sync_revert to index 2
        # part_nodes: ['sda0', 'sda1', 'sda2', 'sda3', 'sda4']

        # part 1: 3C1/hash/xxx#0#d.data  <-- job: sync_revert to index 0
        #                 /xxx#1#d.data  <-- job: sync_revert to index 1
        #         061/hash/xxx#1#d.data  <-- included in earlier job (FI 1)
        # part_nodes: ['sda5', 'sda6', 'sda7', 'sda0', 'sda1']

        # part 2: 3C1/hash/xxx#2#d.data  <-- job: sync_revert to index 2
        #         061/hash/xxx#0#d.data  <-- job: sync_revert to index 0
        # part_nodes: ['sda2', 'sda3', 'sda4', 'sda5', 'sda6']

        def _create_frag_archives(policy, obj_path, local_id, obj_set):
            # we'll create 2 sets of objects in different suffix dirs
            # so we cover all the scenarios we want (3 of them)
            # 1) part dir with all FI's matching the local node index
            # 2) part dir with one local and mix of others
            # 3) part dir with no local FI and one or more others
            def part_0(set):
                if set == 0:
                    # just the local
                    return local_id
                else:
                    # one local and all of another
                    if obj_num == 0:
                        return local_id
                    else:
                        return (local_id + 1) % 3

            def part_1(set):
                if set == 0:
                    # one local and all of another
                    if obj_num == 0:
                        return local_id
                    else:
                        return (local_id + 2) % 3
                else:
                    # just the local node
                    return local_id

            def part_2(set):
                # this part is a handoff in our config (always)
                # so lets do a set with indices from different nodes
                if set == 0:
                    return (local_id + 1) % 3
                else:
                    return (local_id + 2) % 3

            # function dictionary for defining test scenarios base on set #
            scenarios = {'0': part_0,
                         '1': part_1,
                         '2': part_2}

            def _create_df(obj_num, part_num):
                self._create_diskfile(
                    part=part_num, object_name='o' + str(obj_set),
                    policy=policy, frag_index=scenarios[part_num](obj_set),
                    timestamp=utils.Timestamp(t))

            for part_num in self.part_nums:
                # create 3 unique objects per part, each part
                # will then have a unique mix of FIs for the
                # possible scenarios
                for obj_num in range(0, 3):
                    _create_df(obj_num, part_num)

        ips = utils.whataremyips(self.reconstructor.bind_ip)
        for policy in [p for p in POLICIES if p.policy_type == EC_POLICY]:
            self.ec_policy = policy
            self.ec_obj_ring = self.reconstructor.load_object_ring(
                self.ec_policy)
            data_dir = diskfile.get_data_dir(self.ec_policy)
            for local_dev in [dev for dev in self.ec_obj_ring.devs
                              if dev and dev['replication_ip'] in ips and
                              dev['replication_port'] ==
                              self.reconstructor.port]:
                self.ec_local_dev = local_dev
                dev_path = os.path.join(self.reconstructor.devices_dir,
                                        self.ec_local_dev['device'])
                self.ec_obj_path = os.path.join(dev_path, data_dir)

                # create a bunch of FA's to test
                t = 1421181937.70054  # time.time()
                with mock.patch('swift.obj.diskfile.time') as mock_time:
                    # since (a) we are using a fixed time here to create
                    # frags which corresponds to all the hardcoded hashes and
                    # (b) the EC diskfile will delete its .data file right
                    # after creating if it has expired, use this horrible hack
                    # to prevent the reclaim happening
                    mock_time.time.return_value = 0.0
                    _create_frag_archives(self.ec_policy, self.ec_obj_path,
                                          self.ec_local_dev['id'], 0)
                    _create_frag_archives(self.ec_policy, self.ec_obj_path,
                                          self.ec_local_dev['id'], 1)
                break
            break

    def tearDown(self):
        rmtree(self.testdir, ignore_errors=1)

    def _create_diskfile(self, policy=None, part=0, object_name='o',
                         frag_index=0, timestamp=None, test_data=None):
        policy = policy or self.policy
        df_mgr = self.reconstructor._df_router[policy]
        df = df_mgr.get_diskfile('sda1', part, 'a', 'c', object_name,
                                 policy=policy)
        timestamp = timestamp or utils.Timestamp.now()
        test_data = test_data or b'test data'
        write_diskfile(df, timestamp, data=test_data, frag_index=frag_index,
                       legacy_durable=self.legacy_durable)
        return df

    def assert_expected_jobs(self, part_num, jobs):
        # the dict diffs can be pretty big
        self.maxDiff = 2048

        for job in jobs:
            del job['path']
            del job['policy']
            if 'local_index' in job:
                del job['local_index']
            job['suffixes'].sort()

        expected = []
        # part num 0
        expected.append(
            [{
                'sync_to': [{
                    'index': 2,
                    'replication_port': 6200,
                    'zone': 1,
                    'ip': '10.0.0.2',
                    'region': 1,
                    'port': 6200,
                    'replication_ip': '10.0.0.2',
                    'device': 'sda2',
                    'id': 2,
                    'weight': 1.0,
                }],
                'job_type': object_reconstructor.REVERT,
                'suffixes': ['061'],
                'partition': 0,
                'frag_index': 2,
                'device': 'sda1',
                'local_dev': {
                    'replication_port': 6200,
                    'zone': 1,
                    'ip': '10.0.0.1',
                    'region': 1,
                    'id': 1,
                    'replication_ip': '10.0.0.1',
                    'device': 'sda1',
                    'port': 6200,
                    'weight': 1.0,
                },
                'hashes': {
                    '061': {
                        None: '85b02a5283704292a511078a5c483da5',
                        2: '0e6e8d48d801dc89fd31904ae3b31229',
                        1: '0e6e8d48d801dc89fd31904ae3b31229',
                    },
                    '3c1': {
                        None: '85b02a5283704292a511078a5c483da5',
                        1: '0e6e8d48d801dc89fd31904ae3b31229',
                    },
                },
            }, {
                'sync_to': [{
                    'index': 0,
                    'replication_port': 6200,
                    'zone': 1,
                    'ip': '10.0.0.0',
                    'region': 1,
                    'port': 6200,
                    'replication_ip': '10.0.0.0',
                    'device': 'sda0',
                    'id': 0,
                    'weight': 1.0,
                }, {
                    'index': 2,
                    'replication_port': 6200,
                    'zone': 1,
                    'ip': '10.0.0.2',
                    'region': 1,
                    'port': 6200,
                    'replication_ip': '10.0.0.2',
                    'device': 'sda2',
                    'id': 2,
                    'weight': 1.0,
                }, {
                    'index': 3,
                    'replication_port': 6200,
                    'zone': 1,
                    'ip': '10.0.0.3',
                    'region': 1,
                    'port': 6200,
                    'replication_ip': '10.0.0.3',
                    'device': 'sda3',
                    'id': 3,
                    'weight': 1.0,
                }],
                'job_type': object_reconstructor.SYNC,
                'sync_diskfile_builder': self.reconstructor.reconstruct_fa,
                'suffixes': ['061', '3c1'],
                'partition': 0,
                'frag_index': 1,
                'device': 'sda1',
                'local_dev': {
                    'replication_port': 6200,
                    'zone': 1,
                    'ip': '10.0.0.1',
                    'region': 1,
                    'id': 1,
                    'replication_ip': '10.0.0.1',
                    'device': 'sda1',
                    'port': 6200,
                    'weight': 1.0,
                },
                'hashes':
                {
                    '061': {
                        None: '85b02a5283704292a511078a5c483da5',
                        2: '0e6e8d48d801dc89fd31904ae3b31229',
                        1: '0e6e8d48d801dc89fd31904ae3b31229'
                    },
                    '3c1': {
                        None: '85b02a5283704292a511078a5c483da5',
                        1: '0e6e8d48d801dc89fd31904ae3b31229',
                    },
                },
            }]
        )
        # part num 1
        expected.append(
            [{
                'sync_to': [{
                    'index': 1,
                    'replication_port': 6200,
                    'zone': 1,
                    'ip': '10.0.0.2',
                    'region': 1,
                    'port': 6200,
                    'replication_ip': '10.0.0.2',
                    'device': 'sda6',
                    'id': 6,
                    'weight': 1.0,
                }],
                'job_type': object_reconstructor.REVERT,
                'suffixes': ['061', '3c1'],
                'partition': 1,
                'frag_index': 1,
                'device': 'sda1',
                'local_dev': {
                    'replication_port': 6200,
                    'zone': 1,
                    'ip': '10.0.0.1',
                    'region': 1,
                    'id': 1,
                    'replication_ip': '10.0.0.1',
                    'device': 'sda1',
                    'port': 6200,
                    'weight': 1.0,
                },
                'hashes':
                {
                    '061': {
                        None: '85b02a5283704292a511078a5c483da5',
                        1: '0e6e8d48d801dc89fd31904ae3b31229',
                    },
                    '3c1': {
                        0: '0e6e8d48d801dc89fd31904ae3b31229',
                        None: '85b02a5283704292a511078a5c483da5',
                        1: '0e6e8d48d801dc89fd31904ae3b31229',
                    },
                },
            }, {
                'sync_to': [{
                    'index': 0,
                    'replication_port': 6200,
                    'zone': 1,
                    'ip': '10.0.0.1',
                    'region': 1,
                    'port': 6200,
                    'replication_ip': '10.0.0.1',
                    'device': 'sda5',
                    'id': 5,
                    'weight': 1.0,
                }],
                'job_type': object_reconstructor.REVERT,
                'suffixes': ['3c1'],
                'partition': 1,
                'frag_index': 0,
                'device': 'sda1',
                'local_dev': {
                    'replication_port': 6200,
                    'zone': 1,
                    'ip': '10.0.0.1',
                    'region': 1,
                    'id': 1,
                    'replication_ip': '10.0.0.1',
                    'device': 'sda1',
                    'port': 6200,
                    'weight': 1.0,
                },
                'hashes': {
                    '061': {
                        None: '85b02a5283704292a511078a5c483da5',
                        1: '0e6e8d48d801dc89fd31904ae3b31229',
                    },
                    '3c1': {
                        0: '0e6e8d48d801dc89fd31904ae3b31229',
                        None: '85b02a5283704292a511078a5c483da5',
                        1: '0e6e8d48d801dc89fd31904ae3b31229',
                    },
                },
            }, {
                'sync_to': [{
                    'index': 3,
                    'replication_port': 6200,
                    'zone': 1,
                    'ip': '10.0.0.0',
                    'region': 1,
                    'port': 6200,
                    'replication_ip': '10.0.0.0',
                    'device': 'sda0',
                    'id': 0,
                    'weight': 1.0,
                }, {
                    'index': 0,
                    'replication_port': 6200,
                    'zone': 1,
                    'ip': '10.0.0.1',
                    'region': 1,
                    'port': 6200,
                    'replication_ip': '10.0.0.1',
                    'device': 'sda5',
                    'id': 5,
                    'weight': 1.0,
                }, {
                    'index': 1,
                    'replication_port': 6200,
                    'zone': 1,
                    'ip': '10.0.0.2',
                    'region': 1,
                    'port': 6200,
                    'replication_ip': '10.0.0.2',
                    'device': 'sda6',
                    'id': 6,
                    'weight': 1.0,
                }],
                'job_type': object_reconstructor.SYNC,
                'sync_diskfile_builder': self.reconstructor.reconstruct_fa,
                'suffixes': [],
                'partition': 1,
                'frag_index': 4,
                'device': 'sda1',
                'local_dev': {
                    'replication_port': 6200,
                    'zone': 1,
                    'ip': '10.0.0.1',
                    'region': 1,
                    'id': 1,
                    'replication_ip': '10.0.0.1',
                    'device': 'sda1',
                    'port': 6200,
                    'weight': 1.0,
                },
                'hashes': {
                    '061': {
                        None: '85b02a5283704292a511078a5c483da5',
                        1: '0e6e8d48d801dc89fd31904ae3b31229',
                    },
                    '3c1': {
                        0: '0e6e8d48d801dc89fd31904ae3b31229',
                        None: '85b02a5283704292a511078a5c483da5',
                        1: '0e6e8d48d801dc89fd31904ae3b31229',
                    },
                },

            }]
        )
        # part num 2
        expected.append(
            [{
                'sync_to': [{
                    'index': 0,
                    'replication_port': 6200,
                    'zone': 1,
                    'ip': '10.0.0.2',
                    'region': 1,
                    'port': 6200,
                    'replication_ip': '10.0.0.2',
                    'device': 'sda2',
                    'id': 2,
                    'weight': 1.0,
                }],
                'job_type': object_reconstructor.REVERT,
                'suffixes': ['061'],
                'partition': 2,
                'frag_index': 0,
                'device': 'sda1',
                'local_dev': {
                    'replication_port': 6200,
                    'zone': 1,
                    'ip': '10.0.0.1',
                    'region': 1,
                    'id': 1,
                    'replication_ip': '10.0.0.1',
                    'device': 'sda1',
                    'port': 6200,
                    'weight': 1.0,
                },
                'hashes': {
                    '061': {
                        0: '0e6e8d48d801dc89fd31904ae3b31229',
                        None: '85b02a5283704292a511078a5c483da5'
                    },
                    '3c1': {
                        None: '85b02a5283704292a511078a5c483da5',
                        2: '0e6e8d48d801dc89fd31904ae3b31229'
                    },
                },
            }, {
                'sync_to': [{
                    'index': 2,
                    'replication_port': 6200,
                    'zone': 1,
                    'ip': '10.0.0.0',
                    'region': 1,
                    'port': 6200,
                    'replication_ip': '10.0.0.0',
                    'device': 'sda4',
                    'id': 4,
                    'weight': 1.0,
                }],
                'job_type': object_reconstructor.REVERT,
                'suffixes': ['3c1'],
                'partition': 2,
                'frag_index': 2,
                'device': 'sda1',
                'local_dev': {
                    'replication_port': 6200,
                    'zone': 1,
                    'ip': '10.0.0.1',
                    'region': 1,
                    'id': 1,
                    'replication_ip': '10.0.0.1',
                    'device': 'sda1',
                    'port': 6200,
                    'weight': 1.0,
                },
                'hashes': {
                    '061': {
                        0: '0e6e8d48d801dc89fd31904ae3b31229',
                        None: '85b02a5283704292a511078a5c483da5'
                    },
                    '3c1': {
                        None: '85b02a5283704292a511078a5c483da5',
                        2: '0e6e8d48d801dc89fd31904ae3b31229'
                    },
                },
            }]
        )

        def check_jobs(part_num):
            try:
                expected_jobs = expected[int(part_num)]
            except (IndexError, ValueError):
                self.fail('Unknown part number %r' % part_num)
            expected_by_part_frag_index = dict(
                ((j['partition'], j['frag_index']), j) for j in expected_jobs)
            unexpected_jobs = []
            for job in jobs:
                job_key = (job['partition'], job['frag_index'])
                if job_key in expected_by_part_frag_index:
                    self.assertEqual(job, expected_by_part_frag_index[job_key])
                else:
                    unexpected_jobs.append(job)
            if unexpected_jobs:
                self.fail(
                    'Unexpected jobs for frags %r in part num %s - '
                    'expected jobs for frags %r' % (
                        [j['frag_index'] for j in unexpected_jobs], part_num,
                        [k[1] for k in expected_by_part_frag_index]))
            for expected_job in expected_jobs:
                if expected_job in jobs:
                    jobs.remove(expected_job)
            self.assertFalse(jobs)  # that should be all of them
        check_jobs(part_num)

    def _run_once(self, http_count, extra_devices, override_devices=None):
        id_counter = itertools.count(
            max(d['id'] for d in self.policy.object_ring.devs) + 1)
        for device, parts in extra_devices.items():
            device_path = os.path.join(self.devices, device)
            os.mkdir(device_path)
            for part in range(parts):
                hash_path = os.path.join(
                    device_path, 'objects-1', str(part), 'abc', 'hash')
                os.makedirs(hash_path)
                tombstone_file = utils.Timestamp(time.time()).internal + '.ts'
                with open(os.path.join(hash_path, tombstone_file), 'w'):
                    pass
            # use sda1 as a base to make is_local happy
            new_device = dict(self.policy.object_ring.devs[1])
            new_device['device'] = device
            new_device['id'] = next(id_counter)
            self.policy.object_ring.devs.append(new_device)

        self.reconstructor.stats_interval = object()

        can_process = threading.Event()
        can_do_stats = threading.Event()
        can_do_stats.set()

        def fake_sleep(secs=0):
            if secs is not self.reconstructor.stats_interval:
                return sleep(secs)
            can_do_stats.wait()
            can_do_stats.clear()
            can_process.set()

        def fake_process(job):
            can_process.wait()
            can_process.clear()
            can_do_stats.set()

        self.reconstructor.process_job = fake_process
        with mock_ssync_sender(), mock.patch(
                'swift.obj.reconstructor.sleep', fake_sleep):
            self.reconstructor.run_once(devices=override_devices)

    def test_run_once(self):
        # sda1: 3 is done in setup
        extra_devices = {
            'sdb1': 4,
            'sdc1': 1,
            'sdd1': 0,
        }
        with Timeout(60):
            self._run_once(32, extra_devices)
        stats_lines = set()
        for line in self.logger.get_lines_for_level('info'):
            if 'reconstructed in' not in line:
                continue
            stat_line = line.split('reconstructed', 1)[0].strip()
            stats_lines.add(stat_line)
        acceptable = set([
            '2/8 (25.00%) partitions',
            '3/8 (37.50%) partitions',
            '4/8 (50.00%) partitions',
            '5/8 (62.50%) partitions',
            '6/8 (75.00%) partitions',
            '7/8 (87.50%) partitions',
            '8/8 (100.00%) partitions',
        ])
        matched = stats_lines & acceptable
        self.assertEqual(matched, acceptable,
                         'missing some expected acceptable:\n%s' % (
                             '\n'.join(sorted(acceptable - matched))))
        self.assertEqual(self.reconstructor.reconstruction_part_count, 8)
        self.assertEqual(self.reconstructor.part_count, 8)

    def test_run_once_override_devices(self):
        # sda1: 3 is done in setup
        extra_devices = {
            'sdb1': 4,
            'sdc1': 1,
            'sdd1': 0,
        }
        with Timeout(60):
            self._run_once(3, extra_devices, 'sdc1')
        stats_lines = set()
        for line in self.logger.get_lines_for_level('info'):
            if 'reconstructed in' not in line:
                continue
            stat_line = line.split('reconstructed', 1)[0].strip()
            stats_lines.add(stat_line)
        acceptable = set([
            '1/1 (100.00%) partitions',
        ])
        matched = stats_lines & acceptable
        self.assertEqual(matched, acceptable,
                         'missing some expected acceptable:\n%s' % (
                             '\n'.join(sorted(acceptable - matched))))
        self.assertEqual(self.reconstructor.reconstruction_part_count, 1)
        self.assertEqual(self.reconstructor.part_count, 1)

    def test_get_response(self):
        part = self.part_nums[0]
        node = self.policy.object_ring.get_part_nodes(int(part))[0]

        def do_test(stat_code):
            with mocked_http_conn(stat_code):
                resp = self.reconstructor._get_response(node, part,
                                                        path='nada',
                                                        headers={},
                                                        full_path='nada/nada')
            return resp

        resp = do_test(200)
        self.assertEqual(resp.status, 200)

        resp = do_test(400)
        # on the error case return value will be None instead of response
        self.assertIsNone(resp)
        # ... and log warnings for 400
        for line in self.logger.get_lines_for_level('warning'):
            self.assertIn('Invalid response 400', line)
        self.logger._clear()

        resp = do_test(Exception())
        self.assertIsNone(resp)
        # exception should result in error logs
        for line in self.logger.get_lines_for_level('error'):
            self.assertIn('Trying to GET', line)
        self.logger._clear()

        # Timeout also should result in error logs
        resp = do_test(Timeout())
        self.assertIsNone(resp)
        for line in self.logger.get_lines_for_level('error'):
            self.assertIn('Trying to GET', line)
            # sanity Timeout has extra message in the error log
            self.assertIn('Timeout', line)
        self.logger.clear()

        # we should get a warning on 503 (sanity)
        resp = do_test(503)
        self.assertIsNone(resp)
        warnings = self.logger.get_lines_for_level('warning')
        self.assertEqual(1, len(warnings))
        self.assertIn('Invalid response 503', warnings[0])
        self.logger.clear()

        # ... but no messages should be emitted for 404
        resp = do_test(404)
        self.assertIsNone(resp)
        for level, msgs in self.logger.lines_dict.items():
            self.assertFalse(msgs)

    def test_reconstructor_skips_bogus_partition_dirs(self):
        # A directory in the wrong place shouldn't crash the reconstructor
        self.reconstructor._reset_stats()
        rmtree(self.objects_1)
        os.mkdir(self.objects_1)

        os.mkdir(os.path.join(self.objects_1, "burrito"))
        jobs = []
        for part_info in self.reconstructor.collect_parts():
            jobs += self.reconstructor.build_reconstruction_jobs(part_info)
        self.assertFalse(jobs)

    def test_check_ring(self):
        testring = tempfile.mkdtemp()
        _create_test_rings(testring)
        obj_ring = ring.Ring(testring, ring_name='object')  # noqa
        self.assertTrue(self.reconstructor.check_ring(obj_ring))
        orig_check = self.reconstructor.next_check
        self.reconstructor.next_check = orig_check - 30
        self.assertTrue(self.reconstructor.check_ring(obj_ring))
        self.reconstructor.next_check = orig_check
        orig_ring_time = obj_ring._mtime
        obj_ring._mtime = orig_ring_time - 30
        self.assertTrue(self.reconstructor.check_ring(obj_ring))
        self.reconstructor.next_check = orig_check - 30
        self.assertFalse(self.reconstructor.check_ring(obj_ring))
        rmtree(testring, ignore_errors=1)

    def test_reconstruct_check_ring(self):
        # test reconstruct logs info when check_ring is false and that
        # there are no jobs built
        with mock.patch('swift.obj.reconstructor.ObjectReconstructor.'
                        'check_ring', return_value=False):
            self.reconstructor.reconstruct()
        msgs = self.logger.get_lines_for_level('info')
        self.assertIn('Ring change detected. Aborting'
                      ' current reconstruction pass.', msgs[0])
        self.assertEqual(self.reconstructor.reconstruction_count, 0)

    def test_build_reconstruction_jobs(self):
        self.reconstructor._reset_stats()
        for part_info in self.reconstructor.collect_parts():
            jobs = self.reconstructor.build_reconstruction_jobs(part_info)
            self.assertTrue(jobs[0]['job_type'] in
                            (object_reconstructor.SYNC,
                             object_reconstructor.REVERT))
            self.assert_expected_jobs(part_info['partition'], jobs)

    def test_handoffs_only(self):
        self.reconstructor.handoffs_only = True

        found_job_types = set()

        def fake_process_job(job):
            # increment failure counter
            self.reconstructor.handoffs_remaining += 1
            found_job_types.add(job['job_type'])

        self.reconstructor.process_job = fake_process_job

        _orig_build_jobs = self.reconstructor.build_reconstruction_jobs
        built_jobs = []

        def capture_jobs(part_info):
            jobs = _orig_build_jobs(part_info)
            built_jobs.append((part_info, jobs))
            return jobs

        with mock.patch.object(self.reconstructor, 'build_reconstruction_jobs',
                               capture_jobs):
            self.reconstructor.reconstruct()
        # only revert jobs
        found = [(part_info['partition'], set(
                 j['job_type'] for j in jobs))
                 for part_info, jobs in built_jobs]
        self.assertEqual([
            # partition, job_types
            (2, {'sync_revert'}),
        ], found)
        self.assertEqual(found_job_types, {object_reconstructor.REVERT})
        # but failures keep handoffs remaining
        msgs = self.logger.get_lines_for_level('info')
        self.assertIn('Next pass will continue to revert handoffs', msgs[-1])
        self.logger._clear()

        found_job_types = set()

        def fake_process_job(job):
            # success does not increment failure counter
            found_job_types.add(job['job_type'])

        self.reconstructor.process_job = fake_process_job

        # only revert jobs ... but all handoffs cleared out successfully
        self.reconstructor.reconstruct()
        self.assertEqual(found_job_types, {object_reconstructor.REVERT})
        # it's time to turn off handoffs_only
        msgs = self.logger.get_lines_for_level('warning')
        self.assertIn('You should disable handoffs_only', msgs[-1])

    def test_get_partners(self):
        expected = (
            # node_index, part_nodes => partners
            (0, [0, 1, 2, 3], [3, 1, 2]),
            (0, [2, 3, 1, 0], [0, 3, 1]),
            (0, [0, 1, 2, 3, 4], [4, 1, 2]),
            (0, [0, 1, 2, 3, 4, 5], [5, 1, 3]),
            (1, [0, 1, 2, 3, 4, 5], [0, 2, 4]),
            (2, [0, 1, 2, 3, 4, 5], [1, 3, 5]),
            (3, [0, 1, 2, 3, 4, 5], [2, 4, 0]),
            (4, [0, 1, 2, 3, 4, 5], [3, 5, 1]),
            (5, [0, 1, 2, 3, 4, 5], [4, 0, 2]),
            (5, [1, 4, 0, 2, 3, 5], [3, 1, 0]),
        )
        failures = []
        for frag_index, part_nodes, partners in expected:
            sync_to = object_reconstructor._get_partners(
                frag_index, part_nodes)
            if partners != sync_to:
                failures.append('Given nodes %r for index %s we expected '
                                '%r but got %r' % (
                                    part_nodes, frag_index, partners, sync_to))
        if failures:
            failures.insert(0, 'Some test scenarios failed:')
            self.fail('\n'.join(failures))

    def test_iter_nodes_for_frag(self):
        # no limit
        self.reconstructor.rebuild_handoff_node_count = -1
        policy = ECStoragePolicy(1, name='test', ec_type=DEFAULT_TEST_EC_TYPE,
                                 ec_ndata=4, ec_nparity=3)
        policy.object_ring = FabricatedRing(replicas=7, devices=28)
        primaries = policy.object_ring.get_part_nodes(0)

        node = primaries[0]
        nodes_for_frag = list(self.reconstructor._iter_nodes_for_frag(
            policy, 0, node))
        expected = [0, 0, 7, 14]
        self.assertEqual(expected, [n.get('index', n.get('handoff_index'))
                                    for n in nodes_for_frag])
        for node in nodes_for_frag:
            self.assertEqual(0, node['backend_index'])

        node = primaries[3]
        nodes_for_frag = list(self.reconstructor._iter_nodes_for_frag(
            policy, 0, node))
        expected = [3, 3, 10, 17]
        self.assertEqual(expected, [n.get('index', n.get('handoff_index'))
                                    for n in nodes_for_frag])
        for node in nodes_for_frag:
            self.assertEqual(3, node['backend_index'])

        node = primaries[-1]
        nodes_for_frag = list(self.reconstructor._iter_nodes_for_frag(
            policy, 0, node))
        expected = [6, 6, 13, 20]
        self.assertEqual(expected, [n.get('index', n.get('handoff_index'))
                                    for n in nodes_for_frag])
        for node in nodes_for_frag:
            self.assertEqual(6, node['backend_index'])

        # default limit is 2
        self.reconstructor.rebuild_handoff_node_count = 2
        node = primaries[0]
        nodes_for_frag = list(self.reconstructor._iter_nodes_for_frag(
            policy, 0, node))
        expected = [0, 0, 7]
        self.assertEqual(expected, [n.get('index', n.get('handoff_index'))
                                    for n in nodes_for_frag])
        for node in nodes_for_frag:
            self.assertEqual(0, node['backend_index'])

        # zero means only primaries
        self.reconstructor.rebuild_handoff_node_count = 0
        node = primaries[0]
        nodes_for_frag = list(self.reconstructor._iter_nodes_for_frag(
            policy, 0, node))
        expected = [0]
        self.assertEqual(expected, [n.get('index', n.get('handoff_index'))
                                    for n in nodes_for_frag])
        for node in nodes_for_frag:
            self.assertEqual(0, node['backend_index'])

    def test_collect_parts(self):
        self.reconstructor._reset_stats()
        parts = []
        for part_info in self.reconstructor.collect_parts():
            parts.append(part_info['partition'])
        self.assertEqual(sorted(parts), [0, 1, 2])

    def test_collect_parts_mkdirs_error(self):

        def blowup_mkdirs(path):
            raise OSError('Ow!')

        self.reconstructor._reset_stats()
        with mock.patch.object(object_reconstructor, 'mkdirs', blowup_mkdirs):
            rmtree(self.objects_1, ignore_errors=1)
            parts = []
            for part_info in self.reconstructor.collect_parts():
                parts.append(part_info['partition'])
            error_lines = self.logger.get_lines_for_level('error')
            self.assertEqual(len(error_lines), 1,
                             'Expected only one error, got %r' % error_lines)
            log_args, log_kwargs = self.logger.log_dict['error'][0]
            self.assertEqual(str(log_kwargs['exc_info'][1]), 'Ow!')

    def test_removes_zbf(self):
        # suppress unmount warning
        os.mkdir(os.path.join(self.devices, 'sda5'))
        # After running xfs_repair, a partition directory could become a
        # zero-byte file. If this happens, the reconstructor should clean it
        # up, log something, and move on to the next partition.

        # Surprise! Partition dir 1 is actually a zero-byte file.
        pol_1_part_1_path = os.path.join(self.objects_1, '1')
        rmtree(pol_1_part_1_path)
        with open(pol_1_part_1_path, 'w'):
            pass
        self.assertTrue(os.path.isfile(pol_1_part_1_path))  # sanity check

        self.reconstructor.process_job = lambda j: None
        self.reconstructor.reconstruct()

        self.assertFalse(os.path.exists(pol_1_part_1_path))
        warnings = self.logger.get_lines_for_level('warning')
        self.assertEqual(2, len(warnings))
        # first warning is due to get_hashes failing to take lock on non-dir
        self.assertIn(pol_1_part_1_path + '/hashes.pkl', warnings[0])
        self.assertIn('unable to read', warnings[0].lower())
        self.assertIn(pol_1_part_1_path, warnings[1])
        self.assertIn('not a directory', warnings[1].lower())

    def test_ignores_status_file(self):
        # Following fd86d5a, the auditor will leave status files on each device
        # until an audit can complete. The reconstructor should ignore these

        @contextmanager
        def status_files(*auditor_types):
            status_paths = [os.path.join(self.objects_1,
                                         'auditor_status_%s.json' % typ)
                            for typ in auditor_types]
            for status_path in status_paths:
                self.assertFalse(os.path.exists(status_path))  # sanity check
                with open(status_path, 'w'):
                    pass
                self.assertTrue(os.path.isfile(status_path))  # sanity check
            try:
                yield status_paths
            finally:
                for status_path in status_paths:
                    try:
                        os.unlink(status_path)
                    except OSError as e:
                        if e.errno != 2:
                            raise

        # suppress unmount warning
        os.mkdir(os.path.join(self.devices, 'sda5'))

        # since our collect_parts job is a generator, that yields directly
        # into build_jobs and then spawns it's safe to do the remove_files
        # without making reconstructor startup slow
        with status_files('ALL', 'ZBF') as status_paths:
            self.reconstructor._reset_stats()
            for part_info in self.reconstructor.collect_parts():
                self.assertNotIn(part_info['part_path'], status_paths)
            warnings = self.logger.get_lines_for_level('warning')
            self.assertEqual(0, len(warnings))
            for status_path in status_paths:
                self.assertTrue(os.path.exists(status_path))

    def _make_fake_ssync(self, ssync_calls, fail_jobs=None):
        """
        Replace SsyncSender with a thin Fake.

        :param ssync_calls: an empty list, a non_local, all calls to ssync will
                            be captured for assertion in the caller.
        :param fail_jobs: optional iter of dicts, any job passed into Fake that
                          matches a failure dict will return success == False.
        """
        class _fake_ssync(object):
            def __init__(self, daemon, node, job, suffixes, **kwargs):
                # capture context and generate an available_map of objs
                context = {}
                context['node'] = node
                context['job'] = job
                context['suffixes'] = suffixes
                self.suffixes = suffixes
                self.daemon = daemon
                self.job = job
                hash_gen = self.daemon._df_router[job['policy']].yield_hashes(
                    self.job['device'], self.job['partition'],
                    self.job['policy'], self.suffixes,
                    frag_index=self.job.get('frag_index'))
                self.available_map = {}
                for hash_, timestamps in hash_gen:
                    self.available_map[hash_] = timestamps
                context['available_map'] = self.available_map
                ssync_calls.append(context)
                self.success = True
                for failure in (fail_jobs or []):
                    if all(job.get(k) == v for (k, v) in failure.items()):
                        self.success = False
                        break
                context['success'] = self.success

            def __call__(self, *args, **kwargs):
                return self.success, self.available_map if self.success else {}

        return _fake_ssync

    def test_delete_reverted(self):
        # verify reconstructor deletes reverted frag indexes after ssync'ing

        def visit_obj_dirs(context):
            for suff in context['suffixes']:
                suff_dir = os.path.join(
                    context['job']['path'], suff)
                for root, dirs, files in os.walk(suff_dir):
                    for d in dirs:
                        dirpath = os.path.join(root, d)
                        files = os.listdir(dirpath)
                        yield dirpath, files

        n_files = n_files_after = 0

        # run reconstructor with delete function mocked out to check calls
        ssync_calls = []
        with mock.patch('swift.obj.reconstructor.ssync_sender',
                        self._make_fake_ssync(ssync_calls)), \
                mocked_http_conn(*[200] * 6, body=pickle.dumps({})), \
                mock.patch.object(
                    self.reconstructor, 'delete_reverted_objs') as mock_delete:
            self.reconstructor.reconstruct()
        expected_calls = []
        for context in ssync_calls:
            if context['job']['job_type'] == REVERT:
                for dirpath, files in visit_obj_dirs(context):
                    # sanity check - expect some files to be in dir,
                    # may not be for the reverted frag index
                    self.assertTrue(files)
                    n_files += len(files)
                expected_calls.append(mock.call(context['job'],
                                      context['available_map'],
                                      context['node']['index']))
        mock_delete.assert_has_calls(expected_calls, any_order=True)

        # N.B. in this next test sequence we acctually delete files after
        # revert, so the on-disk hashes can change.  In partition 1, if the
        # revert jobs (for frag_index 0 or 1) run before the sync job
        # (frag_index 4) all suffixes will get removed and the sync job won't
        # have anything to ship the remote (meaning there's no post-sync
        # REPLICATE call).  To keep the number of mocked_http_conn responses
        # predictable we force a stable job order by mocking random's shuffle.
        ssync_calls = []
        with mock.patch('swift.obj.reconstructor.ssync_sender',
                        self._make_fake_ssync(ssync_calls)), \
                mocked_http_conn(*[200] * 6, body=pickle.dumps({})), \
                mock.patch('swift.obj.reconstructor.random.shuffle'):
            self.reconstructor.reconstruct()
        for context in ssync_calls:
            if context['job']['job_type'] == REVERT:
                data_file_tail = ('#%s.data'
                                  % context['node']['index'])
                for dirpath, files in visit_obj_dirs(context):
                    n_files_after += len(files)
                    for filename in files:
                        self.assertFalse(filename.endswith(data_file_tail))

        # sanity check that some files should were deleted
        self.assertGreater(n_files, n_files_after)

    def test_no_delete_failed_revert(self):
        # test will only process revert jobs
        self.reconstructor.handoffs_only = True
        # suppress unmount warning
        os.mkdir(os.path.join(self.devices, 'sda5'))

        captured_ssync = []
        # fail all jobs on part 2 on sda1
        fail_jobs = [
            {'device': 'sda1', 'partition': 2},
        ]
        with mock.patch('swift.obj.reconstructor.ssync_sender',
                        self._make_fake_ssync(
                            captured_ssync, fail_jobs=fail_jobs)), \
                mocked_http_conn() as request_log:
            self.reconstructor.reconstruct()
        self.assertFalse(request_log.unexpected_requests)

        # global setup has four revert jobs
        self.assertEqual(len(captured_ssync), 2)
        expected_ssync_calls = {
            # device, part, frag_index: expected_occurrences
            ('sda1', 2, 2): 1,
            ('sda1', 2, 0): 1,
        }
        self.assertEqual(expected_ssync_calls, dict(collections.Counter(
            (context['job']['device'],
             context['job']['partition'],
             context['job']['frag_index'])
            for context in captured_ssync
        )))

        # failed jobs don't sync suffixes
        self.assertFalse(
            self.logger.get_lines_for_level('warning'))
        self.assertFalse(
            self.logger.get_lines_for_level('error'))
        # handoffs remaining and part exists
        self.assertEqual(2, self.reconstructor.handoffs_remaining)
        self.assertTrue(os.path.exists(self.parts_1['2']))

        # again with no failures
        captured_ssync = []
        with mock.patch('swift.obj.reconstructor.ssync_sender',
                        self._make_fake_ssync(captured_ssync)):
            self.reconstructor.reconstruct()
        # same jobs
        self.assertEqual(len(captured_ssync), 2)
        self.assertFalse(
            self.logger.get_lines_for_level('error'))
        # handoffs are cleaned up
        self.assertEqual(0, self.reconstructor.handoffs_remaining)
        warning_msgs = self.logger.get_lines_for_level('warning')
        self.assertEqual(1, len(warning_msgs))
        self.assertIn('no handoffs remaining', warning_msgs[0])

        # need one more pass to cleanup the part dir
        self.assertTrue(os.path.exists(self.parts_1['2']))
        with mock.patch('swift.obj.reconstructor.ssync_sender',
                        self._make_fake_ssync([])), \
                mocked_http_conn() as request_log:
            self.reconstructor.reconstruct()
        self.assertFalse(os.path.exists(self.parts_1['2']))

    def test_get_part_jobs(self):
        # yeah, this test code expects a specific setup
        self.assertEqual(len(self.part_nums), 3)

        # OK, at this point we should have 4 loaded parts with one
        jobs = []
        for partition in os.listdir(self.ec_obj_path):
            part_path = os.path.join(self.ec_obj_path, partition)
            jobs = self.reconstructor._get_part_jobs(
                self.ec_local_dev, part_path, int(partition), self.ec_policy)
            self.assert_expected_jobs(partition, jobs)

    def assertStatCount(self, stat_method, stat_prefix, expected_count):
        count = count_stats(self.logger, stat_method, stat_prefix)
        msg = 'expected %s != %s for %s %s' % (
            expected_count, count, stat_method, stat_prefix)
        self.assertEqual(expected_count, count, msg)

    def test_delete_partition(self):
        # part 2 is predefined to have all revert jobs
        part_path = os.path.join(self.objects_1, '2')
        self.assertTrue(os.access(part_path, os.F_OK))

        ssync_calls = []
        with mock.patch('swift.obj.reconstructor.ssync_sender',
                        self._make_fake_ssync(ssync_calls)):
            self.reconstructor.reconstruct(override_partitions=[2])

        expected_ssync_calls = sorted([
            (u'10.0.0.0', REVERT, 2, [u'3c1']),
            (u'10.0.0.2', REVERT, 2, [u'061']),
        ])
        self.assertEqual(expected_ssync_calls, sorted((
            c['node']['ip'],
            c['job']['job_type'],
            c['job']['partition'],
            c['suffixes'],
        ) for c in ssync_calls))

        expected_stats = {
            ('increment', 'partition.delete.count.'): 2,
            ('timing_since', 'partition.delete.timing'): 2,
        }
        for stat_key, expected in expected_stats.items():
            stat_method, stat_prefix = stat_key
            self.assertStatCount(stat_method, stat_prefix, expected)

        stub_data = self.reconstructor._get_hashes(
            'sda1', 2, self.policy, do_listdir=True)
        stub_data.update({'7ca': {None: '8f19c38e1cf8e2390d4ca29051407ae3'}})
        pickle_path = os.path.join(part_path, 'hashes.pkl')
        with open(pickle_path, 'wb') as f:
            pickle.dump(stub_data, f)

        # part 2 should be totally empty
        hash_gen = self.reconstructor._df_router[self.policy].yield_hashes(
            'sda1', '2', self.policy, suffixes=stub_data.keys())
        for path, hash_, ts in hash_gen:
            self.fail('found %s with %s in %s' % (hash_, ts, path))

        new_hashes = self.reconstructor._get_hashes(
            'sda1', 2, self.policy, do_listdir=True)
        self.assertFalse(new_hashes)

        # N.B. the partition directory is removed next pass
        ssync_calls = []
        with mocked_http_conn() as request_log:
            with mock.patch('swift.obj.reconstructor.ssync_sender',
                            self._make_fake_ssync(ssync_calls)):
                self.reconstructor.reconstruct(override_partitions=[2])
        self.assertEqual([], ssync_calls)
        self.assertEqual([], request_log.requests)
        self.assertFalse(os.access(part_path, os.F_OK))

    def test_process_job_all_success(self):
        rehash_per_job_type = {SYNC: 1, REVERT: 0}
        self.reconstructor._reset_stats()
        with mock_ssync_sender():
            found_jobs = []
            for part_info in self.reconstructor.collect_parts():
                jobs = self.reconstructor.build_reconstruction_jobs(
                    part_info)
                found_jobs.extend(jobs)
                for job in jobs:
                    self.logger._clear()
                    node_count = len(job['sync_to'])
                    rehash_count = node_count * rehash_per_job_type[
                        job['job_type']]
                    with mocked_http_conn(*[200] * rehash_count,
                                          body=pickle.dumps({})):
                        self.reconstructor.process_job(job)
                    if job['job_type'] == object_reconstructor.REVERT:
                        self.assertStatCount('update_stats',
                                             'suffix.hashes', 0)
                    else:
                        self.assertStatCount('update_stats',
                                             'suffix.hashes', node_count)
                        self.assertStatCount('update_stats',
                                             'suffix.syncs', node_count)
                    self.assertNotIn('error', self.logger.all_log_lines())
        self.assertEqual(
            dict(collections.Counter((job['device'], job['partition'],
                                      job['frag_index'], job['job_type'])
                                     for job in found_jobs)),
            {('sda1', 0, 1, SYNC): 1,
             ('sda1', 0, 2, REVERT): 1,
             ('sda1', 1, 0, REVERT): 1,
             ('sda1', 1, 1, REVERT): 1,
             ('sda1', 1, 4, SYNC): 1,
             ('sda1', 2, 0, REVERT): 1,
             ('sda1', 2, 2, REVERT): 1})
        self.assertEqual(self.reconstructor.suffix_sync, 12)
        self.assertEqual(self.reconstructor.suffix_count, 12)
        self.assertEqual(self.reconstructor.reconstruction_count, 7)

    def test_process_job_all_insufficient_storage(self):
        self.reconstructor._reset_stats()
        with mock_ssync_sender():
            with mocked_http_conn(*[507] * 10):
                found_jobs = []
                for part_info in self.reconstructor.collect_parts():
                    jobs = self.reconstructor.build_reconstruction_jobs(
                        part_info)
                    found_jobs.extend(jobs)
                    for job in jobs:
                        self.logger._clear()
                        self.reconstructor.process_job(job)
                        for line in self.logger.get_lines_for_level('error'):
                            self.assertIn('responded as unmounted', line)
                        self.assertEqual(0, count_stats(
                            self.logger, 'update_stats', 'suffix.hashes'))
                        self.assertEqual(0, count_stats(
                            self.logger, 'update_stats', 'suffix.syncs'))
        self.assertEqual(
            dict(collections.Counter((job['device'], job['partition'],
                                      job['frag_index'], job['job_type'])
                                     for job in found_jobs)),
            {('sda1', 0, 1, SYNC): 1,
             ('sda1', 0, 2, REVERT): 1,
             ('sda1', 1, 0, REVERT): 1,
             ('sda1', 1, 1, REVERT): 1,
             ('sda1', 1, 4, SYNC): 1,
             ('sda1', 2, 0, REVERT): 1,
             ('sda1', 2, 2, REVERT): 1})
        self.assertEqual(self.reconstructor.suffix_sync, 0)
        self.assertEqual(self.reconstructor.suffix_count, 0)
        self.assertEqual(self.reconstructor.reconstruction_count, 7)

    def test_process_job_all_client_error(self):
        self.reconstructor._reset_stats()
        with mock_ssync_sender():
            with mocked_http_conn(*[400] * 6):
                found_jobs = []
                for part_info in self.reconstructor.collect_parts():
                    jobs = self.reconstructor.build_reconstruction_jobs(
                        part_info)
                    found_jobs.extend(jobs)
                    for job in jobs:
                        self.logger._clear()
                        self.reconstructor.process_job(job)
                        for line in self.logger.get_lines_for_level('error'):
                            self.assertIn('Invalid response 400', line)
                        self.assertEqual(0, count_stats(
                            self.logger, 'update_stats', 'suffix.hashes'))
                        self.assertEqual(0, count_stats(
                            self.logger, 'update_stats', 'suffix.syncs'))
        self.assertEqual(
            dict(collections.Counter(
                (job['device'], job['partition'], job['frag_index'])
                for job in found_jobs)),
            {('sda1', 0, 1): 1,
             ('sda1', 0, 2): 1,
             ('sda1', 1, 0): 1,
             ('sda1', 1, 1): 1,
             ('sda1', 1, 4): 1,
             ('sda1', 2, 0): 1,
             ('sda1', 2, 2): 1})
        self.assertEqual(self.reconstructor.suffix_sync, 0)
        self.assertEqual(self.reconstructor.suffix_count, 0)
        self.assertEqual(self.reconstructor.reconstruction_count, 7)

    def test_process_job_all_timeout(self):
        self.reconstructor._reset_stats()
        with mock_ssync_sender(), mocked_http_conn(*[Timeout()] * 6):
            found_jobs = []
            for part_info in self.reconstructor.collect_parts():
                jobs = self.reconstructor.build_reconstruction_jobs(
                    part_info)
                found_jobs.extend(jobs)
                for job in jobs:
                    self.logger._clear()
                    self.reconstructor.process_job(job)
                    for line in self.logger.get_lines_for_level('error'):
                        self.assertIn('Timeout (Nones)', line)
                    self.assertStatCount(
                        'update_stats', 'suffix.hashes', 0)
                    self.assertStatCount(
                        'update_stats', 'suffix.syncs', 0)
        self.assertEqual(
            dict(collections.Counter(
                (job['device'], job['partition'], job['frag_index'])
                for job in found_jobs)),
            {('sda1', 0, 1): 1,
             ('sda1', 0, 2): 1,
             ('sda1', 1, 0): 1,
             ('sda1', 1, 1): 1,
             ('sda1', 1, 4): 1,
             ('sda1', 2, 0): 1,
             ('sda1', 2, 2): 1})
        self.assertEqual(self.reconstructor.suffix_sync, 0)
        self.assertEqual(self.reconstructor.suffix_count, 0)
        self.assertEqual(self.reconstructor.reconstruction_count, 7)

    def test_reconstructor_skipped_partpower_increase(self):
        self.reconstructor._reset_stats()
        _create_test_rings(self.testdir, 10)
        # Enforce re-reading the EC ring
        POLICIES[1].object_ring = ring.Ring(self.testdir, ring_name='object-1')

        self.reconstructor.reconstruct()

        self.assertEqual(0, self.reconstructor.reconstruction_count)
        warnings = self.logger.get_lines_for_level('warning')
        self.assertIn(
            "next_part_power set in policy 'one'. Skipping", warnings)


class TestGlobalSetupObjectReconstructorLegacyDurable(
        TestGlobalSetupObjectReconstructor):
    # Tests for reconstructor using real objects in test partition directories.
    legacy_durable = True


@patch_policies(with_ec_default=True)
class TestWorkerReconstructor(unittest.TestCase):

    maxDiff = None

    def setUp(self):
        super(TestWorkerReconstructor, self).setUp()
        self.logger = debug_logger()
        self.testdir = tempfile.mkdtemp()
        self.recon_cache_path = os.path.join(self.testdir, 'recon')
        self.rcache = os.path.join(self.recon_cache_path, 'object.recon')
        # dump_recon_cache expects recon_cache_path to exist
        os.mkdir(self.recon_cache_path)

    def tearDown(self):
        super(TestWorkerReconstructor, self).tearDown()
        shutil.rmtree(self.testdir)

    def test_no_workers_by_default(self):
        reconstructor = object_reconstructor.ObjectReconstructor(
            {}, logger=self.logger)
        self.assertEqual(0, reconstructor.reconstructor_workers)
        self.assertEqual(0, len(list(reconstructor.get_worker_args())))

    def test_bad_value_workers(self):
        reconstructor = object_reconstructor.ObjectReconstructor(
            {'reconstructor_workers': '-1'}, logger=self.logger)
        self.assertEqual(-1, reconstructor.reconstructor_workers)
        self.assertEqual(0, len(list(reconstructor.get_worker_args())))

    def test_workers_with_no_devices(self):
        def do_test(num_workers):
            reconstructor = object_reconstructor.ObjectReconstructor(
                {'reconstructor_workers': num_workers}, logger=self.logger)
            self.assertEqual(num_workers, reconstructor.reconstructor_workers)
            self.assertEqual(1, len(list(reconstructor.get_worker_args())))
            self.assertEqual([
                {'override_partitions': [], 'override_devices': [],
                 'multiprocess_worker_index': 0},
            ], list(reconstructor.get_worker_args()))
        do_test(1)
        do_test(10)

    def test_workers_with_devices_and_no_valid_overrides(self):
        reconstructor = object_reconstructor.ObjectReconstructor(
            {'reconstructor_workers': '2'}, logger=self.logger)
        reconstructor.get_local_devices = lambda: ['sdb', 'sdc']
        self.assertEqual(2, reconstructor.reconstructor_workers)
        # N.B. sdz is not in local_devices so there are no devices to process
        # but still expect a single worker process
        worker_args = list(reconstructor.get_worker_args(
            once=True, devices='sdz'))
        self.assertEqual(1, len(worker_args))
        self.assertEqual([{'override_partitions': [],
                           'override_devices': ['sdz'],
                           'multiprocess_worker_index': 0}],
                         worker_args)
        # overrides are ignored in forever mode
        worker_args = list(reconstructor.get_worker_args(
            once=False, devices='sdz'))
        self.assertEqual(2, len(worker_args))
        self.assertEqual([
            {'override_partitions': [], 'override_devices': ['sdb'],
             'multiprocess_worker_index': 0},
            {'override_partitions': [], 'override_devices': ['sdc'],
             'multiprocess_worker_index': 1},
        ], worker_args)

    def test_workers_with_devices(self):
        reconstructor = object_reconstructor.ObjectReconstructor(
            {'reconstructor_workers': '2'}, logger=self.logger)
        reconstructor.get_local_devices = lambda: ['sdb', 'sdc']
        self.assertEqual(2, reconstructor.reconstructor_workers)
        self.assertEqual(2, len(list(reconstructor.get_worker_args())))
        expected = [
            {'override_partitions': [], 'override_devices': ['sdb'],
             'multiprocess_worker_index': 0},
            {'override_partitions': [], 'override_devices': ['sdc'],
             'multiprocess_worker_index': 1},
        ]
        worker_args = list(reconstructor.get_worker_args(once=False))
        self.assertEqual(2, len(worker_args))
        self.assertEqual(expected, worker_args)
        worker_args = list(reconstructor.get_worker_args(once=True))
        self.assertEqual(2, len(worker_args))
        self.assertEqual(expected, worker_args)

    def test_workers_with_devices_and_overrides(self):
        reconstructor = object_reconstructor.ObjectReconstructor(
            {'reconstructor_workers': '2'}, logger=self.logger)
        reconstructor.get_local_devices = lambda: ['sdb', 'sdc']
        self.assertEqual(2, reconstructor.reconstructor_workers)
        # check we don't get more workers than override devices...
        # N.B. sdz is not in local_devices so should be ignored for the
        # purposes of generating workers
        worker_args = list(reconstructor.get_worker_args(
            once=True, devices='sdb,sdz', partitions='99,333'))
        self.assertEqual(1, len(worker_args))
        self.assertEqual(
            [{'override_partitions': [99, 333], 'override_devices': ['sdb'],
              'multiprocess_worker_index': 0}],
            worker_args)

        # overrides are ignored in forever mode
        reconstructor = object_reconstructor.ObjectReconstructor(
            {'reconstructor_workers': '2'}, logger=self.logger)
        reconstructor.get_local_devices = lambda: ['sdb', 'sdc']
        worker_args = list(reconstructor.get_worker_args(
            once=False, devices='sdb,sdz', partitions='99,333'))
        self.assertEqual([
            {'override_partitions': [], 'override_devices': ['sdb'],
             'multiprocess_worker_index': 0},
            {'override_partitions': [], 'override_devices': ['sdc'],
             'multiprocess_worker_index': 1}
        ], worker_args)

    def test_workers_with_lots_of_devices(self):
        reconstructor = object_reconstructor.ObjectReconstructor(
            {'reconstructor_workers': '2'}, logger=self.logger)
        reconstructor.get_local_devices = lambda: [
            'sdb', 'sdc', 'sdd', 'sde', 'sdf']
        self.assertEqual(2, reconstructor.reconstructor_workers)
        self.assertEqual(2, len(list(reconstructor.get_worker_args())))
        self.assertEqual([
            {'override_partitions': [],
             'override_devices': ['sdb', 'sdd', 'sdf'],
             'multiprocess_worker_index': 0},
            {'override_partitions': [],
             'override_devices': ['sdc', 'sde'],
             'multiprocess_worker_index': 1},
        ], list(reconstructor.get_worker_args()))

    def test_workers_with_lots_of_devices_and_overrides(self):
        # check that override devices get distributed across workers
        # in similar fashion to all devices
        reconstructor = object_reconstructor.ObjectReconstructor(
            {'reconstructor_workers': '2'}, logger=self.logger)
        reconstructor.get_local_devices = lambda: [
            'sdb', 'sdc', 'sdd', 'sde', 'sdf']
        self.assertEqual(2, reconstructor.reconstructor_workers)
        worker_args = list(reconstructor.get_worker_args(
            once=True, devices='sdb,sdd,sdf', partitions='99,333'))
        # 3 devices to operate on, 2 workers -> one worker gets two devices
        # and the other worker just gets one
        self.assertEqual([{
            'override_partitions': [99, 333],
            'override_devices': ['sdb', 'sdf'],
            'multiprocess_worker_index': 0,
        }, {
            'override_partitions': [99, 333],
            'override_devices': ['sdd'],
            'multiprocess_worker_index': 1,
        }], worker_args)

        # with 4 override devices, expect 2 per worker
        worker_args = list(reconstructor.get_worker_args(
            once=True, devices='sdb,sdc,sdd,sdf', partitions='99,333'))
        self.assertEqual(2, len(worker_args))
        self.assertEqual([
            {'override_partitions': [99, 333],
             'override_devices': ['sdb', 'sdd'],
             'multiprocess_worker_index': 0},
            {'override_partitions': [99, 333],
             'override_devices': ['sdc', 'sdf'],
             'multiprocess_worker_index': 1},
        ], worker_args)

    def test_workers_with_lots_of_workers(self):
        reconstructor = object_reconstructor.ObjectReconstructor(
            {'reconstructor_workers': '10'}, logger=self.logger)
        reconstructor.get_local_devices = lambda: ['sdb', 'sdc']
        self.assertEqual(10, reconstructor.reconstructor_workers)
        self.assertEqual(2, len(list(reconstructor.get_worker_args())))
        self.assertEqual([
            {'override_partitions': [], 'override_devices': ['sdb'],
             'multiprocess_worker_index': 0},
            {'override_partitions': [], 'override_devices': ['sdc'],
             'multiprocess_worker_index': 1},
        ], list(reconstructor.get_worker_args()))

    def test_workers_with_lots_of_workers_and_devices(self):
        reconstructor = object_reconstructor.ObjectReconstructor(
            {'reconstructor_workers': '10'}, logger=self.logger)
        reconstructor.get_local_devices = lambda: [
            'sdb', 'sdc', 'sdd', 'sde', 'sdf']
        self.assertEqual(10, reconstructor.reconstructor_workers)
        self.assertEqual(5, len(list(reconstructor.get_worker_args())))
        self.assertEqual([
            {'override_partitions': [], 'override_devices': ['sdb'],
             'multiprocess_worker_index': 0},
            {'override_partitions': [], 'override_devices': ['sdc'],
             'multiprocess_worker_index': 1},
            {'override_partitions': [], 'override_devices': ['sdd'],
             'multiprocess_worker_index': 2},
            {'override_partitions': [], 'override_devices': ['sde'],
             'multiprocess_worker_index': 3},
            {'override_partitions': [], 'override_devices': ['sdf'],
             'multiprocess_worker_index': 4},
        ], list(reconstructor.get_worker_args()))

    def test_workers_with_some_workers_and_devices(self):
        reconstructor = object_reconstructor.ObjectReconstructor(
            {}, logger=self.logger)
        reconstructor.get_local_devices = lambda: [
            'd%s' % (i + 1) for i in range(21)]

        # With more devices than workers, the work is spread out as evenly
        # as we can manage. When number-of-devices is a multiple of
        # number-of-workers, every worker has the same number of devices to
        # operate on.
        reconstructor.reconstructor_workers = 7
        worker_args = list(reconstructor.get_worker_args())
        self.assertEqual([len(a['override_devices']) for a in worker_args],
                         [3] * 7)

        # When number-of-devices is not a multiple of number-of-workers,
        # device counts differ by at most 1.
        reconstructor.reconstructor_workers = 5
        worker_args = list(reconstructor.get_worker_args())
        self.assertEqual(
            sorted([len(a['override_devices']) for a in worker_args]),
            [4, 4, 4, 4, 5])

        # With more workers than devices, we don't create useless workers.
        # We'll only make one per device.
        reconstructor.reconstructor_workers = 22
        worker_args = list(reconstructor.get_worker_args())
        self.assertEqual(
            [len(a['override_devices']) for a in worker_args],
            [1] * 21)

        # This is true even if we have far more workers than devices.
        reconstructor.reconstructor_workers = 2 ** 16
        worker_args = list(reconstructor.get_worker_args())
        self.assertEqual(
            [len(a['override_devices']) for a in worker_args],
            [1] * 21)

        # Spot check one full result for sanity's sake
        reconstructor.reconstructor_workers = 11
        self.assertEqual([
            {'override_partitions': [], 'override_devices': ['d1', 'd12'],
             'multiprocess_worker_index': 0},
            {'override_partitions': [], 'override_devices': ['d2', 'd13'],
             'multiprocess_worker_index': 1},
            {'override_partitions': [], 'override_devices': ['d3', 'd14'],
             'multiprocess_worker_index': 2},
            {'override_partitions': [], 'override_devices': ['d4', 'd15'],
             'multiprocess_worker_index': 3},
            {'override_partitions': [], 'override_devices': ['d5', 'd16'],
             'multiprocess_worker_index': 4},
            {'override_partitions': [], 'override_devices': ['d6', 'd17'],
             'multiprocess_worker_index': 5},
            {'override_partitions': [], 'override_devices': ['d7', 'd18'],
             'multiprocess_worker_index': 6},
            {'override_partitions': [], 'override_devices': ['d8', 'd19'],
             'multiprocess_worker_index': 7},
            {'override_partitions': [], 'override_devices': ['d9', 'd20'],
             'multiprocess_worker_index': 8},
            {'override_partitions': [], 'override_devices': ['d10', 'd21'],
             'multiprocess_worker_index': 9},
            {'override_partitions': [], 'override_devices': ['d11'],
             'multiprocess_worker_index': 10},
        ], list(reconstructor.get_worker_args()))

    def test_next_rcache_update_configured_with_stats_interval(self):
        now = time.time()
        with mock.patch('swift.obj.reconstructor.time.time', return_value=now):
            reconstructor = object_reconstructor.ObjectReconstructor(
                {}, logger=self.logger)
            self.assertEqual(now + 300, reconstructor._next_rcache_update)
            reconstructor = object_reconstructor.ObjectReconstructor(
                {'stats_interval': '30'}, logger=self.logger)
            self.assertEqual(now + 30, reconstructor._next_rcache_update)

    def test_is_healthy_rcache_update_waits_for_next_update(self):
        now = time.time()
        with mock.patch('swift.obj.reconstructor.time.time', return_value=now):
            reconstructor = object_reconstructor.ObjectReconstructor(
                {'recon_cache_path': self.recon_cache_path},
                logger=self.logger)
        # file does not exist to start
        self.assertFalse(os.path.exists(self.rcache))
        with mock.patch('swift.obj.reconstructor.os.path.getmtime',
                        return_value=10):
            self.assertTrue(reconstructor.is_healthy())
        # ... and isn't created until _next_rcache_update
        self.assertFalse(os.path.exists(self.rcache))
        # ... but if we wait 5 mins (by default)
        orig_next_update = reconstructor._next_rcache_update
        with mock.patch('swift.obj.reconstructor.time.time',
                        return_value=now + 301):
            with mock.patch('swift.obj.reconstructor.os.path.getmtime',
                            return_value=11):
                self.assertTrue(reconstructor.is_healthy())
        self.assertGreater(reconstructor._next_rcache_update, orig_next_update)
        # ... it will be created
        self.assertTrue(os.path.exists(self.rcache))
        with open(self.rcache) as f:
            data = json.load(f)
        # and empty
        self.assertEqual({}, data)

    def test_is_healthy(self):
        reconstructor = object_reconstructor.ObjectReconstructor(
            {'recon_cache_path': self.recon_cache_path},
            logger=self.logger)
        with mock.patch('swift.obj.reconstructor.os.path.getmtime',
                        return_value=10):
            self.assertTrue(reconstructor.is_healthy())
        reconstructor.get_local_devices = lambda: {
            'sdb%d' % p for p in reconstructor.policies}
        with mock.patch('swift.obj.reconstructor.os.path.getmtime',
                        return_value=11):
            self.assertFalse(reconstructor.is_healthy())
        reconstructor.all_local_devices = {
            'sdb%d' % p for p in reconstructor.policies}
        with mock.patch('swift.obj.reconstructor.os.path.getmtime',
                        return_value=12):
            self.assertTrue(reconstructor.is_healthy())

    def test_is_healthy_detects_ring_change(self):
        reconstructor = object_reconstructor.ObjectReconstructor(
            {'recon_cache_path': self.recon_cache_path,
             'reconstructor_workers': 1,
             # bind ip and port will not match any dev in first version of ring
             'bind_ip': '10.0.0.20', 'bind_port': '1020'},
            logger=self.logger)
        p = random.choice(reconstructor.policies)
        self.assertEqual(14, len(p.object_ring.devs))  # sanity check
        worker_args = list(reconstructor.get_worker_args())
        self.assertFalse(worker_args[0]['override_devices'])  # no local devs
        with mock.patch('swift.obj.reconstructor.os.path.getmtime',
                        return_value=10):
            self.assertTrue(reconstructor.is_healthy())
        # expand ring - now there are local devices
        p.object_ring.set_replicas(28)
        self.assertEqual(28, len(p.object_ring.devs))  # sanity check

        # If ring.gz mtime did not change, there is no change to detect
        with mock.patch('swift.obj.reconstructor.os.path.getmtime',
                        return_value=10):
            self.assertTrue(reconstructor.is_healthy())
        # Now, ring.gz mtime changed, so the change will be detected
        with mock.patch('swift.obj.reconstructor.os.path.getmtime',
                        return_value=11):
            self.assertFalse(reconstructor.is_healthy())

        self.assertNotEqual(worker_args, list(reconstructor.get_worker_args()))
        with mock.patch('swift.obj.reconstructor.os.path.getmtime',
                        return_value=12):
            self.assertTrue(reconstructor.is_healthy())

    def test_final_recon_dump(self):
        reconstructor = object_reconstructor.ObjectReconstructor(
            {'recon_cache_path': self.recon_cache_path},
            logger=self.logger)
        reconstructor.all_local_devices = ['sda', 'sdc']
        total = 12.0
        now = time.time()
        with mock.patch('swift.obj.reconstructor.time.time', return_value=now):
            reconstructor.final_recon_dump(total)
        with open(self.rcache) as f:
            data = json.load(f)
        self.assertEqual({
            'object_reconstruction_last': now,
            'object_reconstruction_time': total,
        }, data)
        total = 14.0
        now += total * 60
        with mock.patch('swift.obj.reconstructor.time.time', return_value=now):
            reconstructor.final_recon_dump(total)
        with open(self.rcache) as f:
            data = json.load(f)
        self.assertEqual({
            'object_reconstruction_last': now,
            'object_reconstruction_time': total,
        }, data)

        def check_per_disk_stats(before, now, old_total, total,
                                 override_devices):
            with mock.patch('swift.obj.reconstructor.time.time',
                            return_value=now), \
                    mock.patch('swift.obj.reconstructor.os.getpid',
                               return_value='pid-1'):
                reconstructor.final_recon_dump(
                    total, override_devices=override_devices)
            with open(self.rcache) as f:
                data = json.load(f)
            self.assertEqual({
                'object_reconstruction_last': before,
                'object_reconstruction_time': old_total,
                'object_reconstruction_per_disk': {
                    'sda': {
                        'object_reconstruction_last': now,
                        'object_reconstruction_time': total,
                        'pid': 'pid-1',
                    },
                    'sdc': {
                        'object_reconstruction_last': now,
                        'object_reconstruction_time': total,
                        'pid': 'pid-1',
                    },

                },
            }, data)

        # per_disk_stats with workers and local_devices
        reconstructor.reconstructor_workers = 1
        old_total = total
        total = 16.0
        before = now
        now += total * 60
        check_per_disk_stats(before, now, old_total, total, ['sda', 'sdc'])

        # per_disk_stats with workers and local_devices but no overrides
        reconstructor.reconstructor_workers = 1
        total = 17.0
        now += total * 60
        check_per_disk_stats(before, now, old_total, total, [])

        # and without workers we clear it out
        reconstructor.reconstructor_workers = 0
        total = 18.0
        now += total * 60
        with mock.patch('swift.obj.reconstructor.time.time', return_value=now):
            reconstructor.final_recon_dump(total)
        with open(self.rcache) as f:
            data = json.load(f)
        self.assertEqual({
            'object_reconstruction_last': now,
            'object_reconstruction_time': total,
        }, data)

        # set per disk stats again...
        reconstructor.reconstructor_workers = 1
        old_total = total
        total = 18.0
        before = now
        now += total * 60
        check_per_disk_stats(before, now, old_total, total, ['sda', 'sdc'])

        # ...then remove all devices and check we clear out per-disk stats
        reconstructor.all_local_devices = []
        total = 20.0
        now += total * 60
        with mock.patch('swift.obj.reconstructor.time.time', return_value=now):
            reconstructor.final_recon_dump(total)
        with open(self.rcache) as f:
            data = json.load(f)
        self.assertEqual({
            'object_reconstruction_last': now,
            'object_reconstruction_time': total,
        }, data)

    def test_dump_recon_run_once_inline(self):
        reconstructor = object_reconstructor.ObjectReconstructor(
            {'recon_cache_path': self.recon_cache_path},
            logger=self.logger)
        reconstructor.reconstruct = mock.MagicMock()
        now = time.time()
        later = now + 300  # 5 mins
        with mock.patch('swift.obj.reconstructor.time.time', side_effect=[
                now, later, later]):
            reconstructor.run_once()
        # no override args passed to reconstruct
        self.assertEqual([mock.call(
            override_devices=[],
            override_partitions=[]
        )], reconstructor.reconstruct.call_args_list)
        # script mode with no override args, we expect recon dumps
        self.assertTrue(os.path.exists(self.rcache))
        with open(self.rcache) as f:
            data = json.load(f)
        self.assertEqual({
            'object_reconstruction_last': later,
            'object_reconstruction_time': 5.0,
        }, data)
        total = 10.0
        later += total * 60
        with mock.patch('swift.obj.reconstructor.time.time',
                        return_value=later):
            reconstructor.final_recon_dump(total)
        with open(self.rcache) as f:
            data = json.load(f)
        self.assertEqual({
            'object_reconstruction_last': later,
            'object_reconstruction_time': 10.0,
        }, data)

    def test_dump_recon_run_once_in_worker(self):
        reconstructor = object_reconstructor.ObjectReconstructor(
            {'recon_cache_path': self.recon_cache_path,
             'reconstructor_workers': 1},
            logger=self.logger)
        reconstructor.get_local_devices = lambda: {'sda'}
        now = time.time()
        later = now + 300  # 5 mins

        def do_test(run_kwargs, expected_device):
            # get the actual kwargs that would be passed to run_once in a
            # worker
            run_once_kwargs = list(
                reconstructor.get_worker_args(once=True, **run_kwargs))[0]
            reconstructor.reconstruct = mock.MagicMock()
            with mock.patch('swift.obj.reconstructor.time.time',
                            side_effect=[now, later, later]):
                reconstructor.run_once(**run_once_kwargs)
            self.assertEqual([mock.call(
                override_devices=[expected_device],
                override_partitions=[]
            )], reconstructor.reconstruct.call_args_list)
            self.assertTrue(os.path.exists(self.rcache))
            with open(self.rcache) as f:
                data = json.load(f)
            self.assertEqual({
                # no aggregate is written but perhaps it should be, in which
                # case this assertion will need to change
                'object_reconstruction_per_disk': {
                    expected_device: {
                        'object_reconstruction_last': later,
                        'object_reconstruction_time': 5.0,
                        'pid': mock.ANY
                    }
                }
            }, data)

        # script mode with no CLI override args, we expect recon dumps
        do_test({}, 'sda')
        # script mode *with* CLI override devices, we expect recon dumps
        os.unlink(self.rcache)
        do_test(dict(devices='sda'), 'sda')
        # if the override device is not in local devices we still get
        # a recon dump, but it'll get cleaned up in the next aggregation
        os.unlink(self.rcache)
        do_test(dict(devices='sdz'), 'sdz')
        # repeat with no local devices
        reconstructor.get_local_devices = lambda: set()
        os.unlink(self.rcache)
        do_test(dict(devices='sdz'), 'sdz')

        # now disable workers and check that inline run_once updates rcache
        # and clears out per disk stats
        reconstructor.get_local_devices = lambda: {'sda'}
        now = time.time()
        later = now + 600  # 10 mins
        reconstructor.reconstructor_workers = 0
        with mock.patch('swift.obj.reconstructor.time.time',
                        side_effect=[now, later, later]):
            reconstructor.run_once()
        with open(self.rcache) as f:
            data = json.load(f)
        self.assertEqual({
            'object_reconstruction_last': later,
            'object_reconstruction_time': 10.0,
        }, data)

    def test_no_dump_recon_run_once(self):
        reconstructor = object_reconstructor.ObjectReconstructor(
            {'recon_cache_path': self.recon_cache_path},
            logger=self.logger)
        reconstructor.get_local_devices = lambda: {'sda', 'sdb', 'sdc'}

        def do_test(run_once_kwargs, expected_devices, expected_partitions):
            reconstructor.reconstruct = mock.MagicMock()
            now = time.time()
            later = now + 300  # 5 mins
            with mock.patch('swift.obj.reconstructor.time.time', side_effect=[
                    now, later, later]):
                reconstructor.run_once(**run_once_kwargs)
            # override args passed to reconstruct
            actual_calls = reconstructor.reconstruct.call_args_list
            self.assertEqual({'override_devices', 'override_partitions'},
                             set(actual_calls[0][1]))
            self.assertEqual(sorted(expected_devices),
                             sorted(actual_calls[0][1]['override_devices']))
            self.assertEqual(sorted(expected_partitions),
                             sorted(actual_calls[0][1]['override_partitions']))
            self.assertFalse(actual_calls[1:])
            self.assertEqual(False, os.path.exists(self.rcache))

        # inline mode with overrides never does recon dump
        reconstructor.reconstructor_workers = 0
        kwargs = {'devices': 'sda,sdb'}
        do_test(kwargs, ['sda', 'sdb'], [])

        # Have partition override, so no recon dump
        kwargs = {'partitions': '1,2,3'}
        do_test(kwargs, [], [1, 2, 3])
        reconstructor.reconstructor_workers = 1
        worker_kwargs = list(
            reconstructor.get_worker_args(once=True, **kwargs))[0]
        do_test(worker_kwargs, ['sda', 'sdb', 'sdc'], [1, 2, 3])

        reconstructor.reconstructor_workers = 0
        kwargs = {'devices': 'sda,sdb', 'partitions': '1,2,3'}
        do_test(kwargs, ['sda', 'sdb'], [1, 2, 3])
        reconstructor.reconstructor_workers = 1
        worker_kwargs = list(
            reconstructor.get_worker_args(once=True, **kwargs))[0]
        do_test(worker_kwargs, ['sda', 'sdb'], [1, 2, 3])

        # 'sdz' is not in local devices
        reconstructor.reconstructor_workers = 0
        kwargs = {'devices': 'sdz'}
        do_test(kwargs, ['sdz'], [])

    def test_run_forever_recon_aggregation(self):

        class StopForever(Exception):
            pass

        reconstructor = object_reconstructor.ObjectReconstructor({
            'reconstructor_workers': 2,
            'recon_cache_path': self.recon_cache_path
        }, logger=self.logger)
        reconstructor.get_local_devices = lambda: ['sda', 'sdb', 'sdc', 'sdd']
        reconstructor.reconstruct = mock.MagicMock()
        now = time.time()
        later = now + 300  # 5 mins
        worker_args = list(
            # include 'devices' kwarg as a sanity check - it should be ignored
            # in run_forever mode
            reconstructor.get_worker_args(once=False, devices='sda'))
        with mock.patch('swift.obj.reconstructor.time.time',
                        side_effect=[now, later, later]), \
                mock.patch('swift.obj.reconstructor.os.getpid',
                           return_value='pid-1'), \
                mock.patch('swift.obj.reconstructor.sleep',
                           side_effect=[StopForever]), \
                Timeout(.3), quiet_eventlet_exceptions(), \
                self.assertRaises(StopForever):
            gt = spawn(reconstructor.run_forever, **worker_args[0])
            gt.wait()
        # override args are passed to reconstruct
        self.assertEqual([mock.call(
            override_devices=['sda', 'sdc'],
            override_partitions=[]
        )], reconstructor.reconstruct.call_args_list)
        # forever mode with override args, we expect per-disk recon dumps
        self.assertTrue(os.path.exists(self.rcache))
        with open(self.rcache) as f:
            data = json.load(f)
        self.assertEqual({
            'object_reconstruction_per_disk': {
                'sda': {
                    'object_reconstruction_last': later,
                    'object_reconstruction_time': 5.0,
                    'pid': 'pid-1',
                },
                'sdc': {
                    'object_reconstruction_last': later,
                    'object_reconstruction_time': 5.0,
                    'pid': 'pid-1',
                },
            }
        }, data)
        reconstructor.reconstruct.reset_mock()
        # another worker would get *different* disks
        before = now = later
        later = now + 300  # 5 more minutes
        with mock.patch('swift.obj.reconstructor.time.time',
                        side_effect=[now, later, later]), \
                mock.patch('swift.obj.reconstructor.os.getpid',
                           return_value='pid-2'), \
                mock.patch('swift.obj.reconstructor.sleep',
                           side_effect=[StopForever]), \
                Timeout(.3), quiet_eventlet_exceptions(), \
                self.assertRaises(StopForever):
            gt = spawn(reconstructor.run_forever, **worker_args[1])
            gt.wait()
        # override args are parsed
        self.assertEqual([mock.call(
            override_devices=['sdb', 'sdd'],
            override_partitions=[]
        )], reconstructor.reconstruct.call_args_list)
        # forever mode with override args, we expect per-disk recon dumps
        self.assertTrue(os.path.exists(self.rcache))
        with open(self.rcache) as f:
            data = json.load(f)
        self.assertEqual({
            'object_reconstruction_per_disk': {
                'sda': {
                    'object_reconstruction_last': before,
                    'object_reconstruction_time': 5.0,
                    'pid': 'pid-1',
                },
                'sdb': {
                    'object_reconstruction_last': later,
                    'object_reconstruction_time': 5.0,
                    'pid': 'pid-2',
                },
                'sdc': {
                    'object_reconstruction_last': before,
                    'object_reconstruction_time': 5.0,
                    'pid': 'pid-1',
                },
                'sdd': {
                    'object_reconstruction_last': later,
                    'object_reconstruction_time': 5.0,
                    'pid': 'pid-2',
                },
            }
        }, data)

        # aggregation is done in the parent thread even later
        reconstructor.aggregate_recon_update()
        with open(self.rcache) as f:
            data = json.load(f)
        self.assertEqual({
            'object_reconstruction_last': later,
            'object_reconstruction_time': 10.0,
            'object_reconstruction_per_disk': {
                'sda': {
                    'object_reconstruction_last': before,
                    'object_reconstruction_time': 5.0,
                    'pid': 'pid-1',
                },
                'sdb': {
                    'object_reconstruction_last': later,
                    'object_reconstruction_time': 5.0,
                    'pid': 'pid-2',
                },
                'sdc': {
                    'object_reconstruction_last': before,
                    'object_reconstruction_time': 5.0,
                    'pid': 'pid-1',
                },
                'sdd': {
                    'object_reconstruction_last': later,
                    'object_reconstruction_time': 5.0,
                    'pid': 'pid-2',
                },
            }
        }, data)

    def test_run_forever_recon_no_devices(self):

        class StopForever(Exception):
            pass

        reconstructor = object_reconstructor.ObjectReconstructor({
            'reconstructor_workers': 2,
            'recon_cache_path': self.recon_cache_path
        }, logger=self.logger)

        def run_forever_but_stop(pid, mock_times, worker_kwargs):
            with mock.patch('swift.obj.reconstructor.time.time',
                            side_effect=mock_times), \
                    mock.patch('swift.obj.reconstructor.os.getpid',
                               return_value=pid), \
                    mock.patch('swift.obj.reconstructor.sleep',
                               side_effect=[StopForever]), \
                    Timeout(.3), quiet_eventlet_exceptions(), \
                    self.assertRaises(StopForever):
                gt = spawn(reconstructor.run_forever, **worker_kwargs)
                gt.wait()

        reconstructor.reconstruct = mock.MagicMock()
        now = time.time()
        # first run_forever with no devices
        reconstructor.get_local_devices = lambda: []
        later = now + 6  # 6 sec
        worker_args = list(
            # include 'devices' kwarg as a sanity check - it should be ignored
            # in run_forever mode
            reconstructor.get_worker_args(once=False, devices='sda'))
        run_forever_but_stop('pid-1', [now, later, later], worker_args[0])
        # override args are passed to reconstruct
        self.assertEqual([mock.call(
            override_devices=[],
            override_partitions=[]
        )], reconstructor.reconstruct.call_args_list)
        # forever mode with no args, we expect total recon dumps
        self.assertTrue(os.path.exists(self.rcache))
        with open(self.rcache) as f:
            data = json.load(f)
        expected = {
            'object_reconstruction_last': later,
            'object_reconstruction_time': 0.1,
        }
        self.assertEqual(expected, data)
        reconstructor.reconstruct.reset_mock()

        # aggregation is done in the parent thread even later
        now = later + 300
        with mock.patch('swift.obj.reconstructor.time.time',
                        side_effect=[now]):
            reconstructor.aggregate_recon_update()
        with open(self.rcache) as f:
            data = json.load(f)
        self.assertEqual(expected, data)

    def test_recon_aggregation_waits_for_all_devices(self):
        reconstructor = object_reconstructor.ObjectReconstructor({
            'reconstructor_workers': 2,
            'recon_cache_path': self.recon_cache_path
        }, logger=self.logger)
        reconstructor.all_local_devices = set([
            'd0', 'd1', 'd2', 'd3',
            # unreported device definitely matters
            'd4'])
        start = time.time() - 1000
        for i in range(4):
            with mock.patch('swift.obj.reconstructor.time.time',
                            return_value=start + (300 * i)), \
                    mock.patch('swift.obj.reconstructor.os.getpid',
                               return_value='pid-%s' % i):
                reconstructor.final_recon_dump(
                    i, override_devices=['d%s' % i])
        # sanity
        with open(self.rcache) as f:
            data = json.load(f)
        self.assertEqual({
            'object_reconstruction_per_disk': {
                'd0': {
                    'object_reconstruction_last': start,
                    'object_reconstruction_time': 0.0,
                    'pid': 'pid-0',
                },
                'd1': {
                    'object_reconstruction_last': start + 300,
                    'object_reconstruction_time': 1,
                    'pid': 'pid-1',
                },
                'd2': {
                    'object_reconstruction_last': start + 600,
                    'object_reconstruction_time': 2,
                    'pid': 'pid-2',
                },
                'd3': {
                    'object_reconstruction_last': start + 900,
                    'object_reconstruction_time': 3,
                    'pid': 'pid-3',
                },
            }
        }, data)

        # unreported device d4 prevents aggregation
        reconstructor.aggregate_recon_update()
        with open(self.rcache) as f:
            data = json.load(f)
        self.assertNotIn('object_reconstruction_last', data)
        self.assertNotIn('object_reconstruction_time', data)
        self.assertEqual(set(['d0', 'd1', 'd2', 'd3']),
                         set(data['object_reconstruction_per_disk'].keys()))

        # it's idempotent
        reconstructor.aggregate_recon_update()
        with open(self.rcache) as f:
            data = json.load(f)
        self.assertNotIn('object_reconstruction_last', data)
        self.assertNotIn('object_reconstruction_time', data)
        self.assertEqual(set(['d0', 'd1', 'd2', 'd3']),
                         set(data['object_reconstruction_per_disk'].keys()))

        # remove d4, we no longer wait on it for aggregation
        reconstructor.all_local_devices = set(['d0', 'd1', 'd2', 'd3'])
        reconstructor.aggregate_recon_update()
        with open(self.rcache) as f:
            data = json.load(f)
        self.assertEqual(start + 900, data['object_reconstruction_last'])
        self.assertEqual(15, data['object_reconstruction_time'])
        self.assertEqual(set(['d0', 'd1', 'd2', 'd3']),
                         set(data['object_reconstruction_per_disk'].keys()))

    def test_recon_aggregation_removes_devices(self):
        reconstructor = object_reconstructor.ObjectReconstructor({
            'reconstructor_workers': 2,
            'recon_cache_path': self.recon_cache_path
        }, logger=self.logger)
        reconstructor.all_local_devices = set(['d0', 'd1', 'd2', 'd3'])
        start = time.time() - 1000
        for i in range(4):
            with mock.patch('swift.obj.reconstructor.time.time',
                            return_value=start + (300 * i)), \
                    mock.patch('swift.obj.reconstructor.os.getpid',
                               return_value='pid-%s' % i):
                reconstructor.final_recon_dump(
                    i, override_devices=['d%s' % i])
        # sanity
        with open(self.rcache) as f:
            data = json.load(f)
        self.assertEqual({
            'object_reconstruction_per_disk': {
                'd0': {
                    'object_reconstruction_last': start,
                    'object_reconstruction_time': 0.0,
                    'pid': 'pid-0',
                },
                'd1': {
                    'object_reconstruction_last': start + 300,
                    'object_reconstruction_time': 1,
                    'pid': 'pid-1',
                },
                'd2': {
                    'object_reconstruction_last': start + 600,
                    'object_reconstruction_time': 2,
                    'pid': 'pid-2',
                },
                'd3': {
                    'object_reconstruction_last': start + 900,
                    'object_reconstruction_time': 3,
                    'pid': 'pid-3',
                },
            }
        }, data)

        reconstructor.all_local_devices = set(['d0', 'd1', 'd2', 'd3'])
        reconstructor.aggregate_recon_update()
        with open(self.rcache) as f:
            data = json.load(f)
        self.assertEqual(start + 900, data['object_reconstruction_last'])
        self.assertEqual(15, data['object_reconstruction_time'])
        self.assertEqual(set(['d0', 'd1', 'd2', 'd3']),
                         set(data['object_reconstruction_per_disk'].keys()))

        # it's idempotent
        reconstructor.aggregate_recon_update()
        with open(self.rcache) as f:
            data = json.load(f)
        self.assertEqual({
            'object_reconstruction_last': start + 900,
            'object_reconstruction_time': 15,
            'object_reconstruction_per_disk': {
                'd0': {
                    'object_reconstruction_last': start,
                    'object_reconstruction_time': 0.0,
                    'pid': 'pid-0',
                },
                'd1': {
                    'object_reconstruction_last': start + 300,
                    'object_reconstruction_time': 1,
                    'pid': 'pid-1',
                },
                'd2': {
                    'object_reconstruction_last': start + 600,
                    'object_reconstruction_time': 2,
                    'pid': 'pid-2',
                },
                'd3': {
                    'object_reconstruction_last': start + 900,
                    'object_reconstruction_time': 3,
                    'pid': 'pid-3',
                },
            }
        }, data)

        # if a device is removed from the ring
        reconstructor.all_local_devices = set(['d1', 'd2', 'd3'])
        reconstructor.aggregate_recon_update()
        with open(self.rcache) as f:
            data = json.load(f)
        # ... it's per-disk stats are removed (d0)
        self.assertEqual({
            'object_reconstruction_last': start + 900,
            'object_reconstruction_time': 11,
            'object_reconstruction_per_disk': {
                'd1': {
                    'object_reconstruction_last': start + 300,
                    'object_reconstruction_time': 1,
                    'pid': 'pid-1',
                },
                'd2': {
                    'object_reconstruction_last': start + 600,
                    'object_reconstruction_time': 2,
                    'pid': 'pid-2',
                },
                'd3': {
                    'object_reconstruction_last': start + 900,
                    'object_reconstruction_time': 3,
                    'pid': 'pid-3',
                },
            }
        }, data)

        # which can affect the aggregates!
        reconstructor.all_local_devices = set(['d1', 'd2'])
        reconstructor.aggregate_recon_update()
        with open(self.rcache) as f:
            data = json.load(f)
        self.assertEqual({
            'object_reconstruction_last': start + 600,
            'object_reconstruction_time': 6,
            'object_reconstruction_per_disk': {
                'd1': {
                    'object_reconstruction_last': start + 300,
                    'object_reconstruction_time': 1,
                    'pid': 'pid-1',
                },
                'd2': {
                    'object_reconstruction_last': start + 600,
                    'object_reconstruction_time': 2,
                    'pid': 'pid-2',
                },
            }
        }, data)

    def test_recon_aggregation_at_end_of_run_once(self):
        reconstructor = object_reconstructor.ObjectReconstructor({
            'reconstructor_workers': 2,
            'recon_cache_path': self.recon_cache_path
        }, logger=self.logger)
        reconstructor.all_local_devices = set(['d0', 'd1', 'd2', 'd3'])
        start = time.time() - 1000
        for i in range(4):
            with mock.patch('swift.obj.reconstructor.time.time',
                            return_value=start + (300 * i)), \
                    mock.patch('swift.obj.reconstructor.os.getpid',
                               return_value='pid-%s' % i):
                reconstructor.final_recon_dump(
                    i, override_devices=['d%s' % i])
        # sanity
        with open(self.rcache) as f:
            data = json.load(f)
        self.assertEqual({
            'object_reconstruction_per_disk': {
                'd0': {
                    'object_reconstruction_last': start,
                    'object_reconstruction_time': 0.0,
                    'pid': 'pid-0',
                },
                'd1': {
                    'object_reconstruction_last': start + 300,
                    'object_reconstruction_time': 1,
                    'pid': 'pid-1',
                },
                'd2': {
                    'object_reconstruction_last': start + 600,
                    'object_reconstruction_time': 2,
                    'pid': 'pid-2',
                },
                'd3': {
                    'object_reconstruction_last': start + 900,
                    'object_reconstruction_time': 3,
                    'pid': 'pid-3',
                },
            }
        }, data)

        reconstructor.post_multiprocess_run()
        with open(self.rcache) as f:
            data = json.load(f)
        self.assertEqual(start + 900, data['object_reconstruction_last'])
        self.assertEqual(15, data['object_reconstruction_time'])

    def test_recon_aggregation_races_with_final_recon_dump(self):
        reconstructor = object_reconstructor.ObjectReconstructor({
            'reconstructor_workers': 2,
            'recon_cache_path': self.recon_cache_path
        }, logger=self.logger)
        reconstructor.all_local_devices = set(['d0', 'd1'])
        start = time.time() - 1000
        # first worker dumps to recon cache
        with mock.patch('swift.obj.reconstructor.time.time',
                        return_value=start), \
                mock.patch('swift.obj.reconstructor.os.getpid',
                           return_value='pid-0'):
            reconstructor.final_recon_dump(
                1, override_devices=['d0'])
        # sanity
        with open(self.rcache) as f:
            data = json.load(f)
        self.assertEqual({
            'object_reconstruction_per_disk': {
                'd0': {
                    'object_reconstruction_last': start,
                    'object_reconstruction_time': 1,
                    'pid': 'pid-0',
                },
            }
        }, data)

        # simulate a second worker concurrently dumping to recon cache while
        # parent is aggregating existing results; mock dump_recon_cache as a
        # convenient way to interrupt parent aggregate_recon_update and 'pass
        # control' to second worker
        updated_data = []  # state of recon cache just after second worker dump

        def simulate_other_process_final_recon_dump():
            with mock.patch('swift.obj.reconstructor.time.time',
                            return_value=start + 999), \
                    mock.patch('swift.obj.reconstructor.os.getpid',
                               return_value='pid-1'):
                reconstructor.final_recon_dump(
                    1000, override_devices=['d1'])
                with open(self.rcache) as f:
                    updated_data.append(json.load(f))

        def fake_dump_recon_cache(*args, **kwargs):
            # temporarily put back real dump_recon_cache
            with mock.patch('swift.obj.reconstructor.dump_recon_cache',
                            dump_recon_cache):
                simulate_other_process_final_recon_dump()
            # and now proceed with parent dump_recon_cache
            dump_recon_cache(*args, **kwargs)

        reconstructor.dump_recon_cache = fake_dump_recon_cache
        with mock.patch('swift.obj.reconstructor.dump_recon_cache',
                        fake_dump_recon_cache):
            reconstructor.aggregate_recon_update()

        self.assertEqual([{  # sanity check - second process did dump its data
            'object_reconstruction_per_disk': {
                'd0': {
                    'object_reconstruction_last': start,
                    'object_reconstruction_time': 1,
                    'pid': 'pid-0',
                },
                'd1': {
                    'object_reconstruction_last': start + 999,
                    'object_reconstruction_time': 1000,
                    'pid': 'pid-1',
                },
            }
        }], updated_data)

        with open(self.rcache) as f:
            data = json.load(f)
        self.assertEqual({
            'object_reconstruction_per_disk': {
                'd0': {
                    'object_reconstruction_last': start,
                    'object_reconstruction_time': 1,
                    'pid': 'pid-0',
                },
                'd1': {
                    'object_reconstruction_last': start + 999,
                    'object_reconstruction_time': 1000,
                    'pid': 'pid-1',
                },
            }
        }, data)

        # next aggregation will find d1 stats
        reconstructor.aggregate_recon_update()

        with open(self.rcache) as f:
            data = json.load(f)
        self.assertEqual({
            'object_reconstruction_last': start + 999,
            'object_reconstruction_time': 1000,
            'object_reconstruction_per_disk': {
                'd0': {
                    'object_reconstruction_last': start,
                    'object_reconstruction_time': 1,
                    'pid': 'pid-0',
                },
                'd1': {
                    'object_reconstruction_last': start + 999,
                    'object_reconstruction_time': 1000,
                    'pid': 'pid-1',
                },
            }
        }, data)

    def test_worker_logging(self):
        reconstructor = object_reconstructor.ObjectReconstructor({
            'reconstructor_workers': 4,
            'recon_cache_path': self.recon_cache_path
        }, logger=self.logger)

        def log_some_stuff(*a, **kw):
            reconstructor.logger.debug("debug message")
            reconstructor.logger.info("info message")
            reconstructor.logger.warning("warning message")
            reconstructor.logger.error("error message")

        with mock.patch.object(reconstructor, 'reconstruct',
                               log_some_stuff), \
                mock.patch("os.getpid", lambda: 20641):
            reconstructor.get_worker_args()
            reconstructor.run_once(multiprocess_worker_index=1,
                                   override_devices=['sda', 'sdb'])

        prefix = "[worker 2/4 pid=20641] "
        for level, lines in self.logger.logger.all_log_lines().items():
            for line in lines:
                self.assertTrue(
                    line.startswith(prefix),
                    "%r doesn't start with %r (level %s)" % (
                        line, prefix, level))


@patch_policies(with_ec_default=True)
class BaseTestObjectReconstructor(unittest.TestCase):
    def setUp(self):
        skip_if_no_xattrs()
        self.policy = POLICIES.default
        self.policy.object_ring._rtime = time.time() + 3600
        self.testdir = tempfile.mkdtemp()
        self.devices = os.path.join(self.testdir, 'devices')
        self.local_dev = self.policy.object_ring.devs[0]
        self.ip = self.local_dev['replication_ip']
        self.port = self.local_dev['replication_port']
        self.conf = {
            'devices': self.devices,
            'mount_check': False,
            'bind_ip': self.ip,
            'bind_port': self.port,
        }
        self.logger = debug_logger('object-reconstructor')
        self._configure_reconstructor()
        self.policy.object_ring.max_more_nodes = \
            self.policy.object_ring.replicas
        self.ts_iter = make_timestamp_iter()
        self.fabricated_ring = FabricatedRing(replicas=14, devices=28)

    def _configure_reconstructor(self, **kwargs):
        self.conf.update(kwargs)
        self.reconstructor = object_reconstructor.ObjectReconstructor(
            self.conf, logger=self.logger)
        self.reconstructor._reset_stats()
        # some tests bypass build_reconstruction_jobs and go to process_job
        # directly, so you end up with a /0 when you try to show the
        # percentage of complete jobs as ratio of the total job count
        self.reconstructor.job_count = 1
        # if we ever let a test through without properly patching the
        # REPLICATE and SSYNC calls - let's fail sort fast-ish
        self.reconstructor.lockup_timeout = 3

    def tearDown(self):
        self.reconstructor._reset_stats()
        self.reconstructor.stats_line()
        shutil.rmtree(self.testdir)

    def ts(self):
        return next(self.ts_iter)


class TestObjectReconstructor(BaseTestObjectReconstructor):
    def test_handoffs_only_default(self):
        # sanity neither option added to default conf
        self.conf.pop('handoffs_first', None)
        self.conf.pop('handoffs_only', None)
        self.reconstructor = object_reconstructor.ObjectReconstructor(
            self.conf, logger=self.logger)
        self.assertFalse(self.reconstructor.handoffs_only)

    def test_handoffs_first_enables_handoffs_only(self):
        self.conf['handoffs_first'] = "True"
        self.conf.pop('handoffs_only', None)  # sanity
        self.reconstructor = object_reconstructor.ObjectReconstructor(
            self.conf, logger=self.logger)
        self.assertTrue(self.reconstructor.handoffs_only)
        warnings = self.logger.get_lines_for_level('warning')
        expected = [
            'The handoffs_first option is deprecated in favor '
            'of handoffs_only. This option may be ignored in a '
            'future release.',
            'Handoff only mode is not intended for normal operation, '
            'use handoffs_only with care.',
        ]
        self.assertEqual(expected, warnings)

    def test_handoffs_only_ignores_handoffs_first(self):
        self.conf['handoffs_first'] = "True"
        self.conf['handoffs_only'] = "False"
        self.reconstructor = object_reconstructor.ObjectReconstructor(
            self.conf, logger=self.logger)
        self.assertFalse(self.reconstructor.handoffs_only)
        warnings = self.logger.get_lines_for_level('warning')
        expected = [
            'The handoffs_first option is deprecated in favor of '
            'handoffs_only. This option may be ignored in a future release.',
            'Ignored handoffs_first option in favor of handoffs_only.',
        ]
        self.assertEqual(expected, warnings)

    def test_handoffs_only_enabled(self):
        self.conf.pop('handoffs_first', None)  # sanity
        self.conf['handoffs_only'] = "True"
        self.reconstructor = object_reconstructor.ObjectReconstructor(
            self.conf, logger=self.logger)
        self.assertTrue(self.reconstructor.handoffs_only)
        warnings = self.logger.get_lines_for_level('warning')
        expected = [
            'Handoff only mode is not intended for normal operation, '
            'use handoffs_only with care.',
        ]
        self.assertEqual(expected, warnings)

    def test_handoffs_only_true_and_first_true(self):
        self.conf['handoffs_first'] = "True"
        self.conf['handoffs_only'] = "True"
        self.reconstructor = object_reconstructor.ObjectReconstructor(
            self.conf, logger=self.logger)
        self.assertTrue(self.reconstructor.handoffs_only)
        warnings = self.logger.get_lines_for_level('warning')
        expected = [
            'The handoffs_first option is deprecated in favor of '
            'handoffs_only. This option may be ignored in a future release.',
            'Handoff only mode is not intended for normal operation, '
            'use handoffs_only with care.',
        ]
        self.assertEqual(expected, warnings)

    def test_handoffs_only_false_and_first_false(self):
        self.conf['handoffs_only'] = "False"
        self.conf['handoffs_first'] = "False"
        self.reconstructor = object_reconstructor.ObjectReconstructor(
            self.conf, logger=self.logger)
        self.assertFalse(self.reconstructor.handoffs_only)
        warnings = self.logger.get_lines_for_level('warning')
        expected = [
            'The handoffs_first option is deprecated in favor of '
            'handoffs_only. This option may be ignored in a future release.',
        ]
        self.assertEqual(expected, warnings)

    def test_handoffs_only_none_and_first_false(self):
        self.conf['handoffs_first'] = "False"
        self.conf.pop('handoffs_only', None)  # sanity
        self.reconstructor = object_reconstructor.ObjectReconstructor(
            self.conf, logger=self.logger)
        self.assertFalse(self.reconstructor.handoffs_only)
        warnings = self.logger.get_lines_for_level('warning')
        expected = [
            'The handoffs_first option is deprecated in favor of '
            'handoffs_only. This option may be ignored in a future release.',
        ]
        self.assertEqual(expected, warnings)

    def test_handoffs_only_false_and_first_none(self):
        self.conf.pop('handoffs_first', None)  # sanity
        self.conf['handoffs_only'] = "False"
        self.reconstructor = object_reconstructor.ObjectReconstructor(
            self.conf, logger=self.logger)
        self.assertFalse(self.reconstructor.handoffs_only)
        warnings = self.logger.get_lines_for_level('warning')
        self.assertFalse(warnings)

    def test_handoffs_only_true_and_first_false(self):
        self.conf['handoffs_first'] = "False"
        self.conf['handoffs_only'] = "True"
        self.reconstructor = object_reconstructor.ObjectReconstructor(
            self.conf, logger=self.logger)
        self.assertTrue(self.reconstructor.handoffs_only)
        warnings = self.logger.get_lines_for_level('warning')
        expected = [
            'The handoffs_first option is deprecated in favor of '
            'handoffs_only. This option may be ignored in a future release.',
            'Handoff only mode is not intended for normal operation, '
            'use handoffs_only with care.',
        ]
        self.assertEqual(expected, warnings)

    def test_two_ec_policies(self):
        with patch_policies([
                StoragePolicy(0, name='zero', is_deprecated=True),
                ECStoragePolicy(1, name='one', is_default=True,
                                ec_type=DEFAULT_TEST_EC_TYPE,
                                ec_ndata=4, ec_nparity=3),
                ECStoragePolicy(2, name='two',
                                ec_type=DEFAULT_TEST_EC_TYPE,
                                ec_ndata=8, ec_nparity=2)],
                            fake_ring_args=[
                                {}, {'replicas': 7}, {'replicas': 10}]):
            self._configure_reconstructor()
            jobs = []

            def process_job(job):
                jobs.append(job)

            self.reconstructor.process_job = process_job

            os.makedirs(os.path.join(self.devices, 'sda', 'objects-1', '0'))
            self.reconstructor.run_once()
            self.assertEqual(1, len(jobs))

    def test_collect_parts_skips_non_ec_policy_and_device(self):
        stub_parts = (371, 78, 419, 834)
        for policy in POLICIES:
            datadir = diskfile.get_data_dir(policy)
            for part in stub_parts:
                utils.mkdirs(os.path.join(
                    self.devices, self.local_dev['device'],
                    datadir, str(part)))
        part_infos = list(self.reconstructor.collect_parts())
        found_parts = sorted(int(p['partition']) for p in part_infos)
        self.assertEqual(found_parts, sorted(stub_parts))
        for part_info in part_infos:
            self.assertEqual(part_info['local_dev'], self.local_dev)
            self.assertEqual(part_info['policy'], self.policy)
            self.assertEqual(part_info['part_path'],
                             os.path.join(self.devices,
                                          self.local_dev['device'],
                                          diskfile.get_data_dir(self.policy),
                                          str(part_info['partition'])))

    def test_collect_parts_skips_non_local_devs_servers_per_port(self):
        self._configure_reconstructor(devices=self.devices, mount_check=False,
                                      bind_ip=self.ip, bind_port=self.port,
                                      servers_per_port=2)

        device_parts = {
            'sda': (374,),
            'sdb': (179, 807),  # w/one-serv-per-port, same IP alone is local
            'sdc': (363, 468, 843),
            'sdd': (912,),  # "not local" via different IP
        }
        for policy in POLICIES:
            datadir = diskfile.get_data_dir(policy)
            for dev, parts in device_parts.items():
                for part in parts:
                    utils.mkdirs(os.path.join(
                        self.devices, dev,
                        datadir, str(part)))

        # we're only going to add sda and sdc into the ring
        local_devs = ('sda', 'sdb', 'sdc')
        stub_ring_devs = [{
            'id': i,
            'device': dev,
            'replication_ip': self.ip,
            'replication_port': self.port + 1 if dev == 'sdb' else self.port,
        } for i, dev in enumerate(local_devs)]
        stub_ring_devs.append({
            'id': len(local_devs),
            'device': 'sdd',
            'replication_ip': '127.0.0.88',  # not local via IP
            'replication_port': self.port,
        })
        self.reconstructor.bind_ip = '0.0.0.0'  # use whataremyips
        with mock.patch('swift.obj.reconstructor.whataremyips',
                        return_value=[self.ip]), \
                mock.patch.object(self.policy.object_ring, '_devs',
                                  new=stub_ring_devs):
            part_infos = list(self.reconstructor.collect_parts())
        found_parts = sorted(int(p['partition']) for p in part_infos)
        expected_parts = sorted(itertools.chain(
            *(device_parts[d] for d in local_devs)))
        self.assertEqual(found_parts, expected_parts)
        for part_info in part_infos:
            self.assertEqual(part_info['policy'], self.policy)
            self.assertIn(part_info['local_dev'], stub_ring_devs)
            dev = part_info['local_dev']
            self.assertEqual(part_info['part_path'],
                             os.path.join(self.devices,
                                          dev['device'],
                                          diskfile.get_data_dir(self.policy),
                                          str(part_info['partition'])))

    def test_collect_parts_multi_device_skips_non_non_local_devs(self):
        device_parts = {
            'sda': (374,),
            'sdb': (179, 807),  # "not local" via different port
            'sdc': (363, 468, 843),
            'sdd': (912,),  # "not local" via different IP
        }
        for policy in POLICIES:
            datadir = diskfile.get_data_dir(policy)
            for dev, parts in device_parts.items():
                for part in parts:
                    utils.mkdirs(os.path.join(
                        self.devices, dev,
                        datadir, str(part)))

        # we're only going to add sda and sdc into the ring
        local_devs = ('sda', 'sdc')
        stub_ring_devs = [{
            'id': i,
            'device': dev,
            'replication_ip': self.ip,
            'replication_port': self.port,
        } for i, dev in enumerate(local_devs)]
        stub_ring_devs.append({
            'id': len(local_devs),
            'device': 'sdb',
            'replication_ip': self.ip,
            'replication_port': self.port + 1,  # not local via port
        })
        stub_ring_devs.append({
            'id': len(local_devs) + 1,
            'device': 'sdd',
            'replication_ip': '127.0.0.88',  # not local via IP
            'replication_port': self.port,
        })
        self.reconstructor.bind_ip = '0.0.0.0'  # use whataremyips
        with mock.patch('swift.obj.reconstructor.whataremyips',
                        return_value=[self.ip]), \
                mock.patch.object(self.policy.object_ring, '_devs',
                                  new=stub_ring_devs):
            part_infos = list(self.reconstructor.collect_parts())
        found_parts = sorted(int(p['partition']) for p in part_infos)
        expected_parts = sorted(itertools.chain(
            *(device_parts[d] for d in local_devs)))
        self.assertEqual(found_parts, expected_parts)
        for part_info in part_infos:
            self.assertEqual(part_info['policy'], self.policy)
            self.assertIn(part_info['local_dev'], stub_ring_devs)
            dev = part_info['local_dev']
            self.assertEqual(part_info['part_path'],
                             os.path.join(self.devices,
                                          dev['device'],
                                          diskfile.get_data_dir(self.policy),
                                          str(part_info['partition'])))

    def test_collect_parts_multi_device_skips_non_ring_devices(self):
        device_parts = {
            'sda': (374,),
            'sdc': (363, 468, 843),
        }
        for policy in POLICIES:
            datadir = diskfile.get_data_dir(policy)
            for dev, parts in device_parts.items():
                for part in parts:
                    utils.mkdirs(os.path.join(
                        self.devices, dev,
                        datadir, str(part)))

        # we're only going to add sda and sdc into the ring
        local_devs = ('sda', 'sdc')
        stub_ring_devs = [{
            'id': i,
            'device': dev,
            'replication_ip': self.ip,
            'replication_port': self.port,
        } for i, dev in enumerate(local_devs)]
        self.reconstructor.bind_ip = '0.0.0.0'  # use whataremyips
        with mock.patch('swift.obj.reconstructor.whataremyips',
                        return_value=[self.ip]), \
                mock.patch.object(self.policy.object_ring, '_devs',
                                  new=stub_ring_devs):
            part_infos = list(self.reconstructor.collect_parts())
        found_parts = sorted(int(p['partition']) for p in part_infos)
        expected_parts = sorted(itertools.chain(
            *(device_parts[d] for d in local_devs)))
        self.assertEqual(found_parts, expected_parts)
        for part_info in part_infos:
            self.assertEqual(part_info['policy'], self.policy)
            self.assertIn(part_info['local_dev'], stub_ring_devs)
            dev = part_info['local_dev']
            self.assertEqual(part_info['part_path'],
                             os.path.join(self.devices,
                                          dev['device'],
                                          diskfile.get_data_dir(self.policy),
                                          str(part_info['partition'])))

    def test_collect_parts_mount_check(self):
        # each device has one part in it
        local_devs = ('sda', 'sdb')
        for i, dev in enumerate(local_devs):
            datadir = diskfile.get_data_dir(self.policy)
            utils.mkdirs(os.path.join(
                self.devices, dev, datadir, str(i)))
        stub_ring_devs = [{
            'id': i,
            'device': dev,
            'replication_ip': self.ip,
            'replication_port': self.port
        } for i, dev in enumerate(local_devs)]
        with mock.patch('swift.obj.reconstructor.whataremyips',
                        return_value=[self.ip]), \
                mock.patch.object(self.policy.object_ring, '_devs',
                                  new=stub_ring_devs):
            part_infos = list(self.reconstructor.collect_parts())
        self.assertEqual(2, len(part_infos))  # sanity
        self.assertEqual(set(int(p['partition']) for p in part_infos),
                         set([0, 1]))

        paths = []

        def fake_check_drive(devices, device, mount_check):
            path = os.path.join(devices, device)
            if (not mount_check) and os.path.isdir(path):
                # while mount_check is false, the test still creates the dirs
                paths.append(path)
                return path
            return None

        with mock.patch('swift.obj.reconstructor.whataremyips',
                        return_value=[self.ip]), \
                mock.patch.object(self.policy.object_ring, '_devs',
                                  new=stub_ring_devs), \
                mock.patch('swift.obj.diskfile.check_drive',
                           fake_check_drive):
            part_infos = list(self.reconstructor.collect_parts())
        self.assertEqual(2, len(part_infos))  # sanity, same jobs
        self.assertEqual(set(int(p['partition']) for p in part_infos),
                         set([0, 1]))

        # ... because fake_check_drive returned paths for both dirs
        self.assertEqual(set(paths), set([
            os.path.join(self.devices, dev) for dev in local_devs]))

        # ... now with mount check
        self._configure_reconstructor(mount_check=True)
        self.assertTrue(self.reconstructor.mount_check)
        paths = []
        for policy in POLICIES:
            self.assertTrue(self.reconstructor._df_router[policy].mount_check)
        with mock.patch('swift.obj.reconstructor.whataremyips',
                        return_value=[self.ip]), \
                mock.patch.object(self.policy.object_ring, '_devs',
                                  new=stub_ring_devs), \
                mock.patch('swift.obj.diskfile.check_drive',
                           fake_check_drive):
            part_infos = list(self.reconstructor.collect_parts())
        self.assertEqual([], part_infos)  # sanity, no jobs

        # ... because fake_check_drive returned False for both paths
        self.assertFalse(paths)

        def fake_check_drive(devices, device, mount_check):
            self.assertTrue(mount_check)
            if device == 'sda':
                return os.path.join(devices, device)
            else:
                return False

        with mock.patch('swift.obj.reconstructor.whataremyips',
                        return_value=[self.ip]), \
                mock.patch.object(self.policy.object_ring, '_devs',
                                  new=stub_ring_devs), \
                mock.patch('swift.obj.diskfile.check_drive',
                           fake_check_drive):
            part_infos = list(self.reconstructor.collect_parts())
        self.assertEqual(1, len(part_infos))  # only sda picked up (part 0)
        self.assertEqual(part_infos[0]['partition'], 0)

    def test_collect_parts_cleans_tmp(self):
        local_devs = ('sda', 'sdc')
        stub_ring_devs = [{
            'id': i,
            'device': dev,
            'replication_ip': self.ip,
            'replication_port': self.port
        } for i, dev in enumerate(local_devs)]
        for device in local_devs:
            utils.mkdirs(os.path.join(self.devices, device))
        fake_unlink = mock.MagicMock()
        self._configure_reconstructor(reclaim_age=1000)
        now = time.time()
        with mock.patch('swift.obj.reconstructor.whataremyips',
                        return_value=[self.ip]), \
                mock.patch('swift.obj.reconstructor.time.time',
                           return_value=now), \
                mock.patch.object(self.policy.object_ring, '_devs',
                                  new=stub_ring_devs), \
                mock.patch('swift.obj.reconstructor.unlink_older_than',
                           fake_unlink):
            self.assertEqual([], list(self.reconstructor.collect_parts()))
        # each local device hash unlink_older_than called on it,
        # with now - self.reclaim_age
        tmpdir = diskfile.get_tmp_dir(self.policy)
        expected = now - 1000
        self.assertEqual(fake_unlink.mock_calls, [
            mock.call(os.path.join(self.devices, dev, tmpdir), expected)
            for dev in local_devs])

    def test_collect_parts_creates_datadir(self):
        # create just the device path
        dev_path = os.path.join(self.devices, self.local_dev['device'])
        utils.mkdirs(dev_path)
        with mock.patch('swift.obj.reconstructor.whataremyips',
                        return_value=[self.ip]):
            self.assertEqual([], list(self.reconstructor.collect_parts()))
        datadir_path = os.path.join(dev_path,
                                    diskfile.get_data_dir(self.policy))
        self.assertTrue(os.path.exists(datadir_path))

    def test_collect_parts_creates_datadir_error(self):
        # create just the device path
        datadir_path = os.path.join(self.devices, self.local_dev['device'],
                                    diskfile.get_data_dir(self.policy))
        utils.mkdirs(os.path.dirname(datadir_path))
        with mock.patch('swift.obj.reconstructor.whataremyips',
                        return_value=[self.ip]), \
                mock.patch('swift.obj.reconstructor.mkdirs',
                           side_effect=OSError('kaboom!')):
            self.assertEqual([], list(self.reconstructor.collect_parts()))
        error_lines = self.logger.get_lines_for_level('error')
        self.assertEqual(len(error_lines), 1,
                         'Expected only one error, got %r' % error_lines)
        line = error_lines[0]
        self.assertIn('Unable to create', line)
        self.assertIn(datadir_path, line)

    def test_collect_parts_skips_invalid_paths(self):
        datadir_path = os.path.join(self.devices, self.local_dev['device'],
                                    diskfile.get_data_dir(self.policy))
        utils.mkdirs(os.path.dirname(datadir_path))
        with open(datadir_path, 'w') as f:
            f.write('junk')
        with mock.patch('swift.obj.reconstructor.whataremyips',
                        return_value=[self.ip]):
            self.assertEqual([], list(self.reconstructor.collect_parts()))
        self.assertTrue(os.path.exists(datadir_path))
        error_lines = self.logger.get_lines_for_level('error')
        self.assertEqual(len(error_lines), 1,
                         'Expected only one error, got %r' % error_lines)
        line = error_lines[0]
        self.assertIn('Unable to list partitions', line)
        self.assertIn(datadir_path, line)

    def test_reconstruct_removes_non_partition_files(self):
        # create some junk next to partitions
        datadir_path = os.path.join(self.devices, self.local_dev['device'],
                                    diskfile.get_data_dir(self.policy))
        num_parts = 3
        for part in range(num_parts):
            utils.mkdirs(os.path.join(datadir_path, str(part)))

        # Add some clearly non-partition dentries
        utils.mkdirs(os.path.join(datadir_path, 'not/a/partition'))
        for junk_name in ('junk', '1234'):
            junk_file = os.path.join(datadir_path, junk_name)
            with open(junk_file, 'w') as f:
                f.write('junk')

        with mock.patch('swift.obj.reconstructor.whataremyips',
                        return_value=[self.ip]), \
                mock.patch('swift.obj.reconstructor.'
                           'ObjectReconstructor.process_job'):
            self.reconstructor.reconstruct()

        # all the bad gets cleaned up
        errors = []
        for junk_name in ('junk', '1234', 'not'):
            junk_file = os.path.join(datadir_path, junk_name)
            if os.path.exists(junk_file):
                errors.append('%s still exists!' % junk_file)

        self.assertFalse(errors)

        error_lines = self.logger.get_lines_for_level('warning')
        self.assertIn('Unexpected entity in data dir: %r'
                      % os.path.join(datadir_path, 'not'), error_lines)
        self.assertIn('Unexpected entity in data dir: %r'
                      % os.path.join(datadir_path, 'junk'), error_lines)
        self.assertIn('Unexpected entity %r is not a directory'
                      % os.path.join(datadir_path, '1234'), error_lines)
        self.assertEqual(self.reconstructor.reconstruction_part_count, 6)

    def test_collect_parts_overrides(self):
        # setup multiple devices, with multiple parts
        device_parts = {
            'sda': (374, 843),
            'sdb': (179, 807),
            'sdc': (363, 468, 843),
        }
        datadir = diskfile.get_data_dir(self.policy)
        for dev, parts in device_parts.items():
            for part in parts:
                utils.mkdirs(os.path.join(
                    self.devices, dev,
                    datadir, str(part)))

        # we're only going to add sda and sdc into the ring
        local_devs = ('sda', 'sdc')
        stub_ring_devs = [{
            'id': i,
            'device': dev,
            'replication_ip': self.ip,
            'replication_port': self.port
        } for i, dev in enumerate(local_devs)]

        expected = (
            ({}, [
                ('sda', 374),
                ('sda', 843),
                ('sdc', 363),
                ('sdc', 468),
                ('sdc', 843),
            ]),
            ({'override_devices': ['sda', 'sdc']}, [
                ('sda', 374),
                ('sda', 843),
                ('sdc', 363),
                ('sdc', 468),
                ('sdc', 843),
            ]),
            ({'override_devices': ['sdc']}, [
                ('sdc', 363),
                ('sdc', 468),
                ('sdc', 843),
            ]),
            ({'override_devices': ['sda']}, [
                ('sda', 374),
                ('sda', 843),
            ]),
            ({'override_devices': ['sdx']}, []),
            ({'override_partitions': [374]}, [
                ('sda', 374),
            ]),
            ({'override_partitions': [843]}, [
                ('sda', 843),
                ('sdc', 843),
            ]),
            ({'override_partitions': [843], 'override_devices': ['sda']}, [
                ('sda', 843),
            ]),
        )
        with mock.patch('swift.obj.reconstructor.whataremyips',
                        return_value=[self.ip]), \
            mock.patch.object(self.policy.object_ring, '_devs',
                              new=stub_ring_devs):
            for kwargs, expected_parts in expected:
                part_infos = list(self.reconstructor.collect_parts(**kwargs))
                expected_paths = set(
                    os.path.join(self.devices, dev, datadir, str(part))
                    for dev, part in expected_parts)
                found_paths = set(p['part_path'] for p in part_infos)
                msg = 'expected %r != %r for %r' % (
                    expected_paths, found_paths, kwargs)
                self.assertEqual(expected_paths, found_paths, msg)

    def test_build_jobs_creates_empty_hashes(self):
        part_path = os.path.join(self.devices, self.local_dev['device'],
                                 diskfile.get_data_dir(self.policy), '0')
        utils.mkdirs(part_path)
        part_info = {
            'local_dev': self.local_dev,
            'policy': self.policy,
            'partition': 0,
            'part_path': part_path,
        }
        jobs = self.reconstructor.build_reconstruction_jobs(part_info)
        self.assertEqual(1, len(jobs))
        job = jobs[0]
        self.assertEqual(job['job_type'], object_reconstructor.SYNC)
        self.assertEqual(job['frag_index'], 0)
        self.assertEqual(job['suffixes'], [])
        self.assertEqual(len(job['sync_to']), 3)
        self.assertEqual(job['partition'], 0)
        self.assertEqual(job['path'], part_path)
        self.assertEqual(job['hashes'], {})
        self.assertEqual(job['policy'], self.policy)
        self.assertEqual(job['local_dev'], self.local_dev)
        self.assertEqual(job['device'], self.local_dev['device'])
        hashes_file = os.path.join(part_path,
                                   diskfile.HASH_FILE)
        self.assertTrue(os.path.exists(hashes_file))
        suffixes = self.reconstructor._get_hashes(
            self.local_dev['device'], 0, self.policy, do_listdir=True)
        self.assertEqual(suffixes, {})

    def test_build_jobs_no_hashes(self):
        part_path = os.path.join(self.devices, self.local_dev['device'],
                                 diskfile.get_data_dir(self.policy), '0')
        part_info = {
            'local_dev': self.local_dev,
            'policy': self.policy,
            'partition': 0,
            'part_path': part_path,
        }
        stub_hashes = {}
        with mock.patch('swift.obj.diskfile.ECDiskFileManager._get_hashes',
                        return_value=(None, stub_hashes)):
            jobs = self.reconstructor.build_reconstruction_jobs(part_info)
        self.assertEqual(1, len(jobs))
        job = jobs[0]
        self.assertEqual(job['job_type'], object_reconstructor.SYNC)
        self.assertEqual(job['frag_index'], 0)
        self.assertEqual(job['suffixes'], [])
        self.assertEqual(len(job['sync_to']), 3)
        self.assertEqual(job['partition'], 0)
        self.assertEqual(job['path'], part_path)
        self.assertEqual(job['hashes'], {})
        self.assertEqual(job['policy'], self.policy)
        self.assertEqual(job['local_dev'], self.local_dev)
        self.assertEqual(job['device'], self.local_dev['device'])

    def test_build_jobs_primary(self):
        ring = self.policy.object_ring = self.fabricated_ring
        # find a partition for which we're a primary
        for partition in range(2 ** ring.part_power):
            part_nodes = ring.get_part_nodes(partition)
            try:
                frag_index = [n['id'] for n in part_nodes].index(
                    self.local_dev['id'])
            except ValueError:
                pass
            else:
                break
        else:
            self.fail("the ring doesn't work: %r" % ring._replica2part2dev_id)
        part_path = os.path.join(self.devices, self.local_dev['device'],
                                 diskfile.get_data_dir(self.policy),
                                 str(partition))
        part_info = {
            'local_dev': self.local_dev,
            'policy': self.policy,
            'partition': partition,
            'part_path': part_path,
        }
        stub_hashes = {
            '123': {frag_index: 'hash', None: 'hash'},
            'abc': {frag_index: 'hash', None: 'hash'},
        }
        with mock.patch('swift.obj.diskfile.ECDiskFileManager._get_hashes',
                        return_value=(None, stub_hashes)):
            jobs = self.reconstructor.build_reconstruction_jobs(part_info)
        self.assertEqual(1, len(jobs))
        job = jobs[0]
        self.assertEqual(job['job_type'], object_reconstructor.SYNC)
        self.assertEqual(job['frag_index'], frag_index)
        self.assertEqual(job['suffixes'], list(stub_hashes.keys()))
        self.assertEqual(set([n['index'] for n in job['sync_to']]),
                         set([(frag_index + 1) % ring.replicas,
                              (frag_index - 1) % ring.replicas,
                              (frag_index + int(0.5 * ring.replicas)),
                              ]))
        self.assertEqual(job['partition'], partition)
        self.assertEqual(job['path'], part_path)
        self.assertEqual(job['hashes'], stub_hashes)
        self.assertEqual(job['policy'], self.policy)
        self.assertEqual(job['local_dev'], self.local_dev)
        self.assertEqual(job['device'], self.local_dev['device'])

    def test_build_jobs_handoff(self):
        ring = self.policy.object_ring = self.fabricated_ring
        # find a partition for which we're a handoff
        for partition in range(2 ** ring.part_power):
            part_nodes = ring.get_part_nodes(partition)
            if self.local_dev['id'] not in [n['id'] for n in part_nodes]:
                break
        else:
            self.fail("the ring doesn't work: %r" % ring._replica2part2dev_id)
        part_path = os.path.join(self.devices, self.local_dev['device'],
                                 diskfile.get_data_dir(self.policy),
                                 str(partition))
        part_info = {
            'local_dev': self.local_dev,
            'policy': self.policy,
            'partition': partition,
            'part_path': part_path,
        }
        # since this part doesn't belong on us it doesn't matter what
        # frag_index we have
        frag_index = random.randint(0, self.policy.ec_n_unique_fragments - 1)
        stub_hashes = {
            '123': {frag_index: 'hash', None: 'hash'},
            'abc': {None: 'hash'},
        }
        with mock.patch('swift.obj.diskfile.ECDiskFileManager._get_hashes',
                        return_value=(None, stub_hashes)):
            jobs = self.reconstructor.build_reconstruction_jobs(part_info)
        self.assertEqual(1, len(jobs), 'Expected only one job, got %r' % jobs)
        job = jobs[0]
        self.assertEqual(job['job_type'], object_reconstructor.REVERT)
        self.assertEqual(job['frag_index'], frag_index)
        self.assertEqual(sorted(job['suffixes']), sorted(stub_hashes.keys()))
        self.assertEqual(
            self.policy.ec_duplication_factor, len(job['sync_to']))
        # the sync_to node should be different each other
        node_ids = set([node['id'] for node in job['sync_to']])
        self.assertEqual(len(node_ids),
                         self.policy.ec_duplication_factor)
        # but all the nodes have same backend index to sync
        node_indexes = set(
            self.policy.get_backend_index(node['index'])
            for node in job['sync_to'])
        self.assertEqual(1, len(node_indexes))
        self.assertEqual(job['sync_to'][0]['index'], frag_index)
        self.assertEqual(job['path'], part_path)
        self.assertEqual(job['partition'], partition)
        self.assertEqual(sorted(job['hashes']), sorted(stub_hashes))
        self.assertEqual(job['local_dev'], self.local_dev)

    def test_build_jobs_mixed(self):
        ring = self.policy.object_ring = self.fabricated_ring
        # find a partition for which we're a primary
        for partition in range(2 ** ring.part_power):
            part_nodes = ring.get_part_nodes(partition)
            try:
                node_index = [n['id'] for n in part_nodes].index(
                    self.local_dev['id'])
            except ValueError:
                pass
            else:
                break
        else:
            self.fail("the ring doesn't work: %r" % ring._replica2part2dev_id)
        part_path = os.path.join(self.devices, self.local_dev['device'],
                                 diskfile.get_data_dir(self.policy),
                                 str(partition))
        part_info = {
            'local_dev': self.local_dev,
            'policy': self.policy,
            'partition': partition,
            'part_path': part_path,
        }
        frag_index = self.policy.get_backend_index(node_index)
        other_frag_index = random.choice(
            [f for f in range(self.policy.ec_n_unique_fragments)
             if f != node_index])
        stub_hashes = {
            '123': {frag_index: 'hash', None: 'hash'},
            '456': {other_frag_index: 'hash', None: 'hash'},
            'abc': {None: 'hash'},
        }
        with mock.patch('swift.obj.diskfile.ECDiskFileManager._get_hashes',
                        return_value=(None, stub_hashes)):
            jobs = self.reconstructor.build_reconstruction_jobs(part_info)
        self.assertEqual(2, len(jobs))
        sync_jobs, revert_jobs = [], []
        for job in jobs:
            self.assertEqual(job['partition'], partition)
            self.assertEqual(job['path'], part_path)
            self.assertEqual(sorted(job['hashes']), sorted(stub_hashes))
            self.assertEqual(job['policy'], self.policy)
            self.assertEqual(job['local_dev'], self.local_dev)
            self.assertEqual(job['device'], self.local_dev['device'])
            {
                object_reconstructor.SYNC: sync_jobs,
                object_reconstructor.REVERT: revert_jobs,
            }[job['job_type']].append(job)
        self.assertEqual(1, len(sync_jobs))
        job = sync_jobs[0]
        self.assertEqual(job['frag_index'], frag_index)
        self.assertEqual(sorted(job['suffixes']), sorted(['123', 'abc']))
        self.assertEqual(len(job['sync_to']), 3)
        self.assertEqual(set([n['index'] for n in job['sync_to']]),
                         set([(frag_index + 1) % ring.replicas,
                              (frag_index - 1) % ring.replicas,
                              (frag_index + int(0.5 * ring.replicas)),
                              ]))
        self.assertEqual(1, len(revert_jobs))
        job = revert_jobs[0]
        self.assertEqual(job['frag_index'], other_frag_index)
        self.assertEqual(job['suffixes'], ['456'])
        self.assertEqual(len(job['sync_to']),
                         self.policy.ec_duplication_factor)
        self.assertEqual(job['sync_to'][0]['index'], other_frag_index)

    def test_build_jobs_revert_only_tombstones(self):
        ring = self.policy.object_ring = self.fabricated_ring
        # find a partition for which we're a handoff
        for partition in range(2 ** ring.part_power):
            part_nodes = ring.get_part_nodes(partition)
            if self.local_dev['id'] not in [n['id'] for n in part_nodes]:
                break
        else:
            self.fail("the ring doesn't work: %r" % ring._replica2part2dev_id)
        part_path = os.path.join(self.devices, self.local_dev['device'],
                                 diskfile.get_data_dir(self.policy),
                                 str(partition))
        part_info = {
            'local_dev': self.local_dev,
            'policy': self.policy,
            'partition': partition,
            'part_path': part_path,
        }
        # we have no fragment index to hint the jobs where they belong
        stub_hashes = {
            '123': {None: 'hash'},
            'abc': {None: 'hash'},
        }
        with mock.patch('swift.obj.diskfile.ECDiskFileManager._get_hashes',
                        return_value=(None, stub_hashes)):
            jobs = self.reconstructor.build_reconstruction_jobs(part_info)
        self.assertEqual(len(jobs), 1, 'Expected only one job, got %r' % jobs)
        job = jobs[0]
        expected = {
            'job_type': object_reconstructor.REVERT,
            'frag_index': None,
            'suffixes': list(stub_hashes.keys()),
            'partition': partition,
            'path': part_path,
            'hashes': stub_hashes,
            'policy': self.policy,
            'local_dev': self.local_dev,
            'device': self.local_dev['device'],
        }
        self.assertEqual(ring.replica_count, len(part_nodes))
        expected_samples = (
            (self.policy.ec_n_unique_fragments *
             self.policy.ec_duplication_factor) -
            self.policy.ec_ndata + 1)
        self.assertEqual(len(job['sync_to']), expected_samples)
        for k, v in expected.items():
            msg = 'expected %s != %s for %s' % (
                v, job[k], k)
            self.assertEqual(v, job[k], msg)

    def test_get_suffixes_to_sync(self):
        part_path = os.path.join(self.devices, self.local_dev['device'],
                                 diskfile.get_data_dir(self.policy), '1')
        utils.mkdirs(part_path)
        part_info = {
            'local_dev': self.local_dev,
            'policy': self.policy,
            'partition': 1,
            'part_path': part_path,
        }
        jobs = self.reconstructor.build_reconstruction_jobs(part_info)
        self.assertEqual(1, len(jobs))
        job = jobs[0]
        node = job['sync_to'][0]
        # process_job used to try and modify the instance base headers
        self.reconstructor.headers['X-Backend-Storage-Policy-Index'] = \
            int(POLICIES[1])
        # ... which doesn't work out under concurrency with multiple policies
        self.assertNotEqual(
            self.reconstructor.headers['X-Backend-Storage-Policy-Index'],
            int(job['policy']))
        with mocked_http_conn(200, body=pickle.dumps({})) as request_log:
            suffixes, new_node = self.reconstructor._get_suffixes_to_sync(
                job, node)
        self.assertEqual([int(job['policy'])], [
            r['headers']['X-Backend-Storage-Policy-Index']
            for r in request_log.requests])
        self.assertEqual(suffixes, [])
        self.assertEqual(new_node, node)

    def test_get_suffixes_in_sync(self):
        part_path = os.path.join(self.devices, self.local_dev['device'],
                                 diskfile.get_data_dir(self.policy), '1')
        utils.mkdirs(part_path)
        part_info = {
            'local_dev': self.local_dev,
            'policy': self.policy,
            'partition': 1,
            'part_path': part_path,
        }
        jobs = self.reconstructor.build_reconstruction_jobs(part_info)
        self.assertEqual(1, len(jobs))
        job = jobs[0]
        node = job['sync_to'][0]
        local_hashes = {
            '123': {job['frag_index']: 'hash', None: 'hash'},
            'abc': {job['frag_index']: 'hash', None: 'hash'},
        }
        self.assertEqual(node['index'], self.policy.object_ring.replicas - 1)
        remote_index = self.policy.get_backend_index(node['index'])
        remote_hashes = {
            '123': {remote_index: 'hash', None: 'hash'},
            'abc': {remote_index: 'hash', None: 'hash'},
        }
        remote_response = pickle.dumps(remote_hashes)
        with mock.patch('swift.obj.diskfile.ECDiskFileManager._get_hashes',
                        return_value=(None, local_hashes)), \
                mocked_http_conn(200, body=remote_response) as request_log:
            suffixes, new_node = self.reconstructor._get_suffixes_to_sync(
                job, node)
        self.assertEqual([node['replication_ip']],
                         [r['ip'] for r in request_log.requests])
        self.assertEqual(suffixes, [])
        self.assertEqual(new_node, node)

    def test_get_suffix_delta(self):
        # different
        local_suff = {'123': {None: 'abc', 0: 'def'}}
        remote_suff = {'456': {None: 'ghi', 0: 'jkl'}}
        local_index = 0
        remote_index = 0
        suffs = self.reconstructor.get_suffix_delta(local_suff,
                                                    local_index,
                                                    remote_suff,
                                                    remote_index)
        self.assertEqual(suffs, ['123'])

        # now the same
        remote_suff = {'123': {None: 'abc', 0: 'def'}}
        suffs = self.reconstructor.get_suffix_delta(local_suff,
                                                    local_index,
                                                    remote_suff,
                                                    remote_index)
        self.assertEqual(suffs, [])

        # now with a mis-matched None key (missing durable)
        remote_suff = {'123': {None: 'ghi', 0: 'def'}}
        suffs = self.reconstructor.get_suffix_delta(local_suff,
                                                    local_index,
                                                    remote_suff,
                                                    remote_index)
        self.assertEqual(suffs, ['123'])

        # now with bogus local index
        local_suff = {'123': {None: 'abc', 99: 'def'}}
        remote_suff = {'456': {None: 'ghi', 0: 'jkl'}}
        suffs = self.reconstructor.get_suffix_delta(local_suff,
                                                    local_index,
                                                    remote_suff,
                                                    remote_index)
        self.assertEqual(suffs, ['123'])

    def test_process_job_primary_in_sync(self):
        partition = 0
        part_nodes = self.policy.object_ring.get_part_nodes(partition)
        local_dev = random.choice(part_nodes)
        frag_index = self.policy.get_backend_index(local_dev['index'])
        sync_to = object_reconstructor._get_partners(
            local_dev['index'], part_nodes)
        # setup left, right and far hashes
        stub_hashes = {
            '123': {frag_index: 'hash', None: 'hash'},
            'abc': {frag_index: 'hash', None: 'hash'},
        }
        left_frag_index = self.policy.get_backend_index(sync_to[0]['index'])
        left_hashes = {
            '123': {left_frag_index: 'hash', None: 'hash'},
            'abc': {left_frag_index: 'hash', None: 'hash'},
        }
        right_frag_index = self.policy.get_backend_index(sync_to[1]['index'])
        right_hashes = {
            '123': {right_frag_index: 'hash', None: 'hash'},
            'abc': {right_frag_index: 'hash', None: 'hash'},
        }
        far_index = self.policy.get_backend_index(sync_to[2]['index'])
        far_hashes = {
            '123': {far_index: 'hash', None: 'hash'},
            'abc': {far_index: 'hash', None: 'hash'},
        }
        partition = 0
        part_path = os.path.join(self.devices, self.local_dev['device'],
                                 diskfile.get_data_dir(self.policy),
                                 str(partition))
        job = {
            'job_type': object_reconstructor.SYNC,
            'frag_index': frag_index,
            'suffixes': stub_hashes.keys(),
            'sync_to': sync_to,
            'partition': partition,
            'path': part_path,
            'hashes': stub_hashes,
            'policy': self.policy,
            'local_dev': self.local_dev,
        }

        responses = [(200, pickle.dumps(hashes)) for hashes in (
            left_hashes, right_hashes, far_hashes)]
        codes, body_iter = zip(*responses)

        ssync_calls = []

        with mock_ssync_sender(ssync_calls), \
                mock.patch('swift.obj.diskfile.ECDiskFileManager._get_hashes',
                           return_value=(None, stub_hashes)), \
                mocked_http_conn(*codes, body_iter=body_iter) as request_log:
            self.reconstructor.process_job(job)

        expected_suffix_calls = [
            (sync_to[0]['ip'], '/%s/0' % sync_to[0]['device']),
            (sync_to[1]['ip'], '/%s/0' % sync_to[1]['device']),
            (sync_to[2]['ip'], '/%s/0' % sync_to[2]['device']),
        ]
        self.assertEqual(expected_suffix_calls,
                         [(r['ip'], r['path']) for r in request_log.requests])

        self.assertFalse(ssync_calls)

    def test_process_job_primary_not_in_sync(self):
        partition = 0
        part_nodes = self.policy.object_ring.get_part_nodes(partition)
        local_dev = random.choice(part_nodes)
        frag_index = self.policy.get_backend_index(local_dev['index'])
        sync_to = object_reconstructor._get_partners(
            local_dev['index'], part_nodes)
        # setup left and right hashes
        stub_hashes = {
            '123': {frag_index: 'hash', None: 'hash'},
            'abc': {frag_index: 'hash', None: 'hash'},
        }
        left_hashes = {}
        right_hashes = {}
        far_hashes = {}

        partition = 0
        part_path = os.path.join(self.devices, self.local_dev['device'],
                                 diskfile.get_data_dir(self.policy),
                                 str(partition))
        job = {
            'job_type': object_reconstructor.SYNC,
            'frag_index': frag_index,
            'suffixes': stub_hashes.keys(),
            'sync_to': sync_to,
            'partition': partition,
            'path': part_path,
            'hashes': stub_hashes,
            'policy': self.policy,
            'local_dev': self.local_dev,
        }

        responses = []
        for hashes in (left_hashes, right_hashes, far_hashes):
            responses.append((200, pickle.dumps(hashes)))
        codes, body_iter = zip(*responses)

        ssync_calls = []
        with mock_ssync_sender(ssync_calls), \
                mock.patch('swift.obj.diskfile.ECDiskFileManager._get_hashes',
                           return_value=(None, stub_hashes)), \
                mocked_http_conn(*codes, body_iter=body_iter) as request_log:
            self.reconstructor.process_job(job)

        expected_suffix_calls = [
            (sync_to[0]['ip'], '/%s/0' % sync_to[0]['device']),
            (sync_to[1]['ip'], '/%s/0' % sync_to[1]['device']),
            (sync_to[2]['ip'], '/%s/0' % sync_to[2]['device']),
        ]
        self.assertEqual(expected_suffix_calls,
                         [(r['ip'], r['path']) for r in request_log.requests])

        expected_ssync_calls = sorted([
            (sync_to[0]['ip'], 0, set(['123', 'abc'])),
            (sync_to[1]['ip'], 0, set(['123', 'abc'])),
            (sync_to[2]['ip'], 0, set(['123', 'abc'])),
        ])
        self.assertEqual(expected_ssync_calls, sorted((
            c['node']['ip'],
            c['job']['partition'],
            set(c['suffixes']),
        ) for c in ssync_calls))

    def test_sync_duplicates_to_remote_region(self):
        partition = 0
        part_nodes = self.policy.object_ring.get_part_nodes(partition)
        # in the non-duplicate case we just pick a random node
        local_dev = random.choice(part_nodes[-14:])
        frag_index = self.policy.get_backend_index(local_dev['index'])
        sync_to = object_reconstructor._get_partners(
            local_dev['index'], part_nodes)
        part_path = os.path.join(self.devices, self.local_dev['device'],
                                 diskfile.get_data_dir(self.policy),
                                 str(partition))
        # setup left and right hashes
        stub_hashes = {
            '123': {frag_index: 'hash', None: 'hash'},
            'abc': {frag_index: 'hash', None: 'hash'},
        }
        # left hand side is in sync
        left_frag_index = self.policy.get_backend_index(sync_to[0]['index'])
        left_hashes = {
            '123': {left_frag_index: 'hash', None: 'hash'},
            'abc': {left_frag_index: 'hash', None: 'hash'},
        }
        # right hand side needs sync
        right_frag_index = self.policy.get_backend_index(sync_to[1]['index'])
        right_hashes = {
            '123': {right_frag_index: 'hash', None: 'hash'},
            'abc': {right_frag_index: 'hashX', None: 'hash'},
        }
        far_index = self.policy.get_backend_index(sync_to[2]['index'])
        far_hashes = {
            '123': {far_index: 'hash', None: 'hash'},
            'abc': {far_index: 'hash', None: 'hash'},
        }

        job = {
            'job_type': object_reconstructor.SYNC,
            'frag_index': frag_index,
            'suffixes': stub_hashes.keys(),
            'sync_to': sync_to,
            'partition': partition,
            'path': part_path,
            'hashes': stub_hashes,
            'policy': self.policy,
            'local_dev': self.local_dev,
            'device': self.local_dev['device'],
        }

        responses = [
            (200, pickle.dumps(left_hashes)),
            (200, pickle.dumps(right_hashes)),
            (200, pickle.dumps(far_hashes)),
        ]
        codes, body_iter = zip(*responses)

        # we're going to dip our mocks into the ssync layer a bit
        ssync_resp = mock.MagicMock()
        ssync_resp.status = 200
        ssync_resp.readline.side_effect = [
            b':MISSING_CHECK: START',
            b':MISSING_CHECK: END',
            b':UPDATES: START',
            b':UPDATES: END',
        ]

        ssync_headers = []

        def capture_headers(name, value):
            ssync_headers.append((name, value))

        ssync_conn = mock.MagicMock()
        ssync_conn.getresponse.return_value = ssync_resp
        ssync_conn.putheader = capture_headers

        with mock.patch('swift.obj.ssync_sender.SsyncBufferedHTTPConnection',
                        return_value=ssync_conn), \
                mock.patch('swift.obj.diskfile.ECDiskFileManager._get_hashes',
                           return_value=(None, stub_hashes)), \
                mock.patch('swift.obj.diskfile.ECDiskFileManager.yield_hashes',
                           return_value=iter([])), \
                mocked_http_conn(*codes, body_iter=body_iter):
            self.reconstructor.process_job(job)

        # ... to make sure it sets up our headers correctly
        self.assertEqual(ssync_headers, [
            ('Transfer-Encoding', 'chunked'),
            ('X-Backend-Storage-Policy-Index', 0),
            ('X-Backend-Ssync-Frag-Index', right_frag_index),
            # we include this for backwards compat
            ('X-Backend-Ssync-Node-Index', right_frag_index),
        ])

    def test_process_job_sync_missing_durable(self):
        partition = 0
        part_nodes = self.policy.object_ring.get_part_nodes(partition)
        local_dev = random.choice(part_nodes)
        frag_index = self.policy.get_backend_index(local_dev['index'])
        sync_to = object_reconstructor._get_partners(
            local_dev['index'], part_nodes)
        # setup left and right hashes
        stub_hashes = {
            '123': {frag_index: 'hash', None: 'hash'},
            'abc': {frag_index: 'hash', None: 'hash'},
        }
        # left hand side is in sync
        left_frag_index = self.policy.get_backend_index(sync_to[0]['index'])
        left_hashes = {
            '123': {left_frag_index: 'hash', None: 'hash'},
            'abc': {left_frag_index: 'hash', None: 'hash'},
        }
        # right hand side has fragment, but no durable (None key is whack)
        right_frag_index = self.policy.get_backend_index(sync_to[1]['index'])
        right_hashes = {
            '123': {right_frag_index: 'hash', None: 'hash'},
            'abc': {right_frag_index: 'hash',
                    None: 'different-because-durable'},
        }
        # far side is in sync
        far_index = self.policy.get_backend_index(sync_to[2]['index'])
        far_hashes = {
            '123': {far_index: 'hash', None: 'hash'},
            'abc': {far_index: 'hash', None: 'hash'},
        }

        part_path = os.path.join(self.devices, self.local_dev['device'],
                                 diskfile.get_data_dir(self.policy),
                                 str(partition))
        job = {
            'job_type': object_reconstructor.SYNC,
            'frag_index': frag_index,
            'suffixes': stub_hashes.keys(),
            'sync_to': sync_to,
            'partition': partition,
            'path': part_path,
            'hashes': stub_hashes,
            'policy': self.policy,
            'local_dev': self.local_dev,
        }

        responses = [(200, pickle.dumps(hashes)) for hashes in (
            left_hashes, right_hashes, far_hashes)]
        codes, body_iter = zip(*responses)

        ssync_calls = []
        with mock_ssync_sender(ssync_calls), \
                mock.patch('swift.obj.diskfile.ECDiskFileManager._get_hashes',
                           return_value=(None, stub_hashes)), \
                mocked_http_conn(*codes, body_iter=body_iter) as request_log:
            self.reconstructor.process_job(job)

        expected_suffix_calls = set([
            (sync_to[0]['ip'], '/%s/0' % sync_to[0]['device']),
            (sync_to[1]['ip'], '/%s/0' % sync_to[1]['device']),
            (sync_to[2]['ip'], '/%s/0' % sync_to[2]['device']),
        ])
        self.assertEqual(expected_suffix_calls,
                         set((r['ip'], r['path'])
                             for r in request_log.requests))

        expected_ssync_calls = sorted([
            (sync_to[1]['ip'], 0, ['abc']),
        ])
        self.assertEqual(expected_ssync_calls, sorted((
            c['node']['ip'],
            c['job']['partition'],
            c['suffixes'],
        ) for c in ssync_calls))

    def test_process_job_primary_some_in_sync(self):
        partition = 0
        part_nodes = self.policy.object_ring.get_part_nodes(partition)
        local_dev = random.choice(part_nodes)
        frag_index = self.policy.get_backend_index(local_dev['index'])
        sync_to = object_reconstructor._get_partners(
            local_dev['index'], part_nodes)
        # setup left and right hashes
        stub_hashes = {
            '123': {frag_index: 'hash', None: 'hash'},
            'abc': {frag_index: 'hash', None: 'hash'},
        }
        left_frag_index = self.policy.get_backend_index(sync_to[0]['index'])
        left_hashes = {
            '123': {left_frag_index: 'hashX', None: 'hash'},
            'abc': {left_frag_index: 'hash', None: 'hash'},
        }
        right_frag_index = self.policy.get_backend_index(sync_to[1]['index'])
        right_hashes = {
            '123': {right_frag_index: 'hash', None: 'hash'},
        }
        far_index = self.policy.get_backend_index(sync_to[2]['index'])
        far_hashes = {
            'abc': {far_index: 'hashX', None: 'hash'},
        }
        part_path = os.path.join(self.devices, self.local_dev['device'],
                                 diskfile.get_data_dir(self.policy),
                                 str(partition))
        job = {
            'job_type': object_reconstructor.SYNC,
            'frag_index': frag_index,
            'suffixes': stub_hashes.keys(),
            'sync_to': sync_to,
            'partition': partition,
            'path': part_path,
            'hashes': stub_hashes,
            'policy': self.policy,
            'local_dev': self.local_dev,
        }

        responses = []
        for hashes in (left_hashes, right_hashes, far_hashes):
            responses.append((200, pickle.dumps(hashes)))
        codes, body_iter = zip(*responses)

        ssync_calls = []

        with mock_ssync_sender(ssync_calls), \
                mock.patch('swift.obj.diskfile.ECDiskFileManager._get_hashes',
                           return_value=(None, stub_hashes)), \
                mocked_http_conn(*codes, body_iter=body_iter) as request_log:
            self.reconstructor.process_job(job)

        expected_suffix_calls = set([
            (sync_to[0]['ip'], '/%s/0' % sync_to[0]['device']),
            (sync_to[1]['ip'], '/%s/0' % sync_to[1]['device']),
            (sync_to[2]['ip'], '/%s/0' % sync_to[2]['device']),
        ])
        self.assertEqual(expected_suffix_calls,
                         set((r['ip'], r['path'])
                             for r in request_log.requests))

        self.assertEqual(
            dict(collections.Counter(
                (c['node']['index'], tuple(sorted(c['suffixes'])))
                for c in ssync_calls)),
            {(sync_to[0]['index'], ('123',)): 1,
             (sync_to[1]['index'], ('abc',)): 1,
             (sync_to[2]['index'], ('123', 'abc')): 1,
             })

    def test_process_job_primary_down(self):
        partition = 0
        frag_index = random.randint(
            0, self.policy.ec_n_unique_fragments - 1)
        stub_hashes = {
            '123': {frag_index: 'hash', None: 'hash'},
            'abc': {frag_index: 'hash', None: 'hash'},
        }

        part_nodes = self.policy.object_ring.get_part_nodes(partition)
        sync_to = part_nodes[:3]

        part_path = os.path.join(self.devices, self.local_dev['device'],
                                 diskfile.get_data_dir(self.policy),
                                 str(partition))
        job = {
            'job_type': object_reconstructor.SYNC,
            'frag_index': frag_index,
            'suffixes': stub_hashes.keys(),
            'sync_to': sync_to,
            'partition': partition,
            'path': part_path,
            'hashes': stub_hashes,
            'policy': self.policy,
            'device': self.local_dev['device'],
            'local_dev': self.local_dev,
        }

        non_local = {'called': 0}

        def ssync_response_callback(*args):
            # in this test, ssync fails on the first (primary sync_to) node
            if non_local['called'] >= 1:
                return True, {}
            non_local['called'] += 1
            return False, {}

        expected_suffix_calls = set()
        for node in part_nodes[:3]:
            expected_suffix_calls.update([
                (node['replication_ip'], '/%s/0' % node['device']),
            ])

        ssync_calls = []
        with mock_ssync_sender(ssync_calls,
                               response_callback=ssync_response_callback), \
                mock.patch('swift.obj.diskfile.ECDiskFileManager._get_hashes',
                           return_value=(None, stub_hashes)), \
                mocked_http_conn(*[200] * len(expected_suffix_calls),
                                 body=pickle.dumps({})) as request_log:
            self.reconstructor.process_job(job)

        found_suffix_calls = set((r['ip'], r['path'])
                                 for r in request_log.requests)
        self.assertEqual(expected_suffix_calls, found_suffix_calls)

        expected_ssync_calls = sorted([
            ('10.0.0.0', 0, set(['123', 'abc'])),
            ('10.0.0.1', 0, set(['123', 'abc'])),
            ('10.0.0.2', 0, set(['123', 'abc'])),
        ])
        found_ssync_calls = sorted((
            c['node']['ip'],
            c['job']['partition'],
            set(c['suffixes']),
        ) for c in ssync_calls)
        self.assertEqual(expected_ssync_calls, found_ssync_calls)

    def test_process_job_suffix_call_errors(self):
        partition = 0
        frag_index = random.randint(
            0, self.policy.ec_n_unique_fragments - 1)
        stub_hashes = {
            '123': {frag_index: 'hash', None: 'hash'},
            'abc': {frag_index: 'hash', None: 'hash'},
        }

        part_nodes = self.policy.object_ring.get_part_nodes(partition)
        sync_to = part_nodes[:2]

        part_path = os.path.join(self.devices, self.local_dev['device'],
                                 diskfile.get_data_dir(self.policy),
                                 str(partition))
        job = {
            'job_type': object_reconstructor.SYNC,
            'frag_index': frag_index,
            'suffixes': stub_hashes.keys(),
            'sync_to': sync_to,
            'partition': partition,
            'path': part_path,
            'hashes': stub_hashes,
            'policy': self.policy,
            'device': self.local_dev['device'],
            'local_dev': self.local_dev,
        }

        expected_suffix_calls = set((
            node['replication_ip'], '/%s/0' % node['device']
        ) for node in sync_to)

        possible_errors = [404, Timeout(), Exception('kaboom!')]
        codes = [random.choice(possible_errors)
                 for r in expected_suffix_calls]

        ssync_calls = []
        with mock_ssync_sender(ssync_calls), \
                mock.patch('swift.obj.diskfile.ECDiskFileManager._get_hashes',
                           return_value=(None, stub_hashes)), \
                mocked_http_conn(*codes) as request_log:
            self.reconstructor.process_job(job)

        found_suffix_calls = set((r['ip'], r['path'])
                                 for r in request_log.requests)
        self.assertEqual(expected_suffix_calls, found_suffix_calls)

        self.assertFalse(ssync_calls)

    def test_process_job_sync_partner_unmounted(self):
        partition = 0
        part_nodes = self.policy.object_ring.get_part_nodes(partition)
        frag_index = [n['id'] for n in part_nodes].index(self.local_dev['id'])
        sync_to = object_reconstructor._get_partners(frag_index, part_nodes)
        self.assertEqual(3, len(sync_to))
        stub_hashes = {
            '123': {frag_index: 'hash', None: 'hash'},
            'abc': {frag_index: 'hash', None: 'hash'},
        }
        # left partner out of sync
        left_frag_index = self.policy.get_backend_index(sync_to[0]['index'])
        left_hashes = {
            '123': {left_frag_index: 'not-in-sync-hash', None: 'hash'},
            'abc': {left_frag_index: 'hash', None: 'hash'},
        }
        # we don't need right partner hashes
        # far partner in sync
        far_index = self.policy.get_backend_index(sync_to[2]['index'])
        far_hashes = {
            '123': {far_index: 'hash', None: 'hash'},
            'abc': {far_index: 'hash', None: 'hash'},
        }
        part_path = os.path.join(self.devices, self.local_dev['device'],
                                 diskfile.get_data_dir(self.policy),
                                 str(partition))
        job = {
            'job_type': object_reconstructor.SYNC,
            'frag_index': frag_index,
            'suffixes': stub_hashes.keys(),
            'sync_to': sync_to,
            'partition': partition,
            'path': part_path,
            'hashes': stub_hashes,
            'policy': self.policy,
            'device': self.local_dev['device'],
            'local_dev': self.local_dev,
        }

        responses = [
            (200, pickle.dumps(left_hashes)),  # hashes left partner
            (507, ''),  # unmounted right partner
            (200, pickle.dumps({})),  # hashes handoff
            (200, pickle.dumps(far_hashes)),  # hashes far partner
        ]
        codes, body_iter = zip(*responses)

        ssync_calls = []
        with mock_ssync_sender(ssync_calls), \
                mock.patch('swift.obj.diskfile.ECDiskFileManager._get_hashes',
                           return_value=(None, stub_hashes)), \
                mocked_http_conn(*codes, body_iter=body_iter) as request_log:
            self.reconstructor.process_job(job)
        # increment frag_index since we're rebuilding to our right
        frag_index = (frag_index + 1) % self.policy.ec_n_unique_fragments
        handoffs = self.policy.object_ring.get_more_nodes(partition)
        for i, handoff in enumerate(handoffs):
            if i == frag_index:
                break
        else:
            self.fail('Unable to find handoff?!')
        expected = collections.Counter([
            (200, sync_to[0]['ip']),
            (507, sync_to[1]['ip']),
            (200, handoff['ip']),
            (200, sync_to[2]['ip']),
        ])
        self.assertEqual(expected, collections.Counter(
            [(c, r['ip']) for c, r in zip(codes, request_log.requests)]))
        expected = collections.Counter([
            sync_to[0]['ip'],
            handoff['ip'],
        ])
        self.assertEqual(expected, collections.Counter(
            [c['node']['ip'] for c in ssync_calls]))

    def test_process_job_handoff(self):
        frag_index = random.randint(
            0, self.policy.ec_n_unique_fragments - 1)
        sync_to = [random.choice([n for n in self.policy.object_ring.devs
                                  if n != self.local_dev])]
        sync_to[0]['index'] = frag_index

        stub_hashes = {
            '123': {frag_index: 'hash', None: 'hash'},
            'abc': {frag_index: 'hash', None: 'hash'},
        }
        partition = 0
        part_path = os.path.join(self.devices, self.local_dev['device'],
                                 diskfile.get_data_dir(self.policy),
                                 str(partition))
        os.makedirs(part_path)
        job = {
            'job_type': object_reconstructor.REVERT,
            'frag_index': frag_index,
            'suffixes': stub_hashes.keys(),
            'sync_to': sync_to,
            'partition': partition,
            'path': part_path,
            'hashes': stub_hashes,
            'policy': self.policy,
            'local_dev': self.local_dev,
            'device': self.local_dev['device'],
        }

        ssync_calls = []
        with mock_ssync_sender(ssync_calls), \
                mock.patch('swift.obj.diskfile.ECDiskFileManager._get_hashes',
                           return_value=(None, stub_hashes)):
            self.reconstructor.process_job(job)

        self.assertEqual(
            sorted(collections.Counter(
                (c['node']['ip'], c['node']['port'], c['node']['device'],
                 tuple(sorted(c['suffixes'])))
                for c in ssync_calls).items()),
            [((sync_to[0]['ip'], sync_to[0]['port'], sync_to[0]['device'],
               ('123', 'abc')), 1)])

    def test_process_job_will_not_revert_to_handoff(self):
        frag_index = random.randint(
            0, self.policy.ec_n_unique_fragments - 1)
        sync_to = [random.choice([n for n in self.policy.object_ring.devs
                                  if n != self.local_dev])]
        sync_to[0]['index'] = frag_index
        partition = 0

        stub_hashes = {
            '123': {frag_index: 'hash', None: 'hash'},
            'abc': {frag_index: 'hash', None: 'hash'},
        }
        part_path = os.path.join(self.devices, self.local_dev['device'],
                                 diskfile.get_data_dir(self.policy),
                                 str(partition))
        os.makedirs(part_path)
        job = {
            'job_type': object_reconstructor.REVERT,
            'frag_index': frag_index,
            'suffixes': stub_hashes.keys(),
            'sync_to': sync_to,
            'partition': partition,
            'path': part_path,
            'hashes': stub_hashes,
            'policy': self.policy,
            'local_dev': self.local_dev,
            'device': self.local_dev['device'],
        }

        non_local = {'called': 0}

        def ssync_response_callback(*args):
            # in this test, ssync fails on the first (primary sync_to) node
            if non_local['called'] >= 1:
                return True, {}
            non_local['called'] += 1
            return False, {}

        ssync_calls = []
        with mock_ssync_sender(ssync_calls,
                               response_callback=ssync_response_callback), \
                mocked_http_conn() as request_log:
            self.reconstructor.process_job(job)

        # failed ssync job should not generate a suffix rehash
        self.assertEqual([], request_log.requests)

        self.assertEqual(
            sorted(collections.Counter(
                (c['node']['ip'], c['node']['port'], c['node']['device'],
                 tuple(sorted(c['suffixes'])))
                for c in ssync_calls).items()),
            [((sync_to[0]['ip'], sync_to[0]['port'], sync_to[0]['device'],
               ('123', 'abc')), 1)])

    def test_process_job_revert_is_handoff_fails(self):
        frag_index = random.randint(
            0, self.policy.ec_n_unique_fragments - 1)
        sync_to = [random.choice([n for n in self.policy.object_ring.devs
                                  if n != self.local_dev])]
        sync_to[0]['index'] = frag_index
        partition = 0
        handoff_nodes = list(self.policy.object_ring.get_more_nodes(partition))

        stub_hashes = {
            '123': {frag_index: 'hash', None: 'hash'},
            'abc': {frag_index: 'hash', None: 'hash'},
        }
        part_path = os.path.join(self.devices, self.local_dev['device'],
                                 diskfile.get_data_dir(self.policy),
                                 str(partition))
        os.makedirs(part_path)
        job = {
            'job_type': object_reconstructor.REVERT,
            'frag_index': frag_index,
            'suffixes': stub_hashes.keys(),
            'sync_to': sync_to,
            'partition': partition,
            'path': part_path,
            'hashes': stub_hashes,
            'policy': self.policy,
            'local_dev': handoff_nodes[-1],
            'device': self.local_dev['device'],
        }

        def ssync_response_callback(*args):
            # in this test ssync always fails, until we encounter ourselves in
            # the list of possible handoff's to sync to, so handoffs_remaining
            # should increment
            return False, {}

        ssync_calls = []
        with mock_ssync_sender(ssync_calls,
                               response_callback=ssync_response_callback), \
                mocked_http_conn() as request_log:
            self.reconstructor.process_job(job)

        # failed ssync job should not generate a suffix rehash
        self.assertEqual([], request_log.requests)

        # this is ssync call to primary (which fails) and nothing else!
        self.assertEqual(
            sorted(collections.Counter(
                (c['node']['ip'], c['node']['port'], c['node']['device'],
                 tuple(sorted(c['suffixes'])))
                for c in ssync_calls).items()),
            [((sync_to[0]['ip'], sync_to[0]['port'], sync_to[0]['device'],
               ('123', 'abc')), 1)])
        self.assertEqual(self.reconstructor.handoffs_remaining, 1)

    def test_process_job_revert_cleanup(self):
        frag_index = random.randint(
            0, self.policy.ec_n_unique_fragments - 1)
        sync_to = [random.choice([n for n in self.policy.object_ring.devs
                                  if n != self.local_dev])]
        sync_to[0]['index'] = frag_index
        partition = 0

        part_path = os.path.join(self.devices, self.local_dev['device'],
                                 diskfile.get_data_dir(self.policy),
                                 str(partition))
        os.makedirs(part_path)
        df_mgr = self.reconstructor._df_router[self.policy]
        df = df_mgr.get_diskfile(self.local_dev['device'], partition, 'a',
                                 'c', 'data-obj', policy=self.policy)
        ts = self.ts()
        with df.create() as writer:
            test_data = b'test data'
            writer.write(test_data)
            metadata = {
                'X-Timestamp': ts.internal,
                'Content-Length': len(test_data),
                'Etag': md5(test_data).hexdigest(),
                'X-Object-Sysmeta-Ec-Frag-Index': frag_index,
            }
            writer.put(metadata)
            writer.commit(ts)

        ohash = os.path.basename(df._datadir)
        suffix = os.path.basename(os.path.dirname(df._datadir))

        job = {
            'job_type': object_reconstructor.REVERT,
            'frag_index': frag_index,
            'suffixes': [suffix],
            'sync_to': sync_to,
            'partition': partition,
            'path': part_path,
            'hashes': {},
            'policy': self.policy,
            'local_dev': self.local_dev,
            'device': self.local_dev['device'],
        }

        def ssync_response_callback(*args):
            # success should not increment handoffs_remaining
            return True, {ohash: {'ts_data': ts}}

        ssync_calls = []
        with mock_ssync_sender(ssync_calls,
                               response_callback=ssync_response_callback):
            self.reconstructor.process_job(job)

        # hashpath has been removed
        self.assertFalse(os.path.exists(df._datadir))

        self.assertEqual(self.reconstructor.handoffs_remaining, 0)

    def test_process_job_revert_cleanup_tombstone(self):
        partition = 0
        sync_to = [random.choice([
            n for n in self.policy.object_ring.get_part_nodes(partition)
            if n['id'] != self.local_dev['id']])]

        part_path = os.path.join(self.devices, self.local_dev['device'],
                                 diskfile.get_data_dir(self.policy),
                                 str(partition))
        os.makedirs(part_path)
        df_mgr = self.reconstructor._df_router[self.policy]
        df = df_mgr.get_diskfile(self.local_dev['device'], partition, 'a',
                                 'c', 'data-obj', policy=self.policy)
        ts = self.ts()
        df.delete(ts)

        ohash = os.path.basename(df._datadir)
        suffix = os.path.basename(os.path.dirname(df._datadir))

        job = {
            'job_type': object_reconstructor.REVERT,
            'frag_index': None,
            'suffixes': [suffix],
            'sync_to': sync_to,
            'partition': partition,
            'path': part_path,
            'hashes': {},
            'policy': self.policy,
            'local_dev': self.local_dev,
            'device': self.local_dev['device'],
        }

        def ssync_response_callback(*args):
            return True, {ohash: {'ts_data': ts}}

        ssync_calls = []
        with mock_ssync_sender(ssync_calls,
                               response_callback=ssync_response_callback):
            self.reconstructor.process_job(job)

        # hashpath is still there, but it's empty
        self.assertEqual([], os.listdir(df._datadir))

    def test_get_local_devices(self):
        local_devs = self.reconstructor.get_local_devices()
        self.assertEqual({'sda'}, local_devs)

    @patch_policies(legacy_only=True)
    def test_get_local_devices_with_no_ec_policy_env(self):
        # even no ec_policy found on the server, it runs just like as
        # no ec device found
        self._configure_reconstructor()
        self.assertEqual([], self.reconstructor.policies)
        local_devs = self.reconstructor.get_local_devices()
        self.assertEqual(set(), local_devs)

    @patch_policies(legacy_only=True)
    def test_reconstruct_with_no_ec_policy_env(self):
        self._configure_reconstructor()
        self.assertEqual([], self.reconstructor.policies)
        collect_parts_results = []
        _orig_collect_parts = self.reconstructor.collect_parts

        def capture_collect_parts(**kwargs):
            part_infos = _orig_collect_parts(**kwargs)
            collect_parts_results.append(part_infos)
            return part_infos

        with mock.patch.object(self.reconstructor, 'collect_parts',
                               capture_collect_parts):
            self.reconstructor.reconstruct()

        # There is one call, and it returns an empty list
        self.assertEqual([[]], collect_parts_results)
        log_lines = self.logger.all_log_lines()
        self.assertEqual(log_lines, {'info': [mock.ANY]})
        line = log_lines['info'][0]
        self.assertTrue(line.startswith('Nothing reconstructed '), line)


class TestReconstructFragmentArchive(BaseTestObjectReconstructor):
    obj_path = b'/a/c/o'  # subclass overrides this

    def setUp(self):
        super(TestReconstructFragmentArchive, self).setUp()
        self.obj_timestamp = self.ts()
        self.obj_metadata = {
            'name': self.obj_path,
            'Content-Length': '0',
            'ETag': 'etag',
            'X-Timestamp': self.obj_timestamp.normal
        }

    def test_reconstruct_fa_no_errors(self):
        job = {
            'partition': 0,
            'policy': self.policy,
        }
        part_nodes = self.policy.object_ring.get_part_nodes(0)
        node = part_nodes[1]
        node['backend_index'] = self.policy.get_backend_index(node['index'])

        test_data = (b'rebuild' * self.policy.ec_segment_size)[:-777]
        etag = md5(test_data).hexdigest()
        ec_archive_bodies = encode_frag_archive_bodies(self.policy, test_data)
        broken_body = ec_archive_bodies.pop(1)

        responses = list()
        for body in ec_archive_bodies:
            headers = get_header_frag_index(self, body)
            headers.update({'X-Object-Sysmeta-Ec-Etag': etag})
            responses.append((200, body, headers))

        # make a hook point at
        # swift.obj.reconstructor.ObjectReconstructor._get_response
        called_headers = []
        orig_func = object_reconstructor.ObjectReconstructor._get_response

        def _get_response_hook(self, node, part, path, headers, policy):
            called_headers.append(headers)
            return orig_func(self, node, part, path, headers, policy)

        codes, body_iter, headers = zip(*responses)
        get_response_path = \
            'swift.obj.reconstructor.ObjectReconstructor._get_response'
        with mock.patch(get_response_path, _get_response_hook):
            with mocked_http_conn(
                    *codes, body_iter=body_iter, headers=headers):
                df = self.reconstructor.reconstruct_fa(
                    job, node, self.obj_metadata)
                self.assertEqual(0, df.content_length)
                fixed_body = b''.join(df.reader())
        self.assertEqual(len(fixed_body), len(broken_body))
        self.assertEqual(md5(fixed_body).hexdigest(),
                         md5(broken_body).hexdigest())
        self.assertEqual(len(part_nodes) - 1, len(called_headers),
                         'Expected %d calls, got %r' % (len(part_nodes) - 1,
                                                        called_headers))
        for called_header in called_headers:
            called_header = HeaderKeyDict(called_header)
            self.assertIn('Content-Length', called_header)
            self.assertEqual(called_header['Content-Length'], '0')
            self.assertIn('User-Agent', called_header)
            user_agent = called_header['User-Agent']
            self.assertTrue(user_agent.startswith('obj-reconstructor'))
            self.assertIn('X-Backend-Storage-Policy-Index', called_header)
            self.assertEqual(called_header['X-Backend-Storage-Policy-Index'],
                             self.policy)
            self.assertIn('X-Backend-Fragment-Preferences', called_header)
            self.assertEqual(
                [{'timestamp': self.obj_timestamp.normal, 'exclude': []}],
                json.loads(called_header['X-Backend-Fragment-Preferences']))
            self.assertIn('X-Backend-Replication', called_header)
        # no error and warning
        self.assertFalse(self.logger.get_lines_for_level('error'))
        self.assertFalse(self.logger.get_lines_for_level('warning'))

    def test_reconstruct_fa_errors_works(self):
        job = {
            'partition': 0,
            'policy': self.policy,
        }
        part_nodes = self.policy.object_ring.get_part_nodes(0)
        node = part_nodes[4]
        node['backend_index'] = self.policy.get_backend_index(node['index'])

        test_data = (b'rebuild' * self.policy.ec_segment_size)[:-777]
        etag = md5(test_data).hexdigest()
        ec_archive_bodies = encode_frag_archive_bodies(self.policy, test_data)

        broken_body = ec_archive_bodies.pop(4)

        base_responses = list()
        for body in ec_archive_bodies:
            headers = get_header_frag_index(self, body)
            headers.update({'X-Object-Sysmeta-Ec-Etag': etag})
            base_responses.append((200, body, headers))

        # since we're already missing a fragment a +2 scheme can only support
        # one additional failure at a time
        for error in (Timeout(), 404, Exception('kaboom!')):
            responses = base_responses
            error_index = random.randint(0, len(responses) - 1)
            responses[error_index] = (error, '', '')
            codes, body_iter, headers_iter = zip(*responses)
            with mocked_http_conn(*codes, body_iter=body_iter,
                                  headers=headers_iter):
                df = self.reconstructor.reconstruct_fa(
                    job, node, dict(self.obj_metadata))
                fixed_body = b''.join(df.reader())
                self.assertEqual(len(fixed_body), len(broken_body))
                self.assertEqual(md5(fixed_body).hexdigest(),
                                 md5(broken_body).hexdigest())

    def test_reconstruct_fa_error_with_invalid_header(self):
        job = {
            'partition': 0,
            'policy': self.policy,
        }
        part_nodes = self.policy.object_ring.get_part_nodes(0)
        node = part_nodes[4]
        node['backend_index'] = self.policy.get_backend_index(node['index'])

        test_data = (b'rebuild' * self.policy.ec_segment_size)[:-777]
        etag = md5(test_data).hexdigest()
        ec_archive_bodies = encode_frag_archive_bodies(self.policy, test_data)

        broken_body = ec_archive_bodies.pop(4)

        base_responses = list()
        for body in ec_archive_bodies:
            headers = get_header_frag_index(self, body)
            headers.update({'X-Object-Sysmeta-Ec-Etag': etag})
            base_responses.append((200, body, headers))

        responses = base_responses
        # force the test to exercise the handling of this bad response by
        # sticking it in near the front
        error_index = random.randint(0, self.policy.ec_ndata - 1)
        status, body, headers = responses[error_index]
        # one esoteric failure is a literal string 'None' in place of the
        # X-Object-Sysmeta-EC-Frag-Index
        stub_node_job = {'some_keys': 'foo', 'but_not': 'frag_index'}
        headers['X-Object-Sysmeta-Ec-Frag-Index'] = str(
            stub_node_job.get('frag_index'))
        # oops!
        self.assertEqual('None',
                         headers.get('X-Object-Sysmeta-Ec-Frag-Index'))
        responses[error_index] = status, body, headers
        codes, body_iter, headers_iter = zip(*responses)
        with mocked_http_conn(*codes, body_iter=body_iter,
                              headers=headers_iter):
            df = self.reconstructor.reconstruct_fa(
                job, node, dict(self.obj_metadata))
            fixed_body = b''.join(df.reader())
            # ... this bad response should be ignored like any other failure
            self.assertEqual(len(fixed_body), len(broken_body))
            self.assertEqual(md5(fixed_body).hexdigest(),
                             md5(broken_body).hexdigest())

    def test_reconstruct_parity_fa_with_data_node_failure(self):
        job = {
            'partition': 0,
            'policy': self.policy,
        }
        part_nodes = self.policy.object_ring.get_part_nodes(0)
        node = part_nodes[-4]
        node['backend_index'] = self.policy.get_backend_index(node['index'])

        # make up some data (trim some amount to make it unaligned with
        # segment size)
        test_data = (b'rebuild' * self.policy.ec_segment_size)[:-454]
        etag = md5(test_data).hexdigest()
        ec_archive_bodies = encode_frag_archive_bodies(self.policy, test_data)
        # the scheme is 10+4, so this gets a parity node
        broken_body = ec_archive_bodies.pop(-4)

        responses = list()
        for body in ec_archive_bodies:
            headers = get_header_frag_index(self, body)
            headers.update({'X-Object-Sysmeta-Ec-Etag': etag})
            responses.append((200, body, headers))

        for error in (Timeout(), 404, Exception('kaboom!')):
            # grab a data node index
            error_index = random.randint(0, self.policy.ec_ndata - 1)
            responses[error_index] = (error, '', '')
            codes, body_iter, headers_iter = zip(*responses)
            with mocked_http_conn(*codes, body_iter=body_iter,
                                  headers=headers_iter):
                df = self.reconstructor.reconstruct_fa(
                    job, node, dict(self.obj_metadata))
                fixed_body = b''.join(df.reader())
                self.assertEqual(len(fixed_body), len(broken_body))
                self.assertEqual(md5(fixed_body).hexdigest(),
                                 md5(broken_body).hexdigest())

    def test_reconstruct_fa_exceptions_fails(self):
        job = {
            'partition': 0,
            'policy': self.policy,
        }
        part_nodes = self.policy.object_ring.get_part_nodes(0)
        node = part_nodes[1]
        node['backend_index'] = self.policy.get_backend_index(node['index'])
        policy = self.policy

        possible_errors = [Timeout(), Exception('kaboom!')]
        codes = [random.choice(possible_errors) for i in
                 range(policy.object_ring.replicas - 1)]
        with mocked_http_conn(*codes):
            self.assertRaises(DiskFileError, self.reconstructor.reconstruct_fa,
                              job, node, self.obj_metadata)
        error_lines = self.logger.get_lines_for_level('error')
        # # of replicas failed and one more error log to report not enough
        # responses to reconstruct.
        self.assertEqual(policy.object_ring.replicas, len(error_lines))
        for line in error_lines[:-1]:
            self.assertIn("Trying to GET", line)
        self.assertIn(
            'Unable to get enough responses (%s error responses)'
            % (policy.object_ring.replicas - 1),
            error_lines[-1],
            "Unexpected error line found: %s" % error_lines[-1])
        # no warning
        self.assertFalse(self.logger.get_lines_for_level('warning'))

    def test_reconstruct_fa_all_404s_fails(self):
        job = {
            'partition': 0,
            'policy': self.policy,
        }
        part_nodes = self.policy.object_ring.get_part_nodes(0)
        node = part_nodes[1]
        node['backend_index'] = self.policy.get_backend_index(node['index'])
        policy = self.policy

        codes = [404 for i in range(policy.object_ring.replicas - 1)]
        with mocked_http_conn(*codes):
            self.assertRaises(DiskFileError, self.reconstructor.reconstruct_fa,
                              job, node, self.obj_metadata)
        error_lines = self.logger.get_lines_for_level('error')
        # only 1 log to report not enough responses
        self.assertEqual(1, len(error_lines))
        self.assertIn(
            'Unable to get enough responses (%s error responses)'
            % (policy.object_ring.replicas - 1),
            error_lines[0],
            "Unexpected error line found: %s" % error_lines[0])
        # no warning
        self.assertFalse(self.logger.get_lines_for_level('warning'))

    def test_reconstruct_fa_with_mixed_old_etag(self):
        job = {
            'partition': 0,
            'policy': self.policy,
        }
        part_nodes = self.policy.object_ring.get_part_nodes(0)
        node = part_nodes[1]
        node['backend_index'] = self.policy.get_backend_index(node['index'])

        test_data = (b'rebuild' * self.policy.ec_segment_size)[:-777]
        etag = md5(test_data).hexdigest()
        ec_archive_bodies = encode_frag_archive_bodies(self.policy, test_data)

        # bad response
        broken_body = ec_archive_bodies.pop(1)
        ts = make_timestamp_iter()
        bad_headers = get_header_frag_index(self, broken_body)
        bad_headers.update({
            'X-Object-Sysmeta-Ec-Etag': 'some garbage',
            'X-Backend-Timestamp': next(ts).internal,
        })

        # good responses
        responses = list()
        t1 = next(ts).internal
        for body in ec_archive_bodies:
            headers = get_header_frag_index(self, body)
            headers.update({'X-Object-Sysmeta-Ec-Etag': etag,
                            'X-Backend-Timestamp': t1})
            responses.append((200, body, headers))

        # include the one older frag with different etag in first responses
        error_index = random.randint(0, self.policy.ec_ndata - 1)
        error_headers = get_header_frag_index(self,
                                              (responses[error_index])[1])
        error_headers.update(bad_headers)
        bad_response = (200, '', bad_headers)
        responses[error_index] = bad_response
        codes, body_iter, headers = zip(*responses)
        with mocked_http_conn(*codes, body_iter=body_iter, headers=headers):
            df = self.reconstructor.reconstruct_fa(
                job, node, self.obj_metadata)
            fixed_body = b''.join(df.reader())
            self.assertEqual(len(fixed_body), len(broken_body))
            self.assertEqual(md5(fixed_body).hexdigest(),
                             md5(broken_body).hexdigest())

        # no error and warning
        self.assertFalse(self.logger.get_lines_for_level('error'))
        self.assertFalse(self.logger.get_lines_for_level('warning'))

    def test_reconstruct_fa_with_mixed_new_etag(self):
        job = {
            'partition': 0,
            'policy': self.policy,
        }
        part_nodes = self.policy.object_ring.get_part_nodes(0)
        node = part_nodes[1]
        node['backend_index'] = self.policy.get_backend_index(node['index'])

        test_data = (b'rebuild' * self.policy.ec_segment_size)[:-777]
        etag = md5(test_data).hexdigest()
        ec_archive_bodies = encode_frag_archive_bodies(self.policy, test_data)

        broken_body = ec_archive_bodies.pop(1)
        ts = make_timestamp_iter()

        # good responses
        responses = list()
        t0 = next(ts).internal
        for body in ec_archive_bodies:
            headers = get_header_frag_index(self, body)
            headers.update({'X-Object-Sysmeta-Ec-Etag': etag,
                            'X-Backend-Timestamp': t0})
            responses.append((200, body, headers))

        # sanity check before negative test
        codes, body_iter, headers = zip(*responses)
        with mocked_http_conn(*codes, body_iter=body_iter, headers=headers):
            df = self.reconstructor.reconstruct_fa(
                job, node, dict(self.obj_metadata))
            fixed_body = b''.join(df.reader())
            self.assertEqual(len(fixed_body), len(broken_body))
            self.assertEqual(md5(fixed_body).hexdigest(),
                             md5(broken_body).hexdigest())

        # one newer etag won't spoil the bunch
        new_index = random.randint(0, self.policy.ec_ndata - 1)
        new_headers = get_header_frag_index(self, (responses[new_index])[1])
        new_headers.update({'X-Object-Sysmeta-Ec-Etag': 'some garbage',
                            'X-Backend-Timestamp': next(ts).internal})
        new_response = (200, '', new_headers)
        responses[new_index] = new_response
        codes, body_iter, headers = zip(*responses)
        with mocked_http_conn(*codes, body_iter=body_iter, headers=headers):
            df = self.reconstructor.reconstruct_fa(
                job, node, dict(self.obj_metadata))
            fixed_body = b''.join(df.reader())
            self.assertEqual(len(fixed_body), len(broken_body))
            self.assertEqual(md5(fixed_body).hexdigest(),
                             md5(broken_body).hexdigest())

        # no error and warning
        self.assertFalse(self.logger.get_lines_for_level('error'))
        self.assertFalse(self.logger.get_lines_for_level('warning'))

    def test_reconstruct_fa_with_mixed_etag_with_same_timestamp(self):
        job = {
            'partition': 0,
            'policy': self.policy,
        }
        part_nodes = self.policy.object_ring.get_part_nodes(0)
        node = part_nodes[1]
        node['backend_index'] = self.policy.get_backend_index(node['index'])

        test_data = (b'rebuild' * self.policy.ec_segment_size)[:-777]
        etag = md5(test_data).hexdigest()
        ec_archive_bodies = encode_frag_archive_bodies(self.policy, test_data)

        broken_body = ec_archive_bodies.pop(1)

        # good responses
        responses = list()
        for body in ec_archive_bodies:
            headers = get_header_frag_index(self, body)
            headers.update({'X-Object-Sysmeta-Ec-Etag': etag})
            responses.append((200, body, headers))

        # sanity check before negative test
        codes, body_iter, headers = zip(*responses)
        with mocked_http_conn(*codes, body_iter=body_iter, headers=headers):
            df = self.reconstructor.reconstruct_fa(
                job, node, dict(self.obj_metadata))
            fixed_body = b''.join(df.reader())
            self.assertEqual(len(fixed_body), len(broken_body))
            self.assertEqual(md5(fixed_body).hexdigest(),
                             md5(broken_body).hexdigest())

        # a response at same timestamp but different etag won't spoil the bunch
        # N.B. (FIXME). if we choose the first response as garbage, the
        # reconstruction fails because all other *correct* frags will be
        # assumed as garbage. To avoid the freaky failing set randint
        # as [1, self.policy.ec_ndata - 1] to make the first response
        # always have the correct etag to reconstruct
        new_index = random.randint(1, self.policy.ec_ndata - 1)
        new_headers = get_header_frag_index(self, (responses[new_index])[1])
        new_headers.update({'X-Object-Sysmeta-Ec-Etag': 'some garbage'})
        new_response = (200, '', new_headers)
        responses[new_index] = new_response
        codes, body_iter, headers = zip(*responses)
        with mocked_http_conn(*codes, body_iter=body_iter, headers=headers):
            df = self.reconstructor.reconstruct_fa(
                job, node, dict(self.obj_metadata))
            fixed_body = b''.join(df.reader())
            self.assertEqual(len(fixed_body), len(broken_body))
            self.assertEqual(md5(fixed_body).hexdigest(),
                             md5(broken_body).hexdigest())

        # expect an error log but no warnings
        error_log_lines = self.logger.get_lines_for_level('error')
        self.assertEqual(1, len(error_log_lines))
        self.assertIn(
            'Mixed Etag (some garbage, %s) for 10.0.0.1:1001/sdb/0%s '
            'policy#%s frag#1' %
            (etag, self.obj_path.decode('utf8'), int(self.policy)),
            error_log_lines[0])
        self.assertFalse(self.logger.get_lines_for_level('warning'))

    def test_reconstruct_fa_with_mixed_not_enough_etags_fail(self):
        job = {
            'partition': 0,
            'policy': self.policy,
        }
        part_nodes = self.policy.object_ring.get_part_nodes(0)
        node = part_nodes[1]
        node['backend_index'] = self.policy.get_backend_index(node['index'])

        test_data = (b'rebuild' * self.policy.ec_segment_size)[:-777]
        ec_archive_dict = dict()
        ts = make_timestamp_iter()
        # create 3 different ec bodies
        for i in range(3):
            body = test_data[i:]
            archive_bodies = encode_frag_archive_bodies(self.policy, body)
            # pop the index to the destination node
            archive_bodies.pop(1)
            key = (md5(body).hexdigest(), next(ts).internal, bool(i % 2))
            ec_archive_dict[key] = archive_bodies

        responses = list()
        # fill out response list by 3 different etag bodies
        for etag, ts, durable in itertools.cycle(ec_archive_dict):
            body = ec_archive_dict[(etag, ts, durable)].pop(0)
            headers = get_header_frag_index(self, body)
            headers.update({'X-Object-Sysmeta-Ec-Etag': etag,
                            'X-Backend-Timestamp': ts})
            if durable:
                headers['X-Backend-Durable-Timestamp'] = ts
            responses.append((200, body, headers))
            if len(responses) >= (self.policy.object_ring.replicas - 1):
                break

        # sanity, there is 3 different etag and each etag
        # doesn't have > ec_k bodies
        etag_count = collections.Counter(
            [in_resp_headers['X-Object-Sysmeta-Ec-Etag']
             for _, _, in_resp_headers in responses])
        self.assertEqual(3, len(etag_count))
        for etag, count in etag_count.items():
            self.assertLess(count, self.policy.ec_ndata)

        codes, body_iter, headers = zip(*responses)
        with mocked_http_conn(*codes, body_iter=body_iter, headers=headers):
            self.assertRaises(DiskFileError, self.reconstructor.reconstruct_fa,
                              job, node, self.obj_metadata)

        error_lines = self.logger.get_lines_for_level('error')
        # 1 error log per etag to report not enough responses
        self.assertEqual(3, len(error_lines))
        for error_line in error_lines:
            for expected_etag, ts, durable in ec_archive_dict:
                if expected_etag in error_line:
                    break
            else:
                self.fail(
                    "no expected etag %s found: %s" %
                    (list(ec_archive_dict), error_line))
            # remove the found etag which should not be found in the
            # following error lines
            del ec_archive_dict[(expected_etag, ts, durable)]

            expected = 'Unable to get enough responses (%s/10) to ' \
                       'reconstruct %s 10.0.0.1:1001/sdb/0%s policy#0 ' \
                       'frag#1 with ETag %s and timestamp %s' % \
                       (etag_count[expected_etag],
                        'durable' if durable else 'non-durable',
                        self.obj_path.decode('utf8'),
                        expected_etag, ts)
            self.assertIn(
                expected, error_line,
                "Unexpected error line found: Expected: %s Got: %s"
                % (expected, error_line))
        # no warning
        self.assertFalse(self.logger.get_lines_for_level('warning'))

    def test_reconstruct_fa_finds_itself_does_not_fail(self):
        # verify that reconstruction of a missing frag can cope with finding
        # that missing frag in the responses it gets from other nodes while
        # attempting to rebuild the missing frag
        job = {
            'partition': 0,
            'policy': self.policy,
        }
        part_nodes = self.policy.object_ring.get_part_nodes(0)
        broken_index = random.randint(0, self.policy.ec_ndata - 1)
        node = part_nodes[broken_index]
        node['backend_index'] = self.policy.get_backend_index(node['index'])

        test_data = (b'rebuild' * self.policy.ec_segment_size)[:-777]
        etag = md5(test_data).hexdigest()
        ec_archive_bodies = encode_frag_archive_bodies(self.policy, test_data)

        # instead of popping the broken body, we'll just leave it in the list
        # of responses and take away something else.
        broken_body = ec_archive_bodies[broken_index]
        ec_archive_bodies = ec_archive_bodies[:-1]

        def make_header(body):
            headers = get_header_frag_index(self, body)
            headers.update({'X-Object-Sysmeta-Ec-Etag': etag})
            return headers

        responses = [(200, body, make_header(body))
                     for body in ec_archive_bodies]
        codes, body_iter, headers = zip(*responses)
        with mocked_http_conn(*codes, body_iter=body_iter, headers=headers):
            df = self.reconstructor.reconstruct_fa(
                job, node, self.obj_metadata)
            fixed_body = b''.join(df.reader())
            self.assertEqual(len(fixed_body), len(broken_body))
            self.assertEqual(md5(fixed_body).hexdigest(),
                             md5(broken_body).hexdigest())

        # no error, no warning
        self.assertFalse(self.logger.get_lines_for_level('error'))
        self.assertFalse(self.logger.get_lines_for_level('warning'))
        # the found own frag will be reported in the debug message
        debug_log_lines = self.logger.get_lines_for_level('debug')
        # redundant frag found once in first ec_ndata responses
        self.assertIn(
            'Found existing frag #%s at' % broken_index,
            debug_log_lines[0])

        # N.B. in the future, we could avoid those check because
        # definitely sending the copy rather than reconstruct will
        # save resources. But one more reason, we're avoiding to
        # use the dest index fragment even if it goes to reconstruct
        # function is that it will cause a bunch of warning log from
        # liberasurecode[1].
        # 1: https://github.com/openstack/liberasurecode/blob/
        #    master/src/erasurecode.c#L870
        log_prefix = 'Reconstruct frag #%s with frag indexes' % broken_index
        self.assertIn(log_prefix, debug_log_lines[1])
        self.assertFalse(debug_log_lines[2:])
        got_frag_index_list = json.loads(
            debug_log_lines[1][len(log_prefix):])
        self.assertNotIn(broken_index, got_frag_index_list)

    def test_reconstruct_fa_finds_duplicate_does_not_fail(self):
        job = {
            'partition': 0,
            'policy': self.policy,
        }
        part_nodes = self.policy.object_ring.get_part_nodes(0)
        node = part_nodes[1]
        node['backend_index'] = self.policy.get_backend_index(node['index'])

        test_data = (b'rebuild' * self.policy.ec_segment_size)[:-777]
        etag = md5(test_data).hexdigest()
        ec_archive_bodies = encode_frag_archive_bodies(self.policy, test_data)

        broken_body = ec_archive_bodies.pop(1)
        # add some duplicates
        num_duplicates = self.policy.ec_nparity - 1
        ec_archive_bodies = (ec_archive_bodies[:num_duplicates] +
                             ec_archive_bodies)[:-num_duplicates]

        def make_header(body):
            headers = get_header_frag_index(self, body)
            headers.update({'X-Object-Sysmeta-Ec-Etag': etag})
            return headers

        responses = [(200, body, make_header(body))
                     for body in ec_archive_bodies]
        codes, body_iter, headers = zip(*responses)
        with mocked_http_conn(*codes, body_iter=body_iter, headers=headers):
            df = self.reconstructor.reconstruct_fa(
                job, node, self.obj_metadata)
            fixed_body = b''.join(df.reader())
            self.assertEqual(len(fixed_body), len(broken_body))
            self.assertEqual(md5(fixed_body).hexdigest(),
                             md5(broken_body).hexdigest())

        # no error and warning
        self.assertFalse(self.logger.get_lines_for_level('error'))
        self.assertFalse(self.logger.get_lines_for_level('warning'))
        debug_log_lines = self.logger.get_lines_for_level('debug')
        self.assertEqual(1, len(debug_log_lines))
        expected_prefix = 'Reconstruct frag #1 with frag indexes'
        self.assertIn(expected_prefix, debug_log_lines[0])
        got_frag_index_list = json.loads(
            debug_log_lines[0][len(expected_prefix):])
        self.assertNotIn(1, got_frag_index_list)

    def test_reconstruct_fa_missing_headers(self):
        # This is much negative tests asserting when the expected
        # headers are missing in the responses to gather fragments
        # to reconstruct

        job = {
            'partition': 0,
            'policy': self.policy,
        }
        part_nodes = self.policy.object_ring.get_part_nodes(0)
        node = part_nodes[1]
        node['backend_index'] = self.policy.get_backend_index(node['index'])

        test_data = (b'rebuild' * self.policy.ec_segment_size)[:-777]
        etag = md5(test_data).hexdigest()
        ec_archive_bodies = encode_frag_archive_bodies(self.policy, test_data)

        broken_body = ec_archive_bodies.pop(1)

        def make_header(body):
            headers = get_header_frag_index(self, body)
            headers.update(
                {'X-Object-Sysmeta-Ec-Etag': etag,
                 'X-Backend-Timestamp': self.obj_timestamp.internal})
            return headers

        def test_missing_header(missing_header, warning_extra):
            self.logger._clear()
            responses = [(200, body, make_header(body))
                         for body in ec_archive_bodies]

            # To drop the header from the response[0], set None as the value
            # explicitly instead of deleting the key because if no key exists
            # in the dict, fake_http_connect will insert some key/value pairs
            # automatically (e.g. X-Backend-Timestamp)
            responses[0][2].update({missing_header: None})

            codes, body_iter, headers = zip(*responses)
            with mocked_http_conn(
                    *codes, body_iter=body_iter, headers=headers) as mock_conn:
                df = self.reconstructor.reconstruct_fa(
                    job, node, self.obj_metadata)
                fixed_body = b''.join(df.reader())
                self.assertEqual(len(fixed_body), len(broken_body))
                self.assertEqual(md5(fixed_body).hexdigest(),
                                 md5(broken_body).hexdigest())

            # no errors
            self.assertFalse(self.logger.get_lines_for_level('error'))
            # ...but warning for the missing header
            warning_log_lines = self.logger.get_lines_for_level('warning')
            self.assertEqual(1, len(warning_log_lines))

            path = unquote(
                '%(ip)s:%(port)d%(path)s' % mock_conn.requests[0]
            )
            expected_warning = 'Invalid resp from %s policy#0%s' % (
                path, warning_extra)
            if six.PY2:
                expected_warning = expected_warning.decode('utf8')
            self.assertIn(expected_warning, warning_log_lines)

        test_missing_header(
            'X-Object-Sysmeta-Ec-Frag-Index',
            ' (invalid X-Object-Sysmeta-Ec-Frag-Index: None)')
        test_missing_header(
            'X-Object-Sysmeta-Ec-Etag',
            ', frag index 0 (missing Etag)')
        test_missing_header(
            'X-Backend-Timestamp',
            ', frag index 0 (missing X-Backend-Timestamp)')

    def test_reconstruct_fa_invalid_frag_index_headers(self):
        # This is much negative tests asserting when the expected
        # ec frag index header has invalid value in the responses
        # to gather fragments to reconstruct

        job = {
            'partition': 0,
            'policy': self.policy,
        }
        part_nodes = self.policy.object_ring.get_part_nodes(0)
        node = part_nodes[1]
        node['backend_index'] = self.policy.get_backend_index(node['index'])

        test_data = (b'rebuild' * self.policy.ec_segment_size)[:-777]
        etag = md5(test_data).hexdigest()
        ec_archive_bodies = encode_frag_archive_bodies(self.policy, test_data)

        broken_body = ec_archive_bodies.pop(1)

        def make_header(body):
            headers = get_header_frag_index(self, body)
            headers.update({'X-Object-Sysmeta-Ec-Etag': etag})
            return headers

        def test_invalid_ec_frag_index_header(invalid_frag_index):
            self.logger._clear()
            responses = [(200, body, make_header(body))
                         for body in ec_archive_bodies]

            responses[0][2].update({
                'X-Object-Sysmeta-Ec-Frag-Index': invalid_frag_index})

            codes, body_iter, headers = zip(*responses)
            with mocked_http_conn(
                    *codes, body_iter=body_iter, headers=headers) as mock_conn:
                df = self.reconstructor.reconstruct_fa(
                    job, node, self.obj_metadata)
                fixed_body = b''.join(df.reader())
                self.assertEqual(len(fixed_body), len(broken_body))
                self.assertEqual(md5(fixed_body).hexdigest(),
                                 md5(broken_body).hexdigest())

            # no errors
            self.assertFalse(self.logger.get_lines_for_level('error'))
            # ...but warning for the invalid header
            warning_log_lines = self.logger.get_lines_for_level('warning')
            self.assertEqual(1, len(warning_log_lines))

            path = unquote(
                '%(ip)s:%(port)d%(path)s' % mock_conn.requests[0]
            )
            expected_warning = (
                'Invalid resp from %s policy#0 '
                '(invalid X-Object-Sysmeta-Ec-Frag-Index: %r)'
                % (path, invalid_frag_index))
            if six.PY2:
                expected_warning = expected_warning.decode('utf8')
            self.assertIn(expected_warning, warning_log_lines)

        for value in ('None', 'invalid'):
            test_invalid_ec_frag_index_header(value)


@patch_policies(with_ec_default=True)
class TestReconstructFragmentArchiveUTF8(TestReconstructFragmentArchive):
    # repeat superclass tests with an object path that contains non-ascii chars
    obj_path = b'/a/c/o\xc3\xa8'


@patch_policies([ECStoragePolicy(0, name='ec', is_default=True,
                                 ec_type=DEFAULT_TEST_EC_TYPE,
                                 ec_ndata=10, ec_nparity=4,
                                 ec_segment_size=4096,
                                 ec_duplication_factor=2),
                 StoragePolicy(1, name='other')],
                fake_ring_args=[{'replicas': 28}, {'replicas': 3}])
class TestObjectReconstructorECDuplicationFactor(TestObjectReconstructor):
    def setUp(self):
        super(TestObjectReconstructorECDuplicationFactor, self).setUp()
        self.fabricated_ring = FabricatedRing(replicas=28, devices=56)

    def _test_reconstruct_with_duplicate_frags_no_errors(self, index):
        job = {
            'partition': 0,
            'policy': self.policy,
        }
        part_nodes = self.policy.object_ring.get_part_nodes(0)
        node = part_nodes[index]
        node['backend_index'] = self.policy.get_backend_index(node['index'])
        metadata = {
            'name': '/a/c/o',
            'Content-Length': 0,
            'ETag': 'etag',
            'X-Timestamp': '1234567890.12345',
        }

        test_data = (b'rebuild' * self.policy.ec_segment_size)[:-777]
        etag = md5(test_data).hexdigest()
        ec_archive_bodies = encode_frag_archive_bodies(self.policy, test_data)

        broken_body = ec_archive_bodies.pop(index)

        responses = list()
        for body in ec_archive_bodies:
            headers = get_header_frag_index(self, body)
            headers.update({'X-Object-Sysmeta-Ec-Etag': etag})
            responses.append((200, body, headers))

        # make a hook point at
        # swift.obj.reconstructor.ObjectReconstructor._get_response
        called_headers = []
        orig_func = object_reconstructor.ObjectReconstructor._get_response

        def _get_response_hook(self, node, part, path, headers, policy):
            called_headers.append(headers)
            return orig_func(self, node, part, path, headers, policy)

        # need parity + 1 node failures to reach duplicated fragments
        failed_start_at = (
            self.policy.ec_n_unique_fragments - self.policy.ec_nparity - 1)

        # set Timeout for node #9, #10, #11, #12, #13
        for i in range(self.policy.ec_nparity + 1):
            responses[failed_start_at + i] = (Timeout(), '', '')

        codes, body_iter, headers = zip(*responses)
        get_response_path = \
            'swift.obj.reconstructor.ObjectReconstructor._get_response'
        with mock.patch(get_response_path, _get_response_hook):
            with mocked_http_conn(
                    *codes, body_iter=body_iter, headers=headers):
                df = self.reconstructor.reconstruct_fa(
                    job, node, metadata)
                fixed_body = b''.join(df.reader())
                self.assertEqual(len(fixed_body), len(broken_body))
                self.assertEqual(md5(fixed_body).hexdigest(),
                                 md5(broken_body).hexdigest())
                for called_header in called_headers:
                    called_header = HeaderKeyDict(called_header)
                    self.assertIn('Content-Length', called_header)
                    self.assertEqual(called_header['Content-Length'], '0')
                    self.assertIn('User-Agent', called_header)
                    user_agent = called_header['User-Agent']
                    self.assertTrue(user_agent.startswith('obj-reconstructor'))

    def test_reconstruct_with_duplicate_frags_no_errors(self):
        # any fragments can be broken
        for index in range(28):
            self._test_reconstruct_with_duplicate_frags_no_errors(index)

    def test_iter_nodes_for_frag(self):
        self.reconstructor.rebuild_handoff_node_count = -1
        policy = ECStoragePolicy(1, name='test', ec_type=DEFAULT_TEST_EC_TYPE,
                                 ec_ndata=4, ec_nparity=3,
                                 ec_duplication_factor=2)
        policy.object_ring = FabricatedRing(replicas=14, devices=42)
        primaries = policy.object_ring.get_part_nodes(0)

        node = primaries[0]
        nodes_for_frag = list(self.reconstructor._iter_nodes_for_frag(
            policy, 0, node))
        expected = [0, 0, 7, 14, 21]
        self.assertEqual(expected, [n.get('index', n.get('handoff_index'))
                                    for n in nodes_for_frag])
        for node in nodes_for_frag:
            self.assertEqual(0, node['backend_index'])

        node = primaries[3]
        nodes_for_frag = list(self.reconstructor._iter_nodes_for_frag(
            policy, 0, node))
        expected = [3, 3, 10, 17, 24]
        self.assertEqual(expected, [n.get('index', n.get('handoff_index'))
                                    for n in nodes_for_frag])
        for node in nodes_for_frag:
            self.assertEqual(3, node['backend_index'])

        node = primaries[7]
        nodes_for_frag = list(self.reconstructor._iter_nodes_for_frag(
            policy, 0, node))
        expected = [7, 0, 7, 14, 21]
        self.assertEqual(expected, [n.get('index', n.get('handoff_index'))
                                    for n in nodes_for_frag])
        for node in nodes_for_frag:
            self.assertEqual(0, node['backend_index'])

        node = primaries[-1]
        nodes_for_frag = list(self.reconstructor._iter_nodes_for_frag(
            policy, 0, node))
        expected = [13, 6, 13, 20, 27]
        self.assertEqual(expected, [n.get('index', n.get('handoff_index'))
                                    for n in nodes_for_frag])
        for node in nodes_for_frag:
            self.assertEqual(6, node['backend_index'])


if __name__ == '__main__':
    unittest.main()