Search in sources :

Example 1 with DistributedJoinContext

use of org.apache.ignite.internal.processors.query.h2.opt.join.DistributedJoinContext in project ignite by apache.

the class GridMapQueryExecutor method onQueryRequest0.

/**
 * @param node Node authored request.
 * @param qryId Query ID.
 * @param reqId Request ID.
 * @param segmentId index segment ID.
 * @param schemaName Schema name.
 * @param qrys Queries to execute.
 * @param cacheIds Caches which will be affected by these queries.
 * @param topVer Topology version.
 * @param partsMap Partitions map for unstable topology.
 * @param parts Explicit partitions for current node.
 * @param pageSize Page size.
 * @param distributedJoins Query distributed join mode.
 * @param enforceJoinOrder Enforce join order H2 flag.
 * @param replicated Replicated only flag.
 * @param timeout Query timeout.
 * @param params Query parameters.
 * @param lazy Streaming flag.
 * @param mvccSnapshot MVCC snapshot.
 * @param dataPageScanEnabled If data page scan is enabled.
 */
private void onQueryRequest0(final ClusterNode node, final long qryId, final long reqId, final int segmentId, final String schemaName, final Collection<GridCacheSqlQuery> qrys, final List<Integer> cacheIds, final AffinityTopologyVersion topVer, final Map<UUID, int[]> partsMap, final int[] parts, final int pageSize, final boolean distributedJoins, final boolean enforceJoinOrder, final boolean replicated, final int timeout, final Object[] params, boolean lazy, @Nullable final MvccSnapshot mvccSnapshot, Boolean dataPageScanEnabled, boolean treatReplicatedAsPartitioned) {
    boolean performanceStatsEnabled = ctx.performanceStatistics().enabled();
    if (performanceStatsEnabled)
        IoStatisticsQueryHelper.startGatheringQueryStatistics();
    // Prepare to run queries.
    GridCacheContext<?, ?> mainCctx = mainCacheContext(cacheIds);
    MapNodeResults nodeRess = resultsForNode(node.id());
    MapQueryResults qryResults = null;
    PartitionReservation reserved = null;
    QueryContext qctx = null;
    // We don't use try with resources on purpose - the catch block must also be executed in the context of this span.
    TraceSurroundings trace = MTC.support(ctx.tracing().create(SQL_QRY_EXEC_REQ, MTC.span()).addTag(SQL_QRY_TEXT, () -> qrys.stream().map(GridCacheSqlQuery::query).collect(Collectors.joining("; "))));
    try {
        if (topVer != null) {
            // Reserve primary for topology version or explicit partitions.
            reserved = h2.partitionReservationManager().reservePartitions(cacheIds, topVer, parts, node.id(), reqId);
            if (reserved.failed()) {
                sendRetry(node, reqId, segmentId, reserved.error());
                return;
            }
        }
        // Prepare query context.
        DistributedJoinContext distributedJoinCtx = null;
        if (distributedJoins && !replicated) {
            distributedJoinCtx = new DistributedJoinContext(topVer, partsMap, node.id(), reqId, segmentId, pageSize);
        }
        qctx = new QueryContext(segmentId, h2.backupFilter(topVer, parts, treatReplicatedAsPartitioned), distributedJoinCtx, mvccSnapshot, reserved, true);
        qryResults = new MapQueryResults(h2, reqId, qrys.size(), mainCctx, lazy, qctx);
        // qctx is set, we have to release reservations inside of it.
        reserved = null;
        if (distributedJoinCtx != null)
            qryCtxRegistry.setShared(node.id(), reqId, qctx);
        if (nodeRess.put(reqId, segmentId, qryResults) != null)
            throw new IllegalStateException();
        if (nodeRess.cancelled(reqId)) {
            qryCtxRegistry.clearShared(node.id(), reqId);
            nodeRess.cancelRequest(reqId);
            throw new QueryCancelledException();
        }
        // Run queries.
        int qryIdx = 0;
        boolean evt = mainCctx != null && mainCctx.events().isRecordable(EVT_CACHE_QUERY_EXECUTED);
        for (GridCacheSqlQuery qry : qrys) {
            H2PooledConnection conn = h2.connections().connection(schemaName);
            H2Utils.setupConnection(conn, qctx, distributedJoins, enforceJoinOrder, lazy);
            MapQueryResult res = new MapQueryResult(h2, mainCctx, node.id(), qry, params, conn, log);
            qryResults.addResult(qryIdx, res);
            try {
                res.lock();
                // Ensure we are on the target node for this replicated query.
                if (qry.node() == null || (segmentId == 0 && qry.node().equals(ctx.localNodeId()))) {
                    String sql = qry.query();
                    Collection<Object> params0 = F.asList(qry.parameters(params));
                    PreparedStatement stmt = conn.prepareStatement(sql, H2StatementCache.queryFlags(distributedJoins, enforceJoinOrder));
                    H2Utils.bindParameters(stmt, params0);
                    MapH2QueryInfo qryInfo = new MapH2QueryInfo(stmt, qry.query(), node.id(), qryId, reqId, segmentId);
                    ResultSet rs = h2.executeSqlQueryWithTimer(stmt, conn, sql, timeout, qryResults.queryCancel(qryIdx), dataPageScanEnabled, qryInfo);
                    if (evt) {
                        ctx.event().record(new CacheQueryExecutedEvent<>(node, "SQL query executed.", EVT_CACHE_QUERY_EXECUTED, CacheQueryType.SQL.name(), mainCctx.name(), null, qry.query(), null, null, params, node.id(), null));
                    }
                    assert rs instanceof JdbcResultSet : rs.getClass();
                    if (qryResults.cancelled()) {
                        rs.close();
                        throw new QueryCancelledException();
                    }
                    res.openResult(rs, qryInfo);
                    final GridQueryNextPageResponse msg = prepareNextPage(nodeRess, node, qryResults, qryIdx, segmentId, pageSize, dataPageScanEnabled);
                    if (msg != null)
                        sendNextPage(node, msg);
                } else {
                    assert !qry.isPartitioned();
                    qryResults.closeResult(qryIdx);
                }
                qryIdx++;
            } finally {
                try {
                    res.unlockTables();
                } finally {
                    res.unlock();
                }
            }
        }
        if (!lazy)
            qryResults.releaseQueryContext();
    } catch (Throwable e) {
        if (qryResults != null) {
            nodeRess.remove(reqId, segmentId, qryResults);
            qryResults.close();
            // If a query is cancelled before execution is started partitions have to be released.
            if (!lazy || !qryResults.isAllClosed())
                qryResults.releaseQueryContext();
        } else
            releaseReservations(qctx);
        if (e instanceof QueryCancelledException)
            sendError(node, reqId, e);
        else {
            SQLException sqlEx = X.cause(e, SQLException.class);
            if (sqlEx != null && sqlEx.getErrorCode() == ErrorCode.STATEMENT_WAS_CANCELED)
                sendQueryCancel(node, reqId);
            else {
                GridH2RetryException retryErr = X.cause(e, GridH2RetryException.class);
                if (retryErr != null) {
                    final String retryCause = String.format("Failed to execute non-collocated query (will retry) [localNodeId=%s, rmtNodeId=%s, reqId=%s, " + "errMsg=%s]", ctx.localNodeId(), node.id(), reqId, retryErr.getMessage());
                    sendRetry(node, reqId, segmentId, retryCause);
                } else {
                    QueryRetryException qryRetryErr = X.cause(e, QueryRetryException.class);
                    if (qryRetryErr != null)
                        sendError(node, reqId, qryRetryErr);
                    else {
                        if (e instanceof Error) {
                            U.error(log, "Failed to execute local query.", e);
                            throw (Error) e;
                        }
                        U.warn(log, "Failed to execute local query.", e);
                        sendError(node, reqId, e);
                    }
                }
            }
        }
    } finally {
        if (reserved != null)
            reserved.release();
        if (trace != null)
            trace.close();
        if (performanceStatsEnabled) {
            IoStatisticsHolder stat = IoStatisticsQueryHelper.finishGatheringQueryStatistics();
            if (stat.logicalReads() > 0 || stat.physicalReads() > 0) {
                ctx.performanceStatistics().queryReads(GridCacheQueryType.SQL_FIELDS, node.id(), reqId, stat.logicalReads(), stat.physicalReads());
            }
        }
    }
}
Also used : QueryRetryException(org.apache.ignite.cache.query.QueryRetryException) SQLException(java.sql.SQLException) GridQueryNextPageResponse(org.apache.ignite.internal.processors.query.h2.twostep.messages.GridQueryNextPageResponse) TraceSurroundings(org.apache.ignite.internal.processors.tracing.MTC.TraceSurroundings) DistributedJoinContext(org.apache.ignite.internal.processors.query.h2.opt.join.DistributedJoinContext) ResultSet(java.sql.ResultSet) JdbcResultSet(org.h2.jdbc.JdbcResultSet) GridCacheSqlQuery(org.apache.ignite.internal.processors.cache.query.GridCacheSqlQuery) JdbcResultSet(org.h2.jdbc.JdbcResultSet) H2PooledConnection(org.apache.ignite.internal.processors.query.h2.H2PooledConnection) MapH2QueryInfo(org.apache.ignite.internal.processors.query.h2.MapH2QueryInfo) GridH2RetryException(org.apache.ignite.internal.processors.query.h2.opt.GridH2RetryException) PreparedStatement(java.sql.PreparedStatement) QueryContext(org.apache.ignite.internal.processors.query.h2.opt.QueryContext) IoStatisticsHolder(org.apache.ignite.internal.metric.IoStatisticsHolder) QueryCancelledException(org.apache.ignite.cache.query.QueryCancelledException)

