Search in sources :

Example 46 with BindException

use of java.net.BindException in project hive by apache.

the class MiniZooKeeperCluster method startup.

/**
 * @param baseDir
 * @param numZooKeeperServers
 * @return ClientPort server bound to, -1 if there was a
 *         binding problem and we couldn't pick another port.
 * @throws IOException
 * @throws InterruptedException
 */
public int startup(File baseDir, int numZooKeeperServers) throws IOException, InterruptedException {
    if (numZooKeeperServers <= 0) {
        return -1;
    }
    setupTestEnv();
    shutdown();
    // the seed port
    int tentativePort = -1;
    int currentClientPort;
    // running all the ZK servers
    for (int i = 0; i < numZooKeeperServers; i++) {
        File dir = new File(baseDir, "zookeeper_" + i).getAbsoluteFile();
        createDir(dir);
        int tickTimeToUse;
        if (this.tickTime > 0) {
            tickTimeToUse = this.tickTime;
        } else {
            tickTimeToUse = TICK_TIME;
        }
        // Set up client port - if we have already had a list of valid ports, use it.
        if (hasValidClientPortInList(i)) {
            currentClientPort = clientPortList.get(i);
        } else {
            // update the seed
            tentativePort = selectClientPort(tentativePort);
            currentClientPort = tentativePort;
        }
        ZooKeeperServer server = new ZooKeeperServer(dir, dir, tickTimeToUse);
        // Setting {min,max}SessionTimeout defaults to be the same as in Zookeeper
        server.setMinSessionTimeout(configuration.getInt("hbase.zookeeper.property.minSessionTimeout", -1));
        server.setMaxSessionTimeout(configuration.getInt("hbase.zookeeper.property.maxSessionTimeout", -1));
        NIOServerCnxnFactory standaloneServerFactory;
        while (true) {
            try {
                standaloneServerFactory = new NIOServerCnxnFactory();
                standaloneServerFactory.configure(new InetSocketAddress(currentClientPort), configuration.getInt(HConstants.ZOOKEEPER_MAX_CLIENT_CNXNS, HConstants.DEFAULT_ZOOKEPER_MAX_CLIENT_CNXNS));
            } catch (BindException e) {
                LOG.debug("Failed binding ZK Server to client port: " + currentClientPort, e);
                // We're told to use some port but it's occupied, fail
                if (hasValidClientPortInList(i)) {
                    return -1;
                }
                // This port is already in use, try to use another.
                tentativePort = selectClientPort(tentativePort);
                currentClientPort = tentativePort;
                continue;
            }
            break;
        }
        // Start up this ZK server
        standaloneServerFactory.startup(server);
        // Runs a 'stat' against the servers.
        if (!waitForServerUp(currentClientPort, connectionTimeout)) {
            throw new IOException("Waiting for startup of standalone server");
        }
        // We have selected a port as a client port.  Update clientPortList if necessary.
        if (clientPortList.size() <= i) {
            // it is not in the list, add the port
            clientPortList.add(currentClientPort);
        } else if (clientPortList.get(i) <= 0) {
            // the list has invalid port, update with valid port
            clientPortList.remove(i);
            clientPortList.add(i, currentClientPort);
        }
        standaloneServerFactoryList.add(standaloneServerFactory);
        zooKeeperServers.add(server);
    }
    // set the first one to be active ZK; Others are backups
    activeZKServerIndex = 0;
    started = true;
    int clientPort = clientPortList.get(activeZKServerIndex);
    LOG.info("Started MiniZooKeeperCluster and ran successful 'stat' " + "on client port=" + clientPort);
    return clientPort;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) BindException(java.net.BindException) NIOServerCnxnFactory(org.apache.zookeeper.server.NIOServerCnxnFactory) IOException(java.io.IOException) InterruptedIOException(java.io.InterruptedIOException) File(java.io.File) ZooKeeperServer(org.apache.zookeeper.server.ZooKeeperServer)

Example 47 with BindException

use of java.net.BindException in project knime-core by knime.

the class HelpviewPlugin method start.

/**
 * This method is called upon plug-in activation.
 *
 * {@inheritDoc}
 */
