Search in sources :

Example 11 with AdminClient

use of org.apache.kafka.clients.admin.AdminClient in project flink by apache.

the class KafkaSourceReaderTest method testCommitEmptyOffsets.

@Test
void testCommitEmptyOffsets() throws Exception {
    final String groupId = "testCommitEmptyOffsets";
    try (KafkaSourceReader<Integer> reader = (KafkaSourceReader<Integer>) createReader(Boundedness.CONTINUOUS_UNBOUNDED, groupId)) {
        reader.snapshotState(100L);
        reader.notifyCheckpointComplete(100L);
    }
    // Verify the committed offsets.
    try (AdminClient adminClient = KafkaSourceTestEnv.getAdminClient()) {
        Map<TopicPartition, OffsetAndMetadata> committedOffsets = adminClient.listConsumerGroupOffsets(groupId).partitionsToOffsetAndMetadata().get();
        assertThat(committedOffsets).isEmpty();
    }
}
Also used : TopicPartition(org.apache.kafka.common.TopicPartition) OffsetAndMetadata(org.apache.kafka.clients.consumer.OffsetAndMetadata) AdminClient(org.apache.kafka.clients.admin.AdminClient) Test(org.junit.jupiter.api.Test)

Example 12 with AdminClient

use of org.apache.kafka.clients.admin.AdminClient in project flink by apache.

the class KafkaSourceReaderTest method setup.

@BeforeAll
public static void setup() throws Throwable {
    KafkaSourceTestEnv.setup();
    try (AdminClient adminClient = KafkaSourceTestEnv.getAdminClient()) {
        adminClient.createTopics(Collections.singleton(new NewTopic(TOPIC, NUM_PARTITIONS, (short) 1)));
        // Use the admin client to trigger the creation of internal __consumer_offsets topic.
        // This makes sure that we won't see unavailable coordinator in the tests.
        waitUtil(() -> {
            try {
                adminClient.listConsumerGroupOffsets("AnyGroup").partitionsToOffsetAndMetadata().get();
            } catch (Exception e) {
                return false;
            }
            return true;
        }, Duration.ofSeconds(60), "Waiting for offsets topic creation failed.");
    }
    KafkaSourceTestEnv.produceToKafka(getRecords(), StringSerializer.class, IntegerSerializer.class);
}
Also used : NewTopic(org.apache.kafka.clients.admin.NewTopic) AdminClient(org.apache.kafka.clients.admin.AdminClient) BeforeAll(org.junit.jupiter.api.BeforeAll)

Example 13 with AdminClient

use of org.apache.kafka.clients.admin.AdminClient in project flink by apache.

the class KafkaContainerClient method createTopic.

public void createTopic(int replicationFactor, int numPartitions, String topic) {
    Map<String, Object> properties = new HashMap<>();
    properties.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, container.getBootstrapServers());
    try (AdminClient admin = AdminClient.create(properties)) {
        admin.createTopics(Collections.singletonList(new NewTopic(topic, numPartitions, (short) replicationFactor)));
    }
}
Also used : HashMap(java.util.HashMap) NewTopic(org.apache.kafka.clients.admin.NewTopic) AdminClient(org.apache.kafka.clients.admin.AdminClient)

Example 14 with AdminClient

use of org.apache.kafka.clients.admin.AdminClient in project kafka by apache.

the class TopicBasedRemoteLogMetadataManager method initializeResources.

