Search in sources :

Example 11 with GridMessageListener

use of org.apache.ignite.internal.managers.communication.GridMessageListener in project ignite by apache.

the class KillQueryTest method testCancelQueryIfPartitionsCantBeReservedOnMapNodes.

/**
 * Check if query hangs (due to reducer spins retrying to reserve partitions but they can't be reserved), we still
 * able to cancel it. Used mocked indexing simulates 100% unability.
 */
@Test
public void testCancelQueryIfPartitionsCantBeReservedOnMapNodes() throws Exception {
    // Releases thread that kills query when map nodes receive query request. At least one map node received is ok.
    GridMessageListener qryStarted = (node, msg, plc) -> {
        if (msg instanceof GridH2QueryRequest)
            TestSQLFunctions.cancelLatch.countDown();
    };
    for (int i = 0; i < NODES_COUNT; i++) grid(i).context().io().addMessageListener(GridTopic.TOPIC_QUERY, qryStarted);
    // Suspends distributed queries on the map nodes.
    MockedIndexing.failReservations = true;
    try {
        IgniteInternalFuture cancelFut = cancel(1, asyncCancel);
        GridTestUtils.assertThrows(log, () -> {
            ignite.cache(DEFAULT_CACHE_NAME).query(new SqlFieldsQuery("select * from Integer where _val <> 42")).getAll();
            return null;
        }, CacheException.class, "The query was cancelled while executing.");
        cancelFut.get(CHECK_RESULT_TIMEOUT);
    } finally {
        for (int i = 0; i < NODES_COUNT; i++) grid(i).context().io().removeMessageListener(GridTopic.TOPIC_QUERY, qryStarted);
    }
}
Also used : IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) Arrays(java.util.Arrays) Connection(java.sql.Connection) QueryCancelledException(org.apache.ignite.cache.query.QueryCancelledException) SqlFieldsQuery(org.apache.ignite.cache.query.SqlFieldsQuery) TimeoutException(java.util.concurrent.TimeoutException) IgniteEx(org.apache.ignite.internal.IgniteEx) PartitionReservation(org.apache.ignite.internal.processors.query.h2.twostep.PartitionReservation) RendezvousAffinityFunction(org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction) IgniteSystemProperties(org.apache.ignite.IgniteSystemProperties) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ResultSet(java.sql.ResultSet) After(org.junit.After) QueryEntity(org.apache.ignite.cache.QueryEntity) GridIoPolicy(org.apache.ignite.internal.managers.communication.GridIoPolicy) PARTITIONED(org.apache.ignite.cache.CacheMode.PARTITIONED) Parameterized(org.junit.runners.Parameterized) ReducePartitionMapper(org.apache.ignite.internal.processors.query.h2.twostep.ReducePartitionMapper) CyclicBarrier(java.util.concurrent.CyclicBarrier) GridCommonAbstractTest(org.apache.ignite.testframework.junits.common.GridCommonAbstractTest) QuerySqlField(org.apache.ignite.cache.query.annotations.QuerySqlField) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) IgniteCache(org.apache.ignite.IgniteCache) DiscoverySpiCustomMessage(org.apache.ignite.spi.discovery.DiscoverySpiCustomMessage) Serializable(java.io.Serializable) GridSpinBusyLock(org.apache.ignite.internal.util.GridSpinBusyLock) GridTestUtils(org.apache.ignite.testframework.GridTestUtils) Objects(java.util.Objects) CountDownLatch(java.util.concurrent.CountDownLatch) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) IgniteConfiguration(org.apache.ignite.configuration.IgniteConfiguration) Stream(java.util.stream.Stream) TestRecordingCommunicationSpi(org.apache.ignite.internal.TestRecordingCommunicationSpi) Arrays.stream(java.util.Arrays.stream) FieldsQueryCursor(org.apache.ignite.cache.query.FieldsQueryCursor) TcpDiscoveryIpFinder(org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder) IgniteUtils.resolveIgnitePath(org.apache.ignite.internal.util.IgniteUtils.resolveIgnitePath) IntStream(java.util.stream.IntStream) GridH2QueryRequest(org.apache.ignite.internal.processors.query.h2.twostep.msg.GridH2QueryRequest) CustomMessageWrapper(org.apache.ignite.internal.managers.discovery.CustomMessageWrapper) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) Affinity(org.apache.ignite.cache.affinity.Affinity) RunWith(org.junit.runner.RunWith) QuerySqlFunction(org.apache.ignite.cache.query.annotations.QuerySqlFunction) ArrayList(java.util.ArrayList) GridKernalContext(org.apache.ignite.internal.GridKernalContext) SQLException(java.sql.SQLException) DiscoveryCustomMessage(org.apache.ignite.internal.managers.discovery.DiscoveryCustomMessage) IgniteH2Indexing(org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing) CacheException(javax.cache.CacheException) ReducePartitionMapResult(org.apache.ignite.internal.processors.query.h2.twostep.ReducePartitionMapResult) GridMessageListener(org.apache.ignite.internal.managers.communication.GridMessageListener) Before(org.junit.Before) F(org.apache.ignite.internal.util.typedef.F) SchemaProposeDiscoveryMessage(org.apache.ignite.internal.processors.query.schema.message.SchemaProposeDiscoveryMessage) GridAbstractTest(org.apache.ignite.testframework.junits.GridAbstractTest) Iterator(java.util.Iterator) AffinityTopologyVersion(org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion) TcpDiscoveryVmIpFinder(org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder) DataStreamerRequest(org.apache.ignite.internal.processors.datastreamer.DataStreamerRequest) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) Test(org.junit.Test) Field(java.lang.reflect.Field) FULL_SYNC(org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC) GridReduceQueryExecutor(org.apache.ignite.internal.processors.query.h2.twostep.GridReduceQueryExecutor) TimeUnit(java.util.concurrent.TimeUnit) WithSystemProperty(org.apache.ignite.testframework.junits.WithSystemProperty) GridTopic(org.apache.ignite.internal.GridTopic) CacheConfiguration(org.apache.ignite.configuration.CacheConfiguration) PartitionReservationManager(org.apache.ignite.internal.processors.query.h2.twostep.PartitionReservationManager) Statement(java.sql.Statement) IgniteDataStreamer(org.apache.ignite.IgniteDataStreamer) TcpDiscoverySpi(org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi) Assert(org.junit.Assert) Collections(java.util.Collections) QueryIndex(org.apache.ignite.cache.QueryIndex) DynamicCacheChangeBatch(org.apache.ignite.internal.processors.cache.DynamicCacheChangeBatch) GridMessageListener(org.apache.ignite.internal.managers.communication.GridMessageListener) GridH2QueryRequest(org.apache.ignite.internal.processors.query.h2.twostep.msg.GridH2QueryRequest) IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) SqlFieldsQuery(org.apache.ignite.cache.query.SqlFieldsQuery) GridCommonAbstractTest(org.apache.ignite.testframework.junits.common.GridCommonAbstractTest) GridAbstractTest(org.apache.ignite.testframework.junits.GridAbstractTest) Test(org.junit.Test)