@Override
public void start(final BundleContext context) throws Exception {
    super.start(context);
    // initialize jetty's logging system
    if (System.getProperty("org.mortbay.log.class") == null) {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        try {
            Thread.currentThread().setContextClassLoader(JettyLogger.class.getClassLoader());
            System.setProperty("org.mortbay.log.class", JettyLogger.class.getName());
            Log.getLog();
        } finally {
            Thread.currentThread().setContextClassLoader(cl);
        }
    }
    // start an embedded webserver for serving bundle-local or node-local
    // files in the node descriptions
    m_server = new Server();
    NetworkTrafficServerConnector connector = new NetworkTrafficServerConnector(m_server);
    connector.setPort(PORT);
    try {
        connector.setHost(InetAddress.getLocalHost().getHostAddress());
    } catch (UnknownHostException ex) {
        // sometimes the above returns this exception; yeah, strange
        try {
            connector.setHost(InetAddress.getByName("localhost").getHostAddress());
        } catch (UnknownHostException ex1) {
            logger.error("Cannot start embedded webserver: " + ex.getMessage(), ex);
        }
    }
    m_server.addConnector(connector);
    m_server.setHandler(FileHandler.instance);
    try {
        m_server.start();
    } catch (BindException ex) {
        logger.error("Cannot start embedded webserver: " + ex.getMessage(), ex);
    // ignore exception otherwise the plugin is not initialized
    }
}
Also used : Server(org.eclipse.jetty.server.Server) UnknownHostException(java.net.UnknownHostException) BindException(java.net.BindException) NetworkTrafficServerConnector(org.eclipse.jetty.server.NetworkTrafficServerConnector)

Example 48 with BindException

use of java.net.BindException in project ignite by apache.

the class ServerSocketMultiThreadedTest method testConcurrentBind.

/**
 * @throws Exception If failed.
 */
public void testConcurrentBind() throws Exception {
    final AtomicInteger bindExCnt = new AtomicInteger();
    final AtomicInteger sockExCnt = new AtomicInteger();
    final AtomicInteger okCnt = new AtomicInteger();
    final CyclicBarrier finishBarrier = new CyclicBarrier(THREADS_CNT, new Runnable() {

        private int i;

        @Override
        public void run() {
            if (++i % 250 == 0)
                X.println("Finished iteration [threadName=" + Thread.currentThread().getName() + ", iter=" + i + ']');
        }
    });
    final InetAddress addr = InetAddress.getByName("127.0.0.1");
    GridTestUtils.runMultiThreaded(new Callable<Object>() {

        @Nullable
        @Override
        public Object call() throws Exception {
            ServerSocket srvSock = null;
            for (int i = 0; i < ITER_CNT; i++) {
                try {
                    srvSock = new ServerSocket(60000, 0, addr);
                    okCnt.incrementAndGet();
                } catch (BindException ignore) {
                    bindExCnt.incrementAndGet();
                } catch (SocketException ignore) {
                    sockExCnt.incrementAndGet();
                } finally {
                    finishBarrier.await();
                    U.closeQuiet(srvSock);
                }
            }
            return null;
        }
    }, THREADS_CNT, "binder");
    X.println("Test stats [bindExCnt=" + bindExCnt.get() + ", sockExCnt=" + sockExCnt.get() + ", okCnt=" + okCnt + ']');
}
Also used : SocketException(java.net.SocketException) BindException(java.net.BindException) ServerSocket(java.net.ServerSocket) SocketException(java.net.SocketException) BindException(java.net.BindException) CyclicBarrier(java.util.concurrent.CyclicBarrier) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) InetAddress(java.net.InetAddress) Nullable(org.jetbrains.annotations.Nullable)

Example 49 with BindException

use of java.net.BindException in project ignite by apache.

the class GridTcpCommunicationSpiRecoverySelfTest method testBlockRead2.

/**
 * @throws Exception If failed.
 */
