Search in sources :

Example 6 with FetchResponse

use of kafka.javaapi.FetchResponse in project heron by twitter.

the class KafkaUtils method fetchMessages.

/***
   * Fetch messages from kafka
   * @param config
   * @param consumer
   * @param partition
   * @param offset
   * @return
   * @throws TopicOffsetOutOfRangeException
   * @throws FailedFetchException
   * @throws RuntimeException
   */
public static ByteBufferMessageSet fetchMessages(KafkaConfig config, SimpleConsumer consumer, Partition partition, long offset) throws TopicOffsetOutOfRangeException, FailedFetchException, RuntimeException {
    ByteBufferMessageSet msgs = null;
    String topic = partition.topic;
    int partitionId = partition.partition;
    FetchRequestBuilder builder = new FetchRequestBuilder();
    FetchRequest fetchRequest = builder.addFetch(topic, partitionId, offset, config.fetchSizeBytes).clientId(config.clientId).maxWait(config.fetchMaxWait).minBytes(config.minFetchByte).build();
    FetchResponse fetchResponse;
    try {
        fetchResponse = consumer.fetch(fetchRequest);
    // SUPPRESS CHECKSTYLE IllegalCatch
    } catch (Exception e) {
        if (e instanceof ConnectException || e instanceof SocketTimeoutException || e instanceof IOException || e instanceof UnresolvedAddressException) {
            LOG.warn("Network error when fetching messages:", e);
            throw new FailedFetchException(e);
        } else {
            throw new RuntimeException(e);
        }
    }
    if (fetchResponse.hasError()) {
        KafkaError error = KafkaError.getError(fetchResponse.errorCode(topic, partitionId));
        if (error.equals(KafkaError.OFFSET_OUT_OF_RANGE) && config.useStartOffsetTimeIfOffsetOutOfRange) {
            String msg = partition + " Got fetch request with offset out of range: [" + offset + "]";
            LOG.warn(msg);
            throw new TopicOffsetOutOfRangeException(msg);
        } else {
            String message = "Error fetching data from [" + partition + "] for topic [" + topic + "]: [" + error + "]";
            LOG.error(message);
            throw new FailedFetchException(message);
        }
    } else {
        msgs = fetchResponse.messageSet(topic, partitionId);
    }
    return msgs;
}
Also used : FetchResponse(kafka.javaapi.FetchResponse) IOException(java.io.IOException) ByteBufferMessageSet(kafka.javaapi.message.ByteBufferMessageSet) SocketTimeoutException(java.net.SocketTimeoutException) ConnectException(java.net.ConnectException) IOException(java.io.IOException) UnresolvedAddressException(java.nio.channels.UnresolvedAddressException) SocketTimeoutException(java.net.SocketTimeoutException) FetchRequestBuilder(kafka.api.FetchRequestBuilder) FetchRequest(kafka.api.FetchRequest) UnresolvedAddressException(java.nio.channels.UnresolvedAddressException) ConnectException(java.net.ConnectException)

Example 7 with FetchResponse

use of kafka.javaapi.FetchResponse in project storm by apache.

the class KafkaUtils method fetchMessages.

public static ByteBufferMessageSet fetchMessages(KafkaConfig config, SimpleConsumer consumer, Partition partition, long offset) throws TopicOffsetOutOfRangeException, FailedFetchException, RuntimeException {
    ByteBufferMessageSet msgs = null;
    String topic = partition.topic;
    int partitionId = partition.partition;
    FetchRequestBuilder builder = new FetchRequestBuilder();
    FetchRequest fetchRequest = builder.addFetch(topic, partitionId, offset, config.fetchSizeBytes).clientId(config.clientId).maxWait(config.fetchMaxWait).minBytes(config.minFetchByte).build();
    FetchResponse fetchResponse;
    try {
        fetchResponse = consumer.fetch(fetchRequest);
    } catch (Exception e) {
        if (e instanceof ConnectException || e instanceof SocketTimeoutException || e instanceof IOException || e instanceof UnresolvedAddressException) {
            LOG.warn("Network error when fetching messages:", e);
            throw new FailedFetchException(e);
        } else {
            throw new RuntimeException(e);
        }
    }
    if (fetchResponse.hasError()) {
        KafkaError error = KafkaError.getError(fetchResponse.errorCode(topic, partitionId));
        if (error.equals(KafkaError.OFFSET_OUT_OF_RANGE) && config.useStartOffsetTimeIfOffsetOutOfRange) {
            String msg = partition + " Got fetch request with offset out of range: [" + offset + "]";
            LOG.warn(msg);
            throw new TopicOffsetOutOfRangeException(msg);
        } else {
            String message = "Error fetching data from [" + partition + "] for topic [" + topic + "]: [" + error + "]";
            LOG.error(message);
            throw new FailedFetchException(message);
        }
    } else {
        msgs = fetchResponse.messageSet(topic, partitionId);
    }
    LOG.debug("Messages fetched. [config = {}], [consumer = {}], [partition = {}], [offset = {}], [msgs = {}]", config, consumer, partition, offset, msgs);
    return msgs;
}
Also used : FetchResponse(kafka.javaapi.FetchResponse) IOException(java.io.IOException) ByteBufferMessageSet(kafka.javaapi.message.ByteBufferMessageSet) SocketTimeoutException(java.net.SocketTimeoutException) ConnectException(java.net.ConnectException) IOException(java.io.IOException) UnresolvedAddressException(java.nio.channels.UnresolvedAddressException) SocketTimeoutException(java.net.SocketTimeoutException) FetchRequestBuilder(kafka.api.FetchRequestBuilder) FetchRequest(kafka.api.FetchRequest) UnresolvedAddressException(java.nio.channels.UnresolvedAddressException) ConnectException(java.net.ConnectException)

