Search in sources :

Example 11 with Channel

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

the class GridIoManager method processOpenedChannel.

/**
 * @param topic Topic to which the channel is created.
 * @param rmtNodeId Remote node id.
 * @param initMsg Channel initialization message with additional params.
 * @param ch Channel instance.
 */
private void processOpenedChannel(Object topic, UUID rmtNodeId, SessionChannelMessage initMsg, SocketChannel ch) {
    ReceiverContext rcvCtx = null;
    ObjectInputStream in = null;
    ObjectOutputStream out = null;
    try {
        if (stopping) {
            throw new NodeStoppingException("Local node is stopping. Channel will be closed [topic=" + topic + ", channel=" + ch + ']');
        }
        if (initMsg == null || initMsg.sesId() == null) {
            U.warn(log, "There is no initial message provied for given topic. Opened channel will be closed " + "[rmtNodeId=" + rmtNodeId + ", topic=" + topic + ", initMsg=" + initMsg + ']');
            return;
        }
        configureChannel(ch, netTimeoutMs);
        in = new ObjectInputStream(ch.socket().getInputStream());
        out = new ObjectOutputStream(ch.socket().getOutputStream());
        IgniteUuid newSesId = initMsg.sesId();
        synchronized (rcvMux) {
            TransmissionHandler hnd = topicTransmissionHnds.get(topic);
            if (hnd == null) {
                U.warn(log, "There is no handler for a given topic. Channel will be closed [rmtNodeId=" + rmtNodeId + ", topic=" + topic + ']');
                return;
            }
            rcvCtx = rcvCtxs.computeIfAbsent(topic, t -> new ReceiverContext(rmtNodeId, hnd, newSesId));
        }
        // Do not allow multiple connections for the same session.
        if (!newSesId.equals(rcvCtx.sesId)) {
            IgniteCheckedException err = new IgniteCheckedException("Requested topic is busy by another transmission. " + "It's not allowed to process different sessions over the same topic simultaneously. " + "Channel will be closed [initMsg=" + initMsg + ", channel=" + ch + ", nodeId=" + rmtNodeId + ']');
            U.error(log, "Error has been sent back to remote node. Receiver holds the local topic " + "[topic=" + topic + ", rmtNodeId=" + rmtNodeId + ", ctx=" + rcvCtx + ']', err);
            out.writeObject(new TransmissionMeta(err));
            return;
        }
        if (log.isDebugEnabled()) {
            log.debug("Trasmission open a new channel [rmtNodeId=" + rmtNodeId + ", topic=" + topic + ", initMsg=" + initMsg + ']');
        }
        if (!rcvCtx.lock.tryLock(netTimeoutMs, TimeUnit.MILLISECONDS))
            throw new IgniteException("Wait for the previous receiver finished its work timeouted: " + rcvCtx);
        try {
            if (rcvCtx.timeoutObj != null)
                ctx.timeout().removeTimeoutObject(rcvCtx.timeoutObj);
            // Send previous context state to sync remote and local node.
            out.writeObject(rcvCtx.lastState == null ? new TransmissionMeta() : rcvCtx.lastState);
            if (rcvCtx.lastState == null || rcvCtx.lastState.error() == null)
                receiveFromChannel(topic, rcvCtx, in, out, ch);
            else
                interruptReceiver(rcvCtxs.remove(topic), rcvCtx.lastState.error());
        } finally {
            rcvCtx.lock.unlock();
        }
    } catch (Throwable t) {
        // Do not remove receiver context here, since sender will recconect to get this error.
        interruptReceiver(rcvCtx, new IgniteCheckedException("Channel processing error [nodeId=" + rmtNodeId + ']', t));
    } finally {
        U.closeQuiet(in);
        U.closeQuiet(out);
        U.closeQuiet(ch);
    }
}
Also used : Arrays(java.util.Arrays) GridFutureAdapter(org.apache.ignite.internal.util.future.GridFutureAdapter) EVT_NODE_LEFT(org.apache.ignite.events.EventType.EVT_NODE_LEFT) GridFinishedFuture(org.apache.ignite.internal.util.future.GridFinishedFuture) CommunicationListenerEx(org.apache.ignite.spi.communication.tcp.internal.CommunicationListenerEx) ConnectionRequestor(org.apache.ignite.spi.communication.tcp.internal.ConnectionRequestor) IgnitePair(org.apache.ignite.internal.util.lang.IgnitePair) TOPIC_COMM_USER(org.apache.ignite.internal.GridTopic.TOPIC_COMM_USER) BooleanSupplier(java.util.function.BooleanSupplier) FileIO(org.apache.ignite.internal.processors.cache.persistence.file.FileIO) Map(java.util.Map) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) Channel(java.nio.channels.Channel) ClusterGroup(org.apache.ignite.cluster.ClusterGroup) IgniteKernal(org.apache.ignite.internal.IgniteKernal) RandomAccessFileIOFactory(org.apache.ignite.internal.processors.cache.persistence.file.RandomAccessFileIOFactory) IgniteInClosure(org.apache.ignite.lang.IgniteInClosure) GridToStringExclude(org.apache.ignite.internal.util.tostring.GridToStringExclude) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) Event(org.apache.ignite.events.Event) Set(java.util.Set) IgniteRunnable(org.apache.ignite.lang.IgniteRunnable) Executors(java.util.concurrent.Executors) Serializable(java.io.Serializable) IgniteConfiguration(org.apache.ignite.configuration.IgniteConfiguration) TcpInverseConnectionResponseMessage(org.apache.ignite.spi.communication.tcp.internal.TcpInverseConnectionResponseMessage) MTC(org.apache.ignite.internal.processors.tracing.MTC) TraceableMessagesTable.traceName(org.apache.ignite.internal.processors.tracing.messages.TraceableMessagesTable.traceName) Message(org.apache.ignite.plugin.extensions.communication.Message) TcpCommunicationSpi(org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi) IgniteBiPredicate(org.apache.ignite.lang.IgniteBiPredicate) IgniteSpiException(org.apache.ignite.spi.IgniteSpiException) RandomAccessFileIO(org.apache.ignite.internal.processors.cache.persistence.file.RandomAccessFileIO) U(org.apache.ignite.internal.util.typedef.internal.U) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) ArrayList(java.util.ArrayList) GridKernalContext(org.apache.ignite.internal.GridKernalContext) ClusterNode(org.apache.ignite.cluster.ClusterNode) GridNioBackPressureControl.threadProcessingMessage(org.apache.ignite.internal.util.nio.GridNioBackPressureControl.threadProcessingMessage) SocketTimeoutException(java.net.SocketTimeoutException) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) S(org.apache.ignite.internal.util.typedef.internal.S) IgniteComponentType(org.apache.ignite.internal.IgniteComponentType) ObjectOutputStream(java.io.ObjectOutputStream) TcpConnectionRequestDiscoveryMessage(org.apache.ignite.spi.communication.tcp.internal.TcpConnectionRequestDiscoveryMessage) Executor(java.util.concurrent.Executor) A(org.apache.ignite.internal.util.typedef.internal.A) DirectMessageWriter(org.apache.ignite.internal.direct.DirectMessageWriter) MvccMessage(org.apache.ignite.internal.processors.cache.mvcc.msg.MvccMessage) IOException(java.io.IOException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) Marshaller(org.apache.ignite.marshaller.Marshaller) MetricRegistry(org.apache.ignite.internal.processors.metric.MetricRegistry) File(java.io.File) T2(org.apache.ignite.internal.util.typedef.T2) AtomicLong(java.util.concurrent.atomic.AtomicLong) CommunicationSpi(org.apache.ignite.spi.communication.CommunicationSpi) DATA_STREAMER_POOL(org.apache.ignite.internal.managers.communication.GridIoPolicy.DATA_STREAMER_POOL) Lock(java.util.concurrent.locks.Lock) TOPIC_IO_TEST(org.apache.ignite.internal.GridTopic.TOPIC_IO_TEST) CHANNEL_COMMUNICATION(org.apache.ignite.internal.IgniteFeatures.CHANNEL_COMMUNICATION) MTC.support(org.apache.ignite.internal.processors.tracing.MTC.support) GridTopic(org.apache.ignite.internal.GridTopic) GridDeployment(org.apache.ignite.internal.managers.deployment.GridDeployment) CustomEventListener(org.apache.ignite.internal.managers.discovery.CustomEventListener) WritableByteChannel(java.nio.channels.WritableByteChannel) DirectMessageReader(org.apache.ignite.internal.direct.DirectMessageReader) PER_SEGMENT_Q_OPTIMIZED_RMV(org.jsr166.ConcurrentLinkedHashMap.QueuePolicy.PER_SEGMENT_Q_OPTIMIZED_RMV) IgniteUuid(org.apache.ignite.lang.IgniteUuid) IgniteMessaging(org.apache.ignite.IgniteMessaging) IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) IgniteFeatures.nodeSupports(org.apache.ignite.internal.IgniteFeatures.nodeSupports) ObjectOutput(java.io.ObjectOutput) COMMUNICATION_REGULAR_PROCESS(org.apache.ignite.internal.processors.tracing.SpanType.COMMUNICATION_REGULAR_PROCESS) ObjectInputStream(java.io.ObjectInputStream) SYSTEM_POOL(org.apache.ignite.internal.managers.communication.GridIoPolicy.SYSTEM_POOL) ATTR_PAIRED_CONN(org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi.ATTR_PAIRED_CONN) SocketChannel(java.nio.channels.SocketChannel) IgniteDeploymentCheckedException(org.apache.ignite.internal.IgniteDeploymentCheckedException) X(org.apache.ignite.internal.util.typedef.X) TOPIC_CACHE_COORDINATOR(org.apache.ignite.internal.GridTopic.TOPIC_CACHE_COORDINATOR) MetricUtils.metricName(org.apache.ignite.internal.processors.metric.impl.MetricUtils.metricName) CyclicBarrier(java.util.concurrent.CyclicBarrier) IgniteClientDisconnectedCheckedException(org.apache.ignite.internal.IgniteClientDisconnectedCheckedException) MessageFormatter(org.apache.ignite.plugin.extensions.communication.MessageFormatter) IgniteThreadFactory(org.apache.ignite.thread.IgniteThreadFactory) OperationSecurityContext(org.apache.ignite.internal.processors.security.OperationSecurityContext) Collection(java.util.Collection) IgniteException(org.apache.ignite.IgniteException) SpanTags(org.apache.ignite.internal.processors.tracing.SpanTags) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) UUID(java.util.UUID) Instant(java.time.Instant) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) EVT_NODE_FAILED(org.apache.ignite.events.EventType.EVT_NODE_FAILED) Entry(java.util.Map.Entry) ObjectInput(java.io.ObjectInput) COMMUNICATION_ORDERED_PROCESS(org.apache.ignite.internal.processors.tracing.SpanType.COMMUNICATION_ORDERED_PROCESS) Queue(java.util.Queue) NotNull(org.jetbrains.annotations.NotNull) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) UTILITY_CACHE_POOL(org.apache.ignite.internal.managers.communication.GridIoPolicy.UTILITY_CACHE_POOL) LongAdder(java.util.concurrent.atomic.LongAdder) NodeStoppingException(org.apache.ignite.internal.NodeStoppingException) Socket(java.net.Socket) DiscoveryEvent(org.apache.ignite.events.DiscoveryEvent) CommunicationListener(org.apache.ignite.spi.communication.CommunicationListener) Span(org.apache.ignite.internal.processors.tracing.Span) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) Deque(java.util.Deque) IgniteFeatures(org.apache.ignite.internal.IgniteFeatures) AtomicReference(java.util.concurrent.atomic.AtomicReference) LT(org.apache.ignite.internal.util.typedef.internal.LT) ConcurrentMap(java.util.concurrent.ConcurrentMap) HashSet(java.util.HashSet) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) MANAGEMENT_POOL(org.apache.ignite.internal.managers.communication.GridIoPolicy.MANAGEMENT_POOL) SERVICE_POOL(org.apache.ignite.internal.managers.communication.GridIoPolicy.SERVICE_POOL) GridManagerAdapter(org.apache.ignite.internal.managers.GridManagerAdapter) IgniteUtils(org.apache.ignite.internal.util.IgniteUtils) FileIOFactory(org.apache.ignite.internal.processors.cache.persistence.file.FileIOFactory) MessageWriter(org.apache.ignite.plugin.extensions.communication.MessageWriter) ExecutorService(java.util.concurrent.ExecutorService) MessageFactory(org.apache.ignite.plugin.extensions.communication.MessageFactory) OutputStream(java.io.OutputStream) F(org.apache.ignite.internal.util.typedef.F) EVT_NODE_JOINED(org.apache.ignite.events.EventType.EVT_NODE_JOINED) ReadableByteChannel(java.nio.channels.ReadableByteChannel) IDX_POOL(org.apache.ignite.internal.managers.communication.GridIoPolicy.IDX_POOL) P2P_POOL(org.apache.ignite.internal.managers.communication.GridIoPolicy.P2P_POOL) Iterator(java.util.Iterator) ReentrantLock(java.util.concurrent.locks.ReentrantLock) AFFINITY_POOL(org.apache.ignite.internal.managers.communication.GridIoPolicy.AFFINITY_POOL) QUERY_POOL(org.apache.ignite.internal.managers.communication.GridIoPolicy.QUERY_POOL) PoolProcessor(org.apache.ignite.internal.processors.pool.PoolProcessor) GridTimeoutObject(org.apache.ignite.internal.processors.timeout.GridTimeoutObject) ClusterTopologyCheckedException(org.apache.ignite.internal.cluster.ClusterTopologyCheckedException) StripedCompositeReadWriteLock(org.apache.ignite.internal.util.StripedCompositeReadWriteLock) ConcurrentLinkedDeque(java.util.concurrent.ConcurrentLinkedDeque) MessageReader(org.apache.ignite.plugin.extensions.communication.MessageReader) GridToStringInclude(org.apache.ignite.internal.util.tostring.GridToStringInclude) PUBLIC_POOL(org.apache.ignite.internal.managers.communication.GridIoPolicy.PUBLIC_POOL) TimeUnit(java.util.concurrent.TimeUnit) GridBoundedConcurrentLinkedHashSet(org.apache.ignite.internal.util.GridBoundedConcurrentLinkedHashSet) SCHEMA_POOL(org.apache.ignite.internal.managers.communication.GridIoPolicy.SCHEMA_POOL) GridIoPolicy.isReservedGridIoPolicy(org.apache.ignite.internal.managers.communication.GridIoPolicy.isReservedGridIoPolicy) Closeable(java.io.Closeable) TOPIC_COMM_SYSTEM(org.apache.ignite.internal.GridTopic.TOPIC_COMM_SYSTEM) GridEventStorageManager(org.apache.ignite.internal.managers.eventstorage.GridEventStorageManager) FileChannel(java.nio.channels.FileChannel) GridLocalEventListener(org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener) PlatformMessageFilter(org.apache.ignite.internal.processors.platform.message.PlatformMessageFilter) TraceSurroundings(org.apache.ignite.internal.processors.tracing.MTC.TraceSurroundings) InputStream(java.io.InputStream) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) NodeStoppingException(org.apache.ignite.internal.NodeStoppingException) IgniteUuid(org.apache.ignite.lang.IgniteUuid) IgniteException(org.apache.ignite.IgniteException) ObjectOutputStream(java.io.ObjectOutputStream) ObjectInputStream(java.io.ObjectInputStream)