public void testBlockRead2() throws Exception {
    createSpis();
    try {
        final TcpCommunicationSpi spi0 = spis.get(0);
        final TcpCommunicationSpi spi1 = spis.get(1);
        final TestListener lsnr0 = (TestListener) spi0.getListener();
        final TestListener lsnr1 = (TestListener) spi1.getListener();
        final ClusterNode node0 = nodes.get(0);
        final ClusterNode node1 = nodes.get(1);
        final AtomicInteger msgId = new AtomicInteger();
        final AtomicInteger expCnt0 = new AtomicInteger();
        final AtomicInteger expCnt1 = new AtomicInteger();
        // Send message to establish connection.
        spi0.sendMessage(node1, new GridTestMessage(node0.id(), msgId.incrementAndGet(), 0));
        GridTestUtils.waitForCondition(new GridAbsPredicate() {

            @Override
            public boolean apply() {
                return lsnr1.rcvCnt.get() >= 1;
            }
        }, 1000);
        expCnt1.incrementAndGet();
        int errCnt = 0;
        for (int i = 0; i < ITERS; i++) {
            log.info("Iteration: " + i);
            try {
                final GridNioSession ses0 = communicationSession(spi0, false);
                final GridNioSession ses1 = communicationSession(spi1, true);
                ses1.pauseReads().get();
                IgniteInternalFuture<?> sndFut = GridTestUtils.runAsync(new Callable<Void>() {

                    @Override
                    public Void call() throws Exception {
                        for (int i = 0; i < 6000; i++) {
                            spi0.sendMessage(node1, new GridTestMessage(node0.id(), msgId.incrementAndGet(), 0));
                            expCnt1.incrementAndGet();
                        }
                        return null;
                    }
                });
                // Wait when session is closed because of write timeout.
                GridTestUtils.waitForCondition(new GridAbsPredicate() {

                    @Override
                    public boolean apply() {
                        return ses0.closeTime() != 0;
                    }
                }, awaitForSocketWriteTimeout());
                assertTrue("Failed to wait for session close", ses0.closeTime() != 0);
                try {
                    ses1.resumeReads().get();
                } catch (IgniteCheckedException ignore) {
                // Can fail if ses1 was closed.
                }
                // Wait when session is closed, then try to open new connection from node1.
                GridTestUtils.waitForCondition(new GridAbsPredicate() {

                    @Override
                    public boolean apply() {
                        return ses1.closeTime() != 0;
                    }
                }, awaitForSocketWriteTimeout());
                assertTrue("Failed to wait for session close", ses1.closeTime() != 0);
                for (int j = 0; j < 100; j++) {
                    spi1.sendMessage(node0, new GridTestMessage(node1.id(), msgId.incrementAndGet(), 0));
                    expCnt0.incrementAndGet();
                }
                sndFut.get();
                final int expMsgs0 = expCnt0.get();
                final int expMsgs1 = expCnt1.get();
                GridTestUtils.waitForCondition(new GridAbsPredicate() {

                    @Override
                    public boolean apply() {
                        return lsnr0.rcvCnt.get() >= expMsgs0 && lsnr1.rcvCnt.get() >= expMsgs1;
                    }
                }, 60_000);
                assertEquals(expMsgs0, lsnr0.rcvCnt.get());
                assertEquals(expMsgs1, lsnr1.rcvCnt.get());
            } catch (IgniteCheckedException e) {
                if (e.hasCause(BindException.class)) {
                    errCnt++;
                    if (errCnt > 3) {
                        log.warning("Got exception > 3 times, test fails.");
                        throw e;
                    }
                    if (i < ITERS - 1) {
                        info("Got exception caused by BindException, will retry after delay: " + e);
                        U.sleep(10_000);
                    } else
                        info("Got exception caused by BindException, will ignore: " + e);
                } else {
                    log.warning("Unexpected exception: " + e, e);
                    throw e;
                }
            }
        }
    } finally {
        stopSpis();
    }
}
Also used : ClusterNode(org.apache.ignite.cluster.ClusterNode) GridTestMessage(org.apache.ignite.spi.communication.GridTestMessage) GridNioSession(org.apache.ignite.internal.util.nio.GridNioSession) GridAbsPredicate(org.apache.ignite.internal.util.lang.GridAbsPredicate) BindException(java.net.BindException) IgniteSpiException(org.apache.ignite.spi.IgniteSpiException) BindException(java.net.BindException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger)

Example 50 with BindException

use of java.net.BindException in project Payara by payara.

the class PayaraMicroImpl method configurePorts.

