use of co.cask.cdap.common.ServiceBindException in project cdap by caskdata.
the class NettyRouter method bootstrapServer.
private void bootstrapServer(final ChannelUpstreamHandler connectionTracker) throws ServiceBindException {
ExecutorService serverBossExecutor = createExecutorService(serverBossThreadPoolSize, "router-server-boss-thread-%d");
ExecutorService serverWorkerExecutor = createExecutorService(serverWorkerThreadPoolSize, "router-server-worker-thread-%d");
serverBootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(serverBossExecutor, serverWorkerExecutor));
serverBootstrap.setOption("backlog", serverConnectionBacklog);
serverBootstrap.setOption("child.bufferFactory", new DirectChannelBufferFactory());
// Setup the pipeline factory
serverBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = Channels.pipeline();
if (isSSLEnabled()) {
// Add SSLHandler is SSL is enabled
pipeline.addLast("ssl", sslHandlerFactory.create());
}
pipeline.addLast("tracker", connectionTracker);
pipeline.addLast("http-response-encoder", new HttpResponseEncoder());
pipeline.addLast("http-decoder", new HttpRequestDecoder());
pipeline.addLast("http-status-request-handler", new HttpStatusRequestHandler());
if (securityEnabled) {
pipeline.addLast("access-token-authenticator", new SecurityAuthenticationHttpHandler(realm, tokenValidator, configuration, accessTokenTransformer, discoveryServiceClient));
}
// for now there's only one hardcoded rule, but if there will be more, we may want it generic and configurable
pipeline.addLast("http-request-handler", new HttpRequestHandler(clientBootstrap, serviceLookup, ImmutableList.<ProxyRule>of()));
return pipeline;
}
});
// Start listening on ports.
ImmutableMap.Builder<Integer, String> serviceMapBuilder = ImmutableMap.builder();
for (Map.Entry<String, Integer> forward : serviceToPortMap.entrySet()) {
int port = forward.getValue();
String service = forward.getKey();
String boundService = serviceLookup.getService(port);
if (boundService != null) {
LOG.warn("Port {} is already configured to service {}, ignoring forward for service {}", port, boundService, service);
continue;
}
InetSocketAddress bindAddress = new InetSocketAddress(hostname, port);
LOG.info("Starting Netty Router for service {} on address {}...", service, bindAddress);
try {
Channel channel = serverBootstrap.bind(bindAddress);
InetSocketAddress boundAddress = (InetSocketAddress) channel.getLocalAddress();
serviceMapBuilder.put(boundAddress.getPort(), service);
channelGroup.add(channel);
// Update service map
serviceLookup.updateServiceMap(serviceMapBuilder.build());
LOG.info("Started Netty Router for service {} on address {}.", service, boundAddress);
} catch (ChannelException e) {
if ((Throwables.getRootCause(e) instanceof BindException)) {
throw new ServiceBindException("Router", hostname.getCanonicalHostName(), port, e);
}
throw e;
}
}
}
use of co.cask.cdap.common.ServiceBindException in project cdap by caskdata.
the class ExternalAuthenticationServer method startUp.
@Override
protected void startUp() throws Exception {
server = new Server();
InetAddress bindAddress = InetAddress.getByName(cConfiguration.get(Constants.Security.AUTH_SERVER_BIND_ADDRESS));
QueuedThreadPool threadPool = new QueuedThreadPool();
threadPool.setMaxThreads(maxThreads);
server.setThreadPool(threadPool);
initHandlers();
ServletContextHandler context = new ServletContextHandler();
context.setServer(server);
context.addServlet(HttpServletDispatcher.class, "/");
context.addEventListener(new AuthenticationGuiceServletContextListener(handlers));
context.setSecurityHandler(authenticationHandler);
// Status endpoint should be handled without the authentication
ContextHandler statusContext = new ContextHandler();
statusContext.setContextPath(Constants.EndPoints.STATUS);
statusContext.setServer(server);
statusContext.setHandler(new StatusRequestHandler());
if (cConfiguration.getBoolean(Constants.Security.SSL.EXTERNAL_ENABLED, false)) {
SslContextFactory sslContextFactory = new SslContextFactory();
String keyStorePath = sConfiguration.get(Constants.Security.AuthenticationServer.SSL_KEYSTORE_PATH);
String keyStorePassword = sConfiguration.get(Constants.Security.AuthenticationServer.SSL_KEYSTORE_PASSWORD);
String keyStoreType = sConfiguration.get(Constants.Security.AuthenticationServer.SSL_KEYSTORE_TYPE, Constants.Security.AuthenticationServer.DEFAULT_SSL_KEYSTORE_TYPE);
String keyPassword = sConfiguration.get(Constants.Security.AuthenticationServer.SSL_KEYPASSWORD);
Preconditions.checkArgument(keyStorePath != null, "Key Store Path Not Configured");
Preconditions.checkArgument(keyStorePassword != null, "KeyStore Password Not Configured");
sslContextFactory.setKeyStorePath(keyStorePath);
sslContextFactory.setKeyStorePassword(keyStorePassword);
sslContextFactory.setKeyStoreType(keyStoreType);
if (keyPassword != null && keyPassword.length() != 0) {
sslContextFactory.setKeyManagerPassword(keyPassword);
}
String trustStorePath = cConfiguration.get(Constants.Security.AuthenticationServer.SSL_TRUSTSTORE_PATH);
if (StringUtils.isNotEmpty(trustStorePath)) {
String trustStorePassword = cConfiguration.get(Constants.Security.AuthenticationServer.SSL_TRUSTSTORE_PASSWORD);
String trustStoreType = cConfiguration.get(Constants.Security.AuthenticationServer.SSL_TRUSTSTORE_TYPE, Constants.Security.AuthenticationServer.DEFAULT_SSL_KEYSTORE_TYPE);
// SSL handshaking will involve requesting for a client certificate, if cert is not provided
// server continues with the connection but the client is considered to be unauthenticated
sslContextFactory.setWantClientAuth(true);
sslContextFactory.setTrustStore(trustStorePath);
sslContextFactory.setTrustStorePassword(trustStorePassword);
sslContextFactory.setTrustStoreType(trustStoreType);
sslContextFactory.setValidateCerts(true);
}
// TODO Figure out how to pick a certificate from key store
SslSelectChannelConnector sslConnector = new SslSelectChannelConnector(sslContextFactory);
sslConnector.setHost(bindAddress.getCanonicalHostName());
sslConnector.setPort(port);
server.setConnectors(new Connector[] { sslConnector });
} else {
SelectChannelConnector connector = new SelectChannelConnector();
connector.setHost(bindAddress.getCanonicalHostName());
connector.setPort(port);
server.setConnectors(new Connector[] { connector });
}
HandlerCollection handlers = new HandlerCollection();
handlers.addHandler(statusContext);
handlers.addHandler(context);
// AuditLogHandler must be last, since it needs the response that was sent to the client
handlers.addHandler(auditLogHandler);
server.setHandler(handlers);
try {
server.start();
} catch (Exception e) {
if ((Throwables.getRootCause(e) instanceof BindException)) {
throw new ServiceBindException("Authentication Server", bindAddress.getCanonicalHostName(), port, e);
}
throw e;
}
// assumes we only have one connector
Connector connector = server.getConnectors()[0];
InetSocketAddress inetSocketAddress = new InetSocketAddress(connector.getHost(), connector.getLocalPort());
serviceCancellable = discoveryService.register(ResolvingDiscoverable.of(new Discoverable(Constants.Service.EXTERNAL_AUTHENTICATION, inetSocketAddress)));
}
use of co.cask.cdap.common.ServiceBindException in project cdap by caskdata.
the class NettyRouter method createServerBootstrap.
private ServerBootstrap createServerBootstrap(final ChannelGroup channelGroup) throws ServiceBindException {
EventLoopGroup bossGroup = createEventLoopGroup(serverBossThreadPoolSize, "router-server-boss-thread-%d");
EventLoopGroup workerGroup = createEventLoopGroup(serverWorkerThreadPoolSize, "router-server-worker-thread-%d");
return new ServerBootstrap().group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, serverConnectionBacklog).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
channelGroup.add(ch);
ChannelPipeline pipeline = ch.pipeline();
if (isSSLEnabled()) {
pipeline.addLast("ssl", sslHandlerFactory.create(ch.alloc()));
}
pipeline.addLast("http-codec", new HttpServerCodec());
pipeline.addLast("http-status-request-handler", new HttpStatusRequestHandler());
if (securityEnabled) {
pipeline.addLast("access-token-authenticator", new AuthenticationHandler(cConf, tokenValidator, discoveryServiceClient, accessTokenTransformer));
}
if (cConf.getBoolean(Constants.Router.ROUTER_AUDIT_LOG_ENABLED)) {
pipeline.addLast("audit-log", new AuditLogHandler());
}
// Always let the client to continue sending the request body after the authentication passed
pipeline.addLast("expect-continue", new HttpServerExpectContinueHandler());
// for now there's only one hardcoded rule, but if there will be more, we may want it generic and configurable
pipeline.addLast("http-request-handler", new HttpRequestRouter(cConf, serviceLookup));
}
});
}
use of co.cask.cdap.common.ServiceBindException in project cdap by caskdata.
the class StandaloneMain method doMain.
/**
* The actual main method. It is called using reflection from {@link #main(String[])}.
*/
@SuppressWarnings("unused")
public static void doMain(String[] args) {
StandaloneMain main = create(CConfiguration.create(), new Configuration());
try {
if (args.length > 0) {
System.out.printf("%s takes no arguments\n", StandaloneMain.class.getSimpleName());
System.out.println("These arguments are being ignored:");
for (int i = 0; i <= args.length - 1; i++) {
System.out.printf("Parameter #%d: %s\n", i, args[i]);
}
}
main.startUp();
} catch (Throwable e) {
@SuppressWarnings("ThrowableResultOfMethodCallIgnored") Throwable rootCause = Throwables.getRootCause(e);
if (rootCause instanceof ServiceBindException) {
LOG.error("Failed to start Standalone CDAP: {}", rootCause.getMessage());
System.err.println("Failed to start Standalone CDAP: " + rootCause.getMessage());
} else {
// exception stack trace will be logged by
// UncaughtExceptionIdleService.UNCAUGHT_EXCEPTION_HANDLER
LOG.error("Failed to start Standalone CDAP");
System.err.println("Failed to start Standalone CDAP");
e.printStackTrace(System.err);
}
Runtime.getRuntime().halt(-2);
}
}
use of co.cask.cdap.common.ServiceBindException in project cdap by caskdata.
the class NettyRouter method startServer.
private Cancellable startServer(final ServerBootstrap serverBootstrap, final ChannelGroup channelGroup) throws Exception {
// Start listening on ports.
Map<Integer, String> serviceMap = new HashMap<>();
for (Map.Entry<String, Integer> forward : serviceToPortMap.entrySet()) {
int port = forward.getValue();
String service = forward.getKey();
String boundService = serviceLookup.getService(port);
if (boundService != null) {
LOG.warn("Port {} is already configured to service {}, ignoring forward for service {}", port, boundService, service);
continue;
}
InetSocketAddress bindAddress = new InetSocketAddress(hostname, port);
LOG.info("Starting Netty Router for service {} on address {}...", service, bindAddress);
try {
Channel channel = serverBootstrap.bind(bindAddress).sync().channel();
channelGroup.add(channel);
InetSocketAddress boundAddress = (InetSocketAddress) channel.localAddress();
serviceMap.put(boundAddress.getPort(), service);
// Update service map
serviceLookup.updateServiceMap(serviceMap);
LOG.info("Started Netty Router for service {} on address {}.", service, boundAddress);
} catch (Exception e) {
if ((Throwables.getRootCause(e) instanceof BindException)) {
throw new ServiceBindException("Router", hostname.getCanonicalHostName(), port, e);
}
throw e;
}
}
return new Cancellable() {
@Override
public void cancel() {
List<Future<?>> futures = new ArrayList<>();
futures.add(channelGroup.close());
futures.add(serverBootstrap.config().group().shutdownGracefully(0, 5, TimeUnit.SECONDS));
futures.add(serverBootstrap.config().childGroup().shutdownGracefully(0, 5, TimeUnit.SECONDS));
for (Future<?> future : futures) {
future.awaitUninterruptibly();
}
}
};
}
Aggregations