Search in sources :

Example 71 with SocketChannel

use of java.nio.channels.SocketChannel in project asterixdb by apache.

the class ReplicationManager method sendRequest.

/**
     * Sends a request to remote replicas
     *
     * @param replicaSockets
     *            The sockets to send the request to.
     * @param requestBuffer
     *            The buffer that contains the request.
     */
private void sendRequest(Map<String, SocketChannel> replicaSockets, ByteBuffer requestBuffer) {
    Iterator<Map.Entry<String, SocketChannel>> iterator = replicaSockets.entrySet().iterator();
    while (iterator.hasNext()) {
        Entry<String, SocketChannel> replicaSocket = iterator.next();
        SocketChannel clientSocket = replicaSocket.getValue();
        try {
            NetworkingUtil.transferBufferToChannel(clientSocket, requestBuffer);
        } catch (IOException e) {
            handleReplicationFailure(clientSocket, e);
            iterator.remove();
        } finally {
            requestBuffer.position(0);
        }
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) Entry(java.util.Map.Entry) IOException(java.io.IOException)

Example 72 with SocketChannel

use of java.nio.channels.SocketChannel in project asterixdb by apache.

the class ReplicationManager method getActiveRemoteReplicasSockets.

private Map<String, SocketChannel> getActiveRemoteReplicasSockets() {
    Map<String, SocketChannel> replicaNodesSockets = new HashMap<>();
    for (Replica replica : replicas.values()) {
        if (replica.getState() == ReplicaState.ACTIVE) {
            try {
                SocketChannel sc = getReplicaSocket(replica.getId());
                replicaNodesSockets.put(replica.getId(), sc);
            } catch (IOException e) {
                if (LOGGER.isLoggable(Level.WARNING)) {
                    LOGGER.log(Level.WARNING, "Could not get replica socket", e);
                }
                reportFailedReplica(replica.getId());
            }
        }
    }
    return replicaNodesSockets;
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) IOException(java.io.IOException) Replica(org.apache.asterix.common.replication.Replica)

Example 73 with SocketChannel

use of java.nio.channels.SocketChannel in project ignite by apache.

the class TcpCommunicationSpi method safeHandshake.

/**
     * Performs handshake in timeout-safe way.
     *
     * @param client Client.
     * @param recovery Recovery descriptor if use recovery handshake, otherwise {@code null}.
     * @param rmtNodeId Remote node.
     * @param timeout Timeout for handshake.
     * @param sslMeta Session meta.
     * @param handshakeConnIdx Non null connection index if need send it in handshake.
     * @throws IgniteCheckedException If handshake failed or wasn't completed withing timeout.
     * @return Handshake response.
     */
@SuppressWarnings("ThrowFromFinallyBlock")
private <T> long safeHandshake(T client, @Nullable GridNioRecoveryDescriptor recovery, UUID rmtNodeId, long timeout, GridSslMeta sslMeta, @Nullable Integer handshakeConnIdx) throws IgniteCheckedException {
    HandshakeTimeoutObject<T> obj = new HandshakeTimeoutObject<>(client, U.currentTimeMillis() + timeout);
    addTimeoutObject(obj);
    long rcvCnt = 0;
    try {
        if (client instanceof GridCommunicationClient)
            ((GridCommunicationClient) client).doHandshake(new HandshakeClosure(rmtNodeId));
        else {
            SocketChannel ch = (SocketChannel) client;
            boolean success = false;
            try {
                BlockingSslHandler sslHnd = null;
                ByteBuffer buf;
                if (isSslEnabled()) {
                    assert sslMeta != null;
                    sslHnd = new BlockingSslHandler(sslMeta.sslEngine(), ch, directBuf, ByteOrder.nativeOrder(), log);
                    if (!sslHnd.handshake())
                        throw new IgniteCheckedException("SSL handshake is not completed.");
                    ByteBuffer handBuff = sslHnd.applicationBuffer();
                    if (handBuff.remaining() < NodeIdMessage.MESSAGE_FULL_SIZE) {
                        buf = ByteBuffer.allocate(1000);
                        int read = ch.read(buf);
                        if (read == -1)
                            throw new IgniteCheckedException("Failed to read remote node ID (connection closed).");
                        buf.flip();
                        buf = sslHnd.decode(buf);
                    } else
                        buf = handBuff;
                } else {
                    buf = ByteBuffer.allocate(NodeIdMessage.MESSAGE_FULL_SIZE);
                    for (int i = 0; i < NodeIdMessage.MESSAGE_FULL_SIZE; ) {
                        int read = ch.read(buf);
                        if (read == -1)
                            throw new IgniteCheckedException("Failed to read remote node ID (connection closed).");
                        i += read;
                    }
                }
                UUID rmtNodeId0 = U.bytesToUuid(buf.array(), Message.DIRECT_TYPE_SIZE);
                if (!rmtNodeId.equals(rmtNodeId0))
                    throw new IgniteCheckedException("Remote node ID is not as expected [expected=" + rmtNodeId + ", rcvd=" + rmtNodeId0 + ']');
                else if (log.isDebugEnabled())
                    log.debug("Received remote node ID: " + rmtNodeId0);
                if (isSslEnabled()) {
                    assert sslHnd != null;
                    ch.write(sslHnd.encrypt(ByteBuffer.wrap(U.IGNITE_HEADER)));
                } else
                    ch.write(ByteBuffer.wrap(U.IGNITE_HEADER));
                ClusterNode locNode = getLocalNode();
                if (locNode == null)
                    throw new IgniteCheckedException("Local node has not been started or " + "fully initialized [isStopping=" + getSpiContext().isStopping() + ']');
                if (recovery != null) {
                    HandshakeMessage msg;
                    int msgSize = HandshakeMessage.MESSAGE_FULL_SIZE;
                    if (handshakeConnIdx != null) {
                        msg = new HandshakeMessage2(locNode.id(), recovery.incrementConnectCount(), recovery.received(), handshakeConnIdx);
                        msgSize += 4;
                    } else {
                        msg = new HandshakeMessage(locNode.id(), recovery.incrementConnectCount(), recovery.received());
                    }
                    if (log.isDebugEnabled())
                        log.debug("Writing handshake message [locNodeId=" + locNode.id() + ", rmtNode=" + rmtNodeId + ", msg=" + msg + ']');
                    buf = ByteBuffer.allocate(msgSize);
                    buf.order(ByteOrder.nativeOrder());
                    boolean written = msg.writeTo(buf, null);
                    assert written;
                    buf.flip();
                    if (isSslEnabled()) {
                        assert sslHnd != null;
                        ch.write(sslHnd.encrypt(buf));
                    } else
                        ch.write(buf);
                } else {
                    if (isSslEnabled()) {
                        assert sslHnd != null;
                        ch.write(sslHnd.encrypt(ByteBuffer.wrap(nodeIdMessage().nodeIdBytesWithType)));
                    } else
                        ch.write(ByteBuffer.wrap(nodeIdMessage().nodeIdBytesWithType));
                }
                if (recovery != null) {
                    if (log.isDebugEnabled())
                        log.debug("Waiting for handshake [rmtNode=" + rmtNodeId + ']');
                    if (isSslEnabled()) {
                        assert sslHnd != null;
                        buf = ByteBuffer.allocate(1000);
                        buf.order(ByteOrder.nativeOrder());
                        ByteBuffer decode = ByteBuffer.allocate(2 * buf.capacity());
                        decode.order(ByteOrder.nativeOrder());
                        for (int i = 0; i < RecoveryLastReceivedMessage.MESSAGE_FULL_SIZE; ) {
                            int read = ch.read(buf);
                            if (read == -1)
                                throw new IgniteCheckedException("Failed to read remote node recovery handshake " + "(connection closed).");
                            buf.flip();
                            ByteBuffer decode0 = sslHnd.decode(buf);
                            i += decode0.remaining();
                            decode = appendAndResizeIfNeeded(decode, decode0);
                            buf.clear();
                        }
                        decode.flip();
                        rcvCnt = decode.getLong(Message.DIRECT_TYPE_SIZE);
                        if (decode.limit() > RecoveryLastReceivedMessage.MESSAGE_FULL_SIZE) {
                            decode.position(RecoveryLastReceivedMessage.MESSAGE_FULL_SIZE);
                            sslMeta.decodedBuffer(decode);
                        }
                        ByteBuffer inBuf = sslHnd.inputBuffer();
                        if (inBuf.position() > 0)
                            sslMeta.encodedBuffer(inBuf);
                    } else {
                        buf = ByteBuffer.allocate(RecoveryLastReceivedMessage.MESSAGE_FULL_SIZE);
                        buf.order(ByteOrder.nativeOrder());
                        for (int i = 0; i < RecoveryLastReceivedMessage.MESSAGE_FULL_SIZE; ) {
                            int read = ch.read(buf);
                            if (read == -1)
                                throw new IgniteCheckedException("Failed to read remote node recovery handshake " + "(connection closed).");
                            i += read;
                        }
                        rcvCnt = buf.getLong(Message.DIRECT_TYPE_SIZE);
                    }
                    if (log.isDebugEnabled())
                        log.debug("Received handshake message [rmtNode=" + rmtNodeId + ", rcvCnt=" + rcvCnt + ']');
                    if (rcvCnt == -1) {
                        if (log.isDebugEnabled())
                            log.debug("Connection rejected, will retry client creation [rmtNode=" + rmtNodeId + ']');
                    } else
                        success = true;
                } else
                    success = true;
            } catch (IOException e) {
                if (log.isDebugEnabled())
                    log.debug("Failed to read from channel: " + e);
                throw new IgniteCheckedException("Failed to read from channel.", e);
            } finally {
                if (!success)
                    U.closeQuiet(ch);
            }
        }
    } finally {
        boolean cancelled = obj.cancel();
        if (cancelled)
            removeTimeoutObject(obj);
        // Ignoring whatever happened after timeout - reporting only timeout event.
        if (!cancelled)
            throw new HandshakeTimeoutException("Failed to perform handshake due to timeout (consider increasing " + "'connectionTimeout' configuration property).");
    }
    return rcvCnt;
}
Also used : ClusterNode(org.apache.ignite.cluster.ClusterNode) SocketChannel(java.nio.channels.SocketChannel) BlockingSslHandler(org.apache.ignite.internal.util.nio.ssl.BlockingSslHandler) IOException(java.io.IOException) GridCommunicationClient(org.apache.ignite.internal.util.nio.GridCommunicationClient) ByteBuffer(java.nio.ByteBuffer) IpcEndpoint(org.apache.ignite.internal.util.ipc.IpcEndpoint) IpcSharedMemoryServerEndpoint(org.apache.ignite.internal.util.ipc.shmem.IpcSharedMemoryServerEndpoint) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) EVT_NODE_LEFT(org.apache.ignite.events.EventType.EVT_NODE_LEFT) LT(org.apache.ignite.internal.util.typedef.internal.LT) UUID(java.util.UUID)

