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

Valery Kharseko
20 hours ago 2863452733f1815ce5557ff01cfe148b49e182b0
[#1208] Retry the discovery responder before declaring replication isolation (#1349)

## Problem

On the first reconnect after losing a replication session, the former
replication server can answer discovery and then refuse the elected TCP
connection. If the alternate discovery responder's start reply times
out, the broker declares isolation before retrying that server. With
`REJECT_ALL_UPDATES`, LDAP writes can receive result 53 until the next
reconnect.

[Failed Ubuntu / Java 17
job](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/46264095245/job/141350054339#step:16)

## Change

Retry the alternate responder once on a start-reply timeout before
declaring isolation. Verify the generation ID in the successful reply.
Record a pending stop before it acquires the broker's start/stop lock so
a queued stop suppresses optional failover retries. The watchdog starts
when the stop is registered under the lock. With the bounded discovery
introduced in #1346, the broker checks again for a queued stop after
continued discovery and before opening a fallback connection.

## Validation

- The socket regression makes the former server answer discovery and
refuse the elected connection. The alternate responder withholds one
start reply. The test checks that the broker stays out of isolation
while the retry is pending, and verifies that the new session delivers
the missing change and a subsequent LDAP update.
- The new case reproduced premature isolation before the fix and passed
afterward.
- A second socket regression queues `stop()` while the responder
withholds its first start reply. It observed an extra start before the
fix. It now verifies that the responder receives one discovery probe and
one session start and that the stop completes.
- After rebasing onto `52694d4` (#1346), Maven `verify` ran 64 selected
integration tests on macOS with Java 17. All responder-retry and
queued-stop cases passed. Two existing tests failed in the combined run,
`aDisableEndsWhenTheReplicationServerGivesNoCredit` and
`theHeartbeatMonitorEndsAWriteToAReplicationServerWhichIsGone`. Both
passed in focused TestNG reruns with the base and rebased versions of
the broker and test fixture. `git diff --check` passed.
- A third [socket
regression](https://github.com/OpenIdentityPlatform/OpenDJ/blob/0727d7c93b408e2c93538065e6989fd58acdd017/opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/ReplicationBrokerStopTest.java#L1508-L1547)
holds the alternate responder's discovery reply until the broker enters
continued discovery. It queues `stop()`, waits for it to block on
`startStopLock`, and then releases the reply. The stop completes and the
alternate RS receives exactly one `ServerStartMsg` for discovery. With
the pending-stop check disabled at that point, the test fails because
the RS receives a second start message.
- With the new regression, Maven `verify` with the `precommit` profile
passed all 49 `ReplicationBrokerStopTest` cases on macOS with Java 17.

### CI follow-up

- Ubuntu / Java 21 timed out in
`RsaSveKeyTransportTestCase.testAnotherPrivateKeyCannotUnwrap` while
generating candidate RSA keys. The test now orders two 2048-bit pairs by
modulus and checks the specific unwrap error returned with the wrong
key. [Java 21 CI
log](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/46397673932/job/141775831892#step:16)
- An earlier Ubuntu / Java 11 run failed in
`aDisableEndsWhenTheReplicationServerGivesNoCredit` on the remaining
offline announcement. Maven `verify` reproduced the old assertion
failure on Ubuntu / Java 11 with a seeded prior announcement whose CSN
sorts after the first update. The test now captures the announcement for
the current `disable()` at the first window probe and checks that it is
withdrawn, allowing the prior announcement to be restored. [Java 11 CI
log](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/46382940305/job/141726375990#step:16)
- Focused TestNG runs passed all 45 `RsaSveKeyTransportTestCase` tests
on macOS / Java 21 and all 49 `ReplicationBrokerStopTest` tests on
Ubuntu / Java 11. `git diff --check` passed.

Follow-up to #1343. Related to #1208.
3 files modified
265 ■■■■■ changed files
opendj-server-legacy/src/main/java/org/opends/server/replication/service/ReplicationBroker.java 37 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/test/java/org/opends/server/crypto/RsaSveKeyTransportTestCase.java 19 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/ReplicationBrokerStopTest.java 209 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/replication/service/ReplicationBroker.java
@@ -49,6 +49,7 @@
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import net.jcip.annotations.GuardedBy;
@@ -192,7 +193,7 @@
  }
  /**
   * A stop of the broker, from the moment {@link #stop()} begins until {@link #start()} clears it.
   * A registered stop of the broker, kept until {@link #start()} clears it.
   * <p>
   * What a publish gives up for the stop is marked on the stop, and not on the broker: a publish
   * which found the stop past its deadline may mark it only after start() cleared it, and then the
@@ -266,9 +267,9 @@
  /** A backend whose state could not be restored must never reconnect through this broker. */
  private volatile boolean permanentlyStopped;
  /**
   * The stop in progress: set by {@link #stop()} before anything else it does, and cleared to
   * {@code null} by {@link #start()}. While it is set, a publish which finds no window credit by
   * its deadline gives its message up instead of waiting on.
   * The stop in progress, registered under {@link #startStopLock} and cleared to {@code null}
   * by {@link #start()}. While it is set, a publish which finds no window credit by its deadline
   * gives its message up instead of waiting on.
   * <p>
   * stop() publishes the replica offline message before it sets {@link #shutdown}, the flag which
   * ends the wait for credit, and that message needs credit too, and the lock of the pending
@@ -282,6 +283,8 @@
   */
  private volatile StopInProgress stopping;
  private final Object startStopLock = new Object();
  /** Stop requests waiting for the lock are visible to the reconnect that holds it. */
  private final AtomicInteger pendingStopRequests = new AtomicInteger();
  private volatile ReplicationDomainCfg config;
  /** String reported under CSN=monitor when there is no connected RS. */
  static final HostPort NO_CONNECTED_SERVER = new HostPort(null, 0);
@@ -1158,7 +1161,7 @@
        }
        computeNewTopology(toRSInfos(rsInfos));
        final boolean canRetry = previousRS != null && stopping == null && !permanentlyStopped;
        final boolean canRetry = previousRS != null && canRetryFailover();
        final boolean hasReplies = !rsInfos.isEmpty();
        String electedURL = null;
        if (hasReplies)
@@ -1242,7 +1245,7 @@
      discovery.close();
    }
    ConnectedRS electedRS = performPhaseOneHandshake(electedURL, true, canRetry);
    if (electedRS.rsInfo == null && canRetry && stopping == null && !permanentlyStopped)
    if (electedRS.rsInfo == null && canRetry && canRetryFailover())
    {
      electedRS = retryElectedConnection(discovery, rsInfos, electedURL, previousRS, electedRS);
    }
@@ -1288,7 +1291,7 @@
    final String timedOutRS = electedFormerRS && responder == null ? discovery.timedOutServer(previousRS) : null;
    discovery.close();
    if (stopping != null || permanentlyStopped)
    if (!canRetryFailover())
    {
      return failure;
    }
@@ -1304,6 +1307,11 @@
    return failure;
  }
  private boolean canRetryFailover()
  {
    return pendingStopRequests.get() == 0 && stopping == null && !permanentlyStopped;
  }
  /** Opens the selected RS session using the fresh state returned by its start reply. */
  private void finishElectedConnection(ConnectedRS electedRS, Map<Integer, ReplicationServerInfo> rsInfos)
  {
@@ -1333,7 +1341,12 @@
  private ConnectedRS connectToDiscoveryResponder(ReplicationServerInfo responder)
  {
    final ConnectedRS replacement = performPhaseOneHandshake(responder.getServerURL(), true, false);
    final String url = responder.getServerURL();
    ConnectedRS replacement = performPhaseOneHandshake(url, true, true);
    if (replacement == ConnectedRS.START_REPLY_TIMED_OUT && canRetryFailover())
    {
      replacement = performPhaseOneHandshake(url, true, false);
    }
    // The generation may have changed since discovery.
    if (replacement.rsInfo != null && !hasCompatibleGeneration(replacement.rsInfo))
    {
@@ -3556,8 +3569,12 @@
    }
    final StopInProgress stop;
    final boolean newStop;
    synchronized (startStopLock) {
      if (shutdown) {
    pendingStopRequests.incrementAndGet();
    synchronized (startStopLock)
    {
      pendingStopRequests.decrementAndGet();
      if (shutdown)
      {
        return;
      }
      // A stop which overlaps one in progress keeps its deadlines and what it gave up.
opendj-server-legacy/src/test/java/org/opends/server/crypto/RsaSveKeyTransportTestCase.java
@@ -120,19 +120,18 @@
  @Test
  public void testAnotherPrivateKeyCannotUnwrap() throws Exception
  {
    KeyPair other;
    do
    {
      other = rsaKeyPair(2048);
    }
    while (modulus(other).compareTo(modulus(keyPair)) <= 0);
    final KeyPair otherKeyPair = other;
    final KeyPair secondKeyPair = rsaKeyPair(2048);
    final int modulusOrder = modulus(keyPair).compareTo(modulus(secondKeyPair));
    assertThat(modulusOrder).as("the two RSA moduli must differ").isNotZero();
    final KeyPair wrappingKeyPair = modulusOrder < 0 ? keyPair : secondKeyPair;
    final KeyPair wrongKeyPair = modulusOrder < 0 ? secondKeyPair : keyPair;
    final SecretKey key = new SecretKeySpec(bytes(16, 0x3C), "AES");
    inProviders(BC_FIPS, () ->
    {
      final byte[] wrapped = RsaSveKeyTransport.wrap(keyPair.getPublic(), key, KEY_ID, random);
      assertThatThrownBy(() -> RsaSveKeyTransport.unwrap(otherKeyPair, wrapped, "AES", KEY_ID))
          .isInstanceOf(GeneralSecurityException.class);
      final byte[] wrapped = RsaSveKeyTransport.wrap(wrappingKeyPair.getPublic(), key, KEY_ID, random);
      assertThatThrownBy(() -> RsaSveKeyTransport.unwrap(wrongKeyPair, wrapped, "AES", KEY_ID))
          .isInstanceOf(InvalidKeyException.class)
          .hasMessage(RsaSveKeyTransport.NAME + " cannot unwrap the key");
      return null;
    });
  }
opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/ReplicationBrokerStopTest.java
@@ -178,6 +178,8 @@
    TestCaseUtils.initializeTestBackend(true);
    setConnectionTimeout(LONG_CONNECTION_TIMEOUT_MS);
    final WithholdingReplicationServer rs = new WithholdingReplicationServer();
    final DSRSShutdownSync shutdownSync = shutdownSync();
    CSN previousAnnouncement = null;
    Thread disabling = null;
    try
    {
@@ -186,9 +188,21 @@
      // The only credit of the window goes to a change of our own.
      assertEquals(replaceDescription("first"), ResultCode.SUCCESS);
      rs.waitForUpdates(1);
      final CSN firstChange = rs.receivedUpdateCSNs().get(0);
      // The previous domain used the same clock tick and had a higher sequence number.
      previousAnnouncement = new CSN(firstChange.getTime(), firstChange.getSeqnum() + 2, DS_ID);
      final CompletableFuture<CSN> announcementAtFirstProbe = new CompletableFuture<>();
      rs.onFirstWindowProbe = () -> {
        announcementAtFirstProbe.complete(offlineAnnouncementOfTheReplica());
        return null;
      };
      shutdownSync.replicaOfflineMsgSent(baseDN, previousAnnouncement);
      final long beforeTheDisable = System.nanoTime();
      disabling = startThread("disable", domain::disable);
      final CSN stopAnnouncement = announcementAtFirstProbe.get(10, SECONDS);
      assertNotNull(stopAnnouncement, "the stop must announce going offline before waiting for credit");
      assertFalse(previousAnnouncement.equals(stopAnnouncement), "the stop must announce its own CSN");
      disabling.join(stopBoundMS());
      final long disableMS = NANOSECONDS.toMillis(System.nanoTime() - beforeTheDisable);
      assertFalse(disabling.isAlive(),
@@ -199,17 +213,24 @@
      assertEquals(rs.count(ReplicaOfflineMsg.class), 0, "the replica offline message was written with no credit");
      assertEquals(rs.count(StopMsg.class), 1, "the session was closed as a failed one, not ended in order");
      /* The grace period of the announcement has run out by now, so whether the shutdown of a
       * collocated replication server would wait for it says nothing: what is left announced does.
       * An announcement older than the change is one of an earlier stop of the replica. */
      final CSN announced = offlineAnnouncementOfTheReplica();
      assertTrue(announced == null || !announced.isNewerThan(rs.receivedUpdateCSNs().get(0)),
          "the replica offline message given up is still announced: " + announced);
      final CSN remainingAnnouncement = offlineAnnouncementOfTheReplica();
      assertTrue(remainingAnnouncement == null || previousAnnouncement.equals(remainingAnnouncement),
          "expected the stop to withdraw " + stopAnnouncement + ", but found " + remainingAnnouncement);
    }
    finally
    {
      cleanUp(rs, disabling);
      setConnectionTimeout(SHORT_CONNECTION_TIMEOUT_MS);
      try
      {
        cleanUp(rs, disabling);
      }
      finally
      {
        if (previousAnnouncement != null)
        {
          shutdownSync.replicaOfflineMsgNotSent(baseDN, previousAnnouncement);
        }
        setConnectionTimeout(SHORT_CONNECTION_TIMEOUT_MS);
      }
    }
  }
@@ -1386,15 +1407,20 @@
    }
  }
  @Test(timeOut = 120_000)
  public void failoverTriesAnotherDiscoveryResponderWhenTheFormerRsRefusesConnection() throws Exception
  @DataProvider
  public Object[][] discoveryResponderStartReplyTimeouts()
  {
    return new Object[][] { { 0 }, { 1 } };
  }
  @Test(dataProvider = "discoveryResponderStartReplyTimeouts", timeOut = 120_000)
  public void failoverTriesAnotherDiscoveryResponderWhenTheFormerRsRefusesConnection(int timedOutReplies)
      throws Exception
  {
    TestCaseUtils.initializeTestBackend(true);
    final WithholdingReplicationServer former = new WithholdingReplicationServer(LARGE_WINDOW);
    final WithholdingReplicationServer survivor = new WithholdingReplicationServer(LARGE_WINDOW, 4);
    final AtomicInteger survivorStarts = new AtomicInteger();
    final CountDownLatch survivorRetry = new CountDownLatch(1);
    final CountDownLatch finishRetry = new CountDownLatch(1);
    final DelayedFailoverHandshake handshake = new DelayedFailoverHandshake(1, timedOutReplies);
    try
    {
      survivor.differentGroup = true;
@@ -1416,19 +1442,13 @@
        former.listenSocket.close();
        return null;
      };
      survivor.beforeStartReply = () -> {
        if (survivorStarts.incrementAndGet() == 2)
        {
          survivorRetry.countDown();
          await(finishRetry);
        }
        return null;
      };
      survivor.delayedFailoverHandshake = handshake;
      former.closeTheSession();
      await(survivorRetry);
      assertFalse(domain.hasConnectionError(), "the broker declared isolation before trying the discovery responder");
      finishRetry.countDown();
      await(handshake.nextStartReceived);
      assertFalse(domain.hasConnectionError(),
          "the broker declared isolation before connecting to the discovery responder");
      handshake.sendNextReply.countDown();
      newTimer().repeatUntilSuccess(() -> {
        assertEquals(domain.getRsServerId(), survivor.serverId);
        assertFalse(domain.hasConnectionError());
@@ -1436,11 +1456,12 @@
      assertEquals(replaceDescription("after failover to the discovery responder"), ResultCode.SUCCESS);
      survivor.waitForUpdates(2);
      assertEquals(survivor.receivedUpdateCSNs(), List.of(beforeFailover, domain.getServerState().getCSN(DS_ID)));
      assertEquals(survivorStarts.get(), 2, "the survivor must receive one discovery probe and one session start");
      assertEquals(handshake.starts.get(), 2 + timedOutReplies,
          "the survivor must receive one discovery probe and the expected session starts");
    }
    finally
    {
      finishRetry.countDown();
      handshake.sendNextReply.countDown();
      try
      {
        survivor.shutdown();
@@ -1453,6 +1474,121 @@
  }
  @Test(timeOut = 120_000)
  public void queuedStopSkipsTheDiscoveryResponderRetry() throws Exception
  {
    TestCaseUtils.initializeTestBackend(true);
    setConnectionTimeout(LONG_CONNECTION_TIMEOUT_MS);
    final WithholdingReplicationServer former = new WithholdingReplicationServer(LARGE_WINDOW);
    final WithholdingReplicationServer responder = new WithholdingReplicationServer(LARGE_WINDOW, 4);
    final DelayedFailoverHandshake handshake = new DelayedFailoverHandshake(1, 1);
    Thread stopping = null;
    try
    {
      responder.differentGroup = true;
      responder.start();
      final LDAPReplicationDomain domain = startDomain(former, 100000, responder.getAddress());
      final ReplicationBroker broker = brokerOf(domain);
      assertEquals(domain.getRsServerId(), former.serverId);
      assertEquals(replaceDescription("elect the former replication server at failover"), ResultCode.SUCCESS);
      former.waitForUpdates(1);
      responder.differentGroup = false;
      former.beforeStartReply = () -> {
        former.listenSocket.close();
        return null;
      };
      responder.delayedFailoverHandshake = handshake;
      handshake.sendNextReply.countDown();
      former.closeTheSession();
      newTimer().repeatUntilSuccess(() -> assertEquals(handshake.starts.get(), 2,
          "the responder must be withholding its first session start reply"));
      final Thread stop = startThread("stop during the responder's start handshake", broker::stop);
      stopping = stop;
      newTimer().repeatUntilSuccess(() -> assertTrue(
          stop.getState() == Thread.State.BLOCKED && isIn(stop, ReplicationBroker.class, "stop"),
          "stop must be waiting for the reconnect to release its lock"));
      stop.join(stopBoundMS());
      assertFalse(stop.isAlive(), "stop did not finish after the first start reply timed out");
      assertEquals(handshake.starts.get(), 2, "the broker retried the responder with a stop queued");
    }
    finally
    {
      try
      {
        responder.shutdown();
      }
      finally
      {
        cleanUp(former, stopping);
        setConnectionTimeout(SHORT_CONNECTION_TIMEOUT_MS);
      }
    }
  }
  @Test(timeOut = 120_000)
  public void queuedStopSkipsTheFallbackAfterContinuedDiscovery() throws Exception
  {
    TestCaseUtils.initializeTestBackend(true);
    final WithholdingReplicationServer former = new WithholdingReplicationServer(LARGE_WINDOW);
    final WithholdingReplicationServer responder = new WithholdingReplicationServer(LARGE_WINDOW, 4);
    final DelayedFailoverHandshake handshake = new DelayedFailoverHandshake(0, 0);
    Thread stopping = null;
    try
    {
      setConnectionTimeout(LONG_CONNECTION_TIMEOUT_MS);
      responder.differentGroup = true;
      responder.start();
      final LDAPReplicationDomain domain = startDomain(former, 100000, responder.getAddress());
      final ReplicationBroker broker = brokerOf(domain);
      assertEquals(domain.getRsServerId(), former.serverId);
      newTimer().repeatUntilSuccess(() -> assertNotNull(former.session.get()));
      responder.differentGroup = false;
      responder.delayedFailoverHandshake = handshake;
      former.beforeStartReply = () -> {
        former.listenSocket.close();
        return null;
      };
      former.dropTheSession();
      await(handshake.nextStartReceived);
      newTimer().repeatUntilSuccess(() -> assertTrue(Thread.getAllStackTraces().keySet().stream()
          .anyMatch(thread -> waitsIn(thread, ReplicationBroker.class, "retryElectedConnection")),
          "the broker must be waiting for the responder in continued discovery"));
      final Thread stop = startThread("stop during continued discovery", broker::stop);
      stopping = stop;
      newTimer().repeatUntilSuccess(() -> assertTrue(
          stop.getState() == Thread.State.BLOCKED && isIn(stop, ReplicationBroker.class, "stop"),
          "stop must be waiting for the reconnect to release its lock"));
      handshake.sendNextReply.countDown();
      stop.join(stopBoundMS());
      assertFalse(stop.isAlive(), "stop did not finish after the discovery reply");
      assertEquals(handshake.starts.get(), 1, "the responder must receive only the discovery probe");
    }
    finally
    {
      handshake.sendNextReply.countDown();
      try
      {
        responder.shutdown();
      }
      finally
      {
        try
        {
          cleanUp(former, stopping);
        }
        finally
        {
          setConnectionTimeout(SHORT_CONNECTION_TIMEOUT_MS);
        }
      }
    }
  }
  @Test(timeOut = 120_000)
  public void reconnectClosesTheSessionWhenTopologyTimesOut() throws Exception
  {
    TestCaseUtils.initializeTestBackend(true);
@@ -2377,17 +2513,22 @@
    return false;
  }
  private static DSRSShutdownSync shutdownSync() throws Exception
  {
    final Field shutdownSync = MultimasterReplication.class.getDeclaredField("dsrsShutdownSync");
    shutdownSync.setAccessible(true);
    return (DSRSShutdownSync) shutdownSync.get(null);
  }
  /**
   * Returns the CSN of the announcement that the replica of the domain went offline which the
   * shutdown of a collocated replication server would wait for the forward of, if there is one.
   */
  private CSN offlineAnnouncementOfTheReplica() throws Exception
  {
    final Field shutdownSync = MultimasterReplication.class.getDeclaredField("dsrsShutdownSync");
    shutdownSync.setAccessible(true);
    final Field announcements = DSRSShutdownSync.class.getDeclaredField("replicaOfflineMsgs");
    announcements.setAccessible(true);
    final Map<?, ?> byDomain = (Map<?, ?>) announcements.get(shutdownSync.get(null));
    final Map<?, ?> byDomain = (Map<?, ?>) announcements.get(shutdownSync());
    final Map<?, ?> byReplica = (Map<?, ?>) byDomain.get(baseDN);
    final Object announcement = byReplica != null ? byReplica.get(DS_ID) : null;
    if (announcement == null)
@@ -2535,6 +2676,7 @@
    /** Whether this server is away: it then sends no heartbeat, and answers no connection either. */
    private volatile boolean away;
    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<>();
@@ -2694,6 +2836,15 @@
          {
            lastOffline = (ReplicaOfflineMsg) msg;
          }
          else if (msg instanceof WindowProbeMsg)
          {
            final Callable<Void> onProbe = onFirstWindowProbe;
            if (onProbe != null)
            {
              onFirstWindowProbe = null;
              onProbe.call();
            }
          }
        }
      }
      catch (Exception e)