Search in sources :

Example 61 with DiscoveryEvent

use of org.apache.ignite.events.DiscoveryEvent in project ignite by apache.

the class GridDeploymentCommunication method sendResourceRequest.

/**
 * Sends request to the remote node and wait for response. If there is
 * no response until threshold time, method returns null.
 *
 * @param rsrcName Resource name.
 * @param clsLdrId Class loader ID.
 * @param dstNode Remote node request should be sent to.
 * @param threshold Time in milliseconds when request is decided to
 *      be obsolete.
 * @return Either response value or {@code null} if timeout occurred.
 * @throws IgniteCheckedException Thrown if there is no connection with remote node.
 */
@SuppressWarnings({ "SynchronizationOnLocalVariableOrMethodParameter" })
GridDeploymentResponse sendResourceRequest(final String rsrcName, IgniteUuid clsLdrId, final ClusterNode dstNode, long threshold) throws IgniteCheckedException {
    assert rsrcName != null;
    assert dstNode != null;
    assert clsLdrId != null;
    Collection<UUID> nodeIds = activeReqNodeIds.get();
    if (nodeIds != null && nodeIds.contains(dstNode.id())) {
        if (log.isDebugEnabled())
            log.debug("Node attempts to load resource from one of the requesters " + "[rsrcName=" + rsrcName + ", dstNodeId=" + dstNode.id() + ", requesters=" + nodeIds + ']');
        GridDeploymentResponse fake = new GridDeploymentResponse();
        fake.success(false);
        fake.errorMessage("Node attempts to load resource from one of the requesters " + "[rsrcName=" + rsrcName + ", dstNodeId=" + dstNode.id() + ", requesters=" + nodeIds + ']');
        return fake;
    }
    Object resTopic = TOPIC_CLASSLOAD.topic(IgniteUuid.fromUuid(ctx.localNodeId()));
    GridDeploymentRequest req = new GridDeploymentRequest(resTopic, clsLdrId, rsrcName, false);
    // Send node IDs chain with request.
    req.nodeIds(nodeIds);
    final Object qryMux = new Object();
    final GridTuple<GridDeploymentResponse> res = new GridTuple<>();
    GridLocalEventListener discoLsnr = new GridLocalEventListener() {

        @Override
        public void onEvent(Event evt) {
            assert evt instanceof DiscoveryEvent;
            assert evt.type() == EVT_NODE_LEFT || evt.type() == EVT_NODE_FAILED;
            DiscoveryEvent discoEvt = (DiscoveryEvent) evt;
            UUID nodeId = discoEvt.eventNode().id();
            if (!nodeId.equals(dstNode.id()))
                // Not a destination node.
                return;
            GridDeploymentResponse fake = new GridDeploymentResponse();
            String errMsg = "Originating node left grid (resource will not be peer loaded) " + "[nodeId=" + dstNode.id() + ", rsrc=" + rsrcName + ']';
            U.warn(log, errMsg);
            fake.success(false);
            fake.errorMessage(errMsg);
            // because originating node has left grid.
            synchronized (qryMux) {
                res.set(fake);
                qryMux.notifyAll();
            }
        }
    };
    GridMessageListener resLsnr = new GridMessageListener() {

        @Override
        public void onMessage(UUID nodeId, Object msg, byte plc) {
            assert nodeId != null;
            assert msg != null;
            synchronized (qryMux) {
                if (!(msg instanceof GridDeploymentResponse)) {
                    U.error(log, "Received unknown peer class loading response [node=" + nodeId + ", msg=" + msg + ']');
                } else
                    res.set((GridDeploymentResponse) msg);
                qryMux.notifyAll();
            }
        }
    };
    try {
        ctx.io().addMessageListener(resTopic, resLsnr);
        // The destination node has potentially left grid here but in this case
        // Communication manager will throw the exception while sending message.
        ctx.event().addLocalEventListener(discoLsnr, EVT_NODE_FAILED, EVT_NODE_LEFT);
        long start = U.currentTimeMillis();
        if (req.responseTopic() != null && !ctx.localNodeId().equals(dstNode.id()))
            req.responseTopicBytes(U.marshal(marsh, req.responseTopic()));
        ctx.io().sendToGridTopic(dstNode, TOPIC_CLASSLOAD, req, GridIoPolicy.P2P_POOL);
        if (log.isDebugEnabled())
            log.debug("Sent peer class loading request [node=" + dstNode.id() + ", req=" + req + ']');
        synchronized (qryMux) {
            try {
                long timeout = threshold - start;
                if (log.isDebugEnabled()) {
                    log.debug("Waiting for peer response from node [node=" + dstNode.id() + ", timeout=" + timeout + ']');
                }
                while (res.get() == null && timeout > 0) {
                    qryMux.wait(timeout);
                    timeout = threshold - U.currentTimeMillis();
                }
            } catch (InterruptedException e) {
                // Interrupt again to get it in the users code.
                Thread.currentThread().interrupt();
                throw new IgniteCheckedException("Got interrupted while waiting for response from node: " + dstNode.id(), e);
            }
        }
        if (res.get() == null) {
            U.warn(log, "Failed to receive peer response from node within duration [node=" + dstNode.id() + ", duration=" + (U.currentTimeMillis() - start) + ']');
        } else if (log.isDebugEnabled())
            log.debug("Received peer loading response [node=" + dstNode.id() + ", res=" + res.get() + ']');
        return res.get();
    } finally {
        ctx.event().removeLocalEventListener(discoLsnr, EVT_NODE_FAILED, EVT_NODE_LEFT);
        ctx.io().removeMessageListener(resTopic, resLsnr);
    }
}
Also used : GridLocalEventListener(org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener) GridMessageListener(org.apache.ignite.internal.managers.communication.GridMessageListener) GridTuple(org.apache.ignite.internal.util.lang.GridTuple) DiscoveryEvent(org.apache.ignite.events.DiscoveryEvent) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) DiscoveryEvent(org.apache.ignite.events.DiscoveryEvent) Event(org.apache.ignite.events.Event) UUID(java.util.UUID)

