Search in sources :

Example 1 with KafkaAdminClient

use of io.vertx.kafka.admin.KafkaAdminClient in project hono by eclipse.

the class IntegrationTestSupport method deleteTenantKafkaTopics.

private Future<Void> deleteTenantKafkaTopics(final List<String> tenantsToDelete) {
    if (!isUsingKafkaMessaging()) {
        return Future.succeededFuture();
    }
    // topics for the given tenants are not deleted right away: It could be that the offset-commit interval of the CommandRouter
    // command consumer (5s) hasn't elapsed yet and it has to be avoided to delete the topics before the consumer has
    // committed corresponding offsets (otherwise the consumer will retry the commit for some time and be blocked during that time)
    final Promise<Void> tenantTopicsDeletionDonePromise = Promise.promise();
    tenantsToDeleteTopicsForAfterDelay.add(Pair.of(tenantsToDelete, Instant.now()));
    final List<String> tenantsToDeleteTopicsForNow = new LinkedList<>();
    final Instant nowMinusCommitInterval = Instant.now().minus(// commit interval with added buffer
    AsyncHandlingAutoCommitKafkaConsumer.DEFAULT_COMMIT_INTERVAL.plusSeconds(1));
    final Iterator<Pair<List<String>, Instant>> iterator = tenantsToDeleteTopicsForAfterDelay.iterator();
    while (iterator.hasNext()) {
        final Pair<List<String>, Instant> tenantsToDeleteAndInstantPair = iterator.next();
        if (tenantsToDeleteAndInstantPair.two().isBefore(nowMinusCommitInterval)) {
            tenantsToDeleteTopicsForNow.addAll(tenantsToDeleteAndInstantPair.one());
            iterator.remove();
        }
    }
    if (!tenantsToDeleteTopicsForNow.isEmpty()) {
        final KafkaAdminClient adminClient = KafkaAdminClient.create(vertx, getKafkaAdminClientConfig().getAdminClientConfig("test"));
        final Promise<Void> adminClientClosedPromise = Promise.promise();
        LOGGER.debug("deleting topics for temporary tenants {}", tenantsToDeleteTopicsForNow);
        final List<String> topicNames = tenantsToDeleteTopicsForNow.stream().flatMap(tenant -> HonoTopic.Type.MESSAGING_API_TYPES.stream().map(type -> new HonoTopic(type, tenant).toString())).collect(Collectors.toList());
        adminClient.deleteTopics(topicNames, ar -> {
            // note that the result will probably have failed with an UnknownTopicOrPartitionException here;
            // not necessarily all tenant topics may have been created before
            LOGGER.debug("done triggering deletion of topics for tenants {}", tenantsToDeleteTopicsForNow);
            adminClient.close(adminClientClosedPromise);
        });
        adminClientClosedPromise.future().recover(thr -> {
            LOGGER.warn("error closing Kafka admin client", thr);
            return Future.succeededFuture();
        }).onComplete(tenantTopicsDeletionDonePromise);
    } else {
        tenantTopicsDeletionDonePromise.complete();
    }
    return tenantTopicsDeletionDonePromise.future();
}
Also used : HttpURLConnection(java.net.HttpURLConnection) X509Certificate(java.security.cert.X509Certificate) KeyPair(java.security.KeyPair) ApplicationClient(org.eclipse.hono.application.client.ApplicationClient) Arrays(java.util.Arrays) MessagingKafkaConsumerConfigProperties(org.eclipse.hono.client.kafka.consumer.MessagingKafkaConsumerConfigProperties) DownstreamMessage(org.eclipse.hono.application.client.DownstreamMessage) MessagingKafkaProducerConfigProperties(org.eclipse.hono.client.kafka.producer.MessagingKafkaProducerConfigProperties) TenantConstants(org.eclipse.hono.util.TenantConstants) LoggerFactory(org.slf4j.LoggerFactory) TimeoutException(java.util.concurrent.TimeoutException) VertxTools(org.eclipse.hono.test.VertxTools) InetAddress(java.net.InetAddress) GeneralSecurityException(java.security.GeneralSecurityException) MessagingType(org.eclipse.hono.util.MessagingType) PskCredential(org.eclipse.hono.service.management.credentials.PskCredential) ProtonBasedApplicationClient(org.eclipse.hono.application.client.amqp.ProtonBasedApplicationClient) Map(java.util.Map) Pair(org.eclipse.hono.util.Pair) JsonObject(io.vertx.core.json.JsonObject) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) KeyPairGenerator(java.security.KeyPairGenerator) Device(org.eclipse.hono.service.management.device.Device) MessageContext(org.eclipse.hono.application.client.MessageContext) Truth.assertWithMessage(com.google.common.truth.Truth.assertWithMessage) CachingKafkaProducerFactory(org.eclipse.hono.client.kafka.producer.CachingKafkaProducerFactory) Set(java.util.Set) ConsumerConfig(org.apache.kafka.clients.consumer.ConsumerConfig) UUID(java.util.UUID) Instant(java.time.Instant) MessageHelper(org.eclipse.hono.util.MessageHelper) RequestResponseApiConstants(org.eclipse.hono.util.RequestResponseApiConstants) Collectors(java.util.stream.Collectors) EventConstants(org.eclipse.hono.util.EventConstants) Future(io.vertx.core.Future) StandardCharsets(java.nio.charset.StandardCharsets) AsyncHandlingAutoCommitKafkaConsumer(org.eclipse.hono.client.kafka.consumer.AsyncHandlingAutoCommitKafkaConsumer) Objects(java.util.Objects) Base64(java.util.Base64) List(java.util.List) KafkaProducerFactory(org.eclipse.hono.client.kafka.producer.KafkaProducerFactory) Buffer(io.vertx.core.buffer.Buffer) MessageProperties(org.eclipse.hono.application.client.MessageProperties) Optional(java.util.Optional) Checkpoint(io.vertx.junit5.Checkpoint) Queue(java.util.Queue) VertxTestContext(io.vertx.junit5.VertxTestContext) HttpResponse(io.vertx.ext.web.client.HttpResponse) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Credentials(org.eclipse.hono.service.management.credentials.Credentials) HashMap(java.util.HashMap) OptionalInt(java.util.OptionalInt) Function(java.util.function.Function) Constants(org.eclipse.hono.util.Constants) TimeUntilDisconnectNotification(org.eclipse.hono.util.TimeUntilDisconnectNotification) HashSet(java.util.HashSet) CompositeFuture(io.vertx.core.CompositeFuture) KafkaAdminClientConfigProperties(org.eclipse.hono.client.kafka.KafkaAdminClientConfigProperties) LinkedList(java.util.LinkedList) HonoConnection(org.eclipse.hono.client.HonoConnection) CommandConstants(org.eclipse.hono.util.CommandConstants) ProducerConfig(org.apache.kafka.clients.producer.ProducerConfig) RegistryManagementConstants(org.eclipse.hono.util.RegistryManagementConstants) Strings(org.eclipse.hono.util.Strings) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) Promise(io.vertx.core.Promise) KafkaApplicationClientImpl(org.eclipse.hono.application.client.kafka.impl.KafkaApplicationClientImpl) Vertx(io.vertx.core.Vertx) Truth.assertThat(com.google.common.truth.Truth.assertThat) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) HonoTopic(org.eclipse.hono.client.kafka.HonoTopic) JsonArray(io.vertx.core.json.JsonArray) MessageConsumer(org.eclipse.hono.application.client.MessageConsumer) SendMessageTimeoutException(org.eclipse.hono.client.SendMessageTimeoutException) SendMessageSampler(org.eclipse.hono.client.SendMessageSampler) NoopSpan(io.opentracing.noop.NoopSpan) GenericSenderLink(org.eclipse.hono.client.amqp.GenericSenderLink) Handler(io.vertx.core.Handler) PasswordCredential(org.eclipse.hono.service.management.credentials.PasswordCredential) KafkaAdminClient(io.vertx.kafka.admin.KafkaAdminClient) KafkaAdminClient(io.vertx.kafka.admin.KafkaAdminClient) Instant(java.time.Instant) HonoTopic(org.eclipse.hono.client.kafka.HonoTopic) LinkedList(java.util.LinkedList) List(java.util.List) LinkedList(java.util.LinkedList) KeyPair(java.security.KeyPair) Pair(org.eclipse.hono.util.Pair)

