Search in sources :

Example 6 with GridCloseableIterator

use of org.apache.ignite.internal.util.lang.GridCloseableIterator in project ignite by apache.

the class IgniteCacheOffheapManagerImpl method rebalanceIterator.

/**
 * {@inheritDoc}
 */
@Override
public IgniteRebalanceIterator rebalanceIterator(IgniteDhtDemandedPartitionsMap parts, AffinityTopologyVersion topVer) throws IgniteCheckedException {
    TreeMap<Integer, GridCloseableIterator<CacheDataRow>> iterators = new TreeMap<>();
    Set<Integer> missing = new HashSet<>();
    for (Integer p : parts.fullSet()) {
        GridCloseableIterator<CacheDataRow> partIter = reservedIterator(p, topVer);
        if (partIter == null) {
            missing.add(p);
            continue;
        }
        iterators.put(p, partIter);
    }
    IgniteHistoricalIterator historicalIterator = historicalIterator(parts.historicalMap(), missing);
    IgniteRebalanceIterator iter = new IgniteRebalanceIteratorImpl(iterators, historicalIterator);
    for (Integer p : missing) iter.setPartitionMissing(p);
    return iter;
}
Also used : CacheDataRow(org.apache.ignite.internal.processors.cache.persistence.CacheDataRow) GridCloseableIterator(org.apache.ignite.internal.util.lang.GridCloseableIterator) IgniteHistoricalIterator(org.apache.ignite.internal.processors.cache.distributed.dht.preloader.IgniteHistoricalIterator) IgniteRebalanceIteratorImpl(org.apache.ignite.internal.processors.cache.distributed.dht.preloader.IgniteRebalanceIteratorImpl) TreeMap(java.util.TreeMap) HashSet(java.util.HashSet)

Example 7 with GridCloseableIterator

use of org.apache.ignite.internal.util.lang.GridCloseableIterator in project ignite by apache.

the class IgniteSnapshotManager method partitionRowIterator.

/**
 * @param snpName Snapshot name.
 * @param folderName The node folder name, usually it's the same as the U.maskForFileName(consistentId).
 * @param grpName Cache group name.
 * @param partId Partition id.
 * @return Iterator over partition.
 * @throws IgniteCheckedException If and error occurs.
 */
