mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

Valery Kharseko
yesterday 5055b6312ff61ef861be42bfb2827aa561bc1593
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
/*
 * The contents of this file are subject to the terms of the Common Development and
 * Distribution License (the License). You may not use this file except in compliance with the
 * License.
 *
 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
 * specific language governing permission and limitations under the License.
 *
 * When distributing Covered Software, include this CDDL Header Notice in each file and include
 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
 * Header, with the fields enclosed by brackets [] replaced by your own identifying
 * information: "Portions Copyright [year] [name of copyright owner]".
 *
 * Copyright 2008-2010 Sun Microsystems, Inc.
 * Portions Copyright 2011-2016 ForgeRock AS.
 * Portions Copyright 2025-2026 3A Systems, LLC.
 */
package org.opends.server.replication.service;
 
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.opends.messages.ReplicationMessages.*;
import static org.opends.server.TestCaseUtils.generateThreadDump;
import static org.opends.server.util.CollectionUtils.*;
import static org.testng.Assert.*;
 
import java.net.SocketTimeoutException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
 
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.slf4j.LocalizedLogger;
import org.opends.server.TestCaseUtils;
import org.opends.server.backends.task.Task;
import org.opends.server.replication.ReplicationTestCase;
import org.opends.server.replication.common.CSN;
import org.opends.server.replication.common.CSNGenerator;
import org.opends.server.replication.common.DSInfo;
import org.opends.server.replication.common.RSInfo;
import org.opends.server.replication.common.ServerState;
import org.opends.server.replication.common.ServerStatus;
import org.opends.server.replication.plugin.DomainFakeCfg;
import org.opends.server.replication.plugin.DummyReplicationDomain;
import org.opends.server.replication.protocol.ByteArrayBuilder;
import org.opends.server.replication.protocol.DeleteMsg;
import org.opends.server.replication.protocol.ErrorMsg;
import org.opends.server.replication.protocol.ProtocolVersion;
import org.opends.server.replication.protocol.ReplicationMsg;
import org.opends.server.replication.protocol.ResetGenerationIdMsg;
import org.opends.server.replication.protocol.TopologyMsg;
import org.opends.server.replication.protocol.UpdateMsg;
import org.opends.server.replication.server.ReplServerFakeConfiguration;
import org.opends.server.replication.server.ReplicationServer;
import org.opends.server.replication.server.ReplicationServerDomain;
import org.opends.server.replication.server.ReplicationServerHandler;
import org.opends.server.replication.server.ServerHandler;
import org.opends.server.replication.service.ReplicationDomain.ImportExportContext;
import org.forgerock.opendj.ldap.DN;
import org.opends.server.tasks.InitializeTask;
import org.opends.server.types.DirectoryException;
import org.opends.server.util.TestTimer;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
 
/**
 * Test the Generic Replication Service.
 */
@SuppressWarnings("javadoc")
public class ReplicationDomainTest extends ReplicationTestCase
{
  private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
  private static final Task NO_INIT_TASK = null;
 
  @DataProvider(name = "publishAndReceiveData")
  public Object[][] createpublishAndReceiveData()
  {
    return new Object[][] {
       {1, 2, 3, 4},
       {1, 2, 1, 2},
       {1, 2, 45891, 45672},
       {45610, 45720, 1, 2},
       {45610, 45720, 45891, 45672}
    };
  }
 
  /**
   * Test that a ReplicationDomain is able to publish and receive UpdateMsg.
   * Also test the ReplicationDomain.resetReplicationLog() method.
   */
  @Test(dataProvider = "publishAndReceiveData", enabled=true)
  public void publishAndReceive(
      int replServerID1, int replServerID2,
      int domain1ServerId, int domain2ServerId)
      throws Exception
  {
    DN testService = DN.valueOf("o=test");
    ReplicationServer replServer1 = null;
    ReplicationServer replServer2 = null;
    FakeReplicationDomain domain1 = null;
    FakeReplicationDomain domain2 = null;
 
    try
    {
      int[] ports = TestCaseUtils.findFreePorts(2);
      int replServerPort1 = ports[0];
      int replServerPort2 = ports[1];
 
      replServer1 = createReplicationServer(replServerID1, replServerPort1,
          "ReplicationDomainTestDb1", 100, "localhost:" + replServerPort2);
      replServer2 = createReplicationServer(replServerID2, replServerPort2,
          "ReplicationDomainTestDb2", 100, "localhost:" + replServerPort1);
 
      SortedSet<String> servers = newTreeSet("localhost:" + replServerPort1);
      BlockingQueue<UpdateMsg> rcvQueue1 = new LinkedBlockingQueue<>();
      domain1 = new FakeReplicationDomain(
          testService, domain1ServerId, servers, 100, 1000, rcvQueue1);
 
      SortedSet<String> servers2 = newTreeSet("localhost:" + replServerPort2);
      BlockingQueue<UpdateMsg> rcvQueue2 = new LinkedBlockingQueue<>();
      domain2 = new FakeReplicationDomain(
          testService, domain2ServerId, servers2, 100, 1000, rcvQueue2);
 
      Thread.sleep(500);
 
      /*
       * Publish a message from domain1,
       * Check that domain2 receives it shortly after.
       */
      byte[] test = {1, 2, 3 ,4, 0, 1, 2, 3, 4, 5};
      publish(domain1, test);
 
      UpdateMsg rcvdMsg = rcvQueue2.poll(20, TimeUnit.SECONDS);
      assertNotNull(rcvdMsg);
      assertEquals(test, rcvdMsg.getPayload());
 
      for (RSInfo replServerInfo : domain1.getRsInfos())
      {
        // The generation Id of the remote should be 1
        assertEquals(replServerInfo.getGenerationId(), 1,
            "Unexpected value of generationId in RSInfo for RS=" + replServerInfo);
      }
 
      for (DSInfo serverInfo : domain1.getReplicaInfos().values())
      {
        assertEquals(serverInfo.getStatus(), ServerStatus.NORMAL_STATUS);
      }
 
      domain1.setGenerationID(2);
      domain1.resetReplicationLog();
      Thread.sleep(500);
 
      for (RSInfo replServerInfo : domain1.getRsInfos())
      {
        // The generation Id of the remote should now be 2
        assertEquals(replServerInfo.getGenerationId(), 2,
            "Unexpected value of generationId in RSInfo for RS=" + replServerInfo);
      }
 
      int sleepTime = 50;
      while (true)
      {
        try
        {
          assertExpectedServerStatuses(domain1.getReplicaInfos(),
              domain1ServerId, domain2ServerId);
          assertExpectedServerStatuses(domain2.getReplicaInfos(),
              domain1ServerId, domain2ServerId);
 
          Map<Integer, ServerState> states1 = domain1.getReplicaStates();
          ServerState state2 = states1.get(domain2ServerId);
          assertNotNull(state2, "getReplicaStates is not showing DS2");
 
          Map<Integer, ServerState> states2 = domain2.getReplicaStates();
          ServerState state1 = states2.get(domain1ServerId);
          assertNotNull(state1, "getReplicaStates is not showing DS1");
 
          // if we reach this point all tests are OK
          break;
        }
        catch (AssertionError e)
        {
          if (sleepTime >= 30000)
          {
            throw e;
          }
          Thread.sleep(sleepTime);
          sleepTime *= 2;
        }
      }
    }
    finally
    {
      disable(domain1, domain2);
      remove(replServer1, replServer2);
    }
  }
 
  /**
   * Publish information to the Replication Service (not assured mode).
   *
   * @param msg  The byte array containing the information that should
   *             be sent to the remote entities.
   */
  void publish(FakeReplicationDomain domain, byte[] msg)
  {
    UpdateMsg updateMsg;
    synchronized (this)
    {
      updateMsg = new UpdateMsg(domain.getGenerator().newCSN(), msg);
      // If assured replication is configured,
      // this will prepare blocking mechanism.
      // If assured replication is disabled, this returns immediately
      domain.prepareWaitForAckIfAssuredEnabled(updateMsg);
      domain.publish(updateMsg);
    }
 
    try
    {
      // If assured replication is enabled,
      // this will wait for the matching ack or time out.
      // If assured replication is disabled, this returns immediately
      domain.waitForAckIfAssuredEnabled(updateMsg);
    }
    catch (TimeoutException ex)
    {
      // This exception may only be raised if assured replication is enabled
      logger.info(NOTE_DS_ACK_TIMEOUT, domain.getBaseDN(), domain.getAssuredTimeout(), updateMsg);
    }
  }
 
  private void assertExpectedServerStatuses(Map<Integer, DSInfo> dsInfos,
      int domain1ServerId, int domain2ServerId)
  {
    for (DSInfo serverInfo : dsInfos.values())
    {
      if (serverInfo.getDsId() == domain2ServerId)
      {
        assertEquals(serverInfo.getStatus(), ServerStatus.BAD_GEN_ID_STATUS);
      }
      else
      {
        assertEquals(serverInfo.getDsId(), domain1ServerId);
        assertEquals(serverInfo.getStatus(), ServerStatus.NORMAL_STATUS);
      }
    }
  }
 
