Search in sources :

Example 1 with RoutingProvider

use of io.crate.metadata.RoutingProvider in project crate by crate.

the class PreExecutionBenchmark method measure_parse_analyze_and_plan_simple_select.

@Benchmark
public Plan measure_parse_analyze_and_plan_simple_select() throws Exception {
    String sql = "select name from users";
    CoordinatorTxnCtx systemTransactionContext = CoordinatorTxnCtx.systemTransactionContext();
    Analysis analysis = new Analysis(systemTransactionContext, ParamTypeHints.EMPTY);
    AnalyzedStatement analyzedStatement = analyzer.analyzedStatement(SqlParser.createStatement(sql), analysis);
    var jobId = UUID.randomUUID();
    var routingProvider = new RoutingProvider(Randomness.get().nextInt(), planner.getAwarenessAttributes());
    var clusterState = clusterService.state();
    var txnCtx = CoordinatorTxnCtx.systemTransactionContext();
    var plannerContext = new PlannerContext(clusterState, routingProvider, jobId, txnCtx, nodeCtx, 0, null);
    return planner.plan(analyzedStatement, plannerContext);
}
Also used : RoutingProvider(io.crate.metadata.RoutingProvider) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) PlannerContext(io.crate.planner.PlannerContext) Benchmark(org.openjdk.jmh.annotations.Benchmark)

Example 2 with RoutingProvider

use of io.crate.metadata.RoutingProvider in project crate by crate.

the class Session method singleExec.

