Search in sources :

Example 1 with FailureProcessor

use of org.apache.ignite.internal.processors.failure.FailureProcessor 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 2 with FailureProcessor

use of org.apache.ignite.internal.processors.failure.FailureProcessor in project ignite by apache.

the class PageMemoryImplTest method createPageMemory.

/**
 * @param throttlingPlc Throttling Policy.
 * @throws Exception If creating mock failed.
 */
private PageMemoryImpl createPageMemory(int maxSize, PageMemoryImpl.ThrottlingPolicy throttlingPlc, IgnitePageStoreManager mgr, PageStoreWriter replaceWriter, @Nullable IgniteInClosure<FullPageId> cpBufChecker) throws Exception {
    long[] sizes = new long[5];
    for (int i = 0; i < sizes.length; i++) sizes[i] = maxSize * MB / 4;
    sizes[4] = maxSize * MB / 4;
    DirectMemoryProvider provider = new UnsafeMemoryProvider(log);
    IgniteConfiguration igniteCfg = new IgniteConfiguration();
    igniteCfg.setDataStorageConfiguration(new DataStorageConfiguration());
    igniteCfg.setFailureHandler(new NoOpFailureHandler());
    igniteCfg.setEncryptionSpi(new NoopEncryptionSpi());
    igniteCfg.setMetricExporterSpi(new NoopMetricExporterSpi());
    igniteCfg.setSystemViewExporterSpi(new JmxSystemViewExporterSpi());
    igniteCfg.setEventStorageSpi(new NoopEventStorageSpi());
    GridTestKernalContext kernalCtx = new GridTestKernalContext(new GridTestLog4jLogger(), igniteCfg);
    kernalCtx.add(new IgnitePluginProcessor(kernalCtx, igniteCfg, Collections.<PluginProvider>emptyList()));
    kernalCtx.add(new GridInternalSubscriptionProcessor(kernalCtx));
    kernalCtx.add(new PerformanceStatisticsProcessor(kernalCtx));
    kernalCtx.add(new GridEncryptionManager(kernalCtx));
    kernalCtx.add(new GridMetricManager(kernalCtx));
    kernalCtx.add(new GridSystemViewManager(kernalCtx));
    kernalCtx.add(new GridEventStorageManager(kernalCtx));
    FailureProcessor failureProc = new FailureProcessor(kernalCtx);
    failureProc.start();
    kernalCtx.add(failureProc);
    GridCacheSharedContext<Object, Object> sharedCtx = new GridCacheSharedContext<>(kernalCtx, null, null, null, mgr, new NoOpWALManager(), null, new IgniteCacheDatabaseSharedManager(), null, null, null, null, null, null, null, null, null, null, null, null, null);
    CheckpointProgressImpl cl0 = Mockito.mock(CheckpointProgressImpl.class);
    IgniteOutClosure<CheckpointProgress> noThrottle = Mockito.mock(IgniteOutClosure.class);
    Mockito.when(noThrottle.apply()).thenReturn(cl0);
    Mockito.when(cl0.currentCheckpointPagesCount()).thenReturn(1_000_000);
    Mockito.when(cl0.evictedPagesCounter()).thenReturn(new AtomicInteger(0));
    Mockito.when(cl0.syncedPagesCounter()).thenReturn(new AtomicInteger(1_000_000));
    Mockito.when(cl0.writtenPagesCounter()).thenReturn(new AtomicInteger(1_000_000));
    PageMemoryImpl mem = cpBufChecker == null ? new PageMemoryImpl(provider, sizes, sharedCtx, sharedCtx.pageStore(), PAGE_SIZE, replaceWriter, new GridInClosure3X<Long, FullPageId, PageMemoryEx>() {

        @Override
        public void applyx(Long page, FullPageId fullId, PageMemoryEx pageMem) {
        }
    }, () -> true, new DataRegionMetricsImpl(igniteCfg.getDataStorageConfiguration().getDefaultDataRegionConfiguration(), kernalCtx), throttlingPlc, noThrottle) : new PageMemoryImpl(provider, sizes, sharedCtx, sharedCtx.pageStore(), PAGE_SIZE, replaceWriter, new GridInClosure3X<Long, FullPageId, PageMemoryEx>() {

        @Override
        public void applyx(Long page, FullPageId fullId, PageMemoryEx pageMem) {
        }
    }, () -> true, new DataRegionMetricsImpl(igniteCfg.getDataStorageConfiguration().getDefaultDataRegionConfiguration(), kernalCtx), throttlingPlc, noThrottle) {

        @Override
        public FullPageId pullPageFromCpBuffer() {
            FullPageId pageId = super.pullPageFromCpBuffer();
            cpBufChecker.apply(pageId);
            return pageId;
        }
    };
    mem.metrics().enableMetrics();
    mem.start();
    return mem;
}
Also used : GridEventStorageManager(org.apache.ignite.internal.managers.eventstorage.GridEventStorageManager) NoOpFailureHandler(org.apache.ignite.failure.NoOpFailureHandler) IgnitePluginProcessor(org.apache.ignite.internal.processors.plugin.IgnitePluginProcessor) CheckpointProgress(org.apache.ignite.internal.processors.cache.persistence.checkpoint.CheckpointProgress) GridTestKernalContext(org.apache.ignite.testframework.junits.GridTestKernalContext) GridCacheSharedContext(org.apache.ignite.internal.processors.cache.GridCacheSharedContext) NoopEventStorageSpi(org.apache.ignite.spi.eventstorage.NoopEventStorageSpi) DataStorageConfiguration(org.apache.ignite.configuration.DataStorageConfiguration) CheckpointProgressImpl(org.apache.ignite.internal.processors.cache.persistence.checkpoint.CheckpointProgressImpl) DirectMemoryProvider(org.apache.ignite.internal.mem.DirectMemoryProvider) FullPageId(org.apache.ignite.internal.pagemem.FullPageId) GridEncryptionManager(org.apache.ignite.internal.managers.encryption.GridEncryptionManager) NoopEncryptionSpi(org.apache.ignite.spi.encryption.noop.NoopEncryptionSpi) GridInternalSubscriptionProcessor(org.apache.ignite.internal.processors.subscription.GridInternalSubscriptionProcessor) PluginProvider(org.apache.ignite.plugin.PluginProvider) DataRegionMetricsImpl(org.apache.ignite.internal.processors.cache.persistence.DataRegionMetricsImpl) JmxSystemViewExporterSpi(org.apache.ignite.internal.managers.systemview.JmxSystemViewExporterSpi) PerformanceStatisticsProcessor(org.apache.ignite.internal.processors.performancestatistics.PerformanceStatisticsProcessor) GridInClosure3X(org.apache.ignite.internal.util.lang.GridInClosure3X) IgniteConfiguration(org.apache.ignite.configuration.IgniteConfiguration) GridSystemViewManager(org.apache.ignite.internal.managers.systemview.GridSystemViewManager) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) NoopMetricExporterSpi(org.apache.ignite.spi.metric.noop.NoopMetricExporterSpi) GridMetricManager(org.apache.ignite.internal.processors.metric.GridMetricManager) UnsafeMemoryProvider(org.apache.ignite.internal.mem.unsafe.UnsafeMemoryProvider) GridTestLog4jLogger(org.apache.ignite.testframework.junits.logger.GridTestLog4jLogger) FailureProcessor(org.apache.ignite.internal.processors.failure.FailureProcessor) IgniteCacheDatabaseSharedManager(org.apache.ignite.internal.processors.cache.persistence.IgniteCacheDatabaseSharedManager)

