use of java.net.BindException in project voldemort by voldemort.
the class ServerTestUtils method startVoldemortCluster.
/**
* This method wraps up all of the work that is done in many different tests
* to set up some number of Voldemort servers in a cluster. This method
* masks an intermittent TOCTOU problem with the ports identified by
* {@link #findFreePorts(int)} not actually being free when a server needs
* to bind to them. If this method returns, it will return a non-null
* cluster. This method is not guaranteed to return, but will likely
* eventually do so...
*
* @param numServers
* @param voldemortServers
* @param partitionMap
* @param socketStoreFactory
* @param useNio
* @param clusterFile
* @param storeFile
* @param properties
* @param customCluster Use this specified cluster object
* @return Cluster object that was used to successfully start all of the
* servers.
* @throws IOException
*/
// TODO: numServers is likely not needed. If this method is refactored in
// the future, then try and drop the numServers argument.
// So, is the socketStoreFactory argument.. It should be entirely hidden
// within the helper method
private static Cluster startVoldemortCluster(int numServers, VoldemortServer[] voldemortServers, int[][] partitionMap, SocketStoreFactory socketStoreFactory, boolean useNio, String clusterFile, String storeFile, Properties properties, Cluster customCluster) throws IOException {
boolean started = false;
Cluster cluster = null;
while (!started) {
try {
cluster = internalStartVoldemortCluster(numServers, voldemortServers, partitionMap, socketStoreFactory, useNio, clusterFile, storeFile, properties, customCluster);
started = true;
} catch (BindException be) {
logger.debug("Caught BindException when starting cluster. Will retry.");
}
}
return cluster;
}
use of java.net.BindException in project distributedlog by twitter.
the class LocalDLMEmulator method runZookeeperOnAnyPort.
/**
* Try to start zookkeeper locally on any port beginning with some base port.
* Dump some socket info when bind fails.
*/
public static Pair<ZooKeeperServerShim, Integer> runZookeeperOnAnyPort(int basePort, File zkDir) throws Exception {
final int MAX_RETRIES = 20;
final int MIN_PORT = 1025;
final int MAX_PORT = 65535;
ZooKeeperServerShim zks = null;
int zkPort = basePort;
boolean success = false;
int retries = 0;
while (!success) {
try {
LOG.info("zk trying to bind to port " + zkPort);
zks = LocalBookKeeper.runZookeeper(1000, zkPort, zkDir);
success = true;
} catch (BindException be) {
retries++;
if (retries > MAX_RETRIES) {
throw be;
}
zkPort++;
if (zkPort > MAX_PORT) {
zkPort = MIN_PORT;
}
}
}
return Pair.of(zks, zkPort);
}
use of java.net.BindException in project midpoint by Evolveum.
the class SqlRepositoryFactory method checkPort.
private void checkPort(int port) throws RepositoryServiceFactoryException {
if (port >= 65635 || port < 0) {
throw new RepositoryServiceFactoryException("Port must be in range 0-65634, not '" + port + "'.");
}
ServerSocket ss = null;
try {
ss = new ServerSocket(port);
ss.setReuseAddress(true);
} catch (BindException e) {
throw new RepositoryServiceFactoryException("Configured port (" + port + ") for H2 already in use.", e);
} catch (IOException e) {
LOGGER.error("Reported IO error, while binding ServerSocket to port " + port + " used to test availability " + "of port for H2 Server", e);
} finally {
try {
if (ss != null) {
ss.close();
}
} catch (IOException ex) {
LOGGER.error("Reported IO error, while closing ServerSocket used to test availability " + "of port for H2 Server", ex);
}
}
}
use of java.net.BindException 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 java.net.BindException in project cdap by caskdata.
the class ExternalAuthenticationServer method startUp.
@Override
protected void startUp() throws Exception {
try {
server = new Server();
try {
bindAddress = InetAddress.getByName(cConfiguration.get(Constants.Security.AUTH_SERVER_BIND_ADDRESS));
} catch (UnknownHostException e) {
LOG.error("Error finding host to connect to.", e);
throw e;
}
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);
} catch (Exception e) {
LOG.error("Error while starting Authentication Server.", e);
}
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)));
}
Aggregations