Search in sources :

Example 26 with ServiceContext

use of io.confluent.ksql.services.ServiceContext in project ksql by confluentinc.

the class TestExecutor method create.

/**
 * Create instance.
 *
 * <p>If {@code validateResults} is {@code true} the test will fail if the results are as
 * expected. This is the norm. If {@code false} the test will not fail if the results differ. This
 * is useful when re-writing the historical plans.
 *
 * @param validateResults flag to indicate if results should be validated.
 * @param extensionDir Optional extension directory.
 * @return the executor.
 */
public static TestExecutor create(final boolean validateResults, final Optional<String> extensionDir) {
    final StubKafkaService kafkaService = StubKafkaService.create();
    final StubKafkaClientSupplier kafkaClientSupplier = new StubKafkaClientSupplier();
    final ServiceContext serviceContext = getServiceContext(kafkaClientSupplier);
    return new TestExecutor(kafkaService, serviceContext, getKsqlEngine(serviceContext, extensionDir), TestExecutorUtil::buildStreamsTopologyTestDrivers, validateResults);
}
Also used : StubKafkaService(io.confluent.ksql.test.tools.stubs.StubKafkaService) ServiceContext(io.confluent.ksql.services.ServiceContext) DefaultServiceContext(io.confluent.ksql.services.DefaultServiceContext) StubKafkaClientSupplier(io.confluent.ksql.test.tools.stubs.StubKafkaClientSupplier)

Example 27 with ServiceContext

use of io.confluent.ksql.services.ServiceContext in project ksql by confluentinc.

the class KsqlTesterTest method execute.

