|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | + * contributor license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright ownership. |
| 5 | + * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | + * (the "License"); you may not use this file except in compliance with |
| 7 | + * the License. You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +package org.apache.flink.cdc.connectors.mysql.source; |
| 19 | + |
| 20 | +import org.apache.flink.api.common.eventtime.WatermarkStrategy; |
| 21 | +import org.apache.flink.cdc.connectors.mysql.debezium.DebeziumUtils; |
| 22 | +import org.apache.flink.cdc.connectors.mysql.source.split.MySqlSnapshotSplit; |
| 23 | +import org.apache.flink.cdc.connectors.mysql.source.utils.hooks.SnapshotPhaseHooks; |
| 24 | +import org.apache.flink.cdc.connectors.mysql.testutils.UniqueDatabase; |
| 25 | +import org.apache.flink.cdc.debezium.table.RowDataDebeziumDeserializeSchema; |
| 26 | +import org.apache.flink.configuration.Configuration; |
| 27 | +import org.apache.flink.configuration.StateRecoveryOptions; |
| 28 | +import org.apache.flink.core.execution.CheckpointingMode; |
| 29 | +import org.apache.flink.core.execution.JobClient; |
| 30 | +import org.apache.flink.core.execution.SavepointFormatType; |
| 31 | +import org.apache.flink.runtime.checkpoint.CheckpointException; |
| 32 | +import org.apache.flink.runtime.dispatcher.UnavailableDispatcherOperationException; |
| 33 | +import org.apache.flink.streaming.api.datastream.DataStreamSource; |
| 34 | +import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; |
| 35 | +import org.apache.flink.table.api.DataTypes; |
| 36 | +import org.apache.flink.table.data.RowData; |
| 37 | +import org.apache.flink.table.data.conversion.RowRowConverter; |
| 38 | +import org.apache.flink.table.runtime.typeutils.InternalTypeInfo; |
| 39 | +import org.apache.flink.table.types.DataType; |
| 40 | +import org.apache.flink.table.types.logical.RowType; |
| 41 | +import org.apache.flink.table.types.utils.TypeConversions; |
| 42 | +import org.apache.flink.util.CloseableIterator; |
| 43 | +import org.apache.flink.util.ExceptionUtils; |
| 44 | + |
| 45 | +import io.debezium.connector.mysql.MySqlConnection; |
| 46 | +import org.assertj.core.api.Assertions; |
| 47 | +import org.junit.jupiter.api.BeforeEach; |
| 48 | +import org.junit.jupiter.api.Test; |
| 49 | +import org.junit.jupiter.api.Timeout; |
| 50 | +import org.junit.jupiter.api.io.TempDir; |
| 51 | + |
| 52 | +import java.nio.file.Path; |
| 53 | +import java.sql.SQLException; |
| 54 | +import java.time.ZoneId; |
| 55 | +import java.util.Arrays; |
| 56 | +import java.util.HashMap; |
| 57 | +import java.util.Map; |
| 58 | +import java.util.Optional; |
| 59 | +import java.util.Properties; |
| 60 | +import java.util.concurrent.CountDownLatch; |
| 61 | + |
| 62 | +/** |
| 63 | + * IT test for FLINK-38334: MySQL CDC source gets stuck in INITIAL_ASSIGNING state when a table is |
| 64 | + * excluded from configuration after splits have been assigned but before they are finished. |
| 65 | + * |
| 66 | + * <p>NOTE: The test uses a JUnit timeout as a CI safeguard. The test logic is deterministic: it |
| 67 | + * either receives a binlog record (proving streaming mode) or blocks forever (bug exists). |
| 68 | + * |
| 69 | + * <p>When the bug exists, the test will timeout because: |
| 70 | + * |
| 71 | + * <ol> |
| 72 | + * <li>The savepoint captures table "a" splits in assignedSplits (assigned but not finished) |
| 73 | + * <li>After restart with table "a" excluded, the reader skips table "a" splits |
| 74 | + * <li>The enumerator waits for table "a" splits to be reported as finished (they never will be) |
| 75 | + * <li>allSnapshotSplitsFinished() never returns true → job stuck in INITIAL_ASSIGNING |
| 76 | + * </ol> |
| 77 | + * |
| 78 | + * <p>When the fix is applied, the test passes because excluded table splits are cleaned up on |
| 79 | + * restore, allowing the job to transition to streaming mode. |
| 80 | + */ |
| 81 | +public class TableExclusionDuringSnapshotIT extends MySqlSourceTestBase { |
| 82 | + private static final UniqueDatabase DATABASE = |
| 83 | + new UniqueDatabase(MYSQL_CONTAINER, "table_exclusion_snapshot", "mysqluser", "mysqlpw"); |
| 84 | + private static final DataType DATA_TYPE = DataTypes.ROW(DataTypes.FIELD("id", DataTypes.INT())); |
| 85 | + private static final RowRowConverter ROW_CONVERTER = RowRowConverter.create(DATA_TYPE); |
| 86 | + private static final RowDataDebeziumDeserializeSchema DESERIALIZER = |
| 87 | + RowDataDebeziumDeserializeSchema.newBuilder() |
| 88 | + .setPhysicalRowType((RowType) DATA_TYPE.getLogicalType()) |
| 89 | + .setResultTypeInfo( |
| 90 | + InternalTypeInfo.of(TypeConversions.fromDataToLogicalType(DATA_TYPE))) |
| 91 | + .build(); |
| 92 | + |
| 93 | + @BeforeEach |
| 94 | + void setUp() { |
| 95 | + DATABASE.createAndInitialize(); |
| 96 | + } |
| 97 | + |
| 98 | + // Latches for coordinating between test thread and snapshot hook |
| 99 | + // These are static because the hook is serialized and deserialized |
| 100 | + private static volatile CountDownLatch hookTriggeredLatch; |
| 101 | + private static volatile CountDownLatch savepointTakenLatch; |
| 102 | + |
| 103 | + /** |
| 104 | + * Tests that excluding a table from configuration during INITIAL_ASSIGNING phase doesn't cause |
| 105 | + * the source to get stuck. |
| 106 | + * |
| 107 | + * <p>Scenario: |
| 108 | + * |
| 109 | + * <ol> |
| 110 | + * <li>Start job capturing tables "a" and "b" with a blocking hook on table "a" |
| 111 | + * <li>Take savepoint while table "a" is being snapshotted (splits assigned but not finished) |
| 112 | + * <li>Restart with configuration excluding table "a" |
| 113 | + * <li>Insert a new record into table "b" |
| 114 | + * <li>Verify we receive the new record (proves job transitioned to streaming) |
| 115 | + * </ol> |
| 116 | + * |
| 117 | + * <p>If the bug exists, the job will be stuck in INITIAL_ASSIGNING because the enumerator waits |
| 118 | + * for table "a" splits to be reported as finished, but the reader skips them. |
| 119 | + */ |
| 120 | + @Test |
| 121 | + @Timeout(120) |
| 122 | + void testTableExclusionDuringInitialAssigning(@TempDir Path tempDir) throws Exception { |
| 123 | + final String savepointDirectory = tempDir.toUri().toString(); |
| 124 | + |
| 125 | + executeSql("INSERT INTO a VALUES (1)"); |
| 126 | + executeSql("INSERT INTO b VALUES (1)"); |
| 127 | + executeSql("INSERT INTO b VALUES (2)"); |
| 128 | + |
| 129 | + // Phase 1: Take savepoint while table "a" splits are assigned but not finished |
| 130 | + String savepointPath = |
| 131 | + runJobAndSavepointDuringInitialAssigning(savepointDirectory, "a", "b"); |
| 132 | + |
| 133 | + // Phase 2: Restart with only table "b", verify streaming mode works |
| 134 | + String binlogRecord = runJobFromSavepointAndVerifyStreaming(savepointPath, "b"); |
| 135 | + Assertions.assertThat(binlogRecord).isEqualTo("+I[200]"); |
| 136 | + } |
| 137 | + |
| 138 | + /** Starts a job and takes a savepoint while splits are assigned but not finished. */ |
| 139 | + private String runJobAndSavepointDuringInitialAssigning( |
| 140 | + String savepointDirectory, String... tableNames) throws Exception { |
| 141 | + hookTriggeredLatch = new CountDownLatch(1); |
| 142 | + savepointTakenLatch = new CountDownLatch(1); |
| 143 | + |
| 144 | + StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); |
| 145 | + env.setParallelism(1); |
| 146 | + env.enableCheckpointing(200, CheckpointingMode.EXACTLY_ONCE); |
| 147 | + |
| 148 | + MySqlSource<RowData> source = createSourceWithBlockingHook(tableNames); |
| 149 | + DataStreamSource<RowData> stream = |
| 150 | + env.fromSource(source, WatermarkStrategy.noWatermarks(), "MySQL CDC Source"); |
| 151 | + stream.print(); |
| 152 | + |
| 153 | + JobClient jobClient = env.executeAsync("Snapshot phase"); |
| 154 | + |
| 155 | + hookTriggeredLatch.await(); |
| 156 | + String savepointPath = triggerSavepointWithRetry(jobClient, savepointDirectory); |
| 157 | + savepointTakenLatch.countDown(); |
| 158 | + |
| 159 | + jobClient.cancel().get(); |
| 160 | + return savepointPath; |
| 161 | + } |
| 162 | + |
| 163 | + /** Restarts job from savepoint and verifies it transitions to streaming mode. */ |
| 164 | + private String runJobFromSavepointAndVerifyStreaming(String savepointPath, String... tableNames) |
| 165 | + throws Exception { |
| 166 | + Configuration configuration = new Configuration(); |
| 167 | + configuration.set(StateRecoveryOptions.SAVEPOINT_PATH, savepointPath); |
| 168 | + |
| 169 | + StreamExecutionEnvironment env = |
| 170 | + StreamExecutionEnvironment.getExecutionEnvironment(configuration); |
| 171 | + env.setParallelism(1); |
| 172 | + env.enableCheckpointing(500, CheckpointingMode.EXACTLY_ONCE); |
| 173 | + |
| 174 | + MySqlSource<RowData> source = createSourceBuilder(tableNames).build(); |
| 175 | + DataStreamSource<RowData> stream = |
| 176 | + env.fromSource(source, WatermarkStrategy.noWatermarks(), "MySQL CDC Source"); |
| 177 | + |
| 178 | + try (CloseableIterator<RowData> iterator = stream.executeAndCollect()) { |
| 179 | + // Consume snapshot records from table "b" (2 rows) |
| 180 | + for (int i = 0; i < 2; i++) { |
| 181 | + iterator.next(); |
| 182 | + } |
| 183 | + |
| 184 | + // Insert a new record - if job is in streaming mode, we'll receive it |
| 185 | + executeSql("INSERT INTO b VALUES (200)"); |
| 186 | + |
| 187 | + // This blocks forever if the job is stuck in INITIAL_ASSIGNING |
| 188 | + return ROW_CONVERTER.toExternal(iterator.next()).toString(); |
| 189 | + } |
| 190 | + } |
| 191 | + |
| 192 | + private MySqlSourceBuilder<RowData> createSourceBuilder(String... tableNames) { |
| 193 | + return MySqlSource.<RowData>builder() |
| 194 | + .hostname(MYSQL_CONTAINER.getHost()) |
| 195 | + .port(MYSQL_CONTAINER.getDatabasePort()) |
| 196 | + .databaseList(DATABASE.getDatabaseName()) |
| 197 | + .serverTimeZone("UTC") |
| 198 | + .tableList( |
| 199 | + Arrays.stream(tableNames) |
| 200 | + .map(t -> DATABASE.getDatabaseName() + "." + t) |
| 201 | + .toArray(String[]::new)) |
| 202 | + .username(DATABASE.getUsername()) |
| 203 | + .password(DATABASE.getPassword()) |
| 204 | + .deserializer(DESERIALIZER) |
| 205 | + .scanNewlyAddedTableEnabled(true); |
| 206 | + } |
| 207 | + |
| 208 | + /** Creates a source with a hook that blocks on table "a" until the savepoint is taken. */ |
| 209 | + private MySqlSource<RowData> createSourceWithBlockingHook(String... tableNames) { |
| 210 | + MySqlSource<RowData> source = createSourceBuilder(tableNames).build(); |
| 211 | + |
| 212 | + SnapshotPhaseHooks hooks = new SnapshotPhaseHooks(); |
| 213 | + hooks.setPostLowWatermarkAction( |
| 214 | + (connection, split) -> { |
| 215 | + MySqlSnapshotSplit snapshotSplit = (MySqlSnapshotSplit) split; |
| 216 | + if (!snapshotSplit.getTableId().table().equals("a")) { |
| 217 | + return; |
| 218 | + } |
| 219 | + hookTriggeredLatch.countDown(); |
| 220 | + try { |
| 221 | + savepointTakenLatch.await(); |
| 222 | + } catch (InterruptedException e) { |
| 223 | + Thread.currentThread().interrupt(); |
| 224 | + } |
| 225 | + }); |
| 226 | + source.setSnapshotHooks(hooks); |
| 227 | + |
| 228 | + return source; |
| 229 | + } |
| 230 | + |
| 231 | + private String triggerSavepointWithRetry(JobClient jobClient, String savepointDirectory) |
| 232 | + throws Exception { |
| 233 | + int retryTimes = 0; |
| 234 | + while (retryTimes < 600) { |
| 235 | + try { |
| 236 | + return jobClient |
| 237 | + .triggerSavepoint(savepointDirectory, SavepointFormatType.DEFAULT) |
| 238 | + .get(); |
| 239 | + } catch (Exception e) { |
| 240 | + // Retry if checkpoint triggering task is not yet ready |
| 241 | + Optional<CheckpointException> checkpointException = |
| 242 | + ExceptionUtils.findThrowable(e, CheckpointException.class); |
| 243 | + if (checkpointException.isPresent() |
| 244 | + && checkpointException |
| 245 | + .get() |
| 246 | + .getMessage() |
| 247 | + .contains("Checkpoint triggering task")) { |
| 248 | + Thread.sleep(100); |
| 249 | + retryTimes++; |
| 250 | + continue; |
| 251 | + } |
| 252 | + // Retry if job is still initializing |
| 253 | + Optional<UnavailableDispatcherOperationException> dispatcherException = |
| 254 | + ExceptionUtils.findThrowable( |
| 255 | + e, UnavailableDispatcherOperationException.class); |
| 256 | + if (dispatcherException.isPresent()) { |
| 257 | + Thread.sleep(100); |
| 258 | + retryTimes++; |
| 259 | + continue; |
| 260 | + } |
| 261 | + throw e; |
| 262 | + } |
| 263 | + } |
| 264 | + throw new RuntimeException("Failed to trigger savepoint after " + retryTimes + " retries"); |
| 265 | + } |
| 266 | + |
| 267 | + private void executeSql(String... statements) throws SQLException { |
| 268 | + Map<String, String> properties = new HashMap<>(); |
| 269 | + properties.put("database.hostname", MYSQL_CONTAINER.getHost()); |
| 270 | + properties.put("database.port", String.valueOf(MYSQL_CONTAINER.getDatabasePort())); |
| 271 | + properties.put("database.user", DATABASE.getUsername()); |
| 272 | + properties.put("database.password", DATABASE.getPassword()); |
| 273 | + properties.put("database.serverTimezone", ZoneId.of("UTC").toString()); |
| 274 | + io.debezium.config.Configuration configuration = |
| 275 | + io.debezium.config.Configuration.from(properties); |
| 276 | + |
| 277 | + try (MySqlConnection connection = |
| 278 | + DebeziumUtils.createMySqlConnection(configuration, new Properties())) { |
| 279 | + connection.execute("USE " + DATABASE.getDatabaseName()); |
| 280 | + connection.execute(statements); |
| 281 | + } |
| 282 | + } |
| 283 | +} |
0 commit comments