Example 62 with DiscoveryEvent

use of org.apache.ignite.events.DiscoveryEvent in project ignite by apache.

the class GridEventStorageManager method query.

/**
 * @param p Grid event predicate.
 * @param nodes Collection of nodes.
 * @param timeout Maximum time to wait for result, if {@code 0}, then wait until result is received.
 * @return Collection of events.
 * @throws IgniteCheckedException Thrown in case of any errors.
 */
@SuppressWarnings({ "SynchronizationOnLocalVariableOrMethodParameter", "deprecation" })
private <T extends Event> List<T> query(IgnitePredicate<T> p, Collection<? extends ClusterNode> nodes, long timeout) throws IgniteCheckedException {
    assert p != null;
    assert nodes != null;
    if (nodes.isEmpty()) {
        U.warn(log, "Failed to query events for empty nodes collection.");
        return Collections.emptyList();
    }
    GridIoManager ioMgr = ctx.io();
    final List<T> evts = new ArrayList<>();
    final AtomicReference<Throwable> err = new AtomicReference<>();
    final Set<UUID> uids = new HashSet<>();
    final Object qryMux = new Object();
    for (ClusterNode node : nodes) uids.add(node.id());
    GridLocalEventListener evtLsnr = new GridLocalEventListener() {

        @Override
        public void onEvent(Event evt) {
            assert evt instanceof DiscoveryEvent;
            synchronized (qryMux) {
                uids.remove(((DiscoveryEvent) evt).eventNode().id());
                if (uids.isEmpty())
                    qryMux.notifyAll();
            }
        }
    };
    GridMessageListener resLsnr = new GridMessageListener() {

        @SuppressWarnings("deprecation")
        @Override
        public void onMessage(UUID nodeId, Object msg, byte plc) {
            assert nodeId != null;
            assert msg != null;
            if (!(msg instanceof GridEventStorageMessage)) {
                U.error(log, "Received unknown message: " + msg);
                return;
            }
            GridEventStorageMessage res = (GridEventStorageMessage) msg;
            try {
                if (res.eventsBytes() != null)
                    res.events(U.<Collection<Event>>unmarshal(marsh, res.eventsBytes(), U.resolveClassLoader(ctx.config())));
                if (res.exceptionBytes() != null)
                    res.exception(U.<Throwable>unmarshal(marsh, res.exceptionBytes(), U.resolveClassLoader(ctx.config())));
            } catch (IgniteCheckedException e) {
                U.error(log, "Failed to unmarshal events query response: " + msg, e);
                return;
            }
            synchronized (qryMux) {
                if (uids.remove(nodeId)) {
                    if (res.events() != null)
                        evts.addAll((Collection<T>) res.events());
                } else
                    U.warn(log, "Received duplicate response (ignoring) [nodeId=" + nodeId + ", msg=" + res + ']');
                if (res.exception() != null)
                    err.set(res.exception());
                if (uids.isEmpty() || err.get() != null)
                    qryMux.notifyAll();
            }
        }
    };
    Object resTopic = TOPIC_EVENT.topic(IgniteUuid.fromUuid(ctx.localNodeId()));
    try {
        addLocalEventListener(evtLsnr, new int[] { EVT_NODE_LEFT, EVT_NODE_FAILED });
        ioMgr.addMessageListener(resTopic, resLsnr);
        byte[] serFilter = U.marshal(marsh, p);
        GridDeployment dep = ctx.deploy().deploy(p.getClass(), U.detectClassLoader(p.getClass()));
        if (dep == null)
            throw new IgniteDeploymentCheckedException("Failed to deploy event filter: " + p);
        GridEventStorageMessage msg = new GridEventStorageMessage(resTopic, serFilter, p.getClass().getName(), dep.classLoaderId(), dep.deployMode(), dep.userVersion(), dep.participants());
        sendMessage(nodes, TOPIC_EVENT, msg, PUBLIC_POOL);
        if (timeout == 0)
            timeout = Long.MAX_VALUE;
        long now = U.currentTimeMillis();
        // Account for overflow of long value.
        long endTime = now + timeout <= 0 ? Long.MAX_VALUE : now + timeout;
        long delta = timeout;
        Collection<UUID> uidsCp = null;
        synchronized (qryMux) {
            try {
                while (!uids.isEmpty() && err.get() == null && delta > 0) {
                    qryMux.wait(delta);
                    delta = endTime - U.currentTimeMillis();
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new IgniteCheckedException("Got interrupted while waiting for event query responses.", e);
            }
            if (err.get() != null)
                throw new IgniteCheckedException("Failed to query events due to exception on remote node.", err.get());
            if (!uids.isEmpty())
                uidsCp = new LinkedList<>(uids);
        }
        // Outside of synchronization.
        if (uidsCp != null) {
            for (Iterator<UUID> iter = uidsCp.iterator(); iter.hasNext(); ) // Ignore nodes that have left the grid.
            if (ctx.discovery().node(iter.next()) == null)
                iter.remove();
            if (!uidsCp.isEmpty())
                throw new IgniteCheckedException("Failed to receive event query response from following nodes: " + uidsCp);
        }
    } finally {
        ioMgr.removeMessageListener(resTopic, resLsnr);
        removeLocalEventListener(evtLsnr);
    }
    return evts;
}
Also used : GridMessageListener(org.apache.ignite.internal.managers.communication.GridMessageListener) ArrayList(java.util.ArrayList) DiscoveryEvent(org.apache.ignite.events.DiscoveryEvent) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) EVT_NODE_LEFT(org.apache.ignite.events.EventType.EVT_NODE_LEFT) EVT_DISCOVERY_CUSTOM_EVT(org.apache.ignite.internal.events.DiscoveryCustomEvent.EVT_DISCOVERY_CUSTOM_EVT) LT(org.apache.ignite.internal.util.typedef.internal.LT) TOPIC_EVENT(org.apache.ignite.internal.GridTopic.TOPIC_EVENT) UUID(java.util.UUID) GridConcurrentLinkedHashSet(org.apache.ignite.internal.util.GridConcurrentLinkedHashSet) HashSet(java.util.HashSet) ClusterNode(org.apache.ignite.cluster.ClusterNode) IgniteDeploymentCheckedException(org.apache.ignite.internal.IgniteDeploymentCheckedException) AtomicReference(java.util.concurrent.atomic.AtomicReference) LinkedList(java.util.LinkedList) GridDeployment(org.apache.ignite.internal.managers.deployment.GridDeployment) GridIoManager(org.apache.ignite.internal.managers.communication.GridIoManager) Event(org.apache.ignite.events.Event) DiscoveryEvent(org.apache.ignite.events.DiscoveryEvent) Collection(java.util.Collection)

