Search in sources :

Example 61 with GridFutureAdapter

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

the class CommandProcessor method start.

/**
 * Start executor.
 */
public void start() {
    ctx.io().addMessageListener(GridTopic.TOPIC_QUERY, (nodeId, msg, plc) -> onMessage(nodeId, msg));
    ctx.event().addLocalEventListener(new GridLocalEventListener() {

        @Override
        public void onEvent(final Event evt) {
            UUID nodeId = ((DiscoveryEvent) evt).eventNode().id();
            List<GridFutureAdapter<String>> futs = new ArrayList<>();
            lock.writeLock().lock();
            try {
                Iterator<KillQueryRun> it = cancellationRuns.values().iterator();
                while (it.hasNext()) {
                    KillQueryRun qryRun = it.next();
                    if (qryRun.nodeId().equals(nodeId)) {
                        futs.add(qryRun.cancelFuture());
                        it.remove();
                    }
                }
            } finally {
                lock.writeLock().unlock();
            }
            futs.forEach(f -> f.onDone("Query node has left the grid: [nodeId=" + nodeId + "]"));
        }
    }, EventType.EVT_NODE_FAILED, EventType.EVT_NODE_LEFT);
}
Also used : GridFutureAdapter(org.apache.ignite.internal.util.future.GridFutureAdapter) GridFinishedFuture(org.apache.ignite.internal.util.future.GridFinishedFuture) QueryUtils(org.apache.ignite.internal.processors.query.QueryUtils) GridQueryKillResponse(org.apache.ignite.internal.processors.query.messages.GridQueryKillResponse) SqlCreateUserCommand(org.apache.ignite.internal.sql.command.SqlCreateUserCommand) MvccUtils.txStart(org.apache.ignite.internal.processors.cache.mvcc.MvccUtils.txStart) GridH2Table(org.apache.ignite.internal.processors.query.h2.opt.GridH2Table) Map(java.util.Map) NoOperation(org.h2.command.dml.NoOperation) SqlSetStreamingCommand(org.apache.ignite.internal.sql.command.SqlSetStreamingCommand) GridIoPolicy(org.apache.ignite.internal.managers.communication.GridIoPolicy) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) SqlCreateIndexCommand(org.apache.ignite.internal.sql.command.SqlCreateIndexCommand) GridQueryTypeDescriptor(org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor) QueryField(org.apache.ignite.internal.processors.query.QueryField) CIX2(org.apache.ignite.internal.util.typedef.CIX2) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) Event(org.apache.ignite.events.Event) Set(java.util.Set) QueryEntityEx(org.apache.ignite.internal.processors.query.QueryEntityEx) AlterTableAlterColumn(org.h2.command.ddl.AlterTableAlterColumn) SqlAnalyzeCommand(org.apache.ignite.internal.sql.command.SqlAnalyzeCommand) DataType(org.h2.value.DataType) SqlRefreshStatitsicsCommand(org.apache.ignite.internal.sql.command.SqlRefreshStatitsicsCommand) PARAM_WRAP_VALUE(org.apache.ignite.internal.processors.query.h2.sql.GridSqlQueryParser.PARAM_WRAP_VALUE) Message(org.apache.ignite.plugin.extensions.communication.Message) GridCacheContext(org.apache.ignite.internal.processors.cache.GridCacheContext) BulkLoadStreamerWriter(org.apache.ignite.internal.processors.bulkload.BulkLoadStreamerWriter) U(org.apache.ignite.internal.util.typedef.internal.U) IgniteLogger(org.apache.ignite.IgniteLogger) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) SecurityPermission(org.apache.ignite.plugin.security.SecurityPermission) ArrayList(java.util.ArrayList) GridKernalContext(org.apache.ignite.internal.GridKernalContext) LinkedHashMap(java.util.LinkedHashMap) Column(org.h2.table.Column) ClusterNode(org.apache.ignite.cluster.ClusterNode) GridSqlAlterTableAddColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlAlterTableAddColumn) SqlBeginTransactionCommand(org.apache.ignite.internal.sql.command.SqlBeginTransactionCommand) SqlIndexColumn(org.apache.ignite.internal.sql.command.SqlIndexColumn) MvccUtils(org.apache.ignite.internal.processors.cache.mvcc.MvccUtils) SqlKillQueryCommand(org.apache.ignite.internal.sql.command.SqlKillQueryCommand) NestedTxMode(org.apache.ignite.internal.processors.query.NestedTxMode) SqlDropUserCommand(org.apache.ignite.internal.sql.command.SqlDropUserCommand) Value(org.h2.value.Value) ServiceMXBeanImpl(org.apache.ignite.internal.ServiceMXBeanImpl) GridQueryProperty(org.apache.ignite.internal.processors.query.GridQueryProperty) GridSqlCreateIndex(org.apache.ignite.internal.processors.query.h2.sql.GridSqlCreateIndex) GridSqlAlterTableDropColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlAlterTableDropColumn) BulkLoadParser(org.apache.ignite.internal.processors.bulkload.BulkLoadParser) SqlBulkLoadCommand(org.apache.ignite.internal.sql.command.SqlBulkLoadCommand) GridRunningQueryInfo(org.apache.ignite.internal.processors.query.GridRunningQueryInfo) DropIndex(org.h2.command.ddl.DropIndex) GridSqlDropTable(org.apache.ignite.internal.processors.query.h2.sql.GridSqlDropTable) AtomicLong(java.util.concurrent.atomic.AtomicLong) GridTopic(org.apache.ignite.internal.GridTopic) SqlClientContext(org.apache.ignite.internal.processors.query.SqlClientContext) CacheConfiguration(org.apache.ignite.configuration.CacheConfiguration) SchemaOperationException(org.apache.ignite.internal.processors.query.schema.SchemaOperationException) TransactionsMXBeanImpl(org.apache.ignite.internal.TransactionsMXBeanImpl) IgniteDataStreamer(org.apache.ignite.IgniteDataStreamer) CacheMode(org.apache.ignite.cache.CacheMode) IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) SqlRollbackTransactionCommand(org.apache.ignite.internal.sql.command.SqlRollbackTransactionCommand) SqlAlterUserCommand(org.apache.ignite.internal.sql.command.SqlAlterUserCommand) DmlBulkLoadDataConverter(org.apache.ignite.internal.processors.query.h2.dml.DmlBulkLoadDataConverter) IgniteSystemProperties(org.apache.ignite.IgniteSystemProperties) SqlAlterTableCommand(org.apache.ignite.internal.sql.command.SqlAlterTableCommand) IgniteCluster(org.apache.ignite.IgniteCluster) StatisticsTarget(org.apache.ignite.internal.processors.query.stat.StatisticsTarget) CreateTable(org.h2.command.ddl.CreateTable) QueryEntity(org.apache.ignite.cache.QueryEntity) UpdatePlan(org.apache.ignite.internal.processors.query.h2.dml.UpdatePlan) SqlCommand(org.apache.ignite.internal.sql.command.SqlCommand) EventType(org.apache.ignite.events.EventType) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) GridSqlStatement(org.apache.ignite.internal.processors.query.h2.sql.GridSqlStatement) UUID(java.util.UUID) IgniteBiTuple(org.apache.ignite.lang.IgniteBiTuple) Objects(java.util.Objects) SqlKillContinuousQueryCommand(org.apache.ignite.internal.sql.command.SqlKillContinuousQueryCommand) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) SqlKillScanQueryCommand(org.apache.ignite.internal.sql.command.SqlKillScanQueryCommand) BulkLoadAckClientParameters(org.apache.ignite.internal.processors.bulkload.BulkLoadAckClientParameters) IgniteProductVersion(org.apache.ignite.lang.IgniteProductVersion) NotNull(org.jetbrains.annotations.NotNull) FieldsQueryCursor(org.apache.ignite.cache.query.FieldsQueryCursor) GridSqlColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn) GridQueryKillRequest(org.apache.ignite.internal.processors.query.messages.GridQueryKillRequest) UpdatePlanBuilder(org.apache.ignite.internal.processors.query.h2.dml.UpdatePlanBuilder) DiscoveryEvent(org.apache.ignite.events.DiscoveryEvent) QueryMXBeanImpl(org.apache.ignite.internal.QueryMXBeanImpl) SqlCommitTransactionCommand(org.apache.ignite.internal.sql.command.SqlCommitTransactionCommand) MvccUtils.tx(org.apache.ignite.internal.processors.cache.mvcc.MvccUtils.tx) HashMap(java.util.HashMap) GridSqlCreateTable(org.apache.ignite.internal.processors.query.h2.sql.GridSqlCreateTable) SqlKillServiceCommand(org.apache.ignite.internal.sql.command.SqlKillServiceCommand) IgniteClosureX(org.apache.ignite.internal.util.lang.IgniteClosureX) ConcurrentMap(java.util.concurrent.ConcurrentMap) HashSet(java.util.HashSet) BulkLoadCacheWriter(org.apache.ignite.internal.processors.bulkload.BulkLoadCacheWriter) StatisticsObjectConfiguration(org.apache.ignite.internal.processors.query.stat.config.StatisticsObjectConfiguration) BulkLoadContextCursor(org.apache.ignite.cache.query.BulkLoadContextCursor) StatisticsKey(org.apache.ignite.internal.processors.query.stat.StatisticsKey) QueryIndexType(org.apache.ignite.cache.QueryIndexType) F(org.apache.ignite.internal.util.typedef.F) GridNearTxLocal(org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal) Iterator(java.util.Iterator) SqlKillComputeTaskCommand(org.apache.ignite.internal.sql.command.SqlKillComputeTaskCommand) GridSqlDropIndex(org.apache.ignite.internal.processors.query.h2.sql.GridSqlDropIndex) SqlDropStatisticsCommand(org.apache.ignite.internal.sql.command.SqlDropStatisticsCommand) SqlKillTransactionCommand(org.apache.ignite.internal.sql.command.SqlKillTransactionCommand) MvccUtils.mvccEnabled(org.apache.ignite.internal.processors.cache.mvcc.MvccUtils.mvccEnabled) IgniteQueryErrorCode(org.apache.ignite.internal.processors.cache.query.IgniteQueryErrorCode) SqlDropIndexCommand(org.apache.ignite.internal.sql.command.SqlDropIndexCommand) Prepared(org.h2.command.Prepared) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) BulkLoadProcessor(org.apache.ignite.internal.processors.bulkload.BulkLoadProcessor) CreateIndex(org.h2.command.ddl.CreateIndex) ComputeMXBeanImpl(org.apache.ignite.internal.ComputeMXBeanImpl) Collections(java.util.Collections) QueryIndex(org.apache.ignite.cache.QueryIndex) DropTable(org.h2.command.ddl.DropTable) GridLocalEventListener(org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener) GridLocalEventListener(org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener) Iterator(java.util.Iterator) Event(org.apache.ignite.events.Event) DiscoveryEvent(org.apache.ignite.events.DiscoveryEvent) DiscoveryEvent(org.apache.ignite.events.DiscoveryEvent) ArrayList(java.util.ArrayList) List(java.util.List) UUID(java.util.UUID)