@SuppressWarnings("unchecked")
private void execute(final ParsedStatement parsedStatement) {
    final PreparedStatement<?> engineStatement = engine.prepare(parsedStatement);
    final ConfiguredStatement<?> configured = ConfiguredStatement.of(engineStatement, SessionConfig.of(config, overrides));
    createTopics(engineStatement);
    if (engineStatement.getStatement() instanceof InsertValues) {
        pipeInput((ConfiguredStatement<InsertValues>) configured);
        return;
    } else if (engineStatement.getStatement() instanceof SetProperty) {
        PropertyOverrider.set((ConfiguredStatement<SetProperty>) configured, overrides);
        return;
    } else if (engineStatement.getStatement() instanceof UnsetProperty) {
        PropertyOverrider.unset((ConfiguredStatement<UnsetProperty>) configured, overrides);
        return;
    }
    final ConfiguredStatement<?> injected = formatInjector.inject(configured);
    final ExecuteResult result = engine.execute(serviceContext, injected);
    // is DDL statement
    if (!result.getQuery().isPresent()) {
        return;
    }
    final PersistentQueryMetadata query = (PersistentQueryMetadata) result.getQuery().get();
    final Topology topology = query.getTopology();
    final Properties properties = new Properties();
    properties.putAll(query.getStreamsProperties());
    properties.put(StreamsConfig.STATE_DIR_CONFIG, tmpFolder.getRoot().getAbsolutePath());
    final TopologyTestDriver driver = new TopologyTestDriver(topology, properties);
    final List<TopicInfo> inputTopics = query.getSourceNames().stream().map(sn -> engine.getMetaStore().getSource(sn)).map(ds -> new TopicInfo(ds.getKafkaTopicName(), keySerde(ds), valueSerde(ds))).collect(Collectors.toList());
    // Sink may be Optional for source tables. Once source table query execution is supported, then
    // we would need have a condition to not create an output topic info
    final DataSource output = engine.getMetaStore().getSource(query.getSinkName().get());
    final TopicInfo outputInfo = new TopicInfo(output.getKafkaTopicName(), keySerde(output), valueSerde(output));
    driverPipeline.addDriver(driver, inputTopics, outputInfo);
    drivers.put(query.getQueryId(), new DriverAndProperties(driver, properties));
}
Also used : DataSource(io.confluent.ksql.metastore.model.DataSource) NoSuchFileException(java.nio.file.NoSuchFileException) SequentialQueryIdGenerator(io.confluent.ksql.query.id.SequentialQueryIdGenerator) ServiceContext(io.confluent.ksql.services.ServiceContext) LoggerFactory(org.slf4j.LoggerFactory) ExecuteResult(io.confluent.ksql.KsqlExecutionContext.ExecuteResult) InsertValues(io.confluent.ksql.parser.tree.InsertValues) Serde(org.apache.kafka.common.serialization.Serde) Map(java.util.Map) After(org.junit.After) DefaultFormatInjector(io.confluent.ksql.format.DefaultFormatInjector) QueryId(io.confluent.ksql.query.QueryId) FakeKafkaTopicClient(io.confluent.ksql.services.FakeKafkaTopicClient) Path(java.nio.file.Path) PersistentQueryMetadata(io.confluent.ksql.util.PersistentQueryMetadata) Parameterized(org.junit.runners.Parameterized) QueryMetadata(io.confluent.ksql.util.QueryMetadata) MockSchemaRegistryClient(io.confluent.kafka.schemaregistry.client.MockSchemaRegistryClient) ImmutableMap(com.google.common.collect.ImmutableMap) UnsetProperty(io.confluent.ksql.parser.tree.UnsetProperty) TestDirective(io.confluent.ksql.test.parser.TestDirective) ConsumerConfig(org.apache.kafka.clients.consumer.ConsumerConfig) ConfiguredStatement(io.confluent.ksql.statement.ConfiguredStatement) KsqlConfig(io.confluent.ksql.util.KsqlConfig) Collectors(java.util.stream.Collectors) TestServiceContext(io.confluent.ksql.services.TestServiceContext) Objects(java.util.Objects) MetaStoreImpl(io.confluent.ksql.metastore.MetaStoreImpl) List(java.util.List) SetProperty(io.confluent.ksql.parser.tree.SetProperty) NoopProcessingLogContext(io.confluent.ksql.logging.processing.NoopProcessingLogContext) PropertyOverrider(io.confluent.ksql.properties.PropertyOverrider) KsqlException(io.confluent.ksql.util.KsqlException) Optional(java.util.Optional) TopicInfo(io.confluent.ksql.test.driver.TestDriverPipeline.TopicInfo) Topology(org.apache.kafka.streams.Topology) StreamsConfig(org.apache.kafka.streams.StreamsConfig) Iterables(com.google.common.collect.Iterables) FormatOptions(io.confluent.ksql.schema.utils.FormatOptions) AssertTable(io.confluent.ksql.parser.AssertTable) RunWith(org.junit.runner.RunWith) HashMap(java.util.HashMap) KsqlGenericRecord(io.confluent.ksql.engine.generic.KsqlGenericRecord) MetricCollectors(io.confluent.ksql.metrics.MetricCollectors) AssertStream(io.confluent.ksql.parser.tree.AssertStream) AssertStatement(io.confluent.ksql.parser.tree.AssertStatement) SessionConfig(io.confluent.ksql.config.SessionConfig) ImmutableList(com.google.common.collect.ImmutableList) Injector(io.confluent.ksql.statement.Injector) KsqlTestException(io.confluent.ksql.test.KsqlTestException) CreateSource(io.confluent.ksql.parser.tree.CreateSource) ParsedStatement(io.confluent.ksql.parser.KsqlParser.ParsedStatement) AssertValues(io.confluent.ksql.parser.tree.AssertValues) KsqlTestFolder(io.confluent.ksql.test.util.KsqlTestFolder) GenericRowSerDe(io.confluent.ksql.serde.GenericRowSerDe) Before(org.junit.Before) TopologyTestDriver(org.apache.kafka.streams.TopologyTestDriver) TestStatement(io.confluent.ksql.test.parser.TestStatement) TestFunctionRegistry(io.confluent.ksql.test.tools.TestFunctionRegistry) Properties(java.util.Properties) Logger(org.slf4j.Logger) KsqlEngine(io.confluent.ksql.engine.KsqlEngine) GenericRecordFactory(io.confluent.ksql.engine.generic.GenericRecordFactory) ServiceInfo(io.confluent.ksql.ServiceInfo) IOException(java.io.IOException) FileUtils(org.apache.commons.io.FileUtils) Test(org.junit.Test) SqlTestLoader(io.confluent.ksql.test.parser.SqlTestLoader) AssertTombstone(io.confluent.ksql.parser.tree.AssertTombstone) File(java.io.File) CreateAsSelect(io.confluent.ksql.parser.tree.CreateAsSelect) GenericKeySerDe(io.confluent.ksql.serde.GenericKeySerDe) Rule(org.junit.Rule) Paths(java.nio.file.Paths) GenericRow(io.confluent.ksql.GenericRow) QueryEventListener(io.confluent.ksql.engine.QueryEventListener) GenericKey(io.confluent.ksql.GenericKey) PersistenceSchema(io.confluent.ksql.schema.ksql.PersistenceSchema) Collections(java.util.Collections) PreparedStatement(io.confluent.ksql.parser.KsqlParser.PreparedStatement) TemporaryFolder(org.junit.rules.TemporaryFolder) UnsetProperty(io.confluent.ksql.parser.tree.UnsetProperty) TopologyTestDriver(org.apache.kafka.streams.TopologyTestDriver) Topology(org.apache.kafka.streams.Topology) Properties(java.util.Properties) TopicInfo(io.confluent.ksql.test.driver.TestDriverPipeline.TopicInfo) DataSource(io.confluent.ksql.metastore.model.DataSource) ConfiguredStatement(io.confluent.ksql.statement.ConfiguredStatement) InsertValues(io.confluent.ksql.parser.tree.InsertValues) ExecuteResult(io.confluent.ksql.KsqlExecutionContext.ExecuteResult) SetProperty(io.confluent.ksql.parser.tree.SetProperty) PersistentQueryMetadata(io.confluent.ksql.util.PersistentQueryMetadata)

