/
AmqpConsumerActor.java
478 lines (428 loc) · 22 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
/*
* 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.services.connectivity.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.MODIFIED_FAILED_UNDELIVERABLE;
import static org.eclipse.ditto.model.base.common.ConditionChecker.checkNotNull;
import java.nio.ByteBuffer;
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.model.base.exceptions.DittoRuntimeException;
import org.eclipse.ditto.model.base.headers.DittoHeaderDefinition;
import org.eclipse.ditto.model.base.headers.DittoHeaders;
import org.eclipse.ditto.model.connectivity.ConnectionId;
import org.eclipse.ditto.model.connectivity.ConnectionType;
import org.eclipse.ditto.model.connectivity.ConnectivityModelFactory;
import org.eclipse.ditto.model.connectivity.ConnectivityStatus;
import org.eclipse.ditto.model.connectivity.Enforcement;
import org.eclipse.ditto.model.connectivity.EnforcementFilterFactory;
import org.eclipse.ditto.model.connectivity.ResourceStatus;
import org.eclipse.ditto.model.placeholders.PlaceholderFactory;
import org.eclipse.ditto.services.connectivity.config.Amqp10Config;
import org.eclipse.ditto.services.connectivity.config.ConnectionConfig;
import org.eclipse.ditto.services.connectivity.config.ConnectivityConfig;
import org.eclipse.ditto.services.connectivity.config.ConnectivityConfigModifiedBehavior;
import org.eclipse.ditto.services.connectivity.config.ConnectivityConfigProvider;
import org.eclipse.ditto.services.connectivity.config.ConnectivityConfigProviderFactory;
import org.eclipse.ditto.services.connectivity.messaging.BaseConsumerActor;
import org.eclipse.ditto.services.connectivity.messaging.amqp.status.ConsumerClosedStatusReport;
import org.eclipse.ditto.services.connectivity.messaging.internal.ConnectionFailure;
import org.eclipse.ditto.services.connectivity.messaging.internal.ImmutableConnectionFailure;
import org.eclipse.ditto.services.connectivity.messaging.internal.RetrieveAddressStatus;
import org.eclipse.ditto.services.connectivity.messaging.monitoring.logs.InfoProviderFactory;
import org.eclipse.ditto.services.models.connectivity.EnforcementFactoryFactory;
import org.eclipse.ditto.services.models.connectivity.ExternalMessage;
import org.eclipse.ditto.services.models.connectivity.ExternalMessageBuilder;
import org.eclipse.ditto.services.models.connectivity.ExternalMessageFactory;
import org.eclipse.ditto.services.utils.akka.logging.DittoDiagnosticLoggingAdapter;
import org.eclipse.ditto.services.utils.akka.logging.DittoLoggerFactory;
import org.eclipse.ditto.services.utils.config.InstanceIdentifierSupplier;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.Status;
import akka.japi.pf.ReceiveBuilder;
import akka.pattern.Patterns;
/**
* Actor which receives message from an AMQP source and forwards them to a {@code MessageMappingProcessorActor}.
*/
final class AmqpConsumerActor extends BaseConsumerActor implements MessageListener,
MessageRateLimiterBehavior<String>, ConnectivityConfigModifiedBehavior {
/**
* The name prefix of this Actor in the ActorSystem.
*/
static final String ACTOR_NAME_PREFIX = "amqpConsumerActor-";
private final DittoDiagnosticLoggingAdapter log = DittoLoggerFactory.getDiagnosticLoggingAdapter(this);
private final EnforcementFilterFactory<Map<String, String>, CharSequence> headerEnforcementFilterFactory;
private 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;
private ConnectivityConfig connectivityConfig;
@SuppressWarnings("unused")
private AmqpConsumerActor(final ConnectionId connectionId, final ConsumerData consumerData,
final ActorRef inboundMappingProcessor, final ActorRef jmsActor) {
super(connectionId,
checkNotNull(consumerData, "consumerData").getAddress(),
inboundMappingProcessor,
consumerData.getSource(),
ConnectionType.AMQP_10);
final ConnectivityConfigProvider connectivityConfigProvider =
ConnectivityConfigProviderFactory.getInstance(getContext().getSystem());
connectivityConfig = connectivityConfigProvider.getConnectivityConfig(connectionId);
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();
messageRateLimiter = initMessageRateLimiter(amqp10Config);
final Enforcement enforcement = consumerData.getSource().getEnforcement().orElse(null);
headerEnforcementFilterFactory = enforcement != null ? EnforcementFactoryFactory
.newEnforcementFilterFactory(enforcement, PlaceholderFactory.newHeadersPlaceholder()) :
input -> null;
}
/**
* Creates Akka configuration object {@link Props} for this {@code AmqpConsumerActor}.
*
* @param connectionId the connection id
* @param consumerData the consumer data.
* @param inboundMappingProcessor the message mapping processor where received messages are forwarded to
* @param jmsActor reference of the {@code JMSConnectionHandlingActor).
* @return the Akka configuration Props object.
*/
static Props props(final ConnectionId connectionId, final ConsumerData consumerData,
final ActorRef inboundMappingProcessor, final ActorRef jmsActor) {
return Props.create(AmqpConsumerActor.class, connectionId, consumerData, inboundMappingProcessor, jmsActor);
}
@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()))
.match(ConsumerClosedStatusReport.class, this::matchesOwnConsumer, this::handleConsumerClosed)
.match(CreateMessageConsumerResponse.class, this::messageConsumerCreated)
.match(Status.Failure.class, this::messageConsumerFailed)
.build();
final Receive rateLimiterBehavior = getRateLimiterBehavior();
final Receive matchAnyBehavior = ReceiveBuilder.create()
.matchAny(m -> {
log.warning("Unknown message: {}", m);
unhandled(m);
}).build();
return messageHandlingBehavior
.orElse(rateLimiterBehavior)
.orElse(connectivityConfigModifiedBehavior())
.orElse(matchAnyBehavior);
}
@Override
public void preStart() throws JMSException {
initMessageConsumer();
registerForConfigChanges(connectionId);
}
@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() throws JMSException {
if (messageConsumer != null) {
messageConsumer.setMessageListener(this);
consumerData = consumerData.withMessageConsumer(messageConsumer);
}
}
private void destroyMessageConsumer() {
if (messageConsumer != null) {
try {
log.debug("Closing AMQP Consumer for '{}'", sourceAddress);
messageConsumer.close();
} catch (final JMSException jmsException) {
log.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 handleConsumerClosed(final ConsumerClosedStatusReport event) {
// consumer closed
// update own status
final ResourceStatus addressStatus = ConnectivityModelFactory.newStatusUpdate(
InstanceIdentifierSupplier.getInstance().get(),
ConnectivityStatus.FAILED,
sourceAddress,
"Consumer closed", Instant.now());
handleAddressStatus(addressStatus);
// destroy current message consumer in any case
destroyMessageConsumer();
/* 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) throws JMSException {
if (consumerData.equals(response.consumerData)) {
log.info("Consumer <{}> created", response.messageConsumer);
destroyMessageConsumer();
messageConsumer = response.messageConsumer;
initMessageConsumer();
resetResourceStatus();
} else {
// got an orphaned message consumer! this is an error.
log.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 = new ImmutableConnectionFailure(getSelf(), failure.cause(),
"Failed to recreate closed message consumer");
getContext().getParent().tell(connectionFailed, getSelf());
}
private void handleJmsMessage(final JmsMessage message) {
Map<String, String> headers = null;
String correlationId = null;
try {
recordIncomingForRateLimit(message.getJMSMessageID());
if (log.isDebugEnabled()) {
final Integer ackType = Optional.ofNullable(message.getAcknowledgeCallback())
.map(JmsAcknowledgeCallback::getAckType)
.orElse(null);
log.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());
final ExternalMessageBuilder builder = ExternalMessageFactory.newExternalMessageBuilder(headers);
final ExternalMessage externalMessage = extractPayloadFromMessage(message, builder, correlationId)
.withAuthorizationContext(source.getAuthorizationContext())
.withEnforcement(headerEnforcementFilterFactory.getFilter(headers))
.withHeaderMapping(source.getHeaderMapping().orElse(null))
.withSourceAddress(sourceAddress)
.withPayloadMapping(consumerData.getSource().getPayloadMapping())
.build();
inboundMonitor.success(externalMessage);
final Map<String, String> externalMessageHeaders = externalMessage.getHeaders();
log.withCorrelationId(correlationId).info("Received message from AMQP 1.0 with externalMessageHeaders: {}",
externalMessageHeaders);
if (log.isDebugEnabled()) {
log.withCorrelationId(correlationId).debug("Received message from AMQP 1.0 with payload: {}",
externalMessage.getTextPayload().orElse("binary"));
}
forwardToMappingActor(externalMessage,
() -> acknowledge(message, true, false, externalMessageHeaders),
redeliver -> acknowledge(message, false, redeliver, externalMessageHeaders)
);
} catch (final DittoRuntimeException e) {
log.withCorrelationId(e)
.info("Got DittoRuntimeException '{}' when command was parsed: {}", e.getErrorCode(),
e.getMessage());
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);
forwardToMappingActor(e.setDittoHeaders(DittoHeaders.of(headers)));
} else {
inboundMonitor.failure(e);
}
} catch (final Exception e) {
if (null != headers) {
inboundMonitor.exception(headers, e);
} else {
inboundMonitor.exception(e);
}
log.withCorrelationId(correlationId)
.error(e, "Unexpected {}: {}", e.getClass().getName(), e.getMessage());
}
}
/**
* 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 String correlationId = 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 : MODIFIED_FAILED_UNDELIVERABLE;
ackTypeName = redeliver ? "modified[delivery-failed]" : "modified[delivery-failed,undeliverable-here]";
}
log.withCorrelationId(correlationId)
.info("Acking <{}> with original external message headers=<{}>, isSuccess=<{}>, ackType=<{} {}>",
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("Sending negative acknowledgement: <{0}>", ackTypeName);
}
} catch (final JMSException e) {
log.withCorrelationId(correlationId).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 (log.isDebugEnabled()) {
final Destination destination = message.getJMSDestination();
final Map<String, String> headersMapFromJmsMessage = extractHeadersMapFromJmsMessage(message);
log.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 DittoDiagnosticLoggingAdapter log() {
return log;
}
@Override
public void onConnectivityConfigModified(final ConnectivityConfig connectivityConfig) {
this.connectivityConfig = connectivityConfig;
final Amqp10Config amqp10Config = connectivityConfig.getConnectionConfig().getAmqp10Config();
if (hasMessageRateLimiterConfigChanged(amqp10Config)) {
this.messageRateLimiter = MessageRateLimiter.of(amqp10Config, messageRateLimiter);
log.info("Built new rate limiter from existing one with modified config: {}", amqp10Config);
} else {
log.debug("Relevant config for MessageRateLimiter unchanged, do nothing.");
}
}
private boolean hasMessageRateLimiterConfigChanged(final Amqp10Config amqp10Config) {
return messageRateLimiter != null
&& (messageRateLimiter.getMaxPerPeriod() != amqp10Config.getConsumerThrottlingLimit()
|| messageRateLimiter.getMaxInFlight() != amqp10Config.getConsumerMaxInFlight()
|| messageRateLimiter.getRedeliveryExpectationTimeout() !=
amqp10Config.getConsumerRedeliveryExpectationTimeout());
}
/**
* 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;
}
}
}