Search in sources :

Example 26 with KafkaFuture

use of org.apache.kafka.common.KafkaFuture in project kafka by apache.

the class MockAdminClient method handleDeleteTopicsUsingIds.

private Map<Uuid, KafkaFuture<Void>> handleDeleteTopicsUsingIds(Collection<Uuid> topicIdCollection, DeleteTopicsOptions options) {
    Map<Uuid, KafkaFuture<Void>> deleteTopicsResult = new HashMap<>();
    Collection<Uuid> topicIds = new ArrayList<>(topicIdCollection);
    if (timeoutNextRequests > 0) {
        for (final Uuid topicId : topicIds) {
            KafkaFutureImpl<Void> future = new KafkaFutureImpl<>();
            future.completeExceptionally(new TimeoutException());
            deleteTopicsResult.put(topicId, future);
        }
        --timeoutNextRequests;
        return deleteTopicsResult;
    }
    for (final Uuid topicId : topicIds) {
        KafkaFutureImpl<Void> future = new KafkaFutureImpl<>();
        String name = topicNames.remove(topicId);
        if (name == null || allTopics.remove(name) == null) {
            future.completeExceptionally(new UnknownTopicOrPartitionException(String.format("Topic %s does not exist.", topicId)));
        } else {
            topicIds.remove(name);
            future.complete(null);
        }
        deleteTopicsResult.put(topicId, future);
    }
    return deleteTopicsResult;
}
Also used : Uuid(org.apache.kafka.common.Uuid) KafkaFuture(org.apache.kafka.common.KafkaFuture) HashMap(java.util.HashMap) UnknownTopicOrPartitionException(org.apache.kafka.common.errors.UnknownTopicOrPartitionException) ArrayList(java.util.ArrayList) KafkaFutureImpl(org.apache.kafka.common.internals.KafkaFutureImpl) TimeoutException(org.apache.kafka.common.errors.TimeoutException)

Example 27 with KafkaFuture

use of org.apache.kafka.common.KafkaFuture in project kafka by apache.

the class MockAdminClient method createTopics.

@Override
public synchronized CreateTopicsResult createTopics(Collection<NewTopic> newTopics, CreateTopicsOptions options) {
    Map<String, KafkaFuture<CreateTopicsResult.TopicMetadataAndConfig>> createTopicResult = new HashMap<>();
    if (timeoutNextRequests > 0) {
        for (final NewTopic newTopic : newTopics) {
            String topicName = newTopic.name();
            KafkaFutureImpl<CreateTopicsResult.TopicMetadataAndConfig> future = new KafkaFutureImpl<>();
            future.completeExceptionally(new TimeoutException());
            createTopicResult.put(topicName, future);
        }
        --timeoutNextRequests;
        return new CreateTopicsResult(createTopicResult);
    }
    for (final NewTopic newTopic : newTopics) {
        KafkaFutureImpl<CreateTopicsResult.TopicMetadataAndConfig> future = new KafkaFutureImpl<>();
        String topicName = newTopic.name();
        if (allTopics.containsKey(topicName)) {
            future.completeExceptionally(new TopicExistsException(String.format("Topic %s exists already.", topicName)));
            createTopicResult.put(topicName, future);
            continue;
        }
        int replicationFactor = newTopic.replicationFactor();
        if (replicationFactor == -1) {
            replicationFactor = defaultReplicationFactor;
        }
        if (replicationFactor > brokers.size()) {
            future.completeExceptionally(new InvalidReplicationFactorException(String.format("Replication factor: %d is larger than brokers: %d", newTopic.replicationFactor(), brokers.size())));
            createTopicResult.put(topicName, future);
            continue;
        }
        List<Node> replicas = new ArrayList<>(replicationFactor);
        for (int i = 0; i < replicationFactor; ++i) {
            replicas.add(brokers.get(i));
        }
        int numberOfPartitions = newTopic.numPartitions();
        if (numberOfPartitions == -1) {
            numberOfPartitions = defaultPartitions;
        }
        List<TopicPartitionInfo> partitions = new ArrayList<>(numberOfPartitions);
        // Partitions start off on the first log directory of each broker, for now.
        List<String> logDirs = new ArrayList<>(numberOfPartitions);
        for (int i = 0; i < numberOfPartitions; i++) {
            partitions.add(new TopicPartitionInfo(i, brokers.get(0), replicas, Collections.emptyList()));
            logDirs.add(brokerLogDirs.get(partitions.get(i).leader().id()).get(0));
        }
        Uuid topicId = Uuid.randomUuid();
        topicIds.put(topicName, topicId);
        topicNames.put(topicId, topicName);
        allTopics.put(topicName, new TopicMetadata(topicId, false, partitions, logDirs, newTopic.configs()));
        future.complete(null);
        createTopicResult.put(topicName, future);
    }
    return new CreateTopicsResult(createTopicResult);
}
Also used : KafkaFuture(org.apache.kafka.common.KafkaFuture) HashMap(java.util.HashMap) Node(org.apache.kafka.common.Node) ArrayList(java.util.ArrayList) KafkaFutureImpl(org.apache.kafka.common.internals.KafkaFutureImpl) TopicExistsException(org.apache.kafka.common.errors.TopicExistsException) Uuid(org.apache.kafka.common.Uuid) TopicPartitionInfo(org.apache.kafka.common.TopicPartitionInfo) InvalidReplicationFactorException(org.apache.kafka.common.errors.InvalidReplicationFactorException) TimeoutException(org.apache.kafka.common.errors.TimeoutException)