Example 3 with FailureProcessor

use of org.apache.ignite.internal.processors.failure.FailureProcessor in project ignite by apache.

the class IgniteKernal method start.

/**
 * @param cfg Ignite configuration to use.
 * @param errHnd Error handler to use for notification about startup problems.
 * @param workerRegistry Worker registry.
 * @param hnd Default uncaught exception handler used by thread pools.
 * @throws IgniteCheckedException Thrown in case of any errors.
 */
public void start(final IgniteConfiguration cfg, GridAbsClosure errHnd, WorkersRegistry workerRegistry, Thread.UncaughtExceptionHandler hnd, TimeBag startTimer) throws IgniteCheckedException {
    gw.compareAndSet(null, new GridKernalGatewayImpl(cfg.getIgniteInstanceName()));
    GridKernalGateway gw = this.gw.get();
    gw.writeLock();
    try {
        switch(gw.getState()) {
            case STARTED:
                {
                    U.warn(log, "Grid has already been started (ignored).");
                    return;
                }
            case STARTING:
                {
                    U.warn(log, "Grid is already in process of being started (ignored).");
                    return;
                }
            case STOPPING:
                {
                    throw new IgniteCheckedException("Grid is in process of being stopped");
                }
            case STOPPED:
                {
                    break;
                }
        }
        gw.setState(STARTING);
    } finally {
        gw.writeUnlock();
    }
    assert cfg != null;
    // Make sure we got proper configuration.
    validateCommon(cfg);
    igniteInstanceName = cfg.getIgniteInstanceName();
    this.cfg = cfg;
    log = (GridLoggerProxy) cfg.getGridLogger().getLogger(getClass().getName() + (igniteInstanceName != null ? '%' + igniteInstanceName : ""));
    longJVMPauseDetector = new LongJVMPauseDetector(log);
    longJVMPauseDetector.start();
    RuntimeMXBean rtBean = ManagementFactory.getRuntimeMXBean();
    // Ack various information.
    ackAsciiLogo();
    ackConfigUrl();
    ackConfiguration(cfg);
    ackDaemon();
    ackOsInfo();
    ackLanguageRuntime();
    ackRemoteManagement();
    ackLogger();
    ackVmArguments(rtBean);
    ackClassPaths(rtBean);
    ackSystemProperties();
    ackEnvironmentVariables();
    ackMemoryConfiguration();
    ackCacheConfiguration();
    ackP2pConfiguration();
    ackRebalanceConfiguration();
    ackIPv4StackFlagIsSet();
    ackWaitForBackupsOnShutdownPropertyIsUsed();
    // Ack 3-rd party licenses location.
    if (log.isInfoEnabled() && cfg.getIgniteHome() != null)
        log.info("3-rd party licenses can be found at: " + cfg.getIgniteHome() + File.separatorChar + "libs" + File.separatorChar + "licenses");
    // with internally reserved names.
    for (String name : cfg.getUserAttributes().keySet()) if (name.startsWith(ATTR_PREFIX))
        throw new IgniteCheckedException("User attribute has illegal name: '" + name + "'. Note that all names " + "starting with '" + ATTR_PREFIX + "' are reserved for internal use.");
    // Ack local node user attributes.
    logNodeUserAttributes();
    // Ack configuration.
    ackSpis();
    List<PluginProvider> plugins = cfg.getPluginProviders() != null && cfg.getPluginProviders().length > 0 ? Arrays.asList(cfg.getPluginProviders()) : U.allPluginProviders();
    // Spin out SPIs & managers.
    try {
        ctx = new GridKernalContextImpl(log, this, cfg, gw, plugins, MarshallerUtils.classNameFilter(this.getClass().getClassLoader()), workerRegistry, hnd, longJVMPauseDetector);
        startProcessor(new DiagnosticProcessor(ctx));
        mBeansMgr = new IgniteMBeansManager(this);
        cfg.getMarshaller().setContext(ctx.marshallerContext());
        startProcessor(new GridInternalSubscriptionProcessor(ctx));
        ClusterProcessor clusterProc = new ClusterProcessor(ctx);
        startProcessor(clusterProc);
        U.onGridStart();
        // Start and configure resource processor first as it contains resources used
        // by all other managers and processors.
        GridResourceProcessor rsrcProc = new GridResourceProcessor(ctx);
        rsrcProc.setSpringContext(rsrcCtx);
        scheduler = new IgniteSchedulerImpl(ctx);
        startProcessor(rsrcProc);
        // Inject resources into lifecycle beans.
        if (!cfg.isDaemon() && cfg.getLifecycleBeans() != null) {
            for (LifecycleBean bean : cfg.getLifecycleBeans()) {
                if (bean != null)
                    rsrcProc.inject(bean);
            }
        }
        // Lifecycle notification.
        notifyLifecycleBeans(BEFORE_NODE_START);
        // Starts lifecycle aware components.
        U.startLifecycleAware(lifecycleAwares(cfg));
        startProcessor(new IgnitePluginProcessor(ctx, cfg, plugins));
        startProcessor(new FailureProcessor(ctx));
        // Start security processors.
        startProcessor(securityProcessor());
        startProcessor(new PoolProcessor(ctx));
        // Run background network diagnostics.
        GridDiagnostic.runBackgroundCheck(igniteInstanceName, ctx.pools().getExecutorService(), log);
        // Closure processor should be started before all others
        // (except for resource processor), as many components can depend on it.
        startProcessor(new GridClosureProcessor(ctx));
        // Start some other processors (order & place is important).
        startProcessor(new GridPortProcessor(ctx));
        startProcessor(new GridJobMetricsProcessor(ctx));
        // Timeout processor needs to be started before managers,
        // as managers may depend on it.
        startProcessor(new GridTimeoutProcessor(ctx));
        // NOTE: that order matters as there are dependencies between managers.
        try {
            startManager(new GridTracingManager(ctx, false));
        } catch (IgniteCheckedException e) {
            startManager(new GridTracingManager(ctx, true));
        }
        startManager(new GridMetricManager(ctx));
        startManager(new GridSystemViewManager(ctx));
        startManager(new GridIoManager(ctx));
        startManager(new GridCheckpointManager(ctx));
        startManager(new GridEventStorageManager(ctx));
        startManager(new GridDeploymentManager(ctx));
        startManager(new GridLoadBalancerManager(ctx));
        startManager(new GridFailoverManager(ctx));
        startManager(new GridCollisionManager(ctx));
        startManager(new GridIndexingManager(ctx));
        ackSecurity();
        // Assign discovery manager to context before other processors start so they
        // are able to register custom event listener.
        GridDiscoveryManager discoMgr = new GridDiscoveryManager(ctx);
        ctx.add(discoMgr, false);
        // Start the encryption manager after assigning the discovery manager to context, so it will be
        // able to register custom event listener.
        startManager(new GridEncryptionManager(ctx));
        startProcessor(new PdsConsistentIdProcessor(ctx));
        MaintenanceProcessor mntcProcessor = new MaintenanceProcessor(ctx);
        startProcessor(mntcProcessor);
        if (mntcProcessor.isMaintenanceMode()) {
            if (log.isInfoEnabled()) {
                log.info("Node is being started in maintenance mode. " + "Starting IsolatedDiscoverySpi instead of configured discovery SPI.");
            }
            cfg.setClusterStateOnStart(ClusterState.INACTIVE);
            if (log.isInfoEnabled())
                log.info("Overriding 'clusterStateOnStart' configuration to 'INACTIVE'.");
            ctx.config().setDiscoverySpi(new IsolatedDiscoverySpi());
            discoMgr = new GridDiscoveryManager(ctx);
            // Reinitialized discovery manager won't have a valid consistentId on creation.
            discoMgr.consistentId(ctx.pdsFolderResolver().resolveFolders().consistentId());
            ctx.add(discoMgr, false);
        }
        // be able to start receiving messages once discovery completes.
        try {
            startProcessor(COMPRESSION.createOptional(ctx));
            startProcessor(new GridMarshallerMappingProcessor(ctx));
            startProcessor(new MvccProcessorImpl(ctx));
            startProcessor(createComponent(DiscoveryNodeValidationProcessor.class, ctx));
            startProcessor(new GridAffinityProcessor(ctx));
            startProcessor(createComponent(GridSegmentationProcessor.class, ctx));
            startTimer.finishGlobalStage("Start managers");
            startProcessor(createComponent(IgniteCacheObjectProcessor.class, ctx));
            startTimer.finishGlobalStage("Configure binary metadata");
            startProcessor(createComponent(IGridClusterStateProcessor.class, ctx));
            startProcessor(new PerformanceStatisticsProcessor(ctx));
            startProcessor(new GridCacheProcessor(ctx));
            if (cfg.isAuthenticationEnabled()) {
                IgniteSecurityProcessor sec = (IgniteSecurityProcessor) ctx.security();
                ((IgniteAuthenticationProcessor) sec.securityProcessor()).startProcessor();
            }
            startProcessor(new IndexProcessor(ctx));
            startProcessor(new GridQueryProcessor(ctx));
            startProcessor(new ClientListenerProcessor(ctx));
            startProcessor(new IgniteServiceProcessor(ctx));
            startProcessor(new GridTaskSessionProcessor(ctx));
            startProcessor(new GridJobProcessor(ctx));
            startProcessor(new GridTaskProcessor(ctx));
            startProcessor((GridProcessor) SCHEDULE.createOptional(ctx));
            startProcessor(createComponent(IgniteRestProcessor.class, ctx));
            startProcessor(new DataStreamProcessor(ctx));
            startProcessor(new GridContinuousProcessor(ctx));
            startProcessor(new DataStructuresProcessor(ctx));
            startProcessor(createComponent(PlatformProcessor.class, ctx));
            startProcessor(new DistributedMetaStorageImpl(ctx));
            startProcessor(new DistributedConfigurationProcessor(ctx));
            startProcessor(new DurableBackgroundTasksProcessor(ctx));
            startTimer.finishGlobalStage("Start processors");
            // Start plugins.
            for (PluginProvider provider : ctx.plugins().allProviders()) {
                ctx.add(new GridPluginComponent(provider));
                provider.start(ctx.plugins().pluginContextForProvider(provider));
                startTimer.finishGlobalStage("Start '" + provider.name() + "' plugin");
            }
            // Start platform plugins.
            if (ctx.config().getPlatformConfiguration() != null)
                startProcessor(new PlatformPluginProcessor(ctx));
            mBeansMgr.registerMBeansDuringInitPhase();
            ctx.cluster().initDiagnosticListeners();
            fillNodeAttributes(clusterProc.updateNotifierEnabled());
            ctx.cache().context().database().notifyMetaStorageSubscribersOnReadyForRead();
            ((DistributedMetaStorageImpl) ctx.distributedMetastorage()).inMemoryReadyForRead();
            startTimer.finishGlobalStage("Init metastore");
            ctx.cache().context().database().startMemoryRestore(ctx, startTimer);
            ctx.recoveryMode(false);
            startTimer.finishGlobalStage("Finish recovery");
        } catch (Throwable e) {
            U.error(log, "Exception during start processors, node will be stopped and close connections", e);
            // Stop discovery spi to close tcp socket.
            ctx.discovery().stop(true);
            throw e;
        }
        // All components exept Discovery are started, time to check if maintenance is still needed.
        mntcProcessor.prepareAndExecuteMaintenance();
        gw.writeLock();
        try {
            gw.setState(STARTED);
            // Start discovery manager last to make sure that grid is fully initialized.
            startManager(discoMgr);
        } finally {
            gw.writeUnlock();
        }
        startTimer.finishGlobalStage("Join topology");
        // Check whether UTF-8 is the default character encoding.
        checkFileEncoding();
        // Check whether physical RAM is not exceeded.
        checkPhysicalRam();
        // Suggest configuration optimizations.
        suggestOptimizations(cfg);
        // Suggest JVM optimizations.
        ctx.performance().addAll(JvmConfigurationSuggestions.getSuggestions());
        // Suggest Operation System optimizations.
        ctx.performance().addAll(OsConfigurationSuggestions.getSuggestions());
        DiscoveryLocalJoinData joinData = ctx.discovery().localJoin();
        IgniteInternalFuture<Boolean> transitionWaitFut = joinData.transitionWaitFuture();
        // Notify discovery manager the first to make sure that topology is discovered.
        // Active flag is not used in managers, so it is safe to pass true.
        ctx.discovery().onKernalStart(true);
        // Notify IO manager the second so further components can send and receive messages.
        // Must notify the IO manager before transition state await to make sure IO connection can be established.
        ctx.io().onKernalStart(true);
        boolean active;
        if (transitionWaitFut != null) {
            if (log.isInfoEnabled()) {
                log.info("Join cluster while cluster state transition is in progress, " + "waiting when transition finish.");
            }
            active = transitionWaitFut.get();
        } else
            active = joinData.active();
        startTimer.finishGlobalStage("Await transition");
        ctx.pools().registerMetrics();
        registerMetrics();
        ctx.cluster().registerMetrics();
        // Register MBeans.
        mBeansMgr.registerMBeansAfterNodeStarted();
        boolean recon = false;
        // Callbacks.
        for (GridComponent comp : ctx) {
            // Skip discovery manager.
            if (comp instanceof GridDiscoveryManager)
                continue;
            // Skip IO manager.
            if (comp instanceof GridIoManager)
                continue;
            if (comp instanceof GridPluginComponent)
                continue;
            if (!skipDaemon(comp)) {
                try {
                    comp.onKernalStart(active);
                } catch (IgniteNeedReconnectException e) {
                    ClusterNode locNode = ctx.discovery().localNode();
                    assert locNode.isClient();
                    if (!ctx.discovery().reconnectSupported())
                        throw new IgniteCheckedException("Client node in forceServerMode " + "is not allowed to reconnect to the cluster and will be stopped.");
                    if (log.isDebugEnabled())
                        log.debug("Failed to start node components on node start, will wait for reconnect: " + e);
                    recon = true;
                }
            }
        }
        // Start plugins.
        for (PluginProvider provider : ctx.plugins().allProviders()) provider.onIgniteStart();
        if (recon)
            reconnectState.waitFirstReconnect();
        // Lifecycle bean notifications.
        notifyLifecycleBeans(AFTER_NODE_START);
    } catch (Throwable e) {
        IgniteSpiVersionCheckException verCheckErr = X.cause(e, IgniteSpiVersionCheckException.class);
        if (verCheckErr != null)
            U.error(log, verCheckErr.getMessage());
        else if (X.hasCause(e, InterruptedException.class, IgniteInterruptedCheckedException.class))
            U.warn(log, "Grid startup routine has been interrupted (will rollback).");
        else
            U.error(log, "Got exception while starting (will rollback startup routine).", e);
        errHnd.apply();
        stop(true);
        if (e instanceof Error)
            throw e;
        else if (e instanceof IgniteCheckedException)
            throw (IgniteCheckedException) e;
        else
            throw new IgniteCheckedException(e);
    }
    // Mark start timestamp.
    startTime = U.currentTimeMillis();
    String intervalStr = IgniteSystemProperties.getString(IGNITE_STARVATION_CHECK_INTERVAL);
    // Start starvation checker if enabled.
    boolean starveCheck = !isDaemon() && !"0".equals(intervalStr);
    if (starveCheck) {
        final long interval = F.isEmpty(intervalStr) ? DFLT_PERIODIC_STARVATION_CHECK_FREQ : Long.parseLong(intervalStr);
        starveTask = ctx.timeout().schedule(new Runnable() {

            /**
             * Last completed task count.
             */
            private long lastCompletedCntPub;

            /**
             * Last completed task count.
             */
            private long lastCompletedCntSys;

            /**
             * Last completed task count.
             */
            private long lastCompletedCntQry;

            @Override
            public void run() {
                if (ctx.pools().getExecutorService() instanceof ThreadPoolExecutor) {
                    ThreadPoolExecutor exec = (ThreadPoolExecutor) ctx.pools().getExecutorService();
                    lastCompletedCntPub = checkPoolStarvation(exec, lastCompletedCntPub, "public");
                }
                if (ctx.pools().getSystemExecutorService() instanceof ThreadPoolExecutor) {
                    ThreadPoolExecutor exec = (ThreadPoolExecutor) ctx.pools().getSystemExecutorService();
                    lastCompletedCntSys = checkPoolStarvation(exec, lastCompletedCntSys, "system");
                }
                if (ctx.pools().getQueryExecutorService() instanceof ThreadPoolExecutor) {
                    ThreadPoolExecutor exec = (ThreadPoolExecutor) ctx.pools().getQueryExecutorService();
                    lastCompletedCntQry = checkPoolStarvation(exec, lastCompletedCntQry, "query");
                }
                if (ctx.pools().getStripedExecutorService() != null)
                    ctx.pools().getStripedExecutorService().detectStarvation();
            }

            /**
             * @param exec Thread pool executor to check.
             * @param lastCompletedCnt Last completed tasks count.
             * @param pool Pool name for message.
             * @return Current completed tasks count.
             */
            private long checkPoolStarvation(ThreadPoolExecutor exec, long lastCompletedCnt, String pool) {
                long completedCnt = exec.getCompletedTaskCount();
                // at least one waiting request, then it is possible starvation.
                if (exec.getPoolSize() == exec.getActiveCount() && completedCnt == lastCompletedCnt && !exec.getQueue().isEmpty())
                    LT.warn(log, "Possible thread pool starvation detected (no task completed in last " + interval + "ms, is " + pool + " thread pool size large enough?)");
                return completedCnt;
            }
        }, interval, interval);
    }
    long metricsLogFreq = cfg.getMetricsLogFrequency();
    if (metricsLogFreq > 0) {
        metricsLogTask = ctx.timeout().schedule(new Runnable() {

            private final DecimalFormat dblFmt = doubleFormat();

            @Override
            public void run() {
                ackNodeMetrics(dblFmt, ctx.pools().getExecutorService(), ctx.pools().getSystemExecutorService(), ctx.pools().getStripedExecutorService(), ctx.pools().customExecutors());
            }
        }, metricsLogFreq, metricsLogFreq);
    }
    ctx.performance().add("Disable assertions (remove '-ea' from JVM options)", !U.assertionsEnabled());
    ctx.performance().logSuggestions(log, igniteInstanceName);
    U.quietAndInfo(log, "To start Console Management & Monitoring run ignitevisorcmd.{sh|bat}");
    if (!IgniteSystemProperties.getBoolean(IgniteSystemProperties.IGNITE_QUIET, true))
        ackClassPathContent();
    ackStart(rtBean);
    if (!isDaemon())
        ctx.discovery().ackTopology(ctx.discovery().localJoin().joinTopologyVersion().topologyVersion(), EventType.EVT_NODE_JOINED, localNode());
    startTimer.finishGlobalStage("Await exchange");
}
Also used : DataStructuresProcessor(org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor) IgniteServiceProcessor(org.apache.ignite.internal.processors.service.IgniteServiceProcessor) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) DiscoveryLocalJoinData(org.apache.ignite.internal.managers.discovery.DiscoveryLocalJoinData) IgniteSystemProperties.getBoolean(org.apache.ignite.IgniteSystemProperties.getBoolean) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MvccProcessorImpl(org.apache.ignite.internal.processors.cache.mvcc.MvccProcessorImpl) GridCheckpointManager(org.apache.ignite.internal.managers.checkpoint.GridCheckpointManager) ClusterNode(org.apache.ignite.cluster.ClusterNode) GridIndexingManager(org.apache.ignite.internal.managers.indexing.GridIndexingManager) GridEncryptionManager(org.apache.ignite.internal.managers.encryption.GridEncryptionManager) GridInternalSubscriptionProcessor(org.apache.ignite.internal.processors.subscription.GridInternalSubscriptionProcessor) GridMarshallerMappingProcessor(org.apache.ignite.internal.processors.marshaller.GridMarshallerMappingProcessor) GridTaskSessionProcessor(org.apache.ignite.internal.processors.session.GridTaskSessionProcessor) PlatformPluginProcessor(org.apache.ignite.internal.processors.platform.plugin.PlatformPluginProcessor) PluginProvider(org.apache.ignite.plugin.PluginProvider) DurableBackgroundTasksProcessor(org.apache.ignite.internal.processors.localtask.DurableBackgroundTasksProcessor) IgniteAuthenticationProcessor(org.apache.ignite.internal.processors.authentication.IgniteAuthenticationProcessor) GridCacheProcessor(org.apache.ignite.internal.processors.cache.GridCacheProcessor) GridPortProcessor(org.apache.ignite.internal.processors.port.GridPortProcessor) PerformanceStatisticsProcessor(org.apache.ignite.internal.processors.performancestatistics.PerformanceStatisticsProcessor) GridDiscoveryManager(org.apache.ignite.internal.managers.discovery.GridDiscoveryManager) IsolatedDiscoverySpi(org.apache.ignite.spi.discovery.isolated.IsolatedDiscoverySpi) GridTracingManager(org.apache.ignite.internal.managers.tracing.GridTracingManager) GridSystemViewManager(org.apache.ignite.internal.managers.systemview.GridSystemViewManager) GridAffinityProcessor(org.apache.ignite.internal.processors.affinity.GridAffinityProcessor) IgniteMBeansManager(org.apache.ignite.internal.managers.IgniteMBeansManager) GridJobMetricsProcessor(org.apache.ignite.internal.processors.jobmetrics.GridJobMetricsProcessor) GridQueryProcessor(org.apache.ignite.internal.processors.query.GridQueryProcessor) GridMetricManager(org.apache.ignite.internal.processors.metric.GridMetricManager) IgniteSpiVersionCheckException(org.apache.ignite.spi.IgniteSpiVersionCheckException) GridLoadBalancerManager(org.apache.ignite.internal.managers.loadbalancer.GridLoadBalancerManager) DataStreamProcessor(org.apache.ignite.internal.processors.datastreamer.DataStreamProcessor) FailureProcessor(org.apache.ignite.internal.processors.failure.FailureProcessor) GridEventStorageManager(org.apache.ignite.internal.managers.eventstorage.GridEventStorageManager) IgnitePluginProcessor(org.apache.ignite.internal.processors.plugin.IgnitePluginProcessor) PdsConsistentIdProcessor(org.apache.ignite.internal.processors.cache.persistence.filename.PdsConsistentIdProcessor) MaintenanceProcessor(org.apache.ignite.internal.maintenance.MaintenanceProcessor) GridTimeoutProcessor(org.apache.ignite.internal.processors.timeout.GridTimeoutProcessor) DecimalFormat(java.text.DecimalFormat) IndexProcessor(org.apache.ignite.internal.cache.query.index.IndexProcessor) GridDeploymentManager(org.apache.ignite.internal.managers.deployment.GridDeploymentManager) NoOpIgniteSecurityProcessor(org.apache.ignite.internal.processors.security.NoOpIgniteSecurityProcessor) IgniteSecurityProcessor(org.apache.ignite.internal.processors.security.IgniteSecurityProcessor) ClusterProcessor(org.apache.ignite.internal.processors.cluster.ClusterProcessor) OsDiscoveryNodeValidationProcessor(org.apache.ignite.internal.processors.nodevalidation.OsDiscoveryNodeValidationProcessor) DiscoveryNodeValidationProcessor(org.apache.ignite.internal.processors.nodevalidation.DiscoveryNodeValidationProcessor) ClientListenerProcessor(org.apache.ignite.internal.processors.odbc.ClientListenerProcessor) DistributedMetaStorageImpl(org.apache.ignite.internal.processors.metastorage.persistence.DistributedMetaStorageImpl) LifecycleBean(org.apache.ignite.lifecycle.LifecycleBean) IGridClusterStateProcessor(org.apache.ignite.internal.processors.cluster.IGridClusterStateProcessor) DiagnosticProcessor(org.apache.ignite.internal.processors.diagnostic.DiagnosticProcessor) IgniteRestProcessor(org.apache.ignite.internal.processors.rest.IgniteRestProcessor) GridSegmentationProcessor(org.apache.ignite.internal.processors.segmentation.GridSegmentationProcessor) GridCollisionManager(org.apache.ignite.internal.managers.collision.GridCollisionManager) IgniteCacheObjectProcessor(org.apache.ignite.internal.processors.cacheobject.IgniteCacheObjectProcessor) GridTaskProcessor(org.apache.ignite.internal.processors.task.GridTaskProcessor) GridContinuousProcessor(org.apache.ignite.internal.processors.continuous.GridContinuousProcessor) RuntimeMXBean(java.lang.management.RuntimeMXBean) DistributedConfigurationProcessor(org.apache.ignite.internal.processors.configuration.distributed.DistributedConfigurationProcessor) GridClosureProcessor(org.apache.ignite.internal.processors.closure.GridClosureProcessor) GridFailoverManager(org.apache.ignite.internal.managers.failover.GridFailoverManager) PlatformProcessor(org.apache.ignite.internal.processors.platform.PlatformProcessor) GridIoManager(org.apache.ignite.internal.managers.communication.GridIoManager) GridResourceProcessor(org.apache.ignite.internal.processors.resource.GridResourceProcessor) PoolProcessor(org.apache.ignite.internal.processors.pool.PoolProcessor) GridJobProcessor(org.apache.ignite.internal.processors.job.GridJobProcessor) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor)

