Search in sources :

Example 1 with QueryStats

use of com.facebook.presto.jdbc.QueryStats in project presto by prestodb.

the class Validator method executeQuery.

private QueryResult executeQuery(String url, String username, String password, Query query, String sql, Duration timeout, Map<String, String> sessionProperties) {
    String queryId = null;
    try (Connection connection = DriverManager.getConnection(url, username, password)) {
        trySetConnectionProperties(query, connection);
        for (Map.Entry<String, String> entry : sessionProperties.entrySet()) {
            connection.unwrap(PrestoConnection.class).setSessionProperty(entry.getKey(), entry.getValue());
        }
        try (Statement statement = connection.createStatement()) {
            TimeLimiter limiter = new SimpleTimeLimiter();
            Stopwatch stopwatch = Stopwatch.createStarted();
            Statement limitedStatement = limiter.newProxy(statement, Statement.class, timeout.toMillis(), TimeUnit.MILLISECONDS);
            if (explainOnly) {
                sql = "EXPLAIN " + sql;
            }
            long start = System.nanoTime();
            PrestoStatement prestoStatement = limitedStatement.unwrap(PrestoStatement.class);
            ProgressMonitor progressMonitor = new ProgressMonitor();
            prestoStatement.setProgressMonitor(progressMonitor);
            try {
                boolean isSelectQuery = limitedStatement.execute(sql);
                List<List<Object>> results = null;
                if (isSelectQuery) {
                    results = limiter.callWithTimeout(getResultSetConverter(limitedStatement.getResultSet()), timeout.toMillis() - stopwatch.elapsed(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS, true);
                } else {
                    results = ImmutableList.of(ImmutableList.of(limitedStatement.getLargeUpdateCount()));
                }
                prestoStatement.clearProgressMonitor();
                QueryStats queryStats = progressMonitor.getFinalQueryStats();
                if (queryStats == null) {
                    throw new VerifierException("Cannot fetch query stats");
                }
                Duration queryCpuTime = new Duration(queryStats.getCpuTimeMillis(), TimeUnit.MILLISECONDS);
                queryId = queryStats.getQueryId();
                return new QueryResult(State.SUCCESS, null, nanosSince(start), queryCpuTime, queryId, results);
            } catch (AssertionError e) {
                if (e.getMessage().startsWith("unimplemented type:")) {
                    return new QueryResult(State.INVALID, null, null, null, queryId, ImmutableList.of());
                }
                throw e;
            } catch (SQLException | VerifierException e) {
                throw e;
            } catch (UncheckedTimeoutException e) {
                return new QueryResult(State.TIMEOUT, null, null, null, queryId, ImmutableList.of());
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw Throwables.propagate(e);
            } catch (Exception e) {
                throw Throwables.propagate(e);
            }
        }
    } catch (SQLException e) {
        Exception exception = e;
        if (("Error executing query".equals(e.getMessage()) || "Error fetching results".equals(e.getMessage())) && (e.getCause() instanceof Exception)) {
            exception = (Exception) e.getCause();
        }
        State state = isPrestoQueryInvalid(e) ? State.INVALID : State.FAILED;
        return new QueryResult(state, exception, null, null, null, null);
    } catch (VerifierException e) {
        return new QueryResult(State.TOO_MANY_ROWS, e, null, null, null, null);
    }
}
Also used : SQLException(java.sql.SQLException) Stopwatch(com.google.common.base.Stopwatch) UncheckedTimeoutException(com.google.common.util.concurrent.UncheckedTimeoutException) PrestoStatement(com.facebook.presto.jdbc.PrestoStatement) Collections.unmodifiableList(java.util.Collections.unmodifiableList) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List) SimpleTimeLimiter(com.google.common.util.concurrent.SimpleTimeLimiter) TimeLimiter(com.google.common.util.concurrent.TimeLimiter) PrestoStatement(com.facebook.presto.jdbc.PrestoStatement) Statement(java.sql.Statement) Connection(java.sql.Connection) PrestoConnection(com.facebook.presto.jdbc.PrestoConnection) Duration(io.airlift.units.Duration) PrestoConnection(com.facebook.presto.jdbc.PrestoConnection) SQLClientInfoException(java.sql.SQLClientInfoException) SQLException(java.sql.SQLException) UncheckedTimeoutException(com.google.common.util.concurrent.UncheckedTimeoutException) QueryStats(com.facebook.presto.jdbc.QueryStats) State(com.facebook.presto.verifier.QueryResult.State) Preconditions.checkState(com.google.common.base.Preconditions.checkState) Map(java.util.Map) SimpleTimeLimiter(com.google.common.util.concurrent.SimpleTimeLimiter)