Example 8 with FetchResponse

use of kafka.javaapi.FetchResponse in project pinot by linkedin.

the class SimpleConsumerWrapper method fetchMessagesAndHighWatermark.

/**
   * Fetch messages and the per-partition high watermark from Kafka between the specified offsets.
   *
   * @param startOffset The offset of the first message desired, inclusive
   * @param endOffset The offset of the last message desired, exclusive, or {@link Long#MAX_VALUE} for no end offset.
   * @param timeoutMillis Timeout in milliseconds
   * @throws java.util.concurrent.TimeoutException If the operation could not be completed within {@code timeoutMillis}
   * milliseconds
   * @return An iterable containing messages fetched from Kafka and their offsets, as well as the high watermark for
   * this partition.
   */
public synchronized Pair<Iterable<MessageAndOffset>, Long> fetchMessagesAndHighWatermark(long startOffset, long endOffset, int timeoutMillis) throws java.util.concurrent.TimeoutException {
    Preconditions.checkState(!_metadataOnlyConsumer, "Cannot fetch messages from a metadata-only SimpleConsumerWrapper");
    // Ensure that we're connected to the leader
    // TODO Improve error handling
    final long connectEndTime = System.currentTimeMillis() + _connectTimeoutMillis;
    while (_currentState.getStateValue() != ConsumerState.CONNECTED_TO_PARTITION_LEADER && System.currentTimeMillis() < connectEndTime) {
        _currentState.process();
    }
    if (_currentState.getStateValue() != ConsumerState.CONNECTED_TO_PARTITION_LEADER && connectEndTime <= System.currentTimeMillis()) {
        throw new java.util.concurrent.TimeoutException();
    }
    FetchResponse fetchResponse = _simpleConsumer.fetch(new FetchRequestBuilder().minBytes(100000).maxWait(timeoutMillis).addFetch(_topic, _partition, startOffset, 500000).build());
    if (!fetchResponse.hasError()) {
        final Iterable<MessageAndOffset> messageAndOffsetIterable = buildOffsetFilteringIterable(fetchResponse.messageSet(_topic, _partition), startOffset, endOffset);
        return Pair.of(messageAndOffsetIterable, fetchResponse.highWatermark(_topic, _partition));
    } else {
        throw exceptionForKafkaErrorCode(fetchResponse.errorCode(_topic, _partition));
    }
}
Also used : FetchRequestBuilder(kafka.api.FetchRequestBuilder) FetchResponse(kafka.javaapi.FetchResponse) MessageAndOffset(kafka.message.MessageAndOffset) TimeoutException(org.apache.kafka.common.errors.TimeoutException)

Example 9 with FetchResponse

use of kafka.javaapi.FetchResponse in project voltdb by VoltDB.

the class KafkaTopicPartitionImporter method accept.