private void initializeResources() {
    log.info("Initializing the resources.");
    final NewTopic remoteLogMetadataTopicRequest = createRemoteLogMetadataTopicRequest();
    boolean topicCreated = false;
    long startTimeMs = time.milliseconds();
    AdminClient adminClient = null;
    try {
        adminClient = AdminClient.create(rlmmConfig.producerProperties());
        // Stop if it is already initialized or closing.
        while (!(initialized.get() || closing.get())) {
            // If it is timed out then raise an error to exit.
            if (time.milliseconds() - startTimeMs > rlmmConfig.initializationRetryMaxTimeoutMs()) {
                log.error("Timed out in initializing the resources, retried to initialize the resource for [{}] ms.", rlmmConfig.initializationRetryMaxTimeoutMs());
                initializationFailed = true;
                return;
            }
            if (!topicCreated) {
                topicCreated = createTopic(adminClient, remoteLogMetadataTopicRequest);
            }
            if (!topicCreated) {
                // Sleep for INITIALIZATION_RETRY_INTERVAL_MS before trying to create the topic again.
                log.info("Sleep for : {} ms before it is retried again.", rlmmConfig.initializationRetryIntervalMs());
                Utils.sleep(rlmmConfig.initializationRetryIntervalMs());
                continue;
            } else {
                // If topic is already created, validate the existing topic partitions.
                try {
                    String topicName = remoteLogMetadataTopicRequest.name();
                    // If the existing topic partition size is not same as configured, mark initialization as failed and exit.
                    if (!isPartitionsCountSameAsConfigured(adminClient, topicName)) {
                        initializationFailed = true;
                    }
                } catch (Exception e) {
                    log.info("Sleep for : {} ms before it is retried again.", rlmmConfig.initializationRetryIntervalMs());
                    Utils.sleep(rlmmConfig.initializationRetryIntervalMs());
                    continue;
                }
            }
            // Create producer and consumer managers.
            lock.writeLock().lock();
            try {
                producerManager = new ProducerManager(rlmmConfig, rlmmTopicPartitioner);
                consumerManager = new ConsumerManager(rlmmConfig, remotePartitionMetadataStore, rlmmTopicPartitioner, time);
                if (startConsumerThread) {
                    consumerManager.startConsumerThread();
                } else {
                    log.info("RLMM Consumer task thread is not configured to be started.");
                }
                if (!pendingAssignPartitions.isEmpty()) {
                    assignPartitions(pendingAssignPartitions);
                    pendingAssignPartitions.clear();
                }
                initialized.set(true);
                log.info("Initialized resources successfully.");
            } catch (Exception e) {
                log.error("Encountered error while initializing producer/consumer", e);
                return;
            } finally {
                lock.writeLock().unlock();
            }
        }
    } finally {
        if (adminClient != null) {
            try {
                adminClient.close(Duration.ofSeconds(10));
            } catch (Exception e) {
                // Ignore the error.
                log.debug("Error occurred while closing the admin client", e);
            }
        }
    }
}
Also used : NewTopic(org.apache.kafka.clients.admin.NewTopic) RemoteStorageException(org.apache.kafka.server.log.remote.storage.RemoteStorageException) KafkaException(org.apache.kafka.common.KafkaException) TimeoutException(java.util.concurrent.TimeoutException) RetriableException(org.apache.kafka.common.errors.RetriableException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) TopicExistsException(org.apache.kafka.common.errors.TopicExistsException) AdminClient(org.apache.kafka.clients.admin.AdminClient)

Example 15 with AdminClient

use of org.apache.kafka.clients.admin.AdminClient in project kafka by apache.

the class InternalTopicManagerTest method shouldThrowTimeoutExceptionWhenFuturesNeverCompleteDuringValidation.

