Search in sources :

Example 1 with GridMessageListener

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

the class IgfsDataManager method start0.

/**
 * {@inheritDoc}
 */
@Override
protected void start0() throws IgniteCheckedException {
    dataCacheStartLatch = new CountDownLatch(1);
    String igfsName = igfsCtx.configuration().getName();
    topic = F.isEmpty(igfsName) ? TOPIC_IGFS : TOPIC_IGFS.topic(igfsName);
    igfsCtx.kernalContext().io().addMessageListener(topic, new GridMessageListener() {

        @Override
        public void onMessage(UUID nodeId, Object msg, byte plc) {
            if (msg instanceof IgfsBlocksMessage)
                processBlocksMessage(nodeId, (IgfsBlocksMessage) msg);
            else if (msg instanceof IgfsAckMessage)
                processAckMessage(nodeId, (IgfsAckMessage) msg);
        }
    });
    igfsCtx.kernalContext().event().addLocalEventListener(new GridLocalEventListener() {

        @Override
        public void onEvent(Event evt) {
            assert evt.type() == EVT_NODE_FAILED || evt.type() == EVT_NODE_LEFT;
            DiscoveryEvent discoEvt = (DiscoveryEvent) evt;
            if (igfsCtx.igfsNode(discoEvt.eventNode())) {
                for (WriteCompletionFuture future : pendingWrites.values()) {
                    future.onError(discoEvt.eventNode().id(), new ClusterTopologyCheckedException("Node left grid before write completed: " + evt.node().id()));
                }
            }
        }
    }, EVT_NODE_LEFT, EVT_NODE_FAILED);
    delWorker = new AsyncDeleteWorker(igfsCtx.kernalContext().igniteInstanceName(), "igfs-" + igfsName + "-delete-worker", log);
    dataCacheName = igfsCtx.configuration().getDataCacheConfiguration().getName();
}
Also used : GridLocalEventListener(org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener) GridMessageListener(org.apache.ignite.internal.managers.communication.GridMessageListener) DiscoveryEvent(org.apache.ignite.events.DiscoveryEvent) CountDownLatch(java.util.concurrent.CountDownLatch) Event(org.apache.ignite.events.Event) DiscoveryEvent(org.apache.ignite.events.DiscoveryEvent) UUID(java.util.UUID) ClusterTopologyCheckedException(org.apache.ignite.internal.cluster.ClusterTopologyCheckedException)

Example 2 with GridMessageListener

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

the class DeploymentRequestOfUnknownClassProcessingTest method testResponseReceivingOnDeploymentRequestOfUnknownClass.

/**
 * @throws Exception If failed.
 */