Example 2 with KafkaAdminClient

use of io.vertx.kafka.admin.KafkaAdminClient in project hono by eclipse.

the class InternalKafkaTopicCleanupServiceTest method setUp.

/**
 * Sets up fixture.
 */
@BeforeEach
public void setUp() {
    final Vertx vertx = mock(Vertx.class);
    adapterInstanceStatusService = mock(AdapterInstanceStatusService.class);
    kafkaAdminClient = mock(KafkaAdminClient.class);
    internalKafkaTopicCleanupService = new InternalKafkaTopicCleanupService(vertx, adapterInstanceStatusService, kafkaAdminClient);
    internalKafkaTopicCleanupService.start();
}
Also used : AdapterInstanceStatusService(org.eclipse.hono.commandrouter.AdapterInstanceStatusService) KafkaAdminClient(io.vertx.kafka.admin.KafkaAdminClient) Vertx(io.vertx.core.Vertx) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 3 with KafkaAdminClient

use of io.vertx.kafka.admin.KafkaAdminClient in project hono by eclipse.

the class InternalKafkaTopicCleanupServiceTest method testPerformCleanup.

/**
 * Verifies that the service deletes topics identified as obsolete.
 */
@Test
@SuppressWarnings("unchecked")
void testPerformCleanup() {
    final AtomicInteger counter = new AtomicInteger();
    final String podName = "myAdapter";
    final String aliveContainerId = "0ad9864b08bf";
    final String deadContainerId = "000000000000";
    final Set<String> toBeDeletedCmdInternalTopics = new HashSet<>();
    toBeDeletedCmdInternalTopics.add(getCmdInternalTopic(podName, deadContainerId, counter.getAndIncrement()));
    toBeDeletedCmdInternalTopics.add(getCmdInternalTopic(podName, deadContainerId, counter.getAndIncrement()));
    toBeDeletedCmdInternalTopics.add(getCmdInternalTopic(podName, deadContainerId, counter.getAndIncrement()));
    // GIVEN a number of topics
    final Set<String> allTopics = new HashSet<>(toBeDeletedCmdInternalTopics);
    allTopics.add("other");
    allTopics.add(getCmdInternalTopic(podName, aliveContainerId, counter.getAndIncrement()));
    allTopics.add(getCmdInternalTopic(podName, aliveContainerId, counter.getAndIncrement()));
    allTopics.add(getCmdInternalTopic(podName, aliveContainerId, counter.getAndIncrement()));
    // all adapter instances whose identifier contains the "deadContainerId" shall be identified as dead
    when(adapterInstanceStatusService.getDeadAdapterInstances(any())).thenAnswer(invocation -> {
        final Collection<String> adapterInstanceIdsParam = invocation.getArgument(0);
        final Set<String> deadIds = adapterInstanceIdsParam.stream().filter(id -> id.contains(deadContainerId)).collect(Collectors.toSet());
        return Future.succeededFuture(deadIds);
    });
    when(kafkaAdminClient.deleteTopics(any())).thenAnswer(invocation -> {
        // remove deleted from allTopics
        final List<String> topicsToDeleteParam = invocation.getArgument(0);
        topicsToDeleteParam.forEach(allTopics::remove);
        return Future.succeededFuture();
    });
    when(kafkaAdminClient.listTopics()).thenReturn(Future.succeededFuture(allTopics));
    // WHEN the cleanup gets performed
    internalKafkaTopicCleanupService.performCleanup();
    verify(kafkaAdminClient, never()).deleteTopics(any());
    // THEN the next invocation ...
    internalKafkaTopicCleanupService.performCleanup();
    // ... will cause the matching topics to be deleted
    final var deletedTopicsCaptor = ArgumentCaptor.forClass(List.class);
    verify(kafkaAdminClient).deleteTopics(deletedTopicsCaptor.capture());
    assertThat(deletedTopicsCaptor.getValue()).isEqualTo(new ArrayList<>(toBeDeletedCmdInternalTopics));
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) Collection(java.util.Collection) Vertx(io.vertx.core.Vertx) Set(java.util.Set) Mockito.when(org.mockito.Mockito.when) Truth.assertThat(com.google.common.truth.Truth.assertThat) Collectors(java.util.stream.Collectors) Future(io.vertx.core.Future) Timeout(io.vertx.junit5.Timeout) Mockito.verify(org.mockito.Mockito.verify) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) HonoTopic(org.eclipse.hono.client.kafka.HonoTopic) Mockito.never(org.mockito.Mockito.never) List(java.util.List) ArgumentCaptor(org.mockito.ArgumentCaptor) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CommandConstants(org.eclipse.hono.util.CommandConstants) KafkaAdminClient(io.vertx.kafka.admin.KafkaAdminClient) Mockito.mock(org.mockito.Mockito.mock) AdapterInstanceStatusService(org.eclipse.hono.commandrouter.AdapterInstanceStatusService) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HashSet(java.util.HashSet) Test(org.junit.jupiter.api.Test)

Aggregations

Vertx (io.vertx.core.Vertx)3 KafkaAdminClient (io.vertx.kafka.admin.KafkaAdminClient)3 Truth.assertThat (com.google.common.truth.Truth.assertThat)2 Future (io.vertx.core.Future)2 HashSet (java.util.HashSet)2 List (java.util.List)2 Set (java.util.Set)2 TimeUnit (java.util.concurrent.TimeUnit)2 Truth.assertWithMessage (com.google.common.truth.Truth.assertWithMessage)1 NoopSpan (io.opentracing.noop.NoopSpan)1 CompositeFuture (io.vertx.core.CompositeFuture)1 Handler (io.vertx.core.Handler)1 Promise (io.vertx.core.Promise)1 Buffer (io.vertx.core.buffer.Buffer)1 JsonArray (io.vertx.core.json.JsonArray)1 JsonObject (io.vertx.core.json.JsonObject)1 HttpResponse (io.vertx.ext.web.client.HttpResponse)1 Checkpoint (io.vertx.junit5.Checkpoint)1 Timeout (io.vertx.junit5.Timeout)1 VertxTestContext (io.vertx.junit5.VertxTestContext)1