Search in sources :

Example 1 with QueryInfo

use of com.facebook.presto.execution.QueryInfo in project presto by prestodb.

the class TestMemoryManager method testClusterPools.

@Test(timeOut = 240_000)
public void testClusterPools() throws Exception {
    Map<String, String> properties = ImmutableMap.<String, String>builder().put("task.verbose-stats", "true").build();
    try (DistributedQueryRunner queryRunner = createQueryRunner(TINY_SESSION, properties)) {
        // Reserve all the memory
        QueryId fakeQueryId = new QueryId("fake");
        for (TestingPrestoServer server : queryRunner.getServers()) {
            for (MemoryPool pool : server.getLocalMemoryManager().getPools()) {
                assertTrue(pool.tryReserve(fakeQueryId, pool.getMaxBytes()));
            }
        }
        List<Future<?>> queryFutures = new ArrayList<>();
        for (int i = 0; i < 2; i++) {
            queryFutures.add(executor.submit(() -> queryRunner.execute("SELECT COUNT(*), clerk FROM orders GROUP BY clerk")));
        }
        ClusterMemoryManager memoryManager = queryRunner.getCoordinator().getClusterMemoryManager();
        ClusterMemoryPool reservedPool;
        while ((reservedPool = memoryManager.getPools().get(RESERVED_POOL)) == null) {
            MILLISECONDS.sleep(10);
        }
        ClusterMemoryPool generalPool = memoryManager.getPools().get(GENERAL_POOL);
        assertNotNull(generalPool);
        // Wait for the queries to start running and get assigned to the expected pools
        while (generalPool.getAssignedQueries() != 1 || reservedPool.getAssignedQueries() != 1 || generalPool.getBlockedNodes() != 2 || reservedPool.getBlockedNodes() != 2) {
            MILLISECONDS.sleep(10);
        }
        // Make sure the queries are blocked
        List<QueryInfo> currentQueryInfos = queryRunner.getCoordinator().getQueryManager().getAllQueryInfo();
        for (QueryInfo info : currentQueryInfos) {
            assertFalse(info.getState().isDone());
        }
        assertEquals(currentQueryInfos.size(), 2);
        // Check that the pool information propagated to the query objects
        assertNotEquals(currentQueryInfos.get(0).getMemoryPool(), currentQueryInfos.get(1).getMemoryPool());
        while (!allQueriesBlocked(currentQueryInfos)) {
            MILLISECONDS.sleep(10);
            currentQueryInfos = queryRunner.getCoordinator().getQueryManager().getAllQueryInfo();
            for (QueryInfo info : currentQueryInfos) {
                assertFalse(info.getState().isDone());
            }
        }
        // Release the memory in the reserved pool and the system pool
        for (TestingPrestoServer server : queryRunner.getServers()) {
            MemoryPool reserved = server.getLocalMemoryManager().getPool(RESERVED_POOL);
            // Free up the entire pool
            reserved.free(fakeQueryId, reserved.getMaxBytes());
            assertTrue(reserved.getFreeBytes() > 0);
            MemoryPool system = server.getLocalMemoryManager().getPool(SYSTEM_POOL);
            // Free up the entire pool
            system.free(fakeQueryId, system.getMaxBytes());
            assertTrue(system.getFreeBytes() > 0);
        }
        // This also checks that the query in the general pool is successfully moved to the reserved pool.
        for (Future<?> query : queryFutures) {
            query.get();
        }
        List<QueryInfo> queryInfos = queryRunner.getCoordinator().getQueryManager().getAllQueryInfo();
        for (QueryInfo info : queryInfos) {
            assertEquals(info.getState(), FINISHED);
        }
        // Make sure we didn't leak any memory on the workers
        for (TestingPrestoServer worker : queryRunner.getServers()) {
            MemoryPool reserved = worker.getLocalMemoryManager().getPool(RESERVED_POOL);
            assertEquals(reserved.getMaxBytes(), reserved.getFreeBytes());
            MemoryPool general = worker.getLocalMemoryManager().getPool(GENERAL_POOL);
            // Free up the memory we reserved earlier
            general.free(fakeQueryId, general.getMaxBytes());
            assertEquals(general.getMaxBytes(), general.getFreeBytes());
            MemoryPool system = worker.getLocalMemoryManager().getPool(SYSTEM_POOL);
            assertEquals(system.getMaxBytes(), system.getFreeBytes());
        }
    }
}
Also used : DistributedQueryRunner(com.facebook.presto.tests.DistributedQueryRunner) QueryId(com.facebook.presto.spi.QueryId) TestingPrestoServer(com.facebook.presto.server.testing.TestingPrestoServer) ArrayList(java.util.ArrayList) QueryInfo(com.facebook.presto.execution.QueryInfo) Future(java.util.concurrent.Future) Test(org.testng.annotations.Test)

