chenhao7253886 commented on a change in pull request #1527: Expose data pruned-filter-scan ability URL: https://github.com/apache/incubator-doris/pull/1527#discussion_r306275680
########## File path: fe/src/main/java/org/apache/doris/http/rest/RestQueryPlanAction.java ########## @@ -0,0 +1,310 @@ +// 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.http.rest; + +import com.google.common.base.Strings; +import io.netty.handler.codec.http.HttpMethod; +import io.netty.handler.codec.http.HttpResponseStatus; +import org.apache.doris.analysis.SelectStmt; +import org.apache.doris.analysis.StatementBase; +import org.apache.doris.analysis.TableName; +import org.apache.doris.analysis.TableRef; +import org.apache.doris.catalog.Catalog; +import org.apache.doris.catalog.Database; +import org.apache.doris.catalog.Table; +import org.apache.doris.cluster.ClusterNamespace; +import org.apache.doris.common.DdlException; +import org.apache.doris.common.DorisHttpException; +import org.apache.doris.http.ActionController; +import org.apache.doris.http.BaseRequest; +import org.apache.doris.http.BaseResponse; +import org.apache.doris.http.IllegalArgException; +import org.apache.doris.mysql.privilege.PrivPredicate; +import org.apache.doris.planner.PlanFragment; +import org.apache.doris.planner.Planner; +import org.apache.doris.planner.ScanNode; +import org.apache.doris.qe.ConnectContext; +import org.apache.doris.qe.StmtExecutor; +import org.apache.doris.thrift.TDataSink; +import org.apache.doris.thrift.TDataSinkType; +import org.apache.doris.thrift.TMemoryScratchSink; +import org.apache.doris.thrift.TNetworkAddress; +import org.apache.doris.thrift.TPaloScanRange; +import org.apache.doris.thrift.TPlanFragment; +import org.apache.doris.thrift.TQueryOptions; +import org.apache.doris.thrift.TQueryPlanInfo; +import org.apache.doris.thrift.TScanRangeLocations; +import org.apache.doris.thrift.TTabletVersionInfo; +import org.apache.doris.thrift.TUniqueId; +import org.apache.thrift.TException; +import org.apache.thrift.TSerializer; +import org.codehaus.jackson.map.ObjectMapper; +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.Base64; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** + * This class responsible for parse the sql and generate the query plan fragment for a (only one) table{@see OlapTable} + * the related tablet maybe pruned by query planer according the `where` predicate. + */ +public class RestQueryPlanAction extends RestBaseAction { + + public RestQueryPlanAction(ActionController controller) { + super(controller); + } + + public static void registerAction(ActionController controller) throws IllegalArgException { + controller.registerHandler(HttpMethod.POST, + "/api/{cluster}/{database}/{table}/_query_plan", new RestQueryPlanAction(controller)); + controller.registerHandler(HttpMethod.GET, + "/api/{cluster}/{database}/{table}/_query_plan", new RestQueryPlanAction(controller)); + } + + @Override + protected void executeWithoutPassword(ActionAuthorizationInfo authInfo, BaseRequest request, BaseResponse response) throws DdlException { + // just allocate 2 slot for top holder map + Map<String, Object> resultMap = new HashMap<>(4); + String clusterName = request.getSingleParameter("cluster"); + String dbName = request.getSingleParameter("database"); + String tableName = request.getSingleParameter("table"); + String postContent = request.getContent(); + try { + // may be these common validate logic should be moved to one base class + if (Strings.isNullOrEmpty(clusterName) + || Strings.isNullOrEmpty(dbName) + || Strings.isNullOrEmpty(tableName)) { + throw new DorisHttpException(HttpResponseStatus.BAD_REQUEST, "{cluster}/{database}/{table} must be selected"); + } + String sql; + if (Strings.isNullOrEmpty(postContent)) { + throw new DorisHttpException(HttpResponseStatus.BAD_REQUEST, "POST body must contains [sql] root object"); + } else { + JSONObject jsonObject; + try { + jsonObject = new JSONObject(postContent); + } catch (JSONException e) { + throw new DorisHttpException(HttpResponseStatus.BAD_REQUEST, "malformed json [ " + postContent + " ]"); + } + sql = String.valueOf(jsonObject.opt("sql")); + if (Strings.isNullOrEmpty(sql)) { + throw new DorisHttpException(HttpResponseStatus.BAD_REQUEST, "POST body must contains [sql] root object"); + } + } + String fullDbName = ClusterNamespace.getFullName(authInfo.cluster, dbName); + // check privilege for select, otherwise return HTTP 401 + checkTblAuth(authInfo, fullDbName, tableName, PrivPredicate.SELECT); + Database db = Catalog.getCurrentCatalog().getDb(fullDbName); + if (db == null) { + throw new DorisHttpException(HttpResponseStatus.NOT_FOUND, "Database [" + dbName + "] " + "does not exists"); + } else { + // may be should acquire writeLock + db.readLock(); + try { + Table table = db.getTable(tableName); + if (table == null) { + throw new DorisHttpException(HttpResponseStatus.NOT_FOUND, "Table [" + tableName + "] " + "does not exists"); + } else { + // just only support OlapTable, ignore others such as ESTable, KuduTable + if (table.getType() != Table.TableType.OLAP) { + // Forbidden + throw new DorisHttpException(HttpResponseStatus.FORBIDDEN, "only support OlapTable currently, but Table [" + tableName + "] " + + "is not a OlapTable"); + } else { + // construct ConnectContext for analyzer + ConnectContext context = new ConnectContext(null); + context.setCatalog(Catalog.getCurrentCatalog()); + context.setCluster(clusterName); + context.setQualifiedUser(authInfo.fullUserName); + context.setRemoteIP(authInfo.remoteIp); + context.setThreadLocalInfo(); + // parse/analysis/plan the sql and acquire tablet distributions + handleQuery(context, fullDbName, tableName, sql, resultMap); + } + } + } finally { + db.readUnlock(); + } + } + + } catch (DorisHttpException e) { + // status code should conforms to HTTP semantic + resultMap.put("status", e.getCode().code()); + resultMap.put("exception", e.getMessage()); + } + ObjectMapper mapper = new ObjectMapper(); + try { + String result = mapper.writeValueAsString(resultMap); + // send result with extra information + response.setContentType("application/json"); + response.getContent().append(result); + sendResult(request, response, HttpResponseStatus.valueOf(Integer.parseInt(String.valueOf(resultMap.get("status"))))); + } catch (Exception e) { + // may be this never happen + response.getContent().append(e.getMessage()); + sendResult(request, response, HttpResponseStatus.INTERNAL_SERVER_ERROR); + } + } + + + /** + * process the sql syntax and return the resolved pruned tablet + * + * @param context context for analyzer + * @param sql the single table select statement + * @param result the acquired results + * @return + * @throws DorisHttpException + */ + private void handleQuery(ConnectContext context, String requestDb, String requestTable, String sql, Map<String, Object> result) throws DorisHttpException { + // use SE to resolve sql + StmtExecutor stmtExecutor = new StmtExecutor(context, sql, false); + try { + TQueryOptions tQueryOptions = context.getSessionVariable().toThrift(); + // Conduct Planner create SingleNodePlan#createPlanFragments + tQueryOptions.num_nodes = 1; + // analyze sql + stmtExecutor.analyze(tQueryOptions); + } catch (Exception e) { + throw new DorisHttpException(HttpResponseStatus.BAD_REQUEST, e.getMessage()); + } + // the parsed logical statement + StatementBase query = stmtExecutor.getParsedStmt(); + // only process select semantic + if (!(query instanceof SelectStmt)) { + throw new DorisHttpException(HttpResponseStatus.BAD_REQUEST, "Select statement needed, but found [" + sql + " ]"); + } + SelectStmt stmt = (SelectStmt) query; + // just only process sql like `select * from table where <predicate>`, only support executing scan semantic + if (stmt.hasAggInfo() || stmt.hasGroupByClause() || stmt.hasAnalyticInfo() + || stmt.hasOrderByClause() || stmt.hasOffset() || stmt.hasLimit() || stmt.isExplain()) { + throw new DorisHttpException(HttpResponseStatus.BAD_REQUEST, "only support single table filter-prune-scan, but found [ " + sql + "]"); + } + // process only one table by one http query + List<TableRef> fromTables = stmt.getTableRefs(); + if (fromTables.size() != 1) { Review comment: Forbid From-subquery (instanceof InlineViewRef) ---------------------------------------------------------------- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: [email protected] With regards, Apache Git Services --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
