Search in sources :

Example 6 with EventPublishingException

use of org.zalando.nakadi.exceptions.EventPublishingException in project nakadi by zalando.

the class KafkaTopicRepository method syncPostBatch.

@Override
public void syncPostBatch(final String topicId, final List<BatchItem> batch) throws EventPublishingException {
    final Producer<String, String> producer = kafkaFactory.takeProducer();
    try {
        final Map<String, String> partitionToBroker = producer.partitionsFor(topicId).stream().collect(Collectors.toMap(p -> String.valueOf(p.partition()), p -> String.valueOf(p.leader().id())));
        batch.forEach(item -> {
            Preconditions.checkNotNull(item.getPartition(), "BatchItem partition can't be null at the moment of publishing!");
            item.setBrokerId(partitionToBroker.get(item.getPartition()));
        });
        int shortCircuited = 0;
        final Map<BatchItem, CompletableFuture<Exception>> sendFutures = new HashMap<>();
        for (final BatchItem item : batch) {
            item.setStep(EventPublishingStep.PUBLISHING);
            final HystrixKafkaCircuitBreaker circuitBreaker = circuitBreakers.computeIfAbsent(item.getBrokerId(), brokerId -> new HystrixKafkaCircuitBreaker(brokerId));
            if (circuitBreaker.allowRequest()) {
                sendFutures.put(item, publishItem(producer, topicId, item, circuitBreaker));
            } else {
                shortCircuited++;
                item.updateStatusAndDetail(EventPublishingStatus.FAILED, "short circuited");
            }
        }
        if (shortCircuited > 0) {
            LOG.warn("Short circuiting request to Kafka {} time(s) due to timeout for topic {}", shortCircuited, topicId);
        }
        final CompletableFuture<Void> multiFuture = CompletableFuture.allOf(sendFutures.values().toArray(new CompletableFuture<?>[sendFutures.size()]));
        multiFuture.get(createSendTimeout(), TimeUnit.MILLISECONDS);
        // Now lets check for errors
        final Optional<Exception> needReset = sendFutures.entrySet().stream().filter(entry -> isExceptionShouldLeadToReset(entry.getValue().getNow(null))).map(entry -> entry.getValue().getNow(null)).findAny();
        if (needReset.isPresent()) {
            LOG.info("Terminating producer while publishing to topic {} because of unrecoverable exception", topicId, needReset.get());
            kafkaFactory.terminateProducer(producer);
        }
    } catch (final TimeoutException ex) {
        failUnpublished(batch, "timed out");
        throw new EventPublishingException("Error publishing message to kafka", ex);
    } catch (final ExecutionException ex) {
        failUnpublished(batch, "internal error");
        throw new EventPublishingException("Error publishing message to kafka", ex);
    } catch (final InterruptedException ex) {
        Thread.currentThread().interrupt();
        failUnpublished(batch, "interrupted");
        throw new EventPublishingException("Error publishing message to kafka", ex);
    } finally {
        kafkaFactory.releaseProducer(producer);
    }
    final boolean atLeastOneFailed = batch.stream().anyMatch(item -> item.getResponse().getPublishingStatus() == EventPublishingStatus.FAILED);
    if (atLeastOneFailed) {
        failUnpublished(batch, "internal error");
        throw new EventPublishingException("Error publishing message to kafka");
    }
}
Also used : EventPublishingException(org.zalando.nakadi.exceptions.EventPublishingException) NotLeaderForPartitionException(org.apache.kafka.common.errors.NotLeaderForPartitionException) Collections.unmodifiableList(java.util.Collections.unmodifiableList) LoggerFactory(org.slf4j.LoggerFactory) TimeoutException(java.util.concurrent.TimeoutException) TopicRepositoryException(org.zalando.nakadi.exceptions.runtime.TopicRepositoryException) PARTITION_NOT_FOUND(org.zalando.nakadi.domain.CursorError.PARTITION_NOT_FOUND) ServiceUnavailableException(org.zalando.nakadi.exceptions.ServiceUnavailableException) Map(java.util.Map) RetryForSpecifiedTimeStrategy(org.echocat.jomon.runtime.concurrent.RetryForSpecifiedTimeStrategy) Consumer(org.apache.kafka.clients.consumer.Consumer) ZooKeeperHolder(org.zalando.nakadi.repository.zookeeper.ZooKeeperHolder) TopicPartition(org.apache.kafka.common.TopicPartition) TopicRepository(org.zalando.nakadi.repository.TopicRepository) Retryer(org.echocat.jomon.runtime.concurrent.Retryer) Collection(java.util.Collection) PartitionStatistics(org.zalando.nakadi.domain.PartitionStatistics) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) ConfigType(kafka.server.ConfigType) PartitionInfo(org.apache.kafka.common.PartitionInfo) InvalidCursorException(org.zalando.nakadi.exceptions.InvalidCursorException) Collectors(java.util.stream.Collectors) TopicDeletionException(org.zalando.nakadi.exceptions.TopicDeletionException) Objects(java.util.Objects) ZkUtils(kafka.utils.ZkUtils) TopicExistsException(org.apache.kafka.common.errors.TopicExistsException) List(java.util.List) Stream(java.util.stream.Stream) Lists.newArrayList(com.google.common.collect.Lists.newArrayList) Timeline(org.zalando.nakadi.domain.Timeline) ZookeeperSettings(org.zalando.nakadi.repository.zookeeper.ZookeeperSettings) NULL_OFFSET(org.zalando.nakadi.domain.CursorError.NULL_OFFSET) BatchItem(org.zalando.nakadi.domain.BatchItem) Optional(java.util.Optional) UnknownTopicOrPartitionException(org.apache.kafka.common.errors.UnknownTopicOrPartitionException) AdminUtils(kafka.admin.AdminUtils) IntStream(java.util.stream.IntStream) ProducerRecord(org.apache.kafka.clients.producer.ProducerRecord) NetworkException(org.apache.kafka.common.errors.NetworkException) NakadiCursor(org.zalando.nakadi.domain.NakadiCursor) NakadiSettings(org.zalando.nakadi.config.NakadiSettings) TopicCreationException(org.zalando.nakadi.exceptions.TopicCreationException) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) TopicConfigException(org.zalando.nakadi.exceptions.runtime.TopicConfigException) UnknownServerException(org.apache.kafka.common.errors.UnknownServerException) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) UUIDGenerator(org.zalando.nakadi.util.UUIDGenerator) InterruptException(org.apache.kafka.common.errors.InterruptException) EventPublishingStep(org.zalando.nakadi.domain.EventPublishingStep) Nullable(javax.annotation.Nullable) UNAVAILABLE(org.zalando.nakadi.domain.CursorError.UNAVAILABLE) NULL_PARTITION(org.zalando.nakadi.domain.CursorError.NULL_PARTITION) Logger(org.slf4j.Logger) Properties(java.util.Properties) Producer(org.apache.kafka.clients.producer.Producer) PartitionEndStatistics(org.zalando.nakadi.domain.PartitionEndStatistics) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) EventConsumer(org.zalando.nakadi.repository.EventConsumer) Collectors.toList(java.util.stream.Collectors.toList) EventPublishingStatus(org.zalando.nakadi.domain.EventPublishingStatus) Preconditions(com.google.common.base.Preconditions) Collections(java.util.Collections) RackAwareMode(kafka.admin.RackAwareMode) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) 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) CompletableFuture(java.util.concurrent.CompletableFuture) BatchItem(org.zalando.nakadi.domain.BatchItem) ExecutionException(java.util.concurrent.ExecutionException) EventPublishingException(org.zalando.nakadi.exceptions.EventPublishingException) TimeoutException(java.util.concurrent.TimeoutException)

