/
ConciergeRootActor.java
267 lines (227 loc) · 12.4 KB
/
ConciergeRootActor.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
/*
* 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.concierge.starter.actors;
import static akka.http.javadsl.server.Directives.logRequest;
import static akka.http.javadsl.server.Directives.logResult;
import static java.util.Objects.requireNonNull;
import java.net.ConnectException;
import java.time.Duration;
import java.util.NoSuchElementException;
import java.util.concurrent.CompletionStage;
import org.eclipse.ditto.model.base.exceptions.DittoRuntimeException;
import org.eclipse.ditto.services.base.config.HealthConfigReader;
import org.eclipse.ditto.services.base.config.HttpConfigReader;
import org.eclipse.ditto.services.concierge.batch.actors.BatchSupervisorActor;
import org.eclipse.ditto.services.concierge.starter.proxy.AbstractEnforcerActorFactory;
import org.eclipse.ditto.services.concierge.util.config.AbstractConciergeConfigReader;
import org.eclipse.ditto.services.models.concierge.ConciergeMessagingConstants;
import org.eclipse.ditto.services.models.concierge.actors.ConciergeForwarderActor;
import org.eclipse.ditto.services.utils.akka.LogUtil;
import org.eclipse.ditto.services.utils.cluster.ClusterStatusSupplier;
import org.eclipse.ditto.services.utils.cluster.ClusterUtil;
import org.eclipse.ditto.services.utils.cluster.RetrieveStatisticsDetailsResponseSupplier;
import org.eclipse.ditto.services.utils.config.ConfigUtil;
import org.eclipse.ditto.services.utils.health.DefaultHealthCheckingActorFactory;
import org.eclipse.ditto.services.utils.health.HealthCheckingActorOptions;
import org.eclipse.ditto.services.utils.health.routes.StatusRoute;
import org.eclipse.ditto.services.utils.persistence.mongo.MongoHealthChecker;
import org.eclipse.ditto.signals.commands.devops.RetrieveStatisticsDetails;
import akka.Done;
import akka.actor.AbstractActor;
import akka.actor.ActorInitializationException;
import akka.actor.ActorKilledException;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.CoordinatedShutdown;
import akka.actor.InvalidActorNameException;
import akka.actor.OneForOneStrategy;
import akka.actor.Props;
import akka.actor.Status;
import akka.actor.SupervisorStrategy;
import akka.cluster.Cluster;
import akka.cluster.pubsub.DistributedPubSubMediator;
import akka.event.DiagnosticLoggingAdapter;
import akka.http.javadsl.ConnectHttp;
import akka.http.javadsl.Http;
import akka.http.javadsl.ServerBinding;
import akka.http.javadsl.server.Route;
import akka.japi.pf.DeciderBuilder;
import akka.japi.pf.ReceiveBuilder;
import akka.pattern.AskTimeoutException;
import akka.pattern.PatternsCS;
import akka.stream.ActorMaterializer;
/**
* The root actor of the concierge service.
*/
public final class ConciergeRootActor extends AbstractActor {
/**
* Name of this actor.
*/
public static final String ACTOR_NAME = "conciergeRoot";
private static final String RESTARTING_CHILD_MSG = "Restarting child...";
private final DiagnosticLoggingAdapter log = LogUtil.obtain(this);
private final SupervisorStrategy supervisorStrategy = new OneForOneStrategy(true, DeciderBuilder
.match(NullPointerException.class, e -> {
log.error(e, "NullPointer in child actor: {}", e.getMessage());
log.info(RESTARTING_CHILD_MSG);
return SupervisorStrategy.restart();
}).match(IllegalArgumentException.class, e -> {
log.warning("Illegal Argument in child actor: {}", e.getMessage());
return SupervisorStrategy.resume();
}).match(IndexOutOfBoundsException.class, e -> {
log.warning("IndexOutOfBounds in child actor: {}", e.getMessage());
return SupervisorStrategy.resume();
}).match(IllegalStateException.class, e -> {
log.warning("Illegal State in child actor: {}", e.getMessage());
return SupervisorStrategy.resume();
}).match(NoSuchElementException.class, e -> {
log.warning("NoSuchElement in child actor: {}", e.getMessage());
return SupervisorStrategy.resume();
}).match(AskTimeoutException.class, e -> {
log.warning("AskTimeoutException in child actor: {}", e.getMessage());
return SupervisorStrategy.resume();
}).match(ConnectException.class, e -> {
log.warning("ConnectException in child actor: {}", e.getMessage());
log.info(RESTARTING_CHILD_MSG);
return SupervisorStrategy.restart();
}).match(InvalidActorNameException.class, e -> {
log.warning("InvalidActorNameException in child actor: {}", e.getMessage());
return SupervisorStrategy.resume();
}).match(ActorInitializationException.class, e -> {
log.error(e, "ActorInitializationException in child actor: {}", e.getMessage());
return SupervisorStrategy.stop();
}).match(ActorKilledException.class, e -> {
log.error(e, "ActorKilledException in child actor: {}", e.message());
log.info(RESTARTING_CHILD_MSG);
return SupervisorStrategy.restart();
}).match(DittoRuntimeException.class, e -> {
log.error(e,
"DittoRuntimeException '{}' should not be escalated to RootActor. Simply resuming Actor.",
e.getErrorCode());
return SupervisorStrategy.resume();
}).match(Throwable.class, e -> {
log.error(e, "Escalating above root actor!");
return SupervisorStrategy.escalate();
}).matchAny(e -> {
log.error("Unknown message:'{}'! Escalating above root actor!", e);
return SupervisorStrategy.escalate();
}).build());
private final RetrieveStatisticsDetailsResponseSupplier retrieveStatisticsDetailsResponseSupplier;
private <C extends AbstractConciergeConfigReader> ConciergeRootActor(final C configReader,
final ActorRef pubSubMediator,
final AbstractEnforcerActorFactory<C> authorizationProxyPropsFactory,
final ActorMaterializer materializer) {
requireNonNull(configReader);
requireNonNull(pubSubMediator);
requireNonNull(authorizationProxyPropsFactory);
requireNonNull(materializer);
final ActorContext context = getContext();
final ActorRef conciergeShardRegion =
authorizationProxyPropsFactory.startEnforcerActor(context, configReader, pubSubMediator);
retrieveStatisticsDetailsResponseSupplier = RetrieveStatisticsDetailsResponseSupplier.of(conciergeShardRegion,
ConciergeMessagingConstants.SHARD_REGION, log);
final ActorRef conciergeForwarder = startChildActor(context, ConciergeForwarderActor.ACTOR_NAME,
ConciergeForwarderActor.props(pubSubMediator, conciergeShardRegion));
pubSubMediator.tell(new DistributedPubSubMediator.Put(getSelf()), getSelf());
pubSubMediator.tell(new DistributedPubSubMediator.Put(conciergeForwarder), getSelf());
startClusterSingletonActor(context, BatchSupervisorActor.ACTOR_NAME,
BatchSupervisorActor.props(pubSubMediator, conciergeForwarder));
final ActorRef healthCheckingActor = startHealthCheckingActor(context, configReader);
final HttpConfigReader httpConfig = configReader.http();
bindHttpStatusRoute(healthCheckingActor, httpConfig, materializer);
}
/**
* Creates Akka configuration object Props for this actor.
*
* @param configReader the config reader.
* @param pubSubMediator the PubSub mediator Actor.
* @param authorizationProxyPropsFactory the {@link AbstractEnforcerActorFactory}.
* @param materializer the materializer for the Akka actor system.
* @return the Akka configuration Props object.
*/
public static <C extends AbstractConciergeConfigReader> Props props(final C configReader,
final ActorRef pubSubMediator,
final AbstractEnforcerActorFactory<C> authorizationProxyPropsFactory,
final ActorMaterializer materializer) {
return Props.create(ConciergeRootActor.class,
() -> new ConciergeRootActor(configReader, pubSubMediator, authorizationProxyPropsFactory,
materializer));
}
private static void startClusterSingletonActor(final akka.actor.ActorContext context, final String actorName,
final Props props) {
ClusterUtil.startSingleton(context, ConciergeMessagingConstants.CLUSTER_ROLE, actorName, props);
}
private static ActorRef startHealthCheckingActor(final ActorContext context,
final AbstractConciergeConfigReader configReader) {
final HealthConfigReader healthConfig = configReader.health();
final HealthCheckingActorOptions.Builder hcBuilder = HealthCheckingActorOptions
.getBuilder(healthConfig.enabled(), healthConfig.getInterval());
if (healthConfig.persistenceEnabled()) {
hcBuilder.enablePersistenceCheck();
}
final HealthCheckingActorOptions healthCheckingActorOptions = hcBuilder.build();
return startChildActor(context, DefaultHealthCheckingActorFactory.ACTOR_NAME,
DefaultHealthCheckingActorFactory.props(healthCheckingActorOptions, MongoHealthChecker.props()));
}
private static ActorRef startChildActor(final akka.actor.ActorContext context, final String actorName,
final Props props) {
return context.actorOf(props, actorName);
}
private static Route createRoute(final ActorSystem actorSystem, final ActorRef healthCheckingActor) {
final StatusRoute statusRoute = new StatusRoute(new ClusterStatusSupplier(Cluster.get(actorSystem)),
healthCheckingActor, actorSystem);
return logRequest("http-request", () ->
logResult("http-response", statusRoute::buildStatusRoute));
}
@Override
public SupervisorStrategy supervisorStrategy() {
return supervisorStrategy;
}
@Override
public Receive createReceive() {
return ReceiveBuilder.create()
.match(RetrieveStatisticsDetails.class, this::handleRetrieveStatisticsDetails)
.match(Status.Failure.class, f -> log.error(f.cause(), "Got failure <{}>!", f))
.matchAny(m -> {
log.warning("Unknown message <{}>.", m);
unhandled(m);
}).build();
}
private void handleRetrieveStatisticsDetails(final RetrieveStatisticsDetails command) {
log.info("Sending the namespace stats of the concierge shard as requested..");
PatternsCS.pipe(retrieveStatisticsDetailsResponseSupplier
.apply(command.getDittoHeaders()), getContext().dispatcher()).to(getSender());
}
private void bindHttpStatusRoute(final ActorRef healthCheckingActor, final HttpConfigReader httpConfig,
final ActorMaterializer materializer) {
String hostname = httpConfig.getHostname();
if (hostname.isEmpty()) {
hostname = ConfigUtil.getLocalHostAddress();
log.info("No explicit hostname configured, using HTTP hostname: {}", hostname);
}
final CompletionStage<ServerBinding> binding = Http.get(getContext().system())
.bindAndHandle(createRoute(getContext().system(), healthCheckingActor).flow(getContext().system(),
materializer), ConnectHttp.toHost(hostname, httpConfig.getPort()), materializer);
binding.thenAccept(theBinding -> CoordinatedShutdown.get(getContext().getSystem()).addTask(
CoordinatedShutdown.PhaseServiceUnbind(), "shutdown_health_http_endpoint", () -> {
log.info("Gracefully shutting down status/health HTTP endpoint..");
return theBinding.terminate(Duration.ofSeconds(1))
.handle((httpTerminated, e) -> Done.getInstance());
})
).exceptionally(failure -> {
log.error(failure, "Something very bad happened: {}", failure.getMessage());
getContext().system().terminate();
return null;
});
}
}