Search in sources :

Example 31 with GridFutureAdapter

use of org.apache.ignite.internal.util.future.GridFutureAdapter in project ignite by apache.

the class GridDhtTxLocalAdapter method lockAllAsync.

/**
 * @param cacheCtx Cache context.
 * @param entries Entries to lock.
 * @param msgId Message ID.
 * @param read Read flag.
 * @param createTtl TTL for create operation.
 * @param accessTtl TTL for read operation.
 * @param needRetVal Return value flag.
 * @param skipStore Skip store flag.
 * @param keepBinary Keep binary flag.
 * @param nearCache {@code True} if near cache enabled on originating node.
 * @return Lock future.
 */
@SuppressWarnings("ForLoopReplaceableByForEach")
IgniteInternalFuture<GridCacheReturn> lockAllAsync(GridCacheContext cacheCtx, List<GridCacheEntryEx> entries, long msgId, final boolean read, final boolean needRetVal, long createTtl, long accessTtl, boolean skipStore, boolean keepBinary, boolean nearCache) {
    try {
        checkValid();
    } catch (IgniteCheckedException e) {
        return new GridFinishedFuture<>(e);
    }
    final GridCacheReturn ret = new GridCacheReturn(localResult(), false);
    if (F.isEmpty(entries))
        return new GridFinishedFuture<>(ret);
    init();
    onePhaseCommit(onePhaseCommit);
    try {
        GridFutureAdapter<GridCacheReturn> enlistFut = new GridFutureAdapter<>();
        if (!updateLockFuture(null, enlistFut))
            return finishFuture(enlistFut, timedOut() ? timeoutException() : rollbackException(), false);
        Set<KeyCacheObject> skipped = null;
        try {
            AffinityTopologyVersion topVer = topologyVersion();
            GridDhtCacheAdapter dhtCache = cacheCtx.isNear() ? cacheCtx.near().dht() : cacheCtx.dht();
            // Enlist locks into transaction.
            for (int i = 0; i < entries.size(); i++) {
                GridCacheEntryEx entry = entries.get(i);
                KeyCacheObject key = entry.key();
                IgniteTxEntry txEntry = entry(entry.txKey());
                // First time access.
                if (txEntry == null) {
                    GridDhtCacheEntry cached;
                    while (true) {
                        try {
                            cached = dhtCache.entryExx(key, topVer);
                            cached.unswap(read);
                            break;
                        } catch (GridCacheEntryRemovedException ignore) {
                            if (log.isDebugEnabled())
                                log.debug("Get removed entry: " + key);
                        }
                    }
                    addActiveCache(dhtCache.context(), false);
                    txEntry = addEntry(NOOP, null, null, null, cached, null, CU.empty0(), false, -1L, -1L, null, skipStore, keepBinary, nearCache);
                    if (read)
                        txEntry.ttl(accessTtl);
                    txEntry.cached(cached);
                    addReader(msgId, cached, txEntry, topVer);
                } else {
                    if (skipped == null)
                        skipped = new GridLeanSet<>();
                    skipped.add(key);
                }
            }
        } finally {
            finishFuture(enlistFut, null, true);
        }
        assert pessimistic();
        Collection<KeyCacheObject> keys = F.viewReadOnly(entries, CU.entry2Key());
        // Acquire locks only after having added operation to the write set.
        // Otherwise, during rollback we will not know whether locks need
        // to be rolled back.
        // Loose all skipped and previously locked (we cannot reenter locks here).
        final Collection<KeyCacheObject> passedKeys = skipped != null ? F.view(keys, F0.notIn(skipped)) : keys;
        if (log.isDebugEnabled())
            log.debug("Lock keys: " + passedKeys);
        return obtainLockAsync(cacheCtx, ret, passedKeys, read, needRetVal, createTtl, accessTtl, skipStore, keepBinary);
    } catch (IgniteCheckedException e) {
        setRollbackOnly();
        return new GridFinishedFuture<>(e);
    }
}
Also used : IgniteTxEntry(org.apache.ignite.internal.processors.cache.transactions.IgniteTxEntry) GridCacheReturn(org.apache.ignite.internal.processors.cache.GridCacheReturn) AffinityTopologyVersion(org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion) GridLeanSet(org.apache.ignite.internal.util.GridLeanSet) GridCacheEntryEx(org.apache.ignite.internal.processors.cache.GridCacheEntryEx) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridFutureAdapter(org.apache.ignite.internal.util.future.GridFutureAdapter) GridCacheEntryRemovedException(org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject)

Example 32 with GridFutureAdapter

use of org.apache.ignite.internal.util.future.GridFutureAdapter in project ignite by apache.

the class GridNioServerWrapper method openChannel.

/**
 * @param remote Destination cluster node to communicate with.
 * @param initMsg Configuration channel attributes wrapped into the message.
 * @return The future, which will be finished on channel ready.
 * @throws IgniteSpiException If fails.
 */