Example 4 with FailureProcessor

use of org.apache.ignite.internal.processors.failure.FailureProcessor in project ignite by apache.

the class TcpDiscoverySpi method onExchange.

/**
 * @param dataPacket object holding discovery data collected during discovery process.
 * @param clsLdr Class loader.
 */
protected void onExchange(DiscoveryDataPacket dataPacket, ClassLoader clsLdr) {
    if (locNode.isDaemon())
        return;
    assert dataPacket != null;
    assert dataPacket.joiningNodeId() != null;
    DiscoveryDataBag dataBag;
    if (dataPacket.joiningNodeId().equals(locNode.id())) {
        try {
            dataBag = dataPacket.unmarshalGridData(marshaller(), clsLdr, locNode.clientRouterNodeId() != null, log);
        } catch (IgniteCheckedException e) {
            if (ignite() instanceof IgniteEx) {
                FailureProcessor failure = ((IgniteEx) ignite()).context().failure();
                failure.process(new FailureContext(CRITICAL_ERROR, e));
            }
            throw new IgniteException(e);
        }
    } else {
        dataBag = dataPacket.unmarshalJoiningNodeDataSilently(marshaller(), clsLdr, locNode.clientRouterNodeId() != null, log);
        // It can be happened due to several nodes, including node without compression support, are trying to join cluster concurrently.
        if (!allNodesSupport(IgniteFeatures.DATA_PACKET_COMPRESSION) && dataPacket.isJoiningDataZipped())
            dataPacket.unzipData(log);
    }
    exchange.onExchange(dataBag);
}
Also used : IgniteCheckedException(org.apache.ignite.IgniteCheckedException) DiscoveryDataBag(org.apache.ignite.spi.discovery.DiscoveryDataBag) FailureContext(org.apache.ignite.failure.FailureContext) IgniteException(org.apache.ignite.IgniteException) IgniteEx(org.apache.ignite.internal.IgniteEx) FailureProcessor(org.apache.ignite.internal.processors.failure.FailureProcessor)

