-
Notifications
You must be signed in to change notification settings - Fork 215
/
ConnectionSupervisorActor.java
280 lines (243 loc) · 12.7 KB
/
ConnectionSupervisorActor.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
/*
* 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.persistence;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Objects;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import javax.jms.JMSRuntimeException;
import org.eclipse.ditto.base.model.exceptions.DittoRuntimeExceptionBuilder;
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.service.actors.ShutdownBehaviour;
import org.eclipse.ditto.base.service.config.supervision.ExponentialBackOffConfig;
import org.eclipse.ditto.connectivity.model.ConnectionId;
import org.eclipse.ditto.connectivity.model.signals.commands.ConnectivityCommand;
import org.eclipse.ditto.connectivity.model.signals.commands.exceptions.ConnectionUnavailableException;
import org.eclipse.ditto.connectivity.model.signals.commands.modify.LoggingExpired;
import org.eclipse.ditto.connectivity.service.config.ConnectionConfig;
import org.eclipse.ditto.connectivity.service.config.ConnectivityConfigModifiedBehavior;
import org.eclipse.ditto.connectivity.service.config.DittoConnectivityConfig;
import org.eclipse.ditto.connectivity.service.enforcement.ConnectionEnforcerActorPropsFactory;
import org.eclipse.ditto.internal.utils.config.DefaultScopedConfig;
import org.eclipse.ditto.internal.utils.persistentactors.AbstractPersistenceSupervisor;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import akka.actor.ActorKilledException;
import akka.actor.ActorRef;
import akka.actor.OneForOneStrategy;
import akka.actor.Props;
import akka.actor.SupervisorStrategy;
import akka.japi.pf.DeciderBuilder;
import akka.japi.pf.FI;
import akka.japi.pf.ReceiveBuilder;
import akka.pattern.Patterns;
/**
* Supervisor for {@link ConnectionPersistenceActor} which means it will create, start and watch it as child actor.
* <p>
* If the child terminates, it will wait for the calculated exponential back-off time and restart it afterwards.
* Between the termination of the child and the restart, this actor answers to all requests with a
* {@link ConnectionUnavailableException} as fail fast strategy.
* </p>
*/
public final class ConnectionSupervisorActor
extends AbstractPersistenceSupervisor<ConnectionId, ConnectivityCommand<?>>
implements ConnectivityConfigModifiedBehavior {
private static final Duration MAX_CONFIG_RETRIEVAL_DURATION = Duration.ofSeconds(5);
/**
* For connectivity, this local ask timeout has to be higher as e.g. "openConnection" commands performed in a
* "staged" way will lead to quite some response times.
*/
private static final Duration CONNECTIVITY_DEFAULT_LOCAL_ASK_TIMEOUT = Duration.ofSeconds(15);
private static final SupervisorStrategy SUPERVISOR_STRATEGY =
new OneForOneStrategy(true,
DeciderBuilder.match(JMSRuntimeException.class, e ->
(SupervisorStrategy.Directive) SupervisorStrategy.resume())
.build()
.orElse(SupervisorStrategy.stoppingStrategy().decider()));
private static final Duration OVERWRITES_CHECK_BACKOFF_DURATION = Duration.ofSeconds(30);
private final ActorRef commandForwarderActor;
private final ActorRef pubSubMediator;
private Config connectivityConfigOverwrites = ConfigFactory.empty();
private boolean isRegisteredForConnectivityConfigChanges = false;
private final ConnectionEnforcerActorPropsFactory enforcerActorPropsFactory;
@SuppressWarnings("unused")
private ConnectionSupervisorActor(final ActorRef commandForwarderActor, final ActorRef pubSubMediator,
final ConnectionEnforcerActorPropsFactory enforcerActorPropsFactory) {
super(null, CONNECTIVITY_DEFAULT_LOCAL_ASK_TIMEOUT);
this.commandForwarderActor = commandForwarderActor;
this.pubSubMediator = pubSubMediator;
this.enforcerActorPropsFactory = enforcerActorPropsFactory;
}
/**
* Props for creating a {@code ConnectionSupervisorActor}.
* <p>
* Exceptions in the child are handled with a supervision strategy that restarts the child on NullPointerExceptions,
* stops it for {@link ActorKilledException}'s and escalates all others.
* </p>
*
* @param commandForwarder the actor used to send signals into the ditto cluster.
* @param pubSubMediator pub-sub-mediator for the shutdown behavior.
* @param enforcerActorPropsFactory used to create the enforcer actor.
* @return the {@link Props} to create this actor.
*/
public static Props props(final ActorRef commandForwarder,
final ActorRef pubSubMediator,
final ConnectionEnforcerActorPropsFactory enforcerActorPropsFactory) {
return Props.create(ConnectionSupervisorActor.class, commandForwarder, pubSubMediator, enforcerActorPropsFactory);
}
@Override
protected ConnectionId getEntityId() throws Exception {
return ConnectionId.of(URLDecoder.decode(getSelf().path().name(), StandardCharsets.UTF_8.name()));
}
@Override
public Receive createReceive() {
return ReceiveBuilder.create()
.match(Config.class, config -> {
this.connectivityConfigOverwrites = config;
getSelf().tell(AbstractPersistenceSupervisor.Control.INIT_DONE, getSelf());
})
.build()
.orElse(super.createReceive());
}
@Override
protected Receive activeBehaviour(
final FI.UnitApply<AbstractPersistenceSupervisor.Control> matchProcessNextTwinMessageBehavior,
final FI.UnitApply<Object> matchAnyBehavior) {
return ReceiveBuilder.create()
.match(Config.class, this::onConnectivityConfigModified)
.match(CheckForOverwritesConfig.class,
checkForOverwrites -> initConfigOverwrites(getEntityId(), checkForOverwrites.dittoHeaders))
.matchEquals(Control.REGISTRATION_FOR_CONFIG_CHANGES_SUCCESSFUL, c -> {
log.debug("Successfully registered for connectivity config changes.");
isRegisteredForConnectivityConfigChanges = true;
})
.build()
.orElse(connectivityConfigModifiedBehavior())
.orElse(super.activeBehaviour(matchProcessNextTwinMessageBehavior, matchAnyBehavior));
}
@Override
protected boolean shouldBecomeTwinSignalProcessingAwaiting(final Signal<?> signal) {
return super.shouldBecomeTwinSignalProcessingAwaiting(signal) &&
!(signal instanceof LoggingExpired) // twin signal without a response
;
}
@Override
protected void handleMessagesDuringStartup(final Object message) {
if (message instanceof WithDittoHeaders withDittoHeaders) {
initConfigOverwrites(entityId, withDittoHeaders.getDittoHeaders());
} else if (message != Control.REGISTRATION_FOR_CONFIG_CHANGES_SUCCESSFUL) {
initConfigOverwrites(entityId, null);
}
super.handleMessagesDuringStartup(message);
}
@Override
protected Props getPersistenceActorProps(final ConnectionId entityId) {
return ConnectionPersistenceActor.props(entityId, commandForwarderActor, pubSubMediator,
connectivityConfigOverwrites, getContext().getSystem());
}
@Override
protected Props getPersistenceEnforcerProps(final ConnectionId connectionId) {
return enforcerActorPropsFactory.get(connectionId);
}
@Override
protected ExponentialBackOffConfig getExponentialBackOffConfig() {
final ConnectionConfig connectionConfig = DittoConnectivityConfig.of(
DefaultScopedConfig.dittoScoped(getContext().getSystem().settings().config())
).getConnectionConfig();
return connectionConfig.getSupervisorConfig().getExponentialBackOffConfig();
}
@Override
protected ShutdownBehaviour getShutdownBehaviour(final ConnectionId entityId) {
return ShutdownBehaviour.fromIdWithoutNamespace(entityId, pubSubMediator, getSelf());
}
@Override
protected DittoRuntimeExceptionBuilder<?> getUnavailableExceptionBuilder(@Nullable final ConnectionId entityId) {
final ConnectionId connectionId = entityId != null ? entityId : ConnectionId.of("UNKNOWN:ID");
return ConnectionUnavailableException.newBuilder(connectionId);
}
@Override
public SupervisorStrategy supervisorStrategy() {
return SUPERVISOR_STRATEGY;
}
@Override
public void onConnectivityConfigModified(final Config modifiedConfig) {
if (Objects.equals(connectivityConfigOverwrites, modifiedConfig)) {
log.debug("Received modified config is unchanged, not restarting persistence actor.");
} else {
log.info("Restarting persistence actor with modified config: {}", modifiedConfig);
restartPersistenceActorWithModifiedConfig(modifiedConfig);
}
}
@Override
protected boolean shouldStartChildImmediately() {
// do not start persistence actor immediately, wait for retrieval or timeout of connectivity config
return false;
}
private void restartPersistenceActorWithModifiedConfig(final Config connectivityConfigOverwrites) {
this.connectivityConfigOverwrites = connectivityConfigOverwrites;
restartChild();
}
private void initConfigOverwrites(final ConnectionId connectionId, @Nullable final DittoHeaders dittoHeaders) {
log.debug("Retrieve config overwrites for connection: {}", connectionId);
Patterns.pipe(retrieveConfigOverwritesOrTimeout(connectionId, dittoHeaders), getContext().getDispatcher())
.to(getSelf());
}
private CompletionStage<Config> retrieveConfigOverwritesOrTimeout(final ConnectionId connectionId,
@Nullable final DittoHeaders dittoHeaders) {
return getConnectivityConfigProvider()
.getConnectivityConfigOverwrites(connectionId, dittoHeaders)
.thenApply(config -> {
// try to register for connectivity changes after retrieval was successful and the actor is not
// yet registered
if (!isRegisteredForConnectivityConfigChanges) {
getConnectivityConfigProvider()
.registerForConnectivityConfigChanges(connectionId, dittoHeaders, getSelf())
.thenAccept(unused -> getSelf().tell(Control.REGISTRATION_FOR_CONFIG_CHANGES_SUCCESSFUL,
getSelf()));
}
return config;
})
.toCompletableFuture()
.orTimeout(MAX_CONFIG_RETRIEVAL_DURATION.toSeconds(), TimeUnit.SECONDS)
.exceptionally(e -> handleConfigRetrievalException(e, dittoHeaders));
}
private void triggerCheckForOverwritesConfig(@Nullable final DittoHeaders dittoHeaders) {
getTimers().startSingleTimer(CheckForOverwritesConfig.class, new CheckForOverwritesConfig(dittoHeaders),
OVERWRITES_CHECK_BACKOFF_DURATION);
}
private Config handleConfigRetrievalException(final Throwable throwable,
@Nullable final DittoHeaders dittoHeaders) {
// If not possible to retrieve overwrites in time, keep going with empty overwrites and potentially restart
// the actor later.
log.error(throwable,
"Could not retrieve overwrites within timeout of <{}>. Persistence actor is started anyway " +
"and retrieval of overwrites will be retried after <{}> potentially causing the actor to " +
"restart.", MAX_CONFIG_RETRIEVAL_DURATION, OVERWRITES_CHECK_BACKOFF_DURATION);
triggerCheckForOverwritesConfig(dittoHeaders);
return ConfigFactory.empty();
}
private enum Control {
REGISTRATION_FOR_CONFIG_CHANGES_SUCCESSFUL
}
private static class CheckForOverwritesConfig {
@Nullable private final DittoHeaders dittoHeaders;
private CheckForOverwritesConfig(@Nullable final DittoHeaders dittoHeaders) {
this.dittoHeaders = dittoHeaders;
}
}
}