Search in sources :

Example 1 with BasicQueryInfo

use of io.trino.server.BasicQueryInfo in project trino by trinodb.

the class ClusterStatsResource method getClusterStats.

@ResourceSecurity(WEB_UI)
@GET
@Produces(MediaType.APPLICATION_JSON)
public ClusterStats getClusterStats() {
    long runningQueries = 0;
    long blockedQueries = 0;
    long queuedQueries = 0;
    long activeNodes = nodeManager.getNodes(NodeState.ACTIVE).stream().filter(node -> isIncludeCoordinator || !node.isCoordinator()).count();
    long activeCoordinators = nodeManager.getNodes(NodeState.ACTIVE).stream().filter(InternalNode::isCoordinator).count();
    long totalAvailableProcessors = clusterMemoryManager.getTotalAvailableProcessors();
    long runningDrivers = 0;
    double memoryReservation = 0;
    long totalInputRows = dispatchManager.getStats().getConsumedInputRows().getTotalCount();
    long totalInputBytes = dispatchManager.getStats().getConsumedInputBytes().getTotalCount();
    long totalCpuTimeSecs = dispatchManager.getStats().getConsumedCpuTimeSecs().getTotalCount();
    for (BasicQueryInfo query : dispatchManager.getQueries()) {
        if (query.getState() == QueryState.QUEUED) {
            queuedQueries++;
        } else if (query.getState() == QueryState.RUNNING) {
            if (query.getQueryStats().isFullyBlocked()) {
                blockedQueries++;
            } else {
                runningQueries++;
            }
        }
        if (!query.getState().isDone()) {
            totalInputBytes += query.getQueryStats().getRawInputDataSize().toBytes();
            totalInputRows += query.getQueryStats().getRawInputPositions();
            totalCpuTimeSecs += query.getQueryStats().getTotalCpuTime().getValue(SECONDS);
            memoryReservation += query.getQueryStats().getUserMemoryReservation().toBytes();
            runningDrivers += query.getQueryStats().getRunningDrivers();
        }
    }
    return new ClusterStats(runningQueries, blockedQueries, queuedQueries, activeCoordinators, activeNodes, runningDrivers, totalAvailableProcessors, memoryReservation, totalInputRows, totalInputBytes, totalCpuTimeSecs);
}
Also used : JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) NodeState(io.trino.metadata.NodeState) InternalNodeManager(io.trino.metadata.InternalNodeManager) ResourceSecurity(io.trino.server.security.ResourceSecurity) DispatchManager(io.trino.dispatcher.DispatchManager) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) BasicQueryInfo(io.trino.server.BasicQueryInfo) NodeSchedulerConfig(io.trino.execution.scheduler.NodeSchedulerConfig) Path(javax.ws.rs.Path) QueryState(io.trino.execution.QueryState) Inject(javax.inject.Inject) ClusterMemoryManager(io.trino.memory.ClusterMemoryManager) InternalNode(io.trino.metadata.InternalNode) MediaType(javax.ws.rs.core.MediaType) Objects.requireNonNull(java.util.Objects.requireNonNull) JsonCreator(com.fasterxml.jackson.annotation.JsonCreator) WEB_UI(io.trino.server.security.ResourceSecurity.AccessType.WEB_UI) SECONDS(java.util.concurrent.TimeUnit.SECONDS) BasicQueryInfo(io.trino.server.BasicQueryInfo) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ResourceSecurity(io.trino.server.security.ResourceSecurity)

Example 2 with BasicQueryInfo

use of io.trino.server.BasicQueryInfo in project trino by trinodb.

the class QueryStateMachine method getBasicQueryInfo.