private void configurePorts() throws GlassFishException {
    PortBinder portBinder = new PortBinder();
    if (httpPort != Integer.MIN_VALUE) {
        if (autoBindHttp == true) {
            // Log warnings if overriding other options
            logPortPrecedenceWarnings(false);
            // Search for an available port from the specified port
            try {
                int port = portBinder.findAvailablePort(httpPort, autoBindRange);
                preBootCommands.add(new BootCommand("set", "configs.config.server-config.network-config.network-listeners.network-listener.http-listener.port=" + port));
                preBootCommands.add(new BootCommand("set", "configs.config.server-config.network-config.network-listeners.network-listener.http-listener.enabled=true"));
            } catch (BindException ex) {
                LOGGER.log(Level.SEVERE, "No available port found in range: " + httpPort + " - " + (httpPort + autoBindRange), ex);
                throw new GlassFishException("Could not bind HTTP port");
            }
        } else {
            // Log warnings if overriding other options
            logPortPrecedenceWarnings(false);
            preBootCommands.add(new BootCommand("set", "configs.config.server-config.network-config.network-listeners.network-listener.http-listener.port=" + httpPort));
        }
    } else if (autoBindHttp == true) {
        // Log warnings if overriding other options
        logPortPrecedenceWarnings(false);
        // Search for an available port from the default HTTP port
        try {
            int port = portBinder.findAvailablePort(defaultHttpPort, autoBindRange);
            preBootCommands.add(new BootCommand("set", "configs.config.server-config.network-config.network-listeners.network-listener.http-listener.port=" + port));
            preBootCommands.add(new BootCommand("set", "configs.config.server-config.network-config.network-listeners.network-listener.http-listener.enabled=true"));
        } catch (BindException ex) {
            LOGGER.log(Level.SEVERE, "No available port found in range: " + defaultHttpPort + " - " + (defaultHttpPort + autoBindRange), ex);
            throw new GlassFishException("Could not bind HTTP port");
        }
    }
    if (sslPort != Integer.MIN_VALUE) {
        if (autoBindSsl == true) {
            // Log warnings if overriding other options
            logPortPrecedenceWarnings(true);
            // Search for an available port from the specified port
            try {
                int port = portBinder.findAvailablePort(sslPort, autoBindRange);
                preBootCommands.add(new BootCommand("set", "configs.config.server-config.network-config.network-listeners.network-listener.https-listener.port=" + port));
                preBootCommands.add(new BootCommand("set", "configs.config.server-config.network-config.network-listeners.network-listener.https-listener.enabled=true"));
            } catch (BindException ex) {
                LOGGER.log(Level.SEVERE, "No available port found in range: " + sslPort + " - " + (sslPort + autoBindRange), ex);
                throw new GlassFishException("Could not bind SSL port");
            }
        } else {
            // Log warnings if overriding other options
            logPortPrecedenceWarnings(true);
            // Set the port as normal
            preBootCommands.add(new BootCommand("set", "configs.config.server-config.network-config.network-listeners.network-listener.https-listener.port=" + sslPort));
            preBootCommands.add(new BootCommand("set", "configs.config.server-config.network-config.network-listeners.network-listener.https-listener.enabled=true"));
        }
    } else if (autoBindSsl == true) {
        // Log warnings if overriding other options
        logPortPrecedenceWarnings(true);
        // Search for an available port from the default HTTPS port
        try {
            int port = portBinder.findAvailablePort(defaultHttpsPort, autoBindRange);
            preBootCommands.add(new BootCommand("set", "configs.config.server-config.network-config.network-listeners.network-listener.https-listener.port=" + port));
            preBootCommands.add(new BootCommand("set", "configs.config.server-config.network-config.network-listeners.network-listener.https-listener.enabled=true"));
        } catch (BindException ex) {
            LOGGER.log(Level.SEVERE, "No available port found in range: " + defaultHttpsPort + " - " + (defaultHttpsPort + autoBindRange), ex);
            throw new GlassFishException("Could not bind SSL port");
        }
    }
    if (sslCert != null) {
        preBootCommands.add(new BootCommand("set", "configs.config.server-config.network-config.protocols.protocol.https-listener.ssl.cert-nickname=" + sslCert));
    }
}
Also used : GlassFishException(org.glassfish.embeddable.GlassFishException) BootCommand(fish.payara.micro.boot.runtime.BootCommand) BindException(java.net.BindException)

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