Example 5 with FailureProcessor

use of org.apache.ignite.internal.processors.failure.FailureProcessor in project ignite by apache.

the class CommunicationWorker method body.

/**
 * Connection stat processing.
 */
@Override
protected void body() throws InterruptedException {
    if (log.isDebugEnabled())
        log.debug("Tcp communication worker has been started.");
    Throwable err = null;
    try {
        while (!isCancelled()) {
            DisconnectedSessionInfo disconnectData;
            blockingSectionBegin();
            try {
                disconnectData = q.poll(cfg.idleConnectionTimeout(), TimeUnit.MILLISECONDS);
            } finally {
                blockingSectionEnd();
            }
            if (disconnectData != null)
                processDisconnect(disconnectData);
            else
                processIdle();
            onIdle();
        }
    } catch (Throwable t) {
        if (!(t instanceof InterruptedException))
            err = t;
        throw t;
    } finally {
        FailureProcessor failureProcessor = failureProcessorSupplier.get();
        if (failureProcessor != null) {
            if (err == null && !stopping)
                err = new IllegalStateException("Thread  " + spiName + " is terminated unexpectedly.");
            if (err instanceof OutOfMemoryError)
                failureProcessor.process(new FailureContext(CRITICAL_ERROR, err));
            else if (err != null)
                failureProcessor.process(new FailureContext(SYSTEM_WORKER_TERMINATION, err));
        }
    }
}
Also used : FailureContext(org.apache.ignite.failure.FailureContext) FailureProcessor(org.apache.ignite.internal.processors.failure.FailureProcessor)

