Search in sources :

Example 56 with CacheDataRow

use of org.apache.ignite.internal.processors.cache.persistence.CacheDataRow in project ignite by apache.

the class IgniteCacheOffheapManagerImpl method reservedIterator.

/**
 * {@inheritDoc}
 */
@Override
public GridCloseableIterator<CacheDataRow> reservedIterator(int part, AffinityTopologyVersion topVer) {
    GridDhtLocalPartition loc = grp.topology().localPartition(part, topVer, false);
    if (loc == null || !loc.reserve())
        return null;
    // It is necessary to check state after reservation to avoid race conditions.
    if (loc.state() != OWNING) {
        loc.release();
        return null;
    }
    CacheDataStore data = dataStore(loc);
    return new GridCloseableIteratorAdapter<CacheDataRow>() {

        /**
         */
        private CacheDataRow next;

        /**
         */
        private GridCursor<? extends CacheDataRow> cur;

        @Override
        protected CacheDataRow onNext() {
            CacheDataRow res = next;
            next = null;
            return res;
        }

        @Override
        protected boolean onHasNext() throws IgniteCheckedException {
            if (cur == null)
                cur = data.cursor(CacheDataRowAdapter.RowData.FULL_WITH_HINTS);
            if (next != null)
                return true;
            if (cur.next())
                next = cur.get();
            boolean hasNext = next != null;
            if (!hasNext)
                cur = null;
            return hasNext;
        }

        @Override
        protected void onClose() throws IgniteCheckedException {
            assert loc != null && loc.state() == OWNING && loc.reservations() > 0 : "Partition should be in OWNING state and has at least 1 reservation: " + loc;
            loc.release();
            cur = null;
        }
    };
}
Also used : CacheDataRow(org.apache.ignite.internal.processors.cache.persistence.CacheDataRow) GridCursor(org.apache.ignite.internal.util.lang.GridCursor) GridCloseableIteratorAdapter(org.apache.ignite.internal.util.GridCloseableIteratorAdapter) GridDhtLocalPartition(org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtLocalPartition)

Example 57 with CacheDataRow

use of org.apache.ignite.internal.processors.cache.persistence.CacheDataRow 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 58 with CacheDataRow

use of org.apache.ignite.internal.processors.cache.persistence.CacheDataRow in project ignite by apache.

the class GridCacheAdapter method getAllAsync0.

/**
 * @param keys Keys.
 * @param readerArgs Near cache reader will be added if not null.
 * @param readThrough Read-through flag.
 * @param checkTx Check local transaction flag.
 * @param taskName Task name/
 * @param deserializeBinary Deserialize binary flag.
 * @param expiry Expiry policy.
 * @param skipVals Skip values flag.
 * @param keepCacheObjects Keep cache objects.
 * @param needVer If {@code true} returns values as tuples containing value and version.
 * @param txLbl Transaction label.
 * @param mvccSnapshot MVCC snapshot.
 * @return Future.
 */