@Test
public void shouldThrowTimeoutExceptionWhenFuturesNeverCompleteDuringValidation() {
    final AdminClient admin = EasyMock.createNiceMock(AdminClient.class);
    final MockTime time = new MockTime((Integer) config.get(StreamsConfig.consumerPrefix(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG)) / 3);
    final InternalTopicManager topicManager = new InternalTopicManager(time, admin, new StreamsConfig(config));
    final KafkaFutureImpl<TopicDescription> topicDescriptionFutureThatNeverCompletes = new KafkaFutureImpl<>();
    EasyMock.expect(admin.describeTopics(Collections.singleton(topic1))).andStubAnswer(() -> new MockDescribeTopicsResult(mkMap(mkEntry(topic1, topicDescriptionFutureThatNeverCompletes))));
    final KafkaFutureImpl<Config> topicConfigSuccessfulFuture = new KafkaFutureImpl<>();
    topicConfigSuccessfulFuture.complete(new Config(repartitionTopicConfig().entrySet().stream().map(entry -> new ConfigEntry(entry.getKey(), entry.getValue())).collect(Collectors.toSet())));
    final ConfigResource topicResource = new ConfigResource(Type.TOPIC, topic1);
    EasyMock.expect(admin.describeConfigs(Collections.singleton(topicResource))).andStubAnswer(() -> new MockDescribeConfigsResult(mkMap(mkEntry(topicResource, topicConfigSuccessfulFuture))));
    EasyMock.replay(admin);
    final InternalTopicConfig internalTopicConfig = setupRepartitionTopicConfig(topic1, 1);
    assertThrows(TimeoutException.class, () -> topicManager.validate(Collections.singletonMap(topic1, internalTopicConfig)));
}
Also used : MockTime(org.apache.kafka.common.utils.MockTime) DescribeConfigsResult(org.apache.kafka.clients.admin.DescribeConfigsResult) Matchers.not(org.hamcrest.Matchers.not) ConfigEntry(org.apache.kafka.clients.admin.ConfigEntry) StreamsException(org.apache.kafka.streams.errors.StreamsException) ValidationResult(org.apache.kafka.streams.processor.internals.InternalTopicManager.ValidationResult) Matchers.hasKey(org.hamcrest.Matchers.hasKey) AdminClient(org.apache.kafka.clients.admin.AdminClient) Utils.mkMap(org.apache.kafka.common.utils.Utils.mkMap) After(org.junit.After) Map(java.util.Map) DeleteTopicsResult(org.apache.kafka.clients.admin.DeleteTopicsResult) Assert.fail(org.junit.Assert.fail) TopicConfig(org.apache.kafka.common.config.TopicConfig) CreatableReplicaAssignmentCollection(org.apache.kafka.common.message.CreateTopicsRequestData.CreatableReplicaAssignmentCollection) Collection(java.util.Collection) Utils.mkSet(org.apache.kafka.common.utils.Utils.mkSet) Set(java.util.Set) ConsumerConfig(org.apache.kafka.clients.consumer.ConsumerConfig) KafkaFuture(org.apache.kafka.common.KafkaFuture) Collectors(java.util.stream.Collectors) MockAdminClient(org.apache.kafka.clients.admin.MockAdminClient) TopicExistsException(org.apache.kafka.common.errors.TopicExistsException) List(java.util.List) Utils.mkEntry(org.apache.kafka.common.utils.Utils.mkEntry) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Optional(java.util.Optional) Node(org.apache.kafka.common.Node) UnknownTopicOrPartitionException(org.apache.kafka.common.errors.UnknownTopicOrPartitionException) Matchers.is(org.hamcrest.Matchers.is) CreateTopicsOptions(org.apache.kafka.clients.admin.CreateTopicsOptions) Type(org.apache.kafka.common.config.ConfigResource.Type) Config(org.apache.kafka.clients.admin.Config) Uuid(org.apache.kafka.common.Uuid) StreamsConfig(org.apache.kafka.streams.StreamsConfig) CreateTopicsRequest(org.apache.kafka.common.requests.CreateTopicsRequest) Assert.assertThrows(org.junit.Assert.assertThrows) HashMap(java.util.HashMap) LeaderNotAvailableException(org.apache.kafka.common.errors.LeaderNotAvailableException) CreatableTopic(org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopic) ArrayList(java.util.ArrayList) ConfigResource(org.apache.kafka.common.config.ConfigResource) DescribeTopicsResult(org.apache.kafka.clients.admin.DescribeTopicsResult) CreateTopicsResult(org.apache.kafka.clients.admin.CreateTopicsResult) TopicDescription(org.apache.kafka.clients.admin.TopicDescription) KafkaFutureImpl(org.apache.kafka.common.internals.KafkaFutureImpl) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) ProducerConfig(org.apache.kafka.clients.producer.ProducerConfig) Before(org.junit.Before) TopicPartitionInfo(org.apache.kafka.common.TopicPartitionInfo) TimeoutException(org.apache.kafka.common.errors.TimeoutException) Matchers.empty(org.hamcrest.Matchers.empty) NewTopic(org.apache.kafka.clients.admin.NewTopic) Test(org.junit.Test) EasyMock(org.easymock.EasyMock) TopicMetadataAndConfig(org.apache.kafka.clients.admin.CreateTopicsResult.TopicMetadataAndConfig) CreatableTopicCollection(org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopicCollection) CreateTopicsRequestData(org.apache.kafka.common.message.CreateTopicsRequestData) Matchers.hasItem(org.hamcrest.Matchers.hasItem) Assert.assertNull(org.junit.Assert.assertNull) LogCaptureAppender(org.apache.kafka.streams.processor.internals.testutil.LogCaptureAppender) UnsupportedVersionException(org.apache.kafka.common.errors.UnsupportedVersionException) Matchers.anEmptyMap(org.hamcrest.Matchers.anEmptyMap) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) TopicConfig(org.apache.kafka.common.config.TopicConfig) ConsumerConfig(org.apache.kafka.clients.consumer.ConsumerConfig) Config(org.apache.kafka.clients.admin.Config) StreamsConfig(org.apache.kafka.streams.StreamsConfig) ProducerConfig(org.apache.kafka.clients.producer.ProducerConfig) TopicMetadataAndConfig(org.apache.kafka.clients.admin.CreateTopicsResult.TopicMetadataAndConfig) KafkaFutureImpl(org.apache.kafka.common.internals.KafkaFutureImpl) ConfigResource(org.apache.kafka.common.config.ConfigResource) ConfigEntry(org.apache.kafka.clients.admin.ConfigEntry) TopicDescription(org.apache.kafka.clients.admin.TopicDescription) MockTime(org.apache.kafka.common.utils.MockTime) AdminClient(org.apache.kafka.clients.admin.AdminClient) MockAdminClient(org.apache.kafka.clients.admin.MockAdminClient) StreamsConfig(org.apache.kafka.streams.StreamsConfig) Test(org.junit.Test)

