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

Valery Kharseko
61 mins ago f82d22de94de20cb44775530e934eb8c26368484
Stabilize replication failover and heartbeat timeout tests (#1353)

The Ubuntu / JDK 25 build on #1351 timed out in
`failoverTriesAnotherDiscoveryResponderWhenTheFormerRsRefusesConnection(1)`.
The directory server reconnected to the former replication server. The
test then waited 30 seconds for a retry on the alternate server. [Failed
CI
job](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/46602539655/job/142487255450#step:16)

A controlled replay on Linux reproduced the timeout on master. The
former server accepted the discovery socket and handed it to a worker.
By the time the worker closed the listener, the accept thread had
entered another `accept()`. That call returned a second socket, and the
former server received `StartSessionMsg` on it.

The test now tells the accept thread to close the listener immediately
after it accepts the discovery socket. The worker can still reply on
that socket, and the broker's subsequent TCP connection to the former
server is refused. This exercises the fallback and retry introduced in
#1349.

The two queued-stop tests now use the same listener flag. One queues
`stop()` while the alternate server withholds its first session start
reply and checks that the broker skips the retry. The other queues
`stop()` while the broker waits for the alternate server's discovery
reply and checks that the alternate server receives only the discovery
probe.

Two follow-up changes address failures seen while verifying the rebased
PR.

- In `failoverAllowsOneRetryOfTheSurvivingRs(1, 1, OFFLINE)`, the client
saw a connection reset during TLS negotiation, before sending
`ServerStartMsg`. The surviving test server now allows 8 seconds for TLS
negotiation and restores the 2-second read timeout before the
replication handshake. If the test fails, its assertion includes the
first server-side handshake failure and the socket endpoints. The new
`createServerSessionOrThrow()` entry point preserves the original
`SSLException` for the caller.
- In the heartbeat test, a write finished 5.383 seconds after the server
went away. Two samples in `Session.send()` had been enough for the test
to tell the writer to stop. The test now keeps writing until the
original session closes, confirms that the directory server receives a
window credit before heartbeats stop, and checks the monitor's timeout
warning for that session. It then discards the old socket and verifies
delivery of the last change by CSN after reconnecting.

## Verification

- With the fix, the alternate server received one discovery probe, one
session attempt whose start reply timed out, and one successful retry.
- Temporarily removing the broker's retry made the corrected test fail
on premature isolation in the one-timeout case. The zero-timeout case
passed.
- The original failover fix passed all 49 cases in
`ReplicationBrokerStopTest` on Linux with Temurin 25.0.5.1, with zero
skips.
- A 3-second delay in TLS setup allowed the failover case to reach the
intended start-reply timeout and retry. A separate loopback test covers
both the existing TLS error return and propagation of the original
exception.
- A controlled write pause reproduced the early exit in the old
heartbeat test and passed with the fix. Disabling the monitor's socket
abort made the updated test fail on the blocked write.
- With a window credit delivered between two overdue heartbeat polls,
the previous test failed when the writer finished after 6.177 seconds.
The same schedule passed after removing the elapsed-time assertion.
- On the rebased PR branch, Maven `verify -Pprecommit` passed all 81
selected tests on macOS with JDK 17, including all 49 cases in
`ReplicationBrokerStopTest`, with zero skips.
3 files modified
167 ■■■■■ changed files
opendj-server-legacy/src/main/java/org/opends/server/replication/protocol/ReplSessionSecurity.java 29 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/ReplicationBrokerStopTest.java 101 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/test/java/org/opends/server/replication/protocol/ReplSessionSecurityTest.java 37 ●●●●● patch | view | raw | blame | history
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
    {
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
      {
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,