Example 2 with DistributedJoinContext

use of org.apache.ignite.internal.processors.query.h2.opt.join.DistributedJoinContext in project ignite by apache.

the class H2TreeIndex method onIndexRangeRequest.

/**
 * @param node Requesting node.
 * @param msg Request message.
 */
private void onIndexRangeRequest(final ClusterNode node, final GridH2IndexRangeRequest msg) {
    // We don't use try with resources on purpose - the catch block must also be executed in the context of this span.
    TraceSurroundings trace = MTC.support(ctx.tracing().create(SQL_IDX_RANGE_REQ, MTC.span()));
    Span span = MTC.span();
    try {
        span.addTag(SQL_IDX, () -> idxName);
        span.addTag(SQL_TABLE, () -> tblName);
        GridH2IndexRangeResponse res = new GridH2IndexRangeResponse();
        res.originNodeId(msg.originNodeId());
        res.queryId(msg.queryId());
        res.originSegmentId(msg.originSegmentId());
        res.segment(msg.segment());
        res.batchLookupId(msg.batchLookupId());
        QueryContext qctx = qryCtxRegistry.getShared(msg.originNodeId(), msg.queryId(), msg.originSegmentId());
        if (qctx == null)
            res.status(STATUS_NOT_FOUND);
        else {
            DistributedJoinContext joinCtx = qctx.distributedJoinContext();
            assert joinCtx != null;
            try {
                RangeSource src;
                if (msg.bounds() != null) {
                    // This is the first request containing all the search rows.
                    assert !msg.bounds().isEmpty() : "empty bounds";
                    src = new RangeSource(this, msg.bounds(), msg.segment(), idxQryContext(qctx));
                } else {
                    // This is request to fetch next portion of data.
                    src = joinCtx.getSource(node.id(), msg.segment(), msg.batchLookupId());
                    assert src != null;
                }
                List<GridH2RowRange> ranges = new ArrayList<>();
                int maxRows = joinCtx.pageSize();
                assert maxRows > 0 : maxRows;
                while (maxRows > 0) {
                    GridH2RowRange range = src.next(maxRows);
                    if (range == null)
                        break;
                    ranges.add(range);
                    if (range.rows() != null)
                        maxRows -= range.rows().size();
                }
                assert !ranges.isEmpty();
                if (src.hasMoreRows()) {
                    // Save source for future fetches.
                    if (msg.bounds() != null)
                        joinCtx.putSource(node.id(), msg.segment(), msg.batchLookupId(), src);
                } else if (msg.bounds() == null) {
                    // Drop saved source.
                    joinCtx.putSource(node.id(), msg.segment(), msg.batchLookupId(), null);
                }
                res.ranges(ranges);
                res.status(STATUS_OK);
                span.addTag(SQL_IDX_RANGE_ROWS, () -> Integer.toString(ranges.stream().mapToInt(GridH2RowRange::rowsSize).sum()));
            } catch (Throwable th) {
                span.addTag(ERROR, th::getMessage);
                U.error(log, "Failed to process request: " + msg, th);
                res.error(th.getClass() + ": " + th.getMessage());
                res.status(STATUS_ERROR);
            }
        }
        send(singletonList(node), res);
    } catch (Throwable th) {
        span.addTag(ERROR, th::getMessage);
        throw th;
    } finally {
        if (trace != null)
            trace.close();
    }
}
Also used : GridH2IndexRangeResponse(org.apache.ignite.internal.processors.query.h2.twostep.msg.GridH2IndexRangeResponse) DistributedJoinContext(org.apache.ignite.internal.processors.query.h2.opt.join.DistributedJoinContext) RangeSource(org.apache.ignite.internal.processors.query.h2.opt.join.RangeSource) ArrayList(java.util.ArrayList) GridH2RowRange(org.apache.ignite.internal.processors.query.h2.twostep.msg.GridH2RowRange) IndexQueryContext(org.apache.ignite.internal.cache.query.index.sorted.inline.IndexQueryContext) QueryContext(org.apache.ignite.internal.processors.query.h2.opt.QueryContext) Span(org.apache.ignite.internal.processors.tracing.Span) TraceSurroundings(org.apache.ignite.internal.processors.tracing.MTC.TraceSurroundings)

