Search in sources :

Example 51 with BindException

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);
            }
        }
    }
}
Also used : UnknownHostException(java.net.UnknownHostException) HashMap(java.util.HashMap) SSLServerSocketFactory(javax.net.ssl.SSLServerSocketFactory) ServerSocketFactory(javax.net.ServerSocketFactory) InetSocketAddress(java.net.InetSocketAddress) BindException(java.net.BindException) ServerSocket(java.net.ServerSocket) SSLServerSocket(javax.net.ssl.SSLServerSocket) SSLServerSocket(javax.net.ssl.SSLServerSocket) URI(java.net.URI) BindException(java.net.BindException) SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 52 with BindException

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;
}
Also used : LocalServerSocket(android.net.LocalServerSocket) BindException(java.net.BindException) IOException(java.io.IOException) InterruptedIOException(java.io.InterruptedIOException) Nonnull(javax.annotation.Nonnull)

Example 53 with BindException

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);
    }
}
Also used : BytesArray(org.elasticsearch.common.bytes.BytesArray) CancelledKeyException(java.nio.channels.CancelledKeyException) AbstractRunnable(org.elasticsearch.common.util.concurrent.AbstractRunnable) AbstractLifecycleRunnable(org.elasticsearch.common.util.concurrent.AbstractLifecycleRunnable) BindException(java.net.BindException) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) Supplier(org.apache.logging.log4j.util.Supplier) IOException(java.io.IOException)

Example 54 with BindException

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]);
}
Also used : ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketChannel(java.nio.channels.SocketChannel) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) InetSocketAddress(java.net.InetSocketAddress) BindException(java.net.BindException) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) SSLException(javax.net.ssl.SSLException) CyclicBarrier(java.util.concurrent.CyclicBarrier) ServerSocketChannel(java.nio.channels.ServerSocketChannel) Test(org.junit.Test)

Example 55 with BindException

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);
}
Also used : BindException(java.net.BindException) ServerSocket(java.net.ServerSocket) IOException(java.io.IOException) BindException(java.net.BindException) IOException(java.io.IOException) NetUtils(org.apache.flink.util.NetUtils)

Aggregations

BindException (java.net.BindException)104 IOException (java.io.IOException)34 InetSocketAddress (java.net.InetSocketAddress)25 ServerSocket (java.net.ServerSocket)22 Test (org.junit.Test)22 File (java.io.File)12 SocketException (java.net.SocketException)10 Configuration (org.apache.hadoop.conf.Configuration)10 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)6 InterruptedIOException (java.io.InterruptedIOException)5 MiniDFSNNTopology (org.apache.hadoop.hdfs.MiniDFSNNTopology)5 InetAddress (java.net.InetAddress)4 UnknownHostException (java.net.UnknownHostException)4 RemoteException (java.rmi.RemoteException)4 NIOServerCnxnFactory (org.apache.zookeeper.server.NIOServerCnxnFactory)4 ZooKeeperServer (org.apache.zookeeper.server.ZooKeeperServer)4 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)3 Socket (java.net.Socket)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3