protected final <K1, V1> IgniteInternalFuture<Map<K1, V1>> getAllAsync0(@Nullable final Collection<KeyCacheObject> keys, @Nullable final ReaderArguments readerArgs, final boolean readThrough, boolean checkTx, final String taskName, final boolean deserializeBinary, @Nullable final IgniteCacheExpiryPolicy expiry, final boolean skipVals, final boolean keepCacheObjects, final boolean recovery, final ReadRepairStrategy readRepairStrategy, final boolean needVer, @Nullable String txLbl, MvccSnapshot mvccSnapshot) {
    if (F.isEmpty(keys))
        return new GridFinishedFuture<>(Collections.<K1, V1>emptyMap());
    GridNearTxLocal tx = null;
    if (checkTx) {
        try {
            checkJta();
        } catch (IgniteCheckedException e) {
            return new GridFinishedFuture<>(e);
        }
        tx = checkCurrentTx();
    }
    if (ctx.mvccEnabled() || tx == null || tx.implicit()) {
        assert (mvccSnapshot == null) == !ctx.mvccEnabled();
        Map<KeyCacheObject, EntryGetResult> misses = null;
        Set<GridCacheEntryEx> newLocalEntries = null;
        final AffinityTopologyVersion topVer = tx == null ? ctx.affinity().affinityTopologyVersion() : tx.topologyVersion();
        ctx.shared().database().checkpointReadLock();
        try {
            int keysSize = keys.size();
            GridDhtTopologyFuture topFut = ctx.shared().exchange().lastFinishedFuture();
            Throwable ex = topFut != null ? topFut.validateCache(ctx, recovery, /*read*/
            true, null, keys) : null;
            if (ex != null)
                return new GridFinishedFuture<>(ex);
            final Map<K1, V1> map = keysSize == 1 ? (Map<K1, V1>) new IgniteBiTuple<>() : U.<K1, V1>newHashMap(keysSize);
            final boolean storeEnabled = !skipVals && readThrough && ctx.readThrough();
            boolean readNoEntry = ctx.readNoEntry(expiry, readerArgs != null);
            for (KeyCacheObject key : keys) {
                while (true) {
                    try {
                        EntryGetResult res = null;
                        boolean evt = !skipVals;
                        boolean updateMetrics = !skipVals;
                        GridCacheEntryEx entry = null;
                        boolean skipEntry = readNoEntry;
                        if (readNoEntry) {
                            CacheDataRow row = mvccSnapshot != null ? ctx.offheap().mvccRead(ctx, key, mvccSnapshot) : ctx.offheap().read(ctx, key);
                            if (row != null) {
                                long expireTime = row.expireTime();
                                if (expireTime != 0) {
                                    if (expireTime > U.currentTimeMillis()) {
                                        res = new EntryGetWithTtlResult(row.value(), row.version(), false, expireTime, 0);
                                    } else
                                        skipEntry = false;
                                } else
                                    res = new EntryGetResult(row.value(), row.version(), false);
                            }
                            if (res != null) {
                                if (evt) {
                                    ctx.events().readEvent(key, null, txLbl, row.value(), taskName, !deserializeBinary);
                                }
                                if (updateMetrics && ctx.statisticsEnabled())
                                    ctx.cache().metrics0().onRead(true);
                            } else if (storeEnabled)
                                skipEntry = false;
                        }
                        if (!skipEntry) {
                            boolean isNewLocalEntry = this.map.getEntry(ctx, key) == null;
                            entry = entryEx(key);
                            if (entry == null) {
                                if (!skipVals && ctx.statisticsEnabled())
                                    ctx.cache().metrics0().onRead(false);
                                break;
                            }
                            if (isNewLocalEntry) {
                                if (newLocalEntries == null)
                                    newLocalEntries = new HashSet<>();
                                newLocalEntries.add(entry);
                            }
                            if (storeEnabled) {
                                res = entry.innerGetAndReserveForLoad(updateMetrics, evt, taskName, expiry, !deserializeBinary, readerArgs);
                                assert res != null;
                                if (res.value() == null) {
                                    if (misses == null)
                                        misses = new HashMap<>();
                                    misses.put(key, res);
                                    res = null;
                                }
                            } else {
                                res = entry.innerGetVersioned(null, null, updateMetrics, evt, null, taskName, expiry, !deserializeBinary, readerArgs);
                                if (res == null)
                                    entry.touch();
                            }
                        }
                        if (res != null) {
                            ctx.addResult(map, key, res, skipVals, keepCacheObjects, deserializeBinary, true, needVer);
                            if (entry != null && (tx == null || (!tx.implicit() && tx.isolation() == READ_COMMITTED)))
                                entry.touch();
                            if (keysSize == 1)
                                // Safe to return because no locks are required in READ_COMMITTED mode.
                                return new GridFinishedFuture<>(map);
                        }
                        break;
                    } catch (GridCacheEntryRemovedException ignored) {
                        if (log.isDebugEnabled())
                            log.debug("Got removed entry in getAllAsync(..) method (will retry): " + key);
                    }
                }
            }
            if (storeEnabled && misses != null) {
                final Map<KeyCacheObject, EntryGetResult> loadKeys = misses;
                final IgniteTxLocalAdapter tx0 = tx;
                final Collection<KeyCacheObject> loaded = new HashSet<>();
                return new GridEmbeddedFuture(ctx.closures().callLocalSafe(ctx.projectSafe(new GPC<Map<K1, V1>>() {

                    @Override
                    public Map<K1, V1> call() throws Exception {
                        ctx.store().loadAll(null, /*tx*/
                        loadKeys.keySet(), new CI2<KeyCacheObject, Object>() {

                            @Override
                            public void apply(KeyCacheObject key, Object val) {
                                EntryGetResult res = loadKeys.get(key);
                                if (res == null || val == null)
                                    return;
                                loaded.add(key);
                                CacheObject cacheVal = ctx.toCacheObject(val);
                                while (true) {
                                    GridCacheEntryEx entry = null;
                                    try {
                                        ctx.shared().database().ensureFreeSpace(ctx.dataRegion());
                                    } catch (IgniteCheckedException e) {
                                        // Wrap errors (will be unwrapped).
                                        throw new GridClosureException(e);
                                    }
                                    ctx.shared().database().checkpointReadLock();
                                    try {
                                        entry = entryEx(key);
                                        entry.unswap();
                                        GridCacheVersion newVer = nextVersion();
                                        EntryGetResult verVal = entry.versionedValue(cacheVal, res.version(), newVer, expiry, readerArgs);
                                        if (log.isDebugEnabled())
                                            log.debug("Set value loaded from store into entry [" + "oldVer=" + res.version() + ", newVer=" + verVal.version() + ", " + "entry=" + entry + ']');
                                        // Don't put key-value pair into result map if value is null.
                                        if (verVal.value() != null) {
                                            ctx.addResult(map, key, verVal, skipVals, keepCacheObjects, deserializeBinary, true, needVer);
                                        } else {
                                            ctx.addResult(map, key, new EntryGetResult(cacheVal, res.version()), skipVals, keepCacheObjects, deserializeBinary, false, needVer);
                                        }
                                        if (tx0 == null || (!tx0.implicit() && tx0.isolation() == READ_COMMITTED))
                                            entry.touch();
                                        break;
                                    } catch (GridCacheEntryRemovedException ignore) {
                                        if (log.isDebugEnabled())
                                            log.debug("Got removed entry during getAllAsync (will retry): " + entry);
                                    } catch (IgniteCheckedException e) {
                                        // Wrap errors (will be unwrapped).
                                        throw new GridClosureException(e);
                                    } finally {
                                        ctx.shared().database().checkpointReadUnlock();
                                    }
                                }
                            }
                        });
                        clearReservationsIfNeeded(topVer, loadKeys, loaded, tx0);
                        return map;
                    }
                }), true), new C2<Map<K, V>, Exception, IgniteInternalFuture<Map<K, V>>>() {

                    @Override
                    public IgniteInternalFuture<Map<K, V>> apply(Map<K, V> map, Exception e) {
                        if (e != null) {
                            clearReservationsIfNeeded(topVer, loadKeys, loaded, tx0);
                            return new GridFinishedFuture<>(e);
                        }
                        if (tx0 == null || (!tx0.implicit() && tx0.isolation() == READ_COMMITTED)) {
                            Collection<KeyCacheObject> notFound = new HashSet<>(loadKeys.keySet());
                            notFound.removeAll(loaded);
                            // Touch entries that were not found in store.
                            for (KeyCacheObject key : notFound) {
                                GridCacheEntryEx entry = peekEx(key);
                                if (entry != null)
                                    entry.touch();
                            }
                        }
                        // There were no misses.
                        return new GridFinishedFuture<>(Collections.<K, V>emptyMap());
                    }
                }, new C2<Map<K1, V1>, Exception, Map<K1, V1>>() {

                    @Override
                    public Map<K1, V1> apply(Map<K1, V1> loaded, Exception e) {
                        if (e == null)
                            map.putAll(loaded);
                        return map;
                    }
                });
            } else
                // Misses can be non-zero only if store is enabled.
                assert misses == null;
            return new GridFinishedFuture<>(map);
        } catch (RuntimeException | AssertionError e) {
            if (misses != null) {
                for (KeyCacheObject key0 : misses.keySet()) {
                    GridCacheEntryEx entry = peekEx(key0);
                    if (entry != null)
                        entry.touch();
                }
            }
            if (newLocalEntries != null) {
                for (GridCacheEntryEx entry : newLocalEntries) removeEntry(entry);
            }
            return new GridFinishedFuture<>(e);
        } catch (IgniteCheckedException e) {
            return new GridFinishedFuture<>(e);
        } finally {
            ctx.shared().database().checkpointReadUnlock();
        }
    } else {
        return asyncOp(tx, new AsyncOp<Map<K1, V1>>(keys) {

            @Override
            public IgniteInternalFuture<Map<K1, V1>> op(GridNearTxLocal tx, AffinityTopologyVersion readyTopVer) {
                return tx.getAllAsync(ctx, readyTopVer, keys, deserializeBinary, skipVals, false, !readThrough, recovery, readRepairStrategy, needVer);
            }
        }, ctx.operationContextPerCall(), /*retry*/
        false);
    }
}
Also used : IgniteBiTuple(org.apache.ignite.lang.IgniteBiTuple) HashMap(java.util.HashMap) IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) CI2(org.apache.ignite.internal.util.typedef.CI2) GridEmbeddedFuture(org.apache.ignite.internal.util.future.GridEmbeddedFuture) GridFinishedFuture(org.apache.ignite.internal.util.future.GridFinishedFuture) GridDhtTopologyFuture(org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTopologyFuture) GridCacheVersion(org.apache.ignite.internal.processors.cache.version.GridCacheVersion) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteTxLocalAdapter(org.apache.ignite.internal.processors.cache.transactions.IgniteTxLocalAdapter) HashSet(java.util.HashSet) CacheDataRow(org.apache.ignite.internal.processors.cache.persistence.CacheDataRow) GridClosureException(org.apache.ignite.internal.util.lang.GridClosureException) AffinityTopologyVersion(org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion) GridNearTxLocal(org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal) IgniteTxRollbackCheckedException(org.apache.ignite.internal.transactions.IgniteTxRollbackCheckedException) InvalidObjectException(java.io.InvalidObjectException) IgniteTxTimeoutCheckedException(org.apache.ignite.internal.transactions.IgniteTxTimeoutCheckedException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) EntryProcessorException(javax.cache.processor.EntryProcessorException) IgniteInterruptedCheckedException(org.apache.ignite.internal.IgniteInterruptedCheckedException) ClusterTopologyServerNotFoundException(org.apache.ignite.internal.cluster.ClusterTopologyServerNotFoundException) IOException(java.io.IOException) GridDhtInvalidPartitionException(org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtInvalidPartitionException) ObjectStreamException(java.io.ObjectStreamException) IgniteConsistencyViolationException(org.apache.ignite.internal.processors.cache.distributed.near.consistency.IgniteConsistencyViolationException) TransactionCheckedException(org.apache.ignite.internal.transactions.TransactionCheckedException) IgniteException(org.apache.ignite.IgniteException) NodeStoppingException(org.apache.ignite.internal.NodeStoppingException) ClusterTopologyException(org.apache.ignite.cluster.ClusterTopologyException) NoSuchElementException(java.util.NoSuchElementException) IgniteTxHeuristicCheckedException(org.apache.ignite.internal.transactions.IgniteTxHeuristicCheckedException) ClusterTopologyCheckedException(org.apache.ignite.internal.cluster.ClusterTopologyCheckedException) GridClosureException(org.apache.ignite.internal.util.lang.GridClosureException) Collection(java.util.Collection) GridSerializableMap(org.apache.ignite.internal.util.GridSerializableMap) Map(java.util.Map) SortedMap(java.util.SortedMap) HashMap(java.util.HashMap)