Example 28 with KafkaFuture

use of org.apache.kafka.common.KafkaFuture in project kafka by apache.

the class MockAdminClient method alterPartitionReassignments.

@Override
public synchronized AlterPartitionReassignmentsResult alterPartitionReassignments(Map<TopicPartition, Optional<NewPartitionReassignment>> newReassignments, AlterPartitionReassignmentsOptions options) {
    Map<TopicPartition, KafkaFuture<Void>> futures = new HashMap<>();
    for (Map.Entry<TopicPartition, Optional<NewPartitionReassignment>> entry : newReassignments.entrySet()) {
        TopicPartition partition = entry.getKey();
        Optional<NewPartitionReassignment> newReassignment = entry.getValue();
        KafkaFutureImpl<Void> future = new KafkaFutureImpl<Void>();
        futures.put(partition, future);
        TopicMetadata topicMetadata = allTopics.get(partition.topic());
        if (partition.partition() < 0 || topicMetadata == null || topicMetadata.partitions.size() <= partition.partition()) {
            future.completeExceptionally(new UnknownTopicOrPartitionException());
        } else if (newReassignment.isPresent()) {
            reassignments.put(partition, newReassignment.get());
            future.complete(null);
        } else {
            reassignments.remove(partition);
            future.complete(null);
        }
    }
    return new AlterPartitionReassignmentsResult(futures);
}
Also used : KafkaFuture(org.apache.kafka.common.KafkaFuture) Optional(java.util.Optional) HashMap(java.util.HashMap) UnknownTopicOrPartitionException(org.apache.kafka.common.errors.UnknownTopicOrPartitionException) KafkaFutureImpl(org.apache.kafka.common.internals.KafkaFutureImpl) TopicPartition(org.apache.kafka.common.TopicPartition) HashMap(java.util.HashMap) Map(java.util.Map)

Example 29 with KafkaFuture

use of org.apache.kafka.common.KafkaFuture in project kafka by apache.

the class MockAdminClient method describeReplicaLogDirs.

