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

Valery Kharseko
10 hours ago 4a462adaa29230742739b64af01ceea01d1ee560
Speed up Linux precommit integration tests (#1329)

## Summary

- Default Maven precommit to four Failsafe JVMs and use that default
across the Linux matrix. Keep a fresh JVM per test class and isolate
test ports, QuickSetup installations, and TestNG reports by fork. Give
the file rename tests unique temporary targets and the changelog tests
separate directories per class.
- Close work queue admission and wake blocked submitters before shutting
down connection handlers. Wake idle workers at queue finalization,
preserve FIFO order when capacity changes, and account for operations
aborted on shutdown, including operations already dequeued by a worker.
- During server shutdown and restart, wait for Grizzly to process the
cancelled accept key and release the listening socket. Drain established
connections separately. Verify that a connection accepted during
finalization gives back its address slot when it closes.
- During live disable or delete, close the LDAP listener on its handler
thread so the configuration request can complete while a selector waits
for queue space. Log listener close failures on the handler thread.
- Limit no-acknowledgement reads to five seconds in 22 assured
replication server cases and three assured replication plugin cases. The
plugin cases verify replay first. Use older replication timestamps to
exercise historical purge without a 90-second sleep. Keep one
unfinished-bind cancellation check and verify every bind constructor
variant after completion.
- Clean up `AciTests` fixtures with synchronous internal deletes.
Post-response delete plugins finish before a subsequent test recreates
the same DN. The ACI assertions still exercise LDAP.
- In the assured replication tests, wait for the fake replication server
to finish its scenario and check that the add returned after ACK
publication began. In the restore test, send the delete to an isolated
replication server and reconnect the restored domain to the server that
holds the backup state. Verify that its changelog contains only the
update made after the restore.

## Validation

- On macOS with Java 27, Maven precommit passed all 84 tests in the two
affected classes (14 in `AssuredReplicationPluginTest` and 70 in
`HistoricalCsnOrderingTest`), with zero failures, errors or skips. The
previous Ubuntu run exposed the ACK race on Java 25 and replayed the
delete after restore on Java 27. [Java 25
job](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/45692294498/job/139480607425)
· [Java 27
job](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/45692294498/job/139480607812)
- In that run, the Ubuntu Maven step took 48, 60 and 44 minutes on Java
11, 17 and 21 respectively. The same jobs on the PR base took 140, 125
and 144 minutes. All six jobs passed. [PR
run](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/45692294498)
· [Base
run](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/45675806177)
- A focused Maven precommit run on macOS with Java 21 passed 767 tests
with zero failures or skips across four Failsafe forks, including all
515 `AciTests` cases. The cleanup change addresses the delayed
disconnect seen on Ubuntu with Java 21. [CI
failure](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/45639995046/job/139295681109)
- A focused Maven precommit run on macOS with Java 17 passed 58 tests
with zero failures or skips. The live disable and delete cases use one
worker and a full queue. Both verify LDAP success, the saved
configuration, another request over the same administrative connection,
and port release when the queue resumes. The run also covers immediate
port reuse and embedded server restart.
- A focused Maven Failsafe run on Java 17 passed 1,359 changelog tests
with zero skips. `LogFileTest`, `LogTest`, and
`BlockLogReaderWriterTest` overlapped in separate JVMs with the
four-fork configuration. The shared-directory failure was reproduced
before the fix. [Java 17 CI
failure](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/45565658345/job/139039676382)
- A focused Maven `verify` on Linux with Java 25 and four CPUs passed
1,215 tests with zero skips. All four Failsafe forks ran and wrote
separate reports. The run includes immediate port reuse, connection
accounting, and two blocked submitters waking with `UNAVAILABLE` before
the worker completes.
- On Linux with Java 25, 100 out of 100 first-attempt binds succeeded
immediately after listener close. A separate embedded-server restart
test passed with a full work queue and a selector waiting for space.
- Verified the Maven profile default and the explicit one-fork override,
checked the profile arguments for every matrix entry, and ran
`actionlint` and `git diff --check`.
26 files modified
1 files added
1937 ■■■■■ changed files
.github/workflows/build.yml 4 ●●●●● patch | view | raw | blame | history
opendj-grizzly/src/main/java/org/forgerock/opendj/grizzly/GrizzlyLDAPListener.java 88 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/pom.xml 9 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/forgerock/opendj/reactive/LDAPConnectionHandler2.java 93 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/api/ConnectionHandler.java 13 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/api/WorkQueue.java 13 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/core/ConnectionHandlerConfigManager.java 4 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/core/DirectoryServer.java 6 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/extensions/TraditionalWorkQueue.java 529 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/extensions/TraditionalWorkerThread.java 85 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/test/java/org/opends/quicksetup/TestUtilities.java 8 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/test/java/org/opends/quicksetup/util/FileManagerTest.java 9 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/test/java/org/opends/server/TestCaseUtils.java 95 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/test/java/org/opends/server/TestListener.java 12 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/test/java/org/opends/server/authorization/dseecompat/AciTests.java 53 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/test/java/org/opends/server/core/BindOperationTestCase.java 30 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/test/java/org/opends/server/extensions/TraditionalWorkQueueShutdownTest.java 277 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/test/java/org/opends/server/protocols/ldap/LDAPConnectionHandler2TransportTestCase.java 176 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/test/java/org/opends/server/protocols/ldap/LDAPConnectionLimitsTestCase.java 80 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/AssuredReplicationPluginTest.java 163 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/HistoricalCsnOrderingTest.java 17 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/HistoricalTest.java 131 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/test/java/org/opends/server/replication/server/AssuredReplicationServerTest.java 16 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/test/java/org/opends/server/replication/server/changelog/file/BlockLogReaderWriterTest.java 3 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/test/java/org/opends/server/replication/server/changelog/file/LogFileTest.java 2 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/test/java/org/opends/server/replication/server/changelog/file/LogTest.java 2 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/test/java/org/opends/server/util/TestStaticUtils.java 19 ●●●●● patch | view | raw | blame | history
.github/workflows/build.yml
@@ -118,8 +118,8 @@
    - name: Set Integration Test Environment
      id: failsafe
      if: runner.os == 'Linux'
      run:   |
        echo "MAVEN_PROFILE_FLAG=-P precommit" >> $GITHUB_OUTPUT
      run: |
        echo "MAVEN_PROFILE_FLAG=-P precommit" >> "$GITHUB_OUTPUT"
    - name: Setup WiX (.NET tool) for MSI
      # Only the java 11 job's MSI is consumed downstream (test-msi*, deploy.yml); without
opendj-grizzly/src/main/java/org/forgerock/opendj/grizzly/GrizzlyLDAPListener.java
@@ -13,7 +13,7 @@
 *
 * Copyright 2010 Sun Microsystems, Inc.
 * Portions copyright 2011-2016 ForgeRock AS.
 * Portions copyright 2025-2026 3A Systems, LLC.
 * Portions Copyright 2025-2026 3A Systems, LLC.
 */
package org.forgerock.opendj.grizzly;
@@ -26,7 +26,9 @@
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import org.forgerock.i18n.LocalizableMessage;
@@ -39,11 +41,15 @@
import org.forgerock.util.Function;
import org.forgerock.util.Option;
import org.forgerock.util.Options;
import org.glassfish.grizzly.EmptyCompletionHandler;
import org.glassfish.grizzly.filterchain.FilterChain;
import org.glassfish.grizzly.impl.FutureImpl;
import org.glassfish.grizzly.nio.SelectorHandler;
import org.glassfish.grizzly.nio.SelectorRunner;
import org.glassfish.grizzly.nio.transport.TCPNIOBindingHandler;
import org.glassfish.grizzly.nio.transport.TCPNIOConnection;
import org.glassfish.grizzly.nio.transport.TCPNIOServerConnection;
import org.glassfish.grizzly.nio.transport.TCPNIOTransport;
import org.glassfish.grizzly.utils.Futures;
import com.forgerock.opendj.util.ReferenceCountedObject;
import com.forgerock.reactive.ReactiveHandler;
@@ -127,17 +133,83 @@
    @Override
    public void close() {
        if (isClosed.compareAndSet(false, true)) {
            for (TCPNIOConnection serverConnection : serverConnections) {
        try {
            close(false);
        } catch (IOException e) {
            logger.warn(LocalizableMessage.raw("Exception occurred while closing listener"), e);
        }
    }
    /**
     * Closes the listener and waits for the accept sockets to be released.
     * Call this from outside the transport's selector threads. If the transport was supplied by the caller, the
     * caller still owns it and can drain existing connections.
     *
     * @throws IOException
     *             If an accept socket could not be closed and deregistered.
     */
    public void closeAndAwaitPortRelease() throws IOException {
        close(true);
    }
    private void close(boolean awaitPortRelease) throws IOException {
        if (!isClosed.compareAndSet(false, true)) {
            return;
        }
        IOException failure = null;
        try {
            for (TCPNIOServerConnection serverConnection : serverConnections) {
                try {
                    serverConnection.close().get(5, TimeUnit.SECONDS);
                } catch (final Exception e) {
                    // TODO: I18N
                    logger.warn(LocalizableMessage.raw("Exception occurred while closing listener", e));
                    closeServerConnection(serverConnection, awaitPortRelease);
                } catch (IOException e) {
                    if (failure == null) {
                        failure = e;
                    } else {
                        failure.addSuppressed(e);
                    }
                }
            }
        } finally {
            transport.release();
        }
        if (failure != null) {
            throw failure;
        }
    }
    private void closeServerConnection(TCPNIOServerConnection connection, boolean awaitPortRelease) throws IOException {
        try {
            final SelectorRunner runner = connection.getSelectorRunner();
            if (awaitPortRelease && runner != null) {
                final FutureImpl<SelectorHandler.Task> released = Futures.createSafeFuture();
                final SelectorHandler selectorHandler = transport.get().getSelectorHandler();
                // A closed NIO channel can still own the socket until the selector processes its cancelled key.
                // Enqueue the check from the owning thread so it runs after the next selection cycle.
                selectorHandler.enque(runner, () -> {
                    connection.closeSilently();
                    selectorHandler.enque(runner, () -> {
                        if (connection.getChannel().isOpen() || connection.getChannel().isRegistered()) {
                            throw new IOException("Listening socket is still registered: " + connection.getLocalAddress());
                        }
                        return true;
                    }, Futures.toCompletionHandler(released));
                    return true;
                }, new EmptyCompletionHandler<SelectorHandler.Task>() {
                    @Override
                    public void failed(Throwable cause) {
                        released.failure(cause);
                    }
                });
                released.get(5, TimeUnit.SECONDS);
            } else {
                connection.close().get(5, TimeUnit.SECONDS);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new IOException("Interrupted while closing listener", e);
        } catch (ExecutionException | TimeoutException e) {
            throw new IOException("Could not close listener", e);
        }
    }
    @Override
opendj-server-legacy/pom.xml
@@ -1178,6 +1178,9 @@
    -->
    <profile>
      <id>precommit</id>
      <properties>
        <opendj.precommit.forkCount>4</opendj.precommit.forkCount>
      </properties>
      <build><finalName>${project.groupId}.${project.artifactId}</finalName>
        <plugins>
@@ -1273,6 +1276,7 @@
                 <systemPropertyVariables>
                    <org.opends.server.BuildRoot>${basedir}</org.opends.server.BuildRoot>
                    <org.opends.server.BuildDir>${project.build.directory}</org.opends.server.BuildDir>
                    <org.opends.test.forkCount>${opendj.precommit.forkCount}</org.opends.test.forkCount>
                    <org.opends.test.replicationDbImpl>LOG</org.opends.test.replicationDbImpl>
                    <org.opends.server.snmp.opendmk>${opendmk.lib.dir}</org.opends.server.snmp.opendmk>
                    <org.opends.server.CleanupDirectories>true</org.opends.server.CleanupDirectories>
@@ -1292,9 +1296,10 @@
                  <environmentVariables>
                    <JAVA_TOOL_OPTIONS>-Dorg.bouncycastle.native.cpu_variant=java</JAVA_TOOL_OPTIONS>
                  </environmentVariables>
                  <argLine>@{argLine}</argLine>
                  <!-- Failsafe substitutes the fork number in each JVM command line. -->
                  <argLine>@{argLine} -Dorg.opends.test.forkNumber=${surefire.forkNumber}</argLine>
                  <reuseForks>false</reuseForks>
                  <forkCount>1</forkCount>
                  <forkCount>${opendj.precommit.forkCount}</forkCount>
                  <parallel>none</parallel>
                  <runOrder>alphabetical</runOrder>
                  <!--
opendj-server-legacy/src/main/java/org/forgerock/opendj/reactive/LDAPConnectionHandler2.java
@@ -41,11 +41,14 @@
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.net.ssl.KeyManager;
@@ -292,7 +295,7 @@
    /** SSL instance name used in context creation. */
    private static final String SSL_CONTEXT_INSTANCE_NAME = "TLS";
    private LDAPListener listener;
    private GrizzlyLDAPListener listener;
    /**
     * The transport serving the connections of this connection handler only. It is started with the listener, and
@@ -342,9 +345,8 @@
    private volatile boolean shutdownRequested;
    /**
     * The server this handler was initialized for. The listener stops on the thread of the handler, up to a second
     * after the handler is finalized: after an in-core restart the current server instance is by then the next one,
     * so only this one tells whether the server of the connections is shutting down.
     * The server this handler was initialized for. The transport may still be draining after an in-core restart,
     * so only this instance tells whether the server of its connections is shutting down.
     */
    private DirectoryServer server;
@@ -378,8 +380,7 @@
    private final QueueingStrategy queueingStrategy;
    /**
     * The condition variable that will be used by the start method to wait for the socket port to be opened and ready
     * to process requests before returning.
     * Coordinates the listener's startup and wakes the listener thread on shutdown.
     */
    private final Object waitListen = new Object();
@@ -390,6 +391,9 @@
     */
    private boolean listenAttempted;
    /** Allows finalization to wait for the listen socket to close before an in-core restart. */
    private final CompletableFuture<Void> listenerClosed = new CompletableFuture<>();
    /** The friendly name of this connection handler. */
    private String friendlyName;
@@ -526,7 +530,17 @@
    @Override
    public void finalizeConnectionHandler(LocalizableMessage finalizeReason) {
        shutdownRequested = true;
        finalizeConnectionHandler(finalizeReason, true);
    }
    @Override
    public void finalizeConnectionHandlerForConfigurationChange(LocalizableMessage finalizeReason) {
        // The listener's selector may be waiting for the worker applying this change to make queue space.
        finalizeConnectionHandler(finalizeReason, false);
    }
    private void finalizeConnectionHandler(LocalizableMessage finalizeReason, boolean awaitPortRelease) {
        processServerShutdown(finalizeReason);
        currentConfig.removeLDAPChangeListener(this);
        if (connMonitor != null) {
@@ -550,6 +564,17 @@
            r.run(); // Flush active queue.
            r.run(); // Flush pending queue.
        }
        if (awaitPortRelease && getState() != Thread.State.NEW && Thread.currentThread() != this) {
            try {
                listenerClosed.get(LISTEN_TIMEOUT_MS, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new IllegalStateException("Interrupted while closing listener " + handlerName, e);
            } catch (ExecutionException | TimeoutException e) {
                throw new IllegalStateException("Could not close listener " + handlerName, e);
            }
        }
    }
    /**
@@ -856,15 +881,33 @@
    @Override
    public void processServerShutdown(LocalizableMessage reason) {
        shutdownRequested = true;
        synchronized (waitListen) {
            shutdownRequested = true;
            waitListen.notifyAll();
        }
    }
    void stopListener() {
        try {
            closeListener();
        } catch (IOException e) {
            logger.traceException(e);
            logger.warn(LocalizableMessage.raw("Could not close listener %s", handlerName));
        } finally {
            drainTransport();
        }
    }
    private void closeListener() throws IOException {
        if (listener != null) {
            listener.close();
            final GrizzlyLDAPListener closing = listener;
            listener = null;
            closing.closeAndAwaitPortRelease();
            logger.info(NOTE_CONNHANDLER_STOPPED_LISTENING, handlerName);
        }
    }
    private void drainTransport() {
        if (transport != null) {
            final TransportDrain drain = new TransportDrain(transport, transportConnections, transportOpenConnections);
            transport = null;
@@ -920,7 +963,7 @@
        transport = newTransport(openConnections);
        transportConnections = accepted;
        transportOpenConnections = openConnections;
        listener = new LDAPListener(
        listener = new GrizzlyLDAPListener(
                listenAddresses,
                new Function<LDAPClientContext,
                             ReactiveHandler<LDAPClientContext, LdapRequestEnvelope, Stream<Response>>,
@@ -971,8 +1014,7 @@
                          .set(LDAPListener.REQUEST_MAX_SIZE_IN_BYTES, (int) currentConfig.getMaxRequestSize())
                          // Set by the listener on every accepted connection, over the values of the transport.
                          .set(LDAPListener.SO_KEEPALIVE, useTCPKeepAlive)
                          .set(LDAPListener.TCP_NO_DELAY, useTCPNoDelay)
                          .set(GrizzlyLDAPListener.GRIZZLY_TRANSPORT, transport));
                          .set(LDAPListener.TCP_NO_DELAY, useTCPNoDelay), transport);
        logger.info(NOTE_CONNHANDLER_STARTED_LISTENING, handlerName);
    }
@@ -1036,13 +1078,13 @@
                    }
                }
                StaticUtils.sleep(1000);
                waitForListenerChange();
                continue;
            }
            if (listener != null) {
                // If already listening, then sleep for a bit and check again.
                StaticUtils.sleep(1000);
                waitForListenerChange();
                continue;
            }
@@ -1084,8 +1126,27 @@
            }
        }
        // Initiate shutdown
        stopListener();
        try {
            closeListener();
            listenerClosed.complete(null);
        } catch (Exception e) {
            listenerClosed.completeExceptionally(e);
            logger.warn(LocalizableMessage.raw("Could not close listener %s", handlerName), e);
        } finally {
            drainTransport();
        }
    }
    private void waitForListenerChange() {
        synchronized (waitListen) {
            if (!shutdownRequested) {
                try {
                    waitListen.wait(1000);
                } catch (InterruptedException e) {
                    // Recheck the listener state.
                }
            }
        }
    }
    private LDAPClientConnection2 canAccept(LDAPClientContext clientContext) throws LdapException {
opendj-server-legacy/src/main/java/org/opends/server/api/ConnectionHandler.java
@@ -106,6 +106,19 @@
  public abstract void finalizeConnectionHandler(
      LocalizableMessage finalizeReason);
  /**
   * Stops this handler after its configuration is disabled or deleted.
   * This can run on a work queue worker. Handlers whose listeners depend on
   * the work queue can initiate closure asynchronously.
   *
   * @param finalizeReason
   *          The reason that this connection handler should be finalized.
   */
  public void finalizeConnectionHandlerForConfigurationChange(LocalizableMessage finalizeReason)
  {
    finalizeConnectionHandler(finalizeReason);
  }
  /**
opendj-server-legacy/src/main/java/org/opends/server/api/WorkQueue.java
@@ -13,6 +13,7 @@
 *
 * Copyright 2006-2010 Sun Microsystems, Inc.
 * Portions Copyright 2013-2016 ForgeRock AS.
 * Portions Copyright 2026 3A Systems, LLC.
 */
package org.opends.server.api;
@@ -71,6 +72,18 @@
  /**
   * Allows a queue to reject new submissions and release submitters waiting for capacity
   * before the server shuts down its connection handlers. Queued and active operations
   * can continue until {@link #finalizeWorkQueue(LocalizableMessage)}.
   */
  public void stopAcceptingOperations()
  {
    // By default, admission stops when the queue is finalized.
  }
  /**
   * Performs any necessary finalization for this work queue,
   * including ensuring that all active operations are interrupted or
   * will be allowed to complete, and that all pending operations will
opendj-server-legacy/src/main/java/org/opends/server/core/ConnectionHandlerConfigManager.java
@@ -172,7 +172,7 @@
            .deregisterConnectionHandler(connectionHandler);
        connectionHandlers.remove(dn);
        connectionHandler.finalizeConnectionHandler(
        connectionHandler.finalizeConnectionHandlerForConfigurationChange(
                INFO_CONNHANDLER_CLOSED_BY_DISABLE.get());
      }
    }
@@ -194,7 +194,7 @@
      DirectoryServer.deregisterConnectionHandler(connectionHandler);
      connectionHandlers.remove(dn);
      connectionHandler.finalizeConnectionHandler(
      connectionHandler.finalizeConnectionHandlerForConfigurationChange(
              INFO_CONNHANDLER_CLOSED_BY_DELETE.get());
    }
opendj-server-legacy/src/main/java/org/opends/server/core/DirectoryServer.java
@@ -4150,6 +4150,12 @@
    ServerShutdownMonitor shutdownMonitor = new ServerShutdownMonitor();
    shutdownMonitor.start();
    // Release connection-handler threads that are waiting for queue space.
    if (directoryServer.workQueue != null)
    {
      directoryServer.workQueue.stopAcceptingOperations();
    }
    // Shut down the connection handlers.
    for (ConnectionHandler<?> handler : directoryServer.connectionHandlers)
    {
opendj-server-legacy/src/main/java/org/opends/server/extensions/TraditionalWorkQueue.java
@@ -13,22 +13,21 @@
 *
 * Copyright 2006-2010 Sun Microsystems, Inc.
 * Portions Copyright 2013-2016 ForgeRock AS.
 * Portions Copyright 2026 3A Systems, LLC
 * Portions Copyright 2026 3A Systems, LLC.
 */
package org.opends.server.extensions;
import static org.opends.messages.ConfigMessages.*;
import static org.opends.messages.CoreMessages.*;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.slf4j.LocalizedLogger;
@@ -87,8 +86,11 @@
   */
  private boolean killThreads;
  /** Indicates whether submissions have been closed before queue finalization. Guarded by queueLock. */
  private boolean submissionsClosed;
  /** Indicates whether the Directory Server is shutting down. */
  private boolean shutdownRequested;
  private volatile boolean shutdownRequested;
  /** The thread number used for the last worker thread that was created. */
  private int lastThreadNumber;
@@ -103,7 +105,7 @@
   * The number of worker threads that should be active (or will be shortly if a
   * configuration change has not been completely applied).
   */
  private int numWorkerThreads;
  private volatile int numWorkerThreads;
  /**
   * The queue overflow policy: true indicates that operations will be blocked
@@ -115,19 +117,11 @@
   */
  private final boolean isBlocking = true;
  /** The queue that will be used to actually hold the pending operations. */
  private LinkedBlockingQueue<Operation> opQueue;
  /** The lock used to provide threadsafe access for the queue, used for non-config changes. */
  private final ReadLock queueReadLock;
  /** The lock used to provide threadsafe access for the queue, used for config changes. */
  private final WriteLock queueWriteLock;
  {
    ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    queueReadLock = lock.readLock();
    queueWriteLock = lock.writeLock();
  }
  /** Guards the queue, capacity, and worker pool. Condition waits release the lock. */
  private final ReentrantLock queueLock = new ReentrantLock();
  private final Condition workAvailable = queueLock.newCondition();
  private final Condition spaceAvailable = queueLock.newCondition();
  private final Deque<Operation> opQueue = new ArrayDeque<>();
  /**
   * Creates a new instance of this work queue. All initialization should be
@@ -142,9 +136,10 @@
  public void initializeWorkQueue(TraditionalWorkQueueCfg configuration)
      throws ConfigException, InitializationException
  {
    queueWriteLock.lock();
    queueLock.lock();
    try
    {
      submissionsClosed = false;
      shutdownRequested = false;
      killThreads = false;
      opsSubmitted = new AtomicLong(0);
@@ -159,17 +154,7 @@
          computeNumWorkerThreads(configuration.getNumWorkerThreads());
      maxCapacity = configuration.getMaxWorkQueueCapacity();
      // Create the actual work queue.
      if (maxCapacity > 0)
      {
        opQueue = new LinkedBlockingQueue<>(maxCapacity);
      }
      else
      {
        // This will never be the case, since the configuration definition
        // ensures that the capacity is always finite.
        opQueue = new LinkedBlockingQueue<>();
      }
      opQueue.clear();
      // Create the set of worker threads that should be used to service the
      // work queue.
@@ -182,79 +167,105 @@
        workerThreads.add(t);
      }
      // Create and register a monitor provider for the work queue.
      try
      {
        TraditionalWorkQueueMonitor monitor = new TraditionalWorkQueueMonitor(
            this);
        monitor.initializeMonitorProvider(null);
        DirectoryServer.registerMonitorProvider(monitor);
      }
      catch (Exception e)
      {
        logger.traceException(e);
        logger.error(ERR_CONFIG_WORK_QUEUE_CANNOT_CREATE_MONITOR, TraditionalWorkQueueMonitor.class, e);
      }
      registerQueueMonitor();
    }
    finally
    {
      queueWriteLock.unlock();
      queueLock.unlock();
    }
  }
  void registerQueueMonitor()
  {
    try
    {
      TraditionalWorkQueueMonitor monitor = new TraditionalWorkQueueMonitor(this);
      monitor.initializeMonitorProvider(null);
      DirectoryServer.registerMonitorProvider(monitor);
    }
    catch (Exception e)
    {
      logger.traceException(e);
      logger.error(ERR_CONFIG_WORK_QUEUE_CANNOT_CREATE_MONITOR, TraditionalWorkQueue.class, e);
    }
  }
  @Override
  public void stopAcceptingOperations()
  {
    queueLock.lock();
    try
    {
      submissionsClosed = true;
      spaceAvailable.signalAll();
    }
    finally
    {
      queueLock.unlock();
    }
  }
  @Override
  public void finalizeWorkQueue(LocalizableMessage reason)
  {
    queueWriteLock.lock();
    List<Operation> pendingOperations;
    List<TraditionalWorkerThread> workers;
    queueLock.lock();
    try
    {
      shutdownRequested = true;
      pendingOperations = new ArrayList<>(opQueue);
      opQueue.clear();
      workers = new ArrayList<>(workerThreads);
      workAvailable.signalAll();
      spaceAvailable.signalAll();
    }
    finally
    {
      queueWriteLock.unlock();
      queueLock.unlock();
    }
    // From now on no more operations can be enqueued or dequeued.
    // Send responses to any operations in the pending queue to indicate that
    // they won't be processed because the server is shutting down.
    CancelRequest cancelRequest = new CancelRequest(true, reason);
    ArrayList<Operation> pendingOperations = new ArrayList<>();
    opQueue.drainTo(pendingOperations);
    for (Operation o : pendingOperations)
    for (Operation operation : pendingOperations)
    {
      try
      {
        // The operation has no chance of responding to the cancel
        // request so avoid waiting for a cancel response.
        if (o.getCancelResult() == null)
        {
          o.abort(cancelRequest);
        }
      }
      catch (Exception e)
      {
        logger.traceException(e);
        logger.warn(WARN_QUEUE_UNABLE_TO_CANCEL, o, e);
      }
      abortPendingOperation(operation, cancelRequest);
    }
    // Notify all the worker threads of the shutdown.
    for (TraditionalWorkerThread t : workerThreads)
    for (TraditionalWorkerThread worker : workers)
    {
      try
      {
        t.shutDown();
        worker.shutDown();
      }
      catch (Exception e)
      {
        logger.traceException(e);
        logger.warn(WARN_QUEUE_UNABLE_TO_NOTIFY_THREAD, t.getName(), e);
        logger.warn(WARN_QUEUE_UNABLE_TO_NOTIFY_THREAD, worker.getName(), e);
      }
    }
  }
  void abortPendingOperation(Operation operation, CancelRequest cancelRequest)
  {
    try
    {
      // Pending operations have no worker to answer a cancel request.
      if (operation.getCancelResult() == null)
      {
        operation.abort(cancelRequest);
      }
    }
    catch (Exception e)
    {
      logger.traceException(e);
      logger.warn(WARN_QUEUE_UNABLE_TO_CANCEL, operation, e);
    }
    finally
    {
      operationDone();
    }
  }
  /**
   * Indicates whether this work queue has received a request to shut down.
   *
@@ -263,15 +274,7 @@
   */
  public boolean shutdownRequested()
  {
    queueReadLock.lock();
    try
    {
      return shutdownRequested;
    }
    finally
    {
      queueReadLock.unlock();
    }
    return shutdownRequested;
  }
  /**
@@ -310,72 +313,40 @@
    }
  }
  private void submitOperation(Operation operation,
      boolean blockEnqueuingWhenFull) throws DirectoryException
  private void submitOperation(Operation operation, boolean blockEnqueuingWhenFull) throws DirectoryException
  {
    // Count the operation before enqueuing it so that isIdle() can never
    // observe an empty queue while the operation is in the process of being
    // submitted; the count is rolled back if the operation is rejected.
    // Include the hand-off from the queue to a worker in the pending operation count.
    pendingOpsCount.incrementAndGet();
    boolean submitted = false;
    queueReadLock.lock();
    queueLock.lock();
    try
    {
      if (shutdownRequested)
      checkForShutdown();
      if (blockEnqueuingWhenFull && Thread.interrupted())
      {
        LocalizableMessage message = WARN_OP_REJECTED_BY_SHUTDOWN.get();
        throw new DirectoryException(ResultCode.UNAVAILABLE, message);
        throw new InterruptedException();
      }
      if (blockEnqueuingWhenFull)
      while (maxCapacity > 0 && opQueue.size() >= maxCapacity)
      {
        try
        {
          // If the queue is full and there is an administrative change taking
          // place then starvation could arise: this thread will hold the read
          // lock, the admin thread will be waiting on the write lock, and the
          // worker threads may be queued behind the admin thread. Since the
          // worker threads cannot run, the queue will never empty and allow
          // this thread to proceed. To help things out we can periodically
          // yield the read lock when the queue is full.
          while (!opQueue.offer(operation, 1, TimeUnit.SECONDS))
          {
            queueReadLock.unlock();
            Thread.yield();
            queueReadLock.lock();
            if (shutdownRequested)
            {
              LocalizableMessage message = WARN_OP_REJECTED_BY_SHUTDOWN.get();
              throw new DirectoryException(ResultCode.UNAVAILABLE, message);
            }
          }
        }
        catch (InterruptedException e)
        {
          // We cannot handle the interruption here. Reject the request and
          // re-interrupt this thread.
          Thread.currentThread().interrupt();
          queueFullRejects.incrementAndGet();
          LocalizableMessage message = WARN_OP_REJECTED_BY_QUEUE_INTERRUPT.get();
          throw new DirectoryException(ResultCode.BUSY, message);
        }
      }
      else
      {
        if (!opQueue.offer(operation))
        if (!blockEnqueuingWhenFull)
        {
          queueFullRejects.incrementAndGet();
          LocalizableMessage message = WARN_OP_REJECTED_BY_QUEUE_FULL.get(maxCapacity);
          throw new DirectoryException(ResultCode.BUSY, message);
          throw new DirectoryException(ResultCode.BUSY, WARN_OP_REJECTED_BY_QUEUE_FULL.get(maxCapacity));
        }
        spaceAvailable.await();
        checkForShutdown();
      }
      opQueue.addLast(operation);
      opsSubmitted.incrementAndGet();
      submitted = true;
      workAvailable.signal();
    }
    catch (InterruptedException e)
    {
      Thread.currentThread().interrupt();
      queueFullRejects.incrementAndGet();
      throw new DirectoryException(ResultCode.BUSY, WARN_OP_REJECTED_BY_QUEUE_INTERRUPT.get());
    }
    finally
    {
@@ -383,7 +354,15 @@
      {
        pendingOpsCount.decrementAndGet();
      }
      queueReadLock.unlock();
      queueLock.unlock();
    }
  }
  private void checkForShutdown() throws DirectoryException
  {
    if (submissionsClosed || shutdownRequested)
    {
      throw new DirectoryException(ResultCode.UNAVAILABLE, WARN_OP_REJECTED_BY_SHUTDOWN.get());
    }
  }
@@ -419,145 +398,70 @@
   *         if the server is shutting down and no more operations will be
   *         processed, or if there have been too many consecutive failures.
   */
  private Operation retryNextOperation(TraditionalWorkerThread workerThread,
      int numFailures)
  private Operation retryNextOperation(TraditionalWorkerThread workerThread, int numFailures)
  {
    // See if we should kill off this thread. This could be necessary if the
    // number of worker threads has been decreased with the server online. If
    // so, then return null and the thread will exit.
    queueReadLock.lock();
    queueLock.lock();
    try
    {
      if (shutdownRequested)
      while (!shutdownRequested)
      {
        return null;
      }
      if (killThreads && tryKillThisWorkerThread(workerThread))
      {
        return null;
      }
      if (numFailures > MAX_RETRY_COUNT)
      {
        logger.error(ERR_CONFIG_WORK_QUEUE_TOO_MANY_FAILURES, Thread
            .currentThread().getName(), numFailures, MAX_RETRY_COUNT);
        return null;
      }
      while (true)
      {
        Operation nextOperation = opQueue.poll(5, TimeUnit.SECONDS);
        if (nextOperation != null)
        {
          return nextOperation;
        }
        // There was no work to do in the specified length of time. Release the
        // read lock allowing shutdown or config changes to proceed and then see
        // if we should give up or check again.
        queueReadLock.unlock();
        Thread.yield();
        queueReadLock.lock();
        if (shutdownRequested)
        {
          return null;
        }
        if (killThreads && tryKillThisWorkerThread(workerThread))
        {
          return null;
        }
        if (numFailures > MAX_RETRY_COUNT)
        {
          logger.error(ERR_CONFIG_WORK_QUEUE_TOO_MANY_FAILURES,
              Thread.currentThread().getName(), numFailures, MAX_RETRY_COUNT);
          return null;
        }
        if (Thread.interrupted())
        {
          throw new InterruptedException();
        }
        Operation nextOperation = opQueue.pollFirst();
        if (nextOperation != null)
        {
          spaceAvailable.signal();
          return nextOperation;
        }
        workAvailable.await();
      }
      return null;
    }
    catch (InterruptedException ie)
    catch (InterruptedException e)
    {
      // This is somewhat expected so don't log.
      // assert debugException(CLASS_NAME, "retryNextOperation", ie);
      // If this occurs, then the worker thread must have been interrupted for
      // some reason. This could be because the Directory Server is shutting
      // down, in which case we should return null.
      if (shutdownRequested)
      {
        return null;
      }
      // If we've gotten here, then the worker thread was interrupted for some
      // other reason. This should not happen, and we need to log a message.
      logger.warn(WARN_WORKER_INTERRUPTED_WITHOUT_SHUTDOWN, Thread.currentThread().getName(), ie);
      logger.warn(WARN_WORKER_INTERRUPTED_WITHOUT_SHUTDOWN, Thread.currentThread().getName(), e);
    }
    catch (Exception e)
    {
      logger.traceException(e);
      // This should not happen. The only recourse we have is to log a message
      // and try again.
      logger.warn(WARN_WORKER_WAITING_UNCAUGHT_EXCEPTION, Thread.currentThread().getName(), e);
    }
    finally
    {
      queueReadLock.unlock();
      queueLock.unlock();
    }
    // An exception has occurred - retry.
    return retryNextOperation(workerThread, numFailures + 1);
  }
  /**
   * Kills this worker thread if needed. This method assumes that the read lock
   * is already taken and ensure that it is taken on exit.
   *
   * @param workerThread
   *          The worker thread associated with this thread.
   * @return {@code true} if this thread was killed or is about to be killed as
   *         a result of shutdown.
   */
  /** Retires an excess worker while holding the queue lock. */
  private boolean tryKillThisWorkerThread(TraditionalWorkerThread workerThread)
  {
    queueReadLock.unlock();
    queueWriteLock.lock();
    try
    if (workerThreads.size() <= numWorkerThreads)
    {
      if (shutdownRequested)
      {
        // Shutdown may have been requested between unlock/lock. This thread is
        // about to shutdown anyway, so return true.
        return true;
      }
      int currentThreads = workerThreads.size();
      if (currentThreads > numWorkerThreads)
      {
        if (workerThreads.remove(Thread.currentThread()))
        {
          currentThreads--;
        }
        if (currentThreads <= numWorkerThreads)
        {
          killThreads = false;
        }
        workerThread.setStoppedByReducedThreadNumber();
        return true;
      }
      killThreads = false;
      return false;
    }
    finally
    {
      queueWriteLock.unlock();
      queueReadLock.lock();
      if (shutdownRequested)
      {
        // Shutdown may have been requested between unlock/lock. This thread is
        // about to shutdown anyway, so return true.
        return true;
      }
    }
    return false;
    workerThreads.remove(workerThread);
    killThreads = workerThreads.size() > numWorkerThreads;
    workerThread.setStoppedByReducedThreadNumber();
    return true;
  }
  /**
@@ -588,23 +492,21 @@
  /**
   * Retrieves the number of pending operations in the queue that have not yet
   * been picked up for processing. Note that this method is not a constant-time
   * operation and can be relatively inefficient, so it should be used
   * sparingly.
   * been picked up for processing.
   *
   * @return The number of pending operations in the queue that have not yet
   *         been picked up for processing.
   */
  public int size()
  {
    queueReadLock.lock();
    queueLock.lock();
    try
    {
      return opQueue.size();
    }
    finally
    {
      queueReadLock.unlock();
      queueLock.unlock();
    }
  }
@@ -616,121 +518,38 @@
  }
  @Override
  public ConfigChangeResult applyConfigurationChange(
      TraditionalWorkQueueCfg configuration)
  public ConfigChangeResult applyConfigurationChange(TraditionalWorkQueueCfg configuration)
  {
    int newNumThreads =
        computeNumWorkerThreads(configuration.getNumWorkerThreads());
    int newMaxCapacity = configuration.getMaxWorkQueueCapacity();
    // Apply a change to the number of worker threads if appropriate.
    int currentThreads = workerThreads.size();
    if (newNumThreads != currentThreads)
    int newNumThreads = computeNumWorkerThreads(configuration.getNumWorkerThreads());
    queueLock.lock();
    try
    {
      queueWriteLock.lock();
      try
      if (shutdownRequested)
      {
        int threadsToAdd = newNumThreads - currentThreads;
        if (threadsToAdd > 0)
        {
          for (int i = 0; i < threadsToAdd; i++)
          {
            TraditionalWorkerThread t = new TraditionalWorkerThread(this,
                lastThreadNumber++);
            workerThreads.add(t);
            t.start();
          }
        return new ConfigChangeResult();
      }
      int threadsToAdd = newNumThreads - workerThreads.size();
      for (int i = 0; i < threadsToAdd; i++)
      {
        TraditionalWorkerThread worker = new TraditionalWorkerThread(this, lastThreadNumber++);
        workerThreads.add(worker);
        worker.start();
      }
      numWorkerThreads = newNumThreads;
      killThreads = threadsToAdd < 0;
      if (killThreads)
      {
        workAvailable.signalAll();
      }
          killThreads = false;
        }
        else
        {
          killThreads = true;
        }
        numWorkerThreads = newNumThreads;
      }
      catch (Exception e)
      {
        logger.traceException(e);
      }
      finally
      {
        queueWriteLock.unlock();
      }
      // Keep queued work in FIFO order even when the new limit is below the backlog size.
      maxCapacity = configuration.getMaxWorkQueueCapacity();
      spaceAvailable.signalAll();
    }
    // Apply a change to the maximum capacity if appropriate. Since we can't
    // change capacity on the fly, then we'll have to create a new queue and
    // transfer any remaining items into it. Any thread that is waiting on the
    // original queue will time out after at most a few seconds and further
    // checks will be against the new queue.
    if (newMaxCapacity != maxCapacity)
    finally
    {
      // First switch the queue with the exclusive lock.
      queueWriteLock.lock();
      LinkedBlockingQueue<Operation> oldOpQueue;
      try
      {
        LinkedBlockingQueue<Operation> newOpQueue = null;
        if (newMaxCapacity > 0)
        {
          newOpQueue = new LinkedBlockingQueue<>(newMaxCapacity);
        }
        else
        {
          newOpQueue = new LinkedBlockingQueue<>();
        }
        oldOpQueue = opQueue;
        opQueue = newOpQueue;
        maxCapacity = newMaxCapacity;
      }
      finally
      {
        queueWriteLock.unlock();
      }
      // Now resubmit any pending requests - we'll need the shared lock.
      Operation pendingOperation = null;
      queueReadLock.lock();
      try
      {
        // We have to be careful when adding any existing pending operations
        // because the new capacity could be less than what was already
        // backlogged in the previous queue. If that happens, we may have to
        // loop a few times to get everything in there.
        while ((pendingOperation = oldOpQueue.poll()) != null)
        {
          opQueue.put(pendingOperation);
        }
      }
      catch (InterruptedException e)
      {
        // We cannot handle the interruption here. Cancel pending requests and
        // re-interrupt this thread.
        Thread.currentThread().interrupt();
        LocalizableMessage message = WARN_OP_REJECTED_BY_QUEUE_INTERRUPT.get();
        CancelRequest cancelRequest = new CancelRequest(true, message);
        if (pendingOperation != null)
        {
          pendingOperation.abort(cancelRequest);
          pendingOpsCount.decrementAndGet();
        }
        while ((pendingOperation = oldOpQueue.poll()) != null)
        {
          pendingOperation.abort(cancelRequest);
          pendingOpsCount.decrementAndGet();
        }
      }
      finally
      {
        queueReadLock.unlock();
      }
      queueLock.unlock();
    }
    return new ConfigChangeResult();
  }
opendj-server-legacy/src/main/java/org/opends/server/extensions/TraditionalWorkerThread.java
@@ -54,15 +54,12 @@
   */
  private boolean stoppedByReducedThreadNumber;
  /** Indicates whether this thread is currently waiting for work. */
  private boolean waitingForWork;
  /** Serializes publication of an operation with the shutdown request. */
  private final Object operationLock = new Object();
  /** The operation that this worker thread is currently processing. */
  private volatile Operation operation;
  /** The handle to the actual thread for this worker thread. */
  private Thread workerThread;
  /** The work queue that this worker thread will service. */
  private final TraditionalWorkQueue workQueue;
@@ -85,9 +82,7 @@
    stoppedByReducedThreadNumber = false;
    shutdownRequested            = false;
    waitingForWork               = false;
    operation                    = null;
    workerThread                 = null;
  }
@@ -127,22 +122,19 @@
  @Override
  public void run()
  {
    workerThread = currentThread();
    while (! shutdownRequested)
    {
      try
      {
        waitingForWork = true;
        operation = null; // this line is necessary because next line can block
        operation = workQueue.nextOperation(this);
        waitingForWork = false;
        if (operation == null)
        operation = null;
        Operation nextOperation = workQueue.nextOperation(this);
        if (nextOperation == null)
        {
          // The operation may be null if the server is shutting down.  If that
          // is the case, then break out of the while loop.
          break;
        }
        if (!startOperation(nextOperation))
        {
          workQueue.abortPendingOperation(nextOperation, new CancelRequest(true, INFO_CANCELED_BY_SHUTDOWN.get()));
          break;
        }
        else
@@ -264,51 +256,28 @@
      logger.trace(getName() + " being signaled to shut down.");
    }
    // Set a flag that indicates that the thread should stop running.
    shutdownRequested = true;
    // Check to see if the thread is waiting for work.  If so, then interrupt
    // it.
    if (waitingForWork)
    final Operation activeOperation;
    synchronized (operationLock)
    {
      try
      {
        workerThread.interrupt();
      }
      catch (Exception e)
      {
        if (logger.isTraceEnabled())
        {
          logger.trace(
            "Caught an exception while trying to interrupt the worker " +
                "thread waiting for work: %s", e);
          logger.traceException(e);
        }
      }
      shutdownRequested = true;
      activeOperation = operation;
    }
    else
    if (activeOperation != null)
    {
      try
      activeOperation.cancel(new CancelRequest(true, INFO_CANCELED_BY_SHUTDOWN.get()));
    }
  }
  private boolean startOperation(Operation nextOperation)
  {
    synchronized (operationLock)
    {
      if (shutdownRequested || workQueue.shutdownRequested())
      {
        final Operation localOperation = operation;
        if (localOperation != null)
        {
          CancelRequest cancelRequest = new CancelRequest(true,
              INFO_CANCELED_BY_SHUTDOWN.get());
          localOperation.cancel(cancelRequest);
        }
        return false;
      }
      catch (Exception e)
      {
        if (logger.isTraceEnabled())
        {
          logger.trace(
            "Caught an exception while trying to abandon the " +
                "operation in progress for the worker thread: %s", e);
          logger.traceException(e);
        }
      }
      operation = nextOperation;
      return true;
    }
  }
opendj-server-legacy/src/test/java/org/opends/quicksetup/TestUtilities.java
@@ -13,7 +13,7 @@
 *
 * Copyright 2009 Sun Microsystems, Inc.
 * Portions Copyright 2013-2015 ForgeRock AS.
 * Portions Copyright 2018-2026 3A Systems, LLC
 * Portions Copyright 2018-2026 3A Systems, LLC.
 */
package org.opends.quicksetup;
@@ -66,7 +66,7 @@
  }
  private static void setupServer() throws IOException, InterruptedException {
    int[] ports = TestCaseUtils.findFreePorts(2);
    int[] ports = TestCaseUtils.findFreePorts(3);
    ldapPort = ports[0];
    jmxPort = ports[1];
@@ -80,6 +80,8 @@
    args.add(Integer.toString(ldapPort));
    args.add("-x");
    args.add(Integer.toString(jmxPort));
    args.add("--adminConnectorPort");
    args.add(Integer.toString(ports[2]));
    args.add("-w");
    args.add(DIRECTORY_MANAGER_PASSWORD);
    // Create a backend so that configuration tests see database paths.
@@ -136,7 +138,7 @@
    String buildRoot = System.getProperty(PROPERTY_BUILD_ROOT);
    File   buildDir  = new File(buildRoot, "build");
    File   unitRootDir  = new File(buildDir, "unit-tests");
    return new File(unitRootDir, "quicksetup");
    return TestCaseUtils.getForkDirectory(new File(unitRootDir, "quicksetup"));
  }
  public static File getQuickSetupTestServerRootDir() {
opendj-server-legacy/src/test/java/org/opends/quicksetup/util/FileManagerTest.java
@@ -13,7 +13,7 @@
 *
 * Copyright 2006-2008 Sun Microsystems, Inc.
 * Portions Copyright 2014-2015 ForgeRock AS.
 * Portions Copyright 2026 3A Systems, LLC
 * Portions Copyright 2026 3A Systems, LLC.
 */
package org.opends.quicksetup.util;
@@ -129,12 +129,9 @@
  @Test
  public void testRenameNonExistentTarget() throws Exception {
    File src = File.createTempFile("src", null);
    File target = new File(src.getParentFile(), "target");
    File target = File.createTempFile("target", null);
    try {
      if (target.exists()) {
        target.delete();
        assertFalse(target.exists());
      }
      assertTrue(target.delete());
      fileManager.rename(src, target);
      assertFalse(src.exists());
      assertTrue(target.exists());
opendj-server-legacy/src/test/java/org/opends/server/TestCaseUtils.java
@@ -14,7 +14,7 @@
 * Copyright 2006-2010 Sun Microsystems, Inc.
 * Portions Copyright 2011-2016 ForgeRock AS.
 * Portions Copyright 2013 Manuel Gaupp
 * Portions Copyright 2018-2026 3A Systems, LLC
 * Portions Copyright 2018-2026 3A Systems, LLC.
 */
package org.opends.server;
@@ -886,47 +886,74 @@
   *
   * @throws IOException in case of underlying exception.
   */
  private static ServerSocket bindPort(int port)
          throws IOException
  private static ServerSocket bindPort(int port) throws IOException
  {
    ServerSocket serverLdapSocket;
    serverLdapSocket = new ServerSocket();
    serverLdapSocket.setReuseAddress(true);
    serverLdapSocket.bind(new InetSocketAddress(port));
    return serverLdapSocket;
    ServerSocket socket = new ServerSocket();
    try
    {
      socket.setReuseAddress(true);
      socket.bind(new InetSocketAddress(port));
      return socket;
    }
    catch (IOException e)
    {
      close(socket);
      throw e;
    }
  }
  static int port = 65535;
  private static final int TEST_FORK_COUNT = Math.max(1,
      Integer.parseInt(System.getProperty("org.opends.test.forkCount", "1")));
  private static final int TEST_FORK_NUMBER = Integer.getInteger("org.opends.test.forkNumber", 0);
  private static int nextTestPort = firstTestPort();
  private static int firstTestPort()
  {
    if (TEST_FORK_COUNT == 1)
    {
      return 65535;
    }
    if (TEST_FORK_NUMBER < 1 || TEST_FORK_NUMBER > TEST_FORK_COUNT)
    {
      throw new IllegalStateException("Expected a Failsafe fork number between 1 and " + TEST_FORK_COUNT
          + ", got " + System.getProperty("org.opends.test.forkNumber"));
    }
    // Concurrent forks start below the Linux ephemeral range and each walks its own sequence.
    return 32768 - TEST_FORK_NUMBER;
  }
  /**
   * Find and binds to a free server socket port on the local host. Avoid allocating ephemeral ports since these may
   * be used by client applications such as dsconfig. Instead scan through ports starting from a reasonably high number
   * which avoids most reserved services (see /etc/services) and continues up to the beginning of the ephemeral port
   * range. On most Linux OSes this is 32768, but may be higher.
   * Finds and binds a free server socket port on the local host.
   * In parallel precommit runs each fork allocates from a disjoint sequence below the Linux
   * ephemeral range, so another fork cannot claim a port between discovery and server startup.
   *
   * @return the bounded Server socket.
   *
   * @throws IOException in case of underlying exception.
   * @return The bound server socket.
   * @throws IOException If unable to bind to a free port.
   */
  public synchronized static ServerSocket bindFreePort() throws IOException
  {
      for (; port > 1024;)
      {
         ServerSocket res=null;
         try
         {
           res=bindPort(port--);
           return res;
         }
         catch (BindException e){
             if (res!=null) {
                 try {
                     res.close();
                 } catch (IOException ex) {}
             }
             res=null;
         }
      }
      throw new BindException("Unable to bind to a free port");
    while (nextTestPort > 1024)
    {
      int candidate = nextTestPort;
      nextTestPort -= TEST_FORK_COUNT;
      try
      {
        return bindPort(candidate);
      }
      catch (BindException e)
      {
        // The candidate is already in use. Try the next port assigned to this fork.
      }
    }
    throw new BindException("Unable to bind to a free port");
  }
  /**
   * Returns a fork-specific subdirectory when more than one test JVM is active.
   */
  public static File getForkDirectory(File directory)
  {
    return TEST_FORK_COUNT > 1 ? new File(directory, "fork-" + TEST_FORK_NUMBER) : directory;
  }
  /**
opendj-server-legacy/src/test/java/org/opends/server/TestListener.java
@@ -176,7 +176,7 @@
    }
    // Delete the previous report if it's there.
    new File(testContext.getOutputDirectory(), REPORT_FILE_NAME).delete();
    new File(getForkDirectory(new File(testContext.getOutputDirectory())), REPORT_FILE_NAME).delete();
  }
  @Override
@@ -199,19 +199,19 @@
  @Override
  public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
    File outputDir = new File(outputDirectory);
    File outputDir = getForkDirectory(new File(outputDirectory));
    if (!outputDir.exists()) {
      outputDir.mkdir();
      outputDir.mkdirs();
    }
    File reportFile = new File(outputDirectory, REPORT_FILE_NAME);
    File reportFile = new File(outputDir, REPORT_FILE_NAME);
    writeReportToFile(reportFile);
    writeReportToScreen(reportFile);
    writeAntTestsFailedMarker(outputDirectory);
    writeAntTestsFailedMarker(outputDir);
  }
  private void writeAntTestsFailedMarker(String outputDirectory) {
  private void writeAntTestsFailedMarker(File outputDirectory) {
    // Signal 'ant' that all of the tests passed by removing this
    // special file.
    if (countTestsWithStatus(ITestResult.FAILURE) == 0
opendj-server-legacy/src/test/java/org/opends/server/authorization/dseecompat/AciTests.java
@@ -20,6 +20,7 @@
import static org.opends.server.TestCaseUtils.*;
import static org.opends.server.config.ConfigConstants.*;
import static org.opends.server.protocols.internal.InternalClientConnection.getRootConnection;
import static org.opends.server.util.CollectionUtils.*;
import static org.opends.server.util.ServerConstants.*;
import static org.testng.Assert.*;
@@ -44,7 +45,9 @@
import com.forgerock.opendj.ldap.tools.LDAPCompare;
import com.forgerock.opendj.ldap.tools.LDIFDiff;
import org.forgerock.opendj.ldap.ResultCode;
import org.opends.server.TestCaseUtils;
import org.opends.server.core.DeleteOperation;
import org.opends.server.protocols.ldap.LDAPResultCode;
import com.forgerock.opendj.ldap.tools.LDAPModify;
import com.forgerock.opendj.ldap.tools.LDAPSearch;
@@ -55,8 +58,7 @@
import org.testng.annotations.Test;
/**
 * These are more functional tests than unit tests.  They go directly over
 * LDAP for all of their operations.  We use the builtin LDAPModify,
 * These functional tests exercise ACI behavior over LDAP. We use the builtin LDAPModify,
 * LDAPSearch, etc. tools to do this, as well as the ones that can
 * do similar operations directly on LDIF (e.g. LDIFDiff).  This is
 * probably the easiest way to test the code, and it makes it easy to test
@@ -188,8 +190,7 @@
  private static final String PROXY_USER_DN = "cn=proxy user," + OU_BASE_DN;
  /**
   * We need to delete all of these between each test.  This list needs to be
   * bottom up so that it can be handed to LDAPDelete.
   * Test entries in deletion order, with child entries before their parents.
   */
  private static final String[] ALL_TEST_ENTRY_DNS_BOTTOM_UP = {
    SALES_USER_1,
@@ -565,8 +566,15 @@
  @BeforeMethod
  public void clearBackend() throws Exception {
    deleteAllTestEntries();
  public void clearBackend() {
    // Wait for post-response delete plugins before the next test reuses the same DNs.
    // An LDAP delete can return while AuthenticatedUsers is still processing the deletion.
    for (String dn : ALL_TEST_ENTRY_DNS_BOTTOM_UP) {
      DeleteOperation delete = getRootConnection().processDelete(dn);
      ResultCode result = delete.getResultCode();
      assertTrue(result == ResultCode.SUCCESS || result == ResultCode.NO_SUCH_OBJECT,
          "Could not delete test entry " + dn + " (" + result + ") " + delete.getErrorMessage());
    }
  }
// -----------------------------------------------------------------------------
@@ -2301,17 +2309,17 @@
  private void modEntries(String ldif, String bindDn, String bindPassword)
          throws Exception {
    modEntries(ldif, bindDn, bindPassword, null, true, false);
    modEntries(ldif, bindDn, bindPassword, null, true);
  }
  private void modEntries(String ldif, String bindDn, String bindPassword, String proxyDN)
          throws Exception {
    modEntries(ldif, bindDn, bindPassword, proxyDN, true, false);
    modEntries(ldif, bindDn, bindPassword, proxyDN, true);
  }
  private void modEntriesExpectFailure(String ldif, String bindDn,
                                       String bindPassword) throws Exception {
    modEntries(ldif, bindDn, bindPassword, null, false, false);
    modEntries(ldif, bindDn, bindPassword, null, false);
  }
  private void _modEntries(String ldif, String bindDn, String bindPassword,
@@ -2332,8 +2340,7 @@
  }
    private void modEntries(String ldif, String bindDn, String bindPassword,
                          String proxyDN, boolean expectSuccess,
                          boolean contFlag)
                          String proxyDN, boolean expectSuccess)
    throws Exception {
    File tempFile = getTemporaryLdifFile();
    TestCaseUtils.writeFile(tempFile, ldif);
@@ -2348,10 +2355,6 @@
    argList.add(bindPassword);
    argList.add("-f");
    argList.add(tempFile.getAbsolutePath());
    if(contFlag)
    {
      argList.add("-c");
    }
    if(proxyDN != null) {
        argList.add("-Y");
        argList.add("dn:" + proxyDN);
@@ -2360,10 +2363,6 @@
    ldapModify(argList.toArray(args), expectSuccess);
  }
    private void deleteAllTestEntries() throws Exception {
        deleteEntries(ALL_TEST_ENTRY_DNS_BOTTOM_UP);
    }
  private void deleteAttrFromEntry(String dn, String attr, String val,
                                   String bindDN, String pwd,
                                   boolean errorOk) throws Exception {
@@ -2373,7 +2372,7 @@
                "changetype: modify",
                "delete: " + attr,
                attr + ":" + val));
        modEntries(ldif.toString(), bindDN, pwd, null, errorOk, false);
        modEntries(ldif.toString(), bindDN, pwd, null, errorOk);
    }
@@ -2400,21 +2399,9 @@
                  "dn: "  + dn,
                  "changetype: modify",
                  "delete: " + attr));
          modEntries(ldif.toString(), DIR_MGR_DN, DIR_MGR_PW,  null, errorOk, false);
          modEntries(ldif.toString(), DIR_MGR_DN, DIR_MGR_PW, null, errorOk);
      }
    private void deleteEntries(String[] entries) throws Exception {
        // TODO: make this actually do a search first!
        StringBuilder ldif = new StringBuilder();
        for (String dn: entries) {
            ldif.append(TestCaseUtils.makeLdif(
                    "dn: " + dn,
                    "changetype: delete"
            ));
        }
        modEntries(ldif.toString(), DIR_MGR_DN, DIR_MGR_PW, null, true, true);
    }
  /**
   * Return the difference between two ldif files.
   */
opendj-server-legacy/src/test/java/org/opends/server/core/BindOperationTestCase.java
@@ -1906,31 +1906,23 @@
    }
  }
  /**
   * Tests the <CODE>cancel</CODE> method to ensure that it indicates that the
   * operation cannot be cancelled.
   * @param bindOperation The bind operation.
   */
  @Test(dataProvider = "simpleBinds")
  public void testCancel(BindOperation bindOperation)
  public void testCancelCompletedBind(BindOperation bindOperation)
  {
    CancelRequest cancelRequest =
         new CancelRequest(false, LocalizableMessage.raw("Test Unbind Cancel"));
    assertEquals(bindOperation.cancel(cancelRequest).getResultCode(),
                 ResultCode.CANNOT_CANCEL);
    bindOperation.operationCompleted();
    assertBindCannotBeCancelled(bindOperation);
  }
  /**
   * Tests the <CODE>getCancelRequest</CODE> method to ensure that it always
   * returns <CODE>null</CODE>.
   * @param bindOperation The bind operation.
   */
  @Test(dataProvider = "simpleBinds")
  public void testGetCancelRequest(BindOperation bindOperation)
  @Test
  public void testCancelUnfinishedBind()
  {
    assertBindCannotBeCancelled(newBindOp(null, ByteString.empty(), ByteString.empty()));
  }
  private void assertBindCannotBeCancelled(BindOperation bindOperation)
  {
    CancelRequest cancelRequest =
         new CancelRequest(false, LocalizableMessage.raw("Test Unbind Cancel"));
         new CancelRequest(false, LocalizableMessage.raw("Test Bind Cancel"));
    assertNull(bindOperation.getCancelRequest());
opendj-server-legacy/src/test/java/org/opends/server/extensions/TraditionalWorkQueueShutdownTest.java
New file
@@ -0,0 +1,277 @@
/*
 * The contents of this file are subject to the terms of the Common Development and
 * Distribution License (the License). You may not use this file except in compliance with the
 * License.
 *
 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
 * specific language governing permission and limitations under the License.
 *
 * When distributing Covered Software, include this CDDL Header Notice in each file and include
 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
 * Header, with the fields enclosed by brackets [] replaced by your own identifying
 * information: "Portions copyright [year] [name of copyright owner]".
 *
 * Copyright 2026 3A Systems, LLC.
 */
package org.opends.server.extensions;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.mockito.Mockito.*;
import static org.testng.Assert.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.FutureTask;
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.opendj.ldap.ResultCode;
import org.forgerock.opendj.server.config.server.TraditionalWorkQueueCfg;
import org.opends.server.DirectoryServerTestCase;
import org.opends.server.types.CancelRequest;
import org.opends.server.types.DirectoryException;
import org.opends.server.types.Operation;
import org.opends.server.util.TestTimer;
import org.testng.annotations.Test;
/** Verifies that shutting down a traditional work queue wakes idle workers and accounts for pending work. */
public class TraditionalWorkQueueShutdownTest extends DirectoryServerTestCase
{
  private static final LocalizableMessage SHUTDOWN_REASON = LocalizableMessage.raw("Test work queue shutdown");
  @Test
  public void wakesAnIdleWorkerBeforeThePollExpires() throws Exception
  {
    TestWorkQueue queue = new TestWorkQueue();
    queue.initializeWorkQueue(config(10));
    try
    {
      waitForIdleWorker(queue);
    }
    finally
    {
      long start = System.nanoTime();
      queue.finalizeWorkQueue(SHUTDOWN_REASON);
      assertTrue(System.nanoTime() - start < SECONDS.toNanos(3),
          "Shutdown waited for the idle worker's five-second poll");
    }
    queue.worker.join(SECONDS.toMillis(3));
    assertFalse(queue.worker.isAlive(), "The idle worker did not exit");
    assertTrue(queue.isIdle());
  }
  @Test
  public void accountsForDrainedOperationsWithoutInterruptingAnActiveWorker() throws Exception
  {
    CountDownLatch running = new CountDownLatch(1);
    CountDownLatch finish = new CountDownLatch(1);
    CountDownLatch interrupted = new CountDownLatch(1);
    TestWorkQueue queue = new TestWorkQueue();
    queue.initializeWorkQueue(config(10));
    Operation active = mock(Operation.class);
    doAnswer(invocation -> {
      running.countDown();
      try
      {
        finish.await();
      }
      catch (InterruptedException e)
      {
        interrupted.countDown();
        Thread.currentThread().interrupt();
      }
      return null;
    }).when(active).run();
    Operation pending = mock(Operation.class);
    try
    {
      queue.submitOperation(active);
      assertTrue(running.await(5, SECONDS), "Worker did not begin the active operation");
      queue.submitOperation(pending);
      Operation anotherPending = mock(Operation.class);
      queue.submitOperation(anotherPending);
      queue.applyConfigurationChange(config(1));
      assertFalse(queue.trySubmitOperation(mock(Operation.class)), "The smaller queue is full");
      queue.finalizeWorkQueue(SHUTDOWN_REASON);
      verify(active).cancel(any(CancelRequest.class));
      verify(anotherPending).abort(any(CancelRequest.class));
      verify(anotherPending, never()).run();
      verify(pending).abort(any(CancelRequest.class));
      verify(pending, never()).run();
      assertFalse(queue.isIdle(), "The active operation is still pending");
    }
    finally
    {
      finish.countDown();
      if (!queue.shutdownRequested())
      {
        queue.finalizeWorkQueue(SHUTDOWN_REASON);
      }
    }
    assertTrue(queue.waitUntilIdle(1000), "The drained operation still counts as pending");
    assertEquals(interrupted.getCount(), 1L, "Shutdown interrupted a worker processing an operation");
  }
  @Test
  public void stoppingAdmissionWakesAllBlockedSubmittersBeforeFinalization() throws Exception
  {
    CountDownLatch running = new CountDownLatch(1);
    CountDownLatch finish = new CountDownLatch(1);
    TestWorkQueue queue = new TestWorkQueue();
    queue.initializeWorkQueue(config(1));
    Operation active = mock(Operation.class);
    doAnswer(invocation -> {
      running.countDown();
      finish.await();
      return null;
    }).when(active).run();
    Operation queued = mock(Operation.class);
    try
    {
      queue.submitOperation(active);
      assertTrue(running.await(5, SECONDS), "Worker did not begin the active operation");
      queue.submitOperation(queued);
      FutureTask<ResultCode> first = startBlockedSubmitter(queue, "First submitter");
      FutureTask<ResultCode> second = startBlockedSubmitter(queue, "Second submitter");
      queue.stopAcceptingOperations();
      assertEquals(first.get(5, SECONDS), ResultCode.UNAVAILABLE, "First submitter was not rejected");
      assertEquals(second.get(5, SECONDS), ResultCode.UNAVAILABLE, "Second submitter was not rejected");
      DirectoryException rejection = expectThrows(DirectoryException.class,
          () -> queue.trySubmitOperation(mock(Operation.class)));
      assertEquals(rejection.getResultCode(), ResultCode.UNAVAILABLE);
      assertFalse(queue.shutdownRequested(), "Stopping admission stopped the worker pool");
      assertEquals(queue.size(), 1, "Stopping admission drained the queue");
      verify(active, never()).cancel(any(CancelRequest.class));
      verify(active, never()).operationCompleted();
      verify(queued, never()).abort(any(CancelRequest.class));
    }
    finally
    {
      try
      {
        queue.finalizeWorkQueue(SHUTDOWN_REASON);
      }
      finally
      {
        finish.countDown();
      }
    }
    verify(active).cancel(any(CancelRequest.class));
    verify(queued).abort(any(CancelRequest.class));
    assertTrue(queue.waitUntilIdle(1000), "Rejected submissions or canceled operations still count as pending");
  }
  @Test
  public void abortsADequeuedOperationWhenShutdownWinsTheHandoff() throws Exception
  {
    CountDownLatch dequeued = new CountDownLatch(1);
    CountDownLatch handoff = new CountDownLatch(1);
    TestWorkQueue queue = new TestWorkQueue()
    {
      @Override
      public Operation nextOperation(TraditionalWorkerThread worker)
      {
        Operation operation = super.nextOperation(worker);
        if (operation != null)
        {
          dequeued.countDown();
          try
          {
            assertTrue(handoff.await(5, SECONDS), "Timed out waiting for handoff to resume");
          }
          catch (InterruptedException e)
          {
            throw new AssertionError("Shutdown interrupted the handoff", e);
          }
        }
        return operation;
      }
    };
    queue.initializeWorkQueue(config(10));
    Operation pending = mock(Operation.class);
    try
    {
      queue.submitOperation(pending);
      assertTrue(dequeued.await(5, SECONDS), "Worker did not dequeue the operation");
      queue.finalizeWorkQueue(SHUTDOWN_REASON);
      assertFalse(queue.isIdle(), "The dequeued operation is still in the handoff");
    }
    finally
    {
      handoff.countDown();
      if (!queue.shutdownRequested())
      {
        queue.finalizeWorkQueue(SHUTDOWN_REASON);
      }
    }
    assertTrue(queue.waitUntilIdle(1000), "The handoff operation was not aborted");
    verify(pending).abort(any(CancelRequest.class));
    verify(pending, never()).run();
  }
  private TraditionalWorkQueueCfg config(int capacity)
  {
    TraditionalWorkQueueCfg config = mock(TraditionalWorkQueueCfg.class);
    when(config.getNumWorkerThreads()).thenReturn(1);
    when(config.getMaxWorkQueueCapacity()).thenReturn(capacity);
    return config;
  }
  private void waitForIdleWorker(TestWorkQueue queue) throws Exception
  {
    new TestTimer.Builder().maxSleep(5, SECONDS).sleepTimes(10, MILLISECONDS).toTimer().repeatUntilSuccess(() -> {
      Thread worker = queue.worker;
      assertNotNull(worker, "Worker has not started");
      assertWaitingInQueue(worker, "retryNextOperation");
    });
  }
  private FutureTask<ResultCode> startBlockedSubmitter(TestWorkQueue queue, String name) throws Exception
  {
    Operation operation = mock(Operation.class);
    FutureTask<ResultCode> submission = new FutureTask<>(() ->
        expectThrows(DirectoryException.class, () -> queue.submitOperation(operation)).getResultCode());
    Thread thread = new Thread(submission, name);
    thread.setDaemon(true);
    thread.start();
    new TestTimer.Builder().maxSleep(5, SECONDS).sleepTimes(10, MILLISECONDS).toTimer().repeatUntilSuccess(
        () -> assertWaitingInQueue(thread, "submitOperation"));
    return submission;
  }
  private void assertWaitingInQueue(Thread thread, String methodName)
  {
    assertEquals(thread.getState(), Thread.State.WAITING, thread.getName() + " has not entered the condition wait");
    StackTraceElement[] stack = thread.getStackTrace();
    for (int i = 1; i < stack.length; i++)
    {
      StackTraceElement frame = stack[i];
      if (frame.getClassName().equals(TraditionalWorkQueue.class.getName())
          && frame.getMethodName().equals(methodName)
          && stack[i - 1].getMethodName().equals("await"))
      {
        return;
      }
    }
    fail(thread.getName() + " has not reached the queue wait");
  }
  private static class TestWorkQueue extends TraditionalWorkQueue
  {
    private volatile TraditionalWorkerThread worker;
    @Override
    void registerQueueMonitor()
    {
      // This queue is local to the test and has no server monitor.
    }
    @Override
    public Operation nextOperation(TraditionalWorkerThread workerThread)
    {
      worker = workerThread;
      return super.nextOperation(workerThread);
    }
  }
}
opendj-server-legacy/src/test/java/org/opends/server/protocols/ldap/LDAPConnectionHandler2TransportTestCase.java
@@ -15,6 +15,13 @@
 */
package org.opends.server.protocols.ldap;
import static java.util.Arrays.stream;
import static java.util.Collections.singletonList;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.forgerock.opendj.ldap.LDAPConnectionFactory.SSL_CONTEXT;
import static org.forgerock.opendj.ldap.ModificationType.REPLACE;
import static org.forgerock.opendj.ldap.requests.Requests.*;
import static org.mockito.Mockito.*;
import static org.opends.messages.CoreMessages.INFO_CONNHANDLER_CLOSED_BY_SHUTDOWN;
import static org.testng.Assert.*;
@@ -29,22 +36,35 @@
import java.net.SocketTimeoutException;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.opendj.ldap.Connection;
import org.forgerock.opendj.ldap.DN;
import org.forgerock.opendj.ldap.LDAPConnectionFactory;
import org.forgerock.opendj.ldap.LdapPromise;
import org.forgerock.opendj.ldap.SSLContextBuilder;
import org.forgerock.opendj.ldap.responses.Result;
import org.forgerock.opendj.ldif.LDIFEntryReader;
import org.forgerock.opendj.reactive.LDAPConnectionHandler2;
import org.forgerock.opendj.server.config.meta.LDAPConnectionHandlerCfgDefn;
import org.forgerock.opendj.server.config.server.LDAPConnectionHandlerCfg;
import org.forgerock.opendj.server.config.server.TraditionalWorkQueueCfg;
import org.forgerock.util.Options;
import org.glassfish.grizzly.memory.Buffers;
import org.glassfish.grizzly.nio.transport.TCPNIOConnection;
import org.glassfish.grizzly.nio.transport.TCPNIOServerConnection;
import org.glassfish.grizzly.nio.transport.TCPNIOTransport;
import org.opends.admin.ads.util.BlindTrustManager;
import org.opends.server.DirectoryServerTestCase;
import org.opends.server.TestCaseUtils;
import org.opends.server.api.ClientConnection;
@@ -52,8 +72,11 @@
import org.opends.server.api.ServerShutdownListener;
import org.opends.server.core.DirectoryServer;
import org.opends.server.extensions.InitializationUtils;
import org.opends.server.extensions.TraditionalWorkQueue;
import org.opends.server.tools.LDAPReader;
import org.opends.server.types.Entry;
import org.opends.server.types.Operation;
import org.opends.server.util.TestTimer;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
@@ -133,6 +156,141 @@
    }
  }
  @Test
  public void finalizeReleasesTheListeningPortForImmediateRestart() throws Exception
  {
    final int port = TestCaseUtils.findFreePort();
    final LDAPConnectionHandler2 handler = start(configuration(port, true, true, true, 2));
    try
    {
      handler.finalizeConnectionHandler(STOP_REASON);
      try (ServerSocket replacement = new ServerSocket())
      {
        replacement.setReuseAddress(true);
        replacement.bind(new InetSocketAddress("127.0.0.1", port));
      }
    }
    finally
    {
      handler.join(TIMEOUT_MS);
    }
  }
  @DataProvider
  public Object[][] liveRemovalOperations()
  {
    return new Object[][] { { false }, { true } };
  }
  @Test(dataProvider = "liveRemovalOperations")
  public void liveDisableOrDeleteCompletesWhileTheListenerWaitsForQueueSpace(boolean delete) throws Exception
  {
    final int port = TestCaseUtils.findFreePort();
    final Entry entry = configurationEntry(port, true, true, true, 1);
    final DN dn = entry.getName();
    final TraditionalWorkQueue queue = (TraditionalWorkQueue) DirectoryServer.getWorkQueue();
    final TraditionalWorkQueueCfg original =
        (TraditionalWorkQueueCfg) DirectoryServer.getInstance().getServerContext().getRootConfig().getWorkQueue();
    final CountDownLatch running = new CountDownLatch(1);
    final CountDownLatch releaseWorker = new CountDownLatch(1);
    final Operation active = mock(Operation.class);
    doAnswer(invocation -> {
      running.countDown();
      releaseWorker.await();
      return null;
    }).when(active).run();
    final Options tls = Options.defaultOptions()
        .set(SSL_CONTEXT, new SSLContextBuilder().setTrustManager(new BlindTrustManager()).getSSLContext());
    TestCaseUtils.addEntry(entry);
    try (LDAPConnectionFactory adminFactory =
            new LDAPConnectionFactory("localhost", TestCaseUtils.getServerAdminPort(), tls);
         Connection admin = adminFactory.getConnection();
         LDAPConnectionFactory targetFactory = new LDAPConnectionFactory("127.0.0.1", port);
         Connection target = targetFactory.getConnection())
    {
      admin.bind("cn=Directory Manager", "password".toCharArray());
      final LDAPConnectionHandler2 handler = DirectoryServer.getConnectionHandlers().stream()
          .filter(candidate -> dn.equals(candidate.getComponentEntryDN()))
          .map(LDAPConnectionHandler2.class::cast)
          .findFirst().orElseThrow();
      final Thread selector = acceptedConnection(handler).getSelectorRunner().getRunnerThread();
      final TestTimer timer = new TestTimer.Builder().maxSleep(TIMEOUT_MS, MILLISECONDS)
          .sleepTimes(10, MILLISECONDS).toTimer();
      try
      {
        setWorkQueueCapacity(queue, 2);
        queue.submitOperation(active);
        assertTrue(running.await(TIMEOUT_MS, MILLISECONDS), "the worker did not start the active operation");
        final LdapPromise<Result> change = delete ? admin.deleteAsync(newDeleteRequest(dn))
            : admin.modifyAsync(newModifyRequest(dn).addModification(REPLACE, "ds-cfg-enabled", "false"));
        timer.repeatUntilSuccess(() -> assertEquals(queue.size(), 1, "the configuration operation was not queued"));
        queue.submitOperation(mock(Operation.class));
        // The second operation keeps the queue full even after the worker takes the configuration operation.
        setWorkQueueCapacity(queue, 1);
        final LdapPromise<?> read = target.readEntryAsync(DN.rootDN(), singletonList("objectClass"));
        timer.repeatUntilSuccess(() -> assertTrue(selector.getState() == Thread.State.WAITING
            && stream(selector.getStackTrace()).anyMatch(frame ->
                frame.getClassName().equals(TraditionalWorkQueue.class.getName())
                    && frame.getMethodName().equals("submitOperation")), "the selector did not block in the queue"));
        releaseWorker.countDown();
        assertTrue(change.getOrThrow(TIMEOUT_MS, MILLISECONDS).isSuccess());
        assertSavedConfiguration(dn, delete);
        assertNotNull(admin.readEntryAsync(DN.rootDN(), singletonList("objectClass"))
            .getOrThrow(TIMEOUT_MS, MILLISECONDS), "the administrative connection no longer serves requests");
        assertNotNull(read.getOrThrow(TIMEOUT_MS, MILLISECONDS), "the established connection did not resume");
        handler.join(TIMEOUT_MS);
        assertFalse(handler.isAlive(), "the disabled or deleted handler did not finish closing");
        try (ServerSocket replacement = new ServerSocket())
        {
          replacement.setReuseAddress(true);
          replacement.bind(new InetSocketAddress("127.0.0.1", port));
        }
      }
      finally
      {
        releaseWorker.countDown();
        queue.applyConfigurationChange(original);
      }
    }
    finally
    {
      if (DirectoryServer.getEntry(dn) != null)
      {
        TestCaseUtils.deleteEntry(dn);
      }
    }
  }
  private static void setWorkQueueCapacity(TraditionalWorkQueue queue, int capacity)
  {
    final TraditionalWorkQueueCfg config = mock(TraditionalWorkQueueCfg.class);
    when(config.getNumWorkerThreads()).thenReturn(1);
    when(config.getMaxWorkQueueCapacity()).thenReturn(capacity);
    queue.applyConfigurationChange(config);
  }
  private static void assertSavedConfiguration(DN dn, boolean delete) throws IOException
  {
    try (LDIFEntryReader reader = new LDIFEntryReader(Files.newInputStream(Paths.get(DirectoryServer.getConfigFile()))))
    {
      while (reader.hasNext())
      {
        final org.forgerock.opendj.ldap.Entry saved = reader.readEntry();
        if (dn.equals(saved.getName()))
        {
          assertFalse(delete, "the deleted handler is still in config.ldif");
          assertEquals(saved.parseAttribute("ds-cfg-enabled").asString(), "false");
          return;
        }
      }
    }
    assertTrue(delete, "the disabled handler is missing from config.ldif");
  }
  @DataProvider
  public Object[][] reuseAddress()
  {
@@ -146,7 +304,7 @@
        start(configuration(freePort(reuseAddress), true, true, reuseAddress, 2));
    try
    {
      final Collection<?> serverConnections = (Collection<?>) field(field(handler, "listener"), "impl", "serverConnections");
      final Collection<?> serverConnections = (Collection<?>) field(field(handler, "listener"), "serverConnections");
      assertFalse(serverConnections.isEmpty(), "the handler does not listen");
      for (Object serverConnection : serverConnections)
      {
@@ -334,9 +492,9 @@
  /**
   * The server shutting down, here for an in-core restart, ends the connections of a handler that is still listening
   * with a notice of disconnection. The handler stops its listener on its own thread, which may wake before or after
   * the next server instance is current: {@link #drainEndsTheConnectionsWhenTheServerOfItsHandlerIsShuttingDown()}
   * covers the latter.
   * with a notice of disconnection. The handler stops listening on its own thread and then drains the transport.
   * {@link #drainEndsTheConnectionsWhenTheServerOfItsHandlerIsShuttingDown()} covers a drain against a previous server
   * instance.
   */
  @Test
  public void serverRestartEndsTheConnectionsOfAListeningHandler() throws Exception
@@ -717,6 +875,13 @@
  private static LDAPConnectionHandlerCfg configuration(int port, boolean keepAlive, boolean noDelay,
      boolean reuseAddress, Integer numRequestHandlers) throws Exception
  {
    return InitializationUtils.getConfiguration(LDAPConnectionHandlerCfgDefn.getInstance(),
        configurationEntry(port, keepAlive, noDelay, reuseAddress, numRequestHandlers));
  }
  private static Entry configurationEntry(int port, boolean keepAlive, boolean noDelay,
      boolean reuseAddress, Integer numRequestHandlers) throws Exception
  {
    final List<String> lines = new ArrayList<>();
    lines.add("dn: cn=Transport Test Handler,cn=Connection Handlers,cn=config");
    lines.add("objectClass: top");
@@ -741,8 +906,7 @@
    {
      lines.add("ds-cfg-num-request-handlers: " + numRequestHandlers);
    }
    final Entry entry = TestCaseUtils.makeEntry(lines.toArray(new String[0]));
    return InitializationUtils.getConfiguration(LDAPConnectionHandlerCfgDefn.getInstance(), entry);
    return TestCaseUtils.makeEntry(lines.toArray(new String[0]));
  }
  private static LDAPConnectionHandler2 start(LDAPConnectionHandlerCfg config) throws Exception
opendj-server-legacy/src/test/java/org/opends/server/protocols/ldap/LDAPConnectionLimitsTestCase.java
@@ -37,6 +37,7 @@
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RunnableScheduledFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@@ -69,7 +70,6 @@
import org.opends.server.tools.LDAPReader;
import org.opends.server.types.DisconnectReason;
import org.opends.server.types.Entry;
import org.testng.SkipException;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
@@ -231,40 +231,63 @@
  }
  /**
   * A connection accepted after the handler is finalized, before its listener stops, is still released when it
   * closes: the handler has no finalizer left to time it.
   * A connection that finishes accept after the connection finalizer shuts down still gives back its place when it
   * closes.
   */
  @Test
  public void connectionAcceptedWhileTheHandlerIsFinalizedIsReleasedWhenItCloses() throws Exception
  public void connectionAcceptedDuringFinalizationGivesBackItsPlaceWhenItCloses() throws Exception
  {
    for (int attempt = 0; attempt < 5; attempt++)
    final int port = TestCaseUtils.findFreePort();
    final LDAPConnectionHandler2 handler =
        start(configuration(port, "ds-cfg-max-client-connections-per-address: 2"));
    final ExecutorService finalizer = finalizer(handler);
    final FutureTask<Void> shutdown = new FutureTask<>(() -> handler.finalizeConnectionHandler(STOP_REASON), null);
    final CompletableFuture<Void> acceptStarted = new CompletableFuture<>();
    final CompletableFuture<Void> finishAccept = new CompletableFuture<>();
    final PostConnectPlugin plugin = new PostConnectPlugin(handler, connection -> {
      acceptStarted.complete(null);
      finishAccept.join();
      return PluginResult.PostConnect.continueConnectProcessing();
    });
    try (Socket established = new Socket("127.0.0.1", port))
    {
      final int port = TestCaseUtils.findFreePort();
      final LDAPConnectionHandler2 handler = start(configuration(port));
      // Keep the transport draining while the next connection is still in its post-connect plugin.
      bindAnonymously(established);
      DirectoryServer.registerInternalPlugin(plugin);
      try
      {
        // The listener stops only when run() next wakes up, up to a second later.
        handler.finalizeConnectionHandler(STOP_REASON);
        try (Socket client = new Socket("127.0.0.1", port))
        {
          if (!awaitClientConnectionsQuietly(handler, 1))
          {
            continue;
          }
          acceptStarted.get(TIMEOUT_MS, TimeUnit.MILLISECONDS);
          new Thread(shutdown, "Finalize limits test handler").start();
          assertTrue(finalizer.awaitTermination(TIMEOUT_MS, TimeUnit.MILLISECONDS),
              "the connection finalizer did not shut down while accept was in flight");
          finishAccept.complete(null);
          shutdown.get(TIMEOUT_MS, TimeUnit.MILLISECONDS);
          bindAnonymously(client);
          awaitClientConnections(handler, 2);
          awaitPlacesHeld(handler, 2);
        }
        catch (IOException listenerAlreadyStopped)
        {
          continue;
        }
        awaitClientConnections(handler, 0);
        return;
        awaitClientConnections(handler, 1);
        awaitPlacesHeld(handler, 1);
      }
      finally
      {
        handler.join(TIMEOUT_MS);
        finishAccept.complete(null);
        DirectoryServer.deregisterInternalPlugin(plugin);
      }
    }
    throw new SkipException("the listener stopped before a connection could reach the finalized handler");
    finally
    {
      // Finalize once, including if setup failed before the shutdown thread was started.
      shutdown.run();
      shutdown.get(TIMEOUT_MS, TimeUnit.MILLISECONDS);
      handler.join(TIMEOUT_MS);
      assertFalse(handler.isAlive(), "the connection handler thread is still running");
    }
    awaitClientConnections(handler, 0);
    awaitPlacesHeld(handler, 0);
  }
  /**
@@ -864,21 +887,6 @@
    assertEquals(client.getInputStream().read(), -1, "the connection stayed open after the notice");
  }
  private static boolean awaitClientConnectionsQuietly(LDAPConnectionHandler2 handler, int expected)
      throws Exception
  {
    final long deadline = System.currentTimeMillis() + TIMEOUT_MS;
    while (handler.getClientConnections().size() != expected)
    {
      if (System.currentTimeMillis() >= deadline)
      {
        return false;
      }
      Thread.sleep(50);
    }
    return true;
  }
  private static void awaitClientConnections(LDAPConnectionHandler2 handler, int expected) throws Exception
  {
    final long deadline = System.currentTimeMillis() + TIMEOUT_MS;
opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/AssuredReplicationPluginTest.java
@@ -37,6 +37,8 @@
import java.util.Set;
import java.util.StringTokenizer;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.assertj.core.api.Assertions;
import org.assertj.core.data.MapEntry;
@@ -132,6 +134,8 @@
  private final int RS_SERVER_ID = 90;
  /** Sleep time of the RS, before sending an ack. */
  private static final long NO_TIMEOUT_RS_SLEEP_TIME = 2000;
  /** Read timeout for the final check that a replay did not send an ack. */
  private static final int NO_ACK_READ_TIMEOUT = 5000;
  private final String testName = getClass().getSimpleName();
  /**
@@ -348,7 +352,8 @@
     * Signal that the current scenario the RS must execute reached the point
     * where the main code can perform test assertion.
     */
    private boolean scenarioExecuted;
    private final CountDownLatch scenarioExecuted = new CountDownLatch(1);
    private long ackSendStartedNanos;
    private CSNGenerator gen;
    private String testcase;
@@ -534,13 +539,20 @@
      return handshakeOk;
    }
    /**
     * Tells the main code that the fake RS executed enough of the expected
     * scenario and can perform test assertion.
     */
    public boolean isScenarioExecuted()
    /** Waits until the fake RS has completed the part of the scenario under test. */
    private void awaitScenarioExecuted() throws InterruptedException
    {
      return scenarioExecuted;
      assertTrue(scenarioExecuted.await(10, TimeUnit.SECONDS),
          testcase + ": timed out waiting for the fake RS to complete the scenario");
    }
    /** Checks the add timing before waiting for the fake RS to finish publishing the ACK. */
    private void assertAddWaitedForAck(long startTime, int timeout) throws InterruptedException
    {
      final long addReturnedNanos = System.nanoTime();
      assertBlockedForLessThanTimeout(startTime, timeout);
      awaitScenarioExecuted();
      assertTrue(addReturnedNanos - ackSendStartedNanos >= 0, "add returned before the fake RS sent the ACK");
    }
    /** Handle client connection then call code specific to configured test. */
@@ -602,6 +614,23 @@
     */
    private AckMsg sendAssuredAddMsg(Entry entry, String parentUid) throws Exception
    {
      publishAssuredAddMsg(entry, parentUid);
      return waitForSpecificMsg(session, AckMsg.class);
    }
    private void assertNoAckForAssuredAdd(Entry entry, String parentUid) throws Exception
    {
      publishAssuredAddMsg(entry, parentUid);
      // Confirm the DS replayed the add before checking whether it acknowledged it.
      assertNotNull(getEntry(entry.getName(), NO_ACK_READ_TIMEOUT, true));
      // This is the session's last read before the test closes it.
      session.setSoTimeout(NO_ACK_READ_TIMEOUT);
      assertThrows(SocketTimeoutException.class, () -> waitForSpecificMsg(session, AckMsg.class));
    }
    private void publishAssuredAddMsg(Entry entry, String parentUid) throws Exception
    {
      AddMsg addMsg = new AddMsg(
          gen.newCSN(), entry.getName(), UUID.randomUUID().toString(),
          parentUid, entry.getObjectClassAttribute(), entry.getAllAttributes(), null);
@@ -611,8 +640,6 @@
      addMsg.setAssuredMode(assuredMode);
      addMsg.setSafeDataLevel(safeDataLevel);
      session.publish(addMsg);
      return waitForSpecificMsg(session, AckMsg.class);
    }
    /** Read the coming update and check parameters are not assured. */
@@ -620,7 +647,7 @@
    {
      checkAssuredParametersOnReceivedUpdateMsg();
      scenarioExecuted = true;
      scenarioExecuted.countDown();
    }
    /** Read the coming update and make the client time out by not sending back the ack. */
@@ -628,7 +655,7 @@
    {
      checkAssuredParametersOnReceivedUpdateMsg();
      scenarioExecuted = true;
      scenarioExecuted.countDown();
      // We do not send back an ack and the client code is expected to be
      // blocked at least for the programmed timeout time.
@@ -644,9 +671,10 @@
      // Send the ack without errors
      AckMsg ackMsg = new AckMsg(updateMsg.getCSN());
      ackSendStartedNanos = System.nanoTime();
      session.publish(ackMsg);
      scenarioExecuted = true;
      scenarioExecuted.countDown();
    }
    /**
@@ -703,7 +731,7 @@
      updateMsg = checkAssuredParametersOnReceivedUpdateMsg();
      // let timeout occur
      scenarioExecuted = true;
      scenarioExecuted.countDown();
    }
    /** Read the coming safe data mode updates and send back acks with errors. */
@@ -737,7 +765,7 @@
      updateMsg = checkAssuredParametersOnReceivedUpdateMsg();
      // let timeout occur
      scenarioExecuted = true;
      scenarioExecuted.countDown();
    }
  }
