From f82d22de94de20cb44775530e934eb8c26368484 Mon Sep 17 00:00:00 2001
From: Valery Kharseko <vharseko@3a-systems.ru>
Date: Tue, 01 Dec 2026 17:06:15 +0000
Subject: [PATCH] Stabilize replication failover and heartbeat timeout tests (#1353)
---
opendj-server-legacy/src/main/java/org/opends/server/replication/protocol/ReplSessionSecurity.java | 29 ++++++++-
opendj-server-legacy/src/test/java/org/opends/server/replication/protocol/ReplSessionSecurityTest.java | 37 ++++++++++++
opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/ReplicationBrokerStopTest.java | 101 ++++++++++++++++++++++-----------
3 files changed, 129 insertions(+), 38 deletions(-)
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/replication/protocol/ReplSessionSecurity.java b/opendj-server-legacy/src/main/java/org/opends/server/replication/protocol/ReplSessionSecurity.java
index 1629e83..8ff859e 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/replication/protocol/ReplSessionSecurity.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/replication/protocol/ReplSessionSecurity.java
@@ -267,7 +267,7 @@
* The connected socket.
* @param soTimeout
* The socket timeout option to use for the protocol session.
- * @return The new protocol session.
+ * @return The new protocol session, or {@code null} if TLS negotiation raised an {@link SSLException}.
* @throws ConfigException
* If the protocol session could not be established due to a
* configuration problem.
@@ -278,6 +278,28 @@
public Session createServerSession(final Socket socket,
final int soTimeout) throws ConfigException, IOException
{
+ try
+ {
+ return createServerSessionOrThrow(socket, soTimeout);
+ }
+ catch (SSLException e)
+ {
+ // The TLS failure was logged before the socket was closed.
+ return null;
+ }
+ }
+
+ /**
+ * Creates a server session and propagates TLS failures to the caller.
+ *
+ * @param socket the connected socket
+ * @param soTimeout the socket read timeout in milliseconds
+ * @return the new protocol session
+ * @throws ConfigException if the session configuration is invalid
+ * @throws IOException if the session cannot be established, including an {@link SSLException} from TLS negotiation
+ */
+ public Session createServerSessionOrThrow(final Socket socket, final int soTimeout) throws ConfigException, IOException
+ {
boolean hasCompleted = false;
SSLSocket secureSocket = null;
@@ -307,8 +329,9 @@
// Force TLS negotiation now.
secureSocket.startHandshake();
+ final Session session = new Session(socket, secureSocket);
hasCompleted = true;
- return new Session(socket, secureSocket);
+ return session;
}
catch (final SSLException e)
{
@@ -316,7 +339,7 @@
// also how a certificate misconfiguration shows up, so warn the
// administrator instead of failing silently.
logHandshakeFailure(socket, e);
- return null;
+ throw e;
}
finally
{
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/ReplicationBrokerStopTest.java b/opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/ReplicationBrokerStopTest.java
index 8b93bf1..65c87eb 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/ReplicationBrokerStopTest.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/ReplicationBrokerStopTest.java
@@ -18,6 +18,7 @@
import static java.util.concurrent.TimeUnit.*;
import static org.forgerock.opendj.ldap.ModificationType.*;
+import static org.opends.messages.ReplicationMessages.WARN_HEARTBEAT_FAILURE;
import static org.opends.messages.ReplicationMessages.WARN_REPLICATION_SERVER_BADLY_DISCONNECTED;
import static org.opends.messages.ReplicationMessages.WARN_TIMEOUT_CONNECTING_TO_RS;
import static org.opends.server.TestCaseUtils.*;
@@ -51,6 +52,7 @@
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.BooleanSupplier;
import org.forgerock.opendj.ldap.DN;
import org.forgerock.opendj.ldap.ResultCode;
@@ -141,10 +143,7 @@
private static final int LARGE_MESSAGE_SIZE = 256 * 1024;
/** How many of those messages a case writes at most before it reports that no write blocks. */
private static final int MAX_LARGE_MESSAGES = 400;
- /**
- * The heartbeat interval of the case of a replication server which is gone: long enough for its
- * writes to fill the socket buffers before the heartbeat monitor gives up on the session.
- */
+ /** Heartbeat interval negotiated by the domain in the lost-server test. */
private static final long HEARTBEAT_INTERVAL_MS = 4000;
/** A value which makes a change of the description one of those messages. */
private static final String LARGE_VALUE = "x".repeat(LARGE_MESSAGE_SIZE);
@@ -724,7 +723,7 @@
final LDAPReplicationDomain domain = startDomain(rs);
TestCaseUtils.ERROR_TEXT_WRITER.clear();
rs.stopReading();
- writer = startLargeChanges(keepWriting, changes, failed);
+ writer = startLargeChanges(keepWriting::get, changes, failed);
waitForAWriteToBlock(writer, changes);
keepWriting.set(false);
@@ -1059,34 +1058,43 @@
{
TestCaseUtils.initializeTestBackend(true);
final WithholdingReplicationServer rs = new WithholdingReplicationServer(LARGE_WINDOW);
- final AtomicBoolean keepWriting = new AtomicBoolean(true);
final AtomicInteger changes = new AtomicInteger();
final AtomicReference<ResultCode> failed = new AtomicReference<>();
Thread writer = null;
try
{
final LDAPReplicationDomain domain = startDomain(rs, HEARTBEAT_INTERVAL_MS);
+ final ReplicationBroker broker = brokerOf(domain);
+ final Session original = broker.getSession();
+ // Give the replication server a CSN from which it can request recovery on reconnect.
+ assertEquals(replaceDescription("before the heartbeat timeout"), ResultCode.SUCCESS);
+ rs.waitForUpdates(1);
TestCaseUtils.ERROR_TEXT_WRITER.clear();
- rs.goAway();
- final long away = System.nanoTime();
- writer = startLargeChanges(keepWriting, changes, failed);
+ rs.stopReading();
+ // A stalled write may still fit in the TCP buffers later. Keep writing until this session closes.
+ writer = startLargeChanges(() -> !original.closeInitiated(), changes, failed);
waitForAWriteToBlock(writer, changes);
- keepWriting.set(false);
- final long blocked = System.nanoTime();
- // The monitor gives up two or three intervals after the last heartbeat.
+ rs.giveCredit(LARGE_WINDOW);
+ newTimer().repeatUntilSuccess(() -> assertTrue(broker.getCurrentSendWindow() > LARGE_WINDOW,
+ "the directory server did not receive the credit on the original session"));
+ rs.goAway();
writer.join(4 * HEARTBEAT_INTERVAL_MS + 10000);
- final long released = System.nanoTime();
assertFalse(writer.isAlive(), "the write still blocks once the heartbeats of the replication server stopped");
- assertTrue(NANOSECONDS.toMillis(released - away) >= 2 * HEARTBEAT_INTERVAL_MS, "the write of change "
- + changes.get() + ", blocked " + NANOSECONDS.toMillis(blocked - away) + " ms after the replication server went away, ended "
- + NANOSECONDS.toMillis(released - away) + " ms after it: before the heartbeat monitor could give the session up");
+ assertTrue(original.closeInitiated(), "the writer exhausted its changes while the original session was open");
assertNull(failed.get(), "a local change failed");
+ final String timeout = WARN_HEARTBEAT_FAILURE.get(DS_ID, rs.serverId,
+ original.getReadableRemoteAddress(), baseDN.toString()).toString();
+ newTimer().repeatUntilSuccess(() -> assertTrue(TestCaseUtils.ERROR_TEXT_WRITER.getMessages().stream()
+ .anyMatch(record -> record.contains(timeout)), "missing heartbeat timeout: " + timeout));
- rs.resumeReading();
- waitForConnection(domain);
+ // Discard any bytes queued on the old socket. Only the reconnected session can deliver the change.
final CSN last = domain.getServerState().getCSN(DS_ID);
assertNotNull(last, "the domain has no change of its own in its state");
+ assertFalse(rs.receivedUpdateCSNs().contains(last), "the old session already delivered the blocked change");
+ rs.dropTheSession();
+ rs.resumeReading();
+ waitForConnection(domain);
newTimer().repeatUntilSuccess(() -> assertTrue(rs.receivedUpdateCSNs().contains(last),
"the change cut short, " + last + ", did not reach the replication server: it has "
+ rs.receivedUpdateCSNs()));
@@ -1437,11 +1445,7 @@
final CSN beforeFailover = former.receivedUpdateCSNs().get(1);
survivor.differentGroup = false;
- former.beforeStartReply = () -> {
- // The accepted socket can answer discovery after the listener stops accepting connections.
- former.listenSocket.close();
- return null;
- };
+ former.closeListenerAfterNextAccept = true;
survivor.delayedFailoverHandshake = handshake;
former.closeTheSession();
@@ -1493,10 +1497,7 @@
former.waitForUpdates(1);
responder.differentGroup = false;
- former.beforeStartReply = () -> {
- former.listenSocket.close();
- return null;
- };
+ former.closeListenerAfterNextAccept = true;
responder.delayedFailoverHandshake = handshake;
handshake.sendNextReply.countDown();
former.closeTheSession();
@@ -1546,10 +1547,7 @@
responder.differentGroup = false;
responder.delayedFailoverHandshake = handshake;
- former.beforeStartReply = () -> {
- former.listenSocket.close();
- return null;
- };
+ former.closeListenerAfterNextAccept = true;
former.dropTheSession();
await(handshake.nextStartReceived);
@@ -2198,6 +2196,8 @@
final LDAPReplicationDomain domain = startDomain(oldRS, 100000, nextRS.getAddress());
assertEquals(domain.getRsServerId(), oldRS.serverId);
nextRS.differentGroup = false;
+ // Allow TLS to finish before exercising the broker's shorter start-reply timeout.
+ nextRS.tlsHandshakeTimeoutMS = 8_000;
nextRS.delayedFailoverHandshake = handshake;
if (formerRs == FormerRsDuringFailover.OFFLINE)
{
@@ -2267,6 +2267,15 @@
nextRS.waitForUpdates(1);
}
}
+ catch (AssertionError e)
+ {
+ final IOException tlsFailure = nextRS.firstTlsHandshakeFailure.get();
+ if (tlsFailure != null)
+ {
+ e.addSuppressed(tlsFailure);
+ }
+ throw e;
+ }
finally
{
handshake.sendNextReply.countDown();
@@ -2445,11 +2454,11 @@
* Starts a thread which makes changes of {@link #LARGE_MESSAGE_SIZE} until it is told to stop,
* counting them, and keeping the first result which is no success.
*/
- private Thread startLargeChanges(final AtomicBoolean keepWriting, final AtomicInteger changes,
+ private Thread startLargeChanges(final BooleanSupplier keepWriting, final AtomicInteger changes,
final AtomicReference<ResultCode> failed)
{
return startThread("writer", () -> {
- while (keepWriting.get() && changes.get() < MAX_LARGE_MESSAGES)
+ while (keepWriting.getAsBoolean() && changes.get() < MAX_LARGE_MESSAGES)
{
final ResultCode result = replaceDescription(changes.get() + LARGE_VALUE);
if (result != ResultCode.SUCCESS)
@@ -2675,12 +2684,17 @@
private boolean reading = true;
/** Whether this server is away: it then sends no heartbeat, and answers no connection either. */
private volatile boolean away;
+ /** Accept the discovery socket, then refuse the session connection. */
+ private volatile boolean closeListenerAfterNextAccept;
private volatile Callable<Void> beforeStartReply;
private volatile Callable<Void> onFirstWindowProbe;
/** If set, read from the next session after StartSessionMsg instead of sending its topology. */
private final AtomicReference<CompletableFuture<ReplicationMsg>> readInsteadOfSendingTopology =
new AtomicReference<>();
private volatile DelayedFailoverHandshake delayedFailoverHandshake;
+ /** A positive timeout applies only to TLS negotiation on this server. */
+ private volatile int tlsHandshakeTimeoutMS;
+ private final AtomicReference<IOException> firstTlsHandshakeFailure = new AtomicReference<>();
WithholdingReplicationServer() throws IOException
{
@@ -2743,6 +2757,10 @@
try
{
socket = listenSocket.accept();
+ if (closeListenerAfterNextAccept)
+ {
+ listenSocket.close();
+ }
}
catch (IOException e)
{
@@ -2763,12 +2781,20 @@
private void serve(Socket socket)
{
Session s = null;
+ int tlsTimeoutMS = 0;
try
{
// A server which is away answers no connection: the connection waits for it to come back.
waitToBeBack();
- s = new ReplSessionSecurity().createServerSession(socket, MultimasterReplication.getConnectionTimeoutMS());
+ final int readTimeoutMS = MultimasterReplication.getConnectionTimeoutMS();
+ tlsTimeoutMS = tlsHandshakeTimeoutMS;
+ s = new ReplSessionSecurity().createServerSessionOrThrow(socket,
+ tlsTimeoutMS > 0 ? tlsTimeoutMS : readTimeoutMS);
sessions.add(s);
+ if (tlsTimeoutMS > 0)
+ {
+ s.setSoTimeout(readTimeoutMS);
+ }
final ServerStartMsg start = (ServerStartMsg) s.receive();
final Callable<Void> hook = beforeStartReply;
if (hook != null)
@@ -2849,7 +2875,12 @@
}
catch (Exception e)
{
- // The domain closed the session, or the test closed this server.
+ if (s == null && tlsTimeoutMS > 0)
+ {
+ firstTlsHandshakeFailure.compareAndSet(null, new IOException("TLS handshake on replication server "
+ + getAddress() + " with peer " + socket.getRemoteSocketAddress(), e));
+ }
+ // An established session may end when the domain or the test closes it.
}
finally
{
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/replication/protocol/ReplSessionSecurityTest.java b/opendj-server-legacy/src/test/java/org/opends/server/replication/protocol/ReplSessionSecurityTest.java
index cbbc462..4dc6baa 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/replication/protocol/ReplSessionSecurityTest.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/replication/protocol/ReplSessionSecurityTest.java
@@ -16,15 +16,52 @@
package org.opends.server.replication.protocol;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.opends.server.replication.protocol.ReplSessionSecurity.HANDSHAKE_FAILURE_WARN_INTERVAL_NANOS;
+import java.net.InetAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.nio.charset.StandardCharsets;
+
+import javax.net.ssl.SSLException;
+
import org.opends.server.DirectoryServerTestCase;
+import org.opends.server.TestCaseUtils;
import org.testng.annotations.Test;
/** Tests for {@link ReplSessionSecurity}. */
@SuppressWarnings("javadoc")
public class ReplSessionSecurityTest extends DirectoryServerTestCase
{
+ @Test
+ public void serverSessionCanPropagateTheTlsFailureToItsCaller() throws Exception
+ {
+ TestCaseUtils.startServer();
+ final ReplSessionSecurity security = new ReplSessionSecurity();
+ try (ServerSocket listener = TestCaseUtils.bindFreePort())
+ {
+ for (boolean propagate : new boolean[] { false, true })
+ {
+ try (Socket peer = new Socket(InetAddress.getLoopbackAddress(), listener.getLocalPort());
+ Socket accepted = listener.accept())
+ {
+ peer.getOutputStream().write("plain text".getBytes(StandardCharsets.US_ASCII));
+ if (propagate)
+ {
+ assertThatThrownBy(() -> security.createServerSessionOrThrow(accepted, 5000))
+ .isInstanceOf(SSLException.class);
+ }
+ else
+ {
+ assertThat(security.createServerSession(accepted, 5000)).isNull();
+ }
+ assertThat(accepted.isClosed()).isTrue();
+ }
+ }
+ }
+ }
+
/**
* Any connection which is not a replication peer fails the handshake on the replication
* port, and a data server which cannot present its certificate reconnects every 500 ms,
--
Gitblit v1.10.0