Example 2 with QueryInfo

use of com.facebook.presto.execution.QueryInfo in project presto by prestodb.

the class TestMemoryManager method testNoLeak.

private void testNoLeak(@Language("SQL") String query) throws Exception {
    Map<String, String> properties = ImmutableMap.<String, String>builder().put("task.verbose-stats", "true").build();
    try (DistributedQueryRunner queryRunner = createQueryRunner(TINY_SESSION, properties)) {
        executor.submit(() -> queryRunner.execute(query)).get();
        List<QueryInfo> queryInfos = queryRunner.getCoordinator().getQueryManager().getAllQueryInfo();
        for (QueryInfo info : queryInfos) {
            assertEquals(info.getState(), FINISHED);
        }
        // Make sure we didn't leak any memory on the workers
        for (TestingPrestoServer worker : queryRunner.getServers()) {
            MemoryPool reserved = worker.getLocalMemoryManager().getPool(RESERVED_POOL);
            assertEquals(reserved.getMaxBytes(), reserved.getFreeBytes());
            MemoryPool general = worker.getLocalMemoryManager().getPool(GENERAL_POOL);
            assertEquals(general.getMaxBytes(), general.getFreeBytes());
            MemoryPool system = worker.getLocalMemoryManager().getPool(SYSTEM_POOL);
            assertEquals(system.getMaxBytes(), system.getFreeBytes());
        }
    }
}
Also used : DistributedQueryRunner(com.facebook.presto.tests.DistributedQueryRunner) TestingPrestoServer(com.facebook.presto.server.testing.TestingPrestoServer) QueryInfo(com.facebook.presto.execution.QueryInfo)

Example 3 with QueryInfo

use of com.facebook.presto.execution.QueryInfo in project presto by prestodb.

the class QueryMonitor method queryCompletedEvent.

