-
Notifications
You must be signed in to change notification settings - Fork 214
/
BaseClientActor.java
2426 lines (2124 loc) · 114 KB
/
BaseClientActor.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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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;
import static org.eclipse.ditto.base.model.common.ConditionChecker.checkArgument;
import static org.eclipse.ditto.base.model.common.ConditionChecker.checkNotNull;
import static org.eclipse.ditto.connectivity.api.BaseClientState.CONNECTED;
import static org.eclipse.ditto.connectivity.api.BaseClientState.CONNECTING;
import static org.eclipse.ditto.connectivity.api.BaseClientState.DISCONNECTED;
import static org.eclipse.ditto.connectivity.api.BaseClientState.DISCONNECTING;
import static org.eclipse.ditto.connectivity.api.BaseClientState.INITIALIZED;
import static org.eclipse.ditto.connectivity.api.BaseClientState.TESTING;
import static org.eclipse.ditto.connectivity.api.BaseClientState.UNKNOWN;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import javax.annotation.Nullable;
import org.eclipse.ditto.base.model.acks.AcknowledgementLabel;
import org.eclipse.ditto.base.model.acks.FatalPubSubException;
import org.eclipse.ditto.base.model.acks.PubSubTerminatedException;
import org.eclipse.ditto.base.model.auth.AuthorizationContext;
import org.eclipse.ditto.base.model.entity.id.EntityId;
import org.eclipse.ditto.base.model.entity.id.WithEntityId;
import org.eclipse.ditto.base.model.exceptions.DittoRuntimeException;
import org.eclipse.ditto.base.model.headers.DittoHeaders;
import org.eclipse.ditto.base.model.headers.WithDittoHeaders;
import org.eclipse.ditto.base.model.signals.Signal;
import org.eclipse.ditto.base.model.signals.WithStreamingSubscriptionId;
import org.eclipse.ditto.base.model.signals.WithType;
import org.eclipse.ditto.base.model.signals.commands.streaming.StreamingSubscriptionCommand;
import org.eclipse.ditto.connectivity.api.BaseClientState;
import org.eclipse.ditto.connectivity.api.InboundSignal;
import org.eclipse.ditto.connectivity.api.OutboundSignal;
import org.eclipse.ditto.connectivity.api.messaging.monitoring.logs.LogEntryFactory;
import org.eclipse.ditto.connectivity.model.Connection;
import org.eclipse.ditto.connectivity.model.ConnectionId;
import org.eclipse.ditto.connectivity.model.ConnectivityModelFactory;
import org.eclipse.ditto.connectivity.model.ConnectivityStatus;
import org.eclipse.ditto.connectivity.model.FilteredTopic;
import org.eclipse.ditto.connectivity.model.RecoveryStatus;
import org.eclipse.ditto.connectivity.model.ResourceStatus;
import org.eclipse.ditto.connectivity.model.Source;
import org.eclipse.ditto.connectivity.model.SshTunnel;
import org.eclipse.ditto.connectivity.model.Target;
import org.eclipse.ditto.connectivity.model.Topic;
import org.eclipse.ditto.connectivity.model.signals.announcements.ConnectionClosedAnnouncement;
import org.eclipse.ditto.connectivity.model.signals.announcements.ConnectionOpenedAnnouncement;
import org.eclipse.ditto.connectivity.model.signals.commands.ConnectivityCommand;
import org.eclipse.ditto.connectivity.model.signals.commands.exceptions.ConnectionFailedException;
import org.eclipse.ditto.connectivity.model.signals.commands.exceptions.ConnectionSignalIllegalException;
import org.eclipse.ditto.connectivity.model.signals.commands.modify.CheckConnectionLogsActive;
import org.eclipse.ditto.connectivity.model.signals.commands.modify.CloseConnection;
import org.eclipse.ditto.connectivity.model.signals.commands.modify.CreateConnection;
import org.eclipse.ditto.connectivity.model.signals.commands.modify.EnableConnectionLogs;
import org.eclipse.ditto.connectivity.model.signals.commands.modify.LoggingExpired;
import org.eclipse.ditto.connectivity.model.signals.commands.modify.OpenConnection;
import org.eclipse.ditto.connectivity.model.signals.commands.modify.ResetConnectionLogs;
import org.eclipse.ditto.connectivity.model.signals.commands.modify.ResetConnectionMetrics;
import org.eclipse.ditto.connectivity.model.signals.commands.modify.TestConnection;
import org.eclipse.ditto.connectivity.model.signals.commands.query.RetrieveConnectionLogs;
import org.eclipse.ditto.connectivity.model.signals.commands.query.RetrieveConnectionLogsResponse;
import org.eclipse.ditto.connectivity.model.signals.commands.query.RetrieveConnectionMetrics;
import org.eclipse.ditto.connectivity.model.signals.commands.query.RetrieveConnectionMetricsResponse;
import org.eclipse.ditto.connectivity.model.signals.commands.query.RetrieveConnectionStatus;
import org.eclipse.ditto.connectivity.service.config.ClientConfig;
import org.eclipse.ditto.connectivity.service.config.ConnectionThrottlingConfig;
import org.eclipse.ditto.connectivity.service.config.ConnectivityConfig;
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.internal.ConnectionFailure;
import org.eclipse.ditto.connectivity.service.messaging.internal.RetrieveAddressStatus;
import org.eclipse.ditto.connectivity.service.messaging.monitoring.logs.ConnectionLogger;
import org.eclipse.ditto.connectivity.service.messaging.monitoring.logs.ConnectionLoggerRegistry;
import org.eclipse.ditto.connectivity.service.messaging.monitoring.logs.InfoProviderFactory;
import org.eclipse.ditto.connectivity.service.messaging.monitoring.metrics.ConnectivityCounterRegistry;
import org.eclipse.ditto.connectivity.service.messaging.persistence.ConnectionPersistenceActor;
import org.eclipse.ditto.connectivity.service.messaging.tunnel.SshTunnelActor;
import org.eclipse.ditto.connectivity.service.messaging.tunnel.SshTunnelState;
import org.eclipse.ditto.connectivity.service.messaging.validation.ConnectionValidator;
import org.eclipse.ditto.connectivity.service.util.ConnectionPubSub;
import org.eclipse.ditto.connectivity.service.util.ConnectivityMdcEntryKey;
import org.eclipse.ditto.edge.service.headers.DittoHeadersValidator;
import org.eclipse.ditto.edge.service.streaming.StreamingSubscriptionManager;
import org.eclipse.ditto.internal.models.signal.correlation.MatchingValidationResult;
import org.eclipse.ditto.internal.utils.akka.logging.DittoLoggerFactory;
import org.eclipse.ditto.internal.utils.akka.logging.ThreadSafeDittoLoggingAdapter;
import org.eclipse.ditto.internal.utils.config.InstanceIdentifierSupplier;
import org.eclipse.ditto.internal.utils.config.ScopedConfig;
import org.eclipse.ditto.internal.utils.metrics.DittoMetrics;
import org.eclipse.ditto.internal.utils.metrics.instruments.gauge.Gauge;
import org.eclipse.ditto.internal.utils.protocol.ProtocolAdapterProvider;
import org.eclipse.ditto.internal.utils.pubsub.StreamingType;
import org.eclipse.ditto.internal.utils.pubsubthings.DittoProtocolSub;
import org.eclipse.ditto.internal.utils.search.SubscriptionManager;
import org.eclipse.ditto.protocol.adapter.ProtocolAdapter;
import org.eclipse.ditto.thingsearch.model.signals.commands.ThingSearchCommand;
import org.eclipse.ditto.thingsearch.model.signals.commands.WithSubscriptionId;
import com.typesafe.config.Config;
import akka.Done;
import akka.NotUsed;
import akka.actor.AbstractFSMWithStash;
import akka.actor.ActorRef;
import akka.actor.ActorSelection;
import akka.actor.ActorSystem;
import akka.actor.Cancellable;
import akka.actor.CoordinatedShutdown;
import akka.actor.FSM;
import akka.actor.OneForOneStrategy;
import akka.actor.Props;
import akka.actor.Status;
import akka.actor.SupervisorStrategy;
import akka.cluster.pubsub.DistributedPubSub;
import akka.japi.Pair;
import akka.japi.pf.DeciderBuilder;
import akka.japi.pf.FSMStateFunctionBuilder;
import akka.pattern.Patterns;
import akka.stream.Materializer;
import akka.stream.javadsl.Sink;
/**
* Base class for ClientActors which implement the connection handling for various connectivity protocols.
* <p>
* The actor expects to receive a {@link CreateConnection} command after it was started. If this command is not received
* within timeout (can be the case when this actor is remotely deployed after the command was sent) the actor requests
* the required information from ConnectionActor.
* </p>
*/
public abstract class BaseClientActor extends AbstractFSMWithStash<BaseClientState, BaseClientData> {
/**
* Common logger for all sub-classes of BaseClientActor as its MDC already contains the connection ID.
*/
protected final ThreadSafeDittoLoggingAdapter logger;
protected static final Status.Success DONE = new Status.Success(Done.getInstance());
protected final ConnectionLogger connectionLogger;
protected final ConnectivityStatusResolver connectivityStatusResolver;
private static final String CONNECTION_STATUS_DETAILS_CONNECTED = "CONNECTED";
/**
* The name of the dispatcher that will be used for async mapping.
*/
private static final String MESSAGE_MAPPING_PROCESSOR_DISPATCHER = "message-mapping-processor-dispatcher";
private static final Pattern EXCLUDED_ADDRESS_REPORTING_CHILD_NAME_PATTERN = Pattern.compile(
OutboundMappingProcessorActor.ACTOR_NAME + "|" + OutboundDispatchingActor.ACTOR_NAME + "|" +
"ackr.*" + "|" + "StreamSupervisor-.*|" +
SubscriptionManager.ACTOR_NAME + "|" + StreamingSubscriptionManager.ACTOR_NAME);
private static final String DITTO_STATE_TIMEOUT_TIMER = "dittoStateTimeout";
private static final int SOCKET_CHECK_TIMEOUT_MS = 2000;
private static final String CLOSED_BECAUSE_OF_UNKNOWN_FAILURE_MISCONFIGURATION_STATUS_IN_CLIENT =
"Closed because of unknown/failure/misconfiguration status in client.";
private final Connection connection;
private final ConnectivityConfig connectivityConfig;
private final ActorRef connectionActor;
private final ActorSelection commandForwarderActorSelection;
private final Gauge clientGauge;
private final Gauge clientConnectingGauge;
private final ReconnectTimeoutStrategy reconnectTimeoutStrategy;
private final SupervisorStrategy supervisorStrategy;
private final ConnectionPubSub connectionPubSub;
private final DittoProtocolSub dittoProtocolSub;
private final int subscriptionIdPrefixLength;
protected final UUID actorUuid;
private final ProtocolAdapter protocolAdapter;
protected final ConnectivityCounterRegistry connectionCounterRegistry;
protected final ConnectionLoggerRegistry connectionLoggerRegistry;
protected final ChildActorNanny childActorNanny;
private final DittoHeadersValidator dittoHeadersValidator;
private final boolean dryRun;
private final List<Cancellable> cancelOnStopTasks = new ArrayList<>();
private Sink<Object, NotUsed> inboundMappingSink;
private ActorRef outboundDispatchingActor;
private ActorRef subscriptionManager;
private ActorRef streamingSubscriptionManager;
private ActorRef tunnelActor;
private int ackregatorCount = 0;
private boolean shuttingDown = false;
protected BaseClientActor(final Connection connection,
final ActorRef commandForwarderActor,
final ActorRef connectionActor,
final DittoHeaders dittoHeaders,
final Config connectivityConfigOverwrites) {
this.connection = checkNotNull(connection, "connection");
final ActorSystem system = getContext().getSystem();
final Config config = system.settings().config();
final Config withOverwrites = connectivityConfigOverwrites.withFallback(config);
connectivityConfig = ConnectivityConfig.of(withOverwrites);
this.connectionActor = connectionActor;
// this is retrieve via the extension for each baseClientActor in order to not pass it as constructor arg
// as all constructor arguments need to be serializable as the BaseClientActor is started behind a cluster
// router
dittoProtocolSub = DittoProtocolSub.get(system);
actorUuid = UUID.randomUUID();
final var connectionId = connection.getId();
logger = DittoLoggerFactory.getThreadSafeDittoLoggingAdapter(this)
.withMdcEntry(ConnectivityMdcEntryKey.CONNECTION_ID, connection.getId());
// log the default client ID for tracing
logger.info("Using default client ID <{}>", getDefaultClientId());
commandForwarderActorSelection = getLocalActorOfSamePath(commandForwarderActor);
childActorNanny = ChildActorNanny.newInstance(getContext(), logger);
dittoHeadersValidator = DittoHeadersValidator.get(system, ScopedConfig.dittoExtension(config));
final UserIndicatedErrors userIndicatedErrors = UserIndicatedErrors.of(config);
connectivityStatusResolver = ConnectivityStatusResolver.of(userIndicatedErrors);
final ClientConfig clientConfig = connectivityConfig().getClientConfig();
final var protocolAdapterProvider =
ProtocolAdapterProvider.load(connectivityConfig().getProtocolConfig(), system);
protocolAdapter = protocolAdapterProvider.getProtocolAdapter(null);
final var monitoringConfig = connectivityConfig().getMonitoringConfig();
connectionCounterRegistry = ConnectivityCounterRegistry.newInstance(connectivityConfig);
connectionLoggerRegistry = ConnectionLoggerRegistry.fromConfig(monitoringConfig.logger());
connectionLoggerRegistry.initForConnection(connection);
connectionLogger = connectionLoggerRegistry.forConnection(connection.getId());
connectionCounterRegistry.initForConnection(connection);
clientGauge = DittoMetrics.gauge("connection_client")
.tag("id", connectionId.toString())
.tag("type", connection.getConnectionType().getName());
clientConnectingGauge = DittoMetrics.gauge("connecting_client")
.tag("id", connectionId.toString())
.tag("type", connection.getConnectionType().getName());
reconnectTimeoutStrategy = DuplicationReconnectTimeoutStrategy.fromConfig(clientConfig);
supervisorStrategy = createSupervisorStrategy(getSelf());
connectionPubSub = ConnectionPubSub.get(system);
subscriptionIdPrefixLength =
ConnectionPersistenceActor.getSubscriptionPrefixLength(connection.getClientCount());
// Send init message to allow for unsafe initialization of subclasses.
dryRun = dittoHeaders.isDryRun();
}
@Override
public SupervisorStrategy supervisorStrategy() {
return supervisorStrategy;
}
@Override
public void preStart() throws Exception {
super.preStart();
// stable states
when(UNKNOWN, inUnknownState());
when(INITIALIZED, inInitializedState());
when(CONNECTED, inConnectedState());
when(DISCONNECTED, inDisconnectedState());
// volatile states
//
// DO NOT use state timeout:
// FSM state timeout gets reset by any message, AND cannot be longer than 5 minutes (Akka v2.5.23).
when(DISCONNECTING, inDisconnectingState());
when(CONNECTING, inConnectingState());
when(TESTING, inTestingState());
// start with UNKNOWN state but send self OpenConnection because client actors are never created closed
final var startingData = BaseClientData.BaseClientDataBuilder.initialized(connection).build();
startWith(UNKNOWN, startingData);
onTransition(this::onTransition);
whenUnhandled(inAnyState().anyEvent(this::onUnknownEvent));
initialize();
// register this client actor at connection pub-sub
registerConnectionPubSub();
addCoordinatedShutdownTasks();
init();
}
protected ConnectivityConfig connectivityConfig() {
return connectivityConfig;
}
/**
* Initialize child actors.
*/
protected void init() {
final var actorPair = startOutboundActors(protocolAdapter);
outboundDispatchingActor = actorPair.first();
final var inboundDispatchingSink = getInboundDispatchingSink(actorPair.second());
inboundMappingSink = getInboundMappingSink(protocolAdapter, inboundDispatchingSink);
subscriptionManager =
startSubscriptionManager(commandForwarderActorSelection, connectivityConfig().getClientConfig());
streamingSubscriptionManager = startStreamingSubscriptionManager(commandForwarderActorSelection, connectivityConfig().getClientConfig());
if (connection.getSshTunnel().map(SshTunnel::isEnabled).orElse(false)) {
tunnelActor = childActorNanny.startChildActor(SshTunnelActor.ACTOR_NAME,
SshTunnelActor.props(connection, connectivityStatusResolver, connectionLogger));
} else {
tunnelActor = null;
}
getSelf().tell(Control.INIT_COMPLETE, ActorRef.noSender());
}
private void registerConnectionPubSub() {
if (dryRun) {
// no need to modify distributed data if it is a dry run
return;
}
final var connectionId = connection.getId();
connectionPubSub.subscribe(connectionId, getSelf(), false).whenComplete((consistent, error) -> {
if (error != null) {
logger.error(error, "Failed to register client actor for connection <{}>", connectionId);
} else {
logger.info("Client actor registered: <{}>", connectionId);
}
});
}
private void addCoordinatedShutdownTasks() {
final var system = getContext().getSystem();
final var coordinatedShutdown = CoordinatedShutdown.get(system);
if (shouldAnyTargetSendConnectionAnnouncements()) {
// only add clients of connections to Coordinated shutdown having connection announcements configured
coordinatedShutdown.addActorTerminationTask(
CoordinatedShutdown.PhaseServiceRequestsDone(),
"closeConnectionAndShutdown",
getSelf(),
Optional.of(CloseConnectionAndShutdown.INSTANCE)
);
}
final var id = getSelf().path().toString();
cancelOnStopTasks.add(coordinatedShutdown.addCancellableTask(CoordinatedShutdown.PhaseServiceUnbind(),
"service-unbind-" + id, askSelfShutdownTask(Control.SERVICE_UNBIND)));
coordinatedShutdown.addActorTerminationTask(CoordinatedShutdown.PhaseServiceRequestsDone(),
"service-requests-done" + id, getSelf(), Optional.of(Control.SERVICE_REQUESTS_DONE));
}
private boolean shouldAnyTargetSendConnectionAnnouncements() {
return connection().getTargets().stream()
.anyMatch(target -> target.getTopics().stream()
.map(FilteredTopic::getTopic)
.anyMatch(Topic.CONNECTION_ANNOUNCEMENTS::equals));
}
@Override
public void postStop() {
cancelOnStopTasks.forEach(Cancellable::cancel);
clientGauge.reset();
clientConnectingGauge.reset();
stopChildActor(tunnelActor);
logger.debug("Stopped client with id - <{}>", getDefaultClientId());
try {
connectionLogger.close();
} catch (final IOException e) {
logger.warning("Exception during closing connection logger <{}>: {}", e.getClass().getSimpleName(),
e.getMessage());
}
try {
super.postStop();
} catch (final Exception e) {
logger.error(e, "An error occurred post stop.");
}
}
/**
* Compute the client ID for this actor. The format of the client ID is prefix-uuid, where the uuid is unique to
* each incarnation of this actor.
*
* @param prefix the prefix.
* @return the client ID.
*/
protected String getClientId(final CharSequence prefix) {
if (connection.getClientCount() == 1) {
return prefix.toString();
} else {
return prefix + "_" + actorUuid;
}
}
/**
* Get the default client ID, which identifies this actor regardless of configuration.
*
* @return the default client ID.
*/
protected String getDefaultClientId() {
return getClientId(connection.getId());
}
private FSM.State<BaseClientState, BaseClientData> completeInitialization() {
final State<BaseClientState, BaseClientData> state = goTo(INITIALIZED);
// Always open connection right away when desired---this actor may be deployed onto other instances and
// will not be directly controlled by the connection persistence actor.
if (connection.getConnectionStatus() == ConnectivityStatus.OPEN) {
getSelf().tell(OpenConnection.of(connection.getId(), DittoHeaders.empty()), getSelf());
}
unstashAll();
return state;
}
/**
* Handles {@link TestConnection} commands by returning a CompletionState of {@link akka.actor.Status.Status Status}
* which may be {@link akka.actor.Status.Success Success} or {@link akka.actor.Status.Failure Failure}.
*
* @param testConnectionCommand the Connection to test
* @return the CompletionStage with the test result
*/
protected abstract CompletionStage<Status.Status> doTestConnection(TestConnection testConnectionCommand);
/**
* Stop consuming messages from the connection.
*
* @return the CompletionStage that completes or fails according to whether consumer disconnection is successful.
*/
protected abstract CompletionStage<Void> stopConsuming();
/**
* Subclasses should allocate resources (publishers and consumers) in the implementation. This method is called once
* this {@code Client} connected successfully.
*
* @param clientConnected the ClientConnected message which may be subclassed and thus adding more information
*/
protected void allocateResourcesOnConnection(final ClientConnected clientConnected) {
// do nothing by default
}
/**
* Clean up everything spawned in {@code allocateResourcesOnConnection}. It should be idempotent.
*/
protected abstract void cleanupResourcesForConnection();
/**
* Invoked when this {@code Client} should connect.
*
* @param connection the Connection to use for connecting.
* @param origin the ActorRef which caused the ConnectClient command.
*/
protected abstract void doConnectClient(Connection connection, @Nullable ActorRef origin);
/**
* Invoked when this {@code Client} should disconnect.
*
* @param connection the Connection to use for disconnecting.
* @param origin the ActorRef which caused the DisconnectClient command.
* @param shutdownAfterDisconnect whether the base client actor should terminate itself after disconnection.
*/
protected abstract void doDisconnectClient(Connection connection, @Nullable ActorRef origin,
final boolean shutdownAfterDisconnect);
/**
* Release any temporary resources allocated during a connection operation when the operation times out. Do nothing
* by default.
*
* @param state current state of the client actor.
*/
protected void cleanupFurtherResourcesOnConnectionTimeout(final BaseClientState state) {
// do nothing by default
}
/**
* Creates the handler for messages common to all states.
* <p>
* Overwrite and extend by additional matchers.
* </p>
*
* @return an FSM function builder
*/
protected FSMStateFunctionBuilder<BaseClientState, BaseClientData> inAnyState() {
return matchEvent(RetrieveConnectionMetrics.class, (command, data) -> retrieveConnectionMetrics(command))
.event(StreamingSubscriptionCommand.class, this::forwardStreamingSubscriptionCommand)
.event(ThingSearchCommand.class, this::forwardThingSearchCommand)
.event(RetrieveConnectionStatus.class, this::retrieveConnectionStatus)
.event(ResetConnectionMetrics.class, this::resetConnectionMetrics)
.event(EnableConnectionLogs.class, (command, data) -> enableConnectionLogs(command))
.event(RetrieveConnectionLogs.class, (command, data) -> retrieveConnectionLogs(command))
.event(ResetConnectionLogs.class, this::resetConnectionLogs)
.event(CheckConnectionLogsActive.class, (command, data) -> checkLoggingActive(command))
.event(InboundSignal.class, (signal, d) -> signal.isDispatched(), this::handleDispatchedInboundSignal)
.event(InboundSignal.class, this::handleInboundSignal)
.event(PublishMappedMessage.class, this::publishMappedMessage)
.event(ConnectivityCommand.class, this::onUnknownEvent) // relevant connectivity commands were handled
.event(Signal.class, this::handleSignal)
.event(FatalPubSubException.class, this::failConnectionDueToPubSubException)
.eventEquals(Control.ACKREGATOR_STARTED, this::ackregatorStarted)
.eventEquals(Control.ACKREGATOR_STOPPED, this::ackregatorStopped)
.eventEquals(Control.SERVICE_REQUESTS_DONE, this::serviceRequestsDone)
.eventEquals(Control.SHUTDOWN_TIMEOUT, this::shutdownTimeout);
}
/**
* @return the inbound mapping sink defined by {@link InboundMappingSink}.
*/
protected final Sink<Object, NotUsed> getInboundMappingSink() {
return inboundMappingSink;
}
/**
* Escapes the passed actorName in a actorName valid way. Actor name should be a valid URL with ASCII letters, see
* also {@code akka.actor.ActorPath#isValidPathElement}, therefore we encode the name as an ASCII URL.
*
* @param name the actorName to escape.
* @return the escaped name.
*/
protected static String escapeActorName(final String name) {
return URLEncoder.encode(name, StandardCharsets.US_ASCII);
}
private FSM.State<BaseClientState, BaseClientData> failConnectionDueToPubSubException(
final FatalPubSubException exception,
final BaseClientData data) {
final boolean isPubSubTerminated = exception instanceof PubSubTerminatedException;
if (isPubSubTerminated && stateName() != CONNECTED) {
// Do not fail connection on abnormal termination of any pubsub actor while not in connected state.
// Each surviving pubsub actor will send an error. It suffices to react to the first error.
logger.error(exception.asDittoRuntimeException(), "BugAlert Bug found in Ditto pubsub");
} else {
final String description = "The connection experienced a transient failure in the distributed " +
"publish/subscribe infrastructure. Failing the connection to try again later.";
getSelf().tell(
// not setting "cause" to put the description literally in the error log
ConnectionFailure.internal(null, exception.asDittoRuntimeException(), description),
getSelf());
}
return stay();
}
/**
* Start a child actor whose name is guaranteed to be different from all other child actors started by this method.
*
* @param prefix prefix of the child actor name.
* @param props props of the child actor.
* @return the created ActorRef.
*/
protected final ActorRef startChildActorConflictFree(final CharSequence prefix, final Props props) {
return childActorNanny.startChildActorConflictFree(prefix, props);
}
/**
* Stops a child actor.
*
* @param actor the ActorRef
*/
protected final void stopChildActor(@Nullable final ActorRef actor) {
if (null != actor) {
childActorNanny.stopChildActor(actor);
}
}
/**
* @return whether this client is consuming at all
*/
protected final boolean isConsuming() {
return !connection().getSources().isEmpty();
}
/**
* @return the currently managed Connection
*/
protected final Connection connection() {
return stateData().getConnection();
}
/**
* @return the Connection Id
*/
protected final ConnectionId connectionId() {
return stateData().getConnectionId();
}
/**
* @return the sources configured for this connection or an empty list if no sources were configured.
*/
protected final List<Source> getSourcesOrEmptyList() {
return connection().getSources();
}
/**
* Invoked on each transition {@code from} a {@link BaseClientState} {@code to} another.
* <p>
* May be extended to react on special transitions.
* </p>
*
* @param from the previous State
* @param to the next State
*/
private void onTransition(final BaseClientState from, final BaseClientState to) {
logger.debug("Transition: {} -> {}", from, to);
if (to == CONNECTED) {
clientGauge.set(1L);
reconnectTimeoutStrategy.reset();
publishConnectionOpenedAnnouncement();
}
if (to == DISCONNECTED) {
clientGauge.reset();
}
if (to == CONNECTING) {
clientConnectingGauge.set(1L);
}
// do not use else if since we might use goTo(CONNECTING) if in CONNECTING state. This will cause another onTransition.
if (from == CONNECTING) {
clientConnectingGauge.reset();
}
// cancel our own state timeout if target state is stable
if (to == CONNECTED || to == DISCONNECTED || to == INITIALIZED) {
cancelStateTimeout();
}
maintainResubscribeTimer(to);
}
private void publishConnectionOpenedAnnouncement() {
if (shouldAnyTargetSendConnectionAnnouncements()) {
getSelf().tell(ConnectionOpenedAnnouncement.of(connectionId(), Instant.now(), DittoHeaders.empty()),
getSelf());
}
}
/*
* For each volatile state, use the special goTo methods for timer management.
*/
private FSM.State<BaseClientState, BaseClientData> goToConnecting(final Duration timeout) {
scheduleStateTimeout(timeout);
return goTo(CONNECTING);
}
private FSM.State<BaseClientState, BaseClientData> goToDisconnecting(final Duration timeout) {
scheduleStateTimeout(timeout);
return goTo(DISCONNECTING);
}
private FSM.State<BaseClientState, BaseClientData> goToTesting() {
scheduleStateTimeout(connectivityConfig().getClientConfig().getTestingTimeout());
return goTo(TESTING);
}
private FSMStateFunctionBuilder<BaseClientState, BaseClientData> inUnknownState() {
return matchEventEquals(Control.INIT_COMPLETE, (init, baseClientData) -> completeInitialization())
.eventEquals(Control.SERVICE_UNBIND, this::serviceUnbindWhenDisconnected)
.event(RuntimeException.class, BaseClientActor::failInitialization)
.anyEvent((o, baseClientData) -> {
stash();
return stay();
});
}
private FSMStateFunctionBuilder<BaseClientState, BaseClientData> inInitializedState() {
return matchEvent(OpenConnection.class, this::openConnection)
.event(CloseConnection.class, this::closeConnection)
.event(CloseConnectionAndShutdown.class, this::closeConnectionAndShutdown)
.event(TestConnection.class, this::testConnection)
.eventEquals(Control.SERVICE_UNBIND, this::serviceUnbindWhenWaitingForCommand);
}
/**
* Creates the handler for messages in disconnected state. Overwrite and extend by additional matchers.
*
* @return an FSM function builder
*/
private FSMStateFunctionBuilder<BaseClientState, BaseClientData> inDisconnectedState() {
return matchEvent(OpenConnection.class, this::openConnection)
.event(CloseConnection.class, this::connectionAlreadyClosed)
.event(TestConnection.class, this::testConnection)
.eventEquals(Control.SERVICE_UNBIND, this::serviceUnbindWhenDisconnected);
}
/**
* Creates the handler for messages in connecting state. Overwrite and extend by additional matchers.
*
* @return an FSM function builder
*/
protected FSMStateFunctionBuilder<BaseClientState, BaseClientData> inConnectingState() {
return matchEventEquals(StateTimeout(), (event, data) -> connectionTimedOut(data))
.event(ConnectionFailure.class, this::connectingConnectionFailed)
.event(ClientConnected.class, this::clientConnectedInConnectingState)
.event(InitializationResult.class, this::handleInitializationResult)
.event(CloseConnection.class, this::closeConnection)
.event(CloseConnectionAndShutdown.class, this::closeConnectionAndShutdown)
.event(SshTunnelActor.TunnelStarted.class, this::tunnelStarted)
.eventEquals(Control.CONNECT_AFTER_TUNNEL_ESTABLISHED, this::connectAfterTunnelStarted)
.eventEquals(Control.GOTO_CONNECTED_AFTER_INITIALIZATION, this::gotoConnectedAfterInitialization)
.event(SshTunnelActor.TunnelClosed.class, this::tunnelClosed)
.event(OpenConnection.class, this::openConnectionInConnectingState)
.eventEquals(Control.SERVICE_UNBIND, this::serviceUnbindWhenDisconnected);
}
/**
* Creates the handler for messages in connected state. Overwrite and extend by additional matchers.
*
* @return an FSM function builder
*/
protected FSMStateFunctionBuilder<BaseClientState, BaseClientData> inConnectedState() {
return matchEvent(CloseConnection.class, this::closeConnection)
.event(CloseConnectionAndShutdown.class, this::closeConnectionAndShutdown)
.event(SshTunnelActor.TunnelClosed.class, this::tunnelClosed)
.event(OpenConnection.class, this::connectionAlreadyOpen)
.event(ConnectionFailure.class, this::connectedConnectionFailed)
.event(ReportConnectionStatusSuccess.class, this::updateConnectionStatusSuccess)
.event(ReportConnectionStatusError.class, this::updateConnectionStatusError)
.eventEquals(Control.RESUBSCRIBE, this::resubscribe)
.eventEquals(Control.SERVICE_UNBIND, this::serviceUnbindWhenConnected)
.eventEquals(SEND_DISCONNECT_ANNOUNCEMENT, (event, data) -> sendDisconnectAnnouncement(data));
}
private State<BaseClientState, BaseClientData> updateConnectionStatusSuccess(
final ReportConnectionStatusSuccess reportConnectionStatusSuccess,
BaseClientData baseClientData) {
BaseClientData nextClientData = baseClientData.setConnectionStatus(ConnectivityStatus.OPEN)
.setRecoveryStatus(RecoveryStatus.SUCCEEDED)
.setConnectionStatusDetails(CONNECTION_STATUS_DETAILS_CONNECTED)
.setInConnectionStatusSince(Instant.now());
return stay().using(nextClientData);
}
private State<BaseClientState, BaseClientData> updateConnectionStatusError(
final ReportConnectionStatusError reportConnectionStatus,
final BaseClientData baseClientData) {
BaseClientData nextClientData =
baseClientData.setConnectionStatus(connectivityStatusResolver.resolve(reportConnectionStatus.cause()))
.setRecoveryStatus(RecoveryStatus.ONGOING)
.setConnectionStatusDetails(
ConnectionFailure.determineFailureDescription(null, reportConnectionStatus.cause(),
null))
.setInConnectionStatusSince(Instant.now());
return stay().using(nextClientData);
}
@Nullable
protected abstract ActorRef getPublisherActor();
private FSM.State<BaseClientState, BaseClientData> publishMappedMessage(final PublishMappedMessage message,
final BaseClientData data) {
final var publisherActor = getPublisherActor();
final var outboundSignal = message.getOutboundSignal();
if (publisherActor != null) {
publisherActor.forward(outboundSignal, getContext());
} else {
logger.withCorrelationId(outboundSignal.getSource())
.error("No publisher actor available, dropping message: {}", message);
}
return stay();
}
/**
* Creates the handler for messages in disconnected state. Overwrite and extend by additional matchers.
*
* @return an FSM function builder
*/
private FSMStateFunctionBuilder<BaseClientState, BaseClientData> inDisconnectingState() {
return matchEventEquals(StateTimeout(), (event, data) -> connectionTimedOut(data))
.eventEquals(SEND_DISCONNECT_ANNOUNCEMENT, (event, data) -> sendDisconnectAnnouncement(data))
.eventEquals(Control.SERVICE_UNBIND, this::serviceUnbindWhenDisconnected)
.event(Disconnect.class, this::disconnect)
.event(ConnectionFailure.class, this::connectingConnectionFailed)
.event(ClientDisconnected.class, this::clientDisconnected);
}
/**
* Creates the handler for messages in testing state. Overwrite and extend by additional matchers.
*
* @return an FSM function builder
*/
protected FSMStateFunctionBuilder<BaseClientState, BaseClientData> inTestingState() {
return matchEvent(Status.Status.class, (e, d) -> Objects.equals(getSender(), getSelf()),
(status, data) -> {
logger.info("{} status: <{}>", stateName(), status);
data.getSessionSenders().forEach(sender ->
sender.first().tell(getStatusToReport(status, sender.second()), getSelf()));
return stop();
})
.event(SshTunnelActor.TunnelStarted.class, this::tunnelStarted)
.eventEquals(Control.CONNECT_AFTER_TUNNEL_ESTABLISHED, this::testConnectionAfterTunnelStarted)
.event(TestConnection.class, this::testConnection)
.event(SshTunnelActor.TunnelClosed.class, this::tunnelClosed)
.event(ConnectionFailure.class, this::testingConnectionFailed)
.eventEquals(StateTimeout(), (stats, data) -> {
logger.info("test timed out.");
data.getSessionSenders().forEach(sender -> {
final DittoRuntimeException error = ConnectionFailedException.newBuilder(connectionId())
.description(String.format("Failed to open requested connection within <%d> seconds!",
connectivityConfig()
.getClientConfig()
.getTestingTimeout()
.getSeconds()))
.dittoHeaders(sender.second())
.build();
sender.first().tell(new Status.Failure(error), getSelf());
});
return stop();
})
.eventEquals(Control.SERVICE_UNBIND, this::serviceUnbindWhenTesting);
}
private State<BaseClientState, BaseClientData> onUnknownEvent(final Object event, final BaseClientData state) {
Object message = event;
if (event instanceof Failure failure) {
message = failure.cause();
} else if (event instanceof Status.Failure statusFailure) {
message = statusFailure.cause();
}
if (message instanceof Throwable throwable) {
logger.warning(throwable, "received Exception {} in state {} - status: {} - sender: {}",
message,
stateName(),
state.getConnectionStatus() + ": " + state.getConnectionStatusDetails().orElse(""),
getSender());
} else {
logger.warning("received unknown/unsupported message {} in state {} - status: {} - sender: {}",
message,
stateName(),
state.getConnectionStatus() + ": " + state.getConnectionStatusDetails().orElse(""),
getSender());
}
final ActorRef sender = getSender();
if (!Objects.equals(sender, getSelf()) && !Objects.equals(sender, getContext().system().deadLetters())) {
sender.tell(unhandledExceptionForSignalInState(event, stateName()), getSelf());
}
return stay();
}
private static FSM.State<BaseClientState, BaseClientData> failInitialization(final RuntimeException error,
final BaseClientData data) {
// throw the error to trigger escalating supervision strategy
throw error;
}
private FSM.State<BaseClientState, BaseClientData> serviceUnbindWhenConnected(final Control serviceUnbind,
final BaseClientData data) {
log().info("ServiceUnbind State=<{}> unsubscribing from pubsub and stopping consumers", stateName());
final var dittoProtocolUnsub = dittoProtocolSub.removeSubscriber(getSelf(), getTargetAuthSubjects());
final var connectionUnsub = connectionPubSub.unsubscribe(connectionId(), getSelf());
final var stopConsumers = stopConsuming();
final var resultFuture = dittoProtocolUnsub.thenCompose(_void -> connectionUnsub)
.thenCompose(_void -> stopConsumers)
.handle((result, error) -> Done.getInstance());
Patterns.pipe(resultFuture, getContext().dispatcher()).to(getSender());
if (shouldAnyTargetSendConnectionAnnouncements()) {
getSelf().tell(SEND_DISCONNECT_ANNOUNCEMENT, getSender());
}
return stay();
}
private FSM.State<BaseClientState, BaseClientData> serviceUnbindWhenWaitingForCommand(final Control serviceUnbind,
final BaseClientData data) {
log().warning("ServiceUnbind waiting for command. Ongoing command is discarded.");
getSender().tell(Done.getInstance(), getSelf());
return stop();
}
private FSM.State<BaseClientState, BaseClientData> serviceUnbindWhenDisconnected(final Control serviceUnbind,
final BaseClientData data) {
log().info("ServiceUnbind State=<{}>", stateName());
getSender().tell(Done.getInstance(), getSelf());
return stop();
}
private FSM.State<BaseClientState, BaseClientData> serviceUnbindWhenTesting(final Control serviceUnbind,
final BaseClientData data) {
log().info("ServiceUnbind testing. Wait for ongoing test.");
getSender().tell(Done.getInstance(), getSelf());
return stay();
}
private FSM.State<BaseClientState, BaseClientData> closeConnectionAndShutdown(
final CloseConnectionAndShutdown closeConnectionAndShutdown,
final BaseClientData data) {
return closeConnection(CloseConnection.of(connectionId(), DittoHeaders.empty()), data, true);
}
private FSM.State<BaseClientState, BaseClientData> closeConnection(final WithDittoHeaders closeConnection,
final BaseClientData data) {
return closeConnection(closeConnection, data, false);
}
private FSM.State<BaseClientState, BaseClientData> closeConnection(final WithDittoHeaders closeConnection,
final BaseClientData data, final boolean shutdownAfterDisconnect) {
final ActorRef sender = getSender();
final Duration timeoutUntilDisconnectCompletes;
final ClientConfig clientConfig = connectivityConfig().getClientConfig();
if (shouldAnyTargetSendConnectionAnnouncements()) {
final Duration disconnectAnnouncementTimeout = clientConfig.getDisconnectAnnouncementTimeout();
timeoutUntilDisconnectCompletes =
clientConfig.getDisconnectingMaxTimeout().plus(disconnectAnnouncementTimeout);
getSelf().tell(SEND_DISCONNECT_ANNOUNCEMENT, sender);
startSingleTimer("startDisconnect", new Disconnect(sender, shutdownAfterDisconnect),
disconnectAnnouncementTimeout);
} else {
timeoutUntilDisconnectCompletes = clientConfig.getDisconnectingMaxTimeout();
getSelf().tell(new Disconnect(sender, shutdownAfterDisconnect), sender);
}
dittoProtocolSub.removeSubscriber(getSelf());
return goToDisconnecting(timeoutUntilDisconnectCompletes).using(
setSession(data, sender, closeConnection.getDittoHeaders())
.setDesiredConnectionStatus(ConnectivityStatus.CLOSED)
.setConnectionStatusDetails(
"cleaning up before closing or deleting connection at " + Instant.now()));
}
private State<BaseClientState, BaseClientData> sendDisconnectAnnouncement(final BaseClientData data) {
final var announcement =
ConnectionClosedAnnouncement.of(data.getConnectionId(), Instant.now(), DittoHeaders.empty());
// need to tell the announcement directly to the dispatching actor since the state == DISCONNECTING
outboundDispatchingActor.tell(announcement, getSender());
return stay();
}
private State<BaseClientState, BaseClientData> disconnect(final Disconnect disconnect, final BaseClientData data) {
doDisconnectClient(connection(), disconnect.getSender(), disconnect.shutdownAfterDisconnect());
return stay().using(data.setConnectionStatusDetails("disconnecting connection at " + Instant.now()));
}
private FSM.State<BaseClientState, BaseClientData> openConnection(final WithDittoHeaders openConnection,
final BaseClientData data) {
final ActorRef sender = getSender();
final var dittoHeaders = openConnection.getDittoHeaders();
reconnectTimeoutStrategy.reset();
final Duration connectingTimeout = connectivityConfig().getClientConfig().getConnectingMinTimeout();
if (stateData().getSshTunnelState().isEnabled()) {
logger.info("Connection requires SSH tunnel, starting tunnel.");
tellTunnelActor(SshTunnelActor.TunnelControl.START_TUNNEL);
return goToConnecting(connectingTimeout).using(setSession(data, sender, dittoHeaders));
} else {
return doOpenConnection(data, sender, dittoHeaders);
}
}
private FSM.State<BaseClientState, BaseClientData> doOpenConnection(final BaseClientData data,
final ActorRef sender, final DittoHeaders dittoHeaders) {
final Duration connectingTimeout = connectivityConfig().getClientConfig().getConnectingMinTimeout();
if (canConnectViaSocket(connection)) {
doConnectClient(connection, sender);
return goToConnecting(connectingTimeout).using(setSession(data, sender, dittoHeaders).resetFailureCount());
} else {
cleanupResourcesForConnection();
final DittoRuntimeException error = newConnectionFailedException(dittoHeaders);
sender.tell(new Status.Failure(error), getSelf());
return goToConnecting(connectingTimeout)
.using(data.resetSession()
.resetFailureCount()
.setConnectionStatus(ConnectivityStatus.MISCONFIGURED)
.setRecoveryStatus(RecoveryStatus.ONGOING)
.setConnectionStatusDetails(
ConnectionFailure.determineFailureDescription(Instant.now(), error, null))