Example 59 with CacheDataRow

use of org.apache.ignite.internal.processors.cache.persistence.CacheDataRow in project ignite by apache.

the class GridCommandHandlerIndexingUtils method breakCacheDataTree.

/**
 * Deleting a rows from the cache without updating indexes.
 *
 * @param log Logger.
 * @param internalCache Cache.
 * @param partId Partition number.
 * @param filter Entry filter.
 */
static <K, V> void breakCacheDataTree(IgniteLogger log, IgniteInternalCache<K, V> internalCache, int partId, @Nullable BiPredicate<Integer, Entry<K, V>> filter) {
    requireNonNull(log);
    requireNonNull(internalCache);
    GridCacheContext<K, V> cacheCtx = internalCache.context();
    CacheDataStore cacheDataStore = cacheCtx.dht().topology().localPartition(partId).dataStore();
    String delegate = "delegate";
    if (hasField(cacheDataStore, delegate))
        cacheDataStore = field(cacheDataStore, delegate);
    CacheDataRowStore cacheDataRowStore = field(cacheDataStore, "rowStore");
    CacheDataTree cacheDataTree = field(cacheDataStore, "dataTree");
    String cacheName = internalCache.name();
    QueryCursor<Entry<K, V>> qryCursor = cacheCtx.kernalContext().grid().cache(cacheName).withKeepBinary().query(new ScanQuery<>(partId));
    Iterator<Entry<K, V>> cacheEntryIter = qryCursor.iterator();
    IgniteCacheDatabaseSharedManager db = cacheCtx.shared().database();
    int cacheId = CU.cacheId(cacheName);
    int i = 0;
    while (cacheEntryIter.hasNext()) {
        Entry<K, V> entry = cacheEntryIter.next();
        if (nonNull(filter) && !filter.test(i++, entry))
            continue;
        db.checkpointReadLock();
        try {
            CacheDataRow oldRow = cacheDataTree.remove(new SearchRow(cacheId, cacheCtx.toCacheKeyObject(entry.getKey())));
            if (nonNull(oldRow))
                cacheDataRowStore.removeRow(oldRow.link(), INSTANCE);
        } catch (IgniteCheckedException e) {
            throw new IgniteException("Failed to remove key skipping indexes: " + entry, e);
        } finally {
            db.checkpointReadUnlock();
        }
    }
}
Also used : CacheDataRow(org.apache.ignite.internal.processors.cache.persistence.CacheDataRow) CacheDataRowStore(org.apache.ignite.internal.processors.cache.tree.CacheDataRowStore) Entry(javax.cache.Cache.Entry) CacheDataStore(org.apache.ignite.internal.processors.cache.IgniteCacheOffheapManager.CacheDataStore) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) CacheDataTree(org.apache.ignite.internal.processors.cache.tree.CacheDataTree) IgniteException(org.apache.ignite.IgniteException) SearchRow(org.apache.ignite.internal.processors.cache.tree.SearchRow) IgniteCacheDatabaseSharedManager(org.apache.ignite.internal.processors.cache.persistence.IgniteCacheDatabaseSharedManager)

