From 729d3630daca045c4c57b5f47d91fa92a2c5de61 Mon Sep 17 00:00:00 2001
From: Valery Kharseko <vharseko@3a-systems.ru>
Date: Sat, 28 Nov 2026 09:45:53 +0000
Subject: [PATCH] [#1208] Try a discovery responder before declaring replication isolation (#1343)
---
opendj-server-legacy/src/main/java/org/opends/server/replication/service/ReplicationBroker.java | 57 ++++++++++++-
opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/ReplicationBrokerStopTest.java | 157 +++++++++++++++++++++++++++++++++++++-
2 files changed, 201 insertions(+), 13 deletions(-)
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/replication/service/ReplicationBroker.java b/opendj-server-legacy/src/main/java/org/opends/server/replication/service/ReplicationBroker.java
index ee63266..3383c67 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/replication/service/ReplicationBroker.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/replication/service/ReplicationBroker.java
@@ -37,6 +37,7 @@
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
+import java.util.TreeMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
@@ -94,6 +95,7 @@
private static final class ConnectedRS
{
private static final ConnectedRS NO_CONNECTED_RS = new ConnectedRS(NO_CONNECTED_SERVER);
+ private static final ConnectedRS CONNECTION_REFUSED = new ConnectedRS(NO_CONNECTED_SERVER);
/** The info of the RS we are connected to. */
private final ReplicationServerInfo rsInfo;
@@ -375,7 +377,7 @@
shutdown = false;
stopping = null;
this.rcvWindow = getMaxRcvWindow();
- connectAsDataServer();
+ connectAsDataServer(null);
}
}
@@ -832,9 +834,10 @@
* decide with which RS the full handshake (phase 1 then phase 2) will be
* finally performed.
*
+ * @param formerServerURL the previous server on the first reconnect after losing its session, or null
* @throws NumberFormatException address was invalid
*/
- private void connectAsDataServer()
+ private void connectAsDataServer(String formerServerURL)
{
/*
* If a first connect or a connection failure occur, we go through here.
@@ -883,8 +886,14 @@
debugInfo("phase 2 : will perform PhaseOneH with the preferred RS=" + evals.getBestRS());
}
- final ConnectedRS electedRS = performPhaseOneHandshake(
- evals.getBestRS().getServerURL(), true);
+ final ReplicationServerInfo preferred = evals.getBestRS();
+ ConnectedRS electedRS = performPhaseOneHandshake(preferred.getServerURL(), true);
+ if (electedRS == ConnectedRS.CONNECTION_REFUSED && preferred.getServerURL().equals(formerServerURL)
+ && stopping == null && !permanentlyStopped)
+ {
+ // Discovery can still see the former RS while its listener is closing.
+ electedRS = tryAnotherDiscoveryResponder(rsInfos, preferred.getServerId());
+ }
final ReplicationServerInfo electedRsInfo = electedRS.rsInfo;
if (electedRsInfo != null)
{
@@ -954,6 +963,34 @@
}
}
+ /** Tries one compatible discovery responder before publishing isolation. */
+ private ConnectedRS tryAnotherDiscoveryResponder(Map<Integer, ReplicationServerInfo> rsInfos, int refusedServerId)
+ {
+ final Map<Integer, ReplicationServerInfo> candidates = new TreeMap<>(rsInfos);
+ candidates.remove(refusedServerId);
+ candidates.values().removeIf(info -> !hasCompatibleGeneration(info));
+ if (candidates.isEmpty())
+ {
+ return ConnectedRS.noConnectedRS();
+ }
+
+ final RSEvaluations evals = computeBestReplicationServer(true, -1, state, candidates, getServerId(), getGroupId(),
+ getGenerationID());
+ final ConnectedRS replacement = performPhaseOneHandshake(evals.getBestRS().getServerURL(), true);
+ // The generation may have changed since discovery.
+ if (replacement.rsInfo != null && !hasCompatibleGeneration(replacement.rsInfo))
+ {
+ close(replacement.session);
+ return ConnectedRS.noConnectedRS();
+ }
+ return replacement;
+ }
+
+ private boolean hasCompatibleGeneration(ReplicationServerInfo info)
+ {
+ return info.getGenerationId() == -1 || info.getGenerationId() == getGenerationID();
+ }
+
private void computeNewTopology(List<RSInfo> newRSInfos)
{
final int rsServerId = getRsServerId();
@@ -1154,6 +1191,7 @@
Session newSession = null;
Socket socket = null;
boolean hasConnected = false;
+ ConnectedRS failure = ConnectedRS.noConnectedRS();
LocalizableMessage errorMessage = null;
try
@@ -1238,6 +1276,7 @@
catch (ConnectException e)
{
logger.traceException(e);
+ failure = ConnectedRS.CONNECTION_REFUSED;
errorMessage = WARN_NO_CHANGELOG_SERVER_LISTENING.get(getServerId(), serverURL, getBaseDN());
}
catch (SocketTimeoutException e)
@@ -1317,7 +1356,8 @@
logger.trace(errorMessage);
}
}
- return setConnectedRS(ConnectedRS.noConnectedRS());
+ setConnectedRS(ConnectedRS.noConnectedRS());
+ return failure;
}
/**
@@ -1368,6 +1408,7 @@
logger.error(WARN_EXCEPTION_STARTING_SESSION_PHASE,
getServerId(), electedRS.rsInfo.getServerURL(), getBaseDN(), stackTraceToSingleLineString(e));
+ close(electedRS.session);
setConnectedRS(ConnectedRS.noConnectedRS());
return null;
}
@@ -2292,6 +2333,8 @@
}
ConnectedRS rs = connectedRS.get();
+ String formerServerURL = infiniteTry && failingSession != null && failingSession == rs.session && !connectionError
+ ? rs.rsInfo.getServerURL() : null;
if (failingSession == rs.session && !rs.equals(ConnectedRS.noConnectedRS()))
{
rs = setConnectedRS(ConnectedRS.noConnectedRS());
@@ -2320,7 +2363,9 @@
{
try
{
- connectAsDataServer();
+ final String previousServerURL = formerServerURL;
+ formerServerURL = null;
+ connectAsDataServer(previousServerURL);
rs = connectedRS.get();
}
catch (Exception e)
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 4de4616..930dfad 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
@@ -24,11 +24,13 @@
import static org.opends.server.protocols.internal.Requests.*;
import static org.testng.Assert.*;
+import java.io.EOFException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
+import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Collections;
@@ -36,8 +38,11 @@
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
@@ -1063,18 +1068,123 @@
}
}
+ @Test(timeOut = 120_000)
+ public void failoverTriesAnotherDiscoveryResponderWhenTheFormerRsRefusesConnection() 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);
+ try
+ {
+ survivor.differentGroup = true;
+ survivor.start();
+ final LDAPReplicationDomain domain = startDomain(former, 100000, survivor.getPort());
+ assertEquals(domain.getRsServerId(), former.serverId);
+ newTimer().repeatUntilSuccess(() -> assertNotNull(former.session.get()));
+ assertEquals(replaceDescription("already on both replication servers"), ResultCode.SUCCESS);
+ former.waitForUpdates(1);
+ survivor.state.update(former.receivedUpdateCSNs().get(0));
+ // The former RS has the latest local change, so it wins discovery even with both RSs in the same group.
+ assertEquals(replaceDescription("before failover"), ResultCode.SUCCESS);
+ former.waitForUpdates(2);
+ 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;
+ };
+ survivor.beforeStartReply = () -> {
+ if (survivorStarts.incrementAndGet() == 2)
+ {
+ survivorRetry.countDown();
+ await(finishRetry);
+ }
+ return null;
+ };
+ former.closeTheSession();
+
+ await(survivorRetry);
+ assertFalse(domain.hasConnectionError(), "the broker declared isolation before trying the discovery responder");
+ finishRetry.countDown();
+ newTimer().repeatUntilSuccess(() -> {
+ assertEquals(domain.getRsServerId(), survivor.serverId);
+ assertFalse(domain.hasConnectionError());
+ });
+ 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");
+ }
+ finally
+ {
+ finishRetry.countDown();
+ try
+ {
+ survivor.shutdown();
+ }
+ finally
+ {
+ cleanUp(former);
+ }
+ }
+ }
+
+ @Test(timeOut = 120_000)
+ public void reconnectClosesTheSessionWhenTopologyTimesOut() throws Exception
+ {
+ TestCaseUtils.initializeTestBackend(true);
+ final WithholdingReplicationServer rs = new WithholdingReplicationServer(LARGE_WINDOW);
+ try
+ {
+ final LDAPReplicationDomain domain = startDomain(rs);
+ newTimer().repeatUntilSuccess(() -> assertNotNull(rs.session.get()));
+ final Session originalSession = rs.session.get();
+
+ final CompletableFuture<ReplicationMsg> nextRead = new CompletableFuture<>();
+ rs.readInsteadOfSendingTopology.set(nextRead);
+ rs.dropTheSession();
+
+ // Observe the broker closing the provisional socket before the fixture is shut down.
+ final Throwable failure = expectThrows(ExecutionException.class, () -> nextRead.get(30, SECONDS)).getCause();
+ assertTrue(failure instanceof EOFException
+ || (failure instanceof SocketException && String.valueOf(failure.getMessage()).startsWith("Connection reset")),
+ "expected EOF or connection reset on the provisional session, got " + failure);
+
+ newTimer().repeatUntilSuccess(() -> {
+ final Session reconnected = rs.session.get();
+ assertNotNull(reconnected, "the replication server did not establish a later session");
+ assertNotSame(reconnected, originalSession);
+ assertTrue(domain.isConnected());
+ assertFalse(domain.hasConnectionError());
+ });
+ }
+ finally
+ {
+ cleanUp(rs);
+ }
+ }
+
private LDAPReplicationDomain startDomain(WithholdingReplicationServer rs) throws Exception
{
// Heartbeats far apart: the session stays up whatever the replication server reads.
return startDomain(rs, 100000);
}
- private LDAPReplicationDomain startDomain(WithholdingReplicationServer rs, long heartbeatIntervalMS)
- throws Exception
+ private LDAPReplicationDomain startDomain(WithholdingReplicationServer rs, long heartbeatIntervalMS,
+ int... additionalPorts) throws Exception
{
rs.start();
- final DomainFakeCfg conf = new DomainFakeCfg(baseDN, DS_ID,
- new TreeSet<>(Collections.singleton("127.0.0.1:" + rs.getPort())));
+ final SortedSet<String> servers = new TreeSet<>(Collections.singleton("127.0.0.1:" + rs.getPort()));
+ for (int port : additionalPorts)
+ {
+ servers.add("127.0.0.1:" + port);
+ }
+ final DomainFakeCfg conf = new DomainFakeCfg(baseDN, DS_ID, servers);
conf.setHeartbeatInterval(heartbeatIntervalMS);
final LDAPReplicationDomain domain = MultimasterReplication.createNewDomain(conf);
domain.start();
@@ -1326,6 +1436,7 @@
{
private static final int RS_ID = 2;
+ private final int serverId;
private final int window;
private final ServerSocket listenSocket;
/** The latest session started, until it ends. */
@@ -1345,6 +1456,11 @@
private boolean reading = true;
/** Whether this server is away: it then sends no heartbeat, and answers no connection either. */
private volatile boolean away;
+ private volatile boolean differentGroup;
+ private volatile Callable<Void> beforeStartReply;
+ /** If set, read from the next session after StartSessionMsg instead of sending its topology. */
+ private final AtomicReference<CompletableFuture<ReplicationMsg>> readInsteadOfSendingTopology =
+ new AtomicReference<>();
WithholdingReplicationServer() throws IOException
{
@@ -1353,8 +1469,14 @@
WithholdingReplicationServer(int window) throws IOException
{
+ this(window, RS_ID);
+ }
+
+ WithholdingReplicationServer(int window, int serverId) throws IOException
+ {
super(ReplicationBrokerStopTest.class.getSimpleName() + " replication server");
setDaemon(true);
+ this.serverId = serverId;
this.window = window;
listenSocket = new ServerSocket(0, 50, InetAddress.getLoopbackAddress());
}
@@ -1400,9 +1522,15 @@
s = new ReplSessionSecurity().createServerSession(socket, MultimasterReplication.getConnectionTimeoutMS());
sessions.add(s);
final ServerStartMsg start = (ServerStartMsg) s.receive();
+ final Callable<Void> hook = beforeStartReply;
+ if (hook != null)
+ {
+ hook.call();
+ }
final String url = "127.0.0.1:" + getPort();
- s.publish(new ReplServerStartMsg(RS_ID, url, start.getBaseDN(), window, state.duplicate(),
- start.getGenerationId(), start.getSSLEncryption(), start.getGroupId(), 5000));
+ final byte groupId = differentGroup ? (byte) (start.getGroupId() + 1) : start.getGroupId();
+ s.publish(new ReplServerStartMsg(serverId, url, start.getBaseDN(), window, state.duplicate(),
+ start.getGenerationId(), start.getSSLEncryption(), groupId, 5000));
if (!start.getSSLEncryption())
{
s.stopEncryption();
@@ -1412,8 +1540,23 @@
return;
}
sessionsStarted.incrementAndGet();
+ final CompletableFuture<ReplicationMsg> nextRead = readInsteadOfSendingTopology.getAndSet(null);
+ if (nextRead != null)
+ {
+ try
+ {
+ // Give the broker its handshake timeout plus time to close the socket.
+ s.setSoTimeout(MultimasterReplication.getConnectionTimeoutMS() + 5_000);
+ nextRead.complete(s.receive());
+ }
+ catch (Exception e)
+ {
+ nextRead.completeExceptionally(e);
+ }
+ return;
+ }
s.publish(new TopologyMsg(new ArrayList<DSInfo>(), Collections.singletonList(
- new RSInfo(RS_ID, url, start.getGenerationId(), start.getGroupId(), 1))));
+ new RSInfo(serverId, url, start.getGenerationId(), groupId, 1))));
s.setSoTimeout(0);
session.set(s);
startHeartbeats(s, start.getHeartbeatInterval());
--
Gitblit v1.10.0