@Test
public void testResponseReceivingOnDeploymentRequestOfUnknownClass() throws Exception {
    IgniteEx locNode = grid(0);
    IgniteEx remNode = grid(1);
    // Register deployment on remote node for attemt to load class on request receiving
    GridTestExternalClassLoader ldr = new GridTestExternalClassLoader(new URL[] { new URL(GridTestProperties.getProperty("p2p.uri.cls")) });
    Class task = ldr.loadClass("org.apache.ignite.tests.p2p.P2PTestTaskExternalPath1");
    GridDeployment locDep = remNode.context().deploy().deploy(task, task.getClassLoader());
    final GridFutureAdapter<Void> testResultFut = new GridFutureAdapter<>();
    final LogListener remNodeLogLsnr = LogListener.matches(s -> s.matches("Failed to resolve class.*?" + UNKNOWN_CLASS_NAME + ".*")).build();
    remNodeLog.registerListener(remNodeLogLsnr);
    locNode.context().io().addMessageListener(TEST_TOPIC_NAME, new GridMessageListener() {

        @Override
        public void onMessage(UUID nodeId, Object msg, byte plc) {
            try {
                assertTrue(msg instanceof GridDeploymentResponse);
                GridDeploymentResponse resp = (GridDeploymentResponse) msg;
                assertFalse("Unexpected response result, success=" + resp.success(), resp.success());
                String errMsg = resp.errorMessage();
                assertNotNull("Response should contain an error message.", errMsg);
                assertTrue("Response contains unexpected error message, errorMessage=" + errMsg, errMsg.matches("Requested resource not found \\(ignoring locally\\).*?" + UNKNOWN_CLASS_NAME + ".*"));
                testResultFut.onDone();
            } catch (Error e) {
                testResultFut.onDone(e);
            }
        }
    });
    GridDeploymentRequest req = new GridDeploymentRequest(TEST_TOPIC_NAME, locDep.classLoaderId(), UNKNOWN_CLASS_NAME, false);
    req.responseTopicBytes(U.marshal(locNode.context(), req.responseTopic()));
    locNode.context().io().sendToGridTopic(remNode.localNode(), TOPIC_CLASSLOAD, req, GridIoPolicy.P2P_POOL);
    // Сhecks that the expected response has been received.
    testResultFut.get(5_000, TimeUnit.MILLISECONDS);
    // Checks that error has been logged on remote node.
    assertTrue(remNodeLogLsnr.check());
}
Also used : ListeningTestLogger(org.apache.ignite.testframework.ListeningTestLogger) LogListener(org.apache.ignite.testframework.LogListener) GridFutureAdapter(org.apache.ignite.internal.util.future.GridFutureAdapter) GridCommonAbstractTest(org.apache.ignite.testframework.junits.common.GridCommonAbstractTest) GridTestProperties(org.apache.ignite.testframework.config.GridTestProperties) URL(java.net.URL) U(org.apache.ignite.internal.util.typedef.internal.U) IgniteEx(org.apache.ignite.internal.IgniteEx) Test(org.junit.Test) UUID(java.util.UUID) TOPIC_CLASSLOAD(org.apache.ignite.internal.GridTopic.TOPIC_CLASSLOAD) GridTestExternalClassLoader(org.apache.ignite.testframework.GridTestExternalClassLoader) TimeUnit(java.util.concurrent.TimeUnit) IgniteConfiguration(org.apache.ignite.configuration.IgniteConfiguration) GridIoPolicy(org.apache.ignite.internal.managers.communication.GridIoPolicy) GridMessageListener(org.apache.ignite.internal.managers.communication.GridMessageListener) LogListener(org.apache.ignite.testframework.LogListener) GridMessageListener(org.apache.ignite.internal.managers.communication.GridMessageListener) GridTestExternalClassLoader(org.apache.ignite.testframework.GridTestExternalClassLoader) URL(java.net.URL) IgniteEx(org.apache.ignite.internal.IgniteEx) GridFutureAdapter(org.apache.ignite.internal.util.future.GridFutureAdapter) UUID(java.util.UUID) GridCommonAbstractTest(org.apache.ignite.testframework.junits.common.GridCommonAbstractTest) Test(org.junit.Test)

Example 3 with GridMessageListener

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

the class GridCacheBinaryObjectMetadataExchangeMultinodeTest method replaceWithStoppingMappingRequestListener.

/**
 */
private void replaceWithStoppingMappingRequestListener(GridIoManager ioMgr, final int nodeIdToStop) {
    ioMgr.removeMessageListener(GridTopic.TOPIC_METADATA_REQ);
    ioMgr.addMessageListener(GridTopic.TOPIC_METADATA_REQ, new GridMessageListener() {

        @Override
        public void onMessage(UUID nodeId, Object msg, byte plc) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    metadataReqsCounter.incrementAndGet();
                    stopGrid(nodeIdToStop, true);
                }
            }).start();
        }
    });
}
Also used : GridMessageListener(org.apache.ignite.internal.managers.communication.GridMessageListener) BinaryObject(org.apache.ignite.binary.BinaryObject) UUID(java.util.UUID)

Example 4 with GridMessageListener

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

the class GridCacheBinaryObjectMetadataExchangeMultinodeTest method replaceWithCountingMappingRequestListener.

/**
 */
private void replaceWithCountingMappingRequestListener(GridIoManager ioMgr) {
    GridMessageListener[] lsnrs = U.field(ioMgr, "sysLsnrs");
    final GridMessageListener delegate = lsnrs[GridTopic.TOPIC_METADATA_REQ.ordinal()];
    GridMessageListener wrapper = new GridMessageListener() {

        @Override
        public void onMessage(UUID nodeId, Object msg, byte plc) {
            metadataReqsCounter.incrementAndGet();
            delegate.onMessage(nodeId, msg, plc);
        }
    };
    lsnrs[GridTopic.TOPIC_METADATA_REQ.ordinal()] = wrapper;
}
Also used : GridMessageListener(org.apache.ignite.internal.managers.communication.GridMessageListener) BinaryObject(org.apache.ignite.binary.BinaryObject) UUID(java.util.UUID)

Example 5 with GridMessageListener

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

the class GridTaskCommandHandler method requestTaskResult.

/**
 * @param resHolderId Result holder.
 * @param taskId Task ID.
 * @return Response from task holder.
 */