public void queryCompletedEvent(QueryInfo queryInfo) {
    try {
        Optional<QueryFailureInfo> queryFailureInfo = Optional.empty();
        if (queryInfo.getFailureInfo() != null) {
            FailureInfo failureInfo = queryInfo.getFailureInfo();
            Optional<TaskInfo> failedTask = queryInfo.getOutputStage().flatMap(QueryMonitor::findFailedTask);
            queryFailureInfo = Optional.of(new QueryFailureInfo(queryInfo.getErrorCode(), Optional.ofNullable(failureInfo.getType()), Optional.ofNullable(failureInfo.getMessage()), failedTask.map(task -> task.getTaskStatus().getTaskId().toString()), failedTask.map(task -> task.getTaskStatus().getSelf().getHost()), objectMapper.writeValueAsString(queryInfo.getFailureInfo())));
        }
        ImmutableList.Builder<QueryInputMetadata> inputs = ImmutableList.builder();
        for (Input input : queryInfo.getInputs()) {
            inputs.add(new QueryInputMetadata(input.getConnectorId().getCatalogName(), input.getSchema(), input.getTable(), input.getColumns().stream().map(Column::toString).collect(Collectors.toList()), input.getConnectorInfo()));
        }
        QueryStats queryStats = queryInfo.getQueryStats();
        Optional<QueryOutputMetadata> output = Optional.empty();
        if (queryInfo.getOutput().isPresent()) {
            Optional<TableFinishInfo> tableFinishInfo = queryStats.getOperatorSummaries().stream().map(OperatorStats::getInfo).filter(TableFinishInfo.class::isInstance).map(TableFinishInfo.class::cast).findFirst();
            output = Optional.of(new QueryOutputMetadata(queryInfo.getOutput().get().getConnectorId().getCatalogName(), queryInfo.getOutput().get().getSchema(), queryInfo.getOutput().get().getTable(), tableFinishInfo.map(TableFinishInfo::getConnectorOutputMetadata), tableFinishInfo.map(TableFinishInfo::isJsonLengthLimitExceeded)));
        }
        eventListenerManager.queryCompleted(new QueryCompletedEvent(new QueryMetadata(queryInfo.getQueryId().toString(), queryInfo.getSession().getTransactionId().map(TransactionId::toString), queryInfo.getQuery(), queryInfo.getState().toString(), queryInfo.getSelf(), queryInfo.getOutputStage().flatMap(stage -> stageInfoCodec.toJsonWithLengthLimit(stage, toIntExact(config.getMaxOutputStageJsonSize().toBytes())))), new QueryStatistics(ofMillis(queryStats.getTotalCpuTime().toMillis()), ofMillis(queryStats.getTotalScheduledTime().toMillis()), ofMillis(queryStats.getQueuedTime().toMillis()), Optional.ofNullable(queryStats.getAnalysisTime()).map(duration -> ofMillis(duration.toMillis())), Optional.ofNullable(queryStats.getDistributedPlanningTime()).map(duration -> ofMillis(duration.toMillis())), queryStats.getPeakMemoryReservation().toBytes(), queryStats.getRawInputDataSize().toBytes(), queryStats.getRawInputPositions(), queryStats.getCompletedDrivers(), queryInfo.isCompleteInfo(), objectMapper.writeValueAsString(queryInfo.getQueryStats().getOperatorSummaries())), new QueryContext(queryInfo.getSession().getUser(), queryInfo.getSession().getPrincipal(), queryInfo.getSession().getRemoteUserAddress(), queryInfo.getSession().getUserAgent(), queryInfo.getSession().getClientInfo(), queryInfo.getSession().getSource(), queryInfo.getSession().getCatalog(), queryInfo.getSession().getSchema(), mergeSessionAndCatalogProperties(queryInfo), serverAddress, serverVersion, environment), new QueryIOMetadata(inputs.build(), output), queryFailureInfo, ofEpochMilli(queryStats.getCreateTime().getMillis()), ofEpochMilli(queryStats.getExecutionStartTime().getMillis()), ofEpochMilli(queryStats.getEndTime().getMillis())));
        logQueryTimeline(queryInfo);
    } catch (JsonProcessingException e) {
        throw Throwables.propagate(e);
    }
}
Also used : TaskStats(com.facebook.presto.operator.TaskStats) QueryContext(com.facebook.presto.spi.eventlistener.QueryContext) NodeInfo(io.airlift.node.NodeInfo) TaskState(com.facebook.presto.execution.TaskState) NodeVersion(com.facebook.presto.client.NodeVersion) TableFinishInfo(com.facebook.presto.operator.TableFinishInfo) EventListenerManager(com.facebook.presto.eventlistener.EventListenerManager) QueryStatistics(com.facebook.presto.spi.eventlistener.QueryStatistics) OperatorStats(com.facebook.presto.operator.OperatorStats) StageInfo(com.facebook.presto.execution.StageInfo) Instant.ofEpochMilli(java.time.Instant.ofEpochMilli) Duration(java.time.Duration) Map(java.util.Map) QueryMetadata(com.facebook.presto.spi.eventlistener.QueryMetadata) TransactionId(com.facebook.presto.transaction.TransactionId) SplitStatistics(com.facebook.presto.spi.eventlistener.SplitStatistics) Column(com.facebook.presto.execution.Column) ImmutableMap(com.google.common.collect.ImmutableMap) SplitCompletedEvent(com.facebook.presto.spi.eventlistener.SplitCompletedEvent) Collectors(java.util.stream.Collectors) List(java.util.List) QueryCompletedEvent(com.facebook.presto.spi.eventlistener.QueryCompletedEvent) Input(com.facebook.presto.execution.Input) QueryInfo(com.facebook.presto.execution.QueryInfo) Optional(java.util.Optional) Math.max(java.lang.Math.max) ConnectorId(com.facebook.presto.connector.ConnectorId) Duration.ofMillis(java.time.Duration.ofMillis) QueryFailureInfo(com.facebook.presto.spi.eventlistener.QueryFailureInfo) JsonCodec(io.airlift.json.JsonCodec) DriverStats(com.facebook.presto.operator.DriverStats) QueryIOMetadata(com.facebook.presto.spi.eventlistener.QueryIOMetadata) Logger(io.airlift.log.Logger) Inject(javax.inject.Inject) ImmutableList(com.google.common.collect.ImmutableList) FailureInfo(com.facebook.presto.client.FailureInfo) Objects.requireNonNull(java.util.Objects.requireNonNull) Math.toIntExact(java.lang.Math.toIntExact) Nullable(javax.annotation.Nullable) QueryOutputMetadata(com.facebook.presto.spi.eventlistener.QueryOutputMetadata) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) DateTime(org.joda.time.DateTime) Throwables(com.google.common.base.Throwables) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) QueryInputMetadata(com.facebook.presto.spi.eventlistener.QueryInputMetadata) QueryStats(com.facebook.presto.execution.QueryStats) SplitFailureInfo(com.facebook.presto.spi.eventlistener.SplitFailureInfo) TaskId(com.facebook.presto.execution.TaskId) QueryCreatedEvent(com.facebook.presto.spi.eventlistener.QueryCreatedEvent) TaskInfo(com.facebook.presto.execution.TaskInfo) TableFinishInfo(com.facebook.presto.operator.TableFinishInfo) QueryMetadata(com.facebook.presto.spi.eventlistener.QueryMetadata) QueryCompletedEvent(com.facebook.presto.spi.eventlistener.QueryCompletedEvent) ImmutableList(com.google.common.collect.ImmutableList) QueryOutputMetadata(com.facebook.presto.spi.eventlistener.QueryOutputMetadata) QueryContext(com.facebook.presto.spi.eventlistener.QueryContext) QueryInputMetadata(com.facebook.presto.spi.eventlistener.QueryInputMetadata) QueryFailureInfo(com.facebook.presto.spi.eventlistener.QueryFailureInfo) TaskInfo(com.facebook.presto.execution.TaskInfo) Input(com.facebook.presto.execution.Input) QueryStats(com.facebook.presto.execution.QueryStats) QueryStatistics(com.facebook.presto.spi.eventlistener.QueryStatistics) QueryFailureInfo(com.facebook.presto.spi.eventlistener.QueryFailureInfo) FailureInfo(com.facebook.presto.client.FailureInfo) SplitFailureInfo(com.facebook.presto.spi.eventlistener.SplitFailureInfo) QueryIOMetadata(com.facebook.presto.spi.eventlistener.QueryIOMetadata) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 4 with QueryInfo