  /**
   * The session generation is the identity of a session: a replay thread which stopped the
   * session and let the lock go compares the generation it read then with the one it reads
   * when it comes back, and starts the session only if the two are the same. Both halves
   * of a restart have to move it, or a session stopped or started by something else in the
   * meantime would look like the one that thread stopped.
   */
  @Test
  public void everyStopAndEveryStartOfTheSessionIsCounted() throws Exception
  {
    final DN testService = DN.valueOf("o=test");
    ReplicationServer replServer = null;
    FakeReplicationDomain domain = null;
    try
    {
      final int replServerPort = TestCaseUtils.findFreePort();
      replServer = createReplicationServer(1, replServerPort, "ReplicationDomainTestDbGeneration", 100);
      domain = new FakeReplicationDomain(testService, 2, newTreeSet("localhost:" + replServerPort), 1000, 1);
 
      final long live = sessionGenerationOf(domain);
      domain.disableService();
      final long stopped = sessionGenerationOf(domain);
      assertNotEquals(stopped, live, "stopping the session left its generation where it was");
 
      domain.enableService();
      final long started = sessionGenerationOf(domain);
      assertNotEquals(started, stopped, "starting the session left its generation where it was");
    }
    finally
    {
      disable(domain);
      remove(replServer);
    }
  }
 
  /**
   * What {@code restartSession()} of the LDAP domain does, minus the wait: the session is
   * stopped, the generation is read as the claim on it, and the lock is let go. A
   * {@link ReplicationDomain#restartService()} run by something else in the meantime - a
   * configuration change - has to leave that claim stale, or the thread which comes back
   * from its wait could not tell the session it stopped from the one which replaced it.
   */
  @Test
  public void aClaimOnAStoppedSessionIsStaleOnceSomethingElseRestartedIt() throws Exception
  {
    final DN testService = DN.valueOf("o=test");
    ReplicationServer replServer = null;
    FakeReplicationDomain domain = null;
    try
    {
      final int replServerPort = TestCaseUtils.findFreePort();
      replServer = createReplicationServer(1, replServerPort, "ReplicationDomainTestDbStaleClaim", 100);
      domain = new FakeReplicationDomain(testService, 2, newTreeSet("localhost:" + replServerPort), 1000, 1);
 
      domain.disableService();
      final long claim = sessionGenerationOf(domain);
 
      domain.restartService();
 
      assertNotEquals(sessionGenerationOf(domain), claim,
          "a restart of the session by something else left the generation where it was,"
              + " so the claim of the thread which stopped it still looks current");
    }
    finally
    {
      disable(domain);
      remove(replServer);
    }
  }
 
  /** Read under the lock, as {@link ReplicationDomain#getSessionGeneration()} asks. */
  private static long sessionGenerationOf(ReplicationDomain domain)
  {
    synchronized (domain.serviceStateLock)
    {
      return domain.getSessionGeneration();
    }
  }
 
  /**
   * Publish performance test.
   * The test loops calling the publish methods of the ReplicationDomain.
   * It should not be enabled by default as it will use a lot of time.
   * Its call is only to investigate performance issues with the replication.
   */
  @Test(enabled=false)
  public void publishPerf() throws Exception
  {
    DN testService = DN.valueOf("o=test");
    ReplicationServer replServer1 = null;
    int replServerID1 = 10;
    FakeReplicationDomain domain1 = null;
    int domain1ServerId = 1;
 
    try
    {
      int replServerPort = TestCaseUtils.findFreePort();
 
      replServer1 = createReplicationServer(replServerID1, replServerPort,
          "ReplicationDomainTestDb", 100000, "localhost:" + replServerPort);
 
      SortedSet<String> servers = newTreeSet("localhost:" + replServerPort);
      BlockingQueue<UpdateMsg> rcvQueue1 = new LinkedBlockingQueue<>();
      domain1 = new FakeReplicationDomain(
          testService, domain1ServerId, servers, 1000, 100000, rcvQueue1);
 
 
      /*
       * Publish a message from domain1,
       * Check that domain2 receives it shortly after.
       */
      byte[] test = {1, 2, 3 ,4, 0, 1, 2, 3, 4, 5};
 
      long timeNow = System.nanoTime();
      timeNow = publishRepeatedly(domain1, test, timeNow);
      timeNow = publishRepeatedly(domain1, test, timeNow);
      timeNow = publishRepeatedly(domain1, test, timeNow);
      timeNow = publishRepeatedly(domain1, test, timeNow);
    }
    finally
    {
      disable(domain1);
      remove(replServer1);
    }
  }
 
  private long publishRepeatedly(FakeReplicationDomain domain1, byte[] test, long timeNow)
  {
    long timeStart = timeNow;
    for (int i = 0; i < 100000; i++)
    {
      publish(domain1, test);
    }
    timeNow = System.nanoTime();
    System.out.println(timeNow - timeStart);
    return timeNow;
  }
 
  private ReplicationServer createReplicationServer(int serverId,
      int replicationPort, String dirName, int windowSize,
      String... replServers) throws Exception
  {
    return createReplicationServer(serverId, replicationPort, dirName, windowSize, newTreeSet(replServers));
  }
 
  private ReplicationServer createReplicationServer(int serverId,
      int replicationPort, String dirName, int windowSize,
      SortedSet<String> replServers) throws Exception
  {
    return new ReplicationServer(
        new ReplServerFakeConfiguration(replicationPort, dirName, 0, serverId, 0, windowSize, replServers));
  }
 
  private void disable(ReplicationDomain... domains) throws InterruptedException {
    for (ReplicationDomain domain : domains)
    {
      if (domain != null)
      {
        domain.disableService();
      }
    }
  }
 
  @DataProvider(name = "exportAndImportData")
  public Object[][] createExportAndimportData()
  {
    return new Object[][] {
       {1, 2},
       {45610, 45720}
    };
  }
 
  /**
   * Test that a ReplicationDomain is able to export and import its database
   * When there is only one replication server.
   */
  @Test(dataProvider = "exportAndImportData", enabled=true)
  public void exportAndImport(int serverId1, int serverId2) throws Exception
  {
    final int ENTRYCOUNT=5000;
    DN testService = DN.valueOf("o=test");
    ReplicationServer replServer = null;
    int replServerID = 11;
    FakeReplicationDomain domain1 = null;
    FakeReplicationDomain domain2 = null;
 
    try
    {
      int replServerPort = TestCaseUtils.findFreePort();
 
      replServer = createReplicationServer(replServerID, replServerPort,
          "exportAndImportData", 100);
      SortedSet<String> servers = newTreeSet("localhost:" + replServerPort);
 
      String exportedData = buildExportedData(ENTRYCOUNT);
      domain1 = new FakeReplicationDomain(
          testService, serverId1, servers, 0, exportedData, null, ENTRYCOUNT);
 
      StringBuffer importedData = new StringBuffer();
      domain2 = new FakeReplicationDomain(
          testService, serverId2, servers, 0, null, importedData, 0);
 
      /*
       * Trigger a total update from domain1 to domain2.
       * Check that the exported data is correctly received on domain2.
       */
      assertTrue(initializeFromRemote(domain2));
      waitEndExport(exportedData, importedData);
      assertExportSucessful(domain1, domain2, exportedData, importedData);
    }
    finally
    {
      disable(domain1, domain2);
      remove(replServer);
    }
  }
 
  private boolean initializeFromRemote(ReplicationDomain domain) throws DirectoryException
  {
    try {
      Thread.sleep(2000);
    } catch (InterruptedException e) {
      throw new RuntimeException(e);
    }
    for (DSInfo remoteDS : domain.getReplicaInfos().values())
    {
      if (remoteDS.getDsId() != domain.getServerId())
      {
        domain.initializeFromRemote(remoteDS.getDsId(), NO_INIT_TASK);
        return true;
      }
    }
    return false;
  }
 
  /**
   * Test that a ReplicationDomain is able to export and import its database
   * across 2 replication servers.
   */
  @Test(enabled=true)
  public void exportAndImportAcross2ReplServers() throws Exception
  {
    final int ENTRYCOUNT=5000;
    DN testService = DN.valueOf("o=test");
    ReplicationServer replServer2 = null;
    ReplicationServer replServer1 = null;
    int replServerID = 11;
    int replServerID2 = 12;
    FakeReplicationDomain domain1 = null;
    FakeReplicationDomain domain2 = null;
 
    try
    {
      int[] ports = TestCaseUtils.findFreePorts(2);
      int replServerPort1 = ports[0];
      int replServerPort2 = ports[1];
 
      replServer1 = createReplicationServer(replServerID, replServerPort1,
          "exportAndImportservice1", 100);
      replServer2 = createReplicationServer(replServerID2, replServerPort2,
          "exportAndImportservice2", 100, "localhost:" + replServerPort1);
 
      SortedSet<String> servers1 = newTreeSet("localhost:" + replServerPort1);
      SortedSet<String> servers2 = newTreeSet("localhost:" + replServerPort2);
 
      String exportedData = buildExportedData(ENTRYCOUNT);
      domain1 = new FakeReplicationDomain(
          testService, 1, servers1, 0, exportedData, null, ENTRYCOUNT);
 
      StringBuffer importedData = new StringBuffer();
      domain2 = new FakeReplicationDomain(
          testService, 2, servers2, 0, null, importedData, 0);
 
 
      //wait for domains topology initialization
      {
        TestTimer timer = new TestTimer.Builder()
                .maxSleep(30, SECONDS)
                .sleepTimes(100, MILLISECONDS)
                .toTimer();
        final FakeReplicationDomain finalDomain1 = domain1;
        final FakeReplicationDomain finalDomain2 = domain2;
        timer.repeatUntilSuccess(() -> {
          assertFalse(finalDomain1.getReplicaInfos().isEmpty());
          assertEquals(2, finalDomain1.getRsInfos().size());
          assertFalse(finalDomain2.getReplicaInfos().isEmpty());
          assertEquals(2, finalDomain2.getRsInfos().size());
        });
      }
 
      domain2.initializeFromRemote(1, NO_INIT_TASK);
 
      waitEndExport(exportedData, importedData);
      assertExportSucessful(domain1, domain2, exportedData, importedData);
    }
    finally
    {
      disable(domain1, domain2);
      remove(replServer1, replServer2);
    }
  }
 