Example 2 with QueryStats

use of com.facebook.presto.jdbc.QueryStats in project presto by prestodb.

the class DeterminismAnalyzer method analyze.

private DeterminismAnalysis analyze(QueryObjectBundle control, ChecksumResult controlChecksum, DeterminismAnalysisDetails.Builder determinismAnalysisDetails) {
    // Handle mutable catalogs
    if (isNonDeterministicCatalogReferenced(control.getQuery())) {
        return NON_DETERMINISTIC_CATALOG;
    }
    // Handle limit query
    LimitQueryDeterminismAnalysis limitQueryAnalysis = new LimitQueryDeterminismAnalyzer(prestoAction, handleLimitQuery, control.getQuery(), controlChecksum.getRowCount(), determinismAnalysisDetails).analyze();
    switch(limitQueryAnalysis) {
        case NOT_RUN:
        case FAILED_QUERY_FAILURE:
        case DETERMINISTIC:
            // try the next analysis
            break;
        case NON_DETERMINISTIC:
            return NON_DETERMINISTIC_LIMIT_CLAUSE;
        case FAILED_DATA_CHANGED:
            return ANALYSIS_FAILED_DATA_CHANGED;
        default:
            throw new IllegalArgumentException(format("Invalid limitQueryAnalysis: %s", limitQueryAnalysis));
    }
    // Rerun control query multiple times
    List<Column> columns = getColumns(prestoAction, typeManager, control.getObjectName());
    Map<QueryBundle, DeterminismAnalysisRun.Builder> queryRuns = new HashMap<>();
    try {
        for (int i = 0; i < maxAnalysisRuns; i++) {
            QueryObjectBundle queryBundle = queryRewriter.rewriteQuery(sourceQuery.getQuery(CONTROL), CONTROL);
            DeterminismAnalysisRun.Builder run = determinismAnalysisDetails.addRun().setTableName(queryBundle.getObjectName().toString());
            queryRuns.put(queryBundle, run);
            // Rerun setup and main query
            queryBundle.getSetupQueries().forEach(query -> runAndConsume(() -> prestoAction.execute(query, DETERMINISM_ANALYSIS_SETUP), stats -> stats.getQueryStats().map(QueryStats::getQueryId).ifPresent(run::addSetupQueryId)));
            runAndConsume(() -> prestoAction.execute(queryBundle.getQuery(), DETERMINISM_ANALYSIS_MAIN), stats -> stats.getQueryStats().map(QueryStats::getQueryId).ifPresent(run::setQueryId));
            // Run checksum query
            Query checksumQuery = checksumValidator.generateChecksumQuery(queryBundle.getObjectName(), columns);
            ChecksumResult testChecksum = getOnlyElement(callAndConsume(() -> prestoAction.execute(checksumQuery, DETERMINISM_ANALYSIS_CHECKSUM, ChecksumResult::fromResultSet), stats -> stats.getQueryStats().map(QueryStats::getQueryId).ifPresent(run::setChecksumQueryId)).getResults());
            DeterminismAnalysis analysis = matchResultToDeterminism(match(checksumValidator, columns, columns, controlChecksum, testChecksum));
            if (analysis != DETERMINISTIC) {
                return analysis;
            }
        }
        return DETERMINISTIC;
    } catch (QueryException qe) {
        return ANALYSIS_FAILED_QUERY_FAILURE;
    } finally {
        if (runTeardown) {
            queryRuns.forEach((queryBundle, run) -> teardownSafely(prestoAction, Optional.of(queryBundle), queryStats -> queryStats.getQueryStats().map(QueryStats::getQueryId).ifPresent(run::addTeardownQueryId)));
        }
    }
}
Also used : NON_DETERMINISTIC_ROW_COUNT(com.facebook.presto.verifier.framework.DeterminismAnalysis.NON_DETERMINISTIC_ROW_COUNT) Table(com.facebook.presto.sql.tree.Table) DataVerificationUtil.match(com.facebook.presto.verifier.framework.DataVerificationUtil.match) ANALYSIS_FAILED_DATA_CHANGED(com.facebook.presto.verifier.framework.DeterminismAnalysis.ANALYSIS_FAILED_DATA_CHANGED) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) DETERMINISTIC(com.facebook.presto.verifier.framework.DeterminismAnalysis.DETERMINISTIC) VerifierUtil.callAndConsume(com.facebook.presto.verifier.framework.VerifierUtil.callAndConsume) NON_DETERMINISTIC_CATALOG(com.facebook.presto.verifier.framework.DeterminismAnalysis.NON_DETERMINISTIC_CATALOG) NON_DETERMINISTIC_COLUMNS(com.facebook.presto.verifier.framework.DeterminismAnalysis.NON_DETERMINISTIC_COLUMNS) DataVerificationUtil.getColumns(com.facebook.presto.verifier.framework.DataVerificationUtil.getColumns) TypeManager(com.facebook.presto.common.type.TypeManager) Map(java.util.Map) Objects.requireNonNull(java.util.Objects.requireNonNull) QueryStats(com.facebook.presto.jdbc.QueryStats) ANALYSIS_FAILED_INCONSISTENT_SCHEMA(com.facebook.presto.verifier.framework.DeterminismAnalysis.ANALYSIS_FAILED_INCONSISTENT_SCHEMA) QueryRewriter(com.facebook.presto.verifier.rewrite.QueryRewriter) DETERMINISM_ANALYSIS_SETUP(com.facebook.presto.verifier.framework.QueryStage.DETERMINISM_ANALYSIS_SETUP) DeterminismAnalysisRun(com.facebook.presto.verifier.event.DeterminismAnalysisRun) ANALYSIS_FAILED_QUERY_FAILURE(com.facebook.presto.verifier.framework.DeterminismAnalysis.ANALYSIS_FAILED_QUERY_FAILURE) DETERMINISM_ANALYSIS_CHECKSUM(com.facebook.presto.verifier.framework.QueryStage.DETERMINISM_ANALYSIS_CHECKSUM) ImmutableSet(com.google.common.collect.ImmutableSet) DataVerificationUtil.teardownSafely(com.facebook.presto.verifier.framework.DataVerificationUtil.teardownSafely) Query(com.facebook.presto.sql.tree.Query) Node(com.facebook.presto.sql.tree.Node) AstVisitor(com.facebook.presto.sql.tree.AstVisitor) Set(java.util.Set) Iterables.getOnlyElement(com.google.common.collect.Iterables.getOnlyElement) CONTROL(com.facebook.presto.verifier.framework.ClusterType.CONTROL) String.format(java.lang.String.format) ChecksumResult(com.facebook.presto.verifier.checksum.ChecksumResult) DeterminismAnalysisDetails(com.facebook.presto.verifier.event.DeterminismAnalysisDetails) List(java.util.List) VerifierUtil.runAndConsume(com.facebook.presto.verifier.framework.VerifierUtil.runAndConsume) ChecksumValidator(com.facebook.presto.verifier.checksum.ChecksumValidator) PrestoAction(com.facebook.presto.verifier.prestoaction.PrestoAction) Optional(java.util.Optional) VisibleForTesting(com.google.common.annotations.VisibleForTesting) NON_DETERMINISTIC_LIMIT_CLAUSE(com.facebook.presto.verifier.framework.DeterminismAnalysis.NON_DETERMINISTIC_LIMIT_CLAUSE) DETERMINISM_ANALYSIS_MAIN(com.facebook.presto.verifier.framework.QueryStage.DETERMINISM_ANALYSIS_MAIN) Statement(com.facebook.presto.sql.tree.Statement) ChecksumResult(com.facebook.presto.verifier.checksum.ChecksumResult) Query(com.facebook.presto.sql.tree.Query) HashMap(java.util.HashMap) QueryStats(com.facebook.presto.jdbc.QueryStats) DeterminismAnalysisRun(com.facebook.presto.verifier.event.DeterminismAnalysisRun)