@@ -803,13 +831,12 @@
      }
      long endTime = System.currentTimeMillis();
      waitForScenarioExecutedOnRs(testcase, replicationServer);
      replicationServer.awaitScenarioExecuted();
      if (rsGroupId == 1)
      {
        // RS has same group id as DS
        assertBlockedLongerThanTimeout(startTime, endTime, TIMEOUT);
        assertTrue(replicationServer.isScenarioExecuted());
        // Check monitoring values
        Thread.sleep(1000); // Sleep a while as counters are updated just after sending thread is unblocked
@@ -914,12 +941,11 @@
      }
      long endTime = System.currentTimeMillis();
      waitForScenarioExecutedOnRs(testcase, replicationServer);
      replicationServer.awaitScenarioExecuted();
      if (rsGroupId == 1)
      {
        assertBlockedLongerThanTimeout(startTime, endTime, TIMEOUT);
        assertTrue(replicationServer.isScenarioExecuted());
        // Check monitoring values
        Thread.sleep(1000); // Sleep a while as counters are updated just after sending thread is unblocked
@@ -972,7 +998,7 @@
          "objectClass: organizationalUnit");
      // Wait for entry received by RS
      waitForScenarioExecutedOnRs(testcase, replicationServer);
      replicationServer.awaitScenarioExecuted();
      // No more test to do here
    } finally
