Search in sources :

Example 11 with TopicExistsException

use of org.apache.kafka.common.errors.TopicExistsException in project kafka by apache.

the class InternalTopicManager method processCreateTopicResults.

private void processCreateTopicResults(final CreateTopicsResult createTopicsResult, final Set<String> topicStillToCreate, final Set<String> createdTopics, final long deadline) {
    final Map<String, Throwable> lastErrorsSeenForTopic = new HashMap<>();
    final Map<String, KafkaFuture<Void>> createResultForTopic = createTopicsResult.values();
    while (!createResultForTopic.isEmpty()) {
        for (final String topicName : new HashSet<>(topicStillToCreate)) {
            if (!createResultForTopic.containsKey(topicName)) {
                cleanUpCreatedTopics(createdTopics);
                throw new IllegalStateException("Create topic results do not contain internal topic " + topicName + " to setup. " + BUG_ERROR_MESSAGE);
            }
            final KafkaFuture<Void> createResult = createResultForTopic.get(topicName);
            if (createResult.isDone()) {
                try {
                    createResult.get();
                    createdTopics.add(topicName);
                    topicStillToCreate.remove(topicName);
                } catch (final ExecutionException executionException) {
                    final Throwable cause = executionException.getCause();
                    if (cause instanceof TopicExistsException) {
                        lastErrorsSeenForTopic.put(topicName, cause);
                        log.info("Internal topic {} already exists. Topic is probably marked for deletion. " + "Will retry to create this topic later (to let broker complete async delete operation first)", topicName);
                    } else if (cause instanceof TimeoutException) {
                        lastErrorsSeenForTopic.put(topicName, cause);
                        log.info("Creating internal topic {} timed out.", topicName);
                    } else {
                        cleanUpCreatedTopics(createdTopics);
                        log.error("Unexpected error during creation of internal topic: ", cause);
                        throw new StreamsException(String.format("Could not create internal topic %s for the following reason: ", topicName), cause);
                    }
                } catch (final InterruptedException interruptedException) {
                    throw new InterruptException(interruptedException);
                } finally {
                    createResultForTopic.remove(topicName);
                }
            }
        }
        maybeThrowTimeoutExceptionDuringSetup(topicStillToCreate, createdTopics, lastErrorsSeenForTopic, deadline);
        if (!createResultForTopic.isEmpty()) {
            Utils.sleep(100);
        }
    }
}
Also used : KafkaFuture(org.apache.kafka.common.KafkaFuture) HashMap(java.util.HashMap) StreamsException(org.apache.kafka.streams.errors.StreamsException) InterruptException(org.apache.kafka.common.errors.InterruptException) TopicExistsException(org.apache.kafka.common.errors.TopicExistsException) ExecutionException(java.util.concurrent.ExecutionException) HashSet(java.util.HashSet) TimeoutException(org.apache.kafka.common.errors.TimeoutException)

Example 12 with TopicExistsException

use of org.apache.kafka.common.errors.TopicExistsException in project zipkin by openzipkin.

the class KafkaExtension method prepareTopics.

void prepareTopics(String topics, int partitions) {
    Properties config = new Properties();
    config.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServer());
    List<NewTopic> newTopics = new ArrayList<>();
    for (String topic : topics.split(",")) {
        if ("".equals(topic))
            continue;
        newTopics.add(new NewTopic(topic, partitions, (short) 1));
    }
    try (AdminClient adminClient = AdminClient.create(config)) {
        adminClient.createTopics(newTopics).all().get();
    } catch (InterruptedException | ExecutionException e) {
        if (e.getCause() != null && e.getCause() instanceof TopicExistsException)
            return;
        throw new TestAbortedException("Topics could not be created " + newTopics + ": " + e.getMessage(), e);
    }
}
Also used : ArrayList(java.util.ArrayList) TestAbortedException(org.opentest4j.TestAbortedException) NewTopic(org.apache.kafka.clients.admin.NewTopic) Properties(java.util.Properties) ExecutionException(java.util.concurrent.ExecutionException) TopicExistsException(org.apache.kafka.common.errors.TopicExistsException) AdminClient(org.apache.kafka.clients.admin.AdminClient)

Example 13 with TopicExistsException

use of org.apache.kafka.common.errors.TopicExistsException in project hono by eclipse.

the class KafkaBasedInternalCommandConsumer method createTopic.