Example 74 with SocketChannel

use of java.nio.channels.SocketChannel in project robovm by robovm.

the class ConcurrentCloseTest method test_connect_nonBlocking.

public void test_connect_nonBlocking() throws Exception {
    StuckServer ss = new StuckServer(false);
    SocketChannel s = SocketChannel.open();
    new Killer(s.socket()).start();
    try {
        System.err.println("connect (non-blocking)...");
        s.configureBlocking(false);
        s.connect(ss.getLocalSocketAddress());
        while (!s.finishConnect()) {
        // Spin like a mad thing!
        }
        fail("connect returned: " + s + "!");
    } catch (SocketException expected) {
        assertEquals("Socket closed", expected.getMessage());
    } catch (AsynchronousCloseException alsoOkay) {
    // See below.
    } catch (ClosedChannelException alsoOkay) {
    // For now, I'm assuming that we're happy as long as we get any reasonable exception.
    // It may be that we're supposed to guarantee only one or the other.
    } finally {
        ss.close();
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) SocketException(java.net.SocketException) ClosedChannelException(java.nio.channels.ClosedChannelException) AsynchronousCloseException(java.nio.channels.AsynchronousCloseException) StuckServer(tests.net.StuckServer)

Example 75 with SocketChannel

use of java.nio.channels.SocketChannel in project robovm by robovm.

the class UnixSelectorTest method testSelectUnConnectedChannel.

public void testSelectUnConnectedChannel() throws Exception {
    SocketChannel socketChannel2 = SocketChannel.open();
    socketChannel2.configureBlocking(false);
    Selector sel3 = Selector.open();
    SelectionKey mkey3 = socketChannel2.register(sel3, SelectionKey.OP_WRITE);
    // HUP is also treating as writable
    assertEquals(1, sel3.select(100));
    assertEquals(false, mkey3.isConnectable());
    // even the channel is not connected, the selector could be writable
    assertEquals(false, socketChannel2.isConnected());
    assertEquals(true, mkey3.isWritable());
    Selector sel4 = Selector.open();
    SelectionKey mkey4 = socketChannel2.register(sel4, SelectionKey.OP_CONNECT);
    assertEquals(1, sel4.select(100));
    assertEquals(false, mkey4.isWritable());
    assertEquals(true, mkey4.isConnectable());
    Selector sel5 = Selector.open();
    SelectionKey mkey5 = socketChannel2.register(sel5, SelectionKey.OP_CONNECT | SelectionKey.OP_WRITE);
    assertEquals(1, sel5.select(100));
    assertEquals(true, mkey5.isWritable());
    assertEquals(true, mkey5.isConnectable());
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) SelectionKey(java.nio.channels.SelectionKey) Selector(java.nio.channels.Selector)

Aggregations

SocketChannel (java.nio.channels.SocketChannel)662 IOException (java.io.IOException)298 ServerSocketChannel (java.nio.channels.ServerSocketChannel)285 InetSocketAddress (java.net.InetSocketAddress)202 ByteBuffer (java.nio.ByteBuffer)163 SelectionKey (java.nio.channels.SelectionKey)105 Socket (java.net.Socket)87 Test (org.junit.Test)81 ClosedChannelException (java.nio.channels.ClosedChannelException)50 Selector (java.nio.channels.Selector)42 SocketAddress (java.net.SocketAddress)35 ServerSocket (java.net.ServerSocket)31 ClosedSelectorException (java.nio.channels.ClosedSelectorException)28 CancelledKeyException (java.nio.channels.CancelledKeyException)27 ConnectException (java.net.ConnectException)26 ArrayList (java.util.ArrayList)26 SocketTimeoutException (java.net.SocketTimeoutException)23 SelectableChannel (java.nio.channels.SelectableChannel)21 SocketException (java.net.SocketException)20 HashMap (java.util.HashMap)20