Example 12 with GridMessageListener

use of org.apache.ignite.internal.managers.communication.GridMessageListener in project ignite by apache.

the class IgniteClusterSnapshotCheckTest method testClusterSnapshotCheckOtherCluster.

/**
 * @throws Exception If fails.
 */
@Test
public void testClusterSnapshotCheckOtherCluster() throws Exception {
    IgniteEx ig0 = startGridsWithCache(3, dfltCacheCfg.setAffinity(new RendezvousAffinityFunction(false, 1)), CACHE_KEYS_RANGE);
    ig0.snapshot().createSnapshot(SNAPSHOT_NAME).get();
    stopAllGrids();
    // Cleanup persistence directory except created snapshots.
    Arrays.stream(new File(U.defaultWorkDirectory()).listFiles()).filter(f -> !f.getName().equals(DFLT_SNAPSHOT_DIRECTORY)).forEach(U::delete);
    Set<UUID> assigns = Collections.newSetFromMap(new ConcurrentHashMap<>());
    for (int i = 4; i < 7; i++) {
        startGrid(optimize(getConfiguration(getTestIgniteInstanceName(i)).setCacheConfiguration()));
        UUID locNodeId = grid(i).localNode().id();
        grid(i).context().io().addMessageListener(GridTopic.TOPIC_JOB, new GridMessageListener() {

            @Override
            public void onMessage(UUID nodeId, Object msg, byte plc) {
                if (msg instanceof GridJobExecuteRequest) {
                    GridJobExecuteRequest msg0 = (GridJobExecuteRequest) msg;
                    if (msg0.getTaskName().contains(SnapshotPartitionsVerifyTask.class.getName()))
                        assigns.add(locNodeId);
                }
            }
        });
    }
    IgniteEx ignite = grid(4);
    ignite.cluster().baselineAutoAdjustEnabled(false);
    ignite.cluster().state(ACTIVE);
    IdleVerifyResultV2 res = snp(ignite).checkSnapshot(SNAPSHOT_NAME).get();
    StringBuilder b = new StringBuilder();
    res.print(b::append, true);
    // GridJobExecuteRequest is not send to the local node.
    assertTrue("Number of jobs must be equal to the cluster size (except local node): " + assigns + ", count: " + assigns.size(), waitForCondition(() -> assigns.size() == 2, 5_000L));
    assertTrue(F.isEmpty(res.exceptions()));
    assertPartitionsSame(res);
    assertContains(log, b.toString(), "The check procedure has finished, no conflicts have been found");
}
Also used : IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) Arrays(java.util.Arrays) PartitionHashRecordV2(org.apache.ignite.internal.processors.cache.verify.PartitionHashRecordV2) Random(java.util.Random) IgniteEx(org.apache.ignite.internal.IgniteEx) CacheObjectBinaryProcessorImpl.binaryWorkDir(org.apache.ignite.internal.processors.cache.binary.CacheObjectBinaryProcessorImpl.binaryWorkDir) ByteBuffer(java.nio.ByteBuffer) RendezvousAffinityFunction(org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction) Collections.singletonList(java.util.Collections.singletonList) PagePartitionMetaIO(org.apache.ignite.internal.processors.cache.persistence.tree.io.PagePartitionMetaIO) Map(java.util.Map) X(org.apache.ignite.internal.util.typedef.X) Path(java.nio.file.Path) FilePageStore(org.apache.ignite.internal.processors.cache.persistence.file.FilePageStore) Parameterized(org.junit.runners.Parameterized) SNAPSHOT_METAFILE_EXT(org.apache.ignite.internal.processors.cache.persistence.snapshot.IgniteSnapshotManager.SNAPSHOT_METAFILE_EXT) IgniteDataIntegrityViolationException(org.apache.ignite.internal.processors.cache.persistence.wal.crc.IgniteDataIntegrityViolationException) BinaryContext(org.apache.ignite.internal.binary.BinaryContext) Collection(java.util.Collection) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) MarshallerContextImpl.mappingFileStoreWorkDir(org.apache.ignite.internal.MarshallerContextImpl.mappingFileStoreWorkDir) FilePageStoreManager(org.apache.ignite.internal.processors.cache.persistence.file.FilePageStoreManager) UUID(java.util.UUID) CacheDataRow(org.apache.ignite.internal.processors.cache.persistence.CacheDataRow) ByteOrder(java.nio.ByteOrder) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) IgniteConfiguration(org.apache.ignite.configuration.IgniteConfiguration) PartitionKeyV2(org.apache.ignite.internal.processors.cache.verify.PartitionKeyV2) GridJobExecuteRequest(org.apache.ignite.internal.GridJobExecuteRequest) CU(org.apache.ignite.internal.util.typedef.internal.CU) BinaryObjectImpl(org.apache.ignite.internal.binary.BinaryObjectImpl) IdleVerifyResultV2(org.apache.ignite.internal.processors.cache.verify.IdleVerifyResultV2) FilePageStoreManager.getPartitionFileName(org.apache.ignite.internal.processors.cache.persistence.file.FilePageStoreManager.getPartitionFileName) GridCacheEntryEx(org.apache.ignite.internal.processors.cache.GridCacheEntryEx) FilePageStoreManager.cacheDirName(org.apache.ignite.internal.processors.cache.persistence.file.FilePageStoreManager.cacheDirName) DR_NONE(org.apache.ignite.internal.processors.dr.GridDrType.DR_NONE) GridCacheAdapter(org.apache.ignite.internal.processors.cache.GridCacheAdapter) GridTestUtils.waitForCondition(org.apache.ignite.testframework.GridTestUtils.waitForCondition) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) PdsFolderSettings(org.apache.ignite.internal.processors.cache.persistence.filename.PdsFolderSettings) GridCacheVersion(org.apache.ignite.internal.processors.cache.version.GridCacheVersion) U(org.apache.ignite.internal.util.typedef.internal.U) IgniteSnapshotManager.databaseRelativePath(org.apache.ignite.internal.processors.cache.persistence.snapshot.IgniteSnapshotManager.databaseRelativePath) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) GridCacheDatabaseSharedManager(org.apache.ignite.internal.processors.cache.persistence.GridCacheDatabaseSharedManager) ComputeJobResult(org.apache.ignite.compute.ComputeJobResult) PageIO(org.apache.ignite.internal.processors.cache.persistence.tree.io.PageIO) CheckpointListener(org.apache.ignite.internal.processors.cache.persistence.checkpoint.CheckpointListener) GridTestUtils.assertNotContains(org.apache.ignite.testframework.GridTestUtils.assertNotContains) GridMessageListener(org.apache.ignite.internal.managers.communication.GridMessageListener) VerifyBackupPartitionsTaskV2(org.apache.ignite.internal.processors.cache.verify.VerifyBackupPartitionsTaskV2) Before(org.junit.Before) ACTIVE(org.apache.ignite.cluster.ClusterState.ACTIVE) F(org.apache.ignite.internal.util.typedef.F) VisorIdleVerifyTaskArg(org.apache.ignite.internal.visor.verify.VisorIdleVerifyTaskArg) Files(java.nio.file.Files) AffinityTopologyVersion(org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion) GridUnsafe(org.apache.ignite.internal.util.GridUnsafe) DFLT_SNAPSHOT_DIRECTORY(org.apache.ignite.configuration.IgniteConfiguration.DFLT_SNAPSHOT_DIRECTORY) TTL_ETERNAL(org.apache.ignite.internal.processors.cache.GridCacheUtils.TTL_ETERNAL) IOException(java.io.IOException) Test(org.junit.Test) File(java.io.File) CacheObjectBinaryProcessorImpl(org.apache.ignite.internal.processors.cache.binary.CacheObjectBinaryProcessorImpl) GridIterator(org.apache.ignite.internal.util.lang.GridIterator) GridTestUtils.assertContains(org.apache.ignite.testframework.GridTestUtils.assertContains) NONE(org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion.NONE) GridCacheSharedContext(org.apache.ignite.internal.processors.cache.GridCacheSharedContext) GridTopic(org.apache.ignite.internal.GridTopic) Paths(java.nio.file.Paths) CacheConfiguration(org.apache.ignite.configuration.CacheConfiguration) CacheFilterEnum(org.apache.ignite.internal.visor.verify.CacheFilterEnum) GroupPartitionId.getTypeByPartId(org.apache.ignite.internal.processors.cache.persistence.partstate.GroupPartitionId.getTypeByPartId) Collections(java.util.Collections) TxState(org.apache.ignite.internal.processors.cache.mvcc.txlog.TxState) GridMessageListener(org.apache.ignite.internal.managers.communication.GridMessageListener) GridJobExecuteRequest(org.apache.ignite.internal.GridJobExecuteRequest) CU(org.apache.ignite.internal.util.typedef.internal.CU) U(org.apache.ignite.internal.util.typedef.internal.U) IgniteEx(org.apache.ignite.internal.IgniteEx) RendezvousAffinityFunction(org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction) IdleVerifyResultV2(org.apache.ignite.internal.processors.cache.verify.IdleVerifyResultV2) UUID(java.util.UUID) File(java.io.File) Test(org.junit.Test)

