Search in sources :

Example 1 with AbstractRunnable

use of org.opensearch.common.util.concurrent.AbstractRunnable in project OpenSearch by opensearch-project.

the class GatewayService method performStateRecovery.

private void performStateRecovery(final boolean enforceRecoverAfterTime, final String reason) {
    if (enforceRecoverAfterTime && recoverAfterTime != null) {
        if (scheduledRecovery.compareAndSet(false, true)) {
            logger.info("delaying initial state recovery for [{}]. {}", recoverAfterTime, reason);
            threadPool.schedule(new AbstractRunnable() {

                @Override
                public void onFailure(Exception e) {
                    logger.warn("delayed state recovery failed", e);
                    resetRecoveredFlags();
                }

                @Override
                protected void doRun() {
                    if (recoveryInProgress.compareAndSet(false, true)) {
                        logger.info("recover_after_time [{}] elapsed. performing state recovery...", recoverAfterTime);
                        recoveryRunnable.run();
                    }
                }
            }, recoverAfterTime, ThreadPool.Names.GENERIC);
        }
    } else {
        if (recoveryInProgress.compareAndSet(false, true)) {
            threadPool.generic().execute(new AbstractRunnable() {

                @Override
                public void onFailure(final Exception e) {
                    logger.warn("state recovery failed", e);
                    resetRecoveredFlags();
                }

                @Override
                protected void doRun() {
                    logger.debug("performing state recovery...");
                    recoveryRunnable.run();
                }
            });
        }
    }
}
Also used : AbstractRunnable(org.opensearch.common.util.concurrent.AbstractRunnable)

Example 2 with AbstractRunnable

use of org.opensearch.common.util.concurrent.AbstractRunnable in project OpenSearch by opensearch-project.

the class PeerFinder method handleWakeUp.

/**
 * @return whether any peers were removed due to disconnection
 */
private boolean handleWakeUp() {
    assert holdsLock() : "PeerFinder mutex not held";
    final boolean peersRemoved = peersByAddress.values().removeIf(Peer::handleWakeUp);
    if (active == false) {
        logger.trace("not active");
        return peersRemoved;
    }
    logger.trace("probing master nodes from cluster state: {}", lastAcceptedNodes);
    for (ObjectCursor<DiscoveryNode> discoveryNodeObjectCursor : lastAcceptedNodes.getMasterNodes().values()) {
        startProbe(discoveryNodeObjectCursor.value.getAddress());
    }
    configuredHostsResolver.resolveConfiguredHosts(providedAddresses -> {
        synchronized (mutex) {
            lastResolvedAddresses = providedAddresses;
            logger.trace("probing resolved transport addresses {}", providedAddresses);
            providedAddresses.forEach(this::startProbe);
        }
    });
    transportService.getThreadPool().scheduleUnlessShuttingDown(findPeersInterval, Names.GENERIC, new AbstractRunnable() {

        @Override
        public boolean isForceExecution() {
            return true;
        }

        @Override
        public void onFailure(Exception e) {
            assert false : e;
            logger.debug("unexpected exception in wakeup", e);
        }

        @Override
        protected void doRun() {
            synchronized (mutex) {
                if (handleWakeUp() == false) {
                    return;
                }
            }
            onFoundPeersUpdated();
        }

        @Override
        public String toString() {
            return "PeerFinder handling wakeup";
        }
    });
    return peersRemoved;
}
Also used : AbstractRunnable(org.opensearch.common.util.concurrent.AbstractRunnable) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) IOException(java.io.IOException) TransportException(org.opensearch.transport.TransportException)

Example 3 with AbstractRunnable

use of org.opensearch.common.util.concurrent.AbstractRunnable in project OpenSearch by opensearch-project.

the class AzureBlobStore method deleteBlobDirectory.