public BasicQueryInfo getBasicQueryInfo(Optional<BasicStageStats> rootStage) {
    // Query state must be captured first in order to provide a
    // correct view of the query.  For example, building this
    // information, the query could finish, and the task states would
    // never be visible.
    QueryState state = queryState.get();
    ErrorCode errorCode = null;
    if (state == FAILED) {
        ExecutionFailureInfo failureCause = this.failureCause.get();
        if (failureCause != null) {
            errorCode = failureCause.getErrorCode();
        }
    }
    BasicStageStats stageStats = rootStage.orElse(EMPTY_STAGE_STATS);
    BasicQueryStats queryStats = new BasicQueryStats(queryStateTimer.getCreateTime(), getEndTime().orElse(null), queryStateTimer.getQueuedTime(), queryStateTimer.getElapsedTime(), queryStateTimer.getExecutionTime(), stageStats.getTotalDrivers(), stageStats.getQueuedDrivers(), stageStats.getRunningDrivers(), stageStats.getCompletedDrivers(), stageStats.getRawInputDataSize(), stageStats.getRawInputPositions(), stageStats.getPhysicalInputDataSize(), stageStats.getCumulativeUserMemory(), stageStats.getFailedCumulativeUserMemory(), stageStats.getUserMemoryReservation(), stageStats.getTotalMemoryReservation(), succinctBytes(getPeakUserMemoryInBytes()), succinctBytes(getPeakTotalMemoryInBytes()), stageStats.getTotalCpuTime(), stageStats.getFailedCpuTime(), stageStats.getTotalScheduledTime(), stageStats.getFailedScheduledTime(), stageStats.isFullyBlocked(), stageStats.getBlockedReasons(), stageStats.getProgressPercentage());
    return new BasicQueryInfo(queryId, session.toSessionRepresentation(), Optional.of(resourceGroup), state, stageStats.isScheduled(), self, query, Optional.ofNullable(updateType.get()), preparedQuery, queryStats, errorCode == null ? null : errorCode.getType(), errorCode, queryType);
}
Also used : BasicQueryStats(io.trino.server.BasicQueryStats) BasicQueryInfo(io.trino.server.BasicQueryInfo) ErrorCode(io.trino.spi.ErrorCode)

Example 3 with BasicQueryInfo

use of io.trino.server.BasicQueryInfo in project trino by trinodb.

the class UiQueryResource method getAllQueryInfo.

@ResourceSecurity(WEB_UI)
@GET
public List<TrimmedBasicQueryInfo> getAllQueryInfo(@QueryParam("state") String stateFilter, @Context HttpServletRequest servletRequest, @Context HttpHeaders httpHeaders) {
    QueryState expectedState = stateFilter == null ? null : QueryState.valueOf(stateFilter.toUpperCase(Locale.ENGLISH));
    List<BasicQueryInfo> queries = dispatchManager.getQueries();
    queries = filterQueries(sessionContextFactory.extractAuthorizedIdentity(servletRequest, httpHeaders, alternateHeaderName), queries, accessControl);
    ImmutableList.Builder<TrimmedBasicQueryInfo> builder = ImmutableList.builder();
    for (BasicQueryInfo queryInfo : queries) {
        if (stateFilter == null || queryInfo.getState() == expectedState) {
            builder.add(new TrimmedBasicQueryInfo(queryInfo));
        }
    }
    return builder.build();
}
Also used : ImmutableList(com.google.common.collect.ImmutableList) BasicQueryInfo(io.trino.server.BasicQueryInfo) QueryState(io.trino.execution.QueryState) GET(javax.ws.rs.GET) ResourceSecurity(io.trino.server.security.ResourceSecurity)

Example 4 with BasicQueryInfo

use of io.trino.server.BasicQueryInfo in project trino by trinodb.

the class BaseConnectorTest method testQueryLoggingCount.

