| | |
| | | import java.nio.channels.SocketChannel; |
| | | import java.security.cert.Certificate; |
| | | import java.util.ArrayDeque; |
| | | import java.util.ArrayList; |
| | | import java.util.Collection; |
| | | import java.util.Iterator; |
| | | import java.util.List; |
| | | import java.util.Map; |
| | | import java.util.Set; |
| | | import java.util.concurrent.ArrayBlockingQueue; |
| | | import java.util.concurrent.ConcurrentHashMap; |
| | | import java.util.concurrent.Future; |
| | | import java.util.concurrent.RejectedExecutionException; |
| | | import java.util.concurrent.ThreadPoolExecutor; |
| | | import java.util.concurrent.TimeUnit; |
| | | import java.util.concurrent.atomic.AtomicInteger; |
| | | import java.util.concurrent.atomic.AtomicLong; |
| | |
| | | import org.forgerock.opendj.ldap.spi.LdapMessages.LdapRequestEnvelope; |
| | | import org.opends.server.api.ClientConnection; |
| | | import org.opends.server.api.ConnectionHandler; |
| | | import org.opends.server.api.DirectoryThread; |
| | | import org.opends.server.core.AbandonOperationBasis; |
| | | import org.opends.server.core.AddOperationBasis; |
| | | import org.opends.server.core.BindOperationBasis; |
| | |
| | | import com.forgerock.reactive.ReactiveHandler; |
| | | import com.forgerock.reactive.Stream; |
| | | |
| | | import io.reactivex.rxjava3.core.Completable; |
| | | import io.reactivex.rxjava3.exceptions.Exceptions; |
| | | import io.reactivex.rxjava3.subjects.CompletableSubject; |
| | | |
| | | /** |
| | | * This class defines an LDAP client connection, which is a type of client connection that will be accepted by an |
| | |
| | | public final class LDAPClientConnection2 extends ClientConnection implements TLSCapableConnection, |
| | | ReactiveHandler<QueueingStrategy, LdapRequestEnvelope, Stream<Response>> { |
| | | private static final String REACTIVE_OUT = "reactive.out"; |
| | | private static final CancelRequest CANCEL_OPERATIONS_FOR_BIND = |
| | | new CancelRequest(true, INFO_CANCELED_BY_BIND_REQUEST.get()); |
| | | |
| | | /** Submit deferred Binds without making the Search writer wait for work-queue capacity. */ |
| | | private static final ThreadPoolExecutor DEFERRED_BIND_SUBMISSIONS = new ThreadPoolExecutor( |
| | | 0, 1, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<>(32), task -> { |
| | | final Thread worker = new DirectoryThread(task, "LDAP deferred Bind submission"); |
| | | worker.setDaemon(true); |
| | | return worker; |
| | | }); |
| | | |
| | | /** The tracer object for the debug logger. */ |
| | | private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass(); |
| | |
| | | /** The set of all operations currently in progress on this connection. */ |
| | | private final ConcurrentHashMap<Integer, Operation> operationsInProgress; |
| | | |
| | | /** Search responses can still be in flight after the operation leaves the work queue. */ |
| | | private final Set<BlockingBackpressureSubscription> searchResponses = ConcurrentHashMap.newKeySet(); |
| | | |
| | | /** |
| | | * The number of operations performed on this connection. Used to compare with the resource limits of the network |
| | | * group. |
| | |
| | | // A persistent search is the other way around: its search operation is no longer in |
| | | // progress once the search phase is over, and yet it still owes the client a response if |
| | | // the server terminates it. |
| | | if (removeOperationInProgress(operation.getMessageID()) |
| | | if (removeOperationInProgress(operation) |
| | | || hasPersistentSearch(operation.getMessageID())) { |
| | | getAttachedResponses(operation).complete(operationToResponse(operation)); |
| | | } |
| | |
| | | } catch (DirectoryException de) { |
| | | logger.traceException(de); |
| | | |
| | | operationsInProgress.remove(messageID); |
| | | operationsInProgress.remove(messageID, operation); |
| | | lastCompletionTime.set(TimeThread.getTime()); |
| | | |
| | | throw de; |
| | |
| | | */ |
| | | @Override |
| | | public boolean removeOperationInProgress(int messageID) { |
| | | Operation operation = operationsInProgress.remove(messageID); |
| | | return operationRemoved(operationsInProgress.remove(messageID)); |
| | | } |
| | | |
| | | @Override |
| | | public boolean removeOperationInProgress(Operation operation) { |
| | | return operationsInProgress.remove(operation.getMessageID(), operation) && operationRemoved(operation); |
| | | } |
| | | |
| | | private boolean operationRemoved(Operation operation) { |
| | | if (operation == null) { |
| | | return false; |
| | | } |
| | |
| | | operationsInProgress.remove(msgID); |
| | | lastCompletionTime.set(TimeThread.getTime()); |
| | | } |
| | | |
| | | for (PersistentSearch persistentSearch : getPersistentSearches()) { |
| | | if (persistentSearch.getMessageID() == messageID) { |
| | | continue; |
| | | } |
| | | |
| | | persistentSearch.cancel(); |
| | | lastCompletionTime.set(TimeThread.getTime()); |
| | | } |
| | | } catch (Exception e) { |
| | | logger.traceException(e); |
| | | } |
| | | } |
| | | // A persistent search can be publishing to the transport while it is being cancelled. |
| | | for (PersistentSearch persistentSearch : getPersistentSearches()) { |
| | | if (persistentSearch.getMessageID() != messageID) { |
| | | persistentSearch.cancel(); |
| | | lastCompletionTime.set(TimeThread.getTime()); |
| | | } |
| | | } |
| | | } |
| | | |
| | | @Override |
| | |
| | | cancelFirstRequestTimer(); |
| | | } |
| | | final Publisher<Response> responses = subscriber -> { |
| | | final boolean search = message.getMessageType() == OP_TYPE_SEARCH_REQUEST; |
| | | final BlockingBackpressureSubscription out = |
| | | new BlockingBackpressureSubscription(connectionHandler.getMaxBlockedWriteTimeLimit(), subscriber); |
| | | new BlockingBackpressureSubscription(connectionHandler.getMaxBlockedWriteTimeLimit(), subscriber, |
| | | search); |
| | | if (search) { |
| | | searchResponses.add(out); |
| | | } |
| | | try { |
| | | subscriber.onSubscribe(out); |
| | | if (!out.cancelled) { |
| | |
| | | |
| | | // Add the operation into the work queue. |
| | | bindOp.setAttachment(REACTIVE_OUT, out); |
| | | try { |
| | | addOperationInProgress(queueingStrategy, bindOp); |
| | | } catch (DirectoryException de) { |
| | | logger.traceException(de); |
| | | |
| | | final Result result = Responses.newBindResult(de.getResultCode()); |
| | | setDetails(result, de, bindOp.getResponseControls()); |
| | | out.complete(result); |
| | | |
| | | // If it was a protocol error, then terminate the connection. |
| | | if (de.getResultCode() == ResultCode.PROTOCOL_ERROR) { |
| | | LocalizableMessage msg = ERR_LDAP_DISCONNECT_DUE_TO_BIND_PROTOCOL_ERROR.get(message.getMessageID(), |
| | | de.getMessageObject()); |
| | | disconnect(DisconnectReason.PROTOCOL_ERROR, true, msg); |
| | | } |
| | | final List<Completable> searchHandoffs = new ArrayList<>(); |
| | | for (BlockingBackpressureSubscription search : searchResponses) { |
| | | search.discardBufferedResponses(); |
| | | searchHandoffs.add(search.searchTerminated); |
| | | } |
| | | |
| | | if (searchHandoffs.isEmpty()) { |
| | | enqueueBind(queueingStrategy, bindOp, out, false); |
| | | } else { |
| | | // Keep request admission closed until the old Search responses have reached the transport. |
| | | Completable.merge(searchHandoffs).subscribe( |
| | | () -> submitDeferredBind(queueingStrategy, bindOp, out), out::terminate); |
| | | } |
| | | return connectionValid; |
| | | } |
| | | |
| | | private void submitDeferredBind(QueueingStrategy queueingStrategy, BindOperationBasis bind, |
| | | BlockingBackpressureSubscription out) { |
| | | try { |
| | | DEFERRED_BIND_SUBMISSIONS.execute(() -> enqueueBind(queueingStrategy::enqueueDeferredRequest, |
| | | bind, out, true)); |
| | | } catch (RejectedExecutionException e) { |
| | | // The connection cannot continue with Search responses already abandoned and cleanup unavailable. |
| | | final ClosedChannelException failure = new ClosedChannelException(); |
| | | failure.initCause(e); |
| | | out.terminate(failure); |
| | | } |
| | | } |
| | | |
| | | private void enqueueBind(QueueingStrategy queueingStrategy, BindOperationBasis bind, |
| | | BlockingBackpressureSubscription out, boolean discardedSearches) { |
| | | if (out.cancelled) { |
| | | return; |
| | | } |
| | | if (!connectionValid) { |
| | | out.complete(null); |
| | | return; |
| | | } |
| | | try { |
| | | addOperationInProgress(queueingStrategy, bind); |
| | | } catch (DirectoryException de) { |
| | | setUnauthenticated(); |
| | | setSASLAuthStateInfo(null); |
| | | if (discardedSearches && de.getResultCode() != ResultCode.PROTOCOL_ERROR) { |
| | | // The Bind did not reach a worker to cancel the operations whose responses were discarded. |
| | | cancelAllOperationsExcept(CANCEL_OPERATIONS_FOR_BIND, bind.getMessageID()); |
| | | } |
| | | rejectBind(bind, out, de); |
| | | } |
| | | } |
| | | |
| | | private void rejectBind(BindOperationBasis bind, BlockingBackpressureSubscription out, DirectoryException error) { |
| | | logger.traceException(error); |
| | | final Result result = Responses.newBindResult(error.getResultCode()); |
| | | setDetails(result, error, bind.getResponseControls()); |
| | | finishSaslBind(); |
| | | finishBind(); |
| | | out.complete(result); |
| | | |
| | | if (error.getResultCode() == ResultCode.PROTOCOL_ERROR) { |
| | | LocalizableMessage msg = ERR_LDAP_DISCONNECT_DUE_TO_BIND_PROTOCOL_ERROR.get(bind.getMessageID(), |
| | | error.getMessageObject()); |
| | | disconnect(DisconnectReason.PROTOCOL_ERROR, true, msg); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * Processes the provided LDAP message as a compare request. |
| | | * |
| | |
| | | * Queues responses before publishing them. A persistent search can receive changes from several workers at once. |
| | | * The bounded queue accepts concurrent producers, and only the drain calls the downstream subscriber. |
| | | */ |
| | | private static final class BlockingBackpressureSubscription implements Subscription { |
| | | private final class BlockingBackpressureSubscription implements Subscription { |
| | | private static final int QUEUE_CAPACITY = 32; |
| | | private final AtomicLong pendingRequests = new AtomicLong(); |
| | | private final AtomicInteger missedDrain = new AtomicInteger(); |
| | | private final ArrayDeque<Response> queue = new ArrayDeque<>(QUEUE_CAPACITY); |
| | | private final Subscriber<? super Response> downstream; |
| | | private final long writeTimeoutNanos; |
| | | private final CompletableSubject searchTerminated; |
| | | private volatile boolean done; |
| | | private Throwable error; |
| | | private volatile boolean cancelled; |
| | | |
| | | BlockingBackpressureSubscription(final long maxBlockedWriteTimeLimit, |
| | | final Subscriber<? super Response> downstream) { |
| | | final Subscriber<? super Response> downstream, boolean search) { |
| | | this.downstream = downstream; |
| | | searchTerminated = search ? CompletableSubject.create() : null; |
| | | // Do not wait indefinitely. |
| | | this.writeTimeoutNanos = TimeUnit.MILLISECONDS.toNanos( |
| | | maxBlockedWriteTimeLimit == 0 ? 30000 : maxBlockedWriteTimeLimit); |
| | |
| | | if (response == null) { |
| | | break; |
| | | } |
| | | downstream.onNext(response); |
| | | try { |
| | | downstream.onNext(response); |
| | | } catch (RuntimeException | Error e) { |
| | | finishSearch(e); |
| | | throw e; |
| | | } |
| | | emitted++; |
| | | } |
| | | |
| | | if (cancelled) { |
| | | finishSearch(null); |
| | | return; |
| | | } |
| | | if (done && isQueueEmpty()) { |
| | | if (error != null) { |
| | | downstream.onError(error); |
| | | } else { |
| | | downstream.onComplete(); |
| | | try { |
| | | if (error != null) { |
| | | downstream.onError(error); |
| | | } else { |
| | | downstream.onComplete(); |
| | | } |
| | | } finally { |
| | | finishSearch(error); |
| | | } |
| | | return; |
| | | } |
| | |
| | | } |
| | | } |
| | | |
| | | private void finishSearch(Throwable failure) { |
| | | if (searchTerminated != null) { |
| | | if (failure == null) { |
| | | searchTerminated.onComplete(); |
| | | } else { |
| | | searchTerminated.onError(failure); |
| | | } |
| | | searchResponses.remove(this); |
| | | } |
| | | } |
| | | |
| | | private void discardBufferedResponses() { |
| | | synchronized (queue) { |
| | | queue.clear(); |
| | | if (done) { |
| | | queue.notifyAll(); |
| | | } else { |
| | | finish(null); |
| | | } |
| | | } |
| | | drain(); |
| | | } |
| | | |
| | | private Response poll() { |
| | | synchronized (queue) { |
| | | final Response response = queue.pollFirst(); |
| | |
| | | queue.clear(); |
| | | queue.notifyAll(); |
| | | } |
| | | if (searchTerminated != null) { |
| | | drain(); |
| | | } |
| | | } |
| | | } |
| | | } |