public GridCloseableIterator<CacheDataRow> partitionRowIterator(GridKernalContext ctx, String snpName, String folderName, String grpName, int partId) throws IgniteCheckedException {
    File snpDir = resolveSnapshotDir(snpName);
    File nodePath = new File(snpDir, databaseRelativePath(folderName));
    if (!nodePath.exists())
        throw new IgniteCheckedException("Consistent id directory doesn't exists: " + nodePath.getAbsolutePath());
    List<File> grps = cacheDirectories(nodePath, name -> name.equals(grpName));
    if (F.isEmpty(grps)) {
        throw new IgniteCheckedException("The snapshot cache group not found [dir=" + snpDir.getAbsolutePath() + ", grpName=" + grpName + ']');
    }
    if (grps.size() > 1) {
        throw new IgniteCheckedException("The snapshot cache group directory cannot be uniquely identified [dir=" + snpDir.getAbsolutePath() + ", grpName=" + grpName + ']');
    }
    File snpPart = getPartitionFile(new File(snapshotLocalDir(snpName), databaseRelativePath(folderName)), grps.get(0).getName(), partId);
    int grpId = CU.cacheId(grpName);
    FilePageStore pageStore = (FilePageStore) storeMgr.getPageStoreFactory(grpId, cctx.cache().isEncrypted(grpId)).createPageStore(getTypeByPartId(partId), snpPart::toPath, val -> {
    });
    GridCloseableIterator<CacheDataRow> partIter = partitionRowIterator(ctx, grpName, partId, pageStore);
    return new GridCloseableIteratorAdapter<CacheDataRow>() {

        /**
         * {@inheritDoc}
         */
        @Override
        protected CacheDataRow onNext() throws IgniteCheckedException {
            return partIter.nextX();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        protected boolean onHasNext() throws IgniteCheckedException {
            return partIter.hasNextX();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        protected void onClose() {
            U.closeQuiet(pageStore);
        }
    };
}
Also used : MappedName(org.apache.ignite.internal.processors.marshaller.MappedName) EVT_CLUSTER_SNAPSHOT_FINISHED(org.apache.ignite.events.EventType.EVT_CLUSTER_SNAPSHOT_FINISHED) BufferedInputStream(java.io.BufferedInputStream) GridFinishedFuture(org.apache.ignite.internal.util.future.GridFinishedFuture) MetastorageLifecycleListener(org.apache.ignite.internal.processors.cache.persistence.metastorage.MetastorageLifecycleListener) CacheObjectBinaryProcessorImpl.binaryWorkDir(org.apache.ignite.internal.processors.cache.binary.CacheObjectBinaryProcessorImpl.binaryWorkDir) ReadOnlyMetastorage(org.apache.ignite.internal.processors.cache.persistence.metastorage.ReadOnlyMetastorage) FileIO(org.apache.ignite.internal.processors.cache.persistence.file.FileIO) METASTORAGE_CACHE_ID(org.apache.ignite.internal.processors.cache.persistence.metastorage.MetaStorage.METASTORAGE_CACHE_ID) Map(java.util.Map) TransmissionHandler(org.apache.ignite.internal.managers.communication.TransmissionHandler) Path(java.nio.file.Path) GridToStringExclude(org.apache.ignite.internal.util.tostring.GridToStringExclude) CacheGroupDescriptor(org.apache.ignite.internal.processors.cache.CacheGroupDescriptor) CacheDataRow(org.apache.ignite.internal.processors.cache.persistence.CacheDataRow) Serializable(java.io.Serializable) ByteOrder(java.nio.ByteOrder) FileVisitResult(java.nio.file.FileVisitResult) SnapshotEvent(org.apache.ignite.events.SnapshotEvent) END_SNAPSHOT(org.apache.ignite.internal.util.distributed.DistributedProcess.DistributedProcessType.END_SNAPSHOT) IgniteFutureImpl(org.apache.ignite.internal.util.future.IgniteFutureImpl) U(org.apache.ignite.internal.util.typedef.internal.U) EVT_DISCOVERY_CUSTOM_EVT(org.apache.ignite.internal.events.DiscoveryCustomEvent.EVT_DISCOVERY_CUSTOM_EVT) IgniteLogger(org.apache.ignite.IgniteLogger) EVT_CLUSTER_SNAPSHOT_STARTED(org.apache.ignite.events.EventType.EVT_CLUSTER_SNAPSHOT_STARTED) PageIO.getVersion(org.apache.ignite.internal.processors.cache.persistence.tree.io.PageIO.getVersion) ReadWriteMetastorage(org.apache.ignite.internal.processors.cache.persistence.metastorage.ReadWriteMetastorage) S(org.apache.ignite.internal.util.typedef.internal.S) METASTORAGE_CACHE_NAME(org.apache.ignite.internal.processors.cache.persistence.metastorage.MetaStorage.METASTORAGE_CACHE_NAME) GridInternal(org.apache.ignite.internal.processors.task.GridInternal) A(org.apache.ignite.internal.util.typedef.internal.A) MarshallerContextImpl.resolveMappingFileStoreWorkDir(org.apache.ignite.internal.MarshallerContextImpl.resolveMappingFileStoreWorkDir) IOException(java.io.IOException) MetricRegistry(org.apache.ignite.internal.processors.metric.MetricRegistry) T2(org.apache.ignite.internal.util.typedef.T2) BinaryType(org.apache.ignite.binary.BinaryType) GridCacheSharedContext(org.apache.ignite.internal.processors.cache.GridCacheSharedContext) StandaloneGridKernalContext(org.apache.ignite.internal.processors.cache.persistence.wal.reader.StandaloneGridKernalContext) BROADCAST(org.apache.ignite.internal.GridClosureCallMode.BROADCAST) CacheConfiguration(org.apache.ignite.configuration.CacheConfiguration) DFLT_BINARY_METADATA_PATH(org.apache.ignite.configuration.DataStorageConfiguration.DFLT_BINARY_METADATA_PATH) GroupPartitionId.getTypeByPartId(org.apache.ignite.internal.processors.cache.persistence.partstate.GroupPartitionId.getTypeByPartId) PageIdUtils.flag(org.apache.ignite.internal.pagemem.PageIdUtils.flag) CacheObjectContext(org.apache.ignite.internal.processors.cache.CacheObjectContext) START_SNAPSHOT(org.apache.ignite.internal.util.distributed.DistributedProcess.DistributedProcessType.START_SNAPSHOT) IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) DiscoveryCustomEvent(org.apache.ignite.internal.events.DiscoveryCustomEvent) PageIdUtils.pageId(org.apache.ignite.internal.pagemem.PageIdUtils.pageId) PageIdUtils.toDetailString(org.apache.ignite.internal.pagemem.PageIdUtils.toDetailString) PageStore(org.apache.ignite.internal.pagemem.store.PageStore) IgniteFeatures.nodeSupports(org.apache.ignite.internal.IgniteFeatures.nodeSupports) BiFunction(java.util.function.BiFunction) SYSTEM_POOL(org.apache.ignite.internal.managers.communication.GridIoPolicy.SYSTEM_POOL) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) MarshallerContextImpl.mappingFileStoreWorkDir(org.apache.ignite.internal.MarshallerContextImpl.mappingFileStoreWorkDir) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) Nullable(org.jetbrains.annotations.Nullable) FastCrc(org.apache.ignite.internal.processors.cache.persistence.wal.crc.FastCrc) InitMessage(org.apache.ignite.internal.util.distributed.InitMessage) FilePageStoreManager.cacheDirectories(org.apache.ignite.internal.processors.cache.persistence.file.FilePageStoreManager.cacheDirectories) CU(org.apache.ignite.internal.util.typedef.internal.CU) Queue(java.util.Queue) FilePageStoreManager.getPartitionFile(org.apache.ignite.internal.processors.cache.persistence.file.FilePageStoreManager.getPartitionFile) MarshallerUtils(org.apache.ignite.marshaller.MarshallerUtils) DataPagePayload(org.apache.ignite.internal.processors.cache.persistence.tree.io.DataPagePayload) SnapshotViewWalker(org.apache.ignite.internal.managers.systemview.walker.SnapshotViewWalker) IgniteFeatures(org.apache.ignite.internal.IgniteFeatures) Function(java.util.function.Function) ConcurrentMap(java.util.concurrent.ConcurrentMap) HashSet(java.util.HashSet) SnapshotView(org.apache.ignite.spi.systemview.view.SnapshotView) GridUnsafe.bufferAddress(org.apache.ignite.internal.util.GridUnsafe.bufferAddress) DFLT_MARSHALLER_PATH(org.apache.ignite.configuration.DataStorageConfiguration.DFLT_MARSHALLER_PATH) LinkedList(java.util.LinkedList) NoSuchElementException(java.util.NoSuchElementException) ExecutorService(java.util.concurrent.ExecutorService) TC_SUBGRID(org.apache.ignite.internal.processors.task.GridTaskThreadContextKey.TC_SUBGRID) GridMessageListener(org.apache.ignite.internal.managers.communication.GridMessageListener) GroupPartitionId(org.apache.ignite.internal.processors.cache.persistence.partstate.GroupPartitionId) FileInputStream(java.io.FileInputStream) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) ConcurrentLinkedDeque(java.util.concurrent.ConcurrentLinkedDeque) GridCloseableIterator(org.apache.ignite.internal.util.lang.GridCloseableIterator) Consumer(java.util.function.Consumer) PartitionsExchangeAware(org.apache.ignite.internal.processors.cache.distributed.dht.preloader.PartitionsExchangeAware) DiscoveryDataClusterState(org.apache.ignite.internal.processors.cluster.DiscoveryDataClusterState) DataPageIO(org.apache.ignite.internal.processors.cache.persistence.tree.io.DataPageIO) GridPlainRunnable(org.apache.ignite.internal.util.lang.GridPlainRunnable) BitSet(java.util.BitSet) FileChannel(java.nio.channels.FileChannel) IgniteSnapshot(org.apache.ignite.IgniteSnapshot) TransmissionMeta(org.apache.ignite.internal.managers.communication.TransmissionMeta) GridClosureException(org.apache.ignite.internal.util.lang.GridClosureException) Arrays(java.util.Arrays) CacheType(org.apache.ignite.internal.processors.cache.CacheType) GridFutureAdapter(org.apache.ignite.internal.util.future.GridFutureAdapter) EVT_NODE_LEFT(org.apache.ignite.events.EventType.EVT_NODE_LEFT) MAX_PARTITION_ID(org.apache.ignite.internal.pagemem.PageIdAllocator.MAX_PARTITION_ID) BooleanSupplier(java.util.function.BooleanSupplier) DirectoryStream(java.nio.file.DirectoryStream) GridCloseableIteratorAdapter(org.apache.ignite.internal.util.GridCloseableIteratorAdapter) MarshallerContextImpl.saveMappings(org.apache.ignite.internal.MarshallerContextImpl.saveMappings) ComputeTask(org.apache.ignite.compute.ComputeTask) T_DATA(org.apache.ignite.internal.processors.cache.persistence.tree.io.PageIO.T_DATA) DataRow(org.apache.ignite.internal.processors.cache.tree.DataRow) PERSISTENCE_CACHE_SNAPSHOT(org.apache.ignite.internal.IgniteFeatures.PERSISTENCE_CACHE_SNAPSHOT) RandomAccessFileIOFactory(org.apache.ignite.internal.processors.cache.persistence.file.RandomAccessFileIOFactory) EnumMap(java.util.EnumMap) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) Set(java.util.Set) IgniteInstanceResource(org.apache.ignite.resources.IgniteInstanceResource) GridBusyLock(org.apache.ignite.internal.util.GridBusyLock) TransmissionCancelledException(org.apache.ignite.internal.managers.communication.TransmissionCancelledException) CacheDataRowAdapter(org.apache.ignite.internal.processors.cache.persistence.CacheDataRowAdapter) PageIO.getType(org.apache.ignite.internal.processors.cache.persistence.tree.io.PageIO.getType) INDEX_PARTITION(org.apache.ignite.internal.pagemem.PageIdAllocator.INDEX_PARTITION) IgniteConfiguration(org.apache.ignite.configuration.IgniteConfiguration) PageIdUtils.pageIndex(org.apache.ignite.internal.pagemem.PageIdUtils.pageIndex) GridCompoundFuture(org.apache.ignite.internal.util.future.GridCompoundFuture) IgniteUtils.isLocalNodeCoordinator(org.apache.ignite.internal.util.IgniteUtils.isLocalNodeCoordinator) CacheObjectBinaryProcessorImpl.resolveBinaryWorkDir(org.apache.ignite.internal.processors.cache.binary.CacheObjectBinaryProcessorImpl.resolveBinaryWorkDir) BufferedOutputStream(java.io.BufferedOutputStream) ArrayList(java.util.ArrayList) GridKernalContext(org.apache.ignite.internal.GridKernalContext) READ(java.nio.file.StandardOpenOption.READ) ClusterNode(org.apache.ignite.cluster.ClusterNode) DB_DEFAULT_FOLDER(org.apache.ignite.internal.processors.cache.persistence.filename.PdsFolderResolver.DB_DEFAULT_FOLDER) GridDhtPartitionsExchangeFuture(org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsExchangeFuture) BiConsumer(java.util.function.BiConsumer) IgniteInterruptedException(org.apache.ignite.IgniteInterruptedException) Files(java.nio.file.Files) Executor(java.util.concurrent.Executor) TC_SKIP_AUTH(org.apache.ignite.internal.processors.task.GridTaskThreadContextKey.TC_SKIP_AUTH) FileOutputStream(java.io.FileOutputStream) Marshaller(org.apache.ignite.marshaller.Marshaller) File(java.io.File) GridTopic(org.apache.ignite.internal.GridTopic) Paths(java.nio.file.Paths) IgniteFinishedFutureImpl(org.apache.ignite.internal.util.future.IgniteFinishedFutureImpl) SNAPSHOT_SYS_VIEW(org.apache.ignite.spi.systemview.view.SnapshotView.SNAPSHOT_SYS_VIEW) ArrayDeque(java.util.ArrayDeque) IgniteUuid(org.apache.ignite.lang.IgniteUuid) FLAG_DATA(org.apache.ignite.internal.pagemem.PageIdAllocator.FLAG_DATA) IgniteEx(org.apache.ignite.internal.IgniteEx) IgniteChangeGlobalStateSupport(org.apache.ignite.internal.processors.cluster.IgniteChangeGlobalStateSupport) ByteBuffer(java.nio.ByteBuffer) IgniteFutureCancelledCheckedException(org.apache.ignite.internal.IgniteFutureCancelledCheckedException) SNAPSHOT_SYS_VIEW_DESC(org.apache.ignite.spi.systemview.view.SnapshotView.SNAPSHOT_SYS_VIEW_DESC) FilePageStore(org.apache.ignite.internal.processors.cache.persistence.file.FilePageStore) IgniteFuture(org.apache.ignite.lang.IgniteFuture) PART_FILE_TEMPLATE(org.apache.ignite.internal.processors.cache.persistence.file.FilePageStoreManager.PART_FILE_TEMPLATE) FailureType(org.apache.ignite.failure.FailureType) IgniteClientDisconnectedCheckedException(org.apache.ignite.internal.IgniteClientDisconnectedCheckedException) Predicate(java.util.function.Predicate) IgniteException(org.apache.ignite.IgniteException) FilePageStoreManager(org.apache.ignite.internal.processors.cache.persistence.file.FilePageStoreManager) GridCacheSharedManagerAdapter(org.apache.ignite.internal.processors.cache.GridCacheSharedManagerAdapter) List(java.util.List) EVT_NODE_FAILED(org.apache.ignite.events.EventType.EVT_NODE_FAILED) DiscoveryEventListener(org.apache.ignite.internal.managers.eventstorage.DiscoveryEventListener) IdleVerifyResultV2(org.apache.ignite.internal.processors.cache.verify.IdleVerifyResultV2) FilePageStoreManager.getPartitionFileName(org.apache.ignite.internal.processors.cache.persistence.file.FilePageStoreManager.getPartitionFileName) NodeStoppingException(org.apache.ignite.internal.NodeStoppingException) DiscoveryEvent(org.apache.ignite.events.DiscoveryEvent) PdsFolderSettings(org.apache.ignite.internal.processors.cache.persistence.filename.PdsFolderSettings) HashMap(java.util.HashMap) GridIoManager(org.apache.ignite.internal.managers.communication.GridIoManager) Deque(java.util.Deque) EVT_CLUSTER_SNAPSHOT_FAILED(org.apache.ignite.events.EventType.EVT_CLUSTER_SNAPSHOT_FAILED) IgniteCallable(org.apache.ignite.lang.IgniteCallable) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) FailureContext(org.apache.ignite.failure.FailureContext) FileIOFactory(org.apache.ignite.internal.processors.cache.persistence.file.FileIOFactory) BALANCE(org.apache.ignite.internal.GridClosureCallMode.BALANCE) PageIO(org.apache.ignite.internal.processors.cache.persistence.tree.io.PageIO) IgniteThrowableFunction(org.apache.ignite.internal.util.lang.IgniteThrowableFunction) DistributedMetaStorageImpl(org.apache.ignite.internal.processors.metastorage.persistence.DistributedMetaStorageImpl) OutputStream(java.io.OutputStream) DistributedProcess(org.apache.ignite.internal.util.distributed.DistributedProcess) F(org.apache.ignite.internal.util.typedef.F) PageIO.getPageIO(org.apache.ignite.internal.processors.cache.persistence.tree.io.PageIO.getPageIO) AffinityTopologyVersion(org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion) ClusterTopologyCheckedException(org.apache.ignite.internal.cluster.ClusterTopologyCheckedException) TransmissionPolicy(org.apache.ignite.internal.managers.communication.TransmissionPolicy) ADMIN_SNAPSHOT(org.apache.ignite.plugin.security.SecurityPermission.ADMIN_SNAPSHOT) INDEX_FILE_NAME(org.apache.ignite.internal.processors.cache.persistence.file.FilePageStoreManager.INDEX_FILE_NAME) Collections(java.util.Collections) InputStream(java.io.InputStream) CacheDataRow(org.apache.ignite.internal.processors.cache.persistence.CacheDataRow) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridCloseableIteratorAdapter(org.apache.ignite.internal.util.GridCloseableIteratorAdapter) FilePageStore(org.apache.ignite.internal.processors.cache.persistence.file.FilePageStore) FilePageStoreManager.getPartitionFile(org.apache.ignite.internal.processors.cache.persistence.file.FilePageStoreManager.getPartitionFile) File(java.io.File)