Example 13 with GridMessageListener

use of org.apache.ignite.internal.managers.communication.GridMessageListener in project ignite by apache.

the class GridIoManagerBenchmark0 method testLatency.

/**
 * @throws Exception If failed.
 */
@Test
public void testLatency() throws Exception {
    final IgniteKernal sndKernal = (IgniteKernal) grid(0);
    final IgniteKernal rcvKernal = (IgniteKernal) grid(1);
    final ClusterNode sndNode = sndKernal.localNode();
    final ClusterNode rcvNode = rcvKernal.localNode();
    final GridIoManager snd = sndKernal.context().io();
    final GridIoManager rcv = rcvKernal.context().io();
    final LongAdder msgCntr = new LongAdder();
    final Integer topic = 1;
    final Map<IgniteUuid, CountDownLatch> map = new ConcurrentHashMap<>();
    rcv.addMessageListener(topic, new GridMessageListener() {

        @Override
        public void onMessage(UUID nodeId, Object msg, byte plc) {
            try {
                rcv.sendToCustomTopic(sndNode, topic, (Message) msg, PUBLIC_POOL);
            } catch (IgniteCheckedException e) {
                error("Failed to send message.", e);
            }
        }
    });
    snd.addMessageListener(topic, new GridMessageListener() {

        @Override
        public void onMessage(UUID nodeId, Object msg, byte plc) {
            map.get(((GridTestMessage) msg).id()).countDown();
        }
    });
    Timer t = new Timer("results-reporter");
    t.schedule(new TimerTask() {

        private long ts = System.currentTimeMillis();

        @Override
        public void run() {
            long newTs = System.currentTimeMillis();
            long qrys = msgCntr.sumThenReset();
            long time = newTs - ts;
            X.println("Communication benchmark [qps=" + qrys * 1000 / time + ", executed=" + qrys + ", time=" + time + ']');
            ts = newTs;
        }
    }, 10000, 10000);
    final AtomicBoolean finish = new AtomicBoolean();
    IgniteInternalFuture<?> f = GridTestUtils.runMultiThreadedAsync(new Callable<Object>() {

        @Override
        public Object call() throws Exception {
            try {
                IgniteUuid msgId = IgniteUuid.randomUuid();
                while (!finish.get()) {
                    CountDownLatch latch = new CountDownLatch(1);
                    map.put(msgId, latch);
                    snd.sendToCustomTopic(rcvNode, topic, new GridTestMessage(msgId, (String) null), PUBLIC_POOL);
                    latch.await();
                    msgCntr.increment();
                }
            } catch (IgniteCheckedException e) {
                X.println("Message send failed", e);
            } catch (InterruptedException ignored) {
            // No-op.
            }
            return null;
        }
    }, 1, "send-thread");
    Thread.sleep(TEST_TIMEOUT);
    finish.set(true);
    t.cancel();
    f.get();
}
Also used : Message(org.apache.ignite.plugin.extensions.communication.Message) GridMessageListener(org.apache.ignite.internal.managers.communication.GridMessageListener) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) TimerTask(java.util.TimerTask) IgniteUuid(org.apache.ignite.lang.IgniteUuid) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) UUID(java.util.UUID) ClusterNode(org.apache.ignite.cluster.ClusterNode) IgniteKernal(org.apache.ignite.internal.IgniteKernal) CountDownLatch(java.util.concurrent.CountDownLatch) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) LongAdder(java.util.concurrent.atomic.LongAdder) Timer(java.util.Timer) GridIoManager(org.apache.ignite.internal.managers.communication.GridIoManager) GridCommonAbstractTest(org.apache.ignite.testframework.junits.common.GridCommonAbstractTest) Test(org.junit.Test)