  @DataProvider
  public Object[][] replicaWithTheIdOfItsReplicationServer()
  {
    // the id of the replication server is 11
    return new Object[][] {
      { 1, 11 }, // the importer has it: InitializeTargetMsg and the entries are sent to 11
      { 11, 2 }, // the exporter has it: InitializeRequestMsg and the acknowledgements are sent to 11
    };
  }
 
  /**
   * A replica whose server id is the one of the replication server it is connected to can be
   * initialized, and can initialize others, through it (issue #1207).
   * <p>
   * The replication server takes a message for one of its replicas, not for itself: it has no data to
   * export or import, and before the fix it answered every total update message sent to its own id
   * with an ErrorMsg, so the total update never got through.
   */
  @Test(dataProvider = "replicaWithTheIdOfItsReplicationServer")
  public void exportAndImportWithAReplicaHavingTheIdOfItsReplicationServer(int exporterId, int importerId)
      throws Exception
  {
    final int ENTRYCOUNT = 100;
    DN testService = DN.valueOf("o=test");
    ReplicationServer replServer = null;
    FakeReplicationDomain exporter = null;
    FakeReplicationDomain importer = null;
 
    try
    {
      int replServerPort = TestCaseUtils.findFreePort();
      replServer = createReplicationServer(11, replServerPort, "replicaWithTheIdOfItsRS", 100);
      SortedSet<String> servers = newTreeSet("localhost:" + replServerPort);
 
      String exportedData = buildExportedData(ENTRYCOUNT);
      exporter = new FakeReplicationDomain(testService, exporterId, servers, 0, exportedData, null, ENTRYCOUNT);
      StringBuffer importedData = new StringBuffer();
      importer = new FakeReplicationDomain(testService, importerId, servers, 0, null, importedData, 0);
      waitTopologyKnowsReplica(importer, exporterId);
      waitTopologyKnowsReplica(exporter, importerId);
 
      importer.initializeFromRemote(exporterId, NO_INIT_TASK);
 
      waitEndExport(exportedData, importedData);
      assertExportSucessful(exporter, importer, exportedData, importedData);
    }
    finally
    {
      disable(exporter, importer);
      remove(replServer);
    }
  }
 
  @DataProvider
  public Object[][] replicaWithTheIdOfAnotherReplicationServer()
  {
    // the replica with the id of the first replication server, 11, is the importer
    return new Object[][] {
      { 0, 1 }, // a replica of the first RS sends to 11: the first RS hands it on to the second
      { 1, 0 }, // a replica of the second RS sends to 11: the first RS gets it from the second RS
    };
  }
 
  /**
   * A replica whose server id is the one of a replication server can be initialized across two
   * replication servers, whether it is connected to that replication server or to the other one
   * (issue #1207).
   */
  @Test(dataProvider = "replicaWithTheIdOfAnotherReplicationServer")
  public void exportAndImportAcross2ReplServersWithAReplicaHavingTheIdOfAReplicationServer(
      int exporterRs, int importerRs) throws Exception
  {
    final int ENTRYCOUNT = 100;
    final int exporterId = 1;
    final int importerId = 11;
    DN testService = DN.valueOf("o=test");
    ReplicationServer replServer1 = null;
    ReplicationServer replServer2 = null;
    FakeReplicationDomain exporter = null;
    FakeReplicationDomain importer = null;
 
    try
    {
      int[] ports = TestCaseUtils.findFreePorts(2);
      replServer1 = createReplicationServer(11, ports[0], "replicaWithTheIdOfAnRS1", 100);
      replServer2 = createReplicationServer(12, ports[1], "replicaWithTheIdOfAnRS2", 100, "localhost:" + ports[0]);
 
      String exportedData = buildExportedData(ENTRYCOUNT);
      exporter = new FakeReplicationDomain(testService, exporterId, newTreeSet("localhost:" + ports[exporterRs]),
          0, exportedData, null, ENTRYCOUNT);
      StringBuffer importedData = new StringBuffer();
      importer = new FakeReplicationDomain(testService, importerId, newTreeSet("localhost:" + ports[importerRs]),
          0, null, importedData, 0);
      waitTopologyKnowsReplica(importer, exporterId);
      waitTopologyKnowsReplica(exporter, importerId);
 
      importer.initializeFromRemote(exporterId, NO_INIT_TASK);
 
      waitEndExport(exportedData, importedData);
      assertExportSucessful(exporter, importer, exportedData, importedData);
    }
    finally
    {
      disable(exporter, importer);
      remove(replServer1, replServer2);
    }
  }
 
  /** A replication server reports a replica which connects to it with its own server id (issue #1207). */
  @Test
  public void replicaWithTheIdOfItsReplicationServerIsReported() throws Exception
  {
    DN testService = DN.valueOf("o=test");
    ReplicationServer replServer = null;
    FakeReplicationDomain domain = null;
 
    try
    {
      int replServerPort = TestCaseUtils.findFreePort();
      replServer = createReplicationServer(11, replServerPort, "replicaWithTheIdOfItsRSIsReported", 100);
      TestCaseUtils.ERROR_TEXT_WRITER.clear();
 
      domain = new FakeReplicationDomain(testService, 11, newTreeSet("localhost:" + replServerPort), 0, 1);
 
      waitSharedServerIdReported(replServer, 11, testService);
    }
    finally
    {
      disable(domain);
      remove(replServer);
    }
  }
 
  /**
   * A replication server reports a replica which connects to it with the server id of a replication
   * server it is connected to, and only that replica (issue #1207).
   */
  @Test
  public void replicaWithTheIdOfAConnectedReplicationServerIsReported() throws Exception
  {
    DN testService = DN.valueOf("o=test");
    ReplicationServer replServer1 = null;
    ReplicationServer replServer2 = null;
    FakeReplicationDomain domain2 = null;
    FakeReplicationDomain domain11 = null;
 
    try
    {
      int[] ports = TestCaseUtils.findFreePorts(2);
      replServer1 = createReplicationServer(11, ports[0], "replicaWithTheIdOfAConnectedRS1", 100);
      replServer2 = createReplicationServer(12, ports[1], "replicaWithTheIdOfAConnectedRS2", 100,
          "localhost:" + ports[0]);
      TestCaseUtils.ERROR_TEXT_WRITER.clear();
      // the domain of the second replication server connects it to the first one
      domain2 = new FakeReplicationDomain(testService, 2, newTreeSet("localhost:" + ports[1]), 0, 1);
      waitTopologyKnowsReplicationServers(domain2, 2);
 
      domain11 = new FakeReplicationDomain(testService, 11, newTreeSet("localhost:" + ports[1]), 0, 1);
 
      waitSharedServerIdReported(replServer2, 11, testService);
      assertEquals(sharedServerIdRecords(replServer2, 2, testService), newArrayList(),
          "a replica whose server id no replication server has must not be reported");
    }
    finally
    {
      disable(domain2, domain11);
      remove(replServer1, replServer2);
    }
  }
 
  /**
   * A replication server reports a replication server which connects to it with the server id of one
   * of its replicas (issue #1207).
   */
  @Test
  public void replicationServerWithTheIdOfAConnectedReplicaIsReported() throws Exception
  {
    DN testService = DN.valueOf("o=test");
    ReplicationServer replServer1 = null;
    ReplicationServer replServer2 = null;
    FakeReplicationDomain domain11 = null;
 
    try
    {
      int[] ports = TestCaseUtils.findFreePorts(2);
      replServer2 = createReplicationServer(12, ports[1], "rsWithTheIdOfAConnectedReplica2", 100);
      domain11 = new FakeReplicationDomain(testService, 11, newTreeSet("localhost:" + ports[1]), 0, 1);
      waitConnected(domain11);
      TestCaseUtils.ERROR_TEXT_WRITER.clear();
 
      replServer1 = createReplicationServer(11, ports[0], "rsWithTheIdOfAConnectedReplica1", 100,
          "localhost:" + ports[1]);
      // a replication server connects to its peers for the domains it has
      replServer1.getReplicationServerDomain(testService, true);
 
      waitSharedServerIdReported(replServer2, 11, testService);
    }
    finally
    {
      disable(domain11);
      remove(replServer1, replServer2);
    }
  }
 
  /**
   * A replication server takes for itself the warning a peer replication server sends it when their
   * generation ids differ, also when one of its replicas has its server id: the replica would take the
   * warning for the end of the total update it is in (issue #1207).
   */
  @Test
  public void generationIdWarningOfAPeerIsNotForTheReplicaWithTheIdOfTheReplicationServer() throws Exception
  {
    DN testService = DN.valueOf("o=test");
    ReplicationServer replServer1 = null;
    ReplicationServer replServer2 = null;
    ReplicationBroker broker11 = null;
    ReplicationBroker broker2 = null;
 
    try
    {
      int[] ports = TestCaseUtils.findFreePorts(2);
      replServer1 = createReplicationServer(11, ports[0], "genIdWarningOfAPeer1", 100);
      replServer2 = createReplicationServer(12, ports[1], "genIdWarningOfAPeer2", 100);
      // a replication server takes the generation id of the first replica which connects to it
      broker11 = openReplicationSession(testService, 11, 100, ports[0], 1000, 1111);
      broker2 = openReplicationSession(testService, 2, 100, ports[1], 1000, 2222);
      TestCaseUtils.ERROR_TEXT_WRITER.clear();
 
      // the second replication server connects to the first one and warns it that their generation ids differ
      replServer2.applyConfigurationChange(new ReplServerFakeConfiguration(
          ports[1], "genIdWarningOfAPeer2", 0, 12, 0, 100, newTreeSet("localhost:" + ports[0])));
 
      waitGenerationIdWarningOfPeerReceived(testService, 11, 1111, 12, 2222);
      assertNoErrorMsgReceived(broker11);
    }
    finally
    {
      stop(broker11, broker2);
      remove(replServer1, replServer2);
    }
  }
 
