use of java.net.BindException in project tomee by apache.
the class ServiceDaemon method start.
@Override
public void start() throws ServiceException {
synchronized (this) {
// Don't bother if we are already started/starting
if (this.socketListener != null) {
return;
}
this.next.start();
final ServerSocket serverSocket;
try {
if (this.secure) {
final ServerSocketFactory factory = SSLServerSocketFactory.getDefault();
serverSocket = factory.createServerSocket(this.port, this.backlog, this.inetAddress);
((SSLServerSocket) serverSocket).setEnabledCipherSuites(this.enabledCipherSuites);
} else {
serverSocket = new ServerSocket();
serverSocket.setReuseAddress(true);
try {
serverSocket.bind(new InetSocketAddress(this.inetAddress, this.port), this.backlog);
} catch (final BindException e) {
// One retry - Port may be closing
Thread.sleep(1000);
serverSocket.bind(new InetSocketAddress(this.inetAddress, this.port), this.backlog);
}
}
serverSocket.setSoTimeout(this.timeout);
int serverPort = serverSocket.getLocalPort();
if (this.port == 0 && next.getName() != null) {
SystemInstance.get().getProperties().put(next.getName() + ".port", Integer.toString(serverPort));
this.port = serverPort;
}
} catch (Exception e) {
throw new ServiceException("Service failed to open socket", e);
}
this.socketListener = new SocketListener(this.next, serverSocket);
final Thread thread = new Thread(this.socketListener);
thread.setName("Service." + this.getName() + "@" + this.socketListener.hashCode());
thread.setDaemon(true);
thread.start();
final DiscoveryAgent agent = SystemInstance.get().getComponent(DiscoveryAgent.class);
if (agent != null && this.discoveryUriFormat != null) {
final Map<String, String> map = new HashMap<String, String>();
// add all the properties that were used to construct this service
for (final Map.Entry<Object, Object> entry : this.props.entrySet()) {
map.put(entry.getKey().toString(), entry.getValue().toString());
}
map.put("port", Integer.toString(this.port));
String address = this.ip;
if ("0.0.0.0".equals(address)) {
try {
address = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
log.error("Failed to resolve 0.0.0.0 to a routable address", e);
}
}
map.put("host", address);
map.put("bind", address);
final String uriString = this.discoveryUriFormat.apply(map);
try {
this.serviceUri = new URI(uriString);
agent.registerService(this.serviceUri);
} catch (Exception e) {
log.error("Cannot register service '" + this.getName() + "' with DiscoveryAgent.", e);
}
}
}
}
use of java.net.BindException in project stetho by facebook.
the class LocalSocketServer method bindToSocket.
@Nonnull
private static LocalServerSocket bindToSocket(String address) throws IOException {
int retries = MAX_BIND_RETRIES;
IOException firstException = null;
do {
try {
if (LogUtil.isLoggable(Log.DEBUG)) {
LogUtil.d("Trying to bind to @" + address);
}
return new LocalServerSocket(address);
} catch (BindException be) {
LogUtil.w(be, "Binding error, sleep " + TIME_BETWEEN_BIND_RETRIES_MS + " ms...");
if (firstException == null) {
firstException = be;
}
Util.sleepUninterruptibly(TIME_BETWEEN_BIND_RETRIES_MS);
}
} while (retries-- > 0);
throw firstException;
}
use of java.net.BindException in project elasticsearch by elastic.
the class TcpTransport method onException.
protected void onException(Channel channel, Exception e) throws IOException {
if (!lifecycle.started()) {
// just close and ignore - we are already stopped and just need to make sure we release all resources
disconnectFromNodeChannel(channel, e);
return;
}
if (isCloseConnectionException(e)) {
logger.trace((Supplier<?>) () -> new ParameterizedMessage("close connection exception caught on transport layer [{}], disconnecting from relevant node", channel), e);
// close the channel, which will cause a node to be disconnected if relevant
disconnectFromNodeChannel(channel, e);
} else if (isConnectException(e)) {
logger.trace((Supplier<?>) () -> new ParameterizedMessage("connect exception caught on transport layer [{}]", channel), e);
// close the channel as safe measure, which will cause a node to be disconnected if relevant
disconnectFromNodeChannel(channel, e);
} else if (e instanceof BindException) {
logger.trace((Supplier<?>) () -> new ParameterizedMessage("bind exception caught on transport layer [{}]", channel), e);
// close the channel as safe measure, which will cause a node to be disconnected if relevant
disconnectFromNodeChannel(channel, e);
} else if (e instanceof CancelledKeyException) {
logger.trace((Supplier<?>) () -> new ParameterizedMessage("cancelled key exception caught on transport layer [{}], disconnecting from relevant node", channel), e);
// close the channel as safe measure, which will cause a node to be disconnected if relevant
disconnectFromNodeChannel(channel, e);
} else if (e instanceof TcpTransport.HttpOnTransportException) {
// in case we are able to return data, serialize the exception content and sent it back to the client
if (isOpen(channel)) {
final Runnable closeChannel = () -> {
try {
closeChannels(Collections.singletonList(channel));
} catch (IOException e1) {
logger.debug("failed to close httpOnTransport channel", e1);
}
};
boolean success = false;
try {
sendMessage(channel, new BytesArray(e.getMessage().getBytes(StandardCharsets.UTF_8)), closeChannel);
success = true;
} finally {
if (success == false) {
// it's fine to call this more than once
closeChannel.run();
}
}
}
} else {
logger.warn((Supplier<?>) () -> new ParameterizedMessage("exception caught on transport layer [{}], closing connection", channel), e);
// close the channel, which will cause a node to be disconnected if relevant
disconnectFromNodeChannel(channel, e);
}
}
use of java.net.BindException in project h2o-3 by h2oai.
the class SSLSocketChannelFactoryTest method shouldHandshake.
@Test
public void shouldHandshake() throws IOException, SSLContextException, BrokenBarrierException, InterruptedException {
SSLProperties props = new SSLProperties();
props.put("h2o_ssl_protocol", SecurityUtils.defaultTLSVersion());
props.put("h2o_ssl_jks_internal", getFile("src/test/resources/keystore.jks").getPath());
props.put("h2o_ssl_jks_password", "password");
props.put("h2o_ssl_jts", getFile("src/test/resources/cacerts.jks").getPath());
props.put("h2o_ssl_jts_password", "password");
final SSLSocketChannelFactory factory = new SSLSocketChannelFactory(props);
final CyclicBarrier barrier = new CyclicBarrier(2);
final CyclicBarrier testOne = new CyclicBarrier(2);
final CyclicBarrier testTwo = new CyclicBarrier(2);
final CyclicBarrier testThree = new CyclicBarrier(2);
final boolean[] hs = new boolean[] { true };
Thread client = new ClientThread(factory, testOne, testTwo, testThree, barrier);
client.setDaemon(false);
client.start();
try {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().setReceiveBufferSize(64 * 1024);
while (true) {
try {
serverSocketChannel.socket().bind(new InetSocketAddress(port));
break;
} catch (BindException e) {
port++;
}
}
barrier.await();
SocketChannel sock = serverSocketChannel.accept();
barrier.reset();
SSLSocketChannel wrappedChannel = (SSLSocketChannel) factory.wrapServerChannel(sock);
assertTrue(wrappedChannel.isHandshakeComplete());
// FIRST TEST: SSL -> SSL SMALL COMMUNICATION
ByteBuffer readBuffer = ByteBuffer.allocate(12);
while (readBuffer.hasRemaining()) {
wrappedChannel.read(readBuffer);
}
readBuffer.flip();
byte[] dst = new byte[12];
readBuffer.get(dst, 0, 12);
readBuffer.clear();
assertEquals("hello, world", new String(dst, "UTF-8"));
testOne.await();
// SECOND TEST: SSL -> SSL BIG COMMUNICATION
int read = 0;
byte[] dstBig = new byte[16];
ByteBuffer readBufferBig = ByteBuffer.allocate(1024);
while (read < 5 * 64 * 1024) {
while (readBufferBig.position() < 16) {
wrappedChannel.read(readBufferBig);
}
readBufferBig.flip();
readBufferBig.get(dstBig, 0, 16);
if (!readBufferBig.hasRemaining()) {
readBufferBig.clear();
} else {
readBufferBig.compact();
}
assertEquals("hello, world" + (read % 9) + "!!!", new String(dstBig, "UTF-8"));
read += 16;
}
testTwo.await();
// THIRD TEST: NON-SSL -> SSL COMMUNICATION
try {
while (readBuffer.hasRemaining()) {
wrappedChannel.read(readBuffer);
}
fail();
} catch (SSLException e) {
// PASSED
}
assertTrue(wrappedChannel.getEngine().isInboundDone());
testThree.await();
// FOURTH TEST: SSL -> NON-SSL COMMUNICATION
readBuffer.clear();
while (readBuffer.hasRemaining()) {
sock.read(readBuffer);
}
readBuffer.flip();
readBuffer.get(dst, 0, 12);
readBuffer.clear();
assertNotEquals("hello, world", new String(dst, "UTF-8"));
} catch (IOException | InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
barrier.await();
assertTrue("One of the handshakes failed!", hs[0]);
}
use of java.net.BindException in project flink by apache.
the class BootstrapTools method startActorSystem.
/**
* Starts an ActorSystem with the given configuration listening at the address/ports.
* @param configuration The Flink configuration
* @param listeningAddress The address to listen at.
* @param portRangeDefinition The port range to choose a port from.
* @param logger The logger to output log information.
* @return The ActorSystem which has been started
* @throws Exception
*/
public static ActorSystem startActorSystem(Configuration configuration, String listeningAddress, String portRangeDefinition, Logger logger) throws Exception {
// parse port range definition and create port iterator
Iterator<Integer> portsIterator;
try {
portsIterator = NetUtils.getPortRangeFromString(portRangeDefinition);
} catch (Exception e) {
throw new IllegalArgumentException("Invalid port range definition: " + portRangeDefinition);
}
while (portsIterator.hasNext()) {
// first, we check if the port is available by opening a socket
// if the actor system fails to start on the port, we try further
ServerSocket availableSocket = NetUtils.createSocketFromPorts(portsIterator, new NetUtils.SocketFactory() {
@Override
public ServerSocket createSocket(int port) throws IOException {
return new ServerSocket(port);
}
});
int port;
if (availableSocket == null) {
throw new BindException("Unable to allocate further port in port range: " + portRangeDefinition);
} else {
port = availableSocket.getLocalPort();
try {
availableSocket.close();
} catch (IOException ignored) {
}
}
try {
return startActorSystem(configuration, listeningAddress, port, logger);
} catch (Exception e) {
// we can continue to try if this contains a netty channel exception
Throwable cause = e.getCause();
if (!(cause instanceof org.jboss.netty.channel.ChannelException || cause instanceof java.net.BindException)) {
throw e;
}
// else fall through the loop and try the next port
}
}
// if we come here, we have exhausted the port range
throw new BindException("Could not start actor system on any port in port range " + portRangeDefinition);
}
Aggregations