Aggregations

FailureProcessor (org.apache.ignite.internal.processors.failure.FailureProcessor)5 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)3 IgniteException (org.apache.ignite.IgniteException)2 ClusterNode (org.apache.ignite.cluster.ClusterNode)2 IgniteConfiguration (org.apache.ignite.configuration.IgniteConfiguration)2 FailureContext (org.apache.ignite.failure.FailureContext)2 IgniteEx (org.apache.ignite.internal.IgniteEx)2 GridIoManager (org.apache.ignite.internal.managers.communication.GridIoManager)2 GridEncryptionManager (org.apache.ignite.internal.managers.encryption.GridEncryptionManager)2 GridEventStorageManager (org.apache.ignite.internal.managers.eventstorage.GridEventStorageManager)2 GridSystemViewManager (org.apache.ignite.internal.managers.systemview.GridSystemViewManager)2 IOException (java.io.IOException)1 RuntimeMXBean (java.lang.management.RuntimeMXBean)1 InetSocketAddress (java.net.InetSocketAddress)1 ByteBuffer (java.nio.ByteBuffer)1 Channel (java.nio.channels.Channel)1 DecimalFormat (java.text.DecimalFormat)1 BitSet (java.util.BitSet)1 Collection (java.util.Collection)1 List (java.util.List)1