-
Notifications
You must be signed in to change notification settings - Fork 15.4k
KAFKA-14247: Consumer background thread base implementation #12672
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
vvcephei
merged 45 commits into
apache:trunk
from
philipnee:consumer-refactor-background-thread
Oct 20, 2022
Merged
Changes from all commits
Commits
Show all changes
45 commits
Select commit
Hold shift + click to select a range
a059d85
Basic event handler definition
008ca46
Define EventHandler interface
5bb3362
lint error
6551807
moving packages
86191c2
reduce the scope
c0ef143
PR comments for naming and documentation
564660f
Documentation on the beahvior
4f0a15e
Add isEmpty and remove excessive public
4828f71
Remove unused import
779c00c
Handle capacity limitation
b18098d
clean up a comment
ce00e48
A stubbed event handler to demonstrate the usage.
30e059b
typo
0e5a6dd
Revert "typo"
1ed6836
Revert "A stubbed event handler to demonstrate the usage."
bbabb93
Prototyping
e081c5f
clean up and documentation
d5c8009
background thread
684a0a1
Testing, background thread impl.
c80059a
renaming for clarity
480eb9a
fixes
422eed4
Refactor the background to make clear it is a network io thread
359eda9
wip
ebdc0d2
delete file
ca1d1c0
tests
6f1f8e5
extra space
14d9f52
spaces
5855d74
tests seem flakey
0cbf1f9
PR comments
6cfa912
cleaned up PR
c3d3d03
exception handling
7669b0a
clean up unused import
2d66bda
More documentation and better exception handling
3a52b13
refactor based on PR comment
45c55f9
Move network client construction to the handler
8f2c870
clean up
a343d2d
wakeup logic
7f3424d
documentation
d0e8f20
swallow interrupt exception
5440664
test swallowed exception
498e06b
remove the test for testing
f3158aa
wakeup exception test
fbb59e8
refactor based on PR comment
bec9391
debug message
f10d530
apply AK code conventions
vvcephei File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
230 changes: 230 additions & 0 deletions
230
...ts/src/main/java/org/apache/kafka/clients/consumer/internals/DefaultBackgroundThread.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,230 @@ | ||
| /* | ||
| * 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.clients.consumer.internals; | ||
|
|
||
| import org.apache.kafka.clients.CommonClientConfigs; | ||
| import org.apache.kafka.clients.consumer.ConsumerConfig; | ||
| import org.apache.kafka.clients.consumer.internals.events.ApplicationEvent; | ||
| import org.apache.kafka.clients.consumer.internals.events.BackgroundEvent; | ||
| import org.apache.kafka.clients.consumer.internals.events.NoopApplicationEvent; | ||
| import org.apache.kafka.common.KafkaException; | ||
| import org.apache.kafka.common.errors.WakeupException; | ||
| import org.apache.kafka.common.metrics.Metrics; | ||
| import org.apache.kafka.common.utils.KafkaThread; | ||
| import org.apache.kafka.common.utils.LogContext; | ||
| import org.apache.kafka.common.utils.Time; | ||
| import org.apache.kafka.common.utils.Utils; | ||
| import org.slf4j.Logger; | ||
|
|
||
| import java.util.Objects; | ||
| import java.util.Optional; | ||
| import java.util.concurrent.BlockingQueue; | ||
| import java.util.concurrent.atomic.AtomicReference; | ||
|
|
||
| /** | ||
| * Background thread runnable that consumes {@code ApplicationEvent} and | ||
| * produces {@code BackgroundEvent}. It uses an event loop to consume and | ||
| * produce events, and poll the network client to handle network IO. | ||
| * <p> | ||
| * It holds a reference to the {@link SubscriptionState}, which is | ||
| * initialized by the polling thread. | ||
| */ | ||
| public class DefaultBackgroundThread extends KafkaThread { | ||
| private static final String BACKGROUND_THREAD_NAME = | ||
| "consumer_background_thread"; | ||
| private final Time time; | ||
| private final Logger log; | ||
| private final BlockingQueue<ApplicationEvent> applicationEventQueue; | ||
| private final BlockingQueue<BackgroundEvent> backgroundEventQueue; | ||
| private final ConsumerNetworkClient networkClient; | ||
| private final SubscriptionState subscriptions; | ||
| private final ConsumerMetadata metadata; | ||
| private final Metrics metrics; | ||
| private final ConsumerConfig config; | ||
|
|
||
| private String clientId; | ||
| private long retryBackoffMs; | ||
| private int heartbeatIntervalMs; | ||
| private boolean running; | ||
| private Optional<ApplicationEvent> inflightEvent = Optional.empty(); | ||
| private final AtomicReference<Optional<RuntimeException>> exception = | ||
| new AtomicReference<>(Optional.empty()); | ||
|
|
||
| public DefaultBackgroundThread(final ConsumerConfig config, | ||
| final LogContext logContext, | ||
| final BlockingQueue<ApplicationEvent> applicationEventQueue, | ||
| final BlockingQueue<BackgroundEvent> backgroundEventQueue, | ||
| final SubscriptionState subscriptions, | ||
| final ConsumerMetadata metadata, | ||
| final ConsumerNetworkClient networkClient, | ||
| final Metrics metrics) { | ||
| this( | ||
| Time.SYSTEM, | ||
| config, | ||
| logContext, | ||
| applicationEventQueue, | ||
| backgroundEventQueue, | ||
| subscriptions, | ||
| metadata, | ||
| networkClient, | ||
| metrics | ||
| ); | ||
| } | ||
|
|
||
| public DefaultBackgroundThread(final Time time, | ||
| final ConsumerConfig config, | ||
| final LogContext logContext, | ||
| final BlockingQueue<ApplicationEvent> applicationEventQueue, | ||
| final BlockingQueue<BackgroundEvent> backgroundEventQueue, | ||
| final SubscriptionState subscriptions, | ||
| final ConsumerMetadata metadata, | ||
| final ConsumerNetworkClient networkClient, | ||
| final Metrics metrics) { | ||
| super(BACKGROUND_THREAD_NAME, true); | ||
| try { | ||
| this.time = time; | ||
| this.log = logContext.logger(DefaultBackgroundThread.class); | ||
| this.applicationEventQueue = applicationEventQueue; | ||
| this.backgroundEventQueue = backgroundEventQueue; | ||
| this.config = config; | ||
| setConfig(); | ||
| this.inflightEvent = Optional.empty(); | ||
| // subscriptionState is initialized by the polling thread | ||
| this.subscriptions = subscriptions; | ||
| this.metadata = metadata; | ||
| this.networkClient = networkClient; | ||
| this.metrics = metrics; | ||
| this.running = true; | ||
| } catch (final Exception e) { | ||
| // now propagate the exception | ||
| close(); | ||
| throw new KafkaException("Failed to construct background processor", e); | ||
| } | ||
| } | ||
|
|
||
| private void setConfig() { | ||
| this.retryBackoffMs = this.config.getLong(ConsumerConfig.RETRY_BACKOFF_MS_CONFIG); | ||
| this.clientId = config.getString(CommonClientConfigs.CLIENT_ID_CONFIG); | ||
| this.heartbeatIntervalMs = config.getInt(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG); | ||
| } | ||
|
|
||
| @Override | ||
| public void run() { | ||
| try { | ||
| log.debug("Background thread started"); | ||
| while (running) { | ||
| try { | ||
| runOnce(); | ||
| } catch (final WakeupException e) { | ||
| log.debug( | ||
| "Exception thrown, background thread won't terminate", | ||
| e | ||
| ); | ||
| // swallow the wakeup exception to prevent killing the | ||
| // background thread. | ||
| } | ||
| } | ||
| } catch (final Throwable t) { | ||
| log.error( | ||
| "The background thread failed due to unexpected error", | ||
| t | ||
| ); | ||
| if (t instanceof RuntimeException) | ||
| this.exception.set(Optional.of((RuntimeException) t)); | ||
| else | ||
| this.exception.set(Optional.of(new RuntimeException(t))); | ||
| } finally { | ||
| close(); | ||
| log.debug("{} closed", getClass()); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Process event from a single poll | ||
| */ | ||
| void runOnce() { | ||
| this.inflightEvent = maybePollEvent(); | ||
| if (this.inflightEvent.isPresent()) { | ||
| log.debug("processing application event: {}", this.inflightEvent); | ||
| } | ||
| if (this.inflightEvent.isPresent() && maybeConsumeInflightEvent(this.inflightEvent.get())) { | ||
| // clear inflight event upon successful consumption | ||
| this.inflightEvent = Optional.empty(); | ||
| } | ||
|
|
||
| // if there are pending events to process, poll then continue without | ||
| // blocking. | ||
| if (!applicationEventQueue.isEmpty() || inflightEvent.isPresent()) { | ||
| networkClient.poll(time.timer(0)); | ||
| return; | ||
| } | ||
| // if there are no events to process, poll until timeout. The timeout | ||
| // will be the minimum of the requestTimeoutMs, nextHeartBeatMs, and | ||
| // nextMetadataUpdate. See NetworkClient.poll impl. | ||
| networkClient.poll(time.timer(timeToNextHeartbeatMs(time.milliseconds()))); | ||
| } | ||
|
|
||
| private long timeToNextHeartbeatMs(final long nowMs) { | ||
| // TODO: implemented when heartbeat is added to the impl | ||
| return 100; | ||
| } | ||
|
|
||
| private Optional<ApplicationEvent> maybePollEvent() { | ||
| if (this.inflightEvent.isPresent() || this.applicationEventQueue.isEmpty()) { | ||
| return this.inflightEvent; | ||
| } | ||
| return Optional.ofNullable(this.applicationEventQueue.poll()); | ||
| } | ||
|
|
||
| /** | ||
| * ApplicationEvent are consumed here. | ||
| * | ||
| * @param event an {@link ApplicationEvent} | ||
| * @return true when successfully consumed the event. | ||
| */ | ||
| private boolean maybeConsumeInflightEvent(final ApplicationEvent event) { | ||
| log.debug("try consuming event: {}", Optional.ofNullable(event)); | ||
| Objects.requireNonNull(event); | ||
| return event.process(); | ||
| } | ||
|
|
||
| /** | ||
| * Processes {@link NoopApplicationEvent} and equeue a | ||
| * {@link NoopBackgroundEvent}. This is intentionally left here for | ||
| * demonstration purpose. | ||
| * | ||
| * @param event a {@link NoopApplicationEvent} | ||
| */ | ||
| private void process(final NoopApplicationEvent event) { | ||
| backgroundEventQueue.add(new NoopBackgroundEvent(event.message)); | ||
| } | ||
|
|
||
| public boolean isRunning() { | ||
| return this.running; | ||
| } | ||
|
|
||
| public void wakeup() { | ||
| networkClient.wakeup(); | ||
| } | ||
|
|
||
| public void close() { | ||
| this.running = false; | ||
| this.wakeup(); | ||
| Utils.closeQuietly(networkClient, "consumer network client"); | ||
| Utils.closeQuietly(metadata, "consumer metadata client"); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do we want to use
KafkaExceptioninstead ofRuntimeException?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We could, there are other places in the code that uses RTE so trying to be consistent with the existing code.