From 004aa45834b2e6abafa06056cc28832d39a249ab Mon Sep 17 00:00:00 2001 From: Ilya Shishkov Date: Mon, 16 Nov 2026 23:17:13 +0300 Subject: [PATCH 1/3] IGNITE-29301 Add command for clearing of CDC directory --- .../persistence/change-data-capture.adoc | 86 +++++++ .../apache/ignite/util/CdcCommandTest.java | 209 ++++++++++++++++++ .../management/cdc/CdcClearCommand.java | 82 +++++++ .../management/cdc/CdcClearCommandArg.java | 63 ++++++ .../internal/management/cdc/CdcClearTask.java | 158 +++++++++++++ .../internal/management/cdc/CdcCommand.java | 3 +- ...mmandHandlerClusterByClassTest_help.output | 7 + ...ndlerClusterByClassWithSSLTest_help.output | 7 + 8 files changed, 614 insertions(+), 1 deletion(-) create mode 100644 modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearCommand.java create mode 100644 modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearCommandArg.java create mode 100644 modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearTask.java diff --git a/docs/_docs/persistence/change-data-capture.adoc b/docs/_docs/persistence/change-data-capture.adoc index a83e1eda2498d..1e052352a66c8 100644 --- a/docs/_docs/persistence/change-data-capture.adoc +++ b/docs/_docs/persistence/change-data-capture.adoc @@ -156,6 +156,45 @@ IMPORTANT: `ignite-cdc.sh` implements the fail-fast approach. It just fails in c 5. Infinitely wait for the newly available segment and process it. 6. Stop the consumer in case of a failure or a received stop signal. +== Disabling CDC + +CDC can be disabled in the whole cluster with the `cdc.disabled` distributed property. While CDC is disabled, Ignite nodes +do not create WAL segment links in the CDC directory, so all cache changes made during this period will not be captured. +The CDC application is not stopped automatically and keeps processing the segment links created before. + +To disable or enable CDC, you can run the following link:tools/control-script[Control Script] commands: + +[source,shell] +---- +# Disable CDC in the cluster. +control.sh|bat --property set --name cdc.disabled --val true + +# Enable CDC in the cluster. +control.sh|bat --property set --name cdc.disabled --val false +---- + +To ensure CDC is disabled, get the current property value: + +[source,shell] +---- +control.sh|bat --property get --name cdc.disabled +---- + +CDC is disabled if the command prints `cdc.disabled = true`. The property change is also logged on every node with CDC configured: + +[source,text] +---- +Distributed property 'cdc.disabled' was changed from 'false' to 'true'. +CDC was disabled. +---- + +Each WAL segment archived while CDC is disabled produces the following log message: + +[source,text] +---- +Creation of segment CDC link skipped. 'cdc.disabled' distributed property is 'true'. +---- + == Handling skipped segments The CDC can be disabled manually or by configured directory maximum size. In this case a hard link creation will be skipped. @@ -207,6 +246,53 @@ The command will iterate over caches and writes primary copies of data entries t NOTE: There are no guarantees of notifying the CDC consumer on concurrent cache updates: use the `CdcEvent#version` to resolve version. +== Clear CDC directory + +Sometimes the CDC application has to start from scratch, for example, after a long CDC outage or when replication +is being set up again. In this case you can delete all WAL segment links and the CDC application state from the CDC directory. + +WARNING: All changes in deleted segment links will be lost! + +Before running the command: + + 1. Ensure CDC is disabled by the `cdc.disabled` distributed property. See link:#disabling-cdc[Disabling CDC]. + 2. Shut down the CDC application. The command fails if the CDC directory is locked by the running application. + +To clear the CDC directory you can run the following link:tools/control-script[Control Script] command: + +[source,shell] +---- +# Clear CDC directories on all server nodes. +control.sh|bat --cdc clear + +# Clear CDC directory on a node. +control.sh|bat --cdc clear --node-id node_id +---- + +NOTE: The command clears CDC directories only on the server nodes that are in the topology. CDC directories of offline +nodes are not cleared. After such a node joins the cluster, clear its CDC directory with the `--node-id` argument. + +By default, the command keeps the CDC mode, which defines where changes are captured: by the CDC application +(`CDC_UTILITY_ACTIVE`) or within the Ignite node (`IGNITE_NODE_ACTIVE`). To reset the CDC mode as well, add the `--reset-mode` argument: + +[source,shell] +---- +control.sh|bat --cdc clear --reset-mode +---- + +WARNING: With `--reset-mode`, the saved CDC mode is removed. If changes are captured by the CDC application +(`CDC_UTILITY_ACTIVE`), this mode is saved again only after an Ignite node restart with CDC enabled. So enable CDC first +(set the `cdc.disabled` distributed property to `false`), and then restart Ignite nodes. If CDC is enabled again without +restarting Ignite nodes, the CDC application ignores WAL segments, because it treats the removed mode as +`IGNITE_NODE_ACTIVE`. After CDC is enabled and Ignite nodes are restarted, the CDC application processes all accumulated WAL segments. + +NOTE: Changes made while CDC was disabled and changes in the cleared segment links are not transmitted to the destination +(e.g. a remote cluster). To synchronize data after clearing, you should enable CDC first, and then use the +link:#forcefully-resend-all-cache-data-to-cdc[resend command], a snapshot or other methods. +Data resent while CDC is disabled is not captured. + +IMPORTANT: Do not start the CDC application until the command succeeds. If the command fails, fix the reported error and run it again. + == cdc-ext Ignite extensions project has link:https://github.com/apache/ignite-extensions/tree/master/modules/cdc-ext[cdc-ext] module which provides two way to setup cross cluster replication based on CDC. diff --git a/modules/control-utility/src/test/java/org/apache/ignite/util/CdcCommandTest.java b/modules/control-utility/src/test/java/org/apache/ignite/util/CdcCommandTest.java index 241b3adc51eeb..e370e60733103 100644 --- a/modules/control-utility/src/test/java/org/apache/ignite/util/CdcCommandTest.java +++ b/modules/control-utility/src/test/java/org/apache/ignite/util/CdcCommandTest.java @@ -19,6 +19,7 @@ import java.io.File; import java.io.Serializable; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; @@ -86,6 +87,12 @@ public class CdcCommandTest extends GridCommandHandlerAbstractTest { /** */ public static final String RESEND = "resend"; + /** */ + public static final String CLEAR = "clear"; + + /** */ + public static final String RESET_MODE = "--reset-mode"; + /** */ private IgniteEx srv0; @@ -524,6 +531,208 @@ public void testResendOnClientJoin() throws Exception { waitForSize(cnsmr1, srv1.cache(DEFAULT_CACHE_NAME).localSize(CachePeekMode.PRIMARY)); } + /** */ + @Test + public void testCdcClearOnAllNodes() throws Exception { + injectTestSystemOut(); + + prepareForClear(); + + // Temporary mode state can remain if the CDC application failed while saving it. + File tmpModeState = grid(0).context().pdsFolderResolver().fileTree().tmpCdcModeState().toFile(); + + assertTrue(tmpModeState.createNewFile()); + + assertContains(log, executeCommand(EXIT_CODE_OK, CDC, CLEAR), "CDC directories were successfully cleared."); + + checkCdcCleared(0, true); + checkCdcCleared(1, true); + } + + /** */ + @Test + public void testCdcClearOnOneNode() throws Exception { + injectTestSystemOut(); + + prepareForClear(); + + assertContains(log, executeCommand(EXIT_CODE_OK, CDC, CLEAR, NODE_ID, grid(1).localNode().id().toString()), + "CDC directories were successfully cleared."); + + checkCdcNotCleared(0, 2); + checkCdcCleared(1, true); + } + + /** */ + @Test + public void testCdcClearOnClientNode() throws Exception { + injectTestSystemOut(); + + IgniteEx client = startClientGrid("client"); + + assertContains(log, executeCommand(EXIT_CODE_INVALID_ARGUMENTS, CDC, CLEAR, NODE_ID, client.localNode().id().toString()), + "Client nodes do not support CDC clear command."); + } + + /** */ + @Test + public void testCdcClearWithResetMode() throws Exception { + injectTestSystemOut(); + + prepareForClear(); + + assertContains(log, executeCommand(EXIT_CODE_OK, CDC, CLEAR, RESET_MODE), "CDC directories were successfully cleared."); + + checkCdcCleared(0, false); + checkCdcCleared(1, false); + } + + /** */ + @Test + public void testCdcClearWithDistributedProperty() throws Exception { + injectTestSystemOut(); + + assertContains(log, executeCommand(EXIT_CODE_UNEXPECTED_ERROR, CDC, CLEAR), "CDC was not disabled."); + + cdcDisabled.propagate(true); + + assertContains(log, executeCommand(EXIT_CODE_OK, CDC, CLEAR), "CDC directories were successfully cleared."); + + cdcDisabled.propagate(false); + + assertContains(log, executeCommand(EXIT_CODE_UNEXPECTED_ERROR, CDC, CLEAR), "CDC was not disabled."); + } + + /** */ + @Test + public void testCdcClearWithLockAcquire() throws Exception { + injectTestSystemOut(); + + runCdc(grid(0)); + + archiveSegment(); + + waitForCdcState(0); + + cdcDisabled.propagate(true); + + assertContains(log, executeCommand(EXIT_CODE_UNEXPECTED_ERROR, CDC, CLEAR), + "Unable to acquire lock to the CDC folder. Make sure a CDC app is shut down"); + + checkCdcNotCleared(0, 1); + checkCdcCleared(1, false); + + stopThreads(log); + + assertContains(log, executeCommand(EXIT_CODE_OK, CDC, CLEAR), "CDC directories were successfully cleared."); + + checkCdcCleared(0, true); + checkCdcCleared(1, false); + } + + /** Checks that the CDC application captures changes after the CDC directory is cleared. */ + @Test + public void testCdcCapturesChangesAfterClear() throws Exception { + injectTestSystemOut(); + + prepareForClear(); + + assertContains(log, executeCommand(EXIT_CODE_OK, CDC, CLEAR), "CDC directories were successfully cleared."); + + cdcDisabled.propagate(false); + + UserCdcConsumer cnsmr0 = runCdc(srv0); + UserCdcConsumer cnsmr1 = runCdc(srv1); + + addData(srv0.cache(DEFAULT_CACHE_NAME), KEYS_CNT, 2 * KEYS_CNT); + + checkPrimaryKeysCaptured(srv0, cnsmr0, KEYS_CNT, 2 * KEYS_CNT); + checkPrimaryKeysCaptured(srv1, cnsmr1, KEYS_CNT, 2 * KEYS_CNT); + } + + /** + * @param srv Server node. + * @param cnsmr CDC consumer of the node. + * @param from First key, inclusive. + * @param to Last key, exclusive. + */ + private void checkPrimaryKeysCaptured(IgniteEx srv, UserCdcConsumer cnsmr, int from, int to) throws Exception { + List expKeys = new ArrayList<>(); + + for (int key = from; key < to; key++) { + if (srv.affinity(DEFAULT_CACHE_NAME).isPrimary(srv.localNode(), key)) + expKeys.add(key); + } + + assertFalse(expKeys.isEmpty()); + + assertTrue(waitForCondition(() -> cnsmr.data(UPDATE, CU.cacheId(DEFAULT_CACHE_NAME)).containsAll(expKeys), + getTestTimeout())); + } + + /** */ + private void prepareForClear() throws Exception { + checkCdcCleared(0, false); + checkCdcCleared(1, false); + + runCdc(grid(0)); + runCdc(grid(1)); + + archiveSegment(); + + waitForCdcState(0); + waitForCdcState(1); + + stopThreads(log); + + // Segments archived after CDC applications stop are not processed and not deleted. + archiveSegment(); + archiveSegment(); + + cdcDisabled.propagate(true); + + checkCdcNotCleared(0, 2); + checkCdcNotCleared(1, 2); + } + + /** @param idx Node index. */ + private void waitForCdcState(int idx) throws Exception { + NodeFileTree ft = grid(idx).context().pdsFolderResolver().fileTree(); + + assertTrue(waitForCondition(() -> ft.cdcWalState().toFile().exists(), getTestTimeout())); + } + + /** + * @param idx Node index. + * @param minSegCnt Minimal expected count of segment links. + */ + private void checkCdcNotCleared(int idx, int minSegCnt) throws Exception { + NodeFileTree ft = grid(idx).context().pdsFolderResolver().fileTree(); + + assertTrue(waitForCondition(() -> ft.walCdcSegments().length >= minSegCnt, getTestTimeout())); + assertTrue(ft.cdcWalState().toFile().exists()); + assertTrue(ft.cdcModeState().toFile().exists()); + } + + /** + * @param idx Node index. + * @param modeExists Whether CDC mode state is expected to exist. + */ + private void checkCdcCleared(int idx, boolean modeExists) { + NodeFileTree ft = grid(idx).context().pdsFolderResolver().fileTree(); + + assertEquals(0, ft.walCdcSegments().length); + + assertEquals(modeExists, ft.cdcState().toFile().exists()); + + if (modeExists) { + File[] stateFiles = ft.cdcState().toFile().listFiles(); + + assertEquals("Only CDC mode state is expected", 1, stateFiles.length); + assertEquals("Unexpected state file", ft.cdcModeState().toFile(), stateFiles[0]); + } + } + /** */ public static UserCdcConsumer runCdc(Ignite ign) { UserCdcConsumer cnsmr = new UserCdcConsumer(); diff --git a/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearCommand.java b/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearCommand.java new file mode 100644 index 0000000000000..5c99e85441dd4 --- /dev/null +++ b/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearCommand.java @@ -0,0 +1,82 @@ +/* + * 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.management.cdc; + +import java.util.Collection; +import java.util.List; +import java.util.function.Consumer; +import org.apache.ignite.cluster.ClusterNode; +import org.apache.ignite.internal.management.api.ComputeCommand; + +import static org.apache.ignite.internal.management.api.CommandUtils.node; +import static org.apache.ignite.internal.management.api.CommandUtils.servers; + +/** Command to clear CDC directory. */ +public class CdcClearCommand implements ComputeCommand { + /** {@inheritDoc} */ + @Override public String description() { + return "Clear CDC directory: delete WAL segment links and CDC application state"; + } + + /** {@inheritDoc} */ + @Override public Class argClass() { + return CdcClearCommandArg.class; + } + + /** {@inheritDoc} */ + @Override public Class taskClass() { + return CdcClearTask.class; + } + + /** {@inheritDoc} */ + @Override public Collection nodes(Collection nodes, CdcClearCommandArg arg) { + if (arg.nodeId() == null) + return servers(nodes); + + List node = node(arg.nodeId(), nodes); + + if (node.get(0).isClient()) + throw new IllegalArgumentException("You specified a client node id. Client nodes do not support CDC clear command."); + + return node; + } + + /** {@inheritDoc} */ + @Override public void printResult(CdcClearCommandArg arg, Void res, Consumer printer) { + printer.accept("CDC directories were successfully cleared."); + } + + /** {@inheritDoc} */ + @Override public String confirmationPrompt(CdcClearCommandArg arg) { + String prompt = """ + Warning: The command will delete all WAL segment links and CDC application state from the CDC directory. + CDC must be disabled by the 'cdc.disabled' distributed property and the CDC application must be shut down. + All changes in deleted segment links will be lost! + To synchronize data after clearing, enable CDC first, and then use the '--cdc resend' command, \ + a snapshot or other methods."""; + + if (arg.resetMode()) { + prompt += """ + + CDC mode state will be deleted too. The CDC application will not capture changes \ + until CDC is enabled and Ignite nodes are restarted."""; + } + + return prompt; + } +} diff --git a/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearCommandArg.java b/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearCommandArg.java new file mode 100644 index 0000000000000..ce2b5df9db1f2 --- /dev/null +++ b/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearCommandArg.java @@ -0,0 +1,63 @@ +/* + * 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.management.cdc; + +import java.util.UUID; +import org.apache.ignite.internal.Order; +import org.apache.ignite.internal.dto.IgniteDataTransferObject; +import org.apache.ignite.internal.management.api.Argument; +import org.apache.ignite.internal.management.api.CliConfirmArgument; + +/** */ +@CliConfirmArgument +public class CdcClearCommandArg extends IgniteDataTransferObject { + /** */ + private static final long serialVersionUID = 0; + + /** */ + @Order(0) + @Argument(optional = true, description = "ID of the node to clear CDC directory from. " + + "If not set, the command will affect all server nodes") + UUID nodeId; + + /** */ + @Order(1) + @Argument(optional = true, description = "Also delete the CDC mode state. The CDC application will not " + + "capture changes until CDC is enabled and Ignite nodes are restarted") + boolean resetMode; + + /** */ + public UUID nodeId() { + return nodeId; + } + + /** */ + public void nodeId(UUID nodeId) { + this.nodeId = nodeId; + } + + /** */ + public boolean resetMode() { + return resetMode; + } + + /** */ + public void resetMode(boolean resetMode) { + this.resetMode = resetMode; + } +} diff --git a/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearTask.java b/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearTask.java new file mode 100644 index 0000000000000..fc4ddab575ccb --- /dev/null +++ b/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearTask.java @@ -0,0 +1,158 @@ +/* + * 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.management.cdc; + +import java.io.File; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.apache.ignite.IgniteCheckedException; +import org.apache.ignite.IgniteException; +import org.apache.ignite.IgniteLogger; +import org.apache.ignite.compute.ComputeJobResult; +import org.apache.ignite.internal.GridKernalContext; +import org.apache.ignite.internal.cdc.CdcFileLockHolder; +import org.apache.ignite.internal.processors.cache.persistence.filename.NodeFileTree; +import org.apache.ignite.internal.processors.task.GridInternal; +import org.apache.ignite.internal.util.typedef.internal.CU; +import org.apache.ignite.internal.util.typedef.internal.U; +import org.apache.ignite.internal.visor.VisorJob; +import org.apache.ignite.internal.visor.VisorMultiNodeTask; +import org.apache.ignite.resources.LoggerResource; +import org.jetbrains.annotations.Nullable; + +import static org.apache.ignite.internal.processors.cache.persistence.wal.FileWriteAheadLogManager.CDC_DISABLED; + +/** Task to clear CDC directory. */ +@GridInternal +public class CdcClearTask extends VisorMultiNodeTask { + /** */ + private static final long serialVersionUID = 0L; + + /** {@inheritDoc} */ + @Override protected VisorJob job(CdcClearCommandArg arg) { + return new CdcClearJob(arg, false); + } + + /** {@inheritDoc} */ + @Override protected @Nullable Void reduce0(List results) throws IgniteException { + for (ComputeJobResult res : results) { + if (res.getException() != null) { + throw new IgniteException("Failed to clear CDC directory on a node " + + "[nodeId=" + res.getNode().id() + "]. The command can be rerun after fixing the error.", + res.getException()); + } + } + + return null; + } + + /** */ + private static class CdcClearJob extends VisorJob { + /** */ + private static final long serialVersionUID = 0L; + + /** */ + @LoggerResource + protected IgniteLogger log; + + /** */ + protected CdcClearJob(CdcClearCommandArg arg, boolean debug) { + super(arg, debug); + } + + /** {@inheritDoc} */ + @Override protected Void run(CdcClearCommandArg arg) throws IgniteException { + GridKernalContext ctx = ignite.context(); + + if (!CU.isCdcEnabled(ignite.configuration())) + throw new IgniteException("CDC is not configured."); + + if (!ctx.distributedConfiguration().property(CDC_DISABLED).getOrDefault(false)) + throw new IgniteException("CDC was not disabled."); + + NodeFileTree ft = ctx.pdsFolderResolver().fileTree(); + + CdcFileLockHolder lock = new CdcFileLockHolder(ft.walCdc().getAbsolutePath(), "Clear CDC job", log); + + try { + lock.tryLock(1); + + // Temporary state files can remain if the CDC application failed while saving its state. + Stream statePaths = Stream.of( + ft.cdcWalState(), ft.tmpCdcWalState(), + ft.cdcCachesState(), ft.tmpCdcCachesState(), + ft.cdcMappingsState(), ft.tmpCdcMappingsState(), + ft.cdcTypesState(), ft.tmpCdcTypesState(), + ft.tmpCdcModeState()); + + // Mode state is kept by default: without it the CDC application waits for CdcManagerStopRecord, which a + // running node does not log again (the default CdcManager logs it only once after node start, a custom + // one once on stop). So if mode state is cleared, changes would not be captured by CDC application + // until node restart with enabled CDC: segments archived while CDC is disabled are not linked. + if (arg.resetMode()) + statePaths = Stream.concat(statePaths, Stream.of(ft.cdcModeState())); + + List stateFiles = statePaths.map(Path::toFile) + .filter(File::exists) + .collect(Collectors.toList()); + + // State is deleted first: if deletion of segment links fails, the CDC application will not continue + // from the saved state. + delete(stateFiles); + + // With mode reset the state directory is expected to be empty, otherwise it contains the mode state. + if (arg.resetMode()) { + File cdcStateDir = ft.cdcState().toFile(); + + if (cdcStateDir.exists() && !cdcStateDir.delete()) { + throw new IgniteException("Failed to delete state directory [cdcStateDir=" + + cdcStateDir.getAbsolutePath() + "]. Check it is empty or your access rights."); + } + } + + List segments = Arrays.asList(ft.walCdcSegments()); + + delete(segments); + + log.info("CDC directory cleared [dir=" + ft.walCdc().getAbsolutePath() + + ", deletedStateFilesCnt=" + stateFiles.size() + ", deletedSegmentLinksCnt=" + segments.size() + ']'); + + return null; + } + catch (IgniteCheckedException e) { + throw new IgniteException("Failed to clear CDC directory. " + + "Unable to acquire lock to the CDC folder. Make sure a CDC app is shut down " + + "[dir=" + ft.walCdc().getAbsolutePath() + ", reason=" + e.getMessage() + ']', e); + } + finally { + U.closeQuiet(lock); + } + } + + /** @param files Files to delete. */ + private static void delete(List files) { + for (File file : files) { + if (!file.delete()) + throw new IgniteException("Failed to delete CDC file [file=" + file.getAbsolutePath() + ']'); + } + } + } +} diff --git a/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcCommand.java b/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcCommand.java index a1ce8eb457b23..79685964bc4f5 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcCommand.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcCommand.java @@ -25,7 +25,8 @@ public class CdcCommand extends CommandRegistryImpl { public CdcCommand() { super( new CdcDeleteLostSegmentLinksCommand(), - new CdcResendCommand() + new CdcResendCommand(), + new CdcClearCommand() ); } } diff --git a/modules/core/src/test/resources/org.apache.ignite.util/GridCommandHandlerClusterByClassTest_help.output b/modules/core/src/test/resources/org.apache.ignite.util/GridCommandHandlerClusterByClassTest_help.output index 91fead434ad99..72dcdba8e7f0a 100644 --- a/modules/core/src/test/resources/org.apache.ignite.util/GridCommandHandlerClusterByClassTest_help.output +++ b/modules/core/src/test/resources/org.apache.ignite.util/GridCommandHandlerClusterByClassTest_help.output @@ -430,6 +430,13 @@ If the file name isn't specified the output file name is: '.bin': Parameters: --caches cache1,...,cacheN - specifies a comma-separated list of cache names. + Clear CDC directory: delete WAL segment links and CDC application state: + control.(sh|bat) --cdc clear [--node-id node_id] [--reset-mode] [--yes] + + Parameters: + --node-id node_id - ID of the node to clear CDC directory from. If not set, the command will affect all server nodes. + --reset-mode - Also delete the CDC mode state. The CDC application will not capture changes until CDC is enabled and Ignite nodes are restarted. + [EXPERIMENTAL] Check/Repair cache consistency using Read Repair approach: control.(sh|bat) --consistency repair --cache cache --partitions partition --strategy LWW|PRIMARY|RELATIVE_MAJORITY|REMOVE|CHECK_ONLY [--parallel] diff --git a/modules/core/src/test/resources/org.apache.ignite.util/GridCommandHandlerClusterByClassWithSSLTest_help.output b/modules/core/src/test/resources/org.apache.ignite.util/GridCommandHandlerClusterByClassWithSSLTest_help.output index 158f8d3b5f4f0..30c4aa6116e74 100644 --- a/modules/core/src/test/resources/org.apache.ignite.util/GridCommandHandlerClusterByClassWithSSLTest_help.output +++ b/modules/core/src/test/resources/org.apache.ignite.util/GridCommandHandlerClusterByClassWithSSLTest_help.output @@ -430,6 +430,13 @@ If the file name isn't specified the output file name is: '.bin': Parameters: --caches cache1,...,cacheN - specifies a comma-separated list of cache names. + Clear CDC directory: delete WAL segment links and CDC application state: + control.(sh|bat) --cdc clear [--node-id node_id] [--reset-mode] [--yes] + + Parameters: + --node-id node_id - ID of the node to clear CDC directory from. If not set, the command will affect all server nodes. + --reset-mode - Also delete the CDC mode state. The CDC application will not capture changes until CDC is enabled and Ignite nodes are restarted. + [EXPERIMENTAL] Check/Repair cache consistency using Read Repair approach: control.(sh|bat) --consistency repair --cache cache --partitions partition --strategy LWW|PRIMARY|RELATIVE_MAJORITY|REMOVE|CHECK_ONLY [--parallel] From 9aee649d50a1cf01f71e9ffb1ed75b5639211dfc Mon Sep 17 00:00:00 2001 From: Ilya Shishkov Date: Mon, 23 Nov 2026 17:18:49 +0300 Subject: [PATCH 2/3] IGNITE-29301 AI code-review fixes. --- .../persistence/change-data-capture.adoc | 87 +++--------- .../apache/ignite/util/CdcCommandTest.java | 129 +++++++++++------- .../management/cdc/CdcClearCommand.java | 7 +- .../management/cdc/CdcClearCommandArg.java | 2 +- .../internal/management/cdc/CdcClearTask.java | 111 +++++++-------- ...mmandHandlerClusterByClassTest_help.output | 2 +- ...ndlerClusterByClassWithSSLTest_help.output | 2 +- 7 files changed, 166 insertions(+), 174 deletions(-) diff --git a/docs/_docs/persistence/change-data-capture.adoc b/docs/_docs/persistence/change-data-capture.adoc index 1e052352a66c8..766d6c0914fe5 100644 --- a/docs/_docs/persistence/change-data-capture.adoc +++ b/docs/_docs/persistence/change-data-capture.adoc @@ -83,7 +83,8 @@ The distributed properties listed in the table below allow you to configure CDC |=== |Property | Description | Default Value |`cdc.disabled`| 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. | false +is disabled. Useful if the CDC application is down for a long time. +See link:tools/control-script#working-with-cluster-properties[Working with Cluster Properties]. | false |=== == API @@ -156,45 +157,6 @@ IMPORTANT: `ignite-cdc.sh` implements the fail-fast approach. It just fails in c 5. Infinitely wait for the newly available segment and process it. 6. Stop the consumer in case of a failure or a received stop signal. -== Disabling CDC - -CDC can be disabled in the whole cluster with the `cdc.disabled` distributed property. While CDC is disabled, Ignite nodes -do not create WAL segment links in the CDC directory, so all cache changes made during this period will not be captured. -The CDC application is not stopped automatically and keeps processing the segment links created before. - -To disable or enable CDC, you can run the following link:tools/control-script[Control Script] commands: - -[source,shell] ----- -# Disable CDC in the cluster. -control.sh|bat --property set --name cdc.disabled --val true - -# Enable CDC in the cluster. -control.sh|bat --property set --name cdc.disabled --val false ----- - -To ensure CDC is disabled, get the current property value: - -[source,shell] ----- -control.sh|bat --property get --name cdc.disabled ----- - -CDC is disabled if the command prints `cdc.disabled = true`. The property change is also logged on every node with CDC configured: - -[source,text] ----- -Distributed property 'cdc.disabled' was changed from 'false' to 'true'. -CDC was disabled. ----- - -Each WAL segment archived while CDC is disabled produces the following log message: - -[source,text] ----- -Creation of segment CDC link skipped. 'cdc.disabled' distributed property is 'true'. ----- - == Handling skipped segments The CDC can be disabled manually or by configured directory maximum size. In this case a hard link creation will be skipped. @@ -251,15 +213,16 @@ NOTE: There are no guarantees of notifying the CDC consumer on concurrent cache Sometimes the CDC application has to start from scratch, for example, after a long CDC outage or when replication is being set up again. In this case you can delete all WAL segment links and the CDC application state from the CDC directory. -WARNING: All changes in deleted segment links will be lost! +NOTE: Use the link:#handling-skipped-segments[`--cdc delete_lost_segment_links`] command if the CDC application fails +because of skipped segments. Use the `--cdc clear` command to drop all the accumulated changes and the CDC application state. -Before running the command: - - 1. Ensure CDC is disabled by the `cdc.disabled` distributed property. See link:#disabling-cdc[Disabling CDC]. - 2. Shut down the CDC application. The command fails if the CDC directory is locked by the running application. +WARNING: All changes in deleted segment links will be lost! -To clear the CDC directory you can run the following link:tools/control-script[Control Script] command: +To clear the CDC directory, follow the steps below. Steps 3–5 are required only if changes must be captured after clearing. + 1. Shut down the CDC application. The command fails if the CDC directory is locked by the running application. + 2. Run the following link:tools/control-script[Control Script] command: ++ [source,shell] ---- # Clear CDC directories on all server nodes. @@ -267,31 +230,23 @@ control.sh|bat --cdc clear # Clear CDC directory on a node. control.sh|bat --cdc clear --node-id node_id ----- -NOTE: The command clears CDC directories only on the server nodes that are in the topology. CDC directories of offline -nodes are not cleared. After such a node joins the cluster, clear its CDC directory with the `--node-id` argument. - -By default, the command keeps the CDC mode, which defines where changes are captured: by the CDC application -(`CDC_UTILITY_ACTIVE`) or within the Ignite node (`IGNITE_NODE_ACTIVE`). To reset the CDC mode as well, add the `--reset-mode` argument: - -[source,shell] ----- +# Clear CDC directories completely, including the CDC mode state. control.sh|bat --cdc clear --reset-mode ---- ++ +If the command fails, fix the reported error and run it again. Do not start the CDC application until the command succeeds. + 3. If the command was run with `--reset-mode`, restart the cleared Ignite nodes with CDC enabled (before the restart, make sure +the `cdc.disabled` distributed property is set to `false`). Without the restart, the CDC application does not capture changes. + 4. Start the CDC application. + 5. Synchronize data with the destination (e.g. a remote cluster), because changes in the cleared segment links are not +transmitted. Use the link:#forcefully-resend-all-cache-data-to-cdc[resend command], a snapshot or other methods. -WARNING: With `--reset-mode`, the saved CDC mode is removed. If changes are captured by the CDC application -(`CDC_UTILITY_ACTIVE`), this mode is saved again only after an Ignite node restart with CDC enabled. So enable CDC first -(set the `cdc.disabled` distributed property to `false`), and then restart Ignite nodes. If CDC is enabled again without -restarting Ignite nodes, the CDC application ignores WAL segments, because it treats the removed mode as -`IGNITE_NODE_ACTIVE`. After CDC is enabled and Ignite nodes are restarted, the CDC application processes all accumulated WAL segments. - -NOTE: Changes made while CDC was disabled and changes in the cleared segment links are not transmitted to the destination -(e.g. a remote cluster). To synchronize data after clearing, you should enable CDC first, and then use the -link:#forcefully-resend-all-cache-data-to-cdc[resend command], a snapshot or other methods. -Data resent while CDC is disabled is not captured. +NOTE: There is no need to disable CDC with the `cdc.disabled` distributed property before clearing. Segment links created +after clearing are kept, and the CDC application consumes them after start. -IMPORTANT: Do not start the CDC application until the command succeeds. If the command fails, fix the reported error and run it again. +NOTE: The command clears CDC directories only on the server nodes that are in the topology. CDC directories of offline +nodes are not cleared. After such a node joins the cluster, clear its CDC directory with the `--node-id` argument. == cdc-ext diff --git a/modules/control-utility/src/test/java/org/apache/ignite/util/CdcCommandTest.java b/modules/control-utility/src/test/java/org/apache/ignite/util/CdcCommandTest.java index e370e60733103..9047769f39907 100644 --- a/modules/control-utility/src/test/java/org/apache/ignite/util/CdcCommandTest.java +++ b/modules/control-utility/src/test/java/org/apache/ignite/util/CdcCommandTest.java @@ -539,14 +539,17 @@ public void testCdcClearOnAllNodes() throws Exception { prepareForClear(); // Temporary mode state can remain if the CDC application failed while saving it. - File tmpModeState = grid(0).context().pdsFolderResolver().fileTree().tmpCdcModeState().toFile(); + File tmpModeState = fileTree(0).tmpCdcModeState().toFile(); assertTrue(tmpModeState.createNewFile()); + File[] links0 = cdcLinks(0); + File[] links1 = cdcLinks(1); + assertContains(log, executeCommand(EXIT_CODE_OK, CDC, CLEAR), "CDC directories were successfully cleared."); - checkCdcCleared(0, true); - checkCdcCleared(1, true); + checkCdcCleared(0, links0, true); + checkCdcCleared(1, links1, true); } /** */ @@ -556,11 +559,13 @@ public void testCdcClearOnOneNode() throws Exception { prepareForClear(); + File[] links1 = cdcLinks(1); + assertContains(log, executeCommand(EXIT_CODE_OK, CDC, CLEAR, NODE_ID, grid(1).localNode().id().toString()), "CDC directories were successfully cleared."); checkCdcNotCleared(0, 2); - checkCdcCleared(1, true); + checkCdcCleared(1, links1, true); } /** */ @@ -581,26 +586,13 @@ public void testCdcClearWithResetMode() throws Exception { prepareForClear(); - assertContains(log, executeCommand(EXIT_CODE_OK, CDC, CLEAR, RESET_MODE), "CDC directories were successfully cleared."); - - checkCdcCleared(0, false); - checkCdcCleared(1, false); - } - - /** */ - @Test - public void testCdcClearWithDistributedProperty() throws Exception { - injectTestSystemOut(); - - assertContains(log, executeCommand(EXIT_CODE_UNEXPECTED_ERROR, CDC, CLEAR), "CDC was not disabled."); - - cdcDisabled.propagate(true); + File[] links0 = cdcLinks(0); + File[] links1 = cdcLinks(1); - assertContains(log, executeCommand(EXIT_CODE_OK, CDC, CLEAR), "CDC directories were successfully cleared."); - - cdcDisabled.propagate(false); + assertContains(log, executeCommand(EXIT_CODE_OK, CDC, CLEAR, RESET_MODE), "CDC directories were successfully cleared."); - assertContains(log, executeCommand(EXIT_CODE_UNEXPECTED_ERROR, CDC, CLEAR), "CDC was not disabled."); + checkCdcCleared(0, links0, false); + checkCdcCleared(1, links1, false); } /** */ @@ -614,40 +606,49 @@ public void testCdcClearWithLockAcquire() throws Exception { waitForCdcState(0); - cdcDisabled.propagate(true); + File[] links1 = cdcLinks(1); + + assertTrue(links1.length > 0); assertContains(log, executeCommand(EXIT_CODE_UNEXPECTED_ERROR, CDC, CLEAR), "Unable to acquire lock to the CDC folder. Make sure a CDC app is shut down"); checkCdcNotCleared(0, 1); - checkCdcCleared(1, false); + checkCdcCleared(1, links1, true); stopThreads(log); + File[] links0 = cdcLinks(0); + + links1 = cdcLinks(1); + assertContains(log, executeCommand(EXIT_CODE_OK, CDC, CLEAR), "CDC directories were successfully cleared."); - checkCdcCleared(0, true); - checkCdcCleared(1, false); + checkCdcCleared(0, links0, true); + checkCdcCleared(1, links1, true); } - /** Checks that the CDC application captures changes after the CDC directory is cleared. */ + /** + * Checks that the CDC application captures changes after the CDC directory is cleared. The CDC application is not + * started on the second node before clear, so its CDC mode is not saved. + */ @Test public void testCdcCapturesChangesAfterClear() throws Exception { injectTestSystemOut(); - prepareForClear(); + prepareForClear(false); - assertContains(log, executeCommand(EXIT_CODE_OK, CDC, CLEAR), "CDC directories were successfully cleared."); + assertFalse(fileTree(1).cdcModeState().toFile().exists()); - cdcDisabled.propagate(false); + assertContains(log, executeCommand(EXIT_CODE_OK, CDC, CLEAR), "CDC directories were successfully cleared."); - UserCdcConsumer cnsmr0 = runCdc(srv0); - UserCdcConsumer cnsmr1 = runCdc(srv1); + UserCdcConsumer cnsmr0 = runCdc(grid(0)); + UserCdcConsumer cnsmr1 = runCdc(grid(1)); - addData(srv0.cache(DEFAULT_CACHE_NAME), KEYS_CNT, 2 * KEYS_CNT); + addData(grid(0).cache(DEFAULT_CACHE_NAME), KEYS_CNT, 2 * KEYS_CNT); - checkPrimaryKeysCaptured(srv0, cnsmr0, KEYS_CNT, 2 * KEYS_CNT); - checkPrimaryKeysCaptured(srv1, cnsmr1, KEYS_CNT, 2 * KEYS_CNT); + checkPrimaryKeysCaptured(grid(0), cnsmr0, KEYS_CNT, 2 * KEYS_CNT); + checkPrimaryKeysCaptured(grid(1), cnsmr1, KEYS_CNT, 2 * KEYS_CNT); } /** @@ -672,16 +673,29 @@ private void checkPrimaryKeysCaptured(IgniteEx srv, UserCdcConsumer cnsmr, int f /** */ private void prepareForClear() throws Exception { - checkCdcCleared(0, false); - checkCdcCleared(1, false); + prepareForClear(true); + } + + /** @param runCdcOnSecondNode Whether to run the CDC application on the second node. */ + private void prepareForClear(boolean runCdcOnSecondNode) throws Exception { + for (int i = 0; i < 2; i++) { + NodeFileTree ft = fileTree(i); + + assertEquals(0, ft.walCdcSegments().length); + assertFalse(ft.cdcState().toFile().exists()); + } runCdc(grid(0)); - runCdc(grid(1)); + + if (runCdcOnSecondNode) + runCdc(grid(1)); archiveSegment(); waitForCdcState(0); - waitForCdcState(1); + + if (runCdcOnSecondNode) + waitForCdcState(1); stopThreads(log); @@ -689,15 +703,15 @@ private void prepareForClear() throws Exception { archiveSegment(); archiveSegment(); - cdcDisabled.propagate(true); - checkCdcNotCleared(0, 2); - checkCdcNotCleared(1, 2); + + if (runCdcOnSecondNode) + checkCdcNotCleared(1, 2); } /** @param idx Node index. */ private void waitForCdcState(int idx) throws Exception { - NodeFileTree ft = grid(idx).context().pdsFolderResolver().fileTree(); + NodeFileTree ft = fileTree(idx); assertTrue(waitForCondition(() -> ft.cdcWalState().toFile().exists(), getTestTimeout())); } @@ -707,7 +721,7 @@ private void waitForCdcState(int idx) throws Exception { * @param minSegCnt Minimal expected count of segment links. */ private void checkCdcNotCleared(int idx, int minSegCnt) throws Exception { - NodeFileTree ft = grid(idx).context().pdsFolderResolver().fileTree(); + NodeFileTree ft = fileTree(idx); assertTrue(waitForCondition(() -> ft.walCdcSegments().length >= minSegCnt, getTestTimeout())); assertTrue(ft.cdcWalState().toFile().exists()); @@ -716,12 +730,33 @@ private void checkCdcNotCleared(int idx, int minSegCnt) throws Exception { /** * @param idx Node index. + * @return CDC segment links of the node. + */ + private File[] cdcLinks(int idx) { + return fileTree(idx).walCdcSegments(); + } + + /** + * @param idx Node index. + * @return File tree of the node. + */ + private NodeFileTree fileTree(int idx) { + return grid(idx).context().pdsFolderResolver().fileTree(); + } + + /** + * Checks that the CDC directory is cleared. Links created after clearing are kept, because CDC is enabled and + * segments can be archived by timeout. + * + * @param idx Node index. + * @param links Segment links existed before clearing. * @param modeExists Whether CDC mode state is expected to exist. */ - private void checkCdcCleared(int idx, boolean modeExists) { - NodeFileTree ft = grid(idx).context().pdsFolderResolver().fileTree(); + private void checkCdcCleared(int idx, File[] links, boolean modeExists) { + NodeFileTree ft = fileTree(idx); - assertEquals(0, ft.walCdcSegments().length); + for (File link : links) + assertFalse("Segment link is not deleted: " + link, link.exists()); assertEquals(modeExists, ft.cdcState().toFile().exists()); diff --git a/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearCommand.java b/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearCommand.java index 5c99e85441dd4..c1230418085be 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearCommand.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearCommand.java @@ -65,16 +65,15 @@ public class CdcClearCommand implements ComputeCommand @Override public String confirmationPrompt(CdcClearCommandArg arg) { String prompt = """ Warning: The command will delete all WAL segment links and CDC application state from the CDC directory. - CDC must be disabled by the 'cdc.disabled' distributed property and the CDC application must be shut down. + The CDC application must be shut down. All changes in deleted segment links will be lost! - To synchronize data after clearing, enable CDC first, and then use the '--cdc resend' command, \ - a snapshot or other methods."""; + To synchronize data after clearing, use the '--cdc resend' command, a snapshot or other methods."""; if (arg.resetMode()) { prompt += """ CDC mode state will be deleted too. The CDC application will not capture changes \ - until CDC is enabled and Ignite nodes are restarted."""; + until Ignite nodes are restarted."""; } return prompt; diff --git a/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearCommandArg.java b/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearCommandArg.java index ce2b5df9db1f2..f977645cb0002 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearCommandArg.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearCommandArg.java @@ -38,7 +38,7 @@ public class CdcClearCommandArg extends IgniteDataTransferObject { /** */ @Order(1) @Argument(optional = true, description = "Also delete the CDC mode state. The CDC application will not " + - "capture changes until CDC is enabled and Ignite nodes are restarted") + "capture changes until Ignite nodes are restarted") boolean resetMode; /** */ diff --git a/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearTask.java b/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearTask.java index fc4ddab575ccb..d6b4cedf63a73 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearTask.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearTask.java @@ -18,17 +18,18 @@ package org.apache.ignite.internal.management.cdc; import java.io.File; +import java.io.IOException; +import java.nio.file.Files; import java.nio.file.Path; -import java.util.Arrays; import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.Stream; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteException; import org.apache.ignite.IgniteLogger; import org.apache.ignite.compute.ComputeJobResult; -import org.apache.ignite.internal.GridKernalContext; +import org.apache.ignite.internal.cdc.CdcConsumerState; import org.apache.ignite.internal.cdc.CdcFileLockHolder; +import org.apache.ignite.internal.cdc.CdcMode; +import org.apache.ignite.internal.cdc.CdcUtilityActiveCdcManager; import org.apache.ignite.internal.processors.cache.persistence.filename.NodeFileTree; import org.apache.ignite.internal.processors.task.GridInternal; import org.apache.ignite.internal.util.typedef.internal.CU; @@ -38,8 +39,6 @@ import org.apache.ignite.resources.LoggerResource; import org.jetbrains.annotations.Nullable; -import static org.apache.ignite.internal.processors.cache.persistence.wal.FileWriteAheadLogManager.CDC_DISABLED; - /** Task to clear CDC directory. */ @GridInternal public class CdcClearTask extends VisorMultiNodeTask { @@ -80,60 +79,33 @@ protected CdcClearJob(CdcClearCommandArg arg, boolean debug) { /** {@inheritDoc} */ @Override protected Void run(CdcClearCommandArg arg) throws IgniteException { - GridKernalContext ctx = ignite.context(); - if (!CU.isCdcEnabled(ignite.configuration())) throw new IgniteException("CDC is not configured."); - if (!ctx.distributedConfiguration().property(CDC_DISABLED).getOrDefault(false)) - throw new IgniteException("CDC was not disabled."); - - NodeFileTree ft = ctx.pdsFolderResolver().fileTree(); + NodeFileTree ft = ignite.context().pdsFolderResolver().fileTree(); CdcFileLockHolder lock = new CdcFileLockHolder(ft.walCdc().getAbsolutePath(), "Clear CDC job", log); try { lock.tryLock(1); - // Temporary state files can remain if the CDC application failed while saving its state. - Stream statePaths = Stream.of( - ft.cdcWalState(), ft.tmpCdcWalState(), - ft.cdcCachesState(), ft.tmpCdcCachesState(), - ft.cdcMappingsState(), ft.tmpCdcMappingsState(), - ft.cdcTypesState(), ft.tmpCdcTypesState(), - ft.tmpCdcModeState()); - - // Mode state is kept by default: without it the CDC application waits for CdcManagerStopRecord, which a - // running node does not log again (the default CdcManager logs it only once after node start, a custom - // one once on stop). So if mode state is cleared, changes would not be captured by CDC application - // until node restart with enabled CDC: segments archived while CDC is disabled are not linked. - if (arg.resetMode()) - statePaths = Stream.concat(statePaths, Stream.of(ft.cdcModeState())); - - List stateFiles = statePaths.map(Path::toFile) - .filter(File::exists) - .collect(Collectors.toList()); - - // State is deleted first: if deletion of segment links fails, the CDC application will not continue - // from the saved state. - delete(stateFiles); - - // With mode reset the state directory is expected to be empty, otherwise it contains the mode state. - if (arg.resetMode()) { - File cdcStateDir = ft.cdcState().toFile(); + // Links go first: if deletion fails midway, the kept state prevents the CDC application from silently + // replaying the remaining links. + File[] links = ft.walCdcSegments(); - if (cdcStateDir.exists() && !cdcStateDir.delete()) { - throw new IgniteException("Failed to delete state directory [cdcStateDir=" + - cdcStateDir.getAbsolutePath() + "]. Check it is empty or your access rights."); - } - } - - List segments = Arrays.asList(ft.walCdcSegments()); + for (File link : links) + Files.delete(link.toPath()); - delete(segments); + if (arg.resetMode()) { + if (Files.exists(ft.cdcState()) && !U.delete(ft.cdcState())) + throw new IgniteException("Failed to delete CDC state directory [dir=" + ft.cdcState() + ']'); + } + else { + deleteStateExceptMode(ft); + saveUtilityActiveModeIfAbsent(ft); + } - log.info("CDC directory cleared [dir=" + ft.walCdc().getAbsolutePath() + - ", deletedStateFilesCnt=" + stateFiles.size() + ", deletedSegmentLinksCnt=" + segments.size() + ']'); + log.info("CDC directory cleared [dir=" + ft.walCdc().getAbsolutePath() + ", deletedLinksCnt=" + links.length + ']'); return null; } @@ -142,17 +114,48 @@ protected CdcClearJob(CdcClearCommandArg arg, boolean debug) { "Unable to acquire lock to the CDC folder. Make sure a CDC app is shut down " + "[dir=" + ft.walCdc().getAbsolutePath() + ", reason=" + e.getMessage() + ']', e); } + catch (IOException e) { + throw new IgniteException("Failed to clear CDC directory [dir=" + ft.walCdc().getAbsolutePath() + ']', e); + } finally { U.closeQuiet(lock); } } - /** @param files Files to delete. */ - private static void delete(List files) { - for (File file : files) { - if (!file.delete()) - throw new IgniteException("Failed to delete CDC file [file=" + file.getAbsolutePath() + ']'); - } + /** + * Deletes CDC application state except the mode: without the mode the CDC application waits for + * {@code CdcManagerStopRecord}, which a running node does not log again. + * + * @param ft Node file tree. + */ + private void deleteStateExceptMode(NodeFileTree ft) throws IOException { + // Temporary files remain if the CDC application failed while saving state. + List stateFiles = List.of( + ft.cdcWalState(), ft.tmpCdcWalState(), + ft.cdcCachesState(), ft.tmpCdcCachesState(), + ft.cdcMappingsState(), ft.tmpCdcMappingsState(), + ft.cdcTypesState(), ft.tmpCdcTypesState(), + ft.tmpCdcModeState()); + + for (Path file : stateFiles) + Files.deleteIfExists(file); + } + + /** + * Saves {@link CdcMode#CDC_UTILITY_ACTIVE} mode if the default CDC manager is used and the mode is not saved yet: + * the {@code CdcManagerStopRecord} switching the CDC application to this mode is logged once on node start and may + * be in a deleted link. + * + * @param ft Node file tree. + */ + private void saveUtilityActiveModeIfAbsent(NodeFileTree ft) throws IOException { + if (!(ignite.context().cache().context().cdc() instanceof CdcUtilityActiveCdcManager) || Files.exists(ft.cdcModeState())) + return; + + // Absent if the CDC application has never started. + Files.createDirectories(ft.cdcState()); + + new CdcConsumerState(log, ft).saveCdcMode(CdcMode.CDC_UTILITY_ACTIVE); } } } diff --git a/modules/core/src/test/resources/org.apache.ignite.util/GridCommandHandlerClusterByClassTest_help.output b/modules/core/src/test/resources/org.apache.ignite.util/GridCommandHandlerClusterByClassTest_help.output index 72dcdba8e7f0a..487e903155c35 100644 --- a/modules/core/src/test/resources/org.apache.ignite.util/GridCommandHandlerClusterByClassTest_help.output +++ b/modules/core/src/test/resources/org.apache.ignite.util/GridCommandHandlerClusterByClassTest_help.output @@ -435,7 +435,7 @@ If the file name isn't specified the output file name is: '.bin': Parameters: --node-id node_id - ID of the node to clear CDC directory from. If not set, the command will affect all server nodes. - --reset-mode - Also delete the CDC mode state. The CDC application will not capture changes until CDC is enabled and Ignite nodes are restarted. + --reset-mode - Also delete the CDC mode state. The CDC application will not capture changes until Ignite nodes are restarted. [EXPERIMENTAL] Check/Repair cache consistency using Read Repair approach: diff --git a/modules/core/src/test/resources/org.apache.ignite.util/GridCommandHandlerClusterByClassWithSSLTest_help.output b/modules/core/src/test/resources/org.apache.ignite.util/GridCommandHandlerClusterByClassWithSSLTest_help.output index 30c4aa6116e74..075f716afebcd 100644 --- a/modules/core/src/test/resources/org.apache.ignite.util/GridCommandHandlerClusterByClassWithSSLTest_help.output +++ b/modules/core/src/test/resources/org.apache.ignite.util/GridCommandHandlerClusterByClassWithSSLTest_help.output @@ -435,7 +435,7 @@ If the file name isn't specified the output file name is: '.bin': Parameters: --node-id node_id - ID of the node to clear CDC directory from. If not set, the command will affect all server nodes. - --reset-mode - Also delete the CDC mode state. The CDC application will not capture changes until CDC is enabled and Ignite nodes are restarted. + --reset-mode - Also delete the CDC mode state. The CDC application will not capture changes until Ignite nodes are restarted. [EXPERIMENTAL] Check/Repair cache consistency using Read Repair approach: From 2ee4ba26e199e4dc46708f068fd5b977fcacba95 Mon Sep 17 00:00:00 2001 From: Ilya Shishkov Date: Mon, 23 Nov 2026 20:31:27 +0300 Subject: [PATCH 3/3] IGNITE-29301 AI code-review fixes. --- .../persistence/change-data-capture.adoc | 21 +++++++++----- .../apache/ignite/util/CdcCommandTest.java | 10 +++++-- .../management/cdc/CdcClearCommand.java | 3 +- .../internal/management/cdc/CdcClearTask.java | 29 ++++++++++++------- .../resources/META-INF/classnames.properties | 3 ++ 5 files changed, 44 insertions(+), 22 deletions(-) diff --git a/docs/_docs/persistence/change-data-capture.adoc b/docs/_docs/persistence/change-data-capture.adoc index 766d6c0914fe5..c4499d74523a5 100644 --- a/docs/_docs/persistence/change-data-capture.adoc +++ b/docs/_docs/persistence/change-data-capture.adoc @@ -211,14 +211,17 @@ NOTE: There are no guarantees of notifying the CDC consumer on concurrent cache == Clear CDC directory Sometimes the CDC application has to start from scratch, for example, after a long CDC outage or when replication -is being set up again. In this case you can delete all WAL segment links and the CDC application state from the CDC directory. +is being set up again. In this case you can delete all WAL segment links and the CDC application state from the CDC +directory. NOTE: Use the link:#handling-skipped-segments[`--cdc delete_lost_segment_links`] command if the CDC application fails -because of skipped segments. Use the `--cdc clear` command to drop all the accumulated changes and the CDC application state. +because of skipped segments. Use the `--cdc clear` command to drop all the accumulated changes and the CDC application +state. WARNING: All changes in deleted segment links will be lost! -To clear the CDC directory, follow the steps below. Steps 3–5 are required only if changes must be captured after clearing. +To clear the CDC directory, follow the steps below. Steps 3–5 are required only if changes must be captured after +clearing. 1. Shut down the CDC application. The command fails if the CDC directory is locked by the running application. 2. Run the following link:tools/control-script[Control Script] command: @@ -235,15 +238,17 @@ control.sh|bat --cdc clear --node-id node_id control.sh|bat --cdc clear --reset-mode ---- + -If the command fails, fix the reported error and run it again. Do not start the CDC application until the command succeeds. - 3. If the command was run with `--reset-mode`, restart the cleared Ignite nodes with CDC enabled (before the restart, make sure -the `cdc.disabled` distributed property is set to `false`). Without the restart, the CDC application does not capture changes. +If the command fails, fix the reported error and run it again. Do not start the CDC application until the command +succeeds. + 3. If the command was run with `--reset-mode`, restart the cleared Ignite nodes with CDC enabled (before the restart, +make sure the `cdc.disabled` distributed property is set to `false`). Without the restart, the CDC application does not +capture changes. 4. Start the CDC application. 5. Synchronize data with the destination (e.g. a remote cluster), because changes in the cleared segment links are not transmitted. Use the link:#forcefully-resend-all-cache-data-to-cdc[resend command], a snapshot or other methods. -NOTE: There is no need to disable CDC with the `cdc.disabled` distributed property before clearing. Segment links created -after clearing are kept, and the CDC application consumes them after start. +NOTE: There is no need to disable CDC with the `cdc.disabled` distributed property before clearing. Segment links +created after clearing are kept, and the CDC application consumes them after start. NOTE: The command clears CDC directories only on the server nodes that are in the topology. CDC directories of offline nodes are not cleared. After such a node joins the cluster, clear its CDC directory with the `--node-id` argument. diff --git a/modules/control-utility/src/test/java/org/apache/ignite/util/CdcCommandTest.java b/modules/control-utility/src/test/java/org/apache/ignite/util/CdcCommandTest.java index 9047769f39907..67c2d0dcc9c3d 100644 --- a/modules/control-utility/src/test/java/org/apache/ignite/util/CdcCommandTest.java +++ b/modules/control-utility/src/test/java/org/apache/ignite/util/CdcCommandTest.java @@ -559,11 +559,15 @@ public void testCdcClearOnOneNode() throws Exception { prepareForClear(); + File[] links0 = cdcLinks(0); File[] links1 = cdcLinks(1); assertContains(log, executeCommand(EXIT_CODE_OK, CDC, CLEAR, NODE_ID, grid(1).localNode().id().toString()), "CDC directories were successfully cleared."); + for (File link : links0) + assertTrue("Segment link is deleted: " + link, link.exists()); + checkCdcNotCleared(0, 2); checkCdcCleared(1, links1, true); } @@ -575,7 +579,8 @@ public void testCdcClearOnClientNode() throws Exception { IgniteEx client = startClientGrid("client"); - assertContains(log, executeCommand(EXIT_CODE_INVALID_ARGUMENTS, CDC, CLEAR, NODE_ID, client.localNode().id().toString()), + assertContains(log, + executeCommand(EXIT_CODE_INVALID_ARGUMENTS, CDC, CLEAR, NODE_ID, client.localNode().id().toString()), "Client nodes do not support CDC clear command."); } @@ -589,7 +594,8 @@ public void testCdcClearWithResetMode() throws Exception { File[] links0 = cdcLinks(0); File[] links1 = cdcLinks(1); - assertContains(log, executeCommand(EXIT_CODE_OK, CDC, CLEAR, RESET_MODE), "CDC directories were successfully cleared."); + assertContains(log, executeCommand(EXIT_CODE_OK, CDC, CLEAR, RESET_MODE), + "CDC directories were successfully cleared."); checkCdcCleared(0, links0, false); checkCdcCleared(1, links1, false); diff --git a/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearCommand.java b/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearCommand.java index c1230418085be..293b78cd4c470 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearCommand.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearCommand.java @@ -51,7 +51,8 @@ public class CdcClearCommand implements ComputeCommand List node = node(arg.nodeId(), nodes); if (node.get(0).isClient()) - throw new IllegalArgumentException("You specified a client node id. Client nodes do not support CDC clear command."); + throw new IllegalArgumentException("You specified a client node id. " + + "Client nodes do not support CDC clear command."); return node; } diff --git a/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearTask.java b/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearTask.java index d6b4cedf63a73..5d66fe561f77d 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearTask.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/management/cdc/CdcClearTask.java @@ -21,6 +21,8 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.util.Arrays; +import java.util.Comparator; import java.util.List; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteException; @@ -89,10 +91,12 @@ protected CdcClearJob(CdcClearCommandArg arg, boolean debug) { try { lock.tryLock(1); - // Links go first: if deletion fails midway, the kept state prevents the CDC application from silently - // replaying the remaining links. + // Links go first, in ascending order: on partial failure the remaining links follow the kept WAL state, + // so the CDC application fails on start instead of consuming them. File[] links = ft.walCdcSegments(); + Arrays.sort(links, Comparator.comparingLong(link -> ft.walSegmentIndex(link.toPath()))); + for (File link : links) Files.delete(link.toPath()); @@ -105,7 +109,8 @@ protected CdcClearJob(CdcClearCommandArg arg, boolean debug) { saveUtilityActiveModeIfAbsent(ft); } - log.info("CDC directory cleared [dir=" + ft.walCdc().getAbsolutePath() + ", deletedLinksCnt=" + links.length + ']'); + log.info("CDC directory cleared [dir=" + ft.walCdc().getAbsolutePath() + + ", deletedLinksCnt=" + links.length + ']'); return null; } @@ -115,7 +120,8 @@ protected CdcClearJob(CdcClearCommandArg arg, boolean debug) { "[dir=" + ft.walCdc().getAbsolutePath() + ", reason=" + e.getMessage() + ']', e); } catch (IOException e) { - throw new IgniteException("Failed to clear CDC directory [dir=" + ft.walCdc().getAbsolutePath() + ']', e); + throw new IgniteException("Failed to clear CDC directory " + + "[dir=" + ft.walCdc().getAbsolutePath() + ']', e); } finally { U.closeQuiet(lock); @@ -123,13 +129,13 @@ protected CdcClearJob(CdcClearCommandArg arg, boolean debug) { } /** - * Deletes CDC application state except the mode: without the mode the CDC application waits for - * {@code CdcManagerStopRecord}, which a running node does not log again. + * Deletes CDC application state except the mode, otherwise the application waits for + * {@code CdcManagerStopRecord}, which is not logged again. * * @param ft Node file tree. */ private void deleteStateExceptMode(NodeFileTree ft) throws IOException { - // Temporary files remain if the CDC application failed while saving state. + // Including temporary files left after a failed save. List stateFiles = List.of( ft.cdcWalState(), ft.tmpCdcWalState(), ft.cdcCachesState(), ft.tmpCdcCachesState(), @@ -142,14 +148,15 @@ private void deleteStateExceptMode(NodeFileTree ft) throws IOException { } /** - * Saves {@link CdcMode#CDC_UTILITY_ACTIVE} mode if the default CDC manager is used and the mode is not saved yet: - * the {@code CdcManagerStopRecord} switching the CDC application to this mode is logged once on node start and may - * be in a deleted link. + * Saves {@link CdcMode#CDC_UTILITY_ACTIVE} for the default CDC manager if the mode is absent: + * {@code CdcManagerStopRecord} is logged once on node start and may be in a deleted link. * * @param ft Node file tree. */ private void saveUtilityActiveModeIfAbsent(NodeFileTree ft) throws IOException { - if (!(ignite.context().cache().context().cdc() instanceof CdcUtilityActiveCdcManager) || Files.exists(ft.cdcModeState())) + boolean dfltMgr = ignite.context().cache().context().cdc() instanceof CdcUtilityActiveCdcManager; + + if (!dfltMgr || Files.exists(ft.cdcModeState())) return; // Absent if the CDC application has never started. diff --git a/modules/core/src/main/resources/META-INF/classnames.properties b/modules/core/src/main/resources/META-INF/classnames.properties index b55a003c2de0e..7c88197e9162a 100644 --- a/modules/core/src/main/resources/META-INF/classnames.properties +++ b/modules/core/src/main/resources/META-INF/classnames.properties @@ -516,6 +516,9 @@ org.apache.ignite.internal.management.cache.scan.CacheScanTask$CacheScanJob org.apache.ignite.internal.management.cache.scan.CacheScanTaskResult org.apache.ignite.internal.management.cdc.CdcCacheDataResendTask org.apache.ignite.internal.management.cdc.CdcCacheDataResendTask$CdcCacheDataResendJob +org.apache.ignite.internal.management.cdc.CdcClearCommandArg +org.apache.ignite.internal.management.cdc.CdcClearTask +org.apache.ignite.internal.management.cdc.CdcClearTask$CdcClearJob org.apache.ignite.internal.management.cdc.CdcDeleteLostSegmentLinksCommandArg org.apache.ignite.internal.management.cdc.CdcDeleteLostSegmentsTask org.apache.ignite.internal.management.cdc.CdcDeleteLostSegmentsTask$CdcDeleteLostSegmentsJob