@Override
protected void accept() {
    info(null, "Starting partition fetcher for " + m_topicAndPartition);
    long submitCount = 0;
    PendingWorkTracker callbackTracker = new PendingWorkTracker();
    Formatter formatter = m_config.getFormatterBuilder().create();
    try {
        //Start with the starting leader.
        resetLeader();
        int sleepCounter = 1;
        while (shouldRun()) {
            if (m_currentOffset.get() < 0) {
                getOffsetCoordinator();
                if (m_offsetManager.get() == null) {
                    sleepCounter = backoffSleep(sleepCounter);
                    continue;
                }
                long lastOffset = getLastOffset();
                if (lastOffset == -1) {
                    sleepCounter = backoffSleep(sleepCounter);
                    continue;
                }
                m_gapTracker.resetTo(lastOffset);
                m_lastCommittedOffset = lastOffset;
                m_currentOffset.set(lastOffset);
                if (m_currentOffset.get() < 0) {
                    //If we dont know the offset get it backoff if we fail.
                    sleepCounter = backoffSleep(sleepCounter);
                    info(null, "No valid offset found for " + m_topicAndPartition);
                    continue;
                }
                info(null, "Starting offset for " + m_topicAndPartition + " is " + m_currentOffset.get());
            }
            long currentFetchCount = 0;
            //Build fetch request of we have a valid offset and not too many are pending.
            FetchRequest req = m_fetchRequestBuilder.addFetch(m_topicAndPartition.topic(), m_topicAndPartition.partition(), m_currentOffset.get(), m_config.getFetchSize()).build();
            FetchResponse fetchResponse = null;
            try {
                fetchResponse = m_consumer.fetch(req);
                if (fetchResponse == null) {
                    sleepCounter = backoffSleep(sleepCounter);
                    continue;
                }
            } catch (Exception ex) {
                rateLimitedLog(Level.WARN, ex, "Failed to fetch from " + m_topicAndPartition);
                //See if its network error and find new leader for this partition.
                if (ex instanceof IOException) {
                    resetLeader();
                    //find leader in resetLeader would sleep and backoff
                    continue;
                }
                sleepCounter = backoffSleep(sleepCounter);
                continue;
            }
            if (fetchResponse.hasError()) {
                // Something went wrong!
                short code = fetchResponse.errorCode(m_topicAndPartition.topic(), m_topicAndPartition.partition());
                warn(ErrorMapping.exceptionFor(code), "Failed to fetch messages for %s", m_topicAndPartition);
                sleepCounter = backoffSleep(sleepCounter);
                if (code == ErrorMapping.OffsetOutOfRangeCode()) {
                    // We asked for an invalid offset. For simple case ask for the last element to reset
                    info(null, "Invalid offset requested for " + m_topicAndPartition);
                    getOffsetCoordinator();
                    m_currentOffset.set(-1L);
                    continue;
                }
                resetLeader();
                continue;
            }
            sleepCounter = 1;
            for (MessageAndOffset messageAndOffset : fetchResponse.messageSet(m_topicAndPartition.topic(), m_topicAndPartition.partition())) {
                //You may be catchin up so dont sleep.
                currentFetchCount++;
                long currentOffset = messageAndOffset.offset();
                //if currentOffset is less means we have already pushed it and also check pending queue.
                if (currentOffset < m_currentOffset.get()) {
                    continue;
                }
                ByteBuffer payload = messageAndOffset.message().payload();
                Object[] params = null;
                try {
                    m_gapTracker.submit(messageAndOffset.nextOffset());
                    params = formatter.transform(payload);
                    Invocation invocation = new Invocation(m_config.getProcedure(), params);
                    TopicPartitionInvocationCallback cb = new TopicPartitionInvocationCallback(messageAndOffset.offset(), messageAndOffset.nextOffset(), callbackTracker, m_gapTracker, m_dead, m_pauseOffset);
                    if (!noTransaction) {
                        if (callProcedure(invocation, cb)) {
                            callbackTracker.produceWork();
                        } else {
                            if (isDebugEnabled()) {
                                debug(null, "Failed to process Invocation possibly bad data: " + Arrays.toString(params));
                            }
                            m_gapTracker.commit(messageAndOffset.nextOffset());
                        }
                    }
                } catch (FormatException e) {
                    rateLimitedLog(Level.WARN, e, "Failed to tranform data: %s", Arrays.toString(params));
                    m_gapTracker.commit(messageAndOffset.nextOffset());
                }
                submitCount++;
                m_currentOffset.set(messageAndOffset.nextOffset());
                if (!shouldRun()) {
                    break;
                }
            }
            if (!shouldRun()) {
                break;
            }
            //wait to fetch more if we read nothing last time.
            if (currentFetchCount == 0) {
                try {
                    Thread.sleep(m_waitSleepMs);
                } catch (InterruptedException ie) {
                }
            }
            if (shouldCommit()) {
                commitOffset(false);
            }
        }
    } catch (Exception ex) {
        error(ex, "Failed to start topic partition fetcher for " + m_topicAndPartition);
    } finally {
        final boolean usePausedOffset = m_pauseOffset.get() != -1;
        boolean skipCommit = false;
        if (usePausedOffset) {
            // Paused offset is not guaranteed reliable until all callbacks have been called.
            if (callbackTracker.waitForWorkToFinish() == false) {
                if (m_pauseOffset.get() < m_lastCommittedOffset) {
                    warn(null, "Committing paused offset even though a timeout occurred waiting for pending stored procedures to finish.");
                } else {
                    warn(null, "Refusing to commit paused offset because a timeout occurred waiting for pending stored procedures to finish.");
                    skipCommit = true;
                }
            }
        }
        if (skipCommit == false) {
            // Force a commit. Paused offset will be re-acquired if needed.
            commitOffset(usePausedOffset);
        }
        KafkaStreamImporterConfig.closeConsumer(m_consumer);
        m_consumer = null;
        BlockingChannel channel = m_offsetManager.getAndSet(null);
        if (channel != null) {
            try {
                channel.disconnect();
            } catch (Exception ignoreIt) {
            }
        }
    }
    m_dead.compareAndSet(false, true);
    info(null, "Partition fetcher stopped for " + m_topicAndPartition + " Last commit point is: " + m_lastCommittedOffset + " Callback Rcvd: " + callbackTracker.getCallbackCount() + " Submitted: " + submitCount);
}
Also used : Invocation(org.voltdb.importer.Invocation) Formatter(org.voltdb.importer.formatter.Formatter) OffsetFetchResponse(kafka.javaapi.OffsetFetchResponse) FetchResponse(kafka.javaapi.FetchResponse) IOException(java.io.IOException) MessageAndOffset(kafka.message.MessageAndOffset) ByteBuffer(java.nio.ByteBuffer) FormatException(org.voltdb.importer.formatter.FormatException) IOException(java.io.IOException) FormatException(org.voltdb.importer.formatter.FormatException) BlockingChannel(kafka.network.BlockingChannel) OffsetFetchRequest(kafka.javaapi.OffsetFetchRequest) FetchRequest(kafka.api.FetchRequest)

