Search in sources :

Example 11 with ServiceContext

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

the class KsqlContext method create.

/**
 * Create a KSQL context object with the given properties. A KSQL context has it's own metastore
 * valid during the life of the object.
 */
public static KsqlContext create(final KsqlConfig ksqlConfig, final ProcessingLogContext processingLogContext, final MetricCollectors metricCollectors) {
    Objects.requireNonNull(ksqlConfig, "ksqlConfig cannot be null.");
    final ServiceContext serviceContext = ServiceContextFactory.create(ksqlConfig, DisabledKsqlClient::instance);
    final MutableFunctionRegistry functionRegistry = new InternalFunctionRegistry();
    UserFunctionLoader.newInstance(ksqlConfig, functionRegistry, ".", metricCollectors.getMetrics()).load();
    final ServiceInfo serviceInfo = ServiceInfo.create(ksqlConfig);
    final KsqlEngine engine = new KsqlEngine(serviceContext, processingLogContext, functionRegistry, serviceInfo, new SequentialQueryIdGenerator(), ksqlConfig, Collections.emptyList(), metricCollectors);
    return new KsqlContext(serviceContext, ksqlConfig, engine, Injectors.DEFAULT);
}
Also used : ServiceInfo(io.confluent.ksql.ServiceInfo) KsqlEngine(io.confluent.ksql.engine.KsqlEngine) MutableFunctionRegistry(io.confluent.ksql.function.MutableFunctionRegistry) DisabledKsqlClient(io.confluent.ksql.services.DisabledKsqlClient) ServiceContext(io.confluent.ksql.services.ServiceContext) SequentialQueryIdGenerator(io.confluent.ksql.query.id.SequentialQueryIdGenerator) InternalFunctionRegistry(io.confluent.ksql.function.InternalFunctionRegistry)

Example 12 with ServiceContext

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

the class KsqlEngineTestUtil method execute.

@SuppressWarnings({ "rawtypes", "unchecked" })
private static ExecuteResult execute(final ServiceContext serviceContext, final KsqlExecutionContext executionContext, final ParsedStatement stmt, final KsqlConfig ksqlConfig, final Map<String, Object> overriddenProperties, final Optional<DefaultSchemaInjector> schemaInjector) {
    final PreparedStatement<?> prepared = executionContext.prepare(stmt);
    final ConfiguredStatement<?> configured = ConfiguredStatement.of(prepared, SessionConfig.of(ksqlConfig, overriddenProperties));
    final ConfiguredStatement<?> withFormats = new DefaultFormatInjector().inject(configured);
    final ConfiguredStatement<?> withSchema = schemaInjector.map(injector -> injector.inject(withFormats)).orElse((ConfiguredStatement) withFormats);
    final ConfiguredStatement<?> reformatted = new SqlFormatInjector(executionContext).inject(withSchema);
    try {
        return executionContext.execute(serviceContext, reformatted);
    } catch (final KsqlStatementException e) {
        // can easily check that the failed statement is the input statement
        throw new KsqlStatementException(e.getRawMessage(), stmt.getStatementText(), e.getCause());
    }
}
Also used : Query(io.confluent.ksql.parser.tree.Query) SequentialQueryIdGenerator(io.confluent.ksql.query.id.SequentialQueryIdGenerator) SchemaRegistryClient(io.confluent.kafka.schemaregistry.client.SchemaRegistryClient) ServiceContext(io.confluent.ksql.services.ServiceContext) SchemaRegistryTopicSchemaSupplier(io.confluent.ksql.schema.ksql.inference.SchemaRegistryTopicSchemaSupplier) ProcessingLogContext(io.confluent.ksql.logging.processing.ProcessingLogContext) MutableMetaStore(io.confluent.ksql.metastore.MutableMetaStore) MetricCollectors(io.confluent.ksql.metrics.MetricCollectors) Function(java.util.function.Function) SessionConfig(io.confluent.ksql.config.SessionConfig) TransientQueryMetadata(io.confluent.ksql.util.TransientQueryMetadata) ExecuteResult(io.confluent.ksql.KsqlExecutionContext.ExecuteResult) Map(java.util.Map) ParsedStatement(io.confluent.ksql.parser.KsqlParser.ParsedStatement) DefaultFormatInjector(io.confluent.ksql.format.DefaultFormatInjector) QueryIdGenerator(io.confluent.ksql.query.id.QueryIdGenerator) QueryMetadata(io.confluent.ksql.util.QueryMetadata) ConfiguredStatement(io.confluent.ksql.statement.ConfiguredStatement) KsqlConfig(io.confluent.ksql.util.KsqlConfig) DefaultSchemaInjector(io.confluent.ksql.schema.ksql.inference.DefaultSchemaInjector) Collectors(java.util.stream.Collectors) KsqlStatementException(io.confluent.ksql.util.KsqlStatementException) List(java.util.List) KsqlExecutionContext(io.confluent.ksql.KsqlExecutionContext) KsqlEngineMetrics(io.confluent.ksql.internal.KsqlEngineMetrics) Optional(java.util.Optional) Collections(java.util.Collections) PreparedStatement(io.confluent.ksql.parser.KsqlParser.PreparedStatement) DefaultFormatInjector(io.confluent.ksql.format.DefaultFormatInjector) KsqlStatementException(io.confluent.ksql.util.KsqlStatementException)