Example 8 with GridCloseableIterator

use of org.apache.ignite.internal.util.lang.GridCloseableIterator in project ignite by apache.

the class GridCacheQueryManager method scanQueryLocal.

/**
 * Process local scan query.
 *
 * @param qry Query.
 * @param updateStatistics Update statistics flag.
 */
@SuppressWarnings({ "unchecked" })
protected GridCloseableIterator scanQueryLocal(final GridCacheQueryAdapter qry, boolean updateStatistics) throws IgniteCheckedException {
    if (!enterBusy())
        throw new IllegalStateException("Failed to process query request (grid is stopping).");
    final boolean statsEnabled = cctx.statisticsEnabled();
    updateStatistics &= statsEnabled;
    long startTime = U.currentTimeMillis();
    final String namex = cctx.name();
    final InternalScanFilter<K, V> intFilter = qry.scanFilter() != null ? new InternalScanFilter<>(qry.scanFilter()) : null;
    try {
        assert qry.type() == SCAN;
        if (log.isDebugEnabled())
            log.debug("Running local SCAN query: " + qry);
        final String taskName = cctx.kernalContext().task().resolveTaskName(qry.taskHash());
        final ClusterNode locNode = cctx.localNode();
        if (cctx.events().isRecordable(EVT_CACHE_QUERY_EXECUTED)) {
            cctx.gridEvents().record(new CacheQueryExecutedEvent<>(locNode, "Scan query executed.", EVT_CACHE_QUERY_EXECUTED, CacheQueryType.SCAN.name(), namex, null, null, intFilter != null ? intFilter.scanFilter() : null, null, null, securitySubjectId(cctx), taskName));
        }
        IgniteClosure transformer = qry.transform();
        injectResources(transformer);
        GridCloseableIterator it = scanIterator(qry, transformer, true);
        updateStatistics = false;
        return it;
    } catch (Exception e) {
        if (intFilter != null)
            intFilter.close();
        if (updateStatistics)
            cctx.queries().collectMetrics(GridCacheQueryType.SCAN, namex, startTime, U.currentTimeMillis() - startTime, true);
        throw e;
    } finally {
        leaveBusy();
    }
}
Also used : ClusterNode(org.apache.ignite.cluster.ClusterNode) IgniteClosure(org.apache.ignite.lang.IgniteClosure) GridCloseableIterator(org.apache.ignite.internal.util.lang.GridCloseableIterator) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) SQLException(java.sql.SQLException) CacheInvalidStateException(org.apache.ignite.internal.processors.cache.CacheInvalidStateException) IOException(java.io.IOException) IgniteException(org.apache.ignite.IgniteException) GridCacheEntryRemovedException(org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException) NodeStoppingException(org.apache.ignite.internal.NodeStoppingException) NoSuchElementException(java.util.NoSuchElementException) GridDhtUnreservedPartitionException(org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtUnreservedPartitionException)