@Override
public synchronized DescribeReplicaLogDirsResult describeReplicaLogDirs(Collection<TopicPartitionReplica> replicas, DescribeReplicaLogDirsOptions options) {
    Map<TopicPartitionReplica, KafkaFuture<ReplicaLogDirInfo>> results = new HashMap<>();
    for (TopicPartitionReplica replica : replicas) {
        TopicMetadata topicMetadata = allTopics.get(replica.topic());
        if (topicMetadata != null) {
            KafkaFutureImpl<ReplicaLogDirInfo> future = new KafkaFutureImpl<>();
            results.put(replica, future);
            String currentLogDir = currentLogDir(replica);
            if (currentLogDir == null) {
                future.complete(new ReplicaLogDirInfo(null, DescribeLogDirsResponse.INVALID_OFFSET_LAG, null, DescribeLogDirsResponse.INVALID_OFFSET_LAG));
            } else {
                ReplicaLogDirInfo info = replicaMoves.get(replica);
                if (info == null) {
                    future.complete(new ReplicaLogDirInfo(currentLogDir, 0, null, 0));
                } else {
                    future.complete(info);
                }
            }
        }
    }
    return new DescribeReplicaLogDirsResult(results);
}
Also used : ReplicaLogDirInfo(org.apache.kafka.clients.admin.DescribeReplicaLogDirsResult.ReplicaLogDirInfo) TopicPartitionReplica(org.apache.kafka.common.TopicPartitionReplica) KafkaFuture(org.apache.kafka.common.KafkaFuture) HashMap(java.util.HashMap) KafkaFutureImpl(org.apache.kafka.common.internals.KafkaFutureImpl)

Example 30 with KafkaFuture

use of org.apache.kafka.common.KafkaFuture in project kafka by apache.

the class TopicAdmin method createOrFindTopics.

/**
 * Attempt to create the topics described by the given definitions, returning all of the names of those topics that
 * were created by this request. Any existing topics with the same name are unchanged, and the names of such topics
 * are excluded from the result.
 * <p>
 * If multiple topic definitions have the same topic name, the last one with that name will be used.
 * <p>
 * Apache Kafka added support for creating topics in 0.10.1.0, so this method works as expected with that and later versions.
 * With brokers older than 0.10.1.0, this method is unable to create topics and always returns an empty set.
 *
 * @param topics the specifications of the topics
 * @return the {@link TopicCreationResponse} with the names of the newly created and existing topics;
 *         never null but possibly empty
 * @throws ConnectException if an error occurs, the operation takes too long, or the thread is interrupted while
 *                          attempting to perform this operation
 */
