|
| 1 | +/* |
| 2 | + * SPDX-License-Identifier: Apache-2.0 |
| 3 | + * |
| 4 | + * The OpenSearch Contributors require contributions made to |
| 5 | + * this file be licensed under the Apache-2.0 license or a |
| 6 | + * compatible open source license. |
| 7 | + */ |
| 8 | + |
| 9 | +package org.opensearch.action.support; |
| 10 | + |
| 11 | +import org.apache.logging.log4j.LogManager; |
| 12 | +import org.apache.logging.log4j.Logger; |
| 13 | +import org.apache.logging.log4j.message.ParameterizedMessage; |
| 14 | +import org.opensearch.action.ActionListener; |
| 15 | +import org.opensearch.action.admin.cluster.node.tasks.cancel.CancelTasksRequest; |
| 16 | +import org.opensearch.client.OriginSettingClient; |
| 17 | +import org.opensearch.client.node.NodeClient; |
| 18 | +import org.opensearch.common.unit.TimeValue; |
| 19 | +import org.opensearch.search.SearchService; |
| 20 | +import org.opensearch.tasks.CancellableTask; |
| 21 | +import org.opensearch.tasks.TaskId; |
| 22 | +import org.opensearch.threadpool.Scheduler; |
| 23 | +import org.opensearch.threadpool.ThreadPool; |
| 24 | + |
| 25 | +import java.util.concurrent.TimeUnit; |
| 26 | +import java.util.concurrent.atomic.AtomicBoolean; |
| 27 | + |
| 28 | +import static org.opensearch.action.admin.cluster.node.tasks.get.GetTaskAction.TASKS_ORIGIN; |
| 29 | + |
| 30 | +public class TimeoutTaskCancellationUtility { |
| 31 | + |
| 32 | + private static final Logger logger = LogManager.getLogger(TimeoutTaskCancellationUtility.class); |
| 33 | + |
| 34 | + /** |
| 35 | + * Wraps a listener with a timeout listener {@link TimeoutRunnableListener} to schedule the task cancellation for provided tasks on |
| 36 | + * generic thread pool |
| 37 | + * @param client - {@link NodeClient} |
| 38 | + * @param taskToCancel - task to schedule cancellation for |
| 39 | + * @param globalTimeout - global timeout to use for scheduling cancellation task in absence of task level parameter |
| 40 | + * @param listener - original listener associated with the task |
| 41 | + * @return wrapped listener |
| 42 | + */ |
| 43 | + public static <Response> ActionListener<Response> wrapWithCancellationListener(NodeClient client, CancellableTask taskToCancel, |
| 44 | + TimeValue globalTimeout, ActionListener<Response> listener) { |
| 45 | + final TimeValue timeoutInterval = (taskToCancel.getCancellationTimeout() == null) ? globalTimeout |
| 46 | + : taskToCancel.getCancellationTimeout(); |
| 47 | + // Note: If -1 (or no timeout) is set at request level then we will use that value instead of cluster level value. This will help |
| 48 | + // to turn off cancellation at request level. |
| 49 | + ActionListener<Response> listenerToReturn = listener; |
| 50 | + if (timeoutInterval.equals(SearchService.NO_TIMEOUT)) { |
| 51 | + return listenerToReturn; |
| 52 | + } |
| 53 | + |
| 54 | + try { |
| 55 | + final TimeoutRunnableListener<Response> wrappedListener = new TimeoutRunnableListener<>(timeoutInterval, listener, () -> { |
| 56 | + final CancelTasksRequest cancelTasksRequest = new CancelTasksRequest(); |
| 57 | + cancelTasksRequest.setTaskId(new TaskId(client.getLocalNodeId(), taskToCancel.getId())); |
| 58 | + cancelTasksRequest.setReason("Cancellation timeout of " + timeoutInterval + " is expired"); |
| 59 | + // force the origin to execute the cancellation as a system user |
| 60 | + new OriginSettingClient(client, TASKS_ORIGIN).admin().cluster() |
| 61 | + .cancelTasks(cancelTasksRequest, ActionListener.wrap(r -> logger.debug( |
| 62 | + "Scheduled cancel task with timeout: {} for original task: {} is successfully completed", timeoutInterval, |
| 63 | + cancelTasksRequest.getTaskId()), |
| 64 | + e -> logger.error(new ParameterizedMessage("Scheduled cancel task with timeout: {} for original task: {} is failed", |
| 65 | + timeoutInterval, cancelTasksRequest.getTaskId()), e)) |
| 66 | + ); |
| 67 | + }); |
| 68 | + wrappedListener.cancellable = client.threadPool().schedule(wrappedListener, timeoutInterval, ThreadPool.Names.GENERIC); |
| 69 | + listenerToReturn = wrappedListener; |
| 70 | + } catch (Exception ex) { |
| 71 | + // if there is any exception in scheduling the cancellation task then continue without it |
| 72 | + logger.warn("Failed to schedule the cancellation task for original task: {}, will continue without it", taskToCancel.getId()); |
| 73 | + } |
| 74 | + return listenerToReturn; |
| 75 | + } |
| 76 | + |
| 77 | + /** |
| 78 | + * Timeout listener which executes the provided runnable after timeout is expired and if a response/failure is not yet received. |
| 79 | + * If either a response/failure is received before timeout then the scheduled task is cancelled and response/failure is sent back to |
| 80 | + * the original listener. |
| 81 | + */ |
| 82 | + private static class TimeoutRunnableListener<Response> implements ActionListener<Response>, Runnable { |
| 83 | + |
| 84 | + private static final Logger logger = LogManager.getLogger(TimeoutRunnableListener.class); |
| 85 | + |
| 86 | + // Runnable to execute after timeout |
| 87 | + private final TimeValue timeout; |
| 88 | + private final ActionListener<Response> originalListener; |
| 89 | + private final Runnable timeoutRunnable; |
| 90 | + private final AtomicBoolean executeRunnable = new AtomicBoolean(true); |
| 91 | + private volatile Scheduler.ScheduledCancellable cancellable; |
| 92 | + private final long creationTime; |
| 93 | + |
| 94 | + TimeoutRunnableListener(TimeValue timeout, ActionListener<Response> listener, Runnable runAfterTimeout) { |
| 95 | + this.timeout = timeout; |
| 96 | + this.originalListener = listener; |
| 97 | + this.timeoutRunnable = runAfterTimeout; |
| 98 | + this.creationTime = System.nanoTime(); |
| 99 | + } |
| 100 | + |
| 101 | + @Override public void onResponse(Response response) { |
| 102 | + checkAndCancel(); |
| 103 | + originalListener.onResponse(response); |
| 104 | + } |
| 105 | + |
| 106 | + @Override public void onFailure(Exception e) { |
| 107 | + checkAndCancel(); |
| 108 | + originalListener.onFailure(e); |
| 109 | + } |
| 110 | + |
| 111 | + @Override public void run() { |
| 112 | + try { |
| 113 | + if (executeRunnable.compareAndSet(true, false)) { |
| 114 | + timeoutRunnable.run(); |
| 115 | + } // else do nothing since either response/failure is already sent to client |
| 116 | + } catch (Exception ex) { |
| 117 | + // ignore the exception |
| 118 | + logger.error(new ParameterizedMessage("Ignoring the failure to run the provided runnable after timeout of {} with " + |
| 119 | + "exception", timeout), ex); |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | + private void checkAndCancel() { |
| 124 | + if (executeRunnable.compareAndSet(true, false)) { |
| 125 | + logger.debug("Aborting the scheduled cancel task after {}", |
| 126 | + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - creationTime)); |
| 127 | + // timer has not yet expired so cancel it |
| 128 | + cancellable.cancel(); |
| 129 | + } |
| 130 | + } |
| 131 | + } |
| 132 | +} |
0 commit comments