@VisibleForTesting
CompletableFuture<?> singleExec(Portal portal, ResultReceiver<?> resultReceiver, int maxRows) {
    var activeConsumer = portal.activeConsumer();
    if (activeConsumer != null && activeConsumer.suspended()) {
        activeConsumer.replaceResultReceiver(resultReceiver, maxRows);
        activeConsumer.resume();
        return resultReceiver.completionFuture();
    }
    var jobId = UUIDs.dirtyUUID();
    var routingProvider = new RoutingProvider(Randomness.get().nextInt(), planner.getAwarenessAttributes());
    var clusterState = executor.clusterService().state();
    var txnCtx = new CoordinatorTxnCtx(sessionContext);
    var nodeCtx = executor.nodeContext();
    var params = new RowN(portal.params().toArray());
    var plannerContext = new PlannerContext(clusterState, routingProvider, jobId, txnCtx, nodeCtx, maxRows, params);
    var analyzedStmt = portal.analyzedStatement();
    String rawStatement = portal.preparedStmt().rawStatement();
    if (analyzedStmt == null) {
        String errorMsg = "Statement must have been analyzed: " + rawStatement;
        jobsLogs.logPreExecutionFailure(jobId, rawStatement, errorMsg, sessionContext.sessionUser());
        throw new IllegalStateException(errorMsg);
    }
    Plan plan;
    try {
        plan = planner.plan(analyzedStmt, plannerContext);
    } catch (Throwable t) {
        jobsLogs.logPreExecutionFailure(jobId, rawStatement, SQLExceptions.messageOf(t), sessionContext.sessionUser());
        throw t;
    }
    if (!analyzedStmt.isWriteOperation()) {
        resultReceiver = new RetryOnFailureResultReceiver(executor.clusterService(), clusterState, indexName -> executor.clusterService().state().metadata().hasIndex(indexName), resultReceiver, jobId, (newJobId, resultRec) -> retryQuery(newJobId, analyzedStmt, routingProvider, new RowConsumerToResultReceiver(resultRec, maxRows, new JobsLogsUpdateListener(newJobId, jobsLogs)), params, txnCtx, nodeCtx));
    }
    jobsLogs.logExecutionStart(jobId, rawStatement, sessionContext.sessionUser(), StatementClassifier.classify(plan));
    RowConsumerToResultReceiver consumer = new RowConsumerToResultReceiver(resultReceiver, maxRows, new JobsLogsUpdateListener(jobId, jobsLogs));
    portal.setActiveConsumer(consumer);
    plan.execute(executor, plannerContext, consumer, params, SubQueryResults.EMPTY);
    return resultReceiver.completionFuture();
}
Also used : ParamTypeHints(io.crate.analyze.ParamTypeHints) RetryOnFailureResultReceiver(io.crate.protocols.postgres.RetryOnFailureResultReceiver) Analyzer(io.crate.analyze.Analyzer) DependencyCarrier(io.crate.planner.DependencyCarrier) ClusterState(org.elasticsearch.cluster.ClusterState) Relations(io.crate.analyze.Relations) RowN(io.crate.data.RowN) TransactionState(io.crate.protocols.postgres.TransactionState) Map(java.util.Map) JobsLogsUpdateListener(io.crate.protocols.postgres.JobsLogsUpdateListener) TableInfo(io.crate.metadata.table.TableInfo) NodeContext(io.crate.metadata.NodeContext) AnalyzedStatement(io.crate.analyze.AnalyzedStatement) UUIDs(org.elasticsearch.common.UUIDs) UUID(java.util.UUID) Lists2(io.crate.common.collections.Lists2) List(java.util.List) Logger(org.apache.logging.log4j.Logger) AnalyzedDiscard(io.crate.analyze.AnalyzedDiscard) Row(io.crate.data.Row) Symbol(io.crate.expression.symbol.Symbol) AnalyzedBegin(io.crate.analyze.AnalyzedBegin) SubQueryResults(io.crate.planner.operators.SubQueryResults) Statement(io.crate.sql.tree.Statement) VisibleForTesting(io.crate.common.annotations.VisibleForTesting) Row1(io.crate.data.Row1) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) AnalyzedCommit(io.crate.analyze.AnalyzedCommit) AccessControl(io.crate.auth.AccessControl) QueriedSelectRelation(io.crate.analyze.QueriedSelectRelation) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Function(java.util.function.Function) JobsLogs(io.crate.execution.engine.collect.stats.JobsLogs) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) Portal(io.crate.protocols.postgres.Portal) Symbols(io.crate.expression.symbol.Symbols) FormatCodes(io.crate.protocols.postgres.FormatCodes) SqlParser(io.crate.sql.parser.SqlParser) Nullable(javax.annotation.Nullable) Iterator(java.util.Iterator) RelationInfo(io.crate.metadata.RelationInfo) Target(io.crate.sql.tree.DiscardStatement.Target) DataType(io.crate.types.DataType) Planner(io.crate.planner.Planner) RoutingProvider(io.crate.metadata.RoutingProvider) RowConsumer(io.crate.data.RowConsumer) StatementClassifier(io.crate.planner.operators.StatementClassifier) AbstractTableRelation(io.crate.analyze.relations.AbstractTableRelation) PlannerContext(io.crate.planner.PlannerContext) Plan(io.crate.planner.Plan) AnalyzedRelation(io.crate.analyze.relations.AnalyzedRelation) ReadOnlyException(io.crate.exceptions.ReadOnlyException) SQLExceptions(io.crate.exceptions.SQLExceptions) LogManager(org.apache.logging.log4j.LogManager) Randomness(org.elasticsearch.common.Randomness) AnalyzedDeallocate(io.crate.analyze.AnalyzedDeallocate) RoutingProvider(io.crate.metadata.RoutingProvider) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) Plan(io.crate.planner.Plan) RowN(io.crate.data.RowN) PlannerContext(io.crate.planner.PlannerContext) JobsLogsUpdateListener(io.crate.protocols.postgres.JobsLogsUpdateListener) RetryOnFailureResultReceiver(io.crate.protocols.postgres.RetryOnFailureResultReceiver) VisibleForTesting(io.crate.common.annotations.VisibleForTesting)

Example 3 with RoutingProvider

use of io.crate.metadata.RoutingProvider in project crate by crate.

the class SysShardsTableInfo method getRouting.

/**
 * Retrieves the routing for sys.shards
 * <p>
 * This routing contains ALL shards of ALL indices.
 * Any shards that are not yet assigned to a node will have a NEGATIVE shard id (see {@link UnassignedShard}
 */