Example 63 with DiscoveryEvent

use of org.apache.ignite.events.DiscoveryEvent in project ignite by apache.

the class IgniteAuthenticationProcessor method start.

/**
 * {@inheritDoc}
 */
@Override
public void start() throws IgniteCheckedException {
    super.start();
    if (isEnabled && !GridCacheUtils.isPersistenceEnabled(ctx.config())) {
        isEnabled = false;
        throw new IgniteCheckedException("Authentication can be enabled only for cluster with enabled persistence." + " Check the DataRegionConfiguration");
    }
    ctx.addNodeAttribute(IgniteNodeAttributes.ATTR_AUTHENTICATION_ENABLED, isEnabled);
    GridDiscoveryManager discoMgr = ctx.discovery();
    GridIoManager ioMgr = ctx.io();
    discoMgr.setCustomEventListener(UserProposedMessage.class, new UserProposedListener());
    discoMgr.setCustomEventListener(UserAcceptedMessage.class, new UserAcceptedListener());
    discoLsnr = new DiscoveryEventListener() {

        @Override
        public void onEvent(DiscoveryEvent evt, DiscoCache discoCache) {
            if (!isEnabled || ctx.isStopping())
                return;
            switch(evt.type()) {
                case EVT_NODE_LEFT:
                case EVT_NODE_FAILED:
                    onNodeLeft(evt.eventNode().id());
                    break;
                case EVT_NODE_JOINED:
                    onNodeJoin(evt.eventNode());
                    break;
            }
        }
    };
    ctx.event().addDiscoveryEventListener(discoLsnr, DISCO_EVT_TYPES);
    ioLsnr = new GridMessageListener() {

        @Override
        public void onMessage(UUID nodeId, Object msg, byte plc) {
            if (!isEnabled || ctx.isStopping())
                return;
            if (msg instanceof UserManagementOperationFinishedMessage)
                onFinishMessage(nodeId, (UserManagementOperationFinishedMessage) msg);
            else if (msg instanceof UserAuthenticateRequestMessage)
                onAuthenticateRequestMessage(nodeId, (UserAuthenticateRequestMessage) msg);
            else if (msg instanceof UserAuthenticateResponseMessage)
                onAuthenticateResponseMessage((UserAuthenticateResponseMessage) msg);
        }
    };
    ioMgr.addMessageListener(GridTopic.TOPIC_AUTH, ioLsnr);
    exec = new IgniteThreadPoolExecutor("auth", ctx.config().getIgniteInstanceName(), 1, 1, 0, new LinkedBlockingQueue<>());
}
Also used : DiscoCache(org.apache.ignite.internal.managers.discovery.DiscoCache) GridMessageListener(org.apache.ignite.internal.managers.communication.GridMessageListener) DiscoveryEvent(org.apache.ignite.events.DiscoveryEvent) IgniteThreadPoolExecutor(org.apache.ignite.thread.IgniteThreadPoolExecutor) DiscoveryEventListener(org.apache.ignite.internal.managers.eventstorage.DiscoveryEventListener) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) GridDiscoveryManager(org.apache.ignite.internal.managers.discovery.GridDiscoveryManager) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridIoManager(org.apache.ignite.internal.managers.communication.GridIoManager) UUID(java.util.UUID)