private Future<Void> createTopic() {
    final Promise<Void> promise = Promise.promise();
    final String topicName = getTopicName();
    // create topic with unspecified replication factor - broker "default.replication.factor" should be used
    final NewTopic newTopic = new NewTopic(topicName, Optional.of(NUM_PARTITIONS), Optional.empty());
    adminClient.createTopics(List.of(newTopic)).all().whenComplete((v, ex) -> {
        context.runOnContext(v1 -> Optional.ofNullable(ex).filter(e -> !(e instanceof TopicExistsException)).ifPresentOrElse(promise::fail, promise::complete));
    });
    return promise.future().onSuccess(v -> LOG.debug("created topic [{}]", topicName)).onFailure(thr -> LOG.error("error creating topic [{}]", topicName, thr));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) MessagingKafkaConsumerConfigProperties(org.eclipse.hono.client.kafka.consumer.MessagingKafkaConsumerConfigProperties) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CommandHandlerWrapper(org.eclipse.hono.client.command.CommandHandlerWrapper) TenantDisabledOrNotRegisteredException(org.eclipse.hono.client.registry.TenantDisabledOrNotRegisteredException) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Supplier(java.util.function.Supplier) CommandResponseSender(org.eclipse.hono.client.command.CommandResponseSender) KafkaClientFactory(org.eclipse.hono.client.kafka.KafkaClientFactory) Context(io.vertx.core.Context) NoConsumerException(org.eclipse.hono.client.NoConsumerException) CompositeFuture(io.vertx.core.CompositeFuture) Status(io.vertx.ext.healthchecks.Status) HealthCheckHandler(io.vertx.ext.healthchecks.HealthCheckHandler) KafkaClientMetricsSupport(org.eclipse.hono.client.kafka.metrics.KafkaClientMetricsSupport) Map(java.util.Map) KafkaAdminClientConfigProperties(org.eclipse.hono.client.kafka.KafkaAdminClientConfigProperties) Admin(org.apache.kafka.clients.admin.Admin) CommandHandlers(org.eclipse.hono.client.command.CommandHandlers) KafkaTracingHelper(org.eclipse.hono.client.kafka.tracing.KafkaTracingHelper) CommonClientConfigs(org.apache.kafka.clients.CommonClientConfigs) Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) Promise(io.vertx.core.Promise) NewTopic(org.apache.kafka.clients.admin.NewTopic) CommandContext(org.eclipse.hono.client.command.CommandContext) Vertx(io.vertx.core.Vertx) Set(java.util.Set) ServerErrorException(org.eclipse.hono.client.ServerErrorException) ConsumerConfig(org.apache.kafka.clients.consumer.ConsumerConfig) KafkaRecordHelper(org.eclipse.hono.client.kafka.KafkaRecordHelper) TenantClient(org.eclipse.hono.client.registry.TenantClient) MessageHelper(org.eclipse.hono.util.MessageHelper) Future(io.vertx.core.Future) InternalCommandConsumer(org.eclipse.hono.client.command.InternalCommandConsumer) SpanContext(io.opentracing.SpanContext) TopicPartition(io.vertx.kafka.client.common.TopicPartition) Objects(java.util.Objects) HonoTopic(org.eclipse.hono.client.kafka.HonoTopic) List(java.util.List) TopicExistsException(org.apache.kafka.common.errors.TopicExistsException) Buffer(io.vertx.core.buffer.Buffer) KafkaConsumerRecord(io.vertx.kafka.client.consumer.KafkaConsumerRecord) Optional(java.util.Optional) Span(io.opentracing.Span) KafkaConsumer(io.vertx.kafka.client.consumer.KafkaConsumer) NewTopic(org.apache.kafka.clients.admin.NewTopic) TopicExistsException(org.apache.kafka.common.errors.TopicExistsException)

Example 14 with TopicExistsException

use of org.apache.kafka.common.errors.TopicExistsException in project nakadi by zalando.

the class KafkaTopicRepository method createTopic.