public IgniteInternalFuture<Channel> openChannel(ClusterNode remote, Message initMsg) throws IgniteSpiException {
    assert !remote.isLocal() : remote;
    assert initMsg != null;
    assert chConnPlc != null;
    assert nodeSupports(remote, CHANNEL_COMMUNICATION) : "Node doesn't support direct connection over socket channel " + "[nodeId=" + remote.id() + ']';
    ConnectionKey key = new ConnectionKey(remote.id(), chConnPlc.connectionIndex());
    GridFutureAdapter<Channel> chFut = new GridFutureAdapter<>();
    connectGate.enter();
    try {
        GridNioSession ses = createNioSession(remote, key.connectionIndex());
        assert ses != null : "Session must be established [remoteId=" + remote.id() + ", key=" + key + ']';
        cleanupLocalNodeRecoveryDescriptor(key);
        ses.addMeta(CHANNEL_FUT_META, chFut);
        // Send configuration message over the created session.
        ses.send(initMsg).listen(f -> {
            if (f.error() != null) {
                GridFutureAdapter<Channel> rq = ses.meta(CHANNEL_FUT_META);
                assert rq != null;
                rq.onDone(f.error());
                ses.close();
                return;
            }
            Runnable closeRun = () -> {
                // Close session if request not complete yet.
                GridFutureAdapter<Channel> rq = ses.meta(CHANNEL_FUT_META);
                assert rq != null;
                if (rq.onDone(handshakeTimeoutException()))
                    ses.close();
            };
            handshakeTimeoutExecutorService.schedule(closeRun, cfg.connectionTimeout(), TimeUnit.MILLISECONDS);
        });
        return chFut;
    } catch (IgniteCheckedException e) {
        throw new IgniteSpiException("Unable to create new channel connection to the remote node: " + remote, e);
    } finally {
        connectGate.leave();
    }
}
Also used : IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridNioSession(org.apache.ignite.internal.util.nio.GridNioSession) Channel(java.nio.channels.Channel) SocketChannel(java.nio.channels.SocketChannel) GridFutureAdapter(org.apache.ignite.internal.util.future.GridFutureAdapter) IgniteSpiException(org.apache.ignite.spi.IgniteSpiException)

Example 33 with GridFutureAdapter

use of org.apache.ignite.internal.util.future.GridFutureAdapter in project ignite by apache.

the class GridDiscoveryManager method start.

/**
 * {@inheritDoc}
 */