Example 64 with DiscoveryEvent

use of org.apache.ignite.events.DiscoveryEvent in project ignite by apache.

the class GridMarshallerMappingProcessor method start.

/**
 * {@inheritDoc}
 */
@Override
public void start() throws IgniteCheckedException {
    GridDiscoveryManager discoMgr = ctx.discovery();
    GridIoManager ioMgr = ctx.io();
    MarshallerMappingTransport transport = new MarshallerMappingTransport(ctx, mappingExchangeSyncMap, clientReqSyncMap);
    marshallerCtx.onMarshallerProcessorStarted(ctx, transport);
    discoMgr.setCustomEventListener(MappingProposedMessage.class, new MappingProposedListener());
    discoMgr.setCustomEventListener(MappingAcceptedMessage.class, new MappingAcceptedListener());
    if (ctx.clientNode())
        ioMgr.addMessageListener(TOPIC_MAPPING_MARSH, new MissingMappingResponseListener());
    else
        ioMgr.addMessageListener(TOPIC_MAPPING_MARSH, new MissingMappingRequestListener(ioMgr));
    if (ctx.clientNode())
        ctx.event().addLocalEventListener(new GridLocalEventListener() {

            @Override
            public void onEvent(Event evt) {
                DiscoveryEvent evt0 = (DiscoveryEvent) evt;
                if (!ctx.isStopping()) {
                    for (ClientRequestFuture fut : clientReqSyncMap.values()) fut.onNodeLeft(evt0.eventNode().id());
                }
            }
        }, EVT_NODE_LEFT, EVT_NODE_FAILED);
}
Also used : GridDiscoveryManager(org.apache.ignite.internal.managers.discovery.GridDiscoveryManager) GridLocalEventListener(org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener) GridIoManager(org.apache.ignite.internal.managers.communication.GridIoManager) DiscoveryEvent(org.apache.ignite.events.DiscoveryEvent) Event(org.apache.ignite.events.Event) DiscoveryEvent(org.apache.ignite.events.DiscoveryEvent)

