This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/dev/pr-13111-436ddea93d3816ef23e38b6850782ffdc46a5a80 in repository https://gitbox.apache.org/repos/asf/seatunnel.git
commit 9ba5a94a41ba5914a9fa1e4f450c134fa7476021 Author: Steven Zhao <[email protected]> AuthorDate: Thu Nov 26 13:45:12 2026 +0000 [Fix][Connector-V2] Make Doris stream-load labels unique for multi-table sinks (#13111) --- docs/en/connectors/sink/Doris.md | 7 +- docs/zh/connectors/sink/Doris.md | 7 +- .../seatunnel/connectors/doris/sink/DorisSink.java | 16 +- .../connectors/doris/sink/DorisSinkFactory.java | 12 +- .../doris/sink/writer/DorisSinkWriter.java | 88 +++++++++- .../doris/sink/writer/DorisStreamLoad.java | 7 +- .../doris/sink/writer/DorisStreamLoadFactory.java | 5 + .../doris/sink/writer/LabelGenerator.java | 18 +- .../doris/sink/writer/DorisSinkWriterTest.java | 168 +++++++++++++++++++ .../doris/sink/writer/DorisStreamLoadTest.java | 39 +++++ .../e2e/connector/doris/DorisCDCSinkIT.java | 184 +++++++++++++++++++-- .../src/test/resources/ddl/mysql_cdc.sql | 55 +++++- .../resources/mysqlcdc_multi_table_to_doris.conf | 51 ++++++ .../mysqlcdc_multi_table_to_doris_2pc.conf | 50 ++++++ 14 files changed, 663 insertions(+), 44 deletions(-) diff --git a/docs/en/connectors/sink/Doris.md b/docs/en/connectors/sink/Doris.md index 52646b9efd..111405d35b 100644 --- a/docs/en/connectors/sink/Doris.md +++ b/docs/en/connectors/sink/Doris.md @@ -690,14 +690,11 @@ sink { } ``` -The `sink.label-prefix` must be unique per job to avoid label conflicts when retrying or restarting. +The `sink.label-prefix` must be unique per job to avoid label conflicts when retrying or restarting. Sub-writers of one job are disambiguated automatically by the connector. ### Why do I get a "Label already exists" error? -Doris uses Stream Load labels to detect and reject duplicate submissions. If a job is restarted with 2PC enabled, the same label prefix may be reused. To resolve: - -- Include a timestamp or unique token in `sink.label-prefix` to ensure uniqueness across restarts. -- Abort uncommitted transactions in Doris before restarting: `CANCEL LOAD WHERE LABEL LIKE 'your-prefix%'`. +Doris uses Stream Load labels to detect and reject duplicate submissions. The connector appends a stable per-source-table discriminator to every sub-writer's label, and non-2PC labels also include a timestamp and a process-wide sequence. This keeps the sub-writers of a multi-table job distinct and lets a restarted writer abort its own pre-committed transactions. Labels are limited to 128 characters by Doris, so keep `sink.label-prefix` and the database/table names reasonably short. If a [...] ### Does Doris Sink support DELETE propagation from CDC sources? diff --git a/docs/zh/connectors/sink/Doris.md b/docs/zh/connectors/sink/Doris.md index 25f5991002..1cf568d144 100644 --- a/docs/zh/connectors/sink/Doris.md +++ b/docs/zh/connectors/sink/Doris.md @@ -687,14 +687,11 @@ sink { } ``` -`sink.label-prefix` 必须全局唯一,以避免重试或重启时出现 label 冲突。 +`sink.label-prefix` 必须全局唯一,以避免重试或重启时出现 label 冲突;同一作业的多个 sub-writer 由连接器自动区分。 ### 为什么出现"Label already exists"错误? -Doris 通过 Stream Load label 去重,防止重复提交。开启 2PC 后重启任务,可能复用相同的 label 前缀导致冲突。解决方法: - -- 在 `sink.label-prefix` 中加入时间戳或唯一标识,确保每次重启后 label 唯一。 -- 重启前在 Doris 中中止未提交的事务:`CANCEL LOAD WHERE LABEL LIKE 'your-prefix%'`。 +Doris 通过 Stream Load label 去重,防止重复提交。连接器会为每个 sub-writer 追加一个基于源表的稳定区分段,非 2PC label 还会包含时间戳和进程内的序号。这样多表作业的各 sub-writer 不会冲突,重启后的 writer 也能中止自己遗留的 pre-committed 事务。Doris 的 label 最长 128 个字符,请尽量保持 `sink.label-prefix` 和库表名简短。如果仍然发生冲突,可以在重启前中止未提交的事务:`CANCEL LOAD WHERE LABEL LIKE 'your-prefix%'`。 ### Doris Sink 是否支持 CDC 的 DELETE 传播? diff --git a/seatunnel-connectors-v2/connector-doris/src/main/java/org/apache/seatunnel/connectors/doris/sink/DorisSink.java b/seatunnel-connectors-v2/connector-doris/src/main/java/org/apache/seatunnel/connectors/doris/sink/DorisSink.java index b592d38972..54d7705cb7 100644 --- a/seatunnel-connectors-v2/connector-doris/src/main/java/org/apache/seatunnel/connectors/doris/sink/DorisSink.java +++ b/seatunnel-connectors-v2/connector-doris/src/main/java/org/apache/seatunnel/connectors/doris/sink/DorisSink.java @@ -65,11 +65,17 @@ public class DorisSink private final DorisSinkConfig dorisSinkConfig; private final ReadonlyConfig config; private final CatalogTable catalogTable; + private final String sourceTableId; private String jobId; public DorisSink(ReadonlyConfig config, CatalogTable catalogTable) { + this(config, catalogTable, catalogTable.getTablePath().getFullName()); + } + + public DorisSink(ReadonlyConfig config, CatalogTable catalogTable, String sourceTableId) { this.config = config; this.catalogTable = catalogTable; + this.sourceTableId = sourceTableId; this.dorisSinkConfig = DorisSinkConfig.of(config); // Load the JDBC driver in to DriverManager try { @@ -98,7 +104,12 @@ public class DorisSink log.warn("Failed to load JDBC driver com.mysql.cj.jdbc.Driver ", e); } return new DorisSinkWriter( - context, Collections.emptyList(), catalogTable, dorisSinkConfig, jobId); + context, + Collections.emptyList(), + catalogTable, + dorisSinkConfig, + jobId, + sourceTableId); } @Override @@ -110,7 +121,8 @@ public class DorisSink } catch (Exception e) { log.warn("Failed to load JDBC driver com.mysql.cj.jdbc.Driver ", e); } - return new DorisSinkWriter(context, states, catalogTable, dorisSinkConfig, jobId); + return new DorisSinkWriter( + context, states, catalogTable, dorisSinkConfig, jobId, sourceTableId); } @Override diff --git a/seatunnel-connectors-v2/connector-doris/src/main/java/org/apache/seatunnel/connectors/doris/sink/DorisSinkFactory.java b/seatunnel-connectors-v2/connector-doris/src/main/java/org/apache/seatunnel/connectors/doris/sink/DorisSinkFactory.java index 99205e035b..154ea05578 100644 --- a/seatunnel-connectors-v2/connector-doris/src/main/java/org/apache/seatunnel/connectors/doris/sink/DorisSinkFactory.java +++ b/seatunnel-connectors-v2/connector-doris/src/main/java/org/apache/seatunnel/connectors/doris/sink/DorisSinkFactory.java @@ -104,13 +104,17 @@ public class DorisSinkFactory implements TableSinkFactory { public TableSink<SeaTunnelRow, DorisSinkState, DorisCommitInfo, DorisCommitInfo> createSink( TableSinkFactoryContext context) { ReadonlyConfig config = context.getOptions(); + CatalogTable sourceCatalogTable = context.getCatalogTable(); CatalogTable catalogTable = config.get(NEEDS_UNSUPPORTED_TYPE_CASTING) - ? UnsupportedTypeConverterUtils.convertCatalogTable( - context.getCatalogTable()) - : context.getCatalogTable(); + ? UnsupportedTypeConverterUtils.convertCatalogTable(sourceCatalogTable) + : sourceCatalogTable; final CatalogTable finalCatalogTable = this.renameCatalogTable(config, catalogTable); - return () -> new DorisSink(config, finalCatalogTable); + // The writer needs the source table identity before the target table is renamed: a + // multi-table sink creates one writer per source table, and all of those writers share + // the same target table, job id and subtask index. + String sourceTableId = sourceCatalogTable.getTablePath().getFullName(); + return () -> new DorisSink(config, finalCatalogTable, sourceTableId); } private CatalogTable renameCatalogTable(ReadonlyConfig options, CatalogTable catalogTable) { diff --git a/seatunnel-connectors-v2/connector-doris/src/main/java/org/apache/seatunnel/connectors/doris/sink/writer/DorisSinkWriter.java b/seatunnel-connectors-v2/connector-doris/src/main/java/org/apache/seatunnel/connectors/doris/sink/writer/DorisSinkWriter.java index 8abed59058..59da3ab263 100644 --- a/seatunnel-connectors-v2/connector-doris/src/main/java/org/apache/seatunnel/connectors/doris/sink/writer/DorisSinkWriter.java +++ b/seatunnel-connectors-v2/connector-doris/src/main/java/org/apache/seatunnel/connectors/doris/sink/writer/DorisSinkWriter.java @@ -49,6 +49,7 @@ import org.apache.seatunnel.connectors.doris.util.UnsupportedTypeConverterUtils; import lombok.extern.slf4j.Slf4j; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.time.ZoneId; import java.util.ArrayList; import java.util.Arrays; @@ -59,6 +60,7 @@ import java.util.Optional; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import java.util.zip.CRC32; import static org.apache.seatunnel.shade.com.google.common.base.Preconditions.checkState; @@ -75,6 +77,7 @@ public class DorisSinkWriter private DorisStreamLoad controlStreamLoad; private final DorisSinkConfig dorisSinkConfig; private final String labelPrefix; + private final String restoredLabelPrefix; private final LabelGenerator labelGenerator; private final int intervalTime; private DorisSerializer serializer; @@ -105,13 +108,25 @@ public class DorisSinkWriter catalogTable, dorisSinkConfig, jobId, - (hostPort, tablePath, sinkConfig, currentLabelGenerator) -> - new DorisStreamLoad( - hostPort, - tablePath, - sinkConfig, - currentLabelGenerator, - new HttpUtil().getHttpClient())); + catalogTable.getTablePath().getFullName(), + defaultStreamLoadFactory()); + } + + public DorisSinkWriter( + SinkWriter.Context context, + List<DorisSinkState> state, + CatalogTable catalogTable, + DorisSinkConfig dorisSinkConfig, + String jobId, + String sourceTableId) { + this( + context, + state, + catalogTable, + dorisSinkConfig, + jobId, + sourceTableId, + defaultStreamLoadFactory()); } DorisSinkWriter( @@ -121,12 +136,30 @@ public class DorisSinkWriter DorisSinkConfig dorisSinkConfig, String jobId, DorisStreamLoadFactory streamLoadFactory) { + this( + context, + state, + catalogTable, + dorisSinkConfig, + jobId, + catalogTable.getTablePath().getFullName(), + streamLoadFactory); + } + + DorisSinkWriter( + SinkWriter.Context context, + List<DorisSinkState> state, + CatalogTable catalogTable, + DorisSinkConfig dorisSinkConfig, + String jobId, + String sourceTableId, + DorisStreamLoadFactory streamLoadFactory) { this.dorisSinkConfig = dorisSinkConfig; this.catalogTable = catalogTable; this.lastCheckpointId = !state.isEmpty() ? state.get(0).getCheckpointId() : 0; log.info("restore checkpointId {}", lastCheckpointId); log.info("labelPrefix " + dorisSinkConfig.getLabelPrefix()); - this.labelPrefix = + String baseLabelPrefix = dorisSinkConfig.getLabelPrefix() + "_" + catalogTable.getTablePath().getFullName().replaceAll("\\.", "_") @@ -134,6 +167,20 @@ public class DorisSinkWriter + jobId + "_" + context.getIndexOfSubtask(); + // A multi-table sink creates one writer per source table, and all of those writers share + // the sink table, the job id and the subtask index. Derive the discriminator from the + // source table identity so sub-writers are distinct, while the same writer keeps the same + // prefix across attempts. The stable prefix is what lets a restarted writer abort + // pre-committed transactions left by a failed attempt that never completed a checkpoint. + this.labelPrefix = baseLabelPrefix + "_" + sourceTableDiscriminator(sourceTableId); + // A restored writer must abort the pre-committed transactions created with the prefix + // persisted in its state. For a state written before the discriminator existed the + // persisted prefix is the old, shared prefix; the new run still uses the stable one. + String persistedLabelPrefix = state.isEmpty() ? null : state.get(0).getLabelPrefix(); + this.restoredLabelPrefix = + persistedLabelPrefix == null || persistedLabelPrefix.isEmpty() + ? null + : persistedLabelPrefix; this.labelGenerator = new LabelGenerator(labelPrefix, dorisSinkConfig.getEnable2PC()); this.scheduledExecutorService = new ScheduledThreadPoolExecutor( @@ -150,6 +197,27 @@ public class DorisSinkWriter } } + private static DorisStreamLoadFactory defaultStreamLoadFactory() { + return (hostPort, tablePath, sinkConfig, currentLabelGenerator) -> + new DorisStreamLoad( + hostPort, + tablePath, + sinkConfig, + currentLabelGenerator, + new HttpUtil().getHttpClient()); + } + + /** + * Stable 8-hex discriminator for a source table. CRC32 is enough to separate the source tables + * of one job and keeps the label short; the value must not change across attempts. + */ + private static String sourceTableDiscriminator(String sourceTableId) { + CRC32 crc = new CRC32(); + String value = sourceTableId == null ? "" : sourceTableId; + crc.update(value.getBytes(StandardCharsets.UTF_8)); + return String.format("%08x", crc.getValue()); + } + private void initializeLoad() { List<String> feNodes = DorisNodeResolver.parseNodes(dorisSinkConfig.getFrontends(), "fenodes"); @@ -465,7 +533,9 @@ public class DorisSinkWriter streamLoadFactory.create( node, catalogTable.getTablePath(), dorisSinkConfig, labelGenerator); if (abortPreCommitOnInit) { - streamLoad.abortPreCommit(labelPrefix, lastCheckpointId + 1); + streamLoad.abortPreCommit( + restoredLabelPrefix != null ? restoredLabelPrefix : labelPrefix, + lastCheckpointId + 1); } return new InitializedStreamLoad(node, streamLoad); } catch (Exception e) { diff --git a/seatunnel-connectors-v2/connector-doris/src/main/java/org/apache/seatunnel/connectors/doris/sink/writer/DorisStreamLoad.java b/seatunnel-connectors-v2/connector-doris/src/main/java/org/apache/seatunnel/connectors/doris/sink/writer/DorisStreamLoad.java index a01ef0d641..9d69e67951 100644 --- a/seatunnel-connectors-v2/connector-doris/src/main/java/org/apache/seatunnel/connectors/doris/sink/writer/DorisStreamLoad.java +++ b/seatunnel-connectors-v2/connector-doris/src/main/java/org/apache/seatunnel/connectors/doris/sink/writer/DorisStreamLoad.java @@ -66,6 +66,8 @@ public class DorisStreamLoad implements Serializable { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private static final int HTTP_OK = 200; private static final int HTTP_TEMPORARY_REDIRECT = 307; + // Retained for the DorisStreamLoadFactory contract. New-load labels are generated by + // DorisSinkWriter; aborting a restored pre-commit uses the prefix passed by the caller. private final LabelGenerator labelGenerator; private final byte[] lineDelimiter; private static final String LOAD_URL_PATTERN = "http://%s/api/%s/%s/_stream_load"; @@ -138,7 +140,10 @@ public class DorisStreamLoad implements Serializable { log.info("abort for labelPrefix {}. start chkId {}.", labelPrefix, chkID); while (true) { try { - String label = labelGenerator.generateLabel(startChkID); + // 2PC labels are prefix + checkpoint id. Use the prefix passed by the caller: + // a restored writer must abort transactions created before this run, whose + // prefix is persisted in its state and differs from this run's active prefix. + String label = labelPrefix + "_" + startChkID; HttpPutBuilder builder = new HttpPutBuilder(); builder.setUrl(loadUrlStr) .baseAuth(user, passwd) diff --git a/seatunnel-connectors-v2/connector-doris/src/main/java/org/apache/seatunnel/connectors/doris/sink/writer/DorisStreamLoadFactory.java b/seatunnel-connectors-v2/connector-doris/src/main/java/org/apache/seatunnel/connectors/doris/sink/writer/DorisStreamLoadFactory.java index 39eeb70547..be135284da 100644 --- a/seatunnel-connectors-v2/connector-doris/src/main/java/org/apache/seatunnel/connectors/doris/sink/writer/DorisStreamLoadFactory.java +++ b/seatunnel-connectors-v2/connector-doris/src/main/java/org/apache/seatunnel/connectors/doris/sink/writer/DorisStreamLoadFactory.java @@ -22,6 +22,11 @@ import org.apache.seatunnel.connectors.doris.config.DorisSinkConfig; @FunctionalInterface public interface DorisStreamLoadFactory { + /** + * Creates a stream load. The {@link LabelGenerator} is retained for compatibility with the + * existing factory contract; new-load labels are generated by {@link DorisSinkWriter}, and + * {@code abortPreCommit} uses the label prefix supplied by its caller. + */ DorisStreamLoad create( String hostPort, TablePath tablePath, diff --git a/seatunnel-connectors-v2/connector-doris/src/main/java/org/apache/seatunnel/connectors/doris/sink/writer/LabelGenerator.java b/seatunnel-connectors-v2/connector-doris/src/main/java/org/apache/seatunnel/connectors/doris/sink/writer/LabelGenerator.java index df13d9b22a..43b903f677 100644 --- a/seatunnel-connectors-v2/connector-doris/src/main/java/org/apache/seatunnel/connectors/doris/sink/writer/LabelGenerator.java +++ b/seatunnel-connectors-v2/connector-doris/src/main/java/org/apache/seatunnel/connectors/doris/sink/writer/LabelGenerator.java @@ -17,8 +17,20 @@ package org.apache.seatunnel.connectors.doris.sink.writer; +import java.util.concurrent.atomic.AtomicLong; + /** Generator label for stream load. */ public class LabelGenerator { + /** + * Non-2PC labels must be unique across every sub-sink of a job. The millisecond timestamp alone + * is not enough because sub-sinks of a multi-table sink can generate a label in the same + * millisecond (for example, while a checkpoint walks all sub-writers), and Doris rejects a + * reused label with LABEL_ALREADY_EXISTS. All sub-sinks of a job share the connector class + * loader, so a process-wide sequence disambiguates them. 2PC labels stay deterministic because + * they are used by checkpoint-id based abort/recovery. + */ + private static final AtomicLong LABEL_SEQUENCE = new AtomicLong(); + private final String labelPrefix; private final boolean enable2PC; @@ -30,6 +42,10 @@ public class LabelGenerator { public String generateLabel(long chkId) { return enable2PC ? labelPrefix + "_" + chkId - : labelPrefix + "_" + System.currentTimeMillis(); + : labelPrefix + + "_" + + System.currentTimeMillis() + + "_" + + Long.toString(LABEL_SEQUENCE.getAndIncrement(), 36); } } diff --git a/seatunnel-connectors-v2/connector-doris/src/test/java/org/apache/seatunnel/connectors/doris/sink/writer/DorisSinkWriterTest.java b/seatunnel-connectors-v2/connector-doris/src/test/java/org/apache/seatunnel/connectors/doris/sink/writer/DorisSinkWriterTest.java index 236c923b79..6787270fa4 100644 --- a/seatunnel-connectors-v2/connector-doris/src/test/java/org/apache/seatunnel/connectors/doris/sink/writer/DorisSinkWriterTest.java +++ b/seatunnel-connectors-v2/connector-doris/src/test/java/org/apache/seatunnel/connectors/doris/sink/writer/DorisSinkWriterTest.java @@ -502,6 +502,174 @@ public class DorisSinkWriterTest { } } + @Test + void testSubWritersWithTheSameSinkTableGetDistinctTwoPhaseCommitLabels() throws Exception { + DorisStreamLoad streamLoad = mock(DorisStreamLoad.class); + doNothing().when(streamLoad).abortPreCommit(anyString(), anyLong()); + + RecordingStreamLoadFactory factory = new RecordingStreamLoadFactory(); + factory.register("fe1:8030", streamLoad); + + DorisSinkWriter first = null; + DorisSinkWriter second = null; + try { + first = + new DorisSinkWriter( + new DefaultSinkWriterContext(0, 1), + new ArrayList<>(), + mockCatalogTable(), + createSinkConfig(false, true), + "job_1", + "source_a", + factory); + second = + new DorisSinkWriter( + new DefaultSinkWriterContext(0, 1), + new ArrayList<>(), + mockCatalogTable(), + createSinkConfig(false, true), + "job_1", + "source_b", + factory); + + ArgumentCaptor<String> labelCaptor = ArgumentCaptor.forClass(String.class); + verify(streamLoad, times(2)).startLoad(labelCaptor.capture()); + List<String> labels = labelCaptor.getAllValues(); + Assertions.assertEquals(2, labels.size()); + Assertions.assertNotEquals(labels.get(0), labels.get(1)); + } finally { + if (first != null) { + first.close(); + } + if (second != null) { + second.close(); + } + } + } + + @Test + void testSameSourceTableKeepsTwoPhaseCommitLabelAcrossAttempts() throws Exception { + DorisStreamLoad streamLoad = mock(DorisStreamLoad.class); + doNothing().when(streamLoad).abortPreCommit(anyString(), anyLong()); + + RecordingStreamLoadFactory factory = new RecordingStreamLoadFactory(); + factory.register("fe1:8030", streamLoad); + + DorisSinkWriter first = null; + DorisSinkWriter second = null; + try { + first = + new DorisSinkWriter( + new DefaultSinkWriterContext(0, 1), + new ArrayList<>(), + mockCatalogTable(), + createSinkConfig(false, true), + "job_1", + "source_a", + factory); + second = + new DorisSinkWriter( + new DefaultSinkWriterContext(0, 1), + new ArrayList<>(), + mockCatalogTable(), + createSinkConfig(false, true), + "job_1", + "source_a", + factory); + + ArgumentCaptor<String> labelCaptor = ArgumentCaptor.forClass(String.class); + verify(streamLoad, times(2)).startLoad(labelCaptor.capture()); + List<String> labels = labelCaptor.getAllValues(); + Assertions.assertEquals(2, labels.size()); + Assertions.assertEquals(labels.get(0), labels.get(1)); + } finally { + if (first != null) { + first.close(); + } + if (second != null) { + second.close(); + } + } + } + + @Test + void testSubWritersWithTheSameSinkTableGetDistinctNonTwoPhaseCommitLabels() throws Exception { + DorisStreamLoad streamLoad = mock(DorisStreamLoad.class); + when(streamLoad.stopLoad()).thenReturn(successRespContent(1L)); + + RecordingStreamLoadFactory factory = new RecordingStreamLoadFactory(); + factory.register("fe1:8030", streamLoad); + + DorisSinkWriter first = null; + DorisSinkWriter second = null; + try { + first = + new DorisSinkWriter( + new DefaultSinkWriterContext(0, 1), + new ArrayList<>(), + mockCatalogTable(), + createSinkConfig(false, false), + "job_1", + "source_a", + factory); + second = + new DorisSinkWriter( + new DefaultSinkWriterContext(0, 1), + new ArrayList<>(), + mockCatalogTable(), + createSinkConfig(false, false), + "job_1", + "source_b", + factory); + + ArgumentCaptor<String> labelCaptor = ArgumentCaptor.forClass(String.class); + verify(streamLoad, times(2)).startLoad(labelCaptor.capture()); + List<String> labels = labelCaptor.getAllValues(); + Assertions.assertEquals(2, labels.size()); + Assertions.assertNotEquals(labels.get(0), labels.get(1)); + } finally { + if (first != null) { + first.close(); + } + if (second != null) { + second.close(); + } + } + } + + @Test + void testRestoreAbortsTwoPhaseCommitLabelsWithThePersistedPrefix() throws Exception { + DorisStreamLoad streamLoad = mock(DorisStreamLoad.class); + doNothing().when(streamLoad).abortPreCommit(anyString(), anyLong()); + + RecordingStreamLoadFactory factory = new RecordingStreamLoadFactory(); + factory.register("fe1:8030", streamLoad); + + List<DorisSinkState> state = + Collections.singletonList(new DorisSinkState("persisted_label_prefix", 7L)); + DorisSinkWriter writer = null; + try { + writer = + new DorisSinkWriter( + new DefaultSinkWriterContext(0, 1), + state, + mockCatalogTable(), + createSinkConfig(false, true), + "job_1", + "source_a", + factory); + + verify(streamLoad).abortPreCommit("persisted_label_prefix", 8L); + ArgumentCaptor<String> labelCaptor = ArgumentCaptor.forClass(String.class); + verify(streamLoad).startLoad(labelCaptor.capture()); + Assertions.assertFalse(labelCaptor.getValue().startsWith("persisted_label_prefix")); + } finally { + if (writer != null) { + writer.close(); + } + } + } + @Test void testTimestampTzZoneWarningNamesColumnsAndJvmZoneWhenZoneUnset() { SeaTunnelRowType rowType = diff --git a/seatunnel-connectors-v2/connector-doris/src/test/java/org/apache/seatunnel/connectors/doris/sink/writer/DorisStreamLoadTest.java b/seatunnel-connectors-v2/connector-doris/src/test/java/org/apache/seatunnel/connectors/doris/sink/writer/DorisStreamLoadTest.java index 6d5dac98bc..3729241258 100644 --- a/seatunnel-connectors-v2/connector-doris/src/test/java/org/apache/seatunnel/connectors/doris/sink/writer/DorisStreamLoadTest.java +++ b/seatunnel-connectors-v2/connector-doris/src/test/java/org/apache/seatunnel/connectors/doris/sink/writer/DorisStreamLoadTest.java @@ -27,6 +27,7 @@ import org.apache.http.Header; import org.apache.http.ProtocolVersion; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicStatusLine; @@ -34,6 +35,7 @@ import org.apache.http.protocol.HttpContext; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpServer; @@ -48,6 +50,8 @@ import java.util.concurrent.Executors; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class DorisStreamLoadTest { @@ -119,6 +123,41 @@ public class DorisStreamLoadTest { } } + @Test + void testAbortPreCommitUsesTheProvidedLabelPrefix() throws Exception { + CloseableHttpClient httpClient = mock(CloseableHttpClient.class); + CloseableHttpResponse preCommitResponse = mock(CloseableHttpResponse.class); + CloseableHttpResponse abortResponse = mock(CloseableHttpResponse.class); + when(preCommitResponse.getStatusLine()) + .thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "Success")); + when(preCommitResponse.getEntity()) + .thenReturn( + new StringEntity( + "{\"TxnId\":123,\"Status\":\"Success\",\"TwoPhaseCommit\":\"true\"}")); + when(abortResponse.getStatusLine()) + .thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "Success")); + when(abortResponse.getEntity()).thenReturn(new StringEntity("{\"status\":\"Success\"}")); + when(httpClient.execute(any(HttpUriRequest.class), any(HttpContext.class))) + .thenReturn(preCommitResponse, abortResponse); + + DorisStreamLoad streamLoad = + new DorisStreamLoad( + "fe1:8030", + TablePath.of("test_db", "test_table"), + createSinkConfig(false, true), + new LabelGenerator("active_prefix", true), + httpClient); + + streamLoad.abortPreCommit("restored_prefix", 1L); + + ArgumentCaptor<HttpUriRequest> requestCaptor = + ArgumentCaptor.forClass(HttpUriRequest.class); + verify(httpClient, times(2)).execute(requestCaptor.capture(), any(HttpContext.class)); + Header labelHeader = requestCaptor.getAllValues().get(0).getFirstHeader("label"); + Assertions.assertNotNull(labelHeader); + Assertions.assertEquals("restored_prefix_1", labelHeader.getValue()); + } + private DorisSinkConfig createSinkConfig(boolean directToBe, boolean enable2PC) { Map<String, Object> options = new HashMap<>(); options.put("fenodes", "fe1:8030"); diff --git a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-doris-e2e/src/test/java/org/apache/seatunnel/e2e/connector/doris/DorisCDCSinkIT.java b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-doris-e2e/src/test/java/org/apache/seatunnel/e2e/connector/doris/DorisCDCSinkIT.java index f40bc64daf..fa4dcc3633 100644 --- a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-doris-e2e/src/test/java/org/apache/seatunnel/e2e/connector/doris/DorisCDCSinkIT.java +++ b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-doris-e2e/src/test/java/org/apache/seatunnel/e2e/connector/doris/DorisCDCSinkIT.java @@ -62,22 +62,12 @@ public class DorisCDCSinkIT extends AbstractDorisIT { private static final String DATABASE = "test"; private static final String SINK_TABLE = "e2e_table_sink"; + private static final String SINK_TABLE_MULTI = "e2e_table_sink_multi"; + private static final String SINK_TABLE_MULTI_2PC = "e2e_table_sink_multi_2pc"; private static final String CREATE_DATABASE = "CREATE DATABASE IF NOT EXISTS " + DATABASE; - private static final String DDL_SINK = - "CREATE TABLE IF NOT EXISTS " - + DATABASE - + "." - + SINK_TABLE - + " (\n" - + " uuid BIGINT,\n" - + " name VARCHAR(128),\n" - + " score INT\n" - + ")ENGINE=OLAP\n" - + "UNIQUE KEY(`uuid`)\n" - + "DISTRIBUTED BY HASH(`uuid`) BUCKETS 1\n" - + "PROPERTIES (\n" - + "\"replication_allocation\" = \"tag.location.default: 1\"" - + ")"; + private static final String DDL_SINK = createSinkTableDdl(SINK_TABLE); + private static final String DDL_SINK_MULTI = createSinkTableDdl(SINK_TABLE_MULTI); + private static final String DDL_SINK_MULTI_2PC = createSinkTableDdl(SINK_TABLE_MULTI_2PC); // mysql private static final String MYSQL_HOST = "mysql_cdc_e2e"; @@ -86,6 +76,27 @@ public class DorisCDCSinkIT extends AbstractDorisIT { private static final String MYSQL_DATABASE = "mysql_cdc"; private static final MySqlContainer MYSQL_CONTAINER = createMySqlContainer(MySqlVersion.V8_0); private static final String SOURCE_TABLE = "mysql_cdc_e2e_source_table"; + private static final String SOURCE_TABLE_MULTI_1 = "mysql_cdc_e2e_source_table_multi_1"; + private static final String SOURCE_TABLE_MULTI_2 = "mysql_cdc_e2e_source_table_multi_2"; + private static final String SOURCE_TABLE_MULTI_2PC_1 = "mysql_cdc_e2e_source_table_multi2pc_1"; + private static final String SOURCE_TABLE_MULTI_2PC_2 = "mysql_cdc_e2e_source_table_multi2pc_2"; + + private static String createSinkTableDdl(String table) { + return "CREATE TABLE IF NOT EXISTS " + + DATABASE + + "." + + table + + " (\n" + + " uuid BIGINT,\n" + + " name VARCHAR(128),\n" + + " score INT\n" + + ")ENGINE=OLAP\n" + + "UNIQUE KEY(`uuid`)\n" + + "DISTRIBUTED BY HASH(`uuid`) BUCKETS 1\n" + + "PROPERTIES (\n" + + "\"replication_allocation\" = \"tag.location.default: 1\"" + + ")"; + } @TestContainerExtension protected final ContainerExtendedFactory extendedFactory = @@ -193,12 +204,153 @@ public class DorisCDCSinkIT extends AbstractDorisIT { "INSERT INTO " + MYSQL_DATABASE + "." + SOURCE_TABLE + " VALUES (1, 'Alice', 95)"); } + @TestTemplate + @DisabledOnContainer( + value = {}, + type = {EngineType.FLINK, EngineType.SPARK}, + disabledReason = + "TestContainer.getJobStatus/stopJob are only implemented by the Zeta engine") + public void testMultiTableCDCSinkToSingleDorisTable(TestContainer container) throws Exception { + clearTable(DATABASE, SINK_TABLE_MULTI); + String jobId = String.valueOf(System.nanoTime()); + CompletableFuture<Void> jobFuture = + CompletableFuture.runAsync( + () -> { + try { + container.executeJob("/mysqlcdc_multi_table_to_doris.conf", jobId); + } catch (Exception e) { + log.error("Commit task exception :" + e.getMessage()); + throw new RuntimeException(e); + } + }); + + try { + await().atMost(120000, TimeUnit.MILLISECONDS) + .untilAsserted( + () -> + Assertions.assertEquals( + "RUNNING", container.getJobStatus(jobId))); + + executeSql(buildInsertSql(MYSQL_DATABASE + "." + SOURCE_TABLE_MULTI_1, 1000, 100)); + executeSql(buildInsertSql(MYSQL_DATABASE + "." + SOURCE_TABLE_MULTI_2, 2000, 100)); + + String sinkSql = + String.format("select count(*) from %s.%s", DATABASE, SINK_TABLE_MULTI); + // Two initial rows in each source table plus 100 inserted rows in each table. + long expectedRows = 204L; + await().atMost(180000, TimeUnit.MILLISECONDS) + .untilAsserted( + () -> { + try (Statement statement = jdbcConnection.createStatement(); + ResultSet resultSet = statement.executeQuery(sinkSql)) { + resultSet.next(); + Assertions.assertEquals(expectedRows, resultSet.getLong(1)); + } + }); + Assertions.assertEquals("RUNNING", container.getJobStatus(jobId)); + } finally { + try { + container.stopJob(jobId); + } catch (Exception e) { + log.warn("Failed to stop job {}", jobId, e); + } + try { + jobFuture.get(60, TimeUnit.SECONDS); + } catch (Exception e) { + log.warn("Job {} did not finish cleanly", jobId, e); + } + } + } + + @TestTemplate + @DisabledOnContainer( + value = {}, + type = {EngineType.FLINK, EngineType.SPARK}, + disabledReason = + "TestContainer.getJobStatus/stopJob are only implemented by the Zeta engine") + public void testMultiTableCDCSinkToSingleDorisTableWithTwoPhaseCommit(TestContainer container) + throws Exception { + clearTable(DATABASE, SINK_TABLE_MULTI_2PC); + String jobId = String.valueOf(System.nanoTime()); + CompletableFuture<Void> jobFuture = + CompletableFuture.runAsync( + () -> { + try { + container.executeJob( + "/mysqlcdc_multi_table_to_doris_2pc.conf", jobId); + } catch (Exception e) { + log.error("Commit task exception :" + e.getMessage()); + throw new RuntimeException(e); + } + }); + + try { + await().atMost(120000, TimeUnit.MILLISECONDS) + .untilAsserted( + () -> + Assertions.assertEquals( + "RUNNING", container.getJobStatus(jobId))); + + executeSql(buildInsertSql(MYSQL_DATABASE + "." + SOURCE_TABLE_MULTI_2PC_1, 3000, 100)); + executeSql(buildInsertSql(MYSQL_DATABASE + "." + SOURCE_TABLE_MULTI_2PC_2, 4000, 100)); + + String sinkSql = + String.format("select count(*) from %s.%s", DATABASE, SINK_TABLE_MULTI_2PC); + // Two initial rows in each source table plus 100 inserted rows in each table. + long expectedRows = 204L; + await().atMost(180000, TimeUnit.MILLISECONDS) + .untilAsserted( + () -> { + try (Statement statement = jdbcConnection.createStatement(); + ResultSet resultSet = statement.executeQuery(sinkSql)) { + resultSet.next(); + Assertions.assertEquals(expectedRows, resultSet.getLong(1)); + } + }); + Assertions.assertEquals("RUNNING", container.getJobStatus(jobId)); + } finally { + try { + container.stopJob(jobId); + } catch (Exception e) { + log.warn("Failed to stop job {}", jobId, e); + } + try { + jobFuture.get(60, TimeUnit.SECONDS); + } catch (Exception e) { + log.warn("Job {} did not finish cleanly", jobId, e); + } + } + } + + private String buildInsertSql(String table, int startUuid, int count) { + StringBuilder sql = + new StringBuilder("INSERT INTO ") + .append(table) + .append(" (uuid, name, score) VALUES "); + for (int i = 0; i < count; i++) { + if (i > 0) { + sql.append(","); + } + int uuid = startUuid + i; + sql.append("(") + .append(uuid) + .append(", 'user_") + .append(uuid) + .append("', ") + .append(80 + (i % 20)) + .append(")"); + } + return sql.toString(); + } + private void initializeJdbcTable() { try (Statement statement = jdbcConnection.createStatement()) { // create databases statement.execute(CREATE_DATABASE); - // create sink table + // create sink tables statement.execute(DDL_SINK); + statement.execute(DDL_SINK_MULTI); + statement.execute(DDL_SINK_MULTI_2PC); } catch (SQLException e) { throw new RuntimeException("Initializing table failed!", e); } diff --git a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-doris-e2e/src/test/resources/ddl/mysql_cdc.sql b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-doris-e2e/src/test/resources/ddl/mysql_cdc.sql index 638da2981b..7d4ebc0b56 100644 --- a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-doris-e2e/src/test/resources/ddl/mysql_cdc.sql +++ b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-doris-e2e/src/test/resources/ddl/mysql_cdc.sql @@ -35,4 +35,57 @@ truncate table `mysql_cdc`.`mysql_cdc_e2e_source_table`; INSERT INTO `mysql_cdc`.`mysql_cdc_e2e_source_table` (uuid, name, score) VALUES (1, 'Alice', 95), -(2, 'Bob', 88); \ No newline at end of file +(2, 'Bob', 88); + +-- Source tables used by the multi-table CDC sink test. They are intentionally separate from +-- mysql_cdc_e2e_source_table so the single-table test cannot observe rows inserted here. +CREATE TABLE IF NOT EXISTS `mysql_cdc`.`mysql_cdc_e2e_source_table_multi_1` ( + `uuid` BIGINT, + `name` VARCHAR(128), + `score` INT, + PRIMARY KEY (`uuid`) +) ENGINE=InnoDB; + +CREATE TABLE IF NOT EXISTS `mysql_cdc`.`mysql_cdc_e2e_source_table_multi_2` ( + `uuid` BIGINT, + `name` VARCHAR(128), + `score` INT, + PRIMARY KEY (`uuid`) +) ENGINE=InnoDB; + +truncate table `mysql_cdc`.`mysql_cdc_e2e_source_table_multi_1`; +truncate table `mysql_cdc`.`mysql_cdc_e2e_source_table_multi_2`; + +INSERT INTO `mysql_cdc`.`mysql_cdc_e2e_source_table_multi_1` (uuid, name, score) VALUES +(3, 'Carol', 90), +(4, 'Dave', 85); + +INSERT INTO `mysql_cdc`.`mysql_cdc_e2e_source_table_multi_2` (uuid, name, score) VALUES +(5, 'Eve', 80), +(6, 'Frank', 75); + +-- Source tables used by the 2PC multi-table CDC sink test. +CREATE TABLE IF NOT EXISTS `mysql_cdc`.`mysql_cdc_e2e_source_table_multi2pc_1` ( + `uuid` BIGINT, + `name` VARCHAR(128), + `score` INT, + PRIMARY KEY (`uuid`) +) ENGINE=InnoDB; + +CREATE TABLE IF NOT EXISTS `mysql_cdc`.`mysql_cdc_e2e_source_table_multi2pc_2` ( + `uuid` BIGINT, + `name` VARCHAR(128), + `score` INT, + PRIMARY KEY (`uuid`) +) ENGINE=InnoDB; + +truncate table `mysql_cdc`.`mysql_cdc_e2e_source_table_multi2pc_1`; +truncate table `mysql_cdc`.`mysql_cdc_e2e_source_table_multi2pc_2`; + +INSERT INTO `mysql_cdc`.`mysql_cdc_e2e_source_table_multi2pc_1` (uuid, name, score) VALUES +(7, 'Grace', 95), +(8, 'Heidi', 90); + +INSERT INTO `mysql_cdc`.`mysql_cdc_e2e_source_table_multi2pc_2` (uuid, name, score) VALUES +(9, 'Ivan', 85), +(10, 'Judy', 80); \ No newline at end of file diff --git a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-doris-e2e/src/test/resources/mysqlcdc_multi_table_to_doris.conf b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-doris-e2e/src/test/resources/mysqlcdc_multi_table_to_doris.conf new file mode 100644 index 0000000000..7848f96869 --- /dev/null +++ b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-doris-e2e/src/test/resources/mysqlcdc_multi_table_to_doris.conf @@ -0,0 +1,51 @@ +# +# 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. +# + +env { + parallelism = 1 + job.mode = "STREAMING" + checkpoint.interval = 1000 +} + +source { + MySQL-CDC { + parallelism = 1 + server-id = 5653 + username = "st_user_source" + password = "mysqlpw" + database-pattern = "mysql_cdc" + table-pattern = "mysql_cdc\\.mysql_cdc_e2e_source_table_multi_.*" + url = "jdbc:mysql://mysql_cdc_e2e:3306" + } +} + +sink { + Doris { + fenodes = "doris_e2e:8030" + username = root + password = "" + database = "test" + table = "e2e_table_sink_multi" + sink.label-prefix = "test-cdc-multi" + sink.enable-2pc = "false" + sink.enable-delete = "true" + doris.config { + format = "csv" + "column_separator" = "," + } + } +} diff --git a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-doris-e2e/src/test/resources/mysqlcdc_multi_table_to_doris_2pc.conf b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-doris-e2e/src/test/resources/mysqlcdc_multi_table_to_doris_2pc.conf new file mode 100644 index 0000000000..1a13d1235b --- /dev/null +++ b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-doris-e2e/src/test/resources/mysqlcdc_multi_table_to_doris_2pc.conf @@ -0,0 +1,50 @@ +# +# 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. +# + +env { + parallelism = 1 + job.mode = "STREAMING" + checkpoint.interval = 1000 +} + +source { + MySQL-CDC { + parallelism = 1 + server-id = 5654 + username = "st_user_source" + password = "mysqlpw" + database-pattern = "mysql_cdc" + table-pattern = "mysql_cdc\\.mysql_cdc_e2e_source_table_multi2pc_.*" + url = "jdbc:mysql://mysql_cdc_e2e:3306" + } +} + +sink { + Doris { + fenodes = "doris_e2e:8030" + username = root + password = "" + database = "test" + table = "e2e_table_sink_multi_2pc" + sink.label-prefix = "test-cdc-multi-2pc" + sink.enable-2pc = "true" + doris.config { + format = "json" + read_json_by_line = "true" + } + } +}