Example 12 with Channel

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

the class TcpCommunicationSpi method spiStart.

/**
 * {@inheritDoc}
 */
@Override
public void spiStart(String igniteInstanceName) throws IgniteSpiException {
    final Function<UUID, ClusterNode> nodeGetter = (nodeId) -> getSpiContext().node(nodeId);
    final Supplier<ClusterNode> locNodeSupplier = () -> getSpiContext().localNode();
    final Supplier<Ignite> igniteExSupplier = this::ignite;
    final Function<UUID, Boolean> pingNode = (nodeId) -> getSpiContext().pingNode(nodeId);
    final Supplier<FailureProcessor> failureProcessorSupplier = () -> ignite instanceof IgniteEx ? ((IgniteEx) ignite).context().failure() : null;
    final Supplier<Boolean> isStopped = () -> getSpiContext().isStopping();
    this.igniteInstanceName = igniteInstanceName;
    cfg.failureDetectionTimeout(ignite.configuration().getFailureDetectionTimeout());
    attributeNames = new AttributeNames(createSpiAttributeName(ATTR_PAIRED_CONN), createSpiAttributeName(ATTR_ADDRS), createSpiAttributeName(ATTR_HOST_NAMES), createSpiAttributeName(ATTR_EXT_ADDRS), createSpiAttributeName(ATTR_PORT), createSpiAttributeName(ATTR_FORCE_CLIENT_SERVER_CONNECTIONS));
    boolean client = Boolean.TRUE.equals(ignite().configuration().isClientMode());
    this.stateProvider = new ClusterStateProvider(ignite, locNodeSupplier, this, isStopped, () -> super.getSpiContext(), log, igniteExSupplier);
    try {
        cfg.localHost(U.resolveLocalHost(cfg.localAddress()));
    } catch (IOException e) {
        throw new IgniteSpiException("Failed to initialize local address: " + cfg.localAddress(), e);
    }
    if (cfg.connectionsPerNode() > 1)
        connPlc = new RoundRobinConnectionPolicy(cfg);
    else
        connPlc = new FirstConnectionPolicy();
    this.srvLsnr = resolve(ignite, new InboundConnectionHandler(log, cfg, nodeGetter, locNodeSupplier, stateProvider, clientPool, commWorker, connectGate, failureProcessorSupplier, attributeNames, metricsLsnr, nioSrvWrapper, ctxInitLatch, client, igniteExSupplier, new CommunicationListener<Message>() {

        @Override
        public void onMessage(UUID nodeId, Message msg, IgniteRunnable msgC) {
            notifyListener(nodeId, msg, msgC);
        }

        @Override
        public void onDisconnected(UUID nodeId) {
            if (lsnr != null)
                lsnr.onDisconnected(nodeId);
        }
    }));
    TcpHandshakeExecutor tcpHandshakeExecutor = resolve(ignite, new TcpHandshakeExecutor(log, stateProvider, cfg.directBuffer()));
    this.nioSrvWrapper = resolve(ignite, new GridNioServerWrapper(log, cfg, attributeNames, tracing, nodeGetter, locNodeSupplier, connectGate, stateProvider, this::getExceptionRegistry, commWorker, ignite.configuration(), this.srvLsnr, getName(), getWorkersRegistry(ignite), ignite instanceof IgniteEx ? ((IgniteEx) ignite).context().metric() : null, this::createTcpClient, new CommunicationListenerEx<Message>() {

        @Override
        public void onMessage(UUID nodeId, Message msg, IgniteRunnable msgC) {
            notifyListener(nodeId, msg, msgC);
        }

        @Override
        public void onDisconnected(UUID nodeId) {
            if (lsnr != null)
                lsnr.onDisconnected(nodeId);
        }

        @Override
        public void onChannelOpened(UUID rmtNodeId, Message initMsg, Channel channel) {
            if (lsnr instanceof CommunicationListenerEx)
                ((CommunicationListenerEx<Message>) lsnr).onChannelOpened(rmtNodeId, initMsg, channel);
        }
    }, tcpHandshakeExecutor));
    this.srvLsnr.setNioSrvWrapper(nioSrvWrapper);
    this.clientPool = resolve(ignite, new ConnectionClientPool(cfg, attributeNames, log, metricsLsnr, locNodeSupplier, nodeGetter, null, getWorkersRegistry(ignite), this, stateProvider, nioSrvWrapper, getName()));
    this.srvLsnr.setClientPool(clientPool);
    nioSrvWrapper.clientPool(clientPool);
    discoLsnr = new CommunicationDiscoveryEventListener(clientPool, metricsLsnr);
    try {
        // This method potentially resets local port to the value
        // local node was bound to.
        nioSrvWrapper.nio(nioSrvWrapper.resetNioServer());
    } catch (IgniteCheckedException e) {
        throw new IgniteSpiException("Failed to initialize TCP server: " + cfg.localHost(), e);
    }
    boolean forceClientToSrvConnections = forceClientToServerConnections() || cfg.localPort() == -1;
    if (cfg.usePairedConnections() && forceClientToSrvConnections) {
        throw new IgniteSpiException("Node using paired connections " + "is not allowed to start in forced client to server connections mode.");
    }
    assert cfg.localHost() != null;
    // Start SPI start stopwatch.
    startStopwatch();
    if (log.isDebugEnabled()) {
        log.debug(configInfo("locAddr", cfg.localAddress()));
        log.debug(configInfo("locPort", cfg.localPort()));
        log.debug(configInfo("locPortRange", cfg.localPortRange()));
        log.debug(configInfo("idleConnTimeout", cfg.idleConnectionTimeout()));
        log.debug(configInfo("directBuf", cfg.directBuffer()));
        log.debug(configInfo("directSendBuf", cfg.directSendBuffer()));
        log.debug(configInfo("selectorsCnt", cfg.selectorsCount()));
        log.debug(configInfo("tcpNoDelay", cfg.tcpNoDelay()));
        log.debug(configInfo("sockSndBuf", cfg.socketSendBuffer()));
        log.debug(configInfo("sockRcvBuf", cfg.socketReceiveBuffer()));
        log.debug(configInfo("msgQueueLimit", cfg.messageQueueLimit()));
        log.debug(configInfo("connectionsPerNode", cfg.connectionsPerNode()));
        if (failureDetectionTimeoutEnabled()) {
            log.debug(configInfo("connTimeout", cfg.connectionTimeout()));
            log.debug(configInfo("maxConnTimeout", cfg.maxConnectionTimeout()));
            log.debug(configInfo("reconCnt", cfg.reconCount()));
        } else
            log.debug(configInfo("failureDetectionTimeout", failureDetectionTimeout()));
        log.debug(configInfo("sockWriteTimeout", cfg.socketWriteTimeout()));
        log.debug(configInfo("ackSndThreshold", cfg.ackSendThreshold()));
        log.debug(configInfo("unackedMsgsBufSize", cfg.unackedMsgsBufferSize()));
    }
    if (!cfg.tcpNoDelay())
        U.quietAndWarn(log, "'TCP_NO_DELAY' for communication is off, which should be used with caution " + "since may produce significant delays with some scenarios.");
    if (cfg.slowClientQueueLimit() > 0 && cfg.messageQueueLimit() > 0 && cfg.slowClientQueueLimit() >= cfg.messageQueueLimit()) {
        U.quietAndWarn(log, "Slow client queue limit is set to a value greater than or equal to message " + "queue limit (slow client queue limit will have no effect) [msgQueueLimit=" + cfg.messageQueueLimit() + ", slowClientQueueLimit=" + cfg.slowClientQueueLimit() + ']');
    }
    if (cfg.messageQueueLimit() == 0)
        U.quietAndWarn(log, "Message queue limit is set to 0 which may lead to " + "potential OOMEs when running cache operations in FULL_ASYNC or PRIMARY_SYNC modes " + "due to message queues growth on sender and receiver sides.");
    nioSrvWrapper.start();
    this.commWorker = new CommunicationWorker(igniteInstanceName, log, cfg, attributeNames, clientPool, failureProcessorSupplier, nodeGetter, pingNode, this::getExceptionRegistry, nioSrvWrapper, getWorkersRegistry(ignite), getName());
    this.srvLsnr.communicationWorker(commWorker);
    this.nioSrvWrapper.communicationWorker(commWorker);
    new IgniteSpiThread(igniteInstanceName, commWorker.name(), log) {

        @Override
        protected void body() {
            commWorker.run();
        }
    }.start();
    // Ack start.
    if (log.isDebugEnabled())
        log.debug(startInfo());
}
Also used : IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) CommunicationWorker(org.apache.ignite.spi.communication.tcp.internal.CommunicationWorker) TcpHandshakeExecutor(org.apache.ignite.spi.communication.tcp.internal.TcpHandshakeExecutor) GridNioSession(org.apache.ignite.internal.util.nio.GridNioSession) TcpCommunicationSpiMBeanImpl(org.apache.ignite.spi.communication.tcp.internal.TcpCommunicationSpiMBeanImpl) EVT_NODE_LEFT(org.apache.ignite.events.EventType.EVT_NODE_LEFT) AddressResolver(org.apache.ignite.configuration.AddressResolver) GridFinishedFuture(org.apache.ignite.internal.util.future.GridFinishedFuture) CommunicationListenerEx(org.apache.ignite.spi.communication.tcp.internal.CommunicationListenerEx) IgniteEx(org.apache.ignite.internal.IgniteEx) TcpCommunicationConfigInitializer(org.apache.ignite.spi.communication.tcp.internal.TcpCommunicationConfigInitializer) ClusterStateProvider(org.apache.ignite.spi.communication.tcp.internal.ClusterStateProvider) ByteBuffer(java.nio.ByteBuffer) GridNioSessionMetaKey(org.apache.ignite.internal.util.nio.GridNioSessionMetaKey) Map(java.util.Map) FirstConnectionPolicy(org.apache.ignite.spi.communication.tcp.internal.FirstConnectionPolicy) ConnectionClientPool(org.apache.ignite.spi.communication.tcp.internal.ConnectionClientPool) FailureProcessor(org.apache.ignite.internal.processors.failure.FailureProcessor) WorkersRegistry(org.apache.ignite.internal.worker.WorkersRegistry) LoggerResource(org.apache.ignite.resources.LoggerResource) RoundRobinConnectionPolicy(org.apache.ignite.spi.communication.tcp.internal.RoundRobinConnectionPolicy) Channel(java.nio.channels.Channel) IgniteKernal(org.apache.ignite.internal.IgniteKernal) NOOP(org.apache.ignite.spi.communication.tcp.internal.CommunicationTcpUtils.NOOP) IgniteFuture(org.apache.ignite.lang.IgniteFuture) IgniteClientDisconnectedCheckedException(org.apache.ignite.internal.IgniteClientDisconnectedCheckedException) IgniteInClosure(org.apache.ignite.lang.IgniteInClosure) GridNioServer(org.apache.ignite.internal.util.nio.GridNioServer) Collection(java.util.Collection) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) CommunicationTcpUtils(org.apache.ignite.spi.communication.tcp.internal.CommunicationTcpUtils) TcpConnectionIndexAwareMessage(org.apache.ignite.spi.communication.tcp.internal.TcpConnectionIndexAwareMessage) IgniteRunnable(org.apache.ignite.lang.IgniteRunnable) UNDEFINED_CONNECTION_INDEX(org.apache.ignite.spi.communication.tcp.internal.TcpConnectionIndexAwareMessage.UNDEFINED_CONNECTION_INDEX) UUID(java.util.UUID) InetSocketAddress(java.net.InetSocketAddress) GridIoMessage(org.apache.ignite.internal.managers.communication.GridIoMessage) CountDownLatch(java.util.concurrent.CountDownLatch) GridResourceProcessor(org.apache.ignite.internal.processors.resource.GridResourceProcessor) List(java.util.List) IgniteConfiguration(org.apache.ignite.configuration.IgniteConfiguration) EVT_NODE_FAILED(org.apache.ignite.events.EventType.EVT_NODE_FAILED) MTC(org.apache.ignite.internal.processors.tracing.MTC) Message(org.apache.ignite.plugin.extensions.communication.Message) GridCommunicationClient(org.apache.ignite.internal.util.nio.GridCommunicationClient) IgniteFutureImpl(org.apache.ignite.internal.util.future.IgniteFutureImpl) ConnectGateway(org.apache.ignite.spi.communication.tcp.internal.ConnectGateway) CommunicationListener(org.apache.ignite.spi.communication.CommunicationListener) IgniteSpiContext(org.apache.ignite.spi.IgniteSpiContext) IgniteSpiException(org.apache.ignite.spi.IgniteSpiException) IgniteSpiThread(org.apache.ignite.spi.IgniteSpiThread) U(org.apache.ignite.internal.util.typedef.internal.U) IgnitePortProtocol(org.apache.ignite.spi.IgnitePortProtocol) InboundConnectionHandler(org.apache.ignite.spi.communication.tcp.internal.InboundConnectionHandler) IgniteLogger(org.apache.ignite.IgniteLogger) GridIoManager(org.apache.ignite.internal.managers.communication.GridIoManager) Function(java.util.function.Function) Supplier(java.util.function.Supplier) CommunicationDiscoveryEventListener(org.apache.ignite.spi.communication.tcp.internal.CommunicationDiscoveryEventListener) ClusterNode(org.apache.ignite.cluster.ClusterNode) IgnitePredicate(org.apache.ignite.lang.IgnitePredicate) IgniteSpiConsistencyChecked(org.apache.ignite.spi.IgniteSpiConsistencyChecked) IgniteSpiMultipleInstancesSupport(org.apache.ignite.spi.IgniteSpiMultipleInstancesSupport) S(org.apache.ignite.internal.util.typedef.internal.S) IgniteInterruptedCheckedException(org.apache.ignite.internal.IgniteInterruptedCheckedException) GridNioServerWrapper(org.apache.ignite.spi.communication.tcp.internal.GridNioServerWrapper) IOException(java.io.IOException) Ignite(org.apache.ignite.Ignite) ConnectionKey(org.apache.ignite.spi.communication.tcp.internal.ConnectionKey) TestOnly(org.jetbrains.annotations.TestOnly) CommunicationSpi(org.apache.ignite.spi.communication.CommunicationSpi) TcpCommunicationConnectionCheckFuture(org.apache.ignite.spi.communication.tcp.internal.TcpCommunicationConnectionCheckFuture) NodeUnreachableException(org.apache.ignite.spi.communication.tcp.internal.NodeUnreachableException) MetricUtils(org.apache.ignite.internal.processors.metric.impl.MetricUtils) BitSet(java.util.BitSet) GridNioRecoveryDescriptor(org.apache.ignite.internal.util.nio.GridNioRecoveryDescriptor) GridLocalEventListener(org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener) TcpConnectionIndexAwareMessage(org.apache.ignite.spi.communication.tcp.internal.TcpConnectionIndexAwareMessage) GridIoMessage(org.apache.ignite.internal.managers.communication.GridIoMessage) Message(org.apache.ignite.plugin.extensions.communication.Message) GridNioServerWrapper(org.apache.ignite.spi.communication.tcp.internal.GridNioServerWrapper) IgniteRunnable(org.apache.ignite.lang.IgniteRunnable) CommunicationDiscoveryEventListener(org.apache.ignite.spi.communication.tcp.internal.CommunicationDiscoveryEventListener) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) RoundRobinConnectionPolicy(org.apache.ignite.spi.communication.tcp.internal.RoundRobinConnectionPolicy) Ignite(org.apache.ignite.Ignite) IgniteSpiException(org.apache.ignite.spi.IgniteSpiException) UUID(java.util.UUID) ClusterNode(org.apache.ignite.cluster.ClusterNode) FirstConnectionPolicy(org.apache.ignite.spi.communication.tcp.internal.FirstConnectionPolicy) TcpHandshakeExecutor(org.apache.ignite.spi.communication.tcp.internal.TcpHandshakeExecutor) ClusterStateProvider(org.apache.ignite.spi.communication.tcp.internal.ClusterStateProvider) CommunicationListenerEx(org.apache.ignite.spi.communication.tcp.internal.CommunicationListenerEx) Channel(java.nio.channels.Channel) IOException(java.io.IOException) CommunicationWorker(org.apache.ignite.spi.communication.tcp.internal.CommunicationWorker) IgniteSpiThread(org.apache.ignite.spi.IgniteSpiThread) IgniteEx(org.apache.ignite.internal.IgniteEx) ConnectionClientPool(org.apache.ignite.spi.communication.tcp.internal.ConnectionClientPool) InboundConnectionHandler(org.apache.ignite.spi.communication.tcp.internal.InboundConnectionHandler) FailureProcessor(org.apache.ignite.internal.processors.failure.FailureProcessor)

