Search in sources :

Example 51 with NewTopic

use of org.apache.kafka.clients.admin.NewTopic 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 52 with NewTopic

use of org.apache.kafka.clients.admin.NewTopic 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 53 with NewTopic

use of org.apache.kafka.clients.admin.NewTopic in project thingsboard by thingsboard.

the class TbKafkaAdmin method createTopicIfNotExists.

@Override
public void createTopicIfNotExists(String topic) {
    if (topics.contains(topic)) {
        return;
    }
    try {
        NewTopic newTopic = new NewTopic(topic, numPartitions, replicationFactor).configs(topicConfigs);
        createTopic(newTopic).values().get(topic).get();
        topics.add(topic);
    } catch (ExecutionException ee) {
        if (ee.getCause() instanceof TopicExistsException) {
        // do nothing
        } else {
            log.warn("[{}] Failed to create topic", topic, ee);
            throw new RuntimeException(ee);
        }
    } catch (Exception e) {
        log.warn("[{}] Failed to create topic", topic, e);
        throw new RuntimeException(e);
    }
}
Also used : NewTopic(org.apache.kafka.clients.admin.NewTopic) ExecutionException(java.util.concurrent.ExecutionException) TopicExistsException(org.apache.kafka.common.errors.TopicExistsException) ExecutionException(java.util.concurrent.ExecutionException) TopicExistsException(org.apache.kafka.common.errors.TopicExistsException)

Example 54 with NewTopic

use of org.apache.kafka.clients.admin.NewTopic in project cruise-control by linkedin.

the class LoadMonitorTaskRunnerTest method setUp.

/**
 * Setup the test.
 */
@Before
public void setUp() {
    super.setUp();
    Properties adminProps = new Properties();
    adminProps.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers());
    AdminClient adminClient = AdminClient.create(adminProps);
    Set<NewTopic> newTopics = new HashSet<>();
    for (int i = 0; i < NUM_TOPICS; i++) {
        newTopics.add(new NewTopic(TOPIC_PREFIX + i, NUM_PARTITIONS, (short) 1));
    }
    CreateTopicsResult createTopicsResult = adminClient.createTopics(newTopics);
    AtomicInteger adminFailed = new AtomicInteger(0);
    createTopicsResult.all().whenComplete((v, e) -> {
        if (e != null) {
            adminFailed.incrementAndGet();
        }
    });
    assertEquals(0, adminFailed.get());
}
Also used : CreateTopicsResult(org.apache.kafka.clients.admin.CreateTopicsResult) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) NewTopic(org.apache.kafka.clients.admin.NewTopic) Properties(java.util.Properties) AdminClient(org.apache.kafka.clients.admin.AdminClient) HashSet(java.util.HashSet) Before(org.junit.Before)

Example 55 with NewTopic

use of org.apache.kafka.clients.admin.NewTopic in project cruise-control by linkedin.

the class KafkaCruiseControlUtils method wrapTopic.

/**
 * Build a wrapper around the topic with the given desired properties and {@link #DEFAULT_CLEANUP_POLICY}.
 *
 * @param topic The name of the topic.
 * @param partitionCount Desired partition count.
 * @param replicationFactor Desired replication factor.
 * @param retentionMs Desired retention in milliseconds.
 * @return A wrapper around the topic with the given desired properties.
 */
public static NewTopic wrapTopic(String topic, int partitionCount, short replicationFactor, long retentionMs) {
    if (partitionCount <= 0 || replicationFactor <= 0 || retentionMs <= 0) {
        throw new IllegalArgumentException(String.format("Partition count (%d), replication factor (%d), and retention ms (%d)" + " must be positive for the topic (%s).", partitionCount, replicationFactor, retentionMs, topic));
    }
    NewTopic newTopic = new NewTopic(topic, partitionCount, replicationFactor);
    Map<String, String> config = new HashMap<>();
    config.put(RetentionMsProp(), Long.toString(retentionMs));
    config.put(CleanupPolicyProp(), DEFAULT_CLEANUP_POLICY);
    newTopic.configs(config);
    return newTopic;
}
Also used : HashMap(java.util.HashMap) NewTopic(org.apache.kafka.clients.admin.NewTopic)

Aggregations

NewTopic (org.apache.kafka.clients.admin.NewTopic)132 Test (org.junit.Test)65 HashMap (java.util.HashMap)37 AdminClient (org.apache.kafka.clients.admin.AdminClient)35 Cluster (org.apache.kafka.common.Cluster)24 ExecutionException (java.util.concurrent.ExecutionException)23 TopicExistsException (org.apache.kafka.common.errors.TopicExistsException)20 MockAdminClient (org.apache.kafka.clients.admin.MockAdminClient)19 Config (org.apache.kafka.clients.admin.Config)16 MockTime (org.apache.kafka.common.utils.MockTime)16 AdminClientUnitTestEnv (org.apache.kafka.clients.admin.AdminClientUnitTestEnv)15 Map (java.util.Map)14 TopicDescription (org.apache.kafka.clients.admin.TopicDescription)13 TopicConfig (org.apache.kafka.common.config.TopicConfig)13 StreamsConfig (org.apache.kafka.streams.StreamsConfig)12 ArrayList (java.util.ArrayList)11 CreateTopicsResult (org.apache.kafka.clients.admin.CreateTopicsResult)11 TimeoutException (org.apache.kafka.common.errors.TimeoutException)11 TopicMetadataAndConfig (org.apache.kafka.clients.admin.CreateTopicsResult.TopicMetadataAndConfig)10 ConsumerConfig (org.apache.kafka.clients.consumer.ConsumerConfig)10