Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.opensearch.action.ActionRequest;
import org.opensearch.action.admin.cluster.node.tasks.cancel.CancelTasksRequest;
import org.opensearch.action.support.ActionFilters;
import org.opensearch.action.support.ContextPreservingActionListener;
import org.opensearch.action.support.HandledTransportAction;
Expand All @@ -31,6 +32,7 @@
import org.opensearch.common.inject.ModulesBuilder;
import org.opensearch.common.util.concurrent.ThreadContext;
import org.opensearch.core.action.ActionListener;
import org.opensearch.core.tasks.TaskId;
import org.opensearch.sql.common.response.ResponseListener;
import org.opensearch.sql.common.setting.Settings;
import org.opensearch.sql.common.utils.QueryContext;
Expand Down Expand Up @@ -95,6 +97,7 @@ public class TransportPPLQueryAction
extends HandledTransportAction<ActionRequest, TransportPPLQueryResponse> {

private static final Logger LOG = LogManager.getLogger(TransportPPLQueryAction.class);
private static final String ASYNC_CANCEL_REASON = "async PPL query cancelled";

private final Injector injector;

Expand Down Expand Up @@ -363,7 +366,7 @@ private void submitAsync(
if (!(task instanceof CancellableTask cancellableTask)) {
throw new IllegalArgumentException("Async PPL queries require a cancellable task");
}
Runnable cancelExecution = () -> cancellableTask.cancel("async PPL query cancelled");
Runnable cancelExecution = () -> cancelWithSearches(cancellableTask);
QueryProgressTracker progressTracker = QueryProgressTracker.attach(cancellableTask);
QueryRunner runner =
new PPLQueryRunner(
Expand Down Expand Up @@ -429,6 +432,36 @@ private void submitAsync(
});
}

/**
* Cancels the query and the searches it started (#6004). Marking the task stops the query from
* starting another search, but not one already running, such as an aggregation. The submit's
* transport task completed when the submit returned, so the task manager no longer tracks it and
* cannot cancel its children: they are cancelled by their parent task id instead.
*/
private void cancelWithSearches(CancellableTask task) {
task.cancel(ASYNC_CANCEL_REASON);
CancelTasksRequest request = new CancelTasksRequest();
// Selects the tasks whose parent is this one, as `_tasks/_cancel?parent_task_id=` does.
request.setParentTaskId(new TaskId(clientRef.getLocalNodeId(), task.getId()));
request.setReason(ASYNC_CANCEL_REASON);
// An internal call: the user may delete their own job without holding cluster task permissions.
try (ThreadContext.StoredContext ignored =
clientRef.threadPool().getThreadContext().stashContext()) {
clientRef
.admin()
.cluster()
.cancelTasks(
request,
ActionListener.wrap(
response -> {},
e ->
LOG.warn(
"Failed to cancel the searches of async PPL task {}", task.getId(), e)));
} catch (RuntimeException e) {
LOG.warn("Failed to cancel the searches of async PPL task {}", task.getId(), e);
}
}

private static void respondRunning(
org.opensearch.sql.job.QueryResult.Running running,
ActionListener<TransportPPLQueryResponse> listener) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,14 @@
package org.opensearch.sql.plugin.transport;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.CALLS_REAL_METHODS;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
Expand All @@ -26,6 +29,7 @@
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.opensearch.action.admin.cluster.node.tasks.cancel.CancelTasksRequest;
import org.opensearch.common.settings.Settings;
import org.opensearch.common.util.concurrent.ThreadContext;
import org.opensearch.core.action.ActionListener;
Expand All @@ -41,6 +45,8 @@
import org.opensearch.tasks.CancellableTask;
import org.opensearch.tasks.Task;
import org.opensearch.threadpool.ThreadPool;
import org.opensearch.transport.client.AdminClient;
import org.opensearch.transport.client.ClusterAdminClient;
import org.opensearch.transport.client.node.NodeClient;

/**
Expand All @@ -52,6 +58,7 @@ public class TransportPPLQueryActionCancellationTest {
private final PPLService pplService = mock(PPLService.class);
private final NodeClient client = mock(NodeClient.class);
private final SecurityAdapter security = mock(SecurityAdapter.class);
private final ClusterAdminClient cluster = mock(ClusterAdminClient.class);
private final ThreadContext threadContext = new ThreadContext(Settings.EMPTY);

@SuppressWarnings("unchecked")
Expand All @@ -69,6 +76,10 @@ public void setUp() throws Exception {
ThreadPool pool = mock(ThreadPool.class);
when(client.threadPool()).thenReturn(pool);
when(pool.getThreadContext()).thenReturn(threadContext);
AdminClient admin = mock(AdminClient.class);
when(client.admin()).thenReturn(admin);
when(admin.cluster()).thenReturn(cluster);
when(client.getLocalNodeId()).thenReturn("owner-node");
when(pool.generic())
.thenReturn(
org.opensearch.common.util.concurrent.OpenSearchExecutors.newDirectExecutorService());
Expand Down Expand Up @@ -151,6 +162,68 @@ public void submittedRunnerCancelsTheOriginalPplTask() throws Exception {
verifyNoInteractions(pplService);
}

/**
* The submit's transport task has completed by the time a job is cancelled, so its searches are
* cancelled by their parent task id; marking the task alone left an aggregation running (#6004).
*/
@Test
public void cancelAlsoCancelsTheSearchesTheQueryStarted() throws Exception {
threadContext.putHeader("user", "alice");
doAnswer(
invocation -> {
// Sent as an internal call, not as the user who deleted the job.
assertNull(threadContext.getHeader("user"));
return null;
})
.when(cluster)
.cancelTasks(any(CancelTasksRequest.class), any());
PPLQueryTask task = submitRunning();

cancelRunner();

ArgumentCaptor<CancelTasksRequest> request = ArgumentCaptor.forClass(CancelTasksRequest.class);
verify(cluster).cancelTasks(request.capture(), any());
assertEquals(new TaskId("owner-node", task.getId()), request.getValue().getParentTaskId());
assertEquals("async PPL query cancelled", request.getValue().getReason());
assertTrue(task.isCancelled());
assertEquals("alice", threadContext.getHeader("user"));
}

@Test
public void cancelStillMarksTheTaskWhenCancellingItsSearchesFails() throws Exception {
doThrow(new IllegalStateException("node is closing"))
.when(cluster)
.cancelTasks(any(CancelTasksRequest.class), any());
PPLQueryTask task = submitRunning();

cancelRunner();

assertTrue(task.isCancelled());
assertEquals("async PPL query cancelled", task.getReasonCancelled());
}

private PPLQueryTask submitRunning() throws Exception {
PPLQueryTask task =
new TransportPPLQueryRequest("source=test", null, "/_plugins/_ppl")
.createTask(3, "transport", PPLQueryAction.NAME, TaskId.EMPTY_TASK_ID, Map.of());
when(security.current()).thenReturn(Principal.UNSECURED);
when(jobs.submit(any(), eq(Principal.UNSECURED), any(), any()))
.thenReturn(
CompletableFuture.completedFuture(
new QueryResult.Running(
new QueryJobId("owner-node", "query-context"),
org.opensearch.sql.job.QueryProgress.NONE,
java.util.Optional.empty())));
submit(task);
return task;
}

private void cancelRunner() {
ArgumentCaptor<QueryRunner> runner = ArgumentCaptor.forClass(QueryRunner.class);
verify(jobs).submit(runner.capture(), eq(Principal.UNSECURED), any(), any());
runner.getValue().cancel();
}

private void submit(Task task) throws Exception {
PPLQueryRequest request =
new PPLQueryRequest("source=test", new JSONObject(), "/_plugins/_ppl", "jdbc");
Expand Down
Loading