Example 3 with QueryStats

use of com.facebook.presto.jdbc.QueryStats in project presto by prestodb.

the class LimitQueryDeterminismAnalyzer method analyzeLimitNoOrderBy.

private LimitQueryDeterminismAnalysis analyzeLimitNoOrderBy(Query newLimitQuery, long limit) {
    Query rowCountQuery = simpleQuery(new Select(false, ImmutableList.of(new SingleColumn(new FunctionCall(QualifiedName.of("count"), ImmutableList.of(new LongLiteral("1")))))), new TableSubquery(newLimitQuery));
    QueryResult<Long> result = callAndConsume(() -> prestoAction.execute(rowCountQuery, DETERMINISM_ANALYSIS_MAIN, resultSet -> Optional.of(resultSet.getLong(1))), stats -> stats.getQueryStats().map(QueryStats::getQueryId).ifPresent(determinismAnalysisDetails::setLimitQueryAnalysisQueryId));
    long rowCountHigherLimit = getOnlyElement(result.getResults());
    if (rowCountHigherLimit == rowCount) {
        return DETERMINISTIC;
    }
    if (rowCountHigherLimit > rowCount) {
        return NON_DETERMINISTIC;
    }
    return FAILED_DATA_CHANGED;
}
Also used : QualifiedName(com.facebook.presto.sql.tree.QualifiedName) NOT_RUN(com.facebook.presto.verifier.framework.LimitQueryDeterminismAnalysis.NOT_RUN) SingleColumn(com.facebook.presto.sql.tree.SingleColumn) ArrayList(java.util.ArrayList) VerifierUtil.callAndConsume(com.facebook.presto.verifier.framework.VerifierUtil.callAndConsume) Identifier(com.facebook.presto.sql.tree.Identifier) SQLException(java.sql.SQLException) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) ImmutableList(com.google.common.collect.ImmutableList) ResultSet(java.sql.ResultSet) SelectItem(com.facebook.presto.sql.tree.SelectItem) Map(java.util.Map) Objects.requireNonNull(java.util.Objects.requireNonNull) QueryStats(com.facebook.presto.jdbc.QueryStats) TableSubquery(com.facebook.presto.sql.tree.TableSubquery) DETERMINISTIC(com.facebook.presto.verifier.framework.LimitQueryDeterminismAnalysis.DETERMINISTIC) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) Math.toIntExact(java.lang.Math.toIntExact) NON_DETERMINISTIC(com.facebook.presto.verifier.framework.LimitQueryDeterminismAnalysis.NON_DETERMINISTIC) ENGLISH(java.util.Locale.ENGLISH) FunctionCall(com.facebook.presto.sql.tree.FunctionCall) CreateTableAsSelect(com.facebook.presto.sql.tree.CreateTableAsSelect) OrderBy(com.facebook.presto.sql.tree.OrderBy) Query(com.facebook.presto.sql.tree.Query) QuerySpecification(com.facebook.presto.sql.tree.QuerySpecification) With(com.facebook.presto.sql.tree.With) Set(java.util.Set) VerifierUtil.getColumnIndices(com.facebook.presto.verifier.framework.VerifierUtil.getColumnIndices) Iterables.getOnlyElement(com.google.common.collect.Iterables.getOnlyElement) ResultSetConverter(com.facebook.presto.verifier.prestoaction.PrestoAction.ResultSetConverter) String.format(java.lang.String.format) Preconditions.checkState(com.google.common.base.Preconditions.checkState) Insert(com.facebook.presto.sql.tree.Insert) Objects(java.util.Objects) DeterminismAnalysisDetails(com.facebook.presto.verifier.event.DeterminismAnalysisDetails) List(java.util.List) Expression(com.facebook.presto.sql.tree.Expression) FAILED_DATA_CHANGED(com.facebook.presto.verifier.framework.LimitQueryDeterminismAnalysis.FAILED_DATA_CHANGED) FAILED_QUERY_FAILURE(com.facebook.presto.verifier.framework.LimitQueryDeterminismAnalysis.FAILED_QUERY_FAILURE) PrestoAction(com.facebook.presto.verifier.prestoaction.PrestoAction) LongLiteral(com.facebook.presto.sql.tree.LongLiteral) Optional(java.util.Optional) VerifierUtil.delimitedIdentifier(com.facebook.presto.verifier.framework.VerifierUtil.delimitedIdentifier) Select(com.facebook.presto.sql.tree.Select) Long.parseLong(java.lang.Long.parseLong) DETERMINISM_ANALYSIS_MAIN(com.facebook.presto.verifier.framework.QueryStage.DETERMINISM_ANALYSIS_MAIN) Statement(com.facebook.presto.sql.tree.Statement) QueryUtil.simpleQuery(com.facebook.presto.sql.QueryUtil.simpleQuery) Query(com.facebook.presto.sql.tree.Query) QueryUtil.simpleQuery(com.facebook.presto.sql.QueryUtil.simpleQuery) LongLiteral(com.facebook.presto.sql.tree.LongLiteral) QueryStats(com.facebook.presto.jdbc.QueryStats) CreateTableAsSelect(com.facebook.presto.sql.tree.CreateTableAsSelect) Select(com.facebook.presto.sql.tree.Select) Long.parseLong(java.lang.Long.parseLong) SingleColumn(com.facebook.presto.sql.tree.SingleColumn) FunctionCall(com.facebook.presto.sql.tree.FunctionCall) TableSubquery(com.facebook.presto.sql.tree.TableSubquery)