public DeleteResult deleteBlobDirectory(String path, Executor executor) throws URISyntaxException, BlobStorageException, IOException {
    final Tuple<BlobServiceClient, Supplier<Context>> client = client();
    final BlobContainerClient blobContainer = client.v1().getBlobContainerClient(container);
    final Collection<Exception> exceptions = Collections.synchronizedList(new ArrayList<>());
    final AtomicLong outstanding = new AtomicLong(1L);
    final PlainActionFuture<Void> result = PlainActionFuture.newFuture();
    final AtomicLong blobsDeleted = new AtomicLong();
    final AtomicLong bytesDeleted = new AtomicLong();
    final ListBlobsOptions listBlobsOptions = new ListBlobsOptions().setPrefix(path);
    SocketAccess.doPrivilegedVoidException(() -> {
        String continuationToken = null;
        do {
            // Fetch one page at a time, others are going to be fetched by continuation token
            // TODO: reconsider reverting to simplified approach once https://github.com/Azure/azure-sdk-for-java/issues/26064
            // gets addressed.
            final Optional<PagedResponse<BlobItem>> pageOpt = blobContainer.listBlobs(listBlobsOptions, timeout()).streamByPage(continuationToken).findFirst();
            if (!pageOpt.isPresent()) {
                // No more pages, should never happen
                break;
            }
            final PagedResponse<BlobItem> page = pageOpt.get();
            for (final BlobItem blobItem : page.getValue()) {
                // Skipping prefixes as those are not deletable and should not be there
                assert (blobItem.isPrefix() == null || !blobItem.isPrefix()) : "Only blobs (not prefixes) are expected";
                outstanding.incrementAndGet();
                executor.execute(new AbstractRunnable() {

                    @Override
                    protected void doRun() throws Exception {
                        final long len = blobItem.getProperties().getContentLength();
                        final BlobClient azureBlob = blobContainer.getBlobClient(blobItem.getName());
                        logger.trace(() -> new ParameterizedMessage("container [{}]: blob [{}] found. removing.", container, blobItem.getName()));
                        final Response<Void> response = azureBlob.deleteWithResponse(null, null, timeout(), client.v2().get());
                        logger.trace(() -> new ParameterizedMessage("container [{}]: blob [{}] deleted status [{}].", container, blobItem.getName(), response.getStatusCode()));
                        blobsDeleted.incrementAndGet();
                        if (len >= 0) {
                            bytesDeleted.addAndGet(len);
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        exceptions.add(e);
                    }

                    @Override
                    public void onAfter() {
                        if (outstanding.decrementAndGet() == 0) {
                            result.onResponse(null);
                        }
                    }
                });
            }
            // Fetch next continuation token
            continuationToken = page.getContinuationToken();
        } while (StringUtils.isNotBlank(continuationToken));
    });
    if (outstanding.decrementAndGet() == 0) {
        result.onResponse(null);
    }
    result.actionGet();
    if (exceptions.isEmpty() == false) {
        final IOException ex = new IOException("Deleting directory [" + path + "] failed");
        exceptions.forEach(ex::addSuppressed);
        throw ex;
    }
    return new DeleteResult(blobsDeleted.get(), bytesDeleted.get());
}
Also used : AbstractRunnable(org.opensearch.common.util.concurrent.AbstractRunnable) ListBlobsOptions(com.azure.storage.blob.models.ListBlobsOptions) BlobClient(com.azure.storage.blob.BlobClient) IOException(java.io.IOException) BlobStorageException(com.azure.storage.blob.models.BlobStorageException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) BlobItem(com.azure.storage.blob.models.BlobItem) HttpResponse(com.azure.core.http.HttpResponse) PagedResponse(com.azure.core.http.rest.PagedResponse) Response(com.azure.core.http.rest.Response) BlobContainerClient(com.azure.storage.blob.BlobContainerClient) AtomicLong(java.util.concurrent.atomic.AtomicLong) BlobServiceClient(com.azure.storage.blob.BlobServiceClient) Supplier(java.util.function.Supplier) PagedResponse(com.azure.core.http.rest.PagedResponse) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) DeleteResult(org.opensearch.common.blobstore.DeleteResult)

Example 4 with AbstractRunnable

use of org.opensearch.common.util.concurrent.AbstractRunnable in project OpenSearch by opensearch-project.

the class TransportGetTaskAction method getRunningTaskFromNode.

/**
 * Executed on the node that should be running the task to find and return the running task. Falls back to
 * {@link #getFinishedTaskFromIndex(Task, GetTaskRequest, ActionListener)} if the task isn't still running.
 */
