Search in sources :

Example 1 with TransactionId

use of com.facebook.presto.transaction.TransactionId 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 2 with TransactionId

use of com.facebook.presto.transaction.TransactionId in project presto by prestodb.

the class QueryMonitor method logQueryTimeline.

private static void logQueryTimeline(QueryInfo queryInfo) {
    try {
        QueryStats queryStats = queryInfo.getQueryStats();
        DateTime queryStartTime = queryStats.getCreateTime();
        DateTime queryEndTime = queryStats.getEndTime();
        // query didn't finish cleanly
        if (queryStartTime == null || queryEndTime == null) {
            return;
        }
        // planning duration -- start to end of planning
        long planning = queryStats.getTotalPlanningTime() == null ? 0 : queryStats.getTotalPlanningTime().toMillis();
        List<StageInfo> stages = StageInfo.getAllStages(queryInfo.getOutputStage());
        // long lastSchedulingCompletion = 0;
        long firstTaskStartTime = queryEndTime.getMillis();
        long lastTaskStartTime = queryStartTime.getMillis() + planning;
        long lastTaskEndTime = queryStartTime.getMillis() + planning;
        for (StageInfo stage : stages) {
            // only consider leaf stages
            if (!stage.getSubStages().isEmpty()) {
                continue;
            }
            for (TaskInfo taskInfo : stage.getTasks()) {
                TaskStats taskStats = taskInfo.getStats();
                DateTime firstStartTime = taskStats.getFirstStartTime();
                if (firstStartTime != null) {
                    firstTaskStartTime = Math.min(firstStartTime.getMillis(), firstTaskStartTime);
                }
                DateTime lastStartTime = taskStats.getLastStartTime();
                if (lastStartTime != null) {
                    lastTaskStartTime = max(lastStartTime.getMillis(), lastTaskStartTime);
                }
                DateTime endTime = taskStats.getEndTime();
                if (endTime != null) {
                    lastTaskEndTime = max(endTime.getMillis(), lastTaskEndTime);
                }
            }
        }
        long elapsed = queryEndTime.getMillis() - queryStartTime.getMillis();
        long scheduling = firstTaskStartTime - queryStartTime.getMillis() - planning;
        long running = lastTaskEndTime - firstTaskStartTime;
        long finishing = queryEndTime.getMillis() - lastTaskEndTime;
        log.info("TIMELINE: Query %s :: Transaction:[%s] :: elapsed %sms :: planning %sms :: scheduling %sms :: running %sms :: finishing %sms :: begin %s :: end %s", queryInfo.getQueryId(), queryInfo.getSession().getTransactionId().map(TransactionId::toString).orElse(""), max(elapsed, 0), max(planning, 0), max(scheduling, 0), max(running, 0), max(finishing, 0), queryStartTime, queryEndTime);
    } catch (Exception e) {
        log.error(e, "Error logging query timeline");
    }
}
Also used : TaskInfo(com.facebook.presto.execution.TaskInfo) QueryStats(com.facebook.presto.execution.QueryStats) StageInfo(com.facebook.presto.execution.StageInfo) TaskStats(com.facebook.presto.operator.TaskStats) DateTime(org.joda.time.DateTime) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) TransactionId(com.facebook.presto.transaction.TransactionId)

Example 3 with TransactionId

use of com.facebook.presto.transaction.TransactionId in project presto by prestodb.

the class TestInformationSchemaMetadata method testInformationSchemaPredicatePushdown.

/**
 * Tests information schema predicate pushdown when both schema and table name are specified.
 */
@Test
public void testInformationSchemaPredicatePushdown() {
    TransactionId transactionId = transactionManager.beginTransaction(false);
    ImmutableMap.Builder<ColumnHandle, Domain> domains = new ImmutableMap.Builder<>();
    domains.put(new InformationSchemaColumnHandle("table_schema"), Domain.singleValue(VARCHAR, Slices.utf8Slice("test_schema")));
    domains.put(new InformationSchemaColumnHandle("table_name"), Domain.singleValue(VARCHAR, Slices.utf8Slice("test_view")));
    Constraint<ColumnHandle> constraint = new Constraint<>(TupleDomain.withColumnDomains(domains.build()));
    InformationSchemaMetadata informationSchemaMetadata = new InformationSchemaMetadata("test_catalog", metadata);
    List<ConnectorTableLayoutResult> layoutResults = informationSchemaMetadata.getTableLayouts(createNewSession(transactionId), new InformationSchemaTableHandle("test_catalog", "information_schema", "views"), constraint, Optional.empty());
    assertEquals(layoutResults.size(), 1);
    ConnectorTableLayoutHandle handle = layoutResults.get(0).getTableLayout().getHandle();
    assertTrue(handle instanceof InformationSchemaTableLayoutHandle);
    InformationSchemaTableLayoutHandle tableHandle = (InformationSchemaTableLayoutHandle) handle;
    assertEquals(tableHandle.getPrefixes(), ImmutableSet.of(new QualifiedTablePrefix("test_catalog", "test_schema", "test_view")));
}
Also used : InformationSchemaColumnHandle(com.facebook.presto.connector.informationSchema.InformationSchemaColumnHandle) ColumnHandle(com.facebook.presto.spi.ColumnHandle) ConnectorTableLayoutHandle(com.facebook.presto.spi.ConnectorTableLayoutHandle) Constraint(com.facebook.presto.spi.Constraint) TestingSession.testSessionBuilder(com.facebook.presto.testing.TestingSession.testSessionBuilder) ImmutableMap(com.google.common.collect.ImmutableMap) TransactionId(com.facebook.presto.transaction.TransactionId) InformationSchemaTableHandle(com.facebook.presto.connector.informationSchema.InformationSchemaTableHandle) ConnectorTableLayoutResult(com.facebook.presto.spi.ConnectorTableLayoutResult) InformationSchemaColumnHandle(com.facebook.presto.connector.informationSchema.InformationSchemaColumnHandle) InformationSchemaTableLayoutHandle(com.facebook.presto.connector.informationSchema.InformationSchemaTableLayoutHandle) InformationSchemaMetadata(com.facebook.presto.connector.informationSchema.InformationSchemaMetadata) Domain(com.facebook.presto.common.predicate.Domain) TupleDomain(com.facebook.presto.common.predicate.TupleDomain) Test(org.testng.annotations.Test)

