From 52694d4c03f9b09b2e52f389701255f3c78dfd9b Mon Sep 17 00:00:00 2001
From: Valery Kharseko <vharseko@3a-systems.ru>
Date: Mon, 30 Nov 2026 08:18:21 +0000
Subject: [PATCH] Bound replication server discovery during failover (#1346)

---
 opendj-server-legacy/src/main/java/org/opends/server/replication/service/ReplicationBroker.java |  548 ++++++++++++++++++++++++++++++++++++++++++------------
 1 files changed, 423 insertions(+), 125 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 2bc3caf..176c02d 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
@@ -39,8 +39,14 @@
 import java.util.Set;
 import java.util.TreeMap;
 import java.util.concurrent.ConcurrentSkipListMap;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorCompletionService;
+import java.util.concurrent.Future;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.RejectedExecutionException;
 import java.util.concurrent.ScheduledFuture;
 import java.util.concurrent.Semaphore;
+import java.util.concurrent.ThreadPoolExecutor;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicReference;
@@ -83,6 +89,7 @@
 import org.opends.server.replication.protocol.WindowMsg;
 import org.opends.server.replication.protocol.WindowProbeMsg;
 import org.opends.server.types.HostPort;
+import org.opends.server.util.StaticUtils;
 
 import static org.opends.messages.ReplicationMessages.*;
 import static org.opends.server.replication.protocol.ProtocolVersion.*;
@@ -92,6 +99,14 @@
 /** The broker for Multi-master Replication. */
 public class ReplicationBroker
 {
+  private static final int MAX_DISCOVERY_PROBES = 4;
+  /** Give a fast probe time to finish before opening more handshakes on the other RSs. */
+  private static final long DISCOVERY_PROBE_DELAY_NANOS = TimeUnit.MILLISECONDS.toNanos(250);
+  /** Bound discovery rounds even when the full session handshake has no configured timeout. */
+  private static final int DEFAULT_DISCOVERY_TIMEOUT_MILLIS = 5_000;
+  /** Allow other candidates to reply once a compatible RS in the preferred group is available. */
+  private static final long DISCOVERY_REPLY_GRACE_NANOS = TimeUnit.SECONDS.toNanos(1);
+
   /**
    * Immutable class containing information about whether the broker is
    * connected to an RS and data associated to this connected RS.
@@ -277,6 +292,9 @@
   private int halfRcvWindow = rcvWindow / 2;
   private int timeout;
   private final ReplSessionSecurity replSessionSecurity;
+  private final ThreadPoolExecutor discoveryExecutor;
+  @GuardedBy("connectPhaseLock")
+  private int nextDiscoveryProbe;
   /**
    * The RS this DS is currently connected to.
    * <p>
@@ -396,6 +414,14 @@
     this.state = state;
     this.config = config;
     this.replSessionSecurity = replSessionSecurity;
+    this.discoveryExecutor = new ThreadPoolExecutor(MAX_DISCOVERY_PROBES, MAX_DISCOVERY_PROBES, 30, TimeUnit.SECONDS,
+        new LinkedBlockingQueue<>(), task -> {
+          final DirectoryThread thread = new DirectoryThread(task,
+              "Replica DS(" + getServerId() + ") discovering replication servers for " + getBaseDN());
+          thread.setDaemon(true);
+          return thread;
+        });
+    this.discoveryExecutor.allowCoreThreadTimeOut(true);
     this.rcvWindow = getMaxRcvWindow();
     this.halfRcvWindow = rcvWindow / 2;
     this.shutdown = true;
@@ -421,7 +447,7 @@
       shutdown = false;
       stopping = null;
       this.rcvWindow = getMaxRcvWindow();
-      connectAsDataServer(null);
+      connectAsDataServer(null, false);
     }
   }
 
@@ -832,26 +858,238 @@
     }
   }
 
-  /**
-   * Collects replies for server selection and remembers an RS that did not answer its start message.
-   * Prefer a different RS from the one whose session just ended.
-   */
-  private String collectReplicationServersInfo(Map<Integer, ReplicationServerInfo> rsInfos, String previousRS)
+  private static final class DiscoveryProbe
   {
-    String timedOutRS = null;
-    for (String serverUrl : getReplicationServerUrls())
+    private final String url;
+    private final Socket socket = new Socket();
+    private final long deadline;
+    private volatile boolean started;
+    private volatile boolean awaitingStartReply;
+    private volatile boolean cancelled;
+    private ConnectedRS result;
+    private LocalizableMessage failure;
+    private boolean collected;
+
+    private DiscoveryProbe(String url, long deadline)
     {
-      final ConnectedRS probe = performPhaseOneHandshake(serverUrl, false, false);
-      if (probe.rsInfo != null)
+      this.url = url;
+      this.deadline = deadline;
+    }
+
+    private int remainingTimeoutMillis() throws SocketTimeoutException
+    {
+      final long remaining = deadline - System.nanoTime();
+      if (remaining <= 0)
       {
-        rsInfos.put(probe.getServerId(), probe.rsInfo);
+        throw new SocketTimeoutException("Replication server discovery deadline expired");
       }
-      else if (probe == ConnectedRS.START_REPLY_TIMED_OUT && (timedOutRS == null || timedOutRS.equals(previousRS)))
+      return (int) Math.max(1, TimeUnit.NANOSECONDS.toMillis(remaining));
+    }
+  }
+
+  /** A batch of staggered probes with one deadline across discovery and any continuation. */
+  private final class DiscoveryRound implements AutoCloseable
+  {
+    private final int connectionTimeout = MultimasterReplication.getConnectionTimeoutMS();
+    private final long discoveryDeadline;
+    private final ExecutorCompletionService<DiscoveryProbe> completions = new ExecutorCompletionService<>(
+        discoveryExecutor);
+    private final List<DiscoveryProbe> probes = new ArrayList<>();
+    private final int firstProbe;
+    private long nextProbeAt = System.nanoTime();
+    private int submitted;
+    private int inFlight;
+    private boolean discoveryTimedOut;
+    private boolean closed;
+    private ScheduledFuture<?> expiry;
+
+    private DiscoveryRound()
+    {
+      final long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(
+          connectionTimeout == 0 ? DEFAULT_DISCOVERY_TIMEOUT_MILLIS : connectionTimeout);
+      final StopInProgress stop = stopping;
+      discoveryDeadline = stop != null && stop.bounded && stop.writeDeadline - deadline < 0
+          ? stop.writeDeadline : deadline;
+      for (String url : getReplicationServerUrls())
       {
-        timedOutRS = serverUrl;
+        probes.add(new DiscoveryProbe(url, discoveryDeadline));
+      }
+      firstProbe = probes.isEmpty() ? 0 : nextDiscoveryProbe % probes.size();
+    }
+
+    private void collect(Map<Integer, ReplicationServerInfo> rsInfos, boolean useReplyGrace)
+    {
+      if (closed)
+      {
+        return;
+      }
+      long deadline = discoveryDeadline;
+      try
+      {
+        while (inFlight > 0 || submitted < probes.size())
+        {
+          final long now = System.nanoTime();
+          final long remaining = Math.max(0, deadline - now);
+          final boolean canSubmit = submitted < probes.size() && inFlight < MAX_DISCOVERY_PROBES;
+          final long untilNextProbe = Math.max(0, nextProbeAt - now);
+          if (canSubmit && untilNextProbe == 0 && remaining > 0)
+          {
+            final DiscoveryProbe probe = probes.get((firstProbe + submitted) % probes.size());
+            completions.submit(() -> {
+              if (!probe.cancelled && probe.deadline - System.nanoTime() > 0)
+              {
+                probe.started = true;
+                probe.result = performPhaseOneHandshake(probe.url, false, false, probe.socket, probe);
+              }
+              return probe;
+            });
+            submitted++;
+            inFlight++;
+            nextProbeAt = now + DISCOVERY_PROBE_DELAY_NANOS;
+            continue;
+          }
+
+          final long wait = canSubmit ? Math.min(remaining, untilNextProbe) : remaining;
+          final Future<DiscoveryProbe> next = completions.poll(wait, TimeUnit.NANOSECONDS);
+          if (next == null)
+          {
+            if (deadline - System.nanoTime() <= 0)
+            {
+              break;
+            }
+            continue;
+          }
+          inFlight--;
+          final DiscoveryProbe probe = next.get();
+          nextProbeAt = System.nanoTime();
+          if (probe.result == null)
+          {
+            continue;
+          }
+          probe.collected = true;
+          final ReplicationServerInfo info = probe.result.rsInfo;
+          if (useReplyGrace && hasCompatibleGeneration(info) && info.getGroupId() == getGroupId())
+          {
+            final long graceDeadline = System.nanoTime() + DISCOVERY_REPLY_GRACE_NANOS;
+            if (graceDeadline - deadline < 0)
+            {
+              deadline = graceDeadline;
+            }
+          }
+        }
+      }
+      catch (InterruptedException e)
+      {
+        Thread.currentThread().interrupt();
+      }
+      catch (ExecutionException e)
+      {
+        logger.traceException(e);
+      }
+      discoveryTimedOut |= deadline == discoveryDeadline && System.nanoTime() - deadline >= 0;
+
+      // Retain the configured order even if replies arrive out of order.
+      for (DiscoveryProbe probe : probes)
+      {
+        if (probe.collected && probe.result.rsInfo != null)
+        {
+          final ReplicationServerInfo info = probe.result.rsInfo;
+          rsInfos.put(info.getServerId(), info);
+        }
       }
     }
-    return timedOutRS;
+
+    private String timedOutServer(String previousRS)
+    {
+      // With no session timeout, retry a silent server through discovery so other candidates still get a turn.
+      if (connectionTimeout == 0)
+      {
+        return null;
+      }
+      String timedOutRS = null;
+      for (DiscoveryProbe probe : probes)
+      {
+        final boolean timedOut = probe.collected
+            ? probe.result == ConnectedRS.START_REPLY_TIMED_OUT || probe.cancelled && probe.awaitingStartReply
+            : probe.awaitingStartReply;
+        if (timedOut && (timedOutRS == null || timedOutRS.equals(previousRS)))
+        {
+          timedOutRS = probe.url;
+        }
+      }
+      return timedOutRS;
+    }
+
+    /** Keep the discovery deadline even while the elected session has its own timeout. */
+    private void expirePendingProbesAtDeadline()
+    {
+      if (inFlight > 0)
+      {
+        try
+        {
+          expiry = DirectoryServer.getInstance().getServerContext().getCronExecutorService().schedule(
+              this::closeProbeSockets, Math.max(0, discoveryDeadline - System.nanoTime()), TimeUnit.NANOSECONDS);
+        }
+        catch (RejectedExecutionException e)
+        {
+          // Server shutdown stops the scheduler before it finalizes replication.
+          close();
+        }
+      }
+    }
+
+    private void closeProbeSockets()
+    {
+      for (DiscoveryProbe probe : probes)
+      {
+        probe.cancelled = true;
+        StaticUtils.close(probe.socket);
+      }
+    }
+
+    @Override
+    public void close()
+    {
+      if (closed)
+      {
+        return;
+      }
+      closed = true;
+      if (expiry != null)
+      {
+        expiry.cancel(false);
+      }
+      // Discovery runs under connectPhaseLock, so this queue contains only this batch.
+      // Closing the sockets also unblocks TLS and protocol reads in the running probes.
+      discoveryExecutor.getQueue().clear();
+      closeProbeSockets();
+      if (submitted < probes.size())
+      {
+        nextDiscoveryProbe = (firstProbe + submitted) % probes.size();
+      }
+      else if (discoveryTimedOut && probes.size() > MAX_DISCOVERY_PROBES)
+      {
+        // A probe submitted just before the deadline may have had almost no time to answer.
+        nextDiscoveryProbe = (firstProbe + MAX_DISCOVERY_PROBES) % probes.size();
+      }
+      else
+      {
+        nextDiscoveryProbe = 0;
+      }
+
+      for (DiscoveryProbe probe : probes)
+      {
+        if (probe.collected && probe.failure != null)
+        {
+          logPhaseOneHandshakeFailure(probe.failure, false, false);
+        }
+        else if (!probe.collected && probe.started && discoveryTimedOut)
+        {
+          logPhaseOneHandshakeFailure(WARN_TIMEOUT_CONNECTING_TO_RS.get(getServerId(), probe.url, getBaseDN()),
+              false, false);
+        }
+      }
+    }
   }
 
   /**
@@ -878,9 +1116,10 @@
    * finally performed.
    *
    * @param previousRS the RS whose established session just ended, or null outside the first failover attempt
+   * @param planned whether monitoring initiated the switch from that session
    * @throws NumberFormatException address was invalid
    */
-  private void connectAsDataServer(String previousRS)
+  private void connectAsDataServer(String previousRS, boolean planned)
   {
     /*
      * If a first connect or a connection failure occur, we go through here.
@@ -908,68 +1147,44 @@
         debugInfo("phase 1 : will perform PhaseOneH with each RS in order to elect the preferred one");
       }
 
-      // Get info from every available replication servers
       final Map<Integer, ReplicationServerInfo> rsInfos = new ConcurrentSkipListMap<>();
-      final String timedOutRS = collectReplicationServersInfo(rsInfos, previousRS);
-      computeNewTopology(toRSInfos(rsInfos));
+      try (DiscoveryRound discovery = new DiscoveryRound())
+      {
+        // The former RS can still answer a planned switch. Give alternatives the full budget while running.
+        discovery.collect(rsInfos, !planned || stopping != null);
+        if (Thread.currentThread().isInterrupted())
+        {
+          return;
+        }
+        computeNewTopology(toRSInfos(rsInfos));
 
-      final boolean hasReplies = !rsInfos.isEmpty();
-      final boolean canRetry = previousRS != null && stopping == null && !permanentlyStopped;
-      String electedURL = null;
-      if (hasReplies)
-      {
-        final RSEvaluations evals = computeBestReplicationServer(true, -1, state,
-            rsInfos, serverId, getGroupId(), getGenerationID());
-        if (logger.isTraceEnabled())
+        final boolean canRetry = previousRS != null && stopping == null && !permanentlyStopped;
+        final boolean hasReplies = !rsInfos.isEmpty();
+        String electedURL = null;
+        if (hasReplies)
         {
-          debugInfo("phase 2 : will perform PhaseOneH with the preferred RS=" + evals.getBestRS());
+          final RSEvaluations evals = computeBestReplicationServer(true, -1, state,
+              rsInfos, serverId, getGroupId(), getGenerationID());
+          if (logger.isTraceEnabled())
+          {
+            debugInfo("phase 2 : will perform PhaseOneH with the preferred RS=" + evals.getBestRS());
+          }
+          electedURL = evals.getBestRS().getServerURL();
         }
-        electedURL = evals.getBestRS().getServerURL();
-      }
-      else if (canRetry)
-      {
-        // A live RS can miss one start reply under load. Use the retry to establish the
-        // actual session before declaring isolation and rejecting LDAP writes.
-        electedURL = timedOutRS;
-      }
+        else if (canRetry)
+        {
+          // A live RS can miss one start reply under load. Use the retry to establish the
+          // actual session before declaring isolation and rejecting LDAP writes.
+          electedURL = discovery.timedOutServer(previousRS);
+        }
 
-      if (electedURL == null)
-      {
-        setConnectedRS(ConnectedRS.noConnectedRS());
-      }
-      else
-      {
-        final boolean canRetryElected = canRetry && hasReplies;
-        ConnectedRS electedRS = performPhaseOneHandshake(electedURL, true, canRetryElected);
-        if (electedRS.rsInfo == null && canRetryElected && stopping == null && !permanentlyStopped)
+        if (electedURL == null)
         {
-          if (electedRS == ConnectedRS.START_REPLY_TIMED_OUT)
-          {
-            electedRS = performPhaseOneHandshake(electedURL, true, false);
-          }
-          else if (electedURL.equals(previousRS))
-          {
-            final ReplicationServerInfo responder = electedRS == ConnectedRS.CONNECTION_REFUSED
-                ? selectDiscoveryResponder(rsInfos, previousRS) : null;
-            if (responder != null)
-            {
-              electedRS = connectToDiscoveryResponder(responder);
-            }
-            else if (timedOutRS != null && !electedURL.equals(timedOutRS))
-            {
-              // The other RS can still accept a session after missing its discovery reply.
-              electedRS = performPhaseOneHandshake(timedOutRS, true, false);
-            }
-          }
+          setConnectedRS(ConnectedRS.noConnectedRS());
         }
-        final StopInProgress stop = stopping;
-        if (electedRS.rsInfo != null)
+        else
         {
-          finishElectedConnection(electedRS, rsInfos);
-        }
-        else if (stop != null && electedURL.equals(previousRS))
-        {
-          connectToReplacementForStop(stop, previousRS, rsInfos);
+          connectToElectedServer(discovery, rsInfos, electedURL, previousRS, canRetry && hasReplies);
         }
       }
 
@@ -992,7 +1207,7 @@
               rs.replicationServer, getGenerationID(), rsGenId);
         }
       }
-      else
+      else if (!Thread.currentThread().isInterrupted())
       {
          // This server could not find any replicationServer.
          // It's going to start in degraded mode. Log a message.
@@ -1015,6 +1230,80 @@
     }
   }
 
+  private void connectToElectedServer(DiscoveryRound discovery, Map<Integer, ReplicationServerInfo> rsInfos,
+      String electedURL, String previousRS, boolean canRetry)
+  {
+    if (canRetry)
+    {
+      discovery.expirePendingProbesAtDeadline();
+    }
+    else
+    {
+      discovery.close();
+    }
+    ConnectedRS electedRS = performPhaseOneHandshake(electedURL, true, canRetry);
+    if (electedRS.rsInfo == null && canRetry && stopping == null && !permanentlyStopped)
+    {
+      electedRS = retryElectedConnection(discovery, rsInfos, electedURL, previousRS, electedRS);
+    }
+    discovery.close();
+
+    final StopInProgress stop = stopping;
+    if (electedRS.rsInfo != null)
+    {
+      finishElectedConnection(electedRS, rsInfos);
+    }
+    else if (stop != null && electedURL.equals(previousRS) && !Thread.currentThread().isInterrupted())
+    {
+      connectToReplacementForStop(stop, previousRS, rsInfos);
+    }
+  }
+
+  private ConnectedRS retryElectedConnection(DiscoveryRound discovery, Map<Integer, ReplicationServerInfo> rsInfos,
+      String electedURL, String previousRS, ConnectedRS failure)
+  {
+    if (failure == ConnectedRS.START_REPLY_TIMED_OUT)
+    {
+      discovery.close();
+      return performPhaseOneHandshake(electedURL, true, false);
+    }
+    final boolean electedFormerRS = electedURL.equals(previousRS);
+    if (!electedFormerRS && failure != ConnectedRS.CONNECTION_REFUSED)
+    {
+      return failure;
+    }
+
+    ReplicationServerInfo responder = selectDiscoveryResponder(rsInfos, electedURL);
+    if (responder == null)
+    {
+      // Keep listening for candidates still within the original discovery budget.
+      discovery.collect(rsInfos, true);
+      if (Thread.currentThread().isInterrupted())
+      {
+        return failure;
+      }
+      computeNewTopology(toRSInfos(rsInfos));
+      responder = selectDiscoveryResponder(rsInfos, electedURL);
+    }
+    final String timedOutRS = electedFormerRS && responder == null ? discovery.timedOutServer(previousRS) : null;
+    discovery.close();
+
+    if (stopping != null || permanentlyStopped)
+    {
+      return failure;
+    }
+    if (responder != null)
+    {
+      return connectToDiscoveryResponder(responder);
+    }
+    if (timedOutRS != null && !electedURL.equals(timedOutRS))
+    {
+      // The other RS can still accept a session after missing its discovery reply.
+      return performPhaseOneHandshake(timedOutRS, true, false);
+    }
+    return failure;
+  }
+
   /** Opens the selected RS session using the fresh state returned by its start reply. */
   private void finishElectedConnection(ConnectedRS electedRS, Map<Integer, ReplicationServerInfo> rsInfos)
   {
@@ -1029,11 +1318,11 @@
     }
   }
 
-  /** Selects a compatible discovery responder other than the former replication server. */
-  private ReplicationServerInfo selectDiscoveryResponder(Map<Integer, ReplicationServerInfo> rsInfos, String formerURL)
+  /** Selects a compatible discovery responder other than the replication server already tried. */
+  private ReplicationServerInfo selectDiscoveryResponder(Map<Integer, ReplicationServerInfo> rsInfos, String triedURL)
   {
     final Map<Integer, ReplicationServerInfo> candidates = new TreeMap<>(rsInfos);
-    candidates.values().removeIf(info -> formerURL.equals(info.getServerURL()) || !hasCompatibleGeneration(info));
+    candidates.values().removeIf(info -> triedURL.equals(info.getServerURL()) || !hasCompatibleGeneration(info));
     if (candidates.isEmpty())
     {
       return null;
@@ -1309,6 +1598,12 @@
   private ConnectedRS performPhaseOneHandshake(String serverURL, boolean keepSession, boolean retryStartTimeout,
       Socket socket)
   {
+    return performPhaseOneHandshake(serverURL, keepSession, retryStartTimeout, socket, null);
+  }
+
+  private ConnectedRS performPhaseOneHandshake(String serverURL, boolean keepSession, boolean retryStartTimeout,
+      Socket socket, DiscoveryProbe probe)
+  {
     Session newSession = null;
     boolean hasConnected = false;
     ConnectedRS failure = ConnectedRS.noConnectedRS();
@@ -1327,8 +1622,9 @@
         InetSocketAddress local = new InetSocketAddress(config.getSourceAddress(), 0);
         socket.bind(local);
       }
-      int timeoutMS = MultimasterReplication.getConnectionTimeoutMS();
-      socket.connect(HostPort.valueOf(serverURL).toInetSocketAddress(), timeoutMS);
+      final int timeoutMS = MultimasterReplication.getConnectionTimeoutMS();
+      socket.connect(HostPort.valueOf(serverURL).toInetSocketAddress(),
+          probe != null ? probe.remainingTimeoutMillis() : timeoutMS);
       if (isSelfConnection(socket))
       {
         // While the RS is down, the kernel may pick the RS port as the local
@@ -1338,7 +1634,8 @@
         throw new ConnectException("Connection to " + serverURL
             + " is a TCP self-connect, no replication server is listening");
       }
-      newSession = replSessionSecurity.createClientSession(socket, timeoutMS, "DS", getServerId(), getBaseDN());
+      newSession = replSessionSecurity.createClientSession(socket,
+          probe != null ? probe.remainingTimeoutMillis() : timeoutMS, "DS", getServerId(), getBaseDN());
       boolean isSslEncryption = replSessionSecurity.isSslEncryption();
 
       // Send our ServerStartMsg.
@@ -1353,8 +1650,17 @@
       // Read the ReplServerStartMsg or ReplServerStartDSMsg that should
       // come back.
       waitingForStartReply = true;
+      if (probe != null)
+      {
+        probe.awaitingStartReply = true;
+        newSession.setSoTimeout(probe.remainingTimeoutMillis());
+      }
       ReplicationMsg msg = newSession.receive();
       waitingForStartReply = false;
+      if (probe != null)
+      {
+        probe.awaitingStartReply = false;
+      }
       if (logger.isTraceEnabled())
       {
         debugInfo("RB HANDSHAKE SENT:\n" + serverStartMsg + "\nAND RECEIVED:\n"
@@ -1370,7 +1676,7 @@
       if (!getBaseDN().equals(repDN))
       {
         errorMessage = ERR_DS_DN_DOES_NOT_MATCH.get(repDN, getBaseDN());
-        return setConnectedRS(ConnectedRS.noConnectedRS());
+        return keepSession ? setConnectedRS(ConnectedRS.noConnectedRS()) : ConnectedRS.noConnectedRS();
       }
 
       /*
@@ -1434,54 +1740,40 @@
 
       if (!hasConnected && errorMessage != null)
       {
-        if (!connectionError)
+        if (probe != null)
         {
-          /*
-           * Report the cause for every replication server contacted, and not only for the
-           * elected one: none is ever elected when none of them answers, and this is then
-           * the only place naming why -- a refused connection, a rejected certificate, a
-           * wrong port -- next to the "unable to connect to any replication servers"
-           * summary which names none of them.
-           *
-           * connectionError is what bounds the volume, and it bounds it to one line per
-           * replication server and per attempt to connect this broker makes. It is set
-           * when an attempt reaches no replication server at all, and stays set until a
-           * session is established, so the 500 ms loop which retries a total outage
-           * reports its first pass only.
-           *
-           * It is not set while this broker is connected, so the unreachable servers of a
-           * topology which still serves this broker are reported again on each
-           * reconnection -- one line each, so a reconnection costs as many lines as there
-           * are servers it could not reach, where it used to cost none. That is the volume
-           * this reporting is worth: a broker reconnects when its session is lost, not on
-           * a schedule, and a server which cannot be reached over several reconnections is
-           * a server whose configuration or certificate needs looking at.
-           *
-           * An unsuccessful attempt to establish the elected session is an error.
-           * A discovery probe or a start reply timeout scheduled for retry is a warning.
-           * ERR_DS_DN_DOES_NOT_MATCH is the one message which reaches the second branch
-           * under an ERR_ name -- it is set without setting hasConnected -- and it is a
-           * permanent misconfiguration rather than a transient. It still goes out as an
-           * error for the server this broker is electing, which is the one it cannot work
-           * without, and where it is only contacted the broker has another server to work
-           * with. Before this, that path logged nothing above trace either way.
-           */
-          if (keepSession && !(startReplyTimedOut && retryStartTimeout))
-          {
-            logger.error(errorMessage);
-          }
-          else
-          {
-            logger.warn(errorMessage);
-          }
+          probe.failure = errorMessage;
         }
-        logger.trace(errorMessage);
+        else
+        {
+          logPhaseOneHandshakeFailure(errorMessage, keepSession, startReplyTimedOut && retryStartTimeout);
+        }
       }
     }
-    setConnectedRS(ConnectedRS.noConnectedRS());
+    if (keepSession)
+    {
+      setConnectedRS(ConnectedRS.noConnectedRS());
+    }
     return startReplyTimedOut ? ConnectedRS.START_REPLY_TIMED_OUT : failure;
   }
 
+  /** Reports failure details until the broker has declared isolation. */
+  private void logPhaseOneHandshakeFailure(LocalizableMessage message, boolean keepSession, boolean retrying)
+  {
+    if (!connectionError)
+    {
+      if (keepSession && !retrying)
+      {
+        logger.error(message);
+      }
+      else
+      {
+        logger.warn(message);
+      }
+    }
+    logger.trace(message);
+  }
+
   /**
    * Performs the second phase handshake (send StartSessionMsg and receive
    * TopologyMsg messages exchange) and return the reply message from the
@@ -2448,6 +2740,11 @@
    */
   private void reStart(Session failingSession, boolean infiniteTry)
   {
+    reStart(failingSession, infiniteTry, false);
+  }
+
+  private void reStart(Session failingSession, boolean infiniteTry, boolean planned)
+  {
     if (failingSession != null)
     {
       failingSession.close();
@@ -2487,7 +2784,7 @@
           {
             final String failedRS = previousRS;
             previousRS = null;
-            connectAsDataServer(failedRS);
+            connectAsDataServer(failedRS, planned && failedRS != null);
             rs = connectedRS.get();
           }
           catch (Exception e)
@@ -2947,14 +3244,15 @@
         }
         else if (msg instanceof StopMsg)
         {
-          if (!finishPlannedSwitch(session))
+          final boolean wasSwitching = finishPlannedSwitch(session);
+          if (!wasSwitching)
           {
             logger.warn(WARN_REPLICATION_SERVER_PROPERLY_DISCONNECTED, previousRsServerID, rs.replicationServer,
                 serverId, baseDN);
           }
 
           // Try to find a suitable RS
-          reStart(session, true);
+          reStart(session, true, wasSwitching);
         }
         else if (msg instanceof MonitorMsg)
         {
@@ -3057,7 +3355,7 @@
         abortPlannedSwitch(session, e);
         if (reconnectOnFailure)
         {
-          reStart(session, true);
+          reStart(session, true, true);
         }
         else
         {
@@ -3084,7 +3382,7 @@
             break; // does not seem necessary to explicitly disconnect ..
           }
 
-          reStart(session, true);
+          reStart(session, true, wasSwitching);
         }
       }
     }
@@ -3099,7 +3397,7 @@
   {
     if (session.getProtocolVersion() < REPLICATION_PROTOCOL_V4)
     {
-      reStart(session, true);
+      reStart(session, true, true);
       return;
     }
 
@@ -3123,7 +3421,7 @@
     }))
     {
       finishPlannedSwitch(session);
-      reStart(session, true);
+      reStart(session, true, true);
     }
   }
 

--
Gitblit v1.10.0