private void createTopic(final String topic, final int partitionsNum, final int replicaFactor, final long retentionMs, final long rotationMs) throws TopicCreationException {
    try {
        doWithZkUtils(zkUtils -> {
            final Properties topicConfig = new Properties();
            topicConfig.setProperty("retention.ms", Long.toString(retentionMs));
            topicConfig.setProperty("segment.ms", Long.toString(rotationMs));
            AdminUtils.createTopic(zkUtils, topic, partitionsNum, replicaFactor, topicConfig, RackAwareMode.Safe$.MODULE$);
        });
    } catch (final TopicExistsException e) {
        throw new TopicCreationException("Topic with name " + topic + " already exists (or wasn't completely removed yet)", e);
    } catch (final Exception e) {
        throw new TopicCreationException("Unable to create topic " + topic, e);
    }
    // Next step is to wait for topic initialization. On can not skip this task, cause kafka instances may not
    // receive information about topic creation, which in turn will block publishing.
    // This kind of behavior was observed during tests, but may also present on highly loaded event types.
    final long timeoutMillis = TimeUnit.SECONDS.toMillis(5);
    final Boolean allowsConsumption = Retryer.executeWithRetry(() -> {
        try (Consumer<byte[], byte[]> consumer = kafkaFactory.getConsumer()) {
            return null != consumer.partitionsFor(topic);
        }
    }, new RetryForSpecifiedTimeStrategy<Boolean>(timeoutMillis).withWaitBetweenEachTry(100L).withResultsThatForceRetry(Boolean.FALSE));
    if (!Boolean.TRUE.equals(allowsConsumption)) {
        throw new TopicCreationException("Failed to confirm topic creation within " + timeoutMillis + " millis");
    }
}
Also used : TopicCreationException(org.zalando.nakadi.exceptions.TopicCreationException) Properties(java.util.Properties) TopicExistsException(org.apache.kafka.common.errors.TopicExistsException) EventPublishingException(org.zalando.nakadi.exceptions.EventPublishingException) NotLeaderForPartitionException(org.apache.kafka.common.errors.NotLeaderForPartitionException) TimeoutException(java.util.concurrent.TimeoutException) TopicRepositoryException(org.zalando.nakadi.exceptions.runtime.TopicRepositoryException) ServiceUnavailableException(org.zalando.nakadi.exceptions.ServiceUnavailableException) InvalidCursorException(org.zalando.nakadi.exceptions.InvalidCursorException) TopicDeletionException(org.zalando.nakadi.exceptions.TopicDeletionException) TopicExistsException(org.apache.kafka.common.errors.TopicExistsException) UnknownTopicOrPartitionException(org.apache.kafka.common.errors.UnknownTopicOrPartitionException) NetworkException(org.apache.kafka.common.errors.NetworkException) TopicCreationException(org.zalando.nakadi.exceptions.TopicCreationException) TopicConfigException(org.zalando.nakadi.exceptions.runtime.TopicConfigException) UnknownServerException(org.apache.kafka.common.errors.UnknownServerException) InterruptException(org.apache.kafka.common.errors.InterruptException) ExecutionException(java.util.concurrent.ExecutionException)

Example 15 with TopicExistsException

use of org.apache.kafka.common.errors.TopicExistsException in project ksql by confluentinc.

the class KafkaTopicClientImplTest method createTopicReturningTopicExistsException.

@SuppressWarnings("unchecked")
private CreateTopicsResult createTopicReturningTopicExistsException() {
    CreateTopicsResult createTopicsResult = niceMock(CreateTopicsResult.class);
    expect(createTopicsResult.all()).andReturn(failedFuture(new TopicExistsException("Topic already exists")));
    replay(createTopicsResult);
    return createTopicsResult;
}
Also used : CreateTopicsResult(org.apache.kafka.clients.admin.CreateTopicsResult) TopicExistsException(org.apache.kafka.common.errors.TopicExistsException)

Aggregations

TopicExistsException (org.apache.kafka.common.errors.TopicExistsException)23 NewTopic (org.apache.kafka.clients.admin.NewTopic)17 HashMap (java.util.HashMap)11 ExecutionException (java.util.concurrent.ExecutionException)11 TimeoutException (org.apache.kafka.common.errors.TimeoutException)9 Map (java.util.Map)7 KafkaFuture (org.apache.kafka.common.KafkaFuture)7 KafkaFutureImpl (org.apache.kafka.common.internals.KafkaFutureImpl)7 ArrayList (java.util.ArrayList)5 HashSet (java.util.HashSet)5 AdminClient (org.apache.kafka.clients.admin.AdminClient)5 TopicMetadataAndConfig (org.apache.kafka.clients.admin.CreateTopicsResult.TopicMetadataAndConfig)5 ConsumerConfig (org.apache.kafka.clients.consumer.ConsumerConfig)5 StreamsConfig (org.apache.kafka.streams.StreamsConfig)5 Test (org.junit.Test)5 Config (org.apache.kafka.clients.admin.Config)4 MockAdminClient (org.apache.kafka.clients.admin.MockAdminClient)4 ProducerConfig (org.apache.kafka.clients.producer.ProducerConfig)4 TopicConfig (org.apache.kafka.common.config.TopicConfig)4 CreateTopicsResult (org.apache.kafka.clients.admin.CreateTopicsResult)3