Example 13 with ServiceContext

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

the class KsqlContextTestUtil method create.

public static KsqlContext create(final KsqlConfig ksqlConfig, final SchemaRegistryClient schemaRegistryClient, final FunctionRegistry functionRegistry) {
    final KafkaClientSupplier clientSupplier = new DefaultKafkaClientSupplier();
    final Admin adminClient = clientSupplier.getAdmin(ksqlConfig.getKsqlAdminClientConfigProps());
    final KafkaTopicClient kafkaTopicClient = new KafkaTopicClientImpl(() -> adminClient);
    final ServiceContext serviceContext = TestServiceContext.create(clientSupplier, adminClient, kafkaTopicClient, () -> schemaRegistryClient, new DefaultConnectClientFactory(ksqlConfig).get(Optional.empty(), Collections.emptyList(), Optional.empty()));
    final String metricsPrefix = "instance-" + COUNTER.getAndIncrement() + "-";
    final KsqlEngine engine = new KsqlEngine(serviceContext, ProcessingLogContext.create(), functionRegistry, ServiceInfo.create(ksqlConfig, metricsPrefix), new SequentialQueryIdGenerator(), ksqlConfig, Collections.emptyList(), new MetricCollectors());
    return new KsqlContext(serviceContext, ksqlConfig, engine, Injectors.DEFAULT);
}
Also used : DefaultConnectClientFactory(io.confluent.ksql.services.DefaultConnectClientFactory) KsqlEngine(io.confluent.ksql.engine.KsqlEngine) KafkaTopicClient(io.confluent.ksql.services.KafkaTopicClient) DefaultKafkaClientSupplier(org.apache.kafka.streams.processor.internals.DefaultKafkaClientSupplier) DefaultKafkaClientSupplier(org.apache.kafka.streams.processor.internals.DefaultKafkaClientSupplier) KafkaClientSupplier(org.apache.kafka.streams.KafkaClientSupplier) ServiceContext(io.confluent.ksql.services.ServiceContext) TestServiceContext(io.confluent.ksql.services.TestServiceContext) MetricCollectors(io.confluent.ksql.metrics.MetricCollectors) SequentialQueryIdGenerator(io.confluent.ksql.query.id.SequentialQueryIdGenerator) Admin(org.apache.kafka.clients.admin.Admin) KafkaTopicClientImpl(io.confluent.ksql.services.KafkaTopicClientImpl)

Example 14 with ServiceContext

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

the class TestExecutorUtil method buildStreamsTopologyTestDrivers.