Example 10 with FetchResponse

use of kafka.javaapi.FetchResponse in project cdap by caskdata.

the class KafkaConsumer method fetchMessageSet.

private ByteBufferMessageSet fetchMessageSet(long fetchOffset) throws OffsetOutOfRangeException {
    Preconditions.checkArgument(fetchOffset >= 0, String.format("Illegal fetch offset %d", fetchOffset));
    int failureCount = 0;
    while (true) {
        SimpleConsumer consumer = getConsumer();
        FetchRequest req = new FetchRequestBuilder().clientId(clientName).addFetch(topic, partition, fetchOffset, BUFFER_SIZE_BYTES).maxWait(fetchTimeoutMs).build();
        FetchResponse fetchResponse = consumer.fetch(req);
        if (!fetchResponse.hasError()) {
            return fetchResponse.messageSet(topic, partition);
        }
        short errorCode = fetchResponse.errorCode(topic, partition);
        if (++failureCount >= MAX_KAFKA_FETCH_RETRIES) {
            throw new RuntimeException(String.format("Error fetching data from broker %s:%d for topic %s, partition %d. Error code: %d", consumer.host(), consumer.port(), topic, partition, errorCode));
        }
        LOG.warn("Error fetching data from broker {}:{} for topic {}, partition {}. Error code: {}", consumer.host(), consumer.port(), topic, partition, errorCode);
        if (errorCode == ErrorMapping.OffsetOutOfRangeCode()) {
            throw new OffsetOutOfRangeException(String.format("Requested offset %d is out of range for topic %s partition %d", fetchOffset, topic, partition));
        }
        closeConsumer();
    }
}
Also used : FetchRequestBuilder(kafka.api.FetchRequestBuilder) FetchRequest(kafka.api.FetchRequest) FetchResponse(kafka.javaapi.FetchResponse) OffsetOutOfRangeException(kafka.common.OffsetOutOfRangeException) SimpleConsumer(kafka.javaapi.consumer.SimpleConsumer)

Aggregations

FetchResponse (kafka.javaapi.FetchResponse)11 FetchRequest (kafka.api.FetchRequest)9 FetchRequestBuilder (kafka.api.FetchRequestBuilder)9 IOException (java.io.IOException)5 SimpleConsumer (kafka.javaapi.consumer.SimpleConsumer)5 ByteBufferMessageSet (kafka.javaapi.message.ByteBufferMessageSet)4 ConnectException (java.net.ConnectException)3 SocketTimeoutException (java.net.SocketTimeoutException)3 UnresolvedAddressException (java.nio.channels.UnresolvedAddressException)3 MessageAndOffset (kafka.message.MessageAndOffset)3 ByteBuffer (java.nio.ByteBuffer)2 ClosedChannelException (java.nio.channels.ClosedChannelException)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Map (java.util.Map)1 OffsetRequest (kafka.api.OffsetRequest)1 Broker (kafka.cluster.Broker)1 KafkaException (kafka.common.KafkaException)1 OffsetOutOfRangeException (kafka.common.OffsetOutOfRangeException)1