-
Notifications
You must be signed in to change notification settings - Fork 214
/
KafkaConsumerActor.java
244 lines (220 loc) · 11 KB
/
KafkaConsumerActor.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
/*
* Copyright (c) 2021 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.ditto.connectivity.service.messaging.kafka;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.CompletionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.annotation.Nullable;
import org.eclipse.ditto.base.service.config.supervision.ExponentialBackOffConfig;
import org.eclipse.ditto.connectivity.model.Connection;
import org.eclipse.ditto.connectivity.model.ConnectivityModelFactory;
import org.eclipse.ditto.connectivity.model.ConnectivityStatus;
import org.eclipse.ditto.connectivity.model.ResourceStatus;
import org.eclipse.ditto.connectivity.service.config.ConnectivityConfig;
import org.eclipse.ditto.connectivity.service.config.KafkaConsumerConfig;
import org.eclipse.ditto.connectivity.service.messaging.BaseConsumerActor;
import org.eclipse.ditto.connectivity.service.messaging.ConnectivityStatusResolver;
import org.eclipse.ditto.connectivity.service.messaging.internal.ConnectionFailure;
import org.eclipse.ditto.connectivity.service.messaging.internal.RetrieveAddressStatus;
import org.eclipse.ditto.internal.utils.pekko.logging.DittoLoggerFactory;
import org.eclipse.ditto.internal.utils.pekko.logging.ThreadSafeDittoLoggingAdapter;
import org.eclipse.ditto.internal.utils.config.InstanceIdentifierSupplier;
import org.apache.pekko.Done;
import org.apache.pekko.NotUsed;
import org.apache.pekko.actor.ActorRef;
import org.apache.pekko.actor.Props;
import org.apache.pekko.stream.Materializer;
import org.apache.pekko.stream.javadsl.Sink;
/**
* Actor which streams messages from Kafka.
*/
final class KafkaConsumerActor extends BaseConsumerActor {
static final String ACTOR_NAME_PREFIX = "kafkaConsumer-";
private static final Duration MAX_SHUTDOWN_TIMEOUT = Duration.ofSeconds(10);
private static final int DEFAULT_CONSUMPTION_QOS = 0;
private final ThreadSafeDittoLoggingAdapter log;
private RestartableKafkaConsumerStream kafkaStream;
@SuppressWarnings("unused")
private KafkaConsumerActor(final Connection connection,
final KafkaConsumerStreamFactory streamFactory,
final ConsumerData consumerData,
final Sink<Object, NotUsed> inboundMappingSink,
final ConnectivityStatusResolver connectivityStatusResolver,
final ConnectivityConfig connectivityConfig) {
super(connection, consumerData.getAddress(), inboundMappingSink, consumerData.getSource(),
connectivityStatusResolver, connectivityConfig);
final KafkaConsumerConfig consumerConfig = connectivityConfig
.getConnectionConfig()
.getKafkaConfig()
.getConsumerConfig();
final ExponentialBackOffConfig exponentialBackOffConfig = consumerConfig.getRestartBackOffConfig();
log = DittoLoggerFactory.getThreadSafeDittoLoggingAdapter(this);
final Materializer materializer = Materializer.createMaterializer(this::getContext);
final Integer qos = source.getQos().orElse(DEFAULT_CONSUMPTION_QOS);
if (qos.equals(1)) {
kafkaStream = new RestartableKafkaConsumerStream(
() -> {
final KafkaConsumerStream kafkaConsumerStream =
streamFactory.newAtLeastOnceConsumerStream(materializer, inboundMonitor,
inboundAcknowledgedMonitor, getMessageMappingSink(),
getDittoRuntimeExceptionSink(),
connection.getId(),
consumerData.getActorNamePrefix());
kafkaConsumerStream.whenComplete(this::handleStreamCompletion);
return kafkaConsumerStream;
}, exponentialBackOffConfig);
} else {
kafkaStream = new RestartableKafkaConsumerStream(
() -> {
final KafkaConsumerStream kafkaConsumerStream =
streamFactory.newAtMostOnceConsumerStream(materializer, inboundMonitor,
getMessageMappingSink(), getDittoRuntimeExceptionSink(), connection.getId(),
consumerData.getActorNamePrefix());
kafkaConsumerStream.whenComplete(this::handleStreamCompletion);
return kafkaConsumerStream;
}, exponentialBackOffConfig);
}
timers().startTimerAtFixedRate(ReportMetrics.class, ReportMetrics.INSTANCE,
consumerConfig.getMetricCollectingInterval());
}
static Props props(final Connection connection,
final KafkaConsumerStreamFactory streamFactory,
final ConsumerData consumerData,
final Sink<Object, NotUsed> inboundMappingSink,
final ConnectivityStatusResolver connectivityStatusResolver,
final ConnectivityConfig connectivityConfig) {
return Props.create(KafkaConsumerActor.class, connection, streamFactory, consumerData,
inboundMappingSink, connectivityStatusResolver, connectivityConfig);
}
@Override
public void postStop() throws Exception {
super.postStop();
shutdown(null);
}
@Override
public Receive createReceive() {
return receiveBuilder()
.match(ResourceStatus.class, this::handleAddressStatus)
.match(RetrieveAddressStatus.class, ram -> getSender().tell(getCurrentSourceStatus(), getSelf()))
.matchEquals(GracefulStop.START, start -> shutdown(getSender()))
.matchEquals(GracefulStop.DONE, done -> getContext().stop(getSelf()))
.match(ReportMetrics.class, reportMetrics -> reportMetrics())
.match(MessageRejectedException.class, this::restartStream)
.match(RestartableKafkaConsumerStream.class, this::setStream)
.matchAny(unhandled -> {
log.info("Unhandled message: {}", unhandled);
unhandled(unhandled);
})
.build();
}
@Override
protected ThreadSafeDittoLoggingAdapter log() {
return log;
}
private void reportMetrics() {
kafkaStream.reportMetrics();
}
private void shutdown(@Nullable final ActorRef sender) {
final var sendResponse = sender != null && !getContext().getSystem().deadLetters().equals(sender);
final var nullableSender = sendResponse ? sender : null;
if (kafkaStream != null) {
kafkaStream.stop()
.toCompletableFuture()
.orTimeout(MAX_SHUTDOWN_TIMEOUT.toSeconds(), TimeUnit.SECONDS)
.handle((done, error) -> {
final var isTimeout = error != null &&
(error instanceof TimeoutException || error.getCause() instanceof TimeoutException);
if (isTimeout) {
final var timeoutTemplate =
"Timeout when shutting down the kafka consumer stream for Connection with ID <{}>";
log.warning(timeoutTemplate, connectionId);
} else {
final var errorTemplate =
"Error when shutting down the kafka consumer stream for connection with ID <{}>";
log.warning(error, errorTemplate, connectionId);
}
return Done.getInstance();
})
.thenAccept(done -> notifyConsumerStopped(nullableSender));
} else {
notifyConsumerStopped(nullableSender);
}
}
private void notifyConsumerStopped(@Nullable final ActorRef sender) {
getSelf().tell(GracefulStop.DONE, getSelf());
if (sender != null) {
sender.tell(Done.getInstance(), getSelf());
}
}
private void handleStreamCompletion(@Nullable final Done done, @Nullable final Throwable throwable) {
final ConnectivityStatus status;
final ResourceStatus statusUpdate;
final Instant now = Instant.now();
final Throwable realCause = throwable instanceof CompletionException ? throwable.getCause() : throwable;
if (null == realCause) {
status = ConnectivityStatus.CLOSED;
statusUpdate = ConnectivityModelFactory.newStatusUpdate(
InstanceIdentifierSupplier.getInstance().get(),
status,
sourceAddress,
"Consumer closed", now);
} else if (realCause instanceof MessageRejectedException) {
status = ConnectivityStatus.CLOSED;
self().tell(realCause, ActorRef.noSender());
statusUpdate = ConnectivityModelFactory.newStatusUpdate(
InstanceIdentifierSupplier.getInstance().get(),
status,
sourceAddress,
"Restarting because of rejected message.", now);
} else {
log.debug("Consumer failed with error! <{}: {}>", throwable.getClass().getSimpleName(),
throwable.getMessage());
status = connectivityStatusResolver.resolve(throwable);
escalate(throwable, "Unexpected consumer failure.");
statusUpdate = ConnectivityModelFactory.newStatusUpdate(
InstanceIdentifierSupplier.getInstance().get(),
status,
sourceAddress,
ConnectionFailure.determineFailureDescription(now, throwable,
"Kafka consumer failed."), now);
}
handleAddressStatus(statusUpdate);
}
private void restartStream(final MessageRejectedException ex) {
kafkaStream.restart().toCompletableFuture()
.thenAccept(newKafkaStream -> self().tell(newKafkaStream, self()));
}
private void setStream(final RestartableKafkaConsumerStream newKafkaStream) {
kafkaStream = newKafkaStream;
resetResourceStatus();
}
private void escalate(final Throwable throwable, final String description) {
getContext().getParent()
.tell(ConnectionFailure.of(getSelf(), throwable, description), getSelf());
}
static final class ReportMetrics {
static final ReportMetrics INSTANCE = new ReportMetrics();
private ReportMetrics() {
// intentionally empty
}
}
/**
* Message that allows gracefully stopping the consumer actor.
*/
static enum GracefulStop {
START,
DONE
}
}