Search in sources :

Example 21 with PageStore

use of org.apache.ignite.internal.pagemem.store.PageStore in project ignite by apache.

the class FilePageStoreManager method truncate.

/**
 * {@inheritDoc}
 */
@Override
public void truncate(int grpId, int partId, int tag) throws IgniteCheckedException {
    assert partId <= MAX_PARTITION_ID;
    PageStore store = getStore(grpId, partId);
    store.truncate(tag);
}
Also used : PageStore(org.apache.ignite.internal.pagemem.store.PageStore)

Example 22 with PageStore

use of org.apache.ignite.internal.pagemem.store.PageStore in project ignite by apache.

the class FilePageStoreManager method initDir.

/**
 * @param cacheWorkDir Work directory.
 * @param grpId Group ID.
 * @param partitions Number of partitions.
 * @param pageMetrics Page metrics.
 * @param encrypted {@code True} if this cache encrypted.
 * @return Cache store holder.
 * @throws IgniteCheckedException If failed.
 */
private CacheStoreHolder initDir(File cacheWorkDir, int grpId, int partitions, PageMetrics pageMetrics, boolean encrypted) throws IgniteCheckedException {
    try {
        boolean dirExisted = checkAndInitCacheWorkDir(cacheWorkDir);
        if (dirExisted) {
            MaintenanceRegistry mntcReg = cctx.kernalContext().maintenanceRegistry();
            if (!mntcReg.isMaintenanceMode())
                DefragmentationFileUtils.beforeInitPageStores(cacheWorkDir, log);
        }
        File idxFile = new File(cacheWorkDir, INDEX_FILE_NAME);
        if (dirExisted && !idxFile.exists())
            grpsWithoutIdx.add(grpId);
        FileVersionCheckingFactory pageStoreFactory = getPageStoreFactory(grpId, encrypted);
        PageStore idxStore = pageStoreFactory.createPageStore(PageStore.TYPE_IDX, idxFile, pageMetrics.totalPages()::add);
        PageStore[] partStores = new PageStore[partitions];
        for (int partId = 0; partId < partStores.length; partId++) {
            final int p = partId;
            PageStore partStore = pageStoreFactory.createPageStore(PageStore.TYPE_DATA, () -> getPartitionFilePath(cacheWorkDir, p), pageMetrics.totalPages()::add);
            partStores[partId] = partStore;
        }
        return new CacheStoreHolder(idxStore, partStores);
    } catch (IgniteCheckedException e) {
        if (X.hasCause(e, StorageException.class, IOException.class))
            cctx.kernalContext().failure().process(new FailureContext(FailureType.CRITICAL_ERROR, e));
        throw e;
    }
}
Also used : IgniteCheckedException(org.apache.ignite.IgniteCheckedException) FailureContext(org.apache.ignite.failure.FailureContext) MaintenanceRegistry(org.apache.ignite.maintenance.MaintenanceRegistry) PageStore(org.apache.ignite.internal.pagemem.store.PageStore) IOException(java.io.IOException) File(java.io.File) StorageException(org.apache.ignite.internal.processors.cache.persistence.StorageException)

Example 23 with PageStore

use of org.apache.ignite.internal.pagemem.store.PageStore in project ignite by apache.

the class FilePageStoreManager method beginRecover.

/**
 * {@inheritDoc}
 */
@Override
public void beginRecover() {
    List<String> groupsWithWalDisabled = checkCachesWithDisabledWal();
    if (!groupsWithWalDisabled.isEmpty()) {
        String errorMsg = "Cache groups with potentially corrupted partition files found. " + "To cleanup them maintenance is needed, node will enter maintenance mode on next restart. " + "Cleanup cache group folders manually or trigger maintenance action to do that and restart the node. " + "Corrupted files are located in subdirectories " + groupsWithWalDisabled + " in a work dir " + storeWorkDir;
        log.warning(errorMsg);
        try {
            cctx.kernalContext().maintenanceRegistry().registerMaintenanceTask(new MaintenanceTask(CORRUPTED_DATA_FILES_MNTC_TASK_NAME, "Corrupted cache groups found", groupsWithWalDisabled.stream().collect(Collectors.joining(File.separator))));
        } catch (IgniteCheckedException e) {
            log.warning("Failed to register maintenance record for corrupted partition files.", e);
        }
        throw new IgniteException(errorMsg);
    }
    for (CacheStoreHolder holder : idxCacheStores.values()) {
        holder.idxStore.beginRecover();
        for (PageStore partStore : holder.partStores) partStore.beginRecover();
    }
}
Also used : IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) PageStore(org.apache.ignite.internal.pagemem.store.PageStore) MaintenanceTask(org.apache.ignite.maintenance.MaintenanceTask)