  /**
   * A peer replication server which presents no generation id has reset its own, seeing no replica left in
   * the topology: it has none to differ from, and a replication server which still has one does not warn
   * about it, nor send it the warning (issue #1235). A peer which presents another generation id is still
   * warned about.
   */
  @Test
  public void peerWithoutGenerationIdIsNotWarnedAbout() throws Exception
  {
    DN testService = DN.valueOf("o=test");
    ReplicationServer replServer1 = null;
    ReplicationServer replServer2 = null;
    ReplicationBroker broker1 = null;
 
    try
    {
      int[] ports = TestCaseUtils.findFreePorts(2);
      replServer1 = createReplicationServer(21, ports[0], "peerWithoutGenerationId1", 100);
      replServer2 = createReplicationServer(22, ports[1], "peerWithoutGenerationId2", 100, "localhost:" + ports[0]);
      // the first replication server takes the generation id of the replica, which keeps it from resetting it,
      // and the second one takes it from the first
      broker1 = openReplicationSession(testService, 1, 100, ports[0], 1000, 3333);
      replServer2.getReplicationServerDomain(testService, true);
      waitReplicationServerConnected(replServer1, testService, 22);
      waitReplicationServerConnected(replServer2, testService, 21);
 
      // what the second replication server sends once it has reset its generation id
      ServerHandler toReplServer1 = replServer2.getReplicationServerDomain(testService).getConnectedRSs().get(21);
      toReplServer1.send(topologyMsgOf(replServer2, -1));
      // sent on the same connection after it: once the warning about this one is back, the one before was handled
      toReplServer1.send(topologyMsgOf(replServer2, 4444));
 
      waitGenerationIdWarningOfPeerReceived(testService, 22, 4444L, 21, 3333L);
      // the warning, as the first replication server logs it or as the second one logs it on receipt
      final String[] warning = WARN_BAD_GENERATION_ID_FROM_RS.get(
          22, "@", -1L, testService, 21, 3333L).toString().split("@");
      for (String record : TestCaseUtils.ERROR_TEXT_WRITER.getMessages())
      {
        assertFalse(record.contains(warning[0]) && record.contains(warning[1]),
            "RS(22) without a generation id was taken for a mismatch: " + record);
      }
    }
    finally
    {
      stop(broker1);
      remove(replServer1, replServer2);
    }
  }
 
  /**
   * A replication server which takes the generation id of a peer from its TopologyMsg, after it reset its own,
   * tells its peers, and they forward it the updates again (issue #1236).
   */
  @Test
  public void peerWhichTakesTheGenerationIdAgainIsForwardedUpdates() throws Exception
  {
    DN testService = DN.valueOf("o=test");
    ReplicationServer replServer1 = null;
    ReplicationServer replServer2 = null;
    ReplicationBroker broker1 = null;
    ReplicationBroker broker2 = null;
 
    try
    {
      int[] ports = TestCaseUtils.findFreePorts(2);
      replServer1 = createReplicationServer(41, ports[0], "takesTheGenerationIdAgain1", 100);
      replServer2 = createReplicationServer(42, ports[1], "takesTheGenerationIdAgain2", 100, "localhost:" + ports[0]);
      broker1 = openReplicationSession(testService, 1, 100, ports[0], 1000, 5555);
      ReplicationServerDomain domain2 = replServer2.getReplicationServerDomain(testService, true);
      waitReplicationServerConnected(replServer1, testService, 42);
      waitReplicationServerConnected(replServer2, testService, 41);
      waitGenerationIdOfPeer(replServer1, testService, 42, 5555);
      // no TopologyMsg of the first one for its replica is left to cross what follows
      waitReplicaOfPeer(replServer2, testService, 41, 5555);
 
      // what the second replication server does when it sees no replica left in the topology
      domain2.changeGenerationId(-1);
      waitGenerationIdOfPeer(replServer1, testService, 42, -1);
 
      // a replica connecting to the first replication server makes it send its TopologyMsg to its peers
      broker2 = openReplicationSession(testService, 2, 100, ports[0], 1000, 5555);
      waitGenerationId(replServer2, testService, 5555);
      waitGenerationIdOfPeer(replServer1, testService, 42, 5555);
 
      CSN csn = new CSNGenerator(1, 0).newCSN();
      broker1.publish(new DeleteMsg(DN.valueOf("cn=deleted," + testService), csn, "uuid"));
      newTimer().repeatUntilSuccess(() -> assertTrue(domain2.getLatestServerState().cover(csn),
          "RS(42) did not get the update " + csn + " of DS(1)"));
    }
    finally
    {
      stop(broker1, broker2);
      remove(replServer1, replServer2);
    }
  }
 
  /**
   * Two replication servers which have no replica and the same generation id, which they did not save, send
   * each other a TopologyMsg with it: both end without a generation id and stay there (issue #1236).
   */
  @Test
  public void peersWithoutReplicaEndWithoutGenerationId() throws Exception
  {
    DN testService = DN.valueOf("o=test");
    ReplicationServer replServer1 = null;
    ReplicationServer replServer2 = null;
 
    try
    {
      int[] ports = TestCaseUtils.findFreePorts(2);
      replServer1 = createReplicationServer(51, ports[0], "peersWithoutReplica1", 100);
      replServer2 = createReplicationServer(52, ports[1], "peersWithoutReplica2", 100, "localhost:" + ports[0]);
      ReplicationServerDomain domain1 = replServer1.getReplicationServerDomain(testService, true);
      ReplicationServerDomain domain2 = replServer2.getReplicationServerDomain(testService, true);
      waitReplicationServerConnected(replServer1, testService, 52);
      waitReplicationServerConnected(replServer2, testService, 51);
 
      // the generation id the last replicas left them, each telling the other
      domain1.changeGenerationId(6666);
      domain2.changeGenerationId(6666);
 
      waitGenerationId(replServer1, testService, -1);
      waitGenerationId(replServer2, testService, -1);
      // and they stay there
      final long end = System.currentTimeMillis() + SECONDS.toMillis(2);
      while (System.currentTimeMillis() < end)
      {
        assertEquals(domain1.getGenerationId(), -1L, "generation id of RS(51)");
        assertEquals(domain2.getGenerationId(), -1L, "generation id of RS(52)");
        Thread.sleep(10);
      }
    }
    finally
    {
      remove(replServer1, replServer2);
    }
  }
 
  /**
   * A replication server without a generation id does not take the one of a peer which has no replica: that
   * peer can reset it on the next TopologyMsg it receives, and two replication servers taking it from each
   * other and telling each other would go on resetting it and taking it again in turn (issue #1236).
   */
  @Test
  public void peerWithoutReplicaGivesNoGenerationId() throws Exception
  {
    DN testService = DN.valueOf("o=test");
    ReplicationServer replServer1 = null;
    ReplicationServer replServer2 = null;
 
    try
    {
      int[] ports = TestCaseUtils.findFreePorts(2);
      replServer1 = createReplicationServer(61, ports[0], "peerWithoutReplicaGivesNoGenerationId1", 100);
      replServer2 = createReplicationServer(62, ports[1], "peerWithoutReplicaGivesNoGenerationId2", 100,
          "localhost:" + ports[0]);
      ReplicationServerDomain domain1 = replServer1.getReplicationServerDomain(testService, true);
      replServer2.getReplicationServerDomain(testService, true);
      waitReplicationServerConnected(replServer1, testService, 62);
      waitReplicationServerConnected(replServer2, testService, 61);
 
      // what the second replication server sends once it took a generation id which it has not saved, handled
      // here rather than by the reader of the connection: what this replication server would tell the second one
      // could only come back after the assertion
      ReplicationServerHandler toReplServer2 = domain1.getConnectedRSs().get(62);
      domain1.receiveTopoInfoFromRS(topologyMsgOf(replServer2, 6666), toReplServer2, true);
 
      assertEquals(toReplServer2.getGenerationId(), 6666L, "generation id RS(61) has for RS(62)");
      assertEquals(domain1.getGenerationId(), -1L, "generation id of RS(61)");
    }
    finally
    {
      remove(replServer1, replServer2);
    }
  }
 
  /**
   * A replication server which resets its generation id on the TopologyMsg of a peer which has a replica and
   * another generation id takes the one of that peer in the same call, and tells its peers (issue #1236).
   */
  @Test
  public void peerWithReplicaGivesItsGenerationIdRightAfterAReset() throws Exception
  {
    DN testService = DN.valueOf("o=test");
    ReplicationServer replServer1 = null;
    ReplicationServer replServer2 = null;
    ReplicationBroker broker1 = null;
 
    try
    {
      int[] ports = TestCaseUtils.findFreePorts(2);
      replServer1 = createReplicationServer(71, ports[0], "givesItsGenerationIdRightAfterAReset1", 100);
      replServer2 = createReplicationServer(72, ports[1], "givesItsGenerationIdRightAfterAReset2", 100,
          "localhost:" + ports[0]);
      broker1 = openReplicationSession(testService, 1, 100, ports[0], 1000, 5555);
      ReplicationServerDomain domain1 = replServer1.getReplicationServerDomain(testService);
      ReplicationServerDomain domain2 = replServer2.getReplicationServerDomain(testService, true);
      waitReplicationServerConnected(replServer1, testService, 72);
      waitReplicationServerConnected(replServer2, testService, 71);
      // no TopologyMsg of the first one for its replica is left to cross what follows
      waitReplicaOfPeer(replServer2, testService, 71, 5555);
 
      // a generation id which the second replication server has not saved and no replica has
      domain2.changeGenerationId(7777);
      waitGenerationIdOfPeer(replServer1, testService, 72, 7777);
 
      // sent once, so that the second replication server can only take the generation id in the call that resets it
      domain1.getConnectedRSs().get(72).send(domain1.createTopologyMsgForRS());
      waitGenerationId(replServer2, testService, 5555);
      waitGenerationIdOfPeer(replServer1, testService, 72, 5555);
    }
    finally
    {
      stop(broker1);
      remove(replServer1, replServer2);
    }
  }
 
