You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ignite.apache.org by ni...@apache.org on 2023/12/08 11:28:55 UTC
(ignite) branch master updated: IGNITE-21013 Support encryption of cache dumps (#11078)
This is an automated email from the ASF dual-hosted git repository.
nizhikov pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/ignite.git
The following commit(s) were added to refs/heads/master by this push:
new 668939affae IGNITE-21013 Support encryption of cache dumps (#11078)
668939affae is described below
commit 668939affaeced34b59f0aa95bedd53f3a5bfe6a
Author: Nikolay <ni...@apache.org>
AuthorDate: Fri Dec 8 14:28:45 2023 +0300
IGNITE-21013 Support encryption of cache dumps (#11078)
---
.../java/org/apache/ignite/dump/DumpReader.java | 19 +-
.../ignite/dump/DumpReaderConfiguration.java | 19 +-
.../snapshot/IgniteSnapshotManager.java | 50 ++++-
.../persistence/snapshot/SnapshotMetadata.java | 14 +-
.../snapshot/SnapshotOperationRequest.java | 13 +-
.../snapshot/SnapshotPartitionsVerifyHandler.java | 5 +-
.../snapshot/SnapshotRestoreProcess.java | 1 +
.../snapshot/dump/CreateDumpFutureTask.java | 35 +++-
.../cache/persistence/snapshot/dump/Dump.java | 43 +++-
.../snapshot/dump/DumpEntrySerializer.java | 220 ++++++++++++++++-----
.../snapshot/AbstractSnapshotSelfTest.java | 1 +
.../snapshot/EncryptedSnapshotTest.java | 1 +
.../snapshot/IgniteSnapshotManagerSelfTest.java | 1 +
.../snapshot/dump/AbstractCacheDumpTest.java | 37 +++-
.../snapshot/dump/IgniteCacheDumpSelf2Test.java | 137 ++++++++++++-
.../dump/IgniteConcurrentCacheDumpTest.java | 13 +-
16 files changed, 516 insertions(+), 93 deletions(-)
diff --git a/modules/core/src/main/java/org/apache/ignite/dump/DumpReader.java b/modules/core/src/main/java/org/apache/ignite/dump/DumpReader.java
index d2ed811ac3f..bb6f8cfb405 100644
--- a/modules/core/src/main/java/org/apache/ignite/dump/DumpReader.java
+++ b/modules/core/src/main/java/org/apache/ignite/dump/DumpReader.java
@@ -41,6 +41,8 @@ import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.internal.CU;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteExperimental;
+import org.apache.ignite.spi.IgniteSpiAdapter;
+import org.apache.ignite.spi.encryption.EncryptionSpi;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.apache.ignite.configuration.DataStorageConfiguration.DFLT_MARSHALLER_PATH;
@@ -75,7 +77,7 @@ public class DumpReader implements Runnable {
@Override public void run() {
ackAsciiLogo();
- try (Dump dump = new Dump(cfg.dumpRoot(), cfg.keepBinary(), false, log)) {
+ try (Dump dump = new Dump(cfg.dumpRoot(), null, cfg.keepBinary(), false, encryptionSpi(), log)) {
DumpConsumer cnsmr = cfg.consumer();
cnsmr.start();
@@ -231,4 +233,19 @@ public class DumpReader implements Runnable {
"");
}
}
+
+ /** */
+ private EncryptionSpi encryptionSpi() {
+ EncryptionSpi encSpi = cfg.encryptionSpi();
+
+ if (encSpi == null)
+ return null;
+
+ if (encSpi instanceof IgniteSpiAdapter)
+ ((IgniteSpiAdapter)encSpi).onBeforeStart();
+
+ encSpi.spiStart("dump-reader");
+
+ return encSpi;
+ }
}
diff --git a/modules/core/src/main/java/org/apache/ignite/dump/DumpReaderConfiguration.java b/modules/core/src/main/java/org/apache/ignite/dump/DumpReaderConfiguration.java
index a7a80b8227f..619c532b1ff 100644
--- a/modules/core/src/main/java/org/apache/ignite/dump/DumpReaderConfiguration.java
+++ b/modules/core/src/main/java/org/apache/ignite/dump/DumpReaderConfiguration.java
@@ -22,6 +22,7 @@ import java.time.Duration;
import org.apache.ignite.internal.processors.cache.CacheObject;
import org.apache.ignite.internal.processors.cache.KeyCacheObject;
import org.apache.ignite.lang.IgniteExperimental;
+import org.apache.ignite.spi.encryption.EncryptionSpi;
/**
* Configuration class of {@link DumpReader}.
@@ -61,12 +62,15 @@ public class DumpReaderConfiguration {
/** Skip copies. */
private final boolean skipCopies;
+ /** Encryption SPI. */
+ private final EncryptionSpi encSpi;
+
/**
* @param dir Root dump directory.
* @param cnsmr Dump consumer.
*/
public DumpReaderConfiguration(File dir, DumpConsumer cnsmr) {
- this(dir, cnsmr, DFLT_THREAD_CNT, DFLT_TIMEOUT, true, true, null, false);
+ this(dir, cnsmr, DFLT_THREAD_CNT, DFLT_TIMEOUT, true, true, null, false, null);
}
/**
@@ -78,15 +82,18 @@ public class DumpReaderConfiguration {
* @param keepBinary If {@code true} then don't deserialize {@link KeyCacheObject} and {@link CacheObject}.
* @param cacheGroupNames Cache group names.
* @param skipCopies Skip copies.
+ * @param encSpi Encryption SPI.
*/
- public DumpReaderConfiguration(File dir,
+ public DumpReaderConfiguration(
+ File dir,
DumpConsumer cnsmr,
int thCnt,
Duration timeout,
boolean failFast,
boolean keepBinary,
String[] cacheGroupNames,
- boolean skipCopies
+ boolean skipCopies,
+ EncryptionSpi encSpi
) {
this.dir = dir;
this.cnsmr = cnsmr;
@@ -96,6 +103,7 @@ public class DumpReaderConfiguration {
this.keepBinary = keepBinary;
this.cacheGroupNames = cacheGroupNames;
this.skipCopies = skipCopies;
+ this.encSpi = encSpi;
}
/** @return Root dump directiory. */
@@ -137,4 +145,9 @@ public class DumpReaderConfiguration {
public boolean skipCopies() {
return skipCopies;
}
+
+ /** @return Encryption SPI */
+ public EncryptionSpi encryptionSpi() {
+ return encSpi;
+ }
}
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/IgniteSnapshotManager.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/IgniteSnapshotManager.java
index 4890ab85b57..e6f3fb635e6 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/IgniteSnapshotManager.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/IgniteSnapshotManager.java
@@ -1194,6 +1194,7 @@ public class IgniteSnapshotManager extends GridCacheSharedManagerAdapter
withMetaStorage,
req.dump(),
req.compress(),
+ req.encrypt(),
locSndrFactory.apply(req.snapshotName(), req.snapshotPath())
);
@@ -1218,6 +1219,10 @@ public class IgniteSnapshotManager extends GridCacheSharedManagerAdapter
SnapshotFutureTaskResult res = (SnapshotFutureTaskResult)task0.result();
+ Serializable encKey = req.encrypt() ? ((CreateDumpFutureTask)task0).encryptionKey() : null;
+
+ EncryptionSpi encSpi = cctx.gridConfig().getEncryptionSpi();
+
SnapshotMetadata meta = new SnapshotMetadata(req.requestId(),
req.snapshotName(),
cctx.localNode().consistentId().toString(),
@@ -1229,9 +1234,10 @@ public class IgniteSnapshotManager extends GridCacheSharedManagerAdapter
blts,
res.parts(),
res.snapshotPointer(),
- cctx.gridConfig().getEncryptionSpi().masterKeyDigest(),
+ encSpi.masterKeyDigest(),
req.onlyPrimary(),
- req.dump()
+ req.dump(),
+ encKey == null ? null : encSpi.encryptKey(encKey)
);
SnapshotHandlerContext ctx = new SnapshotHandlerContext(meta, req.groups(), cctx.localNode(), snpDir,
@@ -1808,7 +1814,7 @@ public class IgniteSnapshotManager extends GridCacheSharedManagerAdapter
/** {@inheritDoc} */
@Override public IgniteFuture<Void> createDump(String name, @Nullable Collection<String> cacheGroupNames) {
- return createSnapshot(name, null, cacheGroupNames, false, false, true, false);
+ return createSnapshot(name, null, cacheGroupNames, false, false, true, false, false);
}
/**
@@ -2196,11 +2202,16 @@ public class IgniteSnapshotManager extends GridCacheSharedManagerAdapter
boolean incremental,
boolean onlyPrimary
) {
- return createSnapshot(name, snpPath, null, incremental, onlyPrimary, false, false);
+ return createSnapshot(name, snpPath, null, incremental, onlyPrimary, false, false, false);
}
/**
* Create a consistent copy of all persistence cache groups from the whole cluster.
+ * Note, {@code encrypt} flag can be used only for cache dump.
+ * Full snapshots store partition files itself.
+ * So if cache is encrypted ({@link CacheConfiguration#isEncryptionEnabled()}{@code = true}) then snapshot files will be encrypted.
+ * On the other hand, dumps stores only entry data and can be used fo in-memory caches.
+ * So we provide an ability to encrypt dump content to protect data on the disk.
*
* @param name Snapshot unique name which satisfies the following name pattern [a-zA-Z0-9_].
* @param snpPath Snapshot directory path.
@@ -2209,6 +2220,7 @@ public class IgniteSnapshotManager extends GridCacheSharedManagerAdapter
* @param onlyPrimary If {@code true} snapshot only primary copies of partitions.
* @param dump If {@code true} cache dump must be created.
* @param compress If {@code true} then compress partition files.
+ * @param encrypt If {@code true} then content of dump encrypted.
* @return Future which will be completed when a process ends.
*/
public IgniteFutureImpl<Void> createSnapshot(
@@ -2218,7 +2230,8 @@ public class IgniteSnapshotManager extends GridCacheSharedManagerAdapter
boolean incremental,
boolean onlyPrimary,
boolean dump,
- boolean compress
+ boolean compress,
+ boolean encrypt
) {
A.notNullOrEmpty(name, "Snapshot name cannot be null or empty.");
A.ensure(U.alphanumericUnderscore(name), "Snapshot name must satisfy the following name pattern: a-zA-Z0-9_");
@@ -2250,11 +2263,17 @@ public class IgniteSnapshotManager extends GridCacheSharedManagerAdapter
return new IgniteSnapshotFutureImpl(cctx.kernalContext().closure()
.callAsync(
BALANCE,
- new CreateSnapshotCallable(name, cacheGroupNames, incremental, onlyPrimary, dump, compress),
+ new CreateSnapshotCallable(name, cacheGroupNames, incremental, onlyPrimary, dump, compress, encrypt),
options(Collections.singletonList(crd)).withFailoverDisabled()
));
}
+ A.ensure(!encrypt || dump, "Encryption key is supported only for dumps");
+ A.ensure(
+ !encrypt || cctx.gridConfig().getEncryptionSpi() != null,
+ "Encryption SPI must be set to encrypt dump"
+ );
+
if (!CU.isPersistenceEnabled(cctx.gridConfig()) && !dump) {
throw new IgniteException("Create snapshot request has been rejected. " +
"Snapshots on an in-memory clusters are not allowed.");
@@ -2353,7 +2372,8 @@ public class IgniteSnapshotManager extends GridCacheSharedManagerAdapter
incIdx,
onlyPrimary,
dump,
- compress
+ compress,
+ encrypt
));
String msg =
@@ -2733,6 +2753,7 @@ public class IgniteSnapshotManager extends GridCacheSharedManagerAdapter
* @param withMetaStorage {@code true} if all metastorage data must be also included into snapshot.
* @param dump {@code true} if cache group dump must be created.
* @param compress If {@code true} then compress partition files.
+ * @param encrypt If {@code true} then content of dump encrypted.
* @param snpSndr Factory which produces snapshot receiver instance.
* @return Snapshot operation task which should be registered on checkpoint to run.
*/
@@ -2745,6 +2766,7 @@ public class IgniteSnapshotManager extends GridCacheSharedManagerAdapter
boolean withMetaStorage,
boolean dump,
boolean compress,
+ boolean encrypt,
SnapshotSender snpSndr
) {
AbstractSnapshotFutureTask<?> task = registerTask(snpName, dump
@@ -2757,7 +2779,8 @@ public class IgniteSnapshotManager extends GridCacheSharedManagerAdapter
transferRateLimiter,
snpSndr,
parts,
- compress
+ compress,
+ encrypt
)
: new SnapshotFutureTask(cctx, srcNodeId, requestId, snpName, tmpWorkDir, ioFactory, snpSndr, parts, withMetaStorage, locBuff));
@@ -4681,6 +4704,9 @@ public class IgniteSnapshotManager extends GridCacheSharedManagerAdapter
/** If {@code true} then compress partition files. */
private final boolean comprParts;
+ /** If {@code true} then content of dump encrypted. */
+ private final boolean encrypt;
+
/** Auto-injected grid instance. */
@IgniteInstanceResource
private transient IgniteEx ignite;
@@ -4692,6 +4718,7 @@ public class IgniteSnapshotManager extends GridCacheSharedManagerAdapter
* @param onlyPrimary If {@code true} then only copy of primary partitions will be created.
* @param dump If {@code true} then cache dump must be created.
* @param comprParts If {@code true} then compress partition files.
+ * @param encrypt If {@code true} then content of dump encrypted.
*/
public CreateSnapshotCallable(
String snpName,
@@ -4699,7 +4726,8 @@ public class IgniteSnapshotManager extends GridCacheSharedManagerAdapter
boolean incremental,
boolean onlyPrimary,
boolean dump,
- boolean comprParts
+ boolean comprParts,
+ boolean encrypt
) {
this.snpName = snpName;
this.cacheGroupNames = cacheGroupNames;
@@ -4707,6 +4735,7 @@ public class IgniteSnapshotManager extends GridCacheSharedManagerAdapter
this.onlyPrimary = onlyPrimary;
this.dump = dump;
this.comprParts = comprParts;
+ this.encrypt = encrypt;
}
/** {@inheritDoc} */
@@ -4721,7 +4750,8 @@ public class IgniteSnapshotManager extends GridCacheSharedManagerAdapter
false,
onlyPrimary,
dump,
- comprParts
+ comprParts,
+ encrypt
).get();
}
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/SnapshotMetadata.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/SnapshotMetadata.java
index 4bb26d0dc39..c57f46276da 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/SnapshotMetadata.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/SnapshotMetadata.java
@@ -111,6 +111,9 @@ public class SnapshotMetadata implements Serializable {
/** If {@code true} cache group dump stored. */
private boolean dump;
+ /** Encryption key. */
+ private @Nullable byte[] encKey;
+
/**
* @param rqId Unique request id.
* @param snpName Snapshot name.
@@ -124,6 +127,7 @@ public class SnapshotMetadata implements Serializable {
* @param masterKeyDigest Master key digest for encrypted caches.
* @param onlyPrimary If {@code true} snapshot only primary copies of partitions.
* @param dump If {@code true} cache group dump stored.
+ * @param encKey Encryption key. For dumps, only.
*/
public SnapshotMetadata(
UUID rqId,
@@ -139,7 +143,8 @@ public class SnapshotMetadata implements Serializable {
@Nullable WALPointer snpRecPtr,
@Nullable byte[] masterKeyDigest,
boolean onlyPrimary,
- boolean dump
+ boolean dump,
+ @Nullable byte[] encKey
) {
this.rqId = rqId;
this.snpName = snpName;
@@ -153,6 +158,7 @@ public class SnapshotMetadata implements Serializable {
this.masterKeyDigest = masterKeyDigest;
this.onlyPrimary = onlyPrimary;
this.dump = dump;
+ this.encKey = encKey;
if (!F.isEmpty(compGrpIds)) {
hasComprGrps = true;
@@ -332,6 +338,11 @@ public class SnapshotMetadata implements Serializable {
return masterKeyDigest;
}
+ /** @return Encryption key. */
+ public byte[] encryptionKey() {
+ return encKey;
+ }
+
/**
* @param warnings Snapshot creation warnings.
*/
@@ -364,6 +375,7 @@ public class SnapshotMetadata implements Serializable {
Objects.equals(grpIds, meta.grpIds) &&
Objects.equals(bltNodes, meta.bltNodes) &&
Arrays.equals(masterKeyDigest, meta.masterKeyDigest) &&
+ Arrays.equals(encKey, meta.encKey) &&
Objects.equals(warnings, meta.warnings) &&
Objects.equals(hasComprGrps, meta.hasComprGrps) &&
Objects.equals(comprGrpIds, meta.comprGrpIds) &&
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/SnapshotOperationRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/SnapshotOperationRequest.java
index 795a1236429..dd5be36a44f 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/SnapshotOperationRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/SnapshotOperationRequest.java
@@ -97,6 +97,9 @@ public class SnapshotOperationRequest implements Serializable {
/** If {@code true} then compress partition files. */
private final boolean compress;
+ /** If {@code true} then content of dump encrypted. */
+ private final boolean encrypt;
+
/**
* @param reqId Request ID.
* @param opNodeId Operational node ID.
@@ -109,6 +112,7 @@ public class SnapshotOperationRequest implements Serializable {
* @param onlyPrimary If {@code true} snapshot only primary copies of partitions.
* @param dump If {@code true} then create dump.
* @param compress If {@code true} then compress partition files.
+ * @param encrypt If {@code true} then content of dump encrypted.
*/
public SnapshotOperationRequest(
UUID reqId,
@@ -121,7 +125,8 @@ public class SnapshotOperationRequest implements Serializable {
int incIdx,
boolean onlyPrimary,
boolean dump,
- boolean compress
+ boolean compress,
+ boolean encrypt
) {
this.reqId = reqId;
this.opNodeId = opNodeId;
@@ -134,6 +139,7 @@ public class SnapshotOperationRequest implements Serializable {
this.onlyPrimary = onlyPrimary;
this.dump = dump;
this.compress = compress;
+ this.encrypt = encrypt;
startTime = U.currentTimeMillis();
}
@@ -218,6 +224,11 @@ public class SnapshotOperationRequest implements Serializable {
return compress;
}
+ /** @return If {@code true} then content of dump encrypted. */
+ public boolean encrypt() {
+ return encrypt;
+ }
+
/** @return Start time. */
public long startTime() {
return startTime;
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/SnapshotPartitionsVerifyHandler.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/SnapshotPartitionsVerifyHandler.java
index 71cafd15828..0a12bfa03d2 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/SnapshotPartitionsVerifyHandler.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/SnapshotPartitionsVerifyHandler.java
@@ -67,6 +67,7 @@ import org.apache.ignite.internal.util.GridUnsafe;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.internal.CU;
import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.spi.encryption.EncryptionSpi;
import org.jetbrains.annotations.Nullable;
import static org.apache.ignite.internal.pagemem.PageIdAllocator.FLAG_DATA;
@@ -364,7 +365,9 @@ public class SnapshotPartitionsVerifyHandler implements SnapshotHandler<Map<Part
try {
String consistentId = cctx.kernalContext().pdsFolderResolver().resolveFolders().consistentId().toString();
- try (Dump dump = new Dump(opCtx.snapshotDirectory(), consistentId, true, true, log)) {
+ EncryptionSpi encSpi = opCtx.metadata().encryptionKey() != null ? cctx.gridConfig().getEncryptionSpi() : null;
+
+ try (Dump dump = new Dump(opCtx.snapshotDirectory(), consistentId, true, true, encSpi, log)) {
Collection<PartitionHashRecordV2> partitionHashRecordV2s = U.doInParallel(
cctx.snapshotMgr().snapshotExecutorService(),
partFiles,
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/SnapshotRestoreProcess.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/SnapshotRestoreProcess.java
index a8e70efd0e3..e8bca0bed88 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/SnapshotRestoreProcess.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/SnapshotRestoreProcess.java
@@ -422,6 +422,7 @@ public class SnapshotRestoreProcess {
incIdx,
onlyPrimary,
false,
+ false,
false
);
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/dump/CreateDumpFutureTask.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/dump/CreateDumpFutureTask.java
index d57f755a8d4..d0654e719b0 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/dump/CreateDumpFutureTask.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/dump/CreateDumpFutureTask.java
@@ -20,6 +20,7 @@ package org.apache.ignite.internal.processors.cache.persistence.snapshot.dump;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
+import java.io.Serializable;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.HashSet;
@@ -103,6 +104,9 @@ public class CreateDumpFutureTask extends AbstractCreateSnapshotFutureTask imple
/** Processed dump size in bytes. */
private final AtomicLong processedSize = new AtomicLong();
+ /** If {@code null} then encryption disabled. */
+ private final @Nullable Serializable encKey;
+
/**
* Dump contextes.
* Key is [group_id, partition_id] combined in single long value.
@@ -122,6 +126,12 @@ public class CreateDumpFutureTask extends AbstractCreateSnapshotFutureTask imple
*/
private final ConcurrentMap<Long, ByteBuffer> thLocBufs = new ConcurrentHashMap<>();
+ /**
+ * Map shared across all instances of {@link PartitionDumpContext} and {@link DumpEntrySerializer}.
+ * Used to store encrypted data in case dump encrypted.
+ */
+ private final @Nullable ConcurrentMap<Long, ByteBuffer> encThLocBufs;
+
/**
* @param cctx Cache context.
* @param srcNodeId Node id which cause snapshot task creation.
@@ -132,6 +142,7 @@ public class CreateDumpFutureTask extends AbstractCreateSnapshotFutureTask imple
* @param rateLimiter Dump transfer rate limiter.
* @param parts Parts to dump.
* @param compress If {@code true} then compress partition files.
+ * @param encrypt If {@code true} then content of dump encrypted.
*/
public CreateDumpFutureTask(
GridCacheSharedContext<?, ?> cctx,
@@ -143,7 +154,8 @@ public class CreateDumpFutureTask extends AbstractCreateSnapshotFutureTask imple
BasicRateLimiter rateLimiter,
SnapshotSender snpSndr,
Map<Integer, Set<Integer>> parts,
- boolean compress
+ boolean compress,
+ boolean encrypt
) {
super(
cctx,
@@ -158,6 +170,8 @@ public class CreateDumpFutureTask extends AbstractCreateSnapshotFutureTask imple
this.ioFactory = compress ? new WriteOnlyZipFileIOFactory() : ioFactory;
this.compress = compress;
this.rateLimiter = rateLimiter;
+ this.encKey = encrypt ? cctx.gridConfig().getEncryptionSpi().create() : null;
+ this.encThLocBufs = encrypt ? new ConcurrentHashMap<>() : null;
}
/** {@inheritDoc} */
@@ -344,6 +358,8 @@ public class CreateDumpFutureTask extends AbstractCreateSnapshotFutureTask imple
closeFut = CompletableFuture.runAsync(
() -> {
thLocBufs.clear();
+ if (encThLocBufs != null)
+ encThLocBufs.clear();
onDone(new SnapshotFutureTaskResult(taken, null), err0);
},
cctx.kernalContext().pools().getSystemExecutorService()
@@ -381,7 +397,7 @@ public class CreateDumpFutureTask extends AbstractCreateSnapshotFutureTask imple
private PartitionDumpContext dumpContext(int grp, int part) {
return dumpCtxs.computeIfAbsent(
toLong(grp, part),
- key -> new PartitionDumpContext(cctx.kernalContext().cache().cacheGroup(grp), part, thLocBufs)
+ key -> new PartitionDumpContext(cctx.kernalContext().cache().cacheGroup(grp), part)
);
}
@@ -446,9 +462,8 @@ public class CreateDumpFutureTask extends AbstractCreateSnapshotFutureTask imple
/**
* @param gctx Group context.
* @param part Partition id.
- * @param thLocBufs Thread local buffers.
*/
- public PartitionDumpContext(CacheGroupContext gctx, int part, ConcurrentMap<Long, ByteBuffer> thLocBufs) {
+ public PartitionDumpContext(CacheGroupContext gctx, int part) {
assert gctx != null;
try {
@@ -459,7 +474,12 @@ public class CreateDumpFutureTask extends AbstractCreateSnapshotFutureTask imple
startVer = grpPrimaries.get(gctx.groupId()).contains(part) ? gctx.shared().versions().last() : null;
isolatedStreamerVer = cctx.versions().isolatedStreamerVersion();
- serializer = new DumpEntrySerializer(thLocBufs);
+ serializer = new DumpEntrySerializer(
+ thLocBufs,
+ encThLocBufs,
+ encKey,
+ cctx.gridConfig().getEncryptionSpi()
+ );
changed = new HashMap<>();
for (int cache : gctx.cacheIds())
@@ -623,4 +643,9 @@ public class CreateDumpFutureTask extends AbstractCreateSnapshotFutureTask imple
(grpCtx.caches().size() > 1 ? CACHE_GRP_DIR_PREFIX : CACHE_DIR_PREFIX) + grpCtx.cacheOrGroupName()
);
}
+
+ /** @return Encryption key. */
+ public @Nullable Serializable encryptionKey() {
+ return encKey;
+ }
}
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/dump/Dump.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/dump/Dump.java
index c27b40375c8..0eb68b5b8e2 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/dump/Dump.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/dump/Dump.java
@@ -30,6 +30,7 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
+import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@@ -60,6 +61,7 @@ import org.apache.ignite.internal.util.typedef.internal.CU;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.marshaller.MarshallerUtils;
import org.apache.ignite.marshaller.jdk.JdkMarshaller;
+import org.apache.ignite.spi.encryption.EncryptionSpi;
import org.jetbrains.annotations.Nullable;
import static org.apache.ignite.configuration.DataStorageConfiguration.DFLT_BINARY_METADATA_PATH;
@@ -97,6 +99,9 @@ public class Dump implements AutoCloseable {
/** If {@code true} then don't deserialize {@link KeyCacheObject} and {@link CacheObject}. */
private final boolean raw;
+ /** Encryption SPI. */
+ private final @Nullable EncryptionSpi encSpi;
+
/**
* Map shared across all instances of {@link DumpEntrySerializer}.
* We use per thread buffer because number of threads is fewer then number of partitions.
@@ -115,7 +120,7 @@ public class Dump implements AutoCloseable {
* @param log Logger.
*/
public Dump(File dumpDir, boolean keepBinary, boolean raw, IgniteLogger log) {
- this(dumpDir, null, keepBinary, raw, log);
+ this(dumpDir, null, keepBinary, raw, null, log);
}
/**
@@ -123,9 +128,17 @@ public class Dump implements AutoCloseable {
* @param consistentId If specified, read dump data only for specific node.
* @param keepBinary If {@code true} then keep read entries in binary form.
* @param raw If {@code true} then keep read entries in form of {@link KeyCacheObject} and {@link CacheObject}.
+ * @param encSpi Encryption SPI instance.
* @param log Logger.
*/
- public Dump(File dumpDir, @Nullable String consistentId, boolean keepBinary, boolean raw, IgniteLogger log) {
+ public Dump(
+ File dumpDir,
+ @Nullable String consistentId,
+ boolean keepBinary,
+ boolean raw,
+ @Nullable EncryptionSpi encSpi,
+ IgniteLogger log
+ ) {
A.ensure(dumpDir != null, "dump directory is null");
A.ensure(dumpDir.exists(), "dump directory not exists");
@@ -135,7 +148,13 @@ public class Dump implements AutoCloseable {
this.keepBinary = keepBinary;
this.cctx = standaloneKernalContext(dumpDir, log);
this.raw = raw;
+ this.encSpi = encSpi;
this.comprParts = metadata.get(0).compressPartitions();
+
+ for (SnapshotMetadata meta : metadata) {
+ if (meta.encryptionKey() != null && encSpi == null)
+ throw new IllegalArgumentException("Encryption SPI required to read encrypted dump");
+ }
}
/**
@@ -261,7 +280,22 @@ public class Dump implements AutoCloseable {
throw new RuntimeException(e);
}
- DumpEntrySerializer serializer = new DumpEntrySerializer(thLocBufs);
+ SnapshotMetadata meta = metadata.stream().filter(m -> Objects.equals(m.folderName(), node)).findFirst().orElseGet(null);
+
+ boolean encrypted = meta.encryptionKey() != null;
+
+ if (encrypted && !Arrays.equals(meta.masterKeyDigest(), encSpi.masterKeyDigest())) {
+ throw new IllegalArgumentException("Dump '" +
+ meta.snapshotName() + "' has different master key digest. To restore this " +
+ "dump, provide the same master key.");
+ }
+
+ DumpEntrySerializer serializer = new DumpEntrySerializer(
+ thLocBufs,
+ encrypted ? new ConcurrentHashMap<>() : null,
+ encrypted ? encSpi.decryptKey(meta.encryptionKey()) : null,
+ encSpi
+ );
serializer.kernalContext(cctx);
serializer.keepBinary(keepBinary);
@@ -367,6 +401,9 @@ public class Dump implements AutoCloseable {
/** {@inheritDoc} */
@Override public void close() throws Exception {
closeAllComponents(cctx);
+
+ if (encSpi != null)
+ encSpi.spiStop();
}
/**
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/dump/DumpEntrySerializer.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/dump/DumpEntrySerializer.java
index 4a1fd7f1c29..70f8eebb33c 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/dump/DumpEntrySerializer.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/dump/DumpEntrySerializer.java
@@ -18,6 +18,7 @@
package org.apache.ignite.internal.processors.cache.persistence.snapshot.dump;
import java.io.IOException;
+import java.io.Serializable;
import java.nio.ByteBuffer;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
@@ -36,6 +37,8 @@ import org.apache.ignite.internal.processors.cache.persistence.wal.crc.FastCrc;
import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
import org.apache.ignite.internal.processors.cache.version.GridCacheVersionEx;
import org.apache.ignite.internal.processors.cacheobject.IgniteCacheObjectProcessor;
+import org.apache.ignite.spi.encryption.EncryptionSpi;
+import org.jetbrains.annotations.Nullable;
/**
* Serialization logic for dump.
@@ -50,6 +53,15 @@ public class DumpEntrySerializer {
/** */
private final ConcurrentMap<Long, ByteBuffer> thLocBufs;
+ /** */
+ private final @Nullable ConcurrentMap<Long, ByteBuffer> encThLocBufs;
+
+ /** */
+ private final @Nullable EncryptionSpi encSpi;
+
+ /** */
+ private final @Nullable Serializable encKey;
+
/** */
private final FastCrc crc = new FastCrc();
@@ -67,9 +79,19 @@ public class DumpEntrySerializer {
/**
* @param thLocBufs Thread local buffers.
+ * @param encKey Encrytpion key. If {@code null} then encryption disabled.
+ * @param encSpi Encryption SPI to use.
*/
- public DumpEntrySerializer(ConcurrentMap<Long, ByteBuffer> thLocBufs) {
+ public DumpEntrySerializer(
+ ConcurrentMap<Long, ByteBuffer> thLocBufs,
+ @Nullable ConcurrentMap<Long, ByteBuffer> encThLocBufs,
+ @Nullable Serializable encKey,
+ @Nullable EncryptionSpi encSpi
+ ) {
this.thLocBufs = thLocBufs;
+ this.encThLocBufs = encThLocBufs;
+ this.encKey = encKey;
+ this.encSpi = encSpi;
}
/** */
@@ -89,22 +111,13 @@ public class DumpEntrySerializer {
}
/**
- * Dump entry structure:
- * <pre>
- * +---------+-----------+----------+-----------------+-----+-------------+
- * | 4 bytes | 4 bytes | 4 bytes | 8 bytes | | | |
- * +---------+-----------+----------+-----------------+-----+-------------+
- * | CRC | Data size | cache ID | expiration time | ver | key | value |
- * +---------+-----------+----------+-----------------+-----+-------------+
- * </pre>
- *
* @param cache Cache id.
* @param expireTime Expire time.
* @param key Key.
* @param val Value.
* @param coCtx Cache object context.
* @return Buffer with serialized entry.
- * @throws IgniteCheckedException If failed
+ * @throws IgniteCheckedException If failed.
*/
public ByteBuffer writeToBuffer(
int cache,
@@ -114,34 +127,71 @@ public class DumpEntrySerializer {
GridCacheVersion ver,
CacheObjectContext coCtx
) throws IgniteCheckedException {
- int verSz = Integer.BYTES/*topVer*/ + Long.BYTES/*order*/ + Integer.BYTES/*nodeOrderDrId*/;
+ ByteBuffer plainBuf = writeToBufferPlain(cache, expireTime, key, val, ver, coCtx);
- boolean hasConflictVer = ver.otherClusterVersion() != null;
+ if (encKey == null)
+ return plainBuf;
- if (hasConflictVer)
- verSz *= 2 /*GridCacheVersion otherClusterVersion*/;
+ int encDataSz = Integer.BYTES + encSpi.encryptedSize(plainBuf.limit());
- assert ver.fieldsCount() == (hasConflictVer ? 4 : 3);
+ ByteBuffer encBuf = threadLocalBuffer(encThLocBufs);
- int keySz = key.valueBytesLength(coCtx);
- int valSz = val.valueBytesLength(coCtx);
- int dataSz = /*cache ID*/Integer.BYTES + /*expire time*/Long.BYTES
- + /* hasConflictVersion */1 + /*version*/verSz + /*key*/keySz + /*value*/valSz;
+ if (encBuf.capacity() < encDataSz)
+ encBuf = enlargeThreadLocalBuffer(thLocBufs, encDataSz);
+ else
+ encBuf.rewind().limit(encDataSz);
+
+ encBuf.putInt(encDataSz - Integer.BYTES);
+ encSpi.encrypt(plainBuf, encKey, encBuf);
+
+ encBuf.position(0);
- int fullSz = dataSz + /*extra bytes for row size*/Integer.BYTES + /*CRC*/Integer.BYTES;
+ return encBuf;
+ }
+
+ /**
+ * Dump entry structure:
+ * <pre>
+ * +-----------+---------+----------+-----------------+-----+-----+-------+
+ * | 4 bytes | 4 bytes | 4 bytes | 8 bytes | | | |
+ * +-----------+---------+----------+-----------------+-----+-----+-------+
+ * | Data size | CRC | cache ID | expiration time | ver | key | value |
+ * +-----------+---------+----------+-----------------+-----+-----+-------+
+ * </pre>
+ *
+ * @param cache Cache id.
+ * @param expireTime Expire time.
+ * @param key Key.
+ * @param val Value.
+ * @param coCtx Cache object context.
+ * @return Buffer with serialized entry.
+ * @throws IgniteCheckedException If failed.
+ */
+ private ByteBuffer writeToBufferPlain(
+ int cache,
+ long expireTime,
+ KeyCacheObject key,
+ CacheObject val,
+ GridCacheVersion ver,
+ CacheObjectContext coCtx
+ ) throws IgniteCheckedException {
+ int dataSz = plainDataSize(key, val, ver, coCtx);
+ int bufSz = dataSz + Integer.BYTES;
- ByteBuffer buf = threadLocalBuffer();
+ ByteBuffer buf = threadLocalBuffer(thLocBufs);
- if (buf.capacity() < fullSz)
- buf = enlargeThreadLocalBuffer(fullSz);
+ if (buf.capacity() < bufSz)
+ buf = enlargeThreadLocalBuffer(thLocBufs, bufSz);
else
- buf.rewind().limit(fullSz);
+ buf.rewind().limit(bufSz);
- buf.position(Integer.BYTES); // CRC value.
buf.putInt(dataSz);
+ buf.putInt(-1); // CRC value.
buf.putInt(cache);
buf.putLong(expireTime);
+ boolean hasConflictVer = ver.otherClusterVersion() != null;
+
buf.put((byte)(hasConflictVer ? 1 : 0));
buf.putInt(ver.topologyVersion());
buf.putLong(ver.order());
@@ -161,14 +211,14 @@ public class DumpEntrySerializer {
if (!val.putValue(buf))
throw new IgniteCheckedException("Can't write value");
- assert buf.position() == fullSz;
+ assert buf.position() == bufSz;
- buf.position(Integer.BYTES);
+ buf.position(HEADER_SZ);
crc.reset();
- crc.update(buf, fullSz - Integer.BYTES);
+ crc.update(buf, dataSz - Integer.BYTES);
- buf.position(0);
+ buf.position(Integer.BYTES);
buf.putInt(crc.getValue());
buf.position(0);
@@ -176,6 +226,29 @@ public class DumpEntrySerializer {
return buf;
}
+ /** */
+ private static int plainDataSize(
+ KeyCacheObject key,
+ CacheObject val,
+ GridCacheVersion ver,
+ CacheObjectContext coCtx
+ ) throws IgniteCheckedException {
+ int verSz = Integer.BYTES/*topVer*/ + Long.BYTES/*order*/ + Integer.BYTES/*nodeOrderDrId*/;
+
+ boolean hasConflictVer = ver.otherClusterVersion() != null;
+
+ if (hasConflictVer)
+ verSz *= 2 /*GridCacheVersion otherClusterVersion*/;
+
+ assert ver.fieldsCount() == (hasConflictVer ? 4 : 3);
+
+ int keySz = key.valueBytesLength(coCtx);
+ int valSz = val.valueBytesLength(coCtx);
+
+ return /* CRC */Integer.BYTES + /*cache ID*/Integer.BYTES + /*expire time*/Long.BYTES
+ + /* hasConflictVersion */1 + /*version*/verSz + /*key*/keySz + /*value*/valSz;
+ }
+
/**
* @param dumpFile File to read data from.
* @param grp Cache group.
@@ -184,38 +257,76 @@ public class DumpEntrySerializer {
public DumpEntry read(FileIO dumpFile, int grp, int part) throws IOException, IgniteCheckedException {
assert co != null : "Set kernalContext first";
- ByteBuffer buf = threadLocalBuffer();
+ ByteBuffer buf = readRecord(dumpFile);
+
+ if (buf == null)
+ return null;
+
+ if (encSpi != null) {
+ ByteBuffer plainBuf = threadLocalBuffer(encThLocBufs);
+
+ plainBuf.limit(plainBuf.capacity());
+
+ if (plainBuf.capacity() < buf.limit())
+ plainBuf = enlargeThreadLocalBuffer(encThLocBufs, buf.limit());
+ else
+ plainBuf.rewind();
+
+ buf.position(Integer.BYTES);
+
+ encSpi.decryptNoPadding(buf, encKey, plainBuf);
+
+ plainBuf.rewind();
+
+ int plainDataSz = plainBuf.getInt();
+
+ plainBuf.limit(plainDataSz + Integer.BYTES);
+
+ buf = plainBuf;
+ }
+
+ return plainDataEntry(part, buf);
+ }
+
+ /** */
+ private ByteBuffer readRecord(FileIO file) throws IOException {
+ ByteBuffer buf = threadLocalBuffer(thLocBufs);
buf.position(0);
- buf.limit(HEADER_SZ);
+ buf.limit(Integer.BYTES);
- int read = dumpFile.readFully(buf);
+ int read = file.readFully(buf);
- if (read < HEADER_SZ)
+ if (read < Integer.BYTES)
return null;
buf.position(0);
- int crc = buf.getInt();
int dataSz = buf.getInt();
+ int bufSz = dataSz + Integer.BYTES;
- if (buf.capacity() < dataSz + HEADER_SZ) {
- buf = enlargeThreadLocalBuffer(dataSz + HEADER_SZ);
-
- buf.position(HEADER_SZ - Integer.BYTES);
- buf.putInt(dataSz); // Required for CRC check.
+ if (buf.capacity() < bufSz) {
+ buf = enlargeThreadLocalBuffer(thLocBufs, bufSz);
+ buf.position(Integer.BYTES);
}
else
- buf.limit(dataSz + HEADER_SZ);
+ buf.limit(bufSz);
- read = dumpFile.readFully(buf);
+ read = file.readFully(buf);
+
+ if (read != buf.limit() - Integer.BYTES)
+ throw new IgniteException("Expected to read " + (buf.limit() - Integer.BYTES) + " bytes but read only " + read);
+
+ return buf;
+ }
- if (read != dataSz)
- throw new IgniteException("Expected to read " + dataSz + " bytes but read only " + read);
+ /** */
+ private DumpEntry plainDataEntry(int part, ByteBuffer buf) throws IgniteCheckedException {
+ buf.position(Integer.BYTES);
- buf.position(HEADER_SZ - Integer.BYTES);
+ int crc = buf.getInt();
- checkCRC(crc, dataSz, buf);
+ checkCRC(crc, buf);
buf.position(HEADER_SZ);
@@ -287,23 +398,28 @@ public class DumpEntrySerializer {
}
/** @return Thread local buffer. */
- private ByteBuffer threadLocalBuffer() {
- return thLocBufs.computeIfAbsent(Thread.currentThread().getId(), DFLT_BUF_ALLOC);
+ private ByteBuffer threadLocalBuffer(ConcurrentMap<Long, ByteBuffer> map) {
+ ByteBuffer res = map.computeIfAbsent(Thread.currentThread().getId(), DFLT_BUF_ALLOC);
+
+ res.limit(res.capacity());
+ res.position(0);
+
+ return res;
}
/** @return Thread local buffer. */
- private ByteBuffer enlargeThreadLocalBuffer(int sz) {
+ private ByteBuffer enlargeThreadLocalBuffer(ConcurrentMap<Long, ByteBuffer> map, int sz) {
ByteBuffer buf = ByteBuffer.allocate(sz);
- thLocBufs.put(Thread.currentThread().getId(), buf);
+ map.put(Thread.currentThread().getId(), buf);
return buf;
}
/** */
- private void checkCRC(int expCrc, int dataSz, ByteBuffer buf) {
+ private void checkCRC(int expCrc, ByteBuffer buf) {
crc.reset();
- crc.update(buf, dataSz + Integer.BYTES /*dataSz field included in CRC calculation*/);
+ crc.update(buf, buf.limit() - buf.position());
if (expCrc != crc.getValue())
throw new IgniteException("Data corrupted [expCrc=" + expCrc + ", crc=" + crc + ']');
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/AbstractSnapshotSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/AbstractSnapshotSelfTest.java
index 2f58e2449a8..2a56d8ceb24 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/AbstractSnapshotSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/AbstractSnapshotSelfTest.java
@@ -831,6 +831,7 @@ public abstract class AbstractSnapshotSelfTest extends GridCommonAbstractTest {
withMetaStorage,
false,
false,
+ false,
snpSndr
);
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/EncryptedSnapshotTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/EncryptedSnapshotTest.java
index 6f5862ef208..a3913b600d7 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/EncryptedSnapshotTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/EncryptedSnapshotTest.java
@@ -298,6 +298,7 @@ public class EncryptedSnapshotTest extends AbstractSnapshotSelfTest {
false,
false,
false,
+ false,
snp(ig).localSnapshotSenderFactory().apply(SNAPSHOT_NAME, null)
).get(TIMEOUT),
IgniteCheckedException.class,
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/IgniteSnapshotManagerSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/IgniteSnapshotManagerSelfTest.java
index d226a4b6a49..f8c3ab02720 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/IgniteSnapshotManagerSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/IgniteSnapshotManagerSelfTest.java
@@ -151,6 +151,7 @@ public class IgniteSnapshotManagerSelfTest extends AbstractSnapshotSelfTest {
encryption,
false,
false,
+ false,
new DelegateSnapshotSender(log, mgr.snapshotExecutorService(), mgr.localSnapshotSenderFactory().apply(SNAPSHOT_NAME, null)) {
@Override public void sendPart0(File part, String cacheDirName, GroupPartitionId pair, Long length) {
try {
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/dump/AbstractCacheDumpTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/dump/AbstractCacheDumpTest.java
index a61a6c8b2d4..75d9bdda06b 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/dump/AbstractCacheDumpTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/dump/AbstractCacheDumpTest.java
@@ -65,6 +65,7 @@ import org.apache.ignite.platform.model.Key;
import org.apache.ignite.platform.model.Role;
import org.apache.ignite.platform.model.User;
import org.apache.ignite.platform.model.Value;
+import org.apache.ignite.spi.encryption.keystore.KeystoreEncryptionSpi;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.apache.ignite.transactions.Transaction;
import org.jetbrains.annotations.Nullable;
@@ -74,6 +75,8 @@ import org.junit.runners.Parameterized;
import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC;
import static org.apache.ignite.dump.DumpReaderConfiguration.DFLT_THREAD_CNT;
import static org.apache.ignite.dump.DumpReaderConfiguration.DFLT_TIMEOUT;
+import static org.apache.ignite.internal.encryption.AbstractEncryptionTest.KEYSTORE_PASSWORD;
+import static org.apache.ignite.internal.encryption.AbstractEncryptionTest.KEYSTORE_PATH;
import static org.apache.ignite.internal.processors.cache.GridCacheUtils.UTILITY_CACHE_NAME;
import static org.apache.ignite.internal.processors.cache.persistence.snapshot.IgniteSnapshotManager.SNP_RUNNING_DIR_KEY;
import static org.apache.ignite.internal.processors.cache.persistence.snapshot.dump.CreateDumpFutureTask.toLong;
@@ -128,7 +131,11 @@ public abstract class AbstractCacheDumpTest extends GridCommonAbstractTest {
public boolean onlyPrimary;
/** */
- @Parameterized.Parameters(name = "nodes={0},backups={1},persistence={2},mode={3},useDataStreamer={4},onlyPrimary={5}")
+ @Parameterized.Parameter(6)
+ public boolean encrypted;
+
+ /** */
+ @Parameterized.Parameters(name = "nodes={0},backups={1},persistence={2},mode={3},useDataStreamer={4},onlyPrimary={5},encrypted={6}")
public static List<Object[]> params() {
List<Object[]> params = new ArrayList<>();
@@ -141,11 +148,11 @@ public abstract class AbstractCacheDumpTest extends GridCommonAbstractTest {
continue;
if (backups > 0) {
- params.add(new Object[]{nodes, backups, persistence, mode, useDataStreamer, false});
- params.add(new Object[]{nodes, backups, persistence, mode, useDataStreamer, true});
+ params.add(new Object[]{nodes, backups, persistence, mode, useDataStreamer, false, false});
+ params.add(new Object[]{nodes, backups, persistence, mode, useDataStreamer, true, false});
}
else
- params.add(new Object[]{nodes, backups, persistence, mode, useDataStreamer, false});
+ params.add(new Object[]{nodes, backups, persistence, mode, useDataStreamer, false, false});
}
}
@@ -174,7 +181,7 @@ public abstract class AbstractCacheDumpTest extends GridCommonAbstractTest {
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
- return super.getConfiguration(igniteInstanceName)
+ IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName)
.setSnapshotThreadPoolSize(snpPoolSz)
.setDataStorageConfiguration(new DataStorageConfiguration()
.setDefaultDataRegionConfiguration(new DataRegionConfiguration().setPersistenceEnabled(persistence)))
@@ -200,6 +207,11 @@ public abstract class AbstractCacheDumpTest extends GridCommonAbstractTest {
.setWriteSynchronizationMode(FULL_SYNC)
.setAffinity(new RendezvousAffinityFunction().setPartitions(20))
);
+
+ if (encrypted)
+ cfg.setEncryptionSpi(encryptionSpi());
+
+ return cfg;
}
/** */
@@ -417,7 +429,8 @@ public abstract class AbstractCacheDumpTest extends GridCommonAbstractTest {
true,
false,
cacheGroupNames,
- skipCopies
+ skipCopies,
+ null
),
log
).run();
@@ -550,7 +563,17 @@ public abstract class AbstractCacheDumpTest extends GridCommonAbstractTest {
/** */
void createDump(IgniteEx ign, String name, @Nullable Collection<String> cacheGroupNames, boolean comprParts) {
ign.context().cache().context().snapshotMgr()
- .createSnapshot(name, null, cacheGroupNames, false, onlyPrimary, true, comprParts).get();
+ .createSnapshot(name, null, cacheGroupNames, false, onlyPrimary, true, comprParts, encrypted).get();
+ }
+
+ /** */
+ public static KeystoreEncryptionSpi encryptionSpi() {
+ KeystoreEncryptionSpi encSpi = new KeystoreEncryptionSpi();
+
+ encSpi.setKeyStorePath(KEYSTORE_PATH);
+ encSpi.setKeyStorePassword(KEYSTORE_PASSWORD.toCharArray());
+
+ return encSpi;
}
/** */
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/dump/IgniteCacheDumpSelf2Test.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/dump/IgniteCacheDumpSelf2Test.java
index 59db0daf349..44b7927d73a 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/dump/IgniteCacheDumpSelf2Test.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/dump/IgniteCacheDumpSelf2Test.java
@@ -32,6 +32,7 @@ import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.BiConsumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@@ -79,6 +80,7 @@ import org.apache.ignite.plugin.AbstractCachePluginProvider;
import org.apache.ignite.plugin.AbstractTestPluginProvider;
import org.apache.ignite.plugin.CachePluginContext;
import org.apache.ignite.plugin.CachePluginProvider;
+import org.apache.ignite.spi.encryption.EncryptionSpi;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.testframework.ListeningTestLogger;
import org.apache.ignite.testframework.LogListener;
@@ -91,6 +93,7 @@ import static java.nio.file.StandardOpenOption.WRITE;
import static org.apache.ignite.configuration.IgniteConfiguration.DFLT_SNAPSHOT_DIRECTORY;
import static org.apache.ignite.dump.DumpReaderConfiguration.DFLT_THREAD_CNT;
import static org.apache.ignite.dump.DumpReaderConfiguration.DFLT_TIMEOUT;
+import static org.apache.ignite.internal.encryption.AbstractEncryptionTest.MASTER_KEY_NAME_2;
import static org.apache.ignite.internal.processors.cache.persistence.file.FilePageStoreManager.CACHE_DATA_FILENAME;
import static org.apache.ignite.internal.processors.cache.persistence.file.FilePageStoreManager.CACHE_DIR_PREFIX;
import static org.apache.ignite.internal.processors.cache.persistence.file.FilePageStoreManager.PART_FILE_PREFIX;
@@ -105,6 +108,7 @@ import static org.apache.ignite.internal.processors.cache.persistence.snapshot.d
import static org.apache.ignite.internal.processors.cache.persistence.snapshot.dump.AbstractCacheDumpTest.USER_FACTORY;
import static org.apache.ignite.internal.processors.cache.persistence.snapshot.dump.AbstractCacheDumpTest.dump;
import static org.apache.ignite.internal.processors.cache.persistence.snapshot.dump.AbstractCacheDumpTest.dumpDirectory;
+import static org.apache.ignite.internal.processors.cache.persistence.snapshot.dump.AbstractCacheDumpTest.encryptionSpi;
import static org.apache.ignite.internal.processors.cache.persistence.snapshot.dump.AbstractCacheDumpTest.invokeCheckCommand;
import static org.apache.ignite.internal.processors.cache.persistence.snapshot.dump.CreateDumpFutureTask.DUMP_FILE_EXT;
import static org.apache.ignite.internal.processors.cache.persistence.snapshot.dump.DumpEntrySerializer.HEADER_SZ;
@@ -400,6 +404,7 @@ public class IgniteCacheDumpSelf2Test extends GridCommonAbstractTest {
false,
false,
true,
+ false,
false
).get();
@@ -492,10 +497,10 @@ public class IgniteCacheDumpSelf2Test extends GridCommonAbstractTest {
String zipDump = "zipDump";
ign.context().cache().context().snapshotMgr()
- .createSnapshot(rawDump, null, null, false, true, true, false).get();
+ .createSnapshot(rawDump, null, null, false, true, true, false, false).get();
ign.context().cache().context().snapshotMgr()
- .createSnapshot(zipDump, null, null, false, true, true, true).get();
+ .createSnapshot(zipDump, null, null, false, true, true, true, false).get();
stopAllGrids();
@@ -610,12 +615,138 @@ public class IgniteCacheDumpSelf2Test extends GridCommonAbstractTest {
true,
false,
null,
- false
+ false,
+ null
+ ),
+ log
+ ).run();
+
+ cnsmr.check();
+ }
+
+ /** */
+ @Test
+ public void testCreateEncryptedFail() throws Exception {
+ BiConsumer<IgniteEx, String> check = (ign, msg) -> assertThrows(null, () -> {
+ ign.context().cache().context().snapshotMgr()
+ .createSnapshot(DMP_NAME, null, null, false, false, true, false, true).get(getTestTimeout());
+ }, IgniteException.class, msg);
+
+ try (IgniteEx srv = startGrid()) {
+ IgniteCache<Integer, Integer> cache = srv.createCache(DEFAULT_CACHE_NAME);
+ IntStream.range(0, KEYS_CNT).forEach(i -> cache.put(i, i));
+
+ IgniteEx cli = startClientGrid(1);
+
+ check.accept(srv, "You have to configure custom EncryptionSpi implementation");
+ check.accept(cli, "Snapshot has not been created");
+ }
+ }
+
+ /** */
+ @Test
+ public void testReadEncrypted() throws Exception {
+ File dumpDir;
+
+ try (IgniteEx srv = startGrid(new IgniteConfiguration().setEncryptionSpi(encryptionSpi()))) {
+ IgniteCache<Integer, byte[]> cache = srv.createCache(DEFAULT_CACHE_NAME);
+ IntStream.range(0, KEYS_CNT).forEach(i -> {
+ byte[] data = new byte[Math.max(Integer.BYTES, ThreadLocalRandom.current().nextInt((int)U.KB))];
+
+ U.intToBytes(i, data, 0);
+
+ cache.put(i, data);
+ });
+
+ srv.context().cache().context().snapshotMgr()
+ .createSnapshot(DMP_NAME, null, null, false, false, true, false, true).get(getTestTimeout());
+
+ dumpDir = dumpDirectory(srv, DMP_NAME);
+ }
+
+ assertThrows(null, () -> new DumpReader(
+ new DumpReaderConfiguration(
+ dumpDir,
+ new TestDumpConsumer() {
+ @Override public void onPartition(int grp, int part, Iterator<DumpEntry> data) {
+ data.forEachRemaining(e -> {
+ assert e != null;
+ });
+ }
+ },
+ DFLT_THREAD_CNT,
+ DFLT_TIMEOUT,
+ true,
+ false,
+ null,
+ false,
+ null
+ ),
+ log
+ ).run(), IgniteException.class, "Encryption SPI required to read encrypted dump");
+
+ assertThrows(
+ null,
+ () -> {
+ EncryptionSpi encSpi = encryptionSpi();
+
+ encSpi.setMasterKeyName(MASTER_KEY_NAME_2);
+
+ new DumpReader(
+ new DumpReaderConfiguration(
+ dumpDir,
+ new TestDumpConsumer() {
+ @Override public void onPartition(int grp, int part, Iterator<DumpEntry> data) {
+ data.forEachRemaining(e -> {
+ assert e != null;
+ });
+ }
+ },
+ DFLT_THREAD_CNT,
+ DFLT_TIMEOUT,
+ true,
+ false,
+ null,
+ false,
+ encSpi
+ ),
+ log
+ ).run();
+ },
+ IgniteException.class,
+ "Dump '" + DMP_NAME + "' has different master key digest. To restore this snapshot, provide the same master key"
+ );
+
+ Map<Integer, Integer> dumpEntries = new HashMap<>();
+
+ TestDumpConsumer cnsmr = new TestDumpConsumer() {
+ @Override public void onPartition(int grp, int part, Iterator<DumpEntry> data) {
+ data.forEachRemaining(e -> {
+ int v = U.bytesToInt((byte[])e.value(), 0);
+
+ dumpEntries.put((Integer)e.key(), v);
+ });
+ }
+ };
+
+ new DumpReader(
+ new DumpReaderConfiguration(
+ dumpDir,
+ cnsmr,
+ DFLT_THREAD_CNT,
+ DFLT_TIMEOUT,
+ true,
+ false,
+ null,
+ false,
+ encryptionSpi()
),
log
).run();
cnsmr.check();
+
+ IntStream.range(0, KEYS_CNT).forEach(i -> assertEquals((Integer)i, dumpEntries.get(i)));
}
/** */
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/dump/IgniteConcurrentCacheDumpTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/dump/IgniteConcurrentCacheDumpTest.java
index 8b50d88bc18..868d37199ca 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/dump/IgniteConcurrentCacheDumpTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/snapshot/dump/IgniteConcurrentCacheDumpTest.java
@@ -36,15 +36,16 @@ import org.junit.runners.Parameterized;
/** */
public class IgniteConcurrentCacheDumpTest extends AbstractCacheDumpTest {
/** */
- @Parameterized.Parameters(name = "nodes={0},backups={1},persistence={2},mode={3},useDataStreamer={4},onlyPrimary={5}")
+ @Parameterized.Parameters(name = "nodes={0},backups={1},persistence={2},mode={3},useDataStreamer={4},onlyPrimary={5},encrypted={6}")
public static List<Object[]> params() {
List<Object[]> params = new ArrayList<>();
- for (int nodes : new int[]{2, 3})
- for (int backups : new int[]{1, 2})
- for (boolean persistence : new boolean[]{true, false})
- for (CacheAtomicityMode mode : CacheAtomicityMode.values())
- params.add(new Object[]{nodes, backups, persistence, mode, false, false});
+ for (boolean encrypted : new boolean[]{true, false})
+ for (int nodes : new int[]{2, 3})
+ for (int backups : new int[]{1, 2})
+ for (boolean persistence : new boolean[]{true, false})
+ for (CacheAtomicityMode mode : CacheAtomicityMode.values())
+ params.add(new Object[]{nodes, backups, persistence, mode, false, false, encrypted});
return params;
}