private IgniteBiTuple<String, GridTaskResultResponse> requestTaskResult(final UUID resHolderId, IgniteUuid taskId) {
    ClusterNode taskNode = ctx.discovery().node(resHolderId);
    if (taskNode == null)
        return F.t("Task result holder has left grid: " + resHolderId, null);
    // Tuple: error message-response.
    final IgniteBiTuple<String, GridTaskResultResponse> t = new IgniteBiTuple<>();
    final Lock lock = new ReentrantLock();
    final Condition cond = lock.newCondition();
    GridMessageListener msgLsnr = new GridMessageListener() {

        @Override
        public void onMessage(UUID nodeId, Object msg, byte plc) {
            String err = null;
            GridTaskResultResponse res = null;
            if (!(msg instanceof GridTaskResultResponse))
                err = "Received unexpected message: " + msg;
            else if (!nodeId.equals(resHolderId))
                err = "Received task result response from unexpected node [resHolderId=" + resHolderId + ", nodeId=" + nodeId + ']';
            else
                // Sender and message type are fine.
                res = (GridTaskResultResponse) msg;
            try {
                res.result(U.unmarshal(ctx, res.resultBytes(), U.resolveClassLoader(ctx.config())));
            } catch (IgniteCheckedException e) {
                U.error(log, "Failed to unmarshal task result: " + res, e);
            }
            lock.lock();
            try {
                if (t.isEmpty()) {
                    t.set(err, res);
                    cond.signalAll();
                }
            } finally {
                lock.unlock();
            }
        }
    };
    GridLocalEventListener discoLsnr = new GridLocalEventListener() {

        @Override
        public void onEvent(Event evt) {
            assert evt instanceof DiscoveryEvent && (evt.type() == EVT_NODE_FAILED || evt.type() == EVT_NODE_LEFT) : "Unexpected event: " + evt;
            DiscoveryEvent discoEvt = (DiscoveryEvent) evt;
            if (resHolderId.equals(discoEvt.eventNode().id())) {
                lock.lock();
                try {
                    if (t.isEmpty()) {
                        t.set("Node that originated task execution has left grid: " + resHolderId, null);
                        cond.signalAll();
                    }
                } finally {
                    lock.unlock();
                }
            }
        }
    };
    // 1. Create unique topic name and register listener.
    Object topic = TOPIC_REST.topic("task-result", topicIdGen.getAndIncrement());
    try {
        ctx.io().addMessageListener(topic, msgLsnr);
        // 2. Send message.
        try {
            byte[] topicBytes = U.marshal(ctx, topic);
            ctx.io().sendToGridTopic(taskNode, TOPIC_REST, new GridTaskResultRequest(taskId, topic, topicBytes), SYSTEM_POOL);
        } catch (IgniteCheckedException e) {
            String errMsg = "Failed to send task result request [resHolderId=" + resHolderId + ", err=" + e.getMessage() + ']';
            if (log.isDebugEnabled())
                log.debug(errMsg);
            return F.t(errMsg, null);
        }
        // 3. Listen to discovery events.
        ctx.event().addLocalEventListener(discoLsnr, EVT_NODE_FAILED, EVT_NODE_LEFT);
        // 4. Check whether node has left before disco listener has been installed.
        taskNode = ctx.discovery().node(resHolderId);
        if (taskNode == null)
            return F.t("Task result holder has left grid: " + resHolderId, null);
        // 5. Wait for result.
        lock.lock();
        try {
            long netTimeout = ctx.config().getNetworkTimeout();
            if (t.isEmpty())
                cond.await(netTimeout, MILLISECONDS);
            if (t.isEmpty())
                t.set1("Timed out waiting for task result (consider increasing 'networkTimeout' " + "configuration property) [resHolderId=" + resHolderId + ", netTimeout=" + netTimeout + ']');
            // Return result
            return t;
        } catch (InterruptedException ignored) {
            Thread.currentThread().interrupt();
            return F.t("Interrupted while waiting for task result.", null);
        } finally {
            lock.unlock();
        }
    } finally {
        ctx.io().removeMessageListener(topic, msgLsnr);
        ctx.event().removeLocalEventListener(discoLsnr);
    }
}
Also used : ClusterNode(org.apache.ignite.cluster.ClusterNode) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Condition(java.util.concurrent.locks.Condition) IgniteBiTuple(org.apache.ignite.lang.IgniteBiTuple) GridLocalEventListener(org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener) GridMessageListener(org.apache.ignite.internal.managers.communication.GridMessageListener) DiscoveryEvent(org.apache.ignite.events.DiscoveryEvent) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Lock(java.util.concurrent.locks.Lock) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) Event(org.apache.ignite.events.Event) DiscoveryEvent(org.apache.ignite.events.DiscoveryEvent) UUID(java.util.UUID)

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