  /**
   * A TopologyMsg which a peer sent before it got a reset of the generation id, as dsreplication
   * pre-external-initialization asks a replica for, still presents the generation id the reset cleared: a
   * replication server which has replicas does not take it, which would undo the reset there and on its peers
   * for good, nothing resetting it again while the replicas stay connected (issue #1236).
   */
  @Test
  public void topologyMsgSentBeforeAResetDoesNotUndoIt() throws Exception
  {
    DN testService = DN.valueOf("o=test");
    ReplicationServer replServer1 = null;
    ReplicationServer replServer2 = null;
    ReplicationBroker broker1 = null;
    ReplicationBroker broker2 = null;
 
    try
    {
      int[] ports = TestCaseUtils.findFreePorts(2);
      replServer1 = createReplicationServer(81, ports[0], "topologyMsgSentBeforeAReset1", 100);
      replServer2 = createReplicationServer(82, ports[1], "topologyMsgSentBeforeAReset2", 100,
          "localhost:" + ports[0]);
      broker1 = openReplicationSession(testService, 1, 100, ports[0], 1000, 5555);
      broker2 = openReplicationSession(testService, 2, 100, ports[1], 1000, 5555);
      ReplicationServerDomain domain1 = replServer1.getReplicationServerDomain(testService);
      ReplicationServerDomain domain2 = replServer2.getReplicationServerDomain(testService);
      waitReplicationServerConnected(replServer1, testService, 82);
      waitReplicationServerConnected(replServer2, testService, 81);
      // once each one knows the replica of the other, no TopologyMsg is left to cross the reset
      waitReplicaOfPeer(replServer1, testService, 82, 5555);
      waitReplicaOfPeer(replServer2, testService, 81, 5555);
      final TopologyMsg sentBeforeTheReset = domain2.createTopologyMsgForRS();
 
      // what dsreplication pre-external-initialization asks a replica for
      broker1.publish(new ResetGenerationIdMsg(-1));
      waitGenerationId(replServer1, testService, -1);
      waitGenerationId(replServer2, testService, -1);
      waitReplicaOfPeer(replServer1, testService, 82, -1);
 
      // handled here rather than by the reader of the connection, as when it crosses the reset
      domain1.receiveTopoInfoFromRS(sentBeforeTheReset, domain1.getConnectedRSs().get(82), true);
      assertEquals(domain1.getGenerationId(), -1L, "generation id of RS(81)");
    }
    finally
    {
      stop(broker1, broker2);
      remove(replServer1, replServer2);
    }
  }
 
  /**
   * A replication server without replicas and without a generation id, to which a peer with replicas presents
   * none either, as dsreplication pre-external-initialization leaves them, has nothing to take, and tells its
   * peers nothing (issue #1236).
   */
  @Test
  public void peerWithReplicaAndWithoutGenerationIdIsNotAnswered() throws Exception
  {
    DN testService = DN.valueOf("o=test");
    ReplicationServer replServer1 = null;
    ReplicationServer replServer2 = null;
    ReplicationBroker broker1 = null;
 
    try
    {
      int[] ports = TestCaseUtils.findFreePorts(2);
      replServer1 = createReplicationServer(101, ports[0], "peerWithReplicaIsNotAnswered1", 100);
      replServer2 = createReplicationServer(102, ports[1], "peerWithReplicaIsNotAnswered2", 100,
          "localhost:" + ports[0]);
      broker1 = openReplicationSession(testService, 1, 100, ports[0], 1000, 5555);
      ReplicationServerDomain domain1 = replServer1.getReplicationServerDomain(testService);
      ReplicationServerDomain domain2 = replServer2.getReplicationServerDomain(testService, true);
      waitReplicationServerConnected(replServer1, testService, 102);
      waitReplicationServerConnected(replServer2, testService, 101);
      waitReplicaOfPeer(replServer2, testService, 101, 5555);
 
      // what dsreplication pre-external-initialization asks a replica for
      broker1.publish(new ResetGenerationIdMsg(-1));
      waitGenerationId(replServer1, testService, -1);
      waitGenerationId(replServer2, testService, -1);
      waitGenerationIdOfPeer(replServer1, testService, 102, -1);
      waitReplicaOfPeer(replServer2, testService, 101, -1);
 
      broker1.setSoTimeout(100);
      // the TopologyMsgs of the reset itself
      countTopologyMsgs(broker1, SECONDS.toMillis(1));
      // what the first replication server sends its peers, handled here rather than by the reader of the
      // connection: whatever the second one tells the first one reaches the replica as a TopologyMsg
      domain2.receiveTopoInfoFromRS(domain1.createTopologyMsgForRS(), domain2.getConnectedRSs().get(101), true);
      final int received = countTopologyMsgs(broker1, SECONDS.toMillis(2));
      // a closed session receives nothing, which would count as quiet
      assertTrue(broker1.isConnected(), "DS(1) is still connected");
      assertEquals(received, 0, "TopologyMsgs DS(1) received once RS(102) was presented no generation id");
    }
    finally
    {
      stop(broker1);
      remove(replServer1, replServer2);
    }
  }
 
  /**
   * A replication server without a generation id, which takes the one of a replica that already has changes
   * from the first update of that replica, tells its peers, and they forward it the updates again
   * (issue #1240).
   */
  @Test
  public void generationIdTakenFromAnUpdateIsToldToThePeers() throws Exception
  {
    DN testService = DN.valueOf("o=test");
    ReplicationServer replServer1 = null;
    ReplicationServer replServer2 = null;
    ReplicationBroker broker1 = null;
    ReplicationBroker broker2 = null;
 
    try
    {
      int[] ports = TestCaseUtils.findFreePorts(2);
      replServer1 = createReplicationServer(91, ports[0], "generationIdTakenFromAnUpdate1", 100);
      replServer2 = createReplicationServer(92, ports[1], "generationIdTakenFromAnUpdate2", 100,
          "localhost:" + ports[0]);
      broker1 = openReplicationSession(testService, 1, 100, ports[0], 1000, 5555);
      ReplicationServerDomain domain2 = replServer2.getReplicationServerDomain(testService, true);
      waitReplicationServerConnected(replServer1, testService, 92);
      waitReplicationServerConnected(replServer2, testService, 91);
      // no TopologyMsg of the first one for its replica is left to cross what follows
      waitReplicaOfPeer(replServer2, testService, 91, 5555);
 
      domain2.changeGenerationId(-1);
      waitGenerationIdOfPeer(replServer1, testService, 92, -1);
 
      // a replica which has changes does not give its generation id at the handshake
      CSNGenerator csnGenerator2 = new CSNGenerator(2, 0);
      ServerState state2 = new ServerState();
      state2.update(csnGenerator2.newCSN());
      broker2 = openReplicationSession(testService, 2, ports[1], state2, 5555);
      // the TopologyMsg the second replication server sent for the replica is handled, and nothing is left
      // to tell the first one the generation id but the update
      waitReplicaOfPeer(replServer1, testService, 92, -1);
      assertEquals(domain2.getGenerationId(), -1L, "generation id of RS(92) before the update of DS(2)");
 
      broker2.publish(new DeleteMsg(DN.valueOf("cn=deleted2," + testService), csnGenerator2.newCSN(), "uuid2"));
      waitGenerationId(replServer2, testService, 5555);
      waitGenerationIdOfPeer(replServer1, testService, 92, 5555);
 
      CSN csn1 = new CSNGenerator(1, 0).newCSN();
      broker1.publish(new DeleteMsg(DN.valueOf("cn=deleted1," + testService), csn1, "uuid1"));
      newTimer().repeatUntilSuccess(() -> assertTrue(domain2.getLatestServerState().cover(csn1),
          "RS(92) did not get the update " + csn1 + " of DS(1)"));
    }
    finally
    {
      stop(broker1, broker2);
      remove(replServer1, replServer2);
    }
  }
 
  /** Opens a session of a replica which announces the provided server state rather than an empty one. */
  private ReplicationBroker openReplicationSession(DN baseDN, int serverId, int port, ServerState state,
      long generationId) throws Exception
  {
    final DomainFakeCfg config = newFakeCfg(baseDN, serverId, port);
    config.setWindowSize(100);
    final ReplicationBroker broker = new ReplicationBroker(
        new DummyReplicationDomain(generationId), state, config, getReplSessionSecurity());
    connect(broker, 1000);
    return broker;
  }
 
  /** Returns how many TopologyMsgs the broker receives in the provided time. */
  private static int countTopologyMsgs(ReplicationBroker broker, long millis)
  {
    int count = 0;
    final long end = System.currentTimeMillis() + millis;
    while (System.currentTimeMillis() < end)
    {
      try
      {
        if (broker.receive(false, false, true) instanceof TopologyMsg)
        {
          count++;
        }
      }
      catch (SocketTimeoutException e)
      {
        // nothing came within the timeout of the session
      }
    }
    return count;
  }
 
