use of org.infinispan.server.router.routes.rest.RestServerRouteDestination in project infinispan by infinispan.
the class Server method run.
public synchronized CompletableFuture<ExitStatus> run() {
CompletableFuture<ExitStatus> r = exitHandler.getExitFuture();
if (status == ComponentStatus.RUNNING) {
return r;
}
protocolServers = new ConcurrentHashMap<>(4);
try {
// Load any server extensions
extensions = new Extensions();
extensions.load(classLoader);
// Create the cache manager
cacheManager = new DefaultCacheManager(configurationBuilderHolder, false);
// Retrieve the server configuration
serverConfiguration = SecurityActions.getCacheManagerConfiguration(cacheManager).module(ServerConfiguration.class);
serverConfiguration.setServer(this);
// Initialize the data sources
dataSources = new HashMap<>();
InitialContext initialContext = new InitialContext();
for (DataSourceConfiguration dataSourceConfiguration : serverConfiguration.dataSources().values()) {
DataSource dataSource = DataSourceFactory.create(dataSourceConfiguration);
dataSources.put(dataSourceConfiguration.name(), dataSource);
initialContext.bind(dataSourceConfiguration.jndiName(), dataSource);
}
// Start the cache manager
SecurityActions.startCacheManager(cacheManager);
BasicComponentRegistry bcr = SecurityActions.getGlobalComponentRegistry(cacheManager).getComponent(BasicComponentRegistry.class.getName());
blockingManager = bcr.getComponent(BlockingManager.class).running();
serverStateManager = new ServerStateManagerImpl(this, cacheManager, bcr.getComponent(GlobalConfigurationManager.class).running());
bcr.registerComponent(ServerStateManager.class, serverStateManager, false);
ScheduledExecutorService timeoutExecutor = bcr.getComponent(KnownComponentNames.TIMEOUT_SCHEDULE_EXECUTOR, ScheduledExecutorService.class).running();
// BlockingManager of single container used for writing the global manifest, but this will need to change
// when multiple containers are supported by the server. Similarly, the default cache manager is used to create
// the clustered locks.
Path dataRoot = serverRoot.toPath().resolve(properties.getProperty(INFINISPAN_SERVER_DATA_PATH));
backupManager = new BackupManagerImpl(blockingManager, cacheManager, dataRoot);
backupManager.init();
// Register the task manager
taskManager = bcr.getComponent(TaskManager.class).running();
taskManager.registerTaskEngine(extensions.getServerTaskEngine(cacheManager));
// Initialize the OpenTracing integration
RequestTracer.start();
for (EndpointConfiguration endpoint : serverConfiguration.endpoints().endpoints()) {
// Start the protocol servers
SinglePortRouteSource routeSource = new SinglePortRouteSource();
Set<Route<? extends RouteSource, ? extends RouteDestination>> routes = ConcurrentHashMap.newKeySet();
endpoint.connectors().parallelStream().forEach(configuration -> {
try {
Class<? extends ProtocolServer> protocolServerClass = configuration.getClass().getAnnotation(ConfigurationFor.class).value().asSubclass(ProtocolServer.class);
ProtocolServer protocolServer = Util.getInstance(protocolServerClass);
protocolServer.setServerManagement(this, endpoint.admin());
if (configuration instanceof HotRodServerConfiguration) {
ElytronSASLAuthenticationProvider.init((HotRodServerConfiguration) configuration, serverConfiguration, timeoutExecutor);
} else if (configuration instanceof RestServerConfiguration) {
ElytronHTTPAuthenticator.init((RestServerConfiguration) configuration, serverConfiguration);
} else if (configuration instanceof RespServerConfiguration) {
ElytronRESPAuthenticator.init((RespServerConfiguration) configuration, serverConfiguration, blockingManager);
}
protocolServers.put(protocolServer.getName() + "-" + configuration.name(), protocolServer);
SecurityActions.startProtocolServer(protocolServer, configuration, cacheManager);
ProtocolServerConfiguration protocolConfig = protocolServer.getConfiguration();
if (protocolConfig.startTransport()) {
log.protocolStarted(protocolServer.getName(), configuration.socketBinding(), protocolConfig.host(), protocolConfig.port());
} else {
if (protocolServer instanceof HotRodServer) {
routes.add(new Route<>(routeSource, new HotRodServerRouteDestination(protocolServer.getName(), (HotRodServer) protocolServer)));
extensions.apply((HotRodServer) protocolServer);
} else if (protocolServer instanceof RestServer) {
routes.add(new Route<>(routeSource, new RestServerRouteDestination(protocolServer.getName(), (RestServer) protocolServer)));
} else if (protocolServer instanceof RespServer) {
routes.add(new Route<>(routeSource, new RespServerRouteDestination(protocolServer.getName(), (RespServer) protocolServer)));
}
log.protocolStarted(protocolServer.getName());
}
} catch (Throwable t) {
throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
});
// Next we start the single-port endpoints
SinglePortRouterConfiguration singlePortRouter = endpoint.singlePortRouter();
SinglePortEndpointRouter endpointServer = new SinglePortEndpointRouter(singlePortRouter);
endpointServer.start(new RoutingTable(routes), cacheManager);
protocolServers.put("endpoint-" + endpoint.socketBinding(), endpointServer);
log.protocolStarted(endpointServer.getName(), singlePortRouter.socketBinding(), singlePortRouter.host(), singlePortRouter.port());
log.endpointUrl(Util.requireNonNullElse(cacheManager.getAddress(), "local"), singlePortRouter.ssl().enabled() ? "https" : "http", singlePortRouter.host(), singlePortRouter.port());
}
serverStateManager.start();
// Change status
this.status = ComponentStatus.RUNNING;
log.serverStarted(Version.getBrandName(), Version.getBrandVersion(), timeService.timeDuration(startTime, TimeUnit.MILLISECONDS));
} catch (Exception e) {
r.completeExceptionally(e);
}
r = r.handle((status, t) -> {
if (t != null) {
Server.log.serverFailedToStart(Version.getBrandName(), t);
}
localShutdown(status);
return null;
});
return r;
}
use of org.infinispan.server.router.routes.rest.RestServerRouteDestination in project infinispan by infinispan.
the class ChannelInboundHandlerDelegator method channelRead0.
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) {
String[] uriSplitted = msg.uri().split("/");
// we are paring something like this: /rest/<context or prefix>/...
if (uriSplitted.length < 2) {
throw RouterLogger.SERVER.noRouteFound();
}
String context = uriSplitted[2];
RouterLogger.SERVER.debugf("Decoded context %s", context);
Optional<Route<PrefixedRouteSource, RestServerRouteDestination>> route = routingTable.streamRoutes(PrefixedRouteSource.class, RestServerRouteDestination.class).filter(r -> r.getRouteSource().getRoutePrefix().equals(context)).findAny();
RestServerRouteDestination routeDestination = route.orElseThrow(RouterLogger.SERVER::noRouteFound).getRouteDestination();
RestRequestHandler restHandler = (RestRequestHandler) routeDestination.getProtocolServer().getRestChannelInitializer().getRestHandler();
// before passing it to REST Handler, we need to replace path. The handler should not be aware of additional context
// used for multi-tenant prefixes
StringBuilder uriWithoutMultiTenantPrefix = new StringBuilder();
for (int i = 0; i < uriSplitted.length; ++i) {
if (i == 1) {
// this is the main uri prefix - "rest", we want to get rid of that.
continue;
}
uriWithoutMultiTenantPrefix.append(uriSplitted[i]);
if (i < uriSplitted.length - 1) {
uriWithoutMultiTenantPrefix.append("/");
}
}
msg.setUri(uriWithoutMultiTenantPrefix.toString());
restHandler.channelRead0(ctx, msg);
}
use of org.infinispan.server.router.routes.rest.RestServerRouteDestination in project infinispan by infinispan.
the class RestEndpointRouterTest method shouldRouteToProperRestServerBasedOnPath.
/**
* In this scenario we create 2 REST servers, each one with different REST Path: <ul> <li>REST1 -
* http://127.0.0.1:8080/rest/rest1</li> <li>REST2 - http://127.0.0.1:8080/rest/rest2</li> </ul>
* <p>
* The router should match requests based on path and redirect them to proper server.
*/
@Test
public void shouldRouteToProperRestServerBasedOnPath() {
// given
restServer1 = RestTestingUtil.createDefaultRestServer("rest1", "default");
restServer2 = RestTestingUtil.createDefaultRestServer("rest2", "default");
RestServerRouteDestination rest1Destination = new RestServerRouteDestination("rest1", restServer1);
RestRouteSource rest1Source = new RestRouteSource("rest1");
Route<RestRouteSource, RestServerRouteDestination> routeToRest1 = new Route<>(rest1Source, rest1Destination);
RestServerRouteDestination rest2Destination = new RestServerRouteDestination("rest2", restServer2);
RestRouteSource rest2Source = new RestRouteSource("rest2");
Route<RestRouteSource, RestServerRouteDestination> routeToRest2 = new Route<>(rest2Source, rest2Destination);
RouterConfigurationBuilder routerConfigurationBuilder = new RouterConfigurationBuilder();
routerConfigurationBuilder.rest().port(8080).ip(InetAddress.getLoopbackAddress()).routing().add(routeToRest1).add(routeToRest2);
router = new Router(routerConfigurationBuilder.build());
router.start();
int port = router.getRouter(EndpointRouter.Protocol.REST).get().getPort();
// when
ServerConfigurationBuilder builder = new RestClientConfigurationBuilder().addServer().host("127.0.0.1").port(port);
restClient = RestClient.forConfiguration(builder.build());
RestRawClient rawClient = restClient.raw();
String path1 = "/rest/rest1/v2/caches/default/test";
String path2 = "/rest/rest2/v2/caches/default/test";
join(rawClient.putValue(path1, emptyMap(), "rest1", TEXT_PLAIN_TYPE));
join(rawClient.putValue(path2, emptyMap(), "rest2", TEXT_PLAIN_TYPE));
String valueReturnedFromRest1 = join(rawClient.get(path1)).getBody();
String valueReturnedFromRest2 = join(rawClient.get(path2)).getBody();
// then
assertThat(valueReturnedFromRest1).isEqualTo("rest1");
assertThat(valueReturnedFromRest2).isEqualTo("rest2");
}
use of org.infinispan.server.router.routes.rest.RestServerRouteDestination in project infinispan by infinispan.
the class SinglePortTest method shouldUpgradeThroughALPN.
@Test
public void shouldUpgradeThroughALPN() throws Exception {
checkForOpenSSL();
// given
restServer = RestTestingUtil.createDefaultRestServer("rest", "default");
RestServerRouteDestination restDestination = new RestServerRouteDestination("rest", restServer);
SinglePortRouteSource singlePortSource = new SinglePortRouteSource();
Route<SinglePortRouteSource, RestServerRouteDestination> routeToRest = new Route<>(singlePortSource, restDestination);
SslContextFactory sslContextFactory = new SslContextFactory();
RouterConfigurationBuilder routerConfigurationBuilder = new RouterConfigurationBuilder();
routerConfigurationBuilder.singlePort().sslContext(sslContextFactory.keyStoreFileName(KEY_STORE_PATH).keyStorePassword(KEY_STORE_PASSWORD.toCharArray()).getContext()).port(0).ip(InetAddress.getLoopbackAddress()).routing().add(routeToRest);
router = new Router(routerConfigurationBuilder.build());
router.start();
EndpointRouter singlePortRouter = router.getRouter(EndpointRouter.Protocol.SINGLE_PORT).get();
// when
RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder();
builder.addServer().host(singlePortRouter.getHost()).port(singlePortRouter.getPort()).protocol(Protocol.HTTP_20).security().ssl().trustStoreFileName(TRUST_STORE_PATH).trustStorePassword("secret".toCharArray()).hostnameVerifier((hostname, session) -> true);
httpClient = RestClient.forConfiguration(builder.build());
CompletionStage<RestResponse> response = httpClient.cache("default").post("test", VALUE);
// then
ResponseAssertion.assertThat(response).hasNoContent();
}
use of org.infinispan.server.router.routes.rest.RestServerRouteDestination in project infinispan by infinispan.
the class SinglePortTest method shouldUpgradeThroughHTTP11UpgradeHeaders.
@Test
public void shouldUpgradeThroughHTTP11UpgradeHeaders() {
// given
restServer = RestTestingUtil.createDefaultRestServer("rest", "default");
RestServerRouteDestination restDestination = new RestServerRouteDestination("rest1", restServer);
SinglePortRouteSource singlePortSource = new SinglePortRouteSource();
Route<SinglePortRouteSource, RestServerRouteDestination> routeToRest = new Route<>(singlePortSource, restDestination);
RouterConfigurationBuilder routerConfigurationBuilder = new RouterConfigurationBuilder();
routerConfigurationBuilder.singlePort().port(0).ip(InetAddress.getLoopbackAddress()).routing().add(routeToRest);
router = new Router(routerConfigurationBuilder.build());
router.start();
int port = router.getRouter(EndpointRouter.Protocol.SINGLE_PORT).get().getPort();
// when
RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder();
builder.addServer().host("localhost").port(port).protocol(Protocol.HTTP_20);
httpClient = RestClient.forConfiguration(builder.build());
CompletionStage<RestResponse> response = httpClient.cache("default").post("test", VALUE);
// then
ResponseAssertion.assertThat(response).hasNoContent();
}
Aggregations