Example 62 with GridFutureAdapter

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

the class IgniteUtilsSelfTest method runTask.

/**
 * @param executorService Executor service.
 */
private void runTask(ExecutorService executorService) {
    List<Integer> data = asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
    long threadId = Thread.currentThread().getId();
    AtomicInteger curThreadCnt = new AtomicInteger();
    Collection<Integer> res;
    // Future for avoiding fast execution in only executor threads.
    // Here we try to pass a number of tasks more that executor size,
    // but there is a case when all task will be completed after last submit return control and
    // current thread can not steal task because all task will be already finished.
    GridFutureAdapter fut = new GridFutureAdapter();
    try {
        res = U.doInParallel(10, executorService, data, new IgniteThrowableFunction<Integer, Integer>() {

            @Override
            public Integer apply(Integer cnt) {
                if (Thread.currentThread().getId() == threadId) {
                    fut.onDone();
                    curThreadCnt.incrementAndGet();
                } else {
                    try {
                        fut.get();
                    } catch (IgniteCheckedException e) {
                        throw U.convertException(e);
                    }
                }
                return -cnt;
            }
        });
    } catch (IgniteCheckedException e) {
        throw new IgniteException(e);
    }
    Assert.assertTrue(curThreadCnt.get() > 0);
    Assert.assertEquals(asList(0, -1, -2, -3, -4, -5, -6, -7, -8, -9), res);
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BigInteger(java.math.BigInteger) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IgniteException(org.apache.ignite.IgniteException) GridFutureAdapter(org.apache.ignite.internal.util.future.GridFutureAdapter) IgniteThrowableFunction(org.apache.ignite.internal.util.lang.IgniteThrowableFunction)

Example 63 with GridFutureAdapter

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

the class GridCachePartitionExchangeManager method onKernalStart0.

/** {@inheritDoc} */
@Override
protected void onKernalStart0(boolean reconnect) throws IgniteCheckedException {
    super.onKernalStart0(reconnect);
    ClusterNode loc = cctx.localNode();
    long startTime = loc.metrics().getStartTime();
    assert startTime > 0;
    // Generate dummy discovery event for local node joining.
    T2<DiscoveryEvent, DiscoCache> locJoin = cctx.discovery().localJoin();
    DiscoveryEvent discoEvt = locJoin.get1();
    DiscoCache discoCache = locJoin.get2();
    GridDhtPartitionExchangeId exchId = initialExchangeId();
    GridDhtPartitionsExchangeFuture fut = exchangeFuture(exchId, discoEvt, discoCache, null, null);
    if (reconnect)
        reconnectExchangeFut = new GridFutureAdapter<>();
    exchWorker.addFirstExchangeFuture(fut);
    if (!cctx.kernalContext().clientNode()) {
        for (int cnt = 0; cnt < cctx.gridConfig().getRebalanceThreadPoolSize(); cnt++) {
            final int idx = cnt;
            cctx.io().addOrderedHandler(rebalanceTopic(cnt), new CI2<UUID, GridCacheMessage>() {

                @Override
                public void apply(final UUID id, final GridCacheMessage m) {
                    if (!enterBusy())
                        return;
                    try {
                        GridCacheContext cacheCtx = cctx.cacheContext(m.cacheId);
                        if (cacheCtx != null) {
                            if (m instanceof GridDhtPartitionSupplyMessage)
                                cacheCtx.preloader().handleSupplyMessage(idx, id, (GridDhtPartitionSupplyMessage) m);
                            else if (m instanceof GridDhtPartitionDemandMessage)
                                cacheCtx.preloader().handleDemandMessage(idx, id, (GridDhtPartitionDemandMessage) m);
                            else
                                U.error(log, "Unsupported message type: " + m.getClass().getName());
                        }
                    } finally {
                        leaveBusy();
                    }
                }
            });
        }
    }
    new IgniteThread(cctx.igniteInstanceName(), "exchange-worker", exchWorker).start();
    if (reconnect) {
        fut.listen(new CI1<IgniteInternalFuture<AffinityTopologyVersion>>() {

            @Override
            public void apply(IgniteInternalFuture<AffinityTopologyVersion> fut) {
                try {
                    fut.get();
                    for (GridCacheContext cacheCtx : cctx.cacheContexts()) cacheCtx.preloader().onInitialExchangeComplete(null);
                    reconnectExchangeFut.onDone();
                } catch (IgniteCheckedException e) {
                    for (GridCacheContext cacheCtx : cctx.cacheContexts()) cacheCtx.preloader().onInitialExchangeComplete(e);
                    reconnectExchangeFut.onDone(e);
                }
            }
        });
    } else {
        if (log.isDebugEnabled())
            log.debug("Beginning to wait on local exchange future: " + fut);
        boolean first = true;
        while (true) {
            try {
                fut.get(cctx.preloadExchangeTimeout());
                break;
            } catch (IgniteFutureTimeoutCheckedException ignored) {
                if (first) {
                    U.warn(log, "Failed to wait for initial partition map exchange. " + "Possible reasons are: " + U.nl() + "  ^-- Transactions in deadlock." + U.nl() + "  ^-- Long running transactions (ignore if this is the case)." + U.nl() + "  ^-- Unreleased explicit locks.");
                    first = false;
                } else
                    U.warn(log, "Still waiting for initial partition map exchange [fut=" + fut + ']');
            } catch (IgniteNeedReconnectException e) {
                throw e;
            } catch (Exception e) {
                if (fut.reconnectOnError(e))
                    throw new IgniteNeedReconnectException(cctx.localNode(), e);
                throw e;
            }
        }
        AffinityTopologyVersion nodeStartVer = new AffinityTopologyVersion(discoEvt.topologyVersion(), 0);
        for (GridCacheContext cacheCtx : cctx.cacheContexts()) {
            if (nodeStartVer.equals(cacheCtx.startTopologyVersion()))
                cacheCtx.preloader().onInitialExchangeComplete(null);
        }
        if (log.isDebugEnabled())
            log.debug("Finished waiting for initial exchange: " + fut.exchangeId());
    }
}
Also used : DiscoCache(org.apache.ignite.internal.managers.discovery.DiscoCache) DiscoveryEvent(org.apache.ignite.events.DiscoveryEvent) GridDhtPartitionExchangeId(org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionExchangeId) IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridFutureAdapter(org.apache.ignite.internal.util.future.GridFutureAdapter) IgniteFutureTimeoutCheckedException(org.apache.ignite.internal.IgniteFutureTimeoutCheckedException) UUID(java.util.UUID) IgniteNeedReconnectException(org.apache.ignite.internal.IgniteNeedReconnectException) ClusterNode(org.apache.ignite.cluster.ClusterNode) GridDhtPartitionsExchangeFuture(org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsExchangeFuture) AffinityTopologyVersion(org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion) GridDhtPartitionSupplyMessage(org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionSupplyMessage) IgniteClientDisconnectedCheckedException(org.apache.ignite.internal.IgniteClientDisconnectedCheckedException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteNeedReconnectException(org.apache.ignite.internal.IgniteNeedReconnectException) IgniteFutureTimeoutCheckedException(org.apache.ignite.internal.IgniteFutureTimeoutCheckedException) IgniteInterruptedCheckedException(org.apache.ignite.internal.IgniteInterruptedCheckedException) ClusterTopologyCheckedException(org.apache.ignite.internal.cluster.ClusterTopologyCheckedException) IgniteThread(org.apache.ignite.thread.IgniteThread) GridDhtPartitionDemandMessage(org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionDemandMessage)

Example 64 with GridFutureAdapter

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

the class GridAffinityProcessor method affinityCache.

/**
 * @param cacheName Cache name.
 * @param topVer Topology version.
 * @return Affinity cache.
 * @throws IgniteCheckedException In case of error.
 */
@SuppressWarnings("ErrorNotRethrown")
@Nullable
private AffinityInfo affinityCache(final String cacheName, AffinityTopologyVersion topVer) throws IgniteCheckedException {
    AffinityAssignmentKey key = new AffinityAssignmentKey(cacheName, topVer);
    IgniteInternalFuture<AffinityInfo> fut = affMap.get(key);
    if (fut != null)
        return fut.get();
    GridCacheAdapter<Object, Object> cache = ctx.cache().internalCache(cacheName);
    if (cache != null) {
        GridCacheContext<Object, Object> cctx = cache.context();
        cctx.awaitStarted();
        AffinityAssignment assign0 = cctx.affinity().assignment(topVer);
        try {
            cctx.gate().enter();
        } catch (IllegalStateException ignored) {
            return null;
        }
        try {
            GridAffinityAssignment assign = assign0 instanceof GridAffinityAssignment ? (GridAffinityAssignment) assign0 : new GridAffinityAssignment(topVer, assign0.assignment(), assign0.idealAssignment());
            AffinityInfo info = new AffinityInfo(cctx.config().getAffinity(), cctx.config().getAffinityMapper(), assign, cctx.cacheObjectContext());
            IgniteInternalFuture<AffinityInfo> old = affMap.putIfAbsent(key, new GridFinishedFuture<>(info));
            if (old != null)
                info = old.get();
            return info;
        } finally {
            cctx.gate().leave();
        }
    }
    Collection<ClusterNode> cacheNodes = ctx.discovery().cacheNodes(cacheName, topVer);
    if (F.isEmpty(cacheNodes))
        return null;
    GridFutureAdapter<AffinityInfo> fut0 = new GridFutureAdapter<>();
    IgniteInternalFuture<AffinityInfo> old = affMap.putIfAbsent(key, fut0);
    if (old != null)
        return old.get();
    int max = ERROR_RETRIES;
    int cnt = 0;
    Iterator<ClusterNode> it = cacheNodes.iterator();
    // We are here because affinity has not been fetched yet, or cache mode is LOCAL.
    while (true) {
        cnt++;
        if (!it.hasNext())
            it = cacheNodes.iterator();
        // Double check since we deal with dynamic view.
        if (!it.hasNext())
            // Exception will be caught in this method.
            throw new IgniteCheckedException("No cache nodes in topology for cache name: " + cacheName);
        ClusterNode n = it.next();
        CacheMode mode = ctx.cache().cacheMode(cacheName);
        if (mode == null) {
            if (ctx.clientDisconnected())
                throw new IgniteClientDisconnectedCheckedException(ctx.cluster().clientReconnectFuture(), "Failed to get affinity mapping, client disconnected.");
            throw new IgniteCheckedException("No cache nodes in topology for cache name: " + cacheName);
        }
        // Map all keys to a single node, if the cache mode is LOCAL.
        if (mode == LOCAL) {
            fut0.onDone(new IgniteCheckedException("Failed to map keys for LOCAL cache."));
            // Will throw exception.
            fut0.get();
        }
        try {
            // Resolve cache context for remote node.
            // Set affinity function before counting down on latch.
            fut0.onDone(affinityInfoFromNode(cacheName, topVer, n));
            break;
        } catch (IgniteCheckedException e) {
            if (log.isDebugEnabled())
                log.debug("Failed to get affinity from node (will retry) [cache=" + cacheName + ", node=" + U.toShortString(n) + ", msg=" + e.getMessage() + ']');
            if (cnt < max) {
                U.sleep(ERROR_WAIT);
                continue;
            }
            affMap.remove(key, fut0);
            fut0.onDone(new IgniteCheckedException("Failed to get affinity mapping from node: " + n, e));
            break;
        } catch (RuntimeException | Error e) {
            fut0.onDone(new IgniteCheckedException("Failed to get affinity mapping from node: " + n, e));
            break;
        }
    }
    return fut0.get();
}
Also used : ClusterNode(org.apache.ignite.cluster.ClusterNode) CacheMode(org.apache.ignite.cache.CacheMode) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridFutureAdapter(org.apache.ignite.internal.util.future.GridFutureAdapter) IgniteClientDisconnectedCheckedException(org.apache.ignite.internal.IgniteClientDisconnectedCheckedException) BinaryObject(org.apache.ignite.binary.BinaryObject) CacheObject(org.apache.ignite.internal.processors.cache.CacheObject) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject) Nullable(org.jetbrains.annotations.Nullable)

Example 65 with GridFutureAdapter

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

the class IgfsDataManager method dataBlock.

/**
 * Get data block for specified file ID and block index.
 *
 * @param fileInfo File info.
 * @param path Path reading from.
 * @param blockIdx Block index.
 * @param secReader Optional secondary file system reader.
 * @return Requested data block or {@code null} if nothing found.
 * @throws IgniteCheckedException If failed.
 */
@Nullable
public IgniteInternalFuture<byte[]> dataBlock(final IgfsEntryInfo fileInfo, final IgfsPath path, final long blockIdx, @Nullable final IgfsSecondaryFileSystemPositionedReadable secReader) throws IgniteCheckedException {
    assert fileInfo != null;
    assert blockIdx >= 0;
    // Schedule block request BEFORE prefetch requests.
    final IgfsBlockKey key = blockKey(blockIdx, fileInfo);
    if (log.isDebugEnabled() && dataCache.affinity().isPrimaryOrBackup(igfsCtx.kernalContext().discovery().localNode(), key)) {
        log.debug("Reading non-local data block [path=" + path + ", fileInfo=" + fileInfo + ", blockIdx=" + blockIdx + ']');
    }
    IgniteInternalFuture<byte[]> fut = dataCachePrj.getAsync(key);
    if (secReader != null) {
        Executor exec = igfsCtx.kernalContext().pools().poolForPolicy(GridIoPolicy.IGFS_POOL);
        fut = fut.chain(new CX1<IgniteInternalFuture<byte[]>, byte[]>() {

            @Override
            public byte[] applyx(IgniteInternalFuture<byte[]> fut) throws IgniteCheckedException {
                byte[] res = fut.get();
                if (res == null) {
                    GridFutureAdapter<byte[]> rmtReadFut = new GridFutureAdapter<>();
                    IgniteInternalFuture<byte[]> oldRmtReadFut = rmtReadFuts.putIfAbsent(key, rmtReadFut);
                    if (oldRmtReadFut == null) {
                        try {
                            res = secondaryDataBlock(path, blockIdx, secReader, fileInfo.blockSize());
                            rmtReadFut.onDone(res);
                            putBlock(fileInfo.blockSize(), key, res);
                        } catch (IgniteCheckedException e) {
                            rmtReadFut.onDone(e);
                            throw e;
                        } finally {
                            boolean rmv = rmtReadFuts.remove(key, rmtReadFut);
                            assert rmv;
                        }
                    } else {
                        // Wait for existing future to finish and get it's result.
                        res = oldRmtReadFut.get();
                        igfsCtx.metrics().addReadBlocks(1, 0);
                    }
                } else
                    igfsCtx.metrics().addReadBlocks(1, 0);
                return res;
            }
        }, exec);
    } else
        igfsCtx.metrics().addReadBlocks(1, 0);
    return fut;
}
Also used : Executor(java.util.concurrent.Executor) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridFutureAdapter(org.apache.ignite.internal.util.future.GridFutureAdapter) IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) CX1(org.apache.ignite.internal.util.typedef.CX1) Nullable(org.jetbrains.annotations.Nullable)

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