summaryrefslogtreecommitdiff
path: root/src/mongo/db/repl/topology_coordinator_impl_test.cpp
blob: 0defa78cd36d8ecb5e55a48007caa1c782f9b91f (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
/**
 *    Copyright (C) 2014 MongoDB Inc.
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the GNU Affero General Public License in all respects for
 *    all of the code used other than as permitted herein. If you modify file(s)
 *    with this exception, you may extend this exception to your version of the
 *    file(s), but you are not obligated to do so. If you do not wish to do so,
 *    delete this exception statement from your version. If you delete this
 *    exception statement from all source files in the program, then also delete
 *    it in the license file.
 */

#include "mongo/platform/basic.h"

#include <boost/scoped_ptr.hpp>
#include <iostream>

#include "mongo/db/repl/heartbeat_response_action.h"
#include "mongo/db/repl/member_heartbeat_data.h"
#include "mongo/db/repl/repl_set_heartbeat_args.h"
#include "mongo/db/repl/repl_set_heartbeat_args_v1.h"
#include "mongo/db/repl/repl_set_heartbeat_response.h"
#include "mongo/db/repl/repl_set_declare_election_winner_args.h"
#include "mongo/db/repl/repl_set_request_votes_args.h"
#include "mongo/db/repl/topology_coordinator.h"
#include "mongo/db/repl/topology_coordinator_impl.h"
#include "mongo/unittest/unittest.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/net/hostandport.h"
#include "mongo/util/time_support.h"

#define ASSERT_NO_ACTION(EXPRESSION) \
    ASSERT_EQUALS(mongo::repl::HeartbeatResponseAction::NoAction, (EXPRESSION))

using boost::scoped_ptr;

namespace mongo {
namespace repl {
namespace {

    Date_t operator++(Date_t& d, int) {
        Date_t result = d;
        d += Milliseconds(1);
        return result;
    }

    bool stringContains(const std::string &haystack, const std::string& needle) {
        return haystack.find(needle) != std::string::npos;
    }

    class TopoCoordTest : public mongo::unittest::Test {
    public:
        virtual void setUp() {
            _topo.reset(new TopologyCoordinatorImpl(Seconds(100)));
            _now = Date_t();
            _selfIndex = -1;
            _cbData.reset(new ReplicationExecutor::CallbackData(
                        NULL, ReplicationExecutor::CallbackHandle(), Status::OK()));
        }

        virtual void tearDown() {
            _topo.reset(NULL);
            _cbData.reset(NULL);
        }

    protected:
        TopologyCoordinatorImpl& getTopoCoord() {return *_topo;}
        ReplicationExecutor::CallbackData cbData() {return *_cbData;}
        Date_t& now() {return _now;}

        int64_t countLogLinesContaining(const std::string& needle) {
            return std::count_if(getCapturedLogMessages().begin(),
                                 getCapturedLogMessages().end(),
                                 stdx::bind(stringContains,
                                            stdx::placeholders::_1,
                                            needle));
        }

        void makeSelfPrimary(const Timestamp& electionOpTime = Timestamp(0,0)) {
            getTopoCoord().changeMemberState_forTest(MemberState::RS_PRIMARY, electionOpTime);
            getTopoCoord()._setCurrentPrimaryForTest(_selfIndex);
        }

        void setSelfMemberState(const MemberState& newState) {
            getTopoCoord().changeMemberState_forTest(newState);
        }

        int getCurrentPrimaryIndex() {
            return getTopoCoord().getCurrentPrimaryIndex();
        }
        // Update config and set selfIndex
        // If "now" is passed in, set _now to now+1
        void updateConfig(BSONObj cfg,
                          int selfIndex,
                          Date_t now = Date_t::fromMillisSinceEpoch(-1),
                          const OpTime& lastOp = OpTime()) {
            ReplicaSetConfig config;
            ASSERT_OK(config.initialize(cfg));
            ASSERT_OK(config.validate());

            _selfIndex = selfIndex;

            if (now == Date_t::fromMillisSinceEpoch(-1)) {
                getTopoCoord().updateConfig(config, selfIndex, _now, lastOp);
                _now += Milliseconds(1);
            }
            else {
                invariant(now > _now);
                getTopoCoord().updateConfig(config, selfIndex, now, lastOp);
                _now = now + Milliseconds(1);
            }
        }

        HeartbeatResponseAction receiveUpHeartbeat(
                const HostAndPort& member,
                const std::string& setName,
                MemberState memberState,
                const OpTime& electionTime,
                const OpTime& lastOpTimeSender,
                const OpTime& lastOpTimeReceiver) {
            return _receiveHeartbeatHelper(Status::OK(),
                                           member,
                                           setName,
                                           memberState,
                                           electionTime.getTimestamp(),
                                           lastOpTimeSender,
                                           lastOpTimeReceiver,
                                           Milliseconds(1));
        }

        HeartbeatResponseAction receiveDownHeartbeat(
                const HostAndPort& member,
                const std::string& setName,
                const OpTime& lastOpTimeReceiver,
                ErrorCodes::Error errcode = ErrorCodes::HostUnreachable) {
            // timed out heartbeat to mark a node as down

            Milliseconds roundTripTime{ReplicaSetConfig::kDefaultHeartbeatTimeoutPeriod};
            return _receiveHeartbeatHelper(Status(errcode, ""),
                                           member,
                                           setName,
                                           MemberState::RS_UNKNOWN,
                                           Timestamp(),
                                           OpTime(),
                                           lastOpTimeReceiver,
                                           roundTripTime);
        }

        HeartbeatResponseAction heartbeatFromMember(const HostAndPort& member,
                                                    const std::string& setName,
                                                    MemberState memberState,
                                                    const OpTime& lastOpTimeSender,
                                                    Milliseconds roundTripTime = Milliseconds(1)) {
            return _receiveHeartbeatHelper(Status::OK(),
                                           member,
                                           setName,
                                           memberState,
                                           Timestamp(),
                                           lastOpTimeSender,
                                           OpTime(),
                                           roundTripTime);
        }

    private:

        HeartbeatResponseAction _receiveHeartbeatHelper(Status responseStatus,
                                                        const HostAndPort& member,
                                                        const std::string& setName,
                                                        MemberState memberState,
                                                        Timestamp electionTime,
                                                        const OpTime& lastOpTimeSender,
                                                        const OpTime& lastOpTimeReceiver,
                                                        Milliseconds roundTripTime) {
            StatusWith<ReplSetHeartbeatResponse> hbResponse =
                    StatusWith<ReplSetHeartbeatResponse>(responseStatus);

            if (responseStatus.isOK()) {
                ReplSetHeartbeatResponse hb;
                hb.setConfigVersion(1);
                hb.setState(memberState);
                hb.setOpTime(lastOpTimeSender);
                hb.setElectionTime(electionTime);
                hbResponse = StatusWith<ReplSetHeartbeatResponse>(hb);
            }
            getTopoCoord().prepareHeartbeatRequest(now(),
                                                   setName,
                                                   member);
            now() += roundTripTime;
            return getTopoCoord().processHeartbeatResponse(now(),
                                                           roundTripTime,
                                                           member,
                                                           hbResponse,
                                                           lastOpTimeReceiver);
        }

    private:
        scoped_ptr<TopologyCoordinatorImpl> _topo;
        scoped_ptr<ReplicationExecutor::CallbackData> _cbData;
        Date_t _now;
        int _selfIndex;
    };

    TEST_F(TopoCoordTest, ChooseSyncSourceBasic) {
        // if we do not have an index in the config, we should get an empty syncsource
        HostAndPort newSyncSource = getTopoCoord().chooseNewSyncSource(now()++, OpTime());
        ASSERT_TRUE(newSyncSource.empty());

        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 1 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 10 << "host" << "hself") <<
                              BSON("_id" << 20 << "host" << "h2") <<
                              BSON("_id" << 30 << "host" << "h3"))),
                     0);
        setSelfMemberState(MemberState::RS_SECONDARY);

        // member h2 is the furthest ahead
        heartbeatFromMember(HostAndPort("h2"),
                            "rs0",
                            MemberState::RS_SECONDARY,
                            OpTime(Timestamp(1,0), 0));
        heartbeatFromMember(HostAndPort("h3"), "rs0", MemberState::RS_SECONDARY, OpTime());

        // We start with no sync source
        ASSERT(getTopoCoord().getSyncSourceAddress().empty());

        // Fail due to insufficient number of pings
        newSyncSource = getTopoCoord().chooseNewSyncSource(now()++, OpTime());
        ASSERT_EQUALS(getTopoCoord().getSyncSourceAddress(), newSyncSource);
        ASSERT(getTopoCoord().getSyncSourceAddress().empty());

        // Record 2nd round of pings to allow choosing a new sync source; all members equidistant
        heartbeatFromMember(HostAndPort("h2"),
                            "rs0",
                            MemberState::RS_SECONDARY,
                            OpTime(Timestamp(1,0), 0));
        heartbeatFromMember(HostAndPort("h3"), "rs0", MemberState::RS_SECONDARY, OpTime());

        // Should choose h2, since it is furthest ahead
        newSyncSource = getTopoCoord().chooseNewSyncSource(now()++, OpTime());
        ASSERT_EQUALS(getTopoCoord().getSyncSourceAddress(), newSyncSource);
        ASSERT_EQUALS(HostAndPort("h2"), getTopoCoord().getSyncSourceAddress());
        
        // h3 becomes further ahead, so it should be chosen
        heartbeatFromMember(HostAndPort("h3"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(2,0), 0));
        getTopoCoord().chooseNewSyncSource(now()++, OpTime());
        ASSERT_EQUALS(HostAndPort("h3"), getTopoCoord().getSyncSourceAddress());

        // h3 becomes an invalid candidate for sync source; should choose h2 again
        heartbeatFromMember(HostAndPort("h3"), "rs0", MemberState::RS_RECOVERING,
                            OpTime(Timestamp(2,0), 0));
        getTopoCoord().chooseNewSyncSource(now()++, OpTime());
        ASSERT_EQUALS(HostAndPort("h2"), getTopoCoord().getSyncSourceAddress());

        // h3 back in SECONDARY and ahead
        heartbeatFromMember(HostAndPort("h3"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(2,0), 0));
        getTopoCoord().chooseNewSyncSource(now()++, OpTime());
        ASSERT_EQUALS(HostAndPort("h3"), getTopoCoord().getSyncSourceAddress());

        // h3 goes down
        receiveDownHeartbeat(HostAndPort("h3"), "rs0", OpTime());
        getTopoCoord().chooseNewSyncSource(now()++, OpTime());
        ASSERT_EQUALS(HostAndPort("h2"), getTopoCoord().getSyncSourceAddress());

        // h3 back up and ahead
        heartbeatFromMember(HostAndPort("h3"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(2,0), 0));
        getTopoCoord().chooseNewSyncSource(now()++, OpTime());
        ASSERT_EQUALS(HostAndPort("h3"), getTopoCoord().getSyncSourceAddress());

    }

    TEST_F(TopoCoordTest, ChooseSyncSourceCandidates) {
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 1 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 1 << "host" << "hself") <<
                              BSON("_id" << 10 << "host" << "h1") <<
                              BSON("_id" << 20 << "host" << "h2" <<
                                   "buildIndexes" << false << "priority" << 0) <<
                              BSON("_id" << 30 << "host" << "h3" <<
                                   "hidden" << true << "priority" << 0 << "votes" << 0) <<
                              BSON("_id" << 40 << "host" << "h4" <<"arbiterOnly" << true) <<
                              BSON("_id" << 50 << "host" << "h5" <<
                                   "slaveDelay" << 1 << "priority" << 0) <<
                              BSON("_id" << 60 << "host" << "h6") <<
                              BSON("_id" << 70 << "host" << "hprimary"))),
                     0);

        setSelfMemberState(MemberState::RS_SECONDARY);
        OpTime lastOpTimeWeApplied = OpTime(Timestamp(100,0), 0);

        heartbeatFromMember(HostAndPort("h1"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(501, 0), 0), Milliseconds(700));
        heartbeatFromMember(HostAndPort("h2"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(501, 0), 0), Milliseconds(600));
        heartbeatFromMember(HostAndPort("h3"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(501, 0), 0), Milliseconds(500));
        heartbeatFromMember(HostAndPort("h4"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(501, 0), 0), Milliseconds(400));
        heartbeatFromMember(HostAndPort("h5"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(501, 0), 0), Milliseconds(300));

        // This node is lagged further than maxSyncSourceLagSeconds.
        heartbeatFromMember(HostAndPort("h6"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(499, 0), 0), Milliseconds(200));

        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        heartbeatFromMember(HostAndPort("hprimary"), "rs0", MemberState::RS_PRIMARY,
                            OpTime(Timestamp(600, 0), 0), Milliseconds(100));
        ASSERT_EQUALS(7, getCurrentPrimaryIndex());

        // Record 2nd round of pings to allow choosing a new sync source
        heartbeatFromMember(HostAndPort("h1"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(501, 0), 0), Milliseconds(700));
        heartbeatFromMember(HostAndPort("h2"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(501, 0), 0), Milliseconds(600));
        heartbeatFromMember(HostAndPort("h3"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(501, 0), 0), Milliseconds(500));
        heartbeatFromMember(HostAndPort("h4"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(501, 0), 0), Milliseconds(400));
        heartbeatFromMember(HostAndPort("h5"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(501, 0), 0), Milliseconds(300));
        heartbeatFromMember(HostAndPort("h6"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(499, 0), 0), Milliseconds(200));
        heartbeatFromMember(HostAndPort("hprimary"), "rs0", MemberState::RS_PRIMARY,
                            OpTime(Timestamp(600, 0), 0), Milliseconds(100));

        // Should choose primary first; it's closest
        getTopoCoord().chooseNewSyncSource(now()++, lastOpTimeWeApplied);
        ASSERT_EQUALS(HostAndPort("hprimary"), getTopoCoord().getSyncSourceAddress());

        // Primary goes far far away
        heartbeatFromMember(HostAndPort("hprimary"), "rs0", MemberState::RS_PRIMARY,
                            OpTime(Timestamp(600, 0), 0), Milliseconds(100000000));

        // Should choose h4.  (if an arbiter has an oplog, it's a valid sync source)
        // h6 is not considered because it is outside the maxSyncLagSeconds window,
        getTopoCoord().chooseNewSyncSource(now()++, lastOpTimeWeApplied);
        ASSERT_EQUALS(HostAndPort("h4"), getTopoCoord().getSyncSourceAddress());
        
        // h4 goes down; should choose h1
        receiveDownHeartbeat(HostAndPort("h4"), "rs0", OpTime());
        getTopoCoord().chooseNewSyncSource(now()++, lastOpTimeWeApplied);
        ASSERT_EQUALS(HostAndPort("h1"), getTopoCoord().getSyncSourceAddress());

        // Primary and h1 go down; should choose h6 
        receiveDownHeartbeat(HostAndPort("h1"), "rs0", OpTime());
        receiveDownHeartbeat(HostAndPort("hprimary"), "rs0", OpTime());
        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        getTopoCoord().chooseNewSyncSource(now()++, lastOpTimeWeApplied);
        ASSERT_EQUALS(HostAndPort("h6"), getTopoCoord().getSyncSourceAddress());

        // h6 goes down; should choose h5
        receiveDownHeartbeat(HostAndPort("h6"), "rs0", OpTime());
        getTopoCoord().chooseNewSyncSource(now()++, lastOpTimeWeApplied);
        ASSERT_EQUALS(HostAndPort("h5"), getTopoCoord().getSyncSourceAddress());

        // h5 goes down; should choose h3
        receiveDownHeartbeat(HostAndPort("h5"), "rs0", OpTime());
        getTopoCoord().chooseNewSyncSource(now()++, lastOpTimeWeApplied);
        ASSERT_EQUALS(HostAndPort("h3"), getTopoCoord().getSyncSourceAddress());

        // h3 goes down; no sync source candidates remain
        receiveDownHeartbeat(HostAndPort("h3"), "rs0", OpTime());
        getTopoCoord().chooseNewSyncSource(now()++, lastOpTimeWeApplied);
        ASSERT(getTopoCoord().getSyncSourceAddress().empty());
    }


    TEST_F(TopoCoordTest, ChooseSyncSourceChainingNotAllowed) {
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 1 <<
                          "settings" << BSON("chainingAllowed" << false) <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 10 << "host" << "hself") <<
                              BSON("_id" << 20 << "host" << "h2") <<
                              BSON("_id" << 30 << "host" << "h3"))),
                     0);

        setSelfMemberState(MemberState::RS_SECONDARY);

        heartbeatFromMember(HostAndPort("h2"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(1, 0), 0), Milliseconds(100));
        heartbeatFromMember(HostAndPort("h2"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(1, 0), 0), Milliseconds(100));
        heartbeatFromMember(HostAndPort("h3"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(0, 0), 0), Milliseconds(300));
        heartbeatFromMember(HostAndPort("h3"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(0, 0), 0), Milliseconds(300));

        // No primary situation: should choose no sync source.
        getTopoCoord().chooseNewSyncSource(now()++, OpTime());
        ASSERT(getTopoCoord().getSyncSourceAddress().empty());
        
        // Add primary
        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        heartbeatFromMember(HostAndPort("h3"), "rs0", MemberState::RS_PRIMARY,
                            OpTime(Timestamp(0, 0), 0), Milliseconds(300));
        ASSERT_EQUALS(2, getCurrentPrimaryIndex());

        // h3 is primary and should be chosen as sync source, despite being further away than h2
        // and the primary (h3) being behind our most recently applied optime
        getTopoCoord().chooseNewSyncSource(now()++, OpTime(Timestamp(10,0), 0));
        ASSERT_EQUALS(HostAndPort("h3"), getTopoCoord().getSyncSourceAddress());

    }

    TEST_F(TopoCoordTest, EmptySyncSourceOnPrimary) {
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 1 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 10 << "host" << "hself") <<
                              BSON("_id" << 20 << "host" << "h2") <<
                              BSON("_id" << 30 << "host" << "h3"))),
                     0);

        setSelfMemberState(MemberState::RS_SECONDARY);

        heartbeatFromMember(HostAndPort("h2"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(1, 0), 0), Milliseconds(100));
        heartbeatFromMember(HostAndPort("h2"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(1, 0), 0), Milliseconds(100));
        heartbeatFromMember(HostAndPort("h3"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(0, 0), 0), Milliseconds(300));
        heartbeatFromMember(HostAndPort("h3"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(0, 0), 0), Milliseconds(300));

        // No primary situation: should choose h2 sync source.
        getTopoCoord().chooseNewSyncSource(now()++, OpTime());
        ASSERT_EQUALS(HostAndPort("h2"), getTopoCoord().getSyncSourceAddress());

        // Become primary
        makeSelfPrimary(Timestamp(3.0));
        ASSERT_EQUALS(0, getCurrentPrimaryIndex());

        // Check sync source
        ASSERT_EQUALS(HostAndPort(), getTopoCoord().getSyncSourceAddress());
    }

    TEST_F(TopoCoordTest, ForceSyncSource) {
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 1 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 10 << "host" << "hself") <<
                              BSON("_id" << 20 << "host" << "h2") <<
                              BSON("_id" << 30 << "host" << "h3"))),
                     0);

        setSelfMemberState(MemberState::RS_SECONDARY);

        // two rounds of heartbeat pings from each member
        heartbeatFromMember(HostAndPort("h2"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(1, 0), 0), Milliseconds(300));
        heartbeatFromMember(HostAndPort("h2"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(1, 0), 0), Milliseconds(300));
        heartbeatFromMember(HostAndPort("h3"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(2, 0), 0), Milliseconds(100));
        heartbeatFromMember(HostAndPort("h3"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(2, 0), 0), Milliseconds(100));

        // force should overrule other defaults
        getTopoCoord().chooseNewSyncSource(now()++, OpTime());
        ASSERT_EQUALS(HostAndPort("h3"), getTopoCoord().getSyncSourceAddress());
        getTopoCoord().setForceSyncSourceIndex(1);
        // force should cause shouldChangeSyncSource() to return true
        // even if the currentSource is the force target
        ASSERT_TRUE(getTopoCoord().shouldChangeSyncSource(HostAndPort("h2"), now()));
        ASSERT_TRUE(getTopoCoord().shouldChangeSyncSource(HostAndPort("h3"), now()));
        getTopoCoord().chooseNewSyncSource(now()++, OpTime());
        ASSERT_EQUALS(HostAndPort("h2"), getTopoCoord().getSyncSourceAddress());

        // force should only work for one call to chooseNewSyncSource
        getTopoCoord().chooseNewSyncSource(now()++, OpTime());
        ASSERT_EQUALS(HostAndPort("h3"), getTopoCoord().getSyncSourceAddress());
    }

    TEST_F(TopoCoordTest, BlacklistSyncSource) {
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 1 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 10 << "host" << "hself") <<
                              BSON("_id" << 20 << "host" << "h2") <<
                              BSON("_id" << 30 << "host" << "h3"))),
                     0);

        setSelfMemberState(MemberState::RS_SECONDARY);

        heartbeatFromMember(HostAndPort("h2"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(1, 0), 0), Milliseconds(300));
        heartbeatFromMember(HostAndPort("h2"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(1, 0), 0), Milliseconds(300));
        heartbeatFromMember(HostAndPort("h3"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(2, 0), 0), Milliseconds(100));
        heartbeatFromMember(HostAndPort("h3"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(2, 0), 0), Milliseconds(100));

        getTopoCoord().chooseNewSyncSource(now()++, OpTime());
        ASSERT_EQUALS(HostAndPort("h3"), getTopoCoord().getSyncSourceAddress());

        Date_t expireTime = Date_t::fromMillisSinceEpoch(1000);
        getTopoCoord().blacklistSyncSource(HostAndPort("h3"), expireTime);
        getTopoCoord().chooseNewSyncSource(now()++, OpTime());
        // Should choose second best choice now that h3 is blacklisted.
        ASSERT_EQUALS(HostAndPort("h2"), getTopoCoord().getSyncSourceAddress());

        // After time has passed, should go back to original sync source
        getTopoCoord().chooseNewSyncSource(expireTime, OpTime());
        ASSERT_EQUALS(HostAndPort("h3"), getTopoCoord().getSyncSourceAddress());
    }

    TEST_F(TopoCoordTest, BlacklistSyncSourceNoChaining) {
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 1 <<
                          "settings" << BSON("chainingAllowed" << false) <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 10 << "host" << "hself") <<
                              BSON("_id" << 20 << "host" << "h2") <<
                              BSON("_id" << 30 << "host" << "h3"))),
                     0);

        setSelfMemberState(MemberState::RS_SECONDARY);

        heartbeatFromMember(HostAndPort("h2"), "rs0", MemberState::RS_PRIMARY,
                            OpTime(Timestamp(2, 0), 0), Milliseconds(100));
        heartbeatFromMember(HostAndPort("h2"), "rs0", MemberState::RS_PRIMARY,
                            OpTime(Timestamp(2, 0), 0), Milliseconds(100));
        ASSERT_EQUALS(1, getCurrentPrimaryIndex());

        heartbeatFromMember(HostAndPort("h3"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(2, 0), 0), Milliseconds(100));
        heartbeatFromMember(HostAndPort("h3"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(2, 0), 0), Milliseconds(100));

        getTopoCoord().chooseNewSyncSource(now()++, OpTime());
        ASSERT_EQUALS(HostAndPort("h2"), getTopoCoord().getSyncSourceAddress());

        Date_t expireTime = Date_t::fromMillisSinceEpoch(1000);
        getTopoCoord().blacklistSyncSource(HostAndPort("h2"), expireTime);
        getTopoCoord().chooseNewSyncSource(now()++, OpTime());
        // Can't choose any sync source now.
        ASSERT(getTopoCoord().getSyncSourceAddress().empty());

        // After time has passed, should go back to the primary
        getTopoCoord().chooseNewSyncSource(expireTime, OpTime());
        ASSERT_EQUALS(HostAndPort("h2"), getTopoCoord().getSyncSourceAddress());
    }

    TEST_F(TopoCoordTest, OnlyUnauthorizedUpCausesRecovering) {
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 1 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 10 << "host" << "hself") <<
                              BSON("_id" << 20 << "host" << "h2") <<
                              BSON("_id" << 30 << "host" << "h3"))),
                     0);

        setSelfMemberState(MemberState::RS_SECONDARY);

        // Generate enough heartbeats to select a sync source below
        heartbeatFromMember(HostAndPort("h2"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(1, 0), 0), Milliseconds(300));
        heartbeatFromMember(HostAndPort("h2"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(1, 0), 0), Milliseconds(300));
        heartbeatFromMember(HostAndPort("h3"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(2, 0), 0), Milliseconds(100));
        heartbeatFromMember(HostAndPort("h3"), "rs0", MemberState::RS_SECONDARY,
                            OpTime(Timestamp(2, 0), 0), Milliseconds(100));

        ASSERT_EQUALS(HostAndPort("h3"),
                      getTopoCoord().chooseNewSyncSource(now()++, OpTime()));
        ASSERT_EQUALS(MemberState::RS_SECONDARY, getTopoCoord().getMemberState().s);
        // Good state setup done

        // Mark nodes down, ensure that we have no source and are secondary
        receiveDownHeartbeat(HostAndPort("h2"), "rs0", OpTime(), ErrorCodes::NetworkTimeout);
        receiveDownHeartbeat(HostAndPort("h3"), "rs0", OpTime(), ErrorCodes::NetworkTimeout);
        ASSERT_TRUE(getTopoCoord().chooseNewSyncSource(now()++, OpTime()).empty());
        ASSERT_EQUALS(MemberState::RS_SECONDARY, getTopoCoord().getMemberState().s);

        // Mark nodes down + unauth, ensure that we have no source and are secondary
        receiveDownHeartbeat(HostAndPort("h2"), "rs0", OpTime(), ErrorCodes::NetworkTimeout);
        receiveDownHeartbeat(HostAndPort("h3"), "rs0", OpTime(), ErrorCodes::Unauthorized);
        ASSERT_TRUE(getTopoCoord().chooseNewSyncSource(now()++, OpTime()).empty());
        ASSERT_EQUALS(MemberState::RS_RECOVERING, getTopoCoord().getMemberState().s);

        // Having an auth error but with another node up should bring us out of RECOVERING
        HeartbeatResponseAction action = receiveUpHeartbeat(HostAndPort("h2"),
                                                            "rs0",
                                                            MemberState::RS_SECONDARY,
                                                            OpTime(),
                                                            OpTime(Timestamp(2, 0), 0),
                                                            OpTime(Timestamp(2, 0), 0));
        ASSERT_EQUALS(MemberState::RS_SECONDARY, getTopoCoord().getMemberState().s);
        // Test that the heartbeat that brings us from RECOVERING to SECONDARY doesn't initiate
        // an election (SERVER-17164)
        ASSERT_NO_ACTION(action.getAction());
    }

    TEST_F(TopoCoordTest, ReceiveHeartbeatWhileAbsentFromConfig) {
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 1 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 10 << "host" << "h1") <<
                              BSON("_id" << 20 << "host" << "h2") <<
                              BSON("_id" << 30 << "host" << "h3"))),
                     -1);
        ASSERT_NO_ACTION(heartbeatFromMember(HostAndPort("h2"), "rs0", MemberState::RS_SECONDARY,
                                      OpTime(Timestamp(1, 0), 0), Milliseconds(300)).getAction());
    }

    TEST_F(TopoCoordTest, PrepareSyncFromResponse) {
        OpTime staleOpTime(Timestamp(1, 1), 0);
        OpTime ourOpTime(Timestamp(staleOpTime.getSecs() + 11, 1), 0);
         
        Status result = Status::OK();
        BSONObjBuilder response;

        // if we do not have an index in the config, we should get ErrorCodes::NotSecondary
        getTopoCoord().prepareSyncFromResponse(cbData(), HostAndPort("h1"),
                                               ourOpTime, &response, &result);
        ASSERT_EQUALS(ErrorCodes::NotSecondary, result);
        ASSERT_EQUALS("Removed and uninitialized nodes do not sync", result.reason());

        // Test trying to sync from another node when we are an arbiter
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 1 <<
                          "members" << BSON_ARRAY(BSON("_id" << 0 <<
                                                       "host" << "hself" <<
                                                       "arbiterOnly" << true) <<
                                                  BSON("_id" << 1 <<
                                                       "host" << "h1"))),
                     0);

        getTopoCoord().prepareSyncFromResponse(cbData(), HostAndPort("h1"),
                                               ourOpTime, &response, &result);
        ASSERT_EQUALS(ErrorCodes::NotSecondary, result);
        ASSERT_EQUALS("arbiters don't sync", result.reason());

        // Set up config for the rest of the tests
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 1 <<
                          "members" << BSON_ARRAY(
                                  BSON("_id" << 0 << "host" << "hself") <<
                                  BSON("_id" << 1 << "host" << "h1" << "arbiterOnly" << true) <<
                                  BSON("_id" << 2 << "host" << "h2" <<
                                       "priority" << 0 << "buildIndexes" << false) <<
                                  BSON("_id" << 3 << "host" << "h3") <<
                                  BSON("_id" << 4 << "host" << "h4") <<
                                  BSON("_id" << 5 << "host" << "h5") <<
                                  BSON("_id" << 6 << "host" << "h6"))),
                     0);

        // Try to sync while PRIMARY
        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        makeSelfPrimary();
        ASSERT_EQUALS(0, getCurrentPrimaryIndex());
        getTopoCoord()._setCurrentPrimaryForTest(0);
        BSONObjBuilder response1;
        getTopoCoord().prepareSyncFromResponse(
                cbData(), HostAndPort("h3"), ourOpTime, &response1, &result);
        ASSERT_EQUALS(ErrorCodes::NotSecondary, result);
        ASSERT_EQUALS("primaries don't sync", result.reason());
        ASSERT_EQUALS("h3:27017", response1.obj()["syncFromRequested"].String());

        // Try to sync from non-existent member
        setSelfMemberState(MemberState::RS_SECONDARY);
        getTopoCoord()._setCurrentPrimaryForTest(-1);
        BSONObjBuilder response2;
        getTopoCoord().prepareSyncFromResponse(
                cbData(), HostAndPort("fakemember"), ourOpTime, &response2, &result);
        ASSERT_EQUALS(ErrorCodes::NodeNotFound, result);
        ASSERT_EQUALS("Could not find member \"fakemember:27017\" in replica set", result.reason());

        // Try to sync from self
        BSONObjBuilder response3;
        getTopoCoord().prepareSyncFromResponse(
                cbData(), HostAndPort("hself"), ourOpTime, &response3, &result);
        ASSERT_EQUALS(ErrorCodes::InvalidOptions, result);
        ASSERT_EQUALS("I cannot sync from myself", result.reason());

        // Try to sync from an arbiter
        BSONObjBuilder response4;
        getTopoCoord().prepareSyncFromResponse(
                cbData(), HostAndPort("h1"), ourOpTime, &response4, &result);
        ASSERT_EQUALS(ErrorCodes::InvalidOptions, result);
        ASSERT_EQUALS("Cannot sync from \"h1:27017\" because it is an arbiter", result.reason());

        // Try to sync from a node that doesn't build indexes
        BSONObjBuilder response5;
        getTopoCoord().prepareSyncFromResponse(
                cbData(), HostAndPort("h2"), ourOpTime, &response5, &result);
        ASSERT_EQUALS(ErrorCodes::InvalidOptions, result);
        ASSERT_EQUALS("Cannot sync from \"h2:27017\" because it does not build indexes",
                      result.reason());

        // Try to sync from a member that is down
        receiveDownHeartbeat(HostAndPort("h4"), "rs0", OpTime());

        BSONObjBuilder response7;
        getTopoCoord().prepareSyncFromResponse(
                cbData(), HostAndPort("h4"), ourOpTime, &response7, &result);
        ASSERT_EQUALS(ErrorCodes::HostUnreachable, result);
        ASSERT_EQUALS("I cannot reach the requested member: h4:27017", result.reason());

        // Sync successfully from a member that is stale
        heartbeatFromMember(HostAndPort("h5"), "rs0", MemberState::RS_SECONDARY,
                            staleOpTime, Milliseconds(100));

        BSONObjBuilder response8;
        getTopoCoord().prepareSyncFromResponse(
                cbData(), HostAndPort("h5"), ourOpTime, &response8, &result);
        ASSERT_OK(result);
        ASSERT_EQUALS("requested member \"h5:27017\" is more than 10 seconds behind us",
                      response8.obj()["warning"].String());
        getTopoCoord().chooseNewSyncSource(now()++, ourOpTime);
        ASSERT_EQUALS(HostAndPort("h5"), getTopoCoord().getSyncSourceAddress());

        // Sync successfully from an up-to-date member
        heartbeatFromMember(HostAndPort("h6"), "rs0", MemberState::RS_SECONDARY,
                            ourOpTime, Milliseconds(100));

        BSONObjBuilder response9;
        getTopoCoord().prepareSyncFromResponse(
                cbData(), HostAndPort("h6"), ourOpTime, &response9, &result);
        ASSERT_OK(result);
        BSONObj response9Obj = response9.obj();
        ASSERT_FALSE(response9Obj.hasField("warning"));
        ASSERT_EQUALS(HostAndPort("h5").toString(), response9Obj["prevSyncTarget"].String());
        getTopoCoord().chooseNewSyncSource(now()++, ourOpTime);
        ASSERT_EQUALS(HostAndPort("h6"), getTopoCoord().getSyncSourceAddress());

        // node goes down between forceSync and chooseNewSyncSource
        BSONObjBuilder response10;
        getTopoCoord().prepareSyncFromResponse(
                cbData(), HostAndPort("h6"), ourOpTime, &response10, &result);
        BSONObj response10Obj = response10.obj();
        ASSERT_FALSE(response10Obj.hasField("warning"));
        ASSERT_EQUALS(HostAndPort("h6").toString(), response10Obj["prevSyncTarget"].String());
        receiveDownHeartbeat(HostAndPort("h6"), "rs0", OpTime());
        HostAndPort syncSource = getTopoCoord().chooseNewSyncSource(now()++, OpTime());
        ASSERT_EQUALS(HostAndPort("h6"), syncSource);

        // Try to sync from a member that is unauth'd
        receiveDownHeartbeat(HostAndPort("h5"), "rs0", OpTime(), ErrorCodes::Unauthorized);

        BSONObjBuilder response11;
        getTopoCoord().prepareSyncFromResponse(
                cbData(), HostAndPort("h5"), ourOpTime, &response11, &result);
        ASSERT_NOT_OK(result);
        ASSERT_EQUALS(ErrorCodes::Unauthorized, result.code());
        ASSERT_EQUALS("not authorized to communicate with h5:27017",
                      result.reason());

        // Sync successfully from an up-to-date member.
        heartbeatFromMember(HostAndPort("h6"), "rs0", MemberState::RS_SECONDARY,
                            ourOpTime, Milliseconds(100));
        BSONObjBuilder response12;
        getTopoCoord().prepareSyncFromResponse(
                cbData(), HostAndPort("h6"), ourOpTime, &response12, &result);
        ASSERT_OK(result);
        syncSource = getTopoCoord().chooseNewSyncSource(now()++, OpTime());
        ASSERT_EQUALS(HostAndPort("h6"), syncSource);
    }

    TEST_F(TopoCoordTest, ReplSetGetStatus) {
        // This test starts by configuring a TopologyCoordinator as a member of a 4 node replica
        // set, with each node in a different state.
        // The first node is DOWN, as if we tried heartbeating them and it failed in some way.
        // The second node is in state SECONDARY, as if we've received a valid heartbeat from them.
        // The third node is in state UNKNOWN, as if we've not yet had any heartbeating activity
        // with them yet.  The fourth node is PRIMARY and corresponds to ourself, which gets its
        // information for replSetGetStatus from a different source than the nodes that aren't
        // ourself.  After this setup, we call prepareStatusResponse and make sure that the fields
        // returned for each member match our expectations.
        Date_t startupTime = Date_t::fromMillisSinceEpoch(100);
        Date_t heartbeatTime = Date_t::fromMillisSinceEpoch(5000);
        Seconds uptimeSecs(10);
        Date_t curTime = heartbeatTime + uptimeSecs;
        Timestamp electionTime(1, 2);
        OpTime oplogProgress(Timestamp(3, 4), 0);
        std::string setName = "mySet";

        ReplSetHeartbeatResponse hb;
        hb.setConfigVersion(1);
        hb.setState(MemberState::RS_SECONDARY);
        hb.setElectionTime(electionTime);
        hb.setHbMsg("READY");
        hb.setOpTime(oplogProgress);
        StatusWith<ReplSetHeartbeatResponse> hbResponseGood =
            StatusWith<ReplSetHeartbeatResponse>(hb);

        updateConfig(BSON("_id" << setName <<
                          "version" << 1 <<
                          "members" << BSON_ARRAY(BSON("_id" << 0 << "host" << "test0:1234") <<
                                                  BSON("_id" << 1 << "host" << "test1:1234") <<
                                                  BSON("_id" << 2 << "host" << "test2:1234") <<
                                                  BSON("_id" << 3 << "host" << "test3:1234"))),
                     3,
                     startupTime + Milliseconds(1));

        // Now that the replica set is setup, put the members into the states we want them in.
        HostAndPort member = HostAndPort("test0:1234");
        getTopoCoord().prepareHeartbeatRequest(startupTime + Milliseconds(1), setName, member);
        getTopoCoord().processHeartbeatResponse(startupTime + Milliseconds(2),
                                                Milliseconds(1),
                                                member,
                                                hbResponseGood,
                                                OpTime());
        getTopoCoord().prepareHeartbeatRequest(startupTime + Milliseconds(3), setName, member);
        Date_t timeoutTime = startupTime + Milliseconds(3) +
            ReplicaSetConfig::kDefaultHeartbeatTimeoutPeriod;

        StatusWith<ReplSetHeartbeatResponse> hbResponseDown =
                StatusWith<ReplSetHeartbeatResponse>(Status(ErrorCodes::HostUnreachable, ""));

        getTopoCoord().processHeartbeatResponse(timeoutTime,
                                                Milliseconds(5000),
                                                member,
                                                hbResponseDown,
                                                OpTime());

        member = HostAndPort("test1:1234");
        getTopoCoord().prepareHeartbeatRequest(startupTime + Milliseconds(2),
                                               setName,
                                               member);
        getTopoCoord().processHeartbeatResponse(heartbeatTime,
                                                Milliseconds(4000),
                                                member,
                                                hbResponseGood,
                                                OpTime());
        makeSelfPrimary();

        // Now node 0 is down, node 1 is up, and for node 2 we have no heartbeat data yet.
        BSONObjBuilder statusBuilder;
        Status resultStatus(ErrorCodes::InternalError, "prepareStatusResponse didn't set result");
        getTopoCoord().prepareStatusResponse(cbData(),
                                             curTime,
                                             uptimeSecs.count(),
                                             oplogProgress,
                                             &statusBuilder,
                                             &resultStatus);
        ASSERT_OK(resultStatus);
        BSONObj rsStatus = statusBuilder.obj();

        // Test results for all non-self members
        ASSERT_EQUALS(setName, rsStatus["set"].String());
        ASSERT_EQUALS(curTime.asInt64(), rsStatus["date"].Date().asInt64());
        std::vector<BSONElement> memberArray = rsStatus["members"].Array();
        ASSERT_EQUALS(4U, memberArray.size());
        BSONObj member0Status = memberArray[0].Obj();
        BSONObj member1Status = memberArray[1].Obj();
        BSONObj member2Status = memberArray[2].Obj();

        // Test member 0, the node that's DOWN
        ASSERT_EQUALS(0, member0Status["_id"].numberInt());
        ASSERT_EQUALS("test0:1234", member0Status["name"].str());
        ASSERT_EQUALS(0, member0Status["health"].numberDouble());
        ASSERT_EQUALS(MemberState::RS_DOWN, member0Status["state"].numberInt());
        ASSERT_EQUALS("(not reachable/healthy)", member0Status["stateStr"].str());
        ASSERT_EQUALS(0, member0Status["uptime"].numberInt());
        ASSERT_EQUALS(Timestamp(), Timestamp(member0Status["optime"]["ts"].timestampValue()));
        ASSERT_TRUE(member0Status.hasField("optimeDate"));
        ASSERT_EQUALS(Date_t::fromMillisSinceEpoch(Timestamp().getSecs() * 1000ULL),
                      member0Status["optimeDate"].Date());
        ASSERT_EQUALS(timeoutTime, member0Status["lastHeartbeat"].date());
        ASSERT_EQUALS(Date_t(), member0Status["lastHeartbeatRecv"].date());

        // Test member 1, the node that's SECONDARY
        ASSERT_EQUALS(1, member1Status["_id"].Int());
        ASSERT_EQUALS("test1:1234", member1Status["name"].String());
        ASSERT_EQUALS(1, member1Status["health"].Double());
        ASSERT_EQUALS(MemberState::RS_SECONDARY, member1Status["state"].numberInt());
        ASSERT_EQUALS(MemberState(MemberState::RS_SECONDARY).toString(),
                      member1Status["stateStr"].String());
        ASSERT_EQUALS(uptimeSecs.count(), member1Status["uptime"].numberInt());
        ASSERT_EQUALS(oplogProgress.getTimestamp(),
                      Timestamp(member1Status["optime"]["ts"].timestampValue()));
        ASSERT_TRUE(member1Status.hasField("optimeDate"));
        ASSERT_EQUALS(Date_t::fromMillisSinceEpoch(oplogProgress.getSecs() * 1000ULL),
                      member1Status["optimeDate"].Date());
        ASSERT_EQUALS(heartbeatTime, member1Status["lastHeartbeat"].date());
        ASSERT_EQUALS(Date_t(), member1Status["lastHeartbeatRecv"].date());
        ASSERT_EQUALS("READY", member1Status["lastHeartbeatMessage"].str());

        // Test member 2, the node that's UNKNOWN
        ASSERT_EQUALS(2, member2Status["_id"].numberInt());
        ASSERT_EQUALS("test2:1234", member2Status["name"].str());
        ASSERT_EQUALS(-1, member2Status["health"].numberDouble());
        ASSERT_EQUALS(MemberState::RS_UNKNOWN, member2Status["state"].numberInt());
        ASSERT_EQUALS(MemberState(MemberState::RS_UNKNOWN).toString(),
                      member2Status["stateStr"].str());
        ASSERT_TRUE(member2Status.hasField("uptime"));
        ASSERT_TRUE(member2Status.hasField("optime"));
        ASSERT_TRUE(member2Status.hasField("optimeDate"));
        ASSERT_FALSE(member2Status.hasField("lastHearbeat"));
        ASSERT_FALSE(member2Status.hasField("lastHearbeatRecv"));

        // Now test results for ourself, the PRIMARY
        ASSERT_EQUALS(MemberState::RS_PRIMARY, rsStatus["myState"].numberInt());
        BSONObj selfStatus = memberArray[3].Obj();
        ASSERT_TRUE(selfStatus["self"].boolean());
        ASSERT_EQUALS(3, selfStatus["_id"].numberInt());
        ASSERT_EQUALS("test3:1234", selfStatus["name"].str());
        ASSERT_EQUALS(1, selfStatus["health"].numberDouble());
        ASSERT_EQUALS(MemberState::RS_PRIMARY, selfStatus["state"].numberInt());
        ASSERT_EQUALS(MemberState(MemberState::RS_PRIMARY).toString(),
                      selfStatus["stateStr"].str());
        ASSERT_EQUALS(uptimeSecs.count(), selfStatus["uptime"].numberInt());
        ASSERT_EQUALS(oplogProgress.getTimestamp(),
                      Timestamp(selfStatus["optime"]["ts"].timestampValue()));
        ASSERT_TRUE(selfStatus.hasField("optimeDate"));
        ASSERT_EQUALS(Date_t::fromMillisSinceEpoch(oplogProgress.getSecs() * 1000ULL),
                      selfStatus["optimeDate"].Date());

        // TODO(spencer): Test electionTime and pingMs are set properly
    }

    TEST_F(TopoCoordTest, ReplSetGetStatusFails) {
        // This test starts by configuring a TopologyCoordinator to NOT be a member of a 3 node
        // replica set. Then running prepareStatusResponse should fail.
        Date_t startupTime = Date_t::fromMillisSinceEpoch(100);
        Date_t heartbeatTime = Date_t::fromMillisSinceEpoch(5000);
        Seconds uptimeSecs(10);
        Date_t curTime = heartbeatTime + uptimeSecs;
        OpTime oplogProgress(Timestamp(3, 4), 0);
        std::string setName = "mySet";

        updateConfig(BSON("_id" << setName <<
                          "version" << 1 <<
                          "members" << BSON_ARRAY(BSON("_id" << 0 << "host" << "test0:1234") <<
                                                  BSON("_id" << 1 << "host" << "test1:1234") <<
                                                  BSON("_id" << 2 << "host" << "test2:1234"))),
                     -1,  // This one is not part of the replica set.
                     startupTime + Milliseconds(1));

        BSONObjBuilder statusBuilder;
        Status resultStatus(ErrorCodes::InternalError, "prepareStatusResponse didn't set result");
        getTopoCoord().prepareStatusResponse(cbData(),
                                             curTime,
                                             uptimeSecs.count(),
                                             oplogProgress,
                                             &statusBuilder,
                                             &resultStatus);
        ASSERT_NOT_OK(resultStatus);
        ASSERT_EQUALS(ErrorCodes::InvalidReplicaSetConfig, resultStatus);
    }

    TEST_F(TopoCoordTest, PrepareFreshResponse) {
        ReplicationCoordinator::ReplSetFreshArgs args;
        OpTime freshestOpTime(Timestamp(15, 10), 0);
        OpTime ourOpTime(Timestamp(10, 10), 0);
        OpTime staleOpTime(Timestamp(1, 1), 0);
        Status internalErrorStatus(ErrorCodes::InternalError, "didn't set status");

        // if we do not have an index in the config, we should get ErrorCodes::ReplicaSetNotFound
        BSONObjBuilder responseBuilder;
        Status status = internalErrorStatus;
        getTopoCoord().prepareFreshResponse(args, Date_t(), ourOpTime, &responseBuilder, &status);
        ASSERT_EQUALS(ErrorCodes::ReplicaSetNotFound, status);
        ASSERT_EQUALS("Cannot participate in elections because not initialized", status.reason());
        ASSERT_TRUE(responseBuilder.obj().isEmpty());

        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 10 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 10 <<
                                   "host" << "hself" <<
                                   "priority" << 10) <<
                              BSON("_id" << 20 << "host" << "h1") <<
                              BSON("_id" << 30 << "host" << "h2") <<
                              BSON("_id" << 40 <<
                                   "host" << "h3" <<
                                   "priority" << 10))),
                     0);

        // Test with incorrect replset name
        args.setName = "fakeset";

        BSONObjBuilder responseBuilder0;
        Status status0 = internalErrorStatus;
        getTopoCoord().prepareFreshResponse(args, Date_t(), ourOpTime, &responseBuilder0, &status0);
        ASSERT_EQUALS(ErrorCodes::ReplicaSetNotFound, status0);
        ASSERT_TRUE(responseBuilder0.obj().isEmpty());

        heartbeatFromMember(HostAndPort("h1"), "rs0", MemberState::RS_SECONDARY, ourOpTime);

        // Test with old config version
        args.setName = "rs0";
        args.cfgver = 5;
        args.id = 20;
        args.who = HostAndPort("h1");
        args.opTime = ourOpTime.getTimestamp();

        BSONObjBuilder responseBuilder1;
        Status status1 = internalErrorStatus;
        getTopoCoord().prepareFreshResponse(args, Date_t(), ourOpTime, &responseBuilder1, &status1);
        ASSERT_OK(status1);
        BSONObj response1 = responseBuilder1.obj();
        ASSERT_EQUALS("config version stale", response1["info"].String());
        ASSERT_EQUALS(ourOpTime.getTimestamp(), Timestamp(response1["opTime"].timestampValue()));
        ASSERT_TRUE(response1["fresher"].Bool());
        ASSERT_FALSE(response1["veto"].Bool());
        ASSERT_FALSE(response1.hasField("errmsg"));

        // Test with non-existent node.
        args.cfgver = 10;
        args.id = 0;
        args.who = HostAndPort("fakenode");

        BSONObjBuilder responseBuilder2;
        Status status2 = internalErrorStatus;
        getTopoCoord().prepareFreshResponse(args, Date_t(), ourOpTime, &responseBuilder2, &status2);
        ASSERT_OK(status2);
        BSONObj response2 = responseBuilder2.obj();
        ASSERT_EQUALS(ourOpTime.getTimestamp(), Timestamp(response2["opTime"].timestampValue()));
        ASSERT_FALSE(response2["fresher"].Bool());
        ASSERT_TRUE(response2["veto"].Bool());
        ASSERT_EQUALS("replSet couldn't find member with id 0", response2["errmsg"].String());


        // Test when we are primary.
        args.id = 20;
        args.who = HostAndPort("h1");

        makeSelfPrimary();

        BSONObjBuilder responseBuilder3;
        Status status3 = internalErrorStatus;
        getTopoCoord().prepareFreshResponse(args, Date_t(), ourOpTime, &responseBuilder3, &status3);
        ASSERT_OK(status3);
        BSONObj response3 = responseBuilder3.obj();
        ASSERT_FALSE(response3.hasField("info"));
        ASSERT_EQUALS(ourOpTime.getTimestamp(), Timestamp(response3["opTime"].timestampValue()));
        ASSERT_FALSE(response3["fresher"].Bool());
        ASSERT_TRUE(response3["veto"].Bool());
        ASSERT_EQUALS("I am already primary, h1:27017 can try again once I've stepped down",
                      response3["errmsg"].String());


        // Test when someone else is primary.
        heartbeatFromMember(HostAndPort("h2"), "rs0", MemberState::RS_SECONDARY, ourOpTime);
        setSelfMemberState(MemberState::RS_SECONDARY);
        getTopoCoord()._setCurrentPrimaryForTest(2);

        BSONObjBuilder responseBuilder4;
        Status status4 = internalErrorStatus;
        getTopoCoord().prepareFreshResponse(args, Date_t(), ourOpTime, &responseBuilder4, &status4);
        ASSERT_OK(status4);
        BSONObj response4 = responseBuilder4.obj();
        ASSERT_FALSE(response4.hasField("info"));
        ASSERT_EQUALS(ourOpTime.getTimestamp(), Timestamp(response4["opTime"].timestampValue()));
        ASSERT_FALSE(response4["fresher"].Bool());
        ASSERT_TRUE(response4["veto"].Bool());
        ASSERT_EQUALS(
                "h1:27017 is trying to elect itself but h2:27017 is already primary and more "
                        "up-to-date",
                response4["errmsg"].String());


        // Test trying to elect a node that is caught up but isn't the highest priority node.
        heartbeatFromMember(HostAndPort("h1"), "rs0", MemberState::RS_SECONDARY, ourOpTime);
        heartbeatFromMember(HostAndPort("h2"), "rs0", MemberState::RS_SECONDARY, staleOpTime);
        heartbeatFromMember(HostAndPort("h3"), "rs0", MemberState::RS_SECONDARY, ourOpTime);

        BSONObjBuilder responseBuilder5;
        Status status5 = internalErrorStatus;
        getTopoCoord().prepareFreshResponse(args, Date_t(), ourOpTime, &responseBuilder5, &status5);
        ASSERT_OK(status5);
        BSONObj response5 = responseBuilder5.obj();
        ASSERT_FALSE(response5.hasField("info"));
        ASSERT_EQUALS(ourOpTime.getTimestamp(), Timestamp(response5["opTime"].timestampValue()));
        ASSERT_FALSE(response5["fresher"].Bool());
        ASSERT_TRUE(response5["veto"].Bool());
        ASSERT(response5["errmsg"].String().find("h1:27017 has lower priority of 1 than") !=
               std::string::npos) << response5["errmsg"].String();

        // Test trying to elect a node that isn't electable because its down
        args.id = 40;
        args.who = HostAndPort("h3");

        receiveDownHeartbeat(HostAndPort("h3"), "rs0", OpTime());

        BSONObjBuilder responseBuilder6;
        Status status6 = internalErrorStatus;
        getTopoCoord().prepareFreshResponse(args, Date_t(), ourOpTime, &responseBuilder6, &status6);
        ASSERT_OK(status6);
        BSONObj response6 = responseBuilder6.obj();
        ASSERT_FALSE(response6.hasField("info"));
        ASSERT_EQUALS(ourOpTime.getTimestamp(), Timestamp(response6["opTime"].timestampValue()));
        ASSERT_FALSE(response6["fresher"].Bool());
        ASSERT_TRUE(response6["veto"].Bool());
        ASSERT_NE(std::string::npos, response6["errmsg"].String().find(
                          "I don't think h3:27017 is electable because the member is not "
                          "currently a secondary")) << response6["errmsg"].String();

        // Test trying to elect a node that isn't electable because it's PRIMARY
        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        heartbeatFromMember(HostAndPort("h3"), "rs0", MemberState::RS_PRIMARY, ourOpTime);
        ASSERT_EQUALS(3, getCurrentPrimaryIndex());

        BSONObjBuilder responseBuilder7;
        Status status7 = internalErrorStatus;
        getTopoCoord().prepareFreshResponse(args, Date_t(), ourOpTime, &responseBuilder7, &status7);
        ASSERT_OK(status7);
        BSONObj response7 = responseBuilder7.obj();
        ASSERT_FALSE(response7.hasField("info"));
        ASSERT_EQUALS(ourOpTime.getTimestamp(), Timestamp(response7["opTime"].timestampValue()));
        ASSERT_FALSE(response7["fresher"].Bool());
        ASSERT_TRUE(response7["veto"].Bool());
        ASSERT_NE(std::string::npos, response7["errmsg"].String().find(
                          "I don't think h3:27017 is electable because the member is not "
                          "currently a secondary")) << response7["errmsg"].String();

        // Test trying to elect a node that isn't electable because it's STARTUP
        heartbeatFromMember(HostAndPort("h3"), "rs0", MemberState::RS_STARTUP, ourOpTime);

        BSONObjBuilder responseBuilder8;
        Status status8 = internalErrorStatus;
        getTopoCoord().prepareFreshResponse(args, Date_t(), ourOpTime, &responseBuilder8, &status8);
        ASSERT_OK(status8);
        BSONObj response8 = responseBuilder8.obj();
        ASSERT_FALSE(response8.hasField("info"));
        ASSERT_EQUALS(ourOpTime.getTimestamp(), Timestamp(response8["opTime"].timestampValue()));
        ASSERT_FALSE(response8["fresher"].Bool());
        ASSERT_TRUE(response8["veto"].Bool());
        ASSERT_NE(std::string::npos, response8["errmsg"].String().find(
                          "I don't think h3:27017 is electable because the member is not "
                          "currently a secondary")) << response8["errmsg"].String();

        // Test trying to elect a node that isn't electable because it's RECOVERING
        heartbeatFromMember(HostAndPort("h3"), "rs0", MemberState::RS_RECOVERING, ourOpTime);

        BSONObjBuilder responseBuilder9;
        Status status9 = internalErrorStatus;
        getTopoCoord().prepareFreshResponse(args, Date_t(), ourOpTime, &responseBuilder9, &status9);
        ASSERT_OK(status9);
        BSONObj response9 = responseBuilder9.obj();
        ASSERT_FALSE(response9.hasField("info"));
        ASSERT_EQUALS(ourOpTime.getTimestamp(), Timestamp(response9["opTime"].timestampValue()));
        ASSERT_FALSE(response9["fresher"].Bool());
        ASSERT_TRUE(response9["veto"].Bool());
        ASSERT_NE(std::string::npos, response9["errmsg"].String().find(
                          "I don't think h3:27017 is electable because the member is not "
                          "currently a secondary")) << response9["errmsg"].String();

        // Test trying to elect a node that is fresher but lower priority than the existing primary
        args.id = 30;
        args.who = HostAndPort("h2");

        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        heartbeatFromMember(HostAndPort("h3"), "rs0", MemberState::RS_PRIMARY, ourOpTime);
        ASSERT_EQUALS(3, getCurrentPrimaryIndex());
        heartbeatFromMember(HostAndPort("h2"), "rs0", MemberState::RS_SECONDARY, freshestOpTime);

        BSONObjBuilder responseBuilder10;
        Status status10 = internalErrorStatus;
        getTopoCoord().prepareFreshResponse(args, Date_t(), ourOpTime, &responseBuilder10, &status10);
        ASSERT_OK(status10);
        BSONObj response10 = responseBuilder10.obj();
        ASSERT_FALSE(response10.hasField("info"));
        ASSERT_EQUALS(ourOpTime.getTimestamp(), Timestamp(response10["opTime"].timestampValue()));
        ASSERT_TRUE(response10["fresher"].Bool());
        ASSERT_TRUE(response10["veto"].Bool());
        ASSERT_TRUE(response10.hasField("errmsg"));


        // Test trying to elect a valid node
        args.id = 40;
        args.who = HostAndPort("h3");

        receiveDownHeartbeat(HostAndPort("h2"), "rs0", OpTime());
        heartbeatFromMember(HostAndPort("h3"), "rs0", MemberState::RS_SECONDARY, ourOpTime);

        BSONObjBuilder responseBuilder11;
        Status status11 = internalErrorStatus;
        getTopoCoord().prepareFreshResponse(
                args, Date_t(), ourOpTime, &responseBuilder11, &status11);
        ASSERT_OK(status11);
        BSONObj response11 = responseBuilder11.obj();
        ASSERT_FALSE(response11.hasField("info")) << response11.toString();
        ASSERT_EQUALS(ourOpTime.getTimestamp(), Timestamp(response11["opTime"].timestampValue()));
        ASSERT_FALSE(response11["fresher"].Bool()) << response11.toString();
        ASSERT_FALSE(response11["veto"].Bool()) << response11.toString();
        ASSERT_FALSE(response11.hasField("errmsg")) << response11.toString();

        // Test with our id
        args.id = 10;
        BSONObjBuilder responseBuilder12;
        Status status12 = internalErrorStatus;
        getTopoCoord().prepareFreshResponse(
                args, Date_t(), ourOpTime, &responseBuilder12, &status12);
        ASSERT_EQUALS(ErrorCodes::BadValue, status12);
        ASSERT_EQUALS(
                "Received replSetFresh command from member with the same member ID as ourself: 10",
                status12.reason());
        ASSERT_TRUE(responseBuilder12.obj().isEmpty());

    }

    class HeartbeatResponseTest : public TopoCoordTest {
    public:

        virtual void setUp() {
            TopoCoordTest::setUp();
            updateConfig(BSON("_id" << "rs0" <<
                              "version" << 5 <<
                              "members" << BSON_ARRAY(
                                  BSON("_id" << 0 << "host" << "host1:27017") <<
                                  BSON("_id" << 1 << "host" << "host2:27017") <<
                                  BSON("_id" << 2 << "host" << "host3:27017")) <<
                              "settings" << BSON("heartbeatTimeoutSecs" << 5)),
                         0);
        }

    };

    class HeartbeatResponseTestOneRetry : public HeartbeatResponseTest {
    public:
        virtual void setUp() {
            HeartbeatResponseTest::setUp();

            // Bring up the node we are heartbeating.
            _target = HostAndPort("host2", 27017);
            Date_t _upRequestDate = unittest::assertGet(dateFromISOString("2014-08-29T12:55Z"));
            std::pair<ReplSetHeartbeatArgs, Milliseconds> uppingRequest =
                getTopoCoord().prepareHeartbeatRequest(_upRequestDate,
                                                       "rs0",
                                                       _target);
            HeartbeatResponseAction upAction =
                getTopoCoord().processHeartbeatResponse(
                        _upRequestDate,
                        Milliseconds(0),
                        _target,
                        StatusWith<ReplSetHeartbeatResponse>(Status::OK()),
                        OpTime(Timestamp(0, 0), 0));  // We've never applied anything.
            ASSERT_EQUALS(HeartbeatResponseAction::NoAction, upAction.getAction());
            ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());


            // Time of first request for this heartbeat period
            _firstRequestDate = unittest::assertGet(dateFromISOString("2014-08-29T13:00Z"));

            // Initial heartbeat attempt prepared, at t + 0.
            std::pair<ReplSetHeartbeatArgs, Milliseconds> request =
                getTopoCoord().prepareHeartbeatRequest(_firstRequestDate,
                                                       "rs0",
                                                       _target);
            // 5 seconds to successfully complete the heartbeat before the timeout expires.
            ASSERT_EQUALS(5000, request.second.count());

            // Initial heartbeat request fails at t + 4000ms
            HeartbeatResponseAction action =
                getTopoCoord().processHeartbeatResponse(
                        _firstRequestDate + Seconds(4), // 4 seconds elapsed, retry allowed.
                        Milliseconds(3990), // Spent 3.99 of the 4 seconds in the network.
                        _target,
                        StatusWith<ReplSetHeartbeatResponse>(ErrorCodes::ExceededTimeLimit,
                                                             "Took too long"),
                        OpTime(Timestamp(0, 0), 0));  // We've never applied anything.

            ASSERT_EQUALS(HeartbeatResponseAction::NoAction, action.getAction());
            ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
            // Because the heartbeat failed without timing out, we expect to retry immediately.
            ASSERT_EQUALS(_firstRequestDate + Seconds(4), action.getNextHeartbeatStartDate());

            // First heartbeat retry prepared, at t + 4000ms.
            request =
                getTopoCoord().prepareHeartbeatRequest(
                        _firstRequestDate + Milliseconds(4000),
                        "rs0",
                        _target);
            // One second left to complete the heartbeat.
            ASSERT_EQUALS(1000, request.second.count());

            // Ensure a single failed heartbeat did not cause the node to be marked down
            BSONObjBuilder statusBuilder;
            Status resultStatus(ErrorCodes::InternalError,
                                "prepareStatusResponse didn't set result");
            getTopoCoord().prepareStatusResponse(cbData(),
                                                 _firstRequestDate + Milliseconds(4000),
                                                 10,
                                                 OpTime(Timestamp(100,0), 0),
                                                 &statusBuilder,
                                                 &resultStatus);
            ASSERT_OK(resultStatus);
            BSONObj rsStatus = statusBuilder.obj();
            std::vector<BSONElement> memberArray = rsStatus["members"].Array();
            BSONObj member1Status = memberArray[1].Obj();

            ASSERT_EQUALS(1, member1Status["_id"].Int());
            ASSERT_EQUALS(1, member1Status["health"].Double());

        }

        Date_t firstRequestDate() {
            return _firstRequestDate;
        }

        HostAndPort target() {
            return _target;
        }

    private:
        Date_t _firstRequestDate;
        HostAndPort _target;

    };

    class HeartbeatResponseTestTwoRetries : public HeartbeatResponseTestOneRetry {
    public:
        virtual void setUp() {
            HeartbeatResponseTestOneRetry::setUp();
            // First retry fails at t + 4500ms
            HeartbeatResponseAction action =
                getTopoCoord().processHeartbeatResponse(
                        firstRequestDate() + Milliseconds(4500), // 4.5 of the 5 seconds elapsed;
                                                                 // could retry.
                        Milliseconds(400), // Spent 0.4 of the 0.5 seconds in the network.
                        target(),
                        StatusWith<ReplSetHeartbeatResponse>(ErrorCodes::NodeNotFound, "Bad DNS?"),
                        OpTime(Timestamp(0, 0), 0));  // We've never applied anything.
            ASSERT_EQUALS(HeartbeatResponseAction::NoAction, action.getAction());
            ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
            // Because the first retry failed without timing out, we expect to retry immediately.
            ASSERT_EQUALS(firstRequestDate() + Milliseconds(4500),
                          action.getNextHeartbeatStartDate());

            // Second retry prepared at t + 4500ms.
            std::pair<ReplSetHeartbeatArgs, Milliseconds> request =
                getTopoCoord().prepareHeartbeatRequest(
                        firstRequestDate() + Milliseconds(4500),
                        "rs0",
                        target());
            // 500ms left to complete the heartbeat.
            ASSERT_EQUALS(500, request.second.count());

            // Ensure a second failed heartbeat did not cause the node to be marked down
            BSONObjBuilder statusBuilder;
            Status resultStatus(ErrorCodes::InternalError,
                                "prepareStatusResponse didn't set result");
            getTopoCoord().prepareStatusResponse(cbData(),
                                                 firstRequestDate() + Seconds(4),
                                                 10,
                                                 OpTime(Timestamp(100,0), 0),
                                                 &statusBuilder,
                                                 &resultStatus);
            ASSERT_OK(resultStatus);
            BSONObj rsStatus = statusBuilder.obj();
            std::vector<BSONElement> memberArray = rsStatus["members"].Array();
            BSONObj member1Status = memberArray[1].Obj();

            ASSERT_EQUALS(1, member1Status["_id"].Int());
            ASSERT_EQUALS(1, member1Status["health"].Double());
        }
    };

    class HeartbeatResponseHighVerbosityTest : public HeartbeatResponseTest {
    public:

        virtual void setUp() {
            HeartbeatResponseTest::setUp();
            // set verbosity as high as the highest verbosity log message we'd like to check for
            logger::globalLogDomain()->setMinimumLoggedSeverity(logger::LogSeverity::Debug(3));
        }

        virtual void tearDown() {
            HeartbeatResponseTest::tearDown();
            logger::globalLogDomain()->setMinimumLoggedSeverity(logger::LogSeverity::Log());
        }

    };

    TEST_F(HeartbeatResponseHighVerbosityTest, UpdateHeartbeatDataNodeBelivesWeAreDown) {
        OpTime lastOpTimeApplied = OpTime(Timestamp(3,0), 0);

        // request heartbeat
        std::pair<ReplSetHeartbeatArgs, Milliseconds> request =
            getTopoCoord().prepareHeartbeatRequest(now()++, "rs0", HostAndPort("host2"));

        ReplSetHeartbeatResponse believesWeAreDownResponse;
        believesWeAreDownResponse.noteReplSet();
        believesWeAreDownResponse.setSetName("rs0");
        believesWeAreDownResponse.setState(MemberState::RS_SECONDARY);
        believesWeAreDownResponse.setElectable(true);
        believesWeAreDownResponse.noteStateDisagreement();
        startCapturingLogMessages();
        HeartbeatResponseAction action = getTopoCoord().processHeartbeatResponse(
                    now()++, // Time is left.
                    Milliseconds(400), // Spent 0.4 of the 0.5 second in the network.
                    HostAndPort("host2"),
                    StatusWith<ReplSetHeartbeatResponse>(believesWeAreDownResponse),
                    lastOpTimeApplied);
        stopCapturingLogMessages();
        ASSERT_NO_ACTION(action.getAction());
        ASSERT_EQUALS(1, countLogLinesContaining("host2:27017 thinks that we are down"));
        
    }

    TEST_F(HeartbeatResponseHighVerbosityTest, UpdateHeartbeatDataMemberNotInConfig) {
        OpTime lastOpTimeApplied = OpTime(Timestamp(3,0), 0);

        // request heartbeat
        std::pair<ReplSetHeartbeatArgs, Milliseconds> request =
            getTopoCoord().prepareHeartbeatRequest(now()++, "rs0", HostAndPort("host5"));

        ReplSetHeartbeatResponse memberMissingResponse;
        memberMissingResponse.noteReplSet();
        memberMissingResponse.setSetName("rs0");
        memberMissingResponse.setState(MemberState::RS_SECONDARY);
        memberMissingResponse.setElectable(true);
        memberMissingResponse.noteStateDisagreement();
        startCapturingLogMessages();
        HeartbeatResponseAction action = getTopoCoord().processHeartbeatResponse(
                    now()++, // Time is left.
                    Milliseconds(400), // Spent 0.4 of the 0.5 second in the network.
                    HostAndPort("host5"),
                    StatusWith<ReplSetHeartbeatResponse>(memberMissingResponse),
                    lastOpTimeApplied);
        stopCapturingLogMessages();
        ASSERT_NO_ACTION(action.getAction());
        ASSERT_EQUALS(1, countLogLinesContaining("Could not find host5:27017 in current config"));
    }

    TEST_F(HeartbeatResponseHighVerbosityTest, UpdateHeartbeatDataSameConfig) {
        OpTime lastOpTimeApplied = OpTime(Timestamp(3,0), 0);

        // request heartbeat
        std::pair<ReplSetHeartbeatArgs, Milliseconds> request =
            getTopoCoord().prepareHeartbeatRequest(now()++, "rs0", HostAndPort("host2"));

        // construct a copy of the original config for log message checking later
        // see HeartbeatResponseTest for the origin of the original config
        ReplicaSetConfig originalConfig;
        originalConfig.initialize(BSON("_id" << "rs0" <<
                                       "version" << 5 <<
                                       "members" << BSON_ARRAY(
                                           BSON("_id" << 0 << "host" << "host1:27017") <<
                                           BSON("_id" << 1 << "host" << "host2:27017") <<
                                           BSON("_id" << 2 << "host" << "host3:27017")) <<
                                       "settings" << BSON("heartbeatTimeoutSecs" << 5)));

        ReplSetHeartbeatResponse sameConfigResponse;
        sameConfigResponse.noteReplSet();
        sameConfigResponse.setSetName("rs0");
        sameConfigResponse.setState(MemberState::RS_SECONDARY);
        sameConfigResponse.setElectable(true);
        sameConfigResponse.noteStateDisagreement();
        sameConfigResponse.setConfigVersion(2);
        sameConfigResponse.setConfig(originalConfig);
        startCapturingLogMessages();
        HeartbeatResponseAction action = getTopoCoord().processHeartbeatResponse(
                    now()++, // Time is left.
                    Milliseconds(400), // Spent 0.4 of the 0.5 second in the network.
                    HostAndPort("host2"),
                    StatusWith<ReplSetHeartbeatResponse>(sameConfigResponse),
                    lastOpTimeApplied);
        stopCapturingLogMessages();
        ASSERT_NO_ACTION(action.getAction());
        ASSERT_EQUALS(1, countLogLinesContaining("Config from heartbeat response was "
                                                 "same as ours."));
    }

    TEST_F(HeartbeatResponseHighVerbosityTest, UpdateHeartbeatDataOldConfig) {
        OpTime lastOpTimeApplied = OpTime(Timestamp(3,0), 0);

        // request heartbeat
        std::pair<ReplSetHeartbeatArgs, Milliseconds> request =
            getTopoCoord().prepareHeartbeatRequest(now()++, "rs0", HostAndPort("host2"));

        ReplSetHeartbeatResponse believesWeAreDownResponse;
        believesWeAreDownResponse.noteReplSet();
        believesWeAreDownResponse.setSetName("rs0");
        believesWeAreDownResponse.setState(MemberState::RS_SECONDARY);
        believesWeAreDownResponse.setElectable(true);
        believesWeAreDownResponse.noteStateDisagreement();
        startCapturingLogMessages();
        HeartbeatResponseAction action = getTopoCoord().processHeartbeatResponse(
                    now()++, // Time is left.
                    Milliseconds(400), // Spent 0.4 of the 0.5 second in the network.
                    HostAndPort("host2"),
                    StatusWith<ReplSetHeartbeatResponse>(believesWeAreDownResponse),
                    lastOpTimeApplied);
        stopCapturingLogMessages();
        ASSERT_NO_ACTION(action.getAction());
        ASSERT_EQUALS(1, countLogLinesContaining("host2:27017 thinks that we are down"));
        
    }

    TEST_F(HeartbeatResponseTestOneRetry, DecideToReconfig) {
        // Confirm that action responses can come back from retries; in this, expect a Reconfig
        // action.
        ReplicaSetConfig newConfig;
        ASSERT_OK(newConfig.initialize(
                          BSON("_id" << "rs0" <<
                               "version" << 7 <<
                               "members" << BSON_ARRAY(
                                       BSON("_id" << 0 << "host" << "host1:27017") <<
                                       BSON("_id" << 1 << "host" << "host2:27017") <<
                                       BSON("_id" << 2 << "host" << "host3:27017") <<
                                       BSON("_id" << 3 << "host" << "host4:27017")) <<
                               "settings" << BSON("heartbeatTimeoutSecs" << 5))));
        ASSERT_OK(newConfig.validate());

        ReplSetHeartbeatResponse reconfigResponse;
        reconfigResponse.noteReplSet();
        reconfigResponse.setSetName("rs0");
        reconfigResponse.setState(MemberState::RS_SECONDARY);
        reconfigResponse.setElectable(true);
        reconfigResponse.setConfigVersion(7);
        reconfigResponse.setConfig(newConfig);
        HeartbeatResponseAction action =
            getTopoCoord().processHeartbeatResponse(
                    firstRequestDate() + Milliseconds(4500), // Time is left.
                    Milliseconds(400), // Spent 0.4 of the 0.5 second in the network.
                    target(),
                    StatusWith<ReplSetHeartbeatResponse>(reconfigResponse),
                    OpTime(Timestamp(0, 0), 0));  // We've never applied anything.
        ASSERT_EQUALS(HeartbeatResponseAction::Reconfig, action.getAction());
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
        ASSERT_EQUALS(firstRequestDate() + Milliseconds(6500), action.getNextHeartbeatStartDate());
    }

    TEST_F(HeartbeatResponseTestOneRetry, DecideToStepDownRemotePrimary) {
        // Confirm that action responses can come back from retries; in this, expect a
        // StepDownRemotePrimary action.

        // make self primary
        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        makeSelfPrimary(Timestamp(5,0));
        ASSERT_EQUALS(0, getCurrentPrimaryIndex());

        ReplSetHeartbeatResponse electedMoreRecentlyResponse;
        electedMoreRecentlyResponse.noteReplSet();
        electedMoreRecentlyResponse.setSetName("rs0");
        electedMoreRecentlyResponse.setState(MemberState::RS_PRIMARY);
        electedMoreRecentlyResponse.setElectable(true);
        electedMoreRecentlyResponse.setElectionTime(Timestamp(3,0));
        electedMoreRecentlyResponse.setConfigVersion(5);
        HeartbeatResponseAction action =
            getTopoCoord().processHeartbeatResponse(
                    firstRequestDate() + Milliseconds(4500), // Time is left.
                    Milliseconds(400), // Spent 0.4 of the 0.5 second in the network.
                    target(),
                    StatusWith<ReplSetHeartbeatResponse>(electedMoreRecentlyResponse),
                    OpTime());  // We've never applied anything.
        ASSERT_EQUALS(HeartbeatResponseAction::StepDownRemotePrimary, action.getAction());
        ASSERT_EQUALS(1, action.getPrimaryConfigIndex());
        ASSERT_EQUALS(firstRequestDate() + Milliseconds(6500), action.getNextHeartbeatStartDate());
    }

    TEST_F(HeartbeatResponseTestOneRetry, DecideToStepDownSelf) {
        // Confirm that action responses can come back from retries; in this, expect a StepDownSelf
        // action.

        // acknowledge the other member so that we see a majority
        HeartbeatResponseAction action = receiveDownHeartbeat(HostAndPort("host3"),
                                                              "rs0",
                                                              OpTime(Timestamp(100, 0), 0));
        ASSERT_NO_ACTION(action.getAction());

        // make us PRIMARY
        makeSelfPrimary();

        ReplSetHeartbeatResponse electedMoreRecentlyResponse;
        electedMoreRecentlyResponse.noteReplSet();
        electedMoreRecentlyResponse.setSetName("rs0");
        electedMoreRecentlyResponse.setState(MemberState::RS_PRIMARY);
        electedMoreRecentlyResponse.setElectable(false);
        electedMoreRecentlyResponse.setElectionTime(Timestamp(10,0));
        electedMoreRecentlyResponse.setConfigVersion(5);
        action =
            getTopoCoord().processHeartbeatResponse(
                    firstRequestDate() + Milliseconds(4500), // Time is left.
                    Milliseconds(400), // Spent 0.4 of the 0.5 second in the network.
                    target(),
                    StatusWith<ReplSetHeartbeatResponse>(electedMoreRecentlyResponse),
                    OpTime(Timestamp(0, 0), 0));  // We've never applied anything.
        ASSERT_EQUALS(HeartbeatResponseAction::StepDownSelf, action.getAction());
        ASSERT_EQUALS(0, action.getPrimaryConfigIndex());
        ASSERT_EQUALS(firstRequestDate() + Milliseconds(6500), action.getNextHeartbeatStartDate());
        // Doesn't actually do the stepdown until stepDownIfPending is called
        ASSERT_TRUE(TopologyCoordinator::Role::leader == getTopoCoord().getRole());
        ASSERT_EQUALS(0, getCurrentPrimaryIndex());

        ASSERT_TRUE(getTopoCoord().stepDownIfPending());
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
        ASSERT_EQUALS(1, getCurrentPrimaryIndex());
    }

    TEST_F(HeartbeatResponseTestOneRetry, DecideToStartElection) {
        // Confirm that action responses can come back from retries; in this, expect a StartElection
        // action.
        
        // acknowledge the other member so that we see a majority
        OpTime election = OpTime(Timestamp(400,0), 0);
        OpTime lastOpTimeApplied = OpTime(Timestamp(300,0), 0);
        HeartbeatResponseAction action = receiveUpHeartbeat(HostAndPort("host3"),
                                                            "rs0",
                                                            MemberState::RS_SECONDARY,
                                                            election,
                                                            election,
                                                            lastOpTimeApplied);
        ASSERT_NO_ACTION(action.getAction());

        // make sure we are electable
        setSelfMemberState(MemberState::RS_SECONDARY);

        ReplSetHeartbeatResponse startElectionResponse;
        startElectionResponse.noteReplSet();
        startElectionResponse.setSetName("rs0");
        startElectionResponse.setState(MemberState::RS_SECONDARY);
        startElectionResponse.setElectable(true);
        startElectionResponse.setConfigVersion(5);
        action =
            getTopoCoord().processHeartbeatResponse(
                    firstRequestDate() + Milliseconds(4500), // Time is left.
                    Milliseconds(400), // Spent 0.4 of the 0.5 second in the network.
                    target(),
                    StatusWith<ReplSetHeartbeatResponse>(startElectionResponse),
                    election);
        ASSERT_EQUALS(HeartbeatResponseAction::StartElection, action.getAction());
        ASSERT_TRUE(TopologyCoordinator::Role::candidate == getTopoCoord().getRole());
        ASSERT_EQUALS(firstRequestDate() + Milliseconds(6500), action.getNextHeartbeatStartDate());
    }

    TEST_F(HeartbeatResponseTestTwoRetries, HeartbeatRetriesAtMostTwice) {
        // Confirm that the topology coordinator attempts to retry a failed heartbeat two times
        // after initial failure, assuming that the heartbeat timeout (set to 5 seconds in the
        // fixture) has not expired.
        //
        // Failed heartbeats propose taking no action, other than scheduling the next heartbeat.  We
        // can detect a retry vs the next regularly scheduled heartbeat because retries are
        // scheduled immediately, while subsequent heartbeats are scheduled after the hard-coded
        // heartbeat interval of 2 seconds.

        // Second retry fails at t + 4800ms
        HeartbeatResponseAction action =
            getTopoCoord().processHeartbeatResponse(
                    firstRequestDate() + Milliseconds(4800), // 4.8 of the 5 seconds elapsed;
                                                             // could still retry.
                    Milliseconds(100), // Spent 0.1 of the 0.3 seconds in the network.
                    target(),
                    StatusWith<ReplSetHeartbeatResponse>(ErrorCodes::NodeNotFound, "Bad DNS?"),
                    OpTime(Timestamp(0, 0), 0));  // We've never applied anything.
        ASSERT_EQUALS(HeartbeatResponseAction::NoAction, action.getAction());
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
        // Because this is the second retry, rather than retry again, we expect to wait for the
        // heartbeat interval of 2 seconds to elapse.
        ASSERT_EQUALS(firstRequestDate() + Milliseconds(6800), action.getNextHeartbeatStartDate());

        // Ensure a third failed heartbeat caused the node to be marked down
        BSONObjBuilder statusBuilder;
        Status resultStatus(ErrorCodes::InternalError,
                            "prepareStatusResponse didn't set result");
        getTopoCoord().prepareStatusResponse(cbData(),
                                             firstRequestDate() + Milliseconds(4900),
                                             10,
                                             OpTime(Timestamp(100,0), 0),
                                             &statusBuilder,
                                             &resultStatus);
        ASSERT_OK(resultStatus);
        BSONObj rsStatus = statusBuilder.obj();
        std::vector<BSONElement> memberArray = rsStatus["members"].Array();
        BSONObj member1Status = memberArray[1].Obj();

        ASSERT_EQUALS(1, member1Status["_id"].Int());
        ASSERT_EQUALS(0, member1Status["health"].Double());
    }

    TEST_F(HeartbeatResponseTestTwoRetries, DecideToStepDownRemotePrimary) {
        // Confirm that action responses can come back from retries; in this, expect a
        // StepDownRemotePrimary action.

        // make self primary
        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        makeSelfPrimary(Timestamp(5,0));
        ASSERT_EQUALS(0, getCurrentPrimaryIndex());

        ReplSetHeartbeatResponse electedMoreRecentlyResponse;
        electedMoreRecentlyResponse.noteReplSet();
        electedMoreRecentlyResponse.setSetName("rs0");
        electedMoreRecentlyResponse.setState(MemberState::RS_PRIMARY);
        electedMoreRecentlyResponse.setElectable(true);
        electedMoreRecentlyResponse.setElectionTime(Timestamp(3,0));
        electedMoreRecentlyResponse.setConfigVersion(5);
        HeartbeatResponseAction action =
            getTopoCoord().processHeartbeatResponse(
                    firstRequestDate() + Milliseconds(5000), // Time is left.
                    Milliseconds(400), // Spent 0.4 of the 0.5 second in the network.
                    target(),
                    StatusWith<ReplSetHeartbeatResponse>(electedMoreRecentlyResponse),
                    OpTime());  // We've never applied anything.
        ASSERT_EQUALS(HeartbeatResponseAction::StepDownRemotePrimary, action.getAction());
        ASSERT_EQUALS(1, action.getPrimaryConfigIndex());
        ASSERT_EQUALS(firstRequestDate() + Milliseconds(7000), action.getNextHeartbeatStartDate());
    }

    TEST_F(HeartbeatResponseTestTwoRetries, DecideToStepDownSelf) {
        // Confirm that action responses can come back from retries; in this, expect a StepDownSelf
        // action.

        // acknowledge the other member so that we see a majority
        HeartbeatResponseAction action = receiveDownHeartbeat(HostAndPort("host3"),
                                                              "rs0",
                                                              OpTime(Timestamp(100, 0), 0));
        ASSERT_NO_ACTION(action.getAction());

        // make us PRIMARY
        makeSelfPrimary();

        ReplSetHeartbeatResponse electedMoreRecentlyResponse;
        electedMoreRecentlyResponse.noteReplSet();
        electedMoreRecentlyResponse.setSetName("rs0");
        electedMoreRecentlyResponse.setState(MemberState::RS_PRIMARY);
        electedMoreRecentlyResponse.setElectable(false);
        electedMoreRecentlyResponse.setElectionTime(Timestamp(10,0));
        electedMoreRecentlyResponse.setConfigVersion(5);
        action =
            getTopoCoord().processHeartbeatResponse(
                    firstRequestDate() + Milliseconds(5000), // Time is left.
                    Milliseconds(400), // Spent 0.4 of the 0.5 second in the network.
                    target(),
                    StatusWith<ReplSetHeartbeatResponse>(electedMoreRecentlyResponse),
                    OpTime(Timestamp(0, 0), 0));  // We've never applied anything.
        ASSERT_EQUALS(HeartbeatResponseAction::StepDownSelf, action.getAction());
        ASSERT_EQUALS(0, action.getPrimaryConfigIndex());
        ASSERT_EQUALS(firstRequestDate() + Milliseconds(7000), action.getNextHeartbeatStartDate());
        // Doesn't actually do the stepdown until stepDownIfPending is called
        ASSERT_TRUE(TopologyCoordinator::Role::leader == getTopoCoord().getRole());
        ASSERT_EQUALS(0, getCurrentPrimaryIndex());

        ASSERT_TRUE(getTopoCoord().stepDownIfPending());
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
        ASSERT_EQUALS(1, getCurrentPrimaryIndex());
    }

    TEST_F(HeartbeatResponseTestTwoRetries, DecideToStartElection) {
        // Confirm that action responses can come back from retries; in this, expect a StartElection
        // action.

        // acknowledge the other member so that we see a majority
        OpTime election = OpTime(Timestamp(400,0), 0);
        OpTime lastOpTimeApplied = OpTime(Timestamp(300,0), 0);
        HeartbeatResponseAction action = receiveUpHeartbeat(HostAndPort("host3"),
                                                            "rs0",
                                                            MemberState::RS_SECONDARY,
                                                            election,
                                                            election,
                                                            lastOpTimeApplied);
        ASSERT_NO_ACTION(action.getAction());

        // make sure we are electable
        setSelfMemberState(MemberState::RS_SECONDARY);

        ReplSetHeartbeatResponse startElectionResponse;
        startElectionResponse.noteReplSet();
        startElectionResponse.setSetName("rs0");
        startElectionResponse.setState(MemberState::RS_SECONDARY);
        startElectionResponse.setElectable(true);
        startElectionResponse.setConfigVersion(5);
        action =
            getTopoCoord().processHeartbeatResponse(
                    firstRequestDate() + Milliseconds(5000), // Time is left.
                    Milliseconds(400), // Spent 0.4 of the 0.5 second in the network.
                    target(),
                    StatusWith<ReplSetHeartbeatResponse>(startElectionResponse),
                    election);
        ASSERT_EQUALS(HeartbeatResponseAction::StartElection, action.getAction());
        ASSERT_TRUE(TopologyCoordinator::Role::candidate == getTopoCoord().getRole());
        ASSERT_EQUALS(firstRequestDate() + Milliseconds(7000), action.getNextHeartbeatStartDate());
    }

    TEST_F(HeartbeatResponseTest, HeartbeatTimeoutSuppressesFirstRetry) {
        // Confirm that the topology coordinator does not schedule an immediate heartbeat retry if
        // the heartbeat timeout period expired before the initial request completed.

        HostAndPort target("host2", 27017);
        Date_t firstRequestDate = unittest::assertGet(dateFromISOString("2014-08-29T13:00Z"));

        // Initial heartbeat request prepared, at t + 0.
        std::pair<ReplSetHeartbeatArgs, Milliseconds> request =
            getTopoCoord().prepareHeartbeatRequest(firstRequestDate,
                                                   "rs0",
                                                   target);
        // 5 seconds to successfully complete the heartbeat before the timeout expires.
        ASSERT_EQUALS(5000, request.second.count());

        // Initial heartbeat request fails at t + 5000ms
        HeartbeatResponseAction action =
            getTopoCoord().processHeartbeatResponse(
                    firstRequestDate + Milliseconds(5000), // Entire heartbeat period elapsed;
                                                           // no retry allowed.
                    Milliseconds(4990), // Spent 4.99 of the 4 seconds in the network.
                    target,
                    StatusWith<ReplSetHeartbeatResponse>(ErrorCodes::ExceededTimeLimit,
                                                         "Took too long"),
                    OpTime(Timestamp(0, 0), 0));  // We've never applied anything.

        ASSERT_EQUALS(HeartbeatResponseAction::NoAction, action.getAction());
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
        // Because the heartbeat timed out, we'll retry in 2 seconds.
        ASSERT_EQUALS(firstRequestDate + Milliseconds(7000), action.getNextHeartbeatStartDate());
    }

    TEST_F(HeartbeatResponseTestOneRetry, HeartbeatTimeoutSuppressesSecondRetry) {
        // Confirm that the topology coordinator does not schedule an second heartbeat retry if
        // the heartbeat timeout period expired before the first retry completed.
        HeartbeatResponseAction action =
            getTopoCoord().processHeartbeatResponse(
                    firstRequestDate() + Milliseconds(5010), // Entire heartbeat period elapsed;
                                                             // no retry allowed.
                    Milliseconds(1000), // Spent 1 of the 1.01 seconds in the network.
                    target(),
                    StatusWith<ReplSetHeartbeatResponse>(ErrorCodes::ExceededTimeLimit,
                                                         "Took too long"),
                    OpTime(Timestamp(0, 0), 0));  // We've never applied anything.

        ASSERT_EQUALS(HeartbeatResponseAction::NoAction, action.getAction());
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
        // Because the heartbeat timed out, we'll retry in 2 seconds.
        ASSERT_EQUALS(firstRequestDate() + Milliseconds(7010), action.getNextHeartbeatStartDate());
    }

    TEST_F(HeartbeatResponseTestTwoRetries, HeartbeatThreeNonconsecutiveFailures) {
        // Confirm that the topology coordinator does not mark a node down on three
        // nonconsecutive heartbeat failures.
        ReplSetHeartbeatResponse response;
        response.noteReplSet();
        response.setSetName("rs0");
        response.setState(MemberState::RS_SECONDARY);
        response.setElectable(true);
        response.setConfigVersion(5);

        // successful response (third response due to the two failures in setUp())
        HeartbeatResponseAction action =
            getTopoCoord().processHeartbeatResponse(
                    firstRequestDate() + Milliseconds(4500),
                    Milliseconds(400),
                    target(),
                    StatusWith<ReplSetHeartbeatResponse>(response),
                    OpTime(Timestamp(0, 0), 0));  // We've never applied anything.

        ASSERT_EQUALS(HeartbeatResponseAction::NoAction, action.getAction());
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
        // Because the heartbeat succeeded, we'll retry in 2 seconds.
        ASSERT_EQUALS(firstRequestDate() + Milliseconds(6500), action.getNextHeartbeatStartDate());

        // request next heartbeat
        getTopoCoord().prepareHeartbeatRequest(
                firstRequestDate() + Milliseconds(6500), "rs0", target());
        // third failed response
        action = getTopoCoord().processHeartbeatResponse(
                firstRequestDate() + Milliseconds(7100),
                Milliseconds(400),
                target(),
                StatusWith<ReplSetHeartbeatResponse>(Status{ErrorCodes::HostUnreachable, ""}),
                OpTime(Timestamp(0, 0), 0));  // We've never applied anything.

        ASSERT_EQUALS(HeartbeatResponseAction::NoAction, action.getAction());
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());

        // Ensure a third nonconsecutive heartbeat failure did not cause the node to be marked down
        BSONObjBuilder statusBuilder;
        Status resultStatus(ErrorCodes::InternalError,
                            "prepareStatusResponse didn't set result");
        getTopoCoord().prepareStatusResponse(cbData(),
                                             firstRequestDate() + Milliseconds(7000),
                                             600,
                                             OpTime(Timestamp(100,0), 0),
                                             &statusBuilder,
                                             &resultStatus);
        ASSERT_OK(resultStatus);
        BSONObj rsStatus = statusBuilder.obj();
        std::vector<BSONElement> memberArray = rsStatus["members"].Array();
        BSONObj member1Status = memberArray[1].Obj();

        ASSERT_EQUALS(1, member1Status["_id"].Int());
        ASSERT_EQUALS(1, member1Status["health"].Double());

    }

    TEST_F(HeartbeatResponseTest, UpdateHeartbeatDataNewPrimary) {
        OpTime election = OpTime(Timestamp(5,0), 0);
        OpTime lastOpTimeApplied = OpTime(Timestamp(3,0), 0);

        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        HeartbeatResponseAction nextAction = receiveUpHeartbeat(HostAndPort("host2"),
                                                                "rs0",
                                                                MemberState::RS_PRIMARY,
                                                                election,
                                                                election,
                                                                lastOpTimeApplied);
        ASSERT_EQUALS(1, getCurrentPrimaryIndex());
        ASSERT_NO_ACTION(nextAction.getAction());
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
    }

    TEST_F(HeartbeatResponseTest, UpdateHeartbeatDataTwoPrimariesNewOneOlder) {
        OpTime election = OpTime(Timestamp(5,0), 0);
        OpTime election2 = OpTime(Timestamp(4,0), 0);
        OpTime lastOpTimeApplied = OpTime(Timestamp(3,0), 0);

        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        HeartbeatResponseAction nextAction = receiveUpHeartbeat(HostAndPort("host2"),
                                                                "rs0",
                                                                MemberState::RS_PRIMARY,
                                                                election,
                                                                election,
                                                                lastOpTimeApplied);
        ASSERT_EQUALS(1, getCurrentPrimaryIndex());
        ASSERT_NO_ACTION(nextAction.getAction());

        nextAction = receiveUpHeartbeat(HostAndPort("host3"),
                                        "rs0",
                                        MemberState::RS_PRIMARY,
                                        election2,
                                        election,
                                        lastOpTimeApplied);
        // second primary does not change primary index
        ASSERT_EQUALS(1, getCurrentPrimaryIndex());
        ASSERT_NO_ACTION(nextAction.getAction());
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
    }

    TEST_F(HeartbeatResponseTest, UpdateHeartbeatDataTwoPrimariesNewOneNewer) {
        OpTime election = OpTime(Timestamp(4,0), 0);
        OpTime election2 = OpTime(Timestamp(5,0), 0);
        OpTime lastOpTimeApplied = OpTime(Timestamp(3,0), 0);

        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        HeartbeatResponseAction nextAction = receiveUpHeartbeat(HostAndPort("host2"),
                                                                "rs0",
                                                                MemberState::RS_PRIMARY,
                                                                election,
                                                                election,
                                                                lastOpTimeApplied);
        ASSERT_EQUALS(1, getCurrentPrimaryIndex());
        ASSERT_NO_ACTION(nextAction.getAction());

        nextAction = receiveUpHeartbeat(HostAndPort("host3"),
                                        "rs0",
                                        MemberState::RS_PRIMARY,
                                        election2,
                                        election,
                                        lastOpTimeApplied);
        // second primary does not change primary index
        ASSERT_EQUALS(1, getCurrentPrimaryIndex());
        ASSERT_NO_ACTION(nextAction.getAction());
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
    }

    TEST_F(HeartbeatResponseTest, UpdateHeartbeatDataTwoPrimariesIncludingMeNewOneOlder) {
        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        makeSelfPrimary(Timestamp(5,0));

        OpTime election = OpTime(Timestamp(4,0), 0);
        OpTime lastOpTimeApplied = OpTime(Timestamp(3,0), 0);

        ASSERT_EQUALS(0, getCurrentPrimaryIndex());
        HeartbeatResponseAction nextAction = receiveUpHeartbeat(HostAndPort("host2"),
                                                                "rs0",
                                                                MemberState::RS_PRIMARY,
                                                                election,
                                                                election,
                                                                lastOpTimeApplied);
        ASSERT_EQUALS(0, getCurrentPrimaryIndex());
        ASSERT_EQUALS(HeartbeatResponseAction::StepDownRemotePrimary, nextAction.getAction());
        ASSERT_EQUALS(1, nextAction.getPrimaryConfigIndex());
        ASSERT_TRUE(TopologyCoordinator::Role::leader == getTopoCoord().getRole());
    }

    TEST_F(HeartbeatResponseTest, UpdateHeartbeatDataStepDownPrimaryForHighPriorityFreshNode) {
        // In this test, the Topology coordinator sees a PRIMARY ("host2") and then sees a higher
        // priority and similarly fresh node ("host3"). However, since the coordinator's node
        // (host1) is not the higher priority node, it takes no action.
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 6 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 0 << "host" << "host1:27017") <<
                              BSON("_id" << 1 << "host" << "host2:27017") <<
                              BSON("_id" << 2 << "host" << "host3:27017" << "priority" << 3)) <<
                          "settings" << BSON("heartbeatTimeoutSecs" << 5)),
                     0);
        setSelfMemberState(MemberState::RS_SECONDARY);

        OpTime election = OpTime();
        OpTime lastOpTimeApplied = OpTime(Timestamp(13,0), 0);
        OpTime slightlyLessFreshLastOpTimeApplied = OpTime(Timestamp(3,0), 0);

        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        HeartbeatResponseAction nextAction = receiveUpHeartbeat(HostAndPort("host2"),
                                                                "rs0",
                                                                MemberState::RS_PRIMARY,
                                                                election,
                                                                lastOpTimeApplied,
                                                                lastOpTimeApplied);
        ASSERT_EQUALS(1, getCurrentPrimaryIndex());

        nextAction = receiveUpHeartbeat(HostAndPort("host3"),
                                        "rs0",
                                        MemberState::RS_SECONDARY,
                                        election,
                                        slightlyLessFreshLastOpTimeApplied,
                                        lastOpTimeApplied);
        ASSERT_EQUALS(HeartbeatResponseAction::NoAction, nextAction.getAction());
    }

    TEST_F(HeartbeatResponseTest, UpdateHeartbeatDataStepDownSelfForHighPriorityFreshNode) {
        // In this test, the Topology coordinator becomes PRIMARY and then sees a higher priority
        // and equally fresh node ("host3"). As a result it responds with a StepDownSelf action.
        //
        // Despite having stepped down, we should remain electable, in order to dissuade lower
        // priority nodes from standing for election.
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 6 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 0 << "host" << "host1:27017") <<
                              BSON("_id" << 1 << "host" << "host2:27017") <<
                              BSON("_id" << 2 << "host" << "host3:27017" << "priority" << 3)) <<
                          "settings" << BSON("heartbeatTimeoutSecs" << 5)),
                     0);
        OpTime election = OpTime(Timestamp(1000,0), 0);

        getTopoCoord().setFollowerMode(MemberState::RS_SECONDARY);
        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        makeSelfPrimary(election.getTimestamp());
        ASSERT_EQUALS(0, getCurrentPrimaryIndex());

        HeartbeatResponseAction nextAction = receiveUpHeartbeat(HostAndPort("host3"),
                                                                "rs0",
                                                                MemberState::RS_SECONDARY,
                                                                election,
                                                                election,
                                                                election);
        ASSERT_EQUALS(HeartbeatResponseAction::StepDownSelf, nextAction.getAction());
        ASSERT_EQUALS(0, nextAction.getPrimaryConfigIndex());

        // Process a heartbeat response to confirm that this node, which is no longer primary,
        // still tells other nodes that it is electable.  This will stop lower priority nodes
        // from standing for election.
        ReplSetHeartbeatArgs hbArgs;
        hbArgs.setSetName("rs0");
        hbArgs.setProtocolVersion(1);
        hbArgs.setConfigVersion(6);
        hbArgs.setSenderId(1);
        hbArgs.setSenderHost(HostAndPort("host3", 27017));
        ReplSetHeartbeatResponse hbResp;
        ASSERT_OK(getTopoCoord().prepareHeartbeatResponse(now(),
                                                          hbArgs,
                                                          "rs0",
                                                          election,
                                                          &hbResp));
        ASSERT(!hbResp.hasIsElectable() || hbResp.isElectable()) << hbResp.toString();
    }

    TEST_F(HeartbeatResponseTest, UpdateHeartbeatDataDoNotStepDownSelfForHighPriorityStaleNode) {
        // In this test, the Topology coordinator becomes PRIMARY and then sees a higher priority
        // and stale node ("host3"). As a result it responds with NoAction.
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 6 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 0 << "host" << "host1:27017") <<
                              BSON("_id" << 1 << "host" << "host2:27017") <<
                              BSON("_id" << 2 << "host" << "host3:27017" << "priority" << 3)) <<
                          "settings" << BSON("heartbeatTimeoutSecs" << 5)),
                     0);
        OpTime election = OpTime(Timestamp(1000,0), 0);
        OpTime staleTime = OpTime();

        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        makeSelfPrimary(election.getTimestamp());
        ASSERT_EQUALS(0, getCurrentPrimaryIndex());

        HeartbeatResponseAction nextAction = receiveUpHeartbeat(HostAndPort("host3"),
                                                                "rs0",
                                                                MemberState::RS_SECONDARY,
                                                                election,
                                                                staleTime,
                                                                election);
        ASSERT_NO_ACTION(nextAction.getAction());
    }

    TEST_F(HeartbeatResponseTest, UpdateHeartbeatDataDoNotStepDownPrimaryForHighPriorityStaleNode) {
        // In this test, the Topology coordinator sees a PRIMARY ("host2") and then sees a higher
        // priority and stale node ("host3"). As a result it responds with NoAction.
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 6 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 0 << "host" << "host1:27017") <<
                              BSON("_id" << 1 << "host" << "host2:27017") <<
                              BSON("_id" << 2 << "host" << "host3:27017" << "priority" << 3)) <<
                          "settings" << BSON("heartbeatTimeoutSecs" << 5)),
                     0);
        setSelfMemberState(MemberState::RS_SECONDARY);

        OpTime election = OpTime(Timestamp(1000,0), 0);
        OpTime stale = OpTime();

        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        HeartbeatResponseAction nextAction = receiveUpHeartbeat(HostAndPort("host2"),
                                                                "rs0",
                                                                MemberState::RS_PRIMARY,
                                                                election,
                                                                election,
                                                                election);
        ASSERT_EQUALS(1, getCurrentPrimaryIndex());

        nextAction = receiveUpHeartbeat(HostAndPort("host3"),
                                        "rs0",
                                        MemberState::RS_SECONDARY,
                                        election,
                                        stale,
                                        election);
        ASSERT_NO_ACTION(nextAction.getAction());
    }

    TEST_F(HeartbeatResponseTest, UpdateHeartbeatDataTwoPrimariesIncludingMeNewOneNewer) {
        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        makeSelfPrimary(Timestamp(2,0));

        OpTime election = OpTime(Timestamp(4,0), 0);
        OpTime lastOpTimeApplied = OpTime(Timestamp(3,0), 0);

        ASSERT_EQUALS(0, getCurrentPrimaryIndex());
        HeartbeatResponseAction nextAction = receiveUpHeartbeat(HostAndPort("host2"),
                                                                "rs0",
                                                                MemberState::RS_PRIMARY,
                                                                election,
                                                                election,
                                                                lastOpTimeApplied);
        ASSERT_EQUALS(HeartbeatResponseAction::StepDownSelf, nextAction.getAction());
        ASSERT_EQUALS(0, nextAction.getPrimaryConfigIndex());
        // Doesn't actually do the stepdown until stepDownIfPending is called
        ASSERT_TRUE(TopologyCoordinator::Role::leader == getTopoCoord().getRole());
        ASSERT_EQUALS(0, getCurrentPrimaryIndex());

        ASSERT_TRUE(getTopoCoord().stepDownIfPending());
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
        ASSERT_EQUALS(1, getCurrentPrimaryIndex());
    }

    TEST_F(HeartbeatResponseTest, UpdateHeartbeatDataPrimaryDownNoMajority) {
        setSelfMemberState(MemberState::RS_SECONDARY);

        OpTime election = OpTime(Timestamp(400,0), 0);
        OpTime lastOpTimeApplied = OpTime(Timestamp(300,0), 0);

        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        HeartbeatResponseAction nextAction = receiveUpHeartbeat(HostAndPort("host2"),
                                                                "rs0",
                                                                MemberState::RS_PRIMARY,
                                                                election,
                                                                election,
                                                                lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());
        ASSERT_EQUALS(1, getCurrentPrimaryIndex());

        nextAction = receiveDownHeartbeat(HostAndPort("host2"), "rs0", lastOpTimeApplied);
        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        ASSERT_NO_ACTION(nextAction.getAction());
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
    }

    TEST_F(HeartbeatResponseTest, UpdateHeartbeatDataPrimaryDownMajorityButNoPriority) {
        setSelfMemberState(MemberState::RS_SECONDARY);

        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 5 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 0 << "host" << "host1:27017" << "priority" << 0) <<
                              BSON("_id" << 1 << "host" << "host2:27017") <<
                              BSON("_id" << 2 << "host" << "host3:27017"))),
                     0);

        OpTime election = OpTime(Timestamp(400,0), 0);
        OpTime lastOpTimeApplied = OpTime(Timestamp(300,0), 0);

        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        HeartbeatResponseAction nextAction = receiveUpHeartbeat(HostAndPort("host2"),
                                                                "rs0",
                                                                MemberState::RS_PRIMARY,
                                                                election,
                                                                election,
                                                                lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());
        ASSERT_EQUALS(1, getCurrentPrimaryIndex());

        nextAction = receiveUpHeartbeat(HostAndPort("host3"),
                                        "rs0",
                                        MemberState::RS_SECONDARY,
                                        election,
                                        election,
                                        lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());
        ASSERT_EQUALS(1, getCurrentPrimaryIndex());

        nextAction = receiveDownHeartbeat(HostAndPort("host2"), "rs0", lastOpTimeApplied);
        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        ASSERT_NO_ACTION(nextAction.getAction());
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
    }

    TEST_F(HeartbeatResponseTest, UpdateHeartbeatDataPrimaryDownMajorityButIAmStarting) {
        setSelfMemberState(MemberState::RS_STARTUP);

        OpTime election = OpTime(Timestamp(400,0), 0);
        OpTime lastOpTimeApplied = OpTime(Timestamp(300,0), 0);

        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        HeartbeatResponseAction nextAction = receiveUpHeartbeat(HostAndPort("host2"),
                                                                "rs0",
                                                                MemberState::RS_PRIMARY,
                                                                election,
                                                                election,
                                                                lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());
        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());

        nextAction = receiveUpHeartbeat(HostAndPort("host3"),
                                        "rs0",
                                        MemberState::RS_SECONDARY,
                                        election,
                                        election,
                                        lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());

        nextAction = receiveDownHeartbeat(HostAndPort("host2"), "rs0", lastOpTimeApplied);
        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        ASSERT_NO_ACTION(nextAction.getAction());
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
    }

    TEST_F(HeartbeatResponseTest, UpdateHeartbeatDataPrimaryDownMajorityButIAmRecovering) {
        setSelfMemberState(MemberState::RS_RECOVERING);

        OpTime election = OpTime(Timestamp(400,0), 0);
        OpTime lastOpTimeApplied = OpTime(Timestamp(300,0), 0);

        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        HeartbeatResponseAction nextAction = receiveUpHeartbeat(HostAndPort("host2"),
                                                                "rs0",
                                                                MemberState::RS_PRIMARY,
                                                                election,
                                                                election,
                                                                lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());
        ASSERT_EQUALS(1, getCurrentPrimaryIndex());

        nextAction = receiveDownHeartbeat(HostAndPort("host2"), "rs0", lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());
        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
    }

    TEST_F(HeartbeatResponseTest, UpdateHeartbeatDataPrimaryDownMajorityButIHaveStepdownWait) {
        setSelfMemberState(MemberState::RS_SECONDARY);

        OpTime election = OpTime(Timestamp(400,0), 0);
        OpTime lastOpTimeApplied = OpTime(Timestamp(300,0), 0);

        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        HeartbeatResponseAction nextAction = receiveUpHeartbeat(HostAndPort("host2"),
                                                                "rs0",
                                                                MemberState::RS_PRIMARY,
                                                                election,
                                                                election,
                                                                lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());
        ASSERT_EQUALS(1, getCurrentPrimaryIndex());

        nextAction = receiveUpHeartbeat(HostAndPort("host3"),
                                        "rs0",
                                        MemberState::RS_SECONDARY,
                                        election,
                                        election,
                                        lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());

        // freeze node to set stepdown wait
        BSONObjBuilder response;
        getTopoCoord().prepareFreezeResponse(now()++, 20, &response);

        nextAction = receiveDownHeartbeat(HostAndPort("host2"), "rs0", lastOpTimeApplied);
        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        ASSERT_NO_ACTION(nextAction.getAction());
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
    }

    TEST_F(HeartbeatResponseTest, UpdateHeartbeatDataPrimaryDownMajorityButIAmArbiter) {
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 5 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 0 << "host" << "host1:27017" <<
                                   "arbiterOnly" << true) <<
                              BSON("_id" << 1 << "host" << "host2:27017") <<
                              BSON("_id" << 2 << "host" << "host3:27017"))),
                     0);

        OpTime election = OpTime(Timestamp(400,0), 0);
        OpTime lastOpTimeApplied = OpTime(Timestamp(300,0), 0);

        HeartbeatResponseAction nextAction = receiveUpHeartbeat(HostAndPort("host3"),
                                                                "rs0",
                                                                MemberState::RS_SECONDARY,
                                                                election,
                                                                election,
                                                                lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());
        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());

        nextAction = receiveUpHeartbeat(HostAndPort("host2"),
                                        "rs0",
                                        MemberState::RS_PRIMARY,
                                        election,
                                        election,
                                        lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());
        ASSERT_EQUALS(1, getCurrentPrimaryIndex());

        nextAction = receiveDownHeartbeat(HostAndPort("host2"), "rs0", lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());
        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
    }

    TEST_F(HeartbeatResponseTest, UpdateHeartbeatDataPrimaryDownMajority) {
        setSelfMemberState(MemberState::RS_SECONDARY);

        OpTime election = OpTime(Timestamp(400,0), 0);
        OpTime lastOpTimeApplied = OpTime(Timestamp(399,0), 0);

        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        HeartbeatResponseAction nextAction = receiveUpHeartbeat(HostAndPort("host2"),
                                                                "rs0",
                                                                MemberState::RS_PRIMARY,
                                                                election,
                                                                election,
                                                                lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());
        ASSERT_EQUALS(1, getCurrentPrimaryIndex());

        nextAction = receiveUpHeartbeat(HostAndPort("host3"),
                                        "rs0",
                                        MemberState::RS_SECONDARY,
                                        election,
                                        election,
                                        lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());

        nextAction = receiveDownHeartbeat(HostAndPort("host2"), "rs0", lastOpTimeApplied);
        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        ASSERT_EQUALS(HeartbeatResponseAction::StartElection, nextAction.getAction());
        ASSERT_TRUE(TopologyCoordinator::Role::candidate == getTopoCoord().getRole());
    }

    TEST_F(HeartbeatResponseTest, ElectionStartElectionWhileCandidate) {
        // In this test, the TopologyCoordinator goes through the steps of a successful election,
        // during which it receives a heartbeat that would normally trigger it to become a candidate
        // and respond with a StartElection HeartbeatResponseAction. However, since it is already in
        // candidate state, it responds with a NoAction HeartbeatResponseAction. Then finishes by
        // being winning the election.

        // 1. All nodes heartbeat to indicate that they are up and that "host2" is PRIMARY.
        // 2. "host2" goes down, triggering an election.
        // 3. "host2" comes back, which would normally trigger election, but since the
        //     TopologyCoordinator is already in candidate mode, does not.
        // 4. TopologyCoordinator concludes its freshness round successfully and wins the election.

        setSelfMemberState(MemberState::RS_SECONDARY);
        now() += Seconds(30); // we need to be more than LastVote::leaseTime from the start of time or
                              // else some Date_t math goes horribly awry

        OpTime election = OpTime();
        OpTime lastOpTimeApplied = OpTime(Timestamp(130,0), 0);
        OID round = OID::gen();

        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        HeartbeatResponseAction nextAction = receiveUpHeartbeat(HostAndPort("host2"),
                                                                "rs0",
                                                                MemberState::RS_PRIMARY,
                                                                election,
                                                                lastOpTimeApplied,
                                                                lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());
        ASSERT_EQUALS(1, getCurrentPrimaryIndex());

        nextAction = receiveUpHeartbeat(HostAndPort("host3"),
                                        "rs0",
                                        MemberState::RS_SECONDARY,
                                        election,
                                        lastOpTimeApplied,
                                        lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());

        // candidate time!
        nextAction = receiveDownHeartbeat(HostAndPort("host2"), "rs0", lastOpTimeApplied);
        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        ASSERT_EQUALS(HeartbeatResponseAction::StartElection, nextAction.getAction());
        ASSERT_TRUE(TopologyCoordinator::Role::candidate == getTopoCoord().getRole());

        // see the downed node as SECONDARY and decide to take no action, but are still a candidate
        nextAction = receiveUpHeartbeat(HostAndPort("host2"),
                                        "rs0",
                                        MemberState::RS_SECONDARY,
                                        election,
                                        lastOpTimeApplied,
                                        lastOpTimeApplied);
        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());

        // normally this would trigger StartElection, but we are already a candidate
        ASSERT_NO_ACTION(nextAction.getAction());
        ASSERT_TRUE(TopologyCoordinator::Role::candidate == getTopoCoord().getRole());

        // now voteForSelf as though we received all our fresh responses
        ASSERT_TRUE(getTopoCoord().voteForMyself(now()++));

        // now win election and ensure _electionId and _electionTime are set properly
        getTopoCoord().processWinElection(round, election.getTimestamp());
        ASSERT_EQUALS(round, getTopoCoord().getElectionId());
        ASSERT_EQUALS(election.getTimestamp(), getTopoCoord().getElectionTime());
        ASSERT_TRUE(TopologyCoordinator::Role::leader == getTopoCoord().getRole());
        ASSERT_EQUALS(0, getCurrentPrimaryIndex());
    }

    TEST_F(HeartbeatResponseTest, ElectionVoteForAnotherNodeBeforeFreshnessReturns) {
        // In this test, the TopologyCoordinator goes through the steps of an election. However,
        // before its freshness round ends, it receives a fresh command followed by an elect command
        // from another node, both of which it responds positively to. The TopologyCoordinator's
        // freshness round then concludes successfully, but it fails to vote for itself, since it
        // recently voted for another node.

        // 1. All nodes heartbeat to indicate that they are up and that "host2" is PRIMARY.
        // 2. "host2" goes down, triggering an election.
        // 3. "host3" sends a fresh command, which the TopologyCoordinator responds to positively.
        // 4. "host3" sends an elect command, which the TopologyCoordinator responds to positively.
        // 5. The TopologyCoordinator's concludes its freshness round successfully.
        // 6. The TopologyCoordinator loses the election.

        setSelfMemberState(MemberState::RS_SECONDARY);
        now() += Seconds(30); // we need to be more than LastVote::leaseTime from the start of time or
                              // else some Date_t math goes horribly awry

        OpTime election = OpTime();
        OpTime lastOpTimeApplied = OpTime(Timestamp(100,0), 0);
        OpTime fresherOpApplied = OpTime(Timestamp(200,0), 0);

        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        HeartbeatResponseAction nextAction = receiveUpHeartbeat(HostAndPort("host2"),
                                                                "rs0",
                                                                MemberState::RS_PRIMARY,
                                                                election,
                                                                lastOpTimeApplied,
                                                                lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());
        ASSERT_EQUALS(1, getCurrentPrimaryIndex());

        nextAction = receiveUpHeartbeat(HostAndPort("host3"),
                                        "rs0",
                                        MemberState::RS_SECONDARY,
                                        election,
                                        lastOpTimeApplied,
                                        lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());

        // candidate time!
        nextAction = receiveDownHeartbeat(HostAndPort("host2"), "rs0", lastOpTimeApplied);
        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        ASSERT_EQUALS(HeartbeatResponseAction::StartElection, nextAction.getAction());
        ASSERT_TRUE(TopologyCoordinator::Role::candidate == getTopoCoord().getRole());

        Timestamp originalElectionTime = getTopoCoord().getElectionTime();
        OID originalElectionId = getTopoCoord().getElectionId();
        // prepare an incoming fresh command
        ReplicationCoordinator::ReplSetFreshArgs freshArgs;
        freshArgs.setName = "rs0";
        freshArgs.cfgver = 5;
        freshArgs.id = 2;
        freshArgs.who = HostAndPort("host3");
        freshArgs.opTime = fresherOpApplied.getTimestamp();

        BSONObjBuilder freshResponseBuilder;
        Status result = Status(ErrorCodes::InternalError, "status not set by prepareElectResponse");
        getTopoCoord().prepareFreshResponse(
                freshArgs, now()++, lastOpTimeApplied, &freshResponseBuilder, &result);
        BSONObj response = freshResponseBuilder.obj();
        ASSERT_OK(result);
        ASSERT_EQUALS(lastOpTimeApplied.getTimestamp(), Timestamp(response["opTime"].timestampValue()));
        ASSERT_FALSE(response["fresher"].trueValue());
        ASSERT_FALSE(response["veto"].trueValue());
        ASSERT_TRUE(TopologyCoordinator::Role::candidate == getTopoCoord().getRole());
        // make sure incoming fresh commands do not change electionTime and electionId
        ASSERT_EQUALS(originalElectionTime, getTopoCoord().getElectionTime());
        ASSERT_EQUALS(originalElectionId, getTopoCoord().getElectionId());

        // an elect command comes in
        ReplicationCoordinator::ReplSetElectArgs electArgs;
        OID round = OID::gen();
        electArgs.set = "rs0";
        electArgs.round = round;
        electArgs.cfgver = 5;
        electArgs.whoid = 2;

        BSONObjBuilder electResponseBuilder;
        result = Status(ErrorCodes::InternalError, "status not set by prepareElectResponse");
        startCapturingLogMessages();
        getTopoCoord().prepareElectResponse(
                electArgs, now()++, OpTime(), &electResponseBuilder, &result);
        stopCapturingLogMessages();
        response = electResponseBuilder.obj();
        ASSERT_OK(result);
        ASSERT_EQUALS(1, response["vote"].Int());
        ASSERT_EQUALS(round, response["round"].OID());
        ASSERT_EQUALS(1, countLogLinesContaining("voting yea for host3:27017 (2)"));
        ASSERT_TRUE(TopologyCoordinator::Role::candidate == getTopoCoord().getRole());
        // make sure incoming elect commands do not change electionTime and electionId
        ASSERT_EQUALS(originalElectionTime, getTopoCoord().getElectionTime());
        ASSERT_EQUALS(originalElectionId, getTopoCoord().getElectionId());

        // now voteForSelf as though we received all our fresh responses
        ASSERT_FALSE(getTopoCoord().voteForMyself(now()++));

        // receive a heartbeat indicating the other node was elected
        nextAction = receiveUpHeartbeat(HostAndPort("host3"),
                                        "rs0",
                                        MemberState::RS_PRIMARY,
                                        election,
                                        lastOpTimeApplied,
                                        lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());
        ASSERT_EQUALS(2, getCurrentPrimaryIndex());
        // make sure seeing a new primary does not change electionTime and electionId
        ASSERT_EQUALS(originalElectionTime, getTopoCoord().getElectionTime());
        ASSERT_EQUALS(originalElectionId, getTopoCoord().getElectionId());

        // now lose election and ensure _electionTime and _electionId are 0'd out 
        getTopoCoord().processLoseElection();
        ASSERT_EQUALS(OID(), getTopoCoord().getElectionId());
        ASSERT_EQUALS(Timestamp(), getTopoCoord().getElectionTime());
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
        ASSERT_EQUALS(2, getCurrentPrimaryIndex());
    }

    TEST_F(HeartbeatResponseTest, ElectionRespondToFreshBeforeOurFreshnessReturns) {
        // In this test, the TopologyCoordinator goes through the steps of an election. However,
        // before its freshness round ends, the TopologyCoordinator receives a fresh command from
        // another node, which it responds positively to. Its freshness then ends successfully and
        // it wins the election. The other node's elect command then comes in and is responded to
        // negatively, maintaining the TopologyCoordinator's PRIMARY state.

        // 1. All nodes heartbeat to indicate that they are up and that "host2" is PRIMARY.
        // 2. "host2" goes down, triggering an election.
        // 3. "host3" sends a fresh command, which the TopologyCoordinator responds to positively.
        // 4. The TopologyCoordinator concludes its freshness round successfully and wins
        //    the election.
        // 5. "host3" sends an elect command, which the TopologyCoordinator responds to negatively.

        setSelfMemberState(MemberState::RS_SECONDARY);
        now() += Seconds(30); // we need to be more than LastVote::leaseTime from the start of time or
                              // else some Date_t math goes horribly awry

        OpTime election = OpTime();
        OpTime lastOpTimeApplied = OpTime(Timestamp(100,0), 0);
        OpTime fresherLastOpTimeApplied = OpTime(Timestamp(200,0), 0);
        OID round = OID::gen();
        OID remoteRound = OID::gen();

        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        HeartbeatResponseAction nextAction = receiveUpHeartbeat(HostAndPort("host2"),
                                                                "rs0",
                                                                MemberState::RS_PRIMARY,
                                                                election,
                                                                lastOpTimeApplied,
                                                                lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());
        ASSERT_EQUALS(1, getCurrentPrimaryIndex());

        nextAction = receiveUpHeartbeat(HostAndPort("host3"),
                                        "rs0",
                                        MemberState::RS_SECONDARY,
                                        election,
                                        lastOpTimeApplied,
                                        lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());

        // candidate time!
        nextAction = receiveDownHeartbeat(HostAndPort("host2"), "rs0", lastOpTimeApplied);
        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        ASSERT_EQUALS(HeartbeatResponseAction::StartElection, nextAction.getAction());
        ASSERT_TRUE(TopologyCoordinator::Role::candidate == getTopoCoord().getRole());

        // prepare an incoming fresh command
        ReplicationCoordinator::ReplSetFreshArgs freshArgs;
        freshArgs.setName = "rs0";
        freshArgs.cfgver = 5;
        freshArgs.id = 2;
        freshArgs.who = HostAndPort("host3");
        freshArgs.opTime = fresherLastOpTimeApplied.getTimestamp();

        BSONObjBuilder freshResponseBuilder;
        Status result = Status(ErrorCodes::InternalError, "status not set by prepareElectResponse");
        getTopoCoord().prepareFreshResponse(
                freshArgs, now()++, lastOpTimeApplied, &freshResponseBuilder, &result);
        BSONObj response = freshResponseBuilder.obj();
        ASSERT_OK(result);
        ASSERT_EQUALS(lastOpTimeApplied.getTimestamp(), Timestamp(response["opTime"].timestampValue()));
        ASSERT_FALSE(response["fresher"].trueValue());
        ASSERT_FALSE(response["veto"].trueValue());
        ASSERT_TRUE(TopologyCoordinator::Role::candidate == getTopoCoord().getRole());

        // now voteForSelf as though we received all our fresh responses
        ASSERT_TRUE(getTopoCoord().voteForMyself(now()++));
        // now win election and ensure _electionId and _electionTime are set properly
        getTopoCoord().processWinElection(round, election.getTimestamp());
        ASSERT_EQUALS(round, getTopoCoord().getElectionId());
        ASSERT_EQUALS(election.getTimestamp(), getTopoCoord().getElectionTime());
        ASSERT_TRUE(TopologyCoordinator::Role::leader == getTopoCoord().getRole());
        ASSERT_EQUALS(0, getCurrentPrimaryIndex());

        // an elect command comes in
        ReplicationCoordinator::ReplSetElectArgs electArgs;
        electArgs.set = "rs0";
        electArgs.round = remoteRound;
        electArgs.cfgver = 5;
        electArgs.whoid = 2;

        BSONObjBuilder electResponseBuilder;
        result = Status(ErrorCodes::InternalError, "status not set by prepareElectResponse");
        startCapturingLogMessages();
        getTopoCoord().prepareElectResponse(
                electArgs, now()++, OpTime(), &electResponseBuilder, &result);
        stopCapturingLogMessages();
        response = electResponseBuilder.obj();
        ASSERT_OK(result);
        ASSERT_EQUALS(-10000, response["vote"].Int());
        ASSERT_EQUALS(remoteRound, response["round"].OID());
        ASSERT_TRUE(TopologyCoordinator::Role::leader == getTopoCoord().getRole());
        ASSERT_EQUALS(0, getCurrentPrimaryIndex());
    }

    TEST_F(HeartbeatResponseTest, ElectionCompleteElectionThenReceiveFresh) {
        // In this test, the TopologyCoordinator goes through the steps of an election. After
        // being successfully elected, a fresher node sends a fresh command, which the
        // TopologyCoordinator responds positively to. The fresher node then sends an elect command,
        // which the Topology coordinator negatively to since the TopologyCoordinator just elected
        // itself.

        // 1. All nodes heartbeat to indicate that they are up and that "host2" is PRIMARY.
        // 2. "host2" goes down, triggering an election.
        // 3. The TopologyCoordinator concludes its freshness round successfully and wins
        //    the election.
        // 4. "host3" sends a fresh command, which the TopologyCoordinator responds to positively.
        // 5. "host3" sends an elect command, which the TopologyCoordinator responds to negatively.

        setSelfMemberState(MemberState::RS_SECONDARY);
        now() += Seconds(30); // we need to be more than LastVote::leaseTime from the start of time or
                              // else some Date_t math goes horribly awry

        OpTime election = OpTime();
        OpTime lastOpTimeApplied = OpTime(Timestamp(100,0), 0);
        OpTime fresherLastOpTimeApplied = OpTime(Timestamp(200,0), 0);
        OID round = OID::gen();
        OID remoteRound = OID::gen();

        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        HeartbeatResponseAction nextAction = receiveUpHeartbeat(HostAndPort("host2"),
                                                                "rs0",
                                                                MemberState::RS_PRIMARY,
                                                                election,
                                                                lastOpTimeApplied,
                                                                lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());
        ASSERT_EQUALS(1, getCurrentPrimaryIndex());

        nextAction = receiveUpHeartbeat(HostAndPort("host3"),
                                        "rs0",
                                        MemberState::RS_SECONDARY,
                                        election,
                                        lastOpTimeApplied,
                                        lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());

        // candidate time!
        nextAction = receiveDownHeartbeat(HostAndPort("host2"), "rs0", lastOpTimeApplied);
        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        ASSERT_EQUALS(HeartbeatResponseAction::StartElection, nextAction.getAction());
        ASSERT_TRUE(TopologyCoordinator::Role::candidate == getTopoCoord().getRole());

        // now voteForSelf as though we received all our fresh responses
        ASSERT_TRUE(getTopoCoord().voteForMyself(now()++));
        // now win election
        getTopoCoord().processWinElection(round, election.getTimestamp());
        ASSERT_EQUALS(0, getTopoCoord().getCurrentPrimaryIndex());
        ASSERT_TRUE(TopologyCoordinator::Role::leader == getTopoCoord().getRole());

        // prepare an incoming fresh command
        ReplicationCoordinator::ReplSetFreshArgs freshArgs;
        freshArgs.setName = "rs0";
        freshArgs.cfgver = 5;
        freshArgs.id = 2;
        freshArgs.who = HostAndPort("host3");
        freshArgs.opTime = fresherLastOpTimeApplied.getTimestamp();

        BSONObjBuilder freshResponseBuilder;
        Status result = Status(ErrorCodes::InternalError, "status not set by prepareElectResponse");
        getTopoCoord().prepareFreshResponse(
                freshArgs, now()++, lastOpTimeApplied, &freshResponseBuilder, &result);
        BSONObj response = freshResponseBuilder.obj();
        ASSERT_OK(result);
        ASSERT_EQUALS(lastOpTimeApplied.getTimestamp(),
                      Timestamp(response["opTime"].timestampValue()));
        ASSERT_FALSE(response["fresher"].trueValue());
        ASSERT_TRUE(response["veto"].trueValue()) << response["errmsg"];
        ASSERT_TRUE(TopologyCoordinator::Role::leader == getTopoCoord().getRole());
        ASSERT_EQUALS(0, getCurrentPrimaryIndex());

        // an elect command comes in
        ReplicationCoordinator::ReplSetElectArgs electArgs;
        electArgs.set = "rs0";
        electArgs.round = remoteRound;
        electArgs.cfgver = 5;
        electArgs.whoid = 2;

        BSONObjBuilder electResponseBuilder;
        result = Status(ErrorCodes::InternalError, "status not set by prepareElectResponse");
        startCapturingLogMessages();
        getTopoCoord().prepareElectResponse(
                electArgs, now()++, OpTime(), &electResponseBuilder, &result);
        stopCapturingLogMessages();
        response = electResponseBuilder.obj();
        ASSERT_OK(result);
        ASSERT_EQUALS(-10000, response["vote"].Int());
        ASSERT_EQUALS(remoteRound, response["round"].OID());
        ASSERT_TRUE(TopologyCoordinator::Role::leader == getTopoCoord().getRole());
        ASSERT_EQUALS(0, getCurrentPrimaryIndex());
    }

    TEST_F(HeartbeatResponseTest, UpdateHeartbeatDataPrimaryDownMajorityOfVotersUp) {
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 5 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 0 << "host" << "host1:27017") <<
                              BSON("_id" << 1 << "host" << "host2:27017") <<
                              BSON("_id" << 2 << "host" << "host3:27017" << "votes" << 0) <<
                              BSON("_id" << 3 << "host" << "host4:27017" << "votes" << 0) <<
                              BSON("_id" << 4 << "host" << "host5:27017" << "votes" << 0) <<
                              BSON("_id" << 5 << "host" << "host6:27017" << "votes" << 0) <<
                              BSON("_id" << 6 << "host" << "host7:27017")) <<
                          "settings" << BSON("heartbeatTimeoutSecs" << 5)),
                     0);

        setSelfMemberState(MemberState::RS_SECONDARY);

        OpTime election = OpTime(Timestamp(400,0), 0);
        OpTime lastOpTimeApplied = OpTime(Timestamp(300,0), 0);

        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        HeartbeatResponseAction nextAction = receiveUpHeartbeat(HostAndPort("host2"),
                                                                "rs0",
                                                                MemberState::RS_PRIMARY,
                                                                election,
                                                                election,
                                                                lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());
        ASSERT_EQUALS(1, getCurrentPrimaryIndex());

        // make sure all non-voting nodes are down, that way we do not have a majority of nodes
        // but do have a majority of votes since one of two voting members is up and so are we
        nextAction = receiveDownHeartbeat(HostAndPort("host3"), "rs0", lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());
        nextAction = receiveDownHeartbeat(HostAndPort("host4"), "rs0", lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());
        nextAction = receiveDownHeartbeat(HostAndPort("host5"), "rs0", lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());
        nextAction = receiveDownHeartbeat(HostAndPort("host6"), "rs0", lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());
        nextAction = receiveUpHeartbeat(HostAndPort("host7"),
                                        "rs0",
                                        MemberState::RS_SECONDARY,
                                        election,
                                        lastOpTimeApplied,
                                        lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());

        nextAction = receiveDownHeartbeat(HostAndPort("host2"), "rs0", lastOpTimeApplied);
        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        ASSERT_EQUALS(HeartbeatResponseAction::StartElection, nextAction.getAction());
        ASSERT_TRUE(TopologyCoordinator::Role::candidate == getTopoCoord().getRole());
    }

    TEST_F(HeartbeatResponseTest, UpdateHeartbeatDataRelinquishPrimaryDueToNodeDisappearing) {
        // become PRIMARY
        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        makeSelfPrimary(Timestamp(2,0));
        ASSERT_EQUALS(0, getCurrentPrimaryIndex());

        // become aware of other nodes
        heartbeatFromMember(HostAndPort("host2"), "rs0",
                            MemberState::RS_SECONDARY, OpTime(Timestamp(1,0), 0));
        heartbeatFromMember(HostAndPort("host2"), "rs0",
                            MemberState::RS_SECONDARY, OpTime(Timestamp(1,0), 0));
        heartbeatFromMember(HostAndPort("host3"), "rs0", MemberState::RS_SECONDARY, OpTime());
        heartbeatFromMember(HostAndPort("host3"), "rs0", MemberState::RS_SECONDARY, OpTime());

        // lose that awareness and be sure we are going to stepdown
        HeartbeatResponseAction nextAction = receiveDownHeartbeat(HostAndPort("host2"),
                                                                  "rs0",
                                                                  OpTime(Timestamp(100, 0), 0));
        ASSERT_NO_ACTION(nextAction.getAction());
        nextAction =
            receiveDownHeartbeat(HostAndPort("host3"), "rs0", OpTime(Timestamp(100, 0), 0));
        ASSERT_EQUALS(HeartbeatResponseAction::StepDownSelf, nextAction.getAction());
        ASSERT_EQUALS(0, nextAction.getPrimaryConfigIndex());
        // Doesn't actually do the stepdown until stepDownIfPending is called
        ASSERT_TRUE(TopologyCoordinator::Role::leader == getTopoCoord().getRole());
        ASSERT_EQUALS(0, getCurrentPrimaryIndex());

        ASSERT_TRUE(getTopoCoord().stepDownIfPending());
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
    }

    TEST_F(HeartbeatResponseTest, UpdateHeartbeatDataRemoteDoesNotExist) {
        OpTime election = OpTime(Timestamp(5,0), 0);
        OpTime lastOpTimeApplied = OpTime(Timestamp(3,0), 0);

        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        HeartbeatResponseAction nextAction = receiveUpHeartbeat(HostAndPort("host9"),
                                                                "rs0",
                                                                MemberState::RS_PRIMARY,
                                                                election,
                                                                election,
                                                                lastOpTimeApplied);
        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        ASSERT_NO_ACTION(nextAction.getAction());
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
    }

    class PrepareElectResponseTest : public TopoCoordTest {
    public:

        PrepareElectResponseTest() :
            round(OID::gen()),
            cbData(NULL, ReplicationExecutor::CallbackHandle(), Status::OK()) {}

        virtual void setUp() {
            TopoCoordTest::setUp();
            updateConfig(BSON("_id" << "rs0" <<
                              "version" << 10 <<
                              "members" << BSON_ARRAY(
                                  BSON("_id" << 0 << "host" << "hself") <<
                                  BSON("_id" << 1 << "host" << "h1") <<
                                  BSON("_id" << 2 <<
                                       "host" << "h2" <<
                                       "priority" << 10) <<
                                  BSON("_id" << 3 <<
                                       "host" << "h3" <<
                                       "priority" << 10))),
                         0);
        }

    protected:
        Date_t now;
        OID round;
        ReplicationExecutor::CallbackData cbData;
    };

    TEST_F(PrepareElectResponseTest, ElectResponseIncorrectReplSetName) {
        // Test with incorrect replset name
        ReplicationCoordinator::ReplSetElectArgs args;
        args.set = "fakeset";
        args.round = round;
        args.cfgver = 10;
        args.whoid = 1;

        BSONObjBuilder responseBuilder;
        Status result = Status(ErrorCodes::InternalError, "status not set by prepareElectResponse");
        startCapturingLogMessages();
        getTopoCoord().prepareElectResponse(args,
                                            now += Seconds(60),
                                            OpTime(),
                                            &responseBuilder,
                                            &result);
        stopCapturingLogMessages();
        BSONObj response = responseBuilder.obj();
        ASSERT_OK(result);
        ASSERT_EQUALS(0, response["vote"].Int());
        ASSERT_EQUALS(round, response["round"].OID());
        ASSERT_EQUALS(1,
                      countLogLinesContaining("received an elect request for 'fakeset' but our "
                              "set name is 'rs0'"));

        // Make sure nay votes, do not prevent subsequent yeas (the way a yea vote would)
        args.set = "rs0";
        BSONObjBuilder responseBuilder2;
        getTopoCoord().prepareElectResponse(args, now++, OpTime(), &responseBuilder2, &result);
        BSONObj response2 = responseBuilder2.obj();
        ASSERT_EQUALS(1, response2["vote"].Int());
        ASSERT_EQUALS(round, response2["round"].OID());
    }

    TEST_F(PrepareElectResponseTest, ElectResponseOurConfigStale) {
        // Test with us having a stale config version
        ReplicationCoordinator::ReplSetElectArgs args;
        args.set = "rs0";
        args.round = round;
        args.cfgver = 20;
        args.whoid = 1;

        BSONObjBuilder responseBuilder;
        Status result = Status(ErrorCodes::InternalError, "status not set by prepareElectResponse");
        startCapturingLogMessages();
        getTopoCoord().prepareElectResponse(args,
                                            now += Seconds(60),
                                            OpTime(),
                                            &responseBuilder,
                                            &result);
        stopCapturingLogMessages();
        BSONObj response = responseBuilder.obj();
        ASSERT_OK(result);
        ASSERT_EQUALS(0, response["vote"].Int());
        ASSERT_EQUALS(round, response["round"].OID());
        ASSERT_EQUALS(1,
                      countLogLinesContaining("not voting because our config version is stale"));

        // Make sure nay votes, do not prevent subsequent yeas (the way a yea vote would)
        args.cfgver = 10;
        BSONObjBuilder responseBuilder2;
        getTopoCoord().prepareElectResponse(args, now++, OpTime(), &responseBuilder2, &result);
        BSONObj response2 = responseBuilder2.obj();
        ASSERT_EQUALS(1, response2["vote"].Int());
        ASSERT_EQUALS(round, response2["round"].OID());
    }

    TEST_F(PrepareElectResponseTest, ElectResponseTheirConfigStale) {
        // Test with them having a stale config version
        ReplicationCoordinator::ReplSetElectArgs args;
        args.set = "rs0";
        args.round = round;
        args.cfgver = 5;
        args.whoid = 1;

        BSONObjBuilder responseBuilder;
        Status result = Status(ErrorCodes::InternalError, "status not set by prepareElectResponse");
        startCapturingLogMessages();
        getTopoCoord().prepareElectResponse(args,
                                            now += Seconds(60),
                                            OpTime(),
                                            &responseBuilder,
                                            &result);
        stopCapturingLogMessages();
        BSONObj response = responseBuilder.obj();
        ASSERT_OK(result);
        ASSERT_EQUALS(-10000, response["vote"].Int());
        ASSERT_EQUALS(round, response["round"].OID());
        ASSERT_EQUALS(1,
                      countLogLinesContaining("received stale config version # during election"));

        // Make sure nay votes, do not prevent subsequent yeas (the way a yea vote would)
        args.cfgver = 10;
        BSONObjBuilder responseBuilder2;
        getTopoCoord().prepareElectResponse(args, now++, OpTime(), &responseBuilder2, &result);
        BSONObj response2 = responseBuilder2.obj();
        ASSERT_EQUALS(1, response2["vote"].Int());
        ASSERT_EQUALS(round, response2["round"].OID());
    }

    TEST_F(PrepareElectResponseTest, ElectResponseNonExistentNode) {
        // Test with a non-existent node
        ReplicationCoordinator::ReplSetElectArgs args;
        args.set = "rs0";
        args.round = round;
        args.cfgver = 10;
        args.whoid = 99;

        BSONObjBuilder responseBuilder;
        Status result = Status(ErrorCodes::InternalError, "status not set by prepareElectResponse");
        startCapturingLogMessages();
        getTopoCoord().prepareElectResponse(args,
                                            now += Seconds(60),
                                            OpTime(),
                                            &responseBuilder,
                                            &result);
        stopCapturingLogMessages();
        BSONObj response = responseBuilder.obj();
        ASSERT_OK(result);
        ASSERT_EQUALS(-10000, response["vote"].Int());
        ASSERT_EQUALS(round, response["round"].OID());
        ASSERT_EQUALS(1, countLogLinesContaining("couldn't find member with id 99"));

        // Make sure nay votes, do not prevent subsequent yeas (the way a yea vote would)
        args.whoid = 1;
        BSONObjBuilder responseBuilder2;
        getTopoCoord().prepareElectResponse(args, now++, OpTime(), &responseBuilder2, &result);
        BSONObj response2 = responseBuilder2.obj();
        ASSERT_EQUALS(1, response2["vote"].Int());
        ASSERT_EQUALS(round, response2["round"].OID());
    }

    TEST_F(PrepareElectResponseTest, ElectResponseWeArePrimary) {
        // Test when we are already primary
        ReplicationCoordinator::ReplSetElectArgs args;
        args.set = "rs0";
        args.round = round;
        args.cfgver = 10;
        args.whoid = 1;

        getTopoCoord()._setCurrentPrimaryForTest(0);

        BSONObjBuilder responseBuilder;
        Status result = Status(ErrorCodes::InternalError, "status not set by prepareElectResponse");
        startCapturingLogMessages();
        getTopoCoord().prepareElectResponse(args,
                                            now += Seconds(60),
                                            OpTime(),
                                            &responseBuilder,
                                            &result);
        stopCapturingLogMessages();
        BSONObj response = responseBuilder.obj();
        ASSERT_OK(result);
        ASSERT_EQUALS(-10000, response["vote"].Int());
        ASSERT_EQUALS(round, response["round"].OID());
        ASSERT_EQUALS(1, countLogLinesContaining("I am already primary"));

        // Make sure nay votes, do not prevent subsequent yeas (the way a yea vote would)
        getTopoCoord()._setCurrentPrimaryForTest(-1);
        BSONObjBuilder responseBuilder2;
        getTopoCoord().prepareElectResponse(args, now++, OpTime(), &responseBuilder2, &result);
        BSONObj response2 = responseBuilder2.obj();
        ASSERT_EQUALS(1, response2["vote"].Int());
        ASSERT_EQUALS(round, response2["round"].OID());
    }

    TEST_F(PrepareElectResponseTest, ElectResponseSomeoneElseIsPrimary) {
        // Test when someone else is already primary
        ReplicationCoordinator::ReplSetElectArgs args;
        args.set = "rs0";
        args.round = round;
        args.cfgver = 10;
        args.whoid = 1;
        getTopoCoord()._setCurrentPrimaryForTest(2);

        BSONObjBuilder responseBuilder;
        Status result = Status(ErrorCodes::InternalError, "status not set by prepareElectResponse");
        startCapturingLogMessages();
        getTopoCoord().prepareElectResponse(args,
                                            now += Seconds(60),
                                            OpTime(),
                                            &responseBuilder,
                                            &result);
        stopCapturingLogMessages();
        BSONObj response = responseBuilder.obj();
        ASSERT_OK(result);
        ASSERT_EQUALS(-10000, response["vote"].Int());
        ASSERT_EQUALS(round, response["round"].OID());
        ASSERT_EQUALS(1, countLogLinesContaining("h2:27017 is already primary"));

        // Make sure nay votes, do not prevent subsequent yeas (the way a yea vote would)
        getTopoCoord()._setCurrentPrimaryForTest(-1);
        BSONObjBuilder responseBuilder2;
        getTopoCoord().prepareElectResponse(args, now++, OpTime(), &responseBuilder2, &result);
        BSONObj response2 = responseBuilder2.obj();
        ASSERT_EQUALS(1, response2["vote"].Int());
        ASSERT_EQUALS(round, response2["round"].OID());
    }

    TEST_F(PrepareElectResponseTest, ElectResponseNotHighestPriority) {
        // Test trying to elect someone who isn't the highest priority node
        ReplicationCoordinator::ReplSetElectArgs args;
        args.set = "rs0";
        args.round = round;
        args.cfgver = 10;
        args.whoid = 1;

        heartbeatFromMember(HostAndPort("h3"), "rs0", MemberState::RS_SECONDARY, OpTime());

        BSONObjBuilder responseBuilder;
        Status result = Status(ErrorCodes::InternalError, "status not set by prepareElectResponse");
        startCapturingLogMessages();
        getTopoCoord().prepareElectResponse(args,
                                            now += Seconds(60),
                                            OpTime(),
                                            &responseBuilder,
                                            &result);
        stopCapturingLogMessages();
        BSONObj response = responseBuilder.obj();
        ASSERT_OK(result);
        ASSERT_EQUALS(-10000, response["vote"].Int());
        ASSERT_EQUALS(round, response["round"].OID());
        ASSERT_EQUALS(1, countLogLinesContaining("h1:27017 has lower priority than h3:27017"));

        // Make sure nay votes, do not prevent subsequent yeas (the way a yea vote would)
        args.whoid = 3;
        BSONObjBuilder responseBuilder2;
        getTopoCoord().prepareElectResponse(args, now++, OpTime(), &responseBuilder2, &result);
        BSONObj response2 = responseBuilder2.obj();
        ASSERT_EQUALS(1, response2["vote"].Int());
        ASSERT_EQUALS(round, response2["round"].OID());
    }

    TEST_F(PrepareElectResponseTest, ElectResponseHighestPriorityOfLiveNodes) {
        // Test trying to elect someone who isn't the highest priority node, but all higher nodes
        // are down
        ReplicationCoordinator::ReplSetElectArgs args;
        args.set = "rs0";
        args.round = round;
        args.cfgver = 10;
        args.whoid = 1;

        receiveDownHeartbeat(HostAndPort("h3"), "rs0", OpTime());
        receiveDownHeartbeat(HostAndPort("h2"), "rs0", OpTime());

        BSONObjBuilder responseBuilder;
        Status result = Status::OK();
        startCapturingLogMessages();
        getTopoCoord().prepareElectResponse(args,
                                            now += Seconds(60),
                                            OpTime(),
                                            &responseBuilder,
                                            &result);
        stopCapturingLogMessages();
        BSONObj response = responseBuilder.obj();
        ASSERT_EQUALS(1, response["vote"].Int());
        ASSERT_EQUALS(round, response["round"].OID());
    }

    TEST_F(PrepareElectResponseTest, ElectResponseValidVotes) {
        // Test a valid vote
        ReplicationCoordinator::ReplSetElectArgs args;
        args.set = "rs0";
        args.round = round;
        args.cfgver = 10;
        args.whoid = 2;
        now = Date_t::fromMillisSinceEpoch(100);

        BSONObjBuilder responseBuilder1;
        Status result = Status(ErrorCodes::InternalError, "status not set by prepareElectResponse");
        startCapturingLogMessages();
        getTopoCoord().prepareElectResponse(args,
                                            now += Seconds(60),
                                            OpTime(),
                                            &responseBuilder1,
                                            &result);
        stopCapturingLogMessages();
        BSONObj response1 = responseBuilder1.obj();
        ASSERT_OK(result);
        ASSERT_EQUALS(1, response1["vote"].Int());
        ASSERT_EQUALS(round, response1["round"].OID());
        ASSERT_EQUALS(1, countLogLinesContaining("voting yea for h2:27017 (2)"));

        // Test what would be a valid vote except that we already voted too recently
        args.whoid = 3;

        BSONObjBuilder responseBuilder2;
        startCapturingLogMessages();
        getTopoCoord().prepareElectResponse(args, now, OpTime(), &responseBuilder2, &result);
        stopCapturingLogMessages();
        BSONObj response2 = responseBuilder2.obj();
        ASSERT_OK(result);
        ASSERT_EQUALS(0, response2["vote"].Int());
        ASSERT_EQUALS(round, response2["round"].OID());
        ASSERT_EQUALS(1, countLogLinesContaining("voting no for h3:27017; "
                "voted for h2:27017 0 secs ago"));

        // Test that after enough time passes the same vote can proceed
        now += Seconds(30) + Milliseconds(1); // just over 30 seconds later

        BSONObjBuilder responseBuilder3;
        startCapturingLogMessages();
        getTopoCoord().prepareElectResponse(args, now++, OpTime(), &responseBuilder3, &result);
        stopCapturingLogMessages();
        BSONObj response3 = responseBuilder3.obj();
        ASSERT_OK(result);
        ASSERT_EQUALS(1, response3["vote"].Int());
        ASSERT_EQUALS(round, response3["round"].OID());
        ASSERT_EQUALS(1, countLogLinesContaining("voting yea for h3:27017 (3)"));
    }

    TEST_F(TopoCoordTest, ElectResponseNotInConfig) {
        ReplicationCoordinator::ReplSetElectArgs args;
        BSONObjBuilder response;
        Status status = Status(ErrorCodes::InternalError, "status not set by prepareElectResponse");
        getTopoCoord().prepareElectResponse(args, now(), OpTime(), &response, &status);
        ASSERT_EQUALS(ErrorCodes::ReplicaSetNotFound, status);
        ASSERT_EQUALS("Cannot participate in election because not initialized", status.reason());
    }

    class PrepareFreezeResponseTest : public TopoCoordTest {
    public:

        virtual void setUp() {
            TopoCoordTest::setUp();
            updateConfig(BSON("_id" << "rs0" <<
                              "version" << 5 <<
                              "members" << BSON_ARRAY(
                                  BSON("_id" << 0 << "host" << "host1:27017") <<
                                  BSON("_id" << 1 << "host" << "host2:27017"))),
                         0);
        }

        BSONObj prepareFreezeResponse(int duration) {
            BSONObjBuilder response;
            startCapturingLogMessages();
            getTopoCoord().prepareFreezeResponse(now()++, duration, &response);
            stopCapturingLogMessages();
            return response.obj();
        }
    };

    TEST_F(PrepareFreezeResponseTest, UnfreezeEvenWhenNotFrozen) {
        BSONObj response = prepareFreezeResponse(0);
        ASSERT_EQUALS("unfreezing", response["info"].String());
        ASSERT_EQUALS(1, countLogLinesContaining("'unfreezing'"));
        // 1 instead of 0 because it assigns to "now" in this case
        ASSERT_EQUALS(1LL, getTopoCoord().getStepDownTime().asInt64());
    }

    TEST_F(PrepareFreezeResponseTest, FreezeForOneSecond) {
        BSONObj response = prepareFreezeResponse(1);
        ASSERT_EQUALS("you really want to freeze for only 1 second?",
                      response["warning"].String());
        ASSERT_EQUALS(1, countLogLinesContaining("'freezing' for 1 seconds"));
        // 1001 because "now" was incremented once during initialization + 1000 ms wait
        ASSERT_EQUALS(1001LL, getTopoCoord().getStepDownTime().asInt64());
    }

    TEST_F(PrepareFreezeResponseTest, FreezeForManySeconds) {
        BSONObj response = prepareFreezeResponse(20);
        ASSERT_TRUE(response.isEmpty());
        ASSERT_EQUALS(1, countLogLinesContaining("'freezing' for 20 seconds"));
        // 20001 because "now" was incremented once during initialization + 20000 ms wait
        ASSERT_EQUALS(20001LL, getTopoCoord().getStepDownTime().asInt64());
    }

    TEST_F(PrepareFreezeResponseTest, UnfreezeEvenWhenNotFrozenWhilePrimary) {
        makeSelfPrimary();
        BSONObj response = prepareFreezeResponse(0);
        ASSERT_EQUALS("unfreezing", response["info"].String());
        // doesn't mention being primary in this case for some reason
        ASSERT_EQUALS(0, countLogLinesContaining(
                "received freeze command but we are primary"));
        // 1 instead of 0 because it assigns to "now" in this case
        ASSERT_EQUALS(1LL, getTopoCoord().getStepDownTime().asInt64());
    }

    TEST_F(PrepareFreezeResponseTest, FreezeForOneSecondWhilePrimary) {
        makeSelfPrimary();
        BSONObj response = prepareFreezeResponse(1);
        ASSERT_EQUALS("you really want to freeze for only 1 second?",
                      response["warning"].String());
        ASSERT_EQUALS(1, countLogLinesContaining(
                "received freeze command but we are primary"));
        ASSERT_EQUALS(0LL, getTopoCoord().getStepDownTime().asInt64());
    }

    TEST_F(PrepareFreezeResponseTest, FreezeForManySecondsWhilePrimary) {
        makeSelfPrimary();
        BSONObj response = prepareFreezeResponse(20);
        ASSERT_TRUE(response.isEmpty());
        ASSERT_EQUALS(1, countLogLinesContaining(
                "received freeze command but we are primary"));
        ASSERT_EQUALS(0LL, getTopoCoord().getStepDownTime().asInt64());
    }

    TEST_F(TopoCoordTest, UnfreezeWhileLoneNode) {
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 5 <<
                          "members" << BSON_ARRAY(BSON("_id" << 0 << "host" << "host1:27017"))),
                     0);
        setSelfMemberState(MemberState::RS_SECONDARY);
        
        BSONObjBuilder response;
        getTopoCoord().prepareFreezeResponse(now()++, 20, &response);
        ASSERT(response.obj().isEmpty());
        BSONObjBuilder response2;
        getTopoCoord().prepareFreezeResponse(now()++, 0, &response2);
        ASSERT_EQUALS("unfreezing", response2.obj()["info"].String());
        ASSERT(TopologyCoordinator::Role::candidate == getTopoCoord().getRole());
    }

    class ShutdownInProgressTest : public TopoCoordTest {
    public:

        ShutdownInProgressTest() :
            ourCbData(NULL,
                      ReplicationExecutor::CallbackHandle(),
                      Status(ErrorCodes::CallbackCanceled, "")) {}

        virtual ReplicationExecutor::CallbackData cbData() { return ourCbData; }

    private:
        ReplicationExecutor::CallbackData ourCbData;
    };

    TEST_F(ShutdownInProgressTest, ShutdownInProgressWhenCallbackCanceledSyncFrom) {
        Status result = Status::OK();
        BSONObjBuilder response;
        getTopoCoord().prepareSyncFromResponse(cbData(),
                                               HostAndPort("host2:27017"),
                                               OpTime(),
                                               &response,
                                               &result);
        ASSERT_EQUALS(ErrorCodes::ShutdownInProgress, result);
        ASSERT_TRUE(response.obj().isEmpty());

    }

    TEST_F(ShutdownInProgressTest, ShutDownInProgressWhenCallbackCanceledStatus) {
        Status result = Status::OK();
        BSONObjBuilder response;
        getTopoCoord().prepareStatusResponse(cbData(),
                                             Date_t(),
                                             0,
                                             OpTime(),
                                             &response,
                                             &result);
        ASSERT_EQUALS(ErrorCodes::ShutdownInProgress, result);
        ASSERT_TRUE(response.obj().isEmpty());
    }

    class PrepareHeartbeatResponseTest : public TopoCoordTest {
    public:

        virtual void setUp() {
            TopoCoordTest::setUp();
            updateConfig(BSON("_id" << "rs0" <<
                              "version" << 1 <<
                              "members" << BSON_ARRAY(
                                  BSON("_id" << 10 << "host" << "hself") <<
                                  BSON("_id" << 20 << "host" << "h2") <<
                                  BSON("_id" << 30 << "host" << "h3"))),
                         0);
            setSelfMemberState(MemberState::RS_SECONDARY);
        }

        void prepareHeartbeatResponse(const ReplSetHeartbeatArgs& args,
                                      OpTime lastOpApplied,
                                      ReplSetHeartbeatResponse* response,
                                      Status* result) {
            *result = getTopoCoord().prepareHeartbeatResponse(now()++,
                                                              args,
                                                              "rs0",
                                                              lastOpApplied,
                                                              response);
        }

    };

    class PrepareHeartbeatResponseV1Test : public TopoCoordTest {
    public:

        virtual void setUp() {
            TopoCoordTest::setUp();
            updateConfig(BSON("_id" << "rs0" <<
                              "version" << 1 <<
                              "members" << BSON_ARRAY(
                                  BSON("_id" << 10 << "host" << "hself") <<
                                  BSON("_id" << 20 << "host" << "h2") <<
                                  BSON("_id" << 30 << "host" << "h3")) <<
                              "protocolVersion" << 1),
                         0);
            setSelfMemberState(MemberState::RS_SECONDARY);
        }

        void prepareHeartbeatResponseV1(const ReplSetHeartbeatArgsV1& args,
                                        OpTime lastOpApplied,
                                        ReplSetHeartbeatResponse* response,
                                        Status* result) {
            *result = getTopoCoord().prepareHeartbeatResponseV1(now()++,
                                                                args,
                                                                "rs0",
                                                                lastOpApplied,
                                                                response);
        }

    };

    TEST_F(PrepareHeartbeatResponseV1Test, PrepareHeartbeatResponseBadSetName) {
        // set up args with incorrect replset name
        ReplSetHeartbeatArgsV1 args;
        args.setSetName("rs1");
        ReplSetHeartbeatResponse response;
        Status result(ErrorCodes::InternalError, "prepareHeartbeatResponse didn't set result");

        startCapturingLogMessages();
        prepareHeartbeatResponseV1(args, OpTime(), &response, &result);
        stopCapturingLogMessages();
        ASSERT_EQUALS(ErrorCodes::InconsistentReplicaSetNames, result);
        ASSERT(result.reason().find("repl set names do not match")) << "Actual string was \"" <<
               result.reason() << '"';
        ASSERT_EQUALS(1,
                      countLogLinesContaining("replSet set names do not match, ours: rs0; remote "
                            "node's: rs1"));
        // only protocolVersion should be set in this failure case
        ASSERT_EQUALS("", response.getReplicaSetName());
    }

    TEST_F(PrepareHeartbeatResponseV1Test, PrepareHeartbeatResponseWhenOutOfSet) {
        // reconfig self out of set
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 3 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 20 << "host" << "h2") <<
                              BSON("_id" << 30 << "host" << "h3")) <<
                          "protocolVersion" << 1),
                     -1);
        ReplSetHeartbeatArgsV1 args;
        args.setSetName("rs0");
        args.setSenderId(20);
        ReplSetHeartbeatResponse response;
        Status result(ErrorCodes::InternalError, "prepareHeartbeatResponse didn't set result");
        prepareHeartbeatResponseV1(args, OpTime(), &response, &result);
        ASSERT_EQUALS(ErrorCodes::InvalidReplicaSetConfig, result);
        ASSERT(result.reason().find("replica set configuration is invalid or does not include us"))
            << "Actual string was \"" << result.reason() << '"';
        // only protocolVersion should be set in this failure case
        ASSERT_EQUALS("", response.getReplicaSetName());
    }

    TEST_F(PrepareHeartbeatResponseV1Test, PrepareHeartbeatResponseFromSelf) {
        // set up args with our id as the senderId
        ReplSetHeartbeatArgsV1 args;
        args.setSetName("rs0");
        args.setSenderId(10);
        ReplSetHeartbeatResponse response;
        Status result(ErrorCodes::InternalError, "prepareHeartbeatResponse didn't set result");
        prepareHeartbeatResponseV1(args, OpTime(), &response, &result);
        ASSERT_EQUALS(ErrorCodes::BadValue, result);
        ASSERT(result.reason().find("from member with the same member ID as our self")) <<
                "Actual string was \"" << result.reason() << '"';
        // only protocolVersion should be set in this failure case
        ASSERT_EQUALS("", response.getReplicaSetName());
    }

    TEST_F(TopoCoordTest, PrepareHeartbeatResponseV1NoConfigYet) {
        // set up args and acknowledge sender
        ReplSetHeartbeatArgsV1 args;
        args.setSetName("rs0");
        args.setSenderId(20);
        ReplSetHeartbeatResponse response;
        // prepare response and check the results
        Status result = getTopoCoord().prepareHeartbeatResponseV1(now()++,
                                                                  args,
                                                                  "rs0",
                                                                  OpTime(),
                                                                  &response);
        ASSERT_OK(result);
        // this change to true because we can now see a majority, unlike in the previous cases
        ASSERT_EQUALS("rs0", response.getReplicaSetName());
        ASSERT_EQUALS(MemberState::RS_STARTUP, response.getState().s);
        ASSERT_EQUALS(OpTime(), response.getOpTime());
        ASSERT_EQUALS(0, response.getTerm());
        ASSERT_EQUALS(-2, response.getConfigVersion());
    }

    TEST_F(PrepareHeartbeatResponseV1Test, PrepareHeartbeatResponseSenderIDMissing) {
        // set up args without a senderID
        ReplSetHeartbeatArgsV1 args;
        args.setSetName("rs0");
        args.setConfigVersion(1);
        ReplSetHeartbeatResponse response;
        Status result(ErrorCodes::InternalError, "prepareHeartbeatResponse didn't set result");

        // prepare response and check the results
        prepareHeartbeatResponseV1(args, OpTime(), &response, &result);
        ASSERT_OK(result);
        ASSERT_EQUALS("rs0", response.getReplicaSetName());
        ASSERT_EQUALS(MemberState::RS_SECONDARY, response.getState().s);
        ASSERT_EQUALS(OpTime(), response.getOpTime());
        ASSERT_EQUALS(0, response.getTerm());
        ASSERT_EQUALS(1, response.getConfigVersion());
    }

    TEST_F(PrepareHeartbeatResponseV1Test, PrepareHeartbeatResponseSenderIDNotInConfig) {
        // set up args with a senderID which is not present in our config
        ReplSetHeartbeatArgsV1 args;
        args.setSetName("rs0");
        args.setConfigVersion(1);
        args.setSenderId(2);
        ReplSetHeartbeatResponse response;
        Status result(ErrorCodes::InternalError, "prepareHeartbeatResponse didn't set result");

        // prepare response and check the results
        prepareHeartbeatResponseV1(args, OpTime(), &response, &result);
        ASSERT_OK(result);
        ASSERT_EQUALS("rs0", response.getReplicaSetName());
        ASSERT_EQUALS(MemberState::RS_SECONDARY, response.getState().s);
        ASSERT_EQUALS(OpTime(), response.getOpTime());
        ASSERT_EQUALS(0, response.getTerm());
        ASSERT_EQUALS(1, response.getConfigVersion());
    }

    TEST_F(PrepareHeartbeatResponseV1Test, PrepareHeartbeatResponseConfigVersionLow) {
        // set up args with a config version lower than ours
        ReplSetHeartbeatArgsV1 args;
        args.setConfigVersion(0);
        args.setSetName("rs0");
        args.setSenderId(20);
        ReplSetHeartbeatResponse response;
        Status result(ErrorCodes::InternalError, "prepareHeartbeatResponse didn't set result");

        // prepare response and check the results
        prepareHeartbeatResponseV1(args, OpTime(), &response, &result);
        ASSERT_OK(result);
        ASSERT_TRUE(response.hasConfig());
        ASSERT_EQUALS("rs0", response.getReplicaSetName());
        ASSERT_EQUALS(MemberState::RS_SECONDARY, response.getState().s);
        ASSERT_EQUALS(OpTime(), response.getOpTime());
        ASSERT_EQUALS(0, response.getTerm());
        ASSERT_EQUALS(1, response.getConfigVersion());
    }

    TEST_F(PrepareHeartbeatResponseV1Test, PrepareHeartbeatResponseConfigVersionHigh) {
        // set up args with a config version higher than ours
        ReplSetHeartbeatArgsV1 args;
        args.setConfigVersion(10);
        args.setSetName("rs0");
        args.setSenderId(20);
        ReplSetHeartbeatResponse response;
        Status result(ErrorCodes::InternalError, "prepareHeartbeatResponse didn't set result");

        // prepare response and check the results
        prepareHeartbeatResponseV1(args, OpTime(), &response, &result);
        ASSERT_OK(result);
        ASSERT_FALSE(response.hasConfig());
        ASSERT_EQUALS("rs0", response.getReplicaSetName());
        ASSERT_EQUALS(MemberState::RS_SECONDARY, response.getState().s);
        ASSERT_EQUALS(OpTime(), response.getOpTime());
        ASSERT_EQUALS(0, response.getTerm());
        ASSERT_EQUALS(1, response.getConfigVersion());
    }

    TEST_F(PrepareHeartbeatResponseV1Test, PrepareHeartbeatResponseAsPrimary) {
        makeSelfPrimary(Timestamp(10,0));

        ReplSetHeartbeatArgsV1 args;
        args.setConfigVersion(1);
        args.setSetName("rs0");
        args.setSenderId(20);
        ReplSetHeartbeatResponse response;
        Status result(ErrorCodes::InternalError, "prepareHeartbeatResponse didn't set result");

        // prepare response and check the results
        prepareHeartbeatResponseV1(args, OpTime(Timestamp(11,0), 0), &response, &result);
        ASSERT_OK(result);
        ASSERT_FALSE(response.hasConfig());
        ASSERT_EQUALS("rs0", response.getReplicaSetName());
        ASSERT_EQUALS(MemberState::RS_PRIMARY, response.getState().s);
        ASSERT_EQUALS(OpTime(Timestamp(11,0), 0), response.getOpTime());
        ASSERT_EQUALS(0, response.getTerm());
        ASSERT_EQUALS(1, response.getConfigVersion());
    }

    TEST_F(PrepareHeartbeatResponseV1Test, PrepareHeartbeatResponseWithSyncSource) {
        // get a sync source
        heartbeatFromMember(HostAndPort("h3"), "rs0",
                            MemberState::RS_SECONDARY, OpTime());
        heartbeatFromMember(HostAndPort("h3"), "rs0",
                            MemberState::RS_SECONDARY, OpTime());
        heartbeatFromMember(HostAndPort("h2"), "rs0",
                            MemberState::RS_SECONDARY, OpTime(Timestamp(1,0), 0));
        heartbeatFromMember(HostAndPort("h2"), "rs0",
                            MemberState::RS_SECONDARY, OpTime(Timestamp(1,0), 0));
        getTopoCoord().chooseNewSyncSource(now()++, OpTime());

        // set up args
        ReplSetHeartbeatArgsV1 args;
        args.setConfigVersion(1);
        args.setSetName("rs0");
        args.setSenderId(20);
        ReplSetHeartbeatResponse response;
        Status result(ErrorCodes::InternalError, "prepareHeartbeatResponse didn't set result");

        // prepare response and check the results
        prepareHeartbeatResponseV1(args, OpTime(Timestamp(100,0), 0), &response, &result);
        ASSERT_OK(result);
        ASSERT_FALSE(response.hasConfig());
        ASSERT_EQUALS("rs0", response.getReplicaSetName());
        ASSERT_EQUALS(MemberState::RS_SECONDARY, response.getState().s);
        ASSERT_EQUALS(OpTime(Timestamp(100,0), 0), response.getOpTime());
        ASSERT_EQUALS(0, response.getTerm());
        ASSERT_EQUALS(1, response.getConfigVersion());
        ASSERT_EQUALS(HostAndPort("h2"), response.getSyncingTo());
    }

    TEST_F(PrepareHeartbeatResponseTest, PrepareHeartbeatResponseBadProtocolVersion) {
        // set up args with bad protocol version
        ReplSetHeartbeatArgs args;
        args.setProtocolVersion(3);
        ReplSetHeartbeatResponse response;
        Status result(ErrorCodes::InternalError, "prepareHeartbeatResponse didn't set result");

        // prepare response and check the results
        prepareHeartbeatResponse(args, OpTime(), &response, &result);
        ASSERT_EQUALS(ErrorCodes::BadValue, result);
        ASSERT_EQUALS("replset: incompatible replset protocol version: 3", result.reason());
        ASSERT_EQUALS("", response.getHbMsg());
    }

    TEST_F(PrepareHeartbeatResponseTest, PrepareHeartbeatResponseFromSelf) {
        // set up args with incorrect replset name
        ReplSetHeartbeatArgs args;
        args.setProtocolVersion(1);
        args.setSetName("rs0");
        args.setSenderId(10);
        ReplSetHeartbeatResponse response;
        Status result(ErrorCodes::InternalError, "prepareHeartbeatResponse didn't set result");
        prepareHeartbeatResponse(args, OpTime(), &response, &result);
        ASSERT_EQUALS(ErrorCodes::BadValue, result);
        ASSERT(result.reason().find("from member with the same member ID as our self")) <<
                "Actual string was \"" << result.reason() << '"';
        ASSERT_EQUALS("", response.getHbMsg());
    }

    TEST_F(PrepareHeartbeatResponseTest, PrepareHeartbeatResponseBadSetName) {
        // set up args with incorrect replset name
        ReplSetHeartbeatArgs args;
        args.setProtocolVersion(1);
        args.setSetName("rs1");
        ReplSetHeartbeatResponse response;
        Status result(ErrorCodes::InternalError, "prepareHeartbeatResponse didn't set result");

        startCapturingLogMessages();
        prepareHeartbeatResponse(args, OpTime(), &response, &result);
        stopCapturingLogMessages();
        ASSERT_EQUALS(ErrorCodes::InconsistentReplicaSetNames, result);
        ASSERT(result.reason().find("repl set names do not match")) << "Actual string was \"" <<
               result.reason() << '"';
        ASSERT_EQUALS(1,
                      countLogLinesContaining("replSet set names do not match, ours: rs0; remote "
                            "node's: rs1"));
        ASSERT_TRUE(response.isMismatched());
        ASSERT_EQUALS("", response.getHbMsg());
    }

    TEST_F(PrepareHeartbeatResponseTest, PrepareHeartbeatResponseSenderIDMissing) {
        // set up args without a senderID
        ReplSetHeartbeatArgs args;
        args.setProtocolVersion(1);
        args.setSetName("rs0");
        args.setConfigVersion(1);
        ReplSetHeartbeatResponse response;
        Status result(ErrorCodes::InternalError, "prepareHeartbeatResponse didn't set result");

        // prepare response and check the results
        prepareHeartbeatResponse(args, OpTime(), &response, &result);
        ASSERT_OK(result);
        ASSERT_FALSE(response.isElectable());
        ASSERT_TRUE(response.isReplSet());
        ASSERT_EQUALS(MemberState::RS_SECONDARY, response.getState().s);
        ASSERT_EQUALS(OpTime(), response.getOpTime());
        ASSERT_EQUALS(0, response.getTime().count());
        ASSERT_EQUALS("", response.getHbMsg());
        ASSERT_EQUALS("rs0", response.getReplicaSetName());
        ASSERT_EQUALS(1, response.getConfigVersion());
    }

    TEST_F(PrepareHeartbeatResponseTest, PrepareHeartbeatResponseSenderIDNotInConfig) {
        // set up args with a senderID which is not present in our config
        ReplSetHeartbeatArgs args;
        args.setProtocolVersion(1);
        args.setSetName("rs0");
        args.setConfigVersion(1);
        args.setSenderId(2);
        ReplSetHeartbeatResponse response;
        Status result(ErrorCodes::InternalError, "prepareHeartbeatResponse didn't set result");

        // prepare response and check the results
        prepareHeartbeatResponse(args, OpTime(), &response, &result);
        ASSERT_OK(result);
        ASSERT_FALSE(response.isElectable());
        ASSERT_TRUE(response.isReplSet());
        ASSERT_EQUALS(MemberState::RS_SECONDARY, response.getState().s);
        ASSERT_EQUALS(OpTime(), response.getOpTime());
        ASSERT_EQUALS(0, response.getTime().count());
        ASSERT_EQUALS("", response.getHbMsg());
        ASSERT_EQUALS("rs0", response.getReplicaSetName());
        ASSERT_EQUALS(1, response.getConfigVersion());
    }

    TEST_F(PrepareHeartbeatResponseTest, PrepareHeartbeatResponseConfigVersionLow) {
        // set up args with a config version lower than ours
        ReplSetHeartbeatArgs args;
        args.setProtocolVersion(1);
        args.setConfigVersion(0);
        args.setSetName("rs0");
        args.setSenderId(20);
        ReplSetHeartbeatResponse response;
        Status result(ErrorCodes::InternalError, "prepareHeartbeatResponse didn't set result");

        // prepare response and check the results
        prepareHeartbeatResponse(args, OpTime(), &response, &result);
        ASSERT_OK(result);
        ASSERT_TRUE(response.hasConfig());
        ASSERT_FALSE(response.isElectable());
        ASSERT_TRUE(response.isReplSet());
        ASSERT_EQUALS(MemberState::RS_SECONDARY, response.getState().s);
        ASSERT_EQUALS(OpTime(), response.getOpTime());
        ASSERT_EQUALS(0, response.getTime().count());
        ASSERT_EQUALS("", response.getHbMsg());
        ASSERT_EQUALS("rs0", response.getReplicaSetName());
        ASSERT_EQUALS(1, response.getConfigVersion());
    }

    TEST_F(PrepareHeartbeatResponseTest, PrepareHeartbeatResponseConfigVersionHigh) {
        // set up args with a config version higher than ours
        ReplSetHeartbeatArgs args;
        args.setProtocolVersion(1);
        args.setConfigVersion(10);
        args.setSetName("rs0");
        args.setSenderId(20);
        ReplSetHeartbeatResponse response;
        Status result(ErrorCodes::InternalError, "prepareHeartbeatResponse didn't set result");

        // prepare response and check the results
        prepareHeartbeatResponse(args, OpTime(), &response, &result);
        ASSERT_OK(result);
        ASSERT_FALSE(response.hasConfig());
        ASSERT_FALSE(response.isElectable());
        ASSERT_TRUE(response.isReplSet());
        ASSERT_EQUALS(MemberState::RS_SECONDARY, response.getState().s);
        ASSERT_EQUALS(OpTime(), response.getOpTime());
        ASSERT_EQUALS(0, response.getTime().count());
        ASSERT_EQUALS("", response.getHbMsg());
        ASSERT_EQUALS("rs0", response.getReplicaSetName());
        ASSERT_EQUALS(1, response.getConfigVersion());
    }

    TEST_F(PrepareHeartbeatResponseTest, PrepareHeartbeatResponseSenderDown) {
        // set up args with sender down from our perspective
        ReplSetHeartbeatArgs args;
        args.setProtocolVersion(1);
        args.setConfigVersion(1);
        args.setSetName("rs0");
        args.setSenderId(20);
        ReplSetHeartbeatResponse response;
        Status result(ErrorCodes::InternalError, "prepareHeartbeatResponse didn't set result");

        // prepare response and check the results
        prepareHeartbeatResponse(args, OpTime(), &response, &result);
        ASSERT_OK(result);
        ASSERT_FALSE(response.isElectable());
        ASSERT_TRUE(response.isReplSet());
        ASSERT_EQUALS(MemberState::RS_SECONDARY, response.getState().s);
        ASSERT_EQUALS(OpTime(), response.getOpTime());
        ASSERT_EQUALS(0, response.getTime().count());
        ASSERT_EQUALS("", response.getHbMsg());
        ASSERT_EQUALS("rs0", response.getReplicaSetName());
        ASSERT_EQUALS(1, response.getConfigVersion());
        ASSERT_TRUE(response.isStateDisagreement());
    }

    TEST_F(PrepareHeartbeatResponseTest, PrepareHeartbeatResponseSenderUp) {
        // set up args and acknowledge sender
        heartbeatFromMember(HostAndPort("h2"), "rs0", MemberState::RS_SECONDARY, OpTime());
        ReplSetHeartbeatArgs args;
        args.setProtocolVersion(1);
        args.setConfigVersion(1);
        args.setSetName("rs0");
        args.setSenderId(20);
        ReplSetHeartbeatResponse response;
        Status result(ErrorCodes::InternalError, "prepareHeartbeatResponse didn't set result");

        // prepare response and check the results
        prepareHeartbeatResponse(args, OpTime(Timestamp(100,0), 0), &response, &result);
        ASSERT_OK(result);
        // this change to true because we can now see a majority, unlike in the previous cases
        ASSERT_TRUE(response.isElectable());
        ASSERT_TRUE(response.isReplSet());
        ASSERT_EQUALS(MemberState::RS_SECONDARY, response.getState().s);
        ASSERT_EQUALS(OpTime(Timestamp(100,0), 0), response.getOpTime());
        ASSERT_EQUALS(0, response.getTime().count());
        ASSERT_EQUALS("", response.getHbMsg());
        ASSERT_EQUALS("rs0", response.getReplicaSetName());
        ASSERT_EQUALS(1, response.getConfigVersion());
    }

    TEST_F(TopoCoordTest, PrepareHeartbeatResponseNoConfigYet) {
        // set up args and acknowledge sender
        ReplSetHeartbeatArgs args;
        args.setProtocolVersion(1);
        args.setConfigVersion(1);
        args.setSetName("rs0");
        args.setSenderId(20);
        ReplSetHeartbeatResponse response;
        // prepare response and check the results
        Status result = getTopoCoord().prepareHeartbeatResponse(now()++,
                                                                args,
                                                                "rs0",
                                                                OpTime(),
                                                                &response);
        ASSERT_OK(result);
        // this change to true because we can now see a majority, unlike in the previous cases
        ASSERT_FALSE(response.isElectable());
        ASSERT_TRUE(response.isReplSet());
        ASSERT_EQUALS(MemberState::RS_STARTUP, response.getState().s);
        ASSERT_EQUALS(OpTime(), response.getOpTime());
        ASSERT_EQUALS(0, response.getTime().count());
        ASSERT_EQUALS("", response.getHbMsg());
        ASSERT_EQUALS("rs0", response.getReplicaSetName());
        ASSERT_EQUALS(-2, response.getConfigVersion());
    }

    TEST_F(PrepareHeartbeatResponseTest, PrepareHeartbeatResponseAsPrimary) {
        makeSelfPrimary(Timestamp(10,0));
        heartbeatFromMember(HostAndPort("h2"), "rs0", MemberState::RS_SECONDARY, OpTime());

        ReplSetHeartbeatArgs args;
        args.setProtocolVersion(1);
        args.setConfigVersion(1);
        args.setSetName("rs0");
        args.setSenderId(20);
        ReplSetHeartbeatResponse response;
        Status result(ErrorCodes::InternalError, "prepareHeartbeatResponse didn't set result");

        // prepare response and check the results
        prepareHeartbeatResponse(args, OpTime(Timestamp(11,0), 0), &response, &result);
        ASSERT_OK(result);
        // electable because we are already primary
        ASSERT_TRUE(response.isElectable());
        ASSERT_TRUE(response.isReplSet());
        ASSERT_EQUALS(MemberState::RS_PRIMARY, response.getState().s);
        ASSERT_EQUALS(OpTime(Timestamp(11,0), 0), response.getOpTime());
        ASSERT_EQUALS(Timestamp(10,0), response.getElectionTime());
        ASSERT_EQUALS(0, response.getTime().count());
        ASSERT_EQUALS("", response.getHbMsg());
        ASSERT_EQUALS("rs0", response.getReplicaSetName());
        ASSERT_EQUALS(1, response.getConfigVersion());
    }

    TEST_F(PrepareHeartbeatResponseTest, PrepareHeartbeatResponseWithSyncSource) {
        // get a sync source
        heartbeatFromMember(HostAndPort("h3"), "rs0",
                            MemberState::RS_SECONDARY, OpTime());
        heartbeatFromMember(HostAndPort("h3"), "rs0",
                            MemberState::RS_SECONDARY, OpTime());
        heartbeatFromMember(HostAndPort("h2"), "rs0",
                            MemberState::RS_SECONDARY, OpTime(Timestamp(1,0), 0));
        heartbeatFromMember(HostAndPort("h2"), "rs0",
                            MemberState::RS_SECONDARY, OpTime(Timestamp(1,0), 0));
        getTopoCoord().chooseNewSyncSource(now()++, OpTime());

        // set up args
        ReplSetHeartbeatArgs args;
        args.setProtocolVersion(1);
        args.setConfigVersion(1);
        args.setSetName("rs0");
        args.setSenderId(20);
        ReplSetHeartbeatResponse response;
        Status result(ErrorCodes::InternalError, "prepareHeartbeatResponse didn't set result");

        // prepare response and check the results
        prepareHeartbeatResponse(args, OpTime(Timestamp(100,0), 0), &response, &result);
        ASSERT_OK(result);
        ASSERT_TRUE(response.isElectable());
        ASSERT_TRUE(response.isReplSet());
        ASSERT_EQUALS(MemberState::RS_SECONDARY, response.getState().s);
        ASSERT_EQUALS(OpTime(Timestamp(100,0), 0), response.getOpTime());
        ASSERT_EQUALS(0, response.getTime().count());
        // changed to a syncing message because our sync source changed recently
        ASSERT_EQUALS("syncing from: h2:27017", response.getHbMsg());
        ASSERT_EQUALS("rs0", response.getReplicaSetName());
        ASSERT_EQUALS(1, response.getConfigVersion());
        ASSERT_EQUALS(HostAndPort("h2"), response.getSyncingTo());
    }

    TEST_F(TopoCoordTest, SetFollowerSecondaryWhenLoneNode) {
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
        ASSERT_EQUALS(MemberState::RS_STARTUP, getTopoCoord().getMemberState().s);
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 1 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 1 << "host" << "hself"))),
                     0);
        ASSERT_EQUALS(MemberState::RS_STARTUP2, getTopoCoord().getMemberState().s);

        // if we are the only node, we should become a candidate when we transition to SECONDARY
        ASSERT_FALSE(TopologyCoordinator::Role::candidate == getTopoCoord().getRole());
        getTopoCoord().setFollowerMode(MemberState::RS_SECONDARY);
        ASSERT_TRUE(TopologyCoordinator::Role::candidate == getTopoCoord().getRole());
        ASSERT_EQUALS(MemberState::RS_SECONDARY, getTopoCoord().getMemberState().s);
    }

    TEST_F(TopoCoordTest, CandidateWhenLoneSecondaryNodeReconfig) {
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
        ASSERT_EQUALS(MemberState::RS_STARTUP, getTopoCoord().getMemberState().s);
        ReplicaSetConfig cfg;
        cfg.initialize(BSON("_id" << "rs0" <<
                            "version" << 1 <<
                            "members" << BSON_ARRAY(
                                BSON("_id" << 1 << "host" << "hself" << "priority" << 0))));
        getTopoCoord().updateConfig(cfg, 0, now()++, OpTime());
        ASSERT_EQUALS(MemberState::RS_STARTUP2, getTopoCoord().getMemberState().s);

        ASSERT_FALSE(TopologyCoordinator::Role::candidate == getTopoCoord().getRole());
        getTopoCoord().setFollowerMode(MemberState::RS_SECONDARY);
        ASSERT_FALSE(TopologyCoordinator::Role::candidate == getTopoCoord().getRole());
        ASSERT_EQUALS(MemberState::RS_SECONDARY, getTopoCoord().getMemberState().s);

        // we should become a candidate when we reconfig to become electable

        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 1 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 1 << "host" << "hself"))),
                     0);
        ASSERT_TRUE(TopologyCoordinator::Role::candidate == getTopoCoord().getRole());
    }

    TEST_F(TopoCoordTest, SetFollowerSecondaryWhenLoneUnelectableNode) {
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
        ASSERT_EQUALS(MemberState::RS_STARTUP, getTopoCoord().getMemberState().s);
        ReplicaSetConfig cfg;
        cfg.initialize(BSON("_id" << "rs0" <<
                            "version" << 1 <<
                            "members" << BSON_ARRAY(
                                BSON("_id" << 1 << "host" << "hself" << "priority" << 0))));

        getTopoCoord().updateConfig(cfg, 0, now()++, OpTime());
        ASSERT_EQUALS(MemberState::RS_STARTUP2, getTopoCoord().getMemberState().s);

        // despite being the only node, we are unelectable, so we should not become a candidate
        ASSERT_FALSE(TopologyCoordinator::Role::candidate == getTopoCoord().getRole());
        getTopoCoord().setFollowerMode(MemberState::RS_SECONDARY);
        ASSERT_FALSE(TopologyCoordinator::Role::candidate == getTopoCoord().getRole());
        ASSERT_EQUALS(MemberState::RS_SECONDARY, getTopoCoord().getMemberState().s);
    }

    TEST_F(TopoCoordTest, ReconfigToBeAddedToTheSet) {
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
        ASSERT_EQUALS(MemberState::RS_STARTUP, getTopoCoord().getMemberState().s);
        // config to be absent from the set
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 1 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 1 << "host" << "host2:27017") <<
                              BSON("_id" << 2 << "host" << "host3:27017"))),
                     -1);
        // should become removed since we are not in the set
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
        ASSERT_EQUALS(MemberState::RS_REMOVED, getTopoCoord().getMemberState().s);

        // reconfig to add to set
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 2 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 0 << "host" << "host1:27017") <<
                              BSON("_id" << 1 << "host" << "host2:27017") <<
                              BSON("_id" << 2 << "host" << "host3:27017"))),
                     0);
        // having been added to the config, we should no longer be REMOVED and should enter STARTUP2
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
        ASSERT_EQUALS(MemberState::RS_STARTUP2, getTopoCoord().getMemberState().s);
    }

    TEST_F(TopoCoordTest, ReconfigToBeRemovedFromTheSet) {
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
        ASSERT_EQUALS(MemberState::RS_STARTUP, getTopoCoord().getMemberState().s);
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 1 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 0 << "host" << "host1:27017") <<
                              BSON("_id" << 1 << "host" << "host2:27017") <<
                              BSON("_id" << 2 << "host" << "host3:27017"))),
                     0);
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
        ASSERT_EQUALS(MemberState::RS_STARTUP2, getTopoCoord().getMemberState().s);
        
        // reconfig to remove self
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 2 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 1 << "host" << "host2:27017") <<
                              BSON("_id" << 2 << "host" << "host3:27017"))),
                     -1);
        // should become removed since we are no longer in the set
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
        ASSERT_EQUALS(MemberState::RS_REMOVED, getTopoCoord().getMemberState().s);
    }

    TEST_F(TopoCoordTest, ReconfigToBeRemovedFromTheSetAsPrimary) {
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
        ASSERT_EQUALS(MemberState::RS_STARTUP, getTopoCoord().getMemberState().s);
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 1 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 0 << "host" << "host1:27017"))),
                     0);
        ASSERT_FALSE(TopologyCoordinator::Role::candidate == getTopoCoord().getRole());
        ASSERT_EQUALS(MemberState::RS_STARTUP2, getTopoCoord().getMemberState().s);
        getTopoCoord().setFollowerMode(MemberState::RS_SECONDARY);
        ASSERT_TRUE(TopologyCoordinator::Role::candidate == getTopoCoord().getRole());

        // win election and primary
        getTopoCoord().processWinElection(OID::gen(), Timestamp());
        ASSERT_TRUE(TopologyCoordinator::Role::leader == getTopoCoord().getRole());
        ASSERT_EQUALS(MemberState::RS_PRIMARY, getTopoCoord().getMemberState().s);

        // reconfig to remove self
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 2 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 1 << "host" << "host2:27017") <<
                              BSON("_id" << 2 << "host" << "host3:27017"))),
                     -1);
        // should become removed since we are no longer in the set even though we were primary
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
        ASSERT_EQUALS(MemberState::RS_REMOVED, getTopoCoord().getMemberState().s);
    }

    TEST_F(TopoCoordTest, ReconfigCanNoLongerBePrimary) {
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
        ASSERT_EQUALS(MemberState::RS_STARTUP, getTopoCoord().getMemberState().s);
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 1 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 0 << "host" << "host1:27017"))),
                     0);
        ASSERT_FALSE(TopologyCoordinator::Role::candidate == getTopoCoord().getRole());
        ASSERT_EQUALS(MemberState::RS_STARTUP2, getTopoCoord().getMemberState().s);
        getTopoCoord().setFollowerMode(MemberState::RS_SECONDARY);
        ASSERT_TRUE(TopologyCoordinator::Role::candidate == getTopoCoord().getRole());

        // win election and primary
        getTopoCoord().processWinElection(OID::gen(), Timestamp());
        ASSERT_TRUE(TopologyCoordinator::Role::leader == getTopoCoord().getRole());
        ASSERT_EQUALS(MemberState::RS_PRIMARY, getTopoCoord().getMemberState().s);

        // now lose primary due to loss of electability
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 2 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 0 << "host" << "host1:27017" << "priority" << 0) <<
                              BSON("_id" << 1 << "host" << "host2:27017") <<
                              BSON("_id" << 2 << "host" << "host3:27017"))),
                     0);
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
        ASSERT_EQUALS(MemberState::RS_SECONDARY, getTopoCoord().getMemberState().s);
    }

     TEST_F(TopoCoordTest, ReconfigContinueToBePrimary) {
         ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
         ASSERT_EQUALS(MemberState::RS_STARTUP, getTopoCoord().getMemberState().s);
         updateConfig(BSON("_id" << "rs0" <<
                           "version" << 1 <<
                           "members" << BSON_ARRAY(
                               BSON("_id" << 0 << "host" << "host1:27017"))),
                      0);

         ASSERT_FALSE(TopologyCoordinator::Role::candidate == getTopoCoord().getRole());
         ASSERT_EQUALS(MemberState::RS_STARTUP2, getTopoCoord().getMemberState().s);
         getTopoCoord().setFollowerMode(MemberState::RS_SECONDARY);
         ASSERT_TRUE(TopologyCoordinator::Role::candidate == getTopoCoord().getRole());

         // win election and primary
         getTopoCoord().processWinElection(OID::gen(), Timestamp());
         ASSERT_TRUE(TopologyCoordinator::Role::leader == getTopoCoord().getRole());
         ASSERT_EQUALS(MemberState::RS_PRIMARY, getTopoCoord().getMemberState().s);

         // Now reconfig in ways that leave us electable and ensure we are still the primary.
         // Add hosts
         updateConfig(BSON("_id" << "rs0" <<
                           "version" << 2 <<
                           "members" << BSON_ARRAY(
                               BSON("_id" << 0 << "host" << "host1:27017") <<
                               BSON("_id" << 1 << "host" << "host2:27017") <<
                               BSON("_id" << 2 << "host" << "host3:27017"))),
                      0,
                      Date_t::fromMillisSinceEpoch(-1),
                      OpTime(Timestamp(10,0), 0));
         ASSERT_TRUE(TopologyCoordinator::Role::leader == getTopoCoord().getRole());
         ASSERT_EQUALS(MemberState::RS_PRIMARY, getTopoCoord().getMemberState().s);

         // Change priorities and tags
         updateConfig(BSON("_id" << "rs0" <<
                           "version" << 2 <<
                           "members" << BSON_ARRAY(
                               BSON("_id" << 0 << "host" << "host1:27017" << "priority" << 10) <<
                               BSON("_id" << 1 <<
                                    "host" << "host2:27017" <<
                                    "priority" << 5 <<
                                    "tags" <<  BSON("dc" << "NA" << "rack" << "rack1")))),
                      0,
                      Date_t::fromMillisSinceEpoch(-1),
                      OpTime(Timestamp(10,0), 0));
         ASSERT_TRUE(TopologyCoordinator::Role::leader == getTopoCoord().getRole());
         ASSERT_EQUALS(MemberState::RS_PRIMARY, getTopoCoord().getMemberState().s);
     }

    TEST_F(TopoCoordTest, ReconfigKeepSecondary) {
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 1 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 1 << "host" << "host1:27017") <<
                              BSON("_id" << 2 << "host" << "host2:27017"))),
                     0);
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
        ASSERT_EQUALS(MemberState::RS_STARTUP2, getTopoCoord().getMemberState().s);
        setSelfMemberState(MemberState::RS_SECONDARY);
        ASSERT_EQUALS(MemberState::RS_SECONDARY, getTopoCoord().getMemberState().s);

        // reconfig and stay secondary
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 2 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 0 << "host" << "host1:27017") <<
                              BSON("_id" << 1 << "host" << "host2:27017") <<
                              BSON("_id" << 2 << "host" << "host3:27017"))),
                     0);
        ASSERT_TRUE(TopologyCoordinator::Role::follower == getTopoCoord().getRole());
        ASSERT_EQUALS(MemberState::RS_SECONDARY, getTopoCoord().getMemberState().s);
    }

    TEST_F(HeartbeatResponseTest, ReconfigBetweenHeartbeatRequestAndRepsonse) {
        OpTime election = OpTime(Timestamp(14,0), 0);
        OpTime lastOpTimeApplied = OpTime(Timestamp(13,0), 0);

        // all three members up and secondaries
        setSelfMemberState(MemberState::RS_SECONDARY);

        HeartbeatResponseAction nextAction = receiveUpHeartbeat(HostAndPort("host3"),
                                                                "rs0",
                                                                MemberState::RS_PRIMARY,
                                                                election,
                                                                lastOpTimeApplied,
                                                                lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());

        nextAction = receiveUpHeartbeat(HostAndPort("host2"),
                                        "rs0",
                                        MemberState::RS_SECONDARY,
                                        election,
                                        lastOpTimeApplied,
                                        lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());

        // now request from host3 and receive after host2 has been removed via reconfig
        getTopoCoord().prepareHeartbeatRequest(now()++, "rs0", HostAndPort("host3"));

        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 2 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 0 << "host" << "host1:27017") <<
                              BSON("_id" << 2 << "host" << "host3:27017"))),
                     0);

        ReplSetHeartbeatResponse hb;
        hb.initialize(BSON("ok" << 1 <<
                           "v" << 1 <<
                           "state" << MemberState::RS_PRIMARY), 0);
        hb.setOpTime(lastOpTimeApplied);
        hb.setElectionTime(election.getTimestamp());
        StatusWith<ReplSetHeartbeatResponse> hbResponse = StatusWith<ReplSetHeartbeatResponse>(hb);
        HeartbeatResponseAction action = getTopoCoord().processHeartbeatResponse(now()++,
                                                Milliseconds(0),
                                                HostAndPort("host3"),
                                                hbResponse,
                                                lastOpTimeApplied);

        // now primary should be host3, index 1, and we should perform NoAction in response
        ASSERT_EQUALS(1, getCurrentPrimaryIndex());
        ASSERT_NO_ACTION(action.getAction());
    }

    TEST_F(HeartbeatResponseTest, ReconfigNodeRemovedBetweenHeartbeatRequestAndRepsonse) {
        OpTime election = OpTime(Timestamp(14,0), 0);
        OpTime lastOpTimeApplied = OpTime(Timestamp(13,0), 0);

        // all three members up and secondaries
        setSelfMemberState(MemberState::RS_SECONDARY);

        HeartbeatResponseAction nextAction = receiveUpHeartbeat(HostAndPort("host3"),
                                                                "rs0",
                                                                MemberState::RS_PRIMARY,
                                                                election,
                                                                lastOpTimeApplied,
                                                                lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());

        nextAction = receiveUpHeartbeat(HostAndPort("host2"),
                                        "rs0",
                                        MemberState::RS_SECONDARY,
                                        election,
                                        lastOpTimeApplied,
                                        lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());

        // now request from host3 and receive after host2 has been removed via reconfig
        getTopoCoord().prepareHeartbeatRequest(now()++, "rs0", HostAndPort("host3"));

        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 2 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 0 << "host" << "host1:27017") <<
                              BSON("_id" << 1 << "host" << "host2:27017"))),
                     0);

        ReplSetHeartbeatResponse hb;
        hb.initialize(BSON("ok" << 1 <<
                           "v" << 1 <<
                           "state" << MemberState::RS_PRIMARY), 0);
        hb.setOpTime(lastOpTimeApplied);
        hb.setElectionTime(election.getTimestamp());
        StatusWith<ReplSetHeartbeatResponse> hbResponse = StatusWith<ReplSetHeartbeatResponse>(hb);
        HeartbeatResponseAction action = getTopoCoord().processHeartbeatResponse(now()++,
                                                Milliseconds(0),
                                                HostAndPort("host3"),
                                                hbResponse,
                                                lastOpTimeApplied);

        // primary should not be set and we should perform NoAction in response
        ASSERT_EQUALS(-1, getCurrentPrimaryIndex());
        ASSERT_NO_ACTION(action.getAction());
    }

    TEST_F(HeartbeatResponseTest, ShouldChangeSyncSourceMemberNotInConfig) {
        // In this test, the TopologyCoordinator should tell us to change sync sources away from
        // "host4" since "host4" is absent from the config
        ASSERT_TRUE(getTopoCoord().shouldChangeSyncSource(HostAndPort("host4"), now()));
    }

    TEST_F(HeartbeatResponseTest, ShouldChangeSyncSourceMemberHasYetToHeartbeat) {
        // In this test, the TopologyCoordinator should not tell us to change sync sources away from
        // "host2" since we do not yet have a heartbeat (and as a result do not yet have an optime)
        // for "host2"
        ASSERT_FALSE(getTopoCoord().shouldChangeSyncSource(HostAndPort("host2"), now()));
    }

    TEST_F(HeartbeatResponseTest, ShouldChangeSyncSourceFresherHappierMemberExists) {
        // In this test, the TopologyCoordinator should tell us to change sync sources away from 
        // "host2" and to "host3" since "host2" is more than maxSyncSourceLagSecs(30) behind "host3"
        OpTime election = OpTime();
        OpTime lastOpTimeApplied = OpTime(Timestamp(4,0), 0);
        // ahead by more than maxSyncSourceLagSecs (30)
        OpTime fresherLastOpTimeApplied = OpTime(Timestamp(3005,0), 0);

        HeartbeatResponseAction nextAction = receiveUpHeartbeat(HostAndPort("host2"),
                                                                "rs0",
                                                                MemberState::RS_SECONDARY,
                                                                election,
                                                                lastOpTimeApplied,
                                                                lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());

        nextAction = receiveUpHeartbeat(HostAndPort("host3"),
                                        "rs0",
                                        MemberState::RS_SECONDARY,
                                        election,
                                        fresherLastOpTimeApplied,
                                        lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());

        // set up complete, time for actual check
        startCapturingLogMessages();
        ASSERT_TRUE(getTopoCoord().shouldChangeSyncSource(HostAndPort("host2"), now()));
        stopCapturingLogMessages();
        ASSERT_EQUALS(1, countLogLinesContaining("changing sync target"));
    }

    TEST_F(HeartbeatResponseTest, ShouldChangeSyncSourceFresherMemberIsBlackListed) {
        // In this test, the TopologyCoordinator should not tell us to change sync sources away from
        // "host2" and to "host3" despite "host2" being more than maxSyncSourceLagSecs(30) behind
        // "host3", since "host3" is blacklisted
        // Then, confirm that unblacklisting only works if time has passed the blacklist time.
        OpTime election = OpTime();
        OpTime lastOpTimeApplied = OpTime(Timestamp(400,0), 0);
        // ahead by more than maxSyncSourceLagSecs (30)
        OpTime fresherLastOpTimeApplied = OpTime(Timestamp(3005,0), 0);

        HeartbeatResponseAction nextAction = receiveUpHeartbeat(HostAndPort("host2"),
                                                                "rs0",
                                                                MemberState::RS_SECONDARY,
                                                                election,
                                                                lastOpTimeApplied,
                                                                lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());

        nextAction = receiveUpHeartbeat(HostAndPort("host3"),
                                        "rs0",
                                        MemberState::RS_SECONDARY,
                                        election,
                                        fresherLastOpTimeApplied,
                                        lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());
        getTopoCoord().blacklistSyncSource(HostAndPort("host3"), now() + Milliseconds(100));

        // set up complete, time for actual check
        ASSERT_FALSE(getTopoCoord().shouldChangeSyncSource(HostAndPort("host2"), now()));

        // unblacklist with too early a time (node should remained blacklisted)
        getTopoCoord().unblacklistSyncSource(HostAndPort("host3"), now() + Milliseconds(90));
        ASSERT_FALSE(getTopoCoord().shouldChangeSyncSource(HostAndPort("host2"), now()));

        // unblacklist and it should succeed
        getTopoCoord().unblacklistSyncSource(HostAndPort("host3"), now() + Milliseconds(100));
        startCapturingLogMessages();
        ASSERT_TRUE(getTopoCoord().shouldChangeSyncSource(HostAndPort("host2"), now()));
        stopCapturingLogMessages();
        ASSERT_EQUALS(1, countLogLinesContaining("changing sync target"));
    }

    TEST_F(HeartbeatResponseTest, ShouldChangeSyncSourceFresherMemberIsDown) {
        // In this test, the TopologyCoordinator should not tell us to change sync sources away from 
        // "host2" and to "host3" despite "host2" being more than maxSyncSourceLagSecs(30) behind
        // "host3", since "host3" is down
        OpTime election = OpTime();
        OpTime lastOpTimeApplied = OpTime(Timestamp(400,0), 0);
        // ahead by more than maxSyncSourceLagSecs (30)
        OpTime fresherLastOpTimeApplied = OpTime(Timestamp(3005,0), 0);

        HeartbeatResponseAction nextAction = receiveUpHeartbeat(HostAndPort("host2"),
                                                                "rs0",
                                                                MemberState::RS_SECONDARY,
                                                                election,
                                                                lastOpTimeApplied,
                                                                lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());

        nextAction = receiveUpHeartbeat(HostAndPort("host3"),
                                        "rs0",
                                        MemberState::RS_SECONDARY,
                                        election,
                                        fresherLastOpTimeApplied,
                                        lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());

        // set up complete, time for actual check
        nextAction = receiveDownHeartbeat(HostAndPort("host3"), "rs0", lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());
        ASSERT_FALSE(getTopoCoord().shouldChangeSyncSource(HostAndPort("host2"), now()));
    }

    TEST_F(HeartbeatResponseTest, ShouldChangeSyncSourceFresherMemberIsNotReadable) {
        // In this test, the TopologyCoordinator should not tell us to change sync sources away from 
        // "host2" and to "host3" despite "host2" being more than maxSyncSourceLagSecs(30) behind
        // "host3", since "host3" is in a non-readable mode (RS_ROLLBACK)
        OpTime election = OpTime();
        OpTime lastOpTimeApplied = OpTime(Timestamp(4,0), 0);
        // ahead by more than m, 0)axSyncSourceLagSecs (30)
        OpTime fresherLastOpTimeApplied = OpTime(Timestamp(3005,0), 0);

        HeartbeatResponseAction nextAction = receiveUpHeartbeat(HostAndPort("host2"),
                                                                "rs0",
                                                                MemberState::RS_SECONDARY,
                                                                election,
                                                                lastOpTimeApplied,
                                                                lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());

        nextAction = receiveUpHeartbeat(HostAndPort("host3"),
                                        "rs0",
                                        MemberState::RS_ROLLBACK,
                                        election,
                                        fresherLastOpTimeApplied,
                                        lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());

        // set up complete, time for actual check
        ASSERT_FALSE(getTopoCoord().shouldChangeSyncSource(HostAndPort("host2"), now()));
    }

    TEST_F(HeartbeatResponseTest, ShouldChangeSyncSourceFresherMemberDoesNotBuildIndexes) {
        // In this test, the TopologyCoordinator should not tell us to change sync sources away from 
        // "host2" and to "host3" despite "host2" being more than maxSyncSourceLagSecs(30) behind
        // "host3", since "host3" does not build indexes
        OpTime election = OpTime();
        OpTime lastOpTimeApplied = OpTime(Timestamp(4,0), 0);
        // ahead by more than maxSyncSourceLagSecs (30)
        OpTime fresherLastOpTimeApplied = OpTime(Timestamp(3005,0), 0);

        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 6 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 0 << "host" << "hself") <<
                              BSON("_id" << 1 << "host" << "host2") <<
                              BSON("_id" << 2 << "host" << "host3" <<
                                   "buildIndexes" << false << "priority" << 0))),
                     0);
        HeartbeatResponseAction nextAction = receiveUpHeartbeat(HostAndPort("host2"),
                                                                "rs0",
                                                                MemberState::RS_SECONDARY,
                                                                election,
                                                                lastOpTimeApplied,
                                                                lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());
        nextAction = receiveUpHeartbeat(HostAndPort("host3"),
                                        "rs0",
                                        MemberState::RS_SECONDARY,
                                        election,
                                        fresherLastOpTimeApplied,
                                        lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());

        // set up complete, time for actual check
        ASSERT_FALSE(getTopoCoord().shouldChangeSyncSource(HostAndPort("host2"), now()));
    }

    TEST_F(HeartbeatResponseTest, ShouldChangeSyncSourceFresherMemberDoesNotBuildIndexesNorDoWe) {
        // In this test, the TopologyCoordinator should tell us to change sync sources away from 
        // "host2" and to "host3" despite "host3" not building indexes because we do not build
        // indexes either and "host2" is more than maxSyncSourceLagSecs(30) behind "host3"
        OpTime election = OpTime();
        OpTime lastOpTimeApplied = OpTime(Timestamp(4,0), 0);
        // ahead by more than maxSyncSourceLagSecs (30)
        OpTime fresherLastOpTimeApplied = OpTime(Timestamp(3005,0), 0);

        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 7 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 0 << "host" << "hself" <<
                                   "buildIndexes" << false << "priority" << 0) <<
                              BSON("_id" << 1 << "host" << "host2") <<
                              BSON("_id" << 2 << "host" << "host3" <<
                                   "buildIndexes" << false << "priority" << 0))),
                     0);
        HeartbeatResponseAction nextAction = receiveUpHeartbeat(HostAndPort("host2"),
                                                                "rs0",
                                                                MemberState::RS_SECONDARY,
                                                                election,
                                                                lastOpTimeApplied,
                                                                lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());
        nextAction = receiveUpHeartbeat(HostAndPort("host3"),
                                        "rs0",
                                        MemberState::RS_SECONDARY,
                                        election,
                                        fresherLastOpTimeApplied,
                                        lastOpTimeApplied);
        ASSERT_NO_ACTION(nextAction.getAction());

        // set up complete, time for actual check
        startCapturingLogMessages();
        ASSERT_TRUE(getTopoCoord().shouldChangeSyncSource(HostAndPort("host2"), now()));
        stopCapturingLogMessages();
        ASSERT_EQUALS(1, countLogLinesContaining("changing sync target"));
    }

    TEST_F(TopoCoordTest, CheckShouldStandForElectionWithPrimary) {
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 1 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 10 << "host" << "hself") <<
                              BSON("_id" << 20 << "host" << "h2") <<
                              BSON("_id" << 30 << "host" << "h3"))),
                     0);
        setSelfMemberState(MemberState::RS_SECONDARY);

        heartbeatFromMember(HostAndPort("h2"), "rs0",
                            MemberState::RS_PRIMARY, OpTime(Timestamp(1,0), 0));
        ASSERT_FALSE(getTopoCoord().checkShouldStandForElection(now()++, OpTime()));
    }

    TEST_F(TopoCoordTest, CheckShouldStandForElectionNotCloseEnoughToLastOptime) {
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 1 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 10 << "host" << "hself") <<
                              BSON("_id" << 20 << "host" << "h2") <<
                              BSON("_id" << 30 << "host" << "h3"))),
                     0);
        setSelfMemberState(MemberState::RS_SECONDARY);

        heartbeatFromMember(HostAndPort("h2"), "rs0",
                            MemberState::RS_SECONDARY, OpTime(Timestamp(10000,0), 0));
        ASSERT_FALSE(getTopoCoord().checkShouldStandForElection(now()++,
                                                                OpTime(Timestamp(100,0), 0)));
    }

    TEST_F(TopoCoordTest, VoteForMyselfFailsWhileNotCandidate) {
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 1 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 10 << "host" << "hself") <<
                              BSON("_id" << 20 << "host" << "h2") <<
                              BSON("_id" << 30 << "host" << "h3"))),
                     0);
        setSelfMemberState(MemberState::RS_SECONDARY);
        ASSERT_FALSE(getTopoCoord().voteForMyself(now()++));
    }

    TEST_F(TopoCoordTest, GetMemberStateArbiter) {
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 1 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 10 << "host" << "hself" << "arbiterOnly" << true) <<
                              BSON("_id" << 20 << "host" << "h2") <<
                              BSON("_id" << 30 << "host" << "h3"))),
                     0);
        ASSERT_EQUALS(MemberState::RS_ARBITER, getTopoCoord().getMemberState().s);
    }

    TEST_F(TopoCoordTest, UnelectableIfAbsentFromConfig) {
        logger::globalLogDomain()->setMinimumLoggedSeverity(logger::LogSeverity::Debug(3));
        startCapturingLogMessages();
        ASSERT_FALSE(getTopoCoord().checkShouldStandForElection(now()++,
                                                                OpTime(Timestamp(10,0), 0)));
        stopCapturingLogMessages();
        ASSERT_EQUALS(1, countLogLinesContaining("not a member of a valid replica set config"));
        logger::globalLogDomain()->setMinimumLoggedSeverity(logger::LogSeverity::Log());
    }

    TEST_F(TopoCoordTest, UnelectableIfVotedRecently) {
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 1 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 10 << "host" << "hself") <<
                              BSON("_id" << 20 << "host" << "h2") <<
                              BSON("_id" << 30 << "host" << "h3"))),
                     0);
        setSelfMemberState(MemberState::RS_SECONDARY);
        heartbeatFromMember(HostAndPort("h2"), "rs0",
                            MemberState::RS_SECONDARY, OpTime(Timestamp(100,0), 0));

        // vote for another node
        OID remoteRound = OID::gen();
        ReplicationCoordinator::ReplSetElectArgs electArgs;
        electArgs.set = "rs0";
        electArgs.round = remoteRound;
        electArgs.cfgver = 1;
        electArgs.whoid = 20;

        // need to be 30 secs beyond the start of time to pass last vote lease
        now() += Seconds(30);
        BSONObjBuilder electResponseBuilder;
        Status result = Status(ErrorCodes::InternalError, "status not set by prepareElectResponse");
        getTopoCoord().prepareElectResponse(
                electArgs, now()++, OpTime(Timestamp(100,0), 0), &electResponseBuilder, &result);
        BSONObj response = electResponseBuilder.obj();
        ASSERT_OK(result);
        std::cout << response;
        ASSERT_EQUALS(1, response["vote"].Int());
        ASSERT_EQUALS(remoteRound, response["round"].OID());

        logger::globalLogDomain()->setMinimumLoggedSeverity(logger::LogSeverity::Debug(3));
        startCapturingLogMessages();
        ASSERT_FALSE(getTopoCoord().checkShouldStandForElection(now()++,
                                                                OpTime(Timestamp(10,0), 0)));
        stopCapturingLogMessages();
        ASSERT_EQUALS(1, countLogLinesContaining("I recently voted for "));
        logger::globalLogDomain()->setMinimumLoggedSeverity(logger::LogSeverity::Log());
    }

    TEST_F(TopoCoordTest, ProcessRequestVotesTwoRequestsForSameTerm) {
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 1 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 10 << "host" << "hself") <<
                              BSON("_id" << 20 << "host" << "h2") <<
                              BSON("_id" << 30 << "host" << "h3"))),
                     0);
        setSelfMemberState(MemberState::RS_SECONDARY);

        ReplSetRequestVotesArgs args;
        args.initialize(BSON("replSetRequestVotes" << 1
                          << "setName" << "rs0"
                          << "term" << 1LL
                          << "candidateId" << 10LL
                          << "configVersion" << 1LL
                          << "lastCommittedOp" << BSON ("ts" << Timestamp(10, 0)
                                                     << "term" << 0LL)));
        ReplSetRequestVotesResponse response;
        OpTime lastAppliedOpTime;

        getTopoCoord().processReplSetRequestVotes(args, &response, lastAppliedOpTime);
        ASSERT_EQUALS("", response.getReason());
        ASSERT_TRUE(response.getVoteGranted());
    
        ReplSetRequestVotesArgs args2;
        args2.initialize(BSON("replSetRequestVotes" << 1
                           << "setName" << "rs0"
                           << "term" << 1LL
                           << "candidateId" << 20LL
                           << "configVersion" << 1LL
                           << "lastCommittedOp" << BSON ("ts" << Timestamp(10, 0)
                                                      << "term" << 0LL)));
        ReplSetRequestVotesResponse response2;

        // different candidate same term, should be a problem
        getTopoCoord().processReplSetRequestVotes(args2, &response2, lastAppliedOpTime);
        ASSERT_EQUALS("already voted for another candidate this term", response2.getReason());
        ASSERT_FALSE(response2.getVoteGranted());
    
    }

    TEST_F(TopoCoordTest, ProcessRequestVotesBadCommands) {
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 1 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 10 << "host" << "hself") <<
                              BSON("_id" << 20 << "host" << "h2") <<
                              BSON("_id" << 30 << "host" << "h3"))),
                     0);
        setSelfMemberState(MemberState::RS_SECONDARY);

        // mismatched setName
        ReplSetRequestVotesArgs args;
        args.initialize(BSON("replSetRequestVotes" << 1
                          << "setName" << "wrongName"
                          << "term" << 1LL
                          << "candidateId" << 10LL
                          << "configVersion" << 1LL
                          << "lastCommittedOp" << BSON ("ts" << Timestamp(10, 0)
                                                     << "term" << 0LL)));
        ReplSetRequestVotesResponse response;
        OpTime lastAppliedOpTime;

        getTopoCoord().processReplSetRequestVotes(args, &response, lastAppliedOpTime);
        ASSERT_EQUALS("candidate's set name differs from mine", response.getReason());
        ASSERT_FALSE(response.getVoteGranted());
    
        // mismatched configVersion
        ReplSetRequestVotesArgs args2;
        args2.initialize(BSON("replSetRequestVotes" << 1
                           << "setName" << "rs0"
                           << "term" << 1LL
                           << "candidateId" << 20LL
                           << "configVersion" << 0LL
                           << "lastCommittedOp" << BSON ("ts" << Timestamp(10, 0)
                                                      << "term" << 0LL)));
        ReplSetRequestVotesResponse response2;

        getTopoCoord().processReplSetRequestVotes(args2, &response2, lastAppliedOpTime);
        ASSERT_EQUALS("candidate's config version differs from mine", response2.getReason());
        ASSERT_FALSE(response2.getVoteGranted());
    
        // set term higher by receiving a replSetDeclareElectionWinnerCommand
        ReplSetDeclareElectionWinnerArgs winnerArgs;
        winnerArgs.initialize(BSON("replSetDeclareElectionWinner" << 1
                                << "setName" << "rs0"
                                << "term" << 2
                                << "winnerId" << 30));
        long long responseTerm;
        ASSERT(getTopoCoord().updateTerm(winnerArgs.getTerm()));
        ASSERT_OK(getTopoCoord().processReplSetDeclareElectionWinner(winnerArgs, &responseTerm));
        ASSERT_EQUALS(2, responseTerm);

        // stale term
        ReplSetRequestVotesArgs args3;
        args3.initialize(BSON("replSetRequestVotes" << 1
                           << "setName" << "rs0"
                           << "term" << 1LL
                           << "candidateId" << 20LL
                           << "configVersion" << 1LL
                           << "lastCommittedOp" << BSON ("ts" << Timestamp(10, 0)
                                                      << "term" << 0LL)));
        ReplSetRequestVotesResponse response3;

        getTopoCoord().processReplSetRequestVotes(args3, &response3, lastAppliedOpTime);
        ASSERT_EQUALS("candidate's term is lower than mine", response3.getReason());
        ASSERT_EQUALS(2, response3.getTerm());
        ASSERT_FALSE(response3.getVoteGranted());
    
        // stale OpTime
        ReplSetRequestVotesArgs args4;
        args4.initialize(BSON("replSetRequestVotes" << 1
                           << "setName" << "rs0"
                           << "term" << 3LL
                           << "candidateId" << 20LL
                           << "configVersion" << 1LL
                           << "lastCommittedOp" << BSON ("ts" << Timestamp(10, 0)
                                                      << "term" << 0LL)));
        ReplSetRequestVotesResponse response4;
        OpTime lastAppliedOpTime2 = {Timestamp(20, 0), 0};

        getTopoCoord().processReplSetRequestVotes(args4, &response4, lastAppliedOpTime2);
        ASSERT_EQUALS("candidate's data is staler than mine", response4.getReason());
        ASSERT_FALSE(response4.getVoteGranted());
    }

    TEST_F(TopoCoordTest, ProcessDeclareElectionWinner) {
        updateConfig(BSON("_id" << "rs0" <<
                          "version" << 1 <<
                          "members" << BSON_ARRAY(
                              BSON("_id" << 10 << "host" << "hself") <<
                              BSON("_id" << 20 << "host" << "h2") <<
                              BSON("_id" << 30 << "host" << "h3"))),
                     0);
        setSelfMemberState(MemberState::RS_SECONDARY);

        // successful
        ReplSetDeclareElectionWinnerArgs winnerArgs;
        winnerArgs.initialize(BSON("replSetDeclareElectionWinner" << 1
                                << "setName" << "rs0"
                                << "term" << 2
                                << "winnerId" << 30));
        long long responseTerm = -1;
        ASSERT(getTopoCoord().updateTerm(winnerArgs.getTerm()));
        ASSERT_OK(getTopoCoord().processReplSetDeclareElectionWinner(winnerArgs, &responseTerm));
        ASSERT_EQUALS(2, responseTerm);

        // repeat, should be problem free
        ReplSetDeclareElectionWinnerArgs winnerArgs2;
        winnerArgs2.initialize(BSON("replSetDeclareElectionWinner" << 1
                                 << "setName" << "rs0"
                                 << "term" << 2
                                 << "winnerId" << 30));
        long long responseTerm2 = -1;
        ASSERT_OK(getTopoCoord().processReplSetDeclareElectionWinner(winnerArgs2, &responseTerm2));
        ASSERT_EQUALS(2, responseTerm2);

        // same term, different primary, should fail
        ReplSetDeclareElectionWinnerArgs winnerArgs3;
        winnerArgs3.initialize(BSON("replSetDeclareElectionWinner" << 1
                                 << "setName" << "rs0"
                                 << "term" << 2
                                 << "winnerId" << 20));
        long long responseTerm3 = -1;
        ASSERT_EQUALS("term already has a primary",
                      getTopoCoord().processReplSetDeclareElectionWinner(winnerArgs3,
                                                                         &responseTerm3).reason());
        ASSERT_EQUALS(2, responseTerm3);

        // stale term, should fail
        ReplSetDeclareElectionWinnerArgs winnerArgs4;
        winnerArgs4.initialize(BSON("replSetDeclareElectionWinner" << 1
                                 << "setName" << "rs0"
                                 << "term" << 0
                                 << "winnerId" << 20));
        long long responseTerm4 = -1;
        ASSERT_EQUALS("term has already passed",
                      getTopoCoord().processReplSetDeclareElectionWinner(winnerArgs4,
                                                                         &responseTerm4).reason());
        ASSERT_EQUALS(2, responseTerm4);

        // wrong setName
        ReplSetDeclareElectionWinnerArgs winnerArgs5;
        winnerArgs5.initialize(BSON("replSetDeclareElectionWinner" << 1
                                 << "setName" << "wrongName"
                                 << "term" << 3
                                 << "winnerId" << 20));
        long long responseTerm5 = -1;
        ASSERT_EQUALS("replSet name does not match",
                      getTopoCoord().processReplSetDeclareElectionWinner(winnerArgs5,
                                                                         &responseTerm5).reason());
        ASSERT_EQUALS(2, responseTerm5);
    }

}  // namespace
}  // namespace repl
}  // namespace mongo