Search in sources :

Example 1 with GridLocalEventListener

use of org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener 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 GridLocalEventListener

use of org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener in project ignite by apache.

the class GridCacheQueryManager method start0.

/**
 * {@inheritDoc}
 */
@Override
public void start0() throws IgniteCheckedException {
    CacheConfiguration ccfg = cctx.config();
    qryProcEnabled = QueryUtils.isEnabled(ccfg);
    qryProc = cctx.kernalContext().query();
    cacheName = cctx.name();
    enabled = qryProcEnabled || (isIndexingSpiEnabled() && !CU.isSystemCache(cacheName));
    maxIterCnt = ccfg.getMaxQueryIteratorsCount();
    detailMetricsSz = ccfg.getQueryDetailMetricsSize();
    if (detailMetricsSz > 0)
        detailMetrics = new ConcurrentHashMap<>(detailMetricsSz);
    lsnr = new GridLocalEventListener() {

        @Override
        public void onEvent(Event evt) {
            UUID nodeId = ((DiscoveryEvent) evt).eventNode().id();
            Map<Long, GridFutureAdapter<QueryResult<K, V>>> futs = qryIters.remove(nodeId);
            if (futs != null) {
                for (Map.Entry<Long, GridFutureAdapter<QueryResult<K, V>>> entry : futs.entrySet()) {
                    final Object rcpt = recipient(nodeId, entry.getKey());
                    entry.getValue().listen(new CIX1<IgniteInternalFuture<QueryResult<K, V>>>() {

                        @Override
                        public void applyx(IgniteInternalFuture<QueryResult<K, V>> f) throws IgniteCheckedException {
                            f.get().closeIfNotShared(rcpt);
                        }
                    });
                }
            }
            Map<Long, GridFutureAdapter<FieldsResult>> fieldsFuts = fieldsQryRes.remove(nodeId);
            if (fieldsFuts != null) {
                for (Map.Entry<Long, GridFutureAdapter<FieldsResult>> entry : fieldsFuts.entrySet()) {
                    final Object rcpt = recipient(nodeId, entry.getKey());
                    entry.getValue().listen(new CIX1<IgniteInternalFuture<FieldsResult>>() {

                        @Override
                        public void applyx(IgniteInternalFuture<FieldsResult> f) throws IgniteCheckedException {
                            f.get().closeIfNotShared(rcpt);
                        }
                    });
                }
            }
        }
    };
    metrics = new GridCacheQueryMetricsAdapter(cctx.kernalContext().metric(), cctx.name(), cctx.isNear());
    cctx.events().addListener(lsnr, EVT_NODE_LEFT, EVT_NODE_FAILED);
    qryTopVer = cctx.startTopologyVersion();
    assert qryTopVer != null : cctx.name();
}
Also used : CIX1(org.apache.ignite.internal.util.typedef.CIX1) GridLocalEventListener(org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener) DiscoveryEvent(org.apache.ignite.events.DiscoveryEvent) IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) IndexQueryResult(org.apache.ignite.internal.cache.query.index.IndexQueryResult) CacheEntry(org.apache.ignite.cache.CacheEntry) CacheQueryExecutedEvent(org.apache.ignite.events.CacheQueryExecutedEvent) Event(org.apache.ignite.events.Event) CacheQueryReadEvent(org.apache.ignite.events.CacheQueryReadEvent) DiscoveryEvent(org.apache.ignite.events.DiscoveryEvent) CacheObject(org.apache.ignite.internal.processors.cache.CacheObject) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) UUID(java.util.UUID) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) GridLeanMap(org.apache.ignite.internal.util.GridLeanMap) CacheConfiguration(org.apache.ignite.configuration.CacheConfiguration)

Example 3 with GridLocalEventListener

use of org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener in project ignite by apache.

the class GridCacheDistributedQueryManager method start0.

/**
 * {@inheritDoc}
 */