Example 13 with Channel

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

the class GridNioServerWrapper method openChannel.

/**
 * @param remote Destination cluster node to communicate with.
 * @param initMsg Configuration channel attributes wrapped into the message.
 * @return The future, which will be finished on channel ready.
 * @throws IgniteSpiException If fails.
 */
public IgniteInternalFuture<Channel> openChannel(ClusterNode remote, Message initMsg) throws IgniteSpiException {
    assert !remote.isLocal() : remote;
    assert initMsg != null;
    assert chConnPlc != null;
    assert nodeSupports(remote, CHANNEL_COMMUNICATION) : "Node doesn't support direct connection over socket channel " + "[nodeId=" + remote.id() + ']';
    ConnectionKey key = new ConnectionKey(remote.id(), chConnPlc.connectionIndex());
    GridFutureAdapter<Channel> chFut = new GridFutureAdapter<>();
    connectGate.enter();
    try {
        GridNioSession ses = createNioSession(remote, key.connectionIndex());
        assert ses != null : "Session must be established [remoteId=" + remote.id() + ", key=" + key + ']';
        cleanupLocalNodeRecoveryDescriptor(key);
        ses.addMeta(CHANNEL_FUT_META, chFut);
        // Send configuration message over the created session.
        ses.send(initMsg).listen(f -> {
            if (f.error() != null) {
                GridFutureAdapter<Channel> rq = ses.meta(CHANNEL_FUT_META);
                assert rq != null;
                rq.onDone(f.error());
                ses.close();
                return;
            }
            Runnable closeRun = () -> {
                // Close session if request not complete yet.
                GridFutureAdapter<Channel> rq = ses.meta(CHANNEL_FUT_META);
                assert rq != null;
                if (rq.onDone(handshakeTimeoutException()))
                    ses.close();
            };
            handshakeTimeoutExecutorService.schedule(closeRun, cfg.connectionTimeout(), TimeUnit.MILLISECONDS);
        });
        return chFut;
    } catch (IgniteCheckedException e) {
        throw new IgniteSpiException("Unable to create new channel connection to the remote node: " + remote, e);
    } finally {
        connectGate.leave();
    }
}
Also used : IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridNioSession(org.apache.ignite.internal.util.nio.GridNioSession) Channel(java.nio.channels.Channel) SocketChannel(java.nio.channels.SocketChannel) GridFutureAdapter(org.apache.ignite.internal.util.future.GridFutureAdapter) IgniteSpiException(org.apache.ignite.spi.IgniteSpiException)