  /** Waits until a replication server knows a replica of a peer, and the provided generation id of that peer. */
  private void waitReplicaOfPeer(ReplicationServer replServer, DN baseDN, int peerId, long generationId)
      throws Exception
  {
    newTimer().repeatUntilSuccess(() ->
    {
      final ReplicationServerHandler peer =
          replServer.getReplicationServerDomain(baseDN).getConnectedRSs().get(peerId);
      assertTrue(peer.hasRemoteLDAPServers(),
          replServer.getMonitorInstanceName() + " knows a replica of RS(" + peerId + ")");
      assertEquals(peer.getGenerationId(), generationId,
          "generation id " + replServer.getMonitorInstanceName() + " has for RS(" + peerId + ")");
    });
  }
 
  private void waitGenerationId(ReplicationServer replServer, DN baseDN, long generationId) throws Exception
  {
    newTimer().repeatUntilSuccess(() -> assertEquals(
        replServer.getReplicationServerDomain(baseDN).getGenerationId(), generationId,
        "generation id of " + replServer.getMonitorInstanceName()));
  }
 
  private void waitGenerationIdOfPeer(ReplicationServer replServer, DN baseDN, int peerId, long generationId)
      throws Exception
  {
    newTimer().repeatUntilSuccess(() -> assertEquals(
        replServer.getReplicationServerDomain(baseDN).getConnectedRSs().get(peerId).getGenerationId(),
        generationId, "generation id " + replServer.getMonitorInstanceName() + " has for RS(" + peerId + ")"));
  }
 
  /** Returns the TopologyMsg a replication server with no replica sends its peers, with the provided generation id. */
  private static TopologyMsg topologyMsgOf(ReplicationServer replServer, long generationId)
  {
    RSInfo rsInfo = new RSInfo(replServer.getServerId(), replServer.getServerURL(), generationId,
        replServer.getGroupId(), replServer.getWeight());
    return new TopologyMsg(Collections.<DSInfo> emptyList(), newArrayList(rsInfo));
  }
 
  @DataProvider
  public Object[][] errorMsgIDsOfAPeer()
  {
    return new Object[][] {
      // the generation id warning, as replication servers send it since OpenDJ 3.0 and as OpenDJ 2.6 sends it
      { "org.opends.messages.replication-77", true },
      { "14811213", true },
      // another message, in either form
      { "org.opends.messages.replication-78", false },
      { "14811214", false },
    };
  }
 
  /**
   * Of the ErrorMsgs a peer replication server sends to the server id of a replication server, only the
   * generation id warning stays with the replication server, in either form of the id of its message;
   * the replica with that server id gets the others (issue #1207). A replication server of this version
   * sends only the form used since OpenDJ 3.0, so the peer here sends ErrorMsgs decoded from their bytes.
   */
  @Test(dataProvider = "errorMsgIDsOfAPeer")
  public void onlyTheGenerationIdWarningOfAPeerStaysWithTheReplicationServer(String msgID,
      boolean staysWithTheReplicationServer) throws Exception
  {
    DN testService = DN.valueOf("o=test");
    ReplicationServer replServer1 = null;
    ReplicationServer replServer2 = null;
    ReplicationBroker broker11 = null;
 
    try
    {
      int[] ports = TestCaseUtils.findFreePorts(2);
      replServer1 = createReplicationServer(11, ports[0], "errorMsgOfAPeer1", 100);
      replServer2 = createReplicationServer(12, ports[1], "errorMsgOfAPeer2", 100, "localhost:" + ports[0]);
      broker11 = openReplicationSession(testService, 11, 100, ports[0], 1000);
      // a replication server connects to its peers for the domains it has
      replServer2.getReplicationServerDomain(testService, true);
      waitReplicationServerConnected(replServer1, testService, 12);
      waitReplicationServerConnected(replServer2, testService, 11);
      TestCaseUtils.ERROR_TEXT_WRITER.clear();
 
      ServerHandler toReplServer1 = replServer2.getReplicationServerDomain(testService).getConnectedRSs().get(11);
      String details = "error " + msgID;
      toReplServer1.send(errorMsg(12, 11, msgID, details));
      // sent on the same connection after the first one: the replica gets the first one before it, or never
      String lastDetails = "last error";
      toReplServer1.send(errorMsg(12, 11, "org.opends.messages.replication-78", lastDetails));
 
      List<String> received = receiveErrorMsgsUntil(broker11, lastDetails);
      if (staysWithTheReplicationServer)
      {
        assertFalse(received.contains(details), "DS(11) received the generation id warning " + msgID);
        waitErrorMsgReceived(details);
      }
      else
      {
        assertTrue(received.contains(details), "DS(11) did not receive the ErrorMsg " + msgID + ": " + received);
      }
    }
    finally
    {
      stop(broker11);
      remove(replServer1, replServer2);
    }
  }
 
  /**
   * Returns an ErrorMsg that carries the provided id of message, decoded from its bytes as a replication
   * server decodes it: the constructors of ErrorMsg build that id from the details.
   */
  private static ErrorMsg errorMsg(int senderId, int destination, String msgID, String details) throws Exception
  {
    byte[] bytes = new ByteArrayBuilder()
        .appendByte(14) // ReplicationMsg.MSG_TYPE_ERROR
        .appendIntUTF8(senderId)
        .appendIntUTF8(destination)
        .appendString(msgID)
        .appendString(details)
        .appendLongUTF8(System.currentTimeMillis())
        .toByteArray();
    return (ErrorMsg) ReplicationMsg.generateMsg(bytes, ProtocolVersion.getCurrentVersion());
  }
 
  /** Returns the details of the ErrorMsgs the replica receives before the one with the provided details. */
  private List<String> receiveErrorMsgsUntil(ReplicationBroker broker, String lastDetails) throws Exception
  {
    final List<String> received = newArrayList();
    final long deadline = System.currentTimeMillis() + SECONDS.toMillis(30);
    while (System.currentTimeMillis() < deadline)
    {
      final ReplicationMsg msg;
      try
      {
        msg = broker.receive();
      }
      catch (SocketTimeoutException e)
      {
        continue;
      }
      assertNotNull(msg, "DS(" + broker.getServerId() + ") lost its connection");
      if (msg instanceof ErrorMsg)
      {
        final String details = ((ErrorMsg) msg).getDetails().toString();
        if (details.equals(lastDetails))
        {
          return received;
        }
        received.add(details);
      }
    }
    throw new AssertionError("DS(" + broker.getServerId() + ") did not receive the ErrorMsg '" + lastDetails
        + "', only " + received);
  }
 
  private void waitReplicationServerConnected(ReplicationServer replServer, DN baseDN, int peerId) throws Exception
  {
    newTimer().repeatUntilSuccess(() -> assertTrue(
        replServer.getReplicationServerDomain(baseDN, true).getConnectedRSs().containsKey(peerId),
        "RS(" + peerId + ") connected to " + replServer.getMonitorInstanceName()));
  }
 
  /** Waits for the error log record in which a replication server reports the ErrorMsg it kept. */
  private void waitErrorMsgReceived(String details) throws Exception
  {
    final String received = ERR_ERROR_MSG_RECEIVED.get(details).toString();
    newTimer().repeatUntilSuccess(() ->
    {
      final List<String> records = TestCaseUtils.ERROR_TEXT_WRITER.getMessages();
      assertTrue(records.stream().anyMatch(record -> record.contains(received)),
          "no replication server reported the ErrorMsg '" + details + "': " + records);
    });
  }
 
  /**
   * A replication server tells its peers that a replica has left also when the replica has the server
   * id of one of these peers (issue #1207).
   */
  @Test
  public void replicaWithTheIdOfAPeerReplicationServerIsForgottenWhenItLeaves() throws Exception
  {
    DN testService = DN.valueOf("o=test");
    ReplicationServer replServer1 = null;
    ReplicationServer replServer2 = null;
    FakeReplicationDomain domain1 = null;
    FakeReplicationDomain domain11 = null;
 
    try
    {
      int[] ports = TestCaseUtils.findFreePorts(2);
      replServer1 = createReplicationServer(11, ports[0], "replicaWithTheIdOfAPeerLeaves1", 100);
      replServer2 = createReplicationServer(12, ports[1], "replicaWithTheIdOfAPeerLeaves2", 100,
          "localhost:" + ports[0]);
      domain1 = new FakeReplicationDomain(testService, 1, newTreeSet("localhost:" + ports[0]), 0, 1);
      domain11 = new FakeReplicationDomain(testService, 11, newTreeSet("localhost:" + ports[1]), 0, 1);
      waitTopologyKnowsReplica(domain1, 11);
 
      domain11.disableService();
 
      waitTopologyForgetsReplica(domain1, 11);
    }
    finally
    {
      disable(domain1, domain11);
      remove(replServer1, replServer2);
    }
  }
 
  private static TestTimer newTimer()
  {
    return new TestTimer.Builder()
        .maxSleep(30, SECONDS)
        .sleepTimes(100, MILLISECONDS)
        .toTimer();
  }
 
  private void waitConnected(ReplicationDomain domain) throws Exception
  {
    newTimer().repeatUntilSuccess(() -> assertTrue(domain.isConnected(), "DS(" + domain.getServerId() + ") connected"));
  }
 