@@ -999,24 +1025,6 @@
    } while (!rs.isHandshakeOk());
  }
  /**
   * Wait for the scenario to be executed by the fake replication server or
   * times out with error after some seconds.
   */
  private void waitForScenarioExecutedOnRs(String testCase, FakeReplicationServer rs) throws Exception
  {
    int nsec = -1;
    do
    {
      nsec++;
      if (nsec == 10)
      {
        fail(testCase + ": timeout waiting for scenario to be exectued on fake RS after " + nsec + " seconds.");
      }
      Thread.sleep(1000);
    } while (!rs.isScenarioExecuted());
  }
  private void endTest(String testcase) throws Exception
  {
    debugInfo("Ending test " + testcase);
@@ -1056,8 +1064,7 @@
          "objectClass: top",
          "objectClass: organizationalUnit");
      assertBlockedForLessThanTimeout(startTime, TIMEOUT);
      assertTrue(replicationServer.isScenarioExecuted());
      replicationServer.assertAddWaitedForAck(startTime, TIMEOUT);
      // Check monitoring values
      Thread.sleep(1000); // Sleep a while as counters are updated just after sending thread is unblocked
@@ -1100,8 +1107,7 @@
          "objectClass: top",
          "objectClass: organizationalUnit");
      assertBlockedForLessThanTimeout(startTime, TIMEOUT);
      assertTrue(replicationServer.isScenarioExecuted());
      replicationServer.assertAddWaitedForAck(startTime, TIMEOUT);
      // Check monitoring values
      Thread.sleep(1000); // Sleep a while as counters are updated just after sending thread is unblocked