Example 9 with GridCloseableIterator

use of org.apache.ignite.internal.util.lang.GridCloseableIterator in project ignite by apache.

the class GridCacheDistributedQueryManager method scanQueryDistributed.

/**
 * {@inheritDoc}
 */
@SuppressWarnings({ "unchecked" })
@Override
public GridCloseableIterator scanQueryDistributed(final GridCacheQueryAdapter qry, Collection<ClusterNode> nodes) throws IgniteCheckedException {
    assert !cctx.isLocal() : cctx.name();
    assert qry.type() == GridCacheQueryType.SCAN : qry;
    assert qry.mvccSnapshot() != null || !cctx.mvccEnabled();
    boolean performanceStatsEnabled = cctx.kernalContext().performanceStatistics().enabled();
    long startTime = performanceStatsEnabled ? System.currentTimeMillis() : 0;
    long startTimeNanos = performanceStatsEnabled ? System.nanoTime() : 0;
    GridCloseableIterator locIter0 = null;
    for (ClusterNode node : nodes) {
        if (node.isLocal()) {
            locIter0 = scanQueryLocal(qry, false);
            Collection<ClusterNode> rmtNodes = new ArrayList<>(nodes.size() - 1);
            for (ClusterNode n : nodes) {
                // Equals by reference can be used here.
                if (n != node)
                    rmtNodes.add(n);
            }
            nodes = rmtNodes;
            break;
        }
    }
    final GridCloseableIterator locIter = locIter0;
    final GridCacheQueryBean bean = new GridCacheQueryBean(qry, null, qry.<K, V>transform(), null);
    final CacheQueryFuture fut = queryDistributed(bean, nodes);
    return new GridCloseableIteratorAdapter() {

        /**
         */
        private Object cur;

        /**
         * Logical reads.
         */
        private long logicalReads;

        /**
         * Physical reads.
         */
        private long physicalReads;

        @Override
        protected Object onNext() throws IgniteCheckedException {
            if (!onHasNext())
                throw new NoSuchElementException();
            Object e = cur;
            cur = null;
            return e;
        }

        @Override
        protected boolean onHasNext() throws IgniteCheckedException {
            if (cur != null)
                return true;
            if (locIter != null) {
                if (performanceStatsEnabled)
                    IoStatisticsQueryHelper.startGatheringQueryStatistics();
                try {
                    if (locIter.hasNextX())
                        cur = locIter.nextX();
                } finally {
                    if (performanceStatsEnabled) {
                        IoStatisticsHolder stat = IoStatisticsQueryHelper.finishGatheringQueryStatistics();
                        logicalReads += stat.logicalReads();
                        physicalReads += stat.physicalReads();
                    }
                }
            }
            return cur != null || (cur = convert(fut.next())) != null;
        }

        /**
         * @param obj Entry to convert.
         * @return Cache entry
         */
        private Object convert(Object obj) {
            if (qry.transform() != null)
                return obj;
            Map.Entry e = (Map.Entry) obj;
            return e == null ? null : new CacheQueryEntry(e.getKey(), e.getValue());
        }

        @Override
        protected void onClose() throws IgniteCheckedException {
            super.onClose();
            if (locIter != null)
                locIter.close();
            if (fut != null)
                fut.cancel();
            if (performanceStatsEnabled) {
                cctx.kernalContext().performanceStatistics().query(SCAN, cctx.name(), ((GridCacheDistributedQueryFuture) fut).requestId(), startTime, System.nanoTime() - startTimeNanos, true);
                if (logicalReads > 0 || physicalReads > 0) {
                    cctx.kernalContext().performanceStatistics().queryReads(SCAN, cctx.localNodeId(), ((GridCacheDistributedQueryFuture) fut).requestId(), logicalReads, physicalReads);
                }
            }
        }
    };
}
Also used : ClusterNode(org.apache.ignite.cluster.ClusterNode) GridCloseableIteratorAdapter(org.apache.ignite.internal.util.GridCloseableIteratorAdapter) GridCloseableIterator(org.apache.ignite.internal.util.lang.GridCloseableIterator) ArrayList(java.util.ArrayList) IoStatisticsHolder(org.apache.ignite.internal.metric.IoStatisticsHolder) ConcurrentMap(java.util.concurrent.ConcurrentMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) NoSuchElementException(java.util.NoSuchElementException)