@Override
public void start0() throws IgniteCheckedException {
    super.start0();
    assert cctx.config().getCacheMode() != LOCAL;
    cctx.io().addCacheHandler(cctx.cacheId(), GridCacheQueryRequest.class, new CI2<UUID, GridCacheQueryRequest>() {

        @Override
        public void apply(UUID nodeId, GridCacheQueryRequest req) {
            processQueryRequest(nodeId, req);
        }
    });
    lsnr = new GridLocalEventListener() {

        @Override
        public void onEvent(Event evt) {
            DiscoveryEvent discoEvt = (DiscoveryEvent) evt;
            for (GridCacheDistributedQueryFuture fut : futs.values()) fut.onNodeLeft(discoEvt.eventNode().id());
        }
    };
    cctx.events().addListener(lsnr, EVT_NODE_LEFT, EVT_NODE_FAILED);
}
Also used : GridLocalEventListener(org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener) DiscoveryEvent(org.apache.ignite.events.DiscoveryEvent) Event(org.apache.ignite.events.Event) DiscoveryEvent(org.apache.ignite.events.DiscoveryEvent) UUID(java.util.UUID)

Example 4 with GridLocalEventListener

use of org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener 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)

Example 5 with GridLocalEventListener

use of org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener in project ignite by apache.

the class WeightedRandomLoadBalancingSpi method onContextInitialized0.

/**
 * {@inheritDoc}
 */
@Override
protected void onContextInitialized0(IgniteSpiContext spiCtx) throws IgniteSpiException {
    getSpiContext().addLocalEventListener(evtLsnr = new GridLocalEventListener() {

        @Override
        public void onEvent(Event evt) {
            assert evt instanceof TaskEvent || evt instanceof JobEvent;
            if (evt.type() == EVT_TASK_FINISHED || evt.type() == EVT_TASK_FAILED) {
                IgniteUuid sesId = ((TaskEvent) evt).taskSessionId();
                taskTops.remove(sesId);
                if (log.isDebugEnabled())
                    log.debug("Removed task topology from topology cache for session: " + sesId);
            } else // Here we set mapped property and later cache will be ignored
            if (evt.type() == EVT_JOB_MAPPED) {
                IgniteUuid sesId = ((JobEvent) evt).taskSessionId();
                IgniteBiTuple<Boolean, WeightedTopology> weightedTop = taskTops.get(sesId);
                if (weightedTop != null)
                    weightedTop.set1(true);
                if (log.isDebugEnabled())
                    log.debug("Job has been mapped. Ignore cache for session: " + sesId);
            }
        }
    }, EVT_TASK_FAILED, EVT_TASK_FINISHED, EVT_JOB_MAPPED);
}
Also used : JobEvent(org.apache.ignite.events.JobEvent) GridLocalEventListener(org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener) IgniteBiTuple(org.apache.ignite.lang.IgniteBiTuple) IgniteUuid(org.apache.ignite.lang.IgniteUuid) TaskEvent(org.apache.ignite.events.TaskEvent) JobEvent(org.apache.ignite.events.JobEvent) TaskEvent(org.apache.ignite.events.TaskEvent) Event(org.apache.ignite.events.Event)

Aggregations

GridLocalEventListener (org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener)30 Event (org.apache.ignite.events.Event)28 DiscoveryEvent (org.apache.ignite.events.DiscoveryEvent)25 UUID (java.util.UUID)20 ClusterNode (org.apache.ignite.cluster.ClusterNode)12 GridMessageListener (org.apache.ignite.internal.managers.communication.GridMessageListener)11 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)9 Collection (java.util.Collection)5 Map (java.util.Map)5 ClusterTopologyCheckedException (org.apache.ignite.internal.cluster.ClusterTopologyCheckedException)5 IgniteBiTuple (org.apache.ignite.lang.IgniteBiTuple)5 HashMap (java.util.HashMap)4 Iterator (java.util.Iterator)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)4 ConcurrentMap (java.util.concurrent.ConcurrentMap)4 GridTimeoutObject (org.apache.ignite.internal.processors.timeout.GridTimeoutObject)4 ArrayList (java.util.ArrayList)3 List (java.util.List)3 AffinityTopologyVersion (org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion)3 LinkedHashMap (java.util.LinkedHashMap)2