@@ -1138,50 +1144,36 @@
      // Wait for connection of domain to RS
      waitForConnectionToRs(testcase, replicationServer);
      /* Send an update from the RS and get the ack */
      // Make the RS send an assured add message
      Entry entry = makeEntry(
          "dn: ou=assured-sr-reply-entry," + SAFE_READ_DN,
          "dn: ou=assured-sr-reply-entry-" + rsGroupId + "," + SAFE_READ_DN,
          "objectClass: top",
          "objectClass: organizationalUnit");
      String parentUid = getEntryUUID(DN.valueOf(SAFE_READ_DN));
      try {
        AckMsg ackMsg = replicationServer.sendAssuredAddMsg(entry, parentUid);
        if (rsGroupId == 2)
        {
          fail("Should only go here for RS with same group id as DS");
        }
        // Ack received, replay has occurred
        assertNotNull(DirectoryServer.getEntry(entry.getName()));
        // Check that DS replied an ack without errors anyway
        assertFalse(ackMsg.hasTimeout());
        assertFalse(ackMsg.hasReplayError());
        assertFalse(ackMsg.hasWrongStatus());
        assertEquals(ackMsg.getFailedServers().size(), 0);
        // Check for monitoring data
        DN baseDN = DN.valueOf(SAFE_READ_DN);
        new MonitorAssertions(baseDN)
          .assertValue("assured-sr-received-updates", 1)
          .assertValue("assured-sr-received-updates-acked", 1)
          .assertRemainingValuesAreZero();
        assertNoServerErrors(baseDN);
      }
      catch (SocketTimeoutException e)
      if (rsGroupId == 2)
      {
        // Expected
        if (rsGroupId == 1)
        {
          fail("Should only go here for RS with group id different from DS one");
        }
        replicationServer.assertNoAckForAssuredAdd(entry, parentUid);
        return;
      }
      AckMsg ackMsg = replicationServer.sendAssuredAddMsg(entry, parentUid);
      // Ack received, replay has occurred
      assertNotNull(DirectoryServer.getEntry(entry.getName()));
      // Check that DS replied an ack without errors
      assertFalse(ackMsg.hasTimeout());
      assertFalse(ackMsg.hasReplayError());
      assertFalse(ackMsg.hasWrongStatus());
      assertEquals(ackMsg.getFailedServers().size(), 0);
      // Check for monitoring data
      DN baseDN = DN.valueOf(SAFE_READ_DN);
      new MonitorAssertions(baseDN)
        .assertValue("assured-sr-received-updates", 1)
        .assertValue("assured-sr-received-updates-acked", 1)
        .assertRemainingValuesAreZero();
      assertNoServerErrors(baseDN);
    } finally
    {
      endTest(testcase);
@@ -1275,7 +1267,7 @@
  /**
   * Tests that a DS receiving an update from a RS in safe data mode does not
   * send back and ack (only safe read is taken into account in DS replay).
   * send back an ack (only safe read is taken into account in DS replay).
   */
  @Test(dataProvider = "rsGroupIdProvider")
  public void testSafeDataModeReply(byte rsGroupId) throws Exception
@@ -1294,20 +1286,13 @@
      // Wait for connection of domain to RS
      waitForConnectionToRs(testcase, replicationServer);
      // Make the RS send an assured add message: we expect a read timeout as
      // safe data should be ignored by DS
      Entry entry = makeEntry(
          "dn: ou=assured-sd-reply-entry," + SAFE_DATA_DN,
          "dn: ou=assured-sd-reply-entry-" + rsGroupId + "," + SAFE_DATA_DN,
          "objectClass: top",
          "objectClass: organizationalUnit");
      String parentUid = getEntryUUID(DN.valueOf(SAFE_DATA_DN));
      AckMsg ackMsg = replicationServer.sendAssuredAddMsg(entry, parentUid);
      fail("DS should not reply an ack in safe data mode, however, it replied: " + ackMsg);
    }
    catch (SocketTimeoutException expected)
    {
      return;
      replicationServer.assertNoAckForAssuredAdd(entry, parentUid);
    }
    finally
    {
@@ -1383,7 +1368,7 @@
          "objectClass: organizationalUnit");
      assertBlockedLongerThanTimeout(startTime, System.currentTimeMillis(), TIMEOUT);
      assertTrue(replicationServer.isScenarioExecuted());
      replicationServer.awaitScenarioExecuted();
      // Check monitoring values
      // No ack should have comen back, so timeout incremented (flag and error for rs)