Example 10 with GridCloseableIterator

use of org.apache.ignite.internal.util.lang.GridCloseableIterator in project ignite by apache.

the class GridCacheQueryAdapter method executeScanQuery.

/**
 * {@inheritDoc}
 */
@Override
public GridCloseableIterator executeScanQuery() throws IgniteCheckedException {
    assert type == SCAN : "Wrong processing of query: " + type;
    if (!cctx.isLocal()) {
        GridDhtCacheAdapter<?, ?> cacheAdapter = cctx.isNear() ? cctx.near().dht() : cctx.dht();
        Set<Integer> lostParts = cacheAdapter.topology().lostPartitions();
        if (!lostParts.isEmpty()) {
            if (part == null || lostParts.contains(part)) {
                throw new CacheException(new CacheInvalidStateException("Failed to execute query because cache partition " + "has been lostParts [cacheName=" + cctx.name() + ", part=" + (part == null ? lostParts.iterator().next() : part) + ']'));
            }
        }
    }
    // Affinity nodes snapshot.
    Collection<ClusterNode> nodes = new ArrayList<>(nodes());
    cctx.checkSecurity(SecurityPermission.CACHE_READ);
    if (nodes.isEmpty()) {
        if (part != null) {
            if (forceLocal) {
                throw new IgniteCheckedException("No queryable nodes for partition " + part + " [forced local query=" + this + "]");
            }
        }
        return new GridEmptyCloseableIterator();
    }
    if (log.isDebugEnabled())
        log.debug("Executing query [query=" + this + ", nodes=" + nodes + ']');
    if (cctx.deploymentEnabled())
        cctx.deploy().registerClasses(filter);
    taskHash = cctx.kernalContext().job().currentTaskNameHash();
    final GridCacheQueryManager qryMgr = cctx.queries();
    MvccQueryTracker mvccTracker = null;
    if (cctx.mvccEnabled() && mvccSnapshot == null) {
        GridNearTxLocal tx = cctx.tm().userTx();
        if (tx != null)
            mvccSnapshot = MvccUtils.requestSnapshot(tx);
        else {
            mvccTracker = MvccUtils.mvccTracker(cctx, null);
            mvccSnapshot = mvccTracker.snapshot();
        }
        assert mvccSnapshot != null;
    }
    boolean loc = nodes.size() == 1 && F.first(nodes).id().equals(cctx.localNodeId());
    GridCloseableIterator it;
    if (loc)
        it = qryMgr.scanQueryLocal(this, true);
    else if (part != null)
        it = new ScanQueryFallbackClosableIterator(part, this, qryMgr, cctx);
    else
        it = qryMgr.scanQueryDistributed(this, nodes);
    return mvccTracker != null ? new MvccTrackingIterator(it, mvccTracker) : it;
}
Also used : ClusterNode(org.apache.ignite.cluster.ClusterNode) GridCloseableIterator(org.apache.ignite.internal.util.lang.GridCloseableIterator) CacheException(javax.cache.CacheException) ArrayList(java.util.ArrayList) GridEmptyCloseableIterator(org.apache.ignite.internal.util.GridEmptyCloseableIterator) GridNearTxLocal(org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal) MvccQueryTracker(org.apache.ignite.internal.processors.cache.mvcc.MvccQueryTracker) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) CacheInvalidStateException(org.apache.ignite.internal.processors.cache.CacheInvalidStateException)

Aggregations

GridCloseableIterator (org.apache.ignite.internal.util.lang.GridCloseableIterator)16 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)14 GridCommonAbstractTest (org.apache.ignite.testframework.junits.common.GridCommonAbstractTest)7 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)6 IgniteBiTuple (org.apache.ignite.lang.IgniteBiTuple)6 Test (org.junit.Test)6 NoSuchElementException (java.util.NoSuchElementException)5 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)5 ClusterNode (org.apache.ignite.cluster.ClusterNode)5 ArrayList (java.util.ArrayList)4 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)4 HashSet (java.util.HashSet)3 Iterator (java.util.Iterator)3 Map (java.util.Map)3 Callable (java.util.concurrent.Callable)3 CacheException (javax.cache.CacheException)3 IgniteException (org.apache.ignite.IgniteException)3 IOException (java.io.IOException)2 SQLException (java.sql.SQLException)2 Collection (java.util.Collection)2