/
GatewayRootActor.java
executable file
·289 lines (254 loc) · 14.3 KB
/
GatewayRootActor.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
/*
* 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.gateway.starter;
import java.net.ConnectException;
import java.time.Duration;
import java.util.NoSuchElementException;
import java.util.Optional;
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.base.config.ServiceConfigReader;
import org.eclipse.ditto.services.gateway.endpoints.directives.auth.DittoGatewayAuthenticationDirectiveFactory;
import org.eclipse.ditto.services.gateway.endpoints.routes.RootRoute;
import org.eclipse.ditto.services.gateway.endpoints.routes.RouteFactory;
import org.eclipse.ditto.services.gateway.proxy.actors.ProxyActor;
import org.eclipse.ditto.services.gateway.starter.service.util.ConfigKeys;
import org.eclipse.ditto.services.gateway.starter.service.util.DefaultHttpClientFacade;
import org.eclipse.ditto.services.gateway.starter.service.util.HttpClientFacade;
import org.eclipse.ditto.services.gateway.streaming.actors.StreamingActor;
import org.eclipse.ditto.services.models.concierge.ConciergeMessagingConstants;
import org.eclipse.ditto.services.models.concierge.actors.ConciergeForwarderActor;
import org.eclipse.ditto.services.models.policies.PoliciesMessagingConstants;
import org.eclipse.ditto.services.models.things.ThingsMessagingConstants;
import org.eclipse.ditto.services.models.thingsearch.ThingsSearchConstants;
import org.eclipse.ditto.services.utils.akka.LogUtil;
import org.eclipse.ditto.services.utils.cluster.ClusterStatusSupplier;
import org.eclipse.ditto.services.utils.cluster.ShardRegionExtractor;
import org.eclipse.ditto.services.utils.config.ConfigUtil;
import org.eclipse.ditto.services.utils.devops.DevOpsCommandsActor;
import org.eclipse.ditto.services.utils.devops.LogbackLoggingFacade;
import org.eclipse.ditto.services.utils.health.DefaultHealthCheckingActorFactory;
import org.eclipse.ditto.services.utils.health.HealthCheckingActorOptions;
import com.typesafe.config.Config;
import akka.Done;
import akka.actor.AbstractActor;
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.cluster.sharding.ClusterSharding;
import akka.dispatch.MessageDispatcher;
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.Creator;
import akka.japi.pf.DeciderBuilder;
import akka.japi.pf.ReceiveBuilder;
import akka.pattern.AskTimeoutException;
import akka.stream.ActorMaterializer;
/**
* The Root Actor of the API Gateway's Akka ActorSystem.
*/
final class GatewayRootActor extends AbstractActor {
/**
* The name of this Actor in the ActorSystem.
*/
static final String ACTOR_NAME = "gatewayRoot";
private static final String BLOCKING_DISPATCHER_NAME = "blocking-dispatcher";
private static final String CHILD_RESTART_INFO_MSG = "Restarting child...";
private final DiagnosticLoggingAdapter log = LogUtil.obtain(this);
private final SupervisorStrategy strategy = new OneForOneStrategy(true, DeciderBuilder
.match(NullPointerException.class, e -> {
log.error(e, "NullPointer in child actor: {}", e.getMessage());
log.info(CHILD_RESTART_INFO_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(CHILD_RESTART_INFO_MSG);
return SupervisorStrategy.restart();
}).match(InvalidActorNameException.class, e -> {
log.warning("InvalidActorNameException in child actor: {}", e.getMessage());
return SupervisorStrategy.resume();
}).match(DittoRuntimeException.class, e -> {
log.error(e,
"DittoRuntimeException '{}' should not be escalated to GatewayRootActor. Simply resuming Actor.",
e.getErrorCode());
return SupervisorStrategy.resume();
}).match(ActorKilledException.class, e -> {
log.error(e, "ActorKilledException in child actor: {}", e.message());
log.info(CHILD_RESTART_INFO_MSG);
return SupervisorStrategy.restart();
}).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 GatewayRootActor(final ServiceConfigReader configReader, final ActorRef pubSubMediator,
final ActorMaterializer materializer) {
final int numberOfShards = configReader.cluster().numberOfShards();
final Config config = configReader.getRawConfig();
final ActorSystem actorSystem = context().system();
// start the cluster sharding proxies for retrieving Statistics via StatisticActor about them:
ClusterSharding.get(actorSystem)
.startProxy(PoliciesMessagingConstants.SHARD_REGION,
Optional.of(PoliciesMessagingConstants.CLUSTER_ROLE),
ShardRegionExtractor.of(numberOfShards, actorSystem));
ClusterSharding.get(actorSystem)
.startProxy(ThingsMessagingConstants.SHARD_REGION, Optional.of(ThingsMessagingConstants.CLUSTER_ROLE),
ShardRegionExtractor.of(numberOfShards, actorSystem));
ClusterSharding.get(actorSystem)
.startProxy(ThingsSearchConstants.SHARD_REGION, Optional.of(ThingsSearchConstants.CLUSTER_ROLE),
ShardRegionExtractor.of(numberOfShards, actorSystem));
final ActorRef devOpsCommandsActor = startChildActor(DevOpsCommandsActor.ACTOR_NAME,
DevOpsCommandsActor.props(LogbackLoggingFacade.newInstance(), GatewayService.SERVICE_NAME,
ConfigUtil.instanceIdentifier()));
final ActorRef conciergeShardRegionProxy = ClusterSharding.get(actorSystem)
.startProxy(ConciergeMessagingConstants.SHARD_REGION,
Optional.of(ConciergeMessagingConstants.CLUSTER_ROLE),
ShardRegionExtractor.of(numberOfShards, actorSystem));
final ActorRef conciergeForwarder = startChildActor(ConciergeForwarderActor.ACTOR_NAME,
ConciergeForwarderActor.props(pubSubMediator, conciergeShardRegionProxy));
final ActorRef proxyActor = startChildActor(ProxyActor.ACTOR_NAME,
ProxyActor.props(pubSubMediator, devOpsCommandsActor, conciergeForwarder));
pubSubMediator.tell(new DistributedPubSubMediator.Put(getSelf()), getSelf());
final ActorRef streamingActor = startChildActor(StreamingActor.ACTOR_NAME,
StreamingActor.props(pubSubMediator, proxyActor));
final HealthConfigReader healthConfig = configReader.health();
final ActorRef healthCheckActor = createHealthCheckActor(healthConfig);
final HttpConfigReader httpConfig = configReader.http();
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(actorSystem)
.bindAndHandle(createRoute(actorSystem, config, proxyActor, streamingActor, healthCheckActor)
.flow(actorSystem, materializer),
ConnectHttp.toHost(hostname, httpConfig.getPort()), materializer);
binding.thenAccept(theBinding -> {
log.info("Serving HTTP requests on port {} ...", theBinding.localAddress().getPort());
CoordinatedShutdown.get(actorSystem).addTask(
CoordinatedShutdown.PhaseServiceUnbind(), "shutdown_http_endpoint", () -> {
log.info("Gracefully shutting down user HTTP endpoint..");
return theBinding.terminate(Duration.ofSeconds(10))
.handle((httpTerminated, e) -> Done.getInstance());
});
}
).exceptionally(failure -> {
log.error(failure, "Something very bad happened: {}", failure.getMessage());
actorSystem.terminate();
return null;
});
}
/**
* Creates Akka configuration object Props for this actor.
*
* @param configReader the configuration reader of this service.
* @param pubSubMediator the pub-sub mediator.
* @param materializer the materializer for the akka actor system.
* @return the Akka configuration Props object.
*/
static Props props(final ServiceConfigReader configReader, final ActorRef pubSubMediator,
final ActorMaterializer materializer) {
return Props.create(GatewayRootActor.class, new Creator<GatewayRootActor>() {
private static final long serialVersionUID = 1L;
@Override
public GatewayRootActor create() {
return new GatewayRootActor(configReader, pubSubMediator, materializer);
}
});
}
@Override
public SupervisorStrategy supervisorStrategy() {
return strategy;
}
@Override
public Receive createReceive() {
return ReceiveBuilder.create()
.match(Status.Failure.class, f -> log.error(f.cause(), "Got failure: {}", f))
.matchAny(m -> {
log.warning("Unknown message: {}", m);
unhandled(m);
}).build();
}
private ActorRef startChildActor(final String actorName, final Props props) {
log.info("Starting child actor '{}'", actorName);
return getContext().actorOf(props, actorName);
}
private Route createRoute(final ActorSystem actorSystem,
final Config config,
final ActorRef proxyActor,
final ActorRef streamingActor,
final ActorRef healthCheckingActor) {
final HttpClientFacade httpClient = DefaultHttpClientFacade.getInstance(actorSystem);
final ClusterStatusSupplier clusterStateSupplier = new ClusterStatusSupplier(Cluster.get(actorSystem));
final MessageDispatcher blockingDispatcher = actorSystem.dispatchers().lookup(BLOCKING_DISPATCHER_NAME);
final DittoGatewayAuthenticationDirectiveFactory authenticationDirectiveFactory =
new DittoGatewayAuthenticationDirectiveFactory(config, httpClient, blockingDispatcher);
final RouteFactory routeFactory = RouteFactory.newInstance(actorSystem, proxyActor, streamingActor,
healthCheckingActor, clusterStateSupplier, authenticationDirectiveFactory);
return RootRoute.getBuilder()
.statsRoute(routeFactory.newStatsRoute())
.statusRoute(routeFactory.newStatusRoute())
.overallStatusRoute(routeFactory.newOverallStatusRoute())
.cachingHealthRoute(routeFactory.newCachingHealthRoute())
.devopsRoute(routeFactory.newDevopsRoute())
.policiesRoute(routeFactory.newPoliciesRoute())
.sseThingsRoute(routeFactory.newSseThingsRoute())
.thingsRoute(routeFactory.newThingsRoute())
.thingSearchRoute(routeFactory.newThingSearchRoute())
.websocketRoute(routeFactory.newWebSocketRoute())
.supportedSchemaVersions(config.getIntList(ConfigKeys.SCHEMA_VERSIONS))
.protocolAdapterProvider(routeFactory.getProtocolAdapterProvider())
.headerTranslator(routeFactory.getHeaderTranslator())
.httpAuthenticationDirective(routeFactory.newHttpAuthenticationDirective())
.wsAuthenticationDirective(routeFactory.newWsAuthenticationDirective())
.build();
}
private ActorRef createHealthCheckActor(final HealthConfigReader healthConfig) {
final HealthCheckingActorOptions.Builder hcBuilder = HealthCheckingActorOptions
.getBuilder(healthConfig.enabled(),
healthConfig.getInterval());
final HealthCheckingActorOptions healthCheckingActorOptions = hcBuilder.build();
return startChildActor(DefaultHealthCheckingActorFactory.ACTOR_NAME,
DefaultHealthCheckingActorFactory.props(healthCheckingActorOptions, null));
}
}