/
AmqpClientActor.java
587 lines (525 loc) · 25.9 KB
/
AmqpClientActor.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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
/*
* 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 java.net.URI;
import java.text.MessageFormat;
import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import javax.annotation.Nullable;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import org.apache.qpid.jms.JmsConnection;
import org.apache.qpid.jms.JmsConnectionListener;
import org.apache.qpid.jms.message.JmsInboundMessageDispatch;
import org.apache.qpid.jms.provider.ProviderFactory;
import org.eclipse.ditto.model.connectivity.Connection;
import org.eclipse.ditto.model.connectivity.ConnectionConfigurationInvalidException;
import org.eclipse.ditto.model.connectivity.ConnectivityModelFactory;
import org.eclipse.ditto.model.connectivity.ConnectivityStatus;
import org.eclipse.ditto.services.connectivity.messaging.BaseClientActor;
import org.eclipse.ditto.services.connectivity.messaging.BaseClientData;
import org.eclipse.ditto.services.connectivity.messaging.BaseClientState;
import org.eclipse.ditto.services.connectivity.messaging.internal.AbstractWithOrigin;
import org.eclipse.ditto.services.connectivity.messaging.internal.ClientConnected;
import org.eclipse.ditto.services.connectivity.messaging.internal.ClientDisconnected;
import org.eclipse.ditto.services.connectivity.messaging.internal.ConnectClient;
import org.eclipse.ditto.services.connectivity.messaging.internal.ConnectionFailure;
import org.eclipse.ditto.services.connectivity.messaging.internal.DisconnectClient;
import org.eclipse.ditto.services.connectivity.messaging.internal.ImmutableConnectionFailure;
import org.eclipse.ditto.services.connectivity.messaging.monitoring.logs.ConnectionLogger;
import org.eclipse.ditto.services.connectivity.util.ConnectionLogUtil;
import org.eclipse.ditto.services.utils.config.ConfigUtil;
import org.eclipse.ditto.signals.commands.connectivity.exceptions.ConnectionFailedException;
import akka.actor.ActorRef;
import akka.actor.FSM;
import akka.actor.Props;
import akka.actor.Status;
import akka.event.DiagnosticLoggingAdapter;
import akka.japi.pf.FSMStateFunctionBuilder;
import akka.pattern.PatternsCS;
/**
* Actor which manages a connection to an AMQP 1.0 server using the Qpid JMS client.
* This actor delegates interaction with the JMS client to a child actor because the JMS client blocks in most cases
* which does not work well with actors.
*/
public final class AmqpClientActor extends BaseClientActor implements ExceptionListener {
private final JmsConnectionFactory jmsConnectionFactory;
private final StatusReportingListener connectionListener;
private final List<ConsumerData> consumers;
@Nullable private JmsConnection jmsConnection;
@Nullable private Session jmsSession;
@Nullable private ActorRef amqpPublisherActor;
@Nullable private ActorRef testConnectionHandler;
@Nullable private ActorRef connectConnectionHandler;
@Nullable private ActorRef disconnectConnectionHandler;
private final Map<String, ActorRef> consumerByNamePrefix;
/*
* This constructor is called via reflection by the static method propsForTest.
*/
@SuppressWarnings("unused")
private AmqpClientActor(final Connection connection, final ConnectivityStatus connectionStatus,
final JmsConnectionFactory jmsConnectionFactory, final ActorRef conciergeForwarder) {
super(connection, connectionStatus, conciergeForwarder);
this.jmsConnectionFactory = jmsConnectionFactory;
connectionListener = new StatusReportingListener(getSelf(), connection.getId(), log, connectionLogger);
consumers = new LinkedList<>();
consumerByNamePrefix = new HashMap<>();
}
/*
* This constructor is called via reflection by the static method props(Connection, ActorRef).
*/
@SuppressWarnings("unused")
private AmqpClientActor(final Connection connection, final ConnectivityStatus connectionStatus,
final ActorRef conciergeForwarder) {
this(connection, connectionStatus, ConnectionBasedJmsConnectionFactory.getInstance(), conciergeForwarder);
}
/**
* Creates Akka configuration object for this actor.
*
* @param connection the connection.
* @param conciergeForwarder the actor used to send signals to the concierge service.
* @return the Akka configuration Props object.
*/
public static Props props(final Connection connection, final ActorRef conciergeForwarder) {
return Props.create(AmqpClientActor.class, validateConnection(connection), connection.getConnectionStatus(),
conciergeForwarder);
}
/**
* Creates Akka configuration object for this actor.
*
* @param connection connection parameters.
* @param connectionStatus the desired status of the connection.
* @param conciergeForwarder the actor used to send signals to the concierge service.
* @param jmsConnectionFactory the JMS connection factory.
* @return the Akka configuration Props object.
*/
static Props propsForTests(final Connection connection, final ConnectivityStatus connectionStatus,
final ActorRef conciergeForwarder, final JmsConnectionFactory jmsConnectionFactory) {
return Props.create(AmqpClientActor.class, validateConnection(connection), connectionStatus,
jmsConnectionFactory, conciergeForwarder);
}
private static Connection validateConnection(final Connection connection) {
try {
final URI uri =
URI.create(ConnectionBasedJmsConnectionFactory.buildAmqpConnectionUriFromConnection(connection));
ProviderFactory.create(uri);
return connection;
} catch (final Exception e) {
final String errorMessageTemplate =
"Failed to instantiate an amqp provider from the given configuration: {0}";
final String errorMessage = MessageFormat.format(errorMessageTemplate, e.getMessage());
throw ConnectionConfigurationInvalidException
.newBuilder(errorMessage)
.description(e.getMessage())
.cause(e)
.build();
}
}
@Override
public void postStop() {
ensureJmsConnectionClosed();
super.postStop();
}
@Override
protected FSMStateFunctionBuilder<BaseClientState, BaseClientData> inAnyState() {
return super.inAnyState()
.event(StatusReport.class, this::handleStatusReport);
}
@Override
protected CompletionStage<Status.Status> doTestConnection(final Connection connection) {
// delegate to child actor because the QPID JMS client is blocking until connection is opened/closed
return PatternsCS.ask(getTestConnectionHandler(connection),
new JmsConnect(getSender()), Duration.ofSeconds(TEST_CONNECTION_TIMEOUT))
.handle((response, throwable) -> {
if (throwable != null || response instanceof Status.Failure || response instanceof Throwable) {
final Throwable ex =
(response instanceof Status.Failure) ? ((Status.Failure) response).cause() :
(response instanceof Throwable) ? (Throwable) response : throwable;
final ConnectionFailedException failedException =
ConnectionFailedException.newBuilder(connectionId())
.description("The requested Connection could not be connected due to '" +
ex.getClass().getSimpleName() + ": " + ex.getMessage() + "'")
.cause(ex).build();
return new Status.Failure(failedException);
} else if (response instanceof ConnectionFailure) {
return ((ConnectionFailure) response).getFailure();
} else {
return new Status.Success(response);
}
});
}
@Override
protected void doConnectClient(final Connection connection, @Nullable final ActorRef origin) {
// delegate to child actor because the QPID JMS client is blocking until connection is opened/closed
getConnectConnectionHandler(connection).tell(new JmsConnect(origin), getSelf());
}
@Override
protected void doDisconnectClient(final Connection connection, @Nullable final ActorRef origin) {
// delegate to child actor because the QPID JMS client is blocking until connection is opened/closed
getDisconnectConnectionHandler(connection)
.tell(new JmsDisconnect(origin, jmsConnection), getSelf());
}
@Override
protected void allocateResourcesOnConnection(final ClientConnected clientConnected) {
if (clientConnected instanceof JmsConnected) {
final JmsConnected c = (JmsConnected) clientConnected;
log.info("Received JmsConnected");
ensureJmsConnectionClosed();
this.jmsConnection = c.connection;
this.jmsConnection.addConnectionListener(connectionListener);
this.jmsSession = c.session;
consumers.clear();
consumers.addAll(c.consumerList);
// note: start order is important (publisher -> mapping -> consumer actor)
startAmqpPublisherActor();
startMessageMappingProcessor(connection().getMappingContext().orElse(null));
startCommandConsumers(consumers);
} else {
log.info("ClientConnected was not JmsConnected as expected, ignoring as this probably was a reconnection");
}
}
@Override
protected void cleanupResourcesForConnection() {
log.debug("cleaning up");
stopCommandConsumers();
stopMessageMappingProcessorActor();
stopCommandProducer();
// closing JMS connection closes all sessions and consumers
ensureJmsConnectionClosed();
this.jmsConnection = null;
this.jmsSession = null;
this.consumers.clear();
}
/*
* Kill connection handlers on timeout to be able to handle the next command immediately.
*/
@Override
protected void cleanupFurtherResourcesOnConnectionTimeout(final BaseClientState currentState) {
switch (currentState) {
case CONNECTING:
if (connectConnectionHandler != null) {
stopChildActor(connectConnectionHandler);
connectConnectionHandler = null;
}
break;
case DISCONNECTING:
if (disconnectConnectionHandler != null) {
stopChildActor(disconnectConnectionHandler);
disconnectConnectionHandler = null;
}
break;
case TESTING:
default:
// no need to handle TESTING state because this actor stops after test timeout.
break;
}
super.cleanupFurtherResourcesOnConnectionTimeout(currentState);
}
@Override
protected ActorRef getPublisherActor() {
return amqpPublisherActor;
}
@Override
protected boolean isEventUpToDate(final Object event, final BaseClientState state, final ActorRef sender) {
switch (state) {
case CONNECTING:
return Objects.equals(sender, connectConnectionHandler);
case DISCONNECTING:
return Objects.equals(sender, disconnectConnectionHandler);
case TESTING:
default:
// no need to check testConnectionHandler because test runs only once during this actor's lifetime
}
// ignore random events by default - they could come from a connection handler that is already dead
return false;
}
private void startCommandConsumers(final List<ConsumerData> consumers) {
final Optional<ActorRef> messageMappingProcessor = getMessageMappingProcessorActor();
if (messageMappingProcessor.isPresent()) {
if (isConsuming()) {
stopCommandConsumers();
consumers.forEach(consumer -> startCommandConsumer(consumer, messageMappingProcessor.get()));
connectionLogger.success("Subscriptions {0} initialized successfully.", consumers);
log.info("Subscribed Connection <{}> to sources: {}", connectionId(), consumers);
} else {
log.debug("Not starting consumers, no sources were configured");
}
} else {
log.warning("The MessageMappingProcessor was not available and therefore no consumers were started!");
}
}
private void startCommandConsumer(final ConsumerData consumer, final ActorRef messageMappingProcessor) {
final String namePrefix = consumer.getActorNamePrefix();
final Props props = AmqpConsumerActor.props(connectionId(), consumer.getAddress(),
consumer.getMessageConsumer(),
messageMappingProcessor, consumer.getSource());
final ActorRef child = startChildActorConflictFree(namePrefix, props);
consumerByNamePrefix.put(namePrefix, child);
}
private void startAmqpPublisherActor() {
stopCommandProducer();
final String namePrefix = AmqpPublisherActor.ACTOR_NAME;
if (jmsSession != null) {
final Props props = AmqpPublisherActor.props(connectionId(), getTargetsOrEmptyList(), jmsSession);
amqpPublisherActor = startChildActorConflictFree(namePrefix, props);
} else {
throw ConnectionFailedException
.newBuilder(connectionId())
.message("Could not start publisher actor due to missing jms session or connection.")
.build();
}
}
private void stopCommandProducer() {
if (amqpPublisherActor != null) {
stopChildActor(amqpPublisherActor);
amqpPublisherActor = null;
}
}
private void stopCommandConsumers() {
consumerByNamePrefix.forEach((namePrefix, child) -> {
final String actorName = child.path().name();
if (actorName.startsWith(AmqpConsumerActor.ACTOR_NAME_PREFIX)) {
stopChildActor(child);
}
});
consumerByNamePrefix.clear();
}
private ActorRef getTestConnectionHandler(final Connection connection) {
if (testConnectionHandler == null) {
testConnectionHandler = startConnectionHandlingActor("test", connection);
}
return testConnectionHandler;
}
private ActorRef getConnectConnectionHandler(final Connection connection) {
if (connectConnectionHandler == null) {
connectConnectionHandler = startConnectionHandlingActor("connect", connection);
}
return connectConnectionHandler;
}
private ActorRef getDisconnectConnectionHandler(final Connection connection) {
if (disconnectConnectionHandler == null) {
disconnectConnectionHandler = startConnectionHandlingActor("disconnect", connection);
}
return disconnectConnectionHandler;
}
private ActorRef startConnectionHandlingActor(final String suffix, final Connection connection) {
final String namePrefix =
JMSConnectionHandlingActor.ACTOR_NAME_PREFIX + escapeActorName(connectionId() + "-" + suffix);
final Props props =
JMSConnectionHandlingActor.propsWithOwnDispatcher(connection, this, jmsConnectionFactory);
return startChildActorConflictFree(namePrefix, props);
}
/**
* Close the JMS connection known to this actor in an isolated dispatcher because it is blocking.
*
* @return future where the closing operation executes.
*/
@SuppressWarnings("UnusedReturnValue")
private CompletableFuture<Void> ensureJmsConnectionClosed() {
if (jmsConnection != null) {
final JmsConnection jmsConnectionToClose = jmsConnection;
final Runnable closeJmsConnectionRunnable = () -> {
try {
jmsConnectionToClose.close();
} catch (final Throwable error) {
// 'log' is final. It is okay to use it in a future.
log.error(error, "RESOURCE-LEAK: failed to close JMSConnection");
throw new RuntimeException(error);
}
};
return CompletableFuture.runAsync(closeJmsConnectionRunnable,
JMSConnectionHandlingActor.getOwnDispatcher(getContext().system()));
} else {
return CompletableFuture.completedFuture(null);
}
}
/**
* Set metrics for self and children when the status report listener sends a report.
*
* @param statusReport status report from status report listener.
* @param currentData known data of the connection.
* @return same FSM state with possibly updated connection status and status detail.
*/
private FSM.State<BaseClientState, BaseClientData> handleStatusReport(final StatusReport statusReport,
final BaseClientData currentData) {
BaseClientData data = currentData;
if (statusReport.isConnectionRestored()) {
data = data.setConnectionStatus(ConnectivityStatus.OPEN)
.setConnectionStatusDetails("Connection restored");
}
final Optional<ConnectionFailure> possibleFailure = statusReport.getFailure();
final Optional<MessageConsumer> possibleClosedConsumer = statusReport.getClosedConsumer();
if (possibleFailure.isPresent()) {
final ConnectionFailure failure = possibleFailure.get();
final String message = MessageFormat.format("Failure: {0}, Description: {1}",
failure.getFailure().cause(), failure.getFailureDescription());
data = data.setConnectionStatus(ConnectivityStatus.FAILED)
.setConnectionStatusDetails(message);
}
if (possibleClosedConsumer.isPresent()) {
final MessageConsumer consumer = possibleClosedConsumer.get();
consumers.stream()
.filter(c -> c.getMessageConsumer().equals(consumer))
.findFirst()
.ifPresent(c -> {
final ActorRef consumerActor = consumerByNamePrefix.get(c.getActorNamePrefix());
if (consumerActor != null) {
final Object message = ConnectivityModelFactory.newStatusUpdate(
ConfigUtil.instanceIdentifier(),
ConnectivityStatus.FAILED,
c.getAddress(),
"Consumer closed", Instant.now());
consumerActor.tell(message, ActorRef.noSender());
}
});
}
statusReport.getClosedProducer().ifPresent(p -> amqpPublisherActor.tell(statusReport, ActorRef.noSender()));
return stay().using(data);
}
@Override
public void onException(final JMSException exception) {
connectionLogger.exception("Exception occured: {0}", exception.getMessage());
log.warning("{} occurred: {}", exception.getClass().getName(), exception.getMessage());
}
/**
* {@code Connect} message for internal communication with {@link JMSConnectionHandlingActor}.
*/
static class JmsConnect extends AbstractWithOrigin implements ConnectClient {
JmsConnect(@Nullable final ActorRef origin) {
super(origin);
}
}
/**
* {@code Disconnect} message for internal communication with {@link JMSConnectionHandlingActor}.
*/
static class JmsDisconnect extends AbstractWithOrigin implements DisconnectClient {
@Nullable private final javax.jms.Connection connection;
JmsDisconnect(@Nullable final ActorRef origin, @Nullable final javax.jms.Connection connection) {
super(origin);
this.connection = connection;
}
Optional<javax.jms.Connection> getConnection() {
return Optional.ofNullable(connection);
}
}
/**
* Response to {@code Connect} message from {@link JMSConnectionHandlingActor}.
*/
static class JmsConnected extends AbstractWithOrigin implements ClientConnected {
private final JmsConnection connection;
private final Session session;
private final List<ConsumerData> consumerList;
JmsConnected(@Nullable final ActorRef origin, final JmsConnection connection, final Session session,
final List<ConsumerData> consumerList) {
super(origin);
this.connection = connection;
this.session = session;
this.consumerList = consumerList;
}
}
/**
* Response to {@code Disconnect} message from {@link JMSConnectionHandlingActor}.
*/
static class JmsDisconnected extends AbstractWithOrigin implements ClientDisconnected {
JmsDisconnected(@Nullable final ActorRef origin) {
super(origin);
}
}
/**
* Listener updates connection status for metrics reporting. Do not alter actor state.
*/
private static final class StatusReportingListener implements JmsConnectionListener {
final ActorRef self;
final DiagnosticLoggingAdapter log;
final String connectionId;
final ConnectionLogger connectionLogger;
private StatusReportingListener(final ActorRef self, final String connectionId,
final DiagnosticLoggingAdapter log, final ConnectionLogger connectionLogger) {
this.self = self;
this.connectionId = connectionId;
this.log = log;
this.connectionLogger = connectionLogger;
}
@Override
public void onConnectionEstablished(final URI remoteURI) {
log.info("Connection established: {}", remoteURI);
}
@Override
public void onConnectionFailure(final Throwable error) {
ConnectionLogUtil.enhanceLogWithConnectionId(log, connectionId);
connectionLogger.failure("Connection failure: {0}", error.getMessage());
log.warning("Connection Failure: {}", error.getMessage());
final ConnectionFailure failure =
new ImmutableConnectionFailure(ActorRef.noSender(), error, null);
self.tell(StatusReport.failure(failure), ActorRef.noSender());
}
@Override
public void onConnectionInterrupted(final URI remoteURI) {
ConnectionLogUtil.enhanceLogWithConnectionId(log, connectionId);
connectionLogger.failure("Connection was interrupted.");
log.warning("Connection interrupted: {}", remoteURI);
final ConnectionFailure failure =
new ImmutableConnectionFailure(ActorRef.noSender(), null, "JMS Interrupted");
self.tell(StatusReport.failure(failure), ActorRef.noSender());
}
@Override
public void onConnectionRestored(final URI remoteURI) {
ConnectionLogUtil.enhanceLogWithConnectionId(log, connectionId);
connectionLogger.success("Connection was restored.");
log.info("Connection restored: {}", remoteURI);
self.tell(StatusReport.connectionRestored(), ActorRef.noSender());
}
@Override
public void onInboundMessage(final JmsInboundMessageDispatch envelope) {
ConnectionLogUtil.enhanceLogWithConnectionId(log, connectionId);
log.debug("Inbound message: {}", envelope);
self.tell(StatusReport.consumedMessage(), ActorRef.noSender());
}
@Override
public void onSessionClosed(final Session session, final Throwable cause) {
ConnectionLogUtil.enhanceLogWithConnectionId(log, connectionId);
connectionLogger.failure("Session was closed: {0}", cause.getMessage());
log.warning("Session closed: {} - {}", session, cause.getMessage());
final ConnectionFailure failure =
new ImmutableConnectionFailure(ActorRef.noSender(), cause, "JMS Session closed");
self.tell(StatusReport.failure(failure), ActorRef.noSender());
}
@Override
public void onConsumerClosed(final MessageConsumer consumer, final Throwable cause) {
ConnectionLogUtil.enhanceLogWithConnectionId(log, connectionId);
connectionLogger.failure("Consumer {0} was closed: {1}", consumer.toString(), cause.getMessage());
log.warning("Consumer <{}> closed due to {}: {}", consumer.toString(),
cause.getClass().getSimpleName(), cause.getMessage());
self.tell(StatusReport.consumerClosed(consumer), ActorRef.noSender());
}
@Override
public void onProducerClosed(final MessageProducer producer, final Throwable cause) {
ConnectionLogUtil.enhanceLogWithConnectionId(log, connectionId);
connectionLogger.failure("Producer {0} was closed: {1}", producer.toString(), cause.getMessage());
log.warning("Producer <{}> closed due to {}: {}", producer, cause.getClass().getSimpleName(),
cause.getMessage());
self.tell(StatusReport.producerClosed(producer), ActorRef.noSender());
}
}
}