static List<TopologyTestDriverContainer> buildStreamsTopologyTestDrivers(final TestCase testCase, final ServiceContext serviceContext, final KsqlEngine ksqlEngine, final KsqlConfig ksqlConfig, final StubKafkaService stubKafkaService, final TestExecutionListener listener) {
    final KsqlConfig maybeUpdatedConfigs = testCase.applyPersistedProperties(ksqlConfig);
    final List<PersistentQueryAndSources> queryMetadataList = doBuildQueries(testCase, serviceContext, ksqlEngine, maybeUpdatedConfigs, stubKafkaService, listener);
    final List<TopologyTestDriverContainer> topologyTestDrivers = new ArrayList<>();
    for (final PersistentQueryAndSources persistentQueryAndSources : queryMetadataList) {
        final PersistentQueryMetadata persistentQueryMetadata = persistentQueryAndSources.getPersistentQueryMetadata();
        final Properties streamsProperties = new Properties();
        streamsProperties.putAll(persistentQueryMetadata.getStreamsProperties());
        final Topology topology = persistentQueryMetadata.getTopology();
        final TopologyTestDriver topologyTestDriver = new TopologyTestDriver(topology, streamsProperties, Instant.EPOCH);
        final List<Topic> sourceTopics = persistentQueryAndSources.getSources().stream().map(dataSource -> {
            stubKafkaService.requireTopicExists(dataSource.getKafkaTopicName());
            return stubKafkaService.getTopic(dataSource.getKafkaTopicName());
        }).collect(Collectors.toList());
        final Optional<Topic> sinkTopic = persistentQueryMetadata.getSinkName().map(name -> buildSinkTopic(ksqlEngine.getMetaStore().getSource(name), stubKafkaService, serviceContext.getSchemaRegistryClient()));
        testCase.setGeneratedTopologies(ImmutableList.of(persistentQueryMetadata.getTopologyDescription()));
        testCase.setGeneratedSchemas(persistentQueryMetadata.getQuerySchemas().getLoggerSchemaInfo());
        topologyTestDrivers.add(TopologyTestDriverContainer.of(topologyTestDriver, sourceTopics, sinkTopic));
    }
    return topologyTestDrivers;
}
Also used : DataSource(io.confluent.ksql.metastore.model.DataSource) KsqlPlan(io.confluent.ksql.engine.KsqlPlan) SessionProperties(io.confluent.ksql.rest.SessionProperties) StringDescription(org.hamcrest.StringDescription) SchemaRegistryClient(io.confluent.kafka.schemaregistry.client.SchemaRegistryClient) SourceName(io.confluent.ksql.name.SourceName) URL(java.net.URL) Matchers.not(org.hamcrest.Matchers.not) ServiceContext(io.confluent.ksql.services.ServiceContext) SchemaRegistryTopicSchemaSupplier(io.confluent.ksql.schema.ksql.inference.SchemaRegistryTopicSchemaSupplier) InjectorChain(io.confluent.ksql.statement.InjectorChain) KsqlConstants.getSRSubject(io.confluent.ksql.util.KsqlConstants.getSRSubject) ExecuteResult(io.confluent.ksql.KsqlExecutionContext.ExecuteResult) InsertValues(io.confluent.ksql.parser.tree.InsertValues) Map(java.util.Map) DefaultFormatInjector(io.confluent.ksql.format.DefaultFormatInjector) QueryId(io.confluent.ksql.query.QueryId) SchemaRegisterInjector(io.confluent.ksql.schema.ksql.inference.SchemaRegisterInjector) PersistentQueryMetadata(io.confluent.ksql.util.PersistentQueryMetadata) PlanJsonMapper(io.confluent.ksql.execution.json.PlanJsonMapper) FunctionRegistry(io.confluent.ksql.function.FunctionRegistry) Collection(java.util.Collection) ConfiguredStatement(io.confluent.ksql.statement.ConfiguredStatement) KsqlConfig(io.confluent.ksql.util.KsqlConfig) Instant(java.time.Instant) ParsedSchema(io.confluent.kafka.schemaregistry.ParsedSchema) DefaultSchemaInjector(io.confluent.ksql.schema.ksql.inference.DefaultSchemaInjector) Collectors(java.util.stream.Collectors) List(java.util.List) KsqlExecutionContext(io.confluent.ksql.KsqlExecutionContext) KsqlException(io.confluent.ksql.util.KsqlException) Optional(java.util.Optional) Matchers.is(org.hamcrest.Matchers.is) Builder(com.google.common.collect.ImmutableList.Builder) KsqlConstants(io.confluent.ksql.util.KsqlConstants) Topology(org.apache.kafka.streams.Topology) FormatFactory(io.confluent.ksql.serde.FormatFactory) KafkaTopicClient(io.confluent.ksql.services.KafkaTopicClient) KsqlHostInfo(io.confluent.ksql.util.KsqlHostInfo) ArrayList(java.util.ArrayList) SessionConfig(io.confluent.ksql.config.SessionConfig) LinkedHashMap(java.util.LinkedHashMap) ImmutableList(com.google.common.collect.ImmutableList) Objects.requireNonNull(java.util.Objects.requireNonNull) ConfiguredKsqlPlan(io.confluent.ksql.planner.plan.ConfiguredKsqlPlan) MetaStore(io.confluent.ksql.metastore.MetaStore) ParsedStatement(io.confluent.ksql.parser.KsqlParser.ParsedStatement) StubKafkaService(io.confluent.ksql.test.tools.stubs.StubKafkaService) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) TopologyTestDriver(org.apache.kafka.streams.TopologyTestDriver) Matchers.empty(org.hamcrest.Matchers.empty) Properties(java.util.Properties) Iterator(java.util.Iterator) KsqlEngine(io.confluent.ksql.engine.KsqlEngine) MalformedURLException(java.net.MalformedURLException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) SerdeFeature(io.confluent.ksql.serde.SerdeFeature) StubInsertValuesExecutor(io.confluent.ksql.engine.StubInsertValuesExecutor) IOException(java.io.IOException) KsqlStatementException(io.confluent.ksql.util.KsqlStatementException) Format(io.confluent.ksql.serde.Format) SqlFormatInjector(io.confluent.ksql.engine.SqlFormatInjector) KsqlTopic(io.confluent.ksql.execution.ddl.commands.KsqlTopic) VisibleForTesting(com.google.common.annotations.VisibleForTesting) SchemaMetadata(io.confluent.kafka.schemaregistry.client.SchemaMetadata) PreparedStatement(io.confluent.ksql.parser.KsqlParser.PreparedStatement) ArrayList(java.util.ArrayList) KsqlConfig(io.confluent.ksql.util.KsqlConfig) TopologyTestDriver(org.apache.kafka.streams.TopologyTestDriver) Topology(org.apache.kafka.streams.Topology) SessionProperties(io.confluent.ksql.rest.SessionProperties) Properties(java.util.Properties) KsqlTopic(io.confluent.ksql.execution.ddl.commands.KsqlTopic) PersistentQueryMetadata(io.confluent.ksql.util.PersistentQueryMetadata)