@Override
public void start() throws IgniteCheckedException {
    ctx.addNodeAttribute(ATTR_OFFHEAP_SIZE, requiredOffheap());
    ctx.addNodeAttribute(ATTR_DATA_REGIONS_OFFHEAP_SIZE, configuredOffheap());
    DiscoverySpi spi = getSpi();
    discoOrdered = discoOrdered();
    histSupported = historySupported();
    isLocDaemon = ctx.isDaemon();
    hasRslvrs = !ctx.config().isClientMode() && !F.isEmpty(ctx.config().getSegmentationResolvers());
    segChkFreq = ctx.config().getSegmentCheckFrequency();
    if (hasRslvrs) {
        if (segChkFreq < 0)
            throw new IgniteCheckedException("Segment check frequency cannot be negative: " + segChkFreq);
        if (segChkFreq > 0 && segChkFreq < 2000)
            U.warn(log, "Configuration parameter 'segmentCheckFrequency' is too low " + "(at least 2000 ms recommended): " + segChkFreq);
        int segResAttemp = ctx.config().getSegmentationResolveAttempts();
        if (segResAttemp < 1)
            throw new IgniteCheckedException("Segment resolve attempts cannot be negative or zero: " + segResAttemp);
        checkSegmentOnStart();
    }
    spi.setMetricsProvider(createMetricsProvider());
    if (ctx.security().enabled()) {
        if (isSecurityCompatibilityMode())
            ctx.addNodeAttribute(ATTR_SECURITY_COMPATIBILITY_MODE, true);
        spi.setAuthenticator(new DiscoverySpiNodeAuthenticator() {

            @Override
            public SecurityContext authenticateNode(ClusterNode node, SecurityCredentials cred) {
                try {
                    return ctx.security().authenticateNode(node, cred);
                } catch (IgniteCheckedException e) {
                    throw U.convertException(e);
                }
            }

            @Override
            public boolean isGlobalNodeAuthentication() {
                return ctx.security().isGlobalNodeAuthentication();
            }
        });
    }
    if (ctx.config().getCommunicationFailureResolver() != null)
        ctx.resource().injectGeneric(ctx.config().getCommunicationFailureResolver());
    // Shared reference between DiscoverySpiListener and DiscoverySpiDataExchange.
    AtomicReference<IgniteFuture<?>> lastStateChangeEvtLsnrFutRef = new AtomicReference<>();
    spi.setListener(new DiscoverySpiListener() {

        private long gridStartTime;

        private final Marshaller marshaller = MarshallerUtils.jdkMarshaller(ctx.igniteInstanceName());

        /**
         * {@inheritDoc}
         */
        @Override
        public void onLocalNodeInitialized(ClusterNode locNode) {
            for (IgniteInClosure<ClusterNode> lsnr : locNodeInitLsnrs) lsnr.apply(locNode);
            if (locNode instanceof IgniteClusterNode) {
                final IgniteClusterNode node = (IgniteClusterNode) locNode;
                if (consistentId != null)
                    node.setConsistentId(consistentId);
            }
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public IgniteFuture<?> onDiscovery(DiscoveryNotification notification) {
            GridFutureAdapter<?> notificationFut = new GridFutureAdapter<>();
            discoNtfWrk.submit(notificationFut, ctx.security().enabled() ? new SecurityAwareNotificationTask(notification) : new NotificationTask(notification));
            IgniteFuture<?> fut = new IgniteFutureImpl<>(notificationFut);
            // TODO could be optimized with more specific conditions.
            switch(notification.type()) {
                case EVT_NODE_JOINED:
                case EVT_NODE_LEFT:
                case EVT_NODE_FAILED:
                    if (!CU.isPersistenceEnabled(ctx.config()))
                        lastStateChangeEvtLsnrFutRef.set(fut);
                    break;
                case EVT_DISCOVERY_CUSTOM_EVT:
                    lastStateChangeEvtLsnrFutRef.set(fut);
            }
            return fut;
        }

        /**
         * @param notification Notification.
         */
        private void onDiscovery0(DiscoveryNotification notification) {
            int type = notification.type();
            ClusterNode node = notification.getNode();
            long topVer = notification.getTopVer();
            DiscoveryCustomMessage customMsg = notification.getCustomMsgData() == null ? null : ((CustomMessageWrapper) notification.getCustomMsgData()).delegate();
            if (skipMessage(notification.type(), customMsg))
                return;
            final ClusterNode locNode = localNode();
            if (notification.getTopHist() != null)
                topHist = notification.getTopHist();
            boolean verChanged;
            if (type == EVT_NODE_METRICS_UPDATED)
                verChanged = false;
            else {
                if (type != EVT_NODE_SEGMENTED && type != EVT_CLIENT_NODE_DISCONNECTED && type != EVT_CLIENT_NODE_RECONNECTED && type != EVT_DISCOVERY_CUSTOM_EVT) {
                    minorTopVer = 0;
                    verChanged = true;
                } else
                    verChanged = false;
            }
            if (type == EVT_NODE_FAILED || type == EVT_NODE_LEFT) {
                for (DiscoCache c : discoCacheHist.values()) c.updateAlives(node);
                updateClientNodes(node.id());
            }
            boolean locJoinEvt = type == EVT_NODE_JOINED && node.id().equals(locNode.id());
            ChangeGlobalStateFinishMessage stateFinishMsg = null;
            if (type == EVT_NODE_FAILED || type == EVT_NODE_LEFT)
                stateFinishMsg = ctx.state().onNodeLeft(node);
            final AffinityTopologyVersion nextTopVer;
            if (type == EVT_DISCOVERY_CUSTOM_EVT) {
                assert customMsg != null;
                boolean incMinorTopVer;
                if (customMsg instanceof ChangeGlobalStateMessage) {
                    incMinorTopVer = ctx.state().onStateChangeMessage(new AffinityTopologyVersion(topVer, minorTopVer), (ChangeGlobalStateMessage) customMsg, discoCache());
                } else if (customMsg instanceof ChangeGlobalStateFinishMessage) {
                    ctx.state().onStateFinishMessage((ChangeGlobalStateFinishMessage) customMsg);
                    Snapshot snapshot = topSnap.get();
                    // Topology version does not change, but need create DiscoCache with new state.
                    DiscoCache discoCache = snapshot.discoCache.copy(snapshot.topVer, ctx.state().clusterState());
                    topSnap.set(new Snapshot(snapshot.topVer, discoCache));
                    incMinorTopVer = false;
                } else {
                    incMinorTopVer = ctx.cache().onCustomEvent(customMsg, new AffinityTopologyVersion(topVer, minorTopVer), node);
                }
                if (incMinorTopVer) {
                    minorTopVer++;
                    verChanged = true;
                }
                nextTopVer = new AffinityTopologyVersion(topVer, minorTopVer);
                if (incMinorTopVer)
                    ctx.cache().onDiscoveryEvent(type, customMsg, node, nextTopVer, ctx.state().clusterState());
            } else {
                nextTopVer = new AffinityTopologyVersion(topVer, minorTopVer);
                ctx.cache().onDiscoveryEvent(type, customMsg, node, nextTopVer, ctx.state().clusterState());
            }
            DiscoCache discoCache;
            // event notifications, since SPI notifies manager about all events from this listener.
            if (verChanged) {
                Snapshot snapshot = topSnap.get();
                if (customMsg == null) {
                    discoCache = createDiscoCache(nextTopVer, ctx.state().clusterState(), locNode, notification.getTopSnapshot());
                } else if (customMsg instanceof ChangeGlobalStateMessage) {
                    discoCache = createDiscoCache(nextTopVer, ctx.state().pendingState((ChangeGlobalStateMessage) customMsg), locNode, notification.getTopSnapshot());
                } else
                    discoCache = customMsg.createDiscoCache(GridDiscoveryManager.this, nextTopVer, snapshot.discoCache);
                discoCacheHist.put(nextTopVer, discoCache);
                assert snapshot.topVer.compareTo(nextTopVer) < 0 : "Topology version out of order [this.topVer=" + topSnap + ", topVer=" + topVer + ", node=" + node + ", nextTopVer=" + nextTopVer + ", evt=" + U.gridEventName(type) + ']';
                topSnap.set(new Snapshot(nextTopVer, discoCache));
            } else
                // Current version.
                discoCache = discoCache();
            if (locJoinEvt || !node.isClient() && !node.isDaemon()) {
                if (type == EVT_NODE_LEFT || type == EVT_NODE_FAILED || type == EVT_NODE_JOINED) {
                    boolean discoCacheRecalculationRequired = ctx.state().autoAdjustInMemoryClusterState(node.id(), notification.getTopSnapshot(), discoCache, topVer, minorTopVer);
                    if (discoCacheRecalculationRequired) {
                        discoCache = createDiscoCache(nextTopVer, ctx.state().clusterState(), locNode, notification.getTopSnapshot());
                        discoCacheHist.put(nextTopVer, discoCache);
                        topSnap.set(new Snapshot(nextTopVer, discoCache));
                    }
                }
            }
            if (type == EVT_DISCOVERY_CUSTOM_EVT) {
                for (Class cls = customMsg.getClass(); cls != null; cls = cls.getSuperclass()) {
                    List<CustomEventListener<DiscoveryCustomMessage>> list = customEvtLsnrs.get(cls);
                    if (list != null) {
                        for (CustomEventListener<DiscoveryCustomMessage> lsnr : list) {
                            try {
                                lsnr.onCustomEvent(nextTopVer, node, customMsg);
                            } catch (Exception e) {
                                U.error(log, "Failed to notify direct custom event listener: " + customMsg, e);
                            }
                        }
                    }
                }
            }
            SecurityContext secCtx = remoteSecurityContext(ctx);
            // If this is a local join event, just save it and do not notify listeners.
            if (locJoinEvt) {
                if (gridStartTime == 0)
                    gridStartTime = getSpi().getGridStartTime();
                topSnap.set(new Snapshot(nextTopVer, discoCache));
                startLatch.countDown();
                DiscoveryEvent discoEvt = new DiscoveryEvent();
                discoEvt.node(ctx.discovery().localNode());
                discoEvt.eventNode(node);
                discoEvt.type(EVT_NODE_JOINED);
                discoEvt.topologySnapshot(topVer, new ArrayList<>(F.view(notification.getTopSnapshot(), FILTER_NOT_DAEMON)));
                if (notification.getSpanContainer() != null)
                    discoEvt.span(notification.getSpanContainer().span());
                discoWrk.discoCache = discoCache;
                if (!ctx.clientDisconnected()) {
                    // The security processor must be notified first, since {@link IgniteSecurity#onLocalJoin}
                    // finishes local node security context initialization that can be demanded by other Ignite
                    // components.
                    ctx.security().onLocalJoin();
                    if (!isLocDaemon) {
                        ctx.cache().context().versions().onLocalJoin(topVer);
                        ctx.cache().context().coordinators().onLocalJoin(discoEvt, discoCache);
                        ctx.cache().context().exchange().onLocalJoin(discoEvt, discoCache);
                        ctx.service().onLocalJoin(discoEvt, discoCache);
                        ctx.encryption().onLocalJoin();
                        ctx.cluster().onLocalJoin();
                    }
                }
                IgniteInternalFuture<Boolean> transitionWaitFut = ctx.state().onLocalJoin(discoCache);
                locJoin.onDone(new DiscoveryLocalJoinData(discoEvt, discoCache, transitionWaitFut, ctx.state().clusterState().active()));
                return;
            } else if (type == EVT_CLIENT_NODE_DISCONNECTED) {
                assert locNode.isClient() : locNode;
                assert node.isClient() : node;
                ((IgniteKernal) ctx.grid()).onDisconnected();
                if (!locJoin.isDone())
                    locJoin.onDone(new IgniteCheckedException("Node disconnected"));
                locJoin = new GridFutureAdapter<>();
                registeredCaches.clear();
                registeredCacheGrps.clear();
                for (AffinityTopologyVersion histVer : discoCacheHist.keySet()) {
                    Object rmvd = discoCacheHist.remove(histVer);
                    assert rmvd != null : histVer;
                }
                topHist.clear();
                topSnap.set(new Snapshot(AffinityTopologyVersion.ZERO, createDiscoCache(AffinityTopologyVersion.ZERO, ctx.state().clusterState(), locNode, Collections.singleton(locNode))));
            } else if (type == EVT_CLIENT_NODE_RECONNECTED) {
                assert locNode.isClient() : locNode;
                assert node.isClient() : node;
                ctx.security().onLocalJoin();
                boolean clusterRestarted = gridStartTime != getSpi().getGridStartTime();
                gridStartTime = getSpi().getGridStartTime();
                ((IgniteKernal) ctx.grid()).onReconnected(clusterRestarted);
                ctx.cache().context().coordinators().onLocalJoin(localJoinEvent(), discoCache);
                ctx.cache().context().exchange().onLocalJoin(localJoinEvent(), discoCache);
                ctx.service().onLocalJoin(localJoinEvent(), discoCache);
                DiscoCache discoCache0 = discoCache;
                ctx.cluster().clientReconnectFuture().listen(new CI1<IgniteFuture<?>>() {

                    @Override
                    public void apply(IgniteFuture<?> fut) {
                        try {
                            fut.get();
                            discoWrk.addEvent(new NotificationEvent(EVT_CLIENT_NODE_RECONNECTED, nextTopVer, node, discoCache0, notification.getTopSnapshot(), null, notification.getSpanContainer(), secCtx));
                        } catch (IgniteException ignore) {
                        // No-op.
                        }
                    }
                });
                return;
            }
            if (type == EVT_CLIENT_NODE_DISCONNECTED || type == EVT_NODE_SEGMENTED || !ctx.clientDisconnected())
                discoWrk.addEvent(new NotificationEvent(type, nextTopVer, node, discoCache, notification.getTopSnapshot(), customMsg, notification.getSpanContainer(), secCtx));
            if (stateFinishMsg != null)
                discoWrk.addEvent(new NotificationEvent(EVT_DISCOVERY_CUSTOM_EVT, nextTopVer, node, discoCache, notification.getTopSnapshot(), stateFinishMsg, notification.getSpanContainer(), secCtx));
            if (type == EVT_CLIENT_NODE_DISCONNECTED)
                discoWrk.awaitDisconnectEvent();
        }

        /**
         * Extends {@link NotificationTask} to run in a security context owned by the initiator of the
         * discovery event.
         */
        class SecurityAwareNotificationTask extends NotificationTask {

            /**
             */
            public SecurityAwareNotificationTask(DiscoveryNotification notification) {
                super(notification);
            }

            /**
             */
            @Override
            public void run() {
                DiscoverySpiCustomMessage customMsg = notification.getCustomMsgData();
                if (customMsg instanceof SecurityAwareCustomMessageWrapper) {
                    UUID secSubjId = ((SecurityAwareCustomMessageWrapper) customMsg).securitySubjectId();
                    try (OperationSecurityContext ignored = ctx.security().withContext(secSubjId)) {
                        super.run();
                    }
                } else {
                    SecurityContext initiatorNodeSecCtx = nodeSecurityContext(marshaller, U.resolveClassLoader(ctx.config()), notification.getNode());
                    try (OperationSecurityContext ignored = ctx.security().withContext(initiatorNodeSecCtx)) {
                        super.run();
                    }
                }
            }
        }

        /**
         * Represents task to handle discovery notification asynchronously.
         */
        class NotificationTask implements Runnable {

            /**
             */
            protected final DiscoveryNotification notification;

            /**
             */
            public NotificationTask(DiscoveryNotification notification) {
                this.notification = notification;
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void run() {
                synchronized (discoEvtMux) {
                    onDiscovery0(notification);
                }
            }
        }
    });
    spi.setDataExchange(new DiscoverySpiDataExchange() {

        @Override
        public DiscoveryDataBag collect(DiscoveryDataBag dataBag) {
            assert dataBag != null;
            assert dataBag.joiningNodeId() != null;
            if (ctx.localNodeId().equals(dataBag.joiningNodeId())) {
                for (GridComponent c : ctx.components()) c.collectJoiningNodeData(dataBag);
            } else {
                waitForLastStateChangeEventFuture();
                for (GridComponent c : ctx.components()) c.collectGridNodeData(dataBag);
            }
            return dataBag;
        }

        @Override
        public void onExchange(DiscoveryDataBag dataBag) {
            assert dataBag != null;
            assert dataBag.joiningNodeId() != null;
            if (ctx.localNodeId().equals(dataBag.joiningNodeId())) {
                // NodeAdded msg reached joining node after round-trip over the ring.
                IGridClusterStateProcessor stateProc = ctx.state();
                stateProc.onGridDataReceived(dataBag.gridDiscoveryData(stateProc.discoveryDataType().ordinal()));
                for (GridComponent c : ctx.components()) {
                    if (c.discoveryDataType() != null && c != stateProc)
                        c.onGridDataReceived(dataBag.gridDiscoveryData(c.discoveryDataType().ordinal()));
                }
            } else {
                // Discovery data from newly joined node has to be applied to the current old node.
                IGridClusterStateProcessor stateProc = ctx.state();
                JoiningNodeDiscoveryData data0 = dataBag.newJoinerDiscoveryData(stateProc.discoveryDataType().ordinal());
                assert data0 != null;
                stateProc.onJoiningNodeDataReceived(data0);
                for (GridComponent c : ctx.components()) {
                    if (c.discoveryDataType() != null && c != stateProc) {
                        JoiningNodeDiscoveryData data = dataBag.newJoinerDiscoveryData(c.discoveryDataType().ordinal());
                        if (data != null)
                            c.onJoiningNodeDataReceived(data);
                    }
                }
            }
        }

        /**
         */
        private void waitForLastStateChangeEventFuture() {
            IgniteFuture<?> lastStateChangeEvtLsnrFut = lastStateChangeEvtLsnrFutRef.get();
            if (lastStateChangeEvtLsnrFut != null) {
                Thread currThread = Thread.currentThread();
                GridWorker worker = currThread instanceof IgniteDiscoveryThread ? ((IgniteDiscoveryThread) currThread).worker() : null;
                if (worker != null)
                    worker.blockingSectionBegin();
                try {
                    lastStateChangeEvtLsnrFut.get();
                } finally {
                    // Guaranteed to be invoked in the same thread as DiscoverySpiListener#onDiscovery.
                    // No additional synchronization for reference is required.
                    lastStateChangeEvtLsnrFutRef.set(null);
                    if (worker != null)
                        worker.blockingSectionEnd();
                }
            }
        }
    });
    new DiscoveryMessageNotifierThread(discoNtfWrk).start();
    startSpi();
    registeredDiscoSpi = true;
    try {
        U.await(startLatch);
    } catch (IgniteInterruptedException e) {
        throw new IgniteCheckedException("Failed to start discovery manager (thread has been interrupted).", e);
    }
    // Start segment check worker only if frequency is greater than 0.
    if (hasRslvrs && segChkFreq > 0) {
        segChkWrk = new SegmentCheckWorker();
        segChkThread = new IgniteThread(segChkWrk);
        segChkThread.setUncaughtExceptionHandler(new OomExceptionHandler(ctx));
        segChkThread.start();
    }
    locNode = spi.getLocalNode();
    checkAttributes(discoCache().remoteNodes());
    // Start discovery worker.
    new IgniteThread(discoWrk).start();
    if (log.isDebugEnabled())
        log.debug(startInfo());
}
Also used : CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) CI1(org.apache.ignite.internal.util.typedef.CI1) IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) GridFutureAdapter(org.apache.ignite.internal.util.future.GridFutureAdapter) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) List(java.util.List) UUID(java.util.UUID) OperationSecurityContext(org.apache.ignite.internal.processors.security.OperationSecurityContext) ClusterNode(org.apache.ignite.cluster.ClusterNode) AffinityTopologyVersion(org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion) DiscoverySpiNodeAuthenticator(org.apache.ignite.spi.discovery.DiscoverySpiNodeAuthenticator) IgniteInterruptedException(org.apache.ignite.IgniteInterruptedException) IgniteDiscoveryThread(org.apache.ignite.spi.discovery.IgniteDiscoveryThread) SecurityCredentials(org.apache.ignite.plugin.security.SecurityCredentials) DiscoverySpiDataExchange(org.apache.ignite.spi.discovery.DiscoverySpiDataExchange) IgniteThread(org.apache.ignite.thread.IgniteThread) OomExceptionHandler(org.apache.ignite.thread.OomExceptionHandler) GridComponent(org.apache.ignite.internal.GridComponent) IgniteFuture(org.apache.ignite.lang.IgniteFuture) DiscoveryEvent(org.apache.ignite.events.DiscoveryEvent) JoiningNodeDiscoveryData(org.apache.ignite.spi.discovery.DiscoveryDataBag.JoiningNodeDiscoveryData) DiscoveryDataBag(org.apache.ignite.spi.discovery.DiscoveryDataBag) IGridClusterStateProcessor(org.apache.ignite.internal.processors.cluster.IGridClusterStateProcessor) IgniteKernal(org.apache.ignite.internal.IgniteKernal) Marshaller(org.apache.ignite.marshaller.Marshaller) ChangeGlobalStateMessage(org.apache.ignite.internal.processors.cluster.ChangeGlobalStateMessage) AtomicReference(java.util.concurrent.atomic.AtomicReference) DiscoverySpiListener(org.apache.ignite.spi.discovery.DiscoverySpiListener) GridWorker(org.apache.ignite.internal.util.worker.GridWorker) IgniteClientDisconnectedException(org.apache.ignite.IgniteClientDisconnectedException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteSpiException(org.apache.ignite.spi.IgniteSpiException) IgniteInterruptedException(org.apache.ignite.IgniteInterruptedException) IgniteInterruptedCheckedException(org.apache.ignite.internal.IgniteInterruptedCheckedException) IgniteClientDisconnectedCheckedException(org.apache.ignite.internal.IgniteClientDisconnectedCheckedException) IgniteException(org.apache.ignite.IgniteException) NodeStoppingException(org.apache.ignite.internal.NodeStoppingException) IgniteThread(org.apache.ignite.thread.IgniteThread) IgniteDiscoveryThread(org.apache.ignite.spi.discovery.IgniteDiscoveryThread) DiscoverySpiCustomMessage(org.apache.ignite.spi.discovery.DiscoverySpiCustomMessage) DiscoverySpi(org.apache.ignite.spi.discovery.DiscoverySpi) TcpDiscoverySpi(org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi) SecurityContext(org.apache.ignite.internal.processors.security.SecurityContext) SecurityUtils.remoteSecurityContext(org.apache.ignite.internal.processors.security.SecurityUtils.remoteSecurityContext) SecurityUtils.withRemoteSecurityContext(org.apache.ignite.internal.processors.security.SecurityUtils.withRemoteSecurityContext) OperationSecurityContext(org.apache.ignite.internal.processors.security.OperationSecurityContext) SecurityUtils.nodeSecurityContext(org.apache.ignite.internal.processors.security.SecurityUtils.nodeSecurityContext) IgniteInClosure(org.apache.ignite.lang.IgniteInClosure) DiscoveryNotification(org.apache.ignite.spi.discovery.DiscoveryNotification) ChangeGlobalStateFinishMessage(org.apache.ignite.internal.processors.cluster.ChangeGlobalStateFinishMessage)

Example 34 with GridFutureAdapter

use of org.apache.ignite.internal.util.future.GridFutureAdapter in project ignite by apache.

the class CachePartitionDefragmentationManager method defragmentOnePartition.

/**
 * Defragment one given partition.
 */
private boolean defragmentOnePartition(CacheGroupContext oldGrpCtx, int grpId, File workDir, GridCacheOffheapManager offheap, FileVersionCheckingFactory pageStoreFactory, GridCompoundFuture<Object, Object> cmpFut, PageMemoryEx oldPageMem, CacheGroupContext newGrpCtx, CacheDataStore oldCacheDataStore) throws IgniteCheckedException {
    TreeIterator treeIter = new TreeIterator(pageSize);
    checkCancellation();
    int partId = oldCacheDataStore.partId();
    PartitionContext partCtx = new PartitionContext(workDir, grpId, partId, partDataRegion, mappingDataRegion, oldGrpCtx, newGrpCtx, oldCacheDataStore, pageStoreFactory);
    if (skipAlreadyDefragmentedPartition(workDir, grpId, partId, log)) {
        partCtx.createPageStore(() -> defragmentedPartMappingFile(workDir, partId).toPath(), partCtx.mappingPagesAllocated, partCtx.mappingPageMemory);
        linkMapByPart.put(partId, partCtx.createLinkMapTree(false));
        return false;
    }
    partCtx.createPageStore(() -> defragmentedPartMappingFile(workDir, partId).toPath(), partCtx.mappingPagesAllocated, partCtx.mappingPageMemory);
    linkMapByPart.put(partId, partCtx.createLinkMapTree(true));
    checkCancellation();
    partCtx.createPageStore(() -> defragmentedPartTmpFile(workDir, partId).toPath(), partCtx.partPagesAllocated, partCtx.partPageMemory);
    partCtx.createNewCacheDataStore(offheap);
    copyPartitionData(partCtx, treeIter);
    DefragmentationPageReadWriteManager pageMgr = (DefragmentationPageReadWriteManager) partCtx.partPageMemory.pageManager();
    PageStore oldPageStore = filePageStoreMgr.getStore(grpId, partId);
    status.onPartitionDefragmented(oldGrpCtx, oldPageStore.size(), // + file header.
    pageSize + partCtx.partPagesAllocated.get() * pageSize);
    // TODO Move inside of defragmentSinglePartition.
    IgniteInClosure<IgniteInternalFuture<?>> cpLsnr = fut -> {
        if (fut.error() == null) {
            if (log.isDebugEnabled()) {
                log.debug(S.toString("Partition defragmented", "grpId", grpId, false, "partId", partId, false, "oldPages", oldPageStore.pages(), false, "newPages", partCtx.partPagesAllocated.get() + 1, false, "mappingPages", partCtx.mappingPagesAllocated.get() + 1, false, "pageSize", pageSize, false, "partFile", defragmentedPartFile(workDir, partId).getName(), false, "workDir", workDir, false));
            }
            oldPageMem.invalidate(grpId, partId);
            partCtx.partPageMemory.invalidate(grpId, partId);
            // Yes, it'll be invalid in a second.
            pageMgr.pageStoreMap().removePageStore(grpId, partId);
            renameTempPartitionFile(workDir, partId);
        }
    };
    GridFutureAdapter<?> cpFut = defragmentationCheckpoint.forceCheckpoint("partition defragmented", null).futureFor(FINISHED);
    cpFut.listen(cpLsnr);
    cmpFut.add((IgniteInternalFuture<Object>) cpFut);
    return true;
}
Also used : IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) Arrays(java.util.Arrays) PageStore(org.apache.ignite.internal.pagemem.store.PageStore) CacheType(org.apache.ignite.internal.processors.cache.CacheType) DataRegion(org.apache.ignite.internal.processors.cache.persistence.DataRegion) GridFutureAdapter(org.apache.ignite.internal.util.future.GridFutureAdapter) GridFinishedFuture(org.apache.ignite.internal.util.future.GridFinishedFuture) FLAG_DATA(org.apache.ignite.internal.pagemem.PageIdAllocator.FLAG_DATA) IntMap(org.apache.ignite.internal.util.collection.IntMap) DEFRAGMENTATION_MAPPING_REGION_NAME(org.apache.ignite.internal.processors.cache.persistence.GridCacheDatabaseSharedManager.DEFRAGMENTATION_MAPPING_REGION_NAME) DEFRAGMENTATION_PART_REGION_NAME(org.apache.ignite.internal.processors.cache.persistence.GridCacheDatabaseSharedManager.DEFRAGMENTATION_PART_REGION_NAME) DefragmentationFileUtils.defragmentedPartMappingFile(org.apache.ignite.internal.processors.cache.persistence.defragmentation.DefragmentationFileUtils.defragmentedPartMappingFile) CacheDataStore(org.apache.ignite.internal.processors.cache.IgniteCacheOffheapManager.CacheDataStore) CheckpointTimeoutLock(org.apache.ignite.internal.processors.cache.persistence.checkpoint.CheckpointTimeoutLock) DefragmentationFileUtils.defragmentedPartFile(org.apache.ignite.internal.processors.cache.persistence.defragmentation.DefragmentationFileUtils.defragmentedPartFile) LightweightCheckpointManager(org.apache.ignite.internal.processors.cache.persistence.checkpoint.LightweightCheckpointManager) PagePartitionMetaIO(org.apache.ignite.internal.processors.cache.persistence.tree.io.PagePartitionMetaIO) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MaintenanceRegistry(org.apache.ignite.maintenance.MaintenanceRegistry) Map(java.util.Map) Path(java.nio.file.Path) AbstractFreeList(org.apache.ignite.internal.processors.cache.persistence.freelist.AbstractFreeList) IndexProcessor(org.apache.ignite.internal.cache.query.index.IndexProcessor) DataRow(org.apache.ignite.internal.processors.cache.tree.DataRow) IgniteInClosure(org.apache.ignite.lang.IgniteInClosure) IgniteOutClosure(org.apache.ignite.lang.IgniteOutClosure) DefragmentationFileUtils.skipAlreadyDefragmentedPartition(org.apache.ignite.internal.processors.cache.persistence.defragmentation.DefragmentationFileUtils.skipAlreadyDefragmentedPartition) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) Set(java.util.Set) PendingRow(org.apache.ignite.internal.processors.cache.tree.PendingRow) FilePageStoreManager(org.apache.ignite.internal.processors.cache.persistence.file.FilePageStoreManager) CacheDataRow(org.apache.ignite.internal.processors.cache.persistence.CacheDataRow) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Collectors(java.util.stream.Collectors) IgniteCacheOffheapManager(org.apache.ignite.internal.processors.cache.IgniteCacheOffheapManager) INDEX_PARTITION(org.apache.ignite.internal.pagemem.PageIdAllocator.INDEX_PARTITION) IntRWHashMap(org.apache.ignite.internal.util.collection.IntRWHashMap) List(java.util.List) GridCacheDataStore(org.apache.ignite.internal.processors.cache.persistence.GridCacheOffheapManager.GridCacheDataStore) StreamSupport.stream(java.util.stream.StreamSupport.stream) PageIdUtils(org.apache.ignite.internal.pagemem.PageIdUtils) CU(org.apache.ignite.internal.util.typedef.internal.CU) PagePartitionMetaIOV3(org.apache.ignite.internal.processors.cache.persistence.tree.io.PagePartitionMetaIOV3) IntHashMap(org.apache.ignite.internal.util.collection.IntHashMap) FLAG_IDX(org.apache.ignite.internal.pagemem.PageIdAllocator.FLAG_IDX) GridAtomicLong(org.apache.ignite.internal.util.GridAtomicLong) SimpleDataRow(org.apache.ignite.internal.processors.cache.persistence.freelist.SimpleDataRow) DefragmentationFileUtils.defragmentedIndexTmpFile(org.apache.ignite.internal.processors.cache.persistence.defragmentation.DefragmentationFileUtils.defragmentedIndexTmpFile) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) GridCompoundFuture(org.apache.ignite.internal.util.future.GridCompoundFuture) U(org.apache.ignite.internal.util.typedef.internal.U) HashMap(java.util.HashMap) IgniteLogger(org.apache.ignite.IgniteLogger) CacheGroupContext(org.apache.ignite.internal.processors.cache.CacheGroupContext) TreeSet(java.util.TreeSet) HashSet(java.util.HashSet) DefragmentationFileUtils.renameTempIndexFile(org.apache.ignite.internal.processors.cache.persistence.defragmentation.DefragmentationFileUtils.renameTempIndexFile) GridCacheDatabaseSharedManager(org.apache.ignite.internal.processors.cache.persistence.GridCacheDatabaseSharedManager) GridCacheOffheapManager(org.apache.ignite.internal.processors.cache.persistence.GridCacheOffheapManager) CheckpointManager(org.apache.ignite.internal.processors.cache.persistence.checkpoint.CheckpointManager) DefragmentationFileUtils.writeDefragmentationCompletionMarker(org.apache.ignite.internal.processors.cache.persistence.defragmentation.DefragmentationFileUtils.writeDefragmentationCompletionMarker) DefragmentationFileUtils.skipAlreadyDefragmentedCacheGroup(org.apache.ignite.internal.processors.cache.persistence.defragmentation.DefragmentationFileUtils.skipAlreadyDefragmentedCacheGroup) IgniteUtils(org.apache.ignite.internal.util.IgniteUtils) S(org.apache.ignite.internal.util.typedef.internal.S) DefragmentationFileUtils.renameTempPartitionFile(org.apache.ignite.internal.processors.cache.persistence.defragmentation.DefragmentationFileUtils.renameTempPartitionFile) PageIO(org.apache.ignite.internal.processors.cache.persistence.tree.io.PageIO) IgniteThreadPoolExecutor(org.apache.ignite.thread.IgniteThreadPoolExecutor) Comparator.comparing(java.util.Comparator.comparing) CacheDataTree(org.apache.ignite.internal.processors.cache.tree.CacheDataTree) AbstractDataLeafIO(org.apache.ignite.internal.processors.cache.tree.AbstractDataLeafIO) FINISHED(org.apache.ignite.internal.processors.cache.persistence.CheckpointState.FINISHED) PendingEntriesTree(org.apache.ignite.internal.processors.cache.tree.PendingEntriesTree) DefragmentationFileUtils.defragmentedPartTmpFile(org.apache.ignite.internal.processors.cache.persistence.defragmentation.DefragmentationFileUtils.defragmentedPartTmpFile) DefragmentationFileUtils.defragmentedIndexFile(org.apache.ignite.internal.processors.cache.persistence.defragmentation.DefragmentationFileUtils.defragmentedIndexFile) IoStatisticsHolderNoOp(org.apache.ignite.internal.metric.IoStatisticsHolderNoOp) DataPageEvictionMode(org.apache.ignite.configuration.DataPageEvictionMode) DefragmentationFileUtils.batchRenameDefragmentedCacheGroupPartitions(org.apache.ignite.internal.processors.cache.persistence.defragmentation.DefragmentationFileUtils.batchRenameDefragmentedCacheGroupPartitions) FileVersionCheckingFactory(org.apache.ignite.internal.processors.cache.persistence.file.FileVersionCheckingFactory) File(java.io.File) LongConsumer(java.util.function.LongConsumer) AtomicLong(java.util.concurrent.atomic.AtomicLong) GridCacheSharedContext(org.apache.ignite.internal.processors.cache.GridCacheSharedContext) TreeMap(java.util.TreeMap) PageMemoryEx(org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMemoryEx) GridQueryProcessor(org.apache.ignite.internal.processors.query.GridQueryProcessor) PageStore(org.apache.ignite.internal.pagemem.store.PageStore) IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture)