public static Routing getRouting(ClusterState clusterState, RoutingProvider routingProvider, SessionContext sessionContext) {
    String[] concreteIndices = Arrays.stream(clusterState.metadata().getConcreteAllIndices()).filter(index -> !IndexParts.isDangling(index)).toArray(String[]::new);
    User user = sessionContext != null ? sessionContext.sessionUser() : null;
    if (user != null) {
        List<String> accessibleTables = new ArrayList<>(concreteIndices.length);
        for (String indexName : concreteIndices) {
            String tableName = RelationName.fqnFromIndexName(indexName);
            if (user.hasAnyPrivilege(Privilege.Clazz.TABLE, tableName)) {
                accessibleTables.add(indexName);
            }
        }
        concreteIndices = accessibleTables.toArray(new String[0]);
    }
    Map<String, Map<String, IntIndexedContainer>> locations = new TreeMap<>();
    GroupShardsIterator<ShardIterator> groupShardsIterator = clusterState.getRoutingTable().allAssignedShardsGrouped(concreteIndices, true);
    for (final ShardIterator shardIt : groupShardsIterator) {
        final ShardRouting shardRouting = shardIt.nextOrNull();
        processShardRouting(clusterState.getNodes().getLocalNodeId(), locations, shardRouting, shardIt.shardId());
    }
    return new Routing(locations);
}
Also used : ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) ShardId(org.elasticsearch.index.shard.ShardId) IndexParts(io.crate.metadata.IndexParts) Arrays(java.util.Arrays) LONG(io.crate.types.DataTypes.LONG) SessionContext(io.crate.action.sql.SessionContext) Privilege(io.crate.user.Privilege) ShardIterator(org.elasticsearch.cluster.routing.ShardIterator) RelationName(io.crate.metadata.RelationName) NestableCollectExpression(io.crate.execution.engine.collect.NestableCollectExpression) ArrayList(java.util.ArrayList) GroupShardsIterator(org.elasticsearch.cluster.routing.GroupShardsIterator) SeqNoStats(org.elasticsearch.index.seqno.SeqNoStats) RetentionLease(org.elasticsearch.index.seqno.RetentionLease) ClusterState(org.elasticsearch.cluster.ClusterState) Routing(io.crate.metadata.Routing) NestableInput(io.crate.expression.NestableInput) UnassignedShard(io.crate.metadata.shard.unassigned.UnassignedShard) INTEGER(io.crate.types.DataTypes.INTEGER) IntArrayList(com.carrotsearch.hppc.IntArrayList) Map(java.util.Map) Map.entry(java.util.Map.entry) ShardRowContext(io.crate.expression.reference.sys.shard.ShardRowContext) IntIndexedContainer(com.carrotsearch.hppc.IntIndexedContainer) User(io.crate.user.User) BOOLEAN(io.crate.types.DataTypes.BOOLEAN) RowCollectExpressionFactory(io.crate.metadata.expressions.RowCollectExpressionFactory) ColumnIdent(io.crate.metadata.ColumnIdent) NestableCollectExpression.constant(io.crate.execution.engine.collect.NestableCollectExpression.constant) STRING(io.crate.types.DataTypes.STRING) RoutingProvider(io.crate.metadata.RoutingProvider) NestableCollectExpression.forFunction(io.crate.execution.engine.collect.NestableCollectExpression.forFunction) List(java.util.List) SystemTable(io.crate.metadata.SystemTable) RowGranularity(io.crate.metadata.RowGranularity) TreeMap(java.util.TreeMap) DataTypes(io.crate.types.DataTypes) User(io.crate.user.User) ArrayList(java.util.ArrayList) IntArrayList(com.carrotsearch.hppc.IntArrayList) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) Routing(io.crate.metadata.Routing) TreeMap(java.util.TreeMap) ShardIterator(org.elasticsearch.cluster.routing.ShardIterator) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) Map(java.util.Map) TreeMap(java.util.TreeMap)

Example 4 with RoutingProvider

use of io.crate.metadata.RoutingProvider in project crate by crate.

the class SQLExecutor method planInternal.