void getRunningTaskFromNode(Task thisTask, GetTaskRequest request, ActionListener<GetTaskResponse> listener) {
    Task runningTask = taskManager.getTask(request.getTaskId().getId());
    if (runningTask == null) {
        // Task isn't running, go look in the task index
        getFinishedTaskFromIndex(thisTask, request, listener);
    } else {
        if (request.getWaitForCompletion()) {
            // Shift to the generic thread pool and let it wait for the task to complete so we don't block any important threads.
            threadPool.generic().execute(new AbstractRunnable() {

                @Override
                protected void doRun() {
                    taskManager.waitForTaskCompletion(runningTask, waitForCompletionTimeout(request.getTimeout()));
                    waitedForCompletion(thisTask, request, runningTask.taskInfo(clusterService.localNode().getId(), true), listener);
                }

                @Override
                public void onFailure(Exception e) {
                    listener.onFailure(e);
                }
            });
        } else {
            TaskInfo info = runningTask.taskInfo(clusterService.localNode().getId(), true);
            listener.onResponse(new GetTaskResponse(new TaskResult(false, info)));
        }
    }
}
Also used : AbstractRunnable(org.opensearch.common.util.concurrent.AbstractRunnable) TaskInfo(org.opensearch.tasks.TaskInfo) Task(org.opensearch.tasks.Task) TaskResult(org.opensearch.tasks.TaskResult) OpenSearchException(org.opensearch.OpenSearchException) ResourceNotFoundException(org.opensearch.ResourceNotFoundException) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) IOException(java.io.IOException)

Example 5 with AbstractRunnable

use of org.opensearch.common.util.concurrent.AbstractRunnable in project OpenSearch by opensearch-project.

the class AbstractAsyncBulkByScrollAction method onScrollResponse.

/**
 * Process a scroll response.
 * @param lastBatchStartTimeNS the time when the last batch started. Used to calculate the throttling delay.
 * @param lastBatchSize the size of the last batch. Used to calculate the throttling delay.
 * @param asyncResponse the response to process from ScrollableHitSource
 */
void onScrollResponse(long lastBatchStartTimeNS, int lastBatchSize, ScrollableHitSource.AsyncResponse asyncResponse) {
    ScrollableHitSource.Response response = asyncResponse.response();
    logger.debug("[{}]: got scroll response with [{}] hits", task.getId(), response.getHits().size());
    if (task.isCancelled()) {
        logger.debug("[{}]: finishing early because the task was cancelled", task.getId());
        finishHim(null);
        return;
    }
    if (// If any of the shards failed that should abort the request.
    (response.getFailures().size() > 0) || // Timeouts aren't shard failures but we still need to pass them back to the user.
    response.isTimedOut()) {
        refreshAndFinish(emptyList(), response.getFailures(), response.isTimedOut());
        return;
    }
    long total = response.getTotalHits();
    if (mainRequest.getMaxDocs() > 0) {
        total = min(total, mainRequest.getMaxDocs());
    }
    worker.setTotal(total);
    AbstractRunnable prepareBulkRequestRunnable = new AbstractRunnable() {

        @Override
        protected void doRun() throws Exception {
            /*
                 * It is important that the batch start time be calculated from here, scroll response to scroll response. That way the time
                 * waiting on the scroll doesn't count against this batch in the throttle.
                 */
            prepareBulkRequest(System.nanoTime(), asyncResponse);
        }

        @Override
        public void onFailure(Exception e) {
            finishHim(e);
        }
    };
    prepareBulkRequestRunnable = (AbstractRunnable) threadPool.getThreadContext().preserveContext(prepareBulkRequestRunnable);
    worker.delayPrepareBulkRequest(threadPool, lastBatchStartTimeNS, lastBatchSize, prepareBulkRequestRunnable);
}
Also used : AbstractRunnable(org.opensearch.common.util.concurrent.AbstractRunnable)

Aggregations

AbstractRunnable (org.opensearch.common.util.concurrent.AbstractRunnable)42 IOException (java.io.IOException)29 OpenSearchException (org.opensearch.OpenSearchException)14 ParameterizedMessage (org.apache.logging.log4j.message.ParameterizedMessage)12 AlreadyClosedException (org.apache.lucene.store.AlreadyClosedException)11 BrokenBarrierException (java.util.concurrent.BrokenBarrierException)10 CountDownLatch (java.util.concurrent.CountDownLatch)10 UncheckedIOException (java.io.UncheckedIOException)9 TimeValue (org.opensearch.common.unit.TimeValue)9 DiscoveryNode (org.opensearch.cluster.node.DiscoveryNode)8 UnknownHostException (java.net.UnknownHostException)7 AtomicReference (java.util.concurrent.atomic.AtomicReference)7 ExecutionException (java.util.concurrent.ExecutionException)6 ActionListener (org.opensearch.action.ActionListener)6 StreamInput (org.opensearch.common.io.stream.StreamInput)6 CyclicBarrier (java.util.concurrent.CyclicBarrier)5 OpenSearchRejectedExecutionException (org.opensearch.common.util.concurrent.OpenSearchRejectedExecutionException)5 IndexNotFoundException (org.opensearch.index.IndexNotFoundException)5 ThreadPool (org.opensearch.threadpool.ThreadPool)5 ArrayList (java.util.ArrayList)4