Example 4 with QueryStats

use of com.facebook.presto.jdbc.QueryStats in project presto by prestodb.

the class AbstractPhaseExecutor method runQuery.

protected BenchmarkQueryEvent runQuery(BenchmarkQuery benchmarkQuery) {
    Optional<QueryStats> queryStats = Optional.empty();
    Statement statement = sqlParser.createStatement(benchmarkQuery.getQuery(), parsingOptions);
    PrestoAction prestoAction = prestoActionFactory.get(benchmarkQuery);
    try {
        queryStats = Optional.of(prestoAction.execute(statement));
        return buildEvent(benchmarkQuery, queryStats, Optional.empty());
    } catch (QueryException e) {
        return buildEvent(benchmarkQuery, queryStats, Optional.of(e));
    } catch (Throwable t) {
        log.error(t);
        return buildEvent(benchmarkQuery, queryStats, Optional.empty());
    }
}
Also used : PrestoAction(com.facebook.presto.benchmark.prestoaction.PrestoAction) QueryStats(com.facebook.presto.jdbc.QueryStats) Statement(com.facebook.presto.sql.tree.Statement)

Example 5 with QueryStats

use of com.facebook.presto.jdbc.QueryStats in project presto by prestodb.

the class TooManyOpenPartitionsFailureResolver method resolveQueryFailure.