  private void waitTopologyForgetsReplica(ReplicationDomain domain, int dsId) throws Exception
  {
    newTimer().repeatUntilSuccess(() -> assertFalse(domain.getReplicaInfos().containsKey(dsId),
        "DS(" + dsId + ") has left, and DS(" + domain.getServerId() + ") still knows it"));
  }
 
  private void waitTopologyKnowsReplicationServers(ReplicationDomain domain, int count) throws Exception
  {
    newTimer().repeatUntilSuccess(() -> assertEquals(domain.getRsInfos().size(), count,
        "replication servers known to DS(" + domain.getServerId() + ")"));
  }
 
  private void waitSharedServerIdReported(ReplicationServer replServer, int serverId, DN baseDN) throws Exception
  {
    newTimer().repeatUntilSuccess(() -> assertFalse(sharedServerIdRecords(replServer, serverId, baseDN).isEmpty(),
        replServer.getMonitorInstanceName() + " did not report that DS(" + serverId + ") has the id of an RS"));
  }
 
  /**
   * Waits for the error log record in which a replication server reports the warning a peer sent it
   * because their generation ids differ.
   */
  private void waitGenerationIdWarningOfPeerReceived(DN baseDN, int rsId, long rsGenerationId, int peerId,
      long peerGenerationId) throws Exception
  {
    // the warning names the address the peer sees the replication server at, which is not known here
    final String[] warning = WARN_BAD_GENERATION_ID_FROM_RS.get(
        rsId, "@", rsGenerationId, baseDN, peerId, peerGenerationId).toString().split("@");
    final String received = ERR_ERROR_MSG_RECEIVED.get(warning[0]).toString();
    newTimer().repeatUntilSuccess(() ->
    {
      for (String record : TestCaseUtils.ERROR_TEXT_WRITER.getMessages())
      {
        if (record.contains(received) && record.contains(warning[1]))
        {
          return;
        }
      }
      fail("RS(" + rsId + ") did not receive the warning of RS(" + peerId + "): "
          + TestCaseUtils.ERROR_TEXT_WRITER.getMessages());
    });
  }
 
  private void assertNoErrorMsgReceived(ReplicationBroker broker)
  {
    try
    {
      ReplicationMsg msg;
      while ((msg = broker.receive()) != null)
      {
        assertFalse(msg instanceof ErrorMsg, "DS(" + broker.getServerId() + ") received " + msg);
      }
    }
    catch (SocketTimeoutException expected)
    {
      // nothing more to receive
    }
  }
 
  /** Returns the records of the error log in which the replication server reports the provided replica. */
  private List<String> sharedServerIdRecords(ReplicationServer replServer, int serverId, DN baseDN)
  {
    final String message = WARN_REPLICA_HAS_THE_SERVER_ID_OF_A_REPLICATION_SERVER.get(
        replServer.getMonitorInstanceName(), serverId, baseDN, serverId).toString();
    final List<String> records = newArrayList();
    for (String record : TestCaseUtils.ERROR_TEXT_WRITER.getMessages())
    {
      if (record.contains(message))
      {
        records.add(record);
      }
    }
    return records;
  }
 
  /**
   * When an export requested by a remote replica cannot start (there is no
   * local task reporting the failure), the requester keeps waiting for the
   * InitializeTargetMsg: the exporter must send an ErrorMsg back, otherwise
   * the requester waits forever (issue #841).
   */
  @Test(enabled=true)
  public void remotelyRequestedExportFailureNotifiesRequester() throws Exception
  {
    DN testService = DN.valueOf("o=test");
    ReplicationServer replServer = null;
    FakeReplicationDomain domain1 = null;
    ReplicationBroker broker2 = null;
    Thread firstExport = null;
 
    try
    {
      int replServerPort = TestCaseUtils.findFreePort();
      replServer = createReplicationServer(11, replServerPort,
          "remoteExportFailureNotifiesRequesterDb", 100);
      SortedSet<String> servers = newTreeSet("localhost:" + replServerPort);
 
      String exportedData = buildExportedData(100);
      domain1 = new FakeReplicationDomain(
          testService, 1, servers, 0, exportedData, null, 100);
 
      broker2 = openReplicationSession(testService, 2, 100, replServerPort,
          10000, domain1.getGenerationID());
 
      final FakeReplicationDomain exporter = domain1;
      TestTimer timer = new TestTimer.Builder()
          .maxSleep(30, SECONDS)
          .sleepTimes(100, MILLISECONDS)
          .toTimer();
      timer.repeatUntilSuccess(() -> assertTrue(exporter.getReplicaInfos().containsKey(2),
          "DS(2) is not known to the exporting domain"));
 
      // Occupy the import/export context of the exporter: broker2 never
      // enters the full update status, so this export stays in
      // waitForRemoteStartOfInit until broker2 disconnects in the finally
      firstExport = new Thread(() -> {
        try
        {
          exporter.initializeRemote(2, 2, NO_INIT_TASK, 100);
        }
        catch (DirectoryException expected)
        {
          // broker2 never plays the importer role
        }
      });
      firstExport.start();
      TestTimer ieRunningTimer = new TestTimer.Builder()
          .maxSleep(30, SECONDS)
          .sleepTimes(100, MILLISECONDS)
          .toTimer();
      ieRunningTimer.repeatUntilSuccess(() -> assertTrue(exporter.ieRunning(),
          "the first export did not acquire the import/export context"));
 
      // A second remotely requested export is rejected...
      try
      {
        domain1.initializeRemote(2, 2, NO_INIT_TASK, 100);
        fail("Expected the simultaneous export to be rejected");
      }
      catch (DirectoryException expected)
      {
        assertEquals(expected.getMessageObject().toString(),
            ERR_SIMULTANEOUS_IMPORT_EXPORT_REJECTED.get().toString());
      }
 
      // ...and the requester is notified instead of waiting forever
      final long deadline = System.currentTimeMillis() + 30000;
      while (true)
      {
        ReplicationMsg msg = broker2.receive();
        if (msg instanceof ErrorMsg)
        {
          assertEquals(((ErrorMsg) msg).getDetails().toString(),
              ERR_SIMULTANEOUS_IMPORT_EXPORT_REJECTED.get().toString());
          break;
        }
        assertNotNull(msg, "connection closed while waiting for the ErrorMsg");
        assertFalse(System.currentTimeMillis() > deadline,
            "no ErrorMsg received within 30s, last received " + msg);
      }
    }
    finally
    {
      stop(broker2);
      boolean firstExportStillRunning = false;
      if (firstExport != null)
      {
        // losing broker2 empties the exporter start list and ends the export
        firstExport.join(30000);
        firstExportStillRunning = firstExport.isAlive();
      }
      disable(domain1);
      remove(replServer);
      // asserted only after the cleanup above: failing before it would leak
      // the domain and the replication server port into the following tests
      assertFalse(firstExportStillRunning, "the first export did not terminate");
    }
  }
 
  /**
   * A total update requested by a remote replica that is not (yet) in the
   * exporter's topology view - the request raced the TopologyMsg propagation,
   * the actual issue #841 trigger - must be rejected without leaving the
   * import/export context acquired. The ErrorMsg sent back cannot be asserted
   * here: the replication server does not route messages to a replica it does
   * not know about, and a requester that is connected yet still unknown to
   * the exporter is exactly the race this rejection guards against.
   */
  @Test(enabled=true)
  public void remotelyRequestedExportForUnknownReplicaIsRejected() throws Exception
  {
    DN testService = DN.valueOf("o=test");
    ReplicationServer replServer = null;
    FakeReplicationDomain domain1 = null;
 
    try
    {
      int replServerPort = TestCaseUtils.findFreePort();
      replServer = createReplicationServer(12, replServerPort,
          "remoteExportUnknownReplicaDb", 100);
      SortedSet<String> servers = newTreeSet("localhost:" + replServerPort);
 
      domain1 = new FakeReplicationDomain(
          testService, 1, servers, 0, buildExportedData(10), null, 100);
 
      try
      {
        domain1.initializeRemote(2, 2, NO_INIT_TASK, 100);
        fail("Expected the export requested by an unknown replica to be rejected");
      }
      catch (DirectoryException expected)
      {
        assertEquals(expected.getMessageObject().toString(),
            ERR_FULL_UPDATE_MISSING_REMOTE.get(testService, 1, 2).toString());
      }
      assertFalse(domain1.ieRunning(),
          "the rejected export must not leave the import/export context acquired");
    }
    finally
    {
      disable(domain1);
      remove(replServer);
    }
  }
 
  /** InitializeTask double recording the completion reported by the domain. */
  private static final class RecordingInitializeTask extends InitializeTask
  {
    private final CountDownLatch completed = new CountDownLatch(1);
    private volatile DirectoryException failure;
 
    @Override
    public void updateTaskCompletionState(DirectoryException de)
    {
      failure = de;
      completed.countDown();
    }
 
    DirectoryException waitForCompletion(long timeout, TimeUnit unit) throws InterruptedException
    {
      assertTrue(completed.await(timeout, unit), "the initialize task never completed");
      return failure;
    }
  }
 