Example 28 with ServiceContext

use of io.confluent.ksql.services.ServiceContext in project ksql by confluentinc.

the class EngineExecutor method executeTablePullQuery.

/**
 * Evaluates a pull query by first analyzing it, then building the logical plan and finally
 * the physical plan. The execution is then done using the physical plan in a pipelined manner.
 * @param statement The pull query
 * @param routingOptions Configuration parameters used for HA routing
 * @param pullQueryMetrics JMX metrics
 * @return the rows that are the result of evaluating the pull query
 */
PullQueryResult executeTablePullQuery(final ImmutableAnalysis analysis, final ConfiguredStatement<Query> statement, final HARouting routing, final RoutingOptions routingOptions, final QueryPlannerOptions queryPlannerOptions, final Optional<PullQueryExecutorMetrics> pullQueryMetrics, final boolean startImmediately, final Optional<ConsistencyOffsetVector> consistencyOffsetVector) {
    if (!statement.getStatement().isPullQuery()) {
        throw new IllegalArgumentException("Executor can only handle pull queries");
    }
    final SessionConfig sessionConfig = statement.getSessionConfig();
    // If we ever change how many hops a request can do, we'll need to update this for correct
    // metrics.
    final RoutingNodeType routingNodeType = routingOptions.getIsSkipForwardRequest() ? RoutingNodeType.REMOTE_NODE : RoutingNodeType.SOURCE_NODE;
    PullPhysicalPlan plan = null;
    try {
        // Do not set sessionConfig.getConfig to true! The copying is inefficient and slows down pull
        // query performance significantly.  Instead use QueryPlannerOptions which check overrides
        // deliberately.
        final KsqlConfig ksqlConfig = sessionConfig.getConfig(false);
        final LogicalPlanNode logicalPlan = buildAndValidateLogicalPlan(statement, analysis, ksqlConfig, queryPlannerOptions, false);
        // This is a cancel signal that is used to stop both local operations and requests
        final CompletableFuture<Void> shouldCancelRequests = new CompletableFuture<>();
        plan = buildPullPhysicalPlan(logicalPlan, analysis, queryPlannerOptions, shouldCancelRequests, consistencyOffsetVector);
        final PullPhysicalPlan physicalPlan = plan;
        final PullQueryQueue pullQueryQueue = new PullQueryQueue(analysis.getLimitClause());
        final PullQueryQueuePopulator populator = () -> routing.handlePullQuery(serviceContext, physicalPlan, statement, routingOptions, physicalPlan.getOutputSchema(), physicalPlan.getQueryId(), pullQueryQueue, shouldCancelRequests, consistencyOffsetVector);
        final PullQueryResult result = new PullQueryResult(physicalPlan.getOutputSchema(), populator, physicalPlan.getQueryId(), pullQueryQueue, pullQueryMetrics, physicalPlan.getSourceType(), physicalPlan.getPlanType(), routingNodeType, physicalPlan::getRowsReadFromDataSource, shouldCancelRequests, consistencyOffsetVector);
        if (startImmediately) {
            result.start();
        }
        return result;
    } catch (final Exception e) {
        if (plan == null) {
            pullQueryMetrics.ifPresent(m -> m.recordErrorRateForNoResult(1));
        } else {
            final PullPhysicalPlan physicalPlan = plan;
            pullQueryMetrics.ifPresent(metrics -> metrics.recordErrorRate(1, physicalPlan.getSourceType(), physicalPlan.getPlanType(), routingNodeType));
        }
        final String stmtLower = statement.getStatementText().toLowerCase(Locale.ROOT);
        final String messageLower = e.getMessage().toLowerCase(Locale.ROOT);
        final String stackLower = Throwables.getStackTraceAsString(e).toLowerCase(Locale.ROOT);
        // the contents of the query
        if (messageLower.contains(stmtLower) || stackLower.contains(stmtLower)) {
            final StackTraceElement loc = Iterables.getLast(Throwables.getCausalChain(e)).getStackTrace()[0];
            LOG.error("Failure to execute pull query {} {}, not logging the error message since it " + "contains the query string, which may contain sensitive information. If you " + "see this LOG message, please submit a GitHub ticket and we will scrub " + "the statement text from the error at {}", routingOptions.debugString(), queryPlannerOptions.debugString(), loc);
        } else {
            LOG.error("Failure to execute pull query. {} {}", routingOptions.debugString(), queryPlannerOptions.debugString(), e);
        }
        LOG.debug("Failed pull query text {}, {}", statement.getStatementText(), e);
        throw new KsqlStatementException(e.getMessage() == null ? "Server Error" + Arrays.toString(e.getStackTrace()) : e.getMessage(), statement.getStatementText(), e);
    }
}
Also used : DataSource(io.confluent.ksql.metastore.model.DataSource) PushPhysicalPlanCreator(io.confluent.ksql.physical.scalablepush.PushPhysicalPlanCreator) CreateTableAsSelect(io.confluent.ksql.parser.tree.CreateTableAsSelect) Arrays(java.util.Arrays) InternalFunctionRegistry(io.confluent.ksql.function.InternalFunctionRegistry) SourceName(io.confluent.ksql.name.SourceName) RoutingOptions(io.confluent.ksql.execution.streams.RoutingOptions) PushPhysicalPlanManager(io.confluent.ksql.physical.scalablepush.PushPhysicalPlanManager) PushPhysicalPlanBuilder(io.confluent.ksql.physical.scalablepush.PushPhysicalPlanBuilder) RoutingNodeType(io.confluent.ksql.util.KsqlConstants.RoutingNodeType) TransientQueryMetadata(io.confluent.ksql.util.TransientQueryMetadata) ExecuteResult(io.confluent.ksql.KsqlExecutionContext.ExecuteResult) Map(java.util.Map) KsqlBareOutputNode(io.confluent.ksql.planner.plan.KsqlBareOutputNode) QueryId(io.confluent.ksql.query.QueryId) ExecutionStep(io.confluent.ksql.execution.plan.ExecutionStep) RefinementInfo(io.confluent.ksql.serde.RefinementInfo) ImmutableAnalysis(io.confluent.ksql.analyzer.ImmutableAnalysis) Sink(io.confluent.ksql.parser.tree.Sink) Set(java.util.Set) Relation(io.confluent.ksql.parser.tree.Relation) ConfiguredStatement(io.confluent.ksql.statement.ConfiguredStatement) MetaStoreImpl(io.confluent.ksql.metastore.MetaStoreImpl) KsqlException(io.confluent.ksql.util.KsqlException) TransientQueryQueue(io.confluent.ksql.query.TransientQueryQueue) PullQueryResult(io.confluent.ksql.physical.pull.PullQueryResult) Iterables(com.google.common.collect.Iterables) FormatOptions(io.confluent.ksql.schema.utils.FormatOptions) PushRouting(io.confluent.ksql.physical.scalablepush.PushRouting) UnqualifiedColumnReferenceExp(io.confluent.ksql.execution.expression.tree.UnqualifiedColumnReferenceExp) CreateStreamAsSelect(io.confluent.ksql.parser.tree.CreateStreamAsSelect) SessionConfig(io.confluent.ksql.config.SessionConfig) CreateStream(io.confluent.ksql.parser.tree.CreateStream) SingleColumn(io.confluent.ksql.parser.tree.SingleColumn) MetaStore(io.confluent.ksql.metastore.MetaStore) KsqlStructuredDataOutputNode(io.confluent.ksql.planner.plan.KsqlStructuredDataOutputNode) PushRoutingOptions(io.confluent.ksql.physical.scalablepush.PushRoutingOptions) PlanInfoExtractor(io.confluent.ksql.execution.plan.PlanInfoExtractor) DataSourceNode(io.confluent.ksql.planner.plan.DataSourceNode) QueryContainer(io.confluent.ksql.parser.tree.QueryContainer) OutputNode(io.confluent.ksql.planner.plan.OutputNode) Throwables(com.google.common.base.Throwables) PushQueryMetadata(io.confluent.ksql.util.PushQueryMetadata) PushQueryQueuePopulator(io.confluent.ksql.physical.scalablepush.PushQueryQueuePopulator) ValueFormat(io.confluent.ksql.serde.ValueFormat) Table(io.confluent.ksql.parser.tree.Table) KsqlStatementException(io.confluent.ksql.util.KsqlStatementException) CreateAsSelect(io.confluent.ksql.parser.tree.CreateAsSelect) KsqlTopic(io.confluent.ksql.execution.ddl.commands.KsqlTopic) OutputRefinement(io.confluent.ksql.parser.OutputRefinement) LogicalPlanNode(io.confluent.ksql.planner.LogicalPlanNode) Query(io.confluent.ksql.parser.tree.Query) ServiceContext(io.confluent.ksql.services.ServiceContext) LoggerFactory(org.slf4j.LoggerFactory) AliasedRelation(io.confluent.ksql.parser.tree.AliasedRelation) Formats(io.confluent.ksql.execution.plan.Formats) MutableMetaStore(io.confluent.ksql.metastore.MutableMetaStore) Context(io.vertx.core.Context) CreateTable(io.confluent.ksql.parser.tree.CreateTable) Locale(java.util.Locale) PersistentQueryMetadata(io.confluent.ksql.util.PersistentQueryMetadata) KsqlTable(io.confluent.ksql.metastore.model.KsqlTable) TopicPartition(org.apache.kafka.common.TopicPartition) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) Collection(java.util.Collection) ScalablePushQueryMetadata(io.confluent.ksql.util.ScalablePushQueryMetadata) ScalablePushQueryMetrics(io.confluent.ksql.internal.ScalablePushQueryMetrics) KsqlConfig(io.confluent.ksql.util.KsqlConfig) ExecutableDdlStatement(io.confluent.ksql.parser.tree.ExecutableDdlStatement) LogicalSchema(io.confluent.ksql.schema.ksql.LogicalSchema) Collectors(java.util.stream.Collectors) DdlCommand(io.confluent.ksql.execution.ddl.commands.DdlCommand) Objects(java.util.Objects) PullQueryExecutorMetrics(io.confluent.ksql.internal.PullQueryExecutorMetrics) QueryPlannerOptions(io.confluent.ksql.planner.QueryPlannerOptions) ConsistencyOffsetVector(io.confluent.ksql.util.ConsistencyOffsetVector) Optional(java.util.Optional) Statement(io.confluent.ksql.parser.tree.Statement) KsqlConstants(io.confluent.ksql.util.KsqlConstants) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) PullQueryQueuePopulator(io.confluent.ksql.physical.pull.PullQueryQueuePopulator) PullQueryQueue(io.confluent.ksql.query.PullQueryQueue) PushPhysicalPlan(io.confluent.ksql.physical.scalablepush.PushPhysicalPlan) HARouting(io.confluent.ksql.physical.pull.HARouting) PlanInfo(io.confluent.ksql.execution.plan.PlanInfo) PullPhysicalPlanBuilder(io.confluent.ksql.physical.pull.PullPhysicalPlanBuilder) KeyFormat(io.confluent.ksql.serde.KeyFormat) ResultType(io.confluent.ksql.util.PushQueryMetadata.ResultType) CompletableFuture(java.util.concurrent.CompletableFuture) DataSourceType(io.confluent.ksql.metastore.model.DataSource.DataSourceType) OptionalInt(java.util.OptionalInt) PushOffsetRange(io.confluent.ksql.util.PushOffsetRange) LogicalPlanner(io.confluent.ksql.planner.LogicalPlanner) Logger(org.slf4j.Logger) PhysicalPlan(io.confluent.ksql.physical.PhysicalPlan) PlanSummary(io.confluent.ksql.util.PlanSummary) PullPhysicalPlan(io.confluent.ksql.physical.pull.PullPhysicalPlan) PlanNode(io.confluent.ksql.planner.plan.PlanNode) QueryRegistry(io.confluent.ksql.query.QueryRegistry) Collections(java.util.Collections) CreateTableCommand(io.confluent.ksql.execution.ddl.commands.CreateTableCommand) Select(io.confluent.ksql.parser.tree.Select) PushQueryPreparer(io.confluent.ksql.physical.scalablepush.PushQueryPreparer) RoutingNodeType(io.confluent.ksql.util.KsqlConstants.RoutingNodeType) SessionConfig(io.confluent.ksql.config.SessionConfig) KsqlConfig(io.confluent.ksql.util.KsqlConfig) LogicalPlanNode(io.confluent.ksql.planner.LogicalPlanNode) PullQueryQueuePopulator(io.confluent.ksql.physical.pull.PullQueryQueuePopulator) PullQueryQueue(io.confluent.ksql.query.PullQueryQueue) KsqlException(io.confluent.ksql.util.KsqlException) KsqlStatementException(io.confluent.ksql.util.KsqlStatementException) PullPhysicalPlan(io.confluent.ksql.physical.pull.PullPhysicalPlan) CompletableFuture(java.util.concurrent.CompletableFuture) KsqlStatementException(io.confluent.ksql.util.KsqlStatementException) PullQueryResult(io.confluent.ksql.physical.pull.PullQueryResult)