@Test
public void testQueryLoggingCount() {
    skipTestUnless(hasBehavior(SUPPORTS_CREATE_TABLE));
    QueryManager queryManager = getDistributedQueryRunner().getCoordinator().getQueryManager();
    executeExclusively(() -> {
        assertEventually(new Duration(1, MINUTES), () -> assertEquals(queryManager.getQueries().stream().map(BasicQueryInfo::getQueryId).map(queryManager::getFullQueryInfo).filter(info -> !info.isFinalQueryInfo()).collect(toList()), ImmutableList.of()));
        // We cannot simply get the number of completed queries as soon as all the queries are completed, because this counter may not be up-to-date at that point.
        // The completed queries counter is updated in a final query info listener, which is called eventually.
        // Therefore, here we wait until the value of this counter gets stable.
        DispatchManager dispatchManager = ((DistributedQueryRunner) getQueryRunner()).getCoordinator().getDispatchManager();
        long beforeCompletedQueriesCount = waitUntilStable(() -> dispatchManager.getStats().getCompletedQueries().getTotalCount(), new Duration(5, SECONDS));
        long beforeSubmittedQueriesCount = dispatchManager.getStats().getSubmittedQueries().getTotalCount();
        String tableName = "test_logging_count" + randomTableSuffix();
        assertUpdate("CREATE TABLE " + tableName + tableDefinitionForQueryLoggingCount());
        assertQueryReturnsEmptyResult("SELECT foo_1, foo_2_4 FROM " + tableName);
        assertUpdate("DROP TABLE " + tableName);
        assertQueryFails("SELECT * FROM " + tableName, ".*Table .* does not exist");
        // TODO: Figure out a better way of synchronization
        assertEventually(new Duration(1, MINUTES), () -> assertEquals(dispatchManager.getStats().getCompletedQueries().getTotalCount() - beforeCompletedQueriesCount, 4));
        assertEquals(dispatchManager.getStats().getSubmittedQueries().getTotalCount() - beforeSubmittedQueriesCount, 4);
    });
}
Also used : SkipException(org.testng.SkipException) SUPPORTS_MULTI_STATEMENT_WRITES(io.trino.testing.TestingConnectorBehavior.SUPPORTS_MULTI_STATEMENT_WRITES) QueryManager(io.trino.execution.QueryManager) SUPPORTS_ARRAY(io.trino.testing.TestingConnectorBehavior.SUPPORTS_ARRAY) Test(org.testng.annotations.Test) TestTable(io.trino.testing.sql.TestTable) Thread.currentThread(java.lang.Thread.currentThread) Future(java.util.concurrent.Future) DataProviders.toDataProvider(io.trino.testing.DataProviders.toDataProvider) Duration.nanosSince(io.airlift.units.Duration.nanosSince) ENGLISH(java.util.Locale.ENGLISH) Assert.assertFalse(org.testng.Assert.assertFalse) Assert.assertEquals(io.trino.testing.assertions.Assert.assertEquals) PlanPrinter.textLogicalPlan(io.trino.sql.planner.planprinter.PlanPrinter.textLogicalPlan) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Uninterruptibles.sleepUninterruptibly(com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly) Collectors.joining(java.util.stream.Collectors.joining) CountDownLatch(java.util.concurrent.CountDownLatch) Stream(java.util.stream.Stream) SUPPORTS_RENAME_TABLE(io.trino.testing.TestingConnectorBehavior.SUPPORTS_RENAME_TABLE) INFORMATION_SCHEMA(io.trino.connector.informationschema.InformationSchemaTable.INFORMATION_SCHEMA) Session(io.trino.Session) Verify.verifyNotNull(com.google.common.base.Verify.verifyNotNull) PlanNodeSearcher.searchFrom(io.trino.sql.planner.optimizations.PlanNodeSearcher.searchFrom) LimitNode(io.trino.sql.planner.plan.LimitNode) SUPPORTS_RENAME_SCHEMA(io.trino.testing.TestingConnectorBehavior.SUPPORTS_RENAME_SCHEMA) Callable(java.util.concurrent.Callable) MINUTES(java.util.concurrent.TimeUnit.MINUTES) SUPPORTS_TOPN_PUSHDOWN(io.trino.testing.TestingConnectorBehavior.SUPPORTS_TOPN_PUSHDOWN) Supplier(java.util.function.Supplier) SUPPORTS_RENAME_MATERIALIZED_VIEW_ACROSS_SCHEMAS(io.trino.testing.TestingConnectorBehavior.SUPPORTS_RENAME_MATERIALIZED_VIEW_ACROSS_SCHEMAS) StatsAndCosts(io.trino.cost.StatsAndCosts) ArrayList(java.util.ArrayList) SUPPORTS_CREATE_VIEW(io.trino.testing.TestingConnectorBehavior.SUPPORTS_CREATE_VIEW) SUPPORTS_TRUNCATE(io.trino.testing.TestingConnectorBehavior.SUPPORTS_TRUNCATE) VARCHAR(io.trino.spi.type.VarcharType.VARCHAR) String.join(java.lang.String.join) UncheckedTimeoutException(com.google.common.util.concurrent.UncheckedTimeoutException) SUPPORTS_COMMENT_ON_COLUMN(io.trino.testing.TestingConnectorBehavior.SUPPORTS_COMMENT_ON_COLUMN) SUPPORTS_CREATE_SCHEMA(io.trino.testing.TestingConnectorBehavior.SUPPORTS_CREATE_SCHEMA) Language(org.intellij.lang.annotations.Language) Iterables.getOnlyElement(com.google.common.collect.Iterables.getOnlyElement) QueryInfo(io.trino.execution.QueryInfo) JoinDistributionType(io.trino.sql.planner.OptimizerConfig.JoinDistributionType) SUPPORTS_CREATE_MATERIALIZED_VIEW(io.trino.testing.TestingConnectorBehavior.SUPPORTS_CREATE_MATERIALIZED_VIEW) QualifiedObjectName(io.trino.metadata.QualifiedObjectName) ArrayDeque(java.util.ArrayDeque) SUPPORTS_ROW_LEVEL_DELETE(io.trino.testing.TestingConnectorBehavior.SUPPORTS_ROW_LEVEL_DELETE) BasicQueryInfo(io.trino.server.BasicQueryInfo) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) SUPPORTS_DROP_COLUMN(io.trino.testing.TestingConnectorBehavior.SUPPORTS_DROP_COLUMN) SUPPORTS_CREATE_TABLE_WITH_DATA(io.trino.testing.TestingConnectorBehavior.SUPPORTS_CREATE_TABLE_WITH_DATA) CompletionService(java.util.concurrent.CompletionService) Duration(io.airlift.units.Duration) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TestTable.randomTableSuffix(io.trino.testing.sql.TestTable.randomTableSuffix) SUPPORTS_CREATE_TABLE(io.trino.testing.TestingConnectorBehavior.SUPPORTS_CREATE_TABLE) CyclicBarrier(java.util.concurrent.CyclicBarrier) ImmutableSet(com.google.common.collect.ImmutableSet) SUPPORTS_RENAME_COLUMN(io.trino.testing.TestingConnectorBehavior.SUPPORTS_RENAME_COLUMN) Collections.nCopies(java.util.Collections.nCopies) SUPPORTS_RENAME_TABLE_ACROSS_SCHEMAS(io.trino.testing.TestingConnectorBehavior.SUPPORTS_RENAME_TABLE_ACROSS_SCHEMAS) String.format(java.lang.String.format) Preconditions.checkState(com.google.common.base.Preconditions.checkState) SUPPORTS_DELETE(io.trino.testing.TestingConnectorBehavior.SUPPORTS_DELETE) List(java.util.List) SUPPORTS_INSERT(io.trino.testing.TestingConnectorBehavior.SUPPORTS_INSERT) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) ExecutorCompletionService(java.util.concurrent.ExecutorCompletionService) IntStream(java.util.stream.IntStream) DataProvider(org.testng.annotations.DataProvider) Assert.assertNull(org.testng.Assert.assertNull) Stopwatch(com.google.common.base.Stopwatch) Deque(java.util.Deque) QueryAssertions.getTrinoExceptionCause(io.trino.testing.QueryAssertions.getTrinoExceptionCause) ImmutableList(com.google.common.collect.ImmutableList) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) SUPPORTS_UPDATE(io.trino.testing.TestingConnectorBehavior.SUPPORTS_UPDATE) Objects.requireNonNull(java.util.Objects.requireNonNull) ExecutorService(java.util.concurrent.ExecutorService) DispatchManager(io.trino.dispatcher.DispatchManager) Assert.fail(org.testng.Assert.fail) SUPPORTS_RENAME_MATERIALIZED_VIEW(io.trino.testing.TestingConnectorBehavior.SUPPORTS_RENAME_MATERIALIZED_VIEW) MoreFutures.tryGetFutureValue(io.airlift.concurrent.MoreFutures.tryGetFutureValue) Executors.newFixedThreadPool(java.util.concurrent.Executors.newFixedThreadPool) FunctionManager(io.trino.metadata.FunctionManager) SUPPORTS_NEGATIVE_DATE(io.trino.testing.TestingConnectorBehavior.SUPPORTS_NEGATIVE_DATE) Consumer(java.util.function.Consumer) SUPPORTS_ADD_COLUMN(io.trino.testing.TestingConnectorBehavior.SUPPORTS_ADD_COLUMN) QueryAssertions.assertContains(io.trino.testing.QueryAssertions.assertContains) Collectors.toList(java.util.stream.Collectors.toList) IGNORE_STATS_CALCULATOR_FAILURES(io.trino.SystemSessionProperties.IGNORE_STATS_CALCULATOR_FAILURES) Assert.assertEventually(io.trino.testing.assertions.Assert.assertEventually) SUPPORTS_COMMENT_ON_TABLE(io.trino.testing.TestingConnectorBehavior.SUPPORTS_COMMENT_ON_TABLE) Metadata(io.trino.metadata.Metadata) Assert.assertTrue(org.testng.Assert.assertTrue) Plan(io.trino.sql.planner.Plan) SUPPORTS_NOT_NULL_CONSTRAINT(io.trino.testing.TestingConnectorBehavior.SUPPORTS_NOT_NULL_CONSTRAINT) SECONDS(java.util.concurrent.TimeUnit.SECONDS) MaterializedResult.resultBuilder(io.trino.testing.MaterializedResult.resultBuilder) DispatchManager(io.trino.dispatcher.DispatchManager) QueryManager(io.trino.execution.QueryManager) Duration(io.airlift.units.Duration) Test(org.testng.annotations.Test)