Example 14 with Channel

use of java.nio.channels.Channel in project jetty.project by eclipse.

the class ServerConnector method open.

@Override
public void open() throws IOException {
    if (_acceptChannel == null) {
        ServerSocketChannel serverChannel = null;
        if (isInheritChannel()) {
            Channel channel = System.inheritedChannel();
            if (channel instanceof ServerSocketChannel)
                serverChannel = (ServerSocketChannel) channel;
            else
                LOG.warn("Unable to use System.inheritedChannel() [{}]. Trying a new ServerSocketChannel at {}:{}", channel, getHost(), getPort());
        }
        if (serverChannel == null) {
            serverChannel = ServerSocketChannel.open();
            InetSocketAddress bindAddress = getHost() == null ? new InetSocketAddress(getPort()) : new InetSocketAddress(getHost(), getPort());
            serverChannel.socket().setReuseAddress(getReuseAddress());
            serverChannel.socket().bind(bindAddress, getAcceptQueueSize());
            _localPort = serverChannel.socket().getLocalPort();
            if (_localPort <= 0)
                throw new IOException("Server channel not bound");
        }
        serverChannel.configureBlocking(true);
        addBean(serverChannel);
        _acceptChannel = serverChannel;
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) SocketChannel(java.nio.channels.SocketChannel) Channel(java.nio.channels.Channel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) SelectableChannel(java.nio.channels.SelectableChannel) IOException(java.io.IOException) ServerSocketChannel(java.nio.channels.ServerSocketChannel)

Example 15 with Channel

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

the class OldSystemTest method test_inheritedChannel.

public void test_inheritedChannel() throws IOException {
    Channel iChannel = System.inheritedChannel();
    assertNull("Incorrect value of channel", iChannel);
    SelectorProvider sp = SelectorProvider.provider();
    assertEquals("Incorrect value of channel", sp.inheritedChannel(), iChannel);
}
Also used : SelectorProvider(java.nio.channels.spi.SelectorProvider) Channel(java.nio.channels.Channel)

Aggregations

Channel (java.nio.channels.Channel)33 IOException (java.io.IOException)22 FileChannel (java.nio.channels.FileChannel)10 ReadableByteChannel (java.nio.channels.ReadableByteChannel)8 SocketChannel (java.nio.channels.SocketChannel)7 WritableByteChannel (java.nio.channels.WritableByteChannel)7 InputStream (java.io.InputStream)6 ServerSocketChannel (java.nio.channels.ServerSocketChannel)5 FileNotFoundException (java.io.FileNotFoundException)4 InetSocketAddress (java.net.InetSocketAddress)4 ArrayList (java.util.ArrayList)4 IgniteRunnable (org.apache.ignite.lang.IgniteRunnable)4 StreamSinkChannel (org.xnio.channels.StreamSinkChannel)4 DataFile (edu.harvard.iq.dataverse.DataFile)3 File (java.io.File)3 FileInputStream (java.io.FileInputStream)3 FileOutputStream (java.io.FileOutputStream)3 OutputStream (java.io.OutputStream)3 List (java.util.List)3 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)3