Aggregations

AdminClient (org.apache.kafka.clients.admin.AdminClient)70 Test (org.junit.Test)38 KafkaFutureImpl (org.apache.kafka.common.internals.KafkaFutureImpl)31 NewTopic (org.apache.kafka.clients.admin.NewTopic)30 StreamsConfig (org.apache.kafka.streams.StreamsConfig)29 MockAdminClient (org.apache.kafka.clients.admin.MockAdminClient)27 HashMap (java.util.HashMap)24 TopicMetadataAndConfig (org.apache.kafka.clients.admin.CreateTopicsResult.TopicMetadataAndConfig)18 TopicDescription (org.apache.kafka.clients.admin.TopicDescription)18 Config (org.apache.kafka.clients.admin.Config)15 Map (java.util.Map)14 ConsumerConfig (org.apache.kafka.clients.consumer.ConsumerConfig)14 ProducerConfig (org.apache.kafka.clients.producer.ProducerConfig)14 TopicConfig (org.apache.kafka.common.config.TopicConfig)13 MockTime (org.apache.kafka.common.utils.MockTime)13 TopicExistsException (org.apache.kafka.common.errors.TopicExistsException)11 ArrayList (java.util.ArrayList)10 TopicPartitionInfo (org.apache.kafka.common.TopicPartitionInfo)10 ConfigResource (org.apache.kafka.common.config.ConfigResource)10 UnknownTopicOrPartitionException (org.apache.kafka.common.errors.UnknownTopicOrPartitionException)10