private <T> T planInternal(AnalyzedStatement analyzedStatement, UUID jobId, int fetchSize, Row params) {
    RoutingProvider routingProvider = new RoutingProvider(random.nextInt(), emptyList());
    PlannerContext plannerContext = new PlannerContext(planner.currentClusterState(), routingProvider, jobId, coordinatorTxnCtx, nodeCtx, fetchSize, null);
    Plan plan = planner.plan(analyzedStatement, plannerContext);
    if (plan instanceof LogicalPlan) {
        return (T) ((LogicalPlan) plan).build(plannerContext, Set.of(), new ProjectionBuilder(nodeCtx), TopN.NO_LIMIT, 0, null, null, params, new SubQueryResults(emptyMap()) {

            @Override
            public Object getSafe(SelectSymbol key) {
                return Literal.of(key.valueType(), null);
            }
        });
    }
    return (T) plan;
}
Also used : SelectSymbol(io.crate.expression.symbol.SelectSymbol) RoutingProvider(io.crate.metadata.RoutingProvider) PlannerContext(io.crate.planner.PlannerContext) SubQueryResults(io.crate.planner.operators.SubQueryResults) LogicalPlan(io.crate.planner.operators.LogicalPlan) CreateBlobTablePlan(io.crate.planner.node.ddl.CreateBlobTablePlan) LogicalPlan(io.crate.planner.operators.LogicalPlan) Plan(io.crate.planner.Plan) CreateTablePlan(io.crate.planner.node.ddl.CreateTablePlan) ProjectionBuilder(io.crate.execution.dsl.projection.builder.ProjectionBuilder)

Example 5 with RoutingProvider

use of io.crate.metadata.RoutingProvider in project crate by crate.

the class SQLIntegrationTestCase method plan.

public PlanForNode plan(String stmt) {
    String[] nodeNames = internalCluster().getNodeNames();
    String nodeName = nodeNames[randomIntBetween(1, nodeNames.length) - 1];
    Analyzer analyzer = internalCluster().getInstance(Analyzer.class, nodeName);
    Planner planner = internalCluster().getInstance(Planner.class, nodeName);
    NodeContext nodeCtx = internalCluster().getInstance(NodeContext.class, nodeName);
    SessionContext sessionContext = new SessionContext(User.CRATE_USER, sqlExecutor.getCurrentSchema());
    CoordinatorTxnCtx coordinatorTxnCtx = new CoordinatorTxnCtx(sessionContext);
    RoutingProvider routingProvider = new RoutingProvider(Randomness.get().nextInt(), planner.getAwarenessAttributes());
    PlannerContext plannerContext = new PlannerContext(planner.currentClusterState(), routingProvider, UUID.randomUUID(), coordinatorTxnCtx, nodeCtx, 0, null);
    Plan plan = planner.plan(analyzer.analyze(SqlParser.createStatement(stmt), coordinatorTxnCtx.sessionContext(), ParamTypeHints.EMPTY), plannerContext);
    return new PlanForNode(plan, nodeName, plannerContext);
}
Also used : RoutingProvider(io.crate.metadata.RoutingProvider) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) PlannerContext(io.crate.planner.PlannerContext) NodeContext(io.crate.metadata.NodeContext) SessionContext(io.crate.action.sql.SessionContext) Planner(io.crate.planner.Planner) Analyzer(io.crate.analyze.Analyzer) Plan(io.crate.planner.Plan)

Aggregations

RoutingProvider (io.crate.metadata.RoutingProvider)9 CoordinatorTxnCtx (io.crate.metadata.CoordinatorTxnCtx)6 PlannerContext (io.crate.planner.PlannerContext)6 Plan (io.crate.planner.Plan)5 Analyzer (io.crate.analyze.Analyzer)4 NodeContext (io.crate.metadata.NodeContext)4 Planner (io.crate.planner.Planner)4 SubQueryResults (io.crate.planner.operators.SubQueryResults)4 AnalyzedBegin (io.crate.analyze.AnalyzedBegin)3 AnalyzedCommit (io.crate.analyze.AnalyzedCommit)3 AnalyzedDeallocate (io.crate.analyze.AnalyzedDeallocate)3 AnalyzedDiscard (io.crate.analyze.AnalyzedDiscard)3 AnalyzedStatement (io.crate.analyze.AnalyzedStatement)3 ParamTypeHints (io.crate.analyze.ParamTypeHints)3 QueriedSelectRelation (io.crate.analyze.QueriedSelectRelation)3 Relations (io.crate.analyze.Relations)3 AbstractTableRelation (io.crate.analyze.relations.AbstractTableRelation)3 AnalyzedRelation (io.crate.analyze.relations.AnalyzedRelation)3 AccessControl (io.crate.auth.AccessControl)3 VisibleForTesting (io.crate.common.annotations.VisibleForTesting)3