Example 24 with PageStore

use of org.apache.ignite.internal.pagemem.store.PageStore 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 25 with PageStore

use of org.apache.ignite.internal.pagemem.store.PageStore in project ignite by apache.

the class CachePartitionDefragmentationManager method executeDefragmentation.

/**
 */
public void executeDefragmentation() throws IgniteCheckedException {
    Map<Integer, List<CacheDataStore>> oldStores = new HashMap<>();
    for (CacheGroupContext oldGrpCtx : cacheGrpCtxsForDefragmentation) {
        int grpId = oldGrpCtx.groupId();
        final IgniteCacheOffheapManager offheap = oldGrpCtx.offheap();
        List<CacheDataStore> oldCacheDataStores = stream(offheap.cacheDataStores().spliterator(), false).filter(store -> {
            try {
                return filePageStoreMgr.exists(grpId, store.partId());
            } catch (IgniteCheckedException e) {
                throw new IgniteException(e);
            }
        }).collect(Collectors.toList());
        oldStores.put(grpId, oldCacheDataStores);
    }
    int partitionCount = oldStores.values().stream().mapToInt(List::size).sum();
    status.onStart(cacheGrpCtxsForDefragmentation, partitionCount);
    try {
        // Now the actual process starts.
        IgniteInternalFuture<?> idxDfrgFut = null;
        DataPageEvictionMode prevPageEvictionMode = null;
        for (CacheGroupContext oldGrpCtx : cacheGrpCtxsForDefragmentation) {
            int grpId = oldGrpCtx.groupId();
            File workDir = filePageStoreMgr.cacheWorkDir(oldGrpCtx.sharedGroup(), oldGrpCtx.cacheOrGroupName());
            List<CacheDataStore> oldCacheDataStores = oldStores.get(grpId);
            if (skipAlreadyDefragmentedCacheGroup(workDir, grpId, log)) {
                status.onCacheGroupSkipped(oldGrpCtx, oldCacheDataStores.size());
                continue;
            }
            try {
                GridCacheOffheapManager offheap = (GridCacheOffheapManager) oldGrpCtx.offheap();
                status.onCacheGroupStart(oldGrpCtx, oldCacheDataStores.size());
                if (workDir == null || oldCacheDataStores.isEmpty()) {
                    status.onCacheGroupFinish(oldGrpCtx);
                    continue;
                }
                // We can't start defragmentation of new group on the region that has wrong eviction mode.
                // So waiting of the previous cache group defragmentation is inevitable.
                DataPageEvictionMode curPageEvictionMode = oldGrpCtx.dataRegion().config().getPageEvictionMode();
                if (prevPageEvictionMode == null || prevPageEvictionMode != curPageEvictionMode) {
                    prevPageEvictionMode = curPageEvictionMode;
                    partDataRegion.config().setPageEvictionMode(curPageEvictionMode);
                    if (idxDfrgFut != null)
                        idxDfrgFut.get();
                }
                IntMap<CacheDataStore> cacheDataStores = new IntHashMap<>();
                for (CacheDataStore store : offheap.cacheDataStores()) {
                    // This would mean that these partitions are empty.
                    assert store.tree() == null || store.tree().groupId() == grpId;
                    if (store.tree() != null)
                        cacheDataStores.put(store.partId(), store);
                }
                dbMgr.checkpointedDataRegions().remove(oldGrpCtx.dataRegion());
                // Another cheat. Ttl cleanup manager knows too much shit.
                oldGrpCtx.caches().stream().filter(cacheCtx -> cacheCtx.groupId() == grpId).forEach(cacheCtx -> cacheCtx.ttl().unregister());
                // Technically wal is already disabled, but "PageHandler.isWalDeltaRecordNeeded" doesn't care
                // and WAL records will be allocated anyway just to be ignored later if we don't disable WAL for
                // cache group explicitly.
                oldGrpCtx.localWalEnabled(false, false);
                boolean encrypted = oldGrpCtx.config().isEncryptionEnabled();
                FileVersionCheckingFactory pageStoreFactory = filePageStoreMgr.getPageStoreFactory(grpId, encrypted);
                AtomicLong idxAllocationTracker = new GridAtomicLong();
                createIndexPageStore(grpId, workDir, pageStoreFactory, partDataRegion, idxAllocationTracker::addAndGet);
                checkCancellation();
                GridCompoundFuture<Object, Object> cmpFut = new GridCompoundFuture<>();
                PageMemoryEx oldPageMem = (PageMemoryEx) oldGrpCtx.dataRegion().pageMemory();
                CacheGroupContext newGrpCtx = new CacheGroupContext(sharedCtx, grpId, oldGrpCtx.receivedFrom(), CacheType.USER, oldGrpCtx.config(), oldGrpCtx.affinityNode(), partDataRegion, oldGrpCtx.cacheObjectContext(), null, null, oldGrpCtx.localStartVersion(), true, false, true);
                defragmentationCheckpoint.checkpointTimeoutLock().checkpointReadLock();
                try {
                    // This will initialize partition meta in index partition - meta tree and reuse list.
                    newGrpCtx.start();
                } finally {
                    defragmentationCheckpoint.checkpointTimeoutLock().checkpointReadUnlock();
                }
                IgniteUtils.doInParallel(defragmentationThreadPool, oldCacheDataStores, oldCacheDataStore -> defragmentOnePartition(oldGrpCtx, grpId, workDir, offheap, pageStoreFactory, cmpFut, oldPageMem, newGrpCtx, oldCacheDataStore));
                // A bit too general for now, but I like it more then saving only the last checkpoint future.
                cmpFut.markInitialized().get();
                idxDfrgFut = new GridFinishedFuture<>();
                if (filePageStoreMgr.hasIndexStore(grpId)) {
                    defragmentIndexPartition(oldGrpCtx, newGrpCtx);
                    idxDfrgFut = defragmentationCheckpoint.forceCheckpoint("index defragmented", null).futureFor(FINISHED);
                }
                PageStore oldIdxPageStore = filePageStoreMgr.getStore(grpId, INDEX_PARTITION);
                idxDfrgFut = idxDfrgFut.chain(fut -> {
                    if (log.isDebugEnabled()) {
                        log.debug(S.toString("Index partition defragmented", "grpId", grpId, false, "oldPages", oldIdxPageStore.pages(), false, "newPages", idxAllocationTracker.get() + 1, false, "pageSize", pageSize, false, "partFile", defragmentedIndexFile(workDir).getName(), false, "workDir", workDir, false));
                    }
                    oldPageMem.invalidate(grpId, INDEX_PARTITION);
                    PageMemoryEx partPageMem = (PageMemoryEx) partDataRegion.pageMemory();
                    partPageMem.invalidate(grpId, INDEX_PARTITION);
                    DefragmentationPageReadWriteManager pageMgr = (DefragmentationPageReadWriteManager) partPageMem.pageManager();
                    pageMgr.pageStoreMap().removePageStore(grpId, INDEX_PARTITION);
                    PageMemoryEx mappingPageMem = (PageMemoryEx) mappingDataRegion.pageMemory();
                    pageMgr = (DefragmentationPageReadWriteManager) mappingPageMem.pageManager();
                    pageMgr.pageStoreMap().clear(grpId);
                    renameTempIndexFile(workDir);
                    writeDefragmentationCompletionMarker(filePageStoreMgr.getPageStoreFileIoFactory(), workDir, log);
                    batchRenameDefragmentedCacheGroupPartitions(workDir, log);
                    return null;
                });
                status.onIndexDefragmented(oldGrpCtx, oldIdxPageStore.size(), // + file header.
                pageSize + idxAllocationTracker.get() * pageSize);
            } catch (DefragmentationCancelledException e) {
                DefragmentationFileUtils.deleteLeftovers(workDir);
                throw e;
            }
            status.onCacheGroupFinish(oldGrpCtx);
        }
        if (idxDfrgFut != null)
            idxDfrgFut.get();
        mntcReg.unregisterMaintenanceTask(DEFRAGMENTATION_MNTC_TASK_NAME);
        status.onFinish();
        completionFut.onDone();
    } catch (DefragmentationCancelledException e) {
        mntcReg.unregisterMaintenanceTask(DEFRAGMENTATION_MNTC_TASK_NAME);
        log.info("Defragmentation process has been cancelled.");
        status.onFinish();
        completionFut.onDone();
    } catch (Throwable t) {
        log.error("Defragmentation process failed.", t);
        status.onFinish();
        completionFut.onDone(t);
        throw t;
    } finally {
        defragmentationCheckpoint.stop(true);
    }
}
Also used : IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) Arrays(java.util.Arrays) PageStore(org.apache.ignite.internal.pagemem.store.PageStore) CacheType(org.apache.ignite.internal.processors.cache.CacheType) DataRegion(org.apache.ignite.internal.processors.cache.persistence.DataRegion) GridFutureAdapter(org.apache.ignite.internal.util.future.GridFutureAdapter) GridFinishedFuture(org.apache.ignite.internal.util.future.GridFinishedFuture) FLAG_DATA(org.apache.ignite.internal.pagemem.PageIdAllocator.FLAG_DATA) IntMap(org.apache.ignite.internal.util.collection.IntMap) DEFRAGMENTATION_MAPPING_REGION_NAME(org.apache.ignite.internal.processors.cache.persistence.GridCacheDatabaseSharedManager.DEFRAGMENTATION_MAPPING_REGION_NAME) DEFRAGMENTATION_PART_REGION_NAME(org.apache.ignite.internal.processors.cache.persistence.GridCacheDatabaseSharedManager.DEFRAGMENTATION_PART_REGION_NAME) DefragmentationFileUtils.defragmentedPartMappingFile(org.apache.ignite.internal.processors.cache.persistence.defragmentation.DefragmentationFileUtils.defragmentedPartMappingFile) CacheDataStore(org.apache.ignite.internal.processors.cache.IgniteCacheOffheapManager.CacheDataStore) CheckpointTimeoutLock(org.apache.ignite.internal.processors.cache.persistence.checkpoint.CheckpointTimeoutLock) DefragmentationFileUtils.defragmentedPartFile(org.apache.ignite.internal.processors.cache.persistence.defragmentation.DefragmentationFileUtils.defragmentedPartFile) LightweightCheckpointManager(org.apache.ignite.internal.processors.cache.persistence.checkpoint.LightweightCheckpointManager) PagePartitionMetaIO(org.apache.ignite.internal.processors.cache.persistence.tree.io.PagePartitionMetaIO) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MaintenanceRegistry(org.apache.ignite.maintenance.MaintenanceRegistry) Map(java.util.Map) Path(java.nio.file.Path) AbstractFreeList(org.apache.ignite.internal.processors.cache.persistence.freelist.AbstractFreeList) IndexProcessor(org.apache.ignite.internal.cache.query.index.IndexProcessor) DataRow(org.apache.ignite.internal.processors.cache.tree.DataRow) IgniteInClosure(org.apache.ignite.lang.IgniteInClosure) IgniteOutClosure(org.apache.ignite.lang.IgniteOutClosure) DefragmentationFileUtils.skipAlreadyDefragmentedPartition(org.apache.ignite.internal.processors.cache.persistence.defragmentation.DefragmentationFileUtils.skipAlreadyDefragmentedPartition) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) Set(java.util.Set) PendingRow(org.apache.ignite.internal.processors.cache.tree.PendingRow) FilePageStoreManager(org.apache.ignite.internal.processors.cache.persistence.file.FilePageStoreManager) CacheDataRow(org.apache.ignite.internal.processors.cache.persistence.CacheDataRow) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Collectors(java.util.stream.Collectors) IgniteCacheOffheapManager(org.apache.ignite.internal.processors.cache.IgniteCacheOffheapManager) INDEX_PARTITION(org.apache.ignite.internal.pagemem.PageIdAllocator.INDEX_PARTITION) IntRWHashMap(org.apache.ignite.internal.util.collection.IntRWHashMap) List(java.util.List) GridCacheDataStore(org.apache.ignite.internal.processors.cache.persistence.GridCacheOffheapManager.GridCacheDataStore) StreamSupport.stream(java.util.stream.StreamSupport.stream) PageIdUtils(org.apache.ignite.internal.pagemem.PageIdUtils) CU(org.apache.ignite.internal.util.typedef.internal.CU) PagePartitionMetaIOV3(org.apache.ignite.internal.processors.cache.persistence.tree.io.PagePartitionMetaIOV3) IntHashMap(org.apache.ignite.internal.util.collection.IntHashMap) FLAG_IDX(org.apache.ignite.internal.pagemem.PageIdAllocator.FLAG_IDX) GridAtomicLong(org.apache.ignite.internal.util.GridAtomicLong) SimpleDataRow(org.apache.ignite.internal.processors.cache.persistence.freelist.SimpleDataRow) DefragmentationFileUtils.defragmentedIndexTmpFile(org.apache.ignite.internal.processors.cache.persistence.defragmentation.DefragmentationFileUtils.defragmentedIndexTmpFile) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) GridCompoundFuture(org.apache.ignite.internal.util.future.GridCompoundFuture) U(org.apache.ignite.internal.util.typedef.internal.U) HashMap(java.util.HashMap) IgniteLogger(org.apache.ignite.IgniteLogger) CacheGroupContext(org.apache.ignite.internal.processors.cache.CacheGroupContext) TreeSet(java.util.TreeSet) HashSet(java.util.HashSet) DefragmentationFileUtils.renameTempIndexFile(org.apache.ignite.internal.processors.cache.persistence.defragmentation.DefragmentationFileUtils.renameTempIndexFile) GridCacheDatabaseSharedManager(org.apache.ignite.internal.processors.cache.persistence.GridCacheDatabaseSharedManager) GridCacheOffheapManager(org.apache.ignite.internal.processors.cache.persistence.GridCacheOffheapManager) CheckpointManager(org.apache.ignite.internal.processors.cache.persistence.checkpoint.CheckpointManager) DefragmentationFileUtils.writeDefragmentationCompletionMarker(org.apache.ignite.internal.processors.cache.persistence.defragmentation.DefragmentationFileUtils.writeDefragmentationCompletionMarker) DefragmentationFileUtils.skipAlreadyDefragmentedCacheGroup(org.apache.ignite.internal.processors.cache.persistence.defragmentation.DefragmentationFileUtils.skipAlreadyDefragmentedCacheGroup) IgniteUtils(org.apache.ignite.internal.util.IgniteUtils) S(org.apache.ignite.internal.util.typedef.internal.S) DefragmentationFileUtils.renameTempPartitionFile(org.apache.ignite.internal.processors.cache.persistence.defragmentation.DefragmentationFileUtils.renameTempPartitionFile) PageIO(org.apache.ignite.internal.processors.cache.persistence.tree.io.PageIO) IgniteThreadPoolExecutor(org.apache.ignite.thread.IgniteThreadPoolExecutor) Comparator.comparing(java.util.Comparator.comparing) CacheDataTree(org.apache.ignite.internal.processors.cache.tree.CacheDataTree) AbstractDataLeafIO(org.apache.ignite.internal.processors.cache.tree.AbstractDataLeafIO) FINISHED(org.apache.ignite.internal.processors.cache.persistence.CheckpointState.FINISHED) PendingEntriesTree(org.apache.ignite.internal.processors.cache.tree.PendingEntriesTree) DefragmentationFileUtils.defragmentedPartTmpFile(org.apache.ignite.internal.processors.cache.persistence.defragmentation.DefragmentationFileUtils.defragmentedPartTmpFile) DefragmentationFileUtils.defragmentedIndexFile(org.apache.ignite.internal.processors.cache.persistence.defragmentation.DefragmentationFileUtils.defragmentedIndexFile) IoStatisticsHolderNoOp(org.apache.ignite.internal.metric.IoStatisticsHolderNoOp) DataPageEvictionMode(org.apache.ignite.configuration.DataPageEvictionMode) DefragmentationFileUtils.batchRenameDefragmentedCacheGroupPartitions(org.apache.ignite.internal.processors.cache.persistence.defragmentation.DefragmentationFileUtils.batchRenameDefragmentedCacheGroupPartitions) FileVersionCheckingFactory(org.apache.ignite.internal.processors.cache.persistence.file.FileVersionCheckingFactory) File(java.io.File) LongConsumer(java.util.function.LongConsumer) AtomicLong(java.util.concurrent.atomic.AtomicLong) GridCacheSharedContext(org.apache.ignite.internal.processors.cache.GridCacheSharedContext) TreeMap(java.util.TreeMap) PageMemoryEx(org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMemoryEx) GridQueryProcessor(org.apache.ignite.internal.processors.query.GridQueryProcessor) IntRWHashMap(org.apache.ignite.internal.util.collection.IntRWHashMap) IntHashMap(org.apache.ignite.internal.util.collection.IntHashMap) HashMap(java.util.HashMap) GridCacheOffheapManager(org.apache.ignite.internal.processors.cache.persistence.GridCacheOffheapManager) PageStore(org.apache.ignite.internal.pagemem.store.PageStore) GridCompoundFuture(org.apache.ignite.internal.util.future.GridCompoundFuture) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) FileVersionCheckingFactory(org.apache.ignite.internal.processors.cache.persistence.file.FileVersionCheckingFactory) IgniteException(org.apache.ignite.IgniteException) AbstractFreeList(org.apache.ignite.internal.processors.cache.persistence.freelist.AbstractFreeList) List(java.util.List) DataPageEvictionMode(org.apache.ignite.configuration.DataPageEvictionMode) GridAtomicLong(org.apache.ignite.internal.util.GridAtomicLong) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IntHashMap(org.apache.ignite.internal.util.collection.IntHashMap) GridAtomicLong(org.apache.ignite.internal.util.GridAtomicLong) AtomicLong(java.util.concurrent.atomic.AtomicLong) CacheDataStore(org.apache.ignite.internal.processors.cache.IgniteCacheOffheapManager.CacheDataStore) GridCacheDataStore(org.apache.ignite.internal.processors.cache.persistence.GridCacheOffheapManager.GridCacheDataStore) IgniteCacheOffheapManager(org.apache.ignite.internal.processors.cache.IgniteCacheOffheapManager) PageMemoryEx(org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMemoryEx) CacheGroupContext(org.apache.ignite.internal.processors.cache.CacheGroupContext) DefragmentationFileUtils.defragmentedPartMappingFile(org.apache.ignite.internal.processors.cache.persistence.defragmentation.DefragmentationFileUtils.defragmentedPartMappingFile) DefragmentationFileUtils.defragmentedPartFile(org.apache.ignite.internal.processors.cache.persistence.defragmentation.DefragmentationFileUtils.defragmentedPartFile) DefragmentationFileUtils.defragmentedIndexTmpFile(org.apache.ignite.internal.processors.cache.persistence.defragmentation.DefragmentationFileUtils.defragmentedIndexTmpFile) DefragmentationFileUtils.renameTempIndexFile(org.apache.ignite.internal.processors.cache.persistence.defragmentation.DefragmentationFileUtils.renameTempIndexFile) DefragmentationFileUtils.renameTempPartitionFile(org.apache.ignite.internal.processors.cache.persistence.defragmentation.DefragmentationFileUtils.renameTempPartitionFile) DefragmentationFileUtils.defragmentedPartTmpFile(org.apache.ignite.internal.processors.cache.persistence.defragmentation.DefragmentationFileUtils.defragmentedPartTmpFile) DefragmentationFileUtils.defragmentedIndexFile(org.apache.ignite.internal.processors.cache.persistence.defragmentation.DefragmentationFileUtils.defragmentedIndexFile) File(java.io.File)

Aggregations

PageStore (org.apache.ignite.internal.pagemem.store.PageStore)27 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)10 FilePageStoreManager (org.apache.ignite.internal.processors.cache.persistence.file.FilePageStoreManager)9 PageMemoryEx (org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMemoryEx)9 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)6 IgniteException (org.apache.ignite.IgniteException)6 ArrayList (java.util.ArrayList)5 HashSet (java.util.HashSet)5 List (java.util.List)5 Map (java.util.Map)5 GridCacheSharedContext (org.apache.ignite.internal.processors.cache.GridCacheSharedContext)5 GridCacheDatabaseSharedManager (org.apache.ignite.internal.processors.cache.persistence.GridCacheDatabaseSharedManager)5 PageIO (org.apache.ignite.internal.processors.cache.persistence.tree.io.PageIO)5 File (java.io.File)4 ByteBuffer (java.nio.ByteBuffer)4 HashMap (java.util.HashMap)4 Set (java.util.Set)4 FailureContext (org.apache.ignite.failure.FailureContext)4 IgniteInternalFuture (org.apache.ignite.internal.IgniteInternalFuture)4 FullPageId (org.apache.ignite.internal.pagemem.FullPageId)4