Example 65 with DiscoveryEvent

use of org.apache.ignite.events.DiscoveryEvent in project ignite by apache.

the class IgfsFragmentizerManager method onKernalStart0.

/**
 * {@inheritDoc}
 */
@Override
protected void onKernalStart0() throws IgniteCheckedException {
    if (igfsCtx.configuration().isFragmentizerEnabled()) {
        // Check at startup if this node is a fragmentizer coordinator.
        DiscoveryEvent locJoinEvt = igfsCtx.kernalContext().discovery().localJoinEvent();
        checkLaunchCoordinator(locJoinEvt);
    }
}
Also used : DiscoveryEvent(org.apache.ignite.events.DiscoveryEvent)

Aggregations

DiscoveryEvent (org.apache.ignite.events.DiscoveryEvent)83 Event (org.apache.ignite.events.Event)54 UUID (java.util.UUID)39 ClusterNode (org.apache.ignite.cluster.ClusterNode)32 CountDownLatch (java.util.concurrent.CountDownLatch)24 GridLocalEventListener (org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener)24 Ignite (org.apache.ignite.Ignite)23 AffinityTopologyVersion (org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion)18 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)15 ArrayList (java.util.ArrayList)12 Collection (java.util.Collection)11 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)11 GridMessageListener (org.apache.ignite.internal.managers.communication.GridMessageListener)11 List (java.util.List)10 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)8 JobEvent (org.apache.ignite.events.JobEvent)8 IgniteInterruptedCheckedException (org.apache.ignite.internal.IgniteInterruptedCheckedException)7 GridAffinityFunctionContextImpl (org.apache.ignite.internal.processors.affinity.GridAffinityFunctionContextImpl)7 IgniteException (org.apache.ignite.IgniteException)6 ClusterTopologyCheckedException (org.apache.ignite.internal.cluster.ClusterTopologyCheckedException)6