Example 35 with GridFutureAdapter

use of org.apache.ignite.internal.util.future.GridFutureAdapter in project ignite by apache.

the class CheckpointWorkflow method fillCacheGroupState.

/**
 * Fill cache group state in checkpoint record.
 *
 * @param cpRec Checkpoint record for filling.
 * @throws IgniteCheckedException if fail.
 */
private void fillCacheGroupState(CheckpointRecord cpRec) throws IgniteCheckedException {
    GridCompoundFuture grpHandleFut = checkpointCollectPagesInfoPool == null ? null : new GridCompoundFuture();
    for (CacheGroupContext grp : cacheGroupsContexts.get()) {
        if (grp.isLocal() || !grp.walEnabled())
            continue;
        Runnable r = () -> {
            ArrayList<GridDhtLocalPartition> parts = new ArrayList<>(grp.topology().localPartitions().size());
            for (GridDhtLocalPartition part : grp.topology().currentLocalPartitions()) parts.add(part);
            CacheState state = new CacheState(parts.size());
            for (GridDhtLocalPartition part : parts) {
                GridDhtPartitionState partState = part.state();
                if (partState == LOST)
                    partState = OWNING;
                state.addPartitionState(part.id(), part.dataStore().fullSize(), part.updateCounter(), (byte) partState.ordinal());
            }
            synchronized (cpRec) {
                cpRec.addCacheGroupState(grp.groupId(), state);
            }
        };
        if (checkpointCollectPagesInfoPool == null)
            r.run();
        else
            try {
                GridFutureAdapter<?> res = new GridFutureAdapter<>();
                checkpointCollectPagesInfoPool.execute(U.wrapIgniteFuture(r, res));
                grpHandleFut.add(res);
            } catch (RejectedExecutionException e) {
                assert false : "Task should never be rejected by async runner";
                // to protect from disabled asserts and call to failure handler
                throw new IgniteException(e);
            }
    }
    if (grpHandleFut != null) {
        grpHandleFut.markInitialized();
        grpHandleFut.get();
    }
}
Also used : IgniteException(org.apache.ignite.IgniteException) ArrayList(java.util.ArrayList) GridFutureAdapter(org.apache.ignite.internal.util.future.GridFutureAdapter) GridDhtPartitionState(org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtPartitionState) GridDhtLocalPartition(org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtLocalPartition) CacheState(org.apache.ignite.internal.pagemem.wal.record.CacheState) CacheGroupContext(org.apache.ignite.internal.processors.cache.CacheGroupContext) GridCompoundFuture(org.apache.ignite.internal.util.future.GridCompoundFuture) RejectedExecutionException(java.util.concurrent.RejectedExecutionException)

Aggregations

GridFutureAdapter (org.apache.ignite.internal.util.future.GridFutureAdapter)110 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)59 IgniteInternalFuture (org.apache.ignite.internal.IgniteInternalFuture)34 IgniteException (org.apache.ignite.IgniteException)23 ArrayList (java.util.ArrayList)21 AffinityTopologyVersion (org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion)21 List (java.util.List)20 UUID (java.util.UUID)20 ClusterNode (org.apache.ignite.cluster.ClusterNode)20 IgniteEx (org.apache.ignite.internal.IgniteEx)20 HashMap (java.util.HashMap)19 Map (java.util.Map)19 IgniteInterruptedCheckedException (org.apache.ignite.internal.IgniteInterruptedCheckedException)18 Test (org.junit.Test)18 Nullable (org.jetbrains.annotations.Nullable)17 Ignite (org.apache.ignite.Ignite)15 ClusterTopologyCheckedException (org.apache.ignite.internal.cluster.ClusterTopologyCheckedException)15 HashSet (java.util.HashSet)14 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)14 T2 (org.apache.ignite.internal.util.typedef.T2)13