-
Notifications
You must be signed in to change notification settings - Fork 215
/
AmqpConsumerActor.java
533 lines (481 loc) · 24.5 KB
/
AmqpConsumerActor.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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
/*
* Copyright (c) 2017 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.amqp;
import static org.apache.qpid.jms.message.JmsMessageSupport.ACCEPTED;
import static org.apache.qpid.jms.message.JmsMessageSupport.MODIFIED_FAILED;
import static org.apache.qpid.jms.message.JmsMessageSupport.REJECTED;
import static org.eclipse.ditto.base.model.common.ConditionChecker.checkNotNull;
import static org.eclipse.ditto.connectivity.service.EnforcementFactoryFactory.newEnforcementFilterFactory;
import static org.eclipse.ditto.placeholders.PlaceholderFactory.newHeadersPlaceholder;
import java.nio.ByteBuffer;
import java.text.MessageFormat;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import javax.annotation.Nullable;
import javax.jms.BytesMessage;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import org.apache.qpid.jms.JmsAcknowledgeCallback;
import org.apache.qpid.jms.JmsMessageConsumer;
import org.apache.qpid.jms.message.JmsMessage;
import org.eclipse.ditto.base.model.exceptions.DittoRuntimeException;
import org.eclipse.ditto.base.model.headers.DittoHeaderDefinition;
import org.eclipse.ditto.base.model.headers.DittoHeaders;
import org.eclipse.ditto.base.model.signals.Signal;
import org.eclipse.ditto.connectivity.api.ExternalMessage;
import org.eclipse.ditto.connectivity.api.ExternalMessageBuilder;
import org.eclipse.ditto.connectivity.api.ExternalMessageFactory;
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.Enforcement;
import org.eclipse.ditto.connectivity.model.EnforcementFilterFactory;
import org.eclipse.ditto.connectivity.model.ResourceStatus;
import org.eclipse.ditto.connectivity.service.config.Amqp10Config;
import org.eclipse.ditto.connectivity.service.config.ConnectionConfig;
import org.eclipse.ditto.connectivity.service.config.ConnectivityConfig;
import org.eclipse.ditto.connectivity.service.messaging.ConnectivityStatusResolver;
import org.eclipse.ditto.connectivity.service.messaging.LegacyBaseConsumerActor;
import org.eclipse.ditto.connectivity.service.messaging.amqp.status.ConsumerClosedStatusReport;
import org.eclipse.ditto.connectivity.service.messaging.backoff.BackOffActor;
import org.eclipse.ditto.connectivity.service.messaging.internal.ConnectionFailure;
import org.eclipse.ditto.connectivity.service.messaging.internal.RetrieveAddressStatus;
import org.eclipse.ditto.connectivity.service.messaging.monitoring.logs.InfoProviderFactory;
import org.eclipse.ditto.internal.utils.akka.logging.ThreadSafeDittoLoggingAdapter;
import org.eclipse.ditto.internal.utils.config.InstanceIdentifierSupplier;
import org.eclipse.ditto.internal.utils.tracing.DittoTracing;
import org.eclipse.ditto.internal.utils.tracing.instruments.trace.StartedTrace;
import org.eclipse.ditto.internal.utils.tracing.instruments.trace.Traces;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.Status;
import akka.japi.pf.ReceiveBuilder;
import akka.pattern.Patterns;
import akka.stream.javadsl.Sink;
/**
* Actor which receives message from an AMQP source and forwards them to a {@code MessageMappingProcessorActor}.
*/
final class AmqpConsumerActor extends LegacyBaseConsumerActor
implements MessageListener, MessageRateLimiterBehavior<String> {
/**
* The name prefix of this Actor in the ActorSystem.
*/
static final String ACTOR_NAME_PREFIX = "amqpConsumerActor-";
private final EnforcementFilterFactory<Map<String, String>, Signal<?>> headerEnforcementFilterFactory;
private final ActorRef backOffActor;
private final MessageRateLimiter<String> messageRateLimiter;
// Access to the actor who performs JMS tasks in own thread
private final ActorRef jmsActor;
private final Duration jmsActorAskTimeout;
// data to reconstruct message consumer if something happens to it
private ConsumerData consumerData;
@Nullable
private MessageConsumer messageConsumer;
@SuppressWarnings("unused")
private AmqpConsumerActor(final Connection connection, final ConsumerData consumerData,
final Sink<Object, ?> inboundMappingSink, final ActorRef jmsActor,
final ConnectivityStatusResolver connectivityStatusResolver,
final ConnectivityConfig connectivityConfig) {
super(connection,
checkNotNull(consumerData, "consumerData").getAddress(),
inboundMappingSink,
consumerData.getSource(),
connectivityStatusResolver,
connectivityConfig);
final ConnectionConfig connectionConfig = connectivityConfig.getConnectionConfig();
final Amqp10Config amqp10Config = connectionConfig.getAmqp10Config();
this.messageConsumer = consumerData.getMessageConsumer();
this.consumerData = consumerData;
this.jmsActor = checkNotNull(jmsActor, "jmsActor");
jmsActorAskTimeout = connectionConfig.getClientActorAskTimeout();
// the amqp consumer is OPEN (ready to handle messages) after setMessageListener() was called successfully
handleAddressStatus(ConnectivityModelFactory.newSourceStatus(InstanceIdentifierSupplier.getInstance().get(),
ConnectivityStatus.UNKNOWN, sourceAddress, "Consumer is being initialized.", Instant.now()));
messageRateLimiter = initMessageRateLimiter(amqp10Config);
backOffActor = getContext().actorOf(BackOffActor.props(amqp10Config.getBackOffConfig()));
final Enforcement enforcement = consumerData.getSource().getEnforcement().orElse(null);
headerEnforcementFilterFactory = enforcement != null
? newEnforcementFilterFactory(enforcement, newHeadersPlaceholder())
: input -> null;
}
/**
* Creates Akka configuration object {@link Props} for this {@code AmqpConsumerActor}.
*
* @param connection the connection
* @param consumerData the consumer data.
* @param inboundMappingSink the message mapping sink where received messages are forwarded to
* @param jmsActor reference of the {@code JMSConnectionHandlingActor}.
* @param connectivityStatusResolver connectivity status resolver to resolve occurred exceptions to a connectivity
* status.
* @param connectivityConfig the connectivity config related to the given connection.
* @return the Akka configuration Props object.
*/
static Props props(final Connection connection, final ConsumerData consumerData,
final Sink<Object, ?> inboundMappingSink, final ActorRef jmsActor,
final ConnectivityStatusResolver connectivityStatusResolver,
final ConnectivityConfig connectivityConfig) {
return Props.create(AmqpConsumerActor.class, connection, consumerData, inboundMappingSink, jmsActor,
connectivityStatusResolver, connectivityConfig);
}
@Override
public Receive createReceive() {
final Receive messageHandlingBehavior = ReceiveBuilder.create()
.match(JmsMessage.class, this::handleJmsMessage)
.match(ResourceStatus.class, this::handleAddressStatus)
.match(RetrieveAddressStatus.class, ras -> getSender().tell(getCurrentSourceStatus(), getSelf()))
.matchEquals(Control.CREATE_CONSUMER, this::createMessageConsumer)
.match(ConsumerClosedStatusReport.class, this::matchesOwnConsumer, this::handleConsumerClosed)
.match(ConsumerClosedStatusReport.class, this::handleNonMatchingConsumerClosed)
.match(CreateMessageConsumerResponse.class, this::messageConsumerCreated)
.match(Status.Failure.class, this::messageConsumerFailed)
.build();
final Receive rateLimiterBehavior = getRateLimiterBehavior();
final Receive matchAnyBehavior = ReceiveBuilder.create()
.matchAny(m -> {
logger.warning("Unknown message: {}", m);
unhandled(m);
}).build();
return messageHandlingBehavior
.orElse(rateLimiterBehavior)
.orElse(matchAnyBehavior);
}
@Override
public void preStart() throws Exception {
super.preStart();
initMessageConsumer();
}
@Override
public void postStop() throws Exception {
super.postStop();
destroyMessageConsumer();
}
@Override
public void onMessage(final Message message) {
getSelf().tell(message, ActorRef.noSender());
}
private void stopMessageConsumer() {
if (messageConsumer != null) {
((JmsMessageConsumer) messageConsumer).stop();
}
}
private void startMessageConsumer() {
if (messageConsumer != null) {
((JmsMessageConsumer) messageConsumer).start();
}
}
@Override
public void stopMessageConsumerDueToRateLimit(final String reason) {
inboundMonitor.getCounter().recordFailure();
inboundMonitor.getLogger().failure("Source <{0}> is rate-limited due to {1}", sourceAddress, reason);
stopMessageConsumer();
}
@Override
public void startMessageConsumerDueToRateLimit() {
inboundMonitor.getLogger().success("Rate limit on source <{0}> is lifted", sourceAddress);
startMessageConsumer();
}
@Override
public MessageRateLimiter<String> getMessageRateLimiter() {
return messageRateLimiter;
}
private void initMessageConsumer() {
try {
if (messageConsumer != null) {
messageConsumer.setMessageListener(this);
consumerData = consumerData.withMessageConsumer(messageConsumer);
resetResourceStatus();
}
} catch (final Exception e) {
final ResourceStatus resourceStatus =
ConnectivityModelFactory.newStatusUpdate(InstanceIdentifierSupplier.getInstance().get(),
connectivityStatusResolver.resolve(e), sourceAddress,
"Initialization of message consumer failed: " + e.getMessage(),
Instant.now());
handleAddressStatus(resourceStatus);
final var failure = ConnectionFailure.of(getSelf(), e, "Failed to initialize message consumers.");
getContext().getParent().tell(failure, getSelf());
}
}
private void destroyMessageConsumer() {
if (messageConsumer != null) {
try {
logger.debug("Closing AMQP Consumer for '{}'", sourceAddress);
messageConsumer.close();
} catch (final JMSException jmsException) {
logger.debug("Closing consumer failed (can be ignored if connection was closed already): {}",
jmsException.getMessage());
}
messageConsumer = null;
}
}
private boolean matchesOwnConsumer(final ConsumerClosedStatusReport event) {
return messageConsumer != null && messageConsumer.equals(event.getMessageConsumer());
}
private void handleNonMatchingConsumerClosed(final ConsumerClosedStatusReport event) {
logger.debug("Received ConsumerClosedStatusReport which is handled by another consumer actor. Ignoring.");
}
private void handleConsumerClosed(final ConsumerClosedStatusReport event) {
// consumer closed
// update own status
final String statusDetails = buildStatusDetailsFromStatusReport(event);
final ResourceStatus addressStatus =
ConnectivityModelFactory.newStatusUpdate(InstanceIdentifierSupplier.getInstance().get(),
connectivityStatusResolver.resolve(event.getCause()), sourceAddress, statusDetails,
Instant.now());
handleAddressStatus(addressStatus);
// destroy current message consumer in any case
destroyMessageConsumer();
logger.info("Consumer for destination '{}' was closed. Will try to recreate after some backoff.",
sourceAddress);
backOffActor.tell(BackOffActor.createBackOffWithAnswerMessage(Control.CREATE_CONSUMER),
getSelf());
}
private String buildStatusDetailsFromStatusReport(final ConsumerClosedStatusReport event) {
if (event.getCause() != null) {
final Throwable cause = event.getCause();
final String causeClass = cause.getClass().getName();
final String causeMessage = cause.getMessage();
return String.format("Consumer closed. Cause: [%s] %s", causeClass, causeMessage);
} else {
return "Consumer closed.";
}
}
private void createMessageConsumer(final Control createConsumer) {
logger.debug("Trying to create consumer for destination '{}'.", sourceAddress);
/* ask JMSConnectionHandlingActor for a new consumer */
final CreateMessageConsumer createMessageConsumer = new CreateMessageConsumer(consumerData);
final CompletionStage<Object> responseFuture =
Patterns.ask(jmsActor, createMessageConsumer, jmsActorAskTimeout)
.thenApply(response -> {
if (response instanceof Throwable) {
// create failed future so that Patterns.pipe sends me Status.Failure
throw new CompletionException((Throwable) response);
}
return response;
});
Patterns.pipe(responseFuture, getContext().getDispatcher()).to(getSelf());
}
private void messageConsumerCreated(final CreateMessageConsumerResponse response) {
if (consumerData.equals(response.consumerData)) {
logger.info("Consumer for destination '{}' created.", sourceAddress);
destroyMessageConsumer();
messageConsumer = response.messageConsumer;
initMessageConsumer();
} else {
// got an orphaned message consumer! this is an error.
logger.error("RESOURCE_LEAK! Got created MessageConsumer <{}> for <{}>, while I have <{}> for <{}>",
response.messageConsumer, response.consumerData, messageConsumer, consumerData);
}
}
private void messageConsumerFailed(final Status.Failure failure) {
// escalate to parent
final ConnectionFailure connectionFailed = ConnectionFailure.of(getSelf(), failure.cause(),
"Failed to recreate closed message consumer");
getContext().getParent().tell(connectionFailed, getSelf());
final ResourceStatus addressStatus =
ConnectivityModelFactory.newStatusUpdate(InstanceIdentifierSupplier.getInstance().get(),
connectivityStatusResolver.resolve(failure.cause()), sourceAddress,
"Failed to recreate closed message consumer.",
Instant.now());
handleAddressStatus(addressStatus);
}
private void handleJmsMessage(final JmsMessage message) {
Map<String, String> headers = null;
String correlationId = null;
StartedTrace trace = Traces.emptyStartedTrace();
try {
recordIncomingForRateLimit(message.getJMSMessageID());
if (logger.isDebugEnabled()) {
final Integer ackType = Optional.ofNullable(message.getAcknowledgeCallback())
.map(JmsAcknowledgeCallback::getAckType)
.orElse(null);
logger.debug("Received JmsMessage from AMQP 1.0: {} with Properties: {} and AckType {}",
message.toString(),
message.getAllPropertyNames(),
ackType);
}
headers = extractHeadersMapFromJmsMessage(message);
correlationId = headers.get(DittoHeaderDefinition.CORRELATION_ID.getKey());
trace = DittoTracing.trace(DittoTracing.extractTraceContext(headers), "amqp.consume")
.correlationId(correlationId)
.start();
headers = trace.propagateContext(headers);
final ExternalMessageBuilder builder = ExternalMessageFactory.newExternalMessageBuilder(headers);
final ExternalMessage externalMessage = extractPayloadFromMessage(message, builder, correlationId)
.withAuthorizationContext(source.getAuthorizationContext())
.withEnforcement(headerEnforcementFilterFactory.getFilter(headers))
.withHeaderMapping(source.getHeaderMapping())
.withSourceAddress(sourceAddress)
.withPayloadMapping(consumerData.getSource().getPayloadMapping())
.build();
inboundMonitor.success(externalMessage);
final Map<String, String> externalMessageHeaders = externalMessage.getHeaders();
logger.withCorrelationId(correlationId)
.info("Received message from AMQP 1.0 with externalMessageHeaders: {}", externalMessageHeaders);
if (logger.isDebugEnabled()) {
logger.withCorrelationId(correlationId).debug("Received message from AMQP 1.0 with payload: {}",
externalMessage.getTextPayload().orElse("binary"));
}
forwardToMapping(externalMessage,
() -> acknowledge(message, true, false, externalMessageHeaders),
redeliver -> acknowledge(message, false, redeliver, externalMessageHeaders)
);
} catch (final DittoRuntimeException e) {
logger.withCorrelationId(e)
.info("Got DittoRuntimeException '{}' when command was parsed: {}", e.getErrorCode(),
e.getMessage());
trace.fail(e);
if (headers != null) {
// forwarding to messageMappingProcessor only make sense if we were able to extract the headers,
// because we need a reply-to address to send the error response
inboundMonitor.failure(headers, e);
forwardToMapping(e.setDittoHeaders(DittoHeaders.of(headers)));
} else {
inboundMonitor.failure(e);
}
} catch (final Exception e) {
if (null != headers) {
inboundMonitor.exception(headers, e);
} else {
inboundMonitor.exception(e);
}
trace.fail(e);
logger.withCorrelationId(correlationId)
.error(e, "Unexpected {}: {}", e.getClass().getName(), e.getMessage());
} finally {
trace.finish();
}
}
/**
* Acknowledge an incoming message with a given acknowledgement type.
*
* @param message The incoming message.
* @param isSuccess Whether this ackType is considered a success.
* @param redeliver whether redelivery should be requested.
* @param externalMessageHeaders used for logging to correlate ack with received log.
*/
private void acknowledge(final JmsMessage message, final boolean isSuccess, final boolean redeliver,
final Map<String, String> externalMessageHeaders) {
final Optional<String> correlationId = Optional.ofNullable(
externalMessageHeaders.get(DittoHeaderDefinition.CORRELATION_ID.getKey()));
try {
final String messageId = message.getJMSMessageID();
recordAckForRateLimit(messageId, isSuccess, redeliver);
// Beware: JMS client may make JmsMessageSupport constants ACCEPTED, etc. package-private.
final int ackType;
final String ackTypeName;
if (isSuccess) {
ackType = ACCEPTED;
ackTypeName = "accepted";
} else {
ackType = redeliver ? MODIFIED_FAILED : REJECTED;
ackTypeName = redeliver ? "modified[delivery-failed]" : "rejected";
}
final String jmsCorrelationID = message.getJMSCorrelationID();
logger.withCorrelationId(correlationId.orElse(jmsCorrelationID))
.info(MessageFormat.format(
"Acking <{0}> with original external message headers=<{1}>, isSuccess=<{2}>, ackType=<{3} {4}>",
messageId,
externalMessageHeaders,
isSuccess,
ackType,
ackTypeName)
);
message.getAcknowledgeCallback().setAckType(ackType);
message.acknowledge();
if (isSuccess) {
inboundAcknowledgedMonitor.success(InfoProviderFactory.forHeaders(externalMessageHeaders),
"Sending success acknowledgement: <{0}>", ackTypeName);
} else {
inboundAcknowledgedMonitor.exception(externalMessageHeaders,
"Sending negative acknowledgement: <{0}>", ackTypeName);
}
} catch (final Exception e) {
logger.withCorrelationId(correlationId.orElse(null)).error(e, "Failed to ack an AMQP message");
}
}
private ExternalMessageBuilder extractPayloadFromMessage(final JmsMessage message,
final ExternalMessageBuilder builder, @Nullable final String correlationId) throws JMSException {
if (message instanceof TextMessage) {
final String payload = ((TextMessage) message).getText();
builder.withTextAndBytes(payload, payload.getBytes());
} else if (message instanceof BytesMessage) {
final BytesMessage bytesMessage = (BytesMessage) message;
final long bodyLength = bytesMessage.getBodyLength();
if (bodyLength >= Integer.MIN_VALUE && bodyLength <= Integer.MAX_VALUE) {
final int length = (int) bodyLength;
final ByteBuffer byteBuffer = ByteBuffer.allocate(length);
bytesMessage.readBytes(byteBuffer.array());
builder.withBytes(byteBuffer);
} else {
throw new IllegalArgumentException("Message too large...");
}
} else {
if (logger.isDebugEnabled()) {
final Destination destination = message.getJMSDestination();
final Map<String, String> headersMapFromJmsMessage = extractHeadersMapFromJmsMessage(message);
logger.withCorrelationId(correlationId)
.debug("Received message at '{}' of unsupported type ({}) with headers: {}",
destination, message.getClass().getName(), headersMapFromJmsMessage);
}
}
return builder;
}
private Map<String, String> extractHeadersMapFromJmsMessage(final JmsMessage message) {
return JMSPropertyMapper.getPropertiesAndApplicationProperties(message);
}
@Override
public ThreadSafeDittoLoggingAdapter log() {
return logger;
}
/**
* Demand a new message consumer be made for this actor.
*/
static final class CreateMessageConsumer {
private final ConsumerData consumerData;
private CreateMessageConsumer(final ConsumerData consumerData) {
this.consumerData = consumerData;
}
ConsumerData getConsumerData() {
return consumerData;
}
Object toResponse(final MessageConsumer messageConsumer) {
return new CreateMessageConsumerResponse(consumerData, messageConsumer);
}
}
private static final class CreateMessageConsumerResponse {
private final ConsumerData consumerData;
private final MessageConsumer messageConsumer;
private CreateMessageConsumerResponse(final ConsumerData consumerData, final MessageConsumer messageConsumer) {
this.consumerData = consumerData;
this.messageConsumer = messageConsumer;
}
}
/**
* Actor control messages.
*/
private enum Control {
/**
* Triggers creation of a new message consumer.
*/
CREATE_CONSUMER
}
}