Example 14 with GridMessageListener

use of org.apache.ignite.internal.managers.communication.GridMessageListener in project ignite by apache.

the class GridIoManagerBenchmark method receiveMessages.

/**
 * @param g Kernal.
 */
private static void receiveMessages(final IgniteKernal g) {
    X.println(">>> Receiving messages.");
    final GridIoManager io = g.context().io();
    GridMessageListener lsnr = new GridMessageListener() {

        private ClusterNode node;

        @Override
        public void onMessage(UUID nodeId, Object msg, byte plc) {
            if (node == null)
                node = g.context().discovery().node(nodeId);
            GridTestMessage testMsg = ((GridTestMessage) msg);
            testMsg.bytes(null);
            try {
                io.sendToCustomTopic(node, TEST_TOPIC, testMsg, PUBLIC_POOL);
            } catch (IgniteCheckedException e) {
                e.printStackTrace();
            }
        }
    };
    io.addMessageListener(TEST_TOPIC, lsnr);
}
Also used : ClusterNode(org.apache.ignite.cluster.ClusterNode) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridIoManager(org.apache.ignite.internal.managers.communication.GridIoManager) GridMessageListener(org.apache.ignite.internal.managers.communication.GridMessageListener) UUID(java.util.UUID)

Example 15 with GridMessageListener