  /**
   * An ErrorMsg answering an initialization request can be created within the
   * same millisecond as the requester's import/export context when the whole
   * topology runs on one host: it must terminate the pending initialization
   * instead of being discarded as stale (issue #861).
   */
  @Test(enabled=true)
  public void errorMsgFromSameMillisecondTerminatesPendingInitialize() throws Exception
  {
    DN testService = DN.valueOf("o=test");
    ReplicationServer replServer = null;
    FakeReplicationDomain domain2 = null;
    ReplicationBroker broker3 = null;
 
    try
    {
      int replServerPort = TestCaseUtils.findFreePort();
      replServer = createReplicationServer(13, replServerPort,
          "sameMillisecondErrorMsgDb", 100);
      SortedSet<String> servers = newTreeSet("localhost:" + replServerPort);
 
      domain2 = new FakeReplicationDomain(
          testService, 2, servers, 0, null, new StringBuffer(), 0);
      broker3 = openReplicationSession(testService, 3, 100, replServerPort,
          10000, domain2.getGenerationID());
 
      waitTopologyKnowsReplica(domain2, 3);
 
      RecordingInitializeTask task = new RecordingInitializeTask();
      domain2.initializeFromRemote(3, task);
      long startTime = domain2.getImportExportContext().getStartTime();
 
      // strictly older than the context: still ignored as stale
      ErrorMsg staleError = new ErrorMsg(3, 2, LocalizableMessage.raw("stale error"));
      staleError.setCreationTime(startTime - 1);
      broker3.publish(staleError);
 
      // same millisecond as the context: must terminate the initialization
      ErrorMsg currentError = new ErrorMsg(3, 2, LocalizableMessage.raw("current error"));
      currentError.setCreationTime(startTime);
      broker3.publish(currentError);
 
      DirectoryException failure = task.waitForCompletion(30, TimeUnit.SECONDS);
      assertNotNull(failure, "the initialization completed without an error");
      assertEquals(failure.getMessageObject().toString(), "current error",
          "the ErrorMsg timestamped before the context must stay ignored");
      assertFalse(domain2.ieRunning(),
          "the terminated initialization must release the import/export context");
    }
    finally
    {
      stop(broker3);
      disable(domain2);
      remove(replServer);
    }
  }
 
  /**
   * When the initialization request receives no answer at all - the publish
   * was silently dropped or the answer was lost - the stalled-request watchdog
   * must fail the task after the configured delay instead of letting it wait
   * forever (issue #861).
   */
  @Test(enabled=true)
  public void stalledInitializeFromRemoteIsAborted() throws Exception
  {
    DN testService = DN.valueOf("o=test");
    ReplicationServer replServer = null;
    FakeReplicationDomain domain2 = null;
    ReplicationBroker broker3 = null;
 
    try
    {
      int replServerPort = TestCaseUtils.findFreePort();
      replServer = createReplicationServer(14, replServerPort,
          "stalledInitializeRequestDb", 100);
      SortedSet<String> servers = newTreeSet("localhost:" + replServerPort);
 
      domain2 = new FakeReplicationDomain(
          testService, 2, servers, 0, null, new StringBuffer(), 0);
      // broker3 receives the InitializeRequestMsg and never answers it
      broker3 = openReplicationSession(testService, 3, 100, replServerPort,
          10000, domain2.getGenerationID());
 
      waitTopologyKnowsReplica(domain2, 3);
 
      RecordingInitializeTask task = new RecordingInitializeTask();
      domain2.initializeFromRemote(3, task);
 
      assertFalse(domain2.abortStalledInitializeFromRemote(60000),
          "the initialization must not be aborted before the delay elapses");
 
      final FakeReplicationDomain requester = domain2;
      TestTimer abortTimer = new TestTimer.Builder()
          .maxSleep(30, SECONDS)
          .sleepTimes(10, MILLISECONDS)
          .toTimer();
      abortTimer.repeatUntilSuccess(() -> assertTrue(
          requester.abortStalledInitializeFromRemote(50),
          "the stalled initialization was never aborted"));
 
      DirectoryException failure = task.waitForCompletion(30, TimeUnit.SECONDS);
      assertNotNull(failure, "the stalled initialization must fail the task");
      assertEquals(failure.getMessageObject().toString(),
          ERR_NO_REACHABLE_PEER_IN_THE_DOMAIN.get(testService, 3).toString());
      assertFalse(domain2.ieRunning(),
          "the aborted initialization must release the import/export context");
      assertFalse(domain2.abortStalledInitializeFromRemote(0),
          "a second abort must be a no-op once the context is released");
    }
    finally
    {
      stop(broker3);
      disable(domain2);
      remove(replServer);
    }
  }
 
  private void waitTopologyKnowsReplica(ReplicationDomain domain, int dsId) throws Exception
  {
    TestTimer timer = new TestTimer.Builder()
        .maxSleep(30, SECONDS)
        .sleepTimes(100, MILLISECONDS)
        .toTimer();
    timer.repeatUntilSuccess(() -> assertTrue(domain.getReplicaInfos().containsKey(dsId),
        "DS(" + dsId + ") is not known to the domain"));
  }
 
  private String buildExportedData(final int ENTRYCOUNT)
  {
    final StringBuilder sb = new StringBuilder();
    for (int i = 0; i < ENTRYCOUNT; i++)
    {
      sb.append("key : value").append(i).append("\n\n");
    }
    return sb.toString();
  }
 
  private void waitEndExport(String exportedData, StringBuffer importedData) throws Exception
  {
    int count = 0;
    while (importedData.length() < exportedData.length() && count < 500*5)
    {
      if(count % 100 == 0) { //capture thread dump on start and every 10 seconds
        logger.debug(LocalizableMessage.raw("waitEndExport: thread dump on count=" + count));
        logger.debug(LocalizableMessage.raw(generateThreadDump()));
      }
      count ++;
      Thread.sleep(100);
    }
  }
 
  private void assertExportSucessful(FakeReplicationDomain domain1,
      FakeReplicationDomain domain2, String exportedData, StringBuffer importedData)
  {
    assertEquals(getLeftEntryCount(domain2), 0, "Wrong LeftEntryCount for export");
    assertEquals(getLeftEntryCount(domain1), 0, "Wrong LeftEntryCount for import");
    assertEquals(importedData.length(), exportedData.length());
    assertEquals(importedData.toString(), exportedData);
    /*
     * The direction of the total update, as each side reported it while it was in it.
     * ieRunning() cannot tell the two apart, and something which is guarding the data of a
     * replica has to: the exporter keeps its data and its ServerState - and keeps replaying
     * into them - while the importer is having both replaced.
     */
    assertEquals(domain2.importReportedDuringImport(), Boolean.TRUE,
        "the replica whose data is being replaced must report a total update into itself");
    assertEquals(domain1.importReportedDuringExport(), Boolean.FALSE,
        "the replica which is exporting must not report a total update into itself:"
            + " its data and its ServerState are left alone");
  }
 
  private long getLeftEntryCount(ReplicationDomain domain)
  {
    final ImportExportContext ieContext = domain.getImportExportContext();
    if (ieContext != null)
    {
      return ieContext.getLeftEntryCount();
    }
    return 0; // import/export is finished
  }
 
  /**
   * Sender side of the Total Update Perf test.
   * The goal of this test is to measure the performance
   * of the total update code.
   * It is not intended to be run as part of the daily unit test but
   * should only be used manually by developer in need of testing the
   * performance improvement or non-regression of the total update code.
   * Use this test in combination with the receiverInitialize() :
   *   - enable the test
   *   - start the senderInitialize first using
   *     ./build.sh \
   *        -Dorg.opends.test.suppressOutput=false \
   *        -Dtest.methods=org.opends.server.replication.service.ReplicationDomainTest.senderInitialize test
   *   - start the receiverInitialize second.
   *   - you may want to change  HOST1 and HOST2 to use 2 different hosts
   *     if you don't want to do a loopback test.
   *   - don't forget to disable again the tests after running them
   */
  final String HOST1 = "localhost:";
  final String HOST2 = "localhost:";
  final int SENDERPORT = 10102;
  final int RECEIVERPORT = 10101;
 
  @Test(enabled=false)
  public void senderInitialize() throws Exception
  {
    DN testService = DN.valueOf("o=test");
    ReplicationServer replServer = null;
    int replServerID = 12;
    FakeStressReplicationDomain domain1 = null;
 
    try
    {
      SortedSet<String> servers =
          newTreeSet(HOST1 + SENDERPORT, HOST2 + RECEIVERPORT);
 
      replServer = createReplicationServer(replServerID, SENDERPORT,
          "ReplicationDomainTestDb", 100, servers);
 
      BlockingQueue<UpdateMsg> rcvQueue1 = new LinkedBlockingQueue<>();
      domain1 = new FakeStressReplicationDomain(
          testService, 2, servers, 1000, rcvQueue1);
 
      System.out.println("waiting");
      Thread.sleep(1000000000);
    }
    finally
    {
      disable(domain1);
      remove(replServer);
    }
  }
 
  /**
   * See comments in senderInitialize() above.
   */
  @Test(enabled=false)
  public void receiverInitialize() throws Exception
  {
    DN testService = DN.valueOf("o=test");
    ReplicationServer replServer = null;
    int replServerID = 11;
    FakeStressReplicationDomain domain1 = null;
 
    try
    {
      SortedSet<String> servers =
          newTreeSet(HOST1 + SENDERPORT, HOST2 + RECEIVERPORT);
 
      replServer = createReplicationServer(replServerID, RECEIVERPORT,
          "ReplicationDomainTestDb", 100, servers);
 
      BlockingQueue<UpdateMsg> rcvQueue1 = new LinkedBlockingQueue<>();
      domain1 = new FakeStressReplicationDomain(
          testService, 1, servers, 100000, rcvQueue1);
      /*
       * Trigger a total update from domain1 to domain2.
       * Check that the exported data is correctly received on domain2.
       */
      while (!initializeFromRemote(domain1))
      {
        System.out.println("trying...");
        Thread.sleep(1000);
      }
      System.out.println("waiting");
      Thread.sleep(10000000);
    }
    finally
    {
      disable(domain1);
      remove(replServer);
    }
  }
 
}