public TopicCreationResponse createOrFindTopics(NewTopic... topics) {
    Map<String, NewTopic> topicsByName = new HashMap<>();
    if (topics != null) {
        for (NewTopic topic : topics) {
            if (topic != null)
                topicsByName.put(topic.name(), topic);
        }
    }
    if (topicsByName.isEmpty())
        return EMPTY_CREATION;
    String bootstrapServers = bootstrapServers();
    String topicNameList = Utils.join(topicsByName.keySet(), "', '");
    // Attempt to create any missing topics
    CreateTopicsOptions args = new CreateTopicsOptions().validateOnly(false);
    Map<String, KafkaFuture<Void>> newResults = admin.createTopics(topicsByName.values(), args).values();
    // Iterate over each future so that we can handle individual failures like when some topics already exist
    Set<String> newlyCreatedTopicNames = new HashSet<>();
    Set<String> existingTopicNames = new HashSet<>();
    for (Map.Entry<String, KafkaFuture<Void>> entry : newResults.entrySet()) {
        String topic = entry.getKey();
        try {
            entry.getValue().get();
            if (logCreation) {
                log.info("Created topic {} on brokers at {}", topicsByName.get(topic), bootstrapServers);
            }
            newlyCreatedTopicNames.add(topic);
        } catch (ExecutionException e) {
            Throwable cause = e.getCause();
            if (cause instanceof TopicExistsException) {
                log.debug("Found existing topic '{}' on the brokers at {}", topic, bootstrapServers);
                existingTopicNames.add(topic);
                continue;
            }
            if (cause instanceof UnsupportedVersionException) {
                log.debug("Unable to create topic(s) '{}' since the brokers at {} do not support the CreateTopics API." + " Falling back to assume topic(s) exist or will be auto-created by the broker.", topicNameList, bootstrapServers);
                return EMPTY_CREATION;
            }
            if (cause instanceof ClusterAuthorizationException) {
                log.debug("Not authorized to create topic(s) '{}' upon the brokers {}." + " Falling back to assume topic(s) exist or will be auto-created by the broker.", topicNameList, bootstrapServers);
                return EMPTY_CREATION;
            }
            if (cause instanceof TopicAuthorizationException) {
                log.debug("Not authorized to create topic(s) '{}' upon the brokers {}." + " Falling back to assume topic(s) exist or will be auto-created by the broker.", topicNameList, bootstrapServers);
                return EMPTY_CREATION;
            }
            if (cause instanceof InvalidConfigurationException) {
                throw new ConnectException("Unable to create topic(s) '" + topicNameList + "': " + cause.getMessage(), cause);
            }
            if (cause instanceof TimeoutException) {
                // Timed out waiting for the operation to complete
                throw new ConnectException("Timed out while checking for or creating topic(s) '" + topicNameList + "'." + " This could indicate a connectivity issue, unavailable topic partitions, or if" + " this is your first use of the topic it may have taken too long to create.", cause);
            }
            throw new ConnectException("Error while attempting to create/find topic(s) '" + topicNameList + "'", e);
        } catch (InterruptedException e) {
            Thread.interrupted();
            throw new ConnectException("Interrupted while attempting to create/find topic(s) '" + topicNameList + "'", e);
        }
    }
    return new TopicCreationResponse(newlyCreatedTopicNames, existingTopicNames);
}
Also used : KafkaFuture(org.apache.kafka.common.KafkaFuture) HashMap(java.util.HashMap) CreateTopicsOptions(org.apache.kafka.clients.admin.CreateTopicsOptions) TopicExistsException(org.apache.kafka.common.errors.TopicExistsException) InvalidConfigurationException(org.apache.kafka.common.errors.InvalidConfigurationException) NewTopic(org.apache.kafka.clients.admin.NewTopic) ExecutionException(java.util.concurrent.ExecutionException) HashMap(java.util.HashMap) Map(java.util.Map) ClusterAuthorizationException(org.apache.kafka.common.errors.ClusterAuthorizationException) TopicAuthorizationException(org.apache.kafka.common.errors.TopicAuthorizationException) HashSet(java.util.HashSet) UnsupportedVersionException(org.apache.kafka.common.errors.UnsupportedVersionException) ConnectException(org.apache.kafka.connect.errors.ConnectException) TimeoutException(org.apache.kafka.common.errors.TimeoutException)

Aggregations

KafkaFuture (org.apache.kafka.common.KafkaFuture)70 HashMap (java.util.HashMap)51 Map (java.util.Map)37 KafkaFutureImpl (org.apache.kafka.common.internals.KafkaFutureImpl)31 ExecutionException (java.util.concurrent.ExecutionException)22 TimeoutException (org.apache.kafka.common.errors.TimeoutException)21 ArrayList (java.util.ArrayList)15 UnknownTopicOrPartitionException (org.apache.kafka.common.errors.UnknownTopicOrPartitionException)15 Test (org.junit.jupiter.api.Test)15 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)14 TopicPartition (org.apache.kafka.common.TopicPartition)13 ConfigResource (org.apache.kafka.common.config.ConfigResource)12 HashSet (java.util.HashSet)11 TopicExistsException (org.apache.kafka.common.errors.TopicExistsException)10 AbstractResponse (org.apache.kafka.common.requests.AbstractResponse)8 UnsupportedVersionException (org.apache.kafka.common.errors.UnsupportedVersionException)7 ChannelBuilder (org.apache.kafka.common.network.ChannelBuilder)7 DescribeTopicsResult (org.apache.kafka.clients.admin.DescribeTopicsResult)6 Node (org.apache.kafka.common.Node)6 TopicPartitionReplica (org.apache.kafka.common.TopicPartitionReplica)6