Search in sources :

Example 1 with QueryManager

use of io.trino.execution.QueryManager 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 2 with QueryManager

use of io.trino.execution.QueryManager in project trino by trinodb.

the class TestLateMaterializationQueries method assertLazyQuery.

private void assertLazyQuery(@Language("SQL") String sql) {
    QueryManager queryManager = getDistributedQueryRunner().getCoordinator().getQueryManager();
    ResultWithQueryId<MaterializedResult> workProcessorResultResultWithQueryId = getDistributedQueryRunner().executeWithQueryId(lateMaterialization(), sql);
    QueryInfo workProcessorQueryInfo = queryManager.getFullQueryInfo(workProcessorResultResultWithQueryId.getQueryId());
    ResultWithQueryId<MaterializedResult> noWorkProcessorResultResultWithQueryId = getDistributedQueryRunner().executeWithQueryId(noLateMaterialization(), sql);
    QueryInfo noWorkProcessorQueryInfo = queryManager.getFullQueryInfo(noWorkProcessorResultResultWithQueryId.getQueryId());
    // ensure results are correct
    MaterializedResult expected = computeExpected(sql, workProcessorResultResultWithQueryId.getResult().getTypes());
    assertEqualsIgnoreOrder(workProcessorResultResultWithQueryId.getResult(), expected, "For query: \n " + sql);
    assertEqualsIgnoreOrder(noWorkProcessorResultResultWithQueryId.getResult(), expected, "For query: \n " + sql);
    // ensure work processor query processed less input data
    long workProcessorProcessedInputBytes = workProcessorQueryInfo.getQueryStats().getProcessedInputDataSize().toBytes();
    long noWorkProcessorProcessedInputBytes = noWorkProcessorQueryInfo.getQueryStats().getProcessedInputDataSize().toBytes();
    assertTrue(workProcessorProcessedInputBytes < noWorkProcessorProcessedInputBytes, "Expected work processor query to process less input data");
}
Also used : QueryManager(io.trino.execution.QueryManager) MaterializedResult(io.trino.testing.MaterializedResult) QueryInfo(io.trino.execution.QueryInfo)

Example 3 with QueryManager

use of io.trino.execution.QueryManager in project trino by trinodb.

the class TestQueuesDb method testSelectorPriority.

@Test(timeOut = 60_000)
public void testSelectorPriority() throws Exception {
    InternalResourceGroupManager<?> manager = queryRunner.getCoordinator().getResourceGroupManager().get();
    QueryManager queryManager = queryRunner.getCoordinator().getQueryManager();
    DbResourceGroupConfigurationManager dbConfigurationManager = (DbResourceGroupConfigurationManager) manager.getConfigurationManager();
    QueryId firstQuery = createQuery(queryRunner, dashboardSession(), LONG_LASTING_QUERY);
    waitForQueryState(queryRunner, firstQuery, RUNNING);
    Optional<ResourceGroupId> resourceGroup = queryManager.getFullQueryInfo(firstQuery).getResourceGroupId();
    assertTrue(resourceGroup.isPresent());
    assertEquals(resourceGroup.get().toString(), "global.user-user.dashboard-user");
    // create a new resource group that rejects all queries submitted to it
    dao.insertResourceGroup(8, "reject-all-queries", "1MB", 0, 0, 0, null, null, null, null, null, 3L, TEST_ENVIRONMENT);
    // add a new selector that has a higher priority than the existing dashboard selector and that routes queries to the "reject-all-queries" resource group
    dao.insertSelector(8, 200, "user.*", null, "(?i).*dashboard.*", null, null, null);
    // reload the configuration
    dbConfigurationManager.load();
    QueryId secondQuery = createQuery(queryRunner, dashboardSession(), LONG_LASTING_QUERY);
    waitForQueryState(queryRunner, secondQuery, FAILED);
    DispatchManager dispatchManager = queryRunner.getCoordinator().getDispatchManager();
    BasicQueryInfo basicQueryInfo = dispatchManager.getQueryInfo(secondQuery);
    assertEquals(basicQueryInfo.getErrorCode(), QUERY_QUEUE_FULL.toErrorCode());
}
Also used : DbResourceGroupConfigurationManager(io.trino.plugin.resourcegroups.db.DbResourceGroupConfigurationManager) ResourceGroupId(io.trino.spi.resourcegroups.ResourceGroupId) TestQueues.createResourceGroupId(io.trino.execution.TestQueues.createResourceGroupId) DispatchManager(io.trino.dispatcher.DispatchManager) QueryId(io.trino.spi.QueryId) BasicQueryInfo(io.trino.server.BasicQueryInfo) QueryManager(io.trino.execution.QueryManager) Test(org.testng.annotations.Test)