Example 4 with TransactionId

use of com.facebook.presto.transaction.TransactionId in project presto by prestodb.

the class QueryStateMachine method beginWithTicker.

static QueryStateMachine beginWithTicker(String query, Optional<String> preparedQuery, Session session, URI self, ResourceGroupId resourceGroup, Optional<QueryType> queryType, boolean transactionControl, TransactionManager transactionManager, AccessControl accessControl, Executor executor, Ticker ticker, Metadata metadata, WarningCollector warningCollector) {
    // If there is not an existing transaction, begin an auto commit transaction
    if (!session.getTransactionId().isPresent() && !transactionControl) {
        // TODO: make autocommit isolation level a session parameter
        TransactionId transactionId = transactionManager.beginTransaction(true);
        session = session.beginTransactionId(transactionId, transactionManager, accessControl);
    }
    QueryStateMachine queryStateMachine = new QueryStateMachine(query, preparedQuery, session, self, resourceGroup, queryType, transactionManager, executor, ticker, metadata, warningCollector);
    queryStateMachine.addStateChangeListener(newState -> {
        QUERY_STATE_LOG.debug("Query %s is %s", queryStateMachine.getQueryId(), newState);
        // mark finished or failed transaction as inactive
        if (newState.isDone()) {
            queryStateMachine.getSession().getTransactionId().ifPresent(transactionManager::trySetInactive);
        }
    });
    return queryStateMachine;
}
Also used : TransactionId(com.facebook.presto.transaction.TransactionId)

Example 5 with TransactionId

use of com.facebook.presto.transaction.TransactionId in project presto by prestodb.

the class RollbackTask method execute.

@Override
public ListenableFuture<?> execute(Rollback statement, TransactionManager transactionManager, Metadata metadata, AccessControl accessControl, QueryStateMachine stateMachine, List<Expression> parameters) {
    Session session = stateMachine.getSession();
    if (!session.getTransactionId().isPresent()) {
        throw new PrestoException(NOT_IN_TRANSACTION, "No transaction in progress");
    }
    TransactionId transactionId = session.getTransactionId().get();
    stateMachine.clearTransactionId();
    transactionManager.asyncAbort(transactionId);
    return immediateFuture(null);
}
Also used : PrestoException(com.facebook.presto.spi.PrestoException) Session(com.facebook.presto.Session) TransactionId(com.facebook.presto.transaction.TransactionId)

Aggregations

TransactionId (com.facebook.presto.transaction.TransactionId)17 Session (com.facebook.presto.Session)5 Test (org.testng.annotations.Test)5 PrestoException (com.facebook.presto.spi.PrestoException)4 DateTime (org.joda.time.DateTime)4 QueryStats (com.facebook.presto.execution.QueryStats)3 StageInfo (com.facebook.presto.execution.StageInfo)3 TaskInfo (com.facebook.presto.execution.TaskInfo)3 TaskStats (com.facebook.presto.operator.TaskStats)3 InformationSchemaColumnHandle (com.facebook.presto.connector.informationSchema.InformationSchemaColumnHandle)2 InformationSchemaMetadata (com.facebook.presto.connector.informationSchema.InformationSchemaMetadata)2 InformationSchemaTableHandle (com.facebook.presto.connector.informationSchema.InformationSchemaTableHandle)2 InformationSchemaTableLayoutHandle (com.facebook.presto.connector.informationSchema.InformationSchemaTableLayoutHandle)2 QueryInfo (com.facebook.presto.execution.QueryInfo)2 ColumnHandle (com.facebook.presto.spi.ColumnHandle)2 ConnectorTableLayoutHandle (com.facebook.presto.spi.ConnectorTableLayoutHandle)2 ConnectorTableLayoutResult (com.facebook.presto.spi.ConnectorTableLayoutResult)2 Constraint (com.facebook.presto.spi.Constraint)2 QueryId (com.facebook.presto.spi.QueryId)2 DelegatingTransactionManager (com.facebook.presto.transaction.DelegatingTransactionManager)2