xtern commented on a change in pull request #7941:
URL: https://github.com/apache/ignite/pull/7941#discussion_r478320474



##########
File path: 
modules/core/src/main/java/org/apache/ignite/internal/managers/encryption/CacheGroupPageScanner.java
##########
@@ -0,0 +1,453 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.managers.encryption;
+
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.locks.ReentrantLock;
+import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.IgniteLogger;
+import org.apache.ignite.configuration.DataStorageConfiguration;
+import org.apache.ignite.configuration.EncryptionConfiguration;
+import org.apache.ignite.internal.GridKernalContext;
+import org.apache.ignite.internal.IgniteInternalFuture;
+import org.apache.ignite.internal.NodeStoppingException;
+import org.apache.ignite.internal.pagemem.PageIdAllocator;
+import org.apache.ignite.internal.pagemem.PageIdUtils;
+import org.apache.ignite.internal.pagemem.store.IgnitePageStoreManager;
+import org.apache.ignite.internal.processors.cache.CacheGroupContext;
+import 
org.apache.ignite.internal.processors.cache.persistence.DbCheckpointListener;
+import 
org.apache.ignite.internal.processors.cache.persistence.GridCacheDatabaseSharedManager;
+import 
org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMemoryEx;
+import 
org.apache.ignite.internal.processors.cache.persistence.partstate.GroupPartitionId;
+import org.apache.ignite.internal.util.BasicRateLimiter;
+import org.apache.ignite.internal.util.GridConcurrentHashSet;
+import org.apache.ignite.internal.util.future.GridFinishedFuture;
+import org.apache.ignite.internal.util.future.GridFutureAdapter;
+import org.apache.ignite.internal.util.lang.IgniteInClosureX;
+import org.apache.ignite.internal.util.typedef.X;
+import org.apache.ignite.internal.util.typedef.internal.CU;
+
+import static org.apache.ignite.internal.util.IgniteUtils.MB;
+
+/**
+ * Cache group page stores scanner.
+ * Scans a range of pages and marks them as dirty to re-encrypt them with the 
last encryption key on disk.
+ */
+public class CacheGroupPageScanner implements DbCheckpointListener {
+    /** Encryption configuration. */
+    private final EncryptionConfiguration encrCfg;
+
+    /** Kernal context. */
+    private final GridKernalContext ctx;
+
+    /** Logger. */
+    private final IgniteLogger log;
+
+    /** Lock. */
+    private final ReentrantLock lock = new ReentrantLock();
+
+    /** Mapping of cache group ID to group scanning task. */
+    private final Map<Integer, GroupScanTask> grps = new ConcurrentHashMap<>();
+
+    /** Collection of groups waiting for a checkpoint. */
+    private final Collection<GroupScanTask> cpWaitGrps = new 
ConcurrentLinkedQueue<>();
+
+    /** Page scanning speed limiter. */
+    private final BasicRateLimiter limiter;
+
+    /** Stop flag. */
+    private boolean stopped;
+
+    /**
+     * @param ctx Grid kernal context.
+     */
+    public CacheGroupPageScanner(GridKernalContext ctx) {
+        this.ctx = ctx;
+
+        log = ctx.log(getClass());
+
+        encrCfg = 
ctx.config().getDataStorageConfiguration().getEncryptionConfiguration();
+
+        DataStorageConfiguration dsCfg = 
ctx.config().getDataStorageConfiguration();
+
+        limiter = CU.isPersistenceEnabled(dsCfg) && 
encrCfg.getReencryptionRateLimit() > 0 ?
+            new BasicRateLimiter(encrCfg.getReencryptionRateLimit() * MB / 
dsCfg.getPageSize()) : null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void onCheckpointBegin(Context cpCtx) {
+        Set<GroupScanTask> completeCandidates = new HashSet<>();
+
+        cpWaitGrps.removeIf(completeCandidates::add);
+
+        cpCtx.finishedStateFut().listen(
+            f -> {
+                // Retry if error occurs.
+                if (f.error() != null || f.isCancelled()) {
+                    cpWaitGrps.addAll(completeCandidates);
+
+                    return;
+                }
+
+                lock.lock();
+
+                try {
+                    for (GroupScanTask grpScanTask : completeCandidates) {
+                        grps.remove(grpScanTask.groupId());
+
+                        grpScanTask.onDone();
+
+                        if (log.isInfoEnabled())
+                            log.info("Cache group reencryption is finished 
[grpId=" + grpScanTask.groupId() + "]");
+                    }
+
+                    if (!grps.isEmpty())
+                        return;
+
+                    
((GridCacheDatabaseSharedManager)ctx.cache().context().database()).
+                        removeCheckpointListener(this);
+                }
+                finally {
+                    lock.unlock();
+                }
+            }
+        );
+    }
+
+    /** {@inheritDoc} */
+    @Override public void beforeCheckpointBegin(Context cpCtx) {
+        // No-op.
+    }
+
+    /** {@inheritDoc} */
+    @Override public void onMarkCheckpointBegin(Context ctx) {
+        // No-op.
+    }
+
+    /**
+     * @return {@code True} If reencryption is disabled.
+     */
+    public boolean disabled() {
+        return encrCfg.isReencryptionDisabled();
+    }
+
+    /**
+     * Schedule scanning partitions.
+     *
+     * @param grpId Cache group ID.
+     */
+    public IgniteInternalFuture<Void> schedule(int grpId) throws 
IgniteCheckedException {
+        if (disabled())
+            throw new IgniteCheckedException("Reencryption is disabled.");
+
+        CacheGroupContext grp = ctx.cache().cacheGroup(grpId);
+
+        if (grp == null) {
+            if (log.isDebugEnabled())
+                log.debug("Skip reencryption, cache group was destroyed [grp=" 
+ grpId + "]");
+
+            return new GridFinishedFuture<>();
+        }
+
+        lock.lock();
+
+        try {
+            if (stopped)
+                throw new NodeStoppingException("Operation has been cancelled 
(node is stopping).");
+
+            if (grps.isEmpty())
+                
((GridCacheDatabaseSharedManager)ctx.cache().context().database()).addCheckpointListener(this);
+
+            GroupScanTask prevState = grps.get(grpId);
+
+            if (prevState != null) {
+                if (log.isDebugEnabled())
+                    log.debug("Reencryption already scheduled [grpId=" + grpId 
+ "]");
+
+                return prevState;
+            }
+
+            Set<Integer> parts = new HashSet<>();
+
+            forEachPageStore(grp, new IgniteInClosureX<Integer>() {
+                @Override public void applyx(Integer partId) {
+                    if (ctx.encryption().getEncryptionState(grpId, partId) == 
0) {
+                        if (log.isDebugEnabled())
+                            log.debug("Skipping partition reencryption [grp=" 
+ grpId + ", p=" + partId + "]");
+
+                        return;
+                    }
+
+                    parts.add(partId);
+                }
+            });
+
+            GroupScanTask grpScan = new GroupScanTask(grp, parts);
+
+            ctx.getSystemExecutorService().submit(grpScan);
+
+            if (log.isInfoEnabled())
+                log.info("Scheduled reencryption [grpId=" + grpId + "]");
+
+            grps.put(grpId, grpScan);
+
+            return grpScan;
+        }
+        finally {
+            lock.unlock();
+        }
+    }
+
+    /**
+     * @param grpId Cache group ID.
+     * @return Future that will be completed when all partitions have been 
scanned and pages have been written to disk.
+     */
+    public IgniteInternalFuture<Void> statusFuture(int grpId) {
+        GroupScanTask ctx0 = grps.get(grpId);
+
+        return ctx0 == null ? new GridFinishedFuture<>() : ctx0;
+    }
+
+    /**
+     * Shutdown scanning and disable new tasks scheduling.
+     */
+    public void stop() throws IgniteCheckedException {
+        lock.lock();
+
+        try {
+            stopped = true;
+
+            for (GroupScanTask grpScanTask : grps.values())
+                grpScanTask.cancel();
+        } finally {
+            lock.unlock();
+        }
+    }
+
+    /**
+     * Stop scannig the specified partition.
+     *
+     * @param grpId Cache group ID.
+     * @param partId Partition ID.
+     * @return {@code True} if reencryption was cancelled.
+     */
+    public boolean cancel(int grpId, int partId) {
+        GroupScanTask grpScanTask = grps.get(grpId);
+
+        if (grpScanTask == null)
+            return false;
+
+        return grpScanTask.cancel(partId);
+    }
+
+    /**
+     * Collect current number of pages in the specified cache group.
+     *
+     * @param grp Cache group.
+     * @return Partitions with current page count.
+     * @throws IgniteCheckedException If failed.
+     */
+    public long[] pagesCount(CacheGroupContext grp) throws 
IgniteCheckedException {
+        long[] partStates = new long[grp.affinity().partitions() + 1];

Review comment:
       added `// The last element of the array is used to store the status of 
the index partition.`




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
[email protected]


Reply via email to