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
11 changes: 11 additions & 0 deletions fe/fe-core/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -958,6 +958,17 @@ under the License.
<artifactId>sdk-core</artifactId>
<version>${awssdk.version}</version>
</dependency>

<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<!-- for hive-catalog-shade -->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public enum ErrorCode {
ERR_DUP_FIELDNAME(1060, new byte[]{'4', '2', 'S', '2', '1'}, "Duplicate column name '%s'"),
ERR_NONUNIQ_TABLE(1066, new byte[]{'4', '2', '0', '0', '0'}, "Not unique table/alias: '%s'"),
ERR_NO_SUCH_THREAD(1094, new byte[]{'H', 'Y', '0', '0', '0'}, "Unknown thread id: %d"),
ERR_KILL_DENIED_ERROR(1095, new byte[]{'H', 'Y', '0', '0', '0'}, "You are not owner of thread %d"),
ERR_KILL_DENIED_ERROR(1095, new byte[] {'H', 'Y', '0', '0', '0'}, "You are not owner of thread or query: %d"),
ERR_NO_TABLES_USED(1096, new byte[]{'H', 'Y', '0', '0', '0'}, "No tables used"),
ERR_NO_SUCH_QUERY(1097, new byte[]{'H', 'Y', '0', '0', '0'}, "Unknown query id: %s"),
ERR_WRONG_DB_NAME(1102, new byte[]{'4', '2', '0', '0', '0'}, "Incorrect database name '%s'"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6271,14 +6271,15 @@ public LogicalPlan visitShowConvertLsc(ShowConvertLscContext ctx) {

@Override
public LogicalPlan visitKillQuery(KillQueryContext ctx) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

based on old planner, if specify QUERY KEYWORD, it always means to kill query, and the query id is whatever INTEGER_VALUE or STRING_LITERAL. Looks like the behavior is changed in this pr?

kill_stmt ::=
    KW_KILL INTEGER_LITERAL:value
    {:
        RESULT = new KillStmt(true, value.intValue());
    :}
    | KW_KILL KW_CONNECTION INTEGER_LITERAL:value
    {:
        RESULT = new KillStmt(true, value.intValue());
    :}
    | KW_KILL KW_QUERY INTEGER_LITERAL:value
    {:
        RESULT = new KillStmt(false, value.intValue());
    :}
    | KW_KILL KW_QUERY STRING_LITERAL:value
    {:
        RESULT = new KillStmt(value);
    :}
    ;

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, there are 2 ways to kill query:

  1. Kill query by query id: KILL QUERY "query_id";
  2. Kill query by connection id: KILL QUERY connection_id, where connection_id is an integer, not a string.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, there are 2 ways to kill query:

  1. Kill query by query id: KILL QUERY "query_id";
  2. Kill query by connection id: KILL QUERY connection_id, where connection_id is an integer, not a string.

the grammer is very weird. KILL QUERY but need a params of connection_id. could lead to misunderstand for people not read doc very carefully.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, there are 2 ways to kill query:

  1. Kill query by query id: KILL QUERY "query_id";
  2. Kill query by connection id: KILL QUERY connection_id, where connection_id is an integer, not a string.

the grammer is very weird. KILL QUERY but need a params of connection_id. could lead to misunderstand for people not read doc very carefully.

This is compatible with MySQL Kill Statement

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, there are 2 ways to kill query:

  1. Kill query by query id: KILL QUERY "query_id";
  2. Kill query by connection id: KILL QUERY connection_id, where connection_id is an integer, not a string.

the grammer is very weird. KILL QUERY but need a params of connection_id. could lead to misunderstand for people not read doc very carefully.

like describe on #50916, mysql-client use 'kill query connection_id' to make ctrl+c work, so we need support it to make mysql-client work well

String queryId;
String queryId = null;
int connectionId = -1;
TerminalNode integerValue = ctx.INTEGER_VALUE();
if (integerValue != null) {
queryId = integerValue.getText();
connectionId = Integer.valueOf(integerValue.getText());
} else {
queryId = stripQuotes(ctx.STRING_LITERAL().getText());
}
return new KillQueryCommand(queryId);
return new KillQueryCommand(queryId, connectionId);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,9 @@
package org.apache.doris.nereids.trees.plans.commands;

import org.apache.doris.analysis.RedirectStatus;
import org.apache.doris.catalog.Env;
import org.apache.doris.common.ErrorCode;
import org.apache.doris.common.ErrorReport;
import org.apache.doris.mysql.privilege.PrivPredicate;
import org.apache.doris.nereids.exceptions.AnalysisException;
import org.apache.doris.nereids.trees.plans.PlanType;
import org.apache.doris.nereids.trees.plans.commands.utils.KillUtils;
import org.apache.doris.nereids.trees.plans.visitor.PlanVisitor;
import org.apache.doris.qe.ConnectContext;
import org.apache.doris.qe.StmtExecutor;
Expand All @@ -44,25 +42,10 @@ public KillConnectionCommand(Integer connectionId) {

@Override
public void doRun(ConnectContext ctx, StmtExecutor executor) throws Exception {
ConnectContext killCtx = ctx.getConnectScheduler().getContext(connectionId);
if (killCtx == null) {
ErrorReport.reportDdlException(ErrorCode.ERR_NO_SUCH_THREAD, id);
if (connectionId < 0) {
throw new AnalysisException("Please specify connection id which >= 0 to kill");
}

if (ctx == killCtx) {
// Suicide
ctx.setKilled();
} else {
// Check auth
// Only user itself and user with admin priv can kill connection
if (!killCtx.getQualifiedUser().equals(ConnectContext.get().getQualifiedUser())
&& !Env.getCurrentEnv().getAccessManager().checkGlobalPriv(ConnectContext.get(),
PrivPredicate.ADMIN)) {
ErrorReport.reportDdlException(ErrorCode.ERR_KILL_DENIED_ERROR, id);
}
killCtx.kill(true);
}
ctx.getState().setOk();
KillUtils.kill(ctx, true, null, connectionId, null);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,81 +18,38 @@
package org.apache.doris.nereids.trees.plans.commands;

import org.apache.doris.analysis.RedirectStatus;
import org.apache.doris.catalog.Env;
import org.apache.doris.common.ErrorCode;
import org.apache.doris.common.ErrorReport;
import org.apache.doris.common.Status;
import org.apache.doris.common.UserException;
import org.apache.doris.common.util.DebugUtil;
import org.apache.doris.mysql.privilege.PrivPredicate;
import org.apache.doris.nereids.exceptions.AnalysisException;
import org.apache.doris.nereids.trees.plans.PlanType;
import org.apache.doris.nereids.trees.plans.commands.utils.KillUtils;
import org.apache.doris.nereids.trees.plans.visitor.PlanVisitor;
import org.apache.doris.qe.ConnectContext;
import org.apache.doris.qe.StmtExecutor;
import org.apache.doris.rpc.BackendServiceProxy;
import org.apache.doris.system.Backend;
import org.apache.doris.thrift.TStatusCode;
import org.apache.doris.thrift.TUniqueId;

import com.google.common.base.Strings;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Collection;
/**
* kill query command
*/

public class KillQueryCommand extends KillCommand {
private static final Logger LOG = LogManager.getLogger(KillQueryCommand.class);
private final String queryId;
private final int connectionId;

public KillQueryCommand(String queryId) {
public KillQueryCommand(String queryId, int connectionId) {
super(PlanType.KILL_QUERY_COMMAND);
this.queryId = queryId;
this.connectionId = connectionId;
}

@Override
public void doRun(ConnectContext ctx, StmtExecutor executor) throws Exception {
ConnectContext killCtx = ctx.getConnectScheduler().getContextWithQueryId(queryId);
// when killCtx == null, this means the query not in FE,
// then we just send kill signal to BE
if (killCtx == null) {
TUniqueId tQueryId = null;
try {
tQueryId = DebugUtil.parseTUniqueIdFromString(queryId);
} catch (NumberFormatException e) {
throw new UserException(e.getMessage());
}

LOG.info("kill query {}", queryId);
Collection<Backend> nodesToPublish = Env.getCurrentSystemInfo()
.getAllBackendsByAllCluster().values();
for (Backend be : nodesToPublish) {
if (be.isAlive()) {
try {
Status cancelReason = new Status(TStatusCode.CANCELLED, "user kill query");
BackendServiceProxy.getInstance()
.cancelPipelineXPlanFragmentAsync(be.getBrpcAddress(), tQueryId,
cancelReason);
} catch (Throwable t) {
LOG.info("send kill query {} rpc to be {} failed", queryId, be);
}
}
}
} else if (ctx == killCtx) {
// Suicide
ctx.setKilled();
} else {
// Check auth
// Only user itself and user with admin priv can kill connection
if (!killCtx.getQualifiedUser().equals(ConnectContext.get().getQualifiedUser())
&& !Env.getCurrentEnv().getAccessManager().checkGlobalPriv(ConnectContext.get(),
PrivPredicate.ADMIN)) {
ErrorReport.reportDdlException(ErrorCode.ERR_KILL_DENIED_ERROR, id);
}
killCtx.kill(false);
if (Strings.isNullOrEmpty(queryId) && connectionId < 0) {
throw new AnalysisException(
"Please specify a non empty query id or connection id which >= 0 to kill");
}
ctx.getState().setOk();
KillUtils.kill(ctx, false, queryId, connectionId, executor.getOriginStmt());
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

package org.apache.doris.nereids.trees.plans.commands.utils;

import org.apache.doris.catalog.Env;
import org.apache.doris.common.DdlException;
import org.apache.doris.common.ErrorCode;
import org.apache.doris.common.ErrorReport;
import org.apache.doris.common.UserException;
import org.apache.doris.mysql.privilege.PrivPredicate;
import org.apache.doris.qe.ConnectContext;
import org.apache.doris.qe.FEOpExecutor;
import org.apache.doris.qe.OriginStatement;
import org.apache.doris.service.ExecuteEnv;
import org.apache.doris.system.Frontend;
import org.apache.doris.thrift.TNetworkAddress;
import org.apache.doris.thrift.TStatusCode;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.List;

/**
* Utility class for killing queries and connections.
*/
public class KillUtils {
private static final Logger LOG = LogManager.getLogger(KillUtils.class);

/**
* Kill a query by query id or connection id.
*
* @param ctx the current connect context
* @param killConnection true if kill connection, false if only kill query
* @param queryId the query id to kill
* @param connectionId the connection id to kill
* @param stmt the origin kill statement, which may need to be forwarded to other FE
*/
public static void kill(ConnectContext ctx, boolean killConnection, String queryId, int connectionId,
OriginStatement stmt) throws UserException {
if (killConnection) {
// kill connection connection_id
// kill connection_id
Preconditions.checkState(connectionId >= 0, connectionId);
killByConnectionId(ctx, true, connectionId);
} else {
if (!Strings.isNullOrEmpty(queryId)) {
// kill query "query_id"
killQueryByQueryId(ctx, queryId, stmt);
} else {
// kill query connection_id
Preconditions.checkState(connectionId >= 0, connectionId);
killByConnectionId(ctx, false, connectionId);
}
}
}

/**
* Kill a query by query id.
*
* @param ctx the current connect context
* @param queryId the query id to kill
* @param stmt the origin kill statement, which may need to be forwarded to other FE
*/
@VisibleForTesting
public static void killQueryByQueryId(ConnectContext ctx, String queryId, OriginStatement stmt)
throws UserException {
// 1. First, try to find the query in the current FE and kill it
if (killByQueryIdOnCurrentNode(ctx, queryId)) {
return;
}

if (ctx.isProxy()) {
// The query is not found in the current FE, and the command is forwarded from other FE.
// return error to let the proxy FE to handle it.
if (LOG.isDebugEnabled()) {
LOG.debug("kill query '{}' in proxy mode but not found", queryId);
}
ErrorReport.reportDdlException(ErrorCode.ERR_NO_SUCH_QUERY, queryId);
}

// 2. Query not found in current FE, try to kill the query in other FE.
List<String> errMsgs = Lists.newArrayList();
for (Frontend fe : Env.getCurrentEnv().getFrontends(null /* all */)) {
if (!fe.isAlive() || fe.getHost().equals(Env.getCurrentEnv().getSelfNode().getHost())) {
continue;
}

TNetworkAddress feAddr = new TNetworkAddress(fe.getHost(), fe.getRpcPort());
FEOpExecutor executor = new FEOpExecutor(feAddr, stmt, ConnectContext.get(), false);
if (LOG.isDebugEnabled()) {
LOG.debug("try kill query '{}' to FE: {}", queryId, feAddr.toString());
}
try {
executor.execute();
} catch (Exception e) {
throw new DdlException(e.getMessage(), e);
}
if (executor.getStatusCode() != TStatusCode.OK.getValue()) {
// The query is not found in this FE, continue to find in other FEs
// and save error msg
errMsgs.add(String.format("failed to apply to fe %s:%s, error message: %s",
fe.getHost(), fe.getRpcPort(), executor.getErrMsg()));
} else {
// Find query in other FE, just return
ctx.getState().setOk();
return;
}
}

// 3. Query not found in any FE, try cancel the query in BE.
if (LOG.isDebugEnabled()) {
LOG.debug("not found query '{}' in any FE, try to kill it in BE. Messages: {}",
queryId, errMsgs);
}
ErrorReport.reportDdlException(ErrorCode.ERR_NO_SUCH_QUERY, queryId);
}

/**
* Kill a query by query id on the current FE.
*
* @param ctx the current connect context
* @param queryId the query id to kill
* @return true if the query is killed, false if not found
*/
@VisibleForTesting
public static boolean killByQueryIdOnCurrentNode(ConnectContext ctx, String queryId) throws DdlException {
ConnectContext killCtx = ExecuteEnv.getInstance().getScheduler().getContextWithQueryId(queryId);
if (LOG.isDebugEnabled()) {
LOG.debug("kill query '{}' on current node", queryId);
}
if (killCtx != null) {
// Check auth. Only user itself and user with admin priv can kill connection
if (!killCtx.getQualifiedUser().equals(ctx.getQualifiedUser())
&& !Env.getCurrentEnv().getAccessManager().checkGlobalPriv(ctx, PrivPredicate.ADMIN)) {
ErrorReport.reportDdlException(ErrorCode.ERR_KILL_DENIED_ERROR, queryId);
}
killCtx.kill(false);
ctx.getState().setOk();
return true;
}
return false;
}

/**
* Kill a connection by connection id.
*
* @param ctx the current connect context
* @param connectionId the connection id to kill
*/
@VisibleForTesting
public static void killByConnectionId(ConnectContext ctx, boolean killConnection, int connectionId)
throws DdlException {
ConnectContext killCtx = ctx.getConnectScheduler().getContext(connectionId);
if (killCtx == null) {
ErrorReport.reportDdlException(ErrorCode.ERR_NO_SUCH_THREAD, connectionId);
}
if (ctx == killCtx) {
// Suicide
ctx.setKilled();
} else {
// Check auth
// Only user itself and user with admin priv can kill connection
if (!killCtx.getQualifiedUser().equals(ctx.getQualifiedUser())
&& !Env.getCurrentEnv().getAccessManager().checkGlobalPriv(ctx, PrivPredicate.ADMIN)) {
ErrorReport.reportDdlException(ErrorCode.ERR_KILL_DENIED_ERROR, connectionId);
}
killCtx.kill(killConnection);
}
ctx.getState().setOk();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ public ConnectContext getContext(int connectionId) {

public ConnectContext getContextWithQueryId(String queryId) {
for (ConnectContext context : connectionMap.values()) {
if (queryId.equals(DebugUtil.printId(context.queryId))) {
if (queryId.equals(DebugUtil.printId(context.queryId)) || queryId.equals(context.traceId())) {
return context;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4404,6 +4404,7 @@ public void setForwardedSessionVariables(TQueryOptions queryOptions) {
/**
* The sessionContext is as follows:
* "k1:v1;k2:v2;..."
* eg: set session_context="trace_id:123456"
* Here we want to get value with key named "trace_id",
* Return empty string is not found.
*
Expand Down
Loading
Loading