use of com.facebook.presto.execution.QueryInfo in project presto by prestodb.

the class QuerySystemTable method cursor.

@Override
public RecordCursor cursor(ConnectorTransactionHandle transactionHandle, ConnectorSession session, TupleDomain<Integer> constraint) {
    Builder table = InMemoryRecordSet.builder(QUERY_TABLE);
    for (QueryInfo queryInfo : queryManager.getAllQueryInfo()) {
        QueryStats queryStats = queryInfo.getQueryStats();
        table.addRow(nodeId, queryInfo.getQueryId().toString(), queryInfo.getState().toString(), queryInfo.getSession().getUser(), queryInfo.getSession().getSource().orElse(null), queryInfo.getQuery(), toMillis(queryStats.getQueuedTime()), toMillis(queryStats.getAnalysisTime()), toMillis(queryStats.getDistributedPlanningTime()), toTimeStamp(queryStats.getCreateTime()), toTimeStamp(queryStats.getExecutionStartTime()), toTimeStamp(queryStats.getLastHeartbeat()), toTimeStamp(queryStats.getEndTime()));
    }
    return table.build().cursor();
}
Also used : QueryStats(com.facebook.presto.execution.QueryStats) TableMetadataBuilder.tableMetadataBuilder(com.facebook.presto.metadata.MetadataUtil.TableMetadataBuilder.tableMetadataBuilder) Builder(com.facebook.presto.spi.InMemoryRecordSet.Builder) QueryInfo(com.facebook.presto.execution.QueryInfo)

