use of org.apache.ignite.internal.processors.tracing.MTC.TraceSurroundings 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();
}
}
use of org.apache.ignite.internal.processors.tracing.MTC.TraceSurroundings in project ignite by apache.
the class IgniteH2Indexing method executeSelect.
/**
* Execute an all-ready {@link SqlFieldsQuery}.
*
* @param qryDesc Plan key.
* @param qryParams Parameters.
* @param select Select.
* @param keepBinary Whether binary objects must not be deserialized automatically.
* @param cancel Query cancel state holder.
* @return Query result.
*/
private List<? extends FieldsQueryCursor<List<?>>> executeSelect(QueryDescriptor qryDesc, QueryParameters qryParams, QueryParserResultSelect select, boolean keepBinary, GridQueryCancel cancel) {
assert cancel != null;
// Register query.
long qryId = registerRunningQuery(qryDesc, qryParams, cancel, select.statement());
try (TraceSurroundings ignored = MTC.support(ctx.tracing().create(SQL_CURSOR_OPEN, MTC.span()))) {
GridNearTxLocal tx = null;
MvccQueryTracker tracker = null;
GridCacheContext mvccCctx = null;
boolean inTx = false;
if (select.mvccEnabled()) {
mvccCctx = ctx.cache().context().cacheContext(select.mvccCacheId());
if (mvccCctx == null)
throw new IgniteCheckedException("Cache has been stopped concurrently [cacheId=" + select.mvccCacheId() + ']');
boolean autoStartTx = !qryParams.autoCommit() && tx(ctx) == null;
// Start new user tx in case of autocommit == false.
if (autoStartTx)
txStart(ctx, qryParams.timeout());
tx = tx(ctx);
checkActive(tx);
inTx = tx != null;
tracker = MvccUtils.mvccTracker(mvccCctx, tx);
}
int timeout = operationTimeout(qryParams.timeout(), tx);
Iterable<List<?>> iter = executeSelect0(qryId, qryDesc, qryParams, select, keepBinary, tracker, cancel, inTx, timeout);
// Execute SELECT FOR UPDATE if needed.
if (select.forUpdate() && inTx)
iter = lockSelectedRows(iter, mvccCctx, timeout, qryParams.pageSize());
RegisteredQueryCursor<List<?>> cursor = new RegisteredQueryCursor<>(iter, cancel, runningQueryManager(), qryParams.lazy(), qryId, ctx.tracing());
cancel.add(cursor::cancel);
cursor.fieldsMeta(select.meta());
cursor.partitionResult(select.twoStepQuery() != null ? select.twoStepQuery().derivedPartitions() : null);
return singletonList(cursor);
} catch (Exception e) {
runningQryMgr.unregister(qryId, e);
if (e instanceof IgniteCheckedException)
throw U.convertException((IgniteCheckedException) e);
if (e instanceof RuntimeException)
throw (RuntimeException) e;
throw new IgniteSQLException("Failed to execute SELECT statement: " + qryDesc.sql(), e);
}
}
use of org.apache.ignite.internal.processors.tracing.MTC.TraceSurroundings in project ignite by apache.
the class IgniteH2Indexing method querySqlFields.
/**
* {@inheritDoc}
*/
@SuppressWarnings({ "StringEquality" })
@Override
public List<FieldsQueryCursor<List<?>>> querySqlFields(String schemaName, SqlFieldsQuery qry, @Nullable SqlClientContext cliCtx, boolean keepBinary, boolean failOnMultipleStmts, GridQueryCancel cancel) {
try {
List<FieldsQueryCursor<List<?>>> res = new ArrayList<>(1);
SqlFieldsQuery remainingQry = qry;
while (remainingQry != null) {
Span qrySpan = ctx.tracing().create(SQL_QRY, MTC.span()).addTag(SQL_SCHEMA, () -> schemaName);
try (TraceSurroundings ignored = MTC.supportContinual(qrySpan)) {
// Parse.
QueryParserResult parseRes = parser.parse(schemaName, remainingQry, !failOnMultipleStmts);
qrySpan.addTag(SQL_QRY_TEXT, () -> parseRes.queryDescriptor().sql());
remainingQry = parseRes.remainingQuery();
// Get next command.
QueryDescriptor newQryDesc = parseRes.queryDescriptor();
QueryParameters newQryParams = parseRes.queryParameters();
// since they pass parameters differently.
if (!newQryDesc.batched()) {
int qryParamsCnt = F.isEmpty(newQryParams.arguments()) ? 0 : newQryParams.arguments().length;
if (qryParamsCnt < parseRes.parametersCount())
throw new IgniteSQLException("Invalid number of query parameters [expected=" + parseRes.parametersCount() + ", actual=" + qryParamsCnt + ']');
}
// Check if cluster state is valid.
checkClusterState(parseRes);
// Execute.
if (parseRes.isCommand()) {
QueryParserResultCommand cmd = parseRes.command();
assert cmd != null;
FieldsQueryCursor<List<?>> cmdRes = executeCommand(newQryDesc, newQryParams, cliCtx, cmd);
res.add(cmdRes);
} else if (parseRes.isDml()) {
QueryParserResultDml dml = parseRes.dml();
assert dml != null;
List<? extends FieldsQueryCursor<List<?>>> dmlRes = executeDml(newQryDesc, newQryParams, dml, cancel);
res.addAll(dmlRes);
} else {
assert parseRes.isSelect();
QueryParserResultSelect select = parseRes.select();
assert select != null;
List<? extends FieldsQueryCursor<List<?>>> qryRes = executeSelect(newQryDesc, newQryParams, select, keepBinary, cancel);
res.addAll(qryRes);
}
} catch (Throwable th) {
qrySpan.addTag(ERROR, th::getMessage).end();
throw th;
}
}
return res;
} catch (RuntimeException | Error e) {
GridNearTxLocal tx = ctx.cache().context().tm().tx();
if (tx != null && tx.mvccSnapshot() != null && (!(e instanceof IgniteSQLException) || /* Parsing errors should not rollback Tx. */
((IgniteSQLException) e).sqlState() != SqlStateCode.PARSING_EXCEPTION))
tx.setRollbackOnly();
throw e;
}
}
use of org.apache.ignite.internal.processors.tracing.MTC.TraceSurroundings in project ignite by apache.
the class IgniteH2Indexing method executeCommand.
/**
* Execute command.
*
* @param qryDesc Query descriptor.
* @param qryParams Query parameters.
* @param cliCtx CLient context.
* @param cmd Command (native).
* @return Result.
*/
private FieldsQueryCursor<List<?>> executeCommand(QueryDescriptor qryDesc, QueryParameters qryParams, @Nullable SqlClientContext cliCtx, QueryParserResultCommand cmd) {
if (cmd.noOp())
return zeroCursor();
SqlCommand cmdNative = cmd.commandNative();
GridSqlStatement cmdH2 = cmd.commandH2();
if (qryDesc.local()) {
throw new IgniteSQLException("DDL statements are not supported for LOCAL caches", IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
}
long qryId = registerRunningQuery(qryDesc, qryParams, null, null);
CommandResult res = null;
Exception failReason = null;
try (TraceSurroundings ignored = MTC.support(ctx.tracing().create(SQL_CMD_QRY_EXECUTE, MTC.span()))) {
res = cmdProc.runCommand(qryDesc.sql(), cmdNative, cmdH2, qryParams, cliCtx, qryId);
return res.cursor();
} catch (IgniteException e) {
failReason = e;
throw e;
} catch (IgniteCheckedException e) {
failReason = e;
throw new IgniteSQLException("Failed to execute DDL statement [stmt=" + qryDesc.sql() + ", err=" + e.getMessage() + ']', e);
} finally {
if (res == null || res.unregisterRunningQuery())
runningQryMgr.unregister(qryId, failReason);
}
}
use of org.apache.ignite.internal.processors.tracing.MTC.TraceSurroundings in project ignite by apache.
the class IgniteH2Indexing method executeSelectDistributed.
/**
* Run distributed query on detected set of partitions.
*
* @param qryId Query id.
* @param qryDesc Query descriptor.
* @param qryParams Query parameters.
* @param twoStepQry Two-step query.
* @param keepBinary Keep binary flag.
* @param mvccTracker Query tracker.
* @param cancel Cancel handler.
* @param timeout Timeout.
* @return Cursor representing distributed query result.
*/
@SuppressWarnings("IfMayBeConditional")
private Iterable<List<?>> executeSelectDistributed(final long qryId, final QueryDescriptor qryDesc, final QueryParameters qryParams, final GridCacheTwoStepQuery twoStepQry, final boolean keepBinary, MvccQueryTracker mvccTracker, final GridQueryCancel cancel, int timeout) {
// When explicit partitions are set, there must be an owning cache they should be applied to.
PartitionResult derivedParts = twoStepQry.derivedPartitions();
final int[] parts = PartitionResult.calculatePartitions(qryParams.partitions(), derivedParts, qryParams.arguments());
Iterable<List<?>> iter;
if (parts != null && parts.length == 0) {
iter = new Iterable<List<?>>() {
@Override
public Iterator<List<?>> iterator() {
return new Iterator<List<?>>() {
@Override
public boolean hasNext() {
return false;
}
@SuppressWarnings("IteratorNextCanNotThrowNoSuchElementException")
@Override
public List<?> next() {
return null;
}
};
}
};
} else {
assert !twoStepQry.mvccEnabled() || !F.isEmpty(twoStepQry.cacheIds());
assert twoStepQry.mvccEnabled() == (mvccTracker != null);
iter = new Iterable<List<?>>() {
@Override
public Iterator<List<?>> iterator() {
try (TraceSurroundings ignored = MTC.support(ctx.tracing().create(SQL_ITER_OPEN, MTC.span()))) {
return IgniteH2Indexing.this.rdcQryExec.query(qryId, qryDesc.schemaName(), twoStepQry, keepBinary, qryDesc.enforceJoinOrder(), timeout, cancel, qryParams.arguments(), parts, qryParams.lazy(), mvccTracker, qryParams.dataPageScanEnabled(), qryParams.pageSize());
} catch (Throwable e) {
if (mvccTracker != null)
mvccTracker.onDone();
throw e;
}
}
};
}
return iter;
}
Aggregations