Example 7 with EventPublishingException

use of org.zalando.nakadi.exceptions.EventPublishingException in project nakadi by zalando.

the class EventPublisher method publishInternal.

EventPublishResult publishInternal(final String events, final String eventTypeName, final boolean useAuthz) throws NoSuchEventTypeException, InternalNakadiException, EventTypeTimeoutException, AccessDeniedException, ServiceTemporarilyUnavailableException {
    Closeable publishingCloser = null;
    final List<BatchItem> batch = BatchFactory.from(events);
    try {
        publishingCloser = timelineSync.workWithEventType(eventTypeName, nakadiSettings.getTimelineWaitTimeoutMs());
        final EventType eventType = eventTypeCache.getEventType(eventTypeName);
        if (useAuthz) {
            authValidator.authorizeEventTypeWrite(eventType);
        }
        validate(batch, eventType);
        partition(batch, eventType);
        enrich(batch, eventType);
        submit(batch, eventType);
        return ok(batch);
    } catch (final EventValidationException e) {
        LOG.debug("Event validation error: {}", e.getMessage());
        return aborted(EventPublishingStep.VALIDATING, batch);
    } catch (final PartitioningException e) {
        LOG.debug("Event partition error: {}", e.getMessage());
        return aborted(EventPublishingStep.PARTITIONING, batch);
    } catch (final EnrichmentException e) {
        LOG.debug("Event enrichment error: {}", e.getMessage());
        return aborted(EventPublishingStep.ENRICHING, batch);
    } catch (final EventPublishingException e) {
        LOG.error("error publishing event", e);
        return failed(batch);
    } catch (final InterruptedException e) {
        Thread.currentThread().interrupt();
        LOG.error("Failed to wait for timeline switch", e);
        throw new EventTypeTimeoutException("Event type is currently in maintenance, please repeat request");
    } catch (final TimeoutException e) {
        LOG.error("Failed to wait for timeline switch", e);
        throw new EventTypeTimeoutException("Event type is currently in maintenance, please repeat request");
    } finally {
        try {
            if (publishingCloser != null) {
                publishingCloser.close();
            }
        } catch (final IOException e) {
            LOG.error("Exception occurred when releasing usage of event-type", e);
        }
    }
}
Also used : EventValidationException(org.zalando.nakadi.exceptions.EventValidationException) PartitioningException(org.zalando.nakadi.exceptions.PartitioningException) EventType(org.zalando.nakadi.domain.EventType) Closeable(java.io.Closeable) BatchItem(org.zalando.nakadi.domain.BatchItem) EnrichmentException(org.zalando.nakadi.exceptions.EnrichmentException) IOException(java.io.IOException) EventTypeTimeoutException(org.zalando.nakadi.exceptions.EventTypeTimeoutException) EventPublishingException(org.zalando.nakadi.exceptions.EventPublishingException) TimeoutException(java.util.concurrent.TimeoutException) EventTypeTimeoutException(org.zalando.nakadi.exceptions.EventTypeTimeoutException)

Aggregations

BatchItem (org.zalando.nakadi.domain.BatchItem)7 EventPublishingException (org.zalando.nakadi.exceptions.EventPublishingException)7 PartitionInfo (org.apache.kafka.common.PartitionInfo)6 ArrayList (java.util.ArrayList)5 ProducerRecord (org.apache.kafka.clients.producer.ProducerRecord)4 Node (org.apache.kafka.common.Node)4 Collections (java.util.Collections)3 List (java.util.List)3 Set (java.util.Set)3 TimeoutException (java.util.concurrent.TimeoutException)3 Collectors (java.util.stream.Collectors)3 Collectors.toList (java.util.stream.Collectors.toList)3 Consumer (org.apache.kafka.clients.consumer.Consumer)3 Test (org.junit.Test)3 InvalidCursorException (org.zalando.nakadi.exceptions.InvalidCursorException)3 Preconditions (com.google.common.base.Preconditions)2 Lists.newArrayList (com.google.common.collect.Lists.newArrayList)2 Collection (java.util.Collection)2 Collections.unmodifiableList (java.util.Collections.unmodifiableList)2 HashMap (java.util.HashMap)2