Example 60 with CacheDataRow

use of org.apache.ignite.internal.processors.cache.persistence.CacheDataRow in project ignite by apache.

the class GridDhtPartitionDemander method preloadEntries.

/**
 * Adds entries to partition p.
 *
 * @param topVer Topology version.
 * @param part Local partition.
 * @param infos Entries info for preload.
 * @throws IgniteCheckedException If failed.
 */
private void preloadEntries(AffinityTopologyVersion topVer, GridDhtLocalPartition part, Iterator<GridCacheEntryInfo> infos) throws IgniteCheckedException {
    // Received keys by caches, for statistics.
    IntHashMap<GridMutableLong> receivedKeys = new IntHashMap<>();
    grp.offheap().storeEntries(part, infos, new IgnitePredicateX<CacheDataRow>() {

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean applyx(CacheDataRow row) throws IgniteCheckedException {
            receivedKeys.computeIfAbsent(row.cacheId(), cid -> new GridMutableLong()).incrementAndGet();
            return preloadEntry(row, topVer);
        }
    });
    updateKeyReceivedMetrics(grp, receivedKeys);
}
Also used : CacheDataRow(org.apache.ignite.internal.processors.cache.persistence.CacheDataRow) IntHashMap(org.apache.ignite.internal.util.collection.IntHashMap) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridMutableLong(org.apache.ignite.internal.util.GridMutableLong)