@Override
public Optional<String> resolveQueryFailure(QueryStats controlQueryStats, QueryException queryException, Optional<QueryObjectBundle> test) {
    if (!test.isPresent()) {
        return Optional.empty();
    }
    return mapMatchingPrestoException(queryException, TEST_MAIN, ImmutableSet.of(HIVE_TOO_MANY_OPEN_PARTITIONS), e -> {
        try {
            ShowCreate showCreate = new ShowCreate(TABLE, test.get().getObjectName());
            String showCreateResult = getOnlyElement(prestoAction.execute(showCreate, DESCRIBE, resultSet -> Optional.of(resultSet.getString(1))).getResults());
            CreateTable createTable = (CreateTable) sqlParser.createStatement(showCreateResult, ParsingOptions.builder().setDecimalLiteralTreatment(AS_DOUBLE).build());
            List<Property> bucketCountProperty = createTable.getProperties().stream().filter(property -> property.getName().getValue().equals(BUCKET_COUNT_PROPERTY)).collect(toImmutableList());
            if (bucketCountProperty.size() != 1) {
                return Optional.empty();
            }
            long bucketCount = ((LongLiteral) getOnlyElement(bucketCountProperty).getValue()).getValue();
            int testClusterSize = this.testClusterSizeSupplier.get();
            if (testClusterSize * maxBucketPerWriter < bucketCount) {
                return Optional.of("Not enough workers on test cluster");
            }
            return Optional.empty();
        } catch (Throwable t) {
            log.warn(t, "Exception when resolving HIVE_TOO_MANY_OPEN_PARTITIONS");
            return Optional.empty();
        }
    });
}
Also used : Logger(com.facebook.airlift.log.Logger) TEST_MAIN(com.facebook.presto.verifier.framework.QueryStage.TEST_MAIN) Suppliers.memoizeWithExpiration(com.google.common.base.Suppliers.memoizeWithExpiration) Supplier(java.util.function.Supplier) Duration(io.airlift.units.Duration) Inject(javax.inject.Inject) QueryObjectBundle(com.facebook.presto.verifier.framework.QueryObjectBundle) DESCRIBE(com.facebook.presto.verifier.framework.QueryStage.DESCRIBE) Objects.requireNonNull(java.util.Objects.requireNonNull) QueryStats(com.facebook.presto.jdbc.QueryStats) CreateTable(com.facebook.presto.sql.tree.CreateTable) ForTest(com.facebook.presto.verifier.annotation.ForTest) Property(com.facebook.presto.sql.tree.Property) ImmutableSet(com.google.common.collect.ImmutableSet) FailureResolverUtil.mapMatchingPrestoException(com.facebook.presto.verifier.resolver.FailureResolverUtil.mapMatchingPrestoException) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) HIVE_TOO_MANY_OPEN_PARTITIONS(com.facebook.presto.hive.HiveErrorCode.HIVE_TOO_MANY_OPEN_PARTITIONS) Iterables.getOnlyElement(com.google.common.collect.Iterables.getOnlyElement) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) SqlParser(com.facebook.presto.sql.parser.SqlParser) QueryException(com.facebook.presto.verifier.framework.QueryException) List(java.util.List) AS_DOUBLE(com.facebook.presto.sql.parser.ParsingOptions.DecimalLiteralTreatment.AS_DOUBLE) BUCKET_COUNT_PROPERTY(com.facebook.presto.hive.HiveTableProperties.BUCKET_COUNT_PROPERTY) ShowCreate(com.facebook.presto.sql.tree.ShowCreate) PrestoAction(com.facebook.presto.verifier.prestoaction.PrestoAction) LongLiteral(com.facebook.presto.sql.tree.LongLiteral) Optional(java.util.Optional) ParsingOptions(com.facebook.presto.sql.parser.ParsingOptions) TABLE(com.facebook.presto.sql.tree.ShowCreate.Type.TABLE) LongLiteral(com.facebook.presto.sql.tree.LongLiteral) ShowCreate(com.facebook.presto.sql.tree.ShowCreate) CreateTable(com.facebook.presto.sql.tree.CreateTable) Property(com.facebook.presto.sql.tree.Property)