use of org.apache.ignite.internal.managers.communication.GridMessageListener in project ignite by apache.

the class GridContinuousProcessor method start.

/** {@inheritDoc} */
@Override
public void start(boolean activeOnStart) throws IgniteCheckedException {
    if (ctx.config().isDaemon())
        return;
    retryDelay = ctx.config().getNetworkSendRetryDelay();
    retryCnt = ctx.config().getNetworkSendRetryCount();
    marsh = ctx.config().getMarshaller();
    ctx.event().addLocalEventListener(new GridLocalEventListener() {

        @SuppressWarnings({ "fallthrough", "TooBroadScope" })
        @Override
        public void onEvent(Event evt) {
            assert evt instanceof DiscoveryEvent;
            assert evt.type() == EVT_NODE_LEFT || evt.type() == EVT_NODE_FAILED;
            UUID nodeId = ((DiscoveryEvent) evt).eventNode().id();
            clientInfos.remove(nodeId);
            // Unregister handlers created by left node.
            for (Map.Entry<UUID, RemoteRoutineInfo> e : rmtInfos.entrySet()) {
                UUID routineId = e.getKey();
                RemoteRoutineInfo info = e.getValue();
                if (nodeId.equals(info.nodeId)) {
                    if (info.autoUnsubscribe)
                        unregisterRemote(routineId);
                    if (info.hnd.isQuery())
                        info.hnd.onNodeLeft();
                }
            }
            for (Map.Entry<IgniteUuid, SyncMessageAckFuture> e : syncMsgFuts.entrySet()) {
                SyncMessageAckFuture fut = e.getValue();
                if (fut.nodeId().equals(nodeId)) {
                    SyncMessageAckFuture fut0 = syncMsgFuts.remove(e.getKey());
                    if (fut0 != null) {
                        ClusterTopologyCheckedException err = new ClusterTopologyCheckedException("Node left grid while sending message to: " + nodeId);
                        fut0.onDone(err);
                    }
                }
            }
        }
    }, EVT_NODE_LEFT, EVT_NODE_FAILED);
    ctx.event().addLocalEventListener(new GridLocalEventListener() {

        @Override
        public void onEvent(Event evt) {
            cancelFutures(new IgniteCheckedException("Topology segmented"));
        }
    }, EVT_NODE_SEGMENTED);
    ctx.discovery().setCustomEventListener(StartRoutineDiscoveryMessage.class, new CustomEventListener<StartRoutineDiscoveryMessage>() {

        @Override
        public void onCustomEvent(AffinityTopologyVersion topVer, ClusterNode snd, StartRoutineDiscoveryMessage msg) {
            if (!snd.id().equals(ctx.localNodeId()) && !ctx.isStopping())
                processStartRequest(snd, msg);
        }
    });
    ctx.discovery().setCustomEventListener(StartRoutineAckDiscoveryMessage.class, new CustomEventListener<StartRoutineAckDiscoveryMessage>() {

        @Override
        public void onCustomEvent(AffinityTopologyVersion topVer, ClusterNode snd, StartRoutineAckDiscoveryMessage msg) {
            StartFuture fut = startFuts.remove(msg.routineId());
            if (fut != null) {
                if (msg.errs().isEmpty()) {
                    LocalRoutineInfo routine = locInfos.get(msg.routineId());
                    // Update partition counters.
                    if (routine != null && routine.handler().isQuery()) {
                        Map<UUID, Map<Integer, T2<Long, Long>>> cntrsPerNode = msg.updateCountersPerNode();
                        Map<Integer, T2<Long, Long>> cntrs = msg.updateCounters();
                        GridCacheAdapter<Object, Object> interCache = ctx.cache().internalCache(routine.handler().cacheName());
                        GridCacheContext cctx = interCache != null ? interCache.context() : null;
                        if (cctx != null && cntrsPerNode != null && !cctx.isLocal() && cctx.affinityNode())
                            cntrsPerNode.put(ctx.localNodeId(), cctx.topology().updateCounters(false));
                        routine.handler().updateCounters(topVer, cntrsPerNode, cntrs);
                    }
                    fut.onRemoteRegistered();
                } else {
                    IgniteCheckedException firstEx = F.first(msg.errs().values());
                    fut.onDone(firstEx);
                    stopRoutine(msg.routineId());
                }
            }
        }
    });
    ctx.discovery().setCustomEventListener(StopRoutineDiscoveryMessage.class, new CustomEventListener<StopRoutineDiscoveryMessage>() {

        @Override
        public void onCustomEvent(AffinityTopologyVersion topVer, ClusterNode snd, StopRoutineDiscoveryMessage msg) {
            if (!snd.id().equals(ctx.localNodeId())) {
                UUID routineId = msg.routineId();
                unregisterRemote(routineId);
            }
            for (Map<UUID, LocalRoutineInfo> clientInfo : clientInfos.values()) {
                if (clientInfo.remove(msg.routineId()) != null)
                    break;
            }
        }
    });
    ctx.discovery().setCustomEventListener(StopRoutineAckDiscoveryMessage.class, new CustomEventListener<StopRoutineAckDiscoveryMessage>() {

        @Override
        public void onCustomEvent(AffinityTopologyVersion topVer, ClusterNode snd, StopRoutineAckDiscoveryMessage msg) {
            StopFuture fut = stopFuts.remove(msg.routineId());
            if (fut != null)
                fut.onDone();
        }
    });
    ctx.io().addMessageListener(TOPIC_CONTINUOUS, new GridMessageListener() {

        @Override
        public void onMessage(UUID nodeId, Object obj) {
            GridContinuousMessage msg = (GridContinuousMessage) obj;
            if (msg.data() == null && msg.dataBytes() != null) {
                try {
                    msg.data(U.unmarshal(marsh, msg.dataBytes(), U.resolveClassLoader(ctx.config())));
                } catch (IgniteCheckedException e) {
                    U.error(log, "Failed to process message (ignoring): " + msg, e);
                    return;
                }
            }
            switch(msg.type()) {
                case MSG_EVT_NOTIFICATION:
                    processNotification(nodeId, msg);
                    break;
                case MSG_EVT_ACK:
                    processMessageAck(msg);
                    break;
                default:
                    assert false : "Unexpected message received: " + msg.type();
            }
        }
    });
    ctx.cacheObjects().onContinuousProcessorStarted(ctx);
    ctx.service().onContinuousProcessorStarted(ctx);
    if (log.isDebugEnabled())
        log.debug("Continuous processor started.");
}
Also used : GridLocalEventListener(org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener) GridMessageListener(org.apache.ignite.internal.managers.communication.GridMessageListener) DiscoveryEvent(org.apache.ignite.events.DiscoveryEvent) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridCacheAdapter(org.apache.ignite.internal.processors.cache.GridCacheAdapter) UUID(java.util.UUID) T2(org.apache.ignite.internal.util.typedef.T2) ClusterNode(org.apache.ignite.cluster.ClusterNode) GridCacheContext(org.apache.ignite.internal.processors.cache.GridCacheContext) AffinityTopologyVersion(org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion) AtomicLong(java.util.concurrent.atomic.AtomicLong) Event(org.apache.ignite.events.Event) DiscoveryEvent(org.apache.ignite.events.DiscoveryEvent) GridTimeoutObject(org.apache.ignite.internal.processors.timeout.GridTimeoutObject) Map(java.util.Map) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) ClusterTopologyCheckedException(org.apache.ignite.internal.cluster.ClusterTopologyCheckedException)

Aggregations

UUID (java.util.UUID)30 GridMessageListener (org.apache.ignite.internal.managers.communication.GridMessageListener)30 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)15 ClusterNode (org.apache.ignite.cluster.ClusterNode)12 DiscoveryEvent (org.apache.ignite.events.DiscoveryEvent)11 Event (org.apache.ignite.events.Event)11 GridLocalEventListener (org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener)11 GridIoManager (org.apache.ignite.internal.managers.communication.GridIoManager)7 Test (org.junit.Test)7 CountDownLatch (java.util.concurrent.CountDownLatch)6 GridCommonAbstractTest (org.apache.ignite.testframework.junits.common.GridCommonAbstractTest)6 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)5 Collection (java.util.Collection)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)4 IgniteKernal (org.apache.ignite.internal.IgniteKernal)4 Message (org.apache.ignite.plugin.extensions.communication.Message)4 ArrayList (java.util.ArrayList)3 Map (java.util.Map)3 IgniteException (org.apache.ignite.IgniteException)3 CacheConfiguration (org.apache.ignite.configuration.CacheConfiguration)3