Example 15 with ServiceContext

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

the class LocalCommandsTest method shouldWriteAppIdToCommandFile.

@Test
public void shouldWriteAppIdToCommandFile() throws IOException {
    // Given
    final File dir = commandsDir.newFolder();
    LocalCommands localCommands = LocalCommands.open(ksqlEngine, dir);
    File processedFile = localCommands.getCurrentLocalCommandsFile();
    // When
    localCommands.write(metadata1);
    localCommands.write(metadata2);
    // Then
    // Need to create a new local commands in order not to skip the "current" file we just wrote.
    localCommands = LocalCommands.open(ksqlEngine, dir);
    localCommands.write(metadata3);
    localCommands.processLocalCommandFiles(serviceContext);
    verify(ksqlEngine).cleanupOrphanedInternalTopics(any(), eq(ImmutableSet.of(QUERY_APP_ID1, QUERY_APP_ID2)));
    List<Path> paths = Files.list(dir.toPath()).collect(Collectors.toList());
    String expectedProcessedFileName = processedFile.getAbsolutePath() + LOCAL_COMMANDS_PROCESSED_SUFFIX;
    assertThat(paths.size(), is(2));
    assertThat(paths.stream().anyMatch(path -> path.toFile().getAbsolutePath().equals(expectedProcessedFileName)), is(true));
}
Also used : Path(java.nio.file.Path) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Mock(org.mockito.Mock) Assert.assertThrows(org.junit.Assert.assertThrows) ServiceContext(io.confluent.ksql.services.ServiceContext) RunWith(org.junit.runner.RunWith) Mockito.doThrow(org.mockito.Mockito.doThrow) TransientQueryMetadata(io.confluent.ksql.util.TransientQueryMetadata) PosixFilePermissions(java.nio.file.attribute.PosixFilePermissions) KsqlTestFolder(io.confluent.ksql.test.util.KsqlTestFolder) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Path(java.nio.file.Path) Before(org.junit.Before) ImmutableSet(com.google.common.collect.ImmutableSet) KsqlEngine(io.confluent.ksql.engine.KsqlEngine) Files(java.nio.file.Files) LOCAL_COMMANDS_PROCESSED_SUFFIX(io.confluent.ksql.rest.server.LocalCommands.LOCAL_COMMANDS_PROCESSED_SUFFIX) IOException(java.io.IOException) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) Collectors(java.util.stream.Collectors) File(java.io.File) Mockito.verify(org.mockito.Mockito.verify) KsqlServerException(io.confluent.ksql.util.KsqlServerException) List(java.util.List) Rule(org.junit.Rule) Paths(java.nio.file.Paths) Matchers.is(org.hamcrest.Matchers.is) Matchers.containsString(org.hamcrest.Matchers.containsString) MockitoJUnitRunner(org.mockito.junit.MockitoJUnitRunner) TemporaryFolder(org.junit.rules.TemporaryFolder) Matchers.containsString(org.hamcrest.Matchers.containsString) File(java.io.File) 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