nizhikov commented on code in PR #13649:
URL: https://github.com/apache/ignite/pull/13649#discussion_r4248620547


##########
modules/core/src/main/java/org/apache/ignite/internal/pagemem/wal/IgniteWriteAheadLogManager.java:
##########
@@ -44,6 +44,11 @@ public interface IgniteWriteAheadLogManager extends 
GridCacheSharedManager, Igni
      */
     public boolean isFullSync();
 
+    /**
+     * @return {@code True} if CDC is disabled by the {@code cdc.disabled} 
distributed property.
+     */
+    public boolean cdcForceDisabled();

Review Comment:
   **[Should fix]** A new abstract method on a plugin-facing interface. 
`GridCacheProcessor` obtains the WAL manager via 
`ctx.plugins().createComponent(IgniteWriteAheadLogManager.class)`, so any 
plugin implementation that does not extend `FileWriteAheadLogManager` stops 
compiling.
   
   `default boolean cdcForceDisabled() { return false; }` keeps compatibility 
and also removes the `NoOpWALManager` edit.



##########
modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/CdcLinkManager.java:
##########
@@ -0,0 +1,156 @@
+/*
+ * 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.processors.cache.persistence.wal;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.util.Arrays;
+import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.IgniteLogger;
+import org.apache.ignite.configuration.DataStorageConfiguration;
+import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
+import 
org.apache.ignite.internal.processors.cache.persistence.filename.NodeFileTree;
+import 
org.apache.ignite.internal.processors.configuration.distributed.DistributedBooleanProperty;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.U;
+
+import static java.lang.String.format;
+import static 
org.apache.ignite.internal.processors.cache.persistence.wal.FileWriteAheadLogManager.CDC_DISABLED;
+import static 
org.apache.ignite.internal.processors.configuration.distributed.DistributedBooleanProperty.detachedBooleanProperty;
+import static 
org.apache.ignite.internal.util.io.GridFileUtils.ensureHardLinkAvailable;
+
+/**
+ * Links the archived WAL segments to the CDC directory. The links are not 
created while CDC is disabled by the
+ * {@link FileWriteAheadLogManager#CDC_DISABLED} distributed property. Data 
regions without persistence do not log the
+ * changes while CDC is disabled, so on the nodes with such regions the 
segment that is current at the disabling is never
+ * linked either: the CDC application fails on the missed segment after CDC is 
enabled again.
+ */
+class CdcLinkManager {
+    /** */
+    private final GridCacheSharedContext<?, ?> cctx;
+
+    /** */
+    private final IgniteLogger log;
+
+    /** */
+    private final NodeFileTree ft;
+
+    /** CDC disabled flag. */
+    private final DistributedBooleanProperty cdcDisabled = 
detachedBooleanProperty(CDC_DISABLED,
+        "CDC disabled flag. Disables CDC in the cluster to avoid disk 
overflow. " +
+            "Note that cache changes will be lost when CDC is disabled. Useful 
if the CDC application " +
+            "is down for a long time.");
+
+    /**
+     * Index of the segment that was current at the last CDC disabling. It is 
never linked, so the CDC application detects
+     * the missed changes as a gap in the segments even if no segment is 
archived while CDC is disabled. Persistent
+     * regions log the changes anyway, so the gap is made only on the nodes 
with in-memory CDC regions.
+     */
+    private volatile long disableSgmnt = -1;
+
+    /** */
+    CdcLinkManager(GridCacheSharedContext<?, ?> cctx) throws 
IgniteCheckedException {
+        this.cctx = cctx;
+
+        log = cctx.logger(CdcLinkManager.class);
+        ft = cctx.kernalContext().pdsFolderResolver().fileTree();
+
+        DataStorageConfiguration dsCfg = 
cctx.gridConfig().getDataStorageConfiguration();
+
+        // True on a node with persistence too, unlike 
FileWriteAheadLogManager#inMemoryCdc.
+        boolean inMemoryCdcRegion = F.exist(
+            F.concat(false, dsCfg.getDefaultDataRegionConfiguration(), 
F.asList(dsCfg.getDataRegionConfigurations())),
+            reg -> reg.isCdcEnabled() && !reg.isPersistenceEnabled());
+
+        U.ensureDirectory(ft.walCdc(), "change data capture directory", log);
+
+        ensureHardLinkAvailable(ft.walArchive().toPath(), 
ft.walCdc().toPath());
+
+        
cctx.kernalContext().internalSubscriptionProcessor().registerDistributedConfigurationListener(dispatcher
 -> {
+            cdcDisabled.addListener((name, oldVal, newVal) -> {
+                if (log.isInfoEnabled())
+                    log.info(format("Distributed property '%s' was changed 
from '%s' to '%s'.", name, oldVal, newVal));
+
+                if (newVal != null && newVal) {
+                    log.warning("CDC was disabled.");
+
+                    if (cctx.cdc() != null)
+                        cctx.cdc().stop(true);
+
+                    if (inMemoryCdcRegion)
+                        markDisableSegment();
+                }
+            });
+
+            dispatcher.registerProperty(cdcDisabled);
+        });
+    }
+
+    /** */
+    private void markDisableSegment() {
+        // -1 if the WAL logging is not resumed yet: the node is restarted 
with CDC disabled, the gap is already made.
+        disableSgmnt = Math.max(disableSgmnt, cctx.wal(true).currentSegment());
+    }
+
+    /** */
+    boolean forceDisabled() {
+        return cdcDisabled.getOrDefault(false);
+    }
+
+    /**
+     * The segment that was current at the CDC disabling is never linked, the 
changes in it are lost. It is closed before
+     * the next record, so the changes made after CDC is enabled again do not 
get into it.
+     */
+    boolean shouldRollover(long idx) {
+        return idx == disableSgmnt;
+    }
+
+    /** */
+    void linkSegment(long idx, File segment) throws IOException {
+        if (forceDisabled())
+            log.warning("Creation of segment CDC link skipped. '" + 
CDC_DISABLED + "' distributed property is 'true'.");
+        else if (idx <= disableSgmnt)

Review Comment:
   **[Blocker]** `idx <= disableSgmnt` also drops segments *older* than the 
disable segment that were still waiting in the WAL work dir for the archiver, 
even though they hold changes made while CDC was enabled. Example: archiver 
lags, N-3..N-1 are not archived yet, CDC is disabled at N and quickly 
re-enabled. The old code linked N-3..N-1 once archived; this code refuses them 
with "was not archived before CDC was disabled". Up to `walSegments - 1` 
segments of pre-disable data are lost beyond the one documented skipped segment.
   
   Only `idx == disableSgmnt` is needed for the gap; `forceDisabled()` above 
already covers the still-disabled case.



##########
modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/CdcLinkManager.java:
##########
@@ -0,0 +1,156 @@
+/*
+ * 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.processors.cache.persistence.wal;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.util.Arrays;
+import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.IgniteLogger;
+import org.apache.ignite.configuration.DataStorageConfiguration;
+import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
+import 
org.apache.ignite.internal.processors.cache.persistence.filename.NodeFileTree;
+import 
org.apache.ignite.internal.processors.configuration.distributed.DistributedBooleanProperty;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.U;
+
+import static java.lang.String.format;
+import static 
org.apache.ignite.internal.processors.cache.persistence.wal.FileWriteAheadLogManager.CDC_DISABLED;
+import static 
org.apache.ignite.internal.processors.configuration.distributed.DistributedBooleanProperty.detachedBooleanProperty;
+import static 
org.apache.ignite.internal.util.io.GridFileUtils.ensureHardLinkAvailable;
+
+/**
+ * Links the archived WAL segments to the CDC directory. The links are not 
created while CDC is disabled by the
+ * {@link FileWriteAheadLogManager#CDC_DISABLED} distributed property. Data 
regions without persistence do not log the
+ * changes while CDC is disabled, so on the nodes with such regions the 
segment that is current at the disabling is never
+ * linked either: the CDC application fails on the missed segment after CDC is 
enabled again.
+ */
+class CdcLinkManager {
+    /** */
+    private final GridCacheSharedContext<?, ?> cctx;
+
+    /** */
+    private final IgniteLogger log;
+
+    /** */
+    private final NodeFileTree ft;
+
+    /** CDC disabled flag. */
+    private final DistributedBooleanProperty cdcDisabled = 
detachedBooleanProperty(CDC_DISABLED,
+        "CDC disabled flag. Disables CDC in the cluster to avoid disk 
overflow. " +
+            "Note that cache changes will be lost when CDC is disabled. Useful 
if the CDC application " +
+            "is down for a long time.");
+
+    /**
+     * Index of the segment that was current at the last CDC disabling. It is 
never linked, so the CDC application detects
+     * the missed changes as a gap in the segments even if no segment is 
archived while CDC is disabled. Persistent
+     * regions log the changes anyway, so the gap is made only on the nodes 
with in-memory CDC regions.
+     */
+    private volatile long disableSgmnt = -1;
+
+    /** */
+    CdcLinkManager(GridCacheSharedContext<?, ?> cctx) throws 
IgniteCheckedException {
+        this.cctx = cctx;
+
+        log = cctx.logger(CdcLinkManager.class);
+        ft = cctx.kernalContext().pdsFolderResolver().fileTree();
+
+        DataStorageConfiguration dsCfg = 
cctx.gridConfig().getDataStorageConfiguration();
+
+        // True on a node with persistence too, unlike 
FileWriteAheadLogManager#inMemoryCdc.
+        boolean inMemoryCdcRegion = F.exist(
+            F.concat(false, dsCfg.getDefaultDataRegionConfiguration(), 
F.asList(dsCfg.getDataRegionConfigurations())),
+            reg -> reg.isCdcEnabled() && !reg.isPersistenceEnabled());
+
+        U.ensureDirectory(ft.walCdc(), "change data capture directory", log);
+
+        ensureHardLinkAvailable(ft.walArchive().toPath(), 
ft.walCdc().toPath());
+
+        
cctx.kernalContext().internalSubscriptionProcessor().registerDistributedConfigurationListener(dispatcher
 -> {
+            cdcDisabled.addListener((name, oldVal, newVal) -> {
+                if (log.isInfoEnabled())
+                    log.info(format("Distributed property '%s' was changed 
from '%s' to '%s'.", name, oldVal, newVal));
+
+                if (newVal != null && newVal) {
+                    log.warning("CDC was disabled.");
+
+                    if (cctx.cdc() != null)
+                        cctx.cdc().stop(true);
+
+                    if (inMemoryCdcRegion)
+                        markDisableSegment();
+                }
+            });
+
+            dispatcher.registerProperty(cdcDisabled);
+        });
+    }
+
+    /** */
+    private void markDisableSegment() {
+        // -1 if the WAL logging is not resumed yet: the node is restarted 
with CDC disabled, the gap is already made.
+        disableSgmnt = Math.max(disableSgmnt, cctx.wal(true).currentSegment());

Review Comment:
   **[Blocker]** `markDisableSegment()` is called from the property listener, 
which fires at node start (`onReadyForRead`) before logging is resumed, so 
`currentSegment()` returns `-1` and nothing is marked. The comment says "the 
gap is already made", but that does not hold for an in-memory-only node: CDC 
disabled at segment N, nothing is logged afterwards, node restarted. 
`resumeLogging` continues in N, `disableSgmnt` stays `-1`, CDC is re-enabled, 
records go into N, and N is archived and linked right after N-1. The consumer 
sees consecutive segments and every change made while disabled is silently 
lost. Same for a persistent node with an in-memory CDC region that restarts or 
joins while the property is already `true`.
   
   Suggest re-running `markDisableSegment()` from `resumeLogging` (or after 
`restoreWriteHandle`) when `forceDisabled() && inMemoryCdcRegion`.



##########
modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheGroupContext.java:
##########
@@ -980,7 +980,7 @@ public boolean persistenceEnabled() {
      * @return {@code True} if {@link DataRecord} should be loged in the WAL.
      */
     public boolean logDataRecords() {
-        return walEnabled() && (persistenceEnabled || cdcEnabled());
+        return walEnabled() && (persistenceEnabled || (cdcEnabled() && 
!wal().cdcForceDisabled()));

Review Comment:
   **[Minor]** `wal()` is `ctx.wal(cdcEnabled())`, so 
`dataRegion.config().isCdcEnabled()` is now evaluated twice on this per-entry 
path. The branch is only reached when `cdcEnabled()` is already `true`, so 
`ctx.wal(true).cdcForceDisabled()` is enough.



##########
modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/FileWriteAheadLogManager.java:
##########
@@ -885,6 +861,12 @@ private boolean checkTimeout(AtomicLong lastEvt, long 
timeout) {
         if (currWrHandle == null || (isDisable != null && isDisable.check()))
             return null;
 
+        if (cdcLinkMgr != null && 
cdcLinkMgr.shouldRollover(currWrHandle.getSegmentId())) {

Review Comment:
   **[Should fix]** This adds a volatile read and a branch to every `log()` 
call on every CDC-configured node, including persistent nodes where CDC is 
never disabled. The gap also only materialises when a later record arrives: on 
an in-memory-only node nothing is logged while CDC is disabled, so the disable 
segment stays open until CDC is re-enabled and something is written, and the 
archive / CDC dir does not reflect the disable until then.
   
   Rolling the disable segment over asynchronously from the listener (the same 
way `TimeoutRollover` / `closeBufAndRollover` do it) keeps `log()` untouched 
and makes the gap independent of future writes.



##########
modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/CdcLinkManager.java:
##########
@@ -0,0 +1,156 @@
+/*
+ * 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.processors.cache.persistence.wal;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.util.Arrays;
+import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.IgniteLogger;
+import org.apache.ignite.configuration.DataStorageConfiguration;
+import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
+import 
org.apache.ignite.internal.processors.cache.persistence.filename.NodeFileTree;
+import 
org.apache.ignite.internal.processors.configuration.distributed.DistributedBooleanProperty;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.U;
+
+import static java.lang.String.format;
+import static 
org.apache.ignite.internal.processors.cache.persistence.wal.FileWriteAheadLogManager.CDC_DISABLED;
+import static 
org.apache.ignite.internal.processors.configuration.distributed.DistributedBooleanProperty.detachedBooleanProperty;
+import static 
org.apache.ignite.internal.util.io.GridFileUtils.ensureHardLinkAvailable;
+
+/**
+ * Links the archived WAL segments to the CDC directory. The links are not 
created while CDC is disabled by the
+ * {@link FileWriteAheadLogManager#CDC_DISABLED} distributed property. Data 
regions without persistence do not log the
+ * changes while CDC is disabled, so on the nodes with such regions the 
segment that is current at the disabling is never
+ * linked either: the CDC application fails on the missed segment after CDC is 
enabled again.
+ */
+class CdcLinkManager {
+    /** */
+    private final GridCacheSharedContext<?, ?> cctx;
+
+    /** */
+    private final IgniteLogger log;
+
+    /** */
+    private final NodeFileTree ft;
+
+    /** CDC disabled flag. */
+    private final DistributedBooleanProperty cdcDisabled = 
detachedBooleanProperty(CDC_DISABLED,
+        "CDC disabled flag. Disables CDC in the cluster to avoid disk 
overflow. " +
+            "Note that cache changes will be lost when CDC is disabled. Useful 
if the CDC application " +
+            "is down for a long time.");
+
+    /**
+     * Index of the segment that was current at the last CDC disabling. It is 
never linked, so the CDC application detects
+     * the missed changes as a gap in the segments even if no segment is 
archived while CDC is disabled. Persistent
+     * regions log the changes anyway, so the gap is made only on the nodes 
with in-memory CDC regions.
+     */
+    private volatile long disableSgmnt = -1;
+
+    /** */
+    CdcLinkManager(GridCacheSharedContext<?, ?> cctx) throws 
IgniteCheckedException {
+        this.cctx = cctx;
+
+        log = cctx.logger(CdcLinkManager.class);
+        ft = cctx.kernalContext().pdsFolderResolver().fileTree();
+
+        DataStorageConfiguration dsCfg = 
cctx.gridConfig().getDataStorageConfiguration();
+
+        // True on a node with persistence too, unlike 
FileWriteAheadLogManager#inMemoryCdc.
+        boolean inMemoryCdcRegion = F.exist(
+            F.concat(false, dsCfg.getDefaultDataRegionConfiguration(), 
F.asList(dsCfg.getDataRegionConfigurations())),
+            reg -> reg.isCdcEnabled() && !reg.isPersistenceEnabled());
+
+        U.ensureDirectory(ft.walCdc(), "change data capture directory", log);
+
+        ensureHardLinkAvailable(ft.walArchive().toPath(), 
ft.walCdc().toPath());
+
+        
cctx.kernalContext().internalSubscriptionProcessor().registerDistributedConfigurationListener(dispatcher
 -> {
+            cdcDisabled.addListener((name, oldVal, newVal) -> {
+                if (log.isInfoEnabled())
+                    log.info(format("Distributed property '%s' was changed 
from '%s' to '%s'.", name, oldVal, newVal));
+
+                if (newVal != null && newVal) {
+                    log.warning("CDC was disabled.");
+
+                    if (cctx.cdc() != null)
+                        cctx.cdc().stop(true);
+
+                    if (inMemoryCdcRegion)
+                        markDisableSegment();
+                }
+            });
+
+            dispatcher.registerProperty(cdcDisabled);
+        });
+    }
+
+    /** */
+    private void markDisableSegment() {

Review Comment:
   **[Minor]** `CdcLinkManager` is created by `FileWriteAheadLogManager` but 
reaches back to its owner through `cctx.wal(true)` (with its assert) just to 
read `currentSegment()`. Correctness here depends on `cctx.wal(true)` resolving 
to the same instance that owns this manager. Passing the owning manager or a 
`LongSupplier` for the current segment into the constructor removes the hidden 
dependency and makes it testable.



##########
modules/core/src/test/java/org/apache/ignite/cdc/CdcSelfTest.java:
##########
@@ -915,6 +951,12 @@ public void testCdcDirectoryMaxSize() throws Exception {
         f.cancel();
     }
 
+    /** */
+    private static List<Long> linkedSegments(NodeFileTree ft) {
+        return 
Arrays.stream(ft.walCdcSegments()).map(File::toPath).map(ft::walSegmentIndex).sorted()

Review Comment:
   **[Minor]** This "linked CDC segment indices" computation is now copy-pasted 
in three test classes (`CdcSelfTest.linkedSegments`, `WalForCdcTest`, 
`CdcCommandTest.checkLinks`) with small variations (sorted vs unsorted, `List` 
vs stream). One helper on `NodeFileTree` (e.g. `walCdcSegmentIndexes()`) or in 
`AbstractCdcTest` would cover all three.



-- 
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.

To unsubscribe, e-mail: [email protected]

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

Reply via email to