/*
* 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 2026 3A Systems, LLC.
*/
package org.opends.server.replication.server;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.opends.messages.ReplicationMessages.WARN_IGNORING_UPDATE_UNSUPPORTED_BY_PEER;
import static org.opends.server.TestCaseUtils.TEST_ROOT_DN_STRING;
import static org.opends.server.util.CollectionUtils.newArrayList;
import static org.mockito.Mockito.*;
import static org.mockito.AdditionalAnswers.delegatesTo;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantLock;
import org.forgerock.opendj.ldap.DN;
import org.forgerock.opendj.ldap.ModificationType;
import org.opends.server.TestCaseUtils;
import org.opends.server.core.DirectoryServer;
import org.opends.server.replication.ReplicationTestCase;
import org.opends.server.replication.common.CSN;
import org.opends.server.replication.common.DSInfo;
import org.opends.server.replication.common.AssuredMode;
import org.opends.server.replication.common.ServerStatus;
import org.opends.server.replication.common.CSNGenerator;
import org.opends.server.replication.common.RSInfo;
import org.opends.server.replication.common.ServerState;
import org.opends.server.replication.plugin.DummyReplicationDomain;
import org.opends.server.replication.protocol.DeleteMsg;
import org.opends.server.replication.protocol.ModifyMsg;
import org.opends.server.replication.protocol.ProtocolVersion;
import org.opends.server.replication.protocol.ReplServerStartMsg;
import org.opends.server.replication.protocol.ReplSessionSecurity;
import org.opends.server.replication.protocol.ReplicaOfflineMsg;
import org.opends.server.replication.protocol.ReplicationMsg;
import org.opends.server.replication.protocol.Session;
import org.opends.server.replication.protocol.StopMsg;
import org.opends.server.replication.protocol.TopologyMsg;
import org.opends.server.replication.protocol.WindowMsg;
import org.opends.server.replication.protocol.UpdateMsg;
import org.opends.server.replication.server.changelog.api.ChangelogException;
import org.opends.server.replication.server.changelog.api.ReplicationDomainDB;
import org.opends.server.replication.service.DSRSShutdownSync;
import org.opends.server.replication.service.DSRSShutdownSync.ForwardingPeer;
import org.opends.server.replication.service.ReplicationBroker;
import org.opends.server.types.Attributes;
import org.opends.server.types.Modification;
import org.opends.server.util.StaticUtils;
import org.opends.server.util.TestTimer;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
* The shutdown of a replication server must let a ReplicaOfflineMsg sent by a collocated
* directory server be forwarded to the other replication servers of the topology before the
* server handlers are stopped - stopping them deactivates their consumer, clears their message
* queue and closes their session, after which the message can no longer be sent.
*
* Most tests drive {@link DSRSShutdownSync} directly rather than through a collocated directory
* server: the contract they pin is when the shutdown of the replication server waits, and how
* long. {@link #thePeerReceivesTheReplicaOfflineMsgBeforeTheShutdownReturns()},
* {@link #thePeerWhoseHandshakeIsInFlightIsStillToldTheReplicaWentOffline()} and
* {@link #theShutdownWaitsForEveryPeerToBeToldTheReplicaWentOffline()} pin the outcome those
* waits exist for, on peers connected through the real handshake, and
* {@link #thePeerWhoseHandshakeCompletesAfterTheShutdownIsStoppedNotServed()} pins what the
* shutdown still does to a handshake which outlasts the wait.
*/
@SuppressWarnings("javadoc")
public class ReplicationServerShutdownSyncTest extends ReplicationTestCase
{
private static final int SOCKET_TIMEOUT_MS = 30000;
/** A session end nobody owns is discarded, so its cleanup waits far less than a live one. */
private static final int DISCARDED_SESSION_TIMEOUT_MS = 2000;
private static final int REMOTE_RS_ID = 92;
private static final int REMOTE_DS_ID = 93;
/** The collocated replica whose ReplicaOfflineMsg the shutdown waits for. */
private static final int LOCAL_DS_ID = 94;
/** The peer replication server whose writer is held back by a full send window. */
private static final int HELD_BACK_RS_ID = 95;
/** The peer replication server whose handshake is aborted while the message is pushed. */
private static final int ABORTED_RS_ID = 96;
/** The peer replication server whose handshake is still in flight when the shutdown starts. */
private static final int HANDSHAKING_RS_ID = 97;
/**
* A replica which announces itself offline and whose message nobody can forward: it never
* published one, so the shutdown spends its whole grace period waiting for it.
*/
private static final int UNREACHABLE_DS_ID = 98;
/** The peer replication server which speaks a protocol version with no ReplicaOfflineMsg. */
private static final int OLD_PEER_RS_ID = 99;
/**
* Base of the id of the replication server serving a peer of a chosen protocol version: the
* version is added to it, so that the two rows of
* {@link #onlyAPeerWhichCanDecodeTheMessageIsToldTheReplicaWentOffline(short, boolean)} do not
* share a server id.
*/
private static final int PEER_VERSION_RS_ID = 8240;
/** The peer replication server whose session thread is busy writing an earlier change. */
private static final int BUSY_RS_ID = 100;
/** The peer replication server whose protocol version predates the ReplicaOfflineMsg. */
private static final int LEGACY_RS_ID = 101;
/** Send window a peer advertises when nothing has to hold its writer back. */
private static final int PEER_WINDOW = 100;
/**
* Socket buffers of the connection to the peer which does not read: small enough that
* {@link #SOCKET_FILLING_CHANGE_SIZE} bytes cannot be written through them, so that the session
* thread writing that change is held inside the write until the peer reads. Set on both ends,
* since the buffers the kernel picks on its own grow well beyond it on a loopback link.
*/
private static final int SMALL_SOCKET_BUFFER_SIZE = 8 * 1024;
/**
* Larger by far than what the socket buffers hold: a kernel which does not honour the size
* asked for on the receiving side - macOS keeps a few hundred kilobytes there - must still
* be unable to take the whole change.
*/
private static final int SOCKET_FILLING_CHANGE_SIZE = 4 * 1024 * 1024;
/**
* What the peer which does not read must have been sent, and not read, for the session thread
* serving it to be inside a write: well below its receive buffer, since the kernel advertises
* less than the whole of it, and well above any of the small messages a replication server
* sends a peer on its own.
*/
private static final int SOCKET_BUFFER_FILL_MARK = SMALL_SOCKET_BUFFER_SIZE / 4;
/**
* Time a shutdown released by the ReplicaOfflineMsg being queued, rather than written, is given
* to close the session of the peer. A shutdown which waits for the write cannot close the
* session before the peer reads, so it spends this time and no more.
*/
private static final long EARLY_CLOSE_TIMEOUT_MS = 1000;
/**
* Send window of the peer which is held back: one change fills it, and the message which
* follows stays with its writer until the peer gives it credit again.
*/
private static final int HELD_BACK_PEER_WINDOW = 1;
/** Time given to the forwarding thread before it releases the shutdown. */
private static final long FORWARD_DELAY = 500;
/**
* Time given to a writer to reach the message it was handed once its send window is opened,
* well short of the grace period so that a writer which never gets there is reported as such
* rather than as a shutdown which waited.
*/
private static final long WRITER_REACTION_TIMEOUT_MS = 10000;
/** How often the domains of {@link #theGracePeriodIsSharedByAllTheDomainsOfOneShutdown()}
* announce themselves offline again while the shutdown is waiting for them. */
private static final long REANNOUNCE_INTERVAL = 200;
/** A departing RS reader may already be waiting to apply its last topology message. */
@Test
public void stoppingPeerDoesNotHoldDomainLockWhileJoiningReader() throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
ReplicationServer server = null;
FakePeerReplicationServer peer = null;
ReplicationBroker broker = null;
final ExecutorService stopping = Executors.newSingleThreadExecutor();
final AtomicReference stoppingThread = new AtomicReference<>();
try
{
final int port = TestCaseUtils.findFreePort();
final ReplServerFakeConfiguration config = new ReplServerFakeConfiguration(
port, "shutdownDomainLockDb", 0, 8258, 0, 100, new TreeSet());
// This peer exercises topology messages, not the unrelated five-second
// wait for replies to monitor requests.
config.setMonitoringPeriod(0);
server = new ReplicationServer(config, new DSRSShutdownSync());
peer = FakePeerReplicationServer.connected(port, REMOTE_RS_ID, baseDN, EMPTY_DN_GENID);
final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, true);
waitForConnectedReplicationServer(domain, REMOTE_RS_ID);
final ReplicationServerHandler handler = domain.getConnectedRSs().get(REMOTE_RS_ID);
final Field lockField = ReplicationServerDomain.class.getDeclaredField("lock");
lockField.setAccessible(true);
final ReentrantLock domainLock = (ReentrantLock) lockField.get(domain);
final Field readerField = ServerHandler.class.getDeclaredField("reader");
readerField.setAccessible(true);
final Thread reader = (Thread) readerField.get(handler);
final Future> stopped;
domain.lock();
try
{
// Queue teardown first, then the real reader of a real peer session. Once
// released, teardown must let that reader finish before joining it.
stopped = stopping.submit(() -> {
stoppingThread.set(Thread.currentThread());
domain.stopServer(handler, false);
});
newConnectionTimer().repeatUntilSuccess(() -> {
assertThat(stoppingThread.get()).isNotNull();
assertThat(domainLock.hasQueuedThread(stoppingThread.get())).isTrue();
});
peer.session.publish(new TopologyMsg(null,
newArrayList(new RSInfo(REMOTE_RS_ID, peer.serverURL, EMPTY_DN_GENID, (byte) 1, 1))));
newConnectionTimer().repeatUntilSuccess(() -> {
assertThat(domainLock.hasQueuedThread(reader)).as("peer reader waiting for domain lock").isTrue();
});
}
finally
{
domain.release();
}
stopped.get(2000, TimeUnit.MILLISECONDS);
assertThat(reader.isAlive()).as("departing peer reader has stopped").isFalse();
broker = openReplicationSession(baseDN, REMOTE_DS_ID, 100, port, 5000, EMPTY_DN_GENID);
waitForConnectedDirectoryServer(domain);
}
finally
{
// Interrupt a failing teardown test before cleanup: it may be in the old
// 30-second join while its reader waits for the lock it still owns.
stopping.shutdownNow();
stopping.awaitTermination(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS);
if (broker != null)
{
broker.stop();
}
closeQuietly(peer);
removeQuietly(server);
}
}
/** Both directory and replication sessions can spend time draining accepted messages. */
@DataProvider
public Object[][] closingHandlerRoles()
{
return new Object[][] { { false }, { true } };
}
/** A slow close must not prevent another DS from completing a real failover handshake. */
@Test(dataProvider = "closingHandlerRoles")
public void stoppingHandlerDoesNotHoldDomainLockWhileClosingSession(boolean replicationPeer)
throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
final CountDownLatch closing = new CountDownLatch(1);
final CountDownLatch releaseClose = new CountDownLatch(1);
final ExecutorService stopping = Executors.newFixedThreadPool(2);
ReplicationServer server = null;
ReplicationBroker keeper = null;
ReplicationBroker reconnecting = null;
Future> stopped = null;
try (ServerSocket listen = TestCaseUtils.bindFreePort())
{
final int port = TestCaseUtils.findFreePort();
final ReplServerFakeConfiguration config = new ReplServerFakeConfiguration(
port, "closingHandlerHandshakeDb" + replicationPeer, 0, 8269, 0, 100, new TreeSet());
config.setMonitoringPeriod(0);
server = new ReplicationServer(config, new DSRSShutdownSync());
keeper = openReplicationSession(baseDN, LOCAL_DS_ID, 100, port, 5000, EMPTY_DN_GENID);
final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, true);
final Session[] pair = connectSessionPair(listen, getReplSessionSecurity());
try (Session remote = pair[0]; Session local = pair[1])
{
final ServerHandler old;
if (replicationPeer)
{
old = registerConnectedReplicationServer(server, baseDN, local);
}
else
{
final DataServerHandler ds = new DataServerHandler(local, 100, server, 100);
ds.serverId = UNREACHABLE_DS_ID;
ds.serverURL = "127.0.0.1:1636";
ds.setBaseDNAndDomain(baseDN, true);
ds.setInitialServerState(new ServerState());
ds.setGenerationId(EMPTY_DN_GENID);
domain.lock();
try
{
domain.register(ds);
}
finally
{
domain.release();
}
old = ds;
}
DirectoryServer.registerMonitorProvider(old);
// Delay only the socket write during close. The real Session still drains
// and sends StopMsg; the new broker performs its real network handshake.
final Field outputField = Session.class.getDeclaredField("output");
outputField.setAccessible(true);
final BufferedOutputStream output = (BufferedOutputStream) outputField.get(local);
outputField.set(local, new BufferedOutputStream(output) {
@Override
public synchronized void flush() throws IOException
{
if (local.closeInitiated())
{
closing.countDown();
try
{
if (!releaseClose.await(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS))
{
throw new IOException("Test did not release the session close");
}
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
throw new IOException(e);
}
}
super.flush();
}
});
stopped = stopping.submit(() -> domain.stopServer(old, false));
assertThat(closing.await(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isTrue();
assertThat(stopped.isDone()).as("the old session is still draining").isFalse();
reconnecting = new ReplicationBroker(new DummyReplicationDomain(EMPTY_DN_GENID),
new ServerState(), newFakeCfg(baseDN, REMOTE_DS_ID, port), getReplSessionSecurity());
final ReplicationBroker newBroker = reconnecting;
stopping.submit(() -> newBroker.start()).get(10, TimeUnit.SECONDS);
assertThat(reconnecting.isConnected())
.as("a live RS must accept failover while another peer's session is closing").isTrue();
assertThat(stopped.isDone()).as("the new handshake did not wait for the old close").isFalse();
assertThat(DirectoryServer.getMonitorProviders()).doesNotContainValue(old);
releaseClose.countDown();
stopped.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS);
assertThat(domain.getConnectedDSs()).containsKey(REMOTE_DS_ID);
}
finally
{
releaseClose.countDown();
}
}
finally
{
releaseClose.countDown();
awaitQuietly(stopped);
if (reconnecting != null)
{
reconnecting.stop();
}
if (keeper != null)
{
keeper.stop();
}
removeQuietly(server);
stopping.shutdownNow();
stopping.awaitTermination(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS);
}
}
/** A replacement can connect while the old reader finishes, but must keep its monitors. */
@Test
public void stoppingPeerKeepsReplacementMonitors() throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
final CountDownLatch releaseReader = new CountDownLatch(1);
final ExecutorService stopping = Executors.newSingleThreadExecutor();
ReplicationServer server = null;
Thread reader = null;
try (ServerSocket listen = new ServerSocket(0))
{
final ReplServerFakeConfiguration config = new ReplServerFakeConfiguration(
TestCaseUtils.findFreePort(), "replacementMonitorsDb", 0, 8260, 0, 100, new TreeSet());
config.setMonitoringPeriod(0);
server = new ReplicationServer(config, new DSRSShutdownSync());
final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, true);
final Session[] oldPair = connectSessionPair(listen, getReplSessionSecurity());
final Session[] newPair = connectSessionPair(listen, getReplSessionSecurity());
try (Session oldRemote = oldPair[0]; Session oldLocal = oldPair[1];
Session newRemote = newPair[0]; Session newLocal = newPair[1])
{
final ReplicationServerHandler old = registerConnectedReplicationServer(server, baseDN, oldLocal);
DirectoryServer.registerMonitorProvider(old);
final DSInfo replica = new DSInfo(REMOTE_DS_ID, "localhost:1389", REMOTE_RS_ID, EMPTY_DN_GENID,
ServerStatus.NORMAL_STATUS, false, AssuredMode.SAFE_READ_MODE, (byte) 1, (byte) 1,
Collections.emptyList(), Collections.emptyList(), Collections.emptyList(),
ProtocolVersion.getCurrentVersion());
final TopologyMsg topology = new TopologyMsg(newArrayList(replica),
newArrayList(new RSInfo(REMOTE_RS_ID, old.serverURL, EMPTY_DN_GENID, (byte) 1, 1)));
domain.receiveTopoInfoFromRS(topology, old, false);
final String replicaMonitorName = StaticUtils.toLowerCase("Connected directory server DS("
+ REMOTE_DS_ID + ") localhost:1389,cn=" + old.getMonitorInstanceName());
final Object oldReplicaMonitor = DirectoryServer.getMonitorProviders().get(replicaMonitorName);
assertThat(oldReplicaMonitor).isInstanceOf(LightweightServerHandler.class);
// Model a reader finishing accepted work after its session has closed.
// Its join must allow the replacement handshake, but cleanup by monitor
// name must finish before that replacement can register its providers.
reader = new ServerReader(oldLocal, old) {
@Override
public void run()
{
try
{
releaseReader.await(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS);
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
}
};
final Field readerField = ServerHandler.class.getDeclaredField("reader");
readerField.setAccessible(true);
readerField.set(old, reader);
reader.start();
final Future> stopped = stopping.submit(() -> domain.stopServer(old, false));
newConnectionTimer().repeatUntilSuccess(() -> {
assertThat(domain.getConnectedRSs()).doesNotContainKey(REMOTE_RS_ID);
assertThat(DirectoryServer.getMonitorProviders()).doesNotContainValue(old);
});
final ReplicationServerHandler replacement =
registerConnectedReplicationServer(server, baseDN, newLocal);
DirectoryServer.registerMonitorProvider(replacement);
domain.receiveTopoInfoFromRS(topology, replacement, false);
final Object replacementReplicaMonitor = DirectoryServer.getMonitorProviders().get(replicaMonitorName);
assertThat(replacementReplicaMonitor).isInstanceOf(LightweightServerHandler.class)
.isNotSameAs(oldReplicaMonitor);
releaseReader.countDown();
stopped.get(WRITER_REACTION_TIMEOUT_MS, TimeUnit.MILLISECONDS);
assertThat(DirectoryServer.getMonitorProviders()).containsValue(replacement);
assertThat(DirectoryServer.getMonitorProviders().get(replicaMonitorName))
.as("old teardown must not remove the replacement's replica monitor")
.isSameAs(replacementReplicaMonitor);
}
finally
{
releaseReader.countDown();
}
}
finally
{
releaseReader.countDown();
stopping.shutdownNow();
stopping.awaitTermination(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS);
if (reader != null)
{
reader.join(SOCKET_TIMEOUT_MS);
}
removeQuietly(server);
}
}
@DataProvider
public Object[][] disconnectedPeerReplacements()
{
return new Object[][] { { false }, { true } };
}
/** A late topology message of a removed session must not resurrect its generation. */
@Test(dataProvider = "disconnectedPeerReplacements")
public void disconnectedPeerCannotChangeGeneration(boolean replacementConnected) throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
ReplicationServer server = null;
ReplicationServerHandler old = null;
try (ServerSocket listen = TestCaseUtils.bindFreePort())
{
server = newReplicationServer(new DSRSShutdownSync(), "disconnectedPeerGenerationDb", 8259);
final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, true);
final Session[] oldPair = connectSessionPair(listen, getReplSessionSecurity());
final Session[] newPair = connectSessionPair(listen, getReplSessionSecurity());
try (Session oldRemote = oldPair[0]; Session oldLocal = oldPair[1];
Session newRemote = newPair[0]; Session newLocal = newPair[1])
{
old = registerConnectedReplicationServer(server, baseDN, oldLocal);
domain.stopServer(old, false);
if (replacementConnected)
{
registerConnectedReplicationServer(server, baseDN, newLocal);
}
final DSInfo replica = new DSInfo(REMOTE_DS_ID, "localhost:1389", REMOTE_RS_ID, 123456,
ServerStatus.NORMAL_STATUS, false, AssuredMode.SAFE_READ_MODE, (byte) 1, (byte) 1,
Collections.emptyList(), Collections.emptyList(), Collections.emptyList(),
ProtocolVersion.getCurrentVersion());
domain.receiveTopoInfoFromRS(new TopologyMsg(newArrayList(replica),
newArrayList(new RSInfo(REMOTE_RS_ID, "localhost:1636", 123456, (byte) 1, 1))), old, true);
assertThat(domain.getGenerationId()).as("removed peer cannot supply a generation id").isEqualTo(-1);
}
}
finally
{
if (old != null)
{
old.shutdown(); // Also clears remote-replica monitors created by a failing implementation.
}
removeQuietly(server);
}
}
@Test
public void stoppingPeerCannotCancelOfflineForwardForItsReplacement() throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
final RecordingShutdownSync shutdownSync = new RecordingShutdownSync();
final CountDownLatch releaseOld = new CountDownLatch(1);
final CountDownLatch oldIsClosing = new CountDownLatch(1);
final ExecutorService stopping = Executors.newSingleThreadExecutor();
ReplicationServer server = null;
ReplicationBroker broker = null;
FakePeerReplicationServer replacement = null;
try (ServerSocket listen = TestCaseUtils.bindFreePort())
{
final int port = TestCaseUtils.findFreePort();
server = newReplicationServer(shutdownSync, "offlineForwardReplacementDb", 8261, port);
broker = openReplicationSession(baseDN, LOCAL_DS_ID, 100, port, 5000, EMPTY_DN_GENID);
final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, true);
final Session[] oldPair = connectSessionPair(listen, getReplSessionSecurity());
try (Session oldRemote = oldPair[0]; Session oldLocal = oldPair[1])
{
final ReplicationServerHandler old = new ReplicationServerHandler(oldLocal, 100, server, 100)
{
@Override
void awaitShutdown()
{
oldIsClosing.countDown();
try
{
assertThat(releaseOld.await(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isTrue();
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
super.awaitShutdown();
}
};
registerConnectedReplicationServer(domain, baseDN, old, REMOTE_RS_ID);
final Future> stopped = stopping.submit(() -> domain.stopServer(old, false));
try
{
assertThat(oldIsClosing.await(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isTrue();
replacement = FakePeerReplicationServer.connected(
port, REMOTE_RS_ID, baseDN, EMPTY_DN_GENID, HELD_BACK_PEER_WINDOW);
waitForConnectedReplicationServer(domain, REMOTE_RS_ID);
final CSNGenerator csns = new CSNGenerator(LOCAL_DS_ID, 0);
final Future windowFiller = replacement.receive(DeleteMsg.class);
broker.publish(new DeleteMsg(DN.valueOf("uid=offline," + baseDN),
csns.newCSN(), "offline-entry-uuid"));
assertThat(windowFiller.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isNotNull();
final CSN offlineCSN = csns.newCSN();
shutdownSync.replicaOfflineMsgSent(baseDN, offlineCSN);
broker.publish(new ReplicaOfflineMsg(offlineCSN));
shutdownSync.awaitDispatch();
assertThat(shutdownSync.dispatchedTo()).containsExactly(REMOTE_RS_ID);
assertThat(shutdownSync.canShutdown(baseDN)).isFalse();
releaseOld.countDown();
stopped.get(WRITER_REACTION_TIMEOUT_MS, TimeUnit.MILLISECONDS);
assertThat(shutdownSync.canShutdown(baseDN))
.as("the old session cannot cancel the new session's forward").isFalse();
final Future received = replacement.receive(ReplicaOfflineMsg.class);
replacement.openSendWindow(1);
final ReplicaOfflineMsg forwarded = received.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS);
assertThat(forwarded).isNotNull();
assertThat(forwarded.getCSN()).isEqualTo(offlineCSN);
newConnectionTimer().repeatUntilSuccess(() -> {
assertThat(shutdownSync.forwardedBy()).contains(REMOTE_RS_ID);
assertThat(shutdownSync.canShutdown(baseDN)).isTrue();
});
}
finally
{
releaseOld.countDown();
}
}
}
finally
{
closeQuietly(replacement);
stop(broker);
stopping.shutdownNow();
stopping.awaitTermination(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS);
removeQuietly(server);
}
}
/** A remote DS can still write when its RS starts shutting down: no offline message
* announces those last changes. Every peer must receive them before its session closes. */
@Test
public void shutdownForwardsRemoteDirectoryUpdatesToEveryPeer() throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
ReplicationServer server = null;
ReplicationBroker broker = null;
FakePeerReplicationServer fast = null;
FakePeerReplicationServer slow = null;
final ExecutorService shutdown = Executors.newSingleThreadExecutor();
try
{
final int port = TestCaseUtils.findFreePort();
server = newReplicationServer(new DSRSShutdownSync(), "shutdownRemoteUpdatesDb", 8250, port);
broker = openReplicationSession(baseDN, REMOTE_DS_ID, 100, port, 5000, EMPTY_DN_GENID);
fast = FakePeerReplicationServer.connected(port, REMOTE_RS_ID, baseDN, EMPTY_DN_GENID);
slow = FakePeerReplicationServer.connected(port, HELD_BACK_RS_ID, baseDN, EMPTY_DN_GENID, 1);
final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, true);
waitForConnectedReplicationServer(domain, REMOTE_RS_ID);
waitForConnectedReplicationServer(domain, HELD_BACK_RS_ID);
final Future> fastMessages = fast.receiveUntil(StopMsg.class);
final Future> slowMessages = slow.receiveUntil(StopMsg.class);
final List expected = new ArrayList<>();
final long time = System.currentTimeMillis();
for (int i = 1; i <= 4; i++)
{
final CSN csn = new CSN(time, i, REMOTE_DS_ID);
expected.add(csn);
broker.publish(new DeleteMsg(DN.valueOf("uid=last-" + i + "," + baseDN), csn,
"22222222-2222-2222-2222-222222222222"));
}
newConnectionTimer().repeatUntilSuccess(() -> {
assertThat(domain.getLatestServerState().getCSN(REMOTE_DS_ID)).isEqualTo(expected.get(3));
});
final ReplicationServer stopping = server;
final Future> stopped = shutdown.submit(() -> stopping.shutdown());
// Keep the slow peer's window closed until all DS readers have been stopped.
newConnectionTimer().repeatUntilSuccess(() -> { assertThat(domain.getConnectedDSs()).isEmpty(); });
slow.openSendWindow(10);
stopped.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS);
for (Future> messages : Arrays.asList(fastMessages, slowMessages))
{
final List actual = new ArrayList<>();
for (ReplicationMsg msg : messages.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS))
{
if (msg instanceof DeleteMsg)
{
actual.add(((DeleteMsg) msg).getCSN());
}
}
assertThat(actual).as("updates received by a peer before the RS stopped").containsExactlyElementsOf(expected);
}
}
finally
{
closeQuietly(fast);
closeQuietly(slow);
if (broker != null)
{
broker.stop();
}
removeQuietly(server);
shutdown.shutdownNow();
}
}
/**
* A DS can move to the peer while older changes still wait for send-window credit.
* The newer change coming back from that peer proves nothing about those older
* records: advancing the outgoing cursor would skip them and strand shutdown.
*/
@DataProvider
public Object[][] migrationHistorySources()
{
return new Object[][] { { false }, { true } };
}
@Test(dataProvider = "migrationHistorySources")
public void incomingPeerUpdateDoesNotSkipDirectoryHistory(boolean retainedHistory) throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
ReplicationServer server = null;
ReplicationBroker broker = null;
FakePeerReplicationServer peer = null;
try
{
final int port = TestCaseUtils.findFreePort();
server = newReplicationServer(new DSRSShutdownSync(), "shutdownMigratedUpdatesDb", 8253, port);
broker = openReplicationSession(baseDN, REMOTE_DS_ID, 100, port, 5000, EMPTY_DN_GENID);
final List expected = new ArrayList<>();
final long time = System.currentTimeMillis();
for (int i = 1; i <= 3; i++)
{
final CSN csn = new CSN(time, i, REMOTE_DS_ID);
expected.add(csn);
}
if (retainedHistory)
{
publishBeforeMigration(broker, baseDN, expected);
}
final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, true);
if (retainedHistory)
{
newConnectionTimer().repeatUntilSuccess(() -> {
assertThat(domain.getLatestServerState().getCSN(REMOTE_DS_ID)).isEqualTo(expected.get(2));
});
}
peer = FakePeerReplicationServer.connected(port, REMOTE_RS_ID, baseDN, EMPTY_DN_GENID, 1);
waitForConnectedReplicationServer(domain, REMOTE_RS_ID);
if (!retainedHistory)
{
waitForFollowing(domain, REMOTE_RS_ID);
publishBeforeMigration(broker, baseDN, expected);
}
final ReplicationServerHandler handler = domain.getConnectedRSs().get(REMOTE_RS_ID);
final Future> received = peer.receiveUntil(StopMsg.class);
newConnectionTimer().repeatUntilSuccess(() -> {
assertThat(domain.getLatestServerState().getCSN(REMOTE_DS_ID)).isEqualTo(expected.get(2));
assertThat(handler.getServerState().getCSN(REMOTE_DS_ID)).isEqualTo(expected.get(1));
});
// Change 2 is dequeued but blocked; change 3 is still in the outgoing queue.
final CSN migrated = new CSN(time, 4, REMOTE_DS_ID);
peer.session.publish(new DeleteMsg(DN.valueOf("uid=after-migration," + baseDN), migrated,
"22222222-2222-2222-2222-222222222222"));
newConnectionTimer().repeatUntilSuccess(() -> {
assertThat(domain.getLatestServerState().getCSN(REMOTE_DS_ID)).isEqualTo(migrated);
assertThat(handler.getServerState().getCSN(REMOTE_DS_ID)).isEqualTo(migrated);
});
final ServerState outstanding = new ServerState();
outstanding.update(expected.get(2));
assertThat(handler.awaitPublished(outstanding, System.nanoTime()))
.as("a newer incoming CSN does not confirm delivery of an older outgoing record")
.isFalse();
peer.openSendWindow(10);
final List records = errorLogRecordsOf(() -> {
domain.awaitDirectUpdatesForwarded(System.nanoTime() + TimeUnit.SECONDS.toNanos(2));
return null;
});
assertThat(records.stream().anyMatch(line -> line.contains("RS shutdown could not forward")))
.as("the incoming update must not strand the earlier direct updates")
.isFalse();
server.shutdown();
final List actual = new ArrayList<>();
for (ReplicationMsg msg : received.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS))
{
if (msg instanceof DeleteMsg)
{
actual.add(((DeleteMsg) msg).getCSN());
}
}
// Crediting the incoming maximum to publishedState would hide the warning,
// but still lose change 3. Verify the actual stream, not just the drain result.
assertThat(actual).containsExactlyElementsOf(expected);
}
finally
{
closeQuietly(peer);
if (broker != null)
{
broker.stop();
}
removeQuietly(server);
}
}
@DataProvider
public Object[][] directWriteOrigins()
{
return new Object[][] { { true, false }, { false, false }, { true, true } };
}
/** A new direct write must not overtake history of its replica received through another RS. */
@Test(dataProvider = "directWriteOrigins")
public void directWriteAfterPeerHistoryPreservesTheOutgoingPrefix(boolean sameOrigin, boolean newerPeerUpdate) throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
ReplicationServer server = null;
ReplicationBroker broker = null;
FakePeerReplicationServer source = null;
FakePeerReplicationServer target = null;
try
{
final int port = TestCaseUtils.findFreePort();
server = newReplicationServer(new DSRSShutdownSync(), "peerHistoryPrefixDb", 8254, port);
broker = openReplicationSession(baseDN, REMOTE_DS_ID, 100, port, 5000, EMPTY_DN_GENID);
source = FakePeerReplicationServer.connected(port, REMOTE_RS_ID, baseDN, EMPTY_DN_GENID);
target = FakePeerReplicationServer.connected(port, HELD_BACK_RS_ID, baseDN, EMPTY_DN_GENID);
final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, true);
waitForConnectedReplicationServer(domain, REMOTE_RS_ID);
waitForConnectedReplicationServer(domain, HELD_BACK_RS_ID);
final Future> received = target.receiveUntil(StopMsg.class);
source.receiveUntil(StopMsg.class);
final List expected = new ArrayList<>();
final long time = System.currentTimeMillis();
for (int i = 1; i <= 4; i++)
{
expected.add(new CSN(time, i, i == 4 && !sameOrigin ? REMOTE_DS_ID + 1 : REMOTE_DS_ID));
}
publishBeforeMigration(broker, baseDN, expected.subList(0, 1));
final ReplicationServerHandler targetHandler = domain.getConnectedRSs().get(HELD_BACK_RS_ID);
newConnectionTimer().repeatUntilSuccess(() -> {
assertThat(targetHandler.getServerState().getCSN(REMOTE_DS_ID)).isEqualTo(expected.get(0));
});
waitForFollowing(domain, HELD_BACK_RS_ID);
for (CSN csn : expected.subList(1, 3))
{
source.session.publish(new DeleteMsg(DN.valueOf("uid=via-peer-" + csn + "," + baseDN), csn,
"22222222-2222-2222-2222-222222222222"));
}
newConnectionTimer().repeatUntilSuccess(() -> {
assertThat(domain.getLatestServerState().getCSN(REMOTE_DS_ID)).isEqualTo(expected.get(2));
});
if (newerPeerUpdate)
{
// Hold the outgoing queue while both publications complete: peer 5 must
// not hide the unqueued prefix 2,3 when direct 4 is selected next.
final Field queueField = MessageHandler.class.getDeclaredField("msgQueue");
queueField.setAccessible(true);
synchronized (queueField.get(targetHandler))
{
domain.put(new DeleteMsg(DN.valueOf("uid=direct-four," + baseDN), expected.get(3),
"22222222-2222-2222-2222-222222222222"), domain.getConnectedDSs().get(REMOTE_DS_ID));
expected.add(new CSN(time, 5, REMOTE_DS_ID));
domain.put(new DeleteMsg(DN.valueOf("uid=peer-five," + baseDN), expected.get(4),
"22222222-2222-2222-2222-222222222222"), domain.getConnectedRSs().get(REMOTE_RS_ID));
}
}
else
{
publishBeforeMigration(broker, baseDN, expected.subList(3, 4));
}
newConnectionTimer().repeatUntilSuccess(() -> {
assertThat(targetHandler.getServerState().cover(expected.get(3))).isTrue();
});
final ServerState delivered = new ServerState();
delivered.update(expected.get(expected.size() - 1));
assertThat(targetHandler.awaitPublished(delivered, System.nanoTime() + TimeUnit.SECONDS.toNanos(5)))
.as("the last peer update is written before shutdown, which only drains direct updates").isTrue();
server.shutdown();
final List actual = new ArrayList<>();
for (ReplicationMsg msg : received.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS))
{
if (msg instanceof DeleteMsg)
{
actual.add(((DeleteMsg) msg).getCSN());
}
}
assertThat(actual).as("only a direct write from the same origin needs the peer history")
.containsExactlyElementsOf(sameOrigin ? expected : Arrays.asList(expected.get(0), expected.get(3)));
}
finally
{
closeQuietly(source);
closeQuietly(target);
if (broker != null)
{
broker.stop();
}
removeQuietly(server);
}
}
/** Registration between the peer watermark and persistence must not lose that prefix. */
@Test
public void newlyConnectedPeerSeesHistoryPublishedDuringItsRegistration() throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
final CountDownLatch beforePersistence = new CountDownLatch(1);
final CountDownLatch releasePut = new CountDownLatch(1);
ReplicationServer server = null;
ReplicationBroker broker = null;
FakePeerReplicationServer source = null;
FakePeerReplicationServer target = null;
try
{
final int port = TestCaseUtils.findFreePort();
server = newReplicationServer(new DSRSShutdownSync(), "peerRegistrationPrefixDb", 8255, port);
broker = openReplicationSession(baseDN, REMOTE_DS_ID, 100, port, 5000, EMPTY_DN_GENID);
source = FakePeerReplicationServer.connected(port, REMOTE_RS_ID, baseDN, EMPTY_DN_GENID);
final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, true);
waitForConnectedReplicationServer(domain, REMOTE_RS_ID);
source.receiveUntil(StopMsg.class);
final Field dbField = ReplicationServerDomain.class.getDeclaredField("domainDB");
dbField.setAccessible(true);
final ReplicationDomainDB database = (ReplicationDomainDB) dbField.get(domain);
final ReplicationDomainDB delayed = mock(ReplicationDomainDB.class, delegatesTo(database));
doAnswer(invocation -> {
beforePersistence.countDown();
assertThat(releasePut.await(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isTrue();
return database.publishUpdateMsg(baseDN, (UpdateMsg) invocation.getArguments()[1]);
}).when(delayed).publishUpdateMsg(eq(baseDN), any(UpdateMsg.class));
dbField.set(domain, delayed);
final CSN first = new CSN(System.currentTimeMillis(), 1, REMOTE_DS_ID);
final CSN last = new CSN(first.getTime(), 2, REMOTE_DS_ID);
source.session.publish(new DeleteMsg(DN.valueOf("uid=peer-history," + baseDN), first,
"22222222-2222-2222-2222-222222222222"));
assertThat(beforePersistence.await(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isTrue();
target = FakePeerReplicationServer.connected(port, HELD_BACK_RS_ID, baseDN, EMPTY_DN_GENID);
waitForConnectedReplicationServer(domain, HELD_BACK_RS_ID);
waitForFollowing(domain, HELD_BACK_RS_ID);
final Future> received = target.receiveUntil(StopMsg.class);
releasePut.countDown();
newConnectionTimer().repeatUntilSuccess(() -> {
assertThat(domain.getLatestServerState().cover(first)).isTrue();
});
publishBeforeMigration(broker, baseDN, Arrays.asList(last));
final ReplicationServerHandler handler = domain.getConnectedRSs().get(HELD_BACK_RS_ID);
newConnectionTimer().repeatUntilSuccess(() -> {
assertThat(handler.getServerState().cover(last)).isTrue();
});
server.shutdown();
final List actual = new ArrayList<>();
for (ReplicationMsg msg : received.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS))
{
if (msg instanceof DeleteMsg)
{
actual.add(((DeleteMsg) msg).getCSN());
}
}
assertThat(actual).containsExactly(first, last);
}
finally
{
releasePut.countDown();
closeQuietly(source);
closeQuietly(target);
if (broker != null)
{
broker.stop();
}
removeQuietly(server);
}
}
/** A future CSN from an old generation must not force replay of every new direct write. */
@Test
public void generationResetForgetsUnqueuedPeerHistory() throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
final ExecutorService consumer = Executors.newSingleThreadExecutor();
ReplicationServer server = null;
ReplicationServerHandler handler = null;
try
{
server = newReplicationServer(new DSRSShutdownSync(), "peerHistoryGenerationDb", 8256);
handler = new ReplicationServerHandler(null, 100, server, 100);
handler.setBaseDNAndDomain(baseDN, false);
handler.setInitialServerState(new ServerState());
handler.setGenerationId(1);
final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, false);
domain.initGenerationID(1);
final ReplicationServerHandler source = new ReplicationServerHandler(null, 100, server, 100);
source.setBaseDNAndDomain(baseDN, false);
source.setInitialServerState(new ServerState());
source.setGenerationId(1);
final long time = System.currentTimeMillis();
final DeleteMsg first = new DeleteMsg(baseDN, new CSN(time, 1, REMOTE_DS_ID),
"22222222-2222-2222-2222-222222222222");
final ReplicationDomainDB database = server.getChangelogDB().getReplicationDomainDB();
database.publishUpdateMsg(baseDN, first);
handler.add(first);
assertThat(handler.getNextMessage().getCSN()).isEqualTo(first.getCSN());
final ReplicationServerHandler target = handler;
final DeleteMsg current = new DeleteMsg(baseDN, new CSN(time + 1, 2, REMOTE_DS_ID),
"22222222-2222-2222-2222-222222222222");
final Future fromChangelog = consumer.submit(() -> {
assertThat(target.getNextMessage().getCSN()).isEqualTo(current.getCSN());
return target.isLastMessageFromLateQueue();
});
newConnectionTimer().repeatUntilSuccess(() -> { assertThat(target.isFollowing()).isTrue(); });
domain.put(new DeleteMsg(baseDN, new CSN(time + 60000, 1, REMOTE_DS_ID),
"22222222-2222-2222-2222-222222222222"), source);
domain.changeGenerationId(2);
handler.setGenerationId(2);
database.publishUpdateMsg(baseDN, current);
handler.add(current);
assertThat(fromChangelog.get(5, TimeUnit.SECONDS))
.as("a new-generation direct write needs no replay of discarded old-generation history").isFalse();
}
finally
{
if (handler != null)
{
handler.setConsumerActive(false);
}
consumer.shutdownNow();
assertThat(consumer.awaitTermination(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isTrue();
removeQuietly(server);
}
}
private void publishBeforeMigration(ReplicationBroker broker, DN baseDN, List csns)
throws Exception
{
for (CSN csn : csns)
{
broker.publish(new DeleteMsg(DN.valueOf("uid=before-migration-" + csn + "," + baseDN), csn,
"22222222-2222-2222-2222-222222222222"));
}
}
@Test
public void catchUpSkipsOnlyExactPeerReceiptsAndWaitsForOlderWrites() throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
ReplicationServer server = null;
try
{
server = newReplicationServer(new DSRSShutdownSync(), "shutdownPeerReceiptsDb", 8254);
final ReplicationServerHandler handler = new ReplicationServerHandler(null, 100, server, 100);
handler.setBaseDNAndDomain(baseDN, false);
handler.setInitialServerState(new ServerState());
final List updates = new ArrayList<>();
for (int i = 1; i <= 5; i++)
{
final DeleteMsg update = new DeleteMsg(baseDN,
new CSN(System.currentTimeMillis(), i, REMOTE_DS_ID),
"22222222-2222-2222-2222-222222222222");
updates.add(update);
if (i == 2 || i == 4)
{
handler.recordReceivedUpdate(update);
}
server.getChangelogDB().getReplicationDomainDB().publishUpdateMsg(baseDN, update);
}
assertThat(handler.getNextMessage().getCSN()).isEqualTo(updates.get(0).getCSN());
assertThat(handler.getNextMessage().getCSN()).isEqualTo(updates.get(2).getCSN());
assertThat(handler.getNextMessage().getCSN()).isEqualTo(updates.get(4).getCSN());
final ServerState target = new ServerState();
target.update(updates.get(3).getCSN());
handler.updatePublishedState(updates.get(0).getCSN());
assertThat(handler.awaitPublished(target, System.nanoTime()))
.as("the received change 4 cannot confirm the unwritten change 3").isFalse();
handler.updatePublishedState(updates.get(2).getCSN());
assertThat(handler.awaitPublished(target, System.nanoTime()))
.as("change 4 is already held by the peer once its older writes complete").isTrue();
target.update(updates.get(4).getCSN());
assertThat(handler.awaitPublished(target, System.nanoTime()))
.as("the selected change 5 is not written yet").isFalse();
handler.updatePublishedState(updates.get(4).getCSN());
assertThat(handler.awaitPublished(target, System.nanoTime())).isTrue();
}
finally
{
removeQuietly(server);
}
}
@DataProvider
public Object[][] peerGenerationChanges()
{
return new Object[][] { { false }, { true } };
}
@Test(dataProvider = "peerGenerationChanges")
public void aDiscardedWriteIsNotConfirmedByALaterReceiptOrWrite(boolean changePeerGeneration) throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
ReplicationServer server = null;
try
{
server = newReplicationServer(new DSRSShutdownSync(), "shutdownDiscardedReceiptDb", 8255);
final ReplicationServerHandler handler = new ReplicationServerHandler(null, 100, server, 100);
handler.setBaseDNAndDomain(baseDN, false);
handler.setInitialServerState(new ServerState());
final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, false);
domain.initGenerationID(1);
handler.setGenerationId(changePeerGeneration ? 2 : 1);
final long time = System.currentTimeMillis();
final CSN first = new CSN(time, 1, REMOTE_DS_ID);
final CSN received = new CSN(time, 2, REMOTE_DS_ID);
final CSN last = new CSN(time, 3, REMOTE_DS_ID);
for (CSN csn : Arrays.asList(first, received, last))
{
final DeleteMsg update = new DeleteMsg(baseDN, csn,
"22222222-2222-2222-2222-222222222222");
if (csn.equals(received))
{
handler.recordReceivedUpdate(update);
}
server.getChangelogDB().getReplicationDomainDB().publishUpdateMsg(baseDN, update);
}
assertThat(handler.getNextMessage().getCSN()).isEqualTo(first);
handler.updateDiscardedState(first);
if (changePeerGeneration)
{
// A peer now advertising the right generation has not received the dropped history.
handler.setGenerationId(1);
// Its old receipts are forgotten, so this record is conservatively sent again.
assertThat(handler.getNextMessage().getCSN()).isEqualTo(received);
handler.updatePublishedState(received);
}
assertThat(handler.getNextMessage().getCSN()).isEqualTo(last);
final ServerState target = new ServerState();
target.update(received);
assertThat(handler.awaitPublished(target, System.nanoTime())).isFalse();
handler.updatePublishedState(last);
assertThat(handler.awaitPublished(target, System.nanoTime()))
.as("a later socket write must not conceal an earlier discarded record").isFalse();
}
finally
{
removeQuietly(server);
}
}
@Test
public void exactReceiptsReleaseOnlyMatchingDiscardedWrites() throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
final ReplicationServer server = newReplicationServer(new DSRSShutdownSync(), "exactDiscardedReceiptDb", 8263);
try
{
final ReplicationServerHandler handler = new ReplicationServerHandler(null, 2, server, 100);
handler.setBaseDNAndDomain(baseDN, false);
handler.setInitialServerState(new ServerState());
server.getReplicationServerDomain(baseDN, false).initGenerationID(1);
handler.setGenerationId(2);
final List updates = new ArrayList<>();
final long time = System.currentTimeMillis();
for (int i = 0; i < 4; i++)
{
final DeleteMsg update = new DeleteMsg(baseDN, new CSN(time, i + 1, REMOTE_DS_ID),
"22222222-2222-2222-2222-222222222222");
updates.add(update);
assertThat(handler.updateServerState(update)).isTrue();
}
final DeleteMsg pending = updates.get(0);
final DeleteMsg firstDiscard = updates.get(1);
final DeleteMsg secondDiscard = updates.get(2);
final DeleteMsg delayedDiscard = updates.get(3);
handler.updateDiscardedState(firstDiscard.getCSN());
handler.updateDiscardedState(secondDiscard.getCSN());
handler.recordReceivedUpdate(firstDiscard); // Wrong generation.
handler.setGenerationId(1);
handler.recordReceivedUpdate(delayedDiscard);
final ServerState target = new ServerState();
target.update(pending.getCSN());
assertThat(handler.awaitPublished(target, System.nanoTime()))
.as("an exact receipt cannot release an earlier pending write").isFalse();
target.update(firstDiscard.getCSN());
handler.updatePublishedState(pending.getCSN());
assertThat(handler.awaitPublished(target, System.nanoTime()))
.as("a receipt from another generation cannot release the first discard").isFalse();
handler.recordReceivedUpdate(firstDiscard);
assertThat(handler.awaitPublished(target, System.nanoTime())).isTrue();
target.update(delayedDiscard.getCSN());
assertThat(handler.awaitPublished(target, System.nanoTime()))
.as("the other discarded write from the same origin is still missing").isFalse();
handler.recordReceivedUpdate(secondDiscard);
// The two intervening receipts evicted this CSN from the ordinary catch-up cache.
handler.updateDiscardedState(delayedDiscard.getCSN());
assertThat(handler.awaitPublished(target, System.nanoTime()))
.as("the last exact receipt preceded its discard callback").isTrue();
}
finally
{
removeQuietly(server);
}
}
@DataProvider
public Object[][] overflowDiscards()
{
// Confirm the first two CSNs in either order, with or without a third missing discard.
return new Object[][] { { 2, 0 }, { 2, 1 }, { 3, 1 } };
}
@Test(dataProvider = "overflowDiscards")
public void exactOverflowReceiptDoesNotHideAnotherDiscard(int discardCount, int firstReceipt) throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
final ReplicationServer server = newReplicationServer(new DSRSShutdownSync(), "overflowDiscardDb", 8265);
try
{
final ReplicationServerHandler handler = new ReplicationServerHandler(null, 1, server, 100);
handler.setBaseDNAndDomain(baseDN, false);
handler.setInitialServerState(new ServerState());
server.getReplicationServerDomain(baseDN, false).initGenerationID(1);
handler.setGenerationId(1);
final List updates = new ArrayList<>();
final long time = System.currentTimeMillis();
for (int i = 0; i < discardCount; i++)
{
final DeleteMsg update = new DeleteMsg(baseDN, new CSN(time, i + 1, REMOTE_DS_ID),
"22222222-2222-2222-2222-222222222222");
updates.add(update);
assertThat(handler.updateServerState(update)).isTrue();
handler.updateDiscardedState(update.getCSN());
}
final ServerState target = new ServerState();
target.update(updates.get(discardCount - 1).getCSN());
handler.recordReceivedUpdate(updates.get(firstReceipt));
assertThat(handler.awaitPublished(target, System.nanoTime())).isFalse();
handler.recordReceivedUpdate(updates.get(1 - firstReceipt));
assertThat(handler.awaitPublished(target, System.nanoTime()))
.as("the first two exact receipts cover the target only if no third discard is missing")
.isEqualTo(discardCount == 2);
}
finally
{
removeQuietly(server);
}
}
@DataProvider
public Object[][] changelogFailureSources()
{
return new Object[][] { { true }, { false } };
}
@Test(dataProvider = "changelogFailureSources")
public void changelogFailureShutsDownAfterReleasingDirectAdmission(boolean fromDS) throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
final ReplicationServer server = newReplicationServer(new DSRSShutdownSync(), "failedDirectPublishDb", 8264);
try
{
final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, true);
domain.initGenerationID(1);
final ServerHandler source = mock(ServerHandler.class);
when(source.isDataServer()).thenReturn(fromDS);
when(source.getGenerationId()).thenReturn(1L);
final Field dbField = ReplicationServerDomain.class.getDeclaredField("domainDB");
dbField.setAccessible(true);
final ReplicationDomainDB failing = mock(ReplicationDomainDB.class);
final DeleteMsg update = new DeleteMsg(baseDN, new CSN(System.currentTimeMillis(), 1, REMOTE_DS_ID),
"22222222-2222-2222-2222-222222222222");
when(failing.publishUpdateMsg(baseDN, update)).thenThrow(new ChangelogException(new IOException("injected")));
dbField.set(domain, failing);
final List records = errorLogRecordsOf(() -> {
domain.put(update, source);
return null;
});
assertThat(records.stream().anyMatch(line -> line.contains("RS shutdown timed out waiting for direct DS updates")))
.as("the failed publisher can cross its own domain's shutdown barrier").isFalse();
when(source.isDataServer()).thenReturn(true);
assertThatThrownBy(() -> domain.put(update, source)).isInstanceOf(IOException.class)
.hasMessageContaining("closing its directory connections");
}
finally
{
removeQuietly(server);
}
}
@DataProvider
public Object[][] discardBeforeOrAfterLocalReset()
{
return new Object[][] { { false }, { true } };
}
@Test(dataProvider = "discardBeforeOrAfterLocalReset")
public void localGenerationResetDoesNotCarryDiscardedWrites(boolean delayedDiscard) throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
ReplicationServer server = null;
try
{
server = newReplicationServer(new DSRSShutdownSync(), "shutdownDiscardedGenerationDb", 8257);
final ReplicationServerHandler handler = new ReplicationServerHandler(null, 100, server, 100);
handler.setBaseDNAndDomain(baseDN, false);
handler.setInitialServerState(new ServerState());
final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, false);
domain.initGenerationID(1);
handler.setGenerationId(1);
final long time = System.currentTimeMillis();
final CSN old = new CSN(time, 1, REMOTE_DS_ID);
final CSN current = new CSN(time, 2, REMOTE_DS_ID);
server.getChangelogDB().getReplicationDomainDB().publishUpdateMsg(baseDN,
new DeleteMsg(baseDN, old, "22222222-2222-2222-2222-222222222222"));
assertThat(handler.getNextMessage().getCSN()).isEqualTo(old);
if (!delayedDiscard)
{
handler.updateDiscardedState(old);
}
domain.changeGenerationId(2);
handler.setGenerationId(2);
if (delayedDiscard)
{
// The writer selected this record before reset, but reports its drop afterwards.
handler.updateDiscardedState(old);
}
server.getChangelogDB().getReplicationDomainDB().publishUpdateMsg(baseDN,
new DeleteMsg(baseDN, current, "22222222-2222-2222-2222-222222222222"));
assertThat(handler.getNextMessage().getCSN()).isEqualTo(current);
handler.updatePublishedState(current);
final ServerState target = new ServerState();
target.update(current);
assertThat(handler.awaitPublished(target, System.nanoTime()))
.as("a local reset discards the old generation's delivery obligation").isTrue();
}
finally
{
removeQuietly(server);
}
}
@DataProvider
public Object[][] receiptCacheResets()
{
return new Object[][] { { false }, { true } };
}
@Test(dataProvider = "receiptCacheResets")
public void boundedReceiptsNeverHideUnknownHistory(boolean newGeneration) throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
ReplicationServer server = null;
try
{
server = newReplicationServer(new DSRSShutdownSync(), "boundedPeerReceiptsDb", 8256);
final ReplicationServerHandler handler = new ReplicationServerHandler(null, 2, server, 100);
handler.setBaseDNAndDomain(baseDN, false);
handler.setInitialServerState(new ServerState());
handler.setGenerationId(1);
final long time = System.currentTimeMillis();
final List expected = new ArrayList<>();
for (int i = 1; i <= 6; i++)
{
final CSN csn = new CSN(time, i, REMOTE_DS_ID);
final DeleteMsg update = new DeleteMsg(baseDN, csn,
"22222222-2222-2222-2222-222222222222");
if (i % 2 == 1)
{
handler.recordReceivedUpdate(update);
}
if (newGeneration || i == 1 || i % 2 == 0)
{
// The first receipt is evicted; an unknown or forgotten record is sent.
expected.add(csn);
}
server.getChangelogDB().getReplicationDomainDB().publishUpdateMsg(baseDN, update);
}
if (newGeneration)
{
handler.setGenerationId(2);
}
for (CSN csn : expected)
{
assertThat(handler.getNextMessage().getCSN()).isEqualTo(csn);
handler.updatePublishedState(csn);
}
}
finally
{
removeQuietly(server);
}
}
@Test
public void generationResetDoesNotAwaitDiscardedUpdates() throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
ReplicationServer server = null;
ReplicationBroker broker = null;
FakePeerReplicationServer peer = null;
try
{
final int port = TestCaseUtils.findFreePort();
server = newReplicationServer(new DSRSShutdownSync(), "shutdownResetUpdatesDb", 8251, port);
broker = openReplicationSession(baseDN, REMOTE_DS_ID, 100, port, 5000, EMPTY_DN_GENID);
final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, true);
final CSN csn = new CSN(System.currentTimeMillis(), 1, REMOTE_DS_ID);
broker.publish(new DeleteMsg(DN.valueOf("uid=old," + baseDN), csn,
"22222222-2222-2222-2222-222222222222"));
newConnectionTimer().repeatUntilSuccess(() -> {
assertThat(domain.getLatestServerState().getCSN(REMOTE_DS_ID)).isEqualTo(csn);
});
broker.stop();
broker = null;
domain.changeGenerationId(EMPTY_DN_GENID + 1);
peer = FakePeerReplicationServer.connected(port, REMOTE_RS_ID, baseDN, EMPTY_DN_GENID + 1);
waitForConnectedReplicationServer(domain, REMOTE_RS_ID);
final List records = errorLogRecordsOf(() -> {
domain.awaitDirectUpdatesForwarded(System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(100));
return null;
});
assertThat(records.stream().anyMatch(line -> line.contains("RS shutdown could not forward")))
.as("a generation reset discarded these changes, so the new generation owes no forward")
.isFalse();
}
finally
{
closeQuietly(peer);
if (broker != null)
{
broker.stop();
}
removeQuietly(server);
}
}
@Test
public void shutdownWaitsForAReaderAlreadyRemovedByConcurrentTeardown() throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
final CountDownLatch inDatabase = new CountDownLatch(1);
final CountDownLatch releasePut = new CountDownLatch(1);
final ExecutorService executor = Executors.newFixedThreadPool(2);
ReplicationServer server = null;
ReplicationBroker broker = null;
FakePeerReplicationServer peer = null;
Future> teardown = null;
Future> stopped = null;
try
{
final int port = TestCaseUtils.findFreePort();
server = newReplicationServer(new DSRSShutdownSync(), "shutdownConcurrentReaderDb", 8252, port);
broker = openReplicationSession(baseDN, REMOTE_DS_ID, 100, port, 5000, EMPTY_DN_GENID);
peer = FakePeerReplicationServer.connected(port, REMOTE_RS_ID, baseDN, EMPTY_DN_GENID);
final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, true);
waitForConnectedReplicationServer(domain, REMOTE_RS_ID);
waitForFollowing(domain, REMOTE_RS_ID);
final CSN first = new CSN(System.currentTimeMillis(), 1, REMOTE_DS_ID);
Future receivedFirst = peer.receive(DeleteMsg.class);
broker.publish(new DeleteMsg(DN.valueOf("uid=first," + baseDN), first,
"22222222-2222-2222-2222-222222222222"));
assertThat(receivedFirst.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS).getCSN()).isEqualTo(first);
final Future> received = peer.receiveUntil(StopMsg.class);
final Field dbField = ReplicationServerDomain.class.getDeclaredField("domainDB");
dbField.setAccessible(true);
final ReplicationDomainDB database = (ReplicationDomainDB) dbField.get(domain);
final ReplicationDomainDB delayed = mock(ReplicationDomainDB.class, delegatesTo(database));
doAnswer(invocation -> {
boolean created = database.publishUpdateMsg(baseDN, (UpdateMsg) invocation.getArguments()[1]);
inDatabase.countDown();
assertThat(releasePut.await(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isTrue();
return created;
}).when(delayed).publishUpdateMsg(eq(baseDN), any(UpdateMsg.class));
dbField.set(domain, delayed);
final CSN last = new CSN(first.getTime(), 2, REMOTE_DS_ID);
broker.publish(new DeleteMsg(DN.valueOf("uid=last," + baseDN), last,
"22222222-2222-2222-2222-222222222222"));
assertThat(inDatabase.await(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isTrue();
final DataServerHandler ds = domain.getConnectedDSs().get(REMOTE_DS_ID);
teardown = executor.submit(() -> domain.stopServer(ds, false));
newConnectionTimer().repeatUntilSuccess(() -> { assertThat(domain.getConnectedDSs()).isEmpty(); });
final ReplicationServer stopping = server;
stopped = executor.submit(() -> stopping.shutdown());
try
{
stopped.get(EARLY_CLOSE_TIMEOUT_MS, TimeUnit.MILLISECONDS);
}
catch (TimeoutException expected)
{
// A correct shutdown is waiting for the put which already reached its database.
}
releasePut.countDown();
stopped.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS);
final List changes = new ArrayList<>();
for (ReplicationMsg msg : received.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS))
{
if (msg instanceof DeleteMsg)
{
changes.add(((DeleteMsg) msg).getCSN());
}
}
assertThat(changes).as("the accepted update of a reader already in teardown").contains(last);
}
finally
{
releasePut.countDown();
awaitQuietly(teardown);
awaitQuietly(stopped);
closeQuietly(peer);
if (broker != null)
{
broker.stop();
}
removeQuietly(server);
executor.shutdownNow();
}
}
@Test
public void shutdownWaitsForTheReplicaOfflineMsgToBeForwarded() throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
final DSRSShutdownSync shutdownSync = new DSRSShutdownSync();
ReplicationServer replicationServer = null;
try (ServerSocket listen = TestCaseUtils.bindFreePort())
{
listen.setSoTimeout(SOCKET_TIMEOUT_MS);
replicationServer = newReplicationServer(shutdownSync, "shutdownSyncWaitDb", 8221);
final Session[] sessionPair = connectSessionPair(listen, getReplSessionSecurity());
try (Session remoteEnd = sessionPair[0];
Session session = sessionPair[1])
{
registerConnectedReplicationServer(replicationServer, baseDN, session);
final long startTime = System.nanoTime();
shutdownSync.replicaOfflineMsgSent(baseDN, newOfflineCSN());
replicationServer.shutdown();
final long elapsed = elapsedMillis(startTime);
assertThat(elapsed).isGreaterThanOrEqualTo(DSRSShutdownSync.REPLICA_OFFLINE_GRACE_PERIOD);
}
}
finally
{
removeQuietly(replicationServer);
}
}
@Test
public void shutdownResumesAsSoonAsTheReplicaOfflineMsgIsForwarded() throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
final DSRSShutdownSync shutdownSync = new DSRSShutdownSync();
ReplicationServer replicationServer = null;
Thread forwarder = null;
try (ServerSocket listen = TestCaseUtils.bindFreePort())
{
listen.setSoTimeout(SOCKET_TIMEOUT_MS);
replicationServer = newReplicationServer(shutdownSync, "shutdownSyncForwardDb", 8222);
final Session[] sessionPair = connectSessionPair(listen, getReplSessionSecurity());
try (Session remoteEnd = sessionPair[0];
Session session = sessionPair[1])
{
registerConnectedReplicationServer(replicationServer, baseDN, session);
final CSN offlineCSN = newOfflineCSN();
forwarder = newForwarderThread(shutdownSync, baseDN, offlineCSN);
shutdownSync.replicaOfflineMsgSent(baseDN, offlineCSN);
final long startTime = System.nanoTime();
forwarder.start();
replicationServer.shutdown();
final long elapsed = elapsedMillis(startTime);
assertThat(elapsed).isGreaterThanOrEqualTo(FORWARD_DELAY)
.isLessThan(DSRSShutdownSync.REPLICA_OFFLINE_GRACE_PERIOD);
}
}
finally
{
joinQuietly(forwarder);
removeQuietly(replicationServer);
}
}
/**
* The outcome the grace period exists for, end to end: a peer replication server connected
* through the real handshake has received the ReplicaOfflineMsg of the collocated replica by
* the time the shutdown returns.
*
* The waiting tests above measure durations only, so they stay green if the wait is moved
* after the handlers are stopped - which reintroduces OPENDJ-1453 and loses the message. This
* one fails in that case.
*/
@Test
public void thePeerReceivesTheReplicaOfflineMsgBeforeTheShutdownReturns() throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
final DSRSShutdownSync shutdownSync = new DSRSShutdownSync();
ReplicationServer replicationServer = null;
ReplicationBroker broker = null;
FakePeerReplicationServer peer = null;
Thread publisher = null;
try
{
final int replicationPort = TestCaseUtils.findFreePort();
replicationServer =
newReplicationServer(shutdownSync, "shutdownSyncDeliveryDb", 8226, replicationPort);
broker = openReplicationSession(baseDN, LOCAL_DS_ID, 100, replicationPort, 5000, EMPTY_DN_GENID);
peer = FakePeerReplicationServer.connected(
replicationPort, REMOTE_RS_ID, baseDN, EMPTY_DN_GENID);
final ReplicationServerDomain domain =
replicationServer.getReplicationServerDomain(baseDN, true);
waitForConnectedReplicationServer(domain, REMOTE_RS_ID);
final Future received = peer.receive(ReplicaOfflineMsg.class);
/*
* The replica announces itself offline once the shutdown of the replication server is
* already waiting for the message, which is the ordering the grace period exists for.
*/
final CSN offlineCSN = newOfflineCSN();
shutdownSync.replicaOfflineMsgSent(baseDN, offlineCSN);
publisher = newPublisherThread(broker, offlineCSN);
final long startTime = System.nanoTime();
publisher.start();
replicationServer.shutdown();
final long elapsed = elapsedMillis(startTime);
final ReplicaOfflineMsg forwarded = received.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS);
assertThat(forwarded)
.as("the peer replication server was never told that the replica went offline, its "
+ "read ended with: %s", peer.failure())
.isNotNull();
assertThat(forwarded.getCSN().getServerId()).isEqualTo(LOCAL_DS_ID);
assertThat(elapsed).isGreaterThanOrEqualTo(FORWARD_DELAY)
.isLessThan(DSRSShutdownSync.REPLICA_OFFLINE_GRACE_PERIOD);
}
finally
{
joinQuietly(publisher);
closeQuietly(peer);
stop(broker);
removeQuietly(replicationServer);
}
}
@DataProvider
public Object[][] peerProtocolVersions()
{
return new Object[][] {
{ ProtocolVersion.getCurrentVersion(), true },
{ ProtocolVersion.REPLICATION_PROTOCOL_V7, false },
};
}
/**
* A peer replication server which negotiated a protocol version older than the one which
* introduced the ReplicaOfflineMsg cannot be told that a replica went offline: the message has
* no encoding for such a peer and {@link Session#publish(ReplicationMsg)} drops what it cannot
* encode. Nothing can be done about the peer itself - the announcement is not part of the
* protocol it speaks - but the writer must not report that drop as a forward, or the shutdown
* counts this peer as told by a writer which sent nothing - and, for an announcement no
* recipient was recorded for, stops waiting for the peers which do need the message.
*
* The drop is reported to the operator as well, once for the copy the writer took, and that
* record is the only account of a peer the topology leaves behind: what it names is asserted
* here next to what the writer told the shutdown. The peer is waited on until it is served
* from its queue - see {@link #waitForFollowing(ReplicationServerDomain, int)} - so that the
* writer is handed the announcement once and the count is not a race.
*
* The change published after the announcement is the synchronization point: the writer of a
* peer takes from one queue in order, so a peer which has received that change has already
* dealt with the announcement which precedes it - forwarded it, or dropped it, logged the drop
* and told the shutdown to stop waiting for this peer.
*/
@Test(dataProvider = "peerProtocolVersions")
public void onlyAPeerWhichCanDecodeTheMessageIsToldTheReplicaWentOffline(
short peerVersion, boolean expectedToBeTold) throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
final RecordingShutdownSync shutdownSync = new RecordingShutdownSync();
ReplicationServer replicationServer = null;
ReplicationBroker broker = null;
FakePeerReplicationServer peer = null;
try
{
final int replicationPort = TestCaseUtils.findFreePort();
replicationServer = newReplicationServer(shutdownSync,
"shutdownSyncPeerVersion" + peerVersion + "Db", PEER_VERSION_RS_ID + peerVersion,
replicationPort);
broker = openReplicationSession(baseDN, LOCAL_DS_ID, 100, replicationPort, 5000, EMPTY_DN_GENID);
peer = FakePeerReplicationServer.connected(
replicationPort, REMOTE_RS_ID, baseDN, EMPTY_DN_GENID, PEER_WINDOW, peerVersion);
final ReplicationServerDomain domain =
replicationServer.getReplicationServerDomain(baseDN, true);
waitForConnectedReplicationServer(domain, REMOTE_RS_ID);
waitForFollowing(domain, REMOTE_RS_ID);
final Future> received = peer.receiveUntil(DeleteMsg.class);
final CSNGenerator csns = new CSNGenerator(LOCAL_DS_ID, 0);
final CSN offlineCSN = csns.newCSN();
final ReplicationBroker publishingBroker = broker;
final AtomicReference> drained = new AtomicReference<>();
final List records = errorLogRecordsOf(() -> {
shutdownSync.replicaOfflineMsgSent(baseDN, offlineCSN);
publishingBroker.publish(new ReplicaOfflineMsg(offlineCSN));
publishingBroker.publish(new DeleteMsg(DN.valueOf("uid=marker," + TEST_ROOT_DN_STRING),
csns.newCSN(), "22222222-2222-2222-2222-222222222222"));
drained.set(received.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS));
return null;
});
final List msgs = drained.get();
assertThat(lastOf(msgs))
.as("the peer never received the change published after the announcement, its read "
+ "ended with: %s", peer.failure())
.isInstanceOf(DeleteMsg.class);
assertThat(containsReplicaOfflineMsg(msgs, offlineCSN))
.as("the peer speaking protocol version %s was %stold that the replica went offline",
peerVersion, expectedToBeTold ? "not " : "")
.isEqualTo(expectedToBeTold);
/*
* The peer gives no credit back, so what its window lacks is what it was sent. The writer
* which dropped the announcement had been charged a permit for it all the same, and gives
* it back - the peer never received it, so no credit will ever come for it (issue #1080).
*/
final ReplicationServerHandler peerHandler = domain.getConnectedRSs().get(REMOTE_RS_ID);
final int sent = expectedToBeTold ? 2 : 1;
assertThat(FilteredUpdateSendWindowTest.monitorValue(peerHandler, "current-send-window"))
.as("the send window of the peer speaking protocol version %s is short of what it "
+ "was not sent", peerVersion)
.isEqualTo(PEER_WINDOW - sent);
assertThat(FilteredUpdateSendWindowTest.monitorValue(peerHandler, "sent-updates"))
.as("the peer speaking protocol version %s was counted as sent what it was not sent",
peerVersion)
.isEqualTo(sent);
assertThat(shutdownSync.dispatchedTo())
.as("the message was never queued for the peer, so its writer had nothing to report")
.containsExactly(REMOTE_RS_ID);
if (expectedToBeTold)
{
assertThat(shutdownSync.forwardedBy())
.as("the writer of the peer speaking protocol version %s never reported the forward "
+ "of a message which did reach it", peerVersion)
.containsExactly(REMOTE_RS_ID);
}
else
{
assertThat(shutdownSync.forwardedBy())
.as("the writer of the peer speaking protocol version %s reported a forward of a "
+ "message which never reached it", peerVersion)
.isEmpty();
assertThat(shutdownSync.gaveUpOn())
.as("the writer of the peer speaking protocol version %s dropped the message without "
+ "telling the shutdown to stop waiting for the peer it was queued for",
peerVersion)
.containsExactly(REMOTE_RS_ID);
}
/*
* The records are picked by the id of the message and the peer they name rather than by
* their whole text: the address the writer logs is the one the replication server sees the
* peer on, which this side does not hold. What the record has to carry is asserted below,
* so that an argument dropped or permuted does not pass here.
*/
final List drops = new ArrayList<>();
for (String record : records)
{
if (record.contains("msgID=" + WARN_IGNORING_UPDATE_UNSUPPORTED_BY_PEER.ordinal())
&& record.contains("to server " + REMOTE_RS_ID))
{
drops.add(record);
}
}
if (expectedToBeTold)
{
assertThat(drops)
.as("a message the peer speaking protocol version %s did receive was reported as "
+ "dropped", peerVersion)
.isEmpty();
}
else
{
assertThat(drops)
.as("the drop for the peer speaking protocol version %s should be logged once",
peerVersion)
.hasSize(1);
/*
* The severity is part of what this reports: an operator reads the warnings, and a drop
* demoted to a trace or an info leaves the announcement lost with nothing said about it.
*/
assertThat(drops.get(0))
.as("the drop should be reported as a warning naming this replication server, the "
+ "domain, the change and the version it has no encoding for")
.contains("severity=WARNING")
.contains("RS(" + (PEER_VERSION_RS_ID + peerVersion) + ")")
.contains(offlineCSN.toString())
.contains("domain \"" + baseDN + "\"")
.contains("protocol version " + peerVersion);
}
}
finally
{
closeQuietly(peer);
stop(broker);
removeQuietly(replicationServer);
}
}
/**
* A peer replication server whose handshake is in flight when the shutdown starts must live
* long enough to be told: it is one of the servers the ReplicaOfflineMsg is forwarded to, and
* the handshake runs in the very listen thread the shutdown interrupts.
*/
@Test
public void thePeerWhoseHandshakeIsInFlightIsStillToldTheReplicaWentOffline() throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
final CountDownLatch shutdownIsWaiting = new CountDownLatch(1);
final DSRSShutdownSync shutdownSync = new DSRSShutdownSync()
{
@Override
public void awaitReplicaOfflineMsgsForwarded(Collection baseDNs, long deadline)
{
shutdownIsWaiting.countDown();
super.awaitReplicaOfflineMsgsForwarded(baseDNs, deadline);
}
};
ReplicationServer replicationServer = null;
ReplicationBroker broker = null;
FakePeerReplicationServer connectedPeer = null;
FakePeerReplicationServer handshakingPeer = null;
Thread shutdown = null;
try
{
final int replicationPort = TestCaseUtils.findFreePort();
replicationServer =
newReplicationServer(shutdownSync, "shutdownSyncHandshakeDb", 8234, replicationPort);
broker = openReplicationSession(baseDN, LOCAL_DS_ID, 100, replicationPort, 5000, EMPTY_DN_GENID);
connectedPeer = FakePeerReplicationServer.connected(
replicationPort, REMOTE_RS_ID, baseDN, EMPTY_DN_GENID);
final ReplicationServerDomain domain =
replicationServer.getReplicationServerDomain(baseDN, true);
waitForConnectedReplicationServer(domain, REMOTE_RS_ID);
/*
* The second peer stops between the two phases of its handshake, which leaves the listen
* thread blocked in the receive of the TopologyMsg it owes, the peer not yet registered on
* the domain - the state in which the shutdown used to send the interrupt which, once the
* handshake got to the startup of its session, tore the peer down. A message nobody can
* forward holds the shutdown in its wait meanwhile, so what the connected peer does with
* the message published below cannot end the wait before this one has been served.
*
* Two clocks run from here, both far longer than what follows costs on the loopback: the
* grace period of that announcement, which is all that holds the wait, and the connection
* timeout of the replication server, which bounds its receive of the TopologyMsg. The
* handshake, the registration and the forward must land inside the first, else the domains
* are stopped and the peer reports the very message of the regression - hence the
* assertion on the elapsed time below; the TopologyMsg must arrive inside the second, else
* the replication server gives the peer up itself and completeHandshake() fails on its
* own account.
*/
handshakingPeer = FakePeerReplicationServer.handshaking(
replicationPort, HANDSHAKING_RS_ID, baseDN, EMPTY_DN_GENID);
final CSN unreachableCSN = newOfflineCSN(UNREACHABLE_DS_ID);
final long startTime = System.nanoTime();
shutdownSync.replicaOfflineMsgSent(baseDN, unreachableCSN);
shutdown = newShutdownThread(replicationServer);
shutdown.start();
assertThat(shutdownIsWaiting.await(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS))
.as("the shutdown never reached its wait for the ReplicaOfflineMsgs").isTrue();
handshakingPeer.completeHandshake();
final Future received = handshakingPeer.receive(ReplicaOfflineMsg.class);
waitForConnectedReplicationServer(domain, HANDSHAKING_RS_ID);
final CSN offlineCSN = newOfflineCSN();
shutdownSync.replicaOfflineMsgSent(baseDN, offlineCSN);
broker.publish(new ReplicaOfflineMsg(offlineCSN));
final ReplicaOfflineMsg forwarded = received.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS);
final long elapsed = elapsedMillis(startTime);
assertThat(forwarded)
.as("the peer which was handshaking when the shutdown started was never told that the "
+ "replica went offline, its read ended with: %s", handshakingPeer.failure())
.isNotNull();
assertThat(forwarded.getCSN().getServerId()).isEqualTo(LOCAL_DS_ID);
assertThat(elapsed)
.as("the handshake and the forward must land inside the grace period which holds the "
+ "wait, or the pass says nothing about the order of the shutdown")
.isLessThan(DSRSShutdownSync.REPLICA_OFFLINE_GRACE_PERIOD);
/*
* The announcement has done its job. An entry which was never queued for anybody is
* released by the first forward reported for it, so end the wait now rather than sit out
* the rest of its grace period in the join below.
*/
shutdownSync.replicaOfflineMsgForwarded(
baseDN, unreachableCSN, domain.getConnectedRSs().get(HANDSHAKING_RS_ID).offlineForwarder());
}
finally
{
joinQuietly(shutdown);
closeQuietly(handshakingPeer);
closeQuietly(connectedPeer);
stop(broker);
removeQuietly(replicationServer);
}
}
/**
* The other half of the order of the shutdown: the interrupt still precedes the shutdown of
* the domains, so a handshake which completes only once the shutdown is over is stopped rather
* than served. Without the interrupt such a peer registers after the domains were stopped and
* nothing ever stops it: its session, reader, writer and heartbeat are started, and its writer
* parks forever on a cursor over the changelog the shutdown has closed - five threads and a
* peer heartbeating a replication server which no longer exists, on a server which was merely
* removed from the configuration.
*/
@Test
public void thePeerWhoseHandshakeCompletesAfterTheShutdownIsStoppedNotServed() throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
ReplicationServer replicationServer = null;
FakePeerReplicationServer handshakingPeer = null;
try
{
final int replicationPort = TestCaseUtils.findFreePort();
replicationServer = newReplicationServer(
new DSRSShutdownSync(), "shutdownSyncLateHandshakeDb", 8235, replicationPort);
final ReplicationServerDomain domain =
replicationServer.getReplicationServerDomain(baseDN, true);
handshakingPeer = FakePeerReplicationServer.handshaking(
replicationPort, HANDSHAKING_RS_ID, baseDN, EMPTY_DN_GENID);
/*
* Nothing is pending, so the wait returns at once and the interrupt lands on the handshake
* in flight - on a receive it does not break, where the flag survives until the startup of
* the session. The handshake is completed once the shutdown has returned, inside the
* connection timeout which bounds that receive: past it the replication server gives the
* peer up on its own, without a StopMsg, and completeHandshake() fails on a closed session
* rather than letting the case pass for the wrong reason.
*/
replicationServer.shutdown();
handshakingPeer.completeHandshake();
final Future stopped = handshakingPeer.receive(StopMsg.class);
StopMsg stopMsg = null;
try
{
stopMsg = stopped.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS);
}
catch (TimeoutException e)
{
// A served peer keeps receiving heartbeats: its read neither ends nor yields a StopMsg.
}
assertThat(stopMsg)
.as("the peer whose handshake completed after the shutdown was served instead of "
+ "stopped: no StopMsg within %s ms, its read ended with: %s",
SOCKET_TIMEOUT_MS, handshakingPeer.failure())
.isNotNull();
// abortStart() sends the StopMsg when it closes the session, and unregisters the peer after
newConnectionTimer().repeatUntilSuccess(new TestTimer.CallableVoid()
{
@Override
public void call() throws Exception
{
assertThat(domain.getConnectedRSs())
.as("the peer whose handshake was aborted by the shutdown stayed registered")
.doesNotContainKey(HANDSHAKING_RS_ID);
}
});
}
finally
{
closeQuietly(handshakingPeer);
removeQuietly(replicationServer);
}
}
/**
* The forward the shutdown waits for must mean that the message has been written to the peer,
* not that it has been queued for the thread of its session: a forward reported on the queue
* ends the wait of the shutdown before the peer has been told, and leaves the message to what
* Session.close() sends of the queue once the write it joins has returned, within a budget of
* its own rather than the grace period. The session thread is busy with an earlier message when
* the ReplicaOfflineMsg is queued behind it whenever the peer reads slower than the
* replication server writes. Here the peer does not read at all, and the
* socket buffers on both sides of its connection are far smaller than the change which fills
* them, so the session thread is held inside the write of that change until the test lets the
* peer read.
*/
@Test
public void thePeerStillReadingAnEarlierChangeIsToldTheReplicaWentOfflineBeforeItIsStopped()
throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
final RecordingShutdownSync shutdownSync = new RecordingShutdownSync();
final ExecutorService executor = Executors.newFixedThreadPool(2);
ReplicationServer replicationServer = null;
ReplicationBroker broker = null;
FakePeerReplicationServer peer = null;
Future shutdown = null;
try (ServerSocket listen = TestCaseUtils.bindFreePort())
{
listen.setSoTimeout(SOCKET_TIMEOUT_MS);
final int replicationPort = TestCaseUtils.findFreePort();
replicationServer =
newReplicationServer(shutdownSync, "shutdownSyncBusySessionDb", 8238, replicationPort);
broker =
openReplicationSession(baseDN, LOCAL_DS_ID, 100, replicationPort, 5000, EMPTY_DN_GENID);
final ConnectedSessions connection =
connectSessionPair(listen, getReplSessionSecurity(), SMALL_SOCKET_BUFFER_SIZE);
final Future served =
serveAsTheListenThreadWould(replicationServer, connection.localEnd, executor);
peer = FakePeerReplicationServer.connected(connection.remoteEnd, connection.remoteSocket,
BUSY_RS_ID, baseDN, EMPTY_DN_GENID, PEER_WINDOW);
served.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS);
final ReplicationServerDomain domain =
replicationServer.getReplicationServerDomain(baseDN, true);
waitForConnectedReplicationServer(domain, BUSY_RS_ID);
/*
* One generator for the change and the announcement: a CSN which does not follow the one
* of the change would be dropped by the handler of the peer as already seen.
*/
final CSNGenerator csns = new CSNGenerator(LOCAL_DS_ID, 0);
broker.publish(newChangeLargerThanTheSocketBuffers(csns.newCSN()));
peer.awaitReceiveBufferFilled();
final CSN offlineCSN = csns.newCSN();
shutdownSync.replicaOfflineMsgSent(baseDN, offlineCSN);
broker.publish(new ReplicaOfflineMsg(offlineCSN));
shutdownSync.awaitDispatch();
shutdown = executor.submit(newShutdown(replicationServer));
awaitCloseInitiated(connection.localEnd, EARLY_CLOSE_TIMEOUT_MS);
final List forwardedBeforeThePeerRead = new ArrayList<>(shutdownSync.forwardedBy());
final Future received = peer.receive(ReplicaOfflineMsg.class);
final ReplicaOfflineMsg forwarded = received.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS);
final long elapsed = shutdown.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS);
assertThat(forwarded)
.as("the peer was never told that the replica went offline: its session was closed "
+ "with the message still queued behind the change it was reading, and its read "
+ "ended with: %s (forward reported by %s, the shutdown took %d ms)",
peer.failure(), shutdownSync.forwardedBy(), elapsed)
.isNotNull();
assertThat(forwardedBeforeThePeerRead)
.as("the writer reported the message forwarded while it was still queued behind a "
+ "change the peer had not read")
.doesNotContain(BUSY_RS_ID);
assertThat(shutdownSync.forwardedBy())
.as("the message was written to the peer and nothing reported the forward")
.contains(BUSY_RS_ID);
assertThat(elapsed)
.as("the shutdown waited out the grace period after the message had been written")
.isLessThan(DSRSShutdownSync.REPLICA_OFFLINE_GRACE_PERIOD);
}
finally
{
// Closing the peer releases a session thread held inside a write, and the shutdown with it.
closeQuietly(peer);
awaitQuietly(shutdown);
stop(broker);
removeQuietly(replicationServer);
executor.shutdownNow();
}
}
/**
* Only a peer replication server learning about the offline replica ends the wait, and a
* directory server is never told. ReplicationServerDomain.put() never queues a
* ReplicaOfflineMsg for a directory server, and one which reaches the queue of its handler
* all the same - the changelog cursor of a directory server which is catching up synthesizes
* one from the offline CSN of the replica - is dropped by the handler before its writer is
* given it (issue #1029): the directory server is not sent it, nothing reports a forward for
* it, and the peer replication servers still know nothing.
*/
@Test
public void theDirectoryServerIsNeitherSentTheMessageNorEndsTheWait() throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
final DSRSShutdownSync shutdownSync = new DSRSShutdownSync();
ReplicationServer replicationServer = null;
ReplicationBroker broker = null;
try (ServerSocket listen = TestCaseUtils.bindFreePort())
{
listen.setSoTimeout(SOCKET_TIMEOUT_MS);
final int replicationPort = TestCaseUtils.findFreePort();
replicationServer =
newReplicationServer(shutdownSync, "shutdownSyncDataServerForwardDb", 8227, replicationPort);
broker = openReplicationSession(baseDN, REMOTE_DS_ID, 100, replicationPort, 5000, EMPTY_DN_GENID);
final Session[] sessionPair = connectSessionPair(listen, getReplSessionSecurity());
try (Session remoteEnd = sessionPair[0];
Session session = sessionPair[1])
{
// a peer replication server, so that the shutdown does wait for the message: what this
// test pins is that the directory server receiving it is not what ends that wait
registerConnectedReplicationServer(replicationServer, baseDN, session);
final ReplicationServerDomain domain =
replicationServer.getReplicationServerDomain(baseDN, true);
final DataServerHandler dsHandler = waitForConnectedDirectoryServer(domain);
final CSNGenerator csns = new CSNGenerator(LOCAL_DS_ID, 0);
final CSN offlineCSN = csns.newCSN();
final long startTime = System.nanoTime();
shutdownSync.replicaOfflineMsgSent(baseDN, offlineCSN);
// the very message the shutdown waits for, queued the only way it can reach a directory
// server: put() never does this
dsHandler.add(new ReplicaOfflineMsg(offlineCSN));
// a change queued behind it: once the directory server holds this one, its handler is
// past the message
final DeleteMsg change = new DeleteMsg(DN.valueOf("uid=offline," + TEST_ROOT_DN_STRING),
csns.newCSN(), "offline-entry-uuid");
dsHandler.add(change);
assertThat(receiveUntil(broker, change.getCSN()))
.as("the directory server was sent the ReplicaOfflineMsg queued for it")
.noneMatch(ReplicaOfflineMsg.class::isInstance);
assertThat(elapsedMillis(startTime))
.as("the fixture must deliver the change well inside the grace period, otherwise "
+ "the wait asserted below cannot be told apart from a slow delivery")
.isLessThan(DSRSShutdownSync.REPLICA_OFFLINE_GRACE_PERIOD / 2);
replicationServer.shutdown();
final long elapsed = elapsedMillis(startTime);
assertThat(elapsed)
.as("the handler of a directory server ended the wait of the shutdown")
.isGreaterThanOrEqualTo(DSRSShutdownSync.REPLICA_OFFLINE_GRACE_PERIOD);
}
}
finally
{
stop(broker);
removeQuietly(replicationServer);
}
}
/**
* The grace period covers every peer replication server, not only the fastest of them. The
* message is queued for each of them and published by its own writer, and the shutdown clears
* the queue and closes the session of whoever has not published it yet: a peer whose writer is
* held back would be left unaware that the replica went offline, and its change number indexer
* would keep the medium consistency point pinned to the last change of that replica.
*/
@Test
public void theShutdownWaitsForEveryPeerToBeToldTheReplicaWentOffline() throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
final RecordingShutdownSync shutdownSync = new RecordingShutdownSync();
ReplicationServer replicationServer = null;
ReplicationBroker broker = null;
FakePeerReplicationServer peer = null;
FakePeerReplicationServer heldBackPeer = null;
Thread windowOpener = null;
try
{
final int replicationPort = TestCaseUtils.findFreePort();
replicationServer =
newReplicationServer(shutdownSync, "shutdownSyncEveryPeerDb", 8229, replicationPort);
broker =
openReplicationSession(baseDN, LOCAL_DS_ID, 100, replicationPort, 5000, EMPTY_DN_GENID);
peer = FakePeerReplicationServer.connected(
replicationPort, REMOTE_RS_ID, baseDN, EMPTY_DN_GENID, PEER_WINDOW);
heldBackPeer = FakePeerReplicationServer.connected(
replicationPort, HELD_BACK_RS_ID, baseDN, EMPTY_DN_GENID, HELD_BACK_PEER_WINDOW);
final ReplicationServerDomain domain =
replicationServer.getReplicationServerDomain(baseDN, true);
waitForConnectedReplicationServer(domain, REMOTE_RS_ID);
waitForConnectedReplicationServer(domain, HELD_BACK_RS_ID);
/*
* One change fills the send window of the held back peer: its writer publishes that one and
* then blocks on the permit of the next message, so the ReplicaOfflineMsg stays with it
* while its neighbour forwards the same message right away.
*/
final CSNGenerator csns = new CSNGenerator(LOCAL_DS_ID, 0);
final Future windowFiller = heldBackPeer.receive(DeleteMsg.class);
broker.publish(new DeleteMsg(DN.valueOf("uid=offline," + TEST_ROOT_DN_STRING),
csns.newCSN(), "offline-entry-uuid"));
assertThat(windowFiller.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS))
.as("the send window of the held back peer was never filled, its exchange ended "
+ "with: %s", heldBackPeer.failure())
.isNotNull();
final Future received = peer.receive(ReplicaOfflineMsg.class);
final Future receivedWhenHeldBack =
heldBackPeer.receive(ReplicaOfflineMsg.class);
final CSN offlineCSN = csns.newCSN();
shutdownSync.replicaOfflineMsgSent(baseDN, offlineCSN);
broker.publish(new ReplicaOfflineMsg(offlineCSN));
windowOpener = newWindowOpenerThread(heldBackPeer);
final long startTime = System.nanoTime();
windowOpener.start();
replicationServer.shutdown();
final long elapsed = elapsedMillis(startTime);
/*
* The barrier first, because it is the one the shutdown is made of and it cannot race:
* the wait ends when both writers have reported, or when the grace period runs out, and
* the duration below tells the two apart.
*/
assertThat(shutdownSync.forwardedBy())
.as("the wait ended on the first peer forwarding the message, without the writer of "
+ "the peer which was held back ever reporting one")
.contains(REMOTE_RS_ID, HELD_BACK_RS_ID);
assertThat(elapsed).isGreaterThanOrEqualTo(FORWARD_DELAY)
.isLessThan(DSRSShutdownSync.REPLICA_OFFLINE_GRACE_PERIOD);
assertThat(received.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS))
.as("the peer which was not held back never received the message, its read ended "
+ "with: %s", peer.failure())
.isNotNull();
/*
* The forward asserted above proves the message was written to the socket of the peer: the
* writer reports it from the callback of Session.publish(), which runs only once the write
* has returned, whether the thread of the session wrote it or the close sent it out of the
* queue. If this is the only assertion which fails, the read of the peer is where to look
* before the granularity of the barrier.
*/
assertThat(receivedWhenHeldBack.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS))
.as("the peer which was held back never learned that the replica went offline, "
+ "although its writer reported the forward, its exchange ended with: %s",
heldBackPeer.failure())
.isNotNull();
}
finally
{
joinQuietly(windowOpener);
closeQuietly(heldBackPeer);
closeQuietly(peer);
stop(broker);
removeQuietly(replicationServer);
}
}
/**
* A message its writer drops on the way out will never be forwarded, so the shutdown must stop
* waiting for the peer it was queued for. The filter of the writer is wider than the one
* ReplicationServerDomain.put() applies when it queues the message - it drops anything for a
* peer whose generation id is unknown as well - so a peer can be given a message which is then
* dropped, and nothing would ever report a forward for it.
*/
@Test
public void theShutdownStopsWaitingForAPeerWhoseMessageTheWriterDropped() throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
final RecordingShutdownSync shutdownSync = new RecordingShutdownSync();
ReplicationServer replicationServer = null;
ReplicationBroker broker = null;
FakePeerReplicationServer peer = null;
try
{
final int replicationPort = TestCaseUtils.findFreePort();
replicationServer =
newReplicationServer(shutdownSync, "shutdownSyncDroppedMsgDb", 8230, replicationPort);
broker =
openReplicationSession(baseDN, LOCAL_DS_ID, 100, replicationPort, 5000, EMPTY_DN_GENID);
peer = FakePeerReplicationServer.connected(
replicationPort, REMOTE_RS_ID, baseDN, EMPTY_DN_GENID, HELD_BACK_PEER_WINDOW);
final ReplicationServerDomain domain =
replicationServer.getReplicationServerDomain(baseDN, true);
waitForConnectedReplicationServer(domain, REMOTE_RS_ID);
final ReplicationServerHandler rsHandler = domain.getConnectedRSs().get(REMOTE_RS_ID);
/*
* One change fills the send window of the peer, so the message which follows stays with
* its writer until the window is opened again. The writer takes the message off the queue
* before it blocks on the permit and evaluates its filter only once it has it, which is
* what makes the generation id below take effect on a message already queued.
*/
final CSNGenerator csns = new CSNGenerator(LOCAL_DS_ID, 0);
final Future windowFiller = peer.receive(DeleteMsg.class);
broker.publish(new DeleteMsg(DN.valueOf("uid=offline," + TEST_ROOT_DN_STRING),
csns.newCSN(), "offline-entry-uuid"));
assertThat(windowFiller.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS))
.as("the send window of the peer was never filled, its exchange ended with: %s",
peer.failure())
.isNotNull();
final CSN offlineCSN = csns.newCSN();
shutdownSync.replicaOfflineMsgSent(baseDN, offlineCSN);
broker.publish(new ReplicaOfflineMsg(offlineCSN));
shutdownSync.awaitDispatch();
assertThat(shutdownSync.dispatchedTo())
.as("the message was never queued for the peer, so its writer has nothing to drop")
.contains(REMOTE_RS_ID);
// the peer no longer shares the generation id of the domain, so its writer drops what was
// queued for it before that - a filter wider than the one put() applied
rsHandler.setGenerationId(domain.getGenerationId() + 1);
peer.openSendWindow(PEER_WINDOW);
awaitGiveUpOn(shutdownSync, REMOTE_RS_ID,
"the writer dropped the message without telling the shutdown to stop waiting for the "
+ "peer it was queued for");
final long startTime = System.nanoTime();
replicationServer.shutdown();
final long elapsed = elapsedMillis(startTime);
assertThat(elapsed)
.as("the shutdown kept waiting for a forward its own writer had already dropped")
.isLessThan(DSRSShutdownSync.REPLICA_OFFLINE_GRACE_PERIOD);
}
finally
{
closeQuietly(peer);
stop(broker);
removeQuietly(replicationServer);
}
}
/**
* A peer whose protocol version has no encoding for the ReplicaOfflineMsg cannot be told that
* the replica went offline - it predates the message, and has nothing to do with it - and
* nothing will ever report a forward to it: the writer drops the message before the session is
* given it (issue #1014), and must strike the peer off rather than let the shutdown wait out the
* grace period for it.
*/
@Test
public void theShutdownStopsWaitingForAPeerWhoseProtocolCannotCarryTheMessage() throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
final RecordingShutdownSync shutdownSync = new RecordingShutdownSync();
ReplicationServer replicationServer = null;
ReplicationBroker broker = null;
FakePeerReplicationServer peer = null;
try
{
final int replicationPort = TestCaseUtils.findFreePort();
replicationServer = newReplicationServer(
shutdownSync, "shutdownSyncLegacyProtocolDb", 8239, replicationPort);
broker =
openReplicationSession(baseDN, LOCAL_DS_ID, 100, replicationPort, 5000, EMPTY_DN_GENID);
peer = FakePeerReplicationServer.connected(replicationPort, LEGACY_RS_ID, baseDN, EMPTY_DN_GENID,
PEER_WINDOW, ProtocolVersion.REPLICATION_PROTOCOL_V7);
final ReplicationServerDomain domain =
replicationServer.getReplicationServerDomain(baseDN, true);
waitForConnectedReplicationServer(domain, LEGACY_RS_ID);
final CSN offlineCSN = newOfflineCSN();
shutdownSync.replicaOfflineMsgSent(baseDN, offlineCSN);
broker.publish(new ReplicaOfflineMsg(offlineCSN));
shutdownSync.awaitDispatch();
awaitGiveUpOn(shutdownSync, LEGACY_RS_ID,
"the writer let the shutdown wait for a peer whose protocol cannot carry the message");
final long startTime = System.nanoTime();
replicationServer.shutdown();
final long elapsed = elapsedMillis(startTime);
assertThat(shutdownSync.dispatchedTo())
.as("the message was not queued for the peer, so this test never reproduced the "
+ "drop it is about")
.contains(LEGACY_RS_ID);
assertThat(shutdownSync.forwardedBy())
.as("a message the peer cannot decode was reported forwarded to it")
.doesNotContain(LEGACY_RS_ID);
assertThat(elapsed)
.as("the shutdown waited for a forward to a peer whose protocol cannot carry the message")
.isLessThan(DSRSShutdownSync.REPLICA_OFFLINE_GRACE_PERIOD);
}
finally
{
closeQuietly(peer);
stop(broker);
removeQuietly(replicationServer);
}
}
/**
* A peer whose handshake is aborted while the message is being pushed must not be waited for.
*
* put() reads the peers of the domain, records them as the recipients of the message and only
* then queues it for each of them. unregisterFailedHandshake() runs on the handshake thread
* and takes no domain lock, so it can land in between: its own give-up then finds nothing
* recorded yet and does nothing. Nothing else would ever strike that peer off - the reader and
* writer threads whose death reaches stopServer() were never started for a handshake which was
* aborted - so the shutdown waits out its whole grace period for a forward which cannot come.
*/
@Test
public void theShutdownStopsWaitingForAPeerWhoseHandshakeWasAborted() throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
final RecordingShutdownSync shutdownSync = new RecordingShutdownSync();
ReplicationServer replicationServer = null;
ReplicationBroker broker = null;
FakePeerReplicationServer peer = null;
try (ServerSocket listen = TestCaseUtils.bindFreePort())
{
listen.setSoTimeout(SOCKET_TIMEOUT_MS);
final int replicationPort = TestCaseUtils.findFreePort();
replicationServer = newReplicationServer(
shutdownSync, "shutdownSyncAbortedHandshakeDb", 8231, replicationPort);
broker =
openReplicationSession(baseDN, LOCAL_DS_ID, 100, replicationPort, 5000, EMPTY_DN_GENID);
peer = FakePeerReplicationServer.connected(
replicationPort, REMOTE_RS_ID, baseDN, EMPTY_DN_GENID);
final ReplicationServerDomain domain =
replicationServer.getReplicationServerDomain(baseDN, true);
waitForConnectedReplicationServer(domain, REMOTE_RS_ID);
final Session[] sessionPair = connectSessionPair(listen, getReplSessionSecurity());
try (Session remoteEnd = sessionPair[0];
Session session = sessionPair[1])
{
// a second peer, registered as a handshake does just before it fails
final ReplicationServerHandler aborting = registerConnectedReplicationServer(
replicationServer, baseDN, session, ABORTED_RS_ID);
aborting.setGenerationId(domain.getGenerationId());
shutdownSync.runWhileDispatching(new Runnable()
{
@Override
public void run()
{
domain.unregisterFailedHandshake(aborting);
}
});
final Future received = peer.receive(ReplicaOfflineMsg.class);
final CSN offlineCSN = newOfflineCSN();
shutdownSync.replicaOfflineMsgSent(baseDN, offlineCSN);
broker.publish(new ReplicaOfflineMsg(offlineCSN));
shutdownSync.awaitDispatch();
final long startTime = System.nanoTime();
replicationServer.shutdown();
final long elapsed = elapsedMillis(startTime);
assertThat(shutdownSync.dispatchedTo())
.as("the peer whose handshake was aborted was not recorded among the recipients, so "
+ "this test never reproduced the window it is about")
.contains(REMOTE_RS_ID, ABORTED_RS_ID);
assertThat(elapsed)
.as("the shutdown waited for a peer whose handshake had been aborted, and which "
+ "nothing else will ever strike off")
.isLessThan(DSRSShutdownSync.REPLICA_OFFLINE_GRACE_PERIOD);
assertThat(received.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS))
.as("the peer which was still connected never learned that the replica went "
+ "offline, its read ended with: %s", peer.failure())
.isNotNull();
}
}
finally
{
closeQuietly(peer);
stop(broker);
removeQuietly(replicationServer);
}
}
/**
* A peer which disconnects during the grace period can no longer forward what it was given -
* its session is closed under its writer - so stopServer() must strike it off rather than let
* the shutdown wait out the rest of its window for a peer which is already gone.
*/
@Test
public void theShutdownStopsWaitingForAPeerWhichDisconnected() throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
final RecordingShutdownSync shutdownSync = new RecordingShutdownSync();
ReplicationServer replicationServer = null;
ReplicationBroker broker = null;
FakePeerReplicationServer peer = null;
FakePeerReplicationServer heldBackPeer = null;
try
{
final int replicationPort = TestCaseUtils.findFreePort();
replicationServer = newReplicationServer(
shutdownSync, "shutdownSyncDisconnectedPeerDb", 8232, replicationPort);
broker =
openReplicationSession(baseDN, LOCAL_DS_ID, 100, replicationPort, 5000, EMPTY_DN_GENID);
peer = FakePeerReplicationServer.connected(
replicationPort, REMOTE_RS_ID, baseDN, EMPTY_DN_GENID, PEER_WINDOW);
heldBackPeer = FakePeerReplicationServer.connected(
replicationPort, HELD_BACK_RS_ID, baseDN, EMPTY_DN_GENID, HELD_BACK_PEER_WINDOW);
final ReplicationServerDomain domain =
replicationServer.getReplicationServerDomain(baseDN, true);
waitForConnectedReplicationServer(domain, REMOTE_RS_ID);
waitForConnectedReplicationServer(domain, HELD_BACK_RS_ID);
// the peer which disconnects is held back by a full send window, so that it cannot have
// forwarded the message before it goes: what ends the wait must be the give-up
final CSNGenerator csns = new CSNGenerator(LOCAL_DS_ID, 0);
final Future windowFiller = heldBackPeer.receive(DeleteMsg.class);
broker.publish(new DeleteMsg(DN.valueOf("uid=offline," + TEST_ROOT_DN_STRING),
csns.newCSN(), "offline-entry-uuid"));
assertThat(windowFiller.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS))
.as("the send window of the held back peer was never filled, its exchange ended "
+ "with: %s", heldBackPeer.failure())
.isNotNull();
final Future received = peer.receive(ReplicaOfflineMsg.class);
final CSN offlineCSN = csns.newCSN();
shutdownSync.replicaOfflineMsgSent(baseDN, offlineCSN);
broker.publish(new ReplicaOfflineMsg(offlineCSN));
shutdownSync.awaitDispatch();
heldBackPeer.close();
final long startTime = System.nanoTime();
replicationServer.shutdown();
final long elapsed = elapsedMillis(startTime);
assertThat(shutdownSync.dispatchedTo())
.as("the message was not queued for the peer which then disconnected, so this test "
+ "never reproduced what it is about")
.contains(REMOTE_RS_ID, HELD_BACK_RS_ID);
assertThat(elapsed)
.as("the shutdown kept waiting for a forward from a peer which had disconnected")
.isLessThan(DSRSShutdownSync.REPLICA_OFFLINE_GRACE_PERIOD);
assertThat(received.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS))
.as("the peer which stayed connected never received the message, its read ended "
+ "with: %s", peer.failure())
.isNotNull();
}
finally
{
closeQuietly(heldBackPeer);
closeQuietly(peer);
stop(broker);
removeQuietly(replicationServer);
}
}
/**
* A peer which does not share the generation id of the domain is not given the message, so it
* must not be recorded among the peers the shutdown waits for. The caller side check on
* getConnectedRSs() does not cover this: such a peer is connected, and would make the domain
* spend its grace period on a message it was never queued.
*/
@Test
public void theMessageIsNotQueuedForAPeerWhoseGenerationIdDiffers() throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
final RecordingShutdownSync shutdownSync = new RecordingShutdownSync();
ReplicationServer replicationServer = null;
ReplicationBroker broker = null;
FakePeerReplicationServer peer = null;
try
{
final int replicationPort = TestCaseUtils.findFreePort();
replicationServer = newReplicationServer(
shutdownSync, "shutdownSyncOtherGenerationIdDb", 8233, replicationPort);
broker =
openReplicationSession(baseDN, LOCAL_DS_ID, 100, replicationPort, 5000, EMPTY_DN_GENID);
peer = FakePeerReplicationServer.connected(
replicationPort, REMOTE_RS_ID, baseDN, EMPTY_DN_GENID);
final ReplicationServerDomain domain =
replicationServer.getReplicationServerDomain(baseDN, true);
waitForConnectedReplicationServer(domain, REMOTE_RS_ID);
domain.getConnectedRSs().get(REMOTE_RS_ID).setGenerationId(domain.getGenerationId() + 1);
final CSN offlineCSN = newOfflineCSN();
shutdownSync.replicaOfflineMsgSent(baseDN, offlineCSN);
broker.publish(new ReplicaOfflineMsg(offlineCSN));
shutdownSync.awaitDispatch();
final long startTime = System.nanoTime();
replicationServer.shutdown();
final long elapsed = elapsedMillis(startTime);
assertThat(shutdownSync.dispatchedTo())
.as("the message was recorded as queued for a peer which does not share the "
+ "generation id of the domain, and which it was never queued for")
.isEmpty();
assertThat(elapsed)
.as("the shutdown waited for a peer the message was not queued for")
.isLessThan(DSRSShutdownSync.REPLICA_OFFLINE_GRACE_PERIOD);
}
finally
{
closeQuietly(peer);
stop(broker);
removeQuietly(replicationServer);
}
}
/**
* With no other replication server connected there is nobody to forward the message to, so
* waiting would only delay the shutdown of a standalone server by the whole grace period.
*/
@Test
public void shutdownIsNotDelayedWhenNoOtherReplicationServerCanForwardTheMessage() throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
final DSRSShutdownSync shutdownSync = new DSRSShutdownSync();
ReplicationServer replicationServer = null;
try
{
replicationServer = newReplicationServer(shutdownSync, "shutdownSyncAloneDb", 8223);
replicationServer.getReplicationServerDomain(baseDN, true);
final long startTime = System.nanoTime();
shutdownSync.replicaOfflineMsgSent(baseDN, newOfflineCSN());
replicationServer.shutdown();
final long elapsed = elapsedMillis(startTime);
assertThat(elapsed).isLessThan(DSRSShutdownSync.REPLICA_OFFLINE_GRACE_PERIOD);
}
finally
{
removeQuietly(replicationServer);
}
}
/**
* A peer replication server which cannot decode the ReplicaOfflineMsg is nobody to forward it
* to either: the message has no encoding for the protocol version that peer negotiated, so no
* writer can ever report a forward for it and waiting would only delay the shutdown by the
* whole grace period.
*/
@Test
public void shutdownIsNotDelayedWhenNoConnectedPeerCanDecodeTheMessage() throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
final DSRSShutdownSync shutdownSync = new DSRSShutdownSync();
ReplicationServer replicationServer = null;
try (ServerSocket listen = TestCaseUtils.bindFreePort())
{
listen.setSoTimeout(SOCKET_TIMEOUT_MS);
replicationServer = newReplicationServer(shutdownSync, "shutdownSyncOldPeerDb", 8236);
final Session[] sessionPair = connectSessionPair(listen, getReplSessionSecurity());
try (Session remoteEnd = sessionPair[0];
Session session = sessionPair[1])
{
session.setProtocolVersion(ProtocolVersion.REPLICATION_PROTOCOL_V7);
registerConnectedReplicationServer(replicationServer, baseDN, session);
final long startTime = System.nanoTime();
shutdownSync.replicaOfflineMsgSent(baseDN, newOfflineCSN());
replicationServer.shutdown();
final long elapsed = elapsedMillis(startTime);
assertThat(elapsed)
.as("the shutdown waited for a peer which cannot decode the message")
.isLessThan(DSRSShutdownSync.REPLICA_OFFLINE_GRACE_PERIOD);
}
}
finally
{
removeQuietly(replicationServer);
}
}
/**
* A peer which cannot decode the message says nothing about the peers which can: a topology
* where one of the connected peers still speaks a protocol version without the
* ReplicaOfflineMsg is waited for, for the sake of the peers which do get it.
*
* What decides is whether any connected peer can be told, not which handler is
* iterated first - {@code connectedRSs} is a ConcurrentHashMap, so the order the two peers
* below are registered in is not the order they are read in. This case asserts the wait
* rather than the peer which caused it for that reason.
*/
@Test
public void shutdownWaitsWhenOnlySomeOfTheConnectedPeersCanDecodeTheMessage() throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
final DSRSShutdownSync shutdownSync = new DSRSShutdownSync();
ReplicationServer replicationServer = null;
try (ServerSocket oldPeerListen = TestCaseUtils.bindFreePort();
ServerSocket currentPeerListen = TestCaseUtils.bindFreePort())
{
oldPeerListen.setSoTimeout(SOCKET_TIMEOUT_MS);
currentPeerListen.setSoTimeout(SOCKET_TIMEOUT_MS);
replicationServer = newReplicationServer(shutdownSync, "shutdownSyncMixedPeersDb", 8237);
final Session[] oldPeerPair = connectSessionPair(oldPeerListen, getReplSessionSecurity());
final Session[] currentPeerPair =
connectSessionPair(currentPeerListen, getReplSessionSecurity());
try (Session oldPeerRemoteEnd = oldPeerPair[0];
Session oldPeerSession = oldPeerPair[1];
Session currentPeerRemoteEnd = currentPeerPair[0];
Session currentPeerSession = currentPeerPair[1])
{
oldPeerSession.setProtocolVersion(ProtocolVersion.REPLICATION_PROTOCOL_V7);
currentPeerSession.setProtocolVersion(ProtocolVersion.getCurrentVersion());
registerConnectedReplicationServer(
replicationServer, baseDN, oldPeerSession, OLD_PEER_RS_ID);
registerConnectedReplicationServer(
replicationServer, baseDN, currentPeerSession, REMOTE_RS_ID);
final long startTime = System.nanoTime();
shutdownSync.replicaOfflineMsgSent(baseDN, newOfflineCSN());
replicationServer.shutdown();
final long elapsed = elapsedMillis(startTime);
assertThat(elapsed)
.as("the shutdown stopped waiting although a connected peer can still be told that "
+ "the replica went offline")
.isGreaterThanOrEqualTo(DSRSShutdownSync.REPLICA_OFFLINE_GRACE_PERIOD);
}
}
finally
{
removeQuietly(replicationServer);
}
}
/**
* The writer serving a directory server must not hold back the shutdown either: it used to
* loop on the pending message until the grace period expired, although its handler had already
* been shut down - which deactivates its consumer and leaves the loop nothing to take.
*/
@Test
public void shutdownIsNotDelayedByTheWriterServingADirectoryServer() throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
final DSRSShutdownSync shutdownSync = new DSRSShutdownSync();
ReplicationServer replicationServer = null;
ReplicationBroker broker = null;
try
{
final int replicationPort = TestCaseUtils.findFreePort();
replicationServer =
newReplicationServer(shutdownSync, "shutdownSyncDataServerDb", 8225, replicationPort);
broker = openReplicationSession(baseDN, REMOTE_DS_ID, 100, replicationPort, 5000, EMPTY_DN_GENID);
// the writer this test is about exists only once the handshake of the directory server is
// over, and the shutdown below would otherwise be free to abort that handshake instead
waitForConnectedDirectoryServer(replicationServer.getReplicationServerDomain(baseDN, true));
final long startTime = System.nanoTime();
shutdownSync.replicaOfflineMsgSent(baseDN, newOfflineCSN());
replicationServer.shutdown();
final long elapsed = elapsedMillis(startTime);
assertThat(elapsed).isLessThan(DSRSShutdownSync.REPLICA_OFFLINE_GRACE_PERIOD);
}
finally
{
stop(broker);
removeQuietly(replicationServer);
}
}
@Test
public void shutdownIsNotDelayedWhenNoReplicaOfflineMsgIsPending() throws Exception
{
final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
final DSRSShutdownSync shutdownSync = new DSRSShutdownSync();
ReplicationServer replicationServer = null;
try (ServerSocket listen = TestCaseUtils.bindFreePort())
{
listen.setSoTimeout(SOCKET_TIMEOUT_MS);
replicationServer = newReplicationServer(shutdownSync, "shutdownSyncNoMsgDb", 8224);
final Session[] sessionPair = connectSessionPair(listen, getReplSessionSecurity());
try (Session remoteEnd = sessionPair[0];
Session session = sessionPair[1])
{
registerConnectedReplicationServer(replicationServer, baseDN, session);
final long startTime = System.nanoTime();
replicationServer.shutdown();
final long elapsed = elapsedMillis(startTime);
assertThat(elapsed).isLessThan(DSRSShutdownSync.REPLICA_OFFLINE_GRACE_PERIOD);
}
}
finally
{
removeQuietly(replicationServer);
}
}
/**
* The domains of a replication server are shut down one after the other, so the grace period
* must bound the whole shutdown and not each of its domains: a process with several base DNs
* would otherwise pay it once per domain.
*
* Both domains keep announcing themselves offline while the shutdown is running, so neither
* wait can be ended by a forward and each of them runs to its bound - one grace period in
* total if it is shared, one per domain otherwise.
*/
@Test
public void theGracePeriodIsSharedByAllTheDomainsOfOneShutdown() throws Exception
{
final DN baseDN1 = DN.valueOf(TEST_ROOT_DN_STRING);
final DN baseDN2 = DN.valueOf("dc=world,dc=company");
final DSRSShutdownSync shutdownSync = new DSRSShutdownSync();
final AtomicBoolean stopped = new AtomicBoolean();
ReplicationServer replicationServer = null;
Thread reAnnouncer = null;
try (ServerSocket listen1 = TestCaseUtils.bindFreePort();
ServerSocket listen2 = TestCaseUtils.bindFreePort())
{
listen1.setSoTimeout(SOCKET_TIMEOUT_MS);
listen2.setSoTimeout(SOCKET_TIMEOUT_MS);
replicationServer = newReplicationServer(shutdownSync, "shutdownSyncSharedDeadlineDb", 8228);
final Session[] sessionPair1 = connectSessionPair(listen1, getReplSessionSecurity());
final Session[] sessionPair2 = connectSessionPair(listen2, getReplSessionSecurity());
try (Session remoteEnd1 = sessionPair1[0];
Session session1 = sessionPair1[1];
Session remoteEnd2 = sessionPair2[0];
Session session2 = sessionPair2[1])
{
registerConnectedReplicationServer(replicationServer, baseDN1, session1);
registerConnectedReplicationServer(replicationServer, baseDN2, session2);
/*
* Announce both domains offline here rather than leaving it to the thread below: the
* wait of the shutdown must be armed whatever that thread has had time to run.
*/
final CSNGenerator csns = new CSNGenerator(LOCAL_DS_ID, 0);
shutdownSync.replicaOfflineMsgSent(baseDN1, csns.newCSN());
shutdownSync.replicaOfflineMsgSent(baseDN2, csns.newCSN());
reAnnouncer = newReAnnouncerThread(shutdownSync, baseDN1, baseDN2, stopped);
reAnnouncer.start();
final long startTime = System.nanoTime();
replicationServer.shutdown();
final long elapsed = elapsedMillis(startTime);
assertThat(elapsed).isGreaterThanOrEqualTo(DSRSShutdownSync.REPLICA_OFFLINE_GRACE_PERIOD);
assertThat(elapsed)
.as("each domain waited its own grace period instead of sharing one deadline")
.isLessThan(2 * DSRSShutdownSync.REPLICA_OFFLINE_GRACE_PERIOD);
}
}
finally
{
stopped.set(true);
joinQuietly(reAnnouncer);
removeQuietly(replicationServer);
}
}
@Test
public void undeliveredDirectUpdatesShareOneDeadlineAcrossDomains() throws Exception
{
final DN baseDN1 = DN.valueOf(TEST_ROOT_DN_STRING);
final DN baseDN2 = DN.valueOf("dc=world,dc=company");
final List brokers = new ArrayList<>();
final List peers = new ArrayList<>();
final int port = TestCaseUtils.findFreePort();
final ReplicationServer server = newReplicationServer(
new DSRSShutdownSync(), "directUpdatesSharedDeadlineDb", 8262, port);
try
{
for (DN baseDN : Arrays.asList(baseDN1, baseDN2))
{
final ReplicationBroker broker =
openReplicationSession(baseDN, REMOTE_DS_ID, 100, port, 5000, EMPTY_DN_GENID);
brokers.add(broker);
final FakePeerReplicationServer peer = FakePeerReplicationServer.connected(
port, REMOTE_RS_ID, baseDN, EMPTY_DN_GENID, HELD_BACK_PEER_WINDOW);
peers.add(peer);
final ReplicationServerDomain domain = server.getReplicationServerDomain(baseDN, true);
waitForConnectedReplicationServer(domain, REMOTE_RS_ID);
final Future windowFiller = peer.receive(DeleteMsg.class);
final CSNGenerator csns = new CSNGenerator(REMOTE_DS_ID, 0);
broker.publish(new DeleteMsg(DN.valueOf("uid=first," + baseDN), csns.newCSN(),
"11111111-1111-1111-1111-111111111111"));
assertThat(windowFiller.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isNotNull();
final CSN blockedCSN = csns.newCSN();
broker.publish(new DeleteMsg(DN.valueOf("uid=blocked," + baseDN), blockedCSN,
"22222222-2222-2222-2222-222222222222"));
newConnectionTimer().repeatUntilSuccess(() ->
assertThat(domain.getLatestServerState().getCSN(REMOTE_DS_ID)).isEqualTo(blockedCSN));
}
final long budgetMillis = 2000;
final List records = errorLogRecordsOf(() -> {
final long start = System.nanoTime();
server.awaitDirectUpdatesForwarded(TimeUnit.MILLISECONDS.toNanos(budgetMillis));
assertThat(elapsedMillis(start))
.as("both domains share one deadline")
.isBetween(budgetMillis, budgetMillis + 1500);
return null;
});
for (DN baseDN : Arrays.asList(baseDN1, baseDN2))
{
final String warning = "RS shutdown could not forward all direct DS updates for "
+ baseDN + " to RS " + REMOTE_RS_ID + ";";
assertThat(records.stream().filter(line -> line.contains(warning)).count()).isEqualTo(1);
}
}
finally
{
peers.forEach(this::closeQuietly);
brokers.forEach(this::stop);
removeQuietly(server);
}
}
private ReplicationServer newReplicationServer(DSRSShutdownSync shutdownSync, String dbDirName,
int serverId) throws Exception
{
return newReplicationServer(shutdownSync, dbDirName, serverId, TestCaseUtils.findFreePort());
}
private ReplicationServer newReplicationServer(DSRSShutdownSync shutdownSync, String dbDirName,
int serverId, int replicationPort) throws Exception
{
return new ReplicationServer(new ReplServerFakeConfiguration(
replicationPort, dbDirName, 0, serverId, 0, 100, new TreeSet()), shutdownSync);
}
/**
* Registers a peer replication server on the domain as the handshake does, but without the
* protocol exchange: the handler this leaves behind has no writer, which is enough for the
* tests which only need a domain with a connected peer.
*/
private ReplicationServerHandler registerConnectedReplicationServer(
ReplicationServer replicationServer, DN baseDN, Session session) throws Exception
{
return registerConnectedReplicationServer(replicationServer, baseDN, session, REMOTE_RS_ID);
}
private ReplicationServerHandler registerConnectedReplicationServer(
ReplicationServer replicationServer, DN baseDN, Session session, int serverId)
throws Exception
{
final ReplicationServerDomain domain = replicationServer.getReplicationServerDomain(baseDN, true);
final ReplicationServerHandler rsHandler =
new ReplicationServerHandler(session, 100, replicationServer, 100);
registerConnectedReplicationServer(domain, baseDN, rsHandler, serverId);
return rsHandler;
}
private void registerConnectedReplicationServer(ReplicationServerDomain domain, DN baseDN,
ReplicationServerHandler rsHandler, int serverId) throws Exception
{
rsHandler.serverId = serverId;
rsHandler.serverURL = "127.0.0.1:1636";
rsHandler.setBaseDNAndDomain(baseDN, false);
domain.lock();
try
{
domain.register(rsHandler);
}
finally
{
domain.release();
}
}
/** Waits for the barrier to have been told that this peer will not forward the message. */
private void awaitGiveUpOn(final RecordingShutdownSync shutdownSync, final int serverId,
final String reason) throws Exception
{
new TestTimer.Builder()
.maxSleep(WRITER_REACTION_TIMEOUT_MS, TimeUnit.MILLISECONDS)
.sleepTimes(10, TimeUnit.MILLISECONDS)
.toTimer()
.repeatUntilSuccess(new TestTimer.CallableVoid()
{
@Override
public void call() throws Exception
{
assertThat(shutdownSync.gaveUpOn()).as(reason).contains(serverId);
}
});
}
/**
* Waits for the peer replication server to be connected and for its handshake to be
* over.
*
* The registration is not the end of the handshake: {@code startFromRemoteRS()} puts the
* handler in {@code connectedRSs} before it calls {@code finalizeStart()}, which is what
* starts the reader and the writer, and the whole handshake runs in the listen thread of the
* replication server. {@link ReplicationServer#shutdown()} interrupts that thread once it is
* done waiting for the ReplicaOfflineMsgs, so a handshake which is still in
* {@code Session.waitForStartup()} by then is aborted: the session is closed and the handler
* unregistered, and the peer is gone before the message could be queued for it, let alone
* forwarded. Issue #821 recorded that same window, from the dead handler it used to leave
* behind; {@link #thePeerWhoseHandshakeIsInFlightIsStillToldTheReplicaWentOffline()} pins the
* part of it the wait now covers, and
* {@link #thePeerWhoseHandshakeCompletesAfterTheShutdownIsStoppedNotServed()} the part the
* shutdown still aborts.
*
* The listen thread serves one handshake at a time, so a peer which is past that window also
* puts every connection accepted before it - the collocated directory server of these tests
* among them - past it.
*/
private void waitForConnectedReplicationServer(
final ReplicationServerDomain domain, final int serverId) throws Exception
{
newConnectionTimer().repeatUntilSuccess(new TestTimer.CallableVoid()
{
@Override
public void call() throws Exception
{
final ReplicationServerHandler rsHandler = domain.getConnectedRSs().get(serverId);
assertThat(rsHandler)
.as("the peer replication server %s never connected", serverId).isNotNull();
assertThat(handshakeIsOver(rsHandler))
.as("the handshake of the peer replication server %s never finished", serverId)
.isTrue();
}
});
}
/**
* Waits for the handler of the peer to be served from its in-memory queue rather than from the
* changelog.
*
* A freshly connected peer is behind by definition, and a handler which is catching up reads
* its updates from the changelog, where {@code ReplicaCursor} synthesizes a
* {@link ReplicaOfflineMsg} from the offline CSN of the replica - on top of the copy
* {@code ReplicationServerDomain.put()} queues for it, and again on every refill of its late
* queue, since an offline CSN never enters the state of a handler. How many copies of one
* announcement its writer takes is then a race, which is a race on how many times the writer
* reports the drop.
*/
private void waitForFollowing(final ReplicationServerDomain domain, final int serverId)
throws Exception
{
newConnectionTimer().repeatUntilSuccess(new TestTimer.CallableVoid()
{
@Override
public void call() throws Exception
{
final ReplicationServerHandler rsHandler = domain.getConnectedRSs().get(serverId);
assertThat(rsHandler)
.as("the peer replication server %s is no longer connected", serverId).isNotNull();
assertThat(rsHandler.isFollowing())
.as("the peer replication server %s is still catching up from the changelog",
serverId)
.isTrue();
}
});
}
/**
* Waits for the collocated directory server to be connected and for its handshake to be over -
* {@link #waitForConnectedReplicationServer(ReplicationServerDomain, int)} says what the
* registration alone leaves open.
*/
private DataServerHandler waitForConnectedDirectoryServer(final ReplicationServerDomain domain)
throws Exception
{
return newConnectionTimer().repeatUntilSuccess(new Callable()
{
@Override
public DataServerHandler call() throws Exception
{
final DataServerHandler dsHandler = domain.getConnectedDSs().get(REMOTE_DS_ID);
assertThat(dsHandler).as("the directory server never connected").isNotNull();
assertThat(handshakeIsOver(dsHandler))
.as("the handshake of the directory server never finished").isTrue();
return dsHandler;
}
});
}
/**
* Whether the handshake of the handler is over, so that the interrupt
* {@link ReplicationServer#shutdown()} sends to its listen thread can no longer abort it:
* {@code ServerHandler.finalizeStart()} registers the handler as a monitor provider by its
* last statement, after the reader and the writer have been started.
*/
private static boolean handshakeIsOver(ServerHandler handler)
{
return DirectoryServer.getMonitorProviders().containsValue(handler);
}
private static TestTimer newConnectionTimer()
{
return new TestTimer.Builder()
.maxSleep(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS)
.sleepTimes(10, TimeUnit.MILLISECONDS)
.toTimer();
}
private Thread newShutdownThread(final ReplicationServer replicationServer)
{
return new Thread(new Runnable()
{
@Override
public void run()
{
replicationServer.shutdown();
}
}, "ReplicationServerShutdownSyncTest shutdown");
}
private Thread newForwarderThread(final DSRSShutdownSync shutdownSync, final DN baseDN,
final CSN offlineCSN)
{
return new Thread(new Runnable()
{
@Override
public void run()
{
if (!sleepQuietly(FORWARD_DELAY))
{
return;
}
shutdownSync.replicaOfflineMsgForwarded(baseDN, offlineCSN, new ForwardingPeer(REMOTE_RS_ID));
}
});
}
private Thread newPublisherThread(final ReplicationBroker broker, final CSN offlineCSN)
{
return new Thread(new Runnable()
{
@Override
public void run()
{
if (!sleepQuietly(FORWARD_DELAY))
{
return;
}
broker.publish(new ReplicaOfflineMsg(offlineCSN));
}
});
}
/**
* Gives the held back peer credit to receive again, once the shutdown has had time to end on
* the forward of the peer which was not held back.
*/
private Thread newWindowOpenerThread(final FakePeerReplicationServer heldBackPeer)
{
return new Thread(new Runnable()
{
@Override
public void run()
{
if (!sleepQuietly(FORWARD_DELAY))
{
return;
}
heldBackPeer.openSendWindow(PEER_WINDOW);
}
});
}
private Thread newReAnnouncerThread(final DSRSShutdownSync shutdownSync, final DN baseDN1,
final DN baseDN2, final AtomicBoolean stopped)
{
return new Thread(new Runnable()
{
@Override
public void run()
{
final CSNGenerator csns = new CSNGenerator(LOCAL_DS_ID, 0);
while (!stopped.get())
{
shutdownSync.replicaOfflineMsgSent(baseDN1, csns.newCSN());
shutdownSync.replicaOfflineMsgSent(baseDN2, csns.newCSN());
if (!sleepQuietly(REANNOUNCE_INTERVAL))
{
return;
}
}
}
});
}
/** Milliseconds elapsed since a {@link System#nanoTime()} reading, the clock the waits use. */
private static long elapsedMillis(long startTime)
{
return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);
}
/** The last message a peer read, null if it read none at all. */
private static ReplicationMsg lastOf(List msgs)
{
return msgs.isEmpty() ? null : msgs.get(msgs.size() - 1);
}
private static boolean containsReplicaOfflineMsg(List msgs, CSN offlineCSN)
{
for (ReplicationMsg msg : msgs)
{
if (msg instanceof ReplicaOfflineMsg
&& offlineCSN.equals(((ReplicaOfflineMsg) msg).getCSN()))
{
return true;
}
}
return false;
}
/** The CSN of a message the collocated replica announces, as PendingChanges generates it. */
private static CSN newOfflineCSN()
{
return newOfflineCSN(LOCAL_DS_ID);
}
/** The CSN of a message the provided replica announces. */
private static CSN newOfflineCSN(int serverId)
{
return new CSNGenerator(serverId, 0).newCSN();
}
/**
* A change of the collocated replica larger than the socket buffers of the connection to the
* peer which does not read, so that the session thread writing it to that peer is held inside
* the write.
*/
private static ModifyMsg newChangeLargerThanTheSocketBuffers(CSN csn)
{
final char[] value = new char[SOCKET_FILLING_CHANGE_SIZE];
Arrays.fill(value, 'x');
final List mods = newArrayList(
new Modification(ModificationType.REPLACE, Attributes.create("description", new String(value))));
return new ModifyMsg(csn, DN.valueOf("uid=busy," + TEST_ROOT_DN_STRING), mods, "busy-entry-uuid");
}
/** The shutdown of the replication server, reporting how long it took. */
private static Callable newShutdown(final ReplicationServer replicationServer)
{
return new Callable()
{
@Override
public Long call()
{
final long startTime = System.nanoTime();
replicationServer.shutdown();
return elapsedMillis(startTime);
}
};
}
/**
* Serves a connection to the replication server as its listen thread does - see
* ReplicationServer.runListen() - over a session the test established itself, so that the
* sockets underneath are its own to configure: the start message of the peer is read, and the
* handler is created and started from it. The start blocks until the handshake is over, so it
* runs on a thread of its own, as it does on the listen thread.
*/
private static Future serveAsTheListenThreadWould(
final ReplicationServer replicationServer, final Session session, ExecutorService executor)
{
return executor.submit(new Callable()
{
@Override
public ReplicationServerHandler call() throws Exception
{
final ReplServerStartMsg startMsg = (ReplServerStartMsg) session.receive();
final ReplicationServerHandler rsHandler =
new ReplicationServerHandler(session, 100, replicationServer, 100);
rsHandler.startFromRemoteRS(startMsg);
return rsHandler;
}
});
}
/**
* Waits for the close of the session to have been initiated, and gives up quietly once the
* timeout is over: the caller says what a close within the timeout, or none, means.
*/
private static void awaitCloseInitiated(Session session, long timeoutMillis)
throws InterruptedException
{
final long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMillis);
while (!session.closeInitiated() && System.nanoTime() < deadline)
{
Thread.sleep(10);
}
}
private static boolean sleepQuietly(long millis)
{
try
{
Thread.sleep(millis);
return true;
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
return false;
}
}
/** Teardown must never mask the primary assertion failure. */
private void removeQuietly(ReplicationServer replicationServer)
{
try
{
remove(replicationServer);
}
catch (Exception ignored)
{
}
}
private void joinQuietly(Thread thread)
{
if (thread != null)
{
try
{
thread.join(SOCKET_TIMEOUT_MS);
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
}
}
private void closeQuietly(FakePeerReplicationServer peer)
{
if (peer != null)
{
peer.close();
}
}
private static void awaitQuietly(Future> future)
{
if (future != null)
{
try
{
future.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS);
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
catch (Exception ignored)
{
}
}
}
/**
* Establishes a connected session pair over the given listen socket, as a remote server
* connecting to the RS would. The TLS negotiation performed by the session factories needs both
* ends handshaking at the same time, so the client end runs on its own thread.
*
* @return the two sessions: the remote (client) end first, then the local (server) end to hand
* to the handler under test
*/
private Session[] connectSessionPair(ServerSocket listenSocket, final ReplSessionSecurity security)
throws Exception
{
final ConnectedSessions connection = connectSessionPair(listenSocket, security, 0);
return new Session[] { connection.remoteEnd, connection.localEnd };
}
/**
* Establishes a connected session pair over the given listen socket, with the send buffer of
* the local end and the receive buffer of the remote end bounded by the given size: a message
* larger than both then holds the thread writing it until the remote end reads. A size of 0
* leaves the buffers to the kernel.
*/
private ConnectedSessions connectSessionPair(ServerSocket listenSocket,
final ReplSessionSecurity security, int socketBufferSize) throws Exception
{
final Socket clientSocket = new Socket();
final ExecutorService executor = Executors.newSingleThreadExecutor();
Future clientEnd = null;
Socket serverSocket = null;
Session serverEnd = null;
boolean connected = false;
try
{
if (socketBufferSize > 0)
{
// Before the connection is made: the window the local end is told is sized from it.
clientSocket.setReceiveBufferSize(socketBufferSize);
}
clientSocket.setTcpNoDelay(true);
clientSocket.connect(
new InetSocketAddress("127.0.0.1", listenSocket.getLocalPort()), SOCKET_TIMEOUT_MS);
clientEnd = executor.submit(new Callable()
{
@Override
public Session call() throws Exception
{
return security.createClientSession(clientSocket, SOCKET_TIMEOUT_MS);
}
});
serverSocket = listenSocket.accept();
if (socketBufferSize > 0)
{
serverSocket.setSendBufferSize(socketBufferSize);
}
serverSocket.setTcpNoDelay(true);
serverEnd = security.createServerSession(serverSocket, SOCKET_TIMEOUT_MS);
assertThat(serverEnd).as("could not create a session for the handler under test").isNotNull();
final ConnectedSessions connection = new ConnectedSessions(
clientEnd.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS), clientSocket, serverEnd);
connected = true;
return connection;
}
finally
{
if (!connected)
{
// Nobody owns either end yet: close whatever they managed to create.
closeClientEndQuietly(clientEnd, clientSocket);
closeServerEndQuietly(serverEnd, serverSocket);
}
executor.shutdown();
}
}
/** The two ends of a connection to the replication server, and the socket of the remote one. */
private static final class ConnectedSessions
{
private final Session remoteEnd;
private final Socket remoteSocket;
private final Session localEnd;
private ConnectedSessions(Session remoteEnd, Socket remoteSocket, Session localEnd)
{
this.remoteEnd = remoteEnd;
this.remoteSocket = remoteSocket;
this.localEnd = localEnd;
}
}
private void closeServerEndQuietly(Session serverEnd, Socket serverSocket)
{
if (serverEnd != null)
{
serverEnd.close();
}
else
{
StaticUtils.close(serverSocket);
}
}
private void closeClientEndQuietly(Future clientEnd, Socket clientSocket)
{
if (clientEnd != null)
{
try
{
final Session session = clientEnd.get(DISCARDED_SESSION_TIMEOUT_MS, TimeUnit.MILLISECONDS);
if (session != null)
{
session.close();
}
}
catch (Exception ignored)
{
clientEnd.cancel(true);
}
}
StaticUtils.close(clientSocket);
}
/**
* A synchronization object which records what the production code reports to it, so that a
* test can assert on the barrier the shutdown is made of rather than only on how long it took,
* and can interleave a teardown with the dispatch of a message.
*/
private static final class RecordingShutdownSync extends DSRSShutdownSync
{
private final List dispatchedTo = new CopyOnWriteArrayList<>();
private final List forwardedBy = new CopyOnWriteArrayList<>();
private final List gaveUpOn = new CopyOnWriteArrayList<>();
private final CountDownLatch dispatched = new CountDownLatch(1);
/** Runs inside the next dispatch, before the recipients are recorded. */
private final AtomicReference whileDispatching = new AtomicReference<>();
/**
* Runs the provided action inside the next dispatch, before the recipients are recorded:
* the window in which put() has read the peers of the domain and nothing knows yet which of
* them the message is for.
*/
void runWhileDispatching(Runnable action)
{
whileDispatching.set(action);
}
@Override
public void replicaOfflineMsgDispatched(
DN baseDN, CSN offlineCSN, Collection peers)
{
final Runnable action = whileDispatching.getAndSet(null);
if (action != null)
{
action.run();
}
for (ForwardingPeer peer : peers)
{
dispatchedTo.add(peer.getServerId());
}
super.replicaOfflineMsgDispatched(baseDN, offlineCSN, peers);
dispatched.countDown();
}
@Override
public void replicaOfflineMsgForwarded(DN baseDN, CSN forwardedCSN, ForwardingPeer peer)
{
forwardedBy.add(peer.getServerId());
super.replicaOfflineMsgForwarded(baseDN, forwardedCSN, peer);
}
@Override
public void replicaOfflineMsgNotForwarded(DN baseDN, ForwardingPeer peer)
{
gaveUpOn.add(peer.getServerId());
super.replicaOfflineMsgNotForwarded(baseDN, peer);
}
/** Waits for put() to have pushed a ReplicaOfflineMsg to the peers of its domain. */
void awaitDispatch() throws InterruptedException
{
assertThat(dispatched.await(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS))
.as("no ReplicaOfflineMsg was ever pushed to the peers of the domain")
.isTrue();
}
/** The peers the message was recorded as queued for. */
List dispatchedTo()
{
return dispatchedTo;
}
/** The peers whose writer reported having forwarded the message. */
List forwardedBy()
{
return forwardedBy;
}
/** The peers the shutdown was told to stop waiting for. */
List gaveUpOn()
{
return gaveUpOn;
}
}
/**
* A peer replication server which connects to the replication server under test.
* {@link #connected(int, int, DN, long)} completes the handshake, so that the handler it leaves
* behind on the domain has a real writer and can actually forward what the domain pushes to
* it.
*
* {@link #handshaking(int, int, DN, long)} stops between the two phases of the handshake
* instead, which leaves the listen thread of the replication server blocked in the receive of
* the TopologyMsg this peer owes it, before the handshake has registered the peer on the
* domain. That pause is bounded by the socket timeout of the handshake, so
* {@link #completeHandshake()} must follow shortly: a peer which stays silent for longer is
* given up on by the replication server itself.
*/
private static final class FakePeerReplicationServer
{
private static final byte GROUP_ID = 1;
private final int serverId;
private final long generationId;
private final String serverURL;
private final Session session;
/** The socket under the session: what it has received and not read is what the replication
* server has written to this peer. */
private final Socket socket;
private final ExecutorService reader = Executors.newSingleThreadExecutor();
/**
* What ended the exchange with the replication server, so that a message which never arrived
* can be told from an exchange which failed. The reader and the thread which opens the send
* window both report here, and the first failure is the one kept: it is the one which
* explains the rest.
*/
private final AtomicReference failure = new AtomicReference<>();
/** A peer which has completed its handshake and is served by a writer of the domain. */
static FakePeerReplicationServer connected(
int replicationPort, int serverId, DN baseDN, long generationId) throws Exception
{
return connected(replicationPort, serverId, baseDN, generationId, PEER_WINDOW);
}
/** A connected peer which advertises the given send window to the replication server. */
static FakePeerReplicationServer connected(int replicationPort, int serverId, DN baseDN,
long generationId, int windowSize) throws Exception
{
return connected(replicationPort, serverId, baseDN, generationId, windowSize,
ProtocolVersion.getCurrentVersion());
}
/**
* A connected peer speaking the given version of the replication protocol.
*
* @param protocolVersion
* the replication protocol version this peer announces in its start message, so
* that a peer which predates a message type can be reproduced
*/
static FakePeerReplicationServer connected(int replicationPort, int serverId, DN baseDN,
long generationId, int windowSize, short protocolVersion) throws Exception
{
return completed(new FakePeerReplicationServer(
replicationPort, serverId, baseDN, generationId, windowSize, protocolVersion));
}
/**
* A connected peer over a session the test established itself - one whose sockets it
* configured - which the replication server serves as its listen thread would.
*/
static FakePeerReplicationServer connected(Session newSession, Socket newSocket, int serverId,
DN baseDN, long generationId, int windowSize) throws Exception
{
return completed(new FakePeerReplicationServer(newSession, newSocket, serverId, baseDN,
generationId, windowSize, ProtocolVersion.getCurrentVersion()));
}
/** A peer whose handshake stops after its first phase, before it sends its TopologyMsg. */
static FakePeerReplicationServer handshaking(
int replicationPort, int serverId, DN baseDN, long generationId) throws Exception
{
return new FakePeerReplicationServer(replicationPort, serverId, baseDN, generationId,
PEER_WINDOW, ProtocolVersion.getCurrentVersion());
}
private static FakePeerReplicationServer completed(FakePeerReplicationServer peer)
throws Exception
{
boolean handshaken = false;
try
{
peer.completeHandshake();
handshaken = true;
}
finally
{
if (!handshaken)
{
// The caller has no handle on this peer yet, so nothing else would close it.
peer.close();
}
}
return peer;
}
private FakePeerReplicationServer(int replicationPort, int serverId, DN baseDN,
long generationId, int windowSize, short protocolVersion) throws Exception
{
this.serverId = serverId;
this.generationId = generationId;
final Socket newSocket = new Socket();
Session newSession = null;
String newServerURL = null;
boolean started = false;
try
{
newSocket.setTcpNoDelay(true);
newSocket.connect(new InetSocketAddress("127.0.0.1", replicationPort), SOCKET_TIMEOUT_MS);
newSession = getReplSessionSecurity().createClientSession(newSocket, SOCKET_TIMEOUT_MS);
newServerURL = start(newSession, newSocket, serverId, baseDN, generationId, windowSize,
protocolVersion);
started = true;
}
finally
{
if (!started)
{
abandon(newSession, newSocket);
}
}
serverURL = newServerURL;
session = newSession;
socket = newSocket;
}
private FakePeerReplicationServer(Session newSession, Socket newSocket, int serverId,
DN baseDN, long generationId, int windowSize, short protocolVersion) throws Exception
{
this.serverId = serverId;
this.generationId = generationId;
String newServerURL = null;
boolean started = false;
try
{
newServerURL = start(newSession, newSocket, serverId, baseDN, generationId, windowSize,
protocolVersion);
started = true;
}
finally
{
if (!started)
{
abandon(newSession, newSocket);
}
}
serverURL = newServerURL;
session = newSession;
socket = newSocket;
}
/**
* Runs the first phase of the handshake, the exchange of the start messages, and returns the
* URL this peer announced itself under.
*/
private static String start(Session newSession, Socket newSocket, int serverId, DN baseDN,
long generationId, int windowSize, short protocolVersion) throws Exception
{
// The replication server speaks the older of the two versions from the start message on.
newSession.setProtocolVersion(protocolVersion);
final String newServerURL = "127.0.0.1:" + newSocket.getLocalPort();
newSession.publish(new ReplServerStartMsg(serverId, newServerURL, baseDN, windowSize,
new ServerState(), generationId, false, GROUP_ID, 5000));
final ReplServerStartMsg inStartMsg =
waitForSpecificMsg(newSession, ReplServerStartMsg.class);
if (!inStartMsg.getSSLEncryption())
{
newSession.stopEncryption();
}
return newServerURL;
}
/** The caller has no handle on this peer yet, so nothing else would close it. */
private void abandon(Session newSession, Socket newSocket)
{
reader.shutdownNow();
if (newSession != null)
{
newSession.close();
}
else
{
StaticUtils.close(newSocket);
}
}
/**
* Waits for the replication server to have filled the receive buffer of this peer, which
* reads nothing meanwhile, up to {@link #SOCKET_BUFFER_FILL_MARK}: the session thread
* serving this peer is then inside the write of a message larger than the buffers on both
* sides of the connection, and stays there until this peer reads.
*/
void awaitReceiveBufferFilled() throws Exception
{
newConnectionTimer().repeatUntilSuccess(new Callable()
{
@Override
public Void call() throws Exception
{
assertThat(socket.getInputStream().available())
.as("the replication server never filled the receive buffer of the peer")
.isGreaterThanOrEqualTo(SOCKET_BUFFER_FILL_MARK);
return null;
}
});
}
/**
* Runs the second phase of the handshake, the one which registers this peer on the domain of
* the replication server.
*/
void completeHandshake() throws Exception
{
session.publish(new TopologyMsg(null,
newArrayList(new RSInfo(serverId, serverURL, generationId, GROUP_ID, 1))));
waitForSpecificMsg(session, TopologyMsg.class);
}
/**
* Returns every message this peer receives up to and including the first one of the provided
* type, or whatever it managed to read if its session ends before that one arrives.
*/
Future> receiveUntil(final Class extends ReplicationMsg> markerType)
{
return reader.submit(new Callable>()
{
@Override
public List call()
{
final List received = new ArrayList<>();
try
{
while (true)
{
final ReplicationMsg msg = session.receive();
received.add(msg);
if (markerType.isInstance(msg))
{
return received;
}
}
}
catch (Exception e)
{
failed(e);
return received;
}
}
});
}
/**
* Returns the first message of the given type this peer receives, or null if its session
* ends first.
*/
Future receive(final Class msgClass)
{
return reader.submit(new Callable()
{
@Override
public T call()
{
try
{
while (true)
{
final ReplicationMsg msg = session.receive();
if (msgClass.isInstance(msg))
{
return msgClass.cast(msg);
}
}
}
catch (Exception e)
{
// The session is closed when the replication server completes its shutdown: whatever
// has not arrived by then never will.
failed(e);
return null;
}
}
});
}
/** Gives the replication server credit to publish again, as a peer which keeps up does. */
void openSendWindow(int credits)
{
try
{
session.publish(new WindowMsg(credits));
}
catch (IOException e)
{
failed(e);
}
}
private void failed(Exception e)
{
failure.compareAndSet(null, e);
}
/** Returns what ended the exchange with this peer, null if nothing did. */
Exception failure()
{
return failure.get();
}
void close()
{
reader.shutdownNow();
session.close();
}
}
}