@@ -1498,7 +1483,7 @@
          "objectClass: organizationalUnit");
      assertBlockedLongerThanTimeout(startTime, System.currentTimeMillis(), TIMEOUT);
      assertTrue(replicationServer.isScenarioExecuted());
      replicationServer.awaitScenarioExecuted();
      // Check monitoring values
      // No ack should have comen back, so timeout incremented (flag and error for rs)
opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/HistoricalCsnOrderingTest.java
@@ -2557,6 +2557,7 @@
    final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
    TestCaseUtils.initializeTestBackend(true);
    ReplicationServer rs = createReplicationServer();
    ReplicationServer second = null;
    LDAPReplicationDomain rd1 = createReplicationDomain(serverId);
    try
    {
@@ -2567,19 +2568,31 @@
      waitUntilTheStateIsSaved(baseDN, rsMaxCSN);
      final List<Entry> backup = newArrayList(DirectoryServer.getEntry(baseDN).duplicate(false),
          DirectoryServer.getEntry(dnA).duplicate(false), DirectoryServer.getEntry(dnB).duplicate(false));
      // Only the second replication server receives the delete. The first stays at the backup.
      final int secondPort = TestCaseUtils.findFreePort();
      second = createIsolatedReplicationServer(secondPort, "HistoricalCsnOrderingSecond", SECOND_RS_ID);
      connectTo(rd1, towards(secondPort), SECOND_RS_ID);
      TestCaseUtils.deleteEntry(dnB);
      assertInTheChangelog(rs, baseDN, rd1.getLastLocalChange());
      assertInTheChangelog(second, baseDN, rd1.getLastLocalChange());
      // The data is restored while the domain is disabled, as it was before the delete.
      rd1.disable();
      restore(backup);
      assertEquals(rd1.applyConfigurationChange(domainConfiguration(serverId, replServers)).getResultCode(),
          ResultCode.SUCCESS);
      rd1.enable();
      assertEquals(rd1.getRsServerId(), FIRST_RS_ID);
      waitUntilTheRecoveryIsOver(rd1);
      assertNotNull(DirectoryServer.getEntry(dnB), "the entry is back");
      // A replication server which misses the changes after the backup: its recovery publishes the
      // change done since, and not the delete.
      replace(dnA, "description", "once the data was restored");
      final CSN afterTheRestore = rd1.getLastLocalChange();
      assertInTheChangelog(rs, baseDN, afterTheRestore);
      assertThat(changelogAfter(rs, baseDN, rsMaxCSN)).containsExactly(afterTheRestore);
      startRecovery(rd1);
      final List<ReplicationMsg> published = new ArrayList<>();
      assertTrue(rd1.buildAndPublishMissingChanges(rsMaxCSN, new TestBroker(published)));
@@ -2588,7 +2601,7 @@
    finally
    {
      MultimasterReplication.deleteDomain(baseDN);
      remove(rs);
      remove(rs, second);
    }
  }
opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/HistoricalTest.java
@@ -13,6 +13,7 @@
 *
 * Copyright 2008-2010 Sun Microsystems, Inc.
 * Portions Copyright 2011-2016 ForgeRock AS.
 * Portions Copyright 2026 3A Systems, LLC.
 */
package org.opends.server.replication.plugin;
@@ -50,6 +51,7 @@
import org.opends.server.types.Entry;
import org.opends.server.types.Modification;
import org.opends.server.types.Operation;
import org.opends.server.types.SearchResultEntry;
import org.opends.server.util.TestTimer;
import org.opends.server.util.TestTimer.CallableVoid;
import org.testng.annotations.BeforeClass;
@@ -480,11 +482,8 @@
  /**
   * Test the task that purges the replication historical stored in the user
   * entry.
   * Steps :
   * - creates entry containing historical
   * - wait for the purge delay
   * - launch the purge task
   * - verify that all historical has been purged
   * Replay changes older than the configured purge delay, then verify
   * that the scheduled task purges their history in one run.
   *
   * TODO: another test should be written that configures the task no NOT have
   * the time to purge everything in 1 run .. and thus to relaunch it to finish
@@ -494,22 +493,17 @@
  @Test(enabled=true)
  public void testRecurringPurgeIn1Run() throws Exception
  {
    TestCaseUtils.initializeTestBackend(true);
    int entryCount = 10;
    addEntriesWithHistorical(1, entryCount);
    addEntriesWithHistorical(entryCount);
    // set the purge delay to 1 minute
    // FIXME could we change this setting to also accept seconds?
    // This way this test would not take one minute to run
    // (and it could also fail less often in jenkins).
    // Make the stored history eligible for the purge task.
    TestCaseUtils.dsconfig(
        "set-replication-domain-prop",
        "--provider-name","Multimaster Synchronization",
        "--domain-name", testName,
        "--set","conflicts-historical-purge-delay:1m");
    // Let's go past the purge delay
    Thread.sleep(90 * 1000);
    // launch the purge
    final int maxWaitTimeInSeconds = 120;
    Entry purgeConflictsHistoricalTask = TestCaseUtils.makeEntry(
@@ -527,89 +521,66 @@
    waitForSearchResult(TEST_ROOT_DN_STRING, WHOLE_SUBTREE, "(ds-sync-hist=*)", SUCCESS, expectedNumberOfEntries);
  }
  /**
   * Add a provided number of generated entries containing historical.
   * @param dnSuffix A suffix to be added to the dn
   * @param entryCnt The number of entries to create
   */
  private void addEntriesWithHistorical(final int dnSuffix, final int entryCnt) throws Exception
  private void addEntriesWithHistorical(int entryCount) throws Exception
  {
    for (int i=0; i<entryCnt;i++)
    {
      String sdn =  "dn: uid=user"+i+dnSuffix+"," + TEST_ROOT_DN_STRING;
    DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING);
    String parentUUID = LDAPReplicationDomain.findEntryUUID(baseDN);
    int serverId = 5;
    long changeTime = System.currentTimeMillis() - MINUTES.toMillis(2);
    List<Modification> modifications = newArrayList(
        new Modification(ModificationType.ADD, Attributes.create("cn;lang-en", "Aaccf Amar", "Aaccf A Amar")),
        new Modification(ModificationType.REPLACE, Attributes.create("givenName", "new given")),
        new Modification(ModificationType.REPLACE, Attributes.create("userPassword", "{CLEAR}new pass")),
        new Modification(ModificationType.REPLACE, Attributes.create("description", "replaced description")),
        new Modification(ModificationType.REPLACE, Attributes.create("sn", "replaced sn")),
        new Modification(ModificationType.REPLACE, Attributes.create("displayName", "2")));
        //  Add a test entry.
        TestCaseUtils.addEntry(
            sdn,
    // Replay the aged changes while the domain still has its default retention.
    ReplicationBroker broker = openReplicationSession(baseDN, serverId, 100, replServerPort, 3000);
    try
    {
      int sequence = 0;
      for (int i = 0; i < entryCount; i++)
      {
        String uid = "purge-user-" + i;
        String entryUUID = UUID.randomUUID().toString();
        Entry entry = TestCaseUtils.makeEntry(
            "dn: uid=" + uid + "," + TEST_ROOT_DN_STRING,
            "objectClass: top",
            "objectClass: person",
            "objectClass: organizationalPerson",
            "objectClass: inetOrgPerson",
            "uid: user"+i,
            "uid: " + uid,
            "cn: Aaccf Amar",
            "sn: Amar",
            "givenName: Aaccf",
            "userPassword: password",
            "userPassword: {CLEAR}password",
            "description: Initial description",
            "displayName: 1"
        );
            "displayName: 1",
            "entryUUID: " + entryUUID);
      // Modify the test entry to give it some history.
      // Test both single and multi-valued attributes.
        CSN addCSN = new CSN(changeTime, sequence++, serverId);
        broker.publish(new AddMsg(addCSN, entry.getName(), entryUUID, parentUUID,
            entry.getObjectClasses(), entry.getUserAttributes(), entry.getOperationalAttributes()));
      }
      String path = TestCaseUtils.createTempFile(
          sdn,
          "changetype: modify",
          "add: cn;lang-en",
          "cn;lang-en: Aaccf Amar",
          "cn;lang-en: Aaccf A Amar",
          "-",
          "replace: givenName",
          "givenName: new given",
          "-",
          "replace: userPassword",
          "userPassword: new pass",
          "-",
          "replace: description",
          "description: replaced description",
          "-",
          "replace: sn",
          "sn: replaced sn",
          "-",
          "add: displayName",
          "displayName: 2",
          "-",
          "delete: displayName",
          "displayName: 1",
          "-"
      );
      String[] args =
      for (SearchResultEntry entry : waitForSearchResult(TEST_ROOT_DN_STRING, WHOLE_SUBTREE,
          "(&(ds-sync-hist=*)(displayName=1))", SUCCESS, entryCount).getSearchEntries())
      {
          "-h", "127.0.0.1",
          "-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
          "-D", "cn=Directory Manager",
          "-w", "password",
          "-f", path
      };
        CSN modifyCSN = new CSN(changeTime, sequence++, serverId);
        broker.publish(new ModifyMsg(modifyCSN, entry.getName(), modifications, EntryHistorical.getEntryUUID(entry)));
      }
      ldapmodify(args);
      args[9] = TestCaseUtils.createTempFile(
          sdn,
          "changetype: modify",
          "replace: displayName",
          "displayName: 2",
          "-"
      );
      ldapmodify(args);
      for (SearchResultEntry entry : waitForSearchResult(TEST_ROOT_DN_STRING, WHOLE_SUBTREE,
          "(&(ds-sync-hist=*)(displayName=2))", SUCCESS, entryCount).getSearchEntries())
      {
        Attribute history = EntryHistorical.getHistoricalAttr(entry).iterator().next();
        assertTrue(history.size() > 1, "Expected add and modify history for " + entry.getName());
      }
    }
    for (int i = 0; i < entryCnt; i++)
    finally
    {
      DN dn = DN.valueOf("uid=user" + i + dnSuffix + "," + TEST_ROOT_DN_STRING);
      getEntry(dn, 1000, true);
      broker.stop();
    }
  }
