-
Notifications
You must be signed in to change notification settings - Fork 215
/
MqttClientActor.java
522 lines (459 loc) · 22.4 KB
/
MqttClientActor.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
/*
* Copyright (c) 2022 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.mqtt.hivemq;
import java.text.MessageFormat;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.eclipse.ditto.base.model.common.ConditionChecker;
import org.eclipse.ditto.base.model.headers.DittoHeaders;
import org.eclipse.ditto.connectivity.api.BaseClientState;
import org.eclipse.ditto.connectivity.model.Connection;
import org.eclipse.ditto.connectivity.model.signals.commands.modify.TestConnection;
import org.eclipse.ditto.connectivity.service.config.MqttConfig;
import org.eclipse.ditto.connectivity.service.messaging.BaseClientActor;
import org.eclipse.ditto.connectivity.service.messaging.BaseClientData;
import org.eclipse.ditto.connectivity.service.messaging.backoff.RetryTimeoutStrategy;
import org.eclipse.ditto.connectivity.service.messaging.internal.ClientConnected;
import org.eclipse.ditto.connectivity.service.messaging.internal.ClientDisconnected;
import org.eclipse.ditto.connectivity.service.messaging.mqtt.MqttSpecificConfig;
import org.eclipse.ditto.connectivity.service.messaging.mqtt.hivemq.client.ClientRole;
import org.eclipse.ditto.connectivity.service.messaging.mqtt.hivemq.client.GenericMqttClient;
import org.eclipse.ditto.connectivity.service.messaging.mqtt.hivemq.client.GenericMqttClientDisconnectedListener;
import org.eclipse.ditto.connectivity.service.messaging.mqtt.hivemq.client.GenericMqttClientFactory;
import org.eclipse.ditto.connectivity.service.messaging.mqtt.hivemq.client.HiveMqttClientProperties;
import org.eclipse.ditto.connectivity.service.messaging.mqtt.hivemq.client.NoMqttConnectionException;
import org.eclipse.ditto.connectivity.service.messaging.mqtt.hivemq.consuming.MqttConsumerActor;
import org.eclipse.ditto.connectivity.service.messaging.mqtt.hivemq.consuming.ReconnectConsumerClient;
import org.eclipse.ditto.connectivity.service.messaging.mqtt.hivemq.publishing.MqttPublisherActor;
import org.eclipse.ditto.connectivity.service.messaging.mqtt.hivemq.subscribing.MqttSubscriber;
import org.eclipse.ditto.connectivity.service.messaging.mqtt.hivemq.subscribing.SubscribeResult;
import com.hivemq.client.mqtt.MqttClientConfig;
import com.hivemq.client.mqtt.MqttClientState;
import com.hivemq.client.mqtt.datatypes.MqttClientIdentifier;
import com.hivemq.client.mqtt.lifecycle.MqttDisconnectSource;
import com.typesafe.config.Config;
import akka.NotUsed;
import akka.actor.ActorRef;
import akka.actor.PoisonPill;
import akka.actor.Props;
import akka.actor.Status;
import akka.japi.pf.FSMStateFunctionBuilder;
import akka.pattern.Patterns;
import akka.stream.javadsl.Keep;
import akka.stream.javadsl.Sink;
import akka.stream.javadsl.Source;
import scala.concurrent.ExecutionContextExecutor;
/**
* Actor for handling connection to an MQTT broker for protocol versions 3 or 5.
*/
public final class MqttClientActor extends BaseClientActor {
private final MqttConfig mqttConfig;
private final MqttSpecificConfig mqttSpecificConfig;
private final GenericMqttClientFactory genericMqttClientFactory;
@Nullable private GenericMqttClient genericMqttClient;
private final AtomicBoolean automaticReconnect;
@Nullable private ActorRef publishingActorRef;
private final List<ActorRef> mqttConsumerActorRefs;
@SuppressWarnings("unused") // called by reflection
private MqttClientActor(final Connection connection,
final ActorRef proxyActor,
final ActorRef connectionActor,
final DittoHeaders dittoHeaders,
final Config connectivityConfigOverwrites) {
this(connection, proxyActor, connectionActor, dittoHeaders, connectivityConfigOverwrites,
GenericMqttClientFactory.newInstance());
}
@SuppressWarnings("java:S1144")
private MqttClientActor(final Connection connection,
final ActorRef proxyActor,
final ActorRef connectionActor,
final DittoHeaders dittoHeaders,
final Config connectivityConfigOverwrites,
final GenericMqttClientFactory genericMqttClientFactory) {
super(connection, proxyActor, connectionActor, dittoHeaders, connectivityConfigOverwrites);
final var connectivityConfig = connectivityConfig();
final var connectionConfig = connectivityConfig.getConnectionConfig();
mqttConfig = connectionConfig.getMqttConfig();
mqttSpecificConfig = MqttSpecificConfig.fromConnection(connection, mqttConfig);
this.genericMqttClientFactory = genericMqttClientFactory;
genericMqttClient = null;
automaticReconnect = new AtomicBoolean(true);
publishingActorRef = null;
mqttConsumerActorRefs = new ArrayList<>();
}
/**
* Returns the {@code Props} for creating a {@code GenericMqttClientActor} with the specified arguments.
*
* @param mqttConnection the MQTT connection.
* @param proxyActor the actor used to send signals into the Ditto cluster.
* @param connectionActor the connection persistence actor which creates the returned client actor.
* @param dittoHeaders headers of the command that caused the returned client actor to be created.
* @param connectivityConfigOverwrites the overwrites of the connectivity config for the given connection.
* actor this props create.
* @return the Props.
* @throws NullPointerException if any argument is {@code null}.
*/
public static Props props(final Connection mqttConnection,
final ActorRef proxyActor,
final ActorRef connectionActor,
final DittoHeaders dittoHeaders,
final Config connectivityConfigOverwrites) {
return Props.create(MqttClientActor.class,
ConditionChecker.checkNotNull(mqttConnection, "mqttConnection"),
ConditionChecker.checkNotNull(proxyActor, "proxyActor"),
ConditionChecker.checkNotNull(connectionActor, "connectionActor"),
ConditionChecker.checkNotNull(dittoHeaders, "dittoHeaders"),
ConditionChecker.checkNotNull(connectivityConfigOverwrites, "connectivityConfigOverwrites"));
}
static Props props(final Connection mqttConnection,
final ActorRef proxyActor,
final ActorRef connectionActor,
final DittoHeaders dittoHeaders,
final Config connectivityConfigOverwrites,
final GenericMqttClientFactory genericMqttClientFactory) {
return Props.create(MqttClientActor.class,
ConditionChecker.checkNotNull(mqttConnection, "mqttConnection"),
ConditionChecker.checkNotNull(proxyActor, "proxyActor"),
ConditionChecker.checkNotNull(connectionActor, "connectionActor"),
ConditionChecker.checkNotNull(dittoHeaders, "dittoHeaders"),
ConditionChecker.checkNotNull(connectivityConfigOverwrites, "connectivityConfigOverwrites"),
ConditionChecker.checkNotNull(genericMqttClientFactory, "genericMqttClientFactory"));
}
@Override
protected FSMStateFunctionBuilder<BaseClientState, BaseClientData> inConnectingState() {
final FSMStateFunctionBuilder<BaseClientState, BaseClientData> result;
if (isReconnectForRedelivery()) {
result = super.inConnectingState()
.event(ReconnectConsumerClient.class, this::scheduleConsumerClientReconnect)
.eventEquals(Control.RECONNECT_CONSUMER_CLIENT, this::reconnectConsumerClient);
} else {
result = super.inConnectingState();
}
return result;
}
private boolean isReconnectForRedelivery() {
return mqttSpecificConfig.reconnectForRedelivery();
}
private State<BaseClientState, BaseClientData> scheduleConsumerClientReconnect(
final ReconnectConsumerClient reconnectConsumerClient,
final BaseClientData baseClientData
) {
final var trigger = Control.RECONNECT_CONSUMER_CLIENT;
if (isTimerActive(trigger.name())) {
logger.debug("Timer <{}> is active, thus not scheduling reconnecting consumer client again.",
trigger.name());
} else {
final var reconnectForRedeliveryDelay = reconnectConsumerClient.getReconnectDelay();
logger.info("Scheduling reconnecting of consumer client in <{}>.", reconnectForRedeliveryDelay);
startSingleTimer(trigger.name(), trigger, reconnectForRedeliveryDelay.getDuration());
}
return stay();
}
private State<BaseClientState, BaseClientData> reconnectConsumerClient(final Control control,
final BaseClientData baseClientData) {
if (null != genericMqttClient) {
enableAutomaticReconnect();
genericMqttClient.disconnectClientRole(ClientRole.CONSUMER);
}
return stay();
}
@Override
protected FSMStateFunctionBuilder<BaseClientState, BaseClientData> inConnectedState() {
final FSMStateFunctionBuilder<BaseClientState, BaseClientData> result;
if (isReconnectForRedelivery()) {
result = super.inConnectedState()
.event(ReconnectConsumerClient.class, this::scheduleConsumerClientReconnect)
.eventEquals(Control.RECONNECT_CONSUMER_CLIENT, this::reconnectConsumerClient);
} else {
result = super.inConnectedState();
}
return result;
}
@Override
protected CompletionStage<Status.Status> doTestConnection(final TestConnection testConnectionCmd) {
final var connectionTesterActorRef = childActorNanny.startChildActorConflictFree(
ConnectionTesterActor.class.getSimpleName(),
ConnectionTesterActor.props(connectivityConfig(),
this::getSshTunnelState,
connectionLogger,
actorUuid,
connectivityStatusResolver,
genericMqttClientFactory)
);
return Patterns.ask(connectionTesterActorRef, testConnectionCmd, ConnectionTesterActor.ASK_TIMEOUT)
.handle((response, throwable) -> {
final Status.Status result;
if (null == throwable) {
result = new Status.Success(response);
} else if (throwable instanceof CompletionException completionException) {
result = new Status.Failure(completionException.getCause());
} else {
result = new Status.Failure(throwable);
}
return result;
})
.whenComplete((status, error) -> connectionTesterActorRef.tell(PoisonPill.getInstance(), getSelf()));
}
@Override
protected void cleanupResourcesForConnection() {
mqttConsumerActorRefs.forEach(this::stopChildActor);
stopChildActor(publishingActorRef);
if (null != genericMqttClient) {
disableAutomaticReconnect();
genericMqttClient.disconnect();
}
genericMqttClient = null;
publishingActorRef = null;
mqttConsumerActorRefs.clear();
}
private void disableAutomaticReconnect() {
automaticReconnect.set(false);
}
@Override
protected void doConnectClient(final Connection connection, @Nullable final ActorRef origin) {
if (null == genericMqttClient) {
genericMqttClient =
genericMqttClientFactory.getGenericMqttClient(getHiveMqttClientPropertiesOrThrow(connection));
enableAutomaticReconnect();
}
Patterns.pipe(
genericMqttClient.connect().thenApply(aVoid -> MqttClientConnected.of(origin)),
getContextDispatcher()
).to(getSelf());
}
private HiveMqttClientProperties getHiveMqttClientPropertiesOrThrow(final Connection connection) {
try {
return HiveMqttClientProperties.builder()
.withMqttConnection(connection)
.withConnectivityConfig(connectivityConfig())
.withMqttSpecificConfig(mqttSpecificConfig)
.withSshTunnelStateSupplier(this::getSshTunnelState)
.withConnectionLogger(connectionLogger)
.withActorUuid(actorUuid)
.withClientConnectedListener((context, clientRole) -> logger.info("Connected client <{}>.",
getClientId(clientRole, getMqttClientIdentifierOrNull(context.getClientConfig()))))
.withClientDisconnectedListener(getClientDisconnectedListener())
.build();
} catch (final NoMqttConnectionException e) {
// Let the supervisor strategy take care. Should not happen anyway.
throw new IllegalArgumentException(e);
}
}
@Nullable
private static MqttClientIdentifier getMqttClientIdentifierOrNull(final MqttClientConfig mqttClientConfig) {
return mqttClientConfig.getClientIdentifier().orElse(null);
}
private static String getClientId(final ClientRole clientRole,
@Nullable final MqttClientIdentifier mqttClientIdentifier) {
return MessageFormat.format("{0}:{1}", clientRole, mqttClientIdentifier);
}
private GenericMqttClientDisconnectedListener getClientDisconnectedListener() {
return (context, clientRole) -> {
final var mqttClientReconnector = context.getReconnector();
final var retryTimeoutStrategy = getRetryTimeoutStrategy();
if (0 == mqttClientReconnector.getAttempts()) {
retryTimeoutStrategy.reset();
}
final var clientId = getClientId(clientRole, getMqttClientIdentifierOrNull(context.getClientConfig()));
if (isMqttClientInConnectingState(context.getClientConfig())) {
/*
* If the client is in initial CONNECTING state (i.e. was never
* connected, not reconnecting), we disable the automatic
* reconnect because the client would continue to connect and
* the caller would never see the cause why the connection
* failed.
*/
logger.info("Initial connect of client <{}> failed. Disabling automatic reconnect.", clientId);
mqttClientReconnector.reconnect(false);
} else {
final var mqttDisconnectSource = context.getSource();
final var reconnect = isReconnect();
final var reconnectDelay = getReconnectDelay(retryTimeoutStrategy, mqttDisconnectSource);
logger.info("Client <{}> disconnected by <{}>.", clientId, mqttDisconnectSource);
if (reconnect) {
logger.info("Reconnecting client <{}> with current tries <{}> and a delay of <{}>.",
clientId,
retryTimeoutStrategy.getCurrentTries(),
reconnectDelay);
} else {
logger.info("Not reconnecting client <{}>.", clientId);
}
mqttClientReconnector.delay(reconnectDelay.toMillis(), TimeUnit.MILLISECONDS);
mqttClientReconnector.reconnect(reconnect);
}
};
}
private RetryTimeoutStrategy getRetryTimeoutStrategy() {
final var reconnectBackOffConfig = mqttConfig.getReconnectBackOffConfig();
return RetryTimeoutStrategy.newDuplicationRetryTimeoutStrategy(reconnectBackOffConfig.getTimeoutConfig());
}
private static boolean isMqttClientInConnectingState(final MqttClientConfig mqttClientConfig) {
return MqttClientState.CONNECTING == mqttClientConfig.getState();
}
private boolean isReconnect() {
final var connection = connection();
return connection.isFailoverEnabled() && automaticReconnect.get();
}
private Duration getReconnectDelay(final RetryTimeoutStrategy retryTimeoutStrategy,
final MqttDisconnectSource mqttDisconnectSource) {
final Duration result;
final var retryTimeoutReconnectDelay = retryTimeoutStrategy.getNextTimeout();
if (MqttDisconnectSource.SERVER == mqttDisconnectSource) {
final var reconnectDelayForBrokerInitiatedDisconnect =
mqttConfig.getReconnectMinTimeoutForMqttBrokerInitiatedDisconnect();
if (0 <= retryTimeoutReconnectDelay.compareTo(reconnectDelayForBrokerInitiatedDisconnect)) {
result = retryTimeoutReconnectDelay;
} else {
result = reconnectDelayForBrokerInitiatedDisconnect;
}
} else {
result = retryTimeoutReconnectDelay;
}
return result;
}
private void enableAutomaticReconnect() {
automaticReconnect.set(true);
}
private ExecutionContextExecutor getContextDispatcher() {
final var actorContext = getContext();
return actorContext.getDispatcher();
}
@Override
protected void doDisconnectClient(final Connection connection,
@Nullable final ActorRef origin,
final boolean shutdownAfterDisconnect) {
final CompletionStage<Void> disconnectFuture;
if (null == genericMqttClient) {
disconnectFuture = CompletableFuture.completedFuture(null);
} else {
disableAutomaticReconnect();
disconnectFuture = genericMqttClient.disconnect();
}
Patterns.pipe(
disconnectFuture.handle((aVoid, throwable) -> ClientDisconnected.of(origin, shutdownAfterDisconnect)),
getContextDispatcher()
).to(getSelf(), origin);
}
@Nullable
@Override
protected ActorRef getPublisherActor() {
return publishingActorRef;
}
@Override
protected CompletionStage<Status.Status> startPublisherActor() {
final CompletionStage<Status.Status> result;
if (null != genericMqttClient) {
publishingActorRef = startChildActorConflictFree(
MqttPublisherActor.class.getSimpleName(),
MqttPublisherActor.propsProcessing(connection(),
connectivityStatusResolver,
connectivityConfig(),
genericMqttClient)
);
result = CompletableFuture.completedFuture(DONE);
} else {
result = CompletableFuture.failedFuture(
new IllegalStateException("Cannot start publisher actor because generic MQTT client is null.")
);
}
return result;
}
@Override
protected CompletionStage<Status.Status> startConsumerActors(@Nullable final ClientConnected clientConnected) {
return subscribe()
.thenCompose(this::handleSourceSubscribeResults)
.thenApply(actorRefs -> {
mqttConsumerActorRefs.addAll(actorRefs);
return DONE;
});
}
private CompletionStage<Source<SubscribeResult, NotUsed>> subscribe() {
final CompletionStage<Source<SubscribeResult, NotUsed>> result;
if (null != genericMqttClient) {
final var subscriber = MqttSubscriber.newInstance(genericMqttClient);
result = CompletableFuture.completedFuture(
subscriber.subscribeForConnectionSources(connection().getSources())
);
} else {
result = CompletableFuture.failedFuture(new IllegalStateException(
"Cannot subscribe for connection sources as generic MQTT client is not yet initialised."
));
}
return result;
}
private CompletionStage<List<ActorRef>> handleSourceSubscribeResults(
final Source<SubscribeResult, NotUsed> sourceSubscribeResults
) {
return sourceSubscribeResults.map(this::startMqttConsumerActorOrThrow)
.toMat(Sink.seq(), Keep.right())
.run(getContext().getSystem());
}
private ActorRef startMqttConsumerActorOrThrow(final SubscribeResult subscribeResult) {
if (subscribeResult.isSuccess()) {
return startChildActorConflictFree(
MqttConsumerActor.class.getSimpleName(),
MqttConsumerActor.propsProcessing(connection(),
getInboundMappingSink(),
subscribeResult.getConnectionSource(),
connectivityStatusResolver,
connectivityConfig(),
subscribeResult.getMqttPublishSourceOrThrow())
);
} else {
throw subscribeResult.getErrorOrThrow();
}
}
/*
* For MQTT connections only one consumer actor for all addresses is started,
* i.e. one consumer actor per connection source.
*/
@Override
protected int determineNumberOfConsumers() {
return connectionSources()
.mapToInt(org.eclipse.ditto.connectivity.model.Source::getConsumerCount)
.sum();
}
private Stream<org.eclipse.ditto.connectivity.model.Source> connectionSources() {
return connection().getSources().stream();
}
/*
* For MQTT connections only one Consumer Actor for all addresses is started,
* i.e. one consumer actor per connection source.
*/
@Override
protected Stream<String> getSourceAddresses() {
return connectionSources()
.map(org.eclipse.ditto.connectivity.model.Source::getAddresses)
.map(sourceAddresses -> String.join(";", sourceAddresses));
}
@Override
public void postStop() {
logger.info("Actor stopped, stopping clients.");
if (null != genericMqttClient) {
disableAutomaticReconnect();
genericMqttClient.disconnect();
}
super.postStop();
}
private enum Control {
RECONNECT_CONSUMER_CLIENT
}
}