Example 4 with QueryManager

use of io.trino.execution.QueryManager in project trino by trinodb.

the class ExecutingStatementResource method getQuery.

protected Query getQuery(QueryId queryId, String slug, long token) {
    Query query = queries.get(queryId);
    if (query != null) {
        if (!query.isSlugValid(slug, token)) {
            throw queryNotFound();
        }
        return query;
    }
    // this is the first time the query has been accessed on this coordinator
    Session session;
    Slug querySlug;
    try {
        session = queryManager.getQuerySession(queryId);
        querySlug = queryManager.getQuerySlug(queryId);
        if (!querySlug.isValid(EXECUTING_QUERY, slug, token)) {
            throw queryNotFound();
        }
    } catch (NoSuchElementException e) {
        throw queryNotFound();
    }
    query = queries.computeIfAbsent(queryId, id -> Query.create(session, querySlug, queryManager, queryInfoUrlFactory.getQueryInfoUrl(queryId), directExchangeClientSupplier, responseExecutor, timeoutExecutor, blockEncodingSerde));
    return query;
}
Also used : QueryId(io.trino.spi.QueryId) ResourceSecurity(io.trino.server.security.ResourceSecurity) Produces(javax.ws.rs.Produces) QueryManager(io.trino.execution.QueryManager) Path(javax.ws.rs.Path) Duration(io.airlift.units.Duration) PreDestroy(javax.annotation.PreDestroy) MediaType(javax.ws.rs.core.MediaType) Executors.newSingleThreadScheduledExecutor(java.util.concurrent.Executors.newSingleThreadScheduledExecutor) QueryParam(javax.ws.rs.QueryParam) EXECUTING_QUERY(io.trino.server.protocol.Slug.Context.EXECUTING_QUERY) BoundedExecutor(io.airlift.concurrent.BoundedExecutor) QueryResults(io.trino.client.QueryResults) DELETE(javax.ws.rs.DELETE) Context(javax.ws.rs.core.Context) AsyncResponse(javax.ws.rs.container.AsyncResponse) NOT_FOUND(javax.ws.rs.core.Response.Status.NOT_FOUND) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Threads.threadsNamed(io.airlift.concurrent.Threads.threadsNamed) Suspended(javax.ws.rs.container.Suspended) MoreExecutors.directExecutor(com.google.common.util.concurrent.MoreExecutors.directExecutor) DirectExchangeClientSupplier(io.trino.operator.DirectExchangeClientSupplier) PUBLIC(io.trino.server.security.ResourceSecurity.AccessType.PUBLIC) DataSize(io.airlift.units.DataSize) Response(javax.ws.rs.core.Response) Entry(java.util.Map.Entry) WebApplicationException(javax.ws.rs.WebApplicationException) UriInfo(javax.ws.rs.core.UriInfo) AsyncResponseHandler.bindAsyncResponse(io.airlift.jaxrs.AsyncResponseHandler.bindAsyncResponse) Session(io.trino.Session) PathParam(javax.ws.rs.PathParam) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Logger(io.airlift.log.Logger) GET(javax.ws.rs.GET) MEGABYTE(io.airlift.units.DataSize.Unit.MEGABYTE) ConcurrentMap(java.util.concurrent.ConcurrentMap) Inject(javax.inject.Inject) Objects.requireNonNull(java.util.Objects.requireNonNull) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) NoSuchElementException(java.util.NoSuchElementException) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) ServerConfig(io.trino.server.ServerConfig) ProtocolHeaders(io.trino.client.ProtocolHeaders) UTF_8(java.nio.charset.StandardCharsets.UTF_8) TEXT_PLAIN_TYPE(javax.ws.rs.core.MediaType.TEXT_PLAIN_TYPE) ForStatementResource(io.trino.server.ForStatementResource) Futures(com.google.common.util.concurrent.Futures) URLEncoder(java.net.URLEncoder) Ordering(com.google.common.collect.Ordering) BlockEncodingSerde(io.trino.spi.block.BlockEncodingSerde) SECONDS(java.util.concurrent.TimeUnit.SECONDS) NoSuchElementException(java.util.NoSuchElementException) Session(io.trino.Session)

