Search in sources :

Example 86 with ConnectException

use of java.net.ConnectException in project voldemort by voldemort.

the class ClientRequestExecutorFactory method createAsync.

/**
     * Create a ClientRequestExecutor for the given {@link SocketDestination}.
     *
     * @param dest {@link SocketDestination}
     */
@Override
public void createAsync(final SocketDestination dest, final KeyedResourcePool<SocketDestination, ClientRequestExecutor> pool) throws Exception {
    int numCreated = created.incrementAndGet();
    if (logger.isDebugEnabled())
        logger.debug("Creating socket " + numCreated + " for " + dest.getHost() + ":" + dest.getPort() + " using protocol " + dest.getRequestFormatType().getCode());
    SocketChannel socketChannel = null;
    ClientRequestExecutor clientRequestExecutor = null;
    long durationMs = 0;
    try {
        socketChannel = SocketChannel.open();
        socketChannel.socket().setReceiveBufferSize(this.socketBufferSize);
        socketChannel.socket().setSendBufferSize(this.socketBufferSize);
        socketChannel.socket().setTcpNoDelay(true);
        socketChannel.socket().setSoTimeout(soTimeoutMs);
        socketChannel.socket().setKeepAlive(this.socketKeepAlive);
        socketChannel.configureBlocking(false);
        socketChannel.connect(new InetSocketAddress(dest.getHost(), dest.getPort()));
        if (logger.isDebugEnabled()) {
            logger.debug("Created socket " + numCreated + " for " + dest.getHost() + ":" + dest.getPort() + " using protocol " + dest.getRequestFormatType().getCode() + " after " + durationMs + " ms.");
        }
        ClientRequestSelectorManager selectorManager = selectorManagers[counter.getAndIncrement() % selectorManagers.length];
        Selector selector = selectorManager.getSelector();
        clientRequestExecutor = new ClientRequestExecutor(selector, socketChannel, socketBufferSize, idleConnectionTimeoutNs, dest);
        int timeoutMs = this.getTimeout();
        ProtocolNegotiatorClientRequest protocolRequest = new ProtocolNegotiatorClientRequest(dest.getRequestFormatType());
        NonblockingStoreCallback callback = new NonblockingStoreCallback() {

            @Override
            public void requestComplete(Object result, long requestTime) {
                if (result instanceof Exception) {
                    Exception e = (Exception) result;
                    /*
                         * There are 2 places where we can get a store timeout
                         * Exception
                         * 
                         * 1) While doing connect - the machine was up once, but
                         * not anymore. In that case, TCP SYN will be sent by
                         * the client, but server would not sent TCP ACK as it
                         * is dead.
                         * 
                         * 2) After connect doing Protocol Negotiation - Most
                         * likely the server and kernel is up, but the process
                         * is in a zombie state because of hard drive failure or
                         * stuck in shutdown or doing a GC. This can be
                         * intermittent or hard failures. Before this code
                         * change, if the process entered this state, Voldemort
                         * clients may not detect the failure immediately. They
                         * are treated as normal errors, instead of catastrophic
                         * erros.This was the reason before it is better to kill
                         * the process on a machine and let the machine stay up.
                         * After this code change they will be treated as
                         * connection failures ( catastrophic errors) to help
                         * recover the clients faster.
                         * 
                         * The second case can increase the false positives, but
                         * if a server is consistently timing out it is better
                         * to treat the server as dead and let the clients
                         * recover faster.
                         */
                    if (e instanceof StoreTimeoutException) {
                        e = new UnreachableStoreException("Error establishing connection for destination " + dest, new ConnectException(e.getMessage()));
                    }
                    if (logger.isDebugEnabled()) {
                        logger.debug("Reporting exception to pool " + e.getClass() + " for destination " + dest);
                    }
                    pool.reportException(dest, e);
                }
            }
        };
        NonblockingStoreCallbackClientRequest<String> clientRequest = new NonblockingStoreCallbackClientRequest<String>(pool, dest, protocolRequest, clientRequestExecutor, callback, stats);
        clientRequestExecutor.setConnectRequest(clientRequest, timeoutMs);
        selectorManager.add(clientRequestExecutor);
        selector.wakeup();
    } catch (Exception e) {
        // Make sure not to leak socketChannels
        if (socketChannel != null) {
            try {
                socketChannel.close();
            } catch (Exception ex) {
                if (logger.isEnabledFor(Level.WARN))
                    logger.warn(ex, ex);
            }
        }
        throw UnreachableStoreException.wrap("Error establishing connection for destination " + dest, e);
    }
    if (stats != null) {
        stats.incrementCount(dest, ClientSocketStats.Tracked.CONNECTION_CREATED_EVENT);
        stats.recordConnectionEstablishmentTimeUs(dest, durationMs * Time.US_PER_MS);
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) InetSocketAddress(java.net.InetSocketAddress) ConnectException(java.net.ConnectException) StoreTimeoutException(voldemort.store.StoreTimeoutException) ClosedChannelException(java.nio.channels.ClosedChannelException) UnreachableStoreException(voldemort.store.UnreachableStoreException) ClosedSelectorException(java.nio.channels.ClosedSelectorException) NonblockingStoreCallback(voldemort.store.nonblockingstore.NonblockingStoreCallback) StoreTimeoutException(voldemort.store.StoreTimeoutException) UnreachableStoreException(voldemort.store.UnreachableStoreException) Selector(java.nio.channels.Selector) ConnectException(java.net.ConnectException)

Example 87 with ConnectException

use of java.net.ConnectException in project voldemort by voldemort.

the class ClientRequestExecutorPoolTest method testRememberedExceptionsBeyondTime.

@Test
public void testRememberedExceptionsBeyondTime() throws Exception {
    final int CURRENT_CONNECTION_TIMEOUT = 50;
    ClientRequestExecutorPool timeoutPool = new ClientRequestExecutorPool(2, maxConnectionsPerNode, CURRENT_CONNECTION_TIMEOUT, CURRENT_CONNECTION_TIMEOUT, IDLE_CONNECTION_TIMEOUT_MS, 32 * 1024, false, true, new String());
    ConnectException connectEx = new ConnectException("Connect exception");
    UnreachableStoreException unreachableEx = new UnreachableStoreException("test Exception", connectEx);
    final int COUNT = 10;
    for (int i = 0; i < COUNT; i++) {
        timeoutPool.internalGetQueuedPool().reportException(dest1, unreachableEx);
    }
    Thread.sleep(CURRENT_CONNECTION_TIMEOUT);
    // Get all exceptions but 1.
    for (int i = 0; i < COUNT - 1; i++) {
        try {
            timeoutPool.internalGetQueuedPool().checkout(dest1);
            fail("should have thrown an exception");
        } catch (Exception ex) {
        }
    }
    Thread.sleep(CURRENT_CONNECTION_TIMEOUT + 1);
    // should not fail
    timeoutPool.checkout(dest1);
}
Also used : ClientRequestExecutorPool(voldemort.store.socket.clientrequest.ClientRequestExecutorPool) UnreachableStoreException(voldemort.store.UnreachableStoreException) ConnectException(java.net.ConnectException) UnreachableStoreException(voldemort.store.UnreachableStoreException) IOException(java.io.IOException) UnresolvedAddressException(java.nio.channels.UnresolvedAddressException) ConnectException(java.net.ConnectException) Test(org.junit.Test)

Example 88 with ConnectException

use of java.net.ConnectException in project voldemort by voldemort.

the class ExceptionUtilsTest method testRecursiveClassEquals.

@Test
public void testRecursiveClassEquals() {
    Assert.assertTrue("recursiveClassEquals should recognize the top-level exception.", ExceptionUtils.recursiveClassEquals(new VoldemortException("blah", new IOException("bleh")), VoldemortException.class));
    Assert.assertFalse("recursiveClassEquals should NOT recognize the exception.", ExceptionUtils.recursiveClassEquals(new VoldemortException("blah", new IOException("bleh")), NullPointerException.class));
    Assert.assertTrue("recursiveClassEquals should recognize a nested exception.", ExceptionUtils.recursiveClassEquals(new VoldemortException("blah", new IOException("bleh")), IOException.class));
    Assert.assertTrue("recursiveClassEquals should recognize a nested exception which is the child of the class we're looking for.", ExceptionUtils.recursiveClassEquals(new VoldemortException("blah", new ConnectException("bleh")), IOException.class));
    Assert.assertFalse("recursiveClassEquals should NOT recognize a nested exception which is the parent of the class we're looking for.", ExceptionUtils.recursiveClassEquals(new VoldemortException("blah", new IOException("bleh")), ConnectException.class));
}
Also used : IOException(java.io.IOException) VoldemortException(voldemort.VoldemortException) ConnectException(java.net.ConnectException) Test(org.junit.Test)

Example 89 with ConnectException

use of java.net.ConnectException in project intellij-community by JetBrains.

the class SocketLock method tryActivate.

@NotNull
private ActivateStatus tryActivate(int portNumber, @NotNull Collection<String> paths, @NotNull String[] args) {
    log("trying: port=%s", portNumber);
    args = checkForJetBrainsProtocolCommand(args);
    try {
        try (Socket socket = new Socket(InetAddress.getLoopbackAddress(), portNumber)) {
            socket.setSoTimeout(1000);
            boolean result = false;
            @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") DataInputStream in = new DataInputStream(socket.getInputStream());
            while (true) {
                try {
                    String path = in.readUTF();
                    log("read: path=%s", path);
                    if (PATHS_EOT_RESPONSE.equals(path)) {
                        break;
                    } else if (paths.contains(path)) {
                        // don't break - read all input
                        result = true;
                    }
                } catch (IOException e) {
                    log("read: %s", e.getMessage());
                    break;
                }
            }
            if (result) {
                try {
                    String token = FileUtil.loadFile(new File(mySystemPath, TOKEN_FILE));
                    @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") DataOutputStream out = new DataOutputStream(socket.getOutputStream());
                    out.writeUTF(ACTIVATE_COMMAND + token + "\0" + new File(".").getAbsolutePath() + "\0" + StringUtil.join(args, "\0"));
                    out.flush();
                    String response = in.readUTF();
                    log("read: response=%s", response);
                    if (response.equals(OK_RESPONSE)) {
                        if (isShutdownCommand()) {
                            printPID(portNumber);
                        }
                        return ActivateStatus.ACTIVATED;
                    }
                } catch (IOException e) {
                    log(e);
                }
                return ActivateStatus.CANNOT_ACTIVATE;
            }
        }
    } catch (ConnectException e) {
        log("%s (stale port file?)", e.getMessage());
    } catch (IOException e) {
        log(e);
    }
    return ActivateStatus.NO_INSTANCE;
}
Also used : Socket(java.net.Socket) ConnectException(java.net.ConnectException) NotNull(org.jetbrains.annotations.NotNull)

Example 90 with ConnectException

use of java.net.ConnectException in project platform_external_apache-http by android.

the class DefaultClientConnectionOperator method updateSecureConnection.

// openConnection
// non-javadoc, see interface ClientConnectionOperator
public void updateSecureConnection(OperatedClientConnection conn, HttpHost target, HttpContext context, HttpParams params) throws IOException {
    if (conn == null) {
        throw new IllegalArgumentException("Connection must not be null.");
    }
    if (target == null) {
        throw new IllegalArgumentException("Target host must not be null.");
    }
    //@@@ is context allowed to be null?
    if (params == null) {
        throw new IllegalArgumentException("Parameters must not be null.");
    }
    if (!conn.isOpen()) {
        throw new IllegalArgumentException("Connection must be open.");
    }
    final Scheme schm = schemeRegistry.getScheme(target.getSchemeName());
    if (!(schm.getSocketFactory() instanceof LayeredSocketFactory)) {
        throw new IllegalArgumentException("Target scheme (" + schm.getName() + ") must have layered socket factory.");
    }
    final LayeredSocketFactory lsf = (LayeredSocketFactory) schm.getSocketFactory();
    final Socket sock;
    try {
        sock = lsf.createSocket(conn.getSocket(), target.getHostName(), schm.resolvePort(target.getPort()), true);
    } catch (ConnectException ex) {
        throw new HttpHostConnectException(target, ex);
    }
    prepareSocket(sock, context, params);
    conn.update(sock, target, lsf.isSecure(sock), params);
//@@@ error handling: close the layered socket in case of exception?
}
Also used : Scheme(org.apache.http.conn.scheme.Scheme) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) LayeredSocketFactory(org.apache.http.conn.scheme.LayeredSocketFactory) Socket(java.net.Socket) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) ConnectException(java.net.ConnectException)

Aggregations

ConnectException (java.net.ConnectException)253 IOException (java.io.IOException)110 Socket (java.net.Socket)57 Test (org.junit.Test)43 InetSocketAddress (java.net.InetSocketAddress)41 SocketTimeoutException (java.net.SocketTimeoutException)35 UnknownHostException (java.net.UnknownHostException)30 InetAddress (java.net.InetAddress)24 FileNotFoundException (java.io.FileNotFoundException)22 InterruptedIOException (java.io.InterruptedIOException)20 SocketException (java.net.SocketException)20 NoRouteToHostException (java.net.NoRouteToHostException)19 InputStreamReader (java.io.InputStreamReader)18 URL (java.net.URL)16 InputStream (java.io.InputStream)14 HttpURLConnection (java.net.HttpURLConnection)14 TimeoutTracker (org.opennms.core.utils.TimeoutTracker)13 BufferedReader (java.io.BufferedReader)12 OutputStream (java.io.OutputStream)12 Exchange (org.apache.camel.Exchange)12