Aggregations

CacheDataRow (org.apache.ignite.internal.processors.cache.persistence.CacheDataRow)78 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)35 KeyCacheObject (org.apache.ignite.internal.processors.cache.KeyCacheObject)20 GridCacheVersion (org.apache.ignite.internal.processors.cache.version.GridCacheVersion)16 ArrayList (java.util.ArrayList)14 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)14 IgniteException (org.apache.ignite.IgniteException)14 Nullable (org.jetbrains.annotations.Nullable)12 AffinityTopologyVersion (org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion)11 CacheObject (org.apache.ignite.internal.processors.cache.CacheObject)11 GridDhtLocalPartition (org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtLocalPartition)11 HashMap (java.util.HashMap)10 IgniteEx (org.apache.ignite.internal.IgniteEx)10 GridCacheContext (org.apache.ignite.internal.processors.cache.GridCacheContext)10 GridCacheEntryEx (org.apache.ignite.internal.processors.cache.GridCacheEntryEx)10 HashSet (java.util.HashSet)9 GridCacheEntryRemovedException (org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException)9 EntryGetResult (org.apache.ignite.internal.processors.cache.EntryGetResult)8 GridCursor (org.apache.ignite.internal.util.lang.GridCursor)8 NodeStoppingException (org.apache.ignite.internal.NodeStoppingException)7