Example 3 with DistributedJoinContext

use of org.apache.ignite.internal.processors.query.h2.opt.join.DistributedJoinContext in project ignite by apache.

the class DistributedLookupBatch method createRequest.

/**
 * @param joinCtx Join context.
 * @param batchLookupId Batch lookup ID.
 * @param segmentId Segment ID.
 * @return Index range request.
 */
public static GridH2IndexRangeRequest createRequest(DistributedJoinContext joinCtx, int batchLookupId, int segmentId) {
    GridH2IndexRangeRequest req = new GridH2IndexRangeRequest();
    req.originNodeId(joinCtx.originNodeId());
    req.queryId(joinCtx.queryId());
    req.originSegmentId(joinCtx.segment());
    req.segment(segmentId);
    req.batchLookupId(batchLookupId);
    return req;
}
Also used : GridH2IndexRangeRequest(org.apache.ignite.internal.processors.query.h2.twostep.msg.GridH2IndexRangeRequest)

Example 4 with DistributedJoinContext

use of org.apache.ignite.internal.processors.query.h2.opt.join.DistributedJoinContext in project ignite by apache.

the class H2TreeIndex method onIndexRangeResponse.

/**
 * @param node Responded node.
 * @param msg Response message.
 */
private void onIndexRangeResponse(ClusterNode node, GridH2IndexRangeResponse msg) {
    try (TraceSurroundings ignored = MTC.support(ctx.tracing().create(SQL_IDX_RANGE_RESP, MTC.span()))) {
        QueryContext qctx = qryCtxRegistry.getShared(msg.originNodeId(), msg.queryId(), msg.originSegmentId());
        if (qctx == null)
            return;
        DistributedJoinContext joinCtx = qctx.distributedJoinContext();
        assert joinCtx != null;
        Map<SegmentKey, RangeStream> streams = joinCtx.getStreams(msg.batchLookupId());
        if (streams == null)
            return;
        RangeStream stream = streams.get(new SegmentKey(node, msg.segment()));
        assert stream != null;
        stream.onResponse(msg);
    }
}
Also used : SegmentKey(org.apache.ignite.internal.processors.query.h2.opt.join.SegmentKey) DistributedJoinContext(org.apache.ignite.internal.processors.query.h2.opt.join.DistributedJoinContext) RangeStream(org.apache.ignite.internal.processors.query.h2.opt.join.RangeStream) IndexQueryContext(org.apache.ignite.internal.cache.query.index.sorted.inline.IndexQueryContext) QueryContext(org.apache.ignite.internal.processors.query.h2.opt.QueryContext) TraceSurroundings(org.apache.ignite.internal.processors.tracing.MTC.TraceSurroundings)