Example 29 with ServiceContext

use of io.confluent.ksql.services.ServiceContext in project ksql by confluentinc.

the class StandaloneExecutorFunctionalTest method setUp.

@SuppressWarnings("unchecked")
@Before
public void setUp() throws Exception {
    queryFile = TMP.newFile().toPath();
    final Map<String, Object> properties = ImmutableMap.<String, Object>builder().putAll(KsqlConfigTestUtil.baseTestConfig()).put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, TEST_HARNESS.kafkaBootstrapServers()).put(KsqlConfig.SCHEMA_REGISTRY_URL_PROPERTY, "http://foo:8080").build();
    final Function<KsqlConfig, ServiceContext> serviceContextFactory = config -> TestServiceContext.create(new KsqlConfig(properties), TEST_HARNESS.getServiceContext().getSchemaRegistryClientFactory());
    standalone = StandaloneExecutorFactory.create((Map) properties, queryFile.toString(), ".", serviceContextFactory, KafkaConfigStore::new, activeQuerySupplier -> versionChecker, StandaloneExecutor::new, new MetricCollectors());
    s1 = KsqlIdentifierTestUtil.uniqueIdentifierName("S1");
    s2 = KsqlIdentifierTestUtil.uniqueIdentifierName("S2");
    t1 = KsqlIdentifierTestUtil.uniqueIdentifierName("T1");
}
Also used : PhysicalSchema(io.confluent.ksql.schema.ksql.PhysicalSchema) MethodSorters(org.junit.runners.MethodSorters) BeforeClass(org.junit.BeforeClass) ColumnName(io.confluent.ksql.name.ColumnName) JSON(io.confluent.ksql.serde.FormatFactory.JSON) Mock(org.mockito.Mock) Assert.assertThrows(org.junit.Assert.assertThrows) ServiceContext(io.confluent.ksql.services.ServiceContext) RunWith(org.junit.runner.RunWith) KsqlIdentifierTestUtil(io.confluent.ksql.test.util.KsqlIdentifierTestUtil) MetricCollectors(io.confluent.ksql.metrics.MetricCollectors) AVRO(io.confluent.ksql.serde.FormatFactory.AVRO) Function(java.util.function.Function) KafkaConfigStore(io.confluent.ksql.rest.server.computation.KafkaConfigStore) Map(java.util.Map) After(org.junit.After) KsqlTestFolder(io.confluent.ksql.test.util.KsqlTestFolder) OrderDataProvider(io.confluent.ksql.util.OrderDataProvider) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) SerdeFeatures(io.confluent.ksql.serde.SerdeFeatures) ClassRule(org.junit.ClassRule) Path(java.nio.file.Path) Before(org.junit.Before) CommonClientConfigs(org.apache.kafka.clients.CommonClientConfigs) SystemColumns(io.confluent.ksql.schema.ksql.SystemColumns) ImmutableMap(com.google.common.collect.ImmutableMap) Files(java.nio.file.Files) IntegrationTest(io.confluent.common.utils.IntegrationTest) KAFKA(io.confluent.ksql.serde.FormatFactory.KAFKA) IOException(java.io.IOException) Test(org.junit.Test) KsqlConfig(io.confluent.ksql.util.KsqlConfig) Category(org.junit.experimental.categories.Category) IntegrationTestHarness(io.confluent.ksql.integration.IntegrationTestHarness) LogicalSchema(io.confluent.ksql.schema.ksql.LogicalSchema) StandardCharsets(java.nio.charset.StandardCharsets) TestServiceContext(io.confluent.ksql.services.TestServiceContext) KsqlConfigTestUtil(io.confluent.ksql.KsqlConfigTestUtil) VersionCheckerAgent(io.confluent.ksql.version.metrics.VersionCheckerAgent) KsqlException(io.confluent.ksql.util.KsqlException) FixMethodOrder(org.junit.FixMethodOrder) Matchers.containsString(org.hamcrest.Matchers.containsString) SqlTypes(io.confluent.ksql.schema.ksql.types.SqlTypes) MockitoJUnitRunner(org.mockito.junit.MockitoJUnitRunner) TemporaryFolder(org.junit.rules.TemporaryFolder) ServiceContext(io.confluent.ksql.services.ServiceContext) TestServiceContext(io.confluent.ksql.services.TestServiceContext) MetricCollectors(io.confluent.ksql.metrics.MetricCollectors) KsqlConfig(io.confluent.ksql.util.KsqlConfig) Matchers.containsString(org.hamcrest.Matchers.containsString) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) Before(org.junit.Before)

