You are viewing a plain text version of this content. The canonical link for it is here.
Posted to jira@kafka.apache.org by "mimaison (via GitHub)" <gi...@apache.org> on 2024/01/26 16:51:46 UTC
[PR] KAFKA-14576: Move ConsoleConsumer to tools [kafka]
mimaison opened a new pull request, #15274:
URL: https://github.com/apache/kafka/pull/15274
### Committer Checklist (excluded from commit message)
- [ ] Verify design and implementation
- [ ] Verify test coverage and CI build status
- [ ] Verify documentation (including upgrade notes)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-14576: Move ConsoleConsumer to tools [kafka]
Posted by "OmniaGM (via GitHub)" <gi...@apache.org>.
OmniaGM commented on code in PR #15274:
URL: https://github.com/apache/kafka/pull/15274#discussion_r1472734283
##########
tools/src/main/java/org/apache/kafka/tools/consumer/ConsoleConsumer.java:
##########
@@ -0,0 +1,233 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.tools.consumer;
+
+import java.io.PrintStream;
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.util.OptionalLong;
+import java.util.concurrent.CountDownLatch;
+import java.util.regex.Pattern;
+import java.util.Collections;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.common.MessageFormatter;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.AuthenticationException;
+import org.apache.kafka.common.errors.TimeoutException;
+import org.apache.kafka.common.errors.WakeupException;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.serialization.ByteArrayDeserializer;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Consumer that dumps messages to standard out.
+ */
+class ConsoleConsumer {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ConsoleConsumer.class);
+ private static final CountDownLatch SHUTDOWN_LATCH = new CountDownLatch(1);
+
+ static int messageCount = 0;
+
+ public static void main(String[] args) throws Exception {
+ ConsoleConsumerOptions opts = new ConsoleConsumerOptions(args);
+ try {
+ run(opts);
+ } catch (AuthenticationException ae) {
+ LOG.error("Authentication failed: terminating consumer process", ae);
+ Exit.exit(1);
+ } catch (Throwable t) {
+ LOG.error("Unknown error when running consumer: ", t);
+ Exit.exit(1);
+ }
+ }
+
+ static void run(ConsoleConsumerOptions conf) {
+ long timeoutMs = conf.timeoutMs() >= 0 ? conf.timeoutMs() : Long.MAX_VALUE;
+ Consumer<byte[], byte[]> consumer = new KafkaConsumer<>(conf.consumerProps(), new ByteArrayDeserializer(), new ByteArrayDeserializer());
+ ConsumerWrapper consumerWrapper = conf.partitionArg().isPresent()
+ ? new ConsumerWrapper(Optional.of(conf.topicArg()), conf.partitionArg(), OptionalLong.of(conf.offsetArg()), Optional.empty(), consumer, timeoutMs)
+ : new ConsumerWrapper(Optional.of(conf.topicArg()), OptionalInt.empty(), OptionalLong.empty(), Optional.ofNullable(conf.includedTopicsArg()), consumer, timeoutMs);
+
+ addShutdownHook(consumerWrapper, conf);
+
+ try {
+ process(conf.maxMessages(), conf.formatter(), consumerWrapper, System.out, conf.skipMessageOnError());
+ } finally {
+ consumerWrapper.cleanup();
+ conf.formatter().close();
+ reportRecordCount();
+
+ SHUTDOWN_LATCH.countDown();
+ }
+ }
+
+ static void addShutdownHook(ConsumerWrapper consumer, ConsoleConsumerOptions conf) {
+ Exit.addShutdownHook("consumer-shutdown-hook", () -> {
+ try {
+ consumer.wakeup();
+ SHUTDOWN_LATCH.await();
+ } catch (Throwable t) {
+ LOG.error("Exception while running shutdown hook " + t.getMessage());
+ }
+ if (conf.enableSystestEventsLogging()) {
+ System.out.println("shutdown_complete");
+ }
+ });
+ }
+
+ static void process(int maxMessages, MessageFormatter formatter, ConsumerWrapper consumer, PrintStream output, boolean skipMessageOnError) {
+ while (messageCount < maxMessages || maxMessages == -1) {
+ ConsumerRecord<byte[], byte[]> msg;
+ try {
+ msg = consumer.receive();
+ } catch (WakeupException we) {
+ LOG.trace("Caught WakeupException because consumer is shutdown, ignore and terminate.");
+ // Consumer will be closed
+ return;
+ } catch (Throwable t) {
+ LOG.error("Error processing message, terminating consumer process: ", t);
+ // Consumer will be closed
+ return;
+ }
+ messageCount += 1;
+ try {
+ formatter.writeTo(new ConsumerRecord<>(msg.topic(), msg.partition(), msg.offset(), msg.timestamp(), msg.timestampType(),
+ 0, 0, msg.key(), msg.value(), msg.headers(), Optional.empty()), output);
+ } catch (Throwable t) {
+ if (skipMessageOnError) {
+ LOG.error("Error processing message, skipping this message: ", t);
+ } else {
+ // Consumer will be closed
+ throw t;
+ }
+ }
+ if (checkErr(output)) {
+ // Consumer will be closed
+ return;
+ }
+ }
+ }
+
+ static void reportRecordCount() {
+ System.err.println("Processed a total of " + messageCount + " messages");
+ }
+
+ static boolean checkErr(PrintStream output) {
+ boolean gotError = output.checkError();
+ if (gotError) {
+ // This means no one is listening to our output stream anymore, time to shut down
+ System.err.println("Unable to write to standard out, closing consumer.");
+ }
+ return gotError;
+ }
+
+ public static class ConsumerWrapper {
+ final Optional<String> topic;
+ final OptionalInt partitionId;
+ final OptionalLong offset;
+ final Optional<String> includedTopics;
+ final Consumer<byte[], byte[]> consumer;
+ final long timeoutMs;
+ final Time time = Time.SYSTEM;
+
+ Iterator<ConsumerRecord<byte[], byte[]>> recordIter = Collections.emptyIterator();
+
+ public ConsumerWrapper(Optional<String> topic,
Review Comment:
Do we really need to wrap these parameters in Optional? Also, `topic`, `partitionId`, `offset`, `includedTopics` values all come from `ConsoleConsumerOptions` so maybe we can just send `ConsoleConsumerOptions` here and get ripped of the extra if/else in line 72 and the optional wrappers
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-14576: Move ConsoleConsumer to tools [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on code in PR #15274:
URL: https://github.com/apache/kafka/pull/15274#discussion_r1474737738
##########
tools/src/main/java/org/apache/kafka/tools/consumer/ConsoleConsumer.java:
##########
@@ -0,0 +1,233 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.tools.consumer;
+
+import java.io.PrintStream;
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.util.OptionalLong;
+import java.util.concurrent.CountDownLatch;
+import java.util.regex.Pattern;
+import java.util.Collections;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.common.MessageFormatter;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.AuthenticationException;
+import org.apache.kafka.common.errors.TimeoutException;
+import org.apache.kafka.common.errors.WakeupException;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.serialization.ByteArrayDeserializer;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Consumer that dumps messages to standard out.
+ */
+class ConsoleConsumer {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ConsoleConsumer.class);
+ private static final CountDownLatch SHUTDOWN_LATCH = new CountDownLatch(1);
+
+ static int messageCount = 0;
+
+ public static void main(String[] args) throws Exception {
+ ConsoleConsumerOptions opts = new ConsoleConsumerOptions(args);
+ try {
+ run(opts);
+ } catch (AuthenticationException ae) {
+ LOG.error("Authentication failed: terminating consumer process", ae);
+ Exit.exit(1);
+ } catch (Throwable t) {
+ LOG.error("Unknown error when running consumer: ", t);
+ Exit.exit(1);
+ }
+ }
+
+ static void run(ConsoleConsumerOptions conf) {
+ long timeoutMs = conf.timeoutMs() >= 0 ? conf.timeoutMs() : Long.MAX_VALUE;
+ Consumer<byte[], byte[]> consumer = new KafkaConsumer<>(conf.consumerProps(), new ByteArrayDeserializer(), new ByteArrayDeserializer());
+ ConsumerWrapper consumerWrapper = conf.partitionArg().isPresent()
+ ? new ConsumerWrapper(Optional.of(conf.topicArg()), conf.partitionArg(), OptionalLong.of(conf.offsetArg()), Optional.empty(), consumer, timeoutMs)
+ : new ConsumerWrapper(Optional.of(conf.topicArg()), OptionalInt.empty(), OptionalLong.empty(), Optional.ofNullable(conf.includedTopicsArg()), consumer, timeoutMs);
+
+ addShutdownHook(consumerWrapper, conf);
+
+ try {
+ process(conf.maxMessages(), conf.formatter(), consumerWrapper, System.out, conf.skipMessageOnError());
+ } finally {
+ consumerWrapper.cleanup();
+ conf.formatter().close();
+ reportRecordCount();
+
+ SHUTDOWN_LATCH.countDown();
+ }
+ }
+
+ static void addShutdownHook(ConsumerWrapper consumer, ConsoleConsumerOptions conf) {
+ Exit.addShutdownHook("consumer-shutdown-hook", () -> {
+ try {
+ consumer.wakeup();
+ SHUTDOWN_LATCH.await();
+ } catch (Throwable t) {
+ LOG.error("Exception while running shutdown hook " + t.getMessage());
+ }
+ if (conf.enableSystestEventsLogging()) {
+ System.out.println("shutdown_complete");
+ }
+ });
+ }
+
+ static void process(int maxMessages, MessageFormatter formatter, ConsumerWrapper consumer, PrintStream output, boolean skipMessageOnError) {
+ while (messageCount < maxMessages || maxMessages == -1) {
+ ConsumerRecord<byte[], byte[]> msg;
+ try {
+ msg = consumer.receive();
+ } catch (WakeupException we) {
+ LOG.trace("Caught WakeupException because consumer is shutdown, ignore and terminate.");
+ // Consumer will be closed
+ return;
+ } catch (Throwable t) {
+ LOG.error("Error processing message, terminating consumer process: ", t);
+ // Consumer will be closed
+ return;
+ }
+ messageCount += 1;
+ try {
+ formatter.writeTo(new ConsumerRecord<>(msg.topic(), msg.partition(), msg.offset(), msg.timestamp(), msg.timestampType(),
+ 0, 0, msg.key(), msg.value(), msg.headers(), Optional.empty()), output);
+ } catch (Throwable t) {
+ if (skipMessageOnError) {
+ LOG.error("Error processing message, skipping this message: ", t);
+ } else {
+ // Consumer will be closed
+ throw t;
+ }
+ }
+ if (checkErr(output)) {
+ // Consumer will be closed
+ return;
+ }
+ }
+ }
+
+ static void reportRecordCount() {
+ System.err.println("Processed a total of " + messageCount + " messages");
+ }
+
+ static boolean checkErr(PrintStream output) {
+ boolean gotError = output.checkError();
+ if (gotError) {
+ // This means no one is listening to our output stream anymore, time to shut down
+ System.err.println("Unable to write to standard out, closing consumer.");
+ }
+ return gotError;
+ }
+
+ public static class ConsumerWrapper {
+ final Optional<String> topic;
+ final OptionalInt partitionId;
+ final OptionalLong offset;
+ final Optional<String> includedTopics;
+ final Consumer<byte[], byte[]> consumer;
+ final long timeoutMs;
+ final Time time = Time.SYSTEM;
+
+ Iterator<ConsumerRecord<byte[], byte[]>> recordIter = Collections.emptyIterator();
+
+ public ConsumerWrapper(Optional<String> topic,
Review Comment:
I opted to copy the previous logic to make it easier to review and avoid changing any behavior by mistake. I agree this could be refactored but I'd prefer doing that in a follow up PR.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-14576: Move ConsoleConsumer to tools [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on PR #15274:
URL: https://github.com/apache/kafka/pull/15274#issuecomment-1941348640
@OmniaGM do you want to take another look?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-14576: Move ConsoleConsumer to tools [kafka]
Posted by "OmniaGM (via GitHub)" <gi...@apache.org>.
OmniaGM commented on code in PR #15274:
URL: https://github.com/apache/kafka/pull/15274#discussion_r1472771173
##########
tools/src/main/java/org/apache/kafka/tools/consumer/ConsoleConsumer.java:
##########
@@ -0,0 +1,233 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.tools.consumer;
+
+import java.io.PrintStream;
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.util.OptionalLong;
+import java.util.concurrent.CountDownLatch;
+import java.util.regex.Pattern;
+import java.util.Collections;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.common.MessageFormatter;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.AuthenticationException;
+import org.apache.kafka.common.errors.TimeoutException;
+import org.apache.kafka.common.errors.WakeupException;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.serialization.ByteArrayDeserializer;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Consumer that dumps messages to standard out.
+ */
+class ConsoleConsumer {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ConsoleConsumer.class);
+ private static final CountDownLatch SHUTDOWN_LATCH = new CountDownLatch(1);
+
+ static int messageCount = 0;
+
+ public static void main(String[] args) throws Exception {
+ ConsoleConsumerOptions opts = new ConsoleConsumerOptions(args);
+ try {
+ run(opts);
+ } catch (AuthenticationException ae) {
+ LOG.error("Authentication failed: terminating consumer process", ae);
+ Exit.exit(1);
+ } catch (Throwable t) {
+ LOG.error("Unknown error when running consumer: ", t);
+ Exit.exit(1);
+ }
+ }
+
+ static void run(ConsoleConsumerOptions conf) {
+ long timeoutMs = conf.timeoutMs() >= 0 ? conf.timeoutMs() : Long.MAX_VALUE;
+ Consumer<byte[], byte[]> consumer = new KafkaConsumer<>(conf.consumerProps(), new ByteArrayDeserializer(), new ByteArrayDeserializer());
+ ConsumerWrapper consumerWrapper = conf.partitionArg().isPresent()
+ ? new ConsumerWrapper(Optional.of(conf.topicArg()), conf.partitionArg(), OptionalLong.of(conf.offsetArg()), Optional.empty(), consumer, timeoutMs)
+ : new ConsumerWrapper(Optional.of(conf.topicArg()), OptionalInt.empty(), OptionalLong.empty(), Optional.ofNullable(conf.includedTopicsArg()), consumer, timeoutMs);
+
+ addShutdownHook(consumerWrapper, conf);
+
+ try {
+ process(conf.maxMessages(), conf.formatter(), consumerWrapper, System.out, conf.skipMessageOnError());
+ } finally {
+ consumerWrapper.cleanup();
+ conf.formatter().close();
+ reportRecordCount();
+
+ SHUTDOWN_LATCH.countDown();
+ }
+ }
+
+ static void addShutdownHook(ConsumerWrapper consumer, ConsoleConsumerOptions conf) {
+ Exit.addShutdownHook("consumer-shutdown-hook", () -> {
+ try {
+ consumer.wakeup();
+ SHUTDOWN_LATCH.await();
+ } catch (Throwable t) {
+ LOG.error("Exception while running shutdown hook " + t.getMessage());
+ }
+ if (conf.enableSystestEventsLogging()) {
+ System.out.println("shutdown_complete");
+ }
+ });
+ }
+
+ static void process(int maxMessages, MessageFormatter formatter, ConsumerWrapper consumer, PrintStream output, boolean skipMessageOnError) {
+ while (messageCount < maxMessages || maxMessages == -1) {
+ ConsumerRecord<byte[], byte[]> msg;
+ try {
+ msg = consumer.receive();
+ } catch (WakeupException we) {
+ LOG.trace("Caught WakeupException because consumer is shutdown, ignore and terminate.");
+ // Consumer will be closed
+ return;
+ } catch (Throwable t) {
+ LOG.error("Error processing message, terminating consumer process: ", t);
+ // Consumer will be closed
+ return;
+ }
+ messageCount += 1;
+ try {
+ formatter.writeTo(new ConsumerRecord<>(msg.topic(), msg.partition(), msg.offset(), msg.timestamp(), msg.timestampType(),
+ 0, 0, msg.key(), msg.value(), msg.headers(), Optional.empty()), output);
+ } catch (Throwable t) {
+ if (skipMessageOnError) {
+ LOG.error("Error processing message, skipping this message: ", t);
+ } else {
+ // Consumer will be closed
+ throw t;
+ }
+ }
+ if (checkErr(output)) {
+ // Consumer will be closed
+ return;
+ }
+ }
+ }
+
+ static void reportRecordCount() {
+ System.err.println("Processed a total of " + messageCount + " messages");
+ }
+
+ static boolean checkErr(PrintStream output) {
+ boolean gotError = output.checkError();
+ if (gotError) {
+ // This means no one is listening to our output stream anymore, time to shut down
+ System.err.println("Unable to write to standard out, closing consumer.");
+ }
+ return gotError;
+ }
+
+ public static class ConsumerWrapper {
+ final Optional<String> topic;
+ final OptionalInt partitionId;
+ final OptionalLong offset;
+ final Optional<String> includedTopics;
+ final Consumer<byte[], byte[]> consumer;
+ final long timeoutMs;
+ final Time time = Time.SYSTEM;
+
+ Iterator<ConsumerRecord<byte[], byte[]>> recordIter = Collections.emptyIterator();
+
+ public ConsumerWrapper(Optional<String> topic,
+ OptionalInt partitionId,
+ OptionalLong offset,
+ Optional<String> includedTopics,
+ Consumer<byte[], byte[]> consumer,
+ long timeoutMs) {
+ this.topic = topic;
+ this.partitionId = partitionId;
+ this.offset = offset;
+ this.includedTopics = includedTopics;
+ this.consumer = consumer;
+ this.timeoutMs = timeoutMs;
+
+ if (topic.isPresent() && partitionId.isPresent() && offset.isPresent() && !includedTopics.isPresent()) {
+ seek(topic.get(), partitionId.getAsInt(), offset.getAsLong());
+ } else if (topic.isPresent() && partitionId.isPresent() && !offset.isPresent() && !includedTopics.isPresent()) {
+ // default to latest if no offset is provided
+ seek(topic.get(), partitionId.getAsInt(), ListOffsetsRequest.LATEST_TIMESTAMP);
Review Comment:
can't we use `ConsoleConsumerOptions.parseOffset` to either grab the given offset or the default instead of these 2 ifs?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-14576: Move ConsoleConsumer to tools [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on code in PR #15274:
URL: https://github.com/apache/kafka/pull/15274#discussion_r1474695808
##########
tools/src/main/java/org/apache/kafka/tools/consumer/ConsoleConsumerOptions.java:
##########
@@ -0,0 +1,414 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.tools.consumer;
+
+import joptsimple.OptionException;
+import joptsimple.OptionSpec;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.common.MessageFormatter;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.utils.Utils;
+import org.apache.kafka.server.util.CommandDefaultOptions;
+import org.apache.kafka.server.util.CommandLineUtils;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.OptionalInt;
+import java.util.Properties;
+import java.util.Random;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+public class ConsoleConsumerOptions extends CommandDefaultOptions {
+
+ private static final Random RANDOM = new Random();
+
+ private final OptionSpec<String> topicOpt;
+ private final OptionSpec<String> whitelistOpt;
+ private final OptionSpec<String> includeOpt;
+ private final OptionSpec<Integer> partitionIdOpt;
+ private final OptionSpec<String> offsetOpt;
+ private final OptionSpec<String> messageFormatterOpt;
+ private final OptionSpec<String> messageFormatterArgOpt;
+ private final OptionSpec<String> messageFormatterConfigOpt;
+ private final OptionSpec<?> resetBeginningOpt;
+ private final OptionSpec<Integer> maxMessagesOpt;
+ private final OptionSpec<Integer> timeoutMsOpt;
+ private final OptionSpec<?> skipMessageOnErrorOpt;
+ private final OptionSpec<String> bootstrapServerOpt;
+ private final OptionSpec<String> keyDeserializerOpt;
+ private final OptionSpec<String> valueDeserializerOpt;
+ private final OptionSpec<?> enableSystestEventsLoggingOpt;
+ private final OptionSpec<String> isolationLevelOpt;
+ private final OptionSpec<String> groupIdOpt;
+
+ private final Properties consumerProps;
+ private final long offset;
+ private final MessageFormatter formatter;
+
+ public ConsoleConsumerOptions(String[] args) throws IOException {
+ super(args);
+ topicOpt = parser.accepts("topic", "The topic to consume on.")
+ .withRequiredArg()
+ .describedAs("topic")
+ .ofType(String.class);
+ whitelistOpt = parser.accepts("whitelist",
+ "DEPRECATED, use --include instead; ignored if --include specified. Regular expression specifying list of topics to include for consumption.")
+ .withRequiredArg()
+ .describedAs("Java regex (String)")
+ .ofType(String.class);
+ includeOpt = parser.accepts("include",
+ "Regular expression specifying list of topics to include for consumption.")
+ .withRequiredArg()
+ .describedAs("Java regex (String)")
+ .ofType(String.class);
+ partitionIdOpt = parser.accepts("partition",
+ "The partition to consume from. Consumption starts from the end of the partition unless '--offset' is specified.")
+ .withRequiredArg()
+ .describedAs("partition")
+ .ofType(Integer.class);
+ offsetOpt = parser.accepts("offset", "The offset to consume from (a non-negative number), or 'earliest' which means from beginning, or 'latest' which means from end")
+ .withRequiredArg()
+ .describedAs("consume offset")
+ .ofType(String.class)
+ .defaultsTo("latest");
+ OptionSpec<String> consumerPropertyOpt = parser.accepts("consumer-property", "A mechanism to pass user-defined properties in the form key=value to the consumer.")
+ .withRequiredArg()
+ .describedAs("consumer_prop")
+ .ofType(String.class);
+ OptionSpec<String> consumerConfigOpt = parser.accepts("consumer.config", "Consumer config properties file. Note that " + consumerPropertyOpt + " takes precedence over this config.")
+ .withRequiredArg()
+ .describedAs("config file")
+ .ofType(String.class);
+ messageFormatterOpt = parser.accepts("formatter", "The name of a class to use for formatting kafka messages for display.")
+ .withRequiredArg()
+ .describedAs("class")
+ .ofType(String.class)
+ .defaultsTo(DefaultMessageFormatter.class.getName());
+ messageFormatterArgOpt = parser.accepts("property",
+ "The properties to initialize the message formatter. Default properties include: \n" +
+ " print.timestamp=true|false\n" +
+ " print.key=true|false\n" +
+ " print.offset=true|false\n" +
+ " print.partition=true|false\n" +
+ " print.headers=true|false\n" +
+ " print.value=true|false\n" +
+ " key.separator=<key.separator>\n" +
+ " line.separator=<line.separator>\n" +
+ " headers.separator=<line.separator>\n" +
+ " null.literal=<null.literal>\n" +
+ " key.deserializer=<key.deserializer>\n" +
+ " value.deserializer=<value.deserializer>\n" +
+ " header.deserializer=<header.deserializer>\n" +
+ "\nUsers can also pass in customized properties for their formatter; more specifically, users can pass in properties keyed with 'key.deserializer.', 'value.deserializer.' and 'headers.deserializer.' prefixes to configure their deserializers.")
+ .withRequiredArg()
+ .describedAs("prop")
+ .ofType(String.class);
+ messageFormatterConfigOpt = parser.accepts("formatter-config", "Config properties file to initialize the message formatter. Note that " + messageFormatterArgOpt + " takes precedence over this config.")
+ .withRequiredArg()
+ .describedAs("config file")
+ .ofType(String.class);
+ resetBeginningOpt = parser.accepts("from-beginning", "If the consumer does not already have an established offset to consume from, " +
+ "start with the earliest message present in the log rather than the latest message.");
+ maxMessagesOpt = parser.accepts("max-messages", "The maximum number of messages to consume before exiting. If not set, consumption is continual.")
+ .withRequiredArg()
+ .describedAs("num_messages")
+ .ofType(Integer.class);
+ timeoutMsOpt = parser.accepts("timeout-ms", "If specified, exit if no message is available for consumption for the specified interval.")
+ .withRequiredArg()
+ .describedAs("timeout_ms")
+ .ofType(Integer.class);
+ skipMessageOnErrorOpt = parser.accepts("skip-message-on-error", "If there is an error when processing a message, " +
+ "skip it instead of halt.");
+ bootstrapServerOpt = parser.accepts("bootstrap-server", "REQUIRED: The server(s) to connect to.")
+ .withRequiredArg()
+ .describedAs("server to connect to")
+ .ofType(String.class);
+ keyDeserializerOpt = parser.accepts("key-deserializer")
+ .withRequiredArg()
+ .describedAs("deserializer for key")
+ .ofType(String.class);
+ valueDeserializerOpt = parser.accepts("value-deserializer")
+ .withRequiredArg()
+ .describedAs("deserializer for values")
+ .ofType(String.class);
+ enableSystestEventsLoggingOpt = parser.accepts("enable-systest-events",
+ "Log lifecycle events of the consumer in addition to logging consumed messages. (This is specific for system tests.)");
+ isolationLevelOpt = parser.accepts("isolation-level",
+ "Set to read_committed in order to filter out transactional messages which are not committed. Set to read_uncommitted " +
+ "to read all messages.")
+ .withRequiredArg()
+ .ofType(String.class)
+ .defaultsTo("read_uncommitted");
+ groupIdOpt = parser.accepts("group", "The consumer group id of the consumer.")
+ .withRequiredArg()
+ .describedAs("consumer group id")
+ .ofType(String.class);
+
+ try {
+ options = parser.parse(args);
+ } catch (OptionException oe) {
+ CommandLineUtils.printUsageAndExit(parser, oe.getMessage());
+ }
+
+ CommandLineUtils.maybePrintHelpOrVersion(this, "This tool helps to read data from Kafka topics and outputs it to standard output.");
+
+ checkRequiredArgs();
+
+ Properties consumerPropsFromFile = options.has(consumerConfigOpt)
+ ? Utils.loadProps(options.valueOf(consumerConfigOpt))
+ : new Properties();
+ Properties extraConsumerProps = CommandLineUtils.parseKeyValueArgs(options.valuesOf(consumerPropertyOpt));
+
+ Set<String> groupIdsProvided = checkConsumerGroup(consumerPropsFromFile, extraConsumerProps);
+ consumerProps = buildConsumerProps(consumerPropsFromFile, extraConsumerProps, groupIdsProvided);
+ offset = parseOffset();
+ formatter = buildFormatter();
+ }
+
+ private void checkRequiredArgs() {
+ List<String> topicOrFilterArgs = new ArrayList<>(Arrays.asList(topicArg(), includedTopicsArg()));
+ topicOrFilterArgs.removeIf(Objects::isNull);
+ // user need to specify value for either --topic or one of the include filters options (--include or --whitelist)
+ if (topicOrFilterArgs.size() != 1) {
+ CommandLineUtils.printUsageAndExit(parser, "Exactly one of --include/--topic is required. " +
+ (options.has(whitelistOpt) ? "--whitelist is DEPRECATED use --include instead; ignored if --include specified." : ""));
+ }
+
+ if (partitionArg().isPresent()) {
+ if (!options.has(topicOpt)) {
+ CommandLineUtils.printUsageAndExit(parser, "The topic is required when partition is specified.");
+ }
+ if (fromBeginning() && options.has(offsetOpt)) {
+ CommandLineUtils.printUsageAndExit(parser, "Options from-beginning and offset cannot be specified together.");
+ }
+ } else if (options.has(offsetOpt)) {
+ CommandLineUtils.printUsageAndExit(parser, "The partition is required when offset is specified.");
+ }
+
+ CommandLineUtils.checkRequiredArgs(parser, options, bootstrapServerOpt);
+ }
+
+ private Set<String> checkConsumerGroup(Properties consumerPropsFromFile, Properties extraConsumerProps) {
+ // if the group id is provided in more than place (through different means) all values must be the same
+ Set<String> groupIdsProvided = new HashSet<>();
+ if (options.has(groupIdOpt)) {
+ groupIdsProvided.add(options.valueOf(groupIdOpt));
+ }
+
+ if (consumerPropsFromFile.containsKey(ConsumerConfig.GROUP_ID_CONFIG)) {
+ groupIdsProvided.add((String) consumerPropsFromFile.get(ConsumerConfig.GROUP_ID_CONFIG));
+ }
+
+ if (extraConsumerProps.containsKey(ConsumerConfig.GROUP_ID_CONFIG)) {
+ groupIdsProvided.add(extraConsumerProps.getProperty(ConsumerConfig.GROUP_ID_CONFIG));
+ }
+ if (groupIdsProvided.size() > 1) {
+ CommandLineUtils.printUsageAndExit(parser, "The group ids provided in different places (directly using '--group', "
+ + "via '--consumer-property', or via '--consumer.config') do not match. "
+ + "Detected group ids: "
+ + groupIdsProvided.stream().map(group -> "'" + group + "'").collect(Collectors.joining(", ")));
+ }
+ if (!groupIdsProvided.isEmpty() && partitionArg().isPresent()) {
+ CommandLineUtils.printUsageAndExit(parser, "Options group and partition cannot be specified together.");
+ }
+ return groupIdsProvided;
+ }
+
+ private Properties buildConsumerProps(Properties consumerPropsFromFile, Properties extraConsumerProps, Set<String> groupIdsProvided) {
+ Properties consumerProps = new Properties(consumerPropsFromFile);
+ consumerProps.putAll(extraConsumerProps);
+ setAutoOffsetResetValue(consumerProps);
+ consumerProps.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServer());
+ if (consumerProps.getProperty(ConsumerConfig.CLIENT_ID_CONFIG) == null) {
+ consumerProps.put(ConsumerConfig.CLIENT_ID_CONFIG, "console-consumer");
+ }
+ CommandLineUtils.maybeMergeOptions(consumerProps, ConsumerConfig.ISOLATION_LEVEL_CONFIG, options, isolationLevelOpt);
+
+ if (groupIdsProvided.isEmpty()) {
+ consumerProps.put(ConsumerConfig.GROUP_ID_CONFIG, "console-consumer-" + RANDOM.nextInt(100000));
+ // By default, avoid unnecessary expansion of the coordinator cache since
+ // the auto-generated group and its offsets is not intended to be used again
+ if (!consumerProps.containsKey(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG)) {
+ consumerProps.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
+ }
+ } else {
+ consumerProps.put(ConsumerConfig.GROUP_ID_CONFIG, groupIdsProvided.iterator().next());
+ }
+ return consumerProps;
+ }
+
+ /**
+ * Used to retrieve the correct value for the consumer parameter 'auto.offset.reset'.
+ * Order of priority is:
+ * 1. Explicitly set parameter via --consumer.property command line parameter
+ * 2. Explicit --from-beginning given -> 'earliest'
+ * 3. Default value of 'latest'
+ * In case both --from-beginning and an explicit value are specified an error is thrown if these
+ * are conflicting.
+ */
+ private void setAutoOffsetResetValue(Properties props) {
+ String earliestConfigValue = "earliest";
+ String latestConfigValue = "latest";
+
+ if (props.containsKey(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG)) {
+ // auto.offset.reset parameter was specified on the command line
+ String autoResetOption = props.getProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG);
+ if (fromBeginning() && !earliestConfigValue.equals(autoResetOption)) {
+ // conflicting options - latest und earliest, throw an error
+ System.err.println("Can't simultaneously specify --from-beginning and 'auto.offset.reset=" + autoResetOption + "', " +
+ "please remove one option");
+ Exit.exit(1);
+ }
+ // nothing to do, checking for valid parameter values happens later and the specified
+ // value was already copied during .putall operation
+ } else {
+ // no explicit value for auto.offset.reset was specified
+ // if --from-beginning was specified use earliest, otherwise default to latest
+ String autoResetOption = fromBeginning() ? earliestConfigValue : latestConfigValue;
+ props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoResetOption);
+ }
+ }
+
+ private long parseOffset() {
+ if (options.has(offsetOpt)) {
+ switch (options.valueOf(offsetOpt).toLowerCase(Locale.ROOT)) {
+ case "earliest":
+ return ListOffsetsRequest.EARLIEST_TIMESTAMP;
+ case "latest":
+ return ListOffsetsRequest.LATEST_TIMESTAMP;
+ default:
+ String offsetString = options.valueOf(offsetOpt);
+ try {
+ long offset = Long.parseLong(offsetString);
+ if (offset < 0) {
+ invalidOffset(offsetString);
+ }
+ return offset;
+ } catch (NumberFormatException nfe) {
+ invalidOffset(offsetString);
+ }
+ }
+ } else if (fromBeginning()) {
+ return ListOffsetsRequest.EARLIEST_TIMESTAMP;
+ }
+ return ListOffsetsRequest.LATEST_TIMESTAMP;
+ }
+
+ private void invalidOffset(String offset) {
+ CommandLineUtils.printUsageAndExit(parser, "The provided offset value '" + offset + "' is incorrect. Valid values are " +
+ "'earliest', 'latest', or a non-negative long.");
+ }
+
+ private MessageFormatter buildFormatter() {
+ MessageFormatter formatter = null;
Review Comment:
Yes it's needed otherwise the compiler complains `formatter` may not have been initialized as it does not understand the catch clause causes the tool to exit.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-14576: Move ConsoleConsumer to tools [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on code in PR #15274:
URL: https://github.com/apache/kafka/pull/15274#discussion_r1482987163
##########
tests/kafkatest/services/console_consumer.py:
##########
@@ -21,7 +21,7 @@
from kafkatest.directory_layout.kafka_path import KafkaPathResolverMixin
from kafkatest.services.monitor.jmx import JmxMixin, JmxTool
-from kafkatest.version import DEV_BRANCH, LATEST_0_8_2, LATEST_0_9, LATEST_0_10_0, V_0_10_0_0, V_0_11_0_0, V_2_0_0
+from kafkatest.version import DEV_BRANCH, LATEST_0_8_2, LATEST_0_9, LATEST_0_10_0, V_0_10_0_0, V_0_11_0_0, V_2_0_0, LATEST_3_7
Review Comment:
Actually since `DEV_VERSION` already points to 3.8, I should be able to introduce `LATEST_3_7` even if it's not released yet. I'll try that.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-14576: Move ConsoleConsumer to tools [kafka]
Posted by "jlprat (via GitHub)" <gi...@apache.org>.
jlprat commented on code in PR #15274:
URL: https://github.com/apache/kafka/pull/15274#discussion_r1478135674
##########
tools/src/main/java/org/apache/kafka/tools/consumer/LoggingMessageFormatter.java:
##########
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.tools.consumer;
+
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.common.MessageFormatter;
+import org.apache.kafka.common.record.TimestampType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.PrintStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Map;
+
+class LoggingMessageFormatter implements MessageFormatter {
+
+ private static final Logger LOG = LoggerFactory.getLogger(LoggingMessageFormatter.class);
+ private final DefaultMessageFormatter defaultWriter = new DefaultMessageFormatter();
+
+ @Override
+ public void configure(Map<String, ?> configs) {
+ defaultWriter.configure(configs);
+ }
+
+ @Override
+ public void writeTo(ConsumerRecord<byte[], byte[]> consumerRecord, PrintStream output) {
+ defaultWriter.writeTo(consumerRecord, output);
+ String timestamp = consumerRecord.timestampType() != TimestampType.NO_TIMESTAMP_TYPE
+ ? consumerRecord.timestampType() + ":" + consumerRecord.timestamp() + " "
Review Comment:
Trailing comma in case timestamps are present is missing
```suggestion
? consumerRecord.timestampType() + ":" + consumerRecord.timestamp() + ", "
```
##########
streams/src/test/java/org/apache/kafka/streams/integration/KStreamAggregationIntegrationTest.java:
##########
@@ -1139,8 +1140,7 @@ private <K, V> String readWindowedKeyedMessagesViaConsoleConsumer(final Deserial
"--property", "key.deserializer.window.size.ms=500",
};
- ConsoleConsumer.messageCount_$eq(0); //reset the message count
Review Comment:
Why this is not needed anymore with the new code?
##########
tools/src/test/java/org/apache/kafka/tools/consumer/ConsoleConsumerOptionsTest.java:
##########
@@ -0,0 +1,622 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.tools.consumer;
+
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.test.MockDeserializer;
+import org.apache.kafka.tools.ToolsTestUtils;
+import org.junit.jupiter.api.Test;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class ConsoleConsumerOptionsTest {
+
+ @Test
+ public void shouldParseValidConsumerValidConfig() throws IOException {
+ String[] args = new String[]{
+ "--bootstrap-server", "localhost:9092",
+ "--topic", "test",
+ "--from-beginning"
+ };
+
+ ConsoleConsumerOptions config = new ConsoleConsumerOptions(args);
+
+ assertEquals("localhost:9092", config.bootstrapServer());
+ assertEquals("test", config.topicArg());
+ assertTrue(config.fromBeginning());
+ assertFalse(config.enableSystestEventsLogging());
+ assertFalse(config.skipMessageOnError());
+ assertEquals(-1, config.maxMessages());
+ assertEquals(-1, config.timeoutMs());
Review Comment:
These were not present in the Scala code, but I guess it's fine to add them.
##########
tools/src/main/java/org/apache/kafka/tools/consumer/ConsoleConsumer.java:
##########
@@ -0,0 +1,234 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.tools.consumer;
+
+import java.io.PrintStream;
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.util.OptionalLong;
+import java.util.concurrent.CountDownLatch;
+import java.util.regex.Pattern;
+import java.util.Collections;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.common.MessageFormatter;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.AuthenticationException;
+import org.apache.kafka.common.errors.TimeoutException;
+import org.apache.kafka.common.errors.WakeupException;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.serialization.ByteArrayDeserializer;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Consumer that dumps messages to standard out.
+ */
+public class ConsoleConsumer {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ConsoleConsumer.class);
+ private static final CountDownLatch SHUTDOWN_LATCH = new CountDownLatch(1);
+
+ static int messageCount = 0;
+
+ public static void main(String[] args) throws Exception {
+ ConsoleConsumerOptions opts = new ConsoleConsumerOptions(args);
+ try {
+ run(opts);
+ } catch (AuthenticationException ae) {
+ LOG.error("Authentication failed: terminating consumer process", ae);
+ Exit.exit(1);
+ } catch (Throwable t) {
+ LOG.error("Unknown error when running consumer: ", t);
+ Exit.exit(1);
+ }
+ }
+
+ public static void run(ConsoleConsumerOptions opts) {
+ messageCount = 0;
+ long timeoutMs = opts.timeoutMs() >= 0 ? opts.timeoutMs() : Long.MAX_VALUE;
+ Consumer<byte[], byte[]> consumer = new KafkaConsumer<>(opts.consumerProps(), new ByteArrayDeserializer(), new ByteArrayDeserializer());
+ ConsumerWrapper consumerWrapper = opts.partitionArg().isPresent()
+ ? new ConsumerWrapper(Optional.of(opts.topicArg()), opts.partitionArg(), OptionalLong.of(opts.offsetArg()), Optional.empty(), consumer, timeoutMs)
+ : new ConsumerWrapper(Optional.of(opts.topicArg()), OptionalInt.empty(), OptionalLong.empty(), Optional.ofNullable(opts.includedTopicsArg()), consumer, timeoutMs);
+
+ addShutdownHook(consumerWrapper, opts);
+
+ try {
+ process(opts.maxMessages(), opts.formatter(), consumerWrapper, System.out, opts.skipMessageOnError());
+ } finally {
+ consumerWrapper.cleanup();
+ opts.formatter().close();
+ reportRecordCount();
+
+ SHUTDOWN_LATCH.countDown();
+ }
+ }
+
+ static void addShutdownHook(ConsumerWrapper consumer, ConsoleConsumerOptions conf) {
+ Exit.addShutdownHook("consumer-shutdown-hook", () -> {
+ try {
+ consumer.wakeup();
+ SHUTDOWN_LATCH.await();
+ } catch (Throwable t) {
+ LOG.error("Exception while running shutdown hook " + t.getMessage());
Review Comment:
Line 64, logs the whole exception, while here we have only the message. I guess it would be good to log the exception as well:
```suggestion
LOG.error("Exception while running shutdown hook ", t);
```
##########
tools/src/main/java/org/apache/kafka/tools/consumer/LoggingMessageFormatter.java:
##########
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.tools.consumer;
+
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.common.MessageFormatter;
+import org.apache.kafka.common.record.TimestampType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.PrintStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Map;
+
+class LoggingMessageFormatter implements MessageFormatter {
+
+ private static final Logger LOG = LoggerFactory.getLogger(LoggingMessageFormatter.class);
+ private final DefaultMessageFormatter defaultWriter = new DefaultMessageFormatter();
+
+ @Override
+ public void configure(Map<String, ?> configs) {
+ defaultWriter.configure(configs);
+ }
+
+ @Override
+ public void writeTo(ConsumerRecord<byte[], byte[]> consumerRecord, PrintStream output) {
+ defaultWriter.writeTo(consumerRecord, output);
+ String timestamp = consumerRecord.timestampType() != TimestampType.NO_TIMESTAMP_TYPE
+ ? consumerRecord.timestampType() + ":" + consumerRecord.timestamp() + " "
+ : "";
+ String key = consumerRecord.key() == null ? "null" : new String(consumerRecord.key(), StandardCharsets.UTF_8);
+ String value = consumerRecord.value() == null ? "null" : new String(consumerRecord.value(), StandardCharsets.UTF_8);
Review Comment:
These 2 lines are not equivalent to the Scala code. Both `key` and `value` Strings are missing "key:" and "value:" respectively. Also trailing comma on `key` is missing.
```suggestion
String key = "key:" + consumerRecord.key() == null ? "null" : new String(consumerRecord.key(), StandardCharsets.UTF_8) + ",";
String value = "value:" + consumerRecord.value() == null ? "null" : new String(consumerRecord.value(), StandardCharsets.UTF_8);
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-14576: Move ConsoleConsumer to tools [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on code in PR #15274:
URL: https://github.com/apache/kafka/pull/15274#discussion_r1478422740
##########
tests/kafkatest/services/console_consumer.py:
##########
@@ -210,7 +210,10 @@ def start_cmd(self, node):
# LoggingMessageFormatter was introduced after 0.9
if node.version > LATEST_0_9:
- cmd += " --formatter org.apache.kafka.tools.consumer.LoggingMessageFormatter"
+ if node.version > LATEST_3_7:
+ cmd += " --formatter org.apache.kafka.tools.consumer.LoggingMessageFormatter"
+ else:
+ cmd += " --formatter kafka.tools.LoggingMessageFormatter"
Review Comment:
`LoggingMessageFormatter`, `DefaultMessageFormatter`, `NoOpMessageFormatter` are not part of the public API and as far as I can tell the class names are not visible anywhere so this shouldn't be considered an API change.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-14576: Move ConsoleConsumer to tools [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on PR #15274:
URL: https://github.com/apache/kafka/pull/15274#issuecomment-1941235786
I rebased on trunk to resolve conflicts. It seems my last fix has resolved the issues with the system tests so it is ready to review again.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-14576: Move ConsoleConsumer to tools [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on code in PR #15274:
URL: https://github.com/apache/kafka/pull/15274#discussion_r1478332515
##########
streams/src/test/java/org/apache/kafka/streams/integration/KStreamAggregationIntegrationTest.java:
##########
@@ -1139,8 +1140,7 @@ private <K, V> String readWindowedKeyedMessagesViaConsoleConsumer(final Deserial
"--property", "key.deserializer.window.size.ms=500",
};
- ConsoleConsumer.messageCount_$eq(0); //reset the message count
Review Comment:
I made `ConsoleConsumer.run()` reset to count to 0 in https://github.com/apache/kafka/pull/15274/files#diff-84e7d94a76d5ecef71ab8b1b978972bcfbe869ace82a87086bdf0067ebf6c2fbR70
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-14576: Move ConsoleConsumer to tools [kafka]
Posted by "OmniaGM (via GitHub)" <gi...@apache.org>.
OmniaGM commented on code in PR #15274:
URL: https://github.com/apache/kafka/pull/15274#discussion_r1472710835
##########
tools/src/main/java/org/apache/kafka/tools/consumer/ConsoleConsumer.java:
##########
@@ -0,0 +1,233 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.tools.consumer;
+
+import java.io.PrintStream;
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.util.OptionalLong;
+import java.util.concurrent.CountDownLatch;
+import java.util.regex.Pattern;
+import java.util.Collections;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.common.MessageFormatter;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.AuthenticationException;
+import org.apache.kafka.common.errors.TimeoutException;
+import org.apache.kafka.common.errors.WakeupException;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.serialization.ByteArrayDeserializer;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Consumer that dumps messages to standard out.
+ */
+class ConsoleConsumer {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ConsoleConsumer.class);
+ private static final CountDownLatch SHUTDOWN_LATCH = new CountDownLatch(1);
+
+ static int messageCount = 0;
+
+ public static void main(String[] args) throws Exception {
+ ConsoleConsumerOptions opts = new ConsoleConsumerOptions(args);
+ try {
+ run(opts);
+ } catch (AuthenticationException ae) {
+ LOG.error("Authentication failed: terminating consumer process", ae);
+ Exit.exit(1);
+ } catch (Throwable t) {
+ LOG.error("Unknown error when running consumer: ", t);
+ Exit.exit(1);
+ }
+ }
+
+ static void run(ConsoleConsumerOptions conf) {
Review Comment:
Just for consistency can we rename `conf` to `opts`like L.57?
##########
tools/src/main/java/org/apache/kafka/tools/consumer/ConsoleConsumer.java:
##########
@@ -0,0 +1,233 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.tools.consumer;
+
+import java.io.PrintStream;
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.util.OptionalLong;
+import java.util.concurrent.CountDownLatch;
+import java.util.regex.Pattern;
+import java.util.Collections;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.common.MessageFormatter;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.AuthenticationException;
+import org.apache.kafka.common.errors.TimeoutException;
+import org.apache.kafka.common.errors.WakeupException;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.serialization.ByteArrayDeserializer;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Consumer that dumps messages to standard out.
+ */
+class ConsoleConsumer {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ConsoleConsumer.class);
+ private static final CountDownLatch SHUTDOWN_LATCH = new CountDownLatch(1);
+
+ static int messageCount = 0;
+
+ public static void main(String[] args) throws Exception {
+ ConsoleConsumerOptions opts = new ConsoleConsumerOptions(args);
+ try {
+ run(opts);
+ } catch (AuthenticationException ae) {
+ LOG.error("Authentication failed: terminating consumer process", ae);
+ Exit.exit(1);
+ } catch (Throwable t) {
+ LOG.error("Unknown error when running consumer: ", t);
+ Exit.exit(1);
+ }
+ }
+
+ static void run(ConsoleConsumerOptions conf) {
+ long timeoutMs = conf.timeoutMs() >= 0 ? conf.timeoutMs() : Long.MAX_VALUE;
+ Consumer<byte[], byte[]> consumer = new KafkaConsumer<>(conf.consumerProps(), new ByteArrayDeserializer(), new ByteArrayDeserializer());
+ ConsumerWrapper consumerWrapper = conf.partitionArg().isPresent()
+ ? new ConsumerWrapper(Optional.of(conf.topicArg()), conf.partitionArg(), OptionalLong.of(conf.offsetArg()), Optional.empty(), consumer, timeoutMs)
+ : new ConsumerWrapper(Optional.of(conf.topicArg()), OptionalInt.empty(), OptionalLong.empty(), Optional.ofNullable(conf.includedTopicsArg()), consumer, timeoutMs);
+
+ addShutdownHook(consumerWrapper, conf);
+
+ try {
+ process(conf.maxMessages(), conf.formatter(), consumerWrapper, System.out, conf.skipMessageOnError());
+ } finally {
+ consumerWrapper.cleanup();
+ conf.formatter().close();
+ reportRecordCount();
+
+ SHUTDOWN_LATCH.countDown();
+ }
+ }
+
+ static void addShutdownHook(ConsumerWrapper consumer, ConsoleConsumerOptions conf) {
+ Exit.addShutdownHook("consumer-shutdown-hook", () -> {
+ try {
+ consumer.wakeup();
+ SHUTDOWN_LATCH.await();
+ } catch (Throwable t) {
+ LOG.error("Exception while running shutdown hook " + t.getMessage());
+ }
+ if (conf.enableSystestEventsLogging()) {
+ System.out.println("shutdown_complete");
+ }
+ });
+ }
+
+ static void process(int maxMessages, MessageFormatter formatter, ConsumerWrapper consumer, PrintStream output, boolean skipMessageOnError) {
+ while (messageCount < maxMessages || maxMessages == -1) {
+ ConsumerRecord<byte[], byte[]> msg;
+ try {
+ msg = consumer.receive();
+ } catch (WakeupException we) {
+ LOG.trace("Caught WakeupException because consumer is shutdown, ignore and terminate.");
+ // Consumer will be closed
+ return;
+ } catch (Throwable t) {
+ LOG.error("Error processing message, terminating consumer process: ", t);
+ // Consumer will be closed
+ return;
+ }
+ messageCount += 1;
+ try {
+ formatter.writeTo(new ConsumerRecord<>(msg.topic(), msg.partition(), msg.offset(), msg.timestamp(), msg.timestampType(),
+ 0, 0, msg.key(), msg.value(), msg.headers(), Optional.empty()), output);
+ } catch (Throwable t) {
+ if (skipMessageOnError) {
+ LOG.error("Error processing message, skipping this message: ", t);
+ } else {
+ // Consumer will be closed
+ throw t;
+ }
+ }
+ if (checkErr(output)) {
+ // Consumer will be closed
+ return;
+ }
+ }
+ }
+
+ static void reportRecordCount() {
+ System.err.println("Processed a total of " + messageCount + " messages");
+ }
+
+ static boolean checkErr(PrintStream output) {
+ boolean gotError = output.checkError();
+ if (gotError) {
+ // This means no one is listening to our output stream anymore, time to shut down
+ System.err.println("Unable to write to standard out, closing consumer.");
+ }
+ return gotError;
+ }
+
+ public static class ConsumerWrapper {
+ final Optional<String> topic;
+ final OptionalInt partitionId;
+ final OptionalLong offset;
+ final Optional<String> includedTopics;
+ final Consumer<byte[], byte[]> consumer;
+ final long timeoutMs;
+ final Time time = Time.SYSTEM;
+
+ Iterator<ConsumerRecord<byte[], byte[]>> recordIter = Collections.emptyIterator();
+
+ public ConsumerWrapper(Optional<String> topic,
Review Comment:
Do we really need to wrap these parameters in Optional? Also, `topic`, `partitionId`, `offset`, `includedTopics` values all come from `ConsoleConsumerOptions` so maybe we can just send `ConsoleConsumerOptions` here and get ripped of the extra if/else in line 72 and the optional wrapper
##########
tools/src/main/java/org/apache/kafka/tools/consumer/ConsoleConsumer.java:
##########
@@ -0,0 +1,233 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.tools.consumer;
+
+import java.io.PrintStream;
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.util.OptionalLong;
+import java.util.concurrent.CountDownLatch;
+import java.util.regex.Pattern;
+import java.util.Collections;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.common.MessageFormatter;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.AuthenticationException;
+import org.apache.kafka.common.errors.TimeoutException;
+import org.apache.kafka.common.errors.WakeupException;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.serialization.ByteArrayDeserializer;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Consumer that dumps messages to standard out.
+ */
+class ConsoleConsumer {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ConsoleConsumer.class);
+ private static final CountDownLatch SHUTDOWN_LATCH = new CountDownLatch(1);
+
+ static int messageCount = 0;
+
+ public static void main(String[] args) throws Exception {
+ ConsoleConsumerOptions opts = new ConsoleConsumerOptions(args);
+ try {
+ run(opts);
+ } catch (AuthenticationException ae) {
+ LOG.error("Authentication failed: terminating consumer process", ae);
+ Exit.exit(1);
+ } catch (Throwable t) {
+ LOG.error("Unknown error when running consumer: ", t);
+ Exit.exit(1);
+ }
+ }
+
+ static void run(ConsoleConsumerOptions conf) {
+ long timeoutMs = conf.timeoutMs() >= 0 ? conf.timeoutMs() : Long.MAX_VALUE;
+ Consumer<byte[], byte[]> consumer = new KafkaConsumer<>(conf.consumerProps(), new ByteArrayDeserializer(), new ByteArrayDeserializer());
+ ConsumerWrapper consumerWrapper = conf.partitionArg().isPresent()
+ ? new ConsumerWrapper(Optional.of(conf.topicArg()), conf.partitionArg(), OptionalLong.of(conf.offsetArg()), Optional.empty(), consumer, timeoutMs)
+ : new ConsumerWrapper(Optional.of(conf.topicArg()), OptionalInt.empty(), OptionalLong.empty(), Optional.ofNullable(conf.includedTopicsArg()), consumer, timeoutMs);
+
+ addShutdownHook(consumerWrapper, conf);
+
+ try {
+ process(conf.maxMessages(), conf.formatter(), consumerWrapper, System.out, conf.skipMessageOnError());
+ } finally {
+ consumerWrapper.cleanup();
+ conf.formatter().close();
+ reportRecordCount();
+
+ SHUTDOWN_LATCH.countDown();
+ }
+ }
+
+ static void addShutdownHook(ConsumerWrapper consumer, ConsoleConsumerOptions conf) {
+ Exit.addShutdownHook("consumer-shutdown-hook", () -> {
+ try {
+ consumer.wakeup();
+ SHUTDOWN_LATCH.await();
+ } catch (Throwable t) {
+ LOG.error("Exception while running shutdown hook " + t.getMessage());
+ }
+ if (conf.enableSystestEventsLogging()) {
+ System.out.println("shutdown_complete");
+ }
+ });
+ }
+
+ static void process(int maxMessages, MessageFormatter formatter, ConsumerWrapper consumer, PrintStream output, boolean skipMessageOnError) {
+ while (messageCount < maxMessages || maxMessages == -1) {
+ ConsumerRecord<byte[], byte[]> msg;
+ try {
+ msg = consumer.receive();
+ } catch (WakeupException we) {
+ LOG.trace("Caught WakeupException because consumer is shutdown, ignore and terminate.");
+ // Consumer will be closed
+ return;
+ } catch (Throwable t) {
+ LOG.error("Error processing message, terminating consumer process: ", t);
+ // Consumer will be closed
+ return;
+ }
+ messageCount += 1;
+ try {
+ formatter.writeTo(new ConsumerRecord<>(msg.topic(), msg.partition(), msg.offset(), msg.timestamp(), msg.timestampType(),
+ 0, 0, msg.key(), msg.value(), msg.headers(), Optional.empty()), output);
+ } catch (Throwable t) {
+ if (skipMessageOnError) {
+ LOG.error("Error processing message, skipping this message: ", t);
+ } else {
+ // Consumer will be closed
+ throw t;
+ }
+ }
+ if (checkErr(output)) {
+ // Consumer will be closed
+ return;
+ }
+ }
+ }
+
+ static void reportRecordCount() {
+ System.err.println("Processed a total of " + messageCount + " messages");
+ }
+
+ static boolean checkErr(PrintStream output) {
+ boolean gotError = output.checkError();
+ if (gotError) {
+ // This means no one is listening to our output stream anymore, time to shut down
+ System.err.println("Unable to write to standard out, closing consumer.");
+ }
+ return gotError;
+ }
+
+ public static class ConsumerWrapper {
+ final Optional<String> topic;
+ final OptionalInt partitionId;
+ final OptionalLong offset;
+ final Optional<String> includedTopics;
+ final Consumer<byte[], byte[]> consumer;
+ final long timeoutMs;
+ final Time time = Time.SYSTEM;
+
+ Iterator<ConsumerRecord<byte[], byte[]>> recordIter = Collections.emptyIterator();
+
+ public ConsumerWrapper(Optional<String> topic,
+ OptionalInt partitionId,
+ OptionalLong offset,
+ Optional<String> includedTopics,
+ Consumer<byte[], byte[]> consumer,
+ long timeoutMs) {
+ this.topic = topic;
+ this.partitionId = partitionId;
+ this.offset = offset;
+ this.includedTopics = includedTopics;
+ this.consumer = consumer;
+ this.timeoutMs = timeoutMs;
+
+ if (topic.isPresent() && partitionId.isPresent() && offset.isPresent() && !includedTopics.isPresent()) {
+ seek(topic.get(), partitionId.getAsInt(), offset.getAsLong());
+ } else if (topic.isPresent() && partitionId.isPresent() && !offset.isPresent() && !includedTopics.isPresent()) {
+ // default to latest if no offset is provided
+ seek(topic.get(), partitionId.getAsInt(), ListOffsetsRequest.LATEST_TIMESTAMP);
+ } else if (topic.isPresent() && !partitionId.isPresent() && !offset.isPresent() && !includedTopics.isPresent()) {
+ consumer.subscribe(Collections.singletonList(topic.get()));
+ } else if (!topic.isPresent() && !partitionId.isPresent() && !offset.isPresent() && includedTopics.isPresent()) {
+ consumer.subscribe(Pattern.compile(includedTopics.get()));
+ } else {
+ throw new IllegalArgumentException("An invalid combination of arguments is provided. " +
Review Comment:
this line feel more fit for `ConsoleConsumerOptions.checkRequiredArgs ` if the combination is invalid we should exit earlier.
##########
tools/src/main/java/org/apache/kafka/tools/consumer/DefaultMessageFormatter.java:
##########
@@ -0,0 +1,210 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.tools.consumer;
+
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.common.MessageFormatter;
+import org.apache.kafka.common.header.Header;
+import org.apache.kafka.common.record.TimestampType;
+import org.apache.kafka.common.serialization.Deserializer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.PrintStream;
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Optional;
+
+class DefaultMessageFormatter implements MessageFormatter {
+
+ private static final Logger LOG = LoggerFactory.getLogger(DefaultMessageFormatter.class);
+
+ private boolean printTimestamp = false;
+ private boolean printKey = false;
+ private boolean printValue = true;
+ private boolean printPartition = false;
+ private boolean printOffset = false;
+ private boolean printHeaders = false;
+ private byte[] keySeparator = utfBytes("\t");
+ private byte[] lineSeparator = utfBytes("\n");
+ private byte[] headersSeparator = utfBytes(",");
+ private byte[] nullLiteral = utfBytes("null");
+
+ private Optional<Deserializer<?>> keyDeserializer;
Review Comment:
Shouldn't we specify the default value to be Optional.empty here
##########
tools/src/main/java/org/apache/kafka/tools/consumer/ConsoleConsumerOptions.java:
##########
@@ -0,0 +1,414 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.tools.consumer;
+
+import joptsimple.OptionException;
+import joptsimple.OptionSpec;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.common.MessageFormatter;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.utils.Utils;
+import org.apache.kafka.server.util.CommandDefaultOptions;
+import org.apache.kafka.server.util.CommandLineUtils;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.OptionalInt;
+import java.util.Properties;
+import java.util.Random;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+public class ConsoleConsumerOptions extends CommandDefaultOptions {
+
+ private static final Random RANDOM = new Random();
+
+ private final OptionSpec<String> topicOpt;
+ private final OptionSpec<String> whitelistOpt;
+ private final OptionSpec<String> includeOpt;
+ private final OptionSpec<Integer> partitionIdOpt;
+ private final OptionSpec<String> offsetOpt;
+ private final OptionSpec<String> messageFormatterOpt;
+ private final OptionSpec<String> messageFormatterArgOpt;
+ private final OptionSpec<String> messageFormatterConfigOpt;
+ private final OptionSpec<?> resetBeginningOpt;
+ private final OptionSpec<Integer> maxMessagesOpt;
+ private final OptionSpec<Integer> timeoutMsOpt;
+ private final OptionSpec<?> skipMessageOnErrorOpt;
+ private final OptionSpec<String> bootstrapServerOpt;
+ private final OptionSpec<String> keyDeserializerOpt;
+ private final OptionSpec<String> valueDeserializerOpt;
+ private final OptionSpec<?> enableSystestEventsLoggingOpt;
+ private final OptionSpec<String> isolationLevelOpt;
+ private final OptionSpec<String> groupIdOpt;
+
+ private final Properties consumerProps;
+ private final long offset;
+ private final MessageFormatter formatter;
+
+ public ConsoleConsumerOptions(String[] args) throws IOException {
+ super(args);
+ topicOpt = parser.accepts("topic", "The topic to consume on.")
+ .withRequiredArg()
+ .describedAs("topic")
+ .ofType(String.class);
+ whitelistOpt = parser.accepts("whitelist",
+ "DEPRECATED, use --include instead; ignored if --include specified. Regular expression specifying list of topics to include for consumption.")
+ .withRequiredArg()
+ .describedAs("Java regex (String)")
+ .ofType(String.class);
+ includeOpt = parser.accepts("include",
+ "Regular expression specifying list of topics to include for consumption.")
+ .withRequiredArg()
+ .describedAs("Java regex (String)")
+ .ofType(String.class);
+ partitionIdOpt = parser.accepts("partition",
+ "The partition to consume from. Consumption starts from the end of the partition unless '--offset' is specified.")
+ .withRequiredArg()
+ .describedAs("partition")
+ .ofType(Integer.class);
+ offsetOpt = parser.accepts("offset", "The offset to consume from (a non-negative number), or 'earliest' which means from beginning, or 'latest' which means from end")
+ .withRequiredArg()
+ .describedAs("consume offset")
+ .ofType(String.class)
+ .defaultsTo("latest");
+ OptionSpec<String> consumerPropertyOpt = parser.accepts("consumer-property", "A mechanism to pass user-defined properties in the form key=value to the consumer.")
+ .withRequiredArg()
+ .describedAs("consumer_prop")
+ .ofType(String.class);
+ OptionSpec<String> consumerConfigOpt = parser.accepts("consumer.config", "Consumer config properties file. Note that " + consumerPropertyOpt + " takes precedence over this config.")
+ .withRequiredArg()
+ .describedAs("config file")
+ .ofType(String.class);
+ messageFormatterOpt = parser.accepts("formatter", "The name of a class to use for formatting kafka messages for display.")
+ .withRequiredArg()
+ .describedAs("class")
+ .ofType(String.class)
+ .defaultsTo(DefaultMessageFormatter.class.getName());
+ messageFormatterArgOpt = parser.accepts("property",
+ "The properties to initialize the message formatter. Default properties include: \n" +
+ " print.timestamp=true|false\n" +
+ " print.key=true|false\n" +
+ " print.offset=true|false\n" +
+ " print.partition=true|false\n" +
+ " print.headers=true|false\n" +
+ " print.value=true|false\n" +
+ " key.separator=<key.separator>\n" +
+ " line.separator=<line.separator>\n" +
+ " headers.separator=<line.separator>\n" +
+ " null.literal=<null.literal>\n" +
+ " key.deserializer=<key.deserializer>\n" +
+ " value.deserializer=<value.deserializer>\n" +
+ " header.deserializer=<header.deserializer>\n" +
+ "\nUsers can also pass in customized properties for their formatter; more specifically, users can pass in properties keyed with 'key.deserializer.', 'value.deserializer.' and 'headers.deserializer.' prefixes to configure their deserializers.")
+ .withRequiredArg()
+ .describedAs("prop")
+ .ofType(String.class);
+ messageFormatterConfigOpt = parser.accepts("formatter-config", "Config properties file to initialize the message formatter. Note that " + messageFormatterArgOpt + " takes precedence over this config.")
+ .withRequiredArg()
+ .describedAs("config file")
+ .ofType(String.class);
+ resetBeginningOpt = parser.accepts("from-beginning", "If the consumer does not already have an established offset to consume from, " +
+ "start with the earliest message present in the log rather than the latest message.");
+ maxMessagesOpt = parser.accepts("max-messages", "The maximum number of messages to consume before exiting. If not set, consumption is continual.")
+ .withRequiredArg()
+ .describedAs("num_messages")
+ .ofType(Integer.class);
+ timeoutMsOpt = parser.accepts("timeout-ms", "If specified, exit if no message is available for consumption for the specified interval.")
+ .withRequiredArg()
+ .describedAs("timeout_ms")
+ .ofType(Integer.class);
+ skipMessageOnErrorOpt = parser.accepts("skip-message-on-error", "If there is an error when processing a message, " +
+ "skip it instead of halt.");
+ bootstrapServerOpt = parser.accepts("bootstrap-server", "REQUIRED: The server(s) to connect to.")
+ .withRequiredArg()
+ .describedAs("server to connect to")
+ .ofType(String.class);
+ keyDeserializerOpt = parser.accepts("key-deserializer")
+ .withRequiredArg()
+ .describedAs("deserializer for key")
+ .ofType(String.class);
+ valueDeserializerOpt = parser.accepts("value-deserializer")
+ .withRequiredArg()
+ .describedAs("deserializer for values")
+ .ofType(String.class);
+ enableSystestEventsLoggingOpt = parser.accepts("enable-systest-events",
+ "Log lifecycle events of the consumer in addition to logging consumed messages. (This is specific for system tests.)");
+ isolationLevelOpt = parser.accepts("isolation-level",
+ "Set to read_committed in order to filter out transactional messages which are not committed. Set to read_uncommitted " +
+ "to read all messages.")
+ .withRequiredArg()
+ .ofType(String.class)
+ .defaultsTo("read_uncommitted");
+ groupIdOpt = parser.accepts("group", "The consumer group id of the consumer.")
+ .withRequiredArg()
+ .describedAs("consumer group id")
+ .ofType(String.class);
+
+ try {
+ options = parser.parse(args);
+ } catch (OptionException oe) {
+ CommandLineUtils.printUsageAndExit(parser, oe.getMessage());
+ }
+
+ CommandLineUtils.maybePrintHelpOrVersion(this, "This tool helps to read data from Kafka topics and outputs it to standard output.");
+
+ checkRequiredArgs();
+
+ Properties consumerPropsFromFile = options.has(consumerConfigOpt)
+ ? Utils.loadProps(options.valueOf(consumerConfigOpt))
+ : new Properties();
+ Properties extraConsumerProps = CommandLineUtils.parseKeyValueArgs(options.valuesOf(consumerPropertyOpt));
+
+ Set<String> groupIdsProvided = checkConsumerGroup(consumerPropsFromFile, extraConsumerProps);
+ consumerProps = buildConsumerProps(consumerPropsFromFile, extraConsumerProps, groupIdsProvided);
+ offset = parseOffset();
+ formatter = buildFormatter();
+ }
+
+ private void checkRequiredArgs() {
+ List<String> topicOrFilterArgs = new ArrayList<>(Arrays.asList(topicArg(), includedTopicsArg()));
+ topicOrFilterArgs.removeIf(Objects::isNull);
+ // user need to specify value for either --topic or one of the include filters options (--include or --whitelist)
+ if (topicOrFilterArgs.size() != 1) {
+ CommandLineUtils.printUsageAndExit(parser, "Exactly one of --include/--topic is required. " +
+ (options.has(whitelistOpt) ? "--whitelist is DEPRECATED use --include instead; ignored if --include specified." : ""));
+ }
+
+ if (partitionArg().isPresent()) {
+ if (!options.has(topicOpt)) {
+ CommandLineUtils.printUsageAndExit(parser, "The topic is required when partition is specified.");
+ }
+ if (fromBeginning() && options.has(offsetOpt)) {
+ CommandLineUtils.printUsageAndExit(parser, "Options from-beginning and offset cannot be specified together.");
+ }
+ } else if (options.has(offsetOpt)) {
+ CommandLineUtils.printUsageAndExit(parser, "The partition is required when offset is specified.");
+ }
+
+ CommandLineUtils.checkRequiredArgs(parser, options, bootstrapServerOpt);
+ }
+
+ private Set<String> checkConsumerGroup(Properties consumerPropsFromFile, Properties extraConsumerProps) {
+ // if the group id is provided in more than place (through different means) all values must be the same
+ Set<String> groupIdsProvided = new HashSet<>();
+ if (options.has(groupIdOpt)) {
+ groupIdsProvided.add(options.valueOf(groupIdOpt));
+ }
+
+ if (consumerPropsFromFile.containsKey(ConsumerConfig.GROUP_ID_CONFIG)) {
+ groupIdsProvided.add((String) consumerPropsFromFile.get(ConsumerConfig.GROUP_ID_CONFIG));
+ }
+
+ if (extraConsumerProps.containsKey(ConsumerConfig.GROUP_ID_CONFIG)) {
+ groupIdsProvided.add(extraConsumerProps.getProperty(ConsumerConfig.GROUP_ID_CONFIG));
+ }
+ if (groupIdsProvided.size() > 1) {
+ CommandLineUtils.printUsageAndExit(parser, "The group ids provided in different places (directly using '--group', "
+ + "via '--consumer-property', or via '--consumer.config') do not match. "
+ + "Detected group ids: "
+ + groupIdsProvided.stream().map(group -> "'" + group + "'").collect(Collectors.joining(", ")));
+ }
+ if (!groupIdsProvided.isEmpty() && partitionArg().isPresent()) {
+ CommandLineUtils.printUsageAndExit(parser, "Options group and partition cannot be specified together.");
+ }
+ return groupIdsProvided;
+ }
+
+ private Properties buildConsumerProps(Properties consumerPropsFromFile, Properties extraConsumerProps, Set<String> groupIdsProvided) {
+ Properties consumerProps = new Properties(consumerPropsFromFile);
+ consumerProps.putAll(extraConsumerProps);
+ setAutoOffsetResetValue(consumerProps);
+ consumerProps.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServer());
+ if (consumerProps.getProperty(ConsumerConfig.CLIENT_ID_CONFIG) == null) {
+ consumerProps.put(ConsumerConfig.CLIENT_ID_CONFIG, "console-consumer");
+ }
+ CommandLineUtils.maybeMergeOptions(consumerProps, ConsumerConfig.ISOLATION_LEVEL_CONFIG, options, isolationLevelOpt);
+
+ if (groupIdsProvided.isEmpty()) {
+ consumerProps.put(ConsumerConfig.GROUP_ID_CONFIG, "console-consumer-" + RANDOM.nextInt(100000));
+ // By default, avoid unnecessary expansion of the coordinator cache since
+ // the auto-generated group and its offsets is not intended to be used again
+ if (!consumerProps.containsKey(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG)) {
+ consumerProps.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
+ }
+ } else {
+ consumerProps.put(ConsumerConfig.GROUP_ID_CONFIG, groupIdsProvided.iterator().next());
+ }
+ return consumerProps;
+ }
+
+ /**
+ * Used to retrieve the correct value for the consumer parameter 'auto.offset.reset'.
+ * Order of priority is:
+ * 1. Explicitly set parameter via --consumer.property command line parameter
+ * 2. Explicit --from-beginning given -> 'earliest'
+ * 3. Default value of 'latest'
+ * In case both --from-beginning and an explicit value are specified an error is thrown if these
+ * are conflicting.
+ */
+ private void setAutoOffsetResetValue(Properties props) {
+ String earliestConfigValue = "earliest";
+ String latestConfigValue = "latest";
+
+ if (props.containsKey(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG)) {
+ // auto.offset.reset parameter was specified on the command line
+ String autoResetOption = props.getProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG);
+ if (fromBeginning() && !earliestConfigValue.equals(autoResetOption)) {
+ // conflicting options - latest und earliest, throw an error
+ System.err.println("Can't simultaneously specify --from-beginning and 'auto.offset.reset=" + autoResetOption + "', " +
+ "please remove one option");
+ Exit.exit(1);
+ }
+ // nothing to do, checking for valid parameter values happens later and the specified
+ // value was already copied during .putall operation
+ } else {
+ // no explicit value for auto.offset.reset was specified
+ // if --from-beginning was specified use earliest, otherwise default to latest
+ String autoResetOption = fromBeginning() ? earliestConfigValue : latestConfigValue;
+ props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoResetOption);
+ }
+ }
+
+ private long parseOffset() {
+ if (options.has(offsetOpt)) {
+ switch (options.valueOf(offsetOpt).toLowerCase(Locale.ROOT)) {
+ case "earliest":
+ return ListOffsetsRequest.EARLIEST_TIMESTAMP;
+ case "latest":
+ return ListOffsetsRequest.LATEST_TIMESTAMP;
+ default:
+ String offsetString = options.valueOf(offsetOpt);
+ try {
+ long offset = Long.parseLong(offsetString);
+ if (offset < 0) {
+ invalidOffset(offsetString);
+ }
+ return offset;
+ } catch (NumberFormatException nfe) {
+ invalidOffset(offsetString);
+ }
+ }
+ } else if (fromBeginning()) {
+ return ListOffsetsRequest.EARLIEST_TIMESTAMP;
+ }
+ return ListOffsetsRequest.LATEST_TIMESTAMP;
+ }
+
+ private void invalidOffset(String offset) {
+ CommandLineUtils.printUsageAndExit(parser, "The provided offset value '" + offset + "' is incorrect. Valid values are " +
+ "'earliest', 'latest', or a non-negative long.");
+ }
+
+ private MessageFormatter buildFormatter() {
+ MessageFormatter formatter = null;
Review Comment:
is `=null` necessary?
##########
tools/src/main/java/org/apache/kafka/tools/consumer/DefaultMessageFormatter.java:
##########
@@ -0,0 +1,210 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.tools.consumer;
+
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.common.MessageFormatter;
+import org.apache.kafka.common.header.Header;
+import org.apache.kafka.common.record.TimestampType;
+import org.apache.kafka.common.serialization.Deserializer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.PrintStream;
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Optional;
+
+class DefaultMessageFormatter implements MessageFormatter {
+
+ private static final Logger LOG = LoggerFactory.getLogger(DefaultMessageFormatter.class);
+
+ private boolean printTimestamp = false;
+ private boolean printKey = false;
+ private boolean printValue = true;
+ private boolean printPartition = false;
+ private boolean printOffset = false;
+ private boolean printHeaders = false;
+ private byte[] keySeparator = utfBytes("\t");
+ private byte[] lineSeparator = utfBytes("\n");
+ private byte[] headersSeparator = utfBytes(",");
+ private byte[] nullLiteral = utfBytes("null");
+
+ private Optional<Deserializer<?>> keyDeserializer;
+ private Optional<Deserializer<?>> valueDeserializer;
Review Comment:
same
##########
tools/src/main/java/org/apache/kafka/tools/consumer/ConsoleConsumer.java:
##########
@@ -0,0 +1,233 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.tools.consumer;
+
+import java.io.PrintStream;
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.util.OptionalLong;
+import java.util.concurrent.CountDownLatch;
+import java.util.regex.Pattern;
+import java.util.Collections;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.common.MessageFormatter;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.AuthenticationException;
+import org.apache.kafka.common.errors.TimeoutException;
+import org.apache.kafka.common.errors.WakeupException;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.serialization.ByteArrayDeserializer;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Consumer that dumps messages to standard out.
+ */
+class ConsoleConsumer {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ConsoleConsumer.class);
+ private static final CountDownLatch SHUTDOWN_LATCH = new CountDownLatch(1);
+
+ static int messageCount = 0;
+
+ public static void main(String[] args) throws Exception {
+ ConsoleConsumerOptions opts = new ConsoleConsumerOptions(args);
+ try {
+ run(opts);
+ } catch (AuthenticationException ae) {
+ LOG.error("Authentication failed: terminating consumer process", ae);
+ Exit.exit(1);
+ } catch (Throwable t) {
+ LOG.error("Unknown error when running consumer: ", t);
+ Exit.exit(1);
+ }
+ }
+
+ static void run(ConsoleConsumerOptions conf) {
+ long timeoutMs = conf.timeoutMs() >= 0 ? conf.timeoutMs() : Long.MAX_VALUE;
+ Consumer<byte[], byte[]> consumer = new KafkaConsumer<>(conf.consumerProps(), new ByteArrayDeserializer(), new ByteArrayDeserializer());
+ ConsumerWrapper consumerWrapper = conf.partitionArg().isPresent()
+ ? new ConsumerWrapper(Optional.of(conf.topicArg()), conf.partitionArg(), OptionalLong.of(conf.offsetArg()), Optional.empty(), consumer, timeoutMs)
+ : new ConsumerWrapper(Optional.of(conf.topicArg()), OptionalInt.empty(), OptionalLong.empty(), Optional.ofNullable(conf.includedTopicsArg()), consumer, timeoutMs);
+
+ addShutdownHook(consumerWrapper, conf);
+
+ try {
+ process(conf.maxMessages(), conf.formatter(), consumerWrapper, System.out, conf.skipMessageOnError());
+ } finally {
+ consumerWrapper.cleanup();
+ conf.formatter().close();
+ reportRecordCount();
+
+ SHUTDOWN_LATCH.countDown();
+ }
+ }
+
+ static void addShutdownHook(ConsumerWrapper consumer, ConsoleConsumerOptions conf) {
+ Exit.addShutdownHook("consumer-shutdown-hook", () -> {
+ try {
+ consumer.wakeup();
+ SHUTDOWN_LATCH.await();
+ } catch (Throwable t) {
+ LOG.error("Exception while running shutdown hook " + t.getMessage());
+ }
+ if (conf.enableSystestEventsLogging()) {
+ System.out.println("shutdown_complete");
+ }
+ });
+ }
+
+ static void process(int maxMessages, MessageFormatter formatter, ConsumerWrapper consumer, PrintStream output, boolean skipMessageOnError) {
+ while (messageCount < maxMessages || maxMessages == -1) {
+ ConsumerRecord<byte[], byte[]> msg;
+ try {
+ msg = consumer.receive();
+ } catch (WakeupException we) {
+ LOG.trace("Caught WakeupException because consumer is shutdown, ignore and terminate.");
+ // Consumer will be closed
+ return;
+ } catch (Throwable t) {
+ LOG.error("Error processing message, terminating consumer process: ", t);
+ // Consumer will be closed
+ return;
+ }
+ messageCount += 1;
+ try {
+ formatter.writeTo(new ConsumerRecord<>(msg.topic(), msg.partition(), msg.offset(), msg.timestamp(), msg.timestampType(),
+ 0, 0, msg.key(), msg.value(), msg.headers(), Optional.empty()), output);
+ } catch (Throwable t) {
+ if (skipMessageOnError) {
+ LOG.error("Error processing message, skipping this message: ", t);
+ } else {
+ // Consumer will be closed
+ throw t;
+ }
+ }
+ if (checkErr(output)) {
+ // Consumer will be closed
+ return;
+ }
+ }
+ }
+
+ static void reportRecordCount() {
+ System.err.println("Processed a total of " + messageCount + " messages");
+ }
+
+ static boolean checkErr(PrintStream output) {
+ boolean gotError = output.checkError();
+ if (gotError) {
+ // This means no one is listening to our output stream anymore, time to shut down
+ System.err.println("Unable to write to standard out, closing consumer.");
+ }
+ return gotError;
+ }
+
+ public static class ConsumerWrapper {
+ final Optional<String> topic;
+ final OptionalInt partitionId;
+ final OptionalLong offset;
+ final Optional<String> includedTopics;
+ final Consumer<byte[], byte[]> consumer;
+ final long timeoutMs;
+ final Time time = Time.SYSTEM;
+
+ Iterator<ConsumerRecord<byte[], byte[]>> recordIter = Collections.emptyIterator();
+
+ public ConsumerWrapper(Optional<String> topic,
+ OptionalInt partitionId,
+ OptionalLong offset,
+ Optional<String> includedTopics,
+ Consumer<byte[], byte[]> consumer,
+ long timeoutMs) {
+ this.topic = topic;
+ this.partitionId = partitionId;
+ this.offset = offset;
+ this.includedTopics = includedTopics;
+ this.consumer = consumer;
+ this.timeoutMs = timeoutMs;
+
+ if (topic.isPresent() && partitionId.isPresent() && offset.isPresent() && !includedTopics.isPresent()) {
+ seek(topic.get(), partitionId.getAsInt(), offset.getAsLong());
Review Comment:
If we opt in for my suggestion before we can also refactor `seek` to decide what to do if offset is provided or not instead of the first 2 ifs we have here.
##########
tools/src/main/java/org/apache/kafka/tools/consumer/ConsoleConsumer.java:
##########
@@ -0,0 +1,233 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.tools.consumer;
+
+import java.io.PrintStream;
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.util.OptionalLong;
+import java.util.concurrent.CountDownLatch;
+import java.util.regex.Pattern;
+import java.util.Collections;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.common.MessageFormatter;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.AuthenticationException;
+import org.apache.kafka.common.errors.TimeoutException;
+import org.apache.kafka.common.errors.WakeupException;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.serialization.ByteArrayDeserializer;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Consumer that dumps messages to standard out.
+ */
+class ConsoleConsumer {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ConsoleConsumer.class);
+ private static final CountDownLatch SHUTDOWN_LATCH = new CountDownLatch(1);
+
+ static int messageCount = 0;
+
+ public static void main(String[] args) throws Exception {
+ ConsoleConsumerOptions opts = new ConsoleConsumerOptions(args);
+ try {
+ run(opts);
+ } catch (AuthenticationException ae) {
+ LOG.error("Authentication failed: terminating consumer process", ae);
+ Exit.exit(1);
+ } catch (Throwable t) {
+ LOG.error("Unknown error when running consumer: ", t);
+ Exit.exit(1);
+ }
+ }
+
+ static void run(ConsoleConsumerOptions conf) {
+ long timeoutMs = conf.timeoutMs() >= 0 ? conf.timeoutMs() : Long.MAX_VALUE;
+ Consumer<byte[], byte[]> consumer = new KafkaConsumer<>(conf.consumerProps(), new ByteArrayDeserializer(), new ByteArrayDeserializer());
+ ConsumerWrapper consumerWrapper = conf.partitionArg().isPresent()
+ ? new ConsumerWrapper(Optional.of(conf.topicArg()), conf.partitionArg(), OptionalLong.of(conf.offsetArg()), Optional.empty(), consumer, timeoutMs)
+ : new ConsumerWrapper(Optional.of(conf.topicArg()), OptionalInt.empty(), OptionalLong.empty(), Optional.ofNullable(conf.includedTopicsArg()), consumer, timeoutMs);
+
+ addShutdownHook(consumerWrapper, conf);
+
+ try {
+ process(conf.maxMessages(), conf.formatter(), consumerWrapper, System.out, conf.skipMessageOnError());
+ } finally {
+ consumerWrapper.cleanup();
+ conf.formatter().close();
+ reportRecordCount();
+
+ SHUTDOWN_LATCH.countDown();
+ }
+ }
+
+ static void addShutdownHook(ConsumerWrapper consumer, ConsoleConsumerOptions conf) {
+ Exit.addShutdownHook("consumer-shutdown-hook", () -> {
+ try {
+ consumer.wakeup();
+ SHUTDOWN_LATCH.await();
+ } catch (Throwable t) {
+ LOG.error("Exception while running shutdown hook " + t.getMessage());
+ }
+ if (conf.enableSystestEventsLogging()) {
+ System.out.println("shutdown_complete");
+ }
+ });
+ }
+
+ static void process(int maxMessages, MessageFormatter formatter, ConsumerWrapper consumer, PrintStream output, boolean skipMessageOnError) {
+ while (messageCount < maxMessages || maxMessages == -1) {
+ ConsumerRecord<byte[], byte[]> msg;
+ try {
+ msg = consumer.receive();
+ } catch (WakeupException we) {
+ LOG.trace("Caught WakeupException because consumer is shutdown, ignore and terminate.");
+ // Consumer will be closed
+ return;
+ } catch (Throwable t) {
+ LOG.error("Error processing message, terminating consumer process: ", t);
+ // Consumer will be closed
+ return;
+ }
+ messageCount += 1;
+ try {
+ formatter.writeTo(new ConsumerRecord<>(msg.topic(), msg.partition(), msg.offset(), msg.timestamp(), msg.timestampType(),
+ 0, 0, msg.key(), msg.value(), msg.headers(), Optional.empty()), output);
+ } catch (Throwable t) {
+ if (skipMessageOnError) {
+ LOG.error("Error processing message, skipping this message: ", t);
+ } else {
+ // Consumer will be closed
+ throw t;
+ }
+ }
+ if (checkErr(output)) {
+ // Consumer will be closed
+ return;
+ }
+ }
+ }
+
+ static void reportRecordCount() {
+ System.err.println("Processed a total of " + messageCount + " messages");
+ }
+
+ static boolean checkErr(PrintStream output) {
+ boolean gotError = output.checkError();
+ if (gotError) {
+ // This means no one is listening to our output stream anymore, time to shut down
+ System.err.println("Unable to write to standard out, closing consumer.");
+ }
+ return gotError;
+ }
+
+ public static class ConsumerWrapper {
+ final Optional<String> topic;
+ final OptionalInt partitionId;
+ final OptionalLong offset;
+ final Optional<String> includedTopics;
+ final Consumer<byte[], byte[]> consumer;
+ final long timeoutMs;
+ final Time time = Time.SYSTEM;
+
+ Iterator<ConsumerRecord<byte[], byte[]>> recordIter = Collections.emptyIterator();
+
+ public ConsumerWrapper(Optional<String> topic,
+ OptionalInt partitionId,
+ OptionalLong offset,
+ Optional<String> includedTopics,
+ Consumer<byte[], byte[]> consumer,
+ long timeoutMs) {
+ this.topic = topic;
+ this.partitionId = partitionId;
+ this.offset = offset;
+ this.includedTopics = includedTopics;
+ this.consumer = consumer;
+ this.timeoutMs = timeoutMs;
+
+ if (topic.isPresent() && partitionId.isPresent() && offset.isPresent() && !includedTopics.isPresent()) {
+ seek(topic.get(), partitionId.getAsInt(), offset.getAsLong());
+ } else if (topic.isPresent() && partitionId.isPresent() && !offset.isPresent() && !includedTopics.isPresent()) {
+ // default to latest if no offset is provided
+ seek(topic.get(), partitionId.getAsInt(), ListOffsetsRequest.LATEST_TIMESTAMP);
Review Comment:
can't we use `ConsoleConsumerOptions .parseOffset` to either grab the given offset or the default instead of these 2 ifs?
##########
tools/src/main/java/org/apache/kafka/tools/consumer/DefaultMessageFormatter.java:
##########
@@ -0,0 +1,210 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.tools.consumer;
+
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.common.MessageFormatter;
+import org.apache.kafka.common.header.Header;
+import org.apache.kafka.common.record.TimestampType;
+import org.apache.kafka.common.serialization.Deserializer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.PrintStream;
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Optional;
+
+class DefaultMessageFormatter implements MessageFormatter {
+
+ private static final Logger LOG = LoggerFactory.getLogger(DefaultMessageFormatter.class);
+
+ private boolean printTimestamp = false;
+ private boolean printKey = false;
+ private boolean printValue = true;
+ private boolean printPartition = false;
+ private boolean printOffset = false;
+ private boolean printHeaders = false;
+ private byte[] keySeparator = utfBytes("\t");
+ private byte[] lineSeparator = utfBytes("\n");
+ private byte[] headersSeparator = utfBytes(",");
+ private byte[] nullLiteral = utfBytes("null");
+
+ private Optional<Deserializer<?>> keyDeserializer;
+ private Optional<Deserializer<?>> valueDeserializer;
+ private Optional<Deserializer<?>> headersDeserializer;
Review Comment:
same as above
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-14576: Move ConsoleConsumer to tools [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on PR #15274:
URL: https://github.com/apache/kafka/pull/15274#issuecomment-1941396381
Thanks @OmniaGM !
I created https://issues.apache.org/jira/browse/KAFKA-16246 to track the follow up refactoring work.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-14576: Move ConsoleConsumer to tools [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on code in PR #15274:
URL: https://github.com/apache/kafka/pull/15274#discussion_r1487675184
##########
tools/src/main/java/org/apache/kafka/tools/consumer/ConsoleConsumerOptions.java:
##########
@@ -238,7 +237,8 @@ private Set<String> checkConsumerGroup(Properties consumerPropsFromFile, Propert
}
private Properties buildConsumerProps(Properties consumerPropsFromFile, Properties extraConsumerProps, Set<String> groupIdsProvided) {
- Properties consumerProps = new Properties(consumerPropsFromFile);
+ Properties consumerProps = new Properties();
+ consumerProps.putAll(consumerPropsFromFile);
Review Comment:
Yep! Default values are only retrieved when using `getProperty()` and not when using `get()`. This is why the unit test was passing.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-14576: Move ConsoleConsumer to tools [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on PR #15274:
URL: https://github.com/apache/kafka/pull/15274#issuecomment-1942090513
None of the test failures seem related, merging to trunk
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-14576: Move ConsoleConsumer to tools [kafka]
Posted by "jlprat (via GitHub)" <gi...@apache.org>.
jlprat commented on code in PR #15274:
URL: https://github.com/apache/kafka/pull/15274#discussion_r1487661551
##########
tools/src/main/java/org/apache/kafka/tools/consumer/ConsoleConsumerOptions.java:
##########
@@ -238,7 +237,8 @@ private Set<String> checkConsumerGroup(Properties consumerPropsFromFile, Propert
}
private Properties buildConsumerProps(Properties consumerPropsFromFile, Properties extraConsumerProps, Set<String> groupIdsProvided) {
- Properties consumerProps = new Properties(consumerPropsFromFile);
+ Properties consumerProps = new Properties();
+ consumerProps.putAll(consumerPropsFromFile);
Review Comment:
Strange that this change is not doing the exact same thing. But reading the API, constructor with `Property` says that it creates an empty list with the passed properties as defaults. Tricky API design from Java's part...
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-14576: Move ConsoleConsumer to tools [kafka]
Posted by "jlprat (via GitHub)" <gi...@apache.org>.
jlprat commented on code in PR #15274:
URL: https://github.com/apache/kafka/pull/15274#discussion_r1481430316
##########
tests/kafkatest/services/console_consumer.py:
##########
@@ -21,7 +21,7 @@
from kafkatest.directory_layout.kafka_path import KafkaPathResolverMixin
from kafkatest.services.monitor.jmx import JmxMixin, JmxTool
-from kafkatest.version import DEV_BRANCH, LATEST_0_8_2, LATEST_0_9, LATEST_0_10_0, V_0_10_0_0, V_0_11_0_0, V_2_0_0
+from kafkatest.version import DEV_BRANCH, LATEST_0_8_2, LATEST_0_9, LATEST_0_10_0, V_0_10_0_0, V_0_11_0_0, V_2_0_0, LATEST_3_7
Review Comment:
Do I understand it right that you want to merge this only after 3.7.0 is released?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-14576: Move ConsoleConsumer to tools [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on code in PR #15274:
URL: https://github.com/apache/kafka/pull/15274#discussion_r1478333292
##########
tools/src/test/java/org/apache/kafka/tools/consumer/ConsoleConsumerOptionsTest.java:
##########
@@ -0,0 +1,622 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.tools.consumer;
+
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.test.MockDeserializer;
+import org.apache.kafka.tools.ToolsTestUtils;
+import org.junit.jupiter.api.Test;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class ConsoleConsumerOptionsTest {
+
+ @Test
+ public void shouldParseValidConsumerValidConfig() throws IOException {
+ String[] args = new String[]{
+ "--bootstrap-server", "localhost:9092",
+ "--topic", "test",
+ "--from-beginning"
+ };
+
+ ConsoleConsumerOptions config = new ConsoleConsumerOptions(args);
+
+ assertEquals("localhost:9092", config.bootstrapServer());
+ assertEquals("test", config.topicArg());
+ assertTrue(config.fromBeginning());
+ assertFalse(config.enableSystestEventsLogging());
+ assertFalse(config.skipMessageOnError());
+ assertEquals(-1, config.maxMessages());
+ assertEquals(-1, config.timeoutMs());
Review Comment:
Yes, I added a few extra tests to improve the coverage.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-14576: Move ConsoleConsumer to tools [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on code in PR #15274:
URL: https://github.com/apache/kafka/pull/15274#discussion_r1478417021
##########
tests/kafkatest/services/console_consumer.py:
##########
@@ -21,7 +21,7 @@
from kafkatest.directory_layout.kafka_path import KafkaPathResolverMixin
from kafkatest.services.monitor.jmx import JmxMixin, JmxTool
-from kafkatest.version import DEV_BRANCH, LATEST_0_8_2, LATEST_0_9, LATEST_0_10_0, V_0_10_0_0, V_0_11_0_0, V_2_0_0
+from kafkatest.version import DEV_BRANCH, LATEST_0_8_2, LATEST_0_9, LATEST_0_10_0, V_0_10_0_0, V_0_11_0_0, V_2_0_0, LATEST_3_7
Review Comment:
`LATEST_3_7` does not exist yet, we need to wait for 3.7.0 to be out before adding it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-14576: Move ConsoleConsumer to tools [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison merged PR #15274:
URL: https://github.com/apache/kafka/pull/15274
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-14576: Move ConsoleConsumer to tools [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on code in PR #15274:
URL: https://github.com/apache/kafka/pull/15274#discussion_r1478369049
##########
tools/src/main/java/org/apache/kafka/tools/consumer/LoggingMessageFormatter.java:
##########
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.tools.consumer;
+
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.common.MessageFormatter;
+import org.apache.kafka.common.record.TimestampType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.PrintStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Map;
+
+class LoggingMessageFormatter implements MessageFormatter {
+
+ private static final Logger LOG = LoggerFactory.getLogger(LoggingMessageFormatter.class);
+ private final DefaultMessageFormatter defaultWriter = new DefaultMessageFormatter();
+
+ @Override
+ public void configure(Map<String, ?> configs) {
+ defaultWriter.configure(configs);
+ }
+
+ @Override
+ public void writeTo(ConsumerRecord<byte[], byte[]> consumerRecord, PrintStream output) {
+ defaultWriter.writeTo(consumerRecord, output);
+ String timestamp = consumerRecord.timestampType() != TimestampType.NO_TIMESTAMP_TYPE
+ ? consumerRecord.timestampType() + ":" + consumerRecord.timestamp() + " "
+ : "";
+ String key = consumerRecord.key() == null ? "null" : new String(consumerRecord.key(), StandardCharsets.UTF_8);
+ String value = consumerRecord.value() == null ? "null" : new String(consumerRecord.value(), StandardCharsets.UTF_8);
Review Comment:
Good catch!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-14576: Move ConsoleConsumer to tools [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on code in PR #15274:
URL: https://github.com/apache/kafka/pull/15274#discussion_r1484652868
##########
tests/kafkatest/services/console_consumer.py:
##########
@@ -21,7 +21,7 @@
from kafkatest.directory_layout.kafka_path import KafkaPathResolverMixin
from kafkatest.services.monitor.jmx import JmxMixin, JmxTool
-from kafkatest.version import DEV_BRANCH, LATEST_0_8_2, LATEST_0_9, LATEST_0_10_0, V_0_10_0_0, V_0_11_0_0, V_2_0_0
+from kafkatest.version import DEV_BRANCH, LATEST_0_8_2, LATEST_0_9, LATEST_0_10_0, V_0_10_0_0, V_0_11_0_0, V_2_0_0, LATEST_3_7
Review Comment:
That seems to work. However while running the system tests I found an issue loading configs via `--consumer.config`. I pushed https://github.com/apache/kafka/pull/15274/commits/c6355fe630a7eae8ea55c8806c66b04cf389bfa2 to fix it.
I've kicked another run on our system tests CI, hopefully it will be clean now.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-14576: Move ConsoleConsumer to tools [kafka]
Posted by "mimaison (via GitHub)" <gi...@apache.org>.
mimaison commented on code in PR #15274:
URL: https://github.com/apache/kafka/pull/15274#discussion_r1474734641
##########
tools/src/main/java/org/apache/kafka/tools/consumer/ConsoleConsumer.java:
##########
@@ -0,0 +1,233 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.tools.consumer;
+
+import java.io.PrintStream;
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.util.OptionalLong;
+import java.util.concurrent.CountDownLatch;
+import java.util.regex.Pattern;
+import java.util.Collections;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.common.MessageFormatter;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.AuthenticationException;
+import org.apache.kafka.common.errors.TimeoutException;
+import org.apache.kafka.common.errors.WakeupException;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.serialization.ByteArrayDeserializer;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Consumer that dumps messages to standard out.
+ */
+class ConsoleConsumer {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ConsoleConsumer.class);
+ private static final CountDownLatch SHUTDOWN_LATCH = new CountDownLatch(1);
+
+ static int messageCount = 0;
+
+ public static void main(String[] args) throws Exception {
+ ConsoleConsumerOptions opts = new ConsoleConsumerOptions(args);
+ try {
+ run(opts);
+ } catch (AuthenticationException ae) {
+ LOG.error("Authentication failed: terminating consumer process", ae);
+ Exit.exit(1);
+ } catch (Throwable t) {
+ LOG.error("Unknown error when running consumer: ", t);
+ Exit.exit(1);
+ }
+ }
+
+ static void run(ConsoleConsumerOptions conf) {
+ long timeoutMs = conf.timeoutMs() >= 0 ? conf.timeoutMs() : Long.MAX_VALUE;
+ Consumer<byte[], byte[]> consumer = new KafkaConsumer<>(conf.consumerProps(), new ByteArrayDeserializer(), new ByteArrayDeserializer());
+ ConsumerWrapper consumerWrapper = conf.partitionArg().isPresent()
+ ? new ConsumerWrapper(Optional.of(conf.topicArg()), conf.partitionArg(), OptionalLong.of(conf.offsetArg()), Optional.empty(), consumer, timeoutMs)
+ : new ConsumerWrapper(Optional.of(conf.topicArg()), OptionalInt.empty(), OptionalLong.empty(), Optional.ofNullable(conf.includedTopicsArg()), consumer, timeoutMs);
+
+ addShutdownHook(consumerWrapper, conf);
+
+ try {
+ process(conf.maxMessages(), conf.formatter(), consumerWrapper, System.out, conf.skipMessageOnError());
+ } finally {
+ consumerWrapper.cleanup();
+ conf.formatter().close();
+ reportRecordCount();
+
+ SHUTDOWN_LATCH.countDown();
+ }
+ }
+
+ static void addShutdownHook(ConsumerWrapper consumer, ConsoleConsumerOptions conf) {
+ Exit.addShutdownHook("consumer-shutdown-hook", () -> {
+ try {
+ consumer.wakeup();
+ SHUTDOWN_LATCH.await();
+ } catch (Throwable t) {
+ LOG.error("Exception while running shutdown hook " + t.getMessage());
+ }
+ if (conf.enableSystestEventsLogging()) {
+ System.out.println("shutdown_complete");
+ }
+ });
+ }
+
+ static void process(int maxMessages, MessageFormatter formatter, ConsumerWrapper consumer, PrintStream output, boolean skipMessageOnError) {
+ while (messageCount < maxMessages || maxMessages == -1) {
+ ConsumerRecord<byte[], byte[]> msg;
+ try {
+ msg = consumer.receive();
+ } catch (WakeupException we) {
+ LOG.trace("Caught WakeupException because consumer is shutdown, ignore and terminate.");
+ // Consumer will be closed
+ return;
+ } catch (Throwable t) {
+ LOG.error("Error processing message, terminating consumer process: ", t);
+ // Consumer will be closed
+ return;
+ }
+ messageCount += 1;
+ try {
+ formatter.writeTo(new ConsumerRecord<>(msg.topic(), msg.partition(), msg.offset(), msg.timestamp(), msg.timestampType(),
+ 0, 0, msg.key(), msg.value(), msg.headers(), Optional.empty()), output);
+ } catch (Throwable t) {
+ if (skipMessageOnError) {
+ LOG.error("Error processing message, skipping this message: ", t);
+ } else {
+ // Consumer will be closed
+ throw t;
+ }
+ }
+ if (checkErr(output)) {
+ // Consumer will be closed
+ return;
+ }
+ }
+ }
+
+ static void reportRecordCount() {
+ System.err.println("Processed a total of " + messageCount + " messages");
+ }
+
+ static boolean checkErr(PrintStream output) {
+ boolean gotError = output.checkError();
+ if (gotError) {
+ // This means no one is listening to our output stream anymore, time to shut down
+ System.err.println("Unable to write to standard out, closing consumer.");
+ }
+ return gotError;
+ }
+
+ public static class ConsumerWrapper {
+ final Optional<String> topic;
+ final OptionalInt partitionId;
+ final OptionalLong offset;
+ final Optional<String> includedTopics;
+ final Consumer<byte[], byte[]> consumer;
+ final long timeoutMs;
+ final Time time = Time.SYSTEM;
+
+ Iterator<ConsumerRecord<byte[], byte[]>> recordIter = Collections.emptyIterator();
+
+ public ConsumerWrapper(Optional<String> topic,
+ OptionalInt partitionId,
+ OptionalLong offset,
+ Optional<String> includedTopics,
+ Consumer<byte[], byte[]> consumer,
+ long timeoutMs) {
+ this.topic = topic;
+ this.partitionId = partitionId;
+ this.offset = offset;
+ this.includedTopics = includedTopics;
+ this.consumer = consumer;
+ this.timeoutMs = timeoutMs;
+
+ if (topic.isPresent() && partitionId.isPresent() && offset.isPresent() && !includedTopics.isPresent()) {
+ seek(topic.get(), partitionId.getAsInt(), offset.getAsLong());
+ } else if (topic.isPresent() && partitionId.isPresent() && !offset.isPresent() && !includedTopics.isPresent()) {
+ // default to latest if no offset is provided
+ seek(topic.get(), partitionId.getAsInt(), ListOffsetsRequest.LATEST_TIMESTAMP);
+ } else if (topic.isPresent() && !partitionId.isPresent() && !offset.isPresent() && !includedTopics.isPresent()) {
+ consumer.subscribe(Collections.singletonList(topic.get()));
+ } else if (!topic.isPresent() && !partitionId.isPresent() && !offset.isPresent() && includedTopics.isPresent()) {
+ consumer.subscribe(Pattern.compile(includedTopics.get()));
+ } else {
+ throw new IllegalArgumentException("An invalid combination of arguments is provided. " +
Review Comment:
I kept the logic this way to make it easier to review and compare against the previous Scala code. There are tons of options and even with the many tests we have and the lot of manual testing I did, I don't want to change the behavior of this tool.
What you propose sounds like a nice improvement but I'd prefer keeping this PR as a "translation" and do improvements in follow up PRs.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-14576: Move ConsoleConsumer to tools [kafka]
Posted by "jlprat (via GitHub)" <gi...@apache.org>.
jlprat commented on code in PR #15274:
URL: https://github.com/apache/kafka/pull/15274#discussion_r1478335911
##########
streams/src/test/java/org/apache/kafka/streams/integration/KStreamAggregationIntegrationTest.java:
##########
@@ -1139,8 +1140,7 @@ private <K, V> String readWindowedKeyedMessagesViaConsoleConsumer(final Deserial
"--property", "key.deserializer.window.size.ms=500",
};
- ConsoleConsumer.messageCount_$eq(0); //reset the message count
Review Comment:
Ah right!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-14576: Move ConsoleConsumer to tools [kafka]
Posted by "OmniaGM (via GitHub)" <gi...@apache.org>.
OmniaGM commented on code in PR #15274:
URL: https://github.com/apache/kafka/pull/15274#discussion_r1472764137
##########
tools/src/main/java/org/apache/kafka/tools/consumer/ConsoleConsumer.java:
##########
@@ -0,0 +1,233 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.tools.consumer;
+
+import java.io.PrintStream;
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.util.OptionalLong;
+import java.util.concurrent.CountDownLatch;
+import java.util.regex.Pattern;
+import java.util.Collections;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.common.MessageFormatter;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.AuthenticationException;
+import org.apache.kafka.common.errors.TimeoutException;
+import org.apache.kafka.common.errors.WakeupException;
+import org.apache.kafka.common.requests.ListOffsetsRequest;
+import org.apache.kafka.common.serialization.ByteArrayDeserializer;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Consumer that dumps messages to standard out.
+ */
+class ConsoleConsumer {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ConsoleConsumer.class);
+ private static final CountDownLatch SHUTDOWN_LATCH = new CountDownLatch(1);
+
+ static int messageCount = 0;
+
+ public static void main(String[] args) throws Exception {
+ ConsoleConsumerOptions opts = new ConsoleConsumerOptions(args);
+ try {
+ run(opts);
+ } catch (AuthenticationException ae) {
+ LOG.error("Authentication failed: terminating consumer process", ae);
+ Exit.exit(1);
+ } catch (Throwable t) {
+ LOG.error("Unknown error when running consumer: ", t);
+ Exit.exit(1);
+ }
+ }
+
+ static void run(ConsoleConsumerOptions conf) {
+ long timeoutMs = conf.timeoutMs() >= 0 ? conf.timeoutMs() : Long.MAX_VALUE;
+ Consumer<byte[], byte[]> consumer = new KafkaConsumer<>(conf.consumerProps(), new ByteArrayDeserializer(), new ByteArrayDeserializer());
+ ConsumerWrapper consumerWrapper = conf.partitionArg().isPresent()
+ ? new ConsumerWrapper(Optional.of(conf.topicArg()), conf.partitionArg(), OptionalLong.of(conf.offsetArg()), Optional.empty(), consumer, timeoutMs)
+ : new ConsumerWrapper(Optional.of(conf.topicArg()), OptionalInt.empty(), OptionalLong.empty(), Optional.ofNullable(conf.includedTopicsArg()), consumer, timeoutMs);
+
+ addShutdownHook(consumerWrapper, conf);
+
+ try {
+ process(conf.maxMessages(), conf.formatter(), consumerWrapper, System.out, conf.skipMessageOnError());
+ } finally {
+ consumerWrapper.cleanup();
+ conf.formatter().close();
+ reportRecordCount();
+
+ SHUTDOWN_LATCH.countDown();
+ }
+ }
+
+ static void addShutdownHook(ConsumerWrapper consumer, ConsoleConsumerOptions conf) {
+ Exit.addShutdownHook("consumer-shutdown-hook", () -> {
+ try {
+ consumer.wakeup();
+ SHUTDOWN_LATCH.await();
+ } catch (Throwable t) {
+ LOG.error("Exception while running shutdown hook " + t.getMessage());
+ }
+ if (conf.enableSystestEventsLogging()) {
+ System.out.println("shutdown_complete");
+ }
+ });
+ }
+
+ static void process(int maxMessages, MessageFormatter formatter, ConsumerWrapper consumer, PrintStream output, boolean skipMessageOnError) {
+ while (messageCount < maxMessages || maxMessages == -1) {
+ ConsumerRecord<byte[], byte[]> msg;
+ try {
+ msg = consumer.receive();
+ } catch (WakeupException we) {
+ LOG.trace("Caught WakeupException because consumer is shutdown, ignore and terminate.");
+ // Consumer will be closed
+ return;
+ } catch (Throwable t) {
+ LOG.error("Error processing message, terminating consumer process: ", t);
+ // Consumer will be closed
+ return;
+ }
+ messageCount += 1;
+ try {
+ formatter.writeTo(new ConsumerRecord<>(msg.topic(), msg.partition(), msg.offset(), msg.timestamp(), msg.timestampType(),
+ 0, 0, msg.key(), msg.value(), msg.headers(), Optional.empty()), output);
+ } catch (Throwable t) {
+ if (skipMessageOnError) {
+ LOG.error("Error processing message, skipping this message: ", t);
+ } else {
+ // Consumer will be closed
+ throw t;
+ }
+ }
+ if (checkErr(output)) {
+ // Consumer will be closed
+ return;
+ }
+ }
+ }
+
+ static void reportRecordCount() {
+ System.err.println("Processed a total of " + messageCount + " messages");
+ }
+
+ static boolean checkErr(PrintStream output) {
+ boolean gotError = output.checkError();
+ if (gotError) {
+ // This means no one is listening to our output stream anymore, time to shut down
+ System.err.println("Unable to write to standard out, closing consumer.");
+ }
+ return gotError;
+ }
+
+ public static class ConsumerWrapper {
+ final Optional<String> topic;
+ final OptionalInt partitionId;
+ final OptionalLong offset;
+ final Optional<String> includedTopics;
+ final Consumer<byte[], byte[]> consumer;
+ final long timeoutMs;
+ final Time time = Time.SYSTEM;
+
+ Iterator<ConsumerRecord<byte[], byte[]>> recordIter = Collections.emptyIterator();
+
+ public ConsumerWrapper(Optional<String> topic,
+ OptionalInt partitionId,
+ OptionalLong offset,
+ Optional<String> includedTopics,
+ Consumer<byte[], byte[]> consumer,
+ long timeoutMs) {
+ this.topic = topic;
+ this.partitionId = partitionId;
+ this.offset = offset;
+ this.includedTopics = includedTopics;
+ this.consumer = consumer;
+ this.timeoutMs = timeoutMs;
+
+ if (topic.isPresent() && partitionId.isPresent() && offset.isPresent() && !includedTopics.isPresent()) {
+ seek(topic.get(), partitionId.getAsInt(), offset.getAsLong());
Review Comment:
If we opt in for my suggestion above we can also refactor `seek` to decide what to do if offset is provided or not instead of the first 2 ifs we have here.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org