Aggregations

QueryContext (org.apache.ignite.internal.processors.query.h2.opt.QueryContext)3 DistributedJoinContext (org.apache.ignite.internal.processors.query.h2.opt.join.DistributedJoinContext)3 TraceSurroundings (org.apache.ignite.internal.processors.tracing.MTC.TraceSurroundings)3 IndexQueryContext (org.apache.ignite.internal.cache.query.index.sorted.inline.IndexQueryContext)2 PreparedStatement (java.sql.PreparedStatement)1 ResultSet (java.sql.ResultSet)1 SQLException (java.sql.SQLException)1 ArrayList (java.util.ArrayList)1 QueryCancelledException (org.apache.ignite.cache.query.QueryCancelledException)1 QueryRetryException (org.apache.ignite.cache.query.QueryRetryException)1 IoStatisticsHolder (org.apache.ignite.internal.metric.IoStatisticsHolder)1 GridCacheSqlQuery (org.apache.ignite.internal.processors.cache.query.GridCacheSqlQuery)1 H2PooledConnection (org.apache.ignite.internal.processors.query.h2.H2PooledConnection)1 MapH2QueryInfo (org.apache.ignite.internal.processors.query.h2.MapH2QueryInfo)1 GridH2RetryException (org.apache.ignite.internal.processors.query.h2.opt.GridH2RetryException)1 RangeSource (org.apache.ignite.internal.processors.query.h2.opt.join.RangeSource)1 RangeStream (org.apache.ignite.internal.processors.query.h2.opt.join.RangeStream)1 SegmentKey (org.apache.ignite.internal.processors.query.h2.opt.join.SegmentKey)1 GridQueryNextPageResponse (org.apache.ignite.internal.processors.query.h2.twostep.messages.GridQueryNextPageResponse)1 GridH2IndexRangeRequest (org.apache.ignite.internal.processors.query.h2.twostep.msg.GridH2IndexRangeRequest)1