Example 30 with ServiceContext

use of io.confluent.ksql.services.ServiceContext in project ksql by confluentinc.

the class DistributingExecutorTest method shouldThrowServerExceptionIfServerServiceContextIsDeniedAuthorization.

@Test
public void shouldThrowServerExceptionIfServerServiceContextIsDeniedAuthorization() {
    // Given:
    final KsqlSecurityContext userSecurityContext = new KsqlSecurityContext(Optional.empty(), SandboxedServiceContext.create(TestServiceContext.create()));
    final PreparedStatement<Statement> preparedStatement = PreparedStatement.of("", new ListProperties(Optional.empty()));
    final ConfiguredStatement<Statement> configured = ConfiguredStatement.of(preparedStatement, SessionConfig.of(KSQL_CONFIG, ImmutableMap.of()));
    doNothing().when(authorizationValidator).checkAuthorization(eq(userSecurityContext), any(), any());
    doThrow(KsqlTopicAuthorizationException.class).when(authorizationValidator).checkAuthorization(ArgumentMatchers.argThat(securityContext -> securityContext.getServiceContext() == serviceContext), any(), any());
    // When:
    final Exception e = assertThrows(KsqlServerException.class, () -> distributor.execute(configured, executionContext, userSecurityContext));
    // Then:
    assertThat(e.getCause(), (is(instanceOf(KsqlTopicAuthorizationException.class))));
}
Also used : DataSource(io.confluent.ksql.metastore.model.DataSource) Query(io.confluent.ksql.parser.tree.Query) ArgumentMatchers(org.mockito.ArgumentMatchers) Matchers.isA(org.hamcrest.Matchers.isA) ColumnName(io.confluent.ksql.name.ColumnName) SourceName(io.confluent.ksql.name.SourceName) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) StatementExecutorResponse(io.confluent.ksql.rest.server.execution.StatementExecutorResponse) ServiceContext(io.confluent.ksql.services.ServiceContext) KsqlTopicAuthorizationException(io.confluent.ksql.exception.KsqlTopicAuthorizationException) CommandId(io.confluent.ksql.rest.entity.CommandId) InjectorChain(io.confluent.ksql.statement.InjectorChain) CommonCreateConfigs(io.confluent.ksql.properties.with.CommonCreateConfigs) StringLiteral(io.confluent.ksql.execution.expression.tree.StringLiteral) KsqlErrorMessage(io.confluent.ksql.rest.entity.KsqlErrorMessage) KsqlAuthorizationValidator(io.confluent.ksql.security.KsqlAuthorizationValidator) Mockito.doThrow(org.mockito.Mockito.doThrow) Duration(java.time.Duration) Mockito.doReturn(org.mockito.Mockito.doReturn) CommandStatus(io.confluent.ksql.rest.entity.CommandStatus) ImmutableMap(com.google.common.collect.ImmutableMap) Errors(io.confluent.ksql.rest.Errors) Mockito.doNothing(org.mockito.Mockito.doNothing) ConfiguredStatement(io.confluent.ksql.statement.ConfiguredStatement) KsqlConfig(io.confluent.ksql.util.KsqlConfig) LogicalSchema(io.confluent.ksql.schema.ksql.LogicalSchema) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) KsqlRestConfig(io.confluent.ksql.rest.server.KsqlRestConfig) TestServiceContext(io.confluent.ksql.services.TestServiceContext) KsqlExecutionContext(io.confluent.ksql.KsqlExecutionContext) ProducerFencedException(org.apache.kafka.common.errors.ProducerFencedException) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Status(io.confluent.ksql.rest.entity.CommandStatus.Status) KsqlRestException(io.confluent.ksql.rest.server.resources.KsqlRestException) KsqlException(io.confluent.ksql.util.KsqlException) Optional(java.util.Optional) Matchers.is(org.hamcrest.Matchers.is) Statement(io.confluent.ksql.parser.tree.Statement) WarningEntity(io.confluent.ksql.rest.entity.WarningEntity) Matchers.containsString(org.hamcrest.Matchers.containsString) MockitoJUnitRunner(org.mockito.junit.MockitoJUnitRunner) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Action(io.confluent.ksql.rest.entity.CommandId.Action) Mock(org.mockito.Mock) Assert.assertThrows(org.junit.Assert.assertThrows) RunWith(org.junit.runner.RunWith) HashMap(java.util.HashMap) KsqlSecurityContext(io.confluent.ksql.security.KsqlSecurityContext) Supplier(java.util.function.Supplier) ListProperties(io.confluent.ksql.parser.tree.ListProperties) SessionConfig(io.confluent.ksql.config.SessionConfig) CreateStream(io.confluent.ksql.parser.tree.CreateStream) ImmutableList(com.google.common.collect.ImmutableList) Injector(io.confluent.ksql.statement.Injector) MetaStore(io.confluent.ksql.metastore.MetaStore) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) InsertInto(io.confluent.ksql.parser.tree.InsertInto) Before(org.junit.Before) TimeoutException(org.apache.kafka.common.errors.TimeoutException) InOrder(org.mockito.InOrder) Producer(org.apache.kafka.clients.producer.Producer) Assert.assertTrue(org.junit.Assert.assertTrue) CommandStatusEntity(io.confluent.ksql.rest.entity.CommandStatusEntity) SandboxedServiceContext(io.confluent.ksql.services.SandboxedServiceContext) Mockito.times(org.mockito.Mockito.times) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) Mockito.verify(org.mockito.Mockito.verify) Type(io.confluent.ksql.rest.entity.CommandId.Type) AtomicLong(java.util.concurrent.atomic.AtomicLong) Mockito(org.mockito.Mockito) Mockito.never(org.mockito.Mockito.never) CreateSourceProperties(io.confluent.ksql.parser.properties.with.CreateSourceProperties) KsqlServerException(io.confluent.ksql.util.KsqlServerException) TableElements(io.confluent.ksql.parser.tree.TableElements) DefaultErrorMessages(io.confluent.ksql.rest.DefaultErrorMessages) Assert.assertEquals(org.junit.Assert.assertEquals) PreparedStatement(io.confluent.ksql.parser.KsqlParser.PreparedStatement) KsqlTopicAuthorizationException(io.confluent.ksql.exception.KsqlTopicAuthorizationException) ListProperties(io.confluent.ksql.parser.tree.ListProperties) KsqlSecurityContext(io.confluent.ksql.security.KsqlSecurityContext) ConfiguredStatement(io.confluent.ksql.statement.ConfiguredStatement) Statement(io.confluent.ksql.parser.tree.Statement) PreparedStatement(io.confluent.ksql.parser.KsqlParser.PreparedStatement) KsqlTopicAuthorizationException(io.confluent.ksql.exception.KsqlTopicAuthorizationException) ProducerFencedException(org.apache.kafka.common.errors.ProducerFencedException) KsqlRestException(io.confluent.ksql.rest.server.resources.KsqlRestException) KsqlException(io.confluent.ksql.util.KsqlException) TimeoutException(org.apache.kafka.common.errors.TimeoutException) KsqlServerException(io.confluent.ksql.util.KsqlServerException) Test(org.junit.Test)

Aggregations

ServiceContext (io.confluent.ksql.services.ServiceContext)44 Optional (java.util.Optional)25 KsqlConfig (io.confluent.ksql.util.KsqlConfig)23 Collectors (java.util.stream.Collectors)23 List (java.util.List)22 ConfiguredStatement (io.confluent.ksql.statement.ConfiguredStatement)21 KsqlException (io.confluent.ksql.util.KsqlException)21 Map (java.util.Map)21 ImmutableMap (com.google.common.collect.ImmutableMap)18 TestServiceContext (io.confluent.ksql.services.TestServiceContext)15 Collections (java.util.Collections)15 ImmutableList (com.google.common.collect.ImmutableList)13 KsqlExecutionContext (io.confluent.ksql.KsqlExecutionContext)13 LogicalSchema (io.confluent.ksql.schema.ksql.LogicalSchema)13 KsqlEngine (io.confluent.ksql.engine.KsqlEngine)12 KsqlStatementException (io.confluent.ksql.util.KsqlStatementException)12 Test (org.junit.Test)12 Logger (org.slf4j.Logger)10 LoggerFactory (org.slf4j.LoggerFactory)10 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)9