Example 5 with QueryInfo

use of com.facebook.presto.execution.QueryInfo in project presto by prestodb.

the class ClusterStatsResource method getClusterStats.

@GET
@Produces(MediaType.APPLICATION_JSON)
public ClusterStats getClusterStats() {
    long runningQueries = 0;
    long blockedQueries = 0;
    long queuedQueries = 0;
    long activeNodes = nodeManager.getNodes(NodeState.ACTIVE).size();
    if (!isIncludeCoordinator) {
        activeNodes -= 1;
    }
    long runningDrivers = 0;
    double memoryReservation = 0;
    double rowInputRate = 0;
    double byteInputRate = 0;
    double cpuTimeRate = 0;
    for (QueryInfo query : queryManager.getAllQueryInfo()) {
        if (query.getState() == QueryState.QUEUED) {
            queuedQueries++;
        } else if (query.getState() == QueryState.RUNNING) {
            if (query.getQueryStats().isFullyBlocked()) {
                blockedQueries++;
            } else {
                runningQueries++;
            }
        }
        if (!query.getState().isDone()) {
            double totalExecutionTimeSeconds = query.getQueryStats().getElapsedTime().getValue(SECONDS);
            if (totalExecutionTimeSeconds != 0) {
                byteInputRate += query.getQueryStats().getProcessedInputDataSize().toBytes() / totalExecutionTimeSeconds;
                rowInputRate += query.getQueryStats().getProcessedInputPositions() / totalExecutionTimeSeconds;
                cpuTimeRate += (query.getQueryStats().getTotalCpuTime().getValue(SECONDS)) / totalExecutionTimeSeconds;
            }
            memoryReservation += query.getQueryStats().getTotalMemoryReservation().toBytes();
            runningDrivers += query.getQueryStats().getRunningDrivers();
        }
    }
    return new ClusterStats(runningQueries, blockedQueries, queuedQueries, activeNodes, runningDrivers, memoryReservation, rowInputRate, byteInputRate, cpuTimeRate);
}
Also used : QueryInfo(com.facebook.presto.execution.QueryInfo) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Aggregations

QueryInfo (com.facebook.presto.execution.QueryInfo)11 Test (org.testng.annotations.Test)5 TestingPrestoServer (com.facebook.presto.server.testing.TestingPrestoServer)4 QueryId (com.facebook.presto.spi.QueryId)4 QueryStats (com.facebook.presto.execution.QueryStats)3 DistributedQueryRunner (com.facebook.presto.tests.DistributedQueryRunner)3 ArrayList (java.util.ArrayList)3 StageInfo (com.facebook.presto.execution.StageInfo)2 TaskInfo (com.facebook.presto.execution.TaskInfo)2 ImmutableList (com.google.common.collect.ImmutableList)2 List (java.util.List)2 FailureInfo (com.facebook.presto.client.FailureInfo)1 NodeVersion (com.facebook.presto.client.NodeVersion)1 QueryResults (com.facebook.presto.client.QueryResults)1 ConnectorId (com.facebook.presto.connector.ConnectorId)1 EventListenerManager (com.facebook.presto.eventlistener.EventListenerManager)1 Column (com.facebook.presto.execution.Column)1 Input (com.facebook.presto.execution.Input)1 TaskId (com.facebook.presto.execution.TaskId)1 TaskManager (com.facebook.presto.execution.TaskManager)1