Aggregations

QueryStats (com.facebook.presto.jdbc.QueryStats)7 Statement (com.facebook.presto.sql.tree.Statement)4 List (java.util.List)4 Query (com.facebook.presto.sql.tree.Query)3 PrestoAction (com.facebook.presto.verifier.prestoaction.PrestoAction)3 Iterables.getOnlyElement (com.google.common.collect.Iterables.getOnlyElement)3 Map (java.util.Map)3 Objects.requireNonNull (java.util.Objects.requireNonNull)3 Optional (java.util.Optional)3 LongLiteral (com.facebook.presto.sql.tree.LongLiteral)2 DeterminismAnalysisDetails (com.facebook.presto.verifier.event.DeterminismAnalysisDetails)2 DETERMINISM_ANALYSIS_MAIN (com.facebook.presto.verifier.framework.QueryStage.DETERMINISM_ANALYSIS_MAIN)2 VerifierUtil.callAndConsume (com.facebook.presto.verifier.framework.VerifierUtil.callAndConsume)2 Preconditions.checkState (com.google.common.base.Preconditions.checkState)2 ImmutableList (com.google.common.collect.ImmutableList)2 String.format (java.lang.String.format)2 SQLException (java.sql.SQLException)2 ArrayList (java.util.ArrayList)2 Set (java.util.Set)2 Logger (com.facebook.airlift.log.Logger)1