opendj-server-legacy/src/test/java/org/opends/server/replication/server/AssuredReplicationServerTest.java
@@ -136,6 +136,8 @@
   * (without errors).
   */
  private static final int MAX_SEND_UPDATE_TIME = 2000;
  /** Read deadline for the fake sender when no ack is expected, including time for an assured timeout ack. */
  private static final int NO_ACK_READ_TIMEOUT = 5000;
  /** Default group id. */
  private static final int DEFAULT_GID = 1;
@@ -794,8 +796,13 @@
     * Make the RS send an assured message and return the ack message it
     * receives from the RS.
     */
    public AckMsg sendNewFakeUpdate() throws Exception
    public AckMsg sendNewFakeUpdate(boolean expectAck) throws Exception
    {
        if (!expectAck)
        {
          session.setSoTimeout(NO_ACK_READ_TIMEOUT);
        }
        // Create a new delete update message (the simplest to create)
        DeleteMsg delMsg = new DeleteMsg(baseDN, gen.newCSN(),
        UUID.randomUUID().toString());
@@ -2206,12 +2213,14 @@
       * Send an assured update using configured assured parameters
       */
      boolean expectAck = sdLevel > 1 && fakeRsGid == DEFAULT_GID
          && fakeRsGenId == DEFAULT_GENID && sendInAssured;
      long startTime = System.currentTimeMillis();
      AckMsg ackMsg = null;
      boolean timeout = false;
      try
      {
        ackMsg = fakeRs1.sendNewFakeUpdate();
        ackMsg = fakeRs1.sendNewFakeUpdate(expectAck);
      } catch (SocketTimeoutException e)
      {
        debugInfo("testSafeDataFromRS: timeout waiting for update ack");
@@ -2223,8 +2232,7 @@
      /*
       * Now check timeout or not according to test configuration parameters
       */
      if (sdLevel == 1 || fakeRsGid != DEFAULT_GID
          || fakeRsGenId != DEFAULT_GENID || !sendInAssured )
      if (!expectAck)
      {
        // Should have timed out (no ack)
        assertTrue(timeout);
opendj-server-legacy/src/test/java/org/opends/server/replication/server/changelog/file/BlockLogReaderWriterTest.java
@@ -12,6 +12,7 @@
 * information: "Portions Copyright [year] [name of copyright owner]".
 *
 * Copyright 2014-2016 ForgeRock AS.
 * Portions Copyright 2026 3A Systems, LLC.
 */
package org.opends.server.replication.server.changelog.file;
@@ -49,7 +50,7 @@
@SuppressWarnings("javadoc")
public class BlockLogReaderWriterTest extends DirectoryServerTestCase
{
  private static final File TEST_DIRECTORY = new File(TestCaseUtils.getUnitTestRootPath(), "changelog-unit");
  private static final File TEST_DIRECTORY = new File(TestCaseUtils.getUnitTestRootPath(), "changelog-block-reader-writer");
  private static final File TEST_FILE = new File(TEST_DIRECTORY, "file");
  private static final RecordParser<Integer, Integer> RECORD_PARSER = new IntRecordParser();
  private static final int INT_RECORD_SIZE = 12;
opendj-server-legacy/src/test/java/org/opends/server/replication/server/changelog/file/LogFileTest.java
@@ -46,7 +46,7 @@
@Test(sequential=true)
public class LogFileTest extends DirectoryServerTestCase
{
  private static final File TEST_DIRECTORY = new File(TestCaseUtils.getUnitTestRootPath(), "changelog-unit");
  private static final File TEST_DIRECTORY = new File(TestCaseUtils.getUnitTestRootPath(), "changelog-log-file");
  private static final File TEST_LOG_FILE = new File(TEST_DIRECTORY, Log.HEAD_LOG_FILE_NAME);
  static final StringRecordParser RECORD_PARSER = new StringRecordParser();
  private static final byte STRING_SEPARATOR = 0;
opendj-server-legacy/src/test/java/org/opends/server/replication/server/changelog/file/LogTest.java
@@ -45,7 +45,7 @@
public class LogTest extends DirectoryServerTestCase
{
  /** Use a directory dedicated to this test class. */
  private static final File LOG_DIRECTORY = new File(TestCaseUtils.getUnitTestRootPath(), "changelog-unit");
  private static final File LOG_DIRECTORY = new File(TestCaseUtils.getUnitTestRootPath(), "changelog-log");
  private static final long NO_TIME_BASED_LOG_ROTATION = 0;
opendj-server-legacy/src/test/java/org/opends/server/util/TestStaticUtils.java
@@ -748,12 +748,9 @@
  @Test
  public void testRenameFileNonExistentTarget() throws Exception {
    File src = File.createTempFile("src", null);
    File target = new File(src.getParentFile(), "target");
    File target = File.createTempFile("target", null);
    try {
      if (target.exists()) {
        target.delete();
        assertFalse(target.exists());
      }
      assertTrue(target.delete());
      StaticUtils.renameFile(src, target);
      assertFalse(src.exists());
      assertTrue(target.exists());
@@ -1077,24 +1074,16 @@
  @Test
  public void testIsSelfConnectionTrueForSelfConnectedSocket() throws Exception
  {
    // find a free port
    final int port;
    try (ServerSocket tmp = new ServerSocket())
    {
      tmp.bind(new InetSocketAddress("127.0.0.1", 0));
      port = tmp.getLocalPort();
    }
    // Force the TCP self-connect (simultaneous open) that the kernel can
    // produce spontaneously when connecting to an unbound port from the
    // ephemeral range: bind the local end to the very port being connected.
    try (Socket socket = new Socket())
    {
      socket.setReuseAddress(true);
      socket.bind(new InetSocketAddress("127.0.0.1", port));
      socket.bind(new InetSocketAddress("127.0.0.1", 0));
      try
      {
        socket.connect(new InetSocketAddress("127.0.0.1", port), 2000);
        socket.connect(socket.getLocalSocketAddress(), 2000);
      }
      catch (IOException e)
      {