Example 5 with BasicQueryInfo

use of io.trino.server.BasicQueryInfo in project trino by trinodb.

the class TestMetadataManager method testMetadataIsClearedAfterQueryCanceled.

@Test
public void testMetadataIsClearedAfterQueryCanceled() throws Exception {
    DispatchManager dispatchManager = queryRunner.getCoordinator().getDispatchManager();
    QueryId queryId = dispatchManager.createQueryId();
    dispatchManager.createQuery(queryId, Slug.createNew(), TestingSessionContext.fromSession(TEST_SESSION), "SELECT * FROM lineitem").get();
    // wait until query starts running
    while (true) {
        BasicQueryInfo queryInfo = dispatchManager.getQueryInfo(queryId);
        if (queryInfo.getState().isDone()) {
            assertEquals(queryInfo.getState(), FAILED);
            throw dispatchManager.getDispatchInfo(queryId).get().getFailureInfo().get().toException();
        }
        if (queryInfo.getState() == RUNNING) {
            break;
        }
        Thread.sleep(100);
    }
    // cancel query
    dispatchManager.cancelQuery(queryId);
    assertEquals(metadataManager.getActiveQueryIds().size(), 0);
}
Also used : DispatchManager(io.trino.dispatcher.DispatchManager) QueryId(io.trino.spi.QueryId) BasicQueryInfo(io.trino.server.BasicQueryInfo) Test(org.testng.annotations.Test)

Aggregations

BasicQueryInfo (io.trino.server.BasicQueryInfo)20 Test (org.testng.annotations.Test)10 QueryId (io.trino.spi.QueryId)7 QueryManager (io.trino.execution.QueryManager)6 DistributedQueryRunner (io.trino.testing.DistributedQueryRunner)5 DispatchManager (io.trino.dispatcher.DispatchManager)4 ImmutableList (com.google.common.collect.ImmutableList)3 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)3 Session (io.trino.Session)3 TestingTrinoServer (io.trino.server.testing.TestingTrinoServer)3 Preconditions.checkState (com.google.common.base.Preconditions.checkState)2 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)2 QueryState (io.trino.execution.QueryState)2 ResourceSecurity (io.trino.server.security.ResourceSecurity)2 String.format (java.lang.String.format)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Objects.requireNonNull (java.util.Objects.requireNonNull)2 SECONDS (java.util.concurrent.TimeUnit.SECONDS)2 GET (javax.ws.rs.GET)2