Example 5 with QueryManager

use of io.trino.execution.QueryManager in project trino by trinodb.

the class BaseDeltaLakeConnectorSmokeTest method testInputDataSize.

@Test
public void testInputDataSize() {
    DistributedQueryRunner queryRunner = (DistributedQueryRunner) getQueryRunner();
    queryRunner.installPlugin(new TestingHivePlugin());
    queryRunner.createCatalog("hive", "hive", ImmutableMap.of("hive.metastore.uri", dockerizedDataLake.getTestingHadoop().getMetastoreAddress(), "hive.allow-drop-table", "true"));
    String hiveTableName = "foo_hive";
    queryRunner.execute(format("CREATE TABLE hive.%s.%s (foo_id bigint, bar_id bigint, data varchar) WITH (format = 'PARQUET', external_location = '%s')", SCHEMA, hiveTableName, getLocationForTable(bucketName, "foo")));
    ResultWithQueryId<MaterializedResult> deltaResult = queryRunner.executeWithQueryId(broadcastJoinDistribution(true), "SELECT * FROM foo");
    assertEquals(deltaResult.getResult().getRowCount(), 2);
    ResultWithQueryId<MaterializedResult> hiveResult = queryRunner.executeWithQueryId(broadcastJoinDistribution(true), format("SELECT * FROM %s.%s.%s", "hive", SCHEMA, hiveTableName));
    assertEquals(hiveResult.getResult().getRowCount(), 2);
    QueryManager queryManager = queryRunner.getCoordinator().getQueryManager();
    assertThat(queryManager.getFullQueryInfo(deltaResult.getQueryId()).getQueryStats().getProcessedInputDataSize()).as("delta processed input data size").isGreaterThan(DataSize.ofBytes(0)).isEqualTo(queryManager.getFullQueryInfo(hiveResult.getQueryId()).getQueryStats().getProcessedInputDataSize());
    queryRunner.execute(format("DROP TABLE hive.%s.%s", SCHEMA, hiveTableName));
}
Also used : DistributedQueryRunner(io.trino.testing.DistributedQueryRunner) TestingHivePlugin(io.trino.plugin.hive.TestingHivePlugin) QueryManager(io.trino.execution.QueryManager) MaterializedResult(io.trino.testing.MaterializedResult) Test(org.testng.annotations.Test) BaseConnectorSmokeTest(io.trino.testing.BaseConnectorSmokeTest)

Aggregations

QueryManager (io.trino.execution.QueryManager)12 Test (org.testng.annotations.Test)10 BasicQueryInfo (io.trino.server.BasicQueryInfo)7 QueryId (io.trino.spi.QueryId)7 Session (io.trino.Session)5 DistributedQueryRunner (io.trino.testing.DistributedQueryRunner)5 DispatchManager (io.trino.dispatcher.DispatchManager)4 QueryInfo (io.trino.execution.QueryInfo)4 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)2 Futures (com.google.common.util.concurrent.Futures)2 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)2 Duration (io.airlift.units.Duration)2 DbResourceGroupConfigurationManager (io.trino.plugin.resourcegroups.db.DbResourceGroupConfigurationManager)2 Preconditions.checkState (com.google.common.base.Preconditions.checkState)1 Stopwatch (com.google.common.base.Stopwatch)1 Verify.verifyNotNull (com.google.common.base.Verify.verifyNotNull)1 ImmutableList (com.google.common.collect.ImmutableList)1 ImmutableSet (com.google.common.collect.ImmutableSet)1 Iterables.getOnlyElement (com